diff --git a/.eslintignore b/.eslintignore index b752006a..0367bc11 100644 --- a/.eslintignore +++ b/.eslintignore @@ -32,6 +32,7 @@ src/external/dom-polyfill/* !src/external/dom-polyfill/dom-polyfill.js !src/external/dynamic-import-polyfill +jsconfig.json mochawesome-report releases !.eslintrc.js diff --git a/.travis.yml b/.travis.yml index ceabf38f..da5418e6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,4 +22,4 @@ jobs: # - 12 # - 10 script: - - npm run eslint + - npm run lint diff --git a/dist/common/browser.js b/dist/common/browser.js deleted file mode 100644 index 21875a30..00000000 --- a/dist/common/browser.js +++ /dev/null @@ -1,285 +0,0 @@ -/* globals jQuery */ -/** - * Browser detection. - * @module browser - * @license MIT - * - * @copyright 2010 Jeff Schiller, 2010 Alexis Deveria - */ - -// Dependencies: -// 1) jQuery (for $.alert()) - -import './svgpathseg.js'; -import {NS} from './namespaces.js'; - -const $ = jQuery; - -const supportsSVG_ = (function () { -return Boolean(document.createElementNS && document.createElementNS(NS.SVG, 'svg').createSVGRect); -}()); - -/** - * @function module:browser.supportsSvg - * @returns {boolean} -*/ -export const supportsSvg = () => supportsSVG_; - -const {userAgent} = navigator; -const svg = document.createElementNS(NS.SVG, 'svg'); - -// Note: Browser sniffing should only be used if no other detection method is possible -const isOpera_ = Boolean(window.opera); -const isWebkit_ = userAgent.includes('AppleWebKit'); -const isGecko_ = userAgent.includes('Gecko/'); -const isIE_ = userAgent.includes('MSIE'); -const isChrome_ = userAgent.includes('Chrome/'); -const isWindows_ = userAgent.includes('Windows'); -const isMac_ = userAgent.includes('Macintosh'); -const isTouch_ = 'ontouchstart' in window; - -const supportsSelectors_ = (function () { -return Boolean(svg.querySelector); -}()); - -const supportsXpath_ = (function () { -return Boolean(document.evaluate); -}()); - -// segList functions (for FF1.5 and 2.0) -const supportsPathReplaceItem_ = (function () { -const path = document.createElementNS(NS.SVG, 'path'); -path.setAttribute('d', 'M0,0 10,10'); -const seglist = path.pathSegList; -const seg = path.createSVGPathSegLinetoAbs(5, 5); -try { - seglist.replaceItem(seg, 1); - return true; -} catch (err) {} -return false; -}()); - -const supportsPathInsertItemBefore_ = (function () { -const path = document.createElementNS(NS.SVG, 'path'); -path.setAttribute('d', 'M0,0 10,10'); -const seglist = path.pathSegList; -const seg = path.createSVGPathSegLinetoAbs(5, 5); -try { - seglist.insertItemBefore(seg, 1); - return true; -} catch (err) {} -return false; -}()); - -// text character positioning (for IE9 and now Chrome) -const supportsGoodTextCharPos_ = (function () { -const svgroot = document.createElementNS(NS.SVG, 'svg'); -const svgcontent = document.createElementNS(NS.SVG, 'svg'); -document.documentElement.append(svgroot); -svgcontent.setAttribute('x', 5); -svgroot.append(svgcontent); -const text = document.createElementNS(NS.SVG, 'text'); -text.textContent = 'a'; -svgcontent.append(text); -try { // Chrome now fails here - const pos = text.getStartPositionOfChar(0).x; - return (pos === 0); -} catch (err) { - return false; -} finally { - svgroot.remove(); -} -}()); - -const supportsPathBBox_ = (function () { -const svgcontent = document.createElementNS(NS.SVG, 'svg'); -document.documentElement.append(svgcontent); -const path = document.createElementNS(NS.SVG, 'path'); -path.setAttribute('d', 'M0,0 C0,0 10,10 10,0'); -svgcontent.append(path); -const bbox = path.getBBox(); -svgcontent.remove(); -return (bbox.height > 4 && bbox.height < 5); -}()); - -// Support for correct bbox sizing on groups with horizontal/vertical lines -const supportsHVLineContainerBBox_ = (function () { -const svgcontent = document.createElementNS(NS.SVG, 'svg'); -document.documentElement.append(svgcontent); -const path = document.createElementNS(NS.SVG, 'path'); -path.setAttribute('d', 'M0,0 10,0'); -const path2 = document.createElementNS(NS.SVG, 'path'); -path2.setAttribute('d', 'M5,0 15,0'); -const g = document.createElementNS(NS.SVG, 'g'); -g.append(path, path2); -svgcontent.append(g); -const bbox = g.getBBox(); -svgcontent.remove(); -// Webkit gives 0, FF gives 10, Opera (correctly) gives 15 -return (bbox.width === 15); -}()); - -const supportsEditableText_ = (function () { -// TODO: Find better way to check support for this -return isOpera_; -}()); - -const supportsGoodDecimals_ = (function () { -// Correct decimals on clone attributes (Opera < 10.5/win/non-en) -const rect = document.createElementNS(NS.SVG, 'rect'); -rect.setAttribute('x', 0.1); -const crect = rect.cloneNode(false); -const 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; -}()); - -const supportsNonScalingStroke_ = (function () { -const rect = document.createElementNS(NS.SVG, 'rect'); -rect.setAttribute('style', 'vector-effect:non-scaling-stroke'); -return rect.style.vectorEffect === 'non-scaling-stroke'; -}()); - -let supportsNativeSVGTransformLists_ = (function () { -const rect = document.createElementNS(NS.SVG, 'rect'); -const rxform = rect.transform.baseVal; -const t1 = svg.createSVGTransform(); -rxform.appendItem(t1); -const r1 = rxform.getItem(0); -const 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} -*/ -export const isOpera = () => isOpera_; -/** - * @function module:browser.isWebkit - * @returns {boolean} -*/ -export const isWebkit = () => isWebkit_; -/** - * @function module:browser.isGecko - * @returns {boolean} -*/ -export const isGecko = () => isGecko_; -/** - * @function module:browser.isIE - * @returns {boolean} -*/ -export const isIE = () => isIE_; -/** - * @function module:browser.isChrome - * @returns {boolean} -*/ -export const isChrome = () => isChrome_; -/** - * @function module:browser.isWindows - * @returns {boolean} -*/ -export const isWindows = () => isWindows_; -/** - * @function module:browser.isMac - * @returns {boolean} -*/ -export const isMac = () => isMac_; -/** - * @function module:browser.isTouch - * @returns {boolean} -*/ -export const isTouch = () => isTouch_; - -/** - * @function module:browser.supportsSelectors - * @returns {boolean} -*/ -export const supportsSelectors = () => supportsSelectors_; - -/** - * @function module:browser.supportsXpath - * @returns {boolean} -*/ -export const supportsXpath = () => supportsXpath_; - -/** - * @function module:browser.supportsPathReplaceItem - * @returns {boolean} -*/ -export const supportsPathReplaceItem = () => supportsPathReplaceItem_; - -/** - * @function module:browser.supportsPathInsertItemBefore - * @returns {boolean} -*/ -export const supportsPathInsertItemBefore = () => supportsPathInsertItemBefore_; - -/** - * @function module:browser.supportsPathBBox - * @returns {boolean} -*/ -export const supportsPathBBox = () => supportsPathBBox_; - -/** - * @function module:browser.supportsHVLineContainerBBox - * @returns {boolean} -*/ -export const supportsHVLineContainerBBox = () => supportsHVLineContainerBBox_; - -/** - * @function module:browser.supportsGoodTextCharPos - * @returns {boolean} -*/ -export const supportsGoodTextCharPos = () => supportsGoodTextCharPos_; - -/** -* @function module:browser.supportsEditableText - * @returns {boolean} -*/ -export const supportsEditableText = () => supportsEditableText_; - -/** - * @function module:browser.supportsGoodDecimals - * @returns {boolean} -*/ -export const supportsGoodDecimals = () => supportsGoodDecimals_; - -/** -* @function module:browser.supportsNonScalingStroke -* @returns {boolean} -*/ -export const supportsNonScalingStroke = () => supportsNonScalingStroke_; - -/** -* @function module:browser.supportsNativeTransformLists -* @returns {boolean} -*/ -export const supportsNativeTransformLists = () => supportsNativeSVGTransformLists_; - -/** - * Set `supportsNativeSVGTransformLists_` to `false` (for unit testing). - * @function module:browser.disableSupportsNativeTransformLists - * @returns {void} -*/ -export const disableSupportsNativeTransformLists = () => { - supportsNativeSVGTransformLists_ = false; -}; diff --git a/dist/common/jQuery.attr.js b/dist/common/jQuery.attr.js deleted file mode 100644 index eafb505e..00000000 --- a/dist/common/jQuery.attr.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 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} -*/ -export default function jQueryPluginSVG ($) { - const 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) { - const len = this.length; - if (!len) { return proxied.call(this, key, value); } - for (let i = 0; i < len; ++i) { - const 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 - const obj = {}; - let j = key.length; - - while (j--) { - const aname = key[j]; - let 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 (const [name, val] of Object.entries(key)) { - elem.setAttribute(name, val); - } - // Getting attribute - } else { - let 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 $; -} diff --git a/dist/common/layer.js b/dist/common/layer.js deleted file mode 100644 index 9cc31d79..00000000 --- a/dist/common/layer.js +++ /dev/null @@ -1,222 +0,0 @@ -/* globals jQuery */ -/** - * Provides tools for the layer concept. - * @module layer - * @license MIT - * - * @copyright 2011 Jeff Schiller, 2016 Flint O'Brien - */ - -import {NS} from './namespaces.js'; -import {toXml, walkTree, isNullish} from './utilities.js'; - -const $ = 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 - */ -class Layer { - /** - * @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. - */ - constructor (name, group, svgElem) { - this.name_ = name; - this.group_ = svgElem ? null : group; - - if (svgElem) { - // Create a group element with title and add it to the DOM. - const svgdoc = svgElem.ownerDocument; - this.group_ = svgdoc.createElementNS(NS.SVG, 'g'); - const layerTitle = svgdoc.createElementNS(NS.SVG, 'title'); - layerTitle.textContent = name; - this.group_.append(layerTitle); - if (group) { - $(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 - */ - getName () { - return this.name_; - } - - /** - * Get the group element for this layer. - * @returns {SVGGElement} The layer SVG group - */ - getGroup () { - return this.group_; - } - - /** - * Active this layer so it takes pointer events. - * @returns {void} - */ - activate () { - this.group_.setAttribute('style', 'pointer-events:all'); - } - - /** - * Deactive this layer so it does NOT take pointer events. - * @returns {void} - */ - 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} - */ - setVisible (visible) { - const expected = visible === undefined || visible ? 'inline' : 'none'; - const oldDisplay = this.group_.getAttribute('display'); - if (oldDisplay !== expected) { - this.group_.setAttribute('display', expected); - } - } - - /** - * Is this layer visible? - * @returns {boolean} True if visible. - */ - isVisible () { - return this.group_.getAttribute('display') !== 'none'; - } - - /** - * Get layer opacity. - * @returns {Float} Opacity value. - */ - getOpacity () { - const 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} - */ - 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} - */ - appendChildren (children) { - for (const child of children) { - this.group_.append(child); - } - } - - /** - * @returns {SVGTitleElement|null} - */ - getTitleElement () { - const len = this.group_.childNodes.length; - for (let i = 0; i < len; ++i) { - const 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. - */ - setName (name, hrService) { - const previousName = this.name_; - name = toXml(name); - // now change the underlying title element contents - const title = this.getTitleElement(); - if (title) { - $(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. - */ - removeGroup () { - const group = this.group_; - this.group_.remove(); - this.group_ = undefined; - return group; - } -} -/** - * @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) { - const 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); - } -} - -export default Layer; diff --git a/dist/common/math.js b/dist/common/math.js deleted file mode 100644 index 0d474381..00000000 --- a/dist/common/math.js +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Mathematical utilities. - * @module math - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ - -/** -* @typedef {PlainObject} module:math.AngleCoord45 -* @property {Float} x - The angle-snapped x value -* @property {Float} y - The angle-snapped y value -* @property {Integer} a - The angle at which to snap -*/ - -/** -* @typedef {PlainObject} module:math.XYObject -* @property {Float} x -* @property {Float} y -*/ - -import {NS} from './namespaces.js'; -import {getTransformList} from './svgtransformlist.js'; - -// Constants -const NEAR_ZERO = 1e-14; - -// Throw away SVGSVGElement used for creating matrices/transforms. -const svg = 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 -*/ -export const transformPoint = function (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 -*/ -export const isIdentity = function (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 -*/ -export const matrixMultiply = function (...args) { - const m = args.reduceRight((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 -*/ -export const hasMatrixTransform = function (tlist) { - if (!tlist) { return false; } - let num = tlist.numberOfItems; - while (num--) { - const 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} -*/ -export const transformBox = function (l, t, w, h, m) { - const 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, - tr, - bl, - 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 -*/ -export const transformListToTransform = function (tlist, min, max) { - if (!tlist) { - // Or should tlist = null have been prevented before this? - return svg.createSVGTransformFromMatrix(svg.createSVGMatrix()); - } - min = min || 0; - max = max || (tlist.numberOfItems - 1); - min = Number.parseInt(min); - max = Number.parseInt(max); - if (min > max) { const temp = max; max = min; min = temp; } - let m = svg.createSVGMatrix(); - for (let i = min; i <= max; ++i) { - // if our indices are out of range, just use a harmless identity matrix - const mtom = (i >= 0 && i < tlist.numberOfItems - ? tlist.getItem(i).matrix - : svg.createSVGMatrix()); - m = matrixMultiply(m, mtom); - } - return svg.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 -*/ -export const getMatrix = function (elem) { - const 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} -*/ -export const snapToAngle = function (x1, y1, x2, y2) { - const snap = Math.PI / 4; // 45 degrees - const dx = x2 - x1; - const dy = y2 - y1; - const angle = Math.atan2(dy, dx); - const dist = Math.sqrt(dx * dx + dy * dy); - const 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 - */ -export const rectsIntersect = function (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; -}; diff --git a/dist/common/namespaces.js b/dist/common/namespaces.js deleted file mode 100644 index 2658760f..00000000 --- a/dist/common/namespaces.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Namespaces or tools therefor. - * @module namespaces - * @license MIT -*/ - -/** -* Common namepaces constants in alpha order. -* @enum {string} -* @type {PlainObject} -* @memberof module:namespaces -*/ -export const 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 -*/ -export const getReverseNS = function () { - const reverseNS = {}; - Object.entries(NS).forEach(([name, URI]) => { - reverseNS[URI] = name.toLowerCase(); - }); - return reverseNS; -}; diff --git a/dist/common/svgpathseg.js b/dist/common/svgpathseg.js deleted file mode 100644 index b78362f6..00000000 --- a/dist/common/svgpathseg.js +++ /dev/null @@ -1,972 +0,0 @@ -/* 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 -(() => { -if (!('SVGPathSeg' in window)) { - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg - class SVGPathSeg { - constructor (type, typeAsLetter, owningPathSegList) { - 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. - _segmentChanged () { - if (this._owningPathSegList) { - this._owningPathSegList.segmentChanged(this); - } - } - } - 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; - - class SVGPathSegClosePath extends SVGPathSeg { - constructor (owningPathSegList) { - super(SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList); - } - toString () { return '[object SVGPathSegClosePath]'; } - _asPathString () { return this.pathSegTypeAsLetter; } - clone () { return new SVGPathSegClosePath(undefined); } - } - - class SVGPathSegMovetoAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegMovetoAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegMovetoAbs(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegMovetoAbs.prototype, { - x: { - get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true - }, - y: { - get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true - } - }); - - class SVGPathSegMovetoRel extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegMovetoRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegMovetoRel(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegMovetoRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegLinetoAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegLinetoAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegLinetoAbs(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegLinetoAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegLinetoRel extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegLinetoRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegLinetoRel(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegLinetoRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoCubicAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y, x1, y1, x2, y2) { - super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList); - this._x = x; - this._y = y; - this._x1 = x1; - this._y1 = y1; - this._x2 = x2; - this._y2 = y2; - } - toString () { return '[object SVGPathSegCurvetoCubicAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } - } - Object.defineProperties(SVGPathSegCurvetoCubicAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true}, - y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true}, - x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true}, - y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoCubicRel extends SVGPathSeg { - constructor (owningPathSegList, x, y, x1, y1, x2, y2) { - super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList); - this._x = x; - this._y = y; - this._x1 = x1; - this._y1 = y1; - this._x2 = x2; - this._y2 = y2; - } - toString () { return '[object SVGPathSegCurvetoCubicRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } - } - Object.defineProperties(SVGPathSegCurvetoCubicRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true}, - y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true}, - x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true}, - y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y, x1, y1) { - super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList); - this._x = x; - this._y = y; - this._x1 = x1; - this._y1 = y1; - } - toString () { return '[object SVGPathSegCurvetoQuadraticAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); } - } - Object.defineProperties(SVGPathSegCurvetoQuadraticAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true}, - y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { - constructor (owningPathSegList, x, y, x1, y1) { - super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList); - this._x = x; - this._y = y; - this._x1 = x1; - this._y1 = y1; - } - toString () { return '[object SVGPathSegCurvetoQuadraticRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); } - } - Object.defineProperties(SVGPathSegCurvetoQuadraticRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true}, - y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegArcAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - super(SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList); - this._x = x; - this._y = y; - this._r1 = r1; - this._r2 = r2; - this._angle = angle; - this._largeArcFlag = largeArcFlag; - this._sweepFlag = sweepFlag; - } - toString () { return '[object SVGPathSegArcAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } - } - Object.defineProperties(SVGPathSegArcAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - r1: {get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true}, - r2: {get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true}, - angle: {get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true}, - largeArcFlag: {get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true}, - sweepFlag: {get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegArcRel extends SVGPathSeg { - constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - super(SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList); - this._x = x; - this._y = y; - this._r1 = r1; - this._r2 = r2; - this._angle = angle; - this._largeArcFlag = largeArcFlag; - this._sweepFlag = sweepFlag; - } - toString () { return '[object SVGPathSegArcRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } - } - Object.defineProperties(SVGPathSegArcRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - r1: {get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true}, - r2: {get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true}, - angle: {get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true}, - largeArcFlag: {get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true}, - sweepFlag: {get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { - constructor (owningPathSegList, x) { - super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList); - this._x = x; - } - toString () { return '[object SVGPathSegLinetoHorizontalAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; } - clone () { return new SVGPathSegLinetoHorizontalAbs(undefined, this._x); } - } - Object.defineProperty(SVGPathSegLinetoHorizontalAbs.prototype, 'x', {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}); - - class SVGPathSegLinetoHorizontalRel extends SVGPathSeg { - constructor (owningPathSegList, x) { - super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList); - this._x = x; - } - toString () { return '[object SVGPathSegLinetoHorizontalRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; } - clone () { return new SVGPathSegLinetoHorizontalRel(undefined, this._x); } - } - Object.defineProperty(SVGPathSegLinetoHorizontalRel.prototype, 'x', {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}); - - class SVGPathSegLinetoVerticalAbs extends SVGPathSeg { - constructor (owningPathSegList, y) { - super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList); - this._y = y; - } - toString () { return '[object SVGPathSegLinetoVerticalAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; } - clone () { return new SVGPathSegLinetoVerticalAbs(undefined, this._y); } - } - Object.defineProperty(SVGPathSegLinetoVerticalAbs.prototype, 'y', {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}); - - class SVGPathSegLinetoVerticalRel extends SVGPathSeg { - constructor (owningPathSegList, y) { - super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList); - this._y = y; - } - toString () { return '[object SVGPathSegLinetoVerticalRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; } - clone () { return new SVGPathSegLinetoVerticalRel(undefined, this._y); } - } - Object.defineProperty(SVGPathSegLinetoVerticalRel.prototype, 'y', {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}); - - class SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y, x2, y2) { - super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList); - this._x = x; - this._y = y; - this._x2 = x2; - this._y2 = y2; - } - toString () { return '[object SVGPathSegCurvetoCubicSmoothAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); } - } - Object.defineProperties(SVGPathSegCurvetoCubicSmoothAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true}, - y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { - constructor (owningPathSegList, x, y, x2, y2) { - super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList); - this._x = x; - this._y = y; - this._x2 = x2; - this._y2 = y2; - } - toString () { return '[object SVGPathSegCurvetoCubicSmoothRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); } - } - Object.defineProperties(SVGPathSegCurvetoCubicSmoothRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}, - x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true}, - y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegCurvetoQuadraticSmoothAbs]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true} - }); - - class SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { - constructor (owningPathSegList, x, y) { - super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList); - this._x = x; - this._y = y; - } - toString () { return '[object SVGPathSegCurvetoQuadraticSmoothRel]'; } - _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } - clone () { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); } - } - Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothRel.prototype, { - x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true}, - y: {get () { return this._y; }, 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.'); - } - - const measurementElement = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - measurementElement.setAttribute('d', this.getAttribute('d')); - let 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 - class SVGPathSegList { - constructor (pathElement) { - 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. - _checkPathSynchronizedToList () { - this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords()); - } - - _updateListFromPathMutations (mutationRecords) { - if (!this._pathElement) { - return; - } - let hasPathMutations = false; - mutationRecords.forEach((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. - _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. - segmentChanged (pathSeg) { - this._writeListToPath(); - } - - clear () { - this._checkPathSynchronizedToList(); - - this._list.forEach((pathSeg) => { - pathSeg._owningPathSegList = null; - }); - this._list = []; - this._writeListToPath(); - } - - initialize (newItem) { - this._checkPathSynchronizedToList(); - - this._list = [newItem]; - newItem._owningPathSegList = this; - this._writeListToPath(); - return newItem; - } - - _checkValidIndex (index) { - if (isNaN(index) || index < 0 || index >= this.numberOfItems) { - throw new Error('INDEX_SIZE_ERR'); - } - } - - getItem (index) { - this._checkPathSynchronizedToList(); - - this._checkValidIndex(index); - return this._list[index]; - } - - 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; - } - - 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; - } - - removeItem (index) { - this._checkPathSynchronizedToList(); - - this._checkValidIndex(index); - const item = this._list[index]; - this._list.splice(index, 1); - this._writeListToPath(); - return item; - } - - 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. - _parsePath (string) { - if (!string || !string.length) { - return []; - } - - const owningPathSegList = this; - - class Builder { - constructor () { - this.pathSegList = []; - } - appendSegment (pathSeg) { - this.pathSegList.push(pathSeg); - } - } - - class Source { - constructor (string) { - this._string = string; - this._currentIndex = 0; - this._endIndex = this._string.length; - this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN; - - this._skipOptionalSpaces(); - } - _isCurrentSpace () { - const character = this._string[this._currentIndex]; - return character <= ' ' && (character === ' ' || character === '\n' || character === '\t' || character === '\r' || character === '\f'); - } - - _skipOptionalSpaces () { - while (this._currentIndex < this._endIndex && this._isCurrentSpace()) { - this._currentIndex++; - } - return this._currentIndex < this._endIndex; - } - - _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; - } - - hasMoreData () { - return this._currentIndex < this._endIndex; - } - - peekSegmentType () { - const lookahead = this._string[this._currentIndex]; - return this._pathSegTypeFromChar(lookahead); - } - - _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; - } - } - - _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; - } - - initialCommandIsMoveTo () { - // If the path is empty it is still valid, so return true. - if (!this.hasMoreData()) { - return true; - } - const 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 - _parseNumber () { - let exponent = 0; - let integer = 0; - let frac = 1; - let decimal = 0; - let sign = 1; - let expsign = 1; - - const 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. - const 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) { - let scanIntPartIndex = this._currentIndex - 1; - let 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++; - } - } - - let number = integer + decimal; - number *= sign; - - if (exponent) { - number *= 10 ** (expsign * exponent); - } - - if (startIndex === this._currentIndex) { - return undefined; - } - - this._skipOptionalSpacesOrDelimiter(); - - return number; - } - - _parseArcFlag () { - if (this._currentIndex >= this._endIndex) { - return undefined; - } - let flag = false; - const flagChar = this._string.charAt(this._currentIndex++); - if (flagChar === '0') { - flag = false; - } else if (flagChar === '1') { - flag = true; - } else { - return undefined; - } - - this._skipOptionalSpacesOrDelimiter(); - return flag; - } - - parseSegment () { - const lookahead = this._string[this._currentIndex]; - let 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: { - const 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: { - const 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: { - const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; - return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2); - } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: { - const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; - return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2); - } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: { - const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; - return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1); - } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: { - const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; - return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.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: { - const points = {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, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep); - } case SVGPathSeg.PATHSEG_ARC_ABS: { - const points = {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, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep); - } default: - throw new Error('Unknown path seg type.'); - } - } - } - - const builder = new Builder(); - const source = new Source(string); - - if (!source.initialCommandIsMoveTo()) { - return []; - } - while (source.hasMoreData()) { - const pathSeg = source.parseSegment(); - if (!pathSeg) { - return []; - } - builder.appendSegment(pathSeg); - } - - return builder.pathSegList; - } - - // STATIC - static _pathSegArrayAsString (pathSegArray) { - let string = ''; - let first = true; - pathSegArray.forEach((pathSeg) => { - if (first) { - first = false; - string += pathSeg._asPathString(); - } else { - string += ' ' + pathSeg._asPathString(); - } - }); - return string; - } - } - - SVGPathSegList.prototype.classname = 'SVGPathSegList'; - - Object.defineProperty(SVGPathSegList.prototype, 'numberOfItems', { - 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 () { - 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 () { return this.pathSegList; }, enumerable: true}, - animatedPathSegList: {get () { return this.pathSegList; }, enumerable: true}, - animatedNormalizedPathSegList: {get () { return this.pathSegList; }, enumerable: true} - }); - window.SVGPathSegList = SVGPathSegList; -} -})(); diff --git a/dist/common/svgtransformlist.js b/dist/common/svgtransformlist.js deleted file mode 100644 index 09d5eae6..00000000 --- a/dist/common/svgtransformlist.js +++ /dev/null @@ -1,397 +0,0 @@ -/** - * Partial polyfill of `SVGTransformList` - * @module SVGTransformList - * - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ - -import {NS} from './namespaces.js'; -import {supportsNativeTransformLists} from './browser.js'; - -const svgroot = document.createElementNS(NS.SVG, 'svg'); - -/** - * Helper function to convert `SVGTransform` to a string. - * @param {SVGTransform} xform - * @returns {string} - */ -function transformToString (xform) { - const m = xform.matrix; - let 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 - let cx = 0; - let cy = 0; - // this prevents divide by zero - if (xform.angle !== 0) { - const 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. - */ -let 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} -*/ -export class SVGTransformList { // eslint-disable-line no-shadow - /** - * @param {Element} elem - * @returns {SVGTransformList} - */ - constructor (elem) { - this._elem = elem || null; - this._xforms = []; - // TODO: how do we capture the undo-ability in the changed transform list? - this._update = function () { - let tstr = ''; - // /* const concatMatrix = */ svgroot.createSVGMatrix(); - for (let i = 0; i < this.numberOfItems; ++i) { - const xform = this._list.getItem(i); - tstr += transformToString(xform) + ' '; - } - this._elem.setAttribute('transform', tstr); - }; - this._list = this; - this._init = function () { - // Transform attribute parser - let str = this._elem.getAttribute('transform'); - if (!str) { return; } - - // TODO: Add skew support in future - const re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; - // const re = /\s*(?(?:scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; - let m = true; - while (m) { - m = str.match(re); - str = str.replace(re, ''); - if (m && m[1]) { - const x = m[1]; - const bits = x.split(/\s*\(/); - const name = bits[0]; - const valBits = bits[1].match(/\s*(.*?)\s*\)/); - valBits[1] = valBits[1].replace(/(\d)-/g, '$1 -'); - const valArr = valBits[1].split(/[, ]+/); - const 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']; - */ - const mtx = svgroot.createSVGMatrix(); - Object.values(valArr).forEach(function (item, i) { - valArr[i] = Number.parseFloat(item); - if (name === 'matrix') { - mtx[letters[i]] = valArr[i]; - } - }); - const xform = svgroot.createSVGTransform(); - const fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1); - const 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](...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((tl) => { - for (let 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} - */ - clear () { - this.numberOfItems = 0; - this._xforms = []; - } - - /** - * @param {SVGTransform} newItem - * @returns {void} - */ - initialize (newItem) { - this.numberOfItems = 1; - this._removeFromOtherLists(newItem); - this._xforms = [newItem]; - } - - /** - * @param {Integer} index unsigned long - * @throws {Error} - * @returns {SVGTransform} - */ - getItem (index) { - if (index < this.numberOfItems && index >= 0) { - return this._xforms[index]; - } - const err = new Error('DOMException with code=INDEX_SIZE_ERR'); - err.code = 1; - throw err; - } - - /** - * @param {SVGTransform} newItem - * @param {Integer} index unsigned long - * @returns {SVGTransform} - */ - insertItemBefore (newItem, index) { - let retValue = null; - if (index >= 0) { - if (index < this.numberOfItems) { - this._removeFromOtherLists(newItem); - const newxforms = new Array(this.numberOfItems + 1); - // TODO: use array copying and slicing - let i; - for (i = 0; i < index; ++i) { - newxforms[i] = this._xforms[i]; - } - newxforms[i] = newItem; - for (let 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} - */ - replaceItem (newItem, index) { - let 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} - */ - removeItem (index) { - if (index < this.numberOfItems && index >= 0) { - const retValue = this._xforms[index]; - const newxforms = new Array(this.numberOfItems - 1); - let i; - for (i = 0; i < index; ++i) { - newxforms[i] = this._xforms[i]; - } - for (let j = i; j < this.numberOfItems - 1; ++j, ++i) { - newxforms[j] = this._xforms[i + 1]; - } - this.numberOfItems--; - this._xforms = newxforms; - this._list._update(); - return retValue; - } - const err = new Error('DOMException with code=INDEX_SIZE_ERR'); - err.code = 1; - throw err; - } - - /** - * @param {SVGTransform} newItem - * @returns {SVGTransform} - */ - appendItem (newItem) { - this._removeFromOtherLists(newItem); - this._xforms.push(newItem); - this.numberOfItems++; - this._list._update(); - return newItem; - } -} - -/** -* @function module:SVGTransformList.resetListMap -* @returns {void} -*/ -export const resetListMap = function () { - listMap_ = {}; -}; - -/** - * Removes transforms of the given element from the map. - * @function module:SVGTransformList.removeElementFromListMap - * @param {Element} elem - a DOM Element - * @returns {void} - */ -export let removeElementFromListMap = function (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} -*/ -export const getTransformList = function (elem) { - if (!supportsNativeTransformLists()) { - const id = elem.id || 'temp'; - let 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; -}; - -/** -* @callback module:SVGTransformList.removeElementFromListMap -* @param {Element} elem -* @returns {void} -*/ -/** -* Replace `removeElementFromListMap` for unit-testing. -* @function module:SVGTransformList.changeRemoveElementFromListMap -* @param {module:SVGTransformList.removeElementFromListMap} cb Passed a single argument `elem` -* @returns {void} -*/ - -export const changeRemoveElementFromListMap = function (cb) { // eslint-disable-line promise/prefer-await-to-callbacks - removeElementFromListMap = cb; -}; diff --git a/dist/common/units.js b/dist/common/units.js deleted file mode 100644 index c2bf694d..00000000 --- a/dist/common/units.js +++ /dev/null @@ -1,313 +0,0 @@ -/** - * Tools for working with units. - * @module units - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ - -import {NS} from './namespaces.js'; - -const wAttrs = ['x', 'x1', 'cx', 'rx', 'width']; -const hAttrs = ['y', 'y1', 'cy', 'ry', 'height']; -const unitAttrs = ['r', 'radius', ...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. -let elementContainer_; - -// Stores mapping of unit type to user coordinates. -let 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} - */ -export const init = function (elementContainer) { - elementContainer_ = elementContainer; - - // Get correct em/ex values by creating a temporary SVG. - const svg = document.createElementNS(NS.SVG, 'svg'); - document.body.append(svg); - const rect = document.createElementNS(NS.SVG, 'rect'); - rect.setAttribute('width', '1em'); - rect.setAttribute('height', '1ex'); - rect.setAttribute('x', '1in'); - svg.append(rect); - const bb = rect.getBBox(); - svg.remove(); - - const 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 -*/ -export const getTypeMap = function () { - 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 -*/ -export const shortFloat = function (val) { - const 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} -*/ -export const convertUnit = function (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} -*/ -export const setUnitAttr = function (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); -}; - -const attrsToConvert = { - line: ['x1', 'x2', 'y1', 'y2'], - circle: ['cx', 'cy', 'r'], - ellipse: ['cx', 'cy', 'rx', 'ry'], - foreignObject: ['x', 'y', 'width', 'height'], - rect: ['x', 'y', 'width', 'height'], - image: ['x', 'y', 'width', 'height'], - use: ['x', 'y', 'width', 'height'], - text: ['x', 'y'] -}; - -/** -* Converts all applicable attributes to the configured baseUnit. -* @function module:units.convertAttrs -* @param {Element} element - A DOM element whose attributes should be converted -* @returns {void} -*/ -export const convertAttrs = function (element) { - const elName = element.tagName; - const unit = elementContainer_.getBaseUnit(); - const attrs = attrsToConvert[elName]; - if (!attrs) { return; } - - const len = attrs.length; - for (let i = 0; i < len; i++) { - const attr = attrs[i]; - const cur = element.getAttribute(attr); - if (cur) { - if (!isNaN(cur)) { - element.setAttribute(attr, (cur / typeMap_[unit]) + unit); - } - // else { - // Convert existing? - // } - } - } -}; - -/** -* 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 -*/ -export const convertToNum = function (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 - const num = val.substr(0, val.length - 1) / 100; - const width = elementContainer_.getWidth(); - const 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); - } - const unit = val.substr(-2); - const 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 -*/ -export const isValidUnit = function (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((unit) => { - const 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. - - let 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 { - const elem = elementContainer_.getElement(val); - result = (!elem || elem === selectedElement); - } catch (e) {} - return result; - } - return true; -}; diff --git a/dist/common/utilities.js b/dist/common/utilities.js deleted file mode 100644 index e30cf483..00000000 --- a/dist/common/utilities.js +++ /dev/null @@ -1,1363 +0,0 @@ -/* globals jQuery */ -/** - * Miscellaneous utilities. - * @module utilities - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ - -import './svgpathseg.js'; -import jQueryPluginSVG from './jQuery.attr.js'; // Needed for SVG attribute setting and array form with `attr` -import {NS} from './namespaces.js'; -import {getTransformList} from './svgtransformlist.js'; -import {setUnitAttr, getTypeMap} from './units.js'; -import { - hasMatrixTransform, transformListToTransform, transformBox -} from './math.js'; -import { - isWebkit, supportsHVLineContainerBBox, supportsPathBBox, supportsXpath, - supportsSelectors -} from './browser.js'; - -// Constants -const $ = jQueryPluginSVG(jQuery); - -// String used to encode base64. -const KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - -// Much faster than running getBBox() every time -const visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use,clipPath'; -const visElemsArr = visElems.split(','); -// const hidElems = 'defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath'; - -let editorContext_ = null; -let domdoc_ = null; -let domcontainer_ = null; -let 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} -*/ -export const init = function (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 - */ -export const 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 -*/ -export const toXml = function (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 -}; - -/** -* Converts XML entities in a string to single characters. -* @function module:utilities.fromXml -* @example `&` becomes `&` -* @param {string} str - The string to be converted -* @returns {string} The converted string -*/ -export function fromXml (str) { - return $('

').html(str).text(); -} - -// This code was written by Tyler Akins and has been placed in the -// 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 -*/ -export 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 - } - const output = new Array(Math.floor((input.length + 2) / 3) * 4); - - let i = 0, - p = 0; - do { - const chr1 = input.charCodeAt(i++); - const chr2 = input.charCodeAt(i++); - const chr3 = input.charCodeAt(i++); - - /* eslint-disable no-bitwise */ - const enc1 = chr1 >> 2; - const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - - let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - let 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 -*/ -export 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, ''); - - let output = ''; - let i = 0; - - do { - const enc1 = KEYSTR.indexOf(input.charAt(i++)); - const enc2 = KEYSTR.indexOf(input.charAt(i++)); - const enc3 = KEYSTR.indexOf(input.charAt(i++)); - const enc4 = KEYSTR.indexOf(input.charAt(i++)); - - /* eslint-disable no-bitwise */ - const chr1 = (enc1 << 2) | (enc2 >> 4); - const chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - const 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} -*/ -export 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} -*/ -export const encodeUTF8 = function (argString) { - return unescape(encodeURIComponent(argString)); -}; - -/** - * Convert dataURL to object URL. - * @function module:utilities.dataURLToObjectURL - * @param {string} dataurl - * @returns {string} object URL or empty string - */ -export const dataURLToObjectURL = function (dataurl) { - if (typeof Uint8Array === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) { - return ''; - } - const arr = dataurl.split(','), - mime = arr[0].match(/:(.*?);/)[1], - bstr = atob(arr[1]); - /* - const [prefix, suffix] = dataurl.split(','), - {groups: {mime}} = prefix.match(/:(?.*?);/), - bstr = atob(suffix); - */ - let n = bstr.length; - const u8arr = new Uint8Array(n); - while (n--) { - u8arr[n] = bstr.charCodeAt(n); - } - const 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 - */ -export const createObjectURL = function (blob) { - if (!blob || typeof URL === 'undefined' || !URL.createObjectURL) { - return ''; - } - return URL.createObjectURL(blob); -}; - -/** - * @property {string} blankPageObjectURL - */ -export const blankPageObjectURL = (function () { - if (typeof Blob === 'undefined') { - return ''; - } - const blob = new Blob(['SVG-edit '], {type: 'text/html'}); - return createObjectURL(blob); -})(); - -/** -* Converts a string to use XML references (for non-ASCII). -* @function module:utilities.convertToXMLReferences -* @param {string} input -* @returns {string} Decimal numeric character references -*/ -export const convertToXMLReferences = function (input) { - let output = ''; - [...input].forEach((ch) => { - const c = ch.charCodeAt(); - if (c <= 127) { - output += ch; - } else { - output += `&#${c};`; - } - }); - return output; -}; - -/** -* 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} -*/ -export const text2xml = function (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" -*/ -export const getUrlFromAttr = function (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 -*/ -export let getHref = function (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} -*/ -export let setHref = function (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 -*/ -export const findDefs = function () { - const svgElement = editorContext_.getSVGContent(); - let 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 -*/ -export const getPathBBox = function (path) { - const seglist = path.pathSegList; - const tot = seglist.numberOfItems; - - const bounds = [[], []]; - const start = seglist.getItem(0); - let P0 = [start.x, start.y]; - - const getCalc = function (j, P1, P2, P3) { - return function (t) { - return 1 - t ** 3 * P0[j] + - 3 * 1 - t ** 2 * t * P1[j] + - 3 * (1 - t) * t ** 2 * P2[j] + - t ** 3 * P3[j]; - }; - }; - - for (let i = 0; i < tot; i++) { - const 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) { - const P1 = [seg.x1, seg.y1], - P2 = [seg.x2, seg.y2], - P3 = [seg.x, seg.y]; - - for (let j = 0; j < 2; j++) { - const calc = getCalc(j, P1, P2, P3); - - const b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j]; - const a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j]; - const c = 3 * P1[j] - 3 * P0[j]; - - if (a === 0) { - if (b === 0) { continue; } - const t = -c / b; - if (t > 0 && t < 1) { - bounds[j].push(calc(t)); - } - continue; - } - const b2ac = b ** 2 - 4 * c * a; - if (b2ac < 0) { continue; } - const t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - if (t1 > 0 && t1 < 1) { bounds[j].push(calc(t1)); } - const 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); - } - } - - const x = Math.min.apply(null, bounds[0]); - const w = Math.max.apply(null, bounds[0]) - x; - const y = Math.min.apply(null, bounds[1]); - const h = Math.max.apply(null, bounds[1]) - y; - return { - x, - 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) {} - } - const ref = $.data(selected, 'ref'); - let matched = null; - let ret, copy; - - if (ref) { - copy = $(ref).children().clone().attr('visibility', 'hidden'); - $(svgroot_).append(copy); - matched = copy.filter('line, path'); - } else { - matched = $(selected).find('line, path'); - } - - let issue = false; - if (matched.length) { - matched.each(function () { - const bb = this.getBBox(); - if (!bb.width || !bb.height) { - issue = true; - } - }); - if (issue) { - const elems = ref ? copy : $(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 -*/ -export const getBBox = function (elem) { - const selected = elem || editorContext_.geSelectedElements()[0]; - if (elem.nodeType !== 1) { return null; } - const elname = selected.nodeName; - - let 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()) { - const {x, y, width, height} = ret; - const bb = { - width, - 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 - const extent = selected.getExtentOfChar(0); // pos+dimensions of the first glyph - const width = selected.getComputedTextLength(); // width of the tspan - ret = { - x: extent.x, - y: extent.y, - width, - height: extent.height - }; - } - } else { - // Check if element is child of a foreignObject - const fo = $(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. -*/ -export const getPathDFromSegments = function (pathSegments) { - let d = ''; - - $.each(pathSegments, function (j, [singleChar, pts]) { - d += singleChar; - for (let 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. -*/ -export const getPathDFromElement = function (elem) { - // Possibly the cubed root of 6, but 1.81 works best - let num = 1.81; - let d, a, rx, ry; - switch (elem.tagName) { - case 'ellipse': - case 'circle': { - a = $(elem).attr(['rx', 'ry', 'cx', 'cy']); - const {cx, cy} = a; - ({rx, ry} = a); - if (elem.tagName === 'circle') { - ry = $(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 = $(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': { - const r = $(elem).attr(['rx', 'ry']); - ({rx, ry} = r); - const b = elem.getBBox(); - const {x, y} = b, - 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; - } default: - 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. -*/ -export const getExtraAttributesForConvertToPath = function (elem) { - const attrs = {}; - // TODO: make this list global so that we can properly maintain it - // TODO: what about @transform, @clip-rule, @fill-rule, etc? - $.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function () { - const 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. -*/ -export const getBBoxOfElementAsPath = function (elem, addSVGElementFromJson, pathActions) { - const path = addSVGElementFromJson({ - element: 'path', - attr: getExtraAttributesForConvertToPath(elem) - }); - - const eltrans = elem.getAttribute('transform'); - if (eltrans) { - path.setAttribute('transform', eltrans); - } - - const {parentNode} = elem; - if (elem.nextSibling) { - elem.before(path); - } else { - parentNode.append(path); - } - - const 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); - let 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. -*/ -export const convertToPath = function ( - elem, attrs, addSVGElementFromJson, pathActions, - clearSelection, addToSelection, hstry, addCommandToHistory -) { - const batchCmd = new hstry.BatchCommand('Convert element to Path'); - - // Any attribute on the element not covered by the passed-in attributes - attrs = $.extend({}, attrs, getExtraAttributesForConvertToPath(elem)); - - const path = addSVGElementFromJson({ - element: 'path', - attr: attrs - }); - - const eltrans = elem.getAttribute('transform'); - if (eltrans) { - path.setAttribute('transform', eltrans); - } - - const {id} = elem; - const {parentNode} = elem; - if (elem.nextSibling) { - elem.before(path); - } else { - parentNode.append(path); - } - - const 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) { - const tlist = getTransformList(path); - if (hasMatrixTransform(tlist)) { - pathActions.resetOrientation(path); - } - } - - const {nextSibling} = elem; - 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) { - const angleModulo90 = angle % 90; - const closeTo90 = angleModulo90 < -89.99 || angleModulo90 > 89.99; - const 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 -*/ -export const getBBoxWithTransform = function (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). - - let bb = getBBox(elem); - - if (!bb) { - return null; - } - - const tlist = getTransformList(elem); - const angle = getRotationAngleFromTransformList(tlist); - const hasMatrixXForm = hasMatrixTransform(tlist); - - if (angle || hasMatrixXForm) { - let goodBb = false; - if (bBoxCanBeOptimizedOverNativeGetBBox(angle, hasMatrixXForm)) { - // Get the BBox from the raw path for these elements - // TODO: why ellipse and not circle - const 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 - const rx = elem.getAttribute('rx'); - const ry = elem.getAttribute('ry'); - if (rx || ry) { - goodBb = getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions); - bb = goodBb; - } - } - } - - if (!goodBb) { - const {matrix} = transformListToTransform(tlist); - 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) { - const 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 -*/ -export const getStrokedBBox = function (elems, addSVGElementFromJson, pathActions) { - if (!elems || !elems.length) { return false; } - - let fullBb; - $.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; - - let maxX = fullBb.x + fullBb.width; - let maxY = fullBb.y + fullBb.height; - let minX = fullBb.x; - let minY = fullBb.y; - - // If only one elem, don't call the potentially slow getBBoxWithTransform method again. - if (elems.length === 1) { - const offset = getStrokeOffsetForBBox(elems[0]); - minX -= offset; - minY -= offset; - maxX += offset; - maxY += offset; - } else { - $.each(elems, function (i, elem) { - const curBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions); - if (curBb) { - const 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. -*/ -export const getVisibleElements = function (parentElement) { - if (!parentElement) { - parentElement = $(editorContext_.getSVGContent()).children(); // Prevent layers from being included - } - - const contentElems = []; - $(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 -*/ -export const getStrokedBBoxDefaultVisible = function (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 -*/ -export const getRotationAngleFromTransformList = function (tlist, toRad) { - if (!tlist) { return 0; } // <svg> elements have no tlist - const N = tlist.numberOfItems; - for (let i = 0; i < N; ++i) { - const 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 -*/ -export let getRotationAngle = function (elem, toRad) { // eslint-disable-line import/no-mutable-exports - const selected = elem || editorContext_.getSelectedElements()[0]; - // find the rotation transform (if any) and set it - const 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 -*/ -export const getRefElem = function (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} -*/ -export const 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 $(svgroot_).find(`[id=${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} -*/ -export const assignAttributes = function (elem, attrs, suspendLength, unitCheck) { - for (const [key, value] of Object.entries(attrs)) { - const 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} -*/ -export const cleanupElement = function (element) { - const 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(([attr, val]) => { - if (element.getAttribute(attr) === String(val)) { - element.removeAttribute(attr); - } - }); -}; - -/** -* Round value to for snapping. -* @function module:utilities.snapToGrid -* @param {Float} value -* @returns {Integer} -*/ -export const snapToGrid = function (value) { - const unit = editorContext_.getBaseUnit(); - let 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} -*/ -export const regexEscape = function (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} - */ -export const preventClickDefault = function (img) { - $(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} - */ -export const isNullish = (val) => { - return val === null || val === undefined; -}; - -/** -* Overwrite methods for unit testing. -* @function module:utilities.mock -* @param {PlainObject} mockMethods -* @param {module:utilities.getHref} mockMethods.getHref -* @param {module:utilities.setHref} mockMethods.setHref -* @param {module:utilities.getRotationAngle} mockMethods.getRotationAngle -* @returns {void} -*/ -export const mock = ({ - getHref: getHrefUser, setHref: setHrefUser, getRotationAngle: getRotationAngleUser -}) => { - getHref = getHrefUser; - setHref = setHrefUser; - getRotationAngle = getRotationAngleUser; -}; - -export const $q = (sel) => document.querySelector(sel); -export const $qq = (sel) => [...document.querySelectorAll(sel)]; diff --git a/dist/editor/browser-not-supported.html b/dist/editor/browser-not-supported.html deleted file mode 100644 index 6ec7af4e..00000000 --- a/dist/editor/browser-not-supported.html +++ /dev/null @@ -1,54 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <meta charset="utf-8" /> - <meta http-equiv="X-UA-Compatible" content="chrome=1"/> - <link rel="icon" type="image/png" href="images/logo.png"/> - <link rel="stylesheet" href="svg-editor.css"/> - <title>Browser does not support SVG | SVG-edit - - - - -

Sorry, but your browser does not support SVG. Below is a list of - alternate browsers and versions that support SVG and SVG-edit - (from caniuse.com). -

-

Try the latest version of - Firefox, - Chrome, - Safari, - Opera or - Internet Explorer. -

-
- -
- - diff --git a/dist/editor/embedapi.html b/dist/editor/embedapi.html deleted file mode 100644 index dda45a19..00000000 --- a/dist/editor/embedapi.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Embed API - - - - - - - - - -
- - diff --git a/dist/editor/embedapi.js b/dist/editor/embedapi.js deleted file mode 100644 index dd6459c4..00000000 --- a/dist/editor/embedapi.js +++ /dev/null @@ -1,395 +0,0 @@ -/** -* Handles underlying communication between the embedding window and the -* editor frame. -* @module EmbeddedSVGEdit -*/ - -let cbid = 0; - -/** -* @callback module:EmbeddedSVGEdit.CallbackSetter -* @param {GenericCallback} newCallback Callback to be stored (signature dependent on function) -* @returns {void} -*/ -/** -* @callback module:EmbeddedSVGEdit.CallbackSetGetter -* @param {...any} args Signature dependent on the function -* @returns {module:EmbeddedSVGEdit.CallbackSetter} -*/ - -/** -* @param {string} funcName -* @returns {module:EmbeddedSVGEdit.CallbackSetGetter} -*/ -function getCallbackSetter (funcName) { - return function (...args) { - const that = this, // New callback - callbackID = this.send(funcName, args, function () { /* */ }); // The callback (currently it's nothing, but will be set later) - - return function (newCallback) { - that.callbacks[callbackID] = newCallback; // Set callback - }; - }; -} - -/** -* Having this separate from messageListener allows us to -* avoid using JSON parsing (and its limitations) in the case -* of same domain control. -* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value -* @param {PlainObject} data -* @param {JSON} data.result -* @param {string} data.error -* @param {Integer} data.id -* @returns {void} -*/ -function addCallback (t, {result, error, id: callbackID}) { - if (typeof callbackID === 'number' && t.callbacks[callbackID]) { - // These should be safe both because we check `cbid` is numeric and - // because the calls are from trusted origins - if (result) { - t.callbacks[callbackID](result); // lgtm [js/unvalidated-dynamic-method-call] - } else { - t.callbacks[callbackID](error, 'error'); // lgtm [js/unvalidated-dynamic-method-call] - } - } -} - -/** -* @param {Event} e -* @returns {void} -*/ -function messageListener (e) { - // We accept and post strings as opposed to objects for the sake of IE9 support; this - // will most likely be changed in the future - if (!e.data || !['string', 'object'].includes(typeof e.data)) { - return; - } - const {allowedOrigins} = this, - data = typeof e.data === 'object' ? e.data : JSON.parse(e.data); - if (!data || typeof data !== 'object' || data.namespace !== 'svg-edit' || - e.source !== this.frame.contentWindow || - (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) - ) { - // eslint-disable-next-line no-console -- Info for developers - console.error( - `The origin ${e.origin} was not whitelisted as an origin from ` + - `which responses may be received by this ${window.origin} script.` - ); - return; - } - addCallback(this, data); -} - -/** -* @callback module:EmbeddedSVGEdit.MessageListener -* @param {MessageEvent} e -* @returns {void} -*/ -/** -* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value -* @returns {module:EmbeddedSVGEdit.MessageListener} Event listener -*/ -function getMessageListener (t) { - return function (e) { - messageListener.call(t, e); - }; -} - -/** -* Embedded SVG-edit API. -* General usage: -* - Have an iframe somewhere pointing to a version of svg-edit > r1000. -* @example -// Initialize the magic with: -const svgCanvas = new EmbeddedSVGEdit(window.frames.svgedit); - -// Pass functions in this format: -svgCanvas.setSvgString('string'); - -// Or if a callback is needed: -svgCanvas.setSvgString('string')(function (data, error) { - if (error) { - // There was an error - } else { - // Handle data - } -}); - -// Everything is done with the same API as the real svg-edit, -// and all documentation is unchanged. - -// However, this file depends on the postMessage API which -// can only support JSON-serializable arguments and -// return values, so, for example, arguments whose value is -// 'undefined', a function, a non-finite number, or a built-in -// object like Date(), RegExp(), etc. will most likely not behave -// as expected. In such a case one may need to host -// the SVG editor on the same domain and reference the -// JavaScript methods on the frame itself. - -// The only other difference is when handling returns: -// the callback notation is used instead. -const blah = new EmbeddedSVGEdit(window.frames.svgedit); -blah.clearSelection('woot', 'blah', 1337, [1, 2, 3, 4, 5, 'moo'], -42, { - a: 'tree', b: 6, c: 9 -})(function () { console.log('GET DATA', args); }); -* -* @memberof module:EmbeddedSVGEdit -*/ -class EmbeddedSVGEdit { - /** - * @param {HTMLIFrameElement} frame - * @param {string[]} [allowedOrigins=[]] Array of origins from which incoming - * messages will be allowed when same origin is not used; defaults to none. - * If supplied, it should probably be the same as svgEditor's allowedOrigins - */ - constructor (frame, allowedOrigins) { - const that = this; - this.allowedOrigins = allowedOrigins || []; - // Initialize communication - this.frame = frame; - this.callbacks = {}; - // List of functions extracted with this: - // Run in firebug on http://svg-edit.googlecode.com/svn/trunk/docs/files/svgcanvas-js.html - - // for (const i=0,q=[],f = document.querySelectorAll('div.CFunction h3.CTitle a'); i < f.length; i++) { q.push(f[i].name); }; q - // const functions = ['clearSelection', 'addToSelection', 'removeFromSelection', 'open', 'save', 'getSvgString', 'setSvgString', - // 'createLayer', 'deleteCurrentLayer', 'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition', 'setLayerVisibility', - // 'moveSelectedToLayer', 'clear']; - - // Newer, well, it extracts things that aren't documented as well. All functions accessible through the normal thingy can now be accessed though the API - // const {svgCanvas} = frame.contentWindow; - // const l = []; - // for (const i in svgCanvas) { if (typeof svgCanvas[i] === 'function') { l.push(i);} }; - // alert("['" + l.join("', '") + "']"); - // Run in svgedit itself - const functions = [ - 'addExtension', - 'addSVGElementFromJson', - 'addToSelection', - 'alignSelectedElements', - 'assignAttributes', - 'bind', - 'call', - 'changeSelectedAttribute', - 'cleanupElement', - 'clear', - 'clearSelection', - 'clearSvgContentElement', - 'cloneLayer', - 'cloneSelectedElements', - 'convertGradients', - 'convertToGroup', - 'convertToNum', - 'convertToPath', - 'copySelectedElements', - 'createLayer', - 'cutSelectedElements', - 'cycleElement', - 'deleteCurrentLayer', - 'deleteSelectedElements', - 'embedImage', - 'exportPDF', - 'findDefs', - 'getBBox', - 'getBlur', - 'getBold', - 'getColor', - 'getContentElem', - 'getCurrentDrawing', - 'getDocumentTitle', - 'getEditorNS', - 'getElem', - 'getFillOpacity', - 'getFontColor', - 'getFontFamily', - 'getFontSize', - 'getHref', - 'getId', - 'getIntersectionList', - 'getItalic', - 'getMode', - 'getMouseTarget', - 'getNextId', - 'getOffset', - 'getOpacity', - 'getPaintOpacity', - 'getPrivateMethods', - 'getRefElem', - 'getResolution', - 'getRootElem', - 'getRotationAngle', - 'getSelectedElems', - 'getStrokeOpacity', - 'getStrokeWidth', - 'getStrokedBBox', - 'getStyle', - 'getSvgString', - 'getText', - 'getTitle', - 'getTransformList', - 'getUIStrings', - 'getUrlFromAttr', - 'getVersion', - 'getVisibleElements', - 'getVisibleElementsAndBBoxes', - 'getZoom', - 'groupSelectedElements', - 'groupSvgElem', - 'hasMatrixTransform', - 'identifyLayers', - 'importSvgString', - 'leaveContext', - 'linkControlPoints', - 'makeHyperlink', - 'matrixMultiply', - 'mergeAllLayers', - 'mergeLayer', - 'moveSelectedElements', - 'moveSelectedToLayer', - 'moveToBottomSelectedElement', - 'moveToTopSelectedElement', - 'moveUpDownSelected', - 'open', - 'pasteElements', - 'prepareSvg', - 'pushGroupProperties', - 'randomizeIds', - 'rasterExport', - 'ready', - 'recalculateAllSelectedDimensions', - 'recalculateDimensions', - 'remapElement', - 'removeFromSelection', - 'removeHyperlink', - 'removeUnusedDefElems', - 'renameCurrentLayer', - 'round', - 'runExtensions', - 'sanitizeSvg', - 'save', - 'selectAllInCurrentLayer', - 'selectOnly', - 'setBBoxZoom', - 'setBackground', - 'setBlur', - 'setBlurNoUndo', - 'setBlurOffsets', - 'setBold', - 'setColor', - 'setConfig', - 'setContext', - 'setCurrentLayer', - 'setCurrentLayerPosition', - 'setDocumentTitle', - 'setFillPaint', - 'setFontColor', - 'setFontFamily', - 'setFontSize', - 'setGoodImage', - 'setGradient', - 'setGroupTitle', - 'setHref', - 'setIdPrefix', - 'setImageURL', - 'setItalic', - 'setLayerVisibility', - 'setLinkURL', - 'setMode', - 'setOpacity', - 'setPaint', - 'setPaintOpacity', - 'setRectRadius', - 'setResolution', - 'setRotationAngle', - 'setSegType', - 'setStrokeAttr', - 'setStrokePaint', - 'setStrokeWidth', - 'setSvgString', - 'setTextContent', - 'setUiStrings', - 'setUseData', - 'setZoom', - 'svgCanvasToString', - 'svgToString', - 'transformListToTransform', - 'ungroupSelectedElement', - 'uniquifyElems', - 'updateCanvas', - 'zoomChanged' - ]; - - // TODO: rewrite the following, it's pretty scary. - for (const func of functions) { - this[func] = getCallbackSetter(func); - } - - // Older IE may need a polyfill for addEventListener, but so it would for SVG - window.addEventListener('message', getMessageListener(this)); - window.addEventListener('keydown', (e) => { - const {type, key} = e; - if (key === 'Backspace') { - e.preventDefault(); - const keyboardEvent = new KeyboardEvent(type, {key}); - that.frame.contentDocument.dispatchEvent(keyboardEvent); - } - }); - } - - /** - * @param {string} name - * @param {ArgumentsArray} args Signature dependent on function - * @param {GenericCallback} callback (This may be better than a promise in case adding an event.) - * @returns {Integer} - */ - send (name, args, callback) { // eslint-disable-line promise/prefer-await-to-callbacks - const that = this; - cbid++; - - this.callbacks[cbid] = callback; - setTimeout((function (callbackID) { - return function () { // Delay for the callback to be set in case its synchronous - /* - * Todo: Handle non-JSON arguments and return values (undefined, - * nonfinite numbers, functions, and built-in objects like Date, - * RegExp), etc.? Allow promises instead of callbacks? Review - * SVG-Edit functions for whether JSON-able parameters can be - * made compatile with all API functionality - */ - // We accept and post strings for the sake of IE9 support - let sameOriginWithGlobal = false; - try { - sameOriginWithGlobal = window.location.origin === that.frame.contentWindow.location.origin && - that.frame.contentWindow.svgEditor.canvas; - } catch (err) {} - - if (sameOriginWithGlobal) { - // Although we do not really need this API if we are working same - // domain, it could allow us to write in a way that would work - // cross-domain as well, assuming we stick to the argument limitations - // of the current JSON-based communication API (e.g., not passing - // callbacks). We might be able to address these shortcomings; see - // the todo elsewhere in this file. - const message = {id: callbackID}, - {svgEditor: {canvas: svgCanvas}} = that.frame.contentWindow; - try { - message.result = svgCanvas[name](...args); - } catch (err) { - message.error = err.message; - } - addCallback(that, message); - } else { // Requires the ext-xdomain-messaging.js extension - that.frame.contentWindow.postMessage(JSON.stringify({ - namespace: 'svgCanvas', id: callbackID, name, args - }), '*'); - } - }; - }(cbid)), 0); - - return cbid; - } -} - -export default EmbeddedSVGEdit; diff --git a/dist/editor/extensions/ext-arrows.js b/dist/editor/extensions/ext-arrows.js deleted file mode 100644 index 2b22cb0c..00000000 --- a/dist/editor/extensions/ext-arrows.js +++ /dev/null @@ -1,2006 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -/** - * @file ext-arrows.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ -var extArrows = { - name: 'arrows', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - colorChanged = function _colorChanged(elem) { - var color = elem.getAttribute('stroke'); - var mtypes = ['start', 'mid', 'end']; - var defs = svgCanvas.findDefs(); - $.each(mtypes, function (i, type) { - var marker = getLinked(elem, 'marker-' + type); - - if (!marker) { - return; - } - - var curColor = $(marker).children().attr('fill'); - var curD = $(marker).children().attr('d'); - - if (curColor === color) { - return; - } - - var allMarkers = $(defs).find('marker'); - var newMarker = null; // Different color, check if already made - - allMarkers.each(function () { - var attrs = $(this).children().attr(['fill', 'd']); - - if (attrs.fill === color && attrs.d === curD) { - // Found another marker with this color and this path - newMarker = this; - } - }); - - if (!newMarker) { - // Create a new marker with this color - var lastId = marker.id; - var dir = lastId.includes('_fw') ? 'fw' : 'bk'; - newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length); - $(newMarker).children().attr('fill', color); - } - - $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed - - var remove = true; - $(S.svgcontent).find('line, polyline, path, polygon').each(function () { - var element = this; - $.each(mtypes, function (j, mtype) { - if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { - remove = false; - return remove; - } - - return undefined; - }); - - if (!remove) { - return false; - } - - return undefined; - }); // Not found, so can safely remove - - if (remove) { - $(marker).remove(); - } - }); - }; - - setArrow = function _setArrow() { - resetMarker(); - var type = this.value; - - if (type === 'none') { - return; - } // Set marker on element - - - var dir = 'fw'; - - if (type === 'mid_bk') { - type = 'mid'; - dir = 'bk'; - } else if (type === 'both') { - addMarker('bk', type); - svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')'); - type = 'end'; - dir = 'fw'; - } else if (type === 'start') { - dir = 'bk'; - } - - addMarker(dir, type); - svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')'); - svgCanvas.call('changed', selElems); - }; - - addMarker = function _addMarker(dir, type, id) { - // TODO: Make marker (or use?) per arrow type, since refX can be different - id = id || arrowprefix + dir; - var data = pathdata[dir]; - - if (type === 'mid') { - data.refx = 5; - } - - var marker = svgCanvas.getElem(id); - - if (!marker) { - marker = addElem({ - element: 'marker', - attr: { - viewBox: '0 0 10 10', - id: id, - refY: 5, - markerUnits: 'strokeWidth', - markerWidth: 5, - markerHeight: 5, - orient: 'auto', - style: 'pointer-events:none' // Currently needed for Opera - - } - }); - var arrow = addElem({ - element: 'path', - attr: { - d: data.d, - fill: '#000000' - } - }); - marker.append(arrow); - svgCanvas.findDefs().append(marker); - } - - marker.setAttribute('refX', data.refx); - return marker; - }; - - resetMarker = function _resetMarker() { - var el = selElems[0]; - el.removeAttribute('marker-start'); - el.removeAttribute('marker-mid'); - el.removeAttribute('marker-end'); - }; - - showPanel = function _showPanel(on) { - $('#arrow_panel').toggle(on); - - if (on) { - var el = selElems[0]; - var end = el.getAttribute('marker-end'); - var start = el.getAttribute('marker-start'); - var mid = el.getAttribute('marker-mid'); - var val; - - if (end && start) { - val = 'both'; - } else if (end) { - val = 'end'; - } else if (start) { - val = 'start'; - } else if (mid) { - val = 'mid'; - - if (mid.includes('bk')) { - val = 'mid_bk'; - } - } - - if (!start && !mid && !end) { - val = 'none'; - } - - $('#arrow_list').val(val); - } - }; - - getLinked = function _getLinked(elem, attr) { - var str = elem.getAttribute(attr); - - if (!str) { - return null; - } - - var m = str.match(/\(#(.*)\)/); // const m = str.match(/\(#(?.+)\)/); - // if (!m || !m.groups.id) { - - if (!m || m.length !== 2) { - return null; - } - - return svgCanvas.getElem(m[1]); // return svgCanvas.getElem(m.groups.id); - }; - - unsetArrowNonce = function _unsetArrowNonce(win) { - randomizeIds = false; - arrowprefix = prefix; - pathdata.fw.id = arrowprefix + 'fw'; - pathdata.bk.id = arrowprefix + 'bk'; - }; - - setArrowNonce = function _setArrowNonce(win, n) { - randomizeIds = true; - arrowprefix = prefix + n + '_'; - pathdata.fw.id = arrowprefix + 'fw'; - pathdata.bk.id = arrowprefix + 'bk'; - }; - - _context2.next = 10; - return S.importLocale(); - - case 10: - strings = _context2.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - // {svgcontent} = S, - addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_'; - randomizeIds = S.randomize_ids; - /** - * @param {Window} win - * @param {!(string|Integer)} n - * @returns {void} - */ - - svgCanvas.bind('setnonce', setArrowNonce); - svgCanvas.bind('unsetnonce', unsetArrowNonce); - - if (randomizeIds) { - arrowprefix = prefix + nonce + '_'; - } else { - arrowprefix = prefix; - } - - pathdata = { - fw: { - d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', - refx: 8, - id: arrowprefix + 'fw' - }, - bk: { - d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', - refx: 2, - id: arrowprefix + 'bk' - } - }; - /** - * Gets linked element. - * @param {Element} elem - * @param {string} attr - * @returns {Element} - */ - - contextTools = [{ - type: 'select', - panel: 'arrow_panel', - id: 'arrow_list', - defval: 'none', - events: { - change: setArrow - } - }]; - return _context2.abrupt("return", { - name: strings.name, - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#arrow_panel').hide(); // Set ID so it can be translated in locale file - - $('#arrow_list option')[0].id = 'connector_no_arrow'; - }, - addLangData: function addLangData(_ref) { - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var lang, importLocale, _yield$importLocale, langList; - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - lang = _ref.lang, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); - - case 3: - _yield$importLocale = _context.sent; - langList = _yield$importLocale.langList; - return _context.abrupt("return", { - data: langList - }); - - case 6: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var markerElems = ['line', 'path', 'polyline', 'polygon']; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && markerElems.includes(elem.tagName)) { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) { - var elem = opts.elems[0]; - - if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { - // const start = elem.getAttribute('marker-start'); - // const mid = elem.getAttribute('marker-mid'); - // const end = elem.getAttribute('marker-end'); - // Has marker, so see if it should match color - colorChanged(elem); - } - } - }); - - case 21: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - } -}; - -export default extArrows; -//# sourceMappingURL=ext-arrows.js.map diff --git a/dist/editor/extensions/ext-arrows.js.map b/dist/editor/extensions/ext-arrows.js.map deleted file mode 100644 index 66481559..00000000 --- a/dist/editor/extensions/ext-arrows.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-arrows.js","sources":["../../../src/editor/extensions/ext-arrows.js"],"sourcesContent":["/**\n * @file ext-arrows.js\n *\n * @license MIT\n *\n * @copyright 2010 Alexis Deveria\n *\n */\n\nexport default {\n name: 'arrows',\n async init (S) {\n const strings = await S.importLocale();\n const svgEditor = this;\n const svgCanvas = svgEditor.canvas;\n const // {svgcontent} = S,\n addElem = svgCanvas.addSVGElementFromJson,\n {nonce, $} = S,\n prefix = 'se_arrow_';\n\n let selElems, arrowprefix, randomizeIds = S.randomize_ids;\n\n /**\n * @param {Window} win\n * @param {!(string|Integer)} n\n * @returns {void}\n */\n function setArrowNonce (win, n) {\n randomizeIds = true;\n arrowprefix = prefix + n + '_';\n pathdata.fw.id = arrowprefix + 'fw';\n pathdata.bk.id = arrowprefix + 'bk';\n }\n\n /**\n * @param {Window} win\n * @returns {void}\n */\n function unsetArrowNonce (win) {\n randomizeIds = false;\n arrowprefix = prefix;\n pathdata.fw.id = arrowprefix + 'fw';\n pathdata.bk.id = arrowprefix + 'bk';\n }\n\n svgCanvas.bind('setnonce', setArrowNonce);\n svgCanvas.bind('unsetnonce', unsetArrowNonce);\n\n if (randomizeIds) {\n arrowprefix = prefix + nonce + '_';\n } else {\n arrowprefix = prefix;\n }\n\n const pathdata = {\n fw: {d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', refx: 8, id: arrowprefix + 'fw'},\n bk: {d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', refx: 2, id: arrowprefix + 'bk'}\n };\n\n /**\n * Gets linked element.\n * @param {Element} elem\n * @param {string} attr\n * @returns {Element}\n */\n function getLinked (elem, attr) {\n const str = elem.getAttribute(attr);\n if (!str) { return null; }\n const m = str.match(/\\(#(.*)\\)/);\n // const m = str.match(/\\(#(?.+)\\)/);\n // if (!m || !m.groups.id) {\n if (!m || m.length !== 2) {\n return null;\n }\n return svgCanvas.getElem(m[1]);\n // return svgCanvas.getElem(m.groups.id);\n }\n\n /**\n * @param {boolean} on\n * @returns {void}\n */\n function showPanel (on) {\n $('#arrow_panel').toggle(on);\n if (on) {\n const el = selElems[0];\n const end = el.getAttribute('marker-end');\n const start = el.getAttribute('marker-start');\n const mid = el.getAttribute('marker-mid');\n let val;\n if (end && start) {\n val = 'both';\n } else if (end) {\n val = 'end';\n } else if (start) {\n val = 'start';\n } else if (mid) {\n val = 'mid';\n if (mid.includes('bk')) {\n val = 'mid_bk';\n }\n }\n\n if (!start && !mid && !end) {\n val = 'none';\n }\n\n $('#arrow_list').val(val);\n }\n }\n\n /**\n *\n * @returns {void}\n */\n function resetMarker () {\n const el = selElems[0];\n el.removeAttribute('marker-start');\n el.removeAttribute('marker-mid');\n el.removeAttribute('marker-end');\n }\n\n /**\n * @param {\"bk\"|\"fw\"} dir\n * @param {\"both\"|\"mid\"|\"end\"|\"start\"} type\n * @param {string} id\n * @returns {Element}\n */\n function addMarker (dir, type, id) {\n // TODO: Make marker (or use?) per arrow type, since refX can be different\n id = id || arrowprefix + dir;\n\n const data = pathdata[dir];\n\n if (type === 'mid') {\n data.refx = 5;\n }\n\n let marker = svgCanvas.getElem(id);\n if (!marker) {\n marker = addElem({\n element: 'marker',\n attr: {\n viewBox: '0 0 10 10',\n id,\n refY: 5,\n markerUnits: 'strokeWidth',\n markerWidth: 5,\n markerHeight: 5,\n orient: 'auto',\n style: 'pointer-events:none' // Currently needed for Opera\n }\n });\n const arrow = addElem({\n element: 'path',\n attr: {\n d: data.d,\n fill: '#000000'\n }\n });\n marker.append(arrow);\n svgCanvas.findDefs().append(marker);\n }\n\n marker.setAttribute('refX', data.refx);\n\n return marker;\n }\n\n /**\n *\n * @returns {void}\n */\n function setArrow () {\n resetMarker();\n\n let type = this.value;\n if (type === 'none') {\n return;\n }\n\n // Set marker on element\n let dir = 'fw';\n if (type === 'mid_bk') {\n type = 'mid';\n dir = 'bk';\n } else if (type === 'both') {\n addMarker('bk', type);\n svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')');\n type = 'end';\n dir = 'fw';\n } else if (type === 'start') {\n dir = 'bk';\n }\n\n addMarker(dir, type);\n svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')');\n svgCanvas.call('changed', selElems);\n }\n\n /**\n * @param {Element} elem\n * @returns {void}\n */\n function colorChanged (elem) {\n const color = elem.getAttribute('stroke');\n const mtypes = ['start', 'mid', 'end'];\n const defs = svgCanvas.findDefs();\n\n $.each(mtypes, function (i, type) {\n const marker = getLinked(elem, 'marker-' + type);\n if (!marker) { return; }\n\n const curColor = $(marker).children().attr('fill');\n const curD = $(marker).children().attr('d');\n if (curColor === color) { return; }\n\n const allMarkers = $(defs).find('marker');\n let newMarker = null;\n // Different color, check if already made\n allMarkers.each(function () {\n const attrs = $(this).children().attr(['fill', 'd']);\n if (attrs.fill === color && attrs.d === curD) {\n // Found another marker with this color and this path\n newMarker = this;\n }\n });\n\n if (!newMarker) {\n // Create a new marker with this color\n const lastId = marker.id;\n const dir = lastId.includes('_fw') ? 'fw' : 'bk';\n\n newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length);\n\n $(newMarker).children().attr('fill', color);\n }\n\n $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')');\n\n // Check if last marker can be removed\n let remove = true;\n $(S.svgcontent).find('line, polyline, path, polygon').each(function () {\n const element = this;\n $.each(mtypes, function (j, mtype) {\n if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') {\n remove = false;\n return remove;\n }\n return undefined;\n });\n if (!remove) { return false; }\n return undefined;\n });\n\n // Not found, so can safely remove\n if (remove) {\n $(marker).remove();\n }\n });\n }\n\n const contextTools = [\n {\n type: 'select',\n panel: 'arrow_panel',\n id: 'arrow_list',\n defval: 'none',\n events: {\n change: setArrow\n }\n }\n ];\n\n return {\n name: strings.name,\n context_tools: strings.contextTools.map((contextTool, i) => {\n return Object.assign(contextTools[i], contextTool);\n }),\n callback () {\n $('#arrow_panel').hide();\n // Set ID so it can be translated in locale file\n $('#arrow_list option')[0].id = 'connector_no_arrow';\n },\n async addLangData ({lang, importLocale}) {\n const {langList} = await importLocale();\n return {\n data: langList\n };\n },\n selectedChanged (opts) {\n // Use this to update the current selected elements\n selElems = opts.elems;\n\n const markerElems = ['line', 'path', 'polyline', 'polygon'];\n let i = selElems.length;\n while (i--) {\n const elem = selElems[i];\n if (elem && markerElems.includes(elem.tagName)) {\n if (opts.selectedElement && !opts.multiselected) {\n showPanel(true);\n } else {\n showPanel(false);\n }\n } else {\n showPanel(false);\n }\n }\n },\n elementChanged (opts) {\n const elem = opts.elems[0];\n if (elem && (\n elem.getAttribute('marker-start') ||\n elem.getAttribute('marker-mid') ||\n elem.getAttribute('marker-end')\n )) {\n // const start = elem.getAttribute('marker-start');\n // const mid = elem.getAttribute('marker-mid');\n // const end = elem.getAttribute('marker-end');\n // Has marker, so see if it should match color\n colorChanged(elem);\n }\n }\n };\n }\n};\n"],"names":["name","init","S","setArrowNonce","unsetArrowNonce","getLinked","showPanel","resetMarker","addMarker","setArrow","colorChanged","elem","color","getAttribute","mtypes","defs","svgCanvas","findDefs","$","each","i","type","marker","curColor","children","attr","curD","allMarkers","find","newMarker","attrs","fill","d","lastId","id","dir","includes","arrowprefix","length","remove","svgcontent","element","j","mtype","undefined","value","changeSelectedAttribute","pathdata","bk","call","selElems","data","refx","getElem","addElem","viewBox","refY","markerUnits","markerWidth","markerHeight","orient","style","arrow","append","setAttribute","el","removeAttribute","on","toggle","end","start","mid","val","str","m","match","win","randomizeIds","prefix","fw","n","importLocale","strings","svgEditor","canvas","addSVGElementFromJson","nonce","randomize_ids","bind","contextTools","panel","defval","events","change","context_tools","map","contextTool","Object","assign","callback","hide","addLangData","lang","langList","selectedChanged","opts","elems","markerElems","tagName","selectedElement","multiselected","elementChanged"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;AASA,gBAAe;AACbA,EAAAA,IAAI,EAAE,QADO;AAEPC,EAAAA,IAFO,gBAEDC,CAFC,EAEE;AAAA;;AAAA;AAAA,yGAgBJC,aAhBI,EA2BJC,eA3BI,YAsDJC,SAtDI,EAuEJC,SAvEI,EAwGJC,WAxGI,EAqHJC,SArHI,EAkKJC,QAlKI,EAiMJC,YAjMI;AAAA;AAAA;AAAA;AAAA;AAiMJA,cAAAA,YAjMI,0BAiMUC,IAjMV,EAiMgB;AAC3B,oBAAMC,KAAK,GAAGD,IAAI,CAACE,YAAL,CAAkB,QAAlB,CAAd;AACA,oBAAMC,MAAM,GAAG,CAAC,OAAD,EAAU,KAAV,EAAiB,KAAjB,CAAf;AACA,oBAAMC,IAAI,GAAGC,SAAS,CAACC,QAAV,EAAb;AAEAC,gBAAAA,CAAC,CAACC,IAAF,CAAOL,MAAP,EAAe,UAAUM,CAAV,EAAaC,IAAb,EAAmB;AAChC,sBAAMC,MAAM,GAAGjB,SAAS,CAACM,IAAD,EAAO,YAAYU,IAAnB,CAAxB;;AACA,sBAAI,CAACC,MAAL,EAAa;AAAE;AAAS;;AAExB,sBAAMC,QAAQ,GAAGL,CAAC,CAACI,MAAD,CAAD,CAAUE,QAAV,GAAqBC,IAArB,CAA0B,MAA1B,CAAjB;AACA,sBAAMC,IAAI,GAAGR,CAAC,CAACI,MAAD,CAAD,CAAUE,QAAV,GAAqBC,IAArB,CAA0B,GAA1B,CAAb;;AACA,sBAAIF,QAAQ,KAAKX,KAAjB,EAAwB;AAAE;AAAS;;AAEnC,sBAAMe,UAAU,GAAGT,CAAC,CAACH,IAAD,CAAD,CAAQa,IAAR,CAAa,QAAb,CAAnB;AACA,sBAAIC,SAAS,GAAG,IAAhB,CATgC;;AAWhCF,kBAAAA,UAAU,CAACR,IAAX,CAAgB,YAAY;AAC1B,wBAAMW,KAAK,GAAGZ,CAAC,CAAC,IAAD,CAAD,CAAQM,QAAR,GAAmBC,IAAnB,CAAwB,CAAC,MAAD,EAAS,GAAT,CAAxB,CAAd;;AACA,wBAAIK,KAAK,CAACC,IAAN,KAAenB,KAAf,IAAwBkB,KAAK,CAACE,CAAN,KAAYN,IAAxC,EAA8C;AAC5C;AACAG,sBAAAA,SAAS,GAAG,IAAZ;AACD;AACF,mBAND;;AAQA,sBAAI,CAACA,SAAL,EAAgB;AACd;AACA,wBAAMI,MAAM,GAAGX,MAAM,CAACY,EAAtB;AACA,wBAAMC,GAAG,GAAGF,MAAM,CAACG,QAAP,CAAgB,KAAhB,IAAyB,IAAzB,GAAgC,IAA5C;AAEAP,oBAAAA,SAAS,GAAGrB,SAAS,CAAC2B,GAAD,EAAMd,IAAN,EAAYgB,WAAW,GAAGF,GAAd,GAAoBR,UAAU,CAACW,MAA3C,CAArB;AAEApB,oBAAAA,CAAC,CAACW,SAAD,CAAD,CAAaL,QAAb,GAAwBC,IAAxB,CAA6B,MAA7B,EAAqCb,KAArC;AACD;;AAEDM,kBAAAA,CAAC,CAACP,IAAD,CAAD,CAAQc,IAAR,CAAa,YAAYJ,IAAzB,EAA+B,UAAUQ,SAAS,CAACK,EAApB,GAAyB,GAAxD,EA7BgC;;AAgChC,sBAAIK,MAAM,GAAG,IAAb;AACArB,kBAAAA,CAAC,CAAChB,CAAC,CAACsC,UAAH,CAAD,CAAgBZ,IAAhB,CAAqB,+BAArB,EAAsDT,IAAtD,CAA2D,YAAY;AACrE,wBAAMsB,OAAO,GAAG,IAAhB;AACAvB,oBAAAA,CAAC,CAACC,IAAF,CAAOL,MAAP,EAAe,UAAU4B,CAAV,EAAaC,KAAb,EAAoB;AACjC,0BAAIzB,CAAC,CAACuB,OAAD,CAAD,CAAWhB,IAAX,CAAgB,YAAYkB,KAA5B,MAAuC,UAAUrB,MAAM,CAACY,EAAjB,GAAsB,GAAjE,EAAsE;AACpEK,wBAAAA,MAAM,GAAG,KAAT;AACA,+BAAOA,MAAP;AACD;;AACD,6BAAOK,SAAP;AACD,qBAND;;AAOA,wBAAI,CAACL,MAAL,EAAa;AAAE,6BAAO,KAAP;AAAe;;AAC9B,2BAAOK,SAAP;AACD,mBAXD,EAjCgC;;AA+ChC,sBAAIL,MAAJ,EAAY;AACVrB,oBAAAA,CAAC,CAACI,MAAD,CAAD,CAAUiB,MAAV;AACD;AACF,iBAlDD;AAmDD,eAzPY;;AAkKJ9B,cAAAA,QAlKI,wBAkKQ;AACnBF,gBAAAA,WAAW;AAEX,oBAAIc,IAAI,GAAG,KAAKwB,KAAhB;;AACA,oBAAIxB,IAAI,KAAK,MAAb,EAAqB;AACnB;AACD,iBANkB;;;AASnB,oBAAIc,GAAG,GAAG,IAAV;;AACA,oBAAId,IAAI,KAAK,QAAb,EAAuB;AACrBA,kBAAAA,IAAI,GAAG,KAAP;AACAc,kBAAAA,GAAG,GAAG,IAAN;AACD,iBAHD,MAGO,IAAId,IAAI,KAAK,MAAb,EAAqB;AAC1Bb,kBAAAA,SAAS,CAAC,IAAD,EAAOa,IAAP,CAAT;AACAL,kBAAAA,SAAS,CAAC8B,uBAAV,CAAkC,cAAlC,EAAkD,UAAUC,QAAQ,CAACC,EAAT,CAAYd,EAAtB,GAA2B,GAA7E;AACAb,kBAAAA,IAAI,GAAG,KAAP;AACAc,kBAAAA,GAAG,GAAG,IAAN;AACD,iBALM,MAKA,IAAId,IAAI,KAAK,OAAb,EAAsB;AAC3Bc,kBAAAA,GAAG,GAAG,IAAN;AACD;;AAED3B,gBAAAA,SAAS,CAAC2B,GAAD,EAAMd,IAAN,CAAT;AACAL,gBAAAA,SAAS,CAAC8B,uBAAV,CAAkC,YAAYzB,IAA9C,EAAoD,UAAU0B,QAAQ,CAACZ,GAAD,CAAR,CAAcD,EAAxB,GAA6B,GAAjF;AACAlB,gBAAAA,SAAS,CAACiC,IAAV,CAAe,SAAf,EAA0BC,QAA1B;AACD,eA3LY;;AAqHJ1C,cAAAA,SArHI,uBAqHO2B,GArHP,EAqHYd,IArHZ,EAqHkBa,EArHlB,EAqHsB;AACjC;AACAA,gBAAAA,EAAE,GAAGA,EAAE,IAAIG,WAAW,GAAGF,GAAzB;AAEA,oBAAMgB,IAAI,GAAGJ,QAAQ,CAACZ,GAAD,CAArB;;AAEA,oBAAId,IAAI,KAAK,KAAb,EAAoB;AAClB8B,kBAAAA,IAAI,CAACC,IAAL,GAAY,CAAZ;AACD;;AAED,oBAAI9B,MAAM,GAAGN,SAAS,CAACqC,OAAV,CAAkBnB,EAAlB,CAAb;;AACA,oBAAI,CAACZ,MAAL,EAAa;AACXA,kBAAAA,MAAM,GAAGgC,OAAO,CAAC;AACfb,oBAAAA,OAAO,EAAE,QADM;AAEfhB,oBAAAA,IAAI,EAAE;AACJ8B,sBAAAA,OAAO,EAAE,WADL;AAEJrB,sBAAAA,EAAE,EAAFA,EAFI;AAGJsB,sBAAAA,IAAI,EAAE,CAHF;AAIJC,sBAAAA,WAAW,EAAE,aAJT;AAKJC,sBAAAA,WAAW,EAAE,CALT;AAMJC,sBAAAA,YAAY,EAAE,CANV;AAOJC,sBAAAA,MAAM,EAAE,MAPJ;AAQJC,sBAAAA,KAAK,EAAE,qBARH;;AAAA;AAFS,mBAAD,CAAhB;AAaA,sBAAMC,KAAK,GAAGR,OAAO,CAAC;AACpBb,oBAAAA,OAAO,EAAE,MADW;AAEpBhB,oBAAAA,IAAI,EAAE;AACJO,sBAAAA,CAAC,EAAEmB,IAAI,CAACnB,CADJ;AAEJD,sBAAAA,IAAI,EAAE;AAFF;AAFc,mBAAD,CAArB;AAOAT,kBAAAA,MAAM,CAACyC,MAAP,CAAcD,KAAd;AACA9C,kBAAAA,SAAS,CAACC,QAAV,GAAqB8C,MAArB,CAA4BzC,MAA5B;AACD;;AAEDA,gBAAAA,MAAM,CAAC0C,YAAP,CAAoB,MAApB,EAA4Bb,IAAI,CAACC,IAAjC;AAEA,uBAAO9B,MAAP;AACD,eA5JY;;AAwGJf,cAAAA,WAxGI,2BAwGW;AACtB,oBAAM0D,EAAE,GAAGf,QAAQ,CAAC,CAAD,CAAnB;AACAe,gBAAAA,EAAE,CAACC,eAAH,CAAmB,cAAnB;AACAD,gBAAAA,EAAE,CAACC,eAAH,CAAmB,YAAnB;AACAD,gBAAAA,EAAE,CAACC,eAAH,CAAmB,YAAnB;AACD,eA7GY;;AAuEJ5D,cAAAA,SAvEI,uBAuEO6D,EAvEP,EAuEW;AACtBjD,gBAAAA,CAAC,CAAC,cAAD,CAAD,CAAkBkD,MAAlB,CAAyBD,EAAzB;;AACA,oBAAIA,EAAJ,EAAQ;AACN,sBAAMF,EAAE,GAAGf,QAAQ,CAAC,CAAD,CAAnB;AACA,sBAAMmB,GAAG,GAAGJ,EAAE,CAACpD,YAAH,CAAgB,YAAhB,CAAZ;AACA,sBAAMyD,KAAK,GAAGL,EAAE,CAACpD,YAAH,CAAgB,cAAhB,CAAd;AACA,sBAAM0D,GAAG,GAAGN,EAAE,CAACpD,YAAH,CAAgB,YAAhB,CAAZ;AACA,sBAAI2D,GAAJ;;AACA,sBAAIH,GAAG,IAAIC,KAAX,EAAkB;AAChBE,oBAAAA,GAAG,GAAG,MAAN;AACD,mBAFD,MAEO,IAAIH,GAAJ,EAAS;AACdG,oBAAAA,GAAG,GAAG,KAAN;AACD,mBAFM,MAEA,IAAIF,KAAJ,EAAW;AAChBE,oBAAAA,GAAG,GAAG,OAAN;AACD,mBAFM,MAEA,IAAID,GAAJ,EAAS;AACdC,oBAAAA,GAAG,GAAG,KAAN;;AACA,wBAAID,GAAG,CAACnC,QAAJ,CAAa,IAAb,CAAJ,EAAwB;AACtBoC,sBAAAA,GAAG,GAAG,QAAN;AACD;AACF;;AAED,sBAAI,CAACF,KAAD,IAAU,CAACC,GAAX,IAAkB,CAACF,GAAvB,EAA4B;AAC1BG,oBAAAA,GAAG,GAAG,MAAN;AACD;;AAEDtD,kBAAAA,CAAC,CAAC,aAAD,CAAD,CAAiBsD,GAAjB,CAAqBA,GAArB;AACD;AACF,eAlGY;;AAsDJnE,cAAAA,SAtDI,uBAsDOM,IAtDP,EAsDac,IAtDb,EAsDmB;AAC9B,oBAAMgD,GAAG,GAAG9D,IAAI,CAACE,YAAL,CAAkBY,IAAlB,CAAZ;;AACA,oBAAI,CAACgD,GAAL,EAAU;AAAE,yBAAO,IAAP;AAAc;;AAC1B,oBAAMC,CAAC,GAAGD,GAAG,CAACE,KAAJ,CAAU,WAAV,CAAV,CAH8B;AAK9B;;AACA,oBAAI,CAACD,CAAD,IAAMA,CAAC,CAACpC,MAAF,KAAa,CAAvB,EAA0B;AACxB,yBAAO,IAAP;AACD;;AACD,uBAAOtB,SAAS,CAACqC,OAAV,CAAkBqB,CAAC,CAAC,CAAD,CAAnB,CAAP,CAT8B;AAW/B,eAjEY;;AA2BJtE,cAAAA,eA3BI,6BA2BawE,GA3Bb,EA2BkB;AAC7BC,gBAAAA,YAAY,GAAG,KAAf;AACAxC,gBAAAA,WAAW,GAAGyC,MAAd;AACA/B,gBAAAA,QAAQ,CAACgC,EAAT,CAAY7C,EAAZ,GAAiBG,WAAW,GAAG,IAA/B;AACAU,gBAAAA,QAAQ,CAACC,EAAT,CAAYd,EAAZ,GAAiBG,WAAW,GAAG,IAA/B;AACD,eAhCY;;AAgBJlC,cAAAA,aAhBI,2BAgBWyE,GAhBX,EAgBgBI,CAhBhB,EAgBmB;AAC9BH,gBAAAA,YAAY,GAAG,IAAf;AACAxC,gBAAAA,WAAW,GAAGyC,MAAM,GAAGE,CAAT,GAAa,GAA3B;AACAjC,gBAAAA,QAAQ,CAACgC,EAAT,CAAY7C,EAAZ,GAAiBG,WAAW,GAAG,IAA/B;AACAU,gBAAAA,QAAQ,CAACC,EAAT,CAAYd,EAAZ,GAAiBG,WAAW,GAAG,IAA/B;AACD,eArBY;;AAAA;AAAA,qBACSnC,CAAC,CAAC+E,YAAF,EADT;;AAAA;AACPC,cAAAA,OADO;AAEPC,cAAAA,SAFO,GAEK,KAFL;AAGPnE,cAAAA,SAHO,GAGKmE,SAAS,CAACC,MAHf;AAIP;AACJ9B,cAAAA,OALW,GAKDtC,SAAS,CAACqE,qBALT,EAMVC,KANU,GAMEpF,CANF,CAMVoF,KANU,EAMHpE,CANG,GAMEhB,CANF,CAMHgB,CANG,EAOX4D,MAPW,GAOF,WAPE;AAScD,cAAAA,YATd,GAS6B3E,CAAC,CAACqF,aAT/B;AAWb;;;;;;AAuBAvE,cAAAA,SAAS,CAACwE,IAAV,CAAe,UAAf,EAA2BrF,aAA3B;AACAa,cAAAA,SAAS,CAACwE,IAAV,CAAe,YAAf,EAA6BpF,eAA7B;;AAEA,kBAAIyE,YAAJ,EAAkB;AAChBxC,gBAAAA,WAAW,GAAGyC,MAAM,GAAGQ,KAAT,GAAiB,GAA/B;AACD,eAFD,MAEO;AACLjD,gBAAAA,WAAW,GAAGyC,MAAd;AACD;;AAEK/B,cAAAA,QA3CO,GA2CI;AACfgC,gBAAAA,EAAE,EAAE;AAAC/C,kBAAAA,CAAC,EAAE,6BAAJ;AAAmCoB,kBAAAA,IAAI,EAAE,CAAzC;AAA4ClB,kBAAAA,EAAE,EAAEG,WAAW,GAAG;AAA9D,iBADW;AAEfW,gBAAAA,EAAE,EAAE;AAAChB,kBAAAA,CAAC,EAAE,8BAAJ;AAAoCoB,kBAAAA,IAAI,EAAE,CAA1C;AAA6ClB,kBAAAA,EAAE,EAAEG,WAAW,GAAG;AAA/D;AAFW,eA3CJ;AAgDb;;;;;;;AA2MMoD,cAAAA,YA3PO,GA2PQ,CACnB;AACEpE,gBAAAA,IAAI,EAAE,QADR;AAEEqE,gBAAAA,KAAK,EAAE,aAFT;AAGExD,gBAAAA,EAAE,EAAE,YAHN;AAIEyD,gBAAAA,MAAM,EAAE,MAJV;AAKEC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,MAAM,EAAEpF;AADF;AALV,eADmB,CA3PR;AAAA,gDAuQN;AACLT,gBAAAA,IAAI,EAAEkF,OAAO,CAAClF,IADT;AAEL8F,gBAAAA,aAAa,EAAEZ,OAAO,CAACO,YAAR,CAAqBM,GAArB,CAAyB,UAACC,WAAD,EAAc5E,CAAd,EAAoB;AAC1D,yBAAO6E,MAAM,CAACC,MAAP,CAAcT,YAAY,CAACrE,CAAD,CAA1B,EAA+B4E,WAA/B,CAAP;AACD,iBAFc,CAFV;AAKLG,gBAAAA,QALK,sBAKO;AACVjF,kBAAAA,CAAC,CAAC,cAAD,CAAD,CAAkBkF,IAAlB,GADU;;AAGVlF,kBAAAA,CAAC,CAAC,oBAAD,CAAD,CAAwB,CAAxB,EAA2BgB,EAA3B,GAAgC,oBAAhC;AACD,iBATI;AAUCmE,gBAAAA,WAVD,6BAUoC;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAArBC,4BAAAA,IAAqB,QAArBA,IAAqB,EAAfrB,YAAe,QAAfA,YAAe;AAAA;AAAA,mCACdA,YAAY,EADE;;AAAA;AAAA;AAChCsB,4BAAAA,QADgC,uBAChCA,QADgC;AAAA,6DAEhC;AACLpD,8BAAAA,IAAI,EAAEoD;AADD,6BAFgC;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKxC,iBAfI;AAgBLC,gBAAAA,eAhBK,2BAgBYC,IAhBZ,EAgBkB;AACrB;AACAvD,kBAAAA,QAAQ,GAAGuD,IAAI,CAACC,KAAhB;AAEA,sBAAMC,WAAW,GAAG,CAAC,MAAD,EAAS,MAAT,EAAiB,UAAjB,EAA6B,SAA7B,CAApB;AACA,sBAAIvF,CAAC,GAAG8B,QAAQ,CAACZ,MAAjB;;AACA,yBAAOlB,CAAC,EAAR,EAAY;AACV,wBAAMT,IAAI,GAAGuC,QAAQ,CAAC9B,CAAD,CAArB;;AACA,wBAAIT,IAAI,IAAIgG,WAAW,CAACvE,QAAZ,CAAqBzB,IAAI,CAACiG,OAA1B,CAAZ,EAAgD;AAC9C,0BAAIH,IAAI,CAACI,eAAL,IAAwB,CAACJ,IAAI,CAACK,aAAlC,EAAiD;AAC/CxG,wBAAAA,SAAS,CAAC,IAAD,CAAT;AACD,uBAFD,MAEO;AACLA,wBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF,qBAND,MAMO;AACLA,sBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF;AACF,iBAlCI;AAmCLyG,gBAAAA,cAnCK,0BAmCWN,IAnCX,EAmCiB;AACpB,sBAAM9F,IAAI,GAAG8F,IAAI,CAACC,KAAL,CAAW,CAAX,CAAb;;AACA,sBAAI/F,IAAI,KACNA,IAAI,CAACE,YAAL,CAAkB,cAAlB,KACAF,IAAI,CAACE,YAAL,CAAkB,YAAlB,CADA,IAEAF,IAAI,CAACE,YAAL,CAAkB,YAAlB,CAHM,CAAR,EAIG;AACD;AACA;AACA;AACA;AACAH,oBAAAA,YAAY,CAACC,IAAD,CAAZ;AACD;AACF;AAhDI,eAvQM;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyTd;AA3TY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-closepath.js b/dist/editor/extensions/ext-closepath.js deleted file mode 100644 index 53a6a9cd..00000000 --- a/dist/editor/extensions/ext-closepath.js +++ /dev/null @@ -1,4090 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -/* 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; - } -})(); - -// The button toggles whether the path is open or closed - -var extClosepath = { - name: 'closepath', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref.importLocale, $ = _ref.$; - _context.next = 3; - return importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - - updateButton = function updateButton(path) { - var seglist = path.pathSegList, - closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, - showbutton = closed ? '#tool_openpath' : '#tool_closepath', - hidebutton = closed ? '#tool_closepath' : '#tool_openpath'; - $(hidebutton).hide(); - $(showbutton).show(); - }; - - showPanel = function showPanel(on) { - $('#closepath_panel').toggle(on); - - if (on) { - var path = selElems[0]; - - if (path) { - updateButton(path); - } - } - }; - - toggleClosed = function toggleClosed() { - var path = selElems[0]; - - if (path) { - var seglist = path.pathSegList, - last = seglist.numberOfItems - 1; // is closed - - if (seglist.getItem(last).pathSegType === 1) { - seglist.removeItem(last); - } else { - seglist.appendItem(path.createSVGPathSegClosePath()); - } - - updateButton(path); - } - }; - - buttons = [{ - id: 'tool_openpath', - icon: svgEditor.curConfig.extIconsPath + 'openpath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } - } - }, { - id: 'tool_closepath', - icon: svgEditor.curConfig.extIconsPath + 'closepath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - callback: function callback() { - $('#closepath_panel').hide(); - }, - selectedChanged: function selectedChanged(opts) { - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.tagName === 'path') { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - } - }); - - case 10: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } -}; - -export default extClosepath; -//# sourceMappingURL=ext-closepath.js.map diff --git a/dist/editor/extensions/ext-closepath.js.map b/dist/editor/extensions/ext-closepath.js.map deleted file mode 100644 index 9eeda1d6..00000000 --- a/dist/editor/extensions/ext-closepath.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-closepath.js","sources":["../../../src/common/svgpathseg.js","../../../src/editor/extensions/ext-closepath.js"],"sourcesContent":["/* eslint-disable import/unambiguous, max-len */\n/* globals SVGPathSeg, SVGPathSegMovetoRel, SVGPathSegMovetoAbs,\n SVGPathSegMovetoRel, SVGPathSegLinetoRel, SVGPathSegLinetoAbs,\n SVGPathSegLinetoHorizontalRel, SVGPathSegLinetoHorizontalAbs,\n SVGPathSegLinetoVerticalRel, SVGPathSegLinetoVerticalAbs,\n SVGPathSegClosePath, SVGPathSegCurvetoCubicRel,\n SVGPathSegCurvetoCubicAbs, SVGPathSegCurvetoCubicSmoothRel,\n SVGPathSegCurvetoCubicSmoothAbs, SVGPathSegCurvetoQuadraticRel,\n SVGPathSegCurvetoQuadraticAbs, SVGPathSegCurvetoQuadraticSmoothRel,\n SVGPathSegCurvetoQuadraticSmoothAbs, SVGPathSegArcRel, SVGPathSegArcAbs */\n/**\n* SVGPathSeg API polyfill\n* https://github.com/progers/pathseg\n*\n* This is a drop-in replacement for the `SVGPathSeg` and `SVGPathSegList` APIs\n* that were removed from SVG2 ({@link https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html}),\n* including the latest spec changes which were implemented in Firefox 43 and\n* Chrome 46.\n*/\n/* eslint-disable no-shadow, class-methods-use-this, jsdoc/require-jsdoc */\n// Linting: We avoid `no-shadow` as ESLint thinks these are still available globals\n// Linting: We avoid `class-methods-use-this` as this is a polyfill that must\n// follow the conventions\n(() => {\nif (!('SVGPathSeg' in window)) {\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg\n class SVGPathSeg {\n constructor (type, typeAsLetter, owningPathSegList) {\n this.pathSegType = type;\n this.pathSegTypeAsLetter = typeAsLetter;\n this._owningPathSegList = owningPathSegList;\n }\n // Notify owning PathSegList on any changes so they can be synchronized back to the path element.\n _segmentChanged () {\n if (this._owningPathSegList) {\n this._owningPathSegList.segmentChanged(this);\n }\n }\n }\n SVGPathSeg.prototype.classname = 'SVGPathSeg';\n\n SVGPathSeg.PATHSEG_UNKNOWN = 0;\n SVGPathSeg.PATHSEG_CLOSEPATH = 1;\n SVGPathSeg.PATHSEG_MOVETO_ABS = 2;\n SVGPathSeg.PATHSEG_MOVETO_REL = 3;\n SVGPathSeg.PATHSEG_LINETO_ABS = 4;\n SVGPathSeg.PATHSEG_LINETO_REL = 5;\n SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;\n SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;\n SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;\n SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;\n SVGPathSeg.PATHSEG_ARC_ABS = 10;\n SVGPathSeg.PATHSEG_ARC_REL = 11;\n SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;\n SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;\n SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;\n SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;\n SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;\n SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;\n SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;\n SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19;\n\n class SVGPathSegClosePath extends SVGPathSeg {\n constructor (owningPathSegList) {\n super(SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList);\n }\n toString () { return '[object SVGPathSegClosePath]'; }\n _asPathString () { return this.pathSegTypeAsLetter; }\n clone () { return new SVGPathSegClosePath(undefined); }\n }\n\n class SVGPathSegMovetoAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegMovetoAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegMovetoAbs(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegMovetoAbs.prototype, {\n x: {\n get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true\n },\n y: {\n get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true\n }\n });\n\n class SVGPathSegMovetoRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegMovetoRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegMovetoRel(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegMovetoRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegLinetoAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegLinetoAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegLinetoAbs(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegLinetoAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegLinetoRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegLinetoRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegLinetoRel(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegLinetoRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x1, y1, x2, y2) {\n super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x1 = x1;\n this._y1 = y1;\n this._x2 = x2;\n this._y2 = y2;\n }\n toString () { return '[object SVGPathSegCurvetoCubicAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }\n }\n Object.defineProperties(SVGPathSegCurvetoCubicAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true},\n y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true},\n x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true},\n y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x1, y1, x2, y2) {\n super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x1 = x1;\n this._y1 = y1;\n this._x2 = x2;\n this._y2 = y2;\n }\n toString () { return '[object SVGPathSegCurvetoCubicRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }\n }\n Object.defineProperties(SVGPathSegCurvetoCubicRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true},\n y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true},\n x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true},\n y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x1, y1) {\n super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x1 = x1;\n this._y1 = y1;\n }\n toString () { return '[object SVGPathSegCurvetoQuadraticAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); }\n }\n Object.defineProperties(SVGPathSegCurvetoQuadraticAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true},\n y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x1, y1) {\n super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x1 = x1;\n this._y1 = y1;\n }\n toString () { return '[object SVGPathSegCurvetoQuadraticRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); }\n }\n Object.defineProperties(SVGPathSegCurvetoQuadraticRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x1: {get () { return this._x1; }, set (x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true},\n y1: {get () { return this._y1; }, set (y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegArcAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {\n super(SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList);\n this._x = x;\n this._y = y;\n this._r1 = r1;\n this._r2 = r2;\n this._angle = angle;\n this._largeArcFlag = largeArcFlag;\n this._sweepFlag = sweepFlag;\n }\n toString () { return '[object SVGPathSegArcAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }\n }\n Object.defineProperties(SVGPathSegArcAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n r1: {get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true},\n r2: {get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true},\n angle: {get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true},\n largeArcFlag: {get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true},\n sweepFlag: {get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegArcRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {\n super(SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList);\n this._x = x;\n this._y = y;\n this._r1 = r1;\n this._r2 = r2;\n this._angle = angle;\n this._largeArcFlag = largeArcFlag;\n this._sweepFlag = sweepFlag;\n }\n toString () { return '[object SVGPathSegArcRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }\n }\n Object.defineProperties(SVGPathSegArcRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n r1: {get () { return this._r1; }, set (r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true},\n r2: {get () { return this._r2; }, set (r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true},\n angle: {get () { return this._angle; }, set (angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true},\n largeArcFlag: {get () { return this._largeArcFlag; }, set (largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true},\n sweepFlag: {get () { return this._sweepFlag; }, set (sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n constructor (owningPathSegList, x) {\n super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList);\n this._x = x;\n }\n toString () { return '[object SVGPathSegLinetoHorizontalAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; }\n clone () { return new SVGPathSegLinetoHorizontalAbs(undefined, this._x); }\n }\n Object.defineProperty(SVGPathSegLinetoHorizontalAbs.prototype, 'x', {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true});\n\n class SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n constructor (owningPathSegList, x) {\n super(SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList);\n this._x = x;\n }\n toString () { return '[object SVGPathSegLinetoHorizontalRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x; }\n clone () { return new SVGPathSegLinetoHorizontalRel(undefined, this._x); }\n }\n Object.defineProperty(SVGPathSegLinetoHorizontalRel.prototype, 'x', {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true});\n\n class SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n constructor (owningPathSegList, y) {\n super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList);\n this._y = y;\n }\n toString () { return '[object SVGPathSegLinetoVerticalAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; }\n clone () { return new SVGPathSegLinetoVerticalAbs(undefined, this._y); }\n }\n Object.defineProperty(SVGPathSegLinetoVerticalAbs.prototype, 'y', {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true});\n\n class SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n constructor (owningPathSegList, y) {\n super(SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList);\n this._y = y;\n }\n toString () { return '[object SVGPathSegLinetoVerticalRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._y; }\n clone () { return new SVGPathSegLinetoVerticalRel(undefined, this._y); }\n }\n Object.defineProperty(SVGPathSegLinetoVerticalRel.prototype, 'y', {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true});\n\n class SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x2, y2) {\n super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x2 = x2;\n this._y2 = y2;\n }\n toString () { return '[object SVGPathSegCurvetoCubicSmoothAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); }\n }\n Object.defineProperties(SVGPathSegCurvetoCubicSmoothAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true},\n y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y, x2, y2) {\n super(SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList);\n this._x = x;\n this._y = y;\n this._x2 = x2;\n this._y2 = y2;\n }\n toString () { return '[object SVGPathSegCurvetoCubicSmoothRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); }\n }\n Object.defineProperties(SVGPathSegCurvetoCubicSmoothRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true},\n x2: {get () { return this._x2; }, set (x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true},\n y2: {get () { return this._y2; }, set (y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegCurvetoQuadraticSmoothAbs]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}\n });\n\n class SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n constructor (owningPathSegList, x, y) {\n super(SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList);\n this._x = x;\n this._y = y;\n }\n toString () { return '[object SVGPathSegCurvetoQuadraticSmoothRel]'; }\n _asPathString () { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; }\n clone () { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); }\n }\n Object.defineProperties(SVGPathSegCurvetoQuadraticSmoothRel.prototype, {\n x: {get () { return this._x; }, set (x) { this._x = x; this._segmentChanged(); }, enumerable: true},\n y: {get () { return this._y; }, set (y) { this._y = y; this._segmentChanged(); }, enumerable: true}\n });\n\n // Add createSVGPathSeg* functions to SVGPathElement.\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement.\n SVGPathElement.prototype.createSVGPathSegClosePath = function () { return new SVGPathSegClosePath(undefined); };\n SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) { return new SVGPathSegMovetoAbs(undefined, x, y); };\n SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) { return new SVGPathSegMovetoRel(undefined, x, y); };\n SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) { return new SVGPathSegLinetoAbs(undefined, x, y); };\n SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) { return new SVGPathSegLinetoRel(undefined, x, y); };\n SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); };\n SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); };\n SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); };\n SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); };\n SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); };\n SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); };\n SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) { return new SVGPathSegLinetoHorizontalAbs(undefined, x); };\n SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) { return new SVGPathSegLinetoHorizontalRel(undefined, x); };\n SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) { return new SVGPathSegLinetoVerticalAbs(undefined, y); };\n SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) { return new SVGPathSegLinetoVerticalRel(undefined, y); };\n SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); };\n SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); };\n SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); };\n SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); };\n\n if (!('getPathSegAtLength' in SVGPathElement.prototype)) {\n // Add getPathSegAtLength to SVGPathElement.\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength\n // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm.\n SVGPathElement.prototype.getPathSegAtLength = function (distance) {\n if (distance === undefined || !isFinite(distance)) {\n throw new Error('Invalid arguments.');\n }\n\n const measurementElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n measurementElement.setAttribute('d', this.getAttribute('d'));\n let lastPathSegment = measurementElement.pathSegList.numberOfItems - 1;\n\n // If the path is empty, return 0.\n if (lastPathSegment <= 0) {\n return 0;\n }\n\n do {\n measurementElement.pathSegList.removeItem(lastPathSegment);\n if (distance > measurementElement.getTotalLength()) {\n break;\n }\n lastPathSegment--;\n } while (lastPathSegment > 0);\n return lastPathSegment;\n };\n }\n\n window.SVGPathSeg = SVGPathSeg;\n window.SVGPathSegClosePath = SVGPathSegClosePath;\n window.SVGPathSegMovetoAbs = SVGPathSegMovetoAbs;\n window.SVGPathSegMovetoRel = SVGPathSegMovetoRel;\n window.SVGPathSegLinetoAbs = SVGPathSegLinetoAbs;\n window.SVGPathSegLinetoRel = SVGPathSegLinetoRel;\n window.SVGPathSegCurvetoCubicAbs = SVGPathSegCurvetoCubicAbs;\n window.SVGPathSegCurvetoCubicRel = SVGPathSegCurvetoCubicRel;\n window.SVGPathSegCurvetoQuadraticAbs = SVGPathSegCurvetoQuadraticAbs;\n window.SVGPathSegCurvetoQuadraticRel = SVGPathSegCurvetoQuadraticRel;\n window.SVGPathSegArcAbs = SVGPathSegArcAbs;\n window.SVGPathSegArcRel = SVGPathSegArcRel;\n window.SVGPathSegLinetoHorizontalAbs = SVGPathSegLinetoHorizontalAbs;\n window.SVGPathSegLinetoHorizontalRel = SVGPathSegLinetoHorizontalRel;\n window.SVGPathSegLinetoVerticalAbs = SVGPathSegLinetoVerticalAbs;\n window.SVGPathSegLinetoVerticalRel = SVGPathSegLinetoVerticalRel;\n window.SVGPathSegCurvetoCubicSmoothAbs = SVGPathSegCurvetoCubicSmoothAbs;\n window.SVGPathSegCurvetoCubicSmoothRel = SVGPathSegCurvetoCubicSmoothRel;\n window.SVGPathSegCurvetoQuadraticSmoothAbs = SVGPathSegCurvetoQuadraticSmoothAbs;\n window.SVGPathSegCurvetoQuadraticSmoothRel = SVGPathSegCurvetoQuadraticSmoothRel;\n}\n\n// Checking for SVGPathSegList in window checks for the case of an implementation without the\n// SVGPathSegList API.\n// The second check for appendItem is specific to Firefox 59+ which removed only parts of the\n// SVGPathSegList API (e.g., appendItem). In this case we need to re-implement the entire API\n// so the polyfill data (i.e., _list) is used throughout.\nif (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.prototype)) {\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList\n class SVGPathSegList {\n constructor (pathElement) {\n this._pathElement = pathElement;\n this._list = this._parsePath(this._pathElement.getAttribute('d'));\n\n // Use a MutationObserver to catch changes to the path's \"d\" attribute.\n this._mutationObserverConfig = {attributes: true, attributeFilter: ['d']};\n this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this));\n this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);\n }\n // Process any pending mutations to the path element and update the list as needed.\n // This should be the first call of all public functions and is needed because\n // MutationObservers are not synchronous so we can have pending asynchronous mutations.\n _checkPathSynchronizedToList () {\n this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords());\n }\n\n _updateListFromPathMutations (mutationRecords) {\n if (!this._pathElement) {\n return;\n }\n let hasPathMutations = false;\n mutationRecords.forEach((record) => {\n if (record.attributeName === 'd') {\n hasPathMutations = true;\n }\n });\n if (hasPathMutations) {\n this._list = this._parsePath(this._pathElement.getAttribute('d'));\n }\n }\n\n // Serialize the list and update the path's 'd' attribute.\n _writeListToPath () {\n this._pathElementMutationObserver.disconnect();\n this._pathElement.setAttribute('d', SVGPathSegList._pathSegArrayAsString(this._list));\n this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);\n }\n\n // When a path segment changes the list needs to be synchronized back to the path element.\n segmentChanged (pathSeg) {\n this._writeListToPath();\n }\n\n clear () {\n this._checkPathSynchronizedToList();\n\n this._list.forEach((pathSeg) => {\n pathSeg._owningPathSegList = null;\n });\n this._list = [];\n this._writeListToPath();\n }\n\n initialize (newItem) {\n this._checkPathSynchronizedToList();\n\n this._list = [newItem];\n newItem._owningPathSegList = this;\n this._writeListToPath();\n return newItem;\n }\n\n _checkValidIndex (index) {\n if (isNaN(index) || index < 0 || index >= this.numberOfItems) {\n throw new Error('INDEX_SIZE_ERR');\n }\n }\n\n getItem (index) {\n this._checkPathSynchronizedToList();\n\n this._checkValidIndex(index);\n return this._list[index];\n }\n\n insertItemBefore (newItem, index) {\n this._checkPathSynchronizedToList();\n\n // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.\n if (index > this.numberOfItems) {\n index = this.numberOfItems;\n }\n if (newItem._owningPathSegList) {\n // SVG2 spec says to make a copy.\n newItem = newItem.clone();\n }\n this._list.splice(index, 0, newItem);\n newItem._owningPathSegList = this;\n this._writeListToPath();\n return newItem;\n }\n\n replaceItem (newItem, index) {\n this._checkPathSynchronizedToList();\n\n if (newItem._owningPathSegList) {\n // SVG2 spec says to make a copy.\n newItem = newItem.clone();\n }\n this._checkValidIndex(index);\n this._list[index] = newItem;\n newItem._owningPathSegList = this;\n this._writeListToPath();\n return newItem;\n }\n\n removeItem (index) {\n this._checkPathSynchronizedToList();\n\n this._checkValidIndex(index);\n const item = this._list[index];\n this._list.splice(index, 1);\n this._writeListToPath();\n return item;\n }\n\n appendItem (newItem) {\n this._checkPathSynchronizedToList();\n\n if (newItem._owningPathSegList) {\n // SVG2 spec says to make a copy.\n newItem = newItem.clone();\n }\n this._list.push(newItem);\n newItem._owningPathSegList = this;\n // TODO: Optimize this to just append to the existing attribute.\n this._writeListToPath();\n return newItem;\n }\n\n // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp.\n _parsePath (string) {\n if (!string || !string.length) {\n return [];\n }\n\n const owningPathSegList = this;\n\n class Builder {\n constructor () {\n this.pathSegList = [];\n }\n appendSegment (pathSeg) {\n this.pathSegList.push(pathSeg);\n }\n }\n\n class Source {\n constructor (string) {\n this._string = string;\n this._currentIndex = 0;\n this._endIndex = this._string.length;\n this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN;\n\n this._skipOptionalSpaces();\n }\n _isCurrentSpace () {\n const character = this._string[this._currentIndex];\n return character <= ' ' && (character === ' ' || character === '\\n' || character === '\\t' || character === '\\r' || character === '\\f');\n }\n\n _skipOptionalSpaces () {\n while (this._currentIndex < this._endIndex && this._isCurrentSpace()) {\n this._currentIndex++;\n }\n return this._currentIndex < this._endIndex;\n }\n\n _skipOptionalSpacesOrDelimiter () {\n if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) !== ',') {\n return false;\n }\n if (this._skipOptionalSpaces()) {\n if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === ',') {\n this._currentIndex++;\n this._skipOptionalSpaces();\n }\n }\n return this._currentIndex < this._endIndex;\n }\n\n hasMoreData () {\n return this._currentIndex < this._endIndex;\n }\n\n peekSegmentType () {\n const lookahead = this._string[this._currentIndex];\n return this._pathSegTypeFromChar(lookahead);\n }\n\n _pathSegTypeFromChar (lookahead) {\n switch (lookahead) {\n case 'Z':\n case 'z':\n return SVGPathSeg.PATHSEG_CLOSEPATH;\n case 'M':\n return SVGPathSeg.PATHSEG_MOVETO_ABS;\n case 'm':\n return SVGPathSeg.PATHSEG_MOVETO_REL;\n case 'L':\n return SVGPathSeg.PATHSEG_LINETO_ABS;\n case 'l':\n return SVGPathSeg.PATHSEG_LINETO_REL;\n case 'C':\n return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;\n case 'c':\n return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;\n case 'Q':\n return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;\n case 'q':\n return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;\n case 'A':\n return SVGPathSeg.PATHSEG_ARC_ABS;\n case 'a':\n return SVGPathSeg.PATHSEG_ARC_REL;\n case 'H':\n return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;\n case 'h':\n return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;\n case 'V':\n return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;\n case 'v':\n return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;\n case 'S':\n return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;\n case 's':\n return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;\n case 'T':\n return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;\n case 't':\n return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;\n default:\n return SVGPathSeg.PATHSEG_UNKNOWN;\n }\n }\n\n _nextCommandHelper (lookahead, previousCommand) {\n // Check for remaining coordinates in the current command.\n if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || (lookahead >= '0' && lookahead <= '9')) && previousCommand !== SVGPathSeg.PATHSEG_CLOSEPATH) {\n if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_ABS) {\n return SVGPathSeg.PATHSEG_LINETO_ABS;\n }\n if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_REL) {\n return SVGPathSeg.PATHSEG_LINETO_REL;\n }\n return previousCommand;\n }\n return SVGPathSeg.PATHSEG_UNKNOWN;\n }\n\n initialCommandIsMoveTo () {\n // If the path is empty it is still valid, so return true.\n if (!this.hasMoreData()) {\n return true;\n }\n const command = this.peekSegmentType();\n // Path must start with moveTo.\n return command === SVGPathSeg.PATHSEG_MOVETO_ABS || command === SVGPathSeg.PATHSEG_MOVETO_REL;\n }\n\n // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp.\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF\n _parseNumber () {\n let exponent = 0;\n let integer = 0;\n let frac = 1;\n let decimal = 0;\n let sign = 1;\n let expsign = 1;\n\n const startIndex = this._currentIndex;\n\n this._skipOptionalSpaces();\n\n // Read the sign.\n if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '+') {\n this._currentIndex++;\n } else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '-') {\n this._currentIndex++;\n sign = -1;\n }\n\n if (this._currentIndex === this._endIndex || ((this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.')) {\n // The first character of a number must be one of [0-9+-.].\n return undefined;\n }\n\n // Read the integer part, build right-to-left.\n const startIntPartIndex = this._currentIndex;\n while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n this._currentIndex++; // Advance to first non-digit.\n }\n\n if (this._currentIndex !== startIntPartIndex) {\n let scanIntPartIndex = this._currentIndex - 1;\n let multiplier = 1;\n while (scanIntPartIndex >= startIntPartIndex) {\n integer += multiplier * (this._string.charAt(scanIntPartIndex--) - '0');\n multiplier *= 10;\n }\n }\n\n // Read the decimals.\n if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '.') {\n this._currentIndex++;\n\n // There must be a least one digit following the .\n if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') {\n return undefined;\n }\n while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n frac *= 10;\n decimal += (this._string.charAt(this._currentIndex) - '0') / frac;\n this._currentIndex += 1;\n }\n }\n\n // Read the exponent part.\n 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')) {\n this._currentIndex++;\n\n // Read the sign of the exponent.\n if (this._string.charAt(this._currentIndex) === '+') {\n this._currentIndex++;\n } else if (this._string.charAt(this._currentIndex) === '-') {\n this._currentIndex++;\n expsign = -1;\n }\n\n // There must be an exponent.\n if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') {\n return undefined;\n }\n\n while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') {\n exponent *= 10;\n exponent += (this._string.charAt(this._currentIndex) - '0');\n this._currentIndex++;\n }\n }\n\n let number = integer + decimal;\n number *= sign;\n\n if (exponent) {\n number *= 10 ** (expsign * exponent);\n }\n\n if (startIndex === this._currentIndex) {\n return undefined;\n }\n\n this._skipOptionalSpacesOrDelimiter();\n\n return number;\n }\n\n _parseArcFlag () {\n if (this._currentIndex >= this._endIndex) {\n return undefined;\n }\n let flag = false;\n const flagChar = this._string.charAt(this._currentIndex++);\n if (flagChar === '0') {\n flag = false;\n } else if (flagChar === '1') {\n flag = true;\n } else {\n return undefined;\n }\n\n this._skipOptionalSpacesOrDelimiter();\n return flag;\n }\n\n parseSegment () {\n const lookahead = this._string[this._currentIndex];\n let command = this._pathSegTypeFromChar(lookahead);\n if (command === SVGPathSeg.PATHSEG_UNKNOWN) {\n // Possibly an implicit command. Not allowed if this is the first command.\n if (this._previousCommand === SVGPathSeg.PATHSEG_UNKNOWN) {\n return null;\n }\n command = this._nextCommandHelper(lookahead, this._previousCommand);\n if (command === SVGPathSeg.PATHSEG_UNKNOWN) {\n return null;\n }\n } else {\n this._currentIndex++;\n }\n\n this._previousCommand = command;\n\n switch (command) {\n case SVGPathSeg.PATHSEG_MOVETO_REL:\n return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_MOVETO_ABS:\n return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_REL:\n return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_ABS:\n return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:\n return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:\n return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:\n return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber());\n case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:\n return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber());\n case SVGPathSeg.PATHSEG_CLOSEPATH:\n this._skipOptionalSpaces();\n return new SVGPathSegClosePath(owningPathSegList);\n case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);\n } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);\n } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: {\n const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2);\n } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: {\n const points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2);\n } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1);\n } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1);\n } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:\n return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:\n return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber());\n case SVGPathSeg.PATHSEG_ARC_REL: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);\n } case SVGPathSeg.PATHSEG_ARC_ABS: {\n const points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};\n return new SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);\n } default:\n throw new Error('Unknown path seg type.');\n }\n }\n }\n\n const builder = new Builder();\n const source = new Source(string);\n\n if (!source.initialCommandIsMoveTo()) {\n return [];\n }\n while (source.hasMoreData()) {\n const pathSeg = source.parseSegment();\n if (!pathSeg) {\n return [];\n }\n builder.appendSegment(pathSeg);\n }\n\n return builder.pathSegList;\n }\n\n // STATIC\n static _pathSegArrayAsString (pathSegArray) {\n let string = '';\n let first = true;\n pathSegArray.forEach((pathSeg) => {\n if (first) {\n first = false;\n string += pathSeg._asPathString();\n } else {\n string += ' ' + pathSeg._asPathString();\n }\n });\n return string;\n }\n }\n\n SVGPathSegList.prototype.classname = 'SVGPathSegList';\n\n Object.defineProperty(SVGPathSegList.prototype, 'numberOfItems', {\n get () {\n this._checkPathSynchronizedToList();\n return this._list.length;\n },\n enumerable: true\n });\n\n // Add the pathSegList accessors to SVGPathElement.\n // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData\n Object.defineProperties(SVGPathElement.prototype, {\n pathSegList: {\n get () {\n if (!this._pathSegList) {\n this._pathSegList = new SVGPathSegList(this);\n }\n return this._pathSegList;\n },\n enumerable: true\n },\n // TODO: The following are not implemented and simply return SVGPathElement.pathSegList.\n normalizedPathSegList: {get () { return this.pathSegList; }, enumerable: true},\n animatedPathSegList: {get () { return this.pathSegList; }, enumerable: true},\n animatedNormalizedPathSegList: {get () { return this.pathSegList; }, enumerable: true}\n });\n window.SVGPathSegList = SVGPathSegList;\n}\n})();\n","/**\n * @file ext-closepath.js\n *\n * @license MIT\n *\n * @copyright 2010 Jeff Schiller\n *\n */\nimport '../../common/svgpathseg.js';\n\n// This extension adds a simple button to the contextual panel for paths\n// The button toggles whether the path is open or closed\nexport default {\n name: 'closepath',\n async init ({importLocale, $}) {\n const strings = await importLocale();\n const svgEditor = this;\n let selElems;\n const updateButton = function (path) {\n const seglist = path.pathSegList,\n closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1,\n showbutton = closed ? '#tool_openpath' : '#tool_closepath',\n hidebutton = closed ? '#tool_closepath' : '#tool_openpath';\n $(hidebutton).hide();\n $(showbutton).show();\n };\n const showPanel = function (on) {\n $('#closepath_panel').toggle(on);\n if (on) {\n const path = selElems[0];\n if (path) { updateButton(path); }\n }\n };\n const toggleClosed = function () {\n const path = selElems[0];\n if (path) {\n const seglist = path.pathSegList,\n last = seglist.numberOfItems - 1;\n // is closed\n if (seglist.getItem(last).pathSegType === 1) {\n seglist.removeItem(last);\n } else {\n seglist.appendItem(path.createSVGPathSegClosePath());\n }\n updateButton(path);\n }\n };\n\n const buttons = [\n {\n id: 'tool_openpath',\n icon: svgEditor.curConfig.extIconsPath + 'openpath.png',\n type: 'context',\n panel: 'closepath_panel',\n events: {\n click () {\n toggleClosed();\n }\n }\n },\n {\n id: 'tool_closepath',\n icon: svgEditor.curConfig.extIconsPath + 'closepath.png',\n type: 'context',\n panel: 'closepath_panel',\n events: {\n click () {\n toggleClosed();\n }\n }\n }\n ];\n\n return {\n name: strings.name,\n svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n callback () {\n $('#closepath_panel').hide();\n },\n selectedChanged (opts) {\n selElems = opts.elems;\n let i = selElems.length;\n while (i--) {\n const elem = selElems[i];\n if (elem && elem.tagName === 'path') {\n if (opts.selectedElement && !opts.multiselected) {\n showPanel(true);\n } else {\n showPanel(false);\n }\n } else {\n showPanel(false);\n }\n }\n }\n };\n }\n};\n"],"names":["window","SVGPathSeg","type","typeAsLetter","owningPathSegList","pathSegType","pathSegTypeAsLetter","_owningPathSegList","segmentChanged","prototype","classname","PATHSEG_UNKNOWN","PATHSEG_CLOSEPATH","PATHSEG_MOVETO_ABS","PATHSEG_MOVETO_REL","PATHSEG_LINETO_ABS","PATHSEG_LINETO_REL","PATHSEG_CURVETO_CUBIC_ABS","PATHSEG_CURVETO_CUBIC_REL","PATHSEG_CURVETO_QUADRATIC_ABS","PATHSEG_CURVETO_QUADRATIC_REL","PATHSEG_ARC_ABS","PATHSEG_ARC_REL","PATHSEG_LINETO_HORIZONTAL_ABS","PATHSEG_LINETO_HORIZONTAL_REL","PATHSEG_LINETO_VERTICAL_ABS","PATHSEG_LINETO_VERTICAL_REL","PATHSEG_CURVETO_CUBIC_SMOOTH_ABS","PATHSEG_CURVETO_CUBIC_SMOOTH_REL","PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS","PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL","SVGPathSegClosePath","undefined","SVGPathSegMovetoAbs","x","y","_x","_y","Object","defineProperties","get","set","_segmentChanged","enumerable","SVGPathSegMovetoRel","SVGPathSegLinetoAbs","SVGPathSegLinetoRel","SVGPathSegCurvetoCubicAbs","x1","y1","x2","y2","_x1","_y1","_x2","_y2","SVGPathSegCurvetoCubicRel","SVGPathSegCurvetoQuadraticAbs","SVGPathSegCurvetoQuadraticRel","SVGPathSegArcAbs","r1","r2","angle","largeArcFlag","sweepFlag","_r1","_r2","_angle","_largeArcFlag","_sweepFlag","SVGPathSegArcRel","SVGPathSegLinetoHorizontalAbs","defineProperty","SVGPathSegLinetoHorizontalRel","SVGPathSegLinetoVerticalAbs","SVGPathSegLinetoVerticalRel","SVGPathSegCurvetoCubicSmoothAbs","SVGPathSegCurvetoCubicSmoothRel","SVGPathSegCurvetoQuadraticSmoothAbs","SVGPathSegCurvetoQuadraticSmoothRel","SVGPathElement","createSVGPathSegClosePath","createSVGPathSegMovetoAbs","createSVGPathSegMovetoRel","createSVGPathSegLinetoAbs","createSVGPathSegLinetoRel","createSVGPathSegCurvetoCubicAbs","createSVGPathSegCurvetoCubicRel","createSVGPathSegCurvetoQuadraticAbs","createSVGPathSegCurvetoQuadraticRel","createSVGPathSegArcAbs","createSVGPathSegArcRel","createSVGPathSegLinetoHorizontalAbs","createSVGPathSegLinetoHorizontalRel","createSVGPathSegLinetoVerticalAbs","createSVGPathSegLinetoVerticalRel","createSVGPathSegCurvetoCubicSmoothAbs","createSVGPathSegCurvetoCubicSmoothRel","createSVGPathSegCurvetoQuadraticSmoothAbs","createSVGPathSegCurvetoQuadraticSmoothRel","getPathSegAtLength","distance","isFinite","Error","measurementElement","document","createElementNS","setAttribute","getAttribute","lastPathSegment","pathSegList","numberOfItems","removeItem","getTotalLength","SVGPathSegList","pathElement","_pathElement","_list","_parsePath","_mutationObserverConfig","attributes","attributeFilter","_pathElementMutationObserver","MutationObserver","_updateListFromPathMutations","bind","observe","takeRecords","mutationRecords","hasPathMutations","forEach","record","attributeName","disconnect","_pathSegArrayAsString","pathSeg","_writeListToPath","_checkPathSynchronizedToList","newItem","index","isNaN","_checkValidIndex","clone","splice","item","push","string","length","Builder","Source","_string","_currentIndex","_endIndex","_previousCommand","_skipOptionalSpaces","character","_isCurrentSpace","charAt","lookahead","_pathSegTypeFromChar","previousCommand","hasMoreData","command","peekSegmentType","exponent","integer","frac","decimal","sign","expsign","startIndex","startIntPartIndex","scanIntPartIndex","multiplier","number","_skipOptionalSpacesOrDelimiter","flag","flagChar","_nextCommandHelper","_parseNumber","points","arcAngle","arcLarge","_parseArcFlag","arcSweep","builder","source","initialCommandIsMoveTo","parseSegment","appendSegment","pathSegArray","first","_asPathString","_pathSegList","normalizedPathSegList","animatedPathSegList","animatedNormalizedPathSegList","name","init","importLocale","$","strings","svgEditor","updateButton","path","seglist","closed","getItem","showbutton","hidebutton","hide","show","showPanel","on","toggle","selElems","toggleClosed","last","appendItem","buttons","id","icon","curConfig","extIconsPath","panel","events","click","svgicons","map","button","i","assign","callback","selectedChanged","opts","elems","elem","tagName","selectedElement","multiselected"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;;;;;;;;;AASA;;;;;;;;;;AASA;AACA;AACA;AACA;AACA,CAAC,YAAM;AACP,MAAI,EAAE,gBAAgBA,MAAlB,CAAJ,EAA+B;AAC7B;AAD6B,QAEvBC,WAFuB;AAG3B,2BAAaC,IAAb,EAAmBC,YAAnB,EAAiCC,iBAAjC,EAAoD;AAAA;;AAClD,aAAKC,WAAL,GAAmBH,IAAnB;AACA,aAAKI,mBAAL,GAA2BH,YAA3B;AACA,aAAKI,kBAAL,GAA0BH,iBAA1B;AACD,OAP0B;;;AAAA;AAAA;AAAA,0CASR;AACjB,cAAI,KAAKG,kBAAT,EAA6B;AAC3B,iBAAKA,kBAAL,CAAwBC,cAAxB,CAAuC,IAAvC;AACD;AACF;AAb0B;;AAAA;AAAA;;AAe7BP,IAAAA,WAAU,CAACQ,SAAX,CAAqBC,SAArB,GAAiC,YAAjC;AAEAT,IAAAA,WAAU,CAACU,eAAX,GAA6B,CAA7B;AACAV,IAAAA,WAAU,CAACW,iBAAX,GAA+B,CAA/B;AACAX,IAAAA,WAAU,CAACY,kBAAX,GAAgC,CAAhC;AACAZ,IAAAA,WAAU,CAACa,kBAAX,GAAgC,CAAhC;AACAb,IAAAA,WAAU,CAACc,kBAAX,GAAgC,CAAhC;AACAd,IAAAA,WAAU,CAACe,kBAAX,GAAgC,CAAhC;AACAf,IAAAA,WAAU,CAACgB,yBAAX,GAAuC,CAAvC;AACAhB,IAAAA,WAAU,CAACiB,yBAAX,GAAuC,CAAvC;AACAjB,IAAAA,WAAU,CAACkB,6BAAX,GAA2C,CAA3C;AACAlB,IAAAA,WAAU,CAACmB,6BAAX,GAA2C,CAA3C;AACAnB,IAAAA,WAAU,CAACoB,eAAX,GAA6B,EAA7B;AACApB,IAAAA,WAAU,CAACqB,eAAX,GAA6B,EAA7B;AACArB,IAAAA,WAAU,CAACsB,6BAAX,GAA2C,EAA3C;AACAtB,IAAAA,WAAU,CAACuB,6BAAX,GAA2C,EAA3C;AACAvB,IAAAA,WAAU,CAACwB,2BAAX,GAAyC,EAAzC;AACAxB,IAAAA,WAAU,CAACyB,2BAAX,GAAyC,EAAzC;AACAzB,IAAAA,WAAU,CAAC0B,gCAAX,GAA8C,EAA9C;AACA1B,IAAAA,WAAU,CAAC2B,gCAAX,GAA8C,EAA9C;AACA3B,IAAAA,WAAU,CAAC4B,oCAAX,GAAkD,EAAlD;AACA5B,IAAAA,WAAU,CAAC6B,oCAAX,GAAkD,EAAlD;;AApC6B,QAsCvBC,oBAtCuB;AAAA;;AAAA;;AAuC3B,oCAAa3B,iBAAb,EAAgC;AAAA;;AAAA,iCACxBH,WAAU,CAACW,iBADa,EACM,GADN,EACWR,iBADX;AAE/B;;AAzC0B;AAAA;AAAA,mCA0Cf;AAAE,iBAAO,8BAAP;AAAwC;AA1C3B;AAAA;AAAA,wCA2CV;AAAE,iBAAO,KAAKE,mBAAZ;AAAkC;AA3C1B;AAAA;AAAA,gCA4ClB;AAAE,iBAAO,IAAIyB,oBAAJ,CAAwBC,SAAxB,CAAP;AAA4C;AA5C5B;;AAAA;AAAA,MAsCK/B,WAtCL;;AAAA,QA+CvBgC,oBA/CuB;AAAA;;AAAA;;AAgD3B,oCAAa7B,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,mCAAMlC,WAAU,CAACY,kBAAjB,EAAqC,GAArC,EAA0CT,iBAA1C;AACA,cAAKgC,EAAL,GAAUF,CAAV;AACA,cAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AApD0B;AAAA;AAAA,mCAqDf;AAAE,iBAAO,8BAAP;AAAwC;AArD3B;AAAA;AAAA,wCAsDV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AAtD1D;AAAA;AAAA,gCAuDlB;AAAE,iBAAO,IAAIJ,oBAAJ,CAAwBD,SAAxB,EAAmC,KAAKI,EAAxC,EAA4C,KAAKC,EAAjD,CAAP;AAA8D;AAvD9C;;AAAA;AAAA,MA+CKpC,WA/CL;;AAyD7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBN,oBAAmB,CAACxB,SAA5C,EAAuD;AACrDyB,MAAAA,CAAC,EAAE;AACDM,QAAAA,GADC,iBACM;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SADzB;AAC2BK,QAAAA,GAD3B,eACgCP,CADhC,EACmC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAD3E;AAC6EC,QAAAA,UAAU,EAAE;AADzF,OADkD;AAIrDR,MAAAA,CAAC,EAAE;AACDK,QAAAA,GADC,iBACM;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SADzB;AAC2BI,QAAAA,GAD3B,eACgCN,CADhC,EACmC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAD3E;AAC6EC,QAAAA,UAAU,EAAE;AADzF;AAJkD,KAAvD;;AAzD6B,QAkEvBC,oBAlEuB;AAAA;;AAAA;;AAmE3B,oCAAaxC,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,oCAAMlC,WAAU,CAACa,kBAAjB,EAAqC,GAArC,EAA0CV,iBAA1C;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AAvE0B;AAAA;AAAA,mCAwEf;AAAE,iBAAO,8BAAP;AAAwC;AAxE3B;AAAA;AAAA,wCAyEV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AAzE1D;AAAA;AAAA,gCA0ElB;AAAE,iBAAO,IAAIO,oBAAJ,CAAwBZ,SAAxB,EAAmC,KAAKI,EAAxC,EAA4C,KAAKC,EAAjD,CAAP;AAA8D;AA1E9C;;AAAA;AAAA,MAkEKpC,WAlEL;;AA4E7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBK,oBAAmB,CAACnC,SAA5C,EAAuD;AACrDyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADkD;AAErDR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F;AAFkD,KAAvD;;AA5E6B,QAiFvBE,oBAjFuB;AAAA;;AAAA;;AAkF3B,oCAAazC,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,oCAAMlC,WAAU,CAACc,kBAAjB,EAAqC,GAArC,EAA0CX,iBAA1C;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AAtF0B;AAAA;AAAA,mCAuFf;AAAE,iBAAO,8BAAP;AAAwC;AAvF3B;AAAA;AAAA,wCAwFV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AAxF1D;AAAA;AAAA,gCAyFlB;AAAE,iBAAO,IAAIQ,oBAAJ,CAAwBb,SAAxB,EAAmC,KAAKI,EAAxC,EAA4C,KAAKC,EAAjD,CAAP;AAA8D;AAzF9C;;AAAA;AAAA,MAiFKpC,WAjFL;;AA2F7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBM,oBAAmB,CAACpC,SAA5C,EAAuD;AACrDyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADkD;AAErDR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F;AAFkD,KAAvD;;AA3F6B,QAgGvBG,oBAhGuB;AAAA;;AAAA;;AAiG3B,oCAAa1C,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,oCAAMlC,WAAU,CAACe,kBAAjB,EAAqC,GAArC,EAA0CZ,iBAA1C;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AArG0B;AAAA;AAAA,mCAsGf;AAAE,iBAAO,8BAAP;AAAwC;AAtG3B;AAAA;AAAA,wCAuGV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AAvG1D;AAAA;AAAA,gCAwGlB;AAAE,iBAAO,IAAIS,oBAAJ,CAAwBd,SAAxB,EAAmC,KAAKI,EAAxC,EAA4C,KAAKC,EAAjD,CAAP;AAA8D;AAxG9C;;AAAA;AAAA,MAgGKpC,WAhGL;;AA0G7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBO,oBAAmB,CAACrC,SAA5C,EAAuD;AACrDyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADkD;AAErDR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F;AAFkD,KAAvD;;AA1G6B,QA+GvBI,0BA/GuB;AAAA;;AAAA;;AAgH3B,0CAAa3C,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCa,EAAtC,EAA0CC,EAA1C,EAA8CC,EAA9C,EAAkDC,EAAlD,EAAsD;AAAA;;AAAA;;AACpD,oCAAMlD,WAAU,CAACgB,yBAAjB,EAA4C,GAA5C,EAAiDb,iBAAjD;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AACA,eAAKiB,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AAPoD;AAQrD;;AAxH0B;AAAA;AAAA,mCAyHf;AAAE,iBAAO,oCAAP;AAA8C;AAzHjC;AAAA;AAAA,wCA0HV;AAAE,iBAAO,KAAK7C,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8C,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKC,GAAxE,GAA8E,GAA9E,GAAoF,KAAKC,GAAzF,GAA+F,GAA/F,GAAqG,KAAKnB,EAA1G,GAA+G,GAA/G,GAAqH,KAAKC,EAAjI;AAAsI;AA1H9H;AAAA;AAAA,gCA2HlB;AAAE,iBAAO,IAAIU,0BAAJ,CAA8Bf,SAA9B,EAAyC,KAAKI,EAA9C,EAAkD,KAAKC,EAAvD,EAA2D,KAAKe,GAAhE,EAAqE,KAAKC,GAA1E,EAA+E,KAAKC,GAApF,EAAyF,KAAKC,GAA9F,CAAP;AAA4G;AA3H5F;;AAAA;AAAA,MA+GWtD,WA/GX;;AA6H7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBQ,0BAAyB,CAACtC,SAAlD,EAA6D;AAC3DyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADwD;AAE3DR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAFwD;AAG3DK,MAAAA,EAAE,EAAE;AAACR,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKY,GAAZ;AAAkB,SAA5B;AAA8BX,QAAAA,GAA9B,eAAmCO,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKN,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAHuD;AAI3DM,MAAAA,EAAE,EAAE;AAACT,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKa,GAAZ;AAAkB,SAA5B;AAA8BZ,QAAAA,GAA9B,eAAmCQ,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKP,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAJuD;AAK3DO,MAAAA,EAAE,EAAE;AAACV,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKc,GAAZ;AAAkB,SAA5B;AAA8Bb,QAAAA,GAA9B,eAAmCS,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKR,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OALuD;AAM3DQ,MAAAA,EAAE,EAAE;AAACX,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKe,GAAZ;AAAkB,SAA5B;AAA8Bd,QAAAA,GAA9B,eAAmCU,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKT,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AANuD,KAA7D;;AA7H6B,QAsIvBa,0BAtIuB;AAAA;;AAAA;;AAuI3B,0CAAapD,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCa,EAAtC,EAA0CC,EAA1C,EAA8CC,EAA9C,EAAkDC,EAAlD,EAAsD;AAAA;;AAAA;;AACpD,oCAAMlD,WAAU,CAACiB,yBAAjB,EAA4C,GAA5C,EAAiDd,iBAAjD;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AACA,eAAKiB,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AAPoD;AAQrD;;AA/I0B;AAAA;AAAA,mCAgJf;AAAE,iBAAO,oCAAP;AAA8C;AAhJjC;AAAA;AAAA,wCAiJV;AAAE,iBAAO,KAAK7C,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8C,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKC,GAAxE,GAA8E,GAA9E,GAAoF,KAAKC,GAAzF,GAA+F,GAA/F,GAAqG,KAAKnB,EAA1G,GAA+G,GAA/G,GAAqH,KAAKC,EAAjI;AAAsI;AAjJ9H;AAAA;AAAA,gCAkJlB;AAAE,iBAAO,IAAImB,0BAAJ,CAA8BxB,SAA9B,EAAyC,KAAKI,EAA9C,EAAkD,KAAKC,EAAvD,EAA2D,KAAKe,GAAhE,EAAqE,KAAKC,GAA1E,EAA+E,KAAKC,GAApF,EAAyF,KAAKC,GAA9F,CAAP;AAA4G;AAlJ5F;;AAAA;AAAA,MAsIWtD,WAtIX;;AAoJ7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBiB,0BAAyB,CAAC/C,SAAlD,EAA6D;AAC3DyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADwD;AAE3DR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAFwD;AAG3DK,MAAAA,EAAE,EAAE;AAACR,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKY,GAAZ;AAAkB,SAA5B;AAA8BX,QAAAA,GAA9B,eAAmCO,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKN,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAHuD;AAI3DM,MAAAA,EAAE,EAAE;AAACT,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKa,GAAZ;AAAkB,SAA5B;AAA8BZ,QAAAA,GAA9B,eAAmCQ,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKP,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAJuD;AAK3DO,MAAAA,EAAE,EAAE;AAACV,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKc,GAAZ;AAAkB,SAA5B;AAA8Bb,QAAAA,GAA9B,eAAmCS,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKR,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OALuD;AAM3DQ,MAAAA,EAAE,EAAE;AAACX,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKe,GAAZ;AAAkB,SAA5B;AAA8Bd,QAAAA,GAA9B,eAAmCU,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKT,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AANuD,KAA7D;;AApJ6B,QA6JvBc,8BA7JuB;AAAA;;AAAA;;AA8J3B,8CAAarD,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCa,EAAtC,EAA0CC,EAA1C,EAA8C;AAAA;;AAAA;;AAC5C,oCAAMhD,WAAU,CAACkB,6BAAjB,EAAgD,GAAhD,EAAqDf,iBAArD;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AACA,eAAKiB,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AAL4C;AAM7C;;AApK0B;AAAA;AAAA,mCAqKf;AAAE,iBAAO,wCAAP;AAAkD;AArKrC;AAAA;AAAA,wCAsKV;AAAE,iBAAO,KAAK3C,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8C,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKjB,EAAxE,GAA6E,GAA7E,GAAmF,KAAKC,EAA/F;AAAoG;AAtK5F;AAAA;AAAA,gCAuKlB;AAAE,iBAAO,IAAIoB,8BAAJ,CAAkCzB,SAAlC,EAA6C,KAAKI,EAAlD,EAAsD,KAAKC,EAA3D,EAA+D,KAAKe,GAApE,EAAyE,KAAKC,GAA9E,CAAP;AAA4F;AAvK5E;;AAAA;AAAA,MA6JepD,WA7Jf;;AAyK7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBkB,8BAA6B,CAAChD,SAAtD,EAAiE;AAC/DyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD4D;AAE/DR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF4D;AAG/DK,MAAAA,EAAE,EAAE;AAACR,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKY,GAAZ;AAAkB,SAA5B;AAA8BX,QAAAA,GAA9B,eAAmCO,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKN,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH2D;AAI/DM,MAAAA,EAAE,EAAE;AAACT,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKa,GAAZ;AAAkB,SAA5B;AAA8BZ,QAAAA,GAA9B,eAAmCQ,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKP,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AAJ2D,KAAjE;;AAzK6B,QAgLvBe,8BAhLuB;AAAA;;AAAA;;AAiL3B,8CAAatD,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCa,EAAtC,EAA0CC,EAA1C,EAA8C;AAAA;;AAAA;;AAC5C,oCAAMhD,WAAU,CAACmB,6BAAjB,EAAgD,GAAhD,EAAqDhB,iBAArD;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AACA,eAAKiB,GAAL,GAAWJ,EAAX;AACA,eAAKK,GAAL,GAAWJ,EAAX;AAL4C;AAM7C;;AAvL0B;AAAA;AAAA,mCAwLf;AAAE,iBAAO,wCAAP;AAAkD;AAxLrC;AAAA;AAAA,wCAyLV;AAAE,iBAAO,KAAK3C,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8C,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKjB,EAAxE,GAA6E,GAA7E,GAAmF,KAAKC,EAA/F;AAAoG;AAzL5F;AAAA;AAAA,gCA0LlB;AAAE,iBAAO,IAAIqB,8BAAJ,CAAkC1B,SAAlC,EAA6C,KAAKI,EAAlD,EAAsD,KAAKC,EAA3D,EAA+D,KAAKe,GAApE,EAAyE,KAAKC,GAA9E,CAAP;AAA4F;AA1L5E;;AAAA;AAAA,MAgLepD,WAhLf;;AA4L7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBmB,8BAA6B,CAACjD,SAAtD,EAAiE;AAC/DyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD4D;AAE/DR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF4D;AAG/DK,MAAAA,EAAE,EAAE;AAACR,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKY,GAAZ;AAAkB,SAA5B;AAA8BX,QAAAA,GAA9B,eAAmCO,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKN,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH2D;AAI/DM,MAAAA,EAAE,EAAE;AAACT,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKa,GAAZ;AAAkB,SAA5B;AAA8BZ,QAAAA,GAA9B,eAAmCQ,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKP,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AAJ2D,KAAjE;;AA5L6B,QAmMvBgB,iBAnMuB;AAAA;;AAAA;;AAoM3B,iCAAavD,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCyB,EAAtC,EAA0CC,EAA1C,EAA8CC,KAA9C,EAAqDC,YAArD,EAAmEC,SAAnE,EAA8E;AAAA;;AAAA;;AAC5E,qCAAM/D,WAAU,CAACoB,eAAjB,EAAkC,GAAlC,EAAuCjB,iBAAvC;AACA,eAAKgC,EAAL,GAAUF,CAAV;AACA,eAAKG,EAAL,GAAUF,CAAV;AACA,eAAK8B,GAAL,GAAWL,EAAX;AACA,eAAKM,GAAL,GAAWL,EAAX;AACA,eAAKM,MAAL,GAAcL,KAAd;AACA,eAAKM,aAAL,GAAqBL,YAArB;AACA,eAAKM,UAAL,GAAkBL,SAAlB;AAR4E;AAS7E;;AA7M0B;AAAA;AAAA,mCA8Mf;AAAE,iBAAO,2BAAP;AAAqC;AA9MxB;AAAA;AAAA,wCA+MV;AAAE,iBAAO,KAAK1D,mBAAL,GAA2B,GAA3B,GAAiC,KAAK2D,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKC,MAAxE,GAAiF,GAAjF,IAAwF,KAAKC,aAAL,GAAqB,GAArB,GAA2B,GAAnH,IAA0H,GAA1H,IAAiI,KAAKC,UAAL,GAAkB,GAAlB,GAAwB,GAAzJ,IAAgK,GAAhK,GAAsK,KAAKjC,EAA3K,GAAgL,GAAhL,GAAsL,KAAKC,EAAlM;AAAuM;AA/M/L;AAAA;AAAA,gCAgNlB;AAAE,iBAAO,IAAIsB,iBAAJ,CAAqB3B,SAArB,EAAgC,KAAKI,EAArC,EAAyC,KAAKC,EAA9C,EAAkD,KAAK4B,GAAvD,EAA4D,KAAKC,GAAjE,EAAsE,KAAKC,MAA3E,EAAmF,KAAKC,aAAxF,EAAuG,KAAKC,UAA5G,CAAP;AAAiI;AAhNjH;;AAAA;AAAA,MAmMEpE,WAnMF;;AAkN7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBoB,iBAAgB,CAAClD,SAAzC,EAAoD;AAClDyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD+C;AAElDR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF+C;AAGlDiB,MAAAA,EAAE,EAAE;AAACpB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKyB,GAAZ;AAAkB,SAA5B;AAA8BxB,QAAAA,GAA9B,eAAmCmB,EAAnC,EAAuC;AAAE,eAAKK,GAAL,GAAWL,EAAX;;AAAe,eAAKlB,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH8C;AAIlDkB,MAAAA,EAAE,EAAE;AAACrB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK0B,GAAZ;AAAkB,SAA5B;AAA8BzB,QAAAA,GAA9B,eAAmCoB,EAAnC,EAAuC;AAAE,eAAKK,GAAL,GAAWL,EAAX;;AAAe,eAAKnB,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAJ8C;AAKlDmB,MAAAA,KAAK,EAAE;AAACtB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK2B,MAAZ;AAAqB,SAA/B;AAAiC1B,QAAAA,GAAjC,eAAsCqB,KAAtC,EAA6C;AAAE,eAAKK,MAAL,GAAcL,KAAd;;AAAqB,eAAKpB,eAAL;AAAyB,SAA7F;AAA+FC,QAAAA,UAAU,EAAE;AAA3G,OAL2C;AAMlDoB,MAAAA,YAAY,EAAE;AAACvB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK4B,aAAZ;AAA4B,SAAtC;AAAwC3B,QAAAA,GAAxC,eAA6CsB,YAA7C,EAA2D;AAAE,eAAKK,aAAL,GAAqBL,YAArB;;AAAmC,eAAKrB,eAAL;AAAyB,SAAzH;AAA2HC,QAAAA,UAAU,EAAE;AAAvI,OANoC;AAOlDqB,MAAAA,SAAS,EAAE;AAACxB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK6B,UAAZ;AAAyB,SAAnC;AAAqC5B,QAAAA,GAArC,eAA0CuB,SAA1C,EAAqD;AAAE,eAAKK,UAAL,GAAkBL,SAAlB;;AAA6B,eAAKtB,eAAL;AAAyB,SAA7G;AAA+GC,QAAAA,UAAU,EAAE;AAA3H;AAPuC,KAApD;;AAlN6B,QA4NvB2B,iBA5NuB;AAAA;;AAAA;;AA6N3B,iCAAalE,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCyB,EAAtC,EAA0CC,EAA1C,EAA8CC,KAA9C,EAAqDC,YAArD,EAAmEC,SAAnE,EAA8E;AAAA;;AAAA;;AAC5E,sCAAM/D,WAAU,CAACqB,eAAjB,EAAkC,GAAlC,EAAuClB,iBAAvC;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AACA,gBAAKG,EAAL,GAAUF,CAAV;AACA,gBAAK8B,GAAL,GAAWL,EAAX;AACA,gBAAKM,GAAL,GAAWL,EAAX;AACA,gBAAKM,MAAL,GAAcL,KAAd;AACA,gBAAKM,aAAL,GAAqBL,YAArB;AACA,gBAAKM,UAAL,GAAkBL,SAAlB;AAR4E;AAS7E;;AAtO0B;AAAA;AAAA,mCAuOf;AAAE,iBAAO,2BAAP;AAAqC;AAvOxB;AAAA;AAAA,wCAwOV;AAAE,iBAAO,KAAK1D,mBAAL,GAA2B,GAA3B,GAAiC,KAAK2D,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKC,MAAxE,GAAiF,GAAjF,IAAwF,KAAKC,aAAL,GAAqB,GAArB,GAA2B,GAAnH,IAA0H,GAA1H,IAAiI,KAAKC,UAAL,GAAkB,GAAlB,GAAwB,GAAzJ,IAAgK,GAAhK,GAAsK,KAAKjC,EAA3K,GAAgL,GAAhL,GAAsL,KAAKC,EAAlM;AAAuM;AAxO/L;AAAA;AAAA,gCAyOlB;AAAE,iBAAO,IAAIiC,iBAAJ,CAAqBtC,SAArB,EAAgC,KAAKI,EAArC,EAAyC,KAAKC,EAA9C,EAAkD,KAAK4B,GAAvD,EAA4D,KAAKC,GAAjE,EAAsE,KAAKC,MAA3E,EAAmF,KAAKC,aAAxF,EAAuG,KAAKC,UAA5G,CAAP;AAAiI;AAzOjH;;AAAA;AAAA,MA4NEpE,WA5NF;;AA2O7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwB+B,iBAAgB,CAAC7D,SAAzC,EAAoD;AAClDyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD+C;AAElDR,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF+C;AAGlDiB,MAAAA,EAAE,EAAE;AAACpB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKyB,GAAZ;AAAkB,SAA5B;AAA8BxB,QAAAA,GAA9B,eAAmCmB,EAAnC,EAAuC;AAAE,eAAKK,GAAL,GAAWL,EAAX;;AAAe,eAAKlB,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH8C;AAIlDkB,MAAAA,EAAE,EAAE;AAACrB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK0B,GAAZ;AAAkB,SAA5B;AAA8BzB,QAAAA,GAA9B,eAAmCoB,EAAnC,EAAuC;AAAE,eAAKK,GAAL,GAAWL,EAAX;;AAAe,eAAKnB,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAJ8C;AAKlDmB,MAAAA,KAAK,EAAE;AAACtB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK2B,MAAZ;AAAqB,SAA/B;AAAiC1B,QAAAA,GAAjC,eAAsCqB,KAAtC,EAA6C;AAAE,eAAKK,MAAL,GAAcL,KAAd;;AAAqB,eAAKpB,eAAL;AAAyB,SAA7F;AAA+FC,QAAAA,UAAU,EAAE;AAA3G,OAL2C;AAMlDoB,MAAAA,YAAY,EAAE;AAACvB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK4B,aAAZ;AAA4B,SAAtC;AAAwC3B,QAAAA,GAAxC,eAA6CsB,YAA7C,EAA2D;AAAE,eAAKK,aAAL,GAAqBL,YAArB;;AAAmC,eAAKrB,eAAL;AAAyB,SAAzH;AAA2HC,QAAAA,UAAU,EAAE;AAAvI,OANoC;AAOlDqB,MAAAA,SAAS,EAAE;AAACxB,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAK6B,UAAZ;AAAyB,SAAnC;AAAqC5B,QAAAA,GAArC,eAA0CuB,SAA1C,EAAqD;AAAE,eAAKK,UAAL,GAAkBL,SAAlB;;AAA6B,eAAKtB,eAAL;AAAyB,SAA7G;AAA+GC,QAAAA,UAAU,EAAE;AAA3H;AAPuC,KAApD;;AA3O6B,QAqPvB4B,8BArPuB;AAAA;;AAAA;;AAsP3B,8CAAanE,iBAAb,EAAgC8B,CAAhC,EAAmC;AAAA;;AAAA;;AACjC,sCAAMjC,WAAU,CAACsB,6BAAjB,EAAgD,GAAhD,EAAqDnB,iBAArD;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AAFiC;AAGlC;;AAzP0B;AAAA;AAAA,mCA0Pf;AAAE,iBAAO,wCAAP;AAAkD;AA1PrC;AAAA;AAAA,wCA2PV;AAAE,iBAAO,KAAK5B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAA7C;AAAkD;AA3P1C;AAAA;AAAA,gCA4PlB;AAAE,iBAAO,IAAImC,8BAAJ,CAAkCvC,SAAlC,EAA6C,KAAKI,EAAlD,CAAP;AAA+D;AA5P/C;;AAAA;AAAA,MAqPenC,WArPf;;AA8P7BqC,IAAAA,MAAM,CAACkC,cAAP,CAAsBD,8BAA6B,CAAC9D,SAApD,EAA+D,GAA/D,EAAoE;AAAC+B,MAAAA,GAAD,iBAAQ;AAAE,eAAO,KAAKJ,EAAZ;AAAiB,OAA3B;AAA6BK,MAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,aAAKE,EAAL,GAAUF,CAAV;;AAAa,aAAKQ,eAAL;AAAyB,OAA7E;AAA+EC,MAAAA,UAAU,EAAE;AAA3F,KAApE;;AA9P6B,QAgQvB8B,8BAhQuB;AAAA;;AAAA;;AAiQ3B,8CAAarE,iBAAb,EAAgC8B,CAAhC,EAAmC;AAAA;;AAAA;;AACjC,sCAAMjC,WAAU,CAACuB,6BAAjB,EAAgD,GAAhD,EAAqDpB,iBAArD;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AAFiC;AAGlC;;AApQ0B;AAAA;AAAA,mCAqQf;AAAE,iBAAO,wCAAP;AAAkD;AArQrC;AAAA;AAAA,wCAsQV;AAAE,iBAAO,KAAK5B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAA7C;AAAkD;AAtQ1C;AAAA;AAAA,gCAuQlB;AAAE,iBAAO,IAAIqC,8BAAJ,CAAkCzC,SAAlC,EAA6C,KAAKI,EAAlD,CAAP;AAA+D;AAvQ/C;;AAAA;AAAA,MAgQenC,WAhQf;;AAyQ7BqC,IAAAA,MAAM,CAACkC,cAAP,CAAsBC,8BAA6B,CAAChE,SAApD,EAA+D,GAA/D,EAAoE;AAAC+B,MAAAA,GAAD,iBAAQ;AAAE,eAAO,KAAKJ,EAAZ;AAAiB,OAA3B;AAA6BK,MAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,aAAKE,EAAL,GAAUF,CAAV;;AAAa,aAAKQ,eAAL;AAAyB,OAA7E;AAA+EC,MAAAA,UAAU,EAAE;AAA3F,KAApE;;AAzQ6B,QA2QvB+B,4BA3QuB;AAAA;;AAAA;;AA4Q3B,4CAAatE,iBAAb,EAAgC+B,CAAhC,EAAmC;AAAA;;AAAA;;AACjC,sCAAMlC,WAAU,CAACwB,2BAAjB,EAA8C,GAA9C,EAAmDrB,iBAAnD;AACA,gBAAKiC,EAAL,GAAUF,CAAV;AAFiC;AAGlC;;AA/Q0B;AAAA;AAAA,mCAgRf;AAAE,iBAAO,sCAAP;AAAgD;AAhRnC;AAAA;AAAA,wCAiRV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK+B,EAA7C;AAAkD;AAjR1C;AAAA;AAAA,gCAkRlB;AAAE,iBAAO,IAAIqC,4BAAJ,CAAgC1C,SAAhC,EAA2C,KAAKK,EAAhD,CAAP;AAA6D;AAlR7C;;AAAA;AAAA,MA2QapC,WA3Qb;;AAoR7BqC,IAAAA,MAAM,CAACkC,cAAP,CAAsBE,4BAA2B,CAACjE,SAAlD,EAA6D,GAA7D,EAAkE;AAAC+B,MAAAA,GAAD,iBAAQ;AAAE,eAAO,KAAKH,EAAZ;AAAiB,OAA3B;AAA6BI,MAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,aAAKE,EAAL,GAAUF,CAAV;;AAAa,aAAKO,eAAL;AAAyB,OAA7E;AAA+EC,MAAAA,UAAU,EAAE;AAA3F,KAAlE;;AApR6B,QAsRvBgC,4BAtRuB;AAAA;;AAAA;;AAuR3B,4CAAavE,iBAAb,EAAgC+B,CAAhC,EAAmC;AAAA;;AAAA;;AACjC,sCAAMlC,WAAU,CAACyB,2BAAjB,EAA8C,GAA9C,EAAmDtB,iBAAnD;AACA,gBAAKiC,EAAL,GAAUF,CAAV;AAFiC;AAGlC;;AA1R0B;AAAA;AAAA,mCA2Rf;AAAE,iBAAO,sCAAP;AAAgD;AA3RnC;AAAA;AAAA,wCA4RV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK+B,EAA7C;AAAkD;AA5R1C;AAAA;AAAA,gCA6RlB;AAAE,iBAAO,IAAIsC,4BAAJ,CAAgC3C,SAAhC,EAA2C,KAAKK,EAAhD,CAAP;AAA6D;AA7R7C;;AAAA;AAAA,MAsRapC,WAtRb;;AA+R7BqC,IAAAA,MAAM,CAACkC,cAAP,CAAsBG,4BAA2B,CAAClE,SAAlD,EAA6D,GAA7D,EAAkE;AAAC+B,MAAAA,GAAD,iBAAQ;AAAE,eAAO,KAAKH,EAAZ;AAAiB,OAA3B;AAA6BI,MAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,aAAKE,EAAL,GAAUF,CAAV;;AAAa,aAAKO,eAAL;AAAyB,OAA7E;AAA+EC,MAAAA,UAAU,EAAE;AAA3F,KAAlE;;AA/R6B,QAiSvBiC,gCAjSuB;AAAA;;AAAA;;AAkS3B,gDAAaxE,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCe,EAAtC,EAA0CC,EAA1C,EAA8C;AAAA;;AAAA;;AAC5C,sCAAMlD,WAAU,CAAC0B,gCAAjB,EAAmD,GAAnD,EAAwDvB,iBAAxD;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AACA,gBAAKG,EAAL,GAAUF,CAAV;AACA,gBAAKmB,GAAL,GAAWJ,EAAX;AACA,gBAAKK,GAAL,GAAWJ,EAAX;AAL4C;AAM7C;;AAxS0B;AAAA;AAAA,mCAySf;AAAE,iBAAO,0CAAP;AAAoD;AAzSvC;AAAA;AAAA,wCA0SV;AAAE,iBAAO,KAAK7C,mBAAL,GAA2B,GAA3B,GAAiC,KAAKgD,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKnB,EAAxE,GAA6E,GAA7E,GAAmF,KAAKC,EAA/F;AAAoG;AA1S5F;AAAA;AAAA,gCA2SlB;AAAE,iBAAO,IAAIuC,gCAAJ,CAAoC5C,SAApC,EAA+C,KAAKI,EAApD,EAAwD,KAAKC,EAA7D,EAAiE,KAAKiB,GAAtE,EAA2E,KAAKC,GAAhF,CAAP;AAA8F;AA3S9E;;AAAA;AAAA,MAiSiBtD,WAjSjB;;AA6S7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBqC,gCAA+B,CAACnE,SAAxD,EAAmE;AACjEyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD8D;AAEjER,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF8D;AAGjEO,MAAAA,EAAE,EAAE;AAACV,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKc,GAAZ;AAAkB,SAA5B;AAA8Bb,QAAAA,GAA9B,eAAmCS,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKR,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH6D;AAIjEQ,MAAAA,EAAE,EAAE;AAACX,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKe,GAAZ;AAAkB,SAA5B;AAA8Bd,QAAAA,GAA9B,eAAmCU,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKT,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AAJ6D,KAAnE;;AA7S6B,QAoTvBkC,gCApTuB;AAAA;;AAAA;;AAqT3B,gDAAazE,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsCe,EAAtC,EAA0CC,EAA1C,EAA8C;AAAA;;AAAA;;AAC5C,sCAAMlD,WAAU,CAAC2B,gCAAjB,EAAmD,GAAnD,EAAwDxB,iBAAxD;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AACA,gBAAKG,EAAL,GAAUF,CAAV;AACA,gBAAKmB,GAAL,GAAWJ,EAAX;AACA,gBAAKK,GAAL,GAAWJ,EAAX;AAL4C;AAM7C;;AA3T0B;AAAA;AAAA,mCA4Tf;AAAE,iBAAO,0CAAP;AAAoD;AA5TvC;AAAA;AAAA,wCA6TV;AAAE,iBAAO,KAAK7C,mBAAL,GAA2B,GAA3B,GAAiC,KAAKgD,GAAtC,GAA4C,GAA5C,GAAkD,KAAKC,GAAvD,GAA6D,GAA7D,GAAmE,KAAKnB,EAAxE,GAA6E,GAA7E,GAAmF,KAAKC,EAA/F;AAAoG;AA7T5F;AAAA;AAAA,gCA8TlB;AAAE,iBAAO,IAAIwC,gCAAJ,CAAoC7C,SAApC,EAA+C,KAAKI,EAApD,EAAwD,KAAKC,EAA7D,EAAiE,KAAKiB,GAAtE,EAA2E,KAAKC,GAAhF,CAAP;AAA8F;AA9T9E;;AAAA;AAAA,MAoTiBtD,WApTjB;;AAgU7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBsC,gCAA+B,CAACpE,SAAxD,EAAmE;AACjEyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAD8D;AAEjER,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OAF8D;AAGjEO,MAAAA,EAAE,EAAE;AAACV,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKc,GAAZ;AAAkB,SAA5B;AAA8Bb,QAAAA,GAA9B,eAAmCS,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKR,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F,OAH6D;AAIjEQ,MAAAA,EAAE,EAAE;AAACX,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKe,GAAZ;AAAkB,SAA5B;AAA8Bd,QAAAA,GAA9B,eAAmCU,EAAnC,EAAuC;AAAE,eAAKI,GAAL,GAAWJ,EAAX;;AAAe,eAAKT,eAAL;AAAyB,SAAjF;AAAmFC,QAAAA,UAAU,EAAE;AAA/F;AAJ6D,KAAnE;;AAhU6B,QAuUvBmC,oCAvUuB;AAAA;;AAAA;;AAwU3B,oDAAa1E,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,sCAAMlC,WAAU,CAAC4B,oCAAjB,EAAuD,GAAvD,EAA4DzB,iBAA5D;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AACA,gBAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AA5U0B;AAAA;AAAA,mCA6Uf;AAAE,iBAAO,8CAAP;AAAwD;AA7U3C;AAAA;AAAA,wCA8UV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AA9U1D;AAAA;AAAA,gCA+UlB;AAAE,iBAAO,IAAIyC,oCAAJ,CAAwC9C,SAAxC,EAAmD,KAAKI,EAAxD,EAA4D,KAAKC,EAAjE,CAAP;AAA8E;AA/U9D;;AAAA;AAAA,MAuUqBpC,WAvUrB;;AAiV7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBuC,oCAAmC,CAACrE,SAA5D,EAAuE;AACrEyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADkE;AAErER,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F;AAFkE,KAAvE;;AAjV6B,QAsVvBoC,oCAtVuB;AAAA;;AAAA;;AAuV3B,oDAAa3E,iBAAb,EAAgC8B,CAAhC,EAAmCC,CAAnC,EAAsC;AAAA;;AAAA;;AACpC,sCAAMlC,WAAU,CAAC6B,oCAAjB,EAAuD,GAAvD,EAA4D1B,iBAA5D;AACA,gBAAKgC,EAAL,GAAUF,CAAV;AACA,gBAAKG,EAAL,GAAUF,CAAV;AAHoC;AAIrC;;AA3V0B;AAAA;AAAA,mCA4Vf;AAAE,iBAAO,8CAAP;AAAwD;AA5V3C;AAAA;AAAA,wCA6VV;AAAE,iBAAO,KAAK7B,mBAAL,GAA2B,GAA3B,GAAiC,KAAK8B,EAAtC,GAA2C,GAA3C,GAAiD,KAAKC,EAA7D;AAAkE;AA7V1D;AAAA;AAAA,gCA8VlB;AAAE,iBAAO,IAAI0C,oCAAJ,CAAwC/C,SAAxC,EAAmD,KAAKI,EAAxD,EAA4D,KAAKC,EAAjE,CAAP;AAA8E;AA9V9D;;AAAA;AAAA,MAsVqBpC,WAtVrB;;AAgW7BqC,IAAAA,MAAM,CAACC,gBAAP,CAAwBwC,oCAAmC,CAACtE,SAA5D,EAAuE;AACrEyB,MAAAA,CAAC,EAAE;AAACM,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKJ,EAAZ;AAAiB,SAA3B;AAA6BK,QAAAA,GAA7B,eAAkCP,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKQ,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F,OADkE;AAErER,MAAAA,CAAC,EAAE;AAACK,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKH,EAAZ;AAAiB,SAA3B;AAA6BI,QAAAA,GAA7B,eAAkCN,CAAlC,EAAqC;AAAE,eAAKE,EAAL,GAAUF,CAAV;;AAAa,eAAKO,eAAL;AAAyB,SAA7E;AAA+EC,QAAAA,UAAU,EAAE;AAA3F;AAFkE,KAAvE,EAhW6B;AAsW7B;;AACAqC,IAAAA,cAAc,CAACvE,SAAf,CAAyBwE,yBAAzB,GAAqD,YAAY;AAAE,aAAO,IAAIlD,oBAAJ,CAAwBC,SAAxB,CAAP;AAA4C,KAA/G;;AACAgD,IAAAA,cAAc,CAACvE,SAAf,CAAyByE,yBAAzB,GAAqD,UAAUhD,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAIF,oBAAJ,CAAwBD,SAAxB,EAAmCE,CAAnC,EAAsCC,CAAtC,CAAP;AAAkD,KAAzH;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyB0E,yBAAzB,GAAqD,UAAUjD,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAIS,oBAAJ,CAAwBZ,SAAxB,EAAmCE,CAAnC,EAAsCC,CAAtC,CAAP;AAAkD,KAAzH;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyB2E,yBAAzB,GAAqD,UAAUlD,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAIU,oBAAJ,CAAwBb,SAAxB,EAAmCE,CAAnC,EAAsCC,CAAtC,CAAP;AAAkD,KAAzH;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyB4E,yBAAzB,GAAqD,UAAUnD,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAIW,oBAAJ,CAAwBd,SAAxB,EAAmCE,CAAnC,EAAsCC,CAAtC,CAAP;AAAkD,KAAzH;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyB6E,+BAAzB,GAA2D,UAAUpD,CAAV,EAAaC,CAAb,EAAgBa,EAAhB,EAAoBC,EAApB,EAAwBC,EAAxB,EAA4BC,EAA5B,EAAgC;AAAE,aAAO,IAAIJ,0BAAJ,CAA8Bf,SAA9B,EAAyCE,CAAzC,EAA4CC,CAA5C,EAA+Ca,EAA/C,EAAmDC,EAAnD,EAAuDC,EAAvD,EAA2DC,EAA3D,CAAP;AAAwE,KAArK;;AACA6B,IAAAA,cAAc,CAACvE,SAAf,CAAyB8E,+BAAzB,GAA2D,UAAUrD,CAAV,EAAaC,CAAb,EAAgBa,EAAhB,EAAoBC,EAApB,EAAwBC,EAAxB,EAA4BC,EAA5B,EAAgC;AAAE,aAAO,IAAIK,0BAAJ,CAA8BxB,SAA9B,EAAyCE,CAAzC,EAA4CC,CAA5C,EAA+Ca,EAA/C,EAAmDC,EAAnD,EAAuDC,EAAvD,EAA2DC,EAA3D,CAAP;AAAwE,KAArK;;AACA6B,IAAAA,cAAc,CAACvE,SAAf,CAAyB+E,mCAAzB,GAA+D,UAAUtD,CAAV,EAAaC,CAAb,EAAgBa,EAAhB,EAAoBC,EAApB,EAAwB;AAAE,aAAO,IAAIQ,8BAAJ,CAAkCzB,SAAlC,EAA6CE,CAA7C,EAAgDC,CAAhD,EAAmDa,EAAnD,EAAuDC,EAAvD,CAAP;AAAoE,KAA7J;;AACA+B,IAAAA,cAAc,CAACvE,SAAf,CAAyBgF,mCAAzB,GAA+D,UAAUvD,CAAV,EAAaC,CAAb,EAAgBa,EAAhB,EAAoBC,EAApB,EAAwB;AAAE,aAAO,IAAIS,8BAAJ,CAAkC1B,SAAlC,EAA6CE,CAA7C,EAAgDC,CAAhD,EAAmDa,EAAnD,EAAuDC,EAAvD,CAAP;AAAoE,KAA7J;;AACA+B,IAAAA,cAAc,CAACvE,SAAf,CAAyBiF,sBAAzB,GAAkD,UAAUxD,CAAV,EAAaC,CAAb,EAAgByB,EAAhB,EAAoBC,EAApB,EAAwBC,KAAxB,EAA+BC,YAA/B,EAA6CC,SAA7C,EAAwD;AAAE,aAAO,IAAIL,iBAAJ,CAAqB3B,SAArB,EAAgCE,CAAhC,EAAmCC,CAAnC,EAAsCyB,EAAtC,EAA0CC,EAA1C,EAA8CC,KAA9C,EAAqDC,YAArD,EAAmEC,SAAnE,CAAP;AAAuF,KAAnM;;AACAgB,IAAAA,cAAc,CAACvE,SAAf,CAAyBkF,sBAAzB,GAAkD,UAAUzD,CAAV,EAAaC,CAAb,EAAgByB,EAAhB,EAAoBC,EAApB,EAAwBC,KAAxB,EAA+BC,YAA/B,EAA6CC,SAA7C,EAAwD;AAAE,aAAO,IAAIM,iBAAJ,CAAqBtC,SAArB,EAAgCE,CAAhC,EAAmCC,CAAnC,EAAsCyB,EAAtC,EAA0CC,EAA1C,EAA8CC,KAA9C,EAAqDC,YAArD,EAAmEC,SAAnE,CAAP;AAAuF,KAAnM;;AACAgB,IAAAA,cAAc,CAACvE,SAAf,CAAyBmF,mCAAzB,GAA+D,UAAU1D,CAAV,EAAa;AAAE,aAAO,IAAIqC,8BAAJ,CAAkCvC,SAAlC,EAA6CE,CAA7C,CAAP;AAAyD,KAAvI;;AACA8C,IAAAA,cAAc,CAACvE,SAAf,CAAyBoF,mCAAzB,GAA+D,UAAU3D,CAAV,EAAa;AAAE,aAAO,IAAIuC,8BAAJ,CAAkCzC,SAAlC,EAA6CE,CAA7C,CAAP;AAAyD,KAAvI;;AACA8C,IAAAA,cAAc,CAACvE,SAAf,CAAyBqF,iCAAzB,GAA6D,UAAU3D,CAAV,EAAa;AAAE,aAAO,IAAIuC,4BAAJ,CAAgC1C,SAAhC,EAA2CG,CAA3C,CAAP;AAAuD,KAAnI;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyBsF,iCAAzB,GAA6D,UAAU5D,CAAV,EAAa;AAAE,aAAO,IAAIwC,4BAAJ,CAAgC3C,SAAhC,EAA2CG,CAA3C,CAAP;AAAuD,KAAnI;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyBuF,qCAAzB,GAAiE,UAAU9D,CAAV,EAAaC,CAAb,EAAgBe,EAAhB,EAAoBC,EAApB,EAAwB;AAAE,aAAO,IAAIyB,gCAAJ,CAAoC5C,SAApC,EAA+CE,CAA/C,EAAkDC,CAAlD,EAAqDe,EAArD,EAAyDC,EAAzD,CAAP;AAAsE,KAAjK;;AACA6B,IAAAA,cAAc,CAACvE,SAAf,CAAyBwF,qCAAzB,GAAiE,UAAU/D,CAAV,EAAaC,CAAb,EAAgBe,EAAhB,EAAoBC,EAApB,EAAwB;AAAE,aAAO,IAAI0B,gCAAJ,CAAoC7C,SAApC,EAA+CE,CAA/C,EAAkDC,CAAlD,EAAqDe,EAArD,EAAyDC,EAAzD,CAAP;AAAsE,KAAjK;;AACA6B,IAAAA,cAAc,CAACvE,SAAf,CAAyByF,yCAAzB,GAAqE,UAAUhE,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAI2C,oCAAJ,CAAwC9C,SAAxC,EAAmDE,CAAnD,EAAsDC,CAAtD,CAAP;AAAkE,KAAzJ;;AACA6C,IAAAA,cAAc,CAACvE,SAAf,CAAyB0F,yCAAzB,GAAqE,UAAUjE,CAAV,EAAaC,CAAb,EAAgB;AAAE,aAAO,IAAI4C,oCAAJ,CAAwC/C,SAAxC,EAAmDE,CAAnD,EAAsDC,CAAtD,CAAP;AAAkE,KAAzJ;;AAEA,QAAI,EAAE,wBAAwB6C,cAAc,CAACvE,SAAzC,CAAJ,EAAyD;AACvD;AACA;AACA;AACAuE,MAAAA,cAAc,CAACvE,SAAf,CAAyB2F,kBAAzB,GAA8C,UAAUC,QAAV,EAAoB;AAChE,YAAIA,QAAQ,KAAKrE,SAAb,IAA0B,CAACsE,QAAQ,CAACD,QAAD,CAAvC,EAAmD;AACjD,gBAAM,IAAIE,KAAJ,CAAU,oBAAV,CAAN;AACD;;AAED,YAAMC,kBAAkB,GAAGC,QAAQ,CAACC,eAAT,CAAyB,4BAAzB,EAAuD,MAAvD,CAA3B;AACAF,QAAAA,kBAAkB,CAACG,YAAnB,CAAgC,GAAhC,EAAqC,KAAKC,YAAL,CAAkB,GAAlB,CAArC;AACA,YAAIC,eAAe,GAAGL,kBAAkB,CAACM,WAAnB,CAA+BC,aAA/B,GAA+C,CAArE,CAPgE;;AAUhE,YAAIF,eAAe,IAAI,CAAvB,EAA0B;AACxB,iBAAO,CAAP;AACD;;AAED,WAAG;AACDL,UAAAA,kBAAkB,CAACM,WAAnB,CAA+BE,UAA/B,CAA0CH,eAA1C;;AACA,cAAIR,QAAQ,GAAGG,kBAAkB,CAACS,cAAnB,EAAf,EAAoD;AAClD;AACD;;AACDJ,UAAAA,eAAe;AAChB,SAND,QAMSA,eAAe,GAAG,CAN3B;;AAOA,eAAOA,eAAP;AACD,OAtBD;AAuBD;;AAED7G,IAAAA,MAAM,CAACC,UAAP,GAAoBA,WAApB;AACAD,IAAAA,MAAM,CAAC+B,mBAAP,GAA6BA,oBAA7B;AACA/B,IAAAA,MAAM,CAACiC,mBAAP,GAA6BA,oBAA7B;AACAjC,IAAAA,MAAM,CAAC4C,mBAAP,GAA6BA,oBAA7B;AACA5C,IAAAA,MAAM,CAAC6C,mBAAP,GAA6BA,oBAA7B;AACA7C,IAAAA,MAAM,CAAC8C,mBAAP,GAA6BA,oBAA7B;AACA9C,IAAAA,MAAM,CAAC+C,yBAAP,GAAmCA,0BAAnC;AACA/C,IAAAA,MAAM,CAACwD,yBAAP,GAAmCA,0BAAnC;AACAxD,IAAAA,MAAM,CAACyD,6BAAP,GAAuCA,8BAAvC;AACAzD,IAAAA,MAAM,CAAC0D,6BAAP,GAAuCA,8BAAvC;AACA1D,IAAAA,MAAM,CAAC2D,gBAAP,GAA0BA,iBAA1B;AACA3D,IAAAA,MAAM,CAACsE,gBAAP,GAA0BA,iBAA1B;AACAtE,IAAAA,MAAM,CAACuE,6BAAP,GAAuCA,8BAAvC;AACAvE,IAAAA,MAAM,CAACyE,6BAAP,GAAuCA,8BAAvC;AACAzE,IAAAA,MAAM,CAAC0E,2BAAP,GAAqCA,4BAArC;AACA1E,IAAAA,MAAM,CAAC2E,2BAAP,GAAqCA,4BAArC;AACA3E,IAAAA,MAAM,CAAC4E,+BAAP,GAAyCA,gCAAzC;AACA5E,IAAAA,MAAM,CAAC6E,+BAAP,GAAyCA,gCAAzC;AACA7E,IAAAA,MAAM,CAAC8E,mCAAP,GAA6CA,oCAA7C;AACA9E,IAAAA,MAAM,CAAC+E,mCAAP,GAA6CA,oCAA7C;AACD,GA7aM;AAgbP;AACA;AACA;AACA;;;AACA,MAAI,EAAE,oBAAoB/E,MAAtB,KAAiC,EAAE,gBAAgBA,MAAM,CAACkH,cAAP,CAAsBzG,SAAxC,CAArC,EAAyF;AACvF;AADuF,QAEjFyG,cAFiF;AAGrF,8BAAaC,WAAb,EAA0B;AAAA;;AACxB,aAAKC,YAAL,GAAoBD,WAApB;AACA,aAAKE,KAAL,GAAa,KAAKC,UAAL,CAAgB,KAAKF,YAAL,CAAkBR,YAAlB,CAA+B,GAA/B,CAAhB,CAAb,CAFwB;;AAKxB,aAAKW,uBAAL,GAA+B;AAACC,UAAAA,UAAU,EAAE,IAAb;AAAmBC,UAAAA,eAAe,EAAE,CAAC,GAAD;AAApC,SAA/B;AACA,aAAKC,4BAAL,GAAoC,IAAIC,gBAAJ,CAAqB,KAAKC,4BAAL,CAAkCC,IAAlC,CAAuC,IAAvC,CAArB,CAApC;;AACA,aAAKH,4BAAL,CAAkCI,OAAlC,CAA0C,KAAKV,YAA/C,EAA6D,KAAKG,uBAAlE;AACD,OAXoF;AAarF;AACA;;;AAdqF;AAAA;AAAA,uDAerD;AAC9B,eAAKK,4BAAL,CAAkC,KAAKF,4BAAL,CAAkCK,WAAlC,EAAlC;AACD;AAjBoF;AAAA;AAAA,qDAmBvDC,eAnBuD,EAmBtC;AAC7C,cAAI,CAAC,KAAKZ,YAAV,EAAwB;AACtB;AACD;;AACD,cAAIa,gBAAgB,GAAG,KAAvB;AACAD,UAAAA,eAAe,CAACE,OAAhB,CAAwB,UAACC,MAAD,EAAY;AAClC,gBAAIA,MAAM,CAACC,aAAP,KAAyB,GAA7B,EAAkC;AAChCH,cAAAA,gBAAgB,GAAG,IAAnB;AACD;AACF,WAJD;;AAKA,cAAIA,gBAAJ,EAAsB;AACpB,iBAAKZ,KAAL,GAAa,KAAKC,UAAL,CAAgB,KAAKF,YAAL,CAAkBR,YAAlB,CAA+B,GAA/B,CAAhB,CAAb;AACD;AACF,SAhCoF;;AAAA;AAAA;AAAA,2CAmCjE;AAClB,eAAKc,4BAAL,CAAkCW,UAAlC;;AACA,eAAKjB,YAAL,CAAkBT,YAAlB,CAA+B,GAA/B,EAAoCO,cAAc,CAACoB,qBAAf,CAAqC,KAAKjB,KAA1C,CAApC;;AACA,eAAKK,4BAAL,CAAkCI,OAAlC,CAA0C,KAAKV,YAA/C,EAA6D,KAAKG,uBAAlE;AACD,SAvCoF;;AAAA;AAAA;AAAA,uCA0CrEgB,OA1CqE,EA0C5D;AACvB,eAAKC,gBAAL;AACD;AA5CoF;AAAA;AAAA,gCA8C5E;AACP,eAAKC,4BAAL;;AAEA,eAAKpB,KAAL,CAAWa,OAAX,CAAmB,UAACK,OAAD,EAAa;AAC9BA,YAAAA,OAAO,CAAChI,kBAAR,GAA6B,IAA7B;AACD,WAFD;;AAGA,eAAK8G,KAAL,GAAa,EAAb;;AACA,eAAKmB,gBAAL;AACD;AAtDoF;AAAA;AAAA,mCAwDzEE,OAxDyE,EAwDhE;AACnB,eAAKD,4BAAL;;AAEA,eAAKpB,KAAL,GAAa,CAACqB,OAAD,CAAb;AACAA,UAAAA,OAAO,CAACnI,kBAAR,GAA6B,IAA7B;;AACA,eAAKiI,gBAAL;;AACA,iBAAOE,OAAP;AACD;AA/DoF;AAAA;AAAA,yCAiEnEC,KAjEmE,EAiE5D;AACvB,cAAIC,KAAK,CAACD,KAAD,CAAL,IAAgBA,KAAK,GAAG,CAAxB,IAA6BA,KAAK,IAAI,KAAK5B,aAA/C,EAA8D;AAC5D,kBAAM,IAAIR,KAAJ,CAAU,gBAAV,CAAN;AACD;AACF;AArEoF;AAAA;AAAA,gCAuE5EoC,KAvE4E,EAuErE;AACd,eAAKF,4BAAL;;AAEA,eAAKI,gBAAL,CAAsBF,KAAtB;;AACA,iBAAO,KAAKtB,KAAL,CAAWsB,KAAX,CAAP;AACD;AA5EoF;AAAA;AAAA,yCA8EnED,OA9EmE,EA8E1DC,KA9E0D,EA8EnD;AAChC,eAAKF,4BAAL,GADgC;;;AAIhC,cAAIE,KAAK,GAAG,KAAK5B,aAAjB,EAAgC;AAC9B4B,YAAAA,KAAK,GAAG,KAAK5B,aAAb;AACD;;AACD,cAAI2B,OAAO,CAACnI,kBAAZ,EAAgC;AAC9B;AACAmI,YAAAA,OAAO,GAAGA,OAAO,CAACI,KAAR,EAAV;AACD;;AACD,eAAKzB,KAAL,CAAW0B,MAAX,CAAkBJ,KAAlB,EAAyB,CAAzB,EAA4BD,OAA5B;;AACAA,UAAAA,OAAO,CAACnI,kBAAR,GAA6B,IAA7B;;AACA,eAAKiI,gBAAL;;AACA,iBAAOE,OAAP;AACD;AA7FoF;AAAA;AAAA,oCA+FxEA,OA/FwE,EA+F/DC,KA/F+D,EA+FxD;AAC3B,eAAKF,4BAAL;;AAEA,cAAIC,OAAO,CAACnI,kBAAZ,EAAgC;AAC9B;AACAmI,YAAAA,OAAO,GAAGA,OAAO,CAACI,KAAR,EAAV;AACD;;AACD,eAAKD,gBAAL,CAAsBF,KAAtB;;AACA,eAAKtB,KAAL,CAAWsB,KAAX,IAAoBD,OAApB;AACAA,UAAAA,OAAO,CAACnI,kBAAR,GAA6B,IAA7B;;AACA,eAAKiI,gBAAL;;AACA,iBAAOE,OAAP;AACD;AA3GoF;AAAA;AAAA,mCA6GzEC,KA7GyE,EA6GlE;AACjB,eAAKF,4BAAL;;AAEA,eAAKI,gBAAL,CAAsBF,KAAtB;;AACA,cAAMK,IAAI,GAAG,KAAK3B,KAAL,CAAWsB,KAAX,CAAb;;AACA,eAAKtB,KAAL,CAAW0B,MAAX,CAAkBJ,KAAlB,EAAyB,CAAzB;;AACA,eAAKH,gBAAL;;AACA,iBAAOQ,IAAP;AACD;AArHoF;AAAA;AAAA,mCAuHzEN,OAvHyE,EAuHhE;AACnB,eAAKD,4BAAL;;AAEA,cAAIC,OAAO,CAACnI,kBAAZ,EAAgC;AAC9B;AACAmI,YAAAA,OAAO,GAAGA,OAAO,CAACI,KAAR,EAAV;AACD;;AACD,eAAKzB,KAAL,CAAW4B,IAAX,CAAgBP,OAAhB;;AACAA,UAAAA,OAAO,CAACnI,kBAAR,GAA6B,IAA7B,CARmB;;AAUnB,eAAKiI,gBAAL;;AACA,iBAAOE,OAAP;AACD,SAnIoF;;AAAA;AAAA;AAAA,mCAsIzEQ,MAtIyE,EAsIjE;AAClB,cAAI,CAACA,MAAD,IAAW,CAACA,MAAM,CAACC,MAAvB,EAA+B;AAC7B,mBAAO,EAAP;AACD;;AAED,cAAM/I,iBAAiB,GAAG,IAA1B;;AALkB,cAOZgJ,OAPY;AAQhB,+BAAe;AAAA;;AACb,mBAAKtC,WAAL,GAAmB,EAAnB;AACD;;AAVe;AAAA;AAAA,4CAWDyB,OAXC,EAWQ;AACtB,qBAAKzB,WAAL,CAAiBmC,IAAjB,CAAsBV,OAAtB;AACD;AAbe;;AAAA;AAAA;;AAAA,cAgBZc,MAhBY;AAiBhB,4BAAaH,MAAb,EAAqB;AAAA;;AACnB,mBAAKI,OAAL,GAAeJ,MAAf;AACA,mBAAKK,aAAL,GAAqB,CAArB;AACA,mBAAKC,SAAL,GAAiB,KAAKF,OAAL,CAAaH,MAA9B;AACA,mBAAKM,gBAAL,GAAwBxJ,UAAU,CAACU,eAAnC;;AAEA,mBAAK+I,mBAAL;AACD;;AAxBe;AAAA;AAAA,gDAyBG;AACjB,oBAAMC,SAAS,GAAG,KAAKL,OAAL,CAAa,KAAKC,aAAlB,CAAlB;AACA,uBAAOI,SAAS,IAAI,GAAb,KAAqBA,SAAS,KAAK,GAAd,IAAqBA,SAAS,KAAK,IAAnC,IAA2CA,SAAS,KAAK,IAAzD,IAAiEA,SAAS,KAAK,IAA/E,IAAuFA,SAAS,KAAK,IAA1H,CAAP;AACD;AA5Be;AAAA;AAAA,oDA8BO;AACrB,uBAAO,KAAKJ,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKI,eAAL,EAA9C,EAAsE;AACpE,uBAAKL,aAAL;AACD;;AACD,uBAAO,KAAKA,aAAL,GAAqB,KAAKC,SAAjC;AACD;AAnCe;AAAA;AAAA,+DAqCkB;AAChC,oBAAI,KAAKD,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,CAAC,KAAKI,eAAL,EAAxC,IAAkE,KAAKN,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAlH,EAAuH;AACrH,yBAAO,KAAP;AACD;;AACD,oBAAI,KAAKG,mBAAL,EAAJ,EAAgC;AAC9B,sBAAI,KAAKH,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAvF,EAA4F;AAC1F,yBAAKA,aAAL;;AACA,yBAAKG,mBAAL;AACD;AACF;;AACD,uBAAO,KAAKH,aAAL,GAAqB,KAAKC,SAAjC;AACD;AAhDe;AAAA;AAAA,4CAkDD;AACb,uBAAO,KAAKD,aAAL,GAAqB,KAAKC,SAAjC;AACD;AApDe;AAAA;AAAA,gDAsDG;AACjB,oBAAMM,SAAS,GAAG,KAAKR,OAAL,CAAa,KAAKC,aAAlB,CAAlB;AACA,uBAAO,KAAKQ,oBAAL,CAA0BD,SAA1B,CAAP;AACD;AAzDe;AAAA;AAAA,mDA2DMA,SA3DN,EA2DiB;AAC/B,wBAAQA,SAAR;AACA,uBAAK,GAAL;AACA,uBAAK,GAAL;AACE,2BAAO7J,UAAU,CAACW,iBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOX,UAAU,CAACY,kBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOZ,UAAU,CAACa,kBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOb,UAAU,CAACc,kBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOd,UAAU,CAACe,kBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOf,UAAU,CAACgB,yBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOhB,UAAU,CAACiB,yBAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOjB,UAAU,CAACkB,6BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOlB,UAAU,CAACmB,6BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOnB,UAAU,CAACoB,eAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOpB,UAAU,CAACqB,eAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOrB,UAAU,CAACsB,6BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOtB,UAAU,CAACuB,6BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOvB,UAAU,CAACwB,2BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOxB,UAAU,CAACyB,2BAAlB;;AACF,uBAAK,GAAL;AACE,2BAAOzB,UAAU,CAAC0B,gCAAlB;;AACF,uBAAK,GAAL;AACE,2BAAO1B,UAAU,CAAC2B,gCAAlB;;AACF,uBAAK,GAAL;AACE,2BAAO3B,UAAU,CAAC4B,oCAAlB;;AACF,uBAAK,GAAL;AACE,2BAAO5B,UAAU,CAAC6B,oCAAlB;;AACF;AACE,2BAAO7B,UAAU,CAACU,eAAlB;AAzCF;AA2CD;AAvGe;AAAA;AAAA,iDAyGImJ,SAzGJ,EAyGeE,eAzGf,EAyGgC;AAC9C;AACA,oBAAI,CAACF,SAAS,KAAK,GAAd,IAAqBA,SAAS,KAAK,GAAnC,IAA0CA,SAAS,KAAK,GAAxD,IAAgEA,SAAS,IAAI,GAAb,IAAoBA,SAAS,IAAI,GAAlG,KAA2GE,eAAe,KAAK/J,UAAU,CAACW,iBAA9I,EAAiK;AAC/J,sBAAIoJ,eAAe,KAAK/J,UAAU,CAACY,kBAAnC,EAAuD;AACrD,2BAAOZ,UAAU,CAACc,kBAAlB;AACD;;AACD,sBAAIiJ,eAAe,KAAK/J,UAAU,CAACa,kBAAnC,EAAuD;AACrD,2BAAOb,UAAU,CAACe,kBAAlB;AACD;;AACD,yBAAOgJ,eAAP;AACD;;AACD,uBAAO/J,UAAU,CAACU,eAAlB;AACD;AArHe;AAAA;AAAA,uDAuHU;AACxB;AACA,oBAAI,CAAC,KAAKsJ,WAAL,EAAL,EAAyB;AACvB,yBAAO,IAAP;AACD;;AACD,oBAAMC,OAAO,GAAG,KAAKC,eAAL,EAAhB,CALwB;;AAOxB,uBAAOD,OAAO,KAAKjK,UAAU,CAACY,kBAAvB,IAA6CqJ,OAAO,KAAKjK,UAAU,CAACa,kBAA3E;AACD,eA/He;AAkIhB;;AAlIgB;AAAA;AAAA,6CAmIA;AACd,oBAAIsJ,QAAQ,GAAG,CAAf;AACA,oBAAIC,OAAO,GAAG,CAAd;AACA,oBAAIC,IAAI,GAAG,CAAX;AACA,oBAAIC,OAAO,GAAG,CAAd;AACA,oBAAIC,IAAI,GAAG,CAAX;AACA,oBAAIC,OAAO,GAAG,CAAd;AAEA,oBAAMC,UAAU,GAAG,KAAKnB,aAAxB;;AAEA,qBAAKG,mBAAL,GAVc;;;AAad,oBAAI,KAAKH,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAvF,EAA4F;AAC1F,uBAAKA,aAAL;AACD,iBAFD,MAEO,IAAI,KAAKA,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAvF,EAA4F;AACjG,uBAAKA,aAAL;AACAiB,kBAAAA,IAAI,GAAG,CAAC,CAAR;AACD;;AAED,oBAAI,KAAKjB,aAAL,KAAuB,KAAKC,SAA5B,IAA0C,CAAC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAA1C,IAAiD,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAA5F,KAAoG,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAA9L,EAAoM;AAClM;AACA,yBAAOvH,SAAP;AACD,iBAvBa;;;AA0Bd,oBAAM2I,iBAAiB,GAAG,KAAKpB,aAA/B;;AACA,uBAAO,KAAKA,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAAlF,IAAyF,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAA3I,EAAgJ;AAC9I,uBAAKA,aAAL,GAD8I;AAE/I;;AAED,oBAAI,KAAKA,aAAL,KAAuBoB,iBAA3B,EAA8C;AAC5C,sBAAIC,gBAAgB,GAAG,KAAKrB,aAAL,GAAqB,CAA5C;AACA,sBAAIsB,UAAU,GAAG,CAAjB;;AACA,yBAAOD,gBAAgB,IAAID,iBAA3B,EAA8C;AAC5CN,oBAAAA,OAAO,IAAIQ,UAAU,IAAI,KAAKvB,OAAL,CAAaO,MAAb,CAAoBe,gBAAgB,EAApC,IAA0C,GAA9C,CAArB;AACAC,oBAAAA,UAAU,IAAI,EAAd;AACD;AACF,iBAtCa;;;AAyCd,oBAAI,KAAKtB,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAvF,EAA4F;AAC1F,uBAAKA,aAAL,GAD0F;;AAI1F,sBAAI,KAAKA,aAAL,IAAsB,KAAKC,SAA3B,IAAwC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAAlF,IAAyF,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAAvI,EAA4I;AAC1I,2BAAOvH,SAAP;AACD;;AACD,yBAAO,KAAKuH,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAAlF,IAAyF,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAA3I,EAAgJ;AAC9Ie,oBAAAA,IAAI,IAAI,EAAR;AACAC,oBAAAA,OAAO,IAAI,CAAC,KAAKjB,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAA3C,IAAkDe,IAA7D;AACA,yBAAKf,aAAL,IAAsB,CAAtB;AACD;AACF,iBArDa;;;AAwDd,oBAAI,KAAKA,aAAL,KAAuBmB,UAAvB,IAAqC,KAAKnB,aAAL,GAAqB,CAArB,GAAyB,KAAKC,SAAnE,KAAiF,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAA5C,IAAmD,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAhL,KAAyL,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAL,GAAqB,CAAzC,MAAgD,GAAhD,IAAuD,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAL,GAAqB,CAAzC,MAAgD,GAApS,EAA0S;AACxS,uBAAKA,aAAL,GADwS;;AAIxS,sBAAI,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAhD,EAAqD;AACnD,yBAAKA,aAAL;AACD,mBAFD,MAEO,IAAI,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,MAA4C,GAAhD,EAAqD;AAC1D,yBAAKA,aAAL;AACAkB,oBAAAA,OAAO,GAAG,CAAC,CAAX;AACD,mBATuS;;;AAYxS,sBAAI,KAAKlB,aAAL,IAAsB,KAAKC,SAA3B,IAAwC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAAlF,IAAyF,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAAvI,EAA4I;AAC1I,2BAAOvH,SAAP;AACD;;AAED,yBAAO,KAAKuH,aAAL,GAAqB,KAAKC,SAA1B,IAAuC,KAAKF,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAAlF,IAAyF,KAAKD,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,KAA2C,GAA3I,EAAgJ;AAC9Ia,oBAAAA,QAAQ,IAAI,EAAZ;AACAA,oBAAAA,QAAQ,IAAK,KAAKd,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAzB,IAA0C,GAAvD;AACA,yBAAKA,aAAL;AACD;AACF;;AAED,oBAAIuB,MAAM,GAAGT,OAAO,GAAGE,OAAvB;AACAO,gBAAAA,MAAM,IAAIN,IAAV;;AAEA,oBAAIJ,QAAJ,EAAc;AACZU,kBAAAA,MAAM,aAAI,EAAJ,EAAWL,OAAO,GAAGL,QAArB,CAAN;AACD;;AAED,oBAAIM,UAAU,KAAK,KAAKnB,aAAxB,EAAuC;AACrC,yBAAOvH,SAAP;AACD;;AAED,qBAAK+I,8BAAL;;AAEA,uBAAOD,MAAP;AACD;AAhOe;AAAA;AAAA,8CAkOC;AACf,oBAAI,KAAKvB,aAAL,IAAsB,KAAKC,SAA/B,EAA0C;AACxC,yBAAOxH,SAAP;AACD;;AACD,oBAAIgJ,IAAI,GAAG,KAAX;;AACA,oBAAMC,QAAQ,GAAG,KAAK3B,OAAL,CAAaO,MAAb,CAAoB,KAAKN,aAAL,EAApB,CAAjB;;AACA,oBAAI0B,QAAQ,KAAK,GAAjB,EAAsB;AACpBD,kBAAAA,IAAI,GAAG,KAAP;AACD,iBAFD,MAEO,IAAIC,QAAQ,KAAK,GAAjB,EAAsB;AAC3BD,kBAAAA,IAAI,GAAG,IAAP;AACD,iBAFM,MAEA;AACL,yBAAOhJ,SAAP;AACD;;AAED,qBAAK+I,8BAAL;;AACA,uBAAOC,IAAP;AACD;AAlPe;AAAA;AAAA,6CAoPA;AACd,oBAAMlB,SAAS,GAAG,KAAKR,OAAL,CAAa,KAAKC,aAAlB,CAAlB;;AACA,oBAAIW,OAAO,GAAG,KAAKH,oBAAL,CAA0BD,SAA1B,CAAd;;AACA,oBAAII,OAAO,KAAKjK,UAAU,CAACU,eAA3B,EAA4C;AAC1C;AACA,sBAAI,KAAK8I,gBAAL,KAA0BxJ,UAAU,CAACU,eAAzC,EAA0D;AACxD,2BAAO,IAAP;AACD;;AACDuJ,kBAAAA,OAAO,GAAG,KAAKgB,kBAAL,CAAwBpB,SAAxB,EAAmC,KAAKL,gBAAxC,CAAV;;AACA,sBAAIS,OAAO,KAAKjK,UAAU,CAACU,eAA3B,EAA4C;AAC1C,2BAAO,IAAP;AACD;AACF,iBATD,MASO;AACL,uBAAK4I,aAAL;AACD;;AAED,qBAAKE,gBAAL,GAAwBS,OAAxB;;AAEA,wBAAQA,OAAR;AACA,uBAAKjK,UAAU,CAACa,kBAAhB;AACE,2BAAO,IAAI8B,mBAAJ,CAAwBxC,iBAAxB,EAA2C,KAAK+K,YAAL,EAA3C,EAAgE,KAAKA,YAAL,EAAhE,CAAP;;AACF,uBAAKlL,UAAU,CAACY,kBAAhB;AACE,2BAAO,IAAIoB,mBAAJ,CAAwB7B,iBAAxB,EAA2C,KAAK+K,YAAL,EAA3C,EAAgE,KAAKA,YAAL,EAAhE,CAAP;;AACF,uBAAKlL,UAAU,CAACe,kBAAhB;AACE,2BAAO,IAAI8B,mBAAJ,CAAwB1C,iBAAxB,EAA2C,KAAK+K,YAAL,EAA3C,EAAgE,KAAKA,YAAL,EAAhE,CAAP;;AACF,uBAAKlL,UAAU,CAACc,kBAAhB;AACE,2BAAO,IAAI8B,mBAAJ,CAAwBzC,iBAAxB,EAA2C,KAAK+K,YAAL,EAA3C,EAAgE,KAAKA,YAAL,EAAhE,CAAP;;AACF,uBAAKlL,UAAU,CAACuB,6BAAhB;AACE,2BAAO,IAAIiD,6BAAJ,CAAkCrE,iBAAlC,EAAqD,KAAK+K,YAAL,EAArD,CAAP;;AACF,uBAAKlL,UAAU,CAACsB,6BAAhB;AACE,2BAAO,IAAIgD,6BAAJ,CAAkCnE,iBAAlC,EAAqD,KAAK+K,YAAL,EAArD,CAAP;;AACF,uBAAKlL,UAAU,CAACyB,2BAAhB;AACE,2BAAO,IAAIiD,2BAAJ,CAAgCvE,iBAAhC,EAAmD,KAAK+K,YAAL,EAAnD,CAAP;;AACF,uBAAKlL,UAAU,CAACwB,2BAAhB;AACE,2BAAO,IAAIiD,2BAAJ,CAAgCtE,iBAAhC,EAAmD,KAAK+K,YAAL,EAAnD,CAAP;;AACF,uBAAKlL,UAAU,CAACW,iBAAhB;AACE,yBAAK8I,mBAAL;;AACA,2BAAO,IAAI3H,mBAAJ,CAAwB3B,iBAAxB,CAAP;;AACF,uBAAKH,UAAU,CAACiB,yBAAhB;AAA2C;AACzC,0BAAMkK,MAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDjI,wBAAAA,EAAE,EAAE,KAAKiI,YAAL,EAAvD;AAA4EhI,wBAAAA,EAAE,EAAE,KAAKgI,YAAL,EAAhF;AAAqGjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAxG;AAA6HhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAAhI,uBAAf;AACA,6BAAO,IAAI3H,yBAAJ,CAA8BpD,iBAA9B,EAAiDgL,MAAM,CAAClJ,CAAxD,EAA2DkJ,MAAM,CAACjJ,CAAlE,EAAqEiJ,MAAM,CAACpI,EAA5E,EAAgFoI,MAAM,CAACnI,EAAvF,EAA2FmI,MAAM,CAAClI,EAAlG,EAAsGkI,MAAM,CAACjI,EAA7G,CAAP;AACD;;AAAC,uBAAKlD,UAAU,CAACgB,yBAAhB;AAA2C;AAC3C,0BAAMmK,OAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDjI,wBAAAA,EAAE,EAAE,KAAKiI,YAAL,EAAvD;AAA4EhI,wBAAAA,EAAE,EAAE,KAAKgI,YAAL,EAAhF;AAAqGjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAxG;AAA6HhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAAhI,uBAAf;AACA,6BAAO,IAAIpI,yBAAJ,CAA8B3C,iBAA9B,EAAiDgL,OAAM,CAAClJ,CAAxD,EAA2DkJ,OAAM,CAACjJ,CAAlE,EAAqEiJ,OAAM,CAACpI,EAA5E,EAAgFoI,OAAM,CAACnI,EAAvF,EAA2FmI,OAAM,CAAClI,EAAlG,EAAsGkI,OAAM,CAACjI,EAA7G,CAAP;AACD;;AAAC,uBAAKlD,UAAU,CAAC2B,gCAAhB;AAAkD;AAClD,0BAAMwJ,QAAM,GAAG;AAAClI,wBAAAA,EAAE,EAAE,KAAKiI,YAAL,EAAL;AAA0BhI,wBAAAA,EAAE,EAAE,KAAKgI,YAAL,EAA9B;AAAmDjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAtD;AAA2EhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA9E,uBAAf;AACA,6BAAO,IAAItG,+BAAJ,CAAoCzE,iBAApC,EAAuDgL,QAAM,CAAClJ,CAA9D,EAAiEkJ,QAAM,CAACjJ,CAAxE,EAA2EiJ,QAAM,CAAClI,EAAlF,EAAsFkI,QAAM,CAACjI,EAA7F,CAAP;AACD;;AAAC,uBAAKlD,UAAU,CAAC0B,gCAAhB;AAAkD;AAClD,0BAAMyJ,QAAM,GAAG;AAAClI,wBAAAA,EAAE,EAAE,KAAKiI,YAAL,EAAL;AAA0BhI,wBAAAA,EAAE,EAAE,KAAKgI,YAAL,EAA9B;AAAmDjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAtD;AAA2EhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA9E,uBAAf;AACA,6BAAO,IAAIvG,+BAAJ,CAAoCxE,iBAApC,EAAuDgL,QAAM,CAAClJ,CAA9D,EAAiEkJ,QAAM,CAACjJ,CAAxE,EAA2EiJ,QAAM,CAAClI,EAAlF,EAAsFkI,QAAM,CAACjI,EAA7F,CAAP;AACD;;AAAC,uBAAKlD,UAAU,CAACmB,6BAAhB;AAA+C;AAC/C,0BAAMgK,QAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAtD;AAA2EhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA9E,uBAAf;AACA,6BAAO,IAAIzH,6BAAJ,CAAkCtD,iBAAlC,EAAqDgL,QAAM,CAAClJ,CAA5D,EAA+DkJ,QAAM,CAACjJ,CAAtE,EAAyEiJ,QAAM,CAACpI,EAAhF,EAAoFoI,QAAM,CAACnI,EAA3F,CAAP;AACD;;AAAC,uBAAKhD,UAAU,CAACkB,6BAAhB;AAA+C;AAC/C,0BAAMiK,QAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDjJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAAtD;AAA2EhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA9E,uBAAf;AACA,6BAAO,IAAI1H,6BAAJ,CAAkCrD,iBAAlC,EAAqDgL,QAAM,CAAClJ,CAA5D,EAA+DkJ,QAAM,CAACjJ,CAAtE,EAAyEiJ,QAAM,CAACpI,EAAhF,EAAoFoI,QAAM,CAACnI,EAA3F,CAAP;AACD;;AAAC,uBAAKhD,UAAU,CAAC6B,oCAAhB;AACA,2BAAO,IAAIiD,mCAAJ,CAAwC3E,iBAAxC,EAA2D,KAAK+K,YAAL,EAA3D,EAAgF,KAAKA,YAAL,EAAhF,CAAP;;AACF,uBAAKlL,UAAU,CAAC4B,oCAAhB;AACE,2BAAO,IAAIiD,mCAAJ,CAAwC1E,iBAAxC,EAA2D,KAAK+K,YAAL,EAA3D,EAAgF,KAAKA,YAAL,EAAhF,CAAP;;AACF,uBAAKlL,UAAU,CAACqB,eAAhB;AAAiC;AAC/B,0BAAM8J,QAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDE,wBAAAA,QAAQ,EAAE,KAAKF,YAAL,EAA7D;AAAkFG,wBAAAA,QAAQ,EAAE,KAAKC,aAAL,EAA5F;AAAkHC,wBAAAA,QAAQ,EAAE,KAAKD,aAAL,EAA5H;AAAkJrJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAArJ;AAA0KhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA7K,uBAAf;AACA,6BAAO,IAAI7G,gBAAJ,CAAqBlE,iBAArB,EAAwCgL,QAAM,CAAClJ,CAA/C,EAAkDkJ,QAAM,CAACjJ,CAAzD,EAA4DiJ,QAAM,CAACpI,EAAnE,EAAuEoI,QAAM,CAACnI,EAA9E,EAAkFmI,QAAM,CAACC,QAAzF,EAAmGD,QAAM,CAACE,QAA1G,EAAoHF,QAAM,CAACI,QAA3H,CAAP;AACD;;AAAC,uBAAKvL,UAAU,CAACoB,eAAhB;AAAiC;AACjC,0BAAM+J,QAAM,GAAG;AAACpI,wBAAAA,EAAE,EAAE,KAAKmI,YAAL,EAAL;AAA0BlI,wBAAAA,EAAE,EAAE,KAAKkI,YAAL,EAA9B;AAAmDE,wBAAAA,QAAQ,EAAE,KAAKF,YAAL,EAA7D;AAAkFG,wBAAAA,QAAQ,EAAE,KAAKC,aAAL,EAA5F;AAAkHC,wBAAAA,QAAQ,EAAE,KAAKD,aAAL,EAA5H;AAAkJrJ,wBAAAA,CAAC,EAAE,KAAKiJ,YAAL,EAArJ;AAA0KhJ,wBAAAA,CAAC,EAAE,KAAKgJ,YAAL;AAA7K,uBAAf;AACA,6BAAO,IAAIxH,gBAAJ,CAAqBvD,iBAArB,EAAwCgL,QAAM,CAAClJ,CAA/C,EAAkDkJ,QAAM,CAACjJ,CAAzD,EAA4DiJ,QAAM,CAACpI,EAAnE,EAAuEoI,QAAM,CAACnI,EAA9E,EAAkFmI,QAAM,CAACC,QAAzF,EAAmGD,QAAM,CAACE,QAA1G,EAAoHF,QAAM,CAACI,QAA3H,CAAP;AACD;;AAAC;AACA,0BAAM,IAAIjF,KAAJ,CAAU,wBAAV,CAAN;AAjDF;AAmDD;AAzTe;;AAAA;AAAA;;AA4TlB,cAAMkF,OAAO,GAAG,IAAIrC,OAAJ,EAAhB;AACA,cAAMsC,MAAM,GAAG,IAAIrC,MAAJ,CAAWH,MAAX,CAAf;;AAEA,cAAI,CAACwC,MAAM,CAACC,sBAAP,EAAL,EAAsC;AACpC,mBAAO,EAAP;AACD;;AACD,iBAAOD,MAAM,CAACzB,WAAP,EAAP,EAA6B;AAC3B,gBAAM1B,OAAO,GAAGmD,MAAM,CAACE,YAAP,EAAhB;;AACA,gBAAI,CAACrD,OAAL,EAAc;AACZ,qBAAO,EAAP;AACD;;AACDkD,YAAAA,OAAO,CAACI,aAAR,CAAsBtD,OAAtB;AACD;;AAED,iBAAOkD,OAAO,CAAC3E,WAAf;AACD,SAjdoF;;AAAA;AAAA;AAAA,8CAodvDgF,YApduD,EAodzC;AAC1C,cAAI5C,MAAM,GAAG,EAAb;AACA,cAAI6C,KAAK,GAAG,IAAZ;AACAD,UAAAA,YAAY,CAAC5D,OAAb,CAAqB,UAACK,OAAD,EAAa;AAChC,gBAAIwD,KAAJ,EAAW;AACTA,cAAAA,KAAK,GAAG,KAAR;AACA7C,cAAAA,MAAM,IAAIX,OAAO,CAACyD,aAAR,EAAV;AACD,aAHD,MAGO;AACL9C,cAAAA,MAAM,IAAI,MAAMX,OAAO,CAACyD,aAAR,EAAhB;AACD;AACF,WAPD;AAQA,iBAAO9C,MAAP;AACD;AAheoF;;AAAA;AAAA;;AAmevFhC,IAAAA,cAAc,CAACzG,SAAf,CAAyBC,SAAzB,GAAqC,gBAArC;AAEA4B,IAAAA,MAAM,CAACkC,cAAP,CAAsB0C,cAAc,CAACzG,SAArC,EAAgD,eAAhD,EAAiE;AAC/D+B,MAAAA,GAD+D,iBACxD;AACL,aAAKiG,4BAAL;;AACA,eAAO,KAAKpB,KAAL,CAAW8B,MAAlB;AACD,OAJ8D;AAK/DxG,MAAAA,UAAU,EAAE;AALmD,KAAjE,EAreuF;AA8evF;;AACAL,IAAAA,MAAM,CAACC,gBAAP,CAAwByC,cAAc,CAACvE,SAAvC,EAAkD;AAChDqG,MAAAA,WAAW,EAAE;AACXtE,QAAAA,GADW,iBACJ;AACL,cAAI,CAAC,KAAKyJ,YAAV,EAAwB;AACtB,iBAAKA,YAAL,GAAoB,IAAI/E,cAAJ,CAAmB,IAAnB,CAApB;AACD;;AACD,iBAAO,KAAK+E,YAAZ;AACD,SANU;AAOXtJ,QAAAA,UAAU,EAAE;AAPD,OADmC;AAUhD;AACAuJ,MAAAA,qBAAqB,EAAE;AAAC1J,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKsE,WAAZ;AAA0B,SAApC;AAAsCnE,QAAAA,UAAU,EAAE;AAAlD,OAXyB;AAYhDwJ,MAAAA,mBAAmB,EAAE;AAAC3J,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKsE,WAAZ;AAA0B,SAApC;AAAsCnE,QAAAA,UAAU,EAAE;AAAlD,OAZ2B;AAahDyJ,MAAAA,6BAA6B,EAAE;AAAC5J,QAAAA,GAAD,iBAAQ;AAAE,iBAAO,KAAKsE,WAAZ;AAA0B,SAApC;AAAsCnE,QAAAA,UAAU,EAAE;AAAlD;AAbiB,KAAlD;AAeA3C,IAAAA,MAAM,CAACkH,cAAP,GAAwBA,cAAxB;AACD;AACA,CAp7BD;;ACZA;;AACA,mBAAe;AACbmF,EAAAA,IAAI,EAAE,WADO;AAEPC,EAAAA,IAFO,sBAEkB;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAlBC,cAAAA,YAAkB,QAAlBA,YAAkB,EAAJC,CAAI,QAAJA,CAAI;AAAA;AAAA,qBACPD,YAAY,EADL;;AAAA;AACvBE,cAAAA,OADuB;AAEvBC,cAAAA,SAFuB,GAEX,KAFW;;AAIvBC,cAAAA,YAJuB,GAIR,SAAfA,YAAe,CAAUC,IAAV,EAAgB;AACnC,oBAAMC,OAAO,GAAGD,IAAI,CAAC9F,WAArB;AAAA,oBACEgG,MAAM,GAAGD,OAAO,CAACE,OAAR,CAAgBF,OAAO,CAAC9F,aAAR,GAAwB,CAAxC,EAA2C1G,WAA3C,KAA2D,CADtE;AAAA,oBAEE2M,UAAU,GAAGF,MAAM,GAAG,gBAAH,GAAsB,iBAF3C;AAAA,oBAGEG,UAAU,GAAGH,MAAM,GAAG,iBAAH,GAAuB,gBAH5C;AAIAN,gBAAAA,CAAC,CAACS,UAAD,CAAD,CAAcC,IAAd;AACAV,gBAAAA,CAAC,CAACQ,UAAD,CAAD,CAAcG,IAAd;AACD,eAX4B;;AAYvBC,cAAAA,SAZuB,GAYX,SAAZA,SAAY,CAAUC,EAAV,EAAc;AAC9Bb,gBAAAA,CAAC,CAAC,kBAAD,CAAD,CAAsBc,MAAtB,CAA6BD,EAA7B;;AACA,oBAAIA,EAAJ,EAAQ;AACN,sBAAMT,IAAI,GAAGW,QAAQ,CAAC,CAAD,CAArB;;AACA,sBAAIX,IAAJ,EAAU;AAAED,oBAAAA,YAAY,CAACC,IAAD,CAAZ;AAAqB;AAClC;AACF,eAlB4B;;AAmBvBY,cAAAA,YAnBuB,GAmBR,SAAfA,YAAe,GAAY;AAC/B,oBAAMZ,IAAI,GAAGW,QAAQ,CAAC,CAAD,CAArB;;AACA,oBAAIX,IAAJ,EAAU;AACR,sBAAMC,OAAO,GAAGD,IAAI,CAAC9F,WAArB;AAAA,sBACE2G,IAAI,GAAGZ,OAAO,CAAC9F,aAAR,GAAwB,CADjC,CADQ;;AAIR,sBAAI8F,OAAO,CAACE,OAAR,CAAgBU,IAAhB,EAAsBpN,WAAtB,KAAsC,CAA1C,EAA6C;AAC3CwM,oBAAAA,OAAO,CAAC7F,UAAR,CAAmByG,IAAnB;AACD,mBAFD,MAEO;AACLZ,oBAAAA,OAAO,CAACa,UAAR,CAAmBd,IAAI,CAAC3H,yBAAL,EAAnB;AACD;;AACD0H,kBAAAA,YAAY,CAACC,IAAD,CAAZ;AACD;AACF,eAhC4B;;AAkCvBe,cAAAA,OAlCuB,GAkCb,CACd;AACEC,gBAAAA,EAAE,EAAE,eADN;AAEEC,gBAAAA,IAAI,EAAEnB,SAAS,CAACoB,SAAV,CAAoBC,YAApB,GAAmC,cAF3C;AAGE7N,gBAAAA,IAAI,EAAE,SAHR;AAIE8N,gBAAAA,KAAK,EAAE,iBAJT;AAKEC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPV,oBAAAA,YAAY;AACb;AAHK;AALV,eADc,EAYd;AACEI,gBAAAA,EAAE,EAAE,gBADN;AAEEC,gBAAAA,IAAI,EAAEnB,SAAS,CAACoB,SAAV,CAAoBC,YAApB,GAAmC,eAF3C;AAGE7N,gBAAAA,IAAI,EAAE,SAHR;AAIE8N,gBAAAA,KAAK,EAAE,iBAJT;AAKEC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPV,oBAAAA,YAAY;AACb;AAHK;AALV,eAZc,CAlCa;AAAA,+CA2DtB;AACLnB,gBAAAA,IAAI,EAAEI,OAAO,CAACJ,IADT;AAEL8B,gBAAAA,QAAQ,EAAEzB,SAAS,CAACoB,SAAV,CAAoBC,YAApB,GAAmC,qBAFxC;AAGLJ,gBAAAA,OAAO,EAAElB,OAAO,CAACkB,OAAR,CAAgBS,GAAhB,CAAoB,UAACC,MAAD,EAASC,CAAT,EAAe;AAC1C,yBAAOhM,MAAM,CAACiM,MAAP,CAAcZ,OAAO,CAACW,CAAD,CAArB,EAA0BD,MAA1B,CAAP;AACD,iBAFQ,CAHJ;AAMLG,gBAAAA,QANK,sBAMO;AACVhC,kBAAAA,CAAC,CAAC,kBAAD,CAAD,CAAsBU,IAAtB;AACD,iBARI;AASLuB,gBAAAA,eATK,2BASYC,IATZ,EASkB;AACrBnB,kBAAAA,QAAQ,GAAGmB,IAAI,CAACC,KAAhB;AACA,sBAAIL,CAAC,GAAGf,QAAQ,CAACpE,MAAjB;;AACA,yBAAOmF,CAAC,EAAR,EAAY;AACV,wBAAMM,IAAI,GAAGrB,QAAQ,CAACe,CAAD,CAArB;;AACA,wBAAIM,IAAI,IAAIA,IAAI,CAACC,OAAL,KAAiB,MAA7B,EAAqC;AACnC,0BAAIH,IAAI,CAACI,eAAL,IAAwB,CAACJ,IAAI,CAACK,aAAlC,EAAiD;AAC/C3B,wBAAAA,SAAS,CAAC,IAAD,CAAT;AACD,uBAFD,MAEO;AACLA,wBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF,qBAND,MAMO;AACLA,sBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF;AACF;AAxBI,eA3DsB;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqF9B;AAvFY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-connector.js b/dist/editor/extensions/ext-connector.js deleted file mode 100644 index d43dbd98..00000000 --- a/dist/editor/extensions/ext-connector.js +++ /dev/null @@ -1,2300 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -/** - * @file ext-connector.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ -var extConnector = { - name: 'connector', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - init = function _init() { - // Make sure all connectors have data set - $(svgcontent).find('*').each(function () { - var conn = this.getAttributeNS(seNs, 'connector'); - - if (conn) { - this.setAttribute('class', connSel.substr(1)); - var connData = conn.split(' '); - var sbb = svgCanvas.getStrokedBBox([getElem(connData[0])]); - var ebb = svgCanvas.getStrokedBBox([getElem(connData[1])]); - $(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb); - svgCanvas.getEditorNS(true); - } - }); // updateConnectors(); - }; - - updateConnectors = function _updateConnectors(elems) { - // Updates connector lines based on selected elements - // Is not used on mousemove, as it runs getStrokedBBox every time, - // which isn't necessary there. - findConnectors(elems); - - if (connections.length) { - // Update line with element - var i = connections.length; - - while (i--) { - var conn = connections[i]; - var line = conn.connector; - var elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5; - - var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element - - var bb = svgCanvas.getStrokedBBox([elem]); - bb.x = conn.start_x; - bb.y = conn.start_y; - elData(line, pre + '_bb', bb); - /* const addOffset = */ - - elData(line, pre + '_off'); - var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element - - var bb2 = elData(line, altPre + '_bb'); - var srcX = bb2.x + bb2.width / 2; - var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); - setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element - - var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit - - if (navigator.userAgent.includes('AppleWebKit')) { - var pts = line.points; - var len = pts.numberOfItems; - var ptArr = []; - - for (var j = 0; j < len; j++) { - pt = pts.getItem(j); - ptArr[j] = pt.x + ',' + pt.y; - } - - line.setAttribute('points', ptArr.join(' ')); - } - } - } - }; - - findConnectors = function _findConnectors() { - var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems; - var connectors = $(svgcontent).find(connSel); - connections = []; // Loop through connectors to see if one is connected to the element - - connectors.each(function () { - var addThis; - /** - * - * @returns {void} - */ - - function add() { - if (elems.includes(this)) { - // Pretend this element is selected - addThis = true; - } - } // Grab the ends - - - var parts = []; - ['start', 'end'].forEach(function (pos, i) { - var key = 'c_' + pos; - var part = elData(this, key); - - if (part === null || part === undefined) { - // Does this ever return nullish values? - part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); - elData(this, 'c_' + pos, part.id); - elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); - } else part = document.getElementById(part); - - parts.push(part); - }, this); - - for (var i = 0; i < 2; i++) { - var cElem = parts[i]; - addThis = false; // The connected element might be part of a selected group - - $(cElem).parents().each(add); - - if (!cElem || !cElem.parentNode) { - $(this).remove(); - continue; - } - - if (elems.includes(cElem) || addThis) { - var bb = svgCanvas.getStrokedBBox([cElem]); - connections.push({ - elem: cElem, - connector: this, - is_start: i === 0, - start_x: bb.x, - start_y: bb.y - }); - } - } - }); - }; - - updateLine = function _updateLine(diffX, diffY) { - // Update line with element - var i = connections.length; - - while (i--) { - var conn = connections[i]; - var line = conn.connector; // const {elem} = conn; - - var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5; - // Update bbox for this element - - var bb = elData(line, pre + '_bb'); - bb.x = conn.start_x + diffX; - bb.y = conn.start_y + diffY; - elData(line, pre + '_bb', bb); - var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element - - var bb2 = elData(line, altPre + '_bb'); - var srcX = bb2.x + bb2.width / 2; - var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0 - - setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element - - var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); - } - }; - - setPoint = function _setPoint(elem, pos, x, y, setMid) { - var pts = elem.points; - var pt = svgroot.createSVGPoint(); - pt.x = x; - pt.y = y; - - if (pos === 'end') { - pos = pts.numberOfItems - 1; - } // TODO: Test for this on init, then use alt only if needed - - - try { - pts.replaceItem(pt, pos); - } catch (err) { - // Should only occur in FF which formats points attr as "n,n n,n", so just split - var ptArr = elem.getAttribute('points').split(' '); - - for (var i = 0; i < ptArr.length; i++) { - if (i === pos) { - ptArr[i] = x + ',' + y; - } - } - - elem.setAttribute('points', ptArr.join(' ')); - } - - if (setMid) { - // Add center point - var ptStart = pts.getItem(0); - var ptEnd = pts.getItem(pts.numberOfItems - 1); - setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2); - } - }; - - showPanel = function _showPanel(on) { - var connRules = $('#connector_rules'); - - if (!connRules.length) { - connRules = $('').appendTo('head'); - } - - connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'); - $('#connector_panel').toggle(on); - }; - - getOffset = function _getOffset(side, line) { - var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); - // TODO: Make this number (5) be based on marker width/height - - var size = line.getAttribute('stroke-width') * 5; - return giveOffset ? size : 0; - }; - - getBBintersect = function _getBBintersect(x, y, bb, offset) { - if (offset) { - offset -= 0; - bb = $.extend({}, bb); - bb.width += offset; - bb.height += offset; - bb.x -= offset / 2; - bb.y -= offset / 2; - } - - var midX = bb.x + bb.width / 2; - var midY = bb.y + bb.height / 2; - var lenX = x - midX; - var lenY = y - midY; - var slope = Math.abs(lenY / lenX); - var ratio; - - if (slope < bb.height / bb.width) { - ratio = bb.width / 2 / Math.abs(lenX); - } else { - ratio = lenY ? bb.height / 2 / Math.abs(lenY) : 0; - } - - return { - x: midX + lenX * ratio, - y: midY + lenY * ratio - }; - }; - - svgEditor = _this; - svgCanvas = svgEditor.canvas; - getElem = svgCanvas.getElem; - $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; - _context.next = 14; - return importLocale(); - - case 14: - strings = _context.sent; - svgcontent = S.svgcontent, started = false, connections = [], selElems = []; - /** - * - * @param {Float} x - * @param {Float} y - * @param {module:utilities.BBoxObject} bb - * @param {Float} offset - * @returns {module:math.XYObject} - */ - - // Do once - (function () { - var gse = svgCanvas.groupSelectedElements; - - svgCanvas.groupSelectedElements = function () { - svgCanvas.removeFromSelection($(connSel).toArray()); - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return gse.apply(this, args); - }; - - var mse = svgCanvas.moveSelectedElements; - - svgCanvas.moveSelectedElements = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var cmd = mse.apply(this, args); - updateConnectors(); - return cmd; - }; - - seNs = svgCanvas.getEditorNS(); - })(); - /** - * Do on reset. - * @returns {void} - */ - - - // $(svgroot).parent().mousemove(function (e) { - // // if (started - // // || svgCanvas.getMode() !== 'connector' - // // || e.target.parentNode.parentNode !== svgcontent) return; - // - // console.log('y') - // // if (e.target.parentNode.parentNode === svgcontent) { - // // - // // } - // }); - buttons = [{ - id: 'mode_connect', - type: 'mode', - icon: svgEditor.curConfig.imgPath + 'cut.png', - includeWith: { - button: '#tool_line', - isDefault: false, - position: 1 - }, - events: { - click: function click() { - svgCanvas.setMode('connector'); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.imgPath + 'conn.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - - /* async */ - addLangData: function addLangData(_ref) { - var lang = _ref.lang; - // , importLocale: importLoc - return { - data: strings.langList - }; - }, - mouseDown: function mouseDown(opts) { - var e = opts.event; - startX = opts.start_x; - startY = opts.start_y; - var mode = svgCanvas.getMode(); - var initStroke = svgEditor.curConfig.initStroke; - - if (mode === 'connector') { - if (started) { - return undefined; - } - - var mouseTarget = e.target; - var parents = $(mouseTarget).parents(); - - if ($.inArray(svgcontent, parents) !== -1) { - // Connectable element - // If child of foreignObject, use parent - var fo = $(mouseTarget).closest('foreignObject'); - startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element - - var bb = svgCanvas.getStrokedBBox([startElem]); - var x = bb.x + bb.width / 2; - var y = bb.y + bb.height / 2; - started = true; - curLine = addElem({ - element: 'polyline', - attr: { - id: svgCanvas.getNextId(), - points: x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY, - stroke: '#' + initStroke.color, - 'stroke-width': !startElem.stroke_width || startElem.stroke_width === 0 ? initStroke.width : startElem.stroke_width, - fill: 'none', - opacity: initStroke.opacity, - style: 'pointer-events:none' - } - }); - elData(curLine, 'start_bb', bb); - } - - return { - started: true - }; - } - - if (mode === 'select') { - findConnectors(); - } - - return undefined; - }, - mouseMove: function mouseMove(opts) { - var zoom = svgCanvas.getZoom(); // const e = opts.event; - - var x = opts.mouse_x / zoom; - var y = opts.mouse_y / zoom; - var diffX = x - startX, - diffY = y - startY; - var mode = svgCanvas.getMode(); - - if (mode === 'connector' && started) { - // const sw = curLine.getAttribute('stroke-width') * 3; - // Set start point (adjusts based on bb) - var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine)); - startX = pt.x; - startY = pt.y; - setPoint(curLine, 0, pt.x, pt.y, true); // Set end point - - setPoint(curLine, 'end', x, y, true); - } else if (mode === 'select') { - var slen = selElems.length; - - while (slen--) { - var elem = selElems[slen]; // Look for selected connector elements - - if (elem && elData(elem, 'c_start')) { - // Remove the "translate" transform given to move - svgCanvas.removeFromSelection([elem]); - svgCanvas.getTransformList(elem).clear(); - } - } - - if (connections.length) { - updateLine(diffX, diffY); - } - } - }, - mouseUp: function mouseUp(opts) { - // const zoom = svgCanvas.getZoom(); - var e = opts.event; // , x = opts.mouse_x / zoom, - // , y = opts.mouse_y / zoom, - - var mouseTarget = e.target; - - if (svgCanvas.getMode() !== 'connector') { - return undefined; - } - - var fo = $(mouseTarget).closest('foreignObject'); - - if (fo.length) { - mouseTarget = fo[0]; - } - - var parents = $(mouseTarget).parents(); - - if (mouseTarget === startElem) { - // Start line through click - started = true; - return { - keep: true, - element: null, - started: started - }; - } - - if ($.inArray(svgcontent, parents) === -1) { - // Not a valid target element, so remove line - $(curLine).remove(); - started = false; - return { - keep: false, - element: null, - started: started - }; - } // Valid end element - - - endElem = mouseTarget; - var startId = startElem.id, - endId = endElem.id; - var connStr = startId + ' ' + endId; - var altStr = endId + ' ' + startId; // Don't create connector if one already exists - - var dupe = $(svgcontent).find(connSel).filter(function () { - var conn = this.getAttributeNS(seNs, 'connector'); - - if (conn === connStr || conn === altStr) { - return true; - } - - return false; - }); - - if (dupe.length) { - $(curLine).remove(); - return { - keep: false, - element: null, - started: false - }; - } - - var bb = svgCanvas.getStrokedBBox([endElem]); - var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine)); - setPoint(curLine, 'end', pt.x, pt.y, true); - $(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb); - seNs = svgCanvas.getEditorNS(true); - curLine.setAttributeNS(seNs, 'se:connector', connStr); - curLine.setAttribute('class', connSel.substr(1)); - curLine.setAttribute('opacity', 1); - svgCanvas.addToSelection([curLine]); - svgCanvas.moveToBottomSelectedElement(); - selManager.requestSelector(curLine).showGrips(false); - started = false; - return { - keep: true, - element: curLine, - started: started - }; - }, - selectedChanged: function selectedChanged(opts) { - // TODO: Find better way to skip operations if no connectors are in use - if (!$(svgcontent).find(connSel).length) { - return; - } - - if (svgCanvas.getMode() === 'connector') { - svgCanvas.setMode('select'); - } // Use this to update the current selected elements - - - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elData(elem, 'c_start')) { - selManager.requestSelector(elem).showGrips(false); - - if (opts.selectedElement && !opts.multiselected) { - // TODO: Set up context tools and hide most regular line tools - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - - updateConnectors(); - }, - elementChanged: function elementChanged(opts) { - var elem = opts.elems[0]; - if (!elem) return; - - if (elem.tagName === 'svg' && elem.id === 'svgcontent') { - // Update svgcontent (can change on import) - svgcontent = elem; - init(); - } // Has marker, so change offset - - - if (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end')) { - var start = elem.getAttribute('marker-start'); - var mid = elem.getAttribute('marker-mid'); - var end = elem.getAttribute('marker-end'); - curLine = elem; - $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end)); - - if (elem.tagName === 'line' && mid) { - // Convert to polyline to accept mid-arrow - var x1 = Number(elem.getAttribute('x1')); - var x2 = Number(elem.getAttribute('x2')); - var y1 = Number(elem.getAttribute('y1')); - var y2 = Number(elem.getAttribute('y2')); - var _elem = elem, - id = _elem.id; - var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; - var pline = addElem({ - element: 'polyline', - attr: { - points: x1 + ',' + y1 + midPt + x2 + ',' + y2, - stroke: elem.getAttribute('stroke'), - 'stroke-width': elem.getAttribute('stroke-width'), - 'marker-mid': mid, - fill: 'none', - opacity: elem.getAttribute('opacity') || 1 - } - }); - $(elem).after(pline).remove(); - svgCanvas.clearSelection(); - pline.id = id; - svgCanvas.addToSelection([pline]); - elem = pline; - } - } // Update line if it's a connector - - - if (elem.getAttribute('class') === connSel.substr(1)) { - var _start = getElem(elData(elem, 'c_start')); - - updateConnectors([_start]); - } else { - updateConnectors(); - } - }, - IDsUpdated: function IDsUpdated(input) { - var remove = []; - input.elems.forEach(function (elem) { - if ('se:connector' in elem.attr) { - elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) { - return input.changes[oldID]; - }).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but - // if one end is missing, it would be 'svg_21' and therefore fail this test - - if (!/. ./.test(elem.attr['se:connector'])) { - remove.push(elem.attr.id); - } - } - }); - return { - remove: remove - }; - }, - toolButtonStateUpdate: function toolButtonStateUpdate(opts) { - if (opts.nostroke) { - if ($('#mode_connect').hasClass('tool_button_current')) { - svgEditor.clickSelect(); - } - } - - $('#mode_connect').toggleClass('disabled', opts.nostroke); - } - }); - - case 19: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } -}; - -export default extConnector; -//# sourceMappingURL=ext-connector.js.map diff --git a/dist/editor/extensions/ext-connector.js.map b/dist/editor/extensions/ext-connector.js.map deleted file mode 100644 index 575f0436..00000000 --- a/dist/editor/extensions/ext-connector.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-connector.js","sources":["../../../src/editor/extensions/ext-connector.js"],"sourcesContent":["/**\n * @file ext-connector.js\n *\n * @license MIT\n *\n * @copyright 2010 Alexis Deveria\n *\n */\n\nexport default {\n name: 'connector',\n async init (S) {\n const svgEditor = this;\n const svgCanvas = svgEditor.canvas;\n const {getElem} = svgCanvas;\n const {$, svgroot, importLocale} = S,\n addElem = svgCanvas.addSVGElementFromJson,\n selManager = S.selectorManager,\n connSel = '.se_connector',\n // connect_str = '-SE_CONNECT-',\n elData = $.data;\n const strings = await importLocale();\n\n let startX,\n startY,\n curLine,\n startElem,\n endElem,\n seNs,\n {svgcontent} = S,\n started = false,\n connections = [],\n selElems = [];\n\n /**\n *\n * @param {Float} x\n * @param {Float} y\n * @param {module:utilities.BBoxObject} bb\n * @param {Float} offset\n * @returns {module:math.XYObject}\n */\n function getBBintersect (x, y, bb, offset) {\n if (offset) {\n offset -= 0;\n bb = $.extend({}, bb);\n bb.width += offset;\n bb.height += offset;\n bb.x -= offset / 2;\n bb.y -= offset / 2;\n }\n\n const midX = bb.x + bb.width / 2;\n const midY = bb.y + bb.height / 2;\n const lenX = x - midX;\n const lenY = y - midY;\n\n const slope = Math.abs(lenY / lenX);\n\n let ratio;\n if (slope < bb.height / bb.width) {\n ratio = (bb.width / 2) / Math.abs(lenX);\n } else {\n ratio = lenY\n ? (bb.height / 2) / Math.abs(lenY)\n : 0;\n }\n\n return {\n x: midX + lenX * ratio,\n y: midY + lenY * ratio\n };\n }\n\n /**\n * @param {\"start\"|\"end\"} side\n * @param {Element} line\n * @returns {Float}\n */\n function getOffset (side, line) {\n const giveOffset = line.getAttribute('marker-' + side);\n // const giveOffset = $(line).data(side+'_off');\n\n // TODO: Make this number (5) be based on marker width/height\n const size = line.getAttribute('stroke-width') * 5;\n return giveOffset ? size : 0;\n }\n\n /**\n * @param {boolean} on\n * @returns {void}\n */\n function showPanel (on) {\n let connRules = $('#connector_rules');\n if (!connRules.length) {\n connRules = $('').appendTo('head');\n }\n connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }');\n $('#connector_panel').toggle(on);\n }\n\n /**\n * @param {Element} elem\n * @param {Integer|\"end\"} pos\n * @param {Float} x\n * @param {Float} y\n * @param {boolean} [setMid]\n * @returns {void}\n */\n function setPoint (elem, pos, x, y, setMid) {\n const pts = elem.points;\n const pt = svgroot.createSVGPoint();\n pt.x = x;\n pt.y = y;\n if (pos === 'end') { pos = pts.numberOfItems - 1; }\n // TODO: Test for this on init, then use alt only if needed\n try {\n pts.replaceItem(pt, pos);\n } catch (err) {\n // Should only occur in FF which formats points attr as \"n,n n,n\", so just split\n const ptArr = elem.getAttribute('points').split(' ');\n for (let i = 0; i < ptArr.length; i++) {\n if (i === pos) {\n ptArr[i] = x + ',' + y;\n }\n }\n elem.setAttribute('points', ptArr.join(' '));\n }\n\n if (setMid) {\n // Add center point\n const ptStart = pts.getItem(0);\n const ptEnd = pts.getItem(pts.numberOfItems - 1);\n setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2);\n }\n }\n\n /**\n * @param {Float} diffX\n * @param {Float} diffY\n * @returns {void}\n */\n function updateLine (diffX, diffY) {\n // Update line with element\n let i = connections.length;\n while (i--) {\n const conn = connections[i];\n const line = conn.connector;\n // const {elem} = conn;\n\n const pre = conn.is_start ? 'start' : 'end';\n // const sw = line.getAttribute('stroke-width') * 5;\n\n // Update bbox for this element\n const bb = elData(line, pre + '_bb');\n bb.x = conn.start_x + diffX;\n bb.y = conn.start_y + diffY;\n elData(line, pre + '_bb', bb);\n\n const altPre = conn.is_start ? 'end' : 'start';\n\n // Get center pt of connected element\n const bb2 = elData(line, altPre + '_bb');\n const srcX = bb2.x + bb2.width / 2;\n const srcY = bb2.y + bb2.height / 2;\n\n // Set point of element being moved\n const pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0\n setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);\n\n // Set point of connected element\n const pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line));\n setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);\n }\n }\n\n /**\n *\n * @param {Element[]} [elems=selElems] Array of elements\n * @returns {void}\n */\n function findConnectors (elems = selElems) {\n const connectors = $(svgcontent).find(connSel);\n connections = [];\n\n // Loop through connectors to see if one is connected to the element\n connectors.each(function () {\n let addThis;\n /**\n *\n * @returns {void}\n */\n function add () {\n if (elems.includes(this)) {\n // Pretend this element is selected\n addThis = true;\n }\n }\n\n // Grab the ends\n const parts = [];\n ['start', 'end'].forEach(function (pos, i) {\n const key = 'c_' + pos;\n let part = elData(this, key);\n if (part === null || part === undefined) { // Does this ever return nullish values?\n part = document.getElementById(\n this.attributes['se:connector'].value.split(' ')[i]\n );\n elData(this, 'c_' + pos, part.id);\n elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part]));\n } else part = document.getElementById(part);\n parts.push(part);\n }, this);\n\n for (let i = 0; i < 2; i++) {\n const cElem = parts[i];\n\n addThis = false;\n // The connected element might be part of a selected group\n $(cElem).parents().each(add);\n\n if (!cElem || !cElem.parentNode) {\n $(this).remove();\n continue;\n }\n if (elems.includes(cElem) || addThis) {\n const bb = svgCanvas.getStrokedBBox([cElem]);\n connections.push({\n elem: cElem,\n connector: this,\n is_start: (i === 0),\n start_x: bb.x,\n start_y: bb.y\n });\n }\n }\n });\n }\n\n /**\n * @param {Element[]} [elems=selElems]\n * @returns {void}\n */\n function updateConnectors (elems) {\n // Updates connector lines based on selected elements\n // Is not used on mousemove, as it runs getStrokedBBox every time,\n // which isn't necessary there.\n findConnectors(elems);\n if (connections.length) {\n // Update line with element\n let i = connections.length;\n while (i--) {\n const conn = connections[i];\n const line = conn.connector;\n const {elem} = conn;\n\n // const sw = line.getAttribute('stroke-width') * 5;\n const pre = conn.is_start ? 'start' : 'end';\n\n // Update bbox for this element\n const bb = svgCanvas.getStrokedBBox([elem]);\n bb.x = conn.start_x;\n bb.y = conn.start_y;\n elData(line, pre + '_bb', bb);\n /* const addOffset = */ elData(line, pre + '_off');\n\n const altPre = conn.is_start ? 'end' : 'start';\n\n // Get center pt of connected element\n const bb2 = elData(line, altPre + '_bb');\n const srcX = bb2.x + bb2.width / 2;\n const srcY = bb2.y + bb2.height / 2;\n\n // Set point of element being moved\n let pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line));\n setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);\n\n // Set point of connected element\n const pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line));\n setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);\n\n // Update points attribute manually for webkit\n if (navigator.userAgent.includes('AppleWebKit')) {\n const pts = line.points;\n const len = pts.numberOfItems;\n const ptArr = [];\n for (let j = 0; j < len; j++) {\n pt = pts.getItem(j);\n ptArr[j] = pt.x + ',' + pt.y;\n }\n line.setAttribute('points', ptArr.join(' '));\n }\n }\n }\n }\n\n // Do once\n (function () {\n const gse = svgCanvas.groupSelectedElements;\n\n svgCanvas.groupSelectedElements = function (...args) {\n svgCanvas.removeFromSelection($(connSel).toArray());\n return gse.apply(this, args);\n };\n\n const mse = svgCanvas.moveSelectedElements;\n\n svgCanvas.moveSelectedElements = function (...args) {\n const cmd = mse.apply(this, args);\n updateConnectors();\n return cmd;\n };\n\n seNs = svgCanvas.getEditorNS();\n }());\n\n /**\n * Do on reset.\n * @returns {void}\n */\n function init () {\n // Make sure all connectors have data set\n $(svgcontent).find('*').each(function () {\n const conn = this.getAttributeNS(seNs, 'connector');\n if (conn) {\n this.setAttribute('class', connSel.substr(1));\n const connData = conn.split(' ');\n const sbb = svgCanvas.getStrokedBBox([getElem(connData[0])]);\n const ebb = svgCanvas.getStrokedBBox([getElem(connData[1])]);\n $(this).data('c_start', connData[0])\n .data('c_end', connData[1])\n .data('start_bb', sbb)\n .data('end_bb', ebb);\n svgCanvas.getEditorNS(true);\n }\n });\n // updateConnectors();\n }\n\n // $(svgroot).parent().mousemove(function (e) {\n // // if (started\n // // || svgCanvas.getMode() !== 'connector'\n // // || e.target.parentNode.parentNode !== svgcontent) return;\n //\n // console.log('y')\n // // if (e.target.parentNode.parentNode === svgcontent) {\n // //\n // // }\n // });\n\n const buttons = [{\n id: 'mode_connect',\n type: 'mode',\n icon: svgEditor.curConfig.imgPath + 'cut.png',\n includeWith: {\n button: '#tool_line',\n isDefault: false,\n position: 1\n },\n events: {\n click () {\n svgCanvas.setMode('connector');\n }\n }\n }];\n\n return {\n name: strings.name,\n svgicons: svgEditor.curConfig.imgPath + 'conn.svg',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n /* async */ addLangData ({lang}) { // , importLocale: importLoc\n return {\n data: strings.langList\n };\n },\n mouseDown (opts) {\n const e = opts.event;\n startX = opts.start_x;\n startY = opts.start_y;\n const mode = svgCanvas.getMode();\n const {curConfig: {initStroke}} = svgEditor;\n\n if (mode === 'connector') {\n if (started) { return undefined; }\n\n const mouseTarget = e.target;\n\n const parents = $(mouseTarget).parents();\n\n if ($.inArray(svgcontent, parents) !== -1) {\n // Connectable element\n\n // If child of foreignObject, use parent\n const fo = $(mouseTarget).closest('foreignObject');\n startElem = fo.length ? fo[0] : mouseTarget;\n\n // Get center of source element\n const bb = svgCanvas.getStrokedBBox([startElem]);\n const x = bb.x + bb.width / 2;\n const y = bb.y + bb.height / 2;\n\n started = true;\n curLine = addElem({\n element: 'polyline',\n attr: {\n id: svgCanvas.getNextId(),\n points: (x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY),\n stroke: '#' + initStroke.color,\n 'stroke-width': (!startElem.stroke_width || startElem.stroke_width === 0)\n ? initStroke.width\n : startElem.stroke_width,\n fill: 'none',\n opacity: initStroke.opacity,\n style: 'pointer-events:none'\n }\n });\n elData(curLine, 'start_bb', bb);\n }\n return {\n started: true\n };\n }\n if (mode === 'select') {\n findConnectors();\n }\n return undefined;\n },\n mouseMove (opts) {\n const zoom = svgCanvas.getZoom();\n // const e = opts.event;\n const x = opts.mouse_x / zoom;\n const y = opts.mouse_y / zoom;\n\n const diffX = x - startX,\n diffY = y - startY;\n\n const mode = svgCanvas.getMode();\n\n if (mode === 'connector' && started) {\n // const sw = curLine.getAttribute('stroke-width') * 3;\n // Set start point (adjusts based on bb)\n const pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine));\n startX = pt.x;\n startY = pt.y;\n\n setPoint(curLine, 0, pt.x, pt.y, true);\n\n // Set end point\n setPoint(curLine, 'end', x, y, true);\n } else if (mode === 'select') {\n let slen = selElems.length;\n while (slen--) {\n const elem = selElems[slen];\n // Look for selected connector elements\n if (elem && elData(elem, 'c_start')) {\n // Remove the \"translate\" transform given to move\n svgCanvas.removeFromSelection([elem]);\n svgCanvas.getTransformList(elem).clear();\n }\n }\n if (connections.length) {\n updateLine(diffX, diffY);\n }\n }\n },\n mouseUp (opts) {\n // const zoom = svgCanvas.getZoom();\n const e = opts.event;\n // , x = opts.mouse_x / zoom,\n // , y = opts.mouse_y / zoom,\n let mouseTarget = e.target;\n\n if (svgCanvas.getMode() !== 'connector') {\n return undefined;\n }\n const fo = $(mouseTarget).closest('foreignObject');\n if (fo.length) { mouseTarget = fo[0]; }\n\n const parents = $(mouseTarget).parents();\n\n if (mouseTarget === startElem) {\n // Start line through click\n started = true;\n return {\n keep: true,\n element: null,\n started\n };\n }\n if ($.inArray(svgcontent, parents) === -1) {\n // Not a valid target element, so remove line\n $(curLine).remove();\n started = false;\n return {\n keep: false,\n element: null,\n started\n };\n }\n // Valid end element\n endElem = mouseTarget;\n\n const startId = startElem.id, endId = endElem.id;\n const connStr = startId + ' ' + endId;\n const altStr = endId + ' ' + startId;\n // Don't create connector if one already exists\n const dupe = $(svgcontent).find(connSel).filter(function () {\n const conn = this.getAttributeNS(seNs, 'connector');\n if (conn === connStr || conn === altStr) { return true; }\n return false;\n });\n if (dupe.length) {\n $(curLine).remove();\n return {\n keep: false,\n element: null,\n started: false\n };\n }\n\n const bb = svgCanvas.getStrokedBBox([endElem]);\n\n const pt = getBBintersect(startX, startY, bb, getOffset('start', curLine));\n setPoint(curLine, 'end', pt.x, pt.y, true);\n $(curLine)\n .data('c_start', startId)\n .data('c_end', endId)\n .data('end_bb', bb);\n seNs = svgCanvas.getEditorNS(true);\n curLine.setAttributeNS(seNs, 'se:connector', connStr);\n curLine.setAttribute('class', connSel.substr(1));\n curLine.setAttribute('opacity', 1);\n svgCanvas.addToSelection([curLine]);\n svgCanvas.moveToBottomSelectedElement();\n selManager.requestSelector(curLine).showGrips(false);\n started = false;\n return {\n keep: true,\n element: curLine,\n started\n };\n },\n selectedChanged (opts) {\n // TODO: Find better way to skip operations if no connectors are in use\n if (!$(svgcontent).find(connSel).length) { return; }\n\n if (svgCanvas.getMode() === 'connector') {\n svgCanvas.setMode('select');\n }\n\n // Use this to update the current selected elements\n selElems = opts.elems;\n\n let i = selElems.length;\n while (i--) {\n const elem = selElems[i];\n if (elem && elData(elem, 'c_start')) {\n selManager.requestSelector(elem).showGrips(false);\n if (opts.selectedElement && !opts.multiselected) {\n // TODO: Set up context tools and hide most regular line tools\n showPanel(true);\n } else {\n showPanel(false);\n }\n } else {\n showPanel(false);\n }\n }\n updateConnectors();\n },\n elementChanged (opts) {\n let elem = opts.elems[0];\n if (!elem) return;\n if (elem.tagName === 'svg' && elem.id === 'svgcontent') {\n // Update svgcontent (can change on import)\n svgcontent = elem;\n init();\n }\n\n // Has marker, so change offset\n if (\n elem.getAttribute('marker-start') ||\n elem.getAttribute('marker-mid') ||\n elem.getAttribute('marker-end')\n ) {\n const start = elem.getAttribute('marker-start');\n const mid = elem.getAttribute('marker-mid');\n const end = elem.getAttribute('marker-end');\n curLine = elem;\n $(elem)\n .data('start_off', Boolean(start))\n .data('end_off', Boolean(end));\n\n if (elem.tagName === 'line' && mid) {\n // Convert to polyline to accept mid-arrow\n\n const x1 = Number(elem.getAttribute('x1'));\n const x2 = Number(elem.getAttribute('x2'));\n const y1 = Number(elem.getAttribute('y1'));\n const y2 = Number(elem.getAttribute('y2'));\n const {id} = elem;\n\n const midPt = (' ' + ((x1 + x2) / 2) + ',' + ((y1 + y2) / 2) + ' ');\n const pline = addElem({\n element: 'polyline',\n attr: {\n points: (x1 + ',' + y1 + midPt + x2 + ',' + y2),\n stroke: elem.getAttribute('stroke'),\n 'stroke-width': elem.getAttribute('stroke-width'),\n 'marker-mid': mid,\n fill: 'none',\n opacity: elem.getAttribute('opacity') || 1\n }\n });\n $(elem).after(pline).remove();\n svgCanvas.clearSelection();\n pline.id = id;\n svgCanvas.addToSelection([pline]);\n elem = pline;\n }\n }\n // Update line if it's a connector\n if (elem.getAttribute('class') === connSel.substr(1)) {\n const start = getElem(elData(elem, 'c_start'));\n updateConnectors([start]);\n } else {\n updateConnectors();\n }\n },\n IDsUpdated (input) {\n const remove = [];\n input.elems.forEach(function (elem) {\n if ('se:connector' in elem.attr) {\n elem.attr['se:connector'] = elem.attr['se:connector'].split(' ')\n .map(function (oldID) { return input.changes[oldID]; }).join(' ');\n\n // Check validity - the field would be something like 'svg_21 svg_22', but\n // if one end is missing, it would be 'svg_21' and therefore fail this test\n if (!(/. ./).test(elem.attr['se:connector'])) {\n remove.push(elem.attr.id);\n }\n }\n });\n return {remove};\n },\n toolButtonStateUpdate (opts) {\n if (opts.nostroke) {\n if ($('#mode_connect').hasClass('tool_button_current')) {\n svgEditor.clickSelect();\n }\n }\n $('#mode_connect')\n .toggleClass('disabled', opts.nostroke);\n }\n };\n }\n};\n"],"names":["name","init","S","getBBintersect","getOffset","showPanel","setPoint","updateLine","findConnectors","updateConnectors","$","svgcontent","find","each","conn","getAttributeNS","seNs","setAttribute","connSel","substr","connData","split","sbb","svgCanvas","getStrokedBBox","getElem","ebb","data","getEditorNS","elems","connections","length","i","line","connector","elem","pre","is_start","bb","x","start_x","y","start_y","elData","altPre","bb2","srcX","width","srcY","height","pt","pt2","navigator","userAgent","includes","pts","points","len","numberOfItems","ptArr","j","getItem","join","selElems","connectors","addThis","add","parts","forEach","pos","key","part","undefined","document","getElementById","attributes","value","id","push","cElem","parents","parentNode","remove","diffX","diffY","setMid","svgroot","createSVGPoint","replaceItem","err","getAttribute","ptStart","ptEnd","on","connRules","appendTo","text","toggle","side","giveOffset","size","offset","extend","midX","midY","lenX","lenY","slope","Math","abs","ratio","svgEditor","canvas","importLocale","addElem","addSVGElementFromJson","selManager","selectorManager","strings","started","gse","groupSelectedElements","removeFromSelection","toArray","args","apply","mse","moveSelectedElements","cmd","buttons","type","icon","curConfig","imgPath","includeWith","button","isDefault","position","events","click","setMode","svgicons","map","Object","assign","addLangData","lang","langList","mouseDown","opts","e","event","startX","startY","mode","getMode","initStroke","mouseTarget","target","inArray","fo","closest","startElem","curLine","element","attr","getNextId","stroke","color","stroke_width","fill","opacity","style","mouseMove","zoom","getZoom","mouse_x","mouse_y","slen","getTransformList","clear","mouseUp","keep","endElem","startId","endId","connStr","altStr","dupe","filter","setAttributeNS","addToSelection","moveToBottomSelectedElement","requestSelector","showGrips","selectedChanged","selectedElement","multiselected","elementChanged","tagName","start","mid","end","Boolean","x1","Number","x2","y1","y2","midPt","pline","after","clearSelection","IDsUpdated","input","oldID","changes","test","toolButtonStateUpdate","nostroke","hasClass","clickSelect","toggleClass"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;AASA,mBAAe;AACbA,EAAAA,IAAI,EAAE,WADO;AAEPC,EAAAA,IAFO,gBAEDC,CAFC,EAEE;AAAA;;AAAA;AAAA,iNA+BJC,cA/BI,EAoEJC,SApEI,EAiFJC,SAjFI,EAkGJC,QAlGI,EAmIJC,UAnII,EA0KJC,cA1KI,EAwOJC,gBAxOI,EAqTJR,IArTI;AAAA;AAAA;AAAA;AAAA;AAqTJA,cAAAA,IArTI,oBAqTI;AACf;AACAS,gBAAAA,CAAC,CAACC,UAAD,CAAD,CAAcC,IAAd,CAAmB,GAAnB,EAAwBC,IAAxB,CAA6B,YAAY;AACvC,sBAAMC,IAAI,GAAG,KAAKC,cAAL,CAAoBC,IAApB,EAA0B,WAA1B,CAAb;;AACA,sBAAIF,IAAJ,EAAU;AACR,yBAAKG,YAAL,CAAkB,OAAlB,EAA2BC,OAAO,CAACC,MAAR,CAAe,CAAf,CAA3B;AACA,wBAAMC,QAAQ,GAAGN,IAAI,CAACO,KAAL,CAAW,GAAX,CAAjB;AACA,wBAAMC,GAAG,GAAGC,SAAS,CAACC,cAAV,CAAyB,CAACC,OAAO,CAACL,QAAQ,CAAC,CAAD,CAAT,CAAR,CAAzB,CAAZ;AACA,wBAAMM,GAAG,GAAGH,SAAS,CAACC,cAAV,CAAyB,CAACC,OAAO,CAACL,QAAQ,CAAC,CAAD,CAAT,CAAR,CAAzB,CAAZ;AACAV,oBAAAA,CAAC,CAAC,IAAD,CAAD,CAAQiB,IAAR,CAAa,SAAb,EAAwBP,QAAQ,CAAC,CAAD,CAAhC,EACGO,IADH,CACQ,OADR,EACiBP,QAAQ,CAAC,CAAD,CADzB,EAEGO,IAFH,CAEQ,UAFR,EAEoBL,GAFpB,EAGGK,IAHH,CAGQ,QAHR,EAGkBD,GAHlB;AAIAH,oBAAAA,SAAS,CAACK,WAAV,CAAsB,IAAtB;AACD;AACF,iBAbD,EAFe;AAiBhB,eAtUY;;AAwOJnB,cAAAA,gBAxOI,8BAwOcoB,KAxOd,EAwOqB;AAChC;AACA;AACA;AACArB,gBAAAA,cAAc,CAACqB,KAAD,CAAd;;AACA,oBAAIC,WAAW,CAACC,MAAhB,EAAwB;AACtB;AACA,sBAAIC,CAAC,GAAGF,WAAW,CAACC,MAApB;;AACA,yBAAOC,CAAC,EAAR,EAAY;AACV,wBAAMlB,IAAI,GAAGgB,WAAW,CAACE,CAAD,CAAxB;AACA,wBAAMC,IAAI,GAAGnB,IAAI,CAACoB,SAAlB;AAFU,wBAGHC,IAHG,GAGKrB,IAHL,CAGHqB,IAHG;;AAMV,wBAAMC,GAAG,GAAGtB,IAAI,CAACuB,QAAL,GAAgB,OAAhB,GAA0B,KAAtC,CANU;;AASV,wBAAMC,EAAE,GAAGf,SAAS,CAACC,cAAV,CAAyB,CAACW,IAAD,CAAzB,CAAX;AACAG,oBAAAA,EAAE,CAACC,CAAH,GAAOzB,IAAI,CAAC0B,OAAZ;AACAF,oBAAAA,EAAE,CAACG,CAAH,GAAO3B,IAAI,CAAC4B,OAAZ;AACAC,oBAAAA,MAAM,CAACV,IAAD,EAAOG,GAAG,GAAG,KAAb,EAAoBE,EAApB,CAAN;AACA;;AAAwBK,oBAAAA,MAAM,CAACV,IAAD,EAAOG,GAAG,GAAG,MAAb,CAAN;AAExB,wBAAMQ,MAAM,GAAG9B,IAAI,CAACuB,QAAL,GAAgB,KAAhB,GAAwB,OAAvC,CAfU;;AAkBV,wBAAMQ,GAAG,GAAGF,MAAM,CAACV,IAAD,EAAOW,MAAM,GAAG,KAAhB,CAAlB;AACA,wBAAME,IAAI,GAAGD,GAAG,CAACN,CAAJ,GAAQM,GAAG,CAACE,KAAJ,GAAY,CAAjC;AACA,wBAAMC,IAAI,GAAGH,GAAG,CAACJ,CAAJ,GAAQI,GAAG,CAACI,MAAJ,GAAa,CAAlC,CApBU;;AAuBV,wBAAIC,EAAE,GAAG/C,cAAc,CAAC2C,IAAD,EAAOE,IAAP,EAAaV,EAAb,EAAiBlC,SAAS,CAACgC,GAAD,EAAMH,IAAN,CAA1B,CAAvB;AACA3B,oBAAAA,QAAQ,CAAC2B,IAAD,EAAOnB,IAAI,CAACuB,QAAL,GAAgB,CAAhB,GAAoB,KAA3B,EAAkCa,EAAE,CAACX,CAArC,EAAwCW,EAAE,CAACT,CAA3C,EAA8C,IAA9C,CAAR,CAxBU;;AA2BV,wBAAMU,GAAG,GAAGhD,cAAc,CAAC+C,EAAE,CAACX,CAAJ,EAAOW,EAAE,CAACT,CAAV,EAAaE,MAAM,CAACV,IAAD,EAAOW,MAAM,GAAG,KAAhB,CAAnB,EAA2CxC,SAAS,CAACwC,MAAD,EAASX,IAAT,CAApD,CAA1B;AACA3B,oBAAAA,QAAQ,CAAC2B,IAAD,EAAOnB,IAAI,CAACuB,QAAL,GAAgB,KAAhB,GAAwB,CAA/B,EAAkCc,GAAG,CAACZ,CAAtC,EAAyCY,GAAG,CAACV,CAA7C,EAAgD,IAAhD,CAAR,CA5BU;;AA+BV,wBAAIW,SAAS,CAACC,SAAV,CAAoBC,QAApB,CAA6B,aAA7B,CAAJ,EAAiD;AAC/C,0BAAMC,GAAG,GAAGtB,IAAI,CAACuB,MAAjB;AACA,0BAAMC,GAAG,GAAGF,GAAG,CAACG,aAAhB;AACA,0BAAMC,KAAK,GAAG,EAAd;;AACA,2BAAK,IAAIC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGH,GAApB,EAAyBG,CAAC,EAA1B,EAA8B;AAC5BV,wBAAAA,EAAE,GAAGK,GAAG,CAACM,OAAJ,CAAYD,CAAZ,CAAL;AACAD,wBAAAA,KAAK,CAACC,CAAD,CAAL,GAAWV,EAAE,CAACX,CAAH,GAAO,GAAP,GAAaW,EAAE,CAACT,CAA3B;AACD;;AACDR,sBAAAA,IAAI,CAAChB,YAAL,CAAkB,QAAlB,EAA4B0C,KAAK,CAACG,IAAN,CAAW,GAAX,CAA5B;AACD;AACF;AACF;AACF,eA3RY;;AA0KJtD,cAAAA,cA1KI,8BA0K8B;AAAA,oBAAlBqB,KAAkB,uEAAVkC,QAAU;AACzC,oBAAMC,UAAU,GAAGtD,CAAC,CAACC,UAAD,CAAD,CAAcC,IAAd,CAAmBM,OAAnB,CAAnB;AACAY,gBAAAA,WAAW,GAAG,EAAd,CAFyC;;AAKzCkC,gBAAAA,UAAU,CAACnD,IAAX,CAAgB,YAAY;AAC1B,sBAAIoD,OAAJ;AACA;;;;;AAIA,2BAASC,GAAT,GAAgB;AACd,wBAAIrC,KAAK,CAACyB,QAAN,CAAe,IAAf,CAAJ,EAA0B;AACxB;AACAW,sBAAAA,OAAO,GAAG,IAAV;AACD;AACF,mBAXyB;;;AAc1B,sBAAME,KAAK,GAAG,EAAd;AACA,mBAAC,OAAD,EAAU,KAAV,EAAiBC,OAAjB,CAAyB,UAAUC,GAAV,EAAerC,CAAf,EAAkB;AACzC,wBAAMsC,GAAG,GAAG,OAAOD,GAAnB;AACA,wBAAIE,IAAI,GAAG5B,MAAM,CAAC,IAAD,EAAO2B,GAAP,CAAjB;;AACA,wBAAIC,IAAI,KAAK,IAAT,IAAiBA,IAAI,KAAKC,SAA9B,EAAyC;AAAE;AACzCD,sBAAAA,IAAI,GAAGE,QAAQ,CAACC,cAAT,CACL,KAAKC,UAAL,CAAgB,cAAhB,EAAgCC,KAAhC,CAAsCvD,KAAtC,CAA4C,GAA5C,EAAiDW,CAAjD,CADK,CAAP;AAGAW,sBAAAA,MAAM,CAAC,IAAD,EAAO,OAAO0B,GAAd,EAAmBE,IAAI,CAACM,EAAxB,CAAN;AACAlC,sBAAAA,MAAM,CAAC,IAAD,EAAO0B,GAAG,GAAG,KAAb,EAAoB9C,SAAS,CAACC,cAAV,CAAyB,CAAC+C,IAAD,CAAzB,CAApB,CAAN;AACD,qBAND,MAMOA,IAAI,GAAGE,QAAQ,CAACC,cAAT,CAAwBH,IAAxB,CAAP;;AACPJ,oBAAAA,KAAK,CAACW,IAAN,CAAWP,IAAX;AACD,mBAXD,EAWG,IAXH;;AAaA,uBAAK,IAAIvC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG,CAApB,EAAuBA,CAAC,EAAxB,EAA4B;AAC1B,wBAAM+C,KAAK,GAAGZ,KAAK,CAACnC,CAAD,CAAnB;AAEAiC,oBAAAA,OAAO,GAAG,KAAV,CAH0B;;AAK1BvD,oBAAAA,CAAC,CAACqE,KAAD,CAAD,CAASC,OAAT,GAAmBnE,IAAnB,CAAwBqD,GAAxB;;AAEA,wBAAI,CAACa,KAAD,IAAU,CAACA,KAAK,CAACE,UAArB,EAAiC;AAC/BvE,sBAAAA,CAAC,CAAC,IAAD,CAAD,CAAQwE,MAAR;AACA;AACD;;AACD,wBAAIrD,KAAK,CAACyB,QAAN,CAAeyB,KAAf,KAAyBd,OAA7B,EAAsC;AACpC,0BAAM3B,EAAE,GAAGf,SAAS,CAACC,cAAV,CAAyB,CAACuD,KAAD,CAAzB,CAAX;AACAjD,sBAAAA,WAAW,CAACgD,IAAZ,CAAiB;AACf3C,wBAAAA,IAAI,EAAE4C,KADS;AAEf7C,wBAAAA,SAAS,EAAE,IAFI;AAGfG,wBAAAA,QAAQ,EAAGL,CAAC,KAAK,CAHF;AAIfQ,wBAAAA,OAAO,EAAEF,EAAE,CAACC,CAJG;AAKfG,wBAAAA,OAAO,EAAEJ,EAAE,CAACG;AALG,uBAAjB;AAOD;AACF;AACF,iBAlDD;AAmDD,eAlOY;;AAmIJlC,cAAAA,UAnII,wBAmIQ4E,KAnIR,EAmIeC,KAnIf,EAmIsB;AACjC;AACA,oBAAIpD,CAAC,GAAGF,WAAW,CAACC,MAApB;;AACA,uBAAOC,CAAC,EAAR,EAAY;AACV,sBAAMlB,IAAI,GAAGgB,WAAW,CAACE,CAAD,CAAxB;AACA,sBAAMC,IAAI,GAAGnB,IAAI,CAACoB,SAAlB,CAFU;;AAKV,sBAAME,GAAG,GAAGtB,IAAI,CAACuB,QAAL,GAAgB,OAAhB,GAA0B,KAAtC,CALU;AAQV;;AACA,sBAAMC,EAAE,GAAGK,MAAM,CAACV,IAAD,EAAOG,GAAG,GAAG,KAAb,CAAjB;AACAE,kBAAAA,EAAE,CAACC,CAAH,GAAOzB,IAAI,CAAC0B,OAAL,GAAe2C,KAAtB;AACA7C,kBAAAA,EAAE,CAACG,CAAH,GAAO3B,IAAI,CAAC4B,OAAL,GAAe0C,KAAtB;AACAzC,kBAAAA,MAAM,CAACV,IAAD,EAAOG,GAAG,GAAG,KAAb,EAAoBE,EAApB,CAAN;AAEA,sBAAMM,MAAM,GAAG9B,IAAI,CAACuB,QAAL,GAAgB,KAAhB,GAAwB,OAAvC,CAdU;;AAiBV,sBAAMQ,GAAG,GAAGF,MAAM,CAACV,IAAD,EAAOW,MAAM,GAAG,KAAhB,CAAlB;AACA,sBAAME,IAAI,GAAGD,GAAG,CAACN,CAAJ,GAAQM,GAAG,CAACE,KAAJ,GAAY,CAAjC;AACA,sBAAMC,IAAI,GAAGH,GAAG,CAACJ,CAAJ,GAAQI,GAAG,CAACI,MAAJ,GAAa,CAAlC,CAnBU;;AAsBV,sBAAMC,EAAE,GAAG/C,cAAc,CAAC2C,IAAD,EAAOE,IAAP,EAAaV,EAAb,EAAiBlC,SAAS,CAACgC,GAAD,EAAMH,IAAN,CAA1B,CAAzB,CAtBU;;AAuBV3B,kBAAAA,QAAQ,CAAC2B,IAAD,EAAOnB,IAAI,CAACuB,QAAL,GAAgB,CAAhB,GAAoB,KAA3B,EAAkCa,EAAE,CAACX,CAArC,EAAwCW,EAAE,CAACT,CAA3C,EAA8C,IAA9C,CAAR,CAvBU;;AA0BV,sBAAMU,GAAG,GAAGhD,cAAc,CAAC+C,EAAE,CAACX,CAAJ,EAAOW,EAAE,CAACT,CAAV,EAAaE,MAAM,CAACV,IAAD,EAAOW,MAAM,GAAG,KAAhB,CAAnB,EAA2CxC,SAAS,CAACwC,MAAD,EAASX,IAAT,CAApD,CAA1B;AACA3B,kBAAAA,QAAQ,CAAC2B,IAAD,EAAOnB,IAAI,CAACuB,QAAL,GAAgB,KAAhB,GAAwB,CAA/B,EAAkCc,GAAG,CAACZ,CAAtC,EAAyCY,GAAG,CAACV,CAA7C,EAAgD,IAAhD,CAAR;AACD;AACF,eAnKY;;AAkGJnC,cAAAA,QAlGI,sBAkGM6B,IAlGN,EAkGYkC,GAlGZ,EAkGiB9B,CAlGjB,EAkGoBE,CAlGpB,EAkGuB4C,MAlGvB,EAkG+B;AAC1C,oBAAM9B,GAAG,GAAGpB,IAAI,CAACqB,MAAjB;AACA,oBAAMN,EAAE,GAAGoC,OAAO,CAACC,cAAR,EAAX;AACArC,gBAAAA,EAAE,CAACX,CAAH,GAAOA,CAAP;AACAW,gBAAAA,EAAE,CAACT,CAAH,GAAOA,CAAP;;AACA,oBAAI4B,GAAG,KAAK,KAAZ,EAAmB;AAAEA,kBAAAA,GAAG,GAAGd,GAAG,CAACG,aAAJ,GAAoB,CAA1B;AAA8B,iBALT;;;AAO1C,oBAAI;AACFH,kBAAAA,GAAG,CAACiC,WAAJ,CAAgBtC,EAAhB,EAAoBmB,GAApB;AACD,iBAFD,CAEE,OAAOoB,GAAP,EAAY;AACZ;AACA,sBAAM9B,KAAK,GAAGxB,IAAI,CAACuD,YAAL,CAAkB,QAAlB,EAA4BrE,KAA5B,CAAkC,GAAlC,CAAd;;AACA,uBAAK,IAAIW,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG2B,KAAK,CAAC5B,MAA1B,EAAkCC,CAAC,EAAnC,EAAuC;AACrC,wBAAIA,CAAC,KAAKqC,GAAV,EAAe;AACbV,sBAAAA,KAAK,CAAC3B,CAAD,CAAL,GAAWO,CAAC,GAAG,GAAJ,GAAUE,CAArB;AACD;AACF;;AACDN,kBAAAA,IAAI,CAAClB,YAAL,CAAkB,QAAlB,EAA4B0C,KAAK,CAACG,IAAN,CAAW,GAAX,CAA5B;AACD;;AAED,oBAAIuB,MAAJ,EAAY;AACV;AACA,sBAAMM,OAAO,GAAGpC,GAAG,CAACM,OAAJ,CAAY,CAAZ,CAAhB;AACA,sBAAM+B,KAAK,GAAGrC,GAAG,CAACM,OAAJ,CAAYN,GAAG,CAACG,aAAJ,GAAoB,CAAhC,CAAd;AACApD,kBAAAA,QAAQ,CAAC6B,IAAD,EAAO,CAAP,EAAU,CAACyD,KAAK,CAACrD,CAAN,GAAUoD,OAAO,CAACpD,CAAnB,IAAwB,CAAlC,EAAqC,CAACqD,KAAK,CAACnD,CAAN,GAAUkD,OAAO,CAAClD,CAAnB,IAAwB,CAA7D,CAAR;AACD;AACF,eA5HY;;AAiFJpC,cAAAA,SAjFI,uBAiFOwF,EAjFP,EAiFW;AACtB,oBAAIC,SAAS,GAAGpF,CAAC,CAAC,kBAAD,CAAjB;;AACA,oBAAI,CAACoF,SAAS,CAAC/D,MAAf,EAAuB;AACrB+D,kBAAAA,SAAS,GAAGpF,CAAC,CAAC,sCAAD,CAAD,CAA0CqF,QAA1C,CAAmD,MAAnD,CAAZ;AACD;;AACDD,gBAAAA,SAAS,CAACE,IAAV,CAAe,CAACH,EAAD,GAAM,EAAN,GAAW,iFAA1B;AACAnF,gBAAAA,CAAC,CAAC,kBAAD,CAAD,CAAsBuF,MAAtB,CAA6BJ,EAA7B;AACD,eAxFY;;AAoEJzF,cAAAA,SApEI,uBAoEO8F,IApEP,EAoEajE,IApEb,EAoEmB;AAC9B,oBAAMkE,UAAU,GAAGlE,IAAI,CAACyD,YAAL,CAAkB,YAAYQ,IAA9B,CAAnB,CAD8B;AAI9B;;AACA,oBAAME,IAAI,GAAGnE,IAAI,CAACyD,YAAL,CAAkB,cAAlB,IAAoC,CAAjD;AACA,uBAAOS,UAAU,GAAGC,IAAH,GAAU,CAA3B;AACD,eA3EY;;AA+BJjG,cAAAA,cA/BI,4BA+BYoC,CA/BZ,EA+BeE,CA/Bf,EA+BkBH,EA/BlB,EA+BsB+D,MA/BtB,EA+B8B;AACzC,oBAAIA,MAAJ,EAAY;AACVA,kBAAAA,MAAM,IAAI,CAAV;AACA/D,kBAAAA,EAAE,GAAG5B,CAAC,CAAC4F,MAAF,CAAS,EAAT,EAAahE,EAAb,CAAL;AACAA,kBAAAA,EAAE,CAACS,KAAH,IAAYsD,MAAZ;AACA/D,kBAAAA,EAAE,CAACW,MAAH,IAAaoD,MAAb;AACA/D,kBAAAA,EAAE,CAACC,CAAH,IAAQ8D,MAAM,GAAG,CAAjB;AACA/D,kBAAAA,EAAE,CAACG,CAAH,IAAQ4D,MAAM,GAAG,CAAjB;AACD;;AAED,oBAAME,IAAI,GAAGjE,EAAE,CAACC,CAAH,GAAOD,EAAE,CAACS,KAAH,GAAW,CAA/B;AACA,oBAAMyD,IAAI,GAAGlE,EAAE,CAACG,CAAH,GAAOH,EAAE,CAACW,MAAH,GAAY,CAAhC;AACA,oBAAMwD,IAAI,GAAGlE,CAAC,GAAGgE,IAAjB;AACA,oBAAMG,IAAI,GAAGjE,CAAC,GAAG+D,IAAjB;AAEA,oBAAMG,KAAK,GAAGC,IAAI,CAACC,GAAL,CAASH,IAAI,GAAGD,IAAhB,CAAd;AAEA,oBAAIK,KAAJ;;AACA,oBAAIH,KAAK,GAAGrE,EAAE,CAACW,MAAH,GAAYX,EAAE,CAACS,KAA3B,EAAkC;AAChC+D,kBAAAA,KAAK,GAAIxE,EAAE,CAACS,KAAH,GAAW,CAAZ,GAAiB6D,IAAI,CAACC,GAAL,CAASJ,IAAT,CAAzB;AACD,iBAFD,MAEO;AACLK,kBAAAA,KAAK,GAAGJ,IAAI,GACPpE,EAAE,CAACW,MAAH,GAAY,CAAb,GAAkB2D,IAAI,CAACC,GAAL,CAASH,IAAT,CADV,GAER,CAFJ;AAGD;;AAED,uBAAO;AACLnE,kBAAAA,CAAC,EAAEgE,IAAI,GAAGE,IAAI,GAAGK,KADZ;AAELrE,kBAAAA,CAAC,EAAE+D,IAAI,GAAGE,IAAI,GAAGI;AAFZ,iBAAP;AAID,eA7DY;;AACPC,cAAAA,SADO,GACK,KADL;AAEPxF,cAAAA,SAFO,GAEKwF,SAAS,CAACC,MAFf;AAGNvF,cAAAA,OAHM,GAGKF,SAHL,CAGNE,OAHM;AAINf,cAAAA,CAJM,GAIsBR,CAJtB,CAINQ,CAJM,EAIH4E,OAJG,GAIsBpF,CAJtB,CAIHoF,OAJG,EAIM2B,YAJN,GAIsB/G,CAJtB,CAIM+G,YAJN,EAKXC,OALW,GAKD3F,SAAS,CAAC4F,qBALT,EAMXC,UANW,GAMElH,CAAC,CAACmH,eANJ,EAOXnG,OAPW,GAOD,eAPC,EASXyB,MATW,GASFjC,CAAC,CAACiB,IATA;AAAA;AAAA,qBAUSsF,YAAY,EAVrB;;AAAA;AAUPK,cAAAA,OAVO;AAkBV3G,cAAAA,UAlBU,GAkBIT,CAlBJ,CAkBVS,UAlBU,EAmBX4G,OAnBW,GAmBD,KAnBC,EAoBXzF,WApBW,GAoBG,EApBH,EAqBXiC,QArBW,GAqBA,EArBA;AAuBb;;;;;;;;;AAsQA;AACC,2BAAY;AACX,oBAAMyD,GAAG,GAAGjG,SAAS,CAACkG,qBAAtB;;AAEAlG,gBAAAA,SAAS,CAACkG,qBAAV,GAAkC,YAAmB;AACnDlG,kBAAAA,SAAS,CAACmG,mBAAV,CAA8BhH,CAAC,CAACQ,OAAD,CAAD,CAAWyG,OAAX,EAA9B;;AADmD,oDAANC,IAAM;AAANA,oBAAAA,IAAM;AAAA;;AAEnD,yBAAOJ,GAAG,CAACK,KAAJ,CAAU,IAAV,EAAgBD,IAAhB,CAAP;AACD,iBAHD;;AAKA,oBAAME,GAAG,GAAGvG,SAAS,CAACwG,oBAAtB;;AAEAxG,gBAAAA,SAAS,CAACwG,oBAAV,GAAiC,YAAmB;AAAA,qDAANH,IAAM;AAANA,oBAAAA,IAAM;AAAA;;AAClD,sBAAMI,GAAG,GAAGF,GAAG,CAACD,KAAJ,CAAU,IAAV,EAAgBD,IAAhB,CAAZ;AACAnH,kBAAAA,gBAAgB;AAChB,yBAAOuH,GAAP;AACD,iBAJD;;AAMAhH,gBAAAA,IAAI,GAAGO,SAAS,CAACK,WAAV,EAAP;AACD,eAjBA,GAAD;AAmBA;;;;;;AAuBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEMqG,cAAAA,OAnVO,GAmVG,CAAC;AACfpD,gBAAAA,EAAE,EAAE,cADW;AAEfqD,gBAAAA,IAAI,EAAE,MAFS;AAGfC,gBAAAA,IAAI,EAAEpB,SAAS,CAACqB,SAAV,CAAoBC,OAApB,GAA8B,SAHrB;AAIfC,gBAAAA,WAAW,EAAE;AACXC,kBAAAA,MAAM,EAAE,YADG;AAEXC,kBAAAA,SAAS,EAAE,KAFA;AAGXC,kBAAAA,QAAQ,EAAE;AAHC,iBAJE;AASfC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPpH,oBAAAA,SAAS,CAACqH,OAAV,CAAkB,WAAlB;AACD;AAHK;AATO,eAAD,CAnVH;AAAA,+CAmWN;AACL5I,gBAAAA,IAAI,EAAEsH,OAAO,CAACtH,IADT;AAEL6I,gBAAAA,QAAQ,EAAE9B,SAAS,CAACqB,SAAV,CAAoBC,OAApB,GAA8B,UAFnC;AAGLJ,gBAAAA,OAAO,EAAEX,OAAO,CAACW,OAAR,CAAgBa,GAAhB,CAAoB,UAACP,MAAD,EAASvG,CAAT,EAAe;AAC1C,yBAAO+G,MAAM,CAACC,MAAP,CAAcf,OAAO,CAACjG,CAAD,CAArB,EAA0BuG,MAA1B,CAAP;AACD,iBAFQ,CAHJ;;AAML;AAAYU,gBAAAA,WANP,6BAM4B;AAAA,sBAAPC,IAAO,QAAPA,IAAO;AAAE;AACjC,yBAAO;AACLvH,oBAAAA,IAAI,EAAE2F,OAAO,CAAC6B;AADT,mBAAP;AAGD,iBAVI;AAWLC,gBAAAA,SAXK,qBAWMC,IAXN,EAWY;AACf,sBAAMC,CAAC,GAAGD,IAAI,CAACE,KAAf;AACAC,kBAAAA,MAAM,GAAGH,IAAI,CAAC7G,OAAd;AACAiH,kBAAAA,MAAM,GAAGJ,IAAI,CAAC3G,OAAd;AACA,sBAAMgH,IAAI,GAAGnI,SAAS,CAACoI,OAAV,EAAb;AAJe,sBAKIC,UALJ,GAKmB7C,SALnB,CAKRqB,SALQ,CAKIwB,UALJ;;AAOf,sBAAIF,IAAI,KAAK,WAAb,EAA0B;AACxB,wBAAInC,OAAJ,EAAa;AAAE,6BAAO/C,SAAP;AAAmB;;AAElC,wBAAMqF,WAAW,GAAGP,CAAC,CAACQ,MAAtB;AAEA,wBAAM9E,OAAO,GAAGtE,CAAC,CAACmJ,WAAD,CAAD,CAAe7E,OAAf,EAAhB;;AAEA,wBAAItE,CAAC,CAACqJ,OAAF,CAAUpJ,UAAV,EAAsBqE,OAAtB,MAAmC,CAAC,CAAxC,EAA2C;AACzC;AAEA;AACA,0BAAMgF,EAAE,GAAGtJ,CAAC,CAACmJ,WAAD,CAAD,CAAeI,OAAf,CAAuB,eAAvB,CAAX;AACAC,sBAAAA,SAAS,GAAGF,EAAE,CAACjI,MAAH,GAAYiI,EAAE,CAAC,CAAD,CAAd,GAAoBH,WAAhC,CALyC;;AAQzC,0BAAMvH,EAAE,GAAGf,SAAS,CAACC,cAAV,CAAyB,CAAC0I,SAAD,CAAzB,CAAX;AACA,0BAAM3H,CAAC,GAAGD,EAAE,CAACC,CAAH,GAAOD,EAAE,CAACS,KAAH,GAAW,CAA5B;AACA,0BAAMN,CAAC,GAAGH,EAAE,CAACG,CAAH,GAAOH,EAAE,CAACW,MAAH,GAAY,CAA7B;AAEAsE,sBAAAA,OAAO,GAAG,IAAV;AACA4C,sBAAAA,OAAO,GAAGjD,OAAO,CAAC;AAChBkD,wBAAAA,OAAO,EAAE,UADO;AAEhBC,wBAAAA,IAAI,EAAE;AACJxF,0BAAAA,EAAE,EAAEtD,SAAS,CAAC+I,SAAV,EADA;AAEJ9G,0BAAAA,MAAM,EAAGjB,CAAC,GAAG,GAAJ,GAAUE,CAAV,GAAc,GAAd,GAAoBF,CAApB,GAAwB,GAAxB,GAA8BE,CAA9B,GAAkC,GAAlC,GAAwC+G,MAAxC,GAAiD,GAAjD,GAAuDC,MAF5D;AAGJc,0BAAAA,MAAM,EAAE,MAAMX,UAAU,CAACY,KAHrB;AAIJ,0CAAiB,CAACN,SAAS,CAACO,YAAX,IAA2BP,SAAS,CAACO,YAAV,KAA2B,CAAvD,GACZb,UAAU,CAAC7G,KADC,GAEZmH,SAAS,CAACO,YANV;AAOJC,0BAAAA,IAAI,EAAE,MAPF;AAQJC,0BAAAA,OAAO,EAAEf,UAAU,CAACe,OARhB;AASJC,0BAAAA,KAAK,EAAE;AATH;AAFU,uBAAD,CAAjB;AAcAjI,sBAAAA,MAAM,CAACwH,OAAD,EAAU,UAAV,EAAsB7H,EAAtB,CAAN;AACD;;AACD,2BAAO;AACLiF,sBAAAA,OAAO,EAAE;AADJ,qBAAP;AAGD;;AACD,sBAAImC,IAAI,KAAK,QAAb,EAAuB;AACrBlJ,oBAAAA,cAAc;AACf;;AACD,yBAAOgE,SAAP;AACD,iBA9DI;AA+DLqG,gBAAAA,SA/DK,qBA+DMxB,IA/DN,EA+DY;AACf,sBAAMyB,IAAI,GAAGvJ,SAAS,CAACwJ,OAAV,EAAb,CADe;;AAGf,sBAAMxI,CAAC,GAAG8G,IAAI,CAAC2B,OAAL,GAAeF,IAAzB;AACA,sBAAMrI,CAAC,GAAG4G,IAAI,CAAC4B,OAAL,GAAeH,IAAzB;AAEA,sBAAM3F,KAAK,GAAG5C,CAAC,GAAGiH,MAAlB;AAAA,sBACEpE,KAAK,GAAG3C,CAAC,GAAGgH,MADd;AAGA,sBAAMC,IAAI,GAAGnI,SAAS,CAACoI,OAAV,EAAb;;AAEA,sBAAID,IAAI,KAAK,WAAT,IAAwBnC,OAA5B,EAAqC;AACnC;AACA;AACA,wBAAMrE,EAAE,GAAG/C,cAAc,CAACoC,CAAD,EAAIE,CAAJ,EAAOE,MAAM,CAACwH,OAAD,EAAU,UAAV,CAAb,EAAoC/J,SAAS,CAAC,OAAD,EAAU+J,OAAV,CAA7C,CAAzB;AACAX,oBAAAA,MAAM,GAAGtG,EAAE,CAACX,CAAZ;AACAkH,oBAAAA,MAAM,GAAGvG,EAAE,CAACT,CAAZ;AAEAnC,oBAAAA,QAAQ,CAAC6J,OAAD,EAAU,CAAV,EAAajH,EAAE,CAACX,CAAhB,EAAmBW,EAAE,CAACT,CAAtB,EAAyB,IAAzB,CAAR,CAPmC;;AAUnCnC,oBAAAA,QAAQ,CAAC6J,OAAD,EAAU,KAAV,EAAiB5H,CAAjB,EAAoBE,CAApB,EAAuB,IAAvB,CAAR;AACD,mBAXD,MAWO,IAAIiH,IAAI,KAAK,QAAb,EAAuB;AAC5B,wBAAIwB,IAAI,GAAGnH,QAAQ,CAAChC,MAApB;;AACA,2BAAOmJ,IAAI,EAAX,EAAe;AACb,0BAAM/I,IAAI,GAAG4B,QAAQ,CAACmH,IAAD,CAArB,CADa;;AAGb,0BAAI/I,IAAI,IAAIQ,MAAM,CAACR,IAAD,EAAO,SAAP,CAAlB,EAAqC;AACnC;AACAZ,wBAAAA,SAAS,CAACmG,mBAAV,CAA8B,CAACvF,IAAD,CAA9B;AACAZ,wBAAAA,SAAS,CAAC4J,gBAAV,CAA2BhJ,IAA3B,EAAiCiJ,KAAjC;AACD;AACF;;AACD,wBAAItJ,WAAW,CAACC,MAAhB,EAAwB;AACtBxB,sBAAAA,UAAU,CAAC4E,KAAD,EAAQC,KAAR,CAAV;AACD;AACF;AACF,iBApGI;AAqGLiG,gBAAAA,OArGK,mBAqGIhC,IArGJ,EAqGU;AACb;AACA,sBAAMC,CAAC,GAAGD,IAAI,CAACE,KAAf,CAFa;AAIb;;AACA,sBAAIM,WAAW,GAAGP,CAAC,CAACQ,MAApB;;AAEA,sBAAIvI,SAAS,CAACoI,OAAV,OAAwB,WAA5B,EAAyC;AACvC,2BAAOnF,SAAP;AACD;;AACD,sBAAMwF,EAAE,GAAGtJ,CAAC,CAACmJ,WAAD,CAAD,CAAeI,OAAf,CAAuB,eAAvB,CAAX;;AACA,sBAAID,EAAE,CAACjI,MAAP,EAAe;AAAE8H,oBAAAA,WAAW,GAAGG,EAAE,CAAC,CAAD,CAAhB;AAAsB;;AAEvC,sBAAMhF,OAAO,GAAGtE,CAAC,CAACmJ,WAAD,CAAD,CAAe7E,OAAf,EAAhB;;AAEA,sBAAI6E,WAAW,KAAKK,SAApB,EAA+B;AAC7B;AACA3C,oBAAAA,OAAO,GAAG,IAAV;AACA,2BAAO;AACL+D,sBAAAA,IAAI,EAAE,IADD;AAELlB,sBAAAA,OAAO,EAAE,IAFJ;AAGL7C,sBAAAA,OAAO,EAAPA;AAHK,qBAAP;AAKD;;AACD,sBAAI7G,CAAC,CAACqJ,OAAF,CAAUpJ,UAAV,EAAsBqE,OAAtB,MAAmC,CAAC,CAAxC,EAA2C;AACzC;AACAtE,oBAAAA,CAAC,CAACyJ,OAAD,CAAD,CAAWjF,MAAX;AACAqC,oBAAAA,OAAO,GAAG,KAAV;AACA,2BAAO;AACL+D,sBAAAA,IAAI,EAAE,KADD;AAELlB,sBAAAA,OAAO,EAAE,IAFJ;AAGL7C,sBAAAA,OAAO,EAAPA;AAHK,qBAAP;AAKD,mBAjCY;;;AAmCbgE,kBAAAA,OAAO,GAAG1B,WAAV;AAEA,sBAAM2B,OAAO,GAAGtB,SAAS,CAACrF,EAA1B;AAAA,sBAA8B4G,KAAK,GAAGF,OAAO,CAAC1G,EAA9C;AACA,sBAAM6G,OAAO,GAAGF,OAAO,GAAG,GAAV,GAAgBC,KAAhC;AACA,sBAAME,MAAM,GAAGF,KAAK,GAAG,GAAR,GAAcD,OAA7B,CAvCa;;AAyCb,sBAAMI,IAAI,GAAGlL,CAAC,CAACC,UAAD,CAAD,CAAcC,IAAd,CAAmBM,OAAnB,EAA4B2K,MAA5B,CAAmC,YAAY;AAC1D,wBAAM/K,IAAI,GAAG,KAAKC,cAAL,CAAoBC,IAApB,EAA0B,WAA1B,CAAb;;AACA,wBAAIF,IAAI,KAAK4K,OAAT,IAAoB5K,IAAI,KAAK6K,MAAjC,EAAyC;AAAE,6BAAO,IAAP;AAAc;;AACzD,2BAAO,KAAP;AACD,mBAJY,CAAb;;AAKA,sBAAIC,IAAI,CAAC7J,MAAT,EAAiB;AACfrB,oBAAAA,CAAC,CAACyJ,OAAD,CAAD,CAAWjF,MAAX;AACA,2BAAO;AACLoG,sBAAAA,IAAI,EAAE,KADD;AAELlB,sBAAAA,OAAO,EAAE,IAFJ;AAGL7C,sBAAAA,OAAO,EAAE;AAHJ,qBAAP;AAKD;;AAED,sBAAMjF,EAAE,GAAGf,SAAS,CAACC,cAAV,CAAyB,CAAC+J,OAAD,CAAzB,CAAX;AAEA,sBAAMrI,EAAE,GAAG/C,cAAc,CAACqJ,MAAD,EAASC,MAAT,EAAiBnH,EAAjB,EAAqBlC,SAAS,CAAC,OAAD,EAAU+J,OAAV,CAA9B,CAAzB;AACA7J,kBAAAA,QAAQ,CAAC6J,OAAD,EAAU,KAAV,EAAiBjH,EAAE,CAACX,CAApB,EAAuBW,EAAE,CAACT,CAA1B,EAA6B,IAA7B,CAAR;AACA/B,kBAAAA,CAAC,CAACyJ,OAAD,CAAD,CACGxI,IADH,CACQ,SADR,EACmB6J,OADnB,EAEG7J,IAFH,CAEQ,OAFR,EAEiB8J,KAFjB,EAGG9J,IAHH,CAGQ,QAHR,EAGkBW,EAHlB;AAIAtB,kBAAAA,IAAI,GAAGO,SAAS,CAACK,WAAV,CAAsB,IAAtB,CAAP;AACAuI,kBAAAA,OAAO,CAAC2B,cAAR,CAAuB9K,IAAvB,EAA6B,cAA7B,EAA6C0K,OAA7C;AACAvB,kBAAAA,OAAO,CAAClJ,YAAR,CAAqB,OAArB,EAA8BC,OAAO,CAACC,MAAR,CAAe,CAAf,CAA9B;AACAgJ,kBAAAA,OAAO,CAAClJ,YAAR,CAAqB,SAArB,EAAgC,CAAhC;AACAM,kBAAAA,SAAS,CAACwK,cAAV,CAAyB,CAAC5B,OAAD,CAAzB;AACA5I,kBAAAA,SAAS,CAACyK,2BAAV;AACA5E,kBAAAA,UAAU,CAAC6E,eAAX,CAA2B9B,OAA3B,EAAoC+B,SAApC,CAA8C,KAA9C;AACA3E,kBAAAA,OAAO,GAAG,KAAV;AACA,yBAAO;AACL+D,oBAAAA,IAAI,EAAE,IADD;AAELlB,oBAAAA,OAAO,EAAED,OAFJ;AAGL5C,oBAAAA,OAAO,EAAPA;AAHK,mBAAP;AAKD,iBAjLI;AAkLL4E,gBAAAA,eAlLK,2BAkLY9C,IAlLZ,EAkLkB;AACrB;AACA,sBAAI,CAAC3I,CAAC,CAACC,UAAD,CAAD,CAAcC,IAAd,CAAmBM,OAAnB,EAA4Ba,MAAjC,EAAyC;AAAE;AAAS;;AAEpD,sBAAIR,SAAS,CAACoI,OAAV,OAAwB,WAA5B,EAAyC;AACvCpI,oBAAAA,SAAS,CAACqH,OAAV,CAAkB,QAAlB;AACD,mBANoB;;;AASrB7E,kBAAAA,QAAQ,GAAGsF,IAAI,CAACxH,KAAhB;AAEA,sBAAIG,CAAC,GAAG+B,QAAQ,CAAChC,MAAjB;;AACA,yBAAOC,CAAC,EAAR,EAAY;AACV,wBAAMG,IAAI,GAAG4B,QAAQ,CAAC/B,CAAD,CAArB;;AACA,wBAAIG,IAAI,IAAIQ,MAAM,CAACR,IAAD,EAAO,SAAP,CAAlB,EAAqC;AACnCiF,sBAAAA,UAAU,CAAC6E,eAAX,CAA2B9J,IAA3B,EAAiC+J,SAAjC,CAA2C,KAA3C;;AACA,0BAAI7C,IAAI,CAAC+C,eAAL,IAAwB,CAAC/C,IAAI,CAACgD,aAAlC,EAAiD;AAC/C;AACAhM,wBAAAA,SAAS,CAAC,IAAD,CAAT;AACD,uBAHD,MAGO;AACLA,wBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF,qBARD,MAQO;AACLA,sBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF;;AACDI,kBAAAA,gBAAgB;AACjB,iBA7MI;AA8ML6L,gBAAAA,cA9MK,0BA8MWjD,IA9MX,EA8MiB;AACpB,sBAAIlH,IAAI,GAAGkH,IAAI,CAACxH,KAAL,CAAW,CAAX,CAAX;AACA,sBAAI,CAACM,IAAL,EAAW;;AACX,sBAAIA,IAAI,CAACoK,OAAL,KAAiB,KAAjB,IAA0BpK,IAAI,CAAC0C,EAAL,KAAY,YAA1C,EAAwD;AACtD;AACAlE,oBAAAA,UAAU,GAAGwB,IAAb;AACAlC,oBAAAA,IAAI;AACL,mBAPmB;;;AAUpB,sBACEkC,IAAI,CAACuD,YAAL,CAAkB,cAAlB,KACAvD,IAAI,CAACuD,YAAL,CAAkB,YAAlB,CADA,IAEAvD,IAAI,CAACuD,YAAL,CAAkB,YAAlB,CAHF,EAIE;AACA,wBAAM8G,KAAK,GAAGrK,IAAI,CAACuD,YAAL,CAAkB,cAAlB,CAAd;AACA,wBAAM+G,GAAG,GAAGtK,IAAI,CAACuD,YAAL,CAAkB,YAAlB,CAAZ;AACA,wBAAMgH,GAAG,GAAGvK,IAAI,CAACuD,YAAL,CAAkB,YAAlB,CAAZ;AACAyE,oBAAAA,OAAO,GAAGhI,IAAV;AACAzB,oBAAAA,CAAC,CAACyB,IAAD,CAAD,CACGR,IADH,CACQ,WADR,EACqBgL,OAAO,CAACH,KAAD,CAD5B,EAEG7K,IAFH,CAEQ,SAFR,EAEmBgL,OAAO,CAACD,GAAD,CAF1B;;AAIA,wBAAIvK,IAAI,CAACoK,OAAL,KAAiB,MAAjB,IAA2BE,GAA/B,EAAoC;AAClC;AAEA,0BAAMG,EAAE,GAAGC,MAAM,CAAC1K,IAAI,CAACuD,YAAL,CAAkB,IAAlB,CAAD,CAAjB;AACA,0BAAMoH,EAAE,GAAGD,MAAM,CAAC1K,IAAI,CAACuD,YAAL,CAAkB,IAAlB,CAAD,CAAjB;AACA,0BAAMqH,EAAE,GAAGF,MAAM,CAAC1K,IAAI,CAACuD,YAAL,CAAkB,IAAlB,CAAD,CAAjB;AACA,0BAAMsH,EAAE,GAAGH,MAAM,CAAC1K,IAAI,CAACuD,YAAL,CAAkB,IAAlB,CAAD,CAAjB;AANkC,kCAOrBvD,IAPqB;AAAA,0BAO3B0C,EAP2B,SAO3BA,EAP2B;AASlC,0BAAMoI,KAAK,GAAI,MAAO,CAACL,EAAE,GAAGE,EAAN,IAAY,CAAnB,GAAwB,GAAxB,GAA+B,CAACC,EAAE,GAAGC,EAAN,IAAY,CAA3C,GAAgD,GAA/D;AACA,0BAAME,KAAK,GAAGhG,OAAO,CAAC;AACpBkD,wBAAAA,OAAO,EAAE,UADW;AAEpBC,wBAAAA,IAAI,EAAE;AACJ7G,0BAAAA,MAAM,EAAGoJ,EAAE,GAAG,GAAL,GAAWG,EAAX,GAAgBE,KAAhB,GAAwBH,EAAxB,GAA6B,GAA7B,GAAmCE,EADxC;AAEJzC,0BAAAA,MAAM,EAAEpI,IAAI,CAACuD,YAAL,CAAkB,QAAlB,CAFJ;AAGJ,0CAAgBvD,IAAI,CAACuD,YAAL,CAAkB,cAAlB,CAHZ;AAIJ,wCAAc+G,GAJV;AAKJ/B,0BAAAA,IAAI,EAAE,MALF;AAMJC,0BAAAA,OAAO,EAAExI,IAAI,CAACuD,YAAL,CAAkB,SAAlB,KAAgC;AANrC;AAFc,uBAAD,CAArB;AAWAhF,sBAAAA,CAAC,CAACyB,IAAD,CAAD,CAAQgL,KAAR,CAAcD,KAAd,EAAqBhI,MAArB;AACA3D,sBAAAA,SAAS,CAAC6L,cAAV;AACAF,sBAAAA,KAAK,CAACrI,EAAN,GAAWA,EAAX;AACAtD,sBAAAA,SAAS,CAACwK,cAAV,CAAyB,CAACmB,KAAD,CAAzB;AACA/K,sBAAAA,IAAI,GAAG+K,KAAP;AACD;AACF,mBAlDmB;;;AAoDpB,sBAAI/K,IAAI,CAACuD,YAAL,CAAkB,OAAlB,MAA+BxE,OAAO,CAACC,MAAR,CAAe,CAAf,CAAnC,EAAsD;AACpD,wBAAMqL,MAAK,GAAG/K,OAAO,CAACkB,MAAM,CAACR,IAAD,EAAO,SAAP,CAAP,CAArB;;AACA1B,oBAAAA,gBAAgB,CAAC,CAAC+L,MAAD,CAAD,CAAhB;AACD,mBAHD,MAGO;AACL/L,oBAAAA,gBAAgB;AACjB;AACF,iBAxQI;AAyQL4M,gBAAAA,UAzQK,sBAyQOC,KAzQP,EAyQc;AACjB,sBAAMpI,MAAM,GAAG,EAAf;AACAoI,kBAAAA,KAAK,CAACzL,KAAN,CAAYuC,OAAZ,CAAoB,UAAUjC,IAAV,EAAgB;AAClC,wBAAI,kBAAkBA,IAAI,CAACkI,IAA3B,EAAiC;AAC/BlI,sBAAAA,IAAI,CAACkI,IAAL,CAAU,cAAV,IAA4BlI,IAAI,CAACkI,IAAL,CAAU,cAAV,EAA0BhJ,KAA1B,CAAgC,GAAhC,EACzByH,GADyB,CACrB,UAAUyE,KAAV,EAAiB;AAAE,+BAAOD,KAAK,CAACE,OAAN,CAAcD,KAAd,CAAP;AAA8B,uBAD5B,EAC8BzJ,IAD9B,CACmC,GADnC,CAA5B,CAD+B;AAK/B;;AACA,0BAAI,CAAE,KAAD,CAAQ2J,IAAR,CAAatL,IAAI,CAACkI,IAAL,CAAU,cAAV,CAAb,CAAL,EAA8C;AAC5CnF,wBAAAA,MAAM,CAACJ,IAAP,CAAY3C,IAAI,CAACkI,IAAL,CAAUxF,EAAtB;AACD;AACF;AACF,mBAXD;AAYA,yBAAO;AAACK,oBAAAA,MAAM,EAANA;AAAD,mBAAP;AACD,iBAxRI;AAyRLwI,gBAAAA,qBAzRK,iCAyRkBrE,IAzRlB,EAyRwB;AAC3B,sBAAIA,IAAI,CAACsE,QAAT,EAAmB;AACjB,wBAAIjN,CAAC,CAAC,eAAD,CAAD,CAAmBkN,QAAnB,CAA4B,qBAA5B,CAAJ,EAAwD;AACtD7G,sBAAAA,SAAS,CAAC8G,WAAV;AACD;AACF;;AACDnN,kBAAAA,CAAC,CAAC,eAAD,CAAD,CACGoN,WADH,CACe,UADf,EAC2BzE,IAAI,CAACsE,QADhC;AAED;AAjSI,eAnWM;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsoBd;AAxoBY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-eyedropper.js b/dist/editor/extensions/ext-eyedropper.js deleted file mode 100644 index 6799fb29..00000000 --- a/dist/editor/extensions/ext-eyedropper.js +++ /dev/null @@ -1,1804 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -var eyedropperIcon = "eyedropper-icon.xml"; - -var extEyedropper = { - name: 'eyedropper', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - getStyle = function _getStyle(opts) { - // if we are in eyedropper mode, we don't want to disable the eye-dropper tool - var mode = svgCanvas.getMode(); - - if (mode === 'eyedropper') { - return; - } - - var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected - - var elem = null; - - if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) { - elem = opts.elems[0]; - tool.removeClass('disabled'); // grab the current style - - currentStyle.fillPaint = elem.getAttribute('fill') || 'black'; - currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0; - currentStyle.strokePaint = elem.getAttribute('stroke'); - currentStyle.strokeOpacity = elem.getAttribute('stroke-opacity') || 1.0; - currentStyle.strokeWidth = elem.getAttribute('stroke-width'); - currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray'); - currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap'); - currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin'); - currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool - } else { - tool.addClass('disabled'); - } - }; - - _context.next = 3; - return S.importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - $ = S.$, ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) { - svgCanvas.undoMgr.addCommandToHistory(cmd); - }, currentStyle = { - fillPaint: 'red', - fillOpacity: 1.0, - strokePaint: 'black', - strokeOpacity: 1.0, - strokeWidth: 5, - strokeDashArray: null, - opacity: 1.0, - strokeLinecap: 'butt', - strokeLinejoin: 'miter' - }; - /** - * - * @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementChanged} opts - * @returns {void} - */ - - buttons = [{ - id: 'tool_eyedropper', - icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png', - type: 'mode', - events: { - click: function click() { - svgCanvas.setMode('eyedropper'); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - // if we have selected an element, grab its paint and enable the eye dropper button - selectedChanged: getStyle, - elementChanged: getStyle, - mouseDown: function mouseDown(opts) { - var mode = svgCanvas.getMode(); - - if (mode === 'eyedropper') { - var e = opts.event; - var target = e.target; - - if (!['svg', 'g', 'use'].includes(target.nodeName)) { - var changes = {}; - - var change = function change(elem, attrname, newvalue) { - changes[attrname] = elem.getAttribute(attrname); - elem.setAttribute(attrname, newvalue); - }; - - if (currentStyle.fillPaint) { - change(target, 'fill', currentStyle.fillPaint); - } - - if (currentStyle.fillOpacity) { - change(target, 'fill-opacity', currentStyle.fillOpacity); - } - - if (currentStyle.strokePaint) { - change(target, 'stroke', currentStyle.strokePaint); - } - - if (currentStyle.strokeOpacity) { - change(target, 'stroke-opacity', currentStyle.strokeOpacity); - } - - if (currentStyle.strokeWidth) { - change(target, 'stroke-width', currentStyle.strokeWidth); - } - - if (currentStyle.strokeDashArray) { - change(target, 'stroke-dasharray', currentStyle.strokeDashArray); - } - - if (currentStyle.opacity) { - change(target, 'opacity', currentStyle.opacity); - } - - if (currentStyle.strokeLinecap) { - change(target, 'stroke-linecap', currentStyle.strokeLinecap); - } - - if (currentStyle.strokeLinejoin) { - change(target, 'stroke-linejoin', currentStyle.strokeLinejoin); - } - - addToHistory(new ChangeElementCommand(target, changes)); - } - } - } - }); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } -}; - -export default extEyedropper; -//# sourceMappingURL=ext-eyedropper.js.map diff --git a/dist/editor/extensions/ext-eyedropper.js.map b/dist/editor/extensions/ext-eyedropper.js.map deleted file mode 100644 index 8d2bbbd9..00000000 --- a/dist/editor/extensions/ext-eyedropper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-eyedropper.js","sources":["../../../src/editor/extensions/eyedropper-icon.xml","../../../src/editor/extensions/ext-eyedropper.js"],"sourcesContent":["export default \"eyedropper-icon.xml\"","/**\n * @file ext-eyedropper.js\n *\n * @license MIT\n *\n * @copyright 2010 Jeff Schiller\n *\n */\n\nimport './eyedropper-icon.xml';\n\nexport default {\n name: 'eyedropper',\n async init (S) {\n const strings = await S.importLocale();\n const svgEditor = this;\n const {$, ChangeElementCommand} = S, // , svgcontent,\n // svgdoc = S.svgroot.parentNode.ownerDocument,\n svgCanvas = svgEditor.canvas,\n addToHistory = function (cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); },\n currentStyle = {\n fillPaint: 'red', fillOpacity: 1.0,\n strokePaint: 'black', strokeOpacity: 1.0,\n strokeWidth: 5, strokeDashArray: null,\n opacity: 1.0,\n strokeLinecap: 'butt',\n strokeLinejoin: 'miter'\n };\n\n /**\n *\n * @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementChanged} opts\n * @returns {void}\n */\n function getStyle (opts) {\n // if we are in eyedropper mode, we don't want to disable the eye-dropper tool\n const mode = svgCanvas.getMode();\n if (mode === 'eyedropper') { return; }\n\n const tool = $('#tool_eyedropper');\n // enable-eye-dropper if one element is selected\n let elem = null;\n if (!opts.multiselected && opts.elems[0] &&\n !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)\n ) {\n elem = opts.elems[0];\n tool.removeClass('disabled');\n // grab the current style\n currentStyle.fillPaint = elem.getAttribute('fill') || 'black';\n currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0;\n currentStyle.strokePaint = elem.getAttribute('stroke');\n currentStyle.strokeOpacity = elem.getAttribute('stroke-opacity') || 1.0;\n currentStyle.strokeWidth = elem.getAttribute('stroke-width');\n currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray');\n currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap');\n currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin');\n currentStyle.opacity = elem.getAttribute('opacity') || 1.0;\n // disable eye-dropper tool\n } else {\n tool.addClass('disabled');\n }\n }\n\n const buttons = [\n {\n id: 'tool_eyedropper',\n icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png',\n type: 'mode',\n events: {\n click () {\n svgCanvas.setMode('eyedropper');\n }\n }\n }\n ];\n\n return {\n name: strings.name,\n svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n\n // if we have selected an element, grab its paint and enable the eye dropper button\n selectedChanged: getStyle,\n elementChanged: getStyle,\n\n mouseDown (opts) {\n const mode = svgCanvas.getMode();\n if (mode === 'eyedropper') {\n const e = opts.event;\n const {target} = e;\n if (!['svg', 'g', 'use'].includes(target.nodeName)) {\n const changes = {};\n\n const change = function (elem, attrname, newvalue) {\n changes[attrname] = elem.getAttribute(attrname);\n elem.setAttribute(attrname, newvalue);\n };\n\n if (currentStyle.fillPaint) { change(target, 'fill', currentStyle.fillPaint); }\n if (currentStyle.fillOpacity) { change(target, 'fill-opacity', currentStyle.fillOpacity); }\n if (currentStyle.strokePaint) { change(target, 'stroke', currentStyle.strokePaint); }\n if (currentStyle.strokeOpacity) { change(target, 'stroke-opacity', currentStyle.strokeOpacity); }\n if (currentStyle.strokeWidth) { change(target, 'stroke-width', currentStyle.strokeWidth); }\n if (currentStyle.strokeDashArray) { change(target, 'stroke-dasharray', currentStyle.strokeDashArray); }\n if (currentStyle.opacity) { change(target, 'opacity', currentStyle.opacity); }\n if (currentStyle.strokeLinecap) { change(target, 'stroke-linecap', currentStyle.strokeLinecap); }\n if (currentStyle.strokeLinejoin) { change(target, 'stroke-linejoin', currentStyle.strokeLinejoin); }\n\n addToHistory(new ChangeElementCommand(target, changes));\n }\n }\n }\n };\n }\n};\n"],"names":["name","init","S","getStyle","opts","mode","svgCanvas","getMode","tool","$","elem","multiselected","elems","includes","nodeName","removeClass","currentStyle","fillPaint","getAttribute","fillOpacity","strokePaint","strokeOpacity","strokeWidth","strokeDashArray","strokeLinecap","strokeLinejoin","opacity","addClass","importLocale","strings","svgEditor","ChangeElementCommand","canvas","addToHistory","cmd","undoMgr","addCommandToHistory","buttons","id","icon","curConfig","extIconsPath","type","events","click","setMode","svgicons","map","button","i","Object","assign","selectedChanged","elementChanged","mouseDown","e","event","target","changes","change","attrname","newvalue","setAttribute"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qBAAe;;ACWf,oBAAe;AACbA,EAAAA,IAAI,EAAE,YADO;AAEPC,EAAAA,IAFO,gBAEDC,CAFC,EAEE;AAAA;;AAAA;AAAA,8FAqBJC,QArBI;AAAA;AAAA;AAAA;AAAA;AAqBJA,cAAAA,QArBI,sBAqBMC,IArBN,EAqBY;AACvB;AACA,oBAAMC,IAAI,GAAGC,SAAS,CAACC,OAAV,EAAb;;AACA,oBAAIF,IAAI,KAAK,YAAb,EAA2B;AAAE;AAAS;;AAEtC,oBAAMG,IAAI,GAAGC,CAAC,CAAC,kBAAD,CAAd,CALuB;;AAOvB,oBAAIC,IAAI,GAAG,IAAX;;AACA,oBAAI,CAACN,IAAI,CAACO,aAAN,IAAuBP,IAAI,CAACQ,KAAL,CAAW,CAAX,CAAvB,IACF,CAAC,CAAC,KAAD,EAAQ,GAAR,EAAa,KAAb,EAAoBC,QAApB,CAA6BT,IAAI,CAACQ,KAAL,CAAW,CAAX,EAAcE,QAA3C,CADH,EAEE;AACAJ,kBAAAA,IAAI,GAAGN,IAAI,CAACQ,KAAL,CAAW,CAAX,CAAP;AACAJ,kBAAAA,IAAI,CAACO,WAAL,CAAiB,UAAjB,EAFA;;AAIAC,kBAAAA,YAAY,CAACC,SAAb,GAAyBP,IAAI,CAACQ,YAAL,CAAkB,MAAlB,KAA6B,OAAtD;AACAF,kBAAAA,YAAY,CAACG,WAAb,GAA2BT,IAAI,CAACQ,YAAL,CAAkB,cAAlB,KAAqC,GAAhE;AACAF,kBAAAA,YAAY,CAACI,WAAb,GAA2BV,IAAI,CAACQ,YAAL,CAAkB,QAAlB,CAA3B;AACAF,kBAAAA,YAAY,CAACK,aAAb,GAA6BX,IAAI,CAACQ,YAAL,CAAkB,gBAAlB,KAAuC,GAApE;AACAF,kBAAAA,YAAY,CAACM,WAAb,GAA2BZ,IAAI,CAACQ,YAAL,CAAkB,cAAlB,CAA3B;AACAF,kBAAAA,YAAY,CAACO,eAAb,GAA+Bb,IAAI,CAACQ,YAAL,CAAkB,kBAAlB,CAA/B;AACAF,kBAAAA,YAAY,CAACQ,aAAb,GAA6Bd,IAAI,CAACQ,YAAL,CAAkB,gBAAlB,CAA7B;AACAF,kBAAAA,YAAY,CAACS,cAAb,GAA8Bf,IAAI,CAACQ,YAAL,CAAkB,iBAAlB,CAA9B;AACAF,kBAAAA,YAAY,CAACU,OAAb,GAAuBhB,IAAI,CAACQ,YAAL,CAAkB,SAAlB,KAAgC,GAAvD,CAZA;AAcD,iBAhBD,MAgBO;AACLV,kBAAAA,IAAI,CAACmB,QAAL,CAAc,UAAd;AACD;AACF,eAhDY;;AAAA;AAAA,qBACSzB,CAAC,CAAC0B,YAAF,EADT;;AAAA;AACPC,cAAAA,OADO;AAEPC,cAAAA,SAFO,GAEK,KAFL;AAGNrB,cAAAA,CAHM,GAGqBP,CAHrB,CAGNO,CAHM,EAGHsB,oBAHG,GAGqB7B,CAHrB,CAGH6B,oBAHG,EAKXzB,SALW,GAKCwB,SAAS,CAACE,MALX,EAMXC,YANW,GAMI,SAAfA,YAAe,CAAUC,GAAV,EAAe;AAAE5B,gBAAAA,SAAS,CAAC6B,OAAV,CAAkBC,mBAAlB,CAAsCF,GAAtC;AAA6C,eANlE,EAOXlB,YAPW,GAOI;AACbC,gBAAAA,SAAS,EAAE,KADE;AACKE,gBAAAA,WAAW,EAAE,GADlB;AAEbC,gBAAAA,WAAW,EAAE,OAFA;AAESC,gBAAAA,aAAa,EAAE,GAFxB;AAGbC,gBAAAA,WAAW,EAAE,CAHA;AAGGC,gBAAAA,eAAe,EAAE,IAHpB;AAIbG,gBAAAA,OAAO,EAAE,GAJI;AAKbF,gBAAAA,aAAa,EAAE,MALF;AAMbC,gBAAAA,cAAc,EAAE;AANH,eAPJ;AAgBb;;;;;;AAkCMY,cAAAA,OAlDO,GAkDG,CACd;AACEC,gBAAAA,EAAE,EAAE,iBADN;AAEEC,gBAAAA,IAAI,EAAET,SAAS,CAACU,SAAV,CAAoBC,YAApB,GAAmC,gBAF3C;AAGEC,gBAAAA,IAAI,EAAE,MAHR;AAIEC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPtC,oBAAAA,SAAS,CAACuC,OAAV,CAAkB,YAAlB;AACD;AAHK;AAJV,eADc,CAlDH;AAAA,+CA+DN;AACL7C,gBAAAA,IAAI,EAAE6B,OAAO,CAAC7B,IADT;AAEL8C,gBAAAA,QAAQ,EAAEhB,SAAS,CAACU,SAAV,CAAoBC,YAApB,GAAmC,qBAFxC;AAGLJ,gBAAAA,OAAO,EAAER,OAAO,CAACQ,OAAR,CAAgBU,GAAhB,CAAoB,UAACC,MAAD,EAASC,CAAT,EAAe;AAC1C,yBAAOC,MAAM,CAACC,MAAP,CAAcd,OAAO,CAACY,CAAD,CAArB,EAA0BD,MAA1B,CAAP;AACD,iBAFQ,CAHJ;AAOL;AACAI,gBAAAA,eAAe,EAAEjD,QARZ;AASLkD,gBAAAA,cAAc,EAAElD,QATX;AAWLmD,gBAAAA,SAXK,qBAWMlD,IAXN,EAWY;AACf,sBAAMC,IAAI,GAAGC,SAAS,CAACC,OAAV,EAAb;;AACA,sBAAIF,IAAI,KAAK,YAAb,EAA2B;AACzB,wBAAMkD,CAAC,GAAGnD,IAAI,CAACoD,KAAf;AADyB,wBAElBC,MAFkB,GAERF,CAFQ,CAElBE,MAFkB;;AAGzB,wBAAI,CAAC,CAAC,KAAD,EAAQ,GAAR,EAAa,KAAb,EAAoB5C,QAApB,CAA6B4C,MAAM,CAAC3C,QAApC,CAAL,EAAoD;AAClD,0BAAM4C,OAAO,GAAG,EAAhB;;AAEA,0BAAMC,MAAM,GAAG,SAATA,MAAS,CAAUjD,IAAV,EAAgBkD,QAAhB,EAA0BC,QAA1B,EAAoC;AACjDH,wBAAAA,OAAO,CAACE,QAAD,CAAP,GAAoBlD,IAAI,CAACQ,YAAL,CAAkB0C,QAAlB,CAApB;AACAlD,wBAAAA,IAAI,CAACoD,YAAL,CAAkBF,QAAlB,EAA4BC,QAA5B;AACD,uBAHD;;AAKA,0BAAI7C,YAAY,CAACC,SAAjB,EAA4B;AAAE0C,wBAAAA,MAAM,CAACF,MAAD,EAAS,MAAT,EAAiBzC,YAAY,CAACC,SAA9B,CAAN;AAAiD;;AAC/E,0BAAID,YAAY,CAACG,WAAjB,EAA8B;AAAEwC,wBAAAA,MAAM,CAACF,MAAD,EAAS,cAAT,EAAyBzC,YAAY,CAACG,WAAtC,CAAN;AAA2D;;AAC3F,0BAAIH,YAAY,CAACI,WAAjB,EAA8B;AAAEuC,wBAAAA,MAAM,CAACF,MAAD,EAAS,QAAT,EAAmBzC,YAAY,CAACI,WAAhC,CAAN;AAAqD;;AACrF,0BAAIJ,YAAY,CAACK,aAAjB,EAAgC;AAAEsC,wBAAAA,MAAM,CAACF,MAAD,EAAS,gBAAT,EAA2BzC,YAAY,CAACK,aAAxC,CAAN;AAA+D;;AACjG,0BAAIL,YAAY,CAACM,WAAjB,EAA8B;AAAEqC,wBAAAA,MAAM,CAACF,MAAD,EAAS,cAAT,EAAyBzC,YAAY,CAACM,WAAtC,CAAN;AAA2D;;AAC3F,0BAAIN,YAAY,CAACO,eAAjB,EAAkC;AAAEoC,wBAAAA,MAAM,CAACF,MAAD,EAAS,kBAAT,EAA6BzC,YAAY,CAACO,eAA1C,CAAN;AAAmE;;AACvG,0BAAIP,YAAY,CAACU,OAAjB,EAA0B;AAAEiC,wBAAAA,MAAM,CAACF,MAAD,EAAS,SAAT,EAAoBzC,YAAY,CAACU,OAAjC,CAAN;AAAkD;;AAC9E,0BAAIV,YAAY,CAACQ,aAAjB,EAAgC;AAAEmC,wBAAAA,MAAM,CAACF,MAAD,EAAS,gBAAT,EAA2BzC,YAAY,CAACQ,aAAxC,CAAN;AAA+D;;AACjG,0BAAIR,YAAY,CAACS,cAAjB,EAAiC;AAAEkC,wBAAAA,MAAM,CAACF,MAAD,EAAS,iBAAT,EAA4BzC,YAAY,CAACS,cAAzC,CAAN;AAAiE;;AAEpGQ,sBAAAA,YAAY,CAAC,IAAIF,oBAAJ,CAAyB0B,MAAzB,EAAiCC,OAAjC,CAAD,CAAZ;AACD;AACF;AACF;AArCI,eA/DM;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsGd;AAxGY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-foreignobject.js b/dist/editor/extensions/ext-foreignobject.js deleted file mode 100644 index 8175f9b8..00000000 --- a/dist/editor/extensions/ext-foreignobject.js +++ /dev/null @@ -1,1965 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -var foreignobjectIcons = "foreignobject-icons.xml"; - -var extForeignobject = { - name: 'foreignobject', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - setAttr = function _setAttr(attr, val) { - svgCanvas.changeSelectedAttribute(attr, val); - svgCanvas.call('changed', selElems); - }; - - showForeignEditor = function _showForeignEditor() { - var elt = selElems[0]; - - if (!elt || editingforeign) { - return; - } - - editingforeign = true; - toggleSourceButtons(true); - elt.removeAttribute('fill'); - var str = svgCanvas.svgToString(elt, 0); - $('#svg_source_textarea').val(str); - $('#svg_source_editor').fadeIn(); - properlySourceSizeTextArea(); - $('#svg_source_textarea').focus(); - }; - - setForeignString = function _setForeignString(xmlString) { - var elt = selElems[0]; // The parent `Element` to append to - - try { - // convert string into XML document - var newDoc = text2xml('' + xmlString + ''); // run it through our sanitizer to remove anything we do not support - - svgCanvas.sanitizeSvg(newDoc.documentElement); - elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true)); - svgCanvas.call('changed', [elt]); - svgCanvas.clearSelection(); - } catch (e) { - // Todo: Surface error to user - console.log(e); // eslint-disable-line no-console - - return false; - } - - return true; - }; - - toggleSourceButtons = function _toggleSourceButtons(on) { - $('#tool_source_save, #tool_source_cancel').toggle(!on); - $('#foreign_save, #foreign_cancel').toggle(on); - }; - - showPanel = function _showPanel(on) { - var fcRules = $('#fc_rules'); - - if (!fcRules.length) { - fcRules = $('').appendTo('head'); - } - - fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); - $('#foreignObject_panel').toggle(on); - }; - - svgEditor = _this; - $ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; - svgCanvas = svgEditor.canvas; - svgdoc = S.svgroot.parentNode.ownerDocument; - _context2.next = 11; - return importLocale(); - - case 11: - strings = _context2.sent; - - properlySourceSizeTextArea = function properlySourceSizeTextArea() { - // TODO: remove magic numbers here and get values from CSS - var height = $('#svg_source_container').height() - 80; - $('#svg_source_textarea').css('height', height); - }; - /** - * @param {boolean} on - * @returns {void} - */ - - - editingforeign = false; - /** - * This function sets the content of element elt to the input XML. - * @param {string} xmlString - The XML text - * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. - */ - - buttons = [{ - id: 'tool_foreign', - icon: svgEditor.curConfig.extIconsPath + 'foreignobject-tool.png', - type: 'mode', - events: { - click: function click() { - svgCanvas.setMode('foreign'); - } - } - }, { - id: 'edit_foreign', - icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png', - type: 'context', - panel: 'foreignObject_panel', - events: { - click: function click() { - showForeignEditor(); - } - } - }]; - contextTools = [{ - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_width', - size: 3, - events: { - change: function change() { - setAttr('width', this.value); - } - } - }, { - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_height', - events: { - change: function change() { - setAttr('height', this.value); - } - } - }, { - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_font_size', - size: 2, - defval: 16, - events: { - change: function change() { - setAttr('font-size', this.value); - } - } - }]; - return _context2.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#foreignObject_panel').hide(); - - var endChanges = function endChanges() { - $('#svg_source_editor').hide(); - editingforeign = false; - $('#svg_source_textarea').blur(); - toggleSourceButtons(false); - }; // TODO: Needs to be done after orig icon loads - - - setTimeout(function () { - // Create source save/cancel buttons - - /* const save = */ - $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var ok; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (editingforeign) { - _context.next = 2; - break; - } - - return _context.abrupt("return"); - - case 2: - if (setForeignString($('#svg_source_textarea').val())) { - _context.next = 11; - break; - } - - _context.next = 5; - return $.confirm('Errors found. Revert to original?'); - - case 5: - ok = _context.sent; - - if (ok) { - _context.next = 8; - break; - } - - return _context.abrupt("return"); - - case 8: - endChanges(); - _context.next = 12; - break; - - case 11: - endChanges(); - - case 12: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - /* const cancel = */ - - $('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () { - endChanges(); - }); - }, 3000); - }, - mouseDown: function mouseDown(opts) { - // const e = opts.event; - if (svgCanvas.getMode() !== 'foreign') { - return undefined; - } - - started = true; - newFO = svgCanvas.addSVGElementFromJson({ - element: 'foreignObject', - attr: { - x: opts.start_x, - y: opts.start_y, - id: svgCanvas.getNextId(), - 'font-size': 16, - // cur_text.font_size, - width: '48', - height: '20', - style: 'pointer-events:inherit' - } - }); - var m = svgdoc.createElementNS(NS.MATH, 'math'); - m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH); - m.setAttribute('display', 'inline'); - var mi = svgdoc.createElementNS(NS.MATH, 'mi'); - mi.setAttribute('mathvariant', 'normal'); - mi.textContent = "\u03A6"; - var mo = svgdoc.createElementNS(NS.MATH, 'mo'); - mo.textContent = "\u222A"; - var mi2 = svgdoc.createElementNS(NS.MATH, 'mi'); - mi2.textContent = "\u2133"; - m.append(mi, mo, mi2); - newFO.append(m); - return { - started: true - }; - }, - mouseUp: function mouseUp(opts) { - // const e = opts.event; - if (svgCanvas.getMode() !== 'foreign' || !started) { - return undefined; - } - - var attrs = $(newFO).attr(['width', 'height']); - var keep = attrs.width !== '0' || attrs.height !== '0'; - svgCanvas.addToSelection([newFO], true); - return { - keep: keep, - element: newFO - }; - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.tagName === 'foreignObject') { - if (opts.selectedElement && !opts.multiselected) { - $('#foreign_font_size').val(elem.getAttribute('font-size')); - $('#foreign_width').val(elem.getAttribute('width')); - $('#foreign_height').val(elem.getAttribute('height')); - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) {// const elem = opts.elems[0]; - } - }); - - case 17: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - } -}; - -export default extForeignobject; -//# sourceMappingURL=ext-foreignobject.js.map diff --git a/dist/editor/extensions/ext-foreignobject.js.map b/dist/editor/extensions/ext-foreignobject.js.map deleted file mode 100644 index 0de36f92..00000000 --- a/dist/editor/extensions/ext-foreignobject.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-foreignobject.js","sources":["../../../src/editor/extensions/foreignobject-icons.xml","../../../src/editor/extensions/ext-foreignobject.js"],"sourcesContent":["export default \"foreignobject-icons.xml\"","/**\n * @file ext-foreignobject.js\n *\n * @license Apache-2.0\n *\n * @copyright 2010 Jacques Distler, 2010 Alexis Deveria\n *\n */\n\nimport './foreignobject-icons.xml';\n\nexport default {\n name: 'foreignobject',\n async init (S) {\n const svgEditor = this;\n const {$, text2xml, NS, importLocale} = S;\n const svgCanvas = svgEditor.canvas;\n const\n // {svgcontent} = S,\n // addElem = svgCanvas.addSVGElementFromJson,\n svgdoc = S.svgroot.parentNode.ownerDocument;\n const strings = await importLocale();\n\n const properlySourceSizeTextArea = function () {\n // TODO: remove magic numbers here and get values from CSS\n const height = $('#svg_source_container').height() - 80;\n $('#svg_source_textarea').css('height', height);\n };\n\n /**\n * @param {boolean} on\n * @returns {void}\n */\n function showPanel (on) {\n let fcRules = $('#fc_rules');\n if (!fcRules.length) {\n fcRules = $('').appendTo('head');\n }\n fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');\n $('#foreignObject_panel').toggle(on);\n }\n\n /**\n * @param {boolean} on\n * @returns {void}\n */\n function toggleSourceButtons (on) {\n $('#tool_source_save, #tool_source_cancel').toggle(!on);\n $('#foreign_save, #foreign_cancel').toggle(on);\n }\n\n let selElems,\n started,\n newFO,\n editingforeign = false;\n\n /**\n * This function sets the content of element elt to the input XML.\n * @param {string} xmlString - The XML text\n * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.\n */\n function setForeignString (xmlString) {\n const elt = selElems[0]; // The parent `Element` to append to\n try {\n // convert string into XML document\n const newDoc = text2xml('' + xmlString + '');\n // run it through our sanitizer to remove anything we do not support\n svgCanvas.sanitizeSvg(newDoc.documentElement);\n elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true));\n svgCanvas.call('changed', [elt]);\n svgCanvas.clearSelection();\n } catch (e) {\n // Todo: Surface error to user\n console.log(e); // eslint-disable-line no-console\n return false;\n }\n\n return true;\n }\n\n /**\n *\n * @returns {void}\n */\n function showForeignEditor () {\n const elt = selElems[0];\n if (!elt || editingforeign) { return; }\n editingforeign = true;\n toggleSourceButtons(true);\n elt.removeAttribute('fill');\n\n const str = svgCanvas.svgToString(elt, 0);\n $('#svg_source_textarea').val(str);\n $('#svg_source_editor').fadeIn();\n properlySourceSizeTextArea();\n $('#svg_source_textarea').focus();\n }\n\n /**\n * @param {string} attr\n * @param {string|Float} val\n * @returns {void}\n */\n function setAttr (attr, val) {\n svgCanvas.changeSelectedAttribute(attr, val);\n svgCanvas.call('changed', selElems);\n }\n\n const buttons = [{\n id: 'tool_foreign',\n icon: svgEditor.curConfig.extIconsPath + 'foreignobject-tool.png',\n type: 'mode',\n events: {\n click () {\n svgCanvas.setMode('foreign');\n }\n }\n }, {\n id: 'edit_foreign',\n icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png',\n type: 'context',\n panel: 'foreignObject_panel',\n events: {\n click () {\n showForeignEditor();\n }\n }\n }];\n\n const contextTools = [\n {\n type: 'input',\n panel: 'foreignObject_panel',\n id: 'foreign_width',\n size: 3,\n events: {\n change () {\n setAttr('width', this.value);\n }\n }\n }, {\n type: 'input',\n panel: 'foreignObject_panel',\n id: 'foreign_height',\n events: {\n change () {\n setAttr('height', this.value);\n }\n }\n }, {\n type: 'input',\n panel: 'foreignObject_panel',\n id: 'foreign_font_size',\n size: 2,\n defval: 16,\n events: {\n change () {\n setAttr('font-size', this.value);\n }\n }\n }\n ];\n\n return {\n name: strings.name,\n svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n context_tools: strings.contextTools.map((contextTool, i) => {\n return Object.assign(contextTools[i], contextTool);\n }),\n callback () {\n $('#foreignObject_panel').hide();\n\n const endChanges = function () {\n $('#svg_source_editor').hide();\n editingforeign = false;\n $('#svg_source_textarea').blur();\n toggleSourceButtons(false);\n };\n\n // TODO: Needs to be done after orig icon loads\n setTimeout(function () {\n // Create source save/cancel buttons\n /* const save = */ $('#tool_source_save').clone()\n .hide().attr('id', 'foreign_save').unbind()\n .appendTo('#tool_source_back').click(async function () {\n if (!editingforeign) { return; }\n\n if (!setForeignString($('#svg_source_textarea').val())) {\n const ok = await $.confirm('Errors found. Revert to original?');\n if (!ok) { return; }\n endChanges();\n } else {\n endChanges();\n }\n // setSelectMode();\n });\n\n /* const cancel = */ $('#tool_source_cancel').clone()\n .hide().attr('id', 'foreign_cancel').unbind()\n .appendTo('#tool_source_back').click(function () {\n endChanges();\n });\n }, 3000);\n },\n mouseDown (opts) {\n // const e = opts.event;\n if (svgCanvas.getMode() !== 'foreign') {\n return undefined;\n }\n started = true;\n newFO = svgCanvas.addSVGElementFromJson({\n element: 'foreignObject',\n attr: {\n x: opts.start_x,\n y: opts.start_y,\n id: svgCanvas.getNextId(),\n 'font-size': 16, // cur_text.font_size,\n width: '48',\n height: '20',\n style: 'pointer-events:inherit'\n }\n });\n const m = svgdoc.createElementNS(NS.MATH, 'math');\n m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH);\n m.setAttribute('display', 'inline');\n const mi = svgdoc.createElementNS(NS.MATH, 'mi');\n mi.setAttribute('mathvariant', 'normal');\n mi.textContent = '\\u03A6';\n const mo = svgdoc.createElementNS(NS.MATH, 'mo');\n mo.textContent = '\\u222A';\n const mi2 = svgdoc.createElementNS(NS.MATH, 'mi');\n mi2.textContent = '\\u2133';\n m.append(mi, mo, mi2);\n newFO.append(m);\n return {\n started: true\n };\n },\n mouseUp (opts) {\n // const e = opts.event;\n if (svgCanvas.getMode() !== 'foreign' || !started) {\n return undefined;\n }\n const attrs = $(newFO).attr(['width', 'height']);\n const keep = (attrs.width !== '0' || attrs.height !== '0');\n svgCanvas.addToSelection([newFO], true);\n\n return {\n keep,\n element: newFO\n };\n },\n selectedChanged (opts) {\n // Use this to update the current selected elements\n selElems = opts.elems;\n\n let i = selElems.length;\n while (i--) {\n const elem = selElems[i];\n if (elem && elem.tagName === 'foreignObject') {\n if (opts.selectedElement && !opts.multiselected) {\n $('#foreign_font_size').val(elem.getAttribute('font-size'));\n $('#foreign_width').val(elem.getAttribute('width'));\n $('#foreign_height').val(elem.getAttribute('height'));\n showPanel(true);\n } else {\n showPanel(false);\n }\n } else {\n showPanel(false);\n }\n }\n },\n elementChanged (opts) {\n // const elem = opts.elems[0];\n }\n };\n }\n};\n"],"names":["name","init","S","showPanel","toggleSourceButtons","setForeignString","showForeignEditor","setAttr","attr","val","svgCanvas","changeSelectedAttribute","call","selElems","elt","editingforeign","removeAttribute","str","svgToString","$","fadeIn","properlySourceSizeTextArea","focus","xmlString","newDoc","text2xml","NS","SVG","XLINK","sanitizeSvg","documentElement","replaceWith","svgdoc","importNode","firstChild","clearSelection","e","console","log","on","toggle","fcRules","length","appendTo","text","svgEditor","importLocale","canvas","svgroot","parentNode","ownerDocument","strings","height","css","buttons","id","icon","curConfig","extIconsPath","type","events","click","setMode","panel","contextTools","size","change","value","defval","svgicons","map","button","i","Object","assign","context_tools","contextTool","callback","hide","endChanges","blur","setTimeout","clone","unbind","confirm","ok","mouseDown","opts","getMode","undefined","started","newFO","addSVGElementFromJson","element","x","start_x","y","start_y","getNextId","width","style","m","createElementNS","MATH","setAttributeNS","XMLNS","setAttribute","mi","textContent","mo","mi2","append","mouseUp","attrs","keep","addToSelection","selectedChanged","elems","elem","tagName","selectedElement","multiselected","getAttribute","elementChanged"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yBAAe;;ACWf,uBAAe;AACbA,EAAAA,IAAI,EAAE,eADO;AAEPC,EAAAA,IAFO,gBAEDC,CAFC,EAEE;AAAA;;AAAA;AAAA,4GAoBJC,SApBI,EAiCJC,mBAjCI,4CAgDJC,gBAhDI,EAuEJC,iBAvEI,EA0FJC,OA1FI;AAAA;AAAA;AAAA;AAAA;AA0FJA,cAAAA,OA1FI,qBA0FKC,IA1FL,EA0FWC,GA1FX,EA0FgB;AAC3BC,gBAAAA,SAAS,CAACC,uBAAV,CAAkCH,IAAlC,EAAwCC,GAAxC;AACAC,gBAAAA,SAAS,CAACE,IAAV,CAAe,SAAf,EAA0BC,QAA1B;AACD,eA7FY;;AAuEJP,cAAAA,iBAvEI,iCAuEiB;AAC5B,oBAAMQ,GAAG,GAAGD,QAAQ,CAAC,CAAD,CAApB;;AACA,oBAAI,CAACC,GAAD,IAAQC,cAAZ,EAA4B;AAAE;AAAS;;AACvCA,gBAAAA,cAAc,GAAG,IAAjB;AACAX,gBAAAA,mBAAmB,CAAC,IAAD,CAAnB;AACAU,gBAAAA,GAAG,CAACE,eAAJ,CAAoB,MAApB;AAEA,oBAAMC,GAAG,GAAGP,SAAS,CAACQ,WAAV,CAAsBJ,GAAtB,EAA2B,CAA3B,CAAZ;AACAK,gBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0BV,GAA1B,CAA8BQ,GAA9B;AACAE,gBAAAA,CAAC,CAAC,oBAAD,CAAD,CAAwBC,MAAxB;AACAC,gBAAAA,0BAA0B;AAC1BF,gBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0BG,KAA1B;AACD,eAnFY;;AAgDJjB,cAAAA,gBAhDI,8BAgDckB,SAhDd,EAgDyB;AACpC,oBAAMT,GAAG,GAAGD,QAAQ,CAAC,CAAD,CAApB,CADoC;;AAEpC,oBAAI;AACF;AACA,sBAAMW,MAAM,GAAGC,QAAQ,CAAC,iBAAiBC,EAAE,CAACC,GAApB,GAA0B,iBAA1B,GAA8CD,EAAE,CAACE,KAAjD,GAAyD,IAAzD,GAAgEL,SAAhE,GAA4E,QAA7E,CAAvB,CAFE;;AAIFb,kBAAAA,SAAS,CAACmB,WAAV,CAAsBL,MAAM,CAACM,eAA7B;AACAhB,kBAAAA,GAAG,CAACiB,WAAJ,CAAgBC,MAAM,CAACC,UAAP,CAAkBT,MAAM,CAACM,eAAP,CAAuBI,UAAzC,EAAqD,IAArD,CAAhB;AACAxB,kBAAAA,SAAS,CAACE,IAAV,CAAe,SAAf,EAA0B,CAACE,GAAD,CAA1B;AACAJ,kBAAAA,SAAS,CAACyB,cAAV;AACD,iBARD,CAQE,OAAOC,CAAP,EAAU;AACV;AACAC,kBAAAA,OAAO,CAACC,GAAR,CAAYF,CAAZ,EAFU;;AAGV,yBAAO,KAAP;AACD;;AAED,uBAAO,IAAP;AACD,eAjEY;;AAiCJhC,cAAAA,mBAjCI,iCAiCiBmC,EAjCjB,EAiCqB;AAChCpB,gBAAAA,CAAC,CAAC,wCAAD,CAAD,CAA4CqB,MAA5C,CAAmD,CAACD,EAApD;AACApB,gBAAAA,CAAC,CAAC,gCAAD,CAAD,CAAoCqB,MAApC,CAA2CD,EAA3C;AACD,eApCY;;AAoBJpC,cAAAA,SApBI,uBAoBOoC,EApBP,EAoBW;AACtB,oBAAIE,OAAO,GAAGtB,CAAC,CAAC,WAAD,CAAf;;AACA,oBAAI,CAACsB,OAAO,CAACC,MAAb,EAAqB;AACnBD,kBAAAA,OAAO,GAAGtB,CAAC,CAAC,+BAAD,CAAD,CAAmCwB,QAAnC,CAA4C,MAA5C,CAAV;AACD;;AACDF,gBAAAA,OAAO,CAACG,IAAR,CAAa,CAACL,EAAD,GAAM,EAAN,GAAW,6CAAxB;AACApB,gBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0BqB,MAA1B,CAAiCD,EAAjC;AACD,eA3BY;;AACPM,cAAAA,SADO,GACK,KADL;AAEN1B,cAAAA,CAFM,GAE2BjB,CAF3B,CAENiB,CAFM,EAEHM,QAFG,GAE2BvB,CAF3B,CAEHuB,QAFG,EAEOC,EAFP,GAE2BxB,CAF3B,CAEOwB,EAFP,EAEWoB,YAFX,GAE2B5C,CAF3B,CAEW4C,YAFX;AAGPpC,cAAAA,SAHO,GAGKmC,SAAS,CAACE,MAHf;AAOXf,cAAAA,MAPW,GAOF9B,CAAC,CAAC8C,OAAF,CAAUC,UAAV,CAAqBC,aAPnB;AAAA;AAAA,qBAQSJ,YAAY,EARrB;;AAAA;AAQPK,cAAAA,OARO;;AAUP9B,cAAAA,0BAVO,GAUsB,SAA7BA,0BAA6B,GAAY;AAC7C;AACA,oBAAM+B,MAAM,GAAGjC,CAAC,CAAC,uBAAD,CAAD,CAA2BiC,MAA3B,KAAsC,EAArD;AACAjC,gBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0BkC,GAA1B,CAA8B,QAA9B,EAAwCD,MAAxC;AACD,eAdY;AAgBb;;;;;;AAyBErC,cAAAA,cAzCW,GAyCM,KAzCN;AA2Cb;;;;;;AAoDMuC,cAAAA,OA/FO,GA+FG,CAAC;AACfC,gBAAAA,EAAE,EAAE,cADW;AAEfC,gBAAAA,IAAI,EAAEX,SAAS,CAACY,SAAV,CAAoBC,YAApB,GAAmC,wBAF1B;AAGfC,gBAAAA,IAAI,EAAE,MAHS;AAIfC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPnD,oBAAAA,SAAS,CAACoD,OAAV,CAAkB,SAAlB;AACD;AAHK;AAJO,eAAD,EASb;AACDP,gBAAAA,EAAE,EAAE,cADH;AAEDC,gBAAAA,IAAI,EAAEX,SAAS,CAACY,SAAV,CAAoBC,YAApB,GAAmC,wBAFxC;AAGDC,gBAAAA,IAAI,EAAE,SAHL;AAIDI,gBAAAA,KAAK,EAAE,qBAJN;AAKDH,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPvD,oBAAAA,iBAAiB;AAClB;AAHK;AALP,eATa,CA/FH;AAoHP0D,cAAAA,YApHO,GAoHQ,CACnB;AACEL,gBAAAA,IAAI,EAAE,OADR;AAEEI,gBAAAA,KAAK,EAAE,qBAFT;AAGER,gBAAAA,EAAE,EAAE,eAHN;AAIEU,gBAAAA,IAAI,EAAE,CAJR;AAKEL,gBAAAA,MAAM,EAAE;AACNM,kBAAAA,MADM,oBACI;AACR3D,oBAAAA,OAAO,CAAC,OAAD,EAAU,KAAK4D,KAAf,CAAP;AACD;AAHK;AALV,eADmB,EAWhB;AACDR,gBAAAA,IAAI,EAAE,OADL;AAEDI,gBAAAA,KAAK,EAAE,qBAFN;AAGDR,gBAAAA,EAAE,EAAE,gBAHH;AAIDK,gBAAAA,MAAM,EAAE;AACNM,kBAAAA,MADM,oBACI;AACR3D,oBAAAA,OAAO,CAAC,QAAD,EAAW,KAAK4D,KAAhB,CAAP;AACD;AAHK;AAJP,eAXgB,EAoBhB;AACDR,gBAAAA,IAAI,EAAE,OADL;AAEDI,gBAAAA,KAAK,EAAE,qBAFN;AAGDR,gBAAAA,EAAE,EAAE,mBAHH;AAIDU,gBAAAA,IAAI,EAAE,CAJL;AAKDG,gBAAAA,MAAM,EAAE,EALP;AAMDR,gBAAAA,MAAM,EAAE;AACNM,kBAAAA,MADM,oBACI;AACR3D,oBAAAA,OAAO,CAAC,WAAD,EAAc,KAAK4D,KAAnB,CAAP;AACD;AAHK;AANP,eApBgB,CApHR;AAAA,gDAsJN;AACLnE,gBAAAA,IAAI,EAAEmD,OAAO,CAACnD,IADT;AAELqE,gBAAAA,QAAQ,EAAExB,SAAS,CAACY,SAAV,CAAoBC,YAApB,GAAmC,yBAFxC;AAGLJ,gBAAAA,OAAO,EAAEH,OAAO,CAACG,OAAR,CAAgBgB,GAAhB,CAAoB,UAACC,MAAD,EAASC,CAAT,EAAe;AAC1C,yBAAOC,MAAM,CAACC,MAAP,CAAcpB,OAAO,CAACkB,CAAD,CAArB,EAA0BD,MAA1B,CAAP;AACD,iBAFQ,CAHJ;AAMLI,gBAAAA,aAAa,EAAExB,OAAO,CAACa,YAAR,CAAqBM,GAArB,CAAyB,UAACM,WAAD,EAAcJ,CAAd,EAAoB;AAC1D,yBAAOC,MAAM,CAACC,MAAP,CAAcV,YAAY,CAACQ,CAAD,CAA1B,EAA+BI,WAA/B,CAAP;AACD,iBAFc,CANV;AASLC,gBAAAA,QATK,sBASO;AACV1D,kBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0B2D,IAA1B;;AAEA,sBAAMC,UAAU,GAAG,SAAbA,UAAa,GAAY;AAC7B5D,oBAAAA,CAAC,CAAC,oBAAD,CAAD,CAAwB2D,IAAxB;AACA/D,oBAAAA,cAAc,GAAG,KAAjB;AACAI,oBAAAA,CAAC,CAAC,sBAAD,CAAD,CAA0B6D,IAA1B;AACA5E,oBAAAA,mBAAmB,CAAC,KAAD,CAAnB;AACD,mBALD,CAHU;;;AAWV6E,kBAAAA,UAAU,CAAC,YAAY;AACrB;;AACA;AAAmB9D,oBAAAA,CAAC,CAAC,mBAAD,CAAD,CAAuB+D,KAAvB,GAChBJ,IADgB,GACTtE,IADS,CACJ,IADI,EACE,cADF,EACkB2E,MADlB,GAEhBxC,QAFgB,CAEP,mBAFO,EAEckB,KAFd,uEAEoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAC9B9C,cAD8B;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA,kCAG9BV,gBAAgB,CAACc,CAAC,CAAC,sBAAD,CAAD,CAA0BV,GAA1B,EAAD,CAHc;AAAA;AAAA;AAAA;;AAAA;AAAA,qCAIhBU,CAAC,CAACiE,OAAF,CAAU,mCAAV,CAJgB;;AAAA;AAI3BC,8BAAAA,EAJ2B;;AAAA,kCAK5BA,EAL4B;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAMjCN,8BAAAA,UAAU;AANuB;AAAA;;AAAA;AAQjCA,8BAAAA,UAAU;;AARuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAFpB;AAenB;;AAAqB5D,oBAAAA,CAAC,CAAC,qBAAD,CAAD,CAAyB+D,KAAzB,GAClBJ,IADkB,GACXtE,IADW,CACN,IADM,EACA,gBADA,EACkB2E,MADlB,GAElBxC,QAFkB,CAET,mBAFS,EAEYkB,KAFZ,CAEkB,YAAY;AAC/CkB,sBAAAA,UAAU;AACX,qBAJkB;AAKtB,mBAtBS,EAsBP,IAtBO,CAAV;AAuBD,iBA3CI;AA4CLO,gBAAAA,SA5CK,qBA4CMC,IA5CN,EA4CY;AACf;AACA,sBAAI7E,SAAS,CAAC8E,OAAV,OAAwB,SAA5B,EAAuC;AACrC,2BAAOC,SAAP;AACD;;AACDC,kBAAAA,OAAO,GAAG,IAAV;AACAC,kBAAAA,KAAK,GAAGjF,SAAS,CAACkF,qBAAV,CAAgC;AACtCC,oBAAAA,OAAO,EAAE,eAD6B;AAEtCrF,oBAAAA,IAAI,EAAE;AACJsF,sBAAAA,CAAC,EAAEP,IAAI,CAACQ,OADJ;AAEJC,sBAAAA,CAAC,EAAET,IAAI,CAACU,OAFJ;AAGJ1C,sBAAAA,EAAE,EAAE7C,SAAS,CAACwF,SAAV,EAHA;AAIJ,mCAAa,EAJT;AAIa;AACjBC,sBAAAA,KAAK,EAAE,IALH;AAMJ/C,sBAAAA,MAAM,EAAE,IANJ;AAOJgD,sBAAAA,KAAK,EAAE;AAPH;AAFgC,mBAAhC,CAAR;AAYA,sBAAMC,CAAC,GAAGrE,MAAM,CAACsE,eAAP,CAAuB5E,EAAE,CAAC6E,IAA1B,EAAgC,MAAhC,CAAV;AACAF,kBAAAA,CAAC,CAACG,cAAF,CAAiB9E,EAAE,CAAC+E,KAApB,EAA2B,OAA3B,EAAoC/E,EAAE,CAAC6E,IAAvC;AACAF,kBAAAA,CAAC,CAACK,YAAF,CAAe,SAAf,EAA0B,QAA1B;AACA,sBAAMC,EAAE,GAAG3E,MAAM,CAACsE,eAAP,CAAuB5E,EAAE,CAAC6E,IAA1B,EAAgC,IAAhC,CAAX;AACAI,kBAAAA,EAAE,CAACD,YAAH,CAAgB,aAAhB,EAA+B,QAA/B;AACAC,kBAAAA,EAAE,CAACC,WAAH,GAAiB,QAAjB;AACA,sBAAMC,EAAE,GAAG7E,MAAM,CAACsE,eAAP,CAAuB5E,EAAE,CAAC6E,IAA1B,EAAgC,IAAhC,CAAX;AACAM,kBAAAA,EAAE,CAACD,WAAH,GAAiB,QAAjB;AACA,sBAAME,GAAG,GAAG9E,MAAM,CAACsE,eAAP,CAAuB5E,EAAE,CAAC6E,IAA1B,EAAgC,IAAhC,CAAZ;AACAO,kBAAAA,GAAG,CAACF,WAAJ,GAAkB,QAAlB;AACAP,kBAAAA,CAAC,CAACU,MAAF,CAASJ,EAAT,EAAaE,EAAb,EAAiBC,GAAjB;AACAnB,kBAAAA,KAAK,CAACoB,MAAN,CAAaV,CAAb;AACA,yBAAO;AACLX,oBAAAA,OAAO,EAAE;AADJ,mBAAP;AAGD,iBA7EI;AA8ELsB,gBAAAA,OA9EK,mBA8EIzB,IA9EJ,EA8EU;AACb;AACA,sBAAI7E,SAAS,CAAC8E,OAAV,OAAwB,SAAxB,IAAqC,CAACE,OAA1C,EAAmD;AACjD,2BAAOD,SAAP;AACD;;AACD,sBAAMwB,KAAK,GAAG9F,CAAC,CAACwE,KAAD,CAAD,CAASnF,IAAT,CAAc,CAAC,OAAD,EAAU,QAAV,CAAd,CAAd;AACA,sBAAM0G,IAAI,GAAID,KAAK,CAACd,KAAN,KAAgB,GAAhB,IAAuBc,KAAK,CAAC7D,MAAN,KAAiB,GAAtD;AACA1C,kBAAAA,SAAS,CAACyG,cAAV,CAAyB,CAACxB,KAAD,CAAzB,EAAkC,IAAlC;AAEA,yBAAO;AACLuB,oBAAAA,IAAI,EAAJA,IADK;AAELrB,oBAAAA,OAAO,EAAEF;AAFJ,mBAAP;AAID,iBA3FI;AA4FLyB,gBAAAA,eA5FK,2BA4FY7B,IA5FZ,EA4FkB;AACrB;AACA1E,kBAAAA,QAAQ,GAAG0E,IAAI,CAAC8B,KAAhB;AAEA,sBAAI7C,CAAC,GAAG3D,QAAQ,CAAC6B,MAAjB;;AACA,yBAAO8B,CAAC,EAAR,EAAY;AACV,wBAAM8C,IAAI,GAAGzG,QAAQ,CAAC2D,CAAD,CAArB;;AACA,wBAAI8C,IAAI,IAAIA,IAAI,CAACC,OAAL,KAAiB,eAA7B,EAA8C;AAC5C,0BAAIhC,IAAI,CAACiC,eAAL,IAAwB,CAACjC,IAAI,CAACkC,aAAlC,EAAiD;AAC/CtG,wBAAAA,CAAC,CAAC,oBAAD,CAAD,CAAwBV,GAAxB,CAA4B6G,IAAI,CAACI,YAAL,CAAkB,WAAlB,CAA5B;AACAvG,wBAAAA,CAAC,CAAC,gBAAD,CAAD,CAAoBV,GAApB,CAAwB6G,IAAI,CAACI,YAAL,CAAkB,OAAlB,CAAxB;AACAvG,wBAAAA,CAAC,CAAC,iBAAD,CAAD,CAAqBV,GAArB,CAAyB6G,IAAI,CAACI,YAAL,CAAkB,QAAlB,CAAzB;AACAvH,wBAAAA,SAAS,CAAC,IAAD,CAAT;AACD,uBALD,MAKO;AACLA,wBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF,qBATD,MASO;AACLA,sBAAAA,SAAS,CAAC,KAAD,CAAT;AACD;AACF;AACF,iBAhHI;AAiHLwH,gBAAAA,cAjHK,0BAiHWpC,IAjHX,EAiHiB;AAErB;AAnHI,eAtJM;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2Qd;AA7QY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-grid.js b/dist/editor/extensions/ext-grid.js deleted file mode 100644 index 466b0490..00000000 --- a/dist/editor/extensions/ext-grid.js +++ /dev/null @@ -1,1824 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -var gridIcon = "grid-icon.xml"; - -var extGrid = { - name: 'grid', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - gridUpdate = function _gridUpdate() { - if (showGrid) { - updateGrid(svgCanvas.getZoom()); - } - - $('#canvasGrid').toggle(showGrid); - $('#view_grid').toggleClass('push_button_pressed tool_button'); - }; - - updateGrid = function _updateGrid(zoom) { - // TODO: Try this with elements, then compare performance difference - var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px - - var uMulti = unit * zoom; // Calculate the main number interval - - var rawM = 100 / uMulti; - var multi = 1; - intervals.some(function (num) { - multi = num; - return rawM <= num; - }); - var bigInt = multi * uMulti; // Set the canvas size to the width of the container - - hcanvas.width = bigInt; - hcanvas.height = bigInt; - var ctx = hcanvas.getContext('2d'); - var curD = 0.5; - var part = bigInt / 10; - ctx.globalAlpha = 0.2; - ctx.strokeStyle = svgEditor.curConfig.gridColor; - - for (var i = 1; i < 10; i++) { - var subD = Math.round(part * i) + 0.5; // const lineNum = (i % 2)?12:10; - - var lineNum = 0; - ctx.moveTo(subD, bigInt); - ctx.lineTo(subD, lineNum); - ctx.moveTo(bigInt, subD); - ctx.lineTo(lineNum, subD); - } - - ctx.stroke(); - ctx.beginPath(); - ctx.globalAlpha = 0.5; - ctx.moveTo(curD, bigInt); - ctx.lineTo(curD, 0); - ctx.moveTo(bigInt, curD); - ctx.lineTo(0, curD); - ctx.stroke(); - var datauri = hcanvas.toDataURL('image/png'); - gridimg.setAttribute('width', bigInt); - gridimg.setAttribute('height', bigInt); - gridimg.parentNode.setAttribute('width', bigInt); - gridimg.parentNode.setAttribute('height', bigInt); - svgCanvas.setHref(gridimg, datauri); - }; - - $ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale; - _context.next = 5; - return importLocale(); - - case 5: - strings = _context.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000]; - showGrid = svgEditor.curConfig.showGrid || false; - $(hcanvas).hide().appendTo('body'); - canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg'); - assignAttributes(canvasGrid, { - id: 'canvasGrid', - width: '100%', - height: '100%', - x: 0, - y: 0, - overflow: 'visible', - display: 'none' - }); - canvBG.append(canvasGrid); - gridDefs = svgdoc.createElementNS(NS.SVG, 'defs'); // grid-pattern - - gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern'); - assignAttributes(gridPattern, { - id: 'gridpattern', - patternUnits: 'userSpaceOnUse', - x: 0, - // -(value.strokeWidth / 2), // position for strokewidth - y: 0, - // -(value.strokeWidth / 2), // position for strokewidth - width: 100, - height: 100 - }); - gridimg = svgdoc.createElementNS(NS.SVG, 'image'); - assignAttributes(gridimg, { - x: 0, - y: 0, - width: 100, - height: 100 - }); - gridPattern.append(gridimg); - gridDefs.append(gridPattern); - $('#canvasGrid').append(gridDefs); // grid-box - - gridBox = svgdoc.createElementNS(NS.SVG, 'rect'); - assignAttributes(gridBox, { - width: '100%', - height: '100%', - x: 0, - y: 0, - 'stroke-width': 0, - stroke: 'none', - fill: 'url(#gridpattern)', - style: 'pointer-events: none; display:visible;' - }); - $('#canvasGrid').append(gridBox); - /** - * - * @param {Float} zoom - * @returns {void} - */ - - buttons = [{ - id: 'view_grid', - icon: svgEditor.curConfig.extIconsPath + 'grid.png', - type: 'context', - panel: 'editor_panel', - events: { - click: function click() { - svgEditor.curConfig.showGrid = showGrid = !showGrid; - gridUpdate(); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml', - zoomChanged: function zoomChanged(zoom) { - if (showGrid) { - updateGrid(zoom); - } - }, - callback: function callback() { - if (showGrid) { - gridUpdate(); - } - }, - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }) - }); - - case 27: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } -}; - -export default extGrid; -//# sourceMappingURL=ext-grid.js.map diff --git a/dist/editor/extensions/ext-grid.js.map b/dist/editor/extensions/ext-grid.js.map deleted file mode 100644 index 8774cf80..00000000 --- a/dist/editor/extensions/ext-grid.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-grid.js","sources":["../../../src/editor/extensions/grid-icon.xml","../../../src/editor/extensions/ext-grid.js"],"sourcesContent":["export default \"grid-icon.xml\"","/**\n * @file ext-grid.js\n *\n * @license Apache-2.0\n *\n * @copyright 2010 Redou Mine, 2010 Alexis Deveria\n *\n */\n\nimport './grid-icon.xml';\n\nexport default {\n name: 'grid',\n async init ({$, NS, getTypeMap, importLocale}) {\n const strings = await importLocale();\n const svgEditor = this;\n const svgCanvas = svgEditor.canvas;\n const svgdoc = document.getElementById('svgcanvas').ownerDocument,\n {assignAttributes} = svgCanvas,\n hcanvas = document.createElement('canvas'),\n canvBG = $('#canvasBackground'),\n units = getTypeMap(), // Assumes prior `init()` call on `units.js` module\n intervals = [0.01, 0.1, 1, 10, 100, 1000];\n let showGrid = svgEditor.curConfig.showGrid || false;\n\n $(hcanvas).hide().appendTo('body');\n\n const canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg');\n assignAttributes(canvasGrid, {\n id: 'canvasGrid',\n width: '100%',\n height: '100%',\n x: 0,\n y: 0,\n overflow: 'visible',\n display: 'none'\n });\n canvBG.append(canvasGrid);\n const gridDefs = svgdoc.createElementNS(NS.SVG, 'defs');\n // grid-pattern\n const gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern');\n assignAttributes(gridPattern, {\n id: 'gridpattern',\n patternUnits: 'userSpaceOnUse',\n x: 0, // -(value.strokeWidth / 2), // position for strokewidth\n y: 0, // -(value.strokeWidth / 2), // position for strokewidth\n width: 100,\n height: 100\n });\n\n const gridimg = svgdoc.createElementNS(NS.SVG, 'image');\n assignAttributes(gridimg, {\n x: 0,\n y: 0,\n width: 100,\n height: 100\n });\n gridPattern.append(gridimg);\n gridDefs.append(gridPattern);\n $('#canvasGrid').append(gridDefs);\n\n // grid-box\n const gridBox = svgdoc.createElementNS(NS.SVG, 'rect');\n assignAttributes(gridBox, {\n width: '100%',\n height: '100%',\n x: 0,\n y: 0,\n 'stroke-width': 0,\n stroke: 'none',\n fill: 'url(#gridpattern)',\n style: 'pointer-events: none; display:visible;'\n });\n $('#canvasGrid').append(gridBox);\n\n /**\n *\n * @param {Float} zoom\n * @returns {void}\n */\n function updateGrid (zoom) {\n // TODO: Try this with elements, then compare performance difference\n const unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px\n const uMulti = unit * zoom;\n // Calculate the main number interval\n const rawM = 100 / uMulti;\n let multi = 1;\n intervals.some((num) => {\n multi = num;\n return rawM <= num;\n });\n const bigInt = multi * uMulti;\n\n // Set the canvas size to the width of the container\n hcanvas.width = bigInt;\n hcanvas.height = bigInt;\n const ctx = hcanvas.getContext('2d');\n const curD = 0.5;\n const part = bigInt / 10;\n\n ctx.globalAlpha = 0.2;\n ctx.strokeStyle = svgEditor.curConfig.gridColor;\n for (let i = 1; i < 10; i++) {\n const subD = Math.round(part * i) + 0.5;\n // const lineNum = (i % 2)?12:10;\n const lineNum = 0;\n ctx.moveTo(subD, bigInt);\n ctx.lineTo(subD, lineNum);\n ctx.moveTo(bigInt, subD);\n ctx.lineTo(lineNum, subD);\n }\n ctx.stroke();\n ctx.beginPath();\n ctx.globalAlpha = 0.5;\n ctx.moveTo(curD, bigInt);\n ctx.lineTo(curD, 0);\n\n ctx.moveTo(bigInt, curD);\n ctx.lineTo(0, curD);\n ctx.stroke();\n\n const datauri = hcanvas.toDataURL('image/png');\n gridimg.setAttribute('width', bigInt);\n gridimg.setAttribute('height', bigInt);\n gridimg.parentNode.setAttribute('width', bigInt);\n gridimg.parentNode.setAttribute('height', bigInt);\n svgCanvas.setHref(gridimg, datauri);\n }\n\n /**\n *\n * @returns {void}\n */\n function gridUpdate () {\n if (showGrid) {\n updateGrid(svgCanvas.getZoom());\n }\n $('#canvasGrid').toggle(showGrid);\n $('#view_grid').toggleClass('push_button_pressed tool_button');\n }\n const buttons = [{\n id: 'view_grid',\n icon: svgEditor.curConfig.extIconsPath + 'grid.png',\n type: 'context',\n panel: 'editor_panel',\n events: {\n click () {\n svgEditor.curConfig.showGrid = showGrid = !showGrid;\n gridUpdate();\n }\n }\n }];\n return {\n name: strings.name,\n svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml',\n\n zoomChanged (zoom) {\n if (showGrid) { updateGrid(zoom); }\n },\n callback () {\n if (showGrid) {\n gridUpdate();\n }\n },\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n })\n };\n }\n};\n"],"names":["name","init","updateGrid","gridUpdate","showGrid","svgCanvas","getZoom","$","toggle","toggleClass","zoom","unit","units","svgEditor","curConfig","baseUnit","uMulti","rawM","multi","intervals","some","num","bigInt","hcanvas","width","height","ctx","getContext","curD","part","globalAlpha","strokeStyle","gridColor","i","subD","Math","round","lineNum","moveTo","lineTo","stroke","beginPath","datauri","toDataURL","gridimg","setAttribute","parentNode","setHref","NS","getTypeMap","importLocale","strings","canvas","svgdoc","document","getElementById","ownerDocument","assignAttributes","createElement","canvBG","hide","appendTo","canvasGrid","createElementNS","SVG","id","x","y","overflow","display","append","gridDefs","gridPattern","patternUnits","gridBox","fill","style","buttons","icon","extIconsPath","type","panel","events","click","svgicons","zoomChanged","callback","map","button","Object","assign"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,eAAe;;ACWf,cAAe;AACbA,EAAAA,IAAI,EAAE,MADO;AAEPC,EAAAA,IAFO,sBAEkC;AAAA;;AAAA;AAAA,sMAmEpCC,UAnEoC,EAwHpCC,UAxHoC;AAAA;AAAA;AAAA;AAAA;AAwHpCA,cAAAA,UAxHoC,0BAwHtB;AACrB,oBAAIC,QAAJ,EAAc;AACZF,kBAAAA,UAAU,CAACG,SAAS,CAACC,OAAV,EAAD,CAAV;AACD;;AACDC,gBAAAA,CAAC,CAAC,aAAD,CAAD,CAAiBC,MAAjB,CAAwBJ,QAAxB;AACAG,gBAAAA,CAAC,CAAC,YAAD,CAAD,CAAgBE,WAAhB,CAA4B,iCAA5B;AACD,eA9H4C;;AAmEpCP,cAAAA,UAnEoC,wBAmExBQ,IAnEwB,EAmElB;AACzB;AACA,oBAAMC,IAAI,GAAGC,KAAK,CAACC,SAAS,CAACC,SAAV,CAAoBC,QAArB,CAAlB,CAFyB;;AAGzB,oBAAMC,MAAM,GAAGL,IAAI,GAAGD,IAAtB,CAHyB;;AAKzB,oBAAMO,IAAI,GAAG,MAAMD,MAAnB;AACA,oBAAIE,KAAK,GAAG,CAAZ;AACAC,gBAAAA,SAAS,CAACC,IAAV,CAAe,UAACC,GAAD,EAAS;AACtBH,kBAAAA,KAAK,GAAGG,GAAR;AACA,yBAAOJ,IAAI,IAAII,GAAf;AACD,iBAHD;AAIA,oBAAMC,MAAM,GAAGJ,KAAK,GAAGF,MAAvB,CAXyB;;AAczBO,gBAAAA,OAAO,CAACC,KAAR,GAAgBF,MAAhB;AACAC,gBAAAA,OAAO,CAACE,MAAR,GAAiBH,MAAjB;AACA,oBAAMI,GAAG,GAAGH,OAAO,CAACI,UAAR,CAAmB,IAAnB,CAAZ;AACA,oBAAMC,IAAI,GAAG,GAAb;AACA,oBAAMC,IAAI,GAAGP,MAAM,GAAG,EAAtB;AAEAI,gBAAAA,GAAG,CAACI,WAAJ,GAAkB,GAAlB;AACAJ,gBAAAA,GAAG,CAACK,WAAJ,GAAkBlB,SAAS,CAACC,SAAV,CAAoBkB,SAAtC;;AACA,qBAAK,IAAIC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG,EAApB,EAAwBA,CAAC,EAAzB,EAA6B;AAC3B,sBAAMC,IAAI,GAAGC,IAAI,CAACC,KAAL,CAAWP,IAAI,GAAGI,CAAlB,IAAuB,GAApC,CAD2B;;AAG3B,sBAAMI,OAAO,GAAG,CAAhB;AACAX,kBAAAA,GAAG,CAACY,MAAJ,CAAWJ,IAAX,EAAiBZ,MAAjB;AACAI,kBAAAA,GAAG,CAACa,MAAJ,CAAWL,IAAX,EAAiBG,OAAjB;AACAX,kBAAAA,GAAG,CAACY,MAAJ,CAAWhB,MAAX,EAAmBY,IAAnB;AACAR,kBAAAA,GAAG,CAACa,MAAJ,CAAWF,OAAX,EAAoBH,IAApB;AACD;;AACDR,gBAAAA,GAAG,CAACc,MAAJ;AACAd,gBAAAA,GAAG,CAACe,SAAJ;AACAf,gBAAAA,GAAG,CAACI,WAAJ,GAAkB,GAAlB;AACAJ,gBAAAA,GAAG,CAACY,MAAJ,CAAWV,IAAX,EAAiBN,MAAjB;AACAI,gBAAAA,GAAG,CAACa,MAAJ,CAAWX,IAAX,EAAiB,CAAjB;AAEAF,gBAAAA,GAAG,CAACY,MAAJ,CAAWhB,MAAX,EAAmBM,IAAnB;AACAF,gBAAAA,GAAG,CAACa,MAAJ,CAAW,CAAX,EAAcX,IAAd;AACAF,gBAAAA,GAAG,CAACc,MAAJ;AAEA,oBAAME,OAAO,GAAGnB,OAAO,CAACoB,SAAR,CAAkB,WAAlB,CAAhB;AACAC,gBAAAA,OAAO,CAACC,YAAR,CAAqB,OAArB,EAA8BvB,MAA9B;AACAsB,gBAAAA,OAAO,CAACC,YAAR,CAAqB,QAArB,EAA+BvB,MAA/B;AACAsB,gBAAAA,OAAO,CAACE,UAAR,CAAmBD,YAAnB,CAAgC,OAAhC,EAAyCvB,MAAzC;AACAsB,gBAAAA,OAAO,CAACE,UAAR,CAAmBD,YAAnB,CAAgC,QAAhC,EAA0CvB,MAA1C;AACAjB,gBAAAA,SAAS,CAAC0C,OAAV,CAAkBH,OAAlB,EAA2BF,OAA3B;AACD,eAlH4C;;AAAlCnC,cAAAA,CAAkC,QAAlCA,CAAkC,EAA/ByC,EAA+B,QAA/BA,EAA+B,EAA3BC,UAA2B,QAA3BA,UAA2B,EAAfC,YAAe,QAAfA,YAAe;AAAA;AAAA,qBACvBA,YAAY,EADW;;AAAA;AACvCC,cAAAA,OADuC;AAEvCtC,cAAAA,SAFuC,GAE3B,KAF2B;AAGvCR,cAAAA,SAHuC,GAG3BQ,SAAS,CAACuC,MAHiB;AAIvCC,cAAAA,MAJuC,GAI9BC,QAAQ,CAACC,cAAT,CAAwB,WAAxB,EAAqCC,aAJP,EAK1CC,gBAL0C,GAKtBpD,SALsB,CAK1CoD,gBAL0C,EAM3ClC,OAN2C,GAMjC+B,QAAQ,CAACI,aAAT,CAAuB,QAAvB,CANiC,EAO3CC,MAP2C,GAOlCpD,CAAC,CAAC,mBAAD,CAPiC,EAQ3CK,KAR2C,GAQnCqC,UAAU,EARyB,EAS3C9B,SAT2C,GAS/B,CAAC,IAAD,EAAO,GAAP,EAAY,CAAZ,EAAe,EAAf,EAAmB,GAAnB,EAAwB,IAAxB,CAT+B;AAUzCf,cAAAA,QAVyC,GAU9BS,SAAS,CAACC,SAAV,CAAoBV,QAApB,IAAgC,KAVF;AAY7CG,cAAAA,CAAC,CAACgB,OAAD,CAAD,CAAWqC,IAAX,GAAkBC,QAAlB,CAA2B,MAA3B;AAEMC,cAAAA,UAduC,GAc1BT,MAAM,CAACU,eAAP,CAAuBf,EAAE,CAACgB,GAA1B,EAA+B,KAA/B,CAd0B;AAe7CP,cAAAA,gBAAgB,CAACK,UAAD,EAAa;AAC3BG,gBAAAA,EAAE,EAAE,YADuB;AAE3BzC,gBAAAA,KAAK,EAAE,MAFoB;AAG3BC,gBAAAA,MAAM,EAAE,MAHmB;AAI3ByC,gBAAAA,CAAC,EAAE,CAJwB;AAK3BC,gBAAAA,CAAC,EAAE,CALwB;AAM3BC,gBAAAA,QAAQ,EAAE,SANiB;AAO3BC,gBAAAA,OAAO,EAAE;AAPkB,eAAb,CAAhB;AASAV,cAAAA,MAAM,CAACW,MAAP,CAAcR,UAAd;AACMS,cAAAA,QAzBuC,GAyB5BlB,MAAM,CAACU,eAAP,CAAuBf,EAAE,CAACgB,GAA1B,EAA+B,MAA/B,CAzB4B;;AA2BvCQ,cAAAA,WA3BuC,GA2BzBnB,MAAM,CAACU,eAAP,CAAuBf,EAAE,CAACgB,GAA1B,EAA+B,SAA/B,CA3ByB;AA4B7CP,cAAAA,gBAAgB,CAACe,WAAD,EAAc;AAC5BP,gBAAAA,EAAE,EAAE,aADwB;AAE5BQ,gBAAAA,YAAY,EAAE,gBAFc;AAG5BP,gBAAAA,CAAC,EAAE,CAHyB;AAGtB;AACNC,gBAAAA,CAAC,EAAE,CAJyB;AAItB;AACN3C,gBAAAA,KAAK,EAAE,GALqB;AAM5BC,gBAAAA,MAAM,EAAE;AANoB,eAAd,CAAhB;AASMmB,cAAAA,OArCuC,GAqC7BS,MAAM,CAACU,eAAP,CAAuBf,EAAE,CAACgB,GAA1B,EAA+B,OAA/B,CArC6B;AAsC7CP,cAAAA,gBAAgB,CAACb,OAAD,EAAU;AACxBsB,gBAAAA,CAAC,EAAE,CADqB;AAExBC,gBAAAA,CAAC,EAAE,CAFqB;AAGxB3C,gBAAAA,KAAK,EAAE,GAHiB;AAIxBC,gBAAAA,MAAM,EAAE;AAJgB,eAAV,CAAhB;AAMA+C,cAAAA,WAAW,CAACF,MAAZ,CAAmB1B,OAAnB;AACA2B,cAAAA,QAAQ,CAACD,MAAT,CAAgBE,WAAhB;AACAjE,cAAAA,CAAC,CAAC,aAAD,CAAD,CAAiB+D,MAAjB,CAAwBC,QAAxB,EA9C6C;;AAiDvCG,cAAAA,OAjDuC,GAiD7BrB,MAAM,CAACU,eAAP,CAAuBf,EAAE,CAACgB,GAA1B,EAA+B,MAA/B,CAjD6B;AAkD7CP,cAAAA,gBAAgB,CAACiB,OAAD,EAAU;AACxBlD,gBAAAA,KAAK,EAAE,MADiB;AAExBC,gBAAAA,MAAM,EAAE,MAFgB;AAGxByC,gBAAAA,CAAC,EAAE,CAHqB;AAIxBC,gBAAAA,CAAC,EAAE,CAJqB;AAKxB,gCAAgB,CALQ;AAMxB3B,gBAAAA,MAAM,EAAE,MANgB;AAOxBmC,gBAAAA,IAAI,EAAE,mBAPkB;AAQxBC,gBAAAA,KAAK,EAAE;AARiB,eAAV,CAAhB;AAUArE,cAAAA,CAAC,CAAC,aAAD,CAAD,CAAiB+D,MAAjB,CAAwBI,OAAxB;AAEA;;;;;;AAiEMG,cAAAA,OA/HuC,GA+H7B,CAAC;AACfZ,gBAAAA,EAAE,EAAE,WADW;AAEfa,gBAAAA,IAAI,EAAEjE,SAAS,CAACC,SAAV,CAAoBiE,YAApB,GAAmC,UAF1B;AAGfC,gBAAAA,IAAI,EAAE,SAHS;AAIfC,gBAAAA,KAAK,EAAE,cAJQ;AAKfC,gBAAAA,MAAM,EAAE;AACNC,kBAAAA,KADM,mBACG;AACPtE,oBAAAA,SAAS,CAACC,SAAV,CAAoBV,QAApB,GAA+BA,QAAQ,GAAG,CAACA,QAA3C;AACAD,oBAAAA,UAAU;AACX;AAJK;AALO,eAAD,CA/H6B;AAAA,+CA2ItC;AACLH,gBAAAA,IAAI,EAAEmD,OAAO,CAACnD,IADT;AAELoF,gBAAAA,QAAQ,EAAEvE,SAAS,CAACC,SAAV,CAAoBiE,YAApB,GAAmC,eAFxC;AAILM,gBAAAA,WAJK,uBAIQ3E,IAJR,EAIc;AACjB,sBAAIN,QAAJ,EAAc;AAAEF,oBAAAA,UAAU,CAACQ,IAAD,CAAV;AAAmB;AACpC,iBANI;AAOL4E,gBAAAA,QAPK,sBAOO;AACV,sBAAIlF,QAAJ,EAAc;AACZD,oBAAAA,UAAU;AACX;AACF,iBAXI;AAYL0E,gBAAAA,OAAO,EAAE1B,OAAO,CAAC0B,OAAR,CAAgBU,GAAhB,CAAoB,UAACC,MAAD,EAASvD,CAAT,EAAe;AAC1C,yBAAOwD,MAAM,CAACC,MAAP,CAAcb,OAAO,CAAC5C,CAAD,CAArB,EAA0BuD,MAA1B,CAAP;AACD,iBAFQ;AAZJ,eA3IsC;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2J9C;AA7JY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-helloworld.js b/dist/editor/extensions/ext-helloworld.js deleted file mode 100644 index b9db0587..00000000 --- a/dist/editor/extensions/ext-helloworld.js +++ /dev/null @@ -1,1757 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -/** - * @file ext-helloworld.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ - -/** -* This is a very basic SVG-Edit extension. It adds a "Hello World" button in -* the left ("mode") panel. Clicking on the button, and then the canvas -* will show the user the point on the canvas that was clicked on. -*/ -var extHelloworld = { - name: 'helloworld', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var $, importLocale, strings, svgEditor, svgCanvas; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - $ = _ref.$, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - return _context.abrupt("return", { - name: strings.name, - // For more notes on how to make an icon file, see the source of - // the helloworld-icon.xml - svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', - // Multiple buttons can be added in this array - buttons: [{ - // Must match the icon ID in helloworld-icon.xml - id: 'hello_world', - // Fallback, e.g., for `file:///` access - icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', - // This indicates that the button will be added to the "mode" - // button panel on the left side - type: 'mode', - // Tooltip text - title: strings.buttons[0].title, - // Events - events: { - click: function click() { - // The action taken when the button is clicked on. - // For "mode" buttons, any other button will - // automatically be de-pressed. - svgCanvas.setMode('hello_world'); - } - } - }], - // This is triggered when the main mouse button is pressed down - // on the editor canvas (not the tool panels) - mouseDown: function mouseDown() { - // Check the mode on mousedown - if (svgCanvas.getMode() === 'hello_world') { - // The returned object must include "started" with - // a value of true in order for mouseUp to be triggered - return { - started: true - }; - } - - return undefined; - }, - // This is triggered from anywhere, but "started" must have been set - // to true (see above). Note that "opts" is an object with event info - mouseUp: function mouseUp(opts) { - // Check the mode on mouseup - if (svgCanvas.getMode() === 'hello_world') { - var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value - - var x = opts.mouse_x / zoom; - var y = opts.mouse_y / zoom; // We do our own formatting - - var text = strings.text; - [['x', x], ['y', y]].forEach(function (_ref2) { - var _ref3 = _slicedToArray(_ref2, 2), - prop = _ref3[0], - val = _ref3[1]; - - text = text.replace('{' + prop + '}', val); - }); // Show the text using the custom alert function - - $.alert(text); - } - } - }); - - case 7: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } -}; - -export default extHelloworld; -//# sourceMappingURL=ext-helloworld.js.map diff --git a/dist/editor/extensions/ext-helloworld.js.map b/dist/editor/extensions/ext-helloworld.js.map deleted file mode 100644 index 4b7881b5..00000000 --- a/dist/editor/extensions/ext-helloworld.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ext-helloworld.js","sources":["../../../src/editor/extensions/ext-helloworld.js"],"sourcesContent":["/**\n * @file ext-helloworld.js\n *\n * @license MIT\n *\n * @copyright 2010 Alexis Deveria\n *\n */\n\n/**\n* This is a very basic SVG-Edit extension. It adds a \"Hello World\" button in\n* the left (\"mode\") panel. Clicking on the button, and then the canvas\n* will show the user the point on the canvas that was clicked on.\n*/\nexport default {\n name: 'helloworld',\n async init ({$, importLocale}) {\n // See `/editor/extensions/ext-locale/helloworld/`\n const strings = await importLocale();\n const svgEditor = this;\n const svgCanvas = svgEditor.canvas;\n return {\n name: strings.name,\n // For more notes on how to make an icon file, see the source of\n // the helloworld-icon.xml\n svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml',\n\n // Multiple buttons can be added in this array\n buttons: [{\n // Must match the icon ID in helloworld-icon.xml\n id: 'hello_world',\n\n // Fallback, e.g., for `file:///` access\n icon: svgEditor.curConfig.extIconsPath + 'helloworld.png',\n\n // This indicates that the button will be added to the \"mode\"\n // button panel on the left side\n type: 'mode',\n\n // Tooltip text\n title: strings.buttons[0].title,\n\n // Events\n events: {\n click () {\n // The action taken when the button is clicked on.\n // For \"mode\" buttons, any other button will\n // automatically be de-pressed.\n svgCanvas.setMode('hello_world');\n }\n }\n }],\n // This is triggered when the main mouse button is pressed down\n // on the editor canvas (not the tool panels)\n mouseDown () {\n // Check the mode on mousedown\n if (svgCanvas.getMode() === 'hello_world') {\n // The returned object must include \"started\" with\n // a value of true in order for mouseUp to be triggered\n return {started: true};\n }\n return undefined;\n },\n\n // This is triggered from anywhere, but \"started\" must have been set\n // to true (see above). Note that \"opts\" is an object with event info\n mouseUp (opts) {\n // Check the mode on mouseup\n if (svgCanvas.getMode() === 'hello_world') {\n const zoom = svgCanvas.getZoom();\n\n // Get the actual coordinate by dividing by the zoom value\n const x = opts.mouse_x / zoom;\n const y = opts.mouse_y / zoom;\n\n // We do our own formatting\n let {text} = strings;\n [\n ['x', x],\n ['y', y]\n ].forEach(([prop, val]) => {\n text = text.replace('{' + prop + '}', val);\n });\n\n // Show the text using the custom alert function\n $.alert(text);\n }\n }\n };\n }\n};\n"],"names":["name","init","$","importLocale","strings","svgEditor","svgCanvas","canvas","svgicons","curConfig","extIconsPath","buttons","id","icon","type","title","events","click","setMode","mouseDown","getMode","started","undefined","mouseUp","opts","zoom","getZoom","x","mouse_x","y","mouse_y","text","forEach","prop","val","replace","alert"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;AASA;;;;;AAKA,oBAAe;AACbA,EAAAA,IAAI,EAAE,YADO;AAEPC,EAAAA,IAFO,sBAEkB;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAlBC,cAAAA,CAAkB,QAAlBA,CAAkB,EAAfC,YAAe,QAAfA,YAAe;AAAA;AAAA,qBAEPA,YAAY,EAFL;;AAAA;AAEvBC,cAAAA,OAFuB;AAGvBC,cAAAA,SAHuB,GAGX,KAHW;AAIvBC,cAAAA,SAJuB,GAIXD,SAAS,CAACE,MAJC;AAAA,+CAKtB;AACLP,gBAAAA,IAAI,EAAEI,OAAO,CAACJ,IADT;AAEL;AACA;AACAQ,gBAAAA,QAAQ,EAAEH,SAAS,CAACI,SAAV,CAAoBC,YAApB,GAAmC,qBAJxC;AAML;AACAC,gBAAAA,OAAO,EAAE,CAAC;AACR;AACAC,kBAAAA,EAAE,EAAE,aAFI;AAIR;AACAC,kBAAAA,IAAI,EAAER,SAAS,CAACI,SAAV,CAAoBC,YAApB,GAAmC,gBALjC;AAOR;AACA;AACAI,kBAAAA,IAAI,EAAE,MATE;AAWR;AACAC,kBAAAA,KAAK,EAAEX,OAAO,CAACO,OAAR,CAAgB,CAAhB,EAAmBI,KAZlB;AAcR;AACAC,kBAAAA,MAAM,EAAE;AACNC,oBAAAA,KADM,mBACG;AACP;AACA;AACA;AACAX,sBAAAA,SAAS,CAACY,OAAV,CAAkB,aAAlB;AACD;AANK;AAfA,iBAAD,CAPJ;AA+BL;AACA;AACAC,gBAAAA,SAjCK,uBAiCQ;AACX;AACA,sBAAIb,SAAS,CAACc,OAAV,OAAwB,aAA5B,EAA2C;AACzC;AACA;AACA,2BAAO;AAACC,sBAAAA,OAAO,EAAE;AAAV,qBAAP;AACD;;AACD,yBAAOC,SAAP;AACD,iBAzCI;AA2CL;AACA;AACAC,gBAAAA,OA7CK,mBA6CIC,IA7CJ,EA6CU;AACb;AACA,sBAAIlB,SAAS,CAACc,OAAV,OAAwB,aAA5B,EAA2C;AACzC,wBAAMK,IAAI,GAAGnB,SAAS,CAACoB,OAAV,EAAb,CADyC;;AAIzC,wBAAMC,CAAC,GAAGH,IAAI,CAACI,OAAL,GAAeH,IAAzB;AACA,wBAAMI,CAAC,GAAGL,IAAI,CAACM,OAAL,GAAeL,IAAzB,CALyC;;AAAA,wBAQpCM,IARoC,GAQ5B3B,OAR4B,CAQpC2B,IARoC;AASzC,qBACE,CAAC,GAAD,EAAMJ,CAAN,CADF,EAEE,CAAC,GAAD,EAAME,CAAN,CAFF,EAGEG,OAHF,CAGU,iBAAiB;AAAA;AAAA,0BAAfC,IAAe;AAAA,0BAATC,GAAS;;AACzBH,sBAAAA,IAAI,GAAGA,IAAI,CAACI,OAAL,CAAa,MAAMF,IAAN,GAAa,GAA1B,EAA+BC,GAA/B,CAAP;AACD,qBALD,EATyC;;AAiBzChC,oBAAAA,CAAC,CAACkC,KAAF,CAAQL,IAAR;AACD;AACF;AAlEI,eALsB;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyE9B;AA3EY,CAAf;;;;"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-imagelib.js b/dist/editor/extensions/ext-imagelib.js deleted file mode 100644 index 2d654e3b..00000000 --- a/dist/editor/extensions/ext-imagelib.js +++ /dev/null @@ -1,2170 +0,0 @@ -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); -} - -var REACT_ELEMENT_TYPE; - -function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; -} - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; -} - -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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; -} - -function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -} - -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -} - -function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); -} - -function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; -} - -function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); -} - -function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); -} - -function _temporalUndefined() {} - -function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); -} - -function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); -} - -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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; -} - -function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; -} - -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); -} - -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); -} - -function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); -} - -function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); -} - -function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -var id = 0; - -function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; -} - -function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; -} - -function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } -} - -function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; -} - -function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; -} - -function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; -} - -function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); -} - -function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); -} - -function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; -} - -function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; -} - -function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } -} - -function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; -} - -function _hasDecorators(element) { - return element.decorators && element.decorators.length; -} - -function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); -} - -function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; -} - -function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; -} - -function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); -} - -function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); -} - -var extImagelib = "ext-imagelib.xml"; - -var extImagelib$1 = { - name: 'imagelib', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, onMessage, _onMessage, toggleMulti, showBrowser, buttons; - - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - showBrowser = function _showBrowser() { - var browser = $('#imgbrowse'); - - if (!browser.length) { - $('
' + '
').insertAfter('#svg_docprops'); - browser = $('#imgbrowse'); - var allLibs = imagelibStrings.select_lib; - var libOpts = $('
    ').appendTo(browser); - var frame = $('', - 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: "<>" - }), 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 = "<>", f.content = i; - var g = f.objId + " 0 R"; - i = "<>";else if (n.options.pageNumber) { - switch (i = "<= 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 <>"); - }), 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 - * Chris G Jones - * Shaon Barman - * Vivien Nicolas <21@vingtetun.org> - * Justin D'Arcangelo - * 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 , 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 = '', - e = unescape(encodeURIComponent('')), - n = unescape(encodeURIComponent(t)), - r = unescape(encodeURIComponent(this.internal.__metadata__.metadata)), - i = unescape(encodeURIComponent("")), - a = unescape(encodeURIComponent("")), - 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>\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("<>"), 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 - * - * 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) { - // 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 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 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); -}; - -/** - * @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 - }; - } - - var canvg; - /** - * @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, - _yield$import$default, - 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 (canvg) { - _context2.next = 10; - break; - } - - _context2.next = 8; - return import(curConfig.canvgPath + 'canvg.js')["default"]; - - case 8: - _yield$import$default = _context2.sent; - canvg = _yield$import$default.canvg; - - case 10: - 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 = 16; - return canvg(c, svg); - - case 16: - 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 17: - 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$1 = 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$1(name)) name = 'xy'; - - switch (name.toLowerCase()) { - case 'x': - return x; - - case 'y': - return y; - - case 'xy': - default: - return { - x: x, - y: y - }; - } - } - - if (!isNullish$1(context) && context === that) return undefined; - var changed = false; - var newX, newY; - if (isNullish$1(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$1(newX)) { - if (newX < minX) newX = minX;else if (newX > maxX) newX = maxX; - - if (x !== newX) { - x = newX; - changed = true; - } - } - - if (!isNullish$1(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$1(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$1(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$1(newMinX) && minX !== newMinX) { - minX = newMinX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMaxX) && maxX !== newMaxX) { - maxX = newMaxX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMinY) && minY !== newMinY) { - minY = newMinY; - rangeY = maxY - minY; - } - - if (!isNullish$1(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$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(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$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(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$1(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$1(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$1(all) ? all.r : ''); - if (context !== green.get(0)) green.val(!isNullish$1(all) ? all.g : ''); - if (context !== blue.get(0)) blue.val(!isNullish$1(all) ? all.b : ''); - if (alpha && context !== alpha.get(0)) alpha.val(!isNullish$1(all) ? toFixedNumeric(all.a * 100 / 255, alphaPrecision) : ''); - if (context !== hue.get(0)) hue.val(!isNullish$1(all) ? all.h : ''); - if (context !== saturation.get(0)) saturation.val(!isNullish$1(all) ? all.s : ''); - if (context !== value.get(0)) value.val(!isNullish$1(all) ? all.v : ''); - if (context !== hex.get(0) && (bindedHex && context !== bindedHex.get(0) || !bindedHex)) hex.val(!isNullish$1(all) ? all.hex : ''); - if (bindedHex && context !== bindedHex.get(0) && context !== hex.get(0)) bindedHex.val(!isNullish$1(all) ? all.hex : ''); - if (ahex && context !== ahex.get(0)) ahex.val(!isNullish$1(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$1(name) || name === '') name = 'all'; - if (isNullish$1(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$1(context) && context === that) return undefined; - if (isNullish$1(name)) name = ''; - var changed = false; - - if (isNullish$1(value)) { - if (!isNullish$1(r)) { - r = null; - changed = true; - } - - if (!isNullish$1(g)) { - g = null; - changed = true; - } - - if (!isNullish$1(b)) { - b = null; - changed = true; - } - - if (!isNullish$1(a)) { - a = null; - changed = true; - } - - if (!isNullish$1(h)) { - h = null; - changed = true; - } - - if (!isNullish$1(s)) { - s = null; - changed = true; - } - - if (!isNullish$1(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$1(a) ? a : 255 - }, context); - break; - } - - default: - { - if (value && (!isNullish$1(value.ahex) || !isNullish$1(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$1(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$1(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$1(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$1(s) ? s : 100; - v = !isNullish$1(v) ? v : 100; - - var _ret3 = ColorMethods.hsvToRgb({ - h: h, - s: s, - v: v - }); - - r = _ret3.r; - g = _ret3.g; - b = _ret3.b; - } - - a = !isNullish$1(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$1(init.ahex)) { - val('ahex', init); - } else if (!isNullish$1(init.hex)) { - val((!isNullish$1(init.a) ? 'a' : '') + 'hex', !isNullish$1(init.a) ? { - ahex: init.hex + ColorMethods.intToHex(init.a) - } : init); - } else if (!isNullish$1(init.r) && !isNullish$1(init.g) && !isNullish$1(init.b)) { - val('rgb' + (!isNullish$1(init.a) ? 'a' : ''), init); - } else if (!isNullish$1(init.h) && !isNullish$1(init.s) && !isNullish$1(init.v)) { - val('hsv' + (!isNullish$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(sv) ? sv.s : 100, - y: 100 - (!isNullish$1(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$1(hv) ? hv.v : 100) - }, context); - break; - } - - case 'v': - { - var hs = ui.val('hs'); - colorMap.val('xy', { - x: hs && hs.h || 0, - y: 100 - (!isNullish$1(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$1(s) ? s : 100), context); - break; - } - - case 'v': - { - var v = ui.val('v'); - colorBar.val('y', 100 - (!isNullish$1(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$1(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$1(s) ? s : 100)); - break; - } - - case 'v': - { - var v = ui.val('v'); - setAlpha.call(that, colorMapL1, !isNullish$1(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$1(hva) ? hva.v : 100 - }); - setBG.call(that, colorBarDiv, saturatedColor.val('hex')); - setAlpha.call(that, colorBarL2, 100 - (!isNullish$1(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$1(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$1(_a) ? 0 : 100); - setAlpha.call(that, colorBarL6, !isNullish$1(_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$1(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$1(_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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(all) ? all.hex : '', "\"/></label>").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"2\" class=\"AHex\" value=\"".concat(!isNullish$1(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$1(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$1(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$1(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 $; -}; - -/* 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 - * @param {{langPath: string}} conf - * @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, conf) { - var url, 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'; - } - - url = "".concat(conf.langPath, "lang.").concat(langParam, ".js"); // eslint-disable-next-line node/no-unsupported-features/es-syntax - - _context2.next = 6; - return import(url); - - case 6: - module = _context2.sent; - return _context2.abrupt("return", readLang(module["default"])); - - case 8: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - - return function putLocale(_x2, _x3, _x4) { - 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} [langPath="locale/"] The path where the language files are located, with trailing slash. Default will be changed to `../dist/locale/` if this is a modular load. 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 {string} [canvgPath="canvg/"] The path used for `canvg` files, with trailing slash. Default will be changed to `../dist/` if this is a modular load. -* @property {string} [extIconsPath="extensions/"] The path used for extension icons, with trailing slash. -* @property {string} [jGraduatePath="jgraduate/images/"] The path where jGraduate images are located. 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) - langPath: './locale/', - // Default will be changed if this is a non-modular load - extPath: './extensions/', - // Default will be changed if this is a non-modular load - canvgPath: './canvg/', - // Default will be changed if this is a non-modular load - imgPath: './images/', - jGraduatePath: './images/', - extIconsPath: './extensions/', - // 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 - - - ['langPath', 'extPath', 'canvgPath', 'imgPath', 'jGraduatePath', 'extIconsPath'].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, curConfig); - - 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(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, curConfig); - - 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({ - paint: paint, - window: { - pickerTitle: title - }, - images: { - clientPath: curConfig.jGraduatePath - }, - 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/', - // langPath: './locale/', - // extPath: 'extensions/', - // jGraduatePath: 'jgraduate/images/', - - /* - 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 - - - - - - - -
    - - diff --git a/dist/editor/system/embedapi.js b/dist/editor/system/embedapi.js deleted file mode 100644 index dd6459c4..00000000 --- a/dist/editor/system/embedapi.js +++ /dev/null @@ -1,395 +0,0 @@ -/** -* Handles underlying communication between the embedding window and the -* editor frame. -* @module EmbeddedSVGEdit -*/ - -let cbid = 0; - -/** -* @callback module:EmbeddedSVGEdit.CallbackSetter -* @param {GenericCallback} newCallback Callback to be stored (signature dependent on function) -* @returns {void} -*/ -/** -* @callback module:EmbeddedSVGEdit.CallbackSetGetter -* @param {...any} args Signature dependent on the function -* @returns {module:EmbeddedSVGEdit.CallbackSetter} -*/ - -/** -* @param {string} funcName -* @returns {module:EmbeddedSVGEdit.CallbackSetGetter} -*/ -function getCallbackSetter (funcName) { - return function (...args) { - const that = this, // New callback - callbackID = this.send(funcName, args, function () { /* */ }); // The callback (currently it's nothing, but will be set later) - - return function (newCallback) { - that.callbacks[callbackID] = newCallback; // Set callback - }; - }; -} - -/** -* Having this separate from messageListener allows us to -* avoid using JSON parsing (and its limitations) in the case -* of same domain control. -* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value -* @param {PlainObject} data -* @param {JSON} data.result -* @param {string} data.error -* @param {Integer} data.id -* @returns {void} -*/ -function addCallback (t, {result, error, id: callbackID}) { - if (typeof callbackID === 'number' && t.callbacks[callbackID]) { - // These should be safe both because we check `cbid` is numeric and - // because the calls are from trusted origins - if (result) { - t.callbacks[callbackID](result); // lgtm [js/unvalidated-dynamic-method-call] - } else { - t.callbacks[callbackID](error, 'error'); // lgtm [js/unvalidated-dynamic-method-call] - } - } -} - -/** -* @param {Event} e -* @returns {void} -*/ -function messageListener (e) { - // We accept and post strings as opposed to objects for the sake of IE9 support; this - // will most likely be changed in the future - if (!e.data || !['string', 'object'].includes(typeof e.data)) { - return; - } - const {allowedOrigins} = this, - data = typeof e.data === 'object' ? e.data : JSON.parse(e.data); - if (!data || typeof data !== 'object' || data.namespace !== 'svg-edit' || - e.source !== this.frame.contentWindow || - (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) - ) { - // eslint-disable-next-line no-console -- Info for developers - console.error( - `The origin ${e.origin} was not whitelisted as an origin from ` + - `which responses may be received by this ${window.origin} script.` - ); - return; - } - addCallback(this, data); -} - -/** -* @callback module:EmbeddedSVGEdit.MessageListener -* @param {MessageEvent} e -* @returns {void} -*/ -/** -* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value -* @returns {module:EmbeddedSVGEdit.MessageListener} Event listener -*/ -function getMessageListener (t) { - return function (e) { - messageListener.call(t, e); - }; -} - -/** -* Embedded SVG-edit API. -* General usage: -* - Have an iframe somewhere pointing to a version of svg-edit > r1000. -* @example -// Initialize the magic with: -const svgCanvas = new EmbeddedSVGEdit(window.frames.svgedit); - -// Pass functions in this format: -svgCanvas.setSvgString('string'); - -// Or if a callback is needed: -svgCanvas.setSvgString('string')(function (data, error) { - if (error) { - // There was an error - } else { - // Handle data - } -}); - -// Everything is done with the same API as the real svg-edit, -// and all documentation is unchanged. - -// However, this file depends on the postMessage API which -// can only support JSON-serializable arguments and -// return values, so, for example, arguments whose value is -// 'undefined', a function, a non-finite number, or a built-in -// object like Date(), RegExp(), etc. will most likely not behave -// as expected. In such a case one may need to host -// the SVG editor on the same domain and reference the -// JavaScript methods on the frame itself. - -// The only other difference is when handling returns: -// the callback notation is used instead. -const blah = new EmbeddedSVGEdit(window.frames.svgedit); -blah.clearSelection('woot', 'blah', 1337, [1, 2, 3, 4, 5, 'moo'], -42, { - a: 'tree', b: 6, c: 9 -})(function () { console.log('GET DATA', args); }); -* -* @memberof module:EmbeddedSVGEdit -*/ -class EmbeddedSVGEdit { - /** - * @param {HTMLIFrameElement} frame - * @param {string[]} [allowedOrigins=[]] Array of origins from which incoming - * messages will be allowed when same origin is not used; defaults to none. - * If supplied, it should probably be the same as svgEditor's allowedOrigins - */ - constructor (frame, allowedOrigins) { - const that = this; - this.allowedOrigins = allowedOrigins || []; - // Initialize communication - this.frame = frame; - this.callbacks = {}; - // List of functions extracted with this: - // Run in firebug on http://svg-edit.googlecode.com/svn/trunk/docs/files/svgcanvas-js.html - - // for (const i=0,q=[],f = document.querySelectorAll('div.CFunction h3.CTitle a'); i < f.length; i++) { q.push(f[i].name); }; q - // const functions = ['clearSelection', 'addToSelection', 'removeFromSelection', 'open', 'save', 'getSvgString', 'setSvgString', - // 'createLayer', 'deleteCurrentLayer', 'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition', 'setLayerVisibility', - // 'moveSelectedToLayer', 'clear']; - - // Newer, well, it extracts things that aren't documented as well. All functions accessible through the normal thingy can now be accessed though the API - // const {svgCanvas} = frame.contentWindow; - // const l = []; - // for (const i in svgCanvas) { if (typeof svgCanvas[i] === 'function') { l.push(i);} }; - // alert("['" + l.join("', '") + "']"); - // Run in svgedit itself - const functions = [ - 'addExtension', - 'addSVGElementFromJson', - 'addToSelection', - 'alignSelectedElements', - 'assignAttributes', - 'bind', - 'call', - 'changeSelectedAttribute', - 'cleanupElement', - 'clear', - 'clearSelection', - 'clearSvgContentElement', - 'cloneLayer', - 'cloneSelectedElements', - 'convertGradients', - 'convertToGroup', - 'convertToNum', - 'convertToPath', - 'copySelectedElements', - 'createLayer', - 'cutSelectedElements', - 'cycleElement', - 'deleteCurrentLayer', - 'deleteSelectedElements', - 'embedImage', - 'exportPDF', - 'findDefs', - 'getBBox', - 'getBlur', - 'getBold', - 'getColor', - 'getContentElem', - 'getCurrentDrawing', - 'getDocumentTitle', - 'getEditorNS', - 'getElem', - 'getFillOpacity', - 'getFontColor', - 'getFontFamily', - 'getFontSize', - 'getHref', - 'getId', - 'getIntersectionList', - 'getItalic', - 'getMode', - 'getMouseTarget', - 'getNextId', - 'getOffset', - 'getOpacity', - 'getPaintOpacity', - 'getPrivateMethods', - 'getRefElem', - 'getResolution', - 'getRootElem', - 'getRotationAngle', - 'getSelectedElems', - 'getStrokeOpacity', - 'getStrokeWidth', - 'getStrokedBBox', - 'getStyle', - 'getSvgString', - 'getText', - 'getTitle', - 'getTransformList', - 'getUIStrings', - 'getUrlFromAttr', - 'getVersion', - 'getVisibleElements', - 'getVisibleElementsAndBBoxes', - 'getZoom', - 'groupSelectedElements', - 'groupSvgElem', - 'hasMatrixTransform', - 'identifyLayers', - 'importSvgString', - 'leaveContext', - 'linkControlPoints', - 'makeHyperlink', - 'matrixMultiply', - 'mergeAllLayers', - 'mergeLayer', - 'moveSelectedElements', - 'moveSelectedToLayer', - 'moveToBottomSelectedElement', - 'moveToTopSelectedElement', - 'moveUpDownSelected', - 'open', - 'pasteElements', - 'prepareSvg', - 'pushGroupProperties', - 'randomizeIds', - 'rasterExport', - 'ready', - 'recalculateAllSelectedDimensions', - 'recalculateDimensions', - 'remapElement', - 'removeFromSelection', - 'removeHyperlink', - 'removeUnusedDefElems', - 'renameCurrentLayer', - 'round', - 'runExtensions', - 'sanitizeSvg', - 'save', - 'selectAllInCurrentLayer', - 'selectOnly', - 'setBBoxZoom', - 'setBackground', - 'setBlur', - 'setBlurNoUndo', - 'setBlurOffsets', - 'setBold', - 'setColor', - 'setConfig', - 'setContext', - 'setCurrentLayer', - 'setCurrentLayerPosition', - 'setDocumentTitle', - 'setFillPaint', - 'setFontColor', - 'setFontFamily', - 'setFontSize', - 'setGoodImage', - 'setGradient', - 'setGroupTitle', - 'setHref', - 'setIdPrefix', - 'setImageURL', - 'setItalic', - 'setLayerVisibility', - 'setLinkURL', - 'setMode', - 'setOpacity', - 'setPaint', - 'setPaintOpacity', - 'setRectRadius', - 'setResolution', - 'setRotationAngle', - 'setSegType', - 'setStrokeAttr', - 'setStrokePaint', - 'setStrokeWidth', - 'setSvgString', - 'setTextContent', - 'setUiStrings', - 'setUseData', - 'setZoom', - 'svgCanvasToString', - 'svgToString', - 'transformListToTransform', - 'ungroupSelectedElement', - 'uniquifyElems', - 'updateCanvas', - 'zoomChanged' - ]; - - // TODO: rewrite the following, it's pretty scary. - for (const func of functions) { - this[func] = getCallbackSetter(func); - } - - // Older IE may need a polyfill for addEventListener, but so it would for SVG - window.addEventListener('message', getMessageListener(this)); - window.addEventListener('keydown', (e) => { - const {type, key} = e; - if (key === 'Backspace') { - e.preventDefault(); - const keyboardEvent = new KeyboardEvent(type, {key}); - that.frame.contentDocument.dispatchEvent(keyboardEvent); - } - }); - } - - /** - * @param {string} name - * @param {ArgumentsArray} args Signature dependent on function - * @param {GenericCallback} callback (This may be better than a promise in case adding an event.) - * @returns {Integer} - */ - send (name, args, callback) { // eslint-disable-line promise/prefer-await-to-callbacks - const that = this; - cbid++; - - this.callbacks[cbid] = callback; - setTimeout((function (callbackID) { - return function () { // Delay for the callback to be set in case its synchronous - /* - * Todo: Handle non-JSON arguments and return values (undefined, - * nonfinite numbers, functions, and built-in objects like Date, - * RegExp), etc.? Allow promises instead of callbacks? Review - * SVG-Edit functions for whether JSON-able parameters can be - * made compatile with all API functionality - */ - // We accept and post strings for the sake of IE9 support - let sameOriginWithGlobal = false; - try { - sameOriginWithGlobal = window.location.origin === that.frame.contentWindow.location.origin && - that.frame.contentWindow.svgEditor.canvas; - } catch (err) {} - - if (sameOriginWithGlobal) { - // Although we do not really need this API if we are working same - // domain, it could allow us to write in a way that would work - // cross-domain as well, assuming we stick to the argument limitations - // of the current JSON-based communication API (e.g., not passing - // callbacks). We might be able to address these shortcomings; see - // the todo elsewhere in this file. - const message = {id: callbackID}, - {svgEditor: {canvas: svgCanvas}} = that.frame.contentWindow; - try { - message.result = svgCanvas[name](...args); - } catch (err) { - message.error = err.message; - } - addCallback(that, message); - } else { // Requires the ext-xdomain-messaging.js extension - that.frame.contentWindow.postMessage(JSON.stringify({ - namespace: 'svgCanvas', id: callbackID, name, args - }), '*'); - } - }; - }(cbid)), 0); - - return cbid; - } -} - -export default EmbeddedSVGEdit; diff --git a/dist/editor/system/extensions/ext-arrows.js b/dist/editor/system/extensions/ext-arrows.js deleted file mode 100644 index 6fc1f8f2..00000000 --- a/dist/editor/system/extensions/ext-arrows.js +++ /dev/null @@ -1,2012 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - /** - * @file ext-arrows.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ - var extArrows = exports('default', { - name: 'arrows', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - colorChanged = function _colorChanged(elem) { - var color = elem.getAttribute('stroke'); - var mtypes = ['start', 'mid', 'end']; - var defs = svgCanvas.findDefs(); - $.each(mtypes, function (i, type) { - var marker = getLinked(elem, 'marker-' + type); - - if (!marker) { - return; - } - - var curColor = $(marker).children().attr('fill'); - var curD = $(marker).children().attr('d'); - - if (curColor === color) { - return; - } - - var allMarkers = $(defs).find('marker'); - var newMarker = null; // Different color, check if already made - - allMarkers.each(function () { - var attrs = $(this).children().attr(['fill', 'd']); - - if (attrs.fill === color && attrs.d === curD) { - // Found another marker with this color and this path - newMarker = this; - } - }); - - if (!newMarker) { - // Create a new marker with this color - var lastId = marker.id; - var dir = lastId.includes('_fw') ? 'fw' : 'bk'; - newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length); - $(newMarker).children().attr('fill', color); - } - - $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed - - var remove = true; - $(S.svgcontent).find('line, polyline, path, polygon').each(function () { - var element = this; - $.each(mtypes, function (j, mtype) { - if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { - remove = false; - return remove; - } - - return undefined; - }); - - if (!remove) { - return false; - } - - return undefined; - }); // Not found, so can safely remove - - if (remove) { - $(marker).remove(); - } - }); - }; - - setArrow = function _setArrow() { - resetMarker(); - var type = this.value; - - if (type === 'none') { - return; - } // Set marker on element - - - var dir = 'fw'; - - if (type === 'mid_bk') { - type = 'mid'; - dir = 'bk'; - } else if (type === 'both') { - addMarker('bk', type); - svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')'); - type = 'end'; - dir = 'fw'; - } else if (type === 'start') { - dir = 'bk'; - } - - addMarker(dir, type); - svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')'); - svgCanvas.call('changed', selElems); - }; - - addMarker = function _addMarker(dir, type, id) { - // TODO: Make marker (or use?) per arrow type, since refX can be different - id = id || arrowprefix + dir; - var data = pathdata[dir]; - - if (type === 'mid') { - data.refx = 5; - } - - var marker = svgCanvas.getElem(id); - - if (!marker) { - marker = addElem({ - element: 'marker', - attr: { - viewBox: '0 0 10 10', - id: id, - refY: 5, - markerUnits: 'strokeWidth', - markerWidth: 5, - markerHeight: 5, - orient: 'auto', - style: 'pointer-events:none' // Currently needed for Opera - - } - }); - var arrow = addElem({ - element: 'path', - attr: { - d: data.d, - fill: '#000000' - } - }); - marker.append(arrow); - svgCanvas.findDefs().append(marker); - } - - marker.setAttribute('refX', data.refx); - return marker; - }; - - resetMarker = function _resetMarker() { - var el = selElems[0]; - el.removeAttribute('marker-start'); - el.removeAttribute('marker-mid'); - el.removeAttribute('marker-end'); - }; - - showPanel = function _showPanel(on) { - $('#arrow_panel').toggle(on); - - if (on) { - var el = selElems[0]; - var end = el.getAttribute('marker-end'); - var start = el.getAttribute('marker-start'); - var mid = el.getAttribute('marker-mid'); - var val; - - if (end && start) { - val = 'both'; - } else if (end) { - val = 'end'; - } else if (start) { - val = 'start'; - } else if (mid) { - val = 'mid'; - - if (mid.includes('bk')) { - val = 'mid_bk'; - } - } - - if (!start && !mid && !end) { - val = 'none'; - } - - $('#arrow_list').val(val); - } - }; - - getLinked = function _getLinked(elem, attr) { - var str = elem.getAttribute(attr); - - if (!str) { - return null; - } - - var m = str.match(/\(#(.*)\)/); // const m = str.match(/\(#(?.+)\)/); - // if (!m || !m.groups.id) { - - if (!m || m.length !== 2) { - return null; - } - - return svgCanvas.getElem(m[1]); // return svgCanvas.getElem(m.groups.id); - }; - - unsetArrowNonce = function _unsetArrowNonce(win) { - randomizeIds = false; - arrowprefix = prefix; - pathdata.fw.id = arrowprefix + 'fw'; - pathdata.bk.id = arrowprefix + 'bk'; - }; - - setArrowNonce = function _setArrowNonce(win, n) { - randomizeIds = true; - arrowprefix = prefix + n + '_'; - pathdata.fw.id = arrowprefix + 'fw'; - pathdata.bk.id = arrowprefix + 'bk'; - }; - - _context2.next = 10; - return S.importLocale(); - - case 10: - strings = _context2.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - // {svgcontent} = S, - addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_'; - randomizeIds = S.randomize_ids; - /** - * @param {Window} win - * @param {!(string|Integer)} n - * @returns {void} - */ - - svgCanvas.bind('setnonce', setArrowNonce); - svgCanvas.bind('unsetnonce', unsetArrowNonce); - - if (randomizeIds) { - arrowprefix = prefix + nonce + '_'; - } else { - arrowprefix = prefix; - } - - pathdata = { - fw: { - d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', - refx: 8, - id: arrowprefix + 'fw' - }, - bk: { - d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', - refx: 2, - id: arrowprefix + 'bk' - } - }; - /** - * Gets linked element. - * @param {Element} elem - * @param {string} attr - * @returns {Element} - */ - - contextTools = [{ - type: 'select', - panel: 'arrow_panel', - id: 'arrow_list', - defval: 'none', - events: { - change: setArrow - } - }]; - return _context2.abrupt("return", { - name: strings.name, - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#arrow_panel').hide(); // Set ID so it can be translated in locale file - - $('#arrow_list option')[0].id = 'connector_no_arrow'; - }, - addLangData: function addLangData(_ref) { - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var lang, importLocale, _yield$importLocale, langList; - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - lang = _ref.lang, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); - - case 3: - _yield$importLocale = _context.sent; - langList = _yield$importLocale.langList; - return _context.abrupt("return", { - data: langList - }); - - case 6: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var markerElems = ['line', 'path', 'polyline', 'polygon']; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && markerElems.includes(elem.tagName)) { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) { - var elem = opts.elems[0]; - - if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { - // const start = elem.getAttribute('marker-start'); - // const mid = elem.getAttribute('marker-mid'); - // const end = elem.getAttribute('marker-end'); - // Has marker, so see if it should match color - colorChanged(elem); - } - } - }); - - case 21: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-closepath.js b/dist/editor/system/extensions/ext-closepath.js deleted file mode 100644 index 1b1a6212..00000000 --- a/dist/editor/system/extensions/ext-closepath.js +++ /dev/null @@ -1,4096 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - /* 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; - } - })(); - - // The button toggles whether the path is open or closed - - var extClosepath = exports('default', { - name: 'closepath', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref.importLocale, $ = _ref.$; - _context.next = 3; - return importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - - updateButton = function updateButton(path) { - var seglist = path.pathSegList, - closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, - showbutton = closed ? '#tool_openpath' : '#tool_closepath', - hidebutton = closed ? '#tool_closepath' : '#tool_openpath'; - $(hidebutton).hide(); - $(showbutton).show(); - }; - - showPanel = function showPanel(on) { - $('#closepath_panel').toggle(on); - - if (on) { - var path = selElems[0]; - - if (path) { - updateButton(path); - } - } - }; - - toggleClosed = function toggleClosed() { - var path = selElems[0]; - - if (path) { - var seglist = path.pathSegList, - last = seglist.numberOfItems - 1; // is closed - - if (seglist.getItem(last).pathSegType === 1) { - seglist.removeItem(last); - } else { - seglist.appendItem(path.createSVGPathSegClosePath()); - } - - updateButton(path); - } - }; - - buttons = [{ - id: 'tool_openpath', - icon: svgEditor.curConfig.extIconsPath + 'openpath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } - } - }, { - id: 'tool_closepath', - icon: svgEditor.curConfig.extIconsPath + 'closepath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - callback: function callback() { - $('#closepath_panel').hide(); - }, - selectedChanged: function selectedChanged(opts) { - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.tagName === 'path') { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - } - }); - - case 10: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-connector.js b/dist/editor/system/extensions/ext-connector.js deleted file mode 100644 index c4b256a9..00000000 --- a/dist/editor/system/extensions/ext-connector.js +++ /dev/null @@ -1,2306 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - /** - * @file ext-connector.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ - var extConnector = exports('default', { - name: 'connector', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - init = function _init() { - // Make sure all connectors have data set - $(svgcontent).find('*').each(function () { - var conn = this.getAttributeNS(seNs, 'connector'); - - if (conn) { - this.setAttribute('class', connSel.substr(1)); - var connData = conn.split(' '); - var sbb = svgCanvas.getStrokedBBox([getElem(connData[0])]); - var ebb = svgCanvas.getStrokedBBox([getElem(connData[1])]); - $(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb); - svgCanvas.getEditorNS(true); - } - }); // updateConnectors(); - }; - - updateConnectors = function _updateConnectors(elems) { - // Updates connector lines based on selected elements - // Is not used on mousemove, as it runs getStrokedBBox every time, - // which isn't necessary there. - findConnectors(elems); - - if (connections.length) { - // Update line with element - var i = connections.length; - - while (i--) { - var conn = connections[i]; - var line = conn.connector; - var elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5; - - var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element - - var bb = svgCanvas.getStrokedBBox([elem]); - bb.x = conn.start_x; - bb.y = conn.start_y; - elData(line, pre + '_bb', bb); - /* const addOffset = */ - - elData(line, pre + '_off'); - var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element - - var bb2 = elData(line, altPre + '_bb'); - var srcX = bb2.x + bb2.width / 2; - var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); - setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element - - var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit - - if (navigator.userAgent.includes('AppleWebKit')) { - var pts = line.points; - var len = pts.numberOfItems; - var ptArr = []; - - for (var j = 0; j < len; j++) { - pt = pts.getItem(j); - ptArr[j] = pt.x + ',' + pt.y; - } - - line.setAttribute('points', ptArr.join(' ')); - } - } - } - }; - - findConnectors = function _findConnectors() { - var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems; - var connectors = $(svgcontent).find(connSel); - connections = []; // Loop through connectors to see if one is connected to the element - - connectors.each(function () { - var addThis; - /** - * - * @returns {void} - */ - - function add() { - if (elems.includes(this)) { - // Pretend this element is selected - addThis = true; - } - } // Grab the ends - - - var parts = []; - ['start', 'end'].forEach(function (pos, i) { - var key = 'c_' + pos; - var part = elData(this, key); - - if (part === null || part === undefined) { - // Does this ever return nullish values? - part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); - elData(this, 'c_' + pos, part.id); - elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); - } else part = document.getElementById(part); - - parts.push(part); - }, this); - - for (var i = 0; i < 2; i++) { - var cElem = parts[i]; - addThis = false; // The connected element might be part of a selected group - - $(cElem).parents().each(add); - - if (!cElem || !cElem.parentNode) { - $(this).remove(); - continue; - } - - if (elems.includes(cElem) || addThis) { - var bb = svgCanvas.getStrokedBBox([cElem]); - connections.push({ - elem: cElem, - connector: this, - is_start: i === 0, - start_x: bb.x, - start_y: bb.y - }); - } - } - }); - }; - - updateLine = function _updateLine(diffX, diffY) { - // Update line with element - var i = connections.length; - - while (i--) { - var conn = connections[i]; - var line = conn.connector; // const {elem} = conn; - - var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5; - // Update bbox for this element - - var bb = elData(line, pre + '_bb'); - bb.x = conn.start_x + diffX; - bb.y = conn.start_y + diffY; - elData(line, pre + '_bb', bb); - var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element - - var bb2 = elData(line, altPre + '_bb'); - var srcX = bb2.x + bb2.width / 2; - var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0 - - setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element - - var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); - } - }; - - setPoint = function _setPoint(elem, pos, x, y, setMid) { - var pts = elem.points; - var pt = svgroot.createSVGPoint(); - pt.x = x; - pt.y = y; - - if (pos === 'end') { - pos = pts.numberOfItems - 1; - } // TODO: Test for this on init, then use alt only if needed - - - try { - pts.replaceItem(pt, pos); - } catch (err) { - // Should only occur in FF which formats points attr as "n,n n,n", so just split - var ptArr = elem.getAttribute('points').split(' '); - - for (var i = 0; i < ptArr.length; i++) { - if (i === pos) { - ptArr[i] = x + ',' + y; - } - } - - elem.setAttribute('points', ptArr.join(' ')); - } - - if (setMid) { - // Add center point - var ptStart = pts.getItem(0); - var ptEnd = pts.getItem(pts.numberOfItems - 1); - setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2); - } - }; - - showPanel = function _showPanel(on) { - var connRules = $('#connector_rules'); - - if (!connRules.length) { - connRules = $('').appendTo('head'); - } - - connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'); - $('#connector_panel').toggle(on); - }; - - getOffset = function _getOffset(side, line) { - var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); - // TODO: Make this number (5) be based on marker width/height - - var size = line.getAttribute('stroke-width') * 5; - return giveOffset ? size : 0; - }; - - getBBintersect = function _getBBintersect(x, y, bb, offset) { - if (offset) { - offset -= 0; - bb = $.extend({}, bb); - bb.width += offset; - bb.height += offset; - bb.x -= offset / 2; - bb.y -= offset / 2; - } - - var midX = bb.x + bb.width / 2; - var midY = bb.y + bb.height / 2; - var lenX = x - midX; - var lenY = y - midY; - var slope = Math.abs(lenY / lenX); - var ratio; - - if (slope < bb.height / bb.width) { - ratio = bb.width / 2 / Math.abs(lenX); - } else { - ratio = lenY ? bb.height / 2 / Math.abs(lenY) : 0; - } - - return { - x: midX + lenX * ratio, - y: midY + lenY * ratio - }; - }; - - svgEditor = _this; - svgCanvas = svgEditor.canvas; - getElem = svgCanvas.getElem; - $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; - _context.next = 14; - return importLocale(); - - case 14: - strings = _context.sent; - svgcontent = S.svgcontent, started = false, connections = [], selElems = []; - /** - * - * @param {Float} x - * @param {Float} y - * @param {module:utilities.BBoxObject} bb - * @param {Float} offset - * @returns {module:math.XYObject} - */ - - // Do once - (function () { - var gse = svgCanvas.groupSelectedElements; - - svgCanvas.groupSelectedElements = function () { - svgCanvas.removeFromSelection($(connSel).toArray()); - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return gse.apply(this, args); - }; - - var mse = svgCanvas.moveSelectedElements; - - svgCanvas.moveSelectedElements = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var cmd = mse.apply(this, args); - updateConnectors(); - return cmd; - }; - - seNs = svgCanvas.getEditorNS(); - })(); - /** - * Do on reset. - * @returns {void} - */ - - - // $(svgroot).parent().mousemove(function (e) { - // // if (started - // // || svgCanvas.getMode() !== 'connector' - // // || e.target.parentNode.parentNode !== svgcontent) return; - // - // console.log('y') - // // if (e.target.parentNode.parentNode === svgcontent) { - // // - // // } - // }); - buttons = [{ - id: 'mode_connect', - type: 'mode', - icon: svgEditor.curConfig.imgPath + 'cut.png', - includeWith: { - button: '#tool_line', - isDefault: false, - position: 1 - }, - events: { - click: function click() { - svgCanvas.setMode('connector'); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.imgPath + 'conn.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - - /* async */ - addLangData: function addLangData(_ref) { - var lang = _ref.lang; - // , importLocale: importLoc - return { - data: strings.langList - }; - }, - mouseDown: function mouseDown(opts) { - var e = opts.event; - startX = opts.start_x; - startY = opts.start_y; - var mode = svgCanvas.getMode(); - var initStroke = svgEditor.curConfig.initStroke; - - if (mode === 'connector') { - if (started) { - return undefined; - } - - var mouseTarget = e.target; - var parents = $(mouseTarget).parents(); - - if ($.inArray(svgcontent, parents) !== -1) { - // Connectable element - // If child of foreignObject, use parent - var fo = $(mouseTarget).closest('foreignObject'); - startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element - - var bb = svgCanvas.getStrokedBBox([startElem]); - var x = bb.x + bb.width / 2; - var y = bb.y + bb.height / 2; - started = true; - curLine = addElem({ - element: 'polyline', - attr: { - id: svgCanvas.getNextId(), - points: x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY, - stroke: '#' + initStroke.color, - 'stroke-width': !startElem.stroke_width || startElem.stroke_width === 0 ? initStroke.width : startElem.stroke_width, - fill: 'none', - opacity: initStroke.opacity, - style: 'pointer-events:none' - } - }); - elData(curLine, 'start_bb', bb); - } - - return { - started: true - }; - } - - if (mode === 'select') { - findConnectors(); - } - - return undefined; - }, - mouseMove: function mouseMove(opts) { - var zoom = svgCanvas.getZoom(); // const e = opts.event; - - var x = opts.mouse_x / zoom; - var y = opts.mouse_y / zoom; - var diffX = x - startX, - diffY = y - startY; - var mode = svgCanvas.getMode(); - - if (mode === 'connector' && started) { - // const sw = curLine.getAttribute('stroke-width') * 3; - // Set start point (adjusts based on bb) - var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine)); - startX = pt.x; - startY = pt.y; - setPoint(curLine, 0, pt.x, pt.y, true); // Set end point - - setPoint(curLine, 'end', x, y, true); - } else if (mode === 'select') { - var slen = selElems.length; - - while (slen--) { - var elem = selElems[slen]; // Look for selected connector elements - - if (elem && elData(elem, 'c_start')) { - // Remove the "translate" transform given to move - svgCanvas.removeFromSelection([elem]); - svgCanvas.getTransformList(elem).clear(); - } - } - - if (connections.length) { - updateLine(diffX, diffY); - } - } - }, - mouseUp: function mouseUp(opts) { - // const zoom = svgCanvas.getZoom(); - var e = opts.event; // , x = opts.mouse_x / zoom, - // , y = opts.mouse_y / zoom, - - var mouseTarget = e.target; - - if (svgCanvas.getMode() !== 'connector') { - return undefined; - } - - var fo = $(mouseTarget).closest('foreignObject'); - - if (fo.length) { - mouseTarget = fo[0]; - } - - var parents = $(mouseTarget).parents(); - - if (mouseTarget === startElem) { - // Start line through click - started = true; - return { - keep: true, - element: null, - started: started - }; - } - - if ($.inArray(svgcontent, parents) === -1) { - // Not a valid target element, so remove line - $(curLine).remove(); - started = false; - return { - keep: false, - element: null, - started: started - }; - } // Valid end element - - - endElem = mouseTarget; - var startId = startElem.id, - endId = endElem.id; - var connStr = startId + ' ' + endId; - var altStr = endId + ' ' + startId; // Don't create connector if one already exists - - var dupe = $(svgcontent).find(connSel).filter(function () { - var conn = this.getAttributeNS(seNs, 'connector'); - - if (conn === connStr || conn === altStr) { - return true; - } - - return false; - }); - - if (dupe.length) { - $(curLine).remove(); - return { - keep: false, - element: null, - started: false - }; - } - - var bb = svgCanvas.getStrokedBBox([endElem]); - var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine)); - setPoint(curLine, 'end', pt.x, pt.y, true); - $(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb); - seNs = svgCanvas.getEditorNS(true); - curLine.setAttributeNS(seNs, 'se:connector', connStr); - curLine.setAttribute('class', connSel.substr(1)); - curLine.setAttribute('opacity', 1); - svgCanvas.addToSelection([curLine]); - svgCanvas.moveToBottomSelectedElement(); - selManager.requestSelector(curLine).showGrips(false); - started = false; - return { - keep: true, - element: curLine, - started: started - }; - }, - selectedChanged: function selectedChanged(opts) { - // TODO: Find better way to skip operations if no connectors are in use - if (!$(svgcontent).find(connSel).length) { - return; - } - - if (svgCanvas.getMode() === 'connector') { - svgCanvas.setMode('select'); - } // Use this to update the current selected elements - - - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elData(elem, 'c_start')) { - selManager.requestSelector(elem).showGrips(false); - - if (opts.selectedElement && !opts.multiselected) { - // TODO: Set up context tools and hide most regular line tools - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - - updateConnectors(); - }, - elementChanged: function elementChanged(opts) { - var elem = opts.elems[0]; - if (!elem) return; - - if (elem.tagName === 'svg' && elem.id === 'svgcontent') { - // Update svgcontent (can change on import) - svgcontent = elem; - init(); - } // Has marker, so change offset - - - if (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end')) { - var start = elem.getAttribute('marker-start'); - var mid = elem.getAttribute('marker-mid'); - var end = elem.getAttribute('marker-end'); - curLine = elem; - $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end)); - - if (elem.tagName === 'line' && mid) { - // Convert to polyline to accept mid-arrow - var x1 = Number(elem.getAttribute('x1')); - var x2 = Number(elem.getAttribute('x2')); - var y1 = Number(elem.getAttribute('y1')); - var y2 = Number(elem.getAttribute('y2')); - var _elem = elem, - id = _elem.id; - var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; - var pline = addElem({ - element: 'polyline', - attr: { - points: x1 + ',' + y1 + midPt + x2 + ',' + y2, - stroke: elem.getAttribute('stroke'), - 'stroke-width': elem.getAttribute('stroke-width'), - 'marker-mid': mid, - fill: 'none', - opacity: elem.getAttribute('opacity') || 1 - } - }); - $(elem).after(pline).remove(); - svgCanvas.clearSelection(); - pline.id = id; - svgCanvas.addToSelection([pline]); - elem = pline; - } - } // Update line if it's a connector - - - if (elem.getAttribute('class') === connSel.substr(1)) { - var _start = getElem(elData(elem, 'c_start')); - - updateConnectors([_start]); - } else { - updateConnectors(); - } - }, - IDsUpdated: function IDsUpdated(input) { - var remove = []; - input.elems.forEach(function (elem) { - if ('se:connector' in elem.attr) { - elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) { - return input.changes[oldID]; - }).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but - // if one end is missing, it would be 'svg_21' and therefore fail this test - - if (!/. ./.test(elem.attr['se:connector'])) { - remove.push(elem.attr.id); - } - } - }); - return { - remove: remove - }; - }, - toolButtonStateUpdate: function toolButtonStateUpdate(opts) { - if (opts.nostroke) { - if ($('#mode_connect').hasClass('tool_button_current')) { - svgEditor.clickSelect(); - } - } - - $('#mode_connect').toggleClass('disabled', opts.nostroke); - } - }); - - case 19: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-eyedropper.js b/dist/editor/system/extensions/ext-eyedropper.js deleted file mode 100644 index 4433b752..00000000 --- a/dist/editor/system/extensions/ext-eyedropper.js +++ /dev/null @@ -1,1810 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - var eyedropperIcon = "eyedropper-icon.xml"; - - var extEyedropper = exports('default', { - name: 'eyedropper', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - getStyle = function _getStyle(opts) { - // if we are in eyedropper mode, we don't want to disable the eye-dropper tool - var mode = svgCanvas.getMode(); - - if (mode === 'eyedropper') { - return; - } - - var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected - - var elem = null; - - if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) { - elem = opts.elems[0]; - tool.removeClass('disabled'); // grab the current style - - currentStyle.fillPaint = elem.getAttribute('fill') || 'black'; - currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0; - currentStyle.strokePaint = elem.getAttribute('stroke'); - currentStyle.strokeOpacity = elem.getAttribute('stroke-opacity') || 1.0; - currentStyle.strokeWidth = elem.getAttribute('stroke-width'); - currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray'); - currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap'); - currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin'); - currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool - } else { - tool.addClass('disabled'); - } - }; - - _context.next = 3; - return S.importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - $ = S.$, ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) { - svgCanvas.undoMgr.addCommandToHistory(cmd); - }, currentStyle = { - fillPaint: 'red', - fillOpacity: 1.0, - strokePaint: 'black', - strokeOpacity: 1.0, - strokeWidth: 5, - strokeDashArray: null, - opacity: 1.0, - strokeLinecap: 'butt', - strokeLinejoin: 'miter' - }; - /** - * - * @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementChanged} opts - * @returns {void} - */ - - buttons = [{ - id: 'tool_eyedropper', - icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png', - type: 'mode', - events: { - click: function click() { - svgCanvas.setMode('eyedropper'); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - // if we have selected an element, grab its paint and enable the eye dropper button - selectedChanged: getStyle, - elementChanged: getStyle, - mouseDown: function mouseDown(opts) { - var mode = svgCanvas.getMode(); - - if (mode === 'eyedropper') { - var e = opts.event; - var target = e.target; - - if (!['svg', 'g', 'use'].includes(target.nodeName)) { - var changes = {}; - - var change = function change(elem, attrname, newvalue) { - changes[attrname] = elem.getAttribute(attrname); - elem.setAttribute(attrname, newvalue); - }; - - if (currentStyle.fillPaint) { - change(target, 'fill', currentStyle.fillPaint); - } - - if (currentStyle.fillOpacity) { - change(target, 'fill-opacity', currentStyle.fillOpacity); - } - - if (currentStyle.strokePaint) { - change(target, 'stroke', currentStyle.strokePaint); - } - - if (currentStyle.strokeOpacity) { - change(target, 'stroke-opacity', currentStyle.strokeOpacity); - } - - if (currentStyle.strokeWidth) { - change(target, 'stroke-width', currentStyle.strokeWidth); - } - - if (currentStyle.strokeDashArray) { - change(target, 'stroke-dasharray', currentStyle.strokeDashArray); - } - - if (currentStyle.opacity) { - change(target, 'opacity', currentStyle.opacity); - } - - if (currentStyle.strokeLinecap) { - change(target, 'stroke-linecap', currentStyle.strokeLinecap); - } - - if (currentStyle.strokeLinejoin) { - change(target, 'stroke-linejoin', currentStyle.strokeLinejoin); - } - - addToHistory(new ChangeElementCommand(target, changes)); - } - } - } - }); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-foreignobject.js b/dist/editor/system/extensions/ext-foreignobject.js deleted file mode 100644 index e37f723c..00000000 --- a/dist/editor/system/extensions/ext-foreignobject.js +++ /dev/null @@ -1,1971 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - var foreignobjectIcons = "foreignobject-icons.xml"; - - var extForeignobject = exports('default', { - name: 'foreignobject', - init: function init(S) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - setAttr = function _setAttr(attr, val) { - svgCanvas.changeSelectedAttribute(attr, val); - svgCanvas.call('changed', selElems); - }; - - showForeignEditor = function _showForeignEditor() { - var elt = selElems[0]; - - if (!elt || editingforeign) { - return; - } - - editingforeign = true; - toggleSourceButtons(true); - elt.removeAttribute('fill'); - var str = svgCanvas.svgToString(elt, 0); - $('#svg_source_textarea').val(str); - $('#svg_source_editor').fadeIn(); - properlySourceSizeTextArea(); - $('#svg_source_textarea').focus(); - }; - - setForeignString = function _setForeignString(xmlString) { - var elt = selElems[0]; // The parent `Element` to append to - - try { - // convert string into XML document - var newDoc = text2xml('' + xmlString + ''); // run it through our sanitizer to remove anything we do not support - - svgCanvas.sanitizeSvg(newDoc.documentElement); - elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true)); - svgCanvas.call('changed', [elt]); - svgCanvas.clearSelection(); - } catch (e) { - // Todo: Surface error to user - console.log(e); // eslint-disable-line no-console - - return false; - } - - return true; - }; - - toggleSourceButtons = function _toggleSourceButtons(on) { - $('#tool_source_save, #tool_source_cancel').toggle(!on); - $('#foreign_save, #foreign_cancel').toggle(on); - }; - - showPanel = function _showPanel(on) { - var fcRules = $('#fc_rules'); - - if (!fcRules.length) { - fcRules = $('').appendTo('head'); - } - - fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); - $('#foreignObject_panel').toggle(on); - }; - - svgEditor = _this; - $ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; - svgCanvas = svgEditor.canvas; - svgdoc = S.svgroot.parentNode.ownerDocument; - _context2.next = 11; - return importLocale(); - - case 11: - strings = _context2.sent; - - properlySourceSizeTextArea = function properlySourceSizeTextArea() { - // TODO: remove magic numbers here and get values from CSS - var height = $('#svg_source_container').height() - 80; - $('#svg_source_textarea').css('height', height); - }; - /** - * @param {boolean} on - * @returns {void} - */ - - - editingforeign = false; - /** - * This function sets the content of element elt to the input XML. - * @param {string} xmlString - The XML text - * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. - */ - - buttons = [{ - id: 'tool_foreign', - icon: svgEditor.curConfig.extIconsPath + 'foreignobject-tool.png', - type: 'mode', - events: { - click: function click() { - svgCanvas.setMode('foreign'); - } - } - }, { - id: 'edit_foreign', - icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png', - type: 'context', - panel: 'foreignObject_panel', - events: { - click: function click() { - showForeignEditor(); - } - } - }]; - contextTools = [{ - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_width', - size: 3, - events: { - change: function change() { - setAttr('width', this.value); - } - } - }, { - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_height', - events: { - change: function change() { - setAttr('height', this.value); - } - } - }, { - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_font_size', - size: 2, - defval: 16, - events: { - change: function change() { - setAttr('font-size', this.value); - } - } - }]; - return _context2.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#foreignObject_panel').hide(); - - var endChanges = function endChanges() { - $('#svg_source_editor').hide(); - editingforeign = false; - $('#svg_source_textarea').blur(); - toggleSourceButtons(false); - }; // TODO: Needs to be done after orig icon loads - - - setTimeout(function () { - // Create source save/cancel buttons - - /* const save = */ - $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var ok; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (editingforeign) { - _context.next = 2; - break; - } - - return _context.abrupt("return"); - - case 2: - if (setForeignString($('#svg_source_textarea').val())) { - _context.next = 11; - break; - } - - _context.next = 5; - return $.confirm('Errors found. Revert to original?'); - - case 5: - ok = _context.sent; - - if (ok) { - _context.next = 8; - break; - } - - return _context.abrupt("return"); - - case 8: - endChanges(); - _context.next = 12; - break; - - case 11: - endChanges(); - - case 12: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - /* const cancel = */ - - $('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () { - endChanges(); - }); - }, 3000); - }, - mouseDown: function mouseDown(opts) { - // const e = opts.event; - if (svgCanvas.getMode() !== 'foreign') { - return undefined; - } - - started = true; - newFO = svgCanvas.addSVGElementFromJson({ - element: 'foreignObject', - attr: { - x: opts.start_x, - y: opts.start_y, - id: svgCanvas.getNextId(), - 'font-size': 16, - // cur_text.font_size, - width: '48', - height: '20', - style: 'pointer-events:inherit' - } - }); - var m = svgdoc.createElementNS(NS.MATH, 'math'); - m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH); - m.setAttribute('display', 'inline'); - var mi = svgdoc.createElementNS(NS.MATH, 'mi'); - mi.setAttribute('mathvariant', 'normal'); - mi.textContent = "\u03A6"; - var mo = svgdoc.createElementNS(NS.MATH, 'mo'); - mo.textContent = "\u222A"; - var mi2 = svgdoc.createElementNS(NS.MATH, 'mi'); - mi2.textContent = "\u2133"; - m.append(mi, mo, mi2); - newFO.append(m); - return { - started: true - }; - }, - mouseUp: function mouseUp(opts) { - // const e = opts.event; - if (svgCanvas.getMode() !== 'foreign' || !started) { - return undefined; - } - - var attrs = $(newFO).attr(['width', 'height']); - var keep = attrs.width !== '0' || attrs.height !== '0'; - svgCanvas.addToSelection([newFO], true); - return { - keep: keep, - element: newFO - }; - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.tagName === 'foreignObject') { - if (opts.selectedElement && !opts.multiselected) { - $('#foreign_font_size').val(elem.getAttribute('font-size')); - $('#foreign_width').val(elem.getAttribute('width')); - $('#foreign_height').val(elem.getAttribute('height')); - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) {// const elem = opts.elems[0]; - } - }); - - case 17: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-grid.js b/dist/editor/system/extensions/ext-grid.js deleted file mode 100644 index 2ca252ef..00000000 --- a/dist/editor/system/extensions/ext-grid.js +++ /dev/null @@ -1,1830 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - var gridIcon = "grid-icon.xml"; - - var extGrid = exports('default', { - name: 'grid', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - gridUpdate = function _gridUpdate() { - if (showGrid) { - updateGrid(svgCanvas.getZoom()); - } - - $('#canvasGrid').toggle(showGrid); - $('#view_grid').toggleClass('push_button_pressed tool_button'); - }; - - updateGrid = function _updateGrid(zoom) { - // TODO: Try this with elements, then compare performance difference - var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px - - var uMulti = unit * zoom; // Calculate the main number interval - - var rawM = 100 / uMulti; - var multi = 1; - intervals.some(function (num) { - multi = num; - return rawM <= num; - }); - var bigInt = multi * uMulti; // Set the canvas size to the width of the container - - hcanvas.width = bigInt; - hcanvas.height = bigInt; - var ctx = hcanvas.getContext('2d'); - var curD = 0.5; - var part = bigInt / 10; - ctx.globalAlpha = 0.2; - ctx.strokeStyle = svgEditor.curConfig.gridColor; - - for (var i = 1; i < 10; i++) { - var subD = Math.round(part * i) + 0.5; // const lineNum = (i % 2)?12:10; - - var lineNum = 0; - ctx.moveTo(subD, bigInt); - ctx.lineTo(subD, lineNum); - ctx.moveTo(bigInt, subD); - ctx.lineTo(lineNum, subD); - } - - ctx.stroke(); - ctx.beginPath(); - ctx.globalAlpha = 0.5; - ctx.moveTo(curD, bigInt); - ctx.lineTo(curD, 0); - ctx.moveTo(bigInt, curD); - ctx.lineTo(0, curD); - ctx.stroke(); - var datauri = hcanvas.toDataURL('image/png'); - gridimg.setAttribute('width', bigInt); - gridimg.setAttribute('height', bigInt); - gridimg.parentNode.setAttribute('width', bigInt); - gridimg.parentNode.setAttribute('height', bigInt); - svgCanvas.setHref(gridimg, datauri); - }; - - $ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale; - _context.next = 5; - return importLocale(); - - case 5: - strings = _context.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000]; - showGrid = svgEditor.curConfig.showGrid || false; - $(hcanvas).hide().appendTo('body'); - canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg'); - assignAttributes(canvasGrid, { - id: 'canvasGrid', - width: '100%', - height: '100%', - x: 0, - y: 0, - overflow: 'visible', - display: 'none' - }); - canvBG.append(canvasGrid); - gridDefs = svgdoc.createElementNS(NS.SVG, 'defs'); // grid-pattern - - gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern'); - assignAttributes(gridPattern, { - id: 'gridpattern', - patternUnits: 'userSpaceOnUse', - x: 0, - // -(value.strokeWidth / 2), // position for strokewidth - y: 0, - // -(value.strokeWidth / 2), // position for strokewidth - width: 100, - height: 100 - }); - gridimg = svgdoc.createElementNS(NS.SVG, 'image'); - assignAttributes(gridimg, { - x: 0, - y: 0, - width: 100, - height: 100 - }); - gridPattern.append(gridimg); - gridDefs.append(gridPattern); - $('#canvasGrid').append(gridDefs); // grid-box - - gridBox = svgdoc.createElementNS(NS.SVG, 'rect'); - assignAttributes(gridBox, { - width: '100%', - height: '100%', - x: 0, - y: 0, - 'stroke-width': 0, - stroke: 'none', - fill: 'url(#gridpattern)', - style: 'pointer-events: none; display:visible;' - }); - $('#canvasGrid').append(gridBox); - /** - * - * @param {Float} zoom - * @returns {void} - */ - - buttons = [{ - id: 'view_grid', - icon: svgEditor.curConfig.extIconsPath + 'grid.png', - type: 'context', - panel: 'editor_panel', - events: { - click: function click() { - svgEditor.curConfig.showGrid = showGrid = !showGrid; - gridUpdate(); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml', - zoomChanged: function zoomChanged(zoom) { - if (showGrid) { - updateGrid(zoom); - } - }, - callback: function callback() { - if (showGrid) { - gridUpdate(); - } - }, - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }) - }); - - case 27: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-helloworld.js b/dist/editor/system/extensions/ext-helloworld.js deleted file mode 100644 index 14f91994..00000000 --- a/dist/editor/system/extensions/ext-helloworld.js +++ /dev/null @@ -1,1763 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - /** - * @file ext-helloworld.js - * - * @license MIT - * - * @copyright 2010 Alexis Deveria - * - */ - - /** - * This is a very basic SVG-Edit extension. It adds a "Hello World" button in - * the left ("mode") panel. Clicking on the button, and then the canvas - * will show the user the point on the canvas that was clicked on. - */ - var extHelloworld = exports('default', { - name: 'helloworld', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var $, importLocale, strings, svgEditor, svgCanvas; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - $ = _ref.$, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - return _context.abrupt("return", { - name: strings.name, - // For more notes on how to make an icon file, see the source of - // the helloworld-icon.xml - svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', - // Multiple buttons can be added in this array - buttons: [{ - // Must match the icon ID in helloworld-icon.xml - id: 'hello_world', - // Fallback, e.g., for `file:///` access - icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', - // This indicates that the button will be added to the "mode" - // button panel on the left side - type: 'mode', - // Tooltip text - title: strings.buttons[0].title, - // Events - events: { - click: function click() { - // The action taken when the button is clicked on. - // For "mode" buttons, any other button will - // automatically be de-pressed. - svgCanvas.setMode('hello_world'); - } - } - }], - // This is triggered when the main mouse button is pressed down - // on the editor canvas (not the tool panels) - mouseDown: function mouseDown() { - // Check the mode on mousedown - if (svgCanvas.getMode() === 'hello_world') { - // The returned object must include "started" with - // a value of true in order for mouseUp to be triggered - return { - started: true - }; - } - - return undefined; - }, - // This is triggered from anywhere, but "started" must have been set - // to true (see above). Note that "opts" is an object with event info - mouseUp: function mouseUp(opts) { - // Check the mode on mouseup - if (svgCanvas.getMode() === 'hello_world') { - var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value - - var x = opts.mouse_x / zoom; - var y = opts.mouse_y / zoom; // We do our own formatting - - var text = strings.text; - [['x', x], ['y', y]].forEach(function (_ref2) { - var _ref3 = _slicedToArray(_ref2, 2), - prop = _ref3[0], - val = _ref3[1]; - - text = text.replace('{' + prop + '}', val); - }); // Show the text using the custom alert function - - $.alert(text); - } - } - }); - - case 7: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }); - - } - }; -}); diff --git a/dist/editor/system/extensions/ext-imagelib.js b/dist/editor/system/extensions/ext-imagelib.js deleted file mode 100644 index def88a46..00000000 --- a/dist/editor/system/extensions/ext-imagelib.js +++ /dev/null @@ -1,2176 +0,0 @@ -System.register([], function (exports) { - 'use strict'; - return { - execute: function () { - - 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); - } - - var REACT_ELEMENT_TYPE; - - function _jsx(type, props, key, children) { - if (!REACT_ELEMENT_TYPE) { - REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; - } - - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = { - children: void 0 - }; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = new Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - function _AwaitValue(value) { - this.wrapped = value; - } - - function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - _AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - _AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - _AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - _AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; - } - - function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); - } - - function _asyncGeneratorDelegate(inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("return", value); - }; - } - - return iter; - } - - 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 _defineEnumerableProperties(obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - if (Object.getOwnPropertySymbols) { - var objectSymbols = Object.getOwnPropertySymbols(descs); - - for (var i = 0; i < objectSymbols.length; i++) { - var sym = objectSymbols[i]; - var desc = descs[sym]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, sym, desc); - } - } - - return obj; - } - - function _defaults(obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? Object(arguments[i]) : {}; - var ownKeys = Object.keys(source); - - if (typeof Object.getOwnPropertySymbols === 'function') { - ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { - return Object.getOwnPropertyDescriptor(source, sym).enumerable; - })); - } - - ownKeys.forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } - - return target; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - 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 _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = 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 _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _instanceof(left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return !!right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function () { - return cache; - }; - - return cache; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj.default = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; - } - - function _newArrowCheck(innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } - } - - function _objectDestructuringEmpty(obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; - } - - function _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 set(target, property, value, receiver) { - if (typeof Reflect !== "undefined" && Reflect.set) { - set = Reflect.set; - } else { - set = function set(target, property, value, receiver) { - var base = _superPropBase(target, property); - - var desc; - - if (base) { - desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.set) { - desc.set.call(receiver, value); - return true; - } else if (!desc.writable) { - return false; - } - } - - desc = Object.getOwnPropertyDescriptor(receiver, property); - - if (desc) { - if (!desc.writable) { - return false; - } - - desc.value = value; - Object.defineProperty(receiver, property, desc); - } else { - _defineProperty(receiver, property, value); - } - - return true; - }; - } - - return set(target, property, value, receiver); - } - - function _set(target, property, value, receiver, isStrict) { - var s = set(target, property, value, receiver || target); - - if (!s && isStrict) { - throw new Error('failed to set property'); - } - - return value; - } - - function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); - } - - function _taggedTemplateLiteralLoose(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - strings.raw = raw; - return strings; - } - - function _readOnlyError(name) { - throw new Error("\"" + name + "\" is read-only"); - } - - function _classNameTDZError(name) { - throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); - } - - function _temporalUndefined() {} - - function _tdz(name) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } - - function _temporalRef(val, name) { - return val === _temporalUndefined ? _tdz(name) : val; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _slicedToArrayLoose(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _maybeArrayLike(next, arr, i) { - if (arr && !Array.isArray(arr) && typeof arr.length === "number") { - var len = arr.length; - return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); - } - - return next(arr, i); - } - - 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 _iterableToArrayLimitLoose(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - 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; - } - } - }; - } - - function _createForOfIteratorHelperLoose(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; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function _skipFirstGeneratorNext(fn) { - return function () { - var it = fn.apply(this, arguments); - it.next(); - return it; - }; - } - - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - - return (hint === "string" ? String : Number)(input); - } - - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - - return typeof key === "symbol" ? key : String(key); - } - - function _initializerWarningHelper(descriptor, context) { - throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); - } - - function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 - }); - } - - function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { - var desc = {}; - Object.keys(descriptor).forEach(function (key) { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce(function (desc, decorator) { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== void 0) { - desc.value = desc.initializer ? desc.initializer.call(context) : void 0; - desc.initializer = undefined; - } - - if (desc.initializer === void 0) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; - } - - var id = 0; - - function _classPrivateFieldLooseKey(name) { - return "__private_" + id++ + "_" + name; - } - - function _classPrivateFieldLooseBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); - } - - return receiver; - } - - function _classPrivateFieldGet(receiver, privateMap) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to get private field on non-instance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classPrivateFieldSet(receiver, privateMap, value) { - var descriptor = privateMap.get(receiver); - - if (!descriptor) { - throw new TypeError("attempted to set private field on non-instance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classPrivateFieldDestructureSet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - - var descriptor = privateMap.get(receiver); - - if (descriptor.set) { - if (!("__destrObj" in descriptor)) { - descriptor.__destrObj = { - set value(v) { - descriptor.set.call(receiver, v); - } - - }; - } - - return descriptor.__destrObj; - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - return descriptor; - } - } - - function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.get) { - return descriptor.get.call(receiver); - } - - return descriptor.value; - } - - function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - if (descriptor.set) { - descriptor.set.call(receiver, value); - } else { - if (!descriptor.writable) { - throw new TypeError("attempted to set read only private field"); - } - - descriptor.value = value; - } - - return value; - } - - function _classStaticPrivateMethodGet(receiver, classConstructor, method) { - if (receiver !== classConstructor) { - throw new TypeError("Private static access of wrong provenance"); - } - - return method; - } - - function _classStaticPrivateMethodSet() { - throw new TypeError("attempted to set read only static private field"); - } - - function _decorate(decorators, factory, superClass, mixins) { - var api = _getDecoratorsApi(); - - if (mixins) { - for (var i = 0; i < mixins.length; i++) { - api = mixins[i](api); - } - } - - var r = factory(function initialize(O) { - api.initializeInstanceElements(O, decorated.elements); - }, superClass); - var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); - api.initializeClassElements(r.F, decorated.elements); - return api.runClassFinishers(r.F, decorated.finishers); - } - - function _getDecoratorsApi() { - _getDecoratorsApi = function () { - return api; - }; - - var api = { - elementsDefinitionOrder: [["method"], ["field"]], - initializeInstanceElements: function (O, elements) { - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - if (element.kind === kind && element.placement === "own") { - this.defineClassElement(O, element); - } - }, this); - }, this); - }, - initializeClassElements: function (F, elements) { - var proto = F.prototype; - ["method", "field"].forEach(function (kind) { - elements.forEach(function (element) { - var placement = element.placement; - - if (element.kind === kind && (placement === "static" || placement === "prototype")) { - var receiver = placement === "static" ? F : proto; - this.defineClassElement(receiver, element); - } - }, this); - }, this); - }, - defineClassElement: function (receiver, element) { - var descriptor = element.descriptor; - - if (element.kind === "field") { - var initializer = element.initializer; - descriptor = { - enumerable: descriptor.enumerable, - writable: descriptor.writable, - configurable: descriptor.configurable, - value: initializer === void 0 ? void 0 : initializer.call(receiver) - }; - } - - Object.defineProperty(receiver, element.key, descriptor); - }, - decorateClass: function (elements, decorators) { - var newElements = []; - var finishers = []; - var placements = { - static: [], - prototype: [], - own: [] - }; - elements.forEach(function (element) { - this.addElementPlacement(element, placements); - }, this); - elements.forEach(function (element) { - if (!_hasDecorators(element)) return newElements.push(element); - var elementFinishersExtras = this.decorateElement(element, placements); - newElements.push(elementFinishersExtras.element); - newElements.push.apply(newElements, elementFinishersExtras.extras); - finishers.push.apply(finishers, elementFinishersExtras.finishers); - }, this); - - if (!decorators) { - return { - elements: newElements, - finishers: finishers - }; - } - - var result = this.decorateConstructor(newElements, decorators); - finishers.push.apply(finishers, result.finishers); - result.finishers = finishers; - return result; - }, - addElementPlacement: function (element, placements, silent) { - var keys = placements[element.placement]; - - if (!silent && keys.indexOf(element.key) !== -1) { - throw new TypeError("Duplicated element (" + element.key + ")"); - } - - keys.push(element.key); - }, - decorateElement: function (element, placements) { - var extras = []; - var finishers = []; - - for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { - var keys = placements[element.placement]; - keys.splice(keys.indexOf(element.key), 1); - var elementObject = this.fromElementDescriptor(element); - var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); - element = elementFinisherExtras.element; - this.addElementPlacement(element, placements); - - if (elementFinisherExtras.finisher) { - finishers.push(elementFinisherExtras.finisher); - } - - var newExtras = elementFinisherExtras.extras; - - if (newExtras) { - for (var j = 0; j < newExtras.length; j++) { - this.addElementPlacement(newExtras[j], placements); - } - - extras.push.apply(extras, newExtras); - } - } - - return { - element: element, - finishers: finishers, - extras: extras - }; - }, - decorateConstructor: function (elements, decorators) { - var finishers = []; - - for (var i = decorators.length - 1; i >= 0; i--) { - var obj = this.fromClassDescriptor(elements); - var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); - - if (elementsAndFinisher.finisher !== undefined) { - finishers.push(elementsAndFinisher.finisher); - } - - if (elementsAndFinisher.elements !== undefined) { - elements = elementsAndFinisher.elements; - - for (var j = 0; j < elements.length - 1; j++) { - for (var k = j + 1; k < elements.length; k++) { - if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { - throw new TypeError("Duplicated element (" + elements[j].key + ")"); - } - } - } - } - } - - return { - elements: elements, - finishers: finishers - }; - }, - fromElementDescriptor: function (element) { - var obj = { - kind: element.kind, - key: element.key, - placement: element.placement, - descriptor: element.descriptor - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - if (element.kind === "field") obj.initializer = element.initializer; - return obj; - }, - toElementDescriptors: function (elementObjects) { - if (elementObjects === undefined) return; - return _toArray(elementObjects).map(function (elementObject) { - var element = this.toElementDescriptor(elementObject); - this.disallowProperty(elementObject, "finisher", "An element descriptor"); - this.disallowProperty(elementObject, "extras", "An element descriptor"); - return element; - }, this); - }, - toElementDescriptor: function (elementObject) { - var kind = String(elementObject.kind); - - if (kind !== "method" && kind !== "field") { - throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); - } - - var key = _toPropertyKey(elementObject.key); - - var placement = String(elementObject.placement); - - if (placement !== "static" && placement !== "prototype" && placement !== "own") { - throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); - } - - var descriptor = elementObject.descriptor; - this.disallowProperty(elementObject, "elements", "An element descriptor"); - var element = { - kind: kind, - key: key, - placement: placement, - descriptor: Object.assign({}, descriptor) - }; - - if (kind !== "field") { - this.disallowProperty(elementObject, "initializer", "A method descriptor"); - } else { - this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); - this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); - element.initializer = elementObject.initializer; - } - - return element; - }, - toElementFinisherExtras: function (elementObject) { - var element = this.toElementDescriptor(elementObject); - - var finisher = _optionalCallableProperty(elementObject, "finisher"); - - var extras = this.toElementDescriptors(elementObject.extras); - return { - element: element, - finisher: finisher, - extras: extras - }; - }, - fromClassDescriptor: function (elements) { - var obj = { - kind: "class", - elements: elements.map(this.fromElementDescriptor, this) - }; - var desc = { - value: "Descriptor", - configurable: true - }; - Object.defineProperty(obj, Symbol.toStringTag, desc); - return obj; - }, - toClassDescriptor: function (obj) { - var kind = String(obj.kind); - - if (kind !== "class") { - throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); - } - - this.disallowProperty(obj, "key", "A class descriptor"); - this.disallowProperty(obj, "placement", "A class descriptor"); - this.disallowProperty(obj, "descriptor", "A class descriptor"); - this.disallowProperty(obj, "initializer", "A class descriptor"); - this.disallowProperty(obj, "extras", "A class descriptor"); - - var finisher = _optionalCallableProperty(obj, "finisher"); - - var elements = this.toElementDescriptors(obj.elements); - return { - elements: elements, - finisher: finisher - }; - }, - runClassFinishers: function (constructor, finishers) { - for (var i = 0; i < finishers.length; i++) { - var newConstructor = (0, finishers[i])(constructor); - - if (newConstructor !== undefined) { - if (typeof newConstructor !== "function") { - throw new TypeError("Finishers must return a constructor."); - } - - constructor = newConstructor; - } - } - - return constructor; - }, - disallowProperty: function (obj, name, objectType) { - if (obj[name] !== undefined) { - throw new TypeError(objectType + " can't have a ." + name + " property."); - } - } - }; - return api; - } - - function _createElementDescriptor(def) { - var key = _toPropertyKey(def.key); - - var descriptor; - - if (def.kind === "method") { - descriptor = { - value: def.value, - writable: true, - configurable: true, - enumerable: false - }; - } else if (def.kind === "get") { - descriptor = { - get: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "set") { - descriptor = { - set: def.value, - configurable: true, - enumerable: false - }; - } else if (def.kind === "field") { - descriptor = { - configurable: true, - writable: true, - enumerable: true - }; - } - - var element = { - kind: def.kind === "field" ? "field" : "method", - key: key, - placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", - descriptor: descriptor - }; - if (def.decorators) element.decorators = def.decorators; - if (def.kind === "field") element.initializer = def.value; - return element; - } - - function _coalesceGetterSetter(element, other) { - if (element.descriptor.get !== undefined) { - other.descriptor.get = element.descriptor.get; - } else { - other.descriptor.set = element.descriptor.set; - } - } - - function _coalesceClassElements(elements) { - var newElements = []; - - var isSameElement = function (other) { - return other.kind === "method" && other.key === element.key && other.placement === element.placement; - }; - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - var other; - - if (element.kind === "method" && (other = newElements.find(isSameElement))) { - if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { - if (_hasDecorators(element) || _hasDecorators(other)) { - throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); - } - - other.descriptor = element.descriptor; - } else { - if (_hasDecorators(element)) { - if (_hasDecorators(other)) { - throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); - } - - other.decorators = element.decorators; - } - - _coalesceGetterSetter(element, other); - } - } else { - newElements.push(element); - } - } - - return newElements; - } - - function _hasDecorators(element) { - return element.decorators && element.decorators.length; - } - - function _isDataDescriptor(desc) { - return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); - } - - function _optionalCallableProperty(obj, name) { - var value = obj[name]; - - if (value !== undefined && typeof value !== "function") { - throw new TypeError("Expected '" + name + "' to be a function"); - } - - return value; - } - - function _classPrivateMethodGet(receiver, privateSet, fn) { - if (!privateSet.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - - return fn; - } - - function _classPrivateMethodSet() { - throw new TypeError("attempted to reassign private method"); - } - - function _wrapRegExp(re, groups) { - _wrapRegExp = function (re, groups) { - return new BabelRegExp(re, undefined, groups); - }; - - var _RegExp = _wrapNativeSuper(RegExp); - - var _super = RegExp.prototype; - - var _groups = new WeakMap(); - - function BabelRegExp(re, flags, groups) { - var _this = _RegExp.call(this, re, flags); - - _groups.set(_this, groups || _groups.get(re)); - - return _this; - } - - _inherits(BabelRegExp, _RegExp); - - BabelRegExp.prototype.exec = function (str) { - var result = _super.exec.call(this, str); - - if (result) result.groups = buildGroups(result, this); - return result; - }; - - BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { - if (typeof substitution === "string") { - var groups = _groups.get(this); - - return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { - return "$" + groups[name]; - })); - } else if (typeof substitution === "function") { - var _this = this; - - return _super[Symbol.replace].call(this, str, function () { - var args = []; - args.push.apply(args, arguments); - - if (typeof args[args.length - 1] !== "object") { - args.push(buildGroups(args, _this)); - } - - return substitution.apply(this, args); - }); - } else { - return _super[Symbol.replace].call(this, str, substitution); - } - }; - - function buildGroups(result, re) { - var g = _groups.get(re); - - return Object.keys(g).reduce(function (groups, name) { - groups[name] = result[g[name]]; - return groups; - }, Object.create(null)); - } - - return _wrapRegExp.apply(this, arguments); - } - - var extImagelib = "ext-imagelib.xml"; - - var extImagelib$1 = exports('default', { - name: 'imagelib', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, onMessage, _onMessage, toggleMulti, showBrowser, buttons; - - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - showBrowser = function _showBrowser() { - var browser = $('#imgbrowse'); - - if (!browser.length) { - $('
    ' + '
    ').insertAfter('#svg_docprops'); - browser = $('#imgbrowse'); - var allLibs = imagelibStrings.select_lib; - var libOpts = $('
      ').appendTo(browser); - var frame = $('', - 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: "<>" - }), 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 = "<>", f.content = i; - var g = f.objId + " 0 R"; - i = "<>";else if (n.options.pageNumber) { - switch (i = "<= 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 <>"); - }), 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 - * Chris G Jones - * Shaon Barman - * Vivien Nicolas <21@vingtetun.org> - * Justin D'Arcangelo - * 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 , 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 = '', - e = unescape(encodeURIComponent('')), - n = unescape(encodeURIComponent(t)), - r = unescape(encodeURIComponent(this.internal.__metadata__.metadata)), - i = unescape(encodeURIComponent("")), - a = unescape(encodeURIComponent("")), - 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>\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("<>"), 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 - * - * 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) { - // 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 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 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); - }; - - /** - * @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 - }; - } - - var canvg; - /** - * @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, - _yield$import$default, - 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 (canvg) { - _context2.next = 10; - break; - } - - _context2.next = 8; - return module.import(curConfig.canvgPath + 'canvg.js')["default"]; - - case 8: - _yield$import$default = _context2.sent; - canvg = _yield$import$default.canvg; - - case 10: - 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 = 16; - return canvg(c, svg); - - case 16: - 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 17: - 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$1 = 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$1(name)) name = 'xy'; - - switch (name.toLowerCase()) { - case 'x': - return x; - - case 'y': - return y; - - case 'xy': - default: - return { - x: x, - y: y - }; - } - } - - if (!isNullish$1(context) && context === that) return undefined; - var changed = false; - var newX, newY; - if (isNullish$1(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$1(newX)) { - if (newX < minX) newX = minX;else if (newX > maxX) newX = maxX; - - if (x !== newX) { - x = newX; - changed = true; - } - } - - if (!isNullish$1(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$1(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$1(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$1(newMinX) && minX !== newMinX) { - minX = newMinX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMaxX) && maxX !== newMaxX) { - maxX = newMaxX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMinY) && minY !== newMinY) { - minY = newMinY; - rangeY = maxY - minY; - } - - if (!isNullish$1(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$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(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$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(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$1(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$1(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$1(all) ? all.r : ''); - if (context !== green.get(0)) green.val(!isNullish$1(all) ? all.g : ''); - if (context !== blue.get(0)) blue.val(!isNullish$1(all) ? all.b : ''); - if (alpha && context !== alpha.get(0)) alpha.val(!isNullish$1(all) ? toFixedNumeric(all.a * 100 / 255, alphaPrecision) : ''); - if (context !== hue.get(0)) hue.val(!isNullish$1(all) ? all.h : ''); - if (context !== saturation.get(0)) saturation.val(!isNullish$1(all) ? all.s : ''); - if (context !== value.get(0)) value.val(!isNullish$1(all) ? all.v : ''); - if (context !== hex.get(0) && (bindedHex && context !== bindedHex.get(0) || !bindedHex)) hex.val(!isNullish$1(all) ? all.hex : ''); - if (bindedHex && context !== bindedHex.get(0) && context !== hex.get(0)) bindedHex.val(!isNullish$1(all) ? all.hex : ''); - if (ahex && context !== ahex.get(0)) ahex.val(!isNullish$1(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$1(name) || name === '') name = 'all'; - if (isNullish$1(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$1(context) && context === that) return undefined; - if (isNullish$1(name)) name = ''; - var changed = false; - - if (isNullish$1(value)) { - if (!isNullish$1(r)) { - r = null; - changed = true; - } - - if (!isNullish$1(g)) { - g = null; - changed = true; - } - - if (!isNullish$1(b)) { - b = null; - changed = true; - } - - if (!isNullish$1(a)) { - a = null; - changed = true; - } - - if (!isNullish$1(h)) { - h = null; - changed = true; - } - - if (!isNullish$1(s)) { - s = null; - changed = true; - } - - if (!isNullish$1(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$1(a) ? a : 255 - }, context); - break; - } - - default: - { - if (value && (!isNullish$1(value.ahex) || !isNullish$1(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$1(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$1(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$1(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$1(s) ? s : 100; - v = !isNullish$1(v) ? v : 100; - - var _ret3 = ColorMethods.hsvToRgb({ - h: h, - s: s, - v: v - }); - - r = _ret3.r; - g = _ret3.g; - b = _ret3.b; - } - - a = !isNullish$1(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$1(init.ahex)) { - val('ahex', init); - } else if (!isNullish$1(init.hex)) { - val((!isNullish$1(init.a) ? 'a' : '') + 'hex', !isNullish$1(init.a) ? { - ahex: init.hex + ColorMethods.intToHex(init.a) - } : init); - } else if (!isNullish$1(init.r) && !isNullish$1(init.g) && !isNullish$1(init.b)) { - val('rgb' + (!isNullish$1(init.a) ? 'a' : ''), init); - } else if (!isNullish$1(init.h) && !isNullish$1(init.s) && !isNullish$1(init.v)) { - val('hsv' + (!isNullish$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(sv) ? sv.s : 100, - y: 100 - (!isNullish$1(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$1(hv) ? hv.v : 100) - }, context); - break; - } - - case 'v': - { - var hs = ui.val('hs'); - colorMap.val('xy', { - x: hs && hs.h || 0, - y: 100 - (!isNullish$1(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$1(s) ? s : 100), context); - break; - } - - case 'v': - { - var v = ui.val('v'); - colorBar.val('y', 100 - (!isNullish$1(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$1(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$1(s) ? s : 100)); - break; - } - - case 'v': - { - var v = ui.val('v'); - setAlpha.call(that, colorMapL1, !isNullish$1(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$1(hva) ? hva.v : 100 - }); - setBG.call(that, colorBarDiv, saturatedColor.val('hex')); - setAlpha.call(that, colorBarL2, 100 - (!isNullish$1(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$1(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$1(_a) ? 0 : 100); - setAlpha.call(that, colorBarL6, !isNullish$1(_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$1(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$1(_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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(all) ? all.hex : '', "\"/></label>").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"2\" class=\"AHex\" value=\"".concat(!isNullish$1(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$1(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$1(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$1(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 $; - }; - - /* 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 - * @param {{langPath: string}} conf - * @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, conf) { - var url, module$1; - 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'; - } - - url = "".concat(conf.langPath, "lang.").concat(langParam, ".js"); // eslint-disable-next-line node/no-unsupported-features/es-syntax - - _context2.next = 6; - return module.import(url); - - case 6: - module$1 = _context2.sent; - return _context2.abrupt("return", readLang(module$1["default"])); - - case 8: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - - return function putLocale(_x2, _x3, _x4) { - 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} [langPath="locale/"] The path where the language files are located, with trailing slash. Default will be changed to `../dist/locale/` if this is a modular load. 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 {string} [canvgPath="canvg/"] The path used for `canvg` files, with trailing slash. Default will be changed to `../dist/` if this is a modular load. - * @property {string} [extIconsPath="extensions/"] The path used for extension icons, with trailing slash. - * @property {string} [jGraduatePath="jgraduate/images/"] The path where jGraduate images are located. 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) - langPath: './locale/', - // Default will be changed if this is a non-modular load - extPath: './extensions/', - // Default will be changed if this is a non-modular load - canvgPath: './canvg/', - // Default will be changed if this is a non-modular load - imgPath: './images/', - jGraduatePath: './images/', - extIconsPath: './extensions/', - // 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 module.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 - - - ['langPath', 'extPath', 'canvgPath', 'imgPath', 'jGraduatePath', 'extIconsPath'].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, curConfig); - - 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 module.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(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, curConfig); - - 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({ - paint: paint, - window: { - pickerTitle: title - }, - images: { - clientPath: curConfig.jGraduatePath - }, - 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/', - // langPath: './locale/', - // extPath: 'extensions/', - // jGraduatePath: 'jgraduate/images/', - - /* - 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