Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Bug] Fix uglify error compiling dom-to-image in prod (#682)

Shan He2bb3867a767f
diff --git a/.nvmrc b/.nvmrc
index 8104cabd3..df5119ec6 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-8.1.0
+8.7.0
diff --git a/package.json b/package.json
index 833618e1e..888fb649e 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
"license": "MIT",
"main": "dist/index.js",
"engines": {
- "node": ">=8.1.0",
+ "node": ">=8.7.0",
"npm": ">=6.1.0",
"yarn": ">=1.6.0"
},
diff --git a/src/utils/dom-to-image.js b/src/utils/dom-to-image.js
index 387bbccfb..1e5f1072e 100644
--- a/src/utils/dom-to-image.js
+++ b/src/utils/dom-to-image.js
@@ -28,8 +28,24 @@ import document from 'global/document';
import console from 'global/console';
import svgToMiniDataURI from 'mini-svg-data-uri';
import {IMAGE_EXPORT_ERRORS} from 'constants/user-feedbacks';
+import {
+ canvasToBlob,
+ escape,
+ escapeXhtml,
+ delay,
+ processClone,
+ asArray,
+ makeImage,
+ mimeType,
+ dataAsUrl,
+ isDataUrl,
+ isSrcAsDataUrl,
+ resolveUrl,
+ getWidth,
+ getHeight,
+ getAndEncode
+} from './dom-utils';
-const util = newUtil();
const inliner = newInliner();
const fontFaces = newFontFaces();
const images = newImages();
@@ -50,7 +66,6 @@ const domtoimage = {
impl: {
fontFaces,
images,
- util,
inliner,
options: {}
}
@@ -82,8 +97,8 @@ function toSvg(node, options) {
.then(clone =>
makeSvgDataUri(
clone,
- options.width || util.width(node),
- options.height || util.height(node)
+ options.width || getWidth(node),
+ options.height || getHeight(node)
)
);
@@ -111,7 +126,7 @@ function toPixelData(node, options) {
return draw(node, options || {}).then(canvas =>
canvas
.getContext('2d')
- .getImageData(0, 0, util.width(node), util.height(node)).data
+ .getImageData(0, 0, getWidth(node), getHeight(node)).data
);
}
@@ -140,7 +155,7 @@ function toJpeg(node, options) {
* @return {Promise} - A promise that is fulfilled with a PNG image blob
* */
function toBlob(node, options) {
- return draw(node, options || {}).then(util.canvasToBlob);
+ return draw(node, options || {}).then(canvasToBlob);
}
function copyOptions(options) {
@@ -161,8 +176,8 @@ function copyOptions(options) {
function draw(domNode, options) {
return toSvg(domNode, options)
- .then(util.makeImage)
- .then(util.delay(100))
+ .then(makeImage)
+ .then(delay(100))
.then(image => {
const canvas = newCanvas(domNode);
canvas.getContext('2d').drawImage(image, 0, 0);
@@ -171,8 +186,8 @@ function draw(domNode, options) {
function newCanvas(dNode) {
const canvas = document.createElement('canvas');
- canvas.width = options.width || util.width(dNode);
- canvas.height = options.height || util.height(dNode);
+ canvas.width = options.width || getWidth(dNode);
+ canvas.height = options.height || getHeight(dNode);
if (options.bgcolor) {
const ctx = canvas.getContext('2d');
@@ -196,135 +211,34 @@ function cloneNode(node, filter, root) {
function makeNodeCopy(nd) {
if (nd instanceof window.HTMLCanvasElement) {
- return util.makeImage(nd.toDataURL());
+ return makeImage(nd.toDataURL());
}
return nd.cloneNode(false);
}
+ function cloneChildrenInOrder(parent, arrChildren, flt) {
+ let done = Promise.resolve();
+ arrChildren.forEach(child => {
+ done = done
+ .then(() => cloneNode(child, flt))
+ .then(childClone => {
+ if (childClone) {
+ parent.appendChild(childClone);
+ }
+ });
+ });
+ return done;
+ }
+
function cloneChildren(original, clone, flt) {
const children = original.childNodes;
if (children.length === 0) {
return Promise.resolve(clone);
}
- function cloneChildrenInOrder(parent, arrChildren) {
- let done = Promise.resolve();
- arrChildren.forEach(child => {
- done = done
- .then(() => cloneNode(child, flt))
- .then(childClone => {
- if (childClone) parent.appendChild(childClone);
- });
- });
- return done;
- }
-
- return cloneChildrenInOrder(clone, util.asArray(children))
+ return cloneChildrenInOrder(clone, asArray(children), flt)
.then(() => clone);
}
-
- function processClone(original, clone) {
- if (!(clone instanceof window.Element)) {
- return clone
- };
-
- return Promise.resolve()
- .then(cloneStyle)
- .then(clonePseudoElements)
- .then(copyUserInput)
- .then(fixSvg)
- .then(() => clone);
-
- function cloneStyle() {
- const originalStyle = window.getComputedStyle(original);
- copyStyle(originalStyle, clone.style);
- function copyStyle(source, target) {
- if (source.cssText) {
- target.cssText = source.cssText;
- // add additional copy of composite styles
- if (source.font) {
- target.font = source.font;
- }
- } else {
- copyProperties(source, target);
- }
- function copyProperties(sourceStyle, targetStyle) {
- const propertyKeys = util.asArray(sourceStyle);
- propertyKeys.forEach(name => {
- targetStyle.setProperty(
- name,
- sourceStyle.getPropertyValue(name),
- sourceStyle.getPropertyPriority(name)
- );
- });
- }
- }
- }
-
- function clonePseudoElements() {
- [':before', ':after'].forEach(element => clonePseudoElement(element));
-
- function clonePseudoElement(element) {
- const style = window.getComputedStyle(original, element);
- const content = style.getPropertyValue('content');
-
- if (content === '' || content === 'none') {
- return;
- }
-
- const className = util.uid();
- clone.className = `${clone.className} ${className}`;
- const styleElement = document.createElement('style');
- styleElement.appendChild(
- formatPseudoElementStyle(className, element, style)
- );
- clone.appendChild(styleElement);
-
- function formatPseudoElementStyle(cln, elm, stl) {
- const selector = `.${cln}:${elm}`;
- const cssText = stl.cssText
- ? formatCssText(stl)
- : formatCssProperties(stl);
- return document.createTextNode(`${selector}{${cssText}}`);
-
- function formatCssText(stl1) {
- const cnt = stl1.getPropertyValue('content');
- return `${stl.cssText} content: ${cnt};`;
- }
-
- function formatCssProperties(stl2) {
- return `${util.asArray(stl2).map(formatProperty).join('; ')};`;
-
- function formatProperty(name) {
- return (
- `${name}:${stl.getPropertyValue(name)}${stl.getPropertyPriority(name) ? ' !important' : ''}`
- );
- }
- }
- }
- }
- }
-
- function copyUserInput() {
- if (original instanceof window.HTMLTextAreaElement)
- clone.innerHTML = original.value;
- if (original instanceof window.HTMLInputElement)
- clone.setAttribute('value', original.value);
- }
-
- function fixSvg() {
- if (!(clone instanceof window.SVGElement)) return;
- clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
-
- if (!(clone instanceof window.SVGRectElement)) return;
- ['width', 'height'].forEach(attribute => {
- const value = clone.getAttribute(attribute);
- if (!value) return;
-
- clone.style.setProperty(attribute, value);
- });
- }
- }
}
function embedFonts(node) {
@@ -346,7 +260,7 @@ function makeSvgDataUri(node, width, height) {
nd.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
const serializedString = new window.XMLSerializer().serializeToString(nd);
- const xhtml = util.escapeXhtml(serializedString);
+ const xhtml = escapeXhtml(serializedString);
const foreignObject = `<foreignObject x="0" y="0" width="100%" height="100%">${xhtml}</foreignObject>`;
const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${foreignObject}</svg>`;
@@ -358,244 +272,6 @@ function makeSvgDataUri(node, width, height) {
});
}
-function newUtil() {
- return {
- escape,
- parseExtension,
- mimeType,
- dataAsUrl,
- isDataUrl,
- isSrcAsDataUrl,
- canvasToBlob,
- resolveUrl,
- getAndEncode,
- uid: uid(),
- delay,
- asArray,
- escapeXhtml,
- makeImage,
- width,
- height
- };
-
- function mimes() {
- /*
- * Only WOFF and EOT mime types for fonts are 'real'
- * see http://www.iana.org/assignments/media-types/media-types.xhtml
- */
- const WOFF = 'application/font-woff';
- const JPEG = 'image/jpeg';
-
- return {
- woff: WOFF,
- woff2: WOFF,
- ttf: 'application/font-truetype',
- eot: 'application/vnd.ms-fontobject',
- png: 'image/png',
- jpg: JPEG,
- jpeg: JPEG,
- gif: 'image/gif',
- tiff: 'image/tiff',
- svg: 'image/svg+xml'
- };
- }
-
- function parseExtension(url) {
- const match = /\.([^\.\/]*?)$/g.exec(url);
- if (match) {
- return match[1];
- }
- return '';
- }
-
- function mimeType(url) {
- const extension = parseExtension(url).toLowerCase();
- return mimes()[extension] || '';
- }
-
- function isDataUrl(url) {
- return url.search(/^(data:)/) !== -1;
- }
-
- function isSrcAsDataUrl(text) {
- const DATA_URL_REGEX = /url\(['"]?(data:)([^'"]+?)['"]?\)/;
-
- return text.search(DATA_URL_REGEX) !== -1;
- }
- function cvToBlob(canvas) {
- return new Promise(resolve => {
- const binaryString = window.atob(canvas.toDataURL().split(',')[1]);
- const length = binaryString.length;
- const binaryArray = new Uint8Array(length);
-
- for (let i = 0; i < length; i++)
- binaryArray[i] = binaryString.charCodeAt(i);
-
- resolve(
- new window.Blob([binaryArray], {type: 'image/png'})
- );
- });
- }
-
- function canvasToBlob(canvas) {
- if (canvas.toBlob)
- return new Promise(resolve => {
- canvas.toBlob(resolve);
- });
-
- return cvToBlob(canvas);
- }
-
- function resolveUrl(url, baseUrl) {
- const doc = document.implementation.createHTMLDocument();
- const base = doc.createElement('base');
- doc.head.appendChild(base);
- const a = doc.createElement('a');
- doc.body.appendChild(a);
- base.href = baseUrl;
- a.href = url;
- return a.href;
- }
-
- function fourRandomChars() {
- /* see http://stackoverflow.com/a/6248722/2519373 */
- return `0000${((Math.random() * Math.pow(36, 4)) << 0).toString(36)}`.slice(-4);
- }
-
- function uid() {
- let index = 0;
-
- return () => `u${fourRandomChars()}${index++}`;
- }
-
- function makeImage(uri) {
- return new Promise((resolve, reject) => {
- const image = new window.Image();
- image.onload = () => {
- resolve(image);
- };
- image.onerror = (err) => {
- const message = IMAGE_EXPORT_ERRORS.dataUri;
- console.log(uri);
- // error is an Event Object
- // https://www.w3schools.com/jsref/obj_event.asp
- reject({event: err, message});
- };
- image.src = uri;
- });
- }
-
- function getAndEncode(url) {
- const TIMEOUT = 30000;
- if (domtoimage.impl.options.cacheBust) {
- // Cache bypass so we dont have CORS issues with cached images
- // Source: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
- url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
- }
-
- return new Promise(resolve => {
- const request = new window.XMLHttpRequest();
-
- request.onreadystatechange = done;
- request.ontimeout = timeout;
- request.responseType = 'blob';
- request.timeout = TIMEOUT;
- request.open('GET', url, true);
- request.send();
-
- let placeholder;
- if (domtoimage.impl.options.imagePlaceholder) {
- const split = domtoimage.impl.options.imagePlaceholder.split(/,/);
- if (split && split[1]) {
- placeholder = split[1];
- }
- }
-
- function done() {
- if (request.readyState !== 4) return;
-
- if (request.status !== 200) {
- if (placeholder) {
- resolve(placeholder);
- } else {
- fail(`cannot fetch resource: ${url}, status: ${request.status}`);
- }
-
- return;
- }
-
- const encoder = new window.FileReader();
- encoder.onloadend = () => {
- const content = encoder.result.split(/,/)[1];
- resolve(content);
- };
- encoder.readAsDataURL(request.response);
- }
-
- function timeout() {
- if (placeholder) {
- resolve(placeholder);
- } else {
- fail(
- `timeout of ${TIMEOUT}ms occurred while fetching resource: ${url}`
- );
- }
- }
-
- function fail(message) {
- console.error(message);
- resolve('');
- }
- });
- }
-
- function dataAsUrl(content, type) {
- return `data:${type};base64,${content}`;
- }
-
- function escape(string) {
- return string.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
- }
-
- function delay(ms) {
- return arg => {
- return new Promise((resolve) => {
- window.setTimeout(() => {
- resolve(arg);
- }, ms);
- });
- };
- }
-
- function asArray(arrayLike) {
- const array = [];
- const length = arrayLike.length;
- for (let i = 0; i < length; i++) array.push(arrayLike[i]);
- return array;
- }
-
- function escapeXhtml(string) {
- return string.replace(/#/g, '%23').replace(/\n/g, '%0A');
- }
-
- function width(node) {
- const leftBorder = px(node, 'border-left-width');
- const rightBorder = px(node, 'border-right-width');
- return node.scrollWidth + leftBorder + rightBorder;
- }
-
- function height(node) {
- const topBorder = px(node, 'border-top-width');
- const bottomBorder = px(node, 'border-bottom-width');
- return node.scrollHeight + topBorder + bottomBorder;
- }
-
- function px(node, styleProperty) {
- const value = window.getComputedStyle(node).getPropertyValue(styleProperty);
- return parseFloat(value.replace('px', ''));
- }
-}
-
function newInliner() {
const URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/g;
@@ -619,27 +295,27 @@ function newInliner() {
result.push(match[1]);
}
return result.filter((url) => {
- return !util.isDataUrl(url);
+ return !isDataUrl(url);
});
}
+ function urlAsRegex(url0) {
+ return new RegExp(
+ `(url\\([\'"]?)(${escape(url0)})([\'"]?\\))`,
+ 'g'
+ );
+ }
+
function inline(string, url, baseUrl, get) {
return Promise.resolve(url)
- .then(ul => baseUrl ? util.resolveUrl(ul, baseUrl) : ul)
- .then(get || util.getAndEncode)
- .then(data => util.dataAsUrl(data, util.mimeType(url)))
+ .then(ul => baseUrl ? resolveUrl(ul, baseUrl) : ul)
+ .then(ul => typeof get === 'function' ? get(ul) : getAndEncode(ul, domtoimage.impl.options))
+ .then(data => dataAsUrl(data, mimeType(url)))
.then(dataUrl => string.replace(urlAsRegex(url), `$1${dataUrl}$3`));
-
- function urlAsRegex(url0) {
- return new RegExp(
- `(url\\([\'"]?)(${util.escape(url0)})([\'"]?\\))`,
- 'g'
- );
- }
}
function inlineAll(string, baseUrl, get) {
- if (nothingToInline() || util.isSrcAsDataUrl(string)) {
+ if (!shouldProcess(string) || isSrcAsDataUrl(string)) {
return Promise.resolve(string);
}
return Promise.resolve(string)
@@ -651,10 +327,6 @@ function newInliner() {
});
return done;
});
-
- function nothingToInline() {
- return !shouldProcess(string);
- }
}
}
@@ -675,7 +347,7 @@ function newFontFaces() {
}
function readAll() {
- return Promise.resolve(util.asArray(document.styleSheets))
+ return Promise.resolve(asArray(document.styleSheets))
.then(loadExternalStyleSheets)
.then(getCssRules)
.then(selectWebFontRules)
@@ -695,7 +367,7 @@ function newFontFaces() {
// error response will remain in cache
const cache = sheet.href.includes('uber-fonts') ? 'no-cache' : 'default';
return window.fetch(sheet.href, {credentials: 'omit', cache})
- .then(toText)
+ .then(response => response.text())
.then(setBaseHref(sheet.href))
.then(toStyleSheet)
.catch(err => {
@@ -711,21 +383,11 @@ function newFontFaces() {
})
);
- function toText(response) {
- return response.text();
- }
-
function setBaseHref(base) {
base = base.split('/');
base.pop();
base = base.join('/');
- return text => {
- return util.isSrcAsDataUrl(text)
- ? text
- : text.replace(/url\(['"]?([^'"]+?)['"]?\)/g, addBaseHrefToUrl);
- };
-
function addBaseHrefToUrl(match, p1) {
const url = /^http/i.test(p1) ? p1 : concatAndResolveUrl(base, p1);
return `url('${url}')`;
@@ -752,6 +414,12 @@ function newFontFaces() {
}
return url3.join('/');
}
+
+ return text => {
+ return isSrcAsDataUrl(text)
+ ? text
+ : text.replace(/url\(['"]?([^'"]+?)['"]?\)/g, addBaseHrefToUrl);
+ };
}
function toStyleSheet(text) {
@@ -782,9 +450,7 @@ function newFontFaces() {
if (rules && typeof rules === 'object') {
try {
- util
- .asArray(rules || [])
- .forEach(cssRules.push.bind(cssRules));
+ asArray(rules || []).forEach(cssRules.push.bind(cssRules));
} catch (e) {
console.log(`Error while reading CSS rules from ${sheet.href}`, e);
return;
@@ -819,17 +485,14 @@ function newImages() {
};
function newImage(element) {
- return {
- inline
- };
function inline(get) {
- if (util.isDataUrl(element.src)) {
+ if (element.src) {
return Promise.resolve();
}
return Promise.resolve(element.src)
- .then(get || util.getAndEncode)
- .then(data => util.dataAsUrl(data, util.mimeType(element.src)))
+ .then(ul => typeof get === 'function' ? get(ul) : getAndEncode(ul, domtoimage.impl.options))
+ .then(data => dataAsUrl(data, mimeType(element.src)))
.then(dataUrl =>
new Promise((resolve, reject) => {
element.onload = resolve;
@@ -838,6 +501,10 @@ function newImages() {
})
);
}
+
+ return {
+ inline
+ };
}
function inlineAll(node) {
@@ -850,7 +517,7 @@ function newImages() {
return newImage(node).inline();
}
return Promise.all(
- util.asArray(node.childNodes).map(child => inlineAll(child))
+ asArray(node.childNodes).map(child => inlineAll(child))
);
});
diff --git a/src/utils/dom-utils.js b/src/utils/dom-utils.js
new file mode 100644
index 000000000..58510ba6a
--- /dev/null
+++ b/src/utils/dom-utils.js
@@ -0,0 +1,364 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import console from 'global/console';
+import window from 'global/window';
+import document from 'global/document';
+import {IMAGE_EXPORT_ERRORS} from 'constants/user-feedbacks';
+
+export function processClone(original, clone) {
+
+ if (!(clone instanceof window.Element)) {
+ return clone
+ };
+
+ function copyProperties(sourceStyle, targetStyle) {
+ const propertyKeys = asArray(sourceStyle);
+ propertyKeys.forEach(name => {
+ targetStyle.setProperty(
+ name,
+ sourceStyle.getPropertyValue(name),
+ sourceStyle.getPropertyPriority(name)
+ );
+ });
+ }
+
+ function copyStyle(source, target) {
+ if (source.cssText) {
+ target.cssText = source.cssText;
+ // add additional copy of composite styles
+ if (source.font) {
+ target.font = source.font;
+ }
+ } else {
+ copyProperties(source, target);
+ }
+ }
+
+ function cloneStyle(og, cln) {
+ const originalStyle = window.getComputedStyle(og);
+ copyStyle(originalStyle, cln.style);
+ }
+
+ function formatPseudoElementStyle(cln, elm, stl) {
+ const formatCssText = (stl1) => {
+ const cnt = stl1.getPropertyValue('content');
+ return `${stl.cssText} content: ${cnt};`;
+ }
+
+ const formatProperty = (name) => {
+ return (
+ `${name}:${stl.getPropertyValue(name)}${stl.getPropertyPriority(name) ? ' !important' : ''}`
+ );
+ }
+
+ const formatCssProperties = (stl2) => {
+ return `${asArray(stl2).map(formatProperty).join('; ')};`;
+ }
+
+ const selector = `.${cln}:${elm}`;
+ const cssText = stl.cssText
+ ? formatCssText(stl)
+ : formatCssProperties(stl);
+
+ return document.createTextNode(`${selector}{${cssText}}`);
+ }
+
+ function clonePseudoElement(org, cln, element) {
+ const style = window.getComputedStyle(org, element);
+ const content = style.getPropertyValue('content');
+
+ if (content === '' || content === 'none') {
+ return;
+ }
+
+ const className = uid();
+ cln.className = `${cln.className} ${className}`;
+ const styleElement = document.createElement('style');
+ styleElement.appendChild(
+ formatPseudoElementStyle(className, element, style)
+ );
+ cln.appendChild(styleElement);
+ }
+
+ function clonePseudoElements([og, cln]) {
+ [':before', ':after'].forEach(element => clonePseudoElement(og, cln, element));
+ }
+
+ function copyUserInput([og, cln]) {
+ if (og instanceof window.HTMLTextAreaElement)
+ cln.innerHTML = og.value;
+ if (og instanceof window.HTMLInputElement)
+ cln.setAttribute('value', og.value);
+ }
+
+ function fixSvg(cln) {
+ if (!(cln instanceof window.SVGElement)) return;
+ cln.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+
+ if (!(cln instanceof window.SVGRectElement)) return;
+ ['width', 'height'].forEach(attribute => {
+ const value = cln.getAttribute(attribute);
+ if (!value) return;
+
+ cln.style.setProperty(attribute, value);
+ });
+ }
+
+ return Promise.resolve([original, clone])
+ .then(([og, cln]) => {
+ cloneStyle(og, cln)
+ return [og, cln];
+ })
+ .then(([og, cln]) => {
+ clonePseudoElements([og, cln])
+ return [og, cln];
+ })
+ .then(([og, cln]) => {
+ copyUserInput([og, cln])
+ return [og, cln];
+ })
+ .then(([og, cln]) => {
+ fixSvg(cln);
+ return [og, cln];
+ })
+ .then(([og, cln]) => cln);
+}
+
+/****
+ * UTILS
+ ****/
+export function asArray(arrayLike) {
+ const array = [];
+ const length = arrayLike.length;
+ for (let i = 0; i < length; i++) array.push(arrayLike[i]);
+ return array;
+}
+
+export function fourRandomChars() {
+ /* see http://stackoverflow.com/a/6248722/2519373 */
+ return `0000${((Math.random() * Math.pow(36, 4)) << 0).toString(36)}`.slice(-4);
+}
+
+export function uid() {
+ let index = 0;
+
+ return `u${fourRandomChars()}${index++}`;
+}
+
+export function makeImage(uri) {
+ return new Promise((resolve, reject) => {
+ const image = new window.Image();
+ image.onload = () => {
+ resolve(image);
+ };
+ image.onerror = (err) => {
+ const message = IMAGE_EXPORT_ERRORS.dataUri;
+ console.log(uri);
+ // error is an Event Object
+ // https://www.w3schools.com/jsref/obj_event.asp
+ reject({event: err, message});
+ };
+ image.src = uri;
+ });
+}
+
+export function isDataUrl(url) {
+ return url.search(/^(data:)/) !== -1;
+}
+
+function parseExtension(url) {
+ const match = /\.([^\.\/]*?)$/g.exec(url);
+ if (match) {
+ return match[1];
+ }
+ return '';
+}
+
+function mimes() {
+ /*
+ * Only WOFF and EOT mime types for fonts are 'real'
+ * see http://www.iana.org/assignments/media-types/media-types.xhtml
+ */
+ const WOFF = 'application/font-woff';
+ const JPEG = 'image/jpeg';
+
+ return {
+ woff: WOFF,
+ woff2: WOFF,
+ ttf: 'application/font-truetype',
+ eot: 'application/vnd.ms-fontobject',
+ png: 'image/png',
+ jpg: JPEG,
+ jpeg: JPEG,
+ gif: 'image/gif',
+ tiff: 'image/tiff',
+ svg: 'image/svg+xml'
+ };
+}
+
+export function mimeType(url) {
+ const extension = parseExtension(url).toLowerCase();
+ return mimes()[extension] || '';
+}
+
+export function dataAsUrl(content, type) {
+ return `data:${type};base64,${content}`;
+}
+
+export function escape(string) {
+ return string.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
+}
+
+export function delay(ms) {
+ return arg => {
+ return new Promise((resolve) => {
+ window.setTimeout(() => {
+ resolve(arg);
+ }, ms);
+ });
+ };
+}
+
+export function isSrcAsDataUrl(text) {
+ const DATA_URL_REGEX = /url\(['"]?(data:)([^'"]+?)['"]?\)/;
+
+ return text.search(DATA_URL_REGEX) !== -1;
+}
+
+function cvToBlob(canvas) {
+ return new Promise(resolve => {
+ const binaryString = window.atob(canvas.toDataURL().split(',')[1]);
+ const length = binaryString.length;
+ const binaryArray = new Uint8Array(length);
+
+ for (let i = 0; i < length; i++)
+ binaryArray[i] = binaryString.charCodeAt(i);
+
+ resolve(
+ new window.Blob([binaryArray], {type: 'image/png'})
+ );
+ });
+}
+
+export function canvasToBlob(canvas) {
+ if (canvas.toBlob)
+ return new Promise(resolve => {
+ canvas.toBlob(resolve);
+ });
+
+ return cvToBlob(canvas);
+}
+
+export function escapeXhtml(string) {
+ return string.replace(/#/g, '%23').replace(/\n/g, '%0A');
+}
+
+export function getWidth(node) {
+ const leftBorder = px(node, 'border-left-width');
+ const rightBorder = px(node, 'border-right-width');
+ return node.scrollWidth + leftBorder + rightBorder;
+}
+
+export function getHeight(node) {
+ const topBorder = px(node, 'border-top-width');
+ const bottomBorder = px(node, 'border-bottom-width');
+ return node.scrollHeight + topBorder + bottomBorder;
+}
+
+function px(node, styleProperty) {
+ const value = window.getComputedStyle(node).getPropertyValue(styleProperty);
+ return parseFloat(value.replace('px', ''));
+}
+
+export function resolveUrl(url, baseUrl) {
+ const doc = document.implementation.createHTMLDocument();
+ const base = doc.createElement('base');
+ doc.head.appendChild(base);
+ const a = doc.createElement('a');
+ doc.body.appendChild(a);
+ base.href = baseUrl;
+ a.href = url;
+ return a.href;
+}
+
+export function getAndEncode(url, options) {
+ const TIMEOUT = 30000;
+ if (options.cacheBust) {
+ // Cache bypass so we dont have CORS issues with cached images
+ // Source: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
+ url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
+ }
+
+ return new Promise(resolve => {
+ const request = new window.XMLHttpRequest();
+
+ request.onreadystatechange = done;
+ request.ontimeout = timeout;
+ request.responseType = 'blob';
+ request.timeout = TIMEOUT;
+ request.open('GET', url, true);
+ request.send();
+
+ let placeholder;
+ if (options.imagePlaceholder) {
+ const split = options.imagePlaceholder.split(/,/);
+ if (split && split[1]) {
+ placeholder = split[1];
+ }
+ }
+
+ function done() {
+ if (request.readyState !== 4) return;
+
+ if (request.status !== 200) {
+ if (placeholder) {
+ resolve(placeholder);
+ } else {
+ fail(`cannot fetch resource: ${url}, status: ${request.status}`);
+ }
+
+ return;
+ }
+
+ const encoder = new window.FileReader();
+ encoder.onloadend = () => {
+ const content = encoder.result.split(/,/)[1];
+ resolve(content);
+ };
+ encoder.readAsDataURL(request.response);
+ }
+
+ function timeout() {
+ if (placeholder) {
+ resolve(placeholder);
+ } else {
+ fail(
+ `timeout of ${TIMEOUT}ms occurred while fetching resource: ${url}`
+ );
+ }
+ }
+
+ function fail(message) {
+ console.error(message);
+ resolve('');
+ }
+ });
+}
diff --git a/website/package.json b/website/package.json
index cc6c300ab..eecd04b38 100644
--- a/website/package.json
+++ b/website/package.json
@@ -75,7 +75,6 @@
"file-loader": "^1.1.11",
"prettier": "^1.7.0",
"source-map-loader": "^0.2.1",
- "uglifyjs-webpack-plugin": "^2.1.1",
"url-loader": "^0.5.9",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",