feature: vor und nachteile

This commit is contained in:
Hikyu
2026-05-31 13:54:31 +02:00
parent 552a947a1c
commit e3dad17446
23270 changed files with 3024794 additions and 200 deletions
+2
View File
@@ -0,0 +1,2 @@
import type { Options } from './types';
export declare function applyStyle<T extends HTMLElement>(node: T, options: Options): T;
+20
View File
@@ -0,0 +1,20 @@
export function applyStyle(node, options) {
const { style } = node;
if (options.backgroundColor) {
style.backgroundColor = options.backgroundColor;
}
if (options.width) {
style.width = `${options.width}px`;
}
if (options.height) {
style.height = `${options.height}px`;
}
const manual = options.style;
if (manual != null) {
Object.keys(manual).forEach((key) => {
style[key] = manual[key];
});
}
return node;
}
//# sourceMappingURL=apply-style.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"apply-style.js","sourceRoot":"","sources":["../src/apply-style.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,UAAU,CACxB,IAAO,EACP,OAAgB;IAEhB,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAA;IAEtB,IAAI,OAAO,CAAC,eAAe,EAAE;QAC3B,KAAK,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAA;KAChD;IAED,IAAI,OAAO,CAAC,KAAK,EAAE;QACjB,KAAK,CAAC,KAAK,GAAG,GAAG,OAAO,CAAC,KAAK,IAAI,CAAA;KACnC;IAED,IAAI,OAAO,CAAC,MAAM,EAAE;QAClB,KAAK,CAAC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,CAAA;KACrC;IAED,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAA;IAC5B,IAAI,MAAM,IAAI,IAAI,EAAE;QAClB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,GAAQ,EAAE,EAAE;YACvC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAW,CAAA;QACpC,CAAC,CAAC,CAAA;KACH;IAED,OAAO,IAAI,CAAA;AACb,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
import type { Options } from './types';
export declare function cloneNode<T extends HTMLElement>(node: T, options: Options, isRoot?: boolean): Promise<T | null>;
+184
View File
@@ -0,0 +1,184 @@
import { clonePseudoElements } from './clone-pseudos';
import { createImage, toArray, isInstanceOfElement, getStyleProperties, } from './util';
import { getMimeType } from './mimes';
import { resourceToDataURL } from './dataurl';
async function cloneCanvasElement(canvas) {
const dataURL = canvas.toDataURL();
if (dataURL === 'data:,') {
return canvas.cloneNode(false);
}
return createImage(dataURL);
}
async function cloneVideoElement(video, options) {
if (video.currentSrc) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = video.clientWidth;
canvas.height = video.clientHeight;
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
return createImage(dataURL);
}
const poster = video.poster;
const contentType = getMimeType(poster);
const dataURL = await resourceToDataURL(poster, contentType, options);
return createImage(dataURL);
}
async function cloneIFrameElement(iframe, options) {
var _a;
try {
if ((_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentDocument) === null || _a === void 0 ? void 0 : _a.body) {
return (await cloneNode(iframe.contentDocument.body, options, true));
}
}
catch (_b) {
// Failed to clone iframe
}
return iframe.cloneNode(false);
}
async function cloneSingleNode(node, options) {
if (isInstanceOfElement(node, HTMLCanvasElement)) {
return cloneCanvasElement(node);
}
if (isInstanceOfElement(node, HTMLVideoElement)) {
return cloneVideoElement(node, options);
}
if (isInstanceOfElement(node, HTMLIFrameElement)) {
return cloneIFrameElement(node, options);
}
return node.cloneNode(isSVGElement(node));
}
const isSlotElement = (node) => node.tagName != null && node.tagName.toUpperCase() === 'SLOT';
const isSVGElement = (node) => node.tagName != null && node.tagName.toUpperCase() === 'SVG';
async function cloneChildren(nativeNode, clonedNode, options) {
var _a, _b;
if (isSVGElement(clonedNode)) {
return clonedNode;
}
let children = [];
if (isSlotElement(nativeNode) && nativeNode.assignedNodes) {
children = toArray(nativeNode.assignedNodes());
}
else if (isInstanceOfElement(nativeNode, HTMLIFrameElement) &&
((_a = nativeNode.contentDocument) === null || _a === void 0 ? void 0 : _a.body)) {
children = toArray(nativeNode.contentDocument.body.childNodes);
}
else {
children = toArray(((_b = nativeNode.shadowRoot) !== null && _b !== void 0 ? _b : nativeNode).childNodes);
}
if (children.length === 0 ||
isInstanceOfElement(nativeNode, HTMLVideoElement)) {
return clonedNode;
}
await children.reduce((deferred, child) => deferred
.then(() => cloneNode(child, options))
.then((clonedChild) => {
if (clonedChild) {
clonedNode.appendChild(clonedChild);
}
}), Promise.resolve());
return clonedNode;
}
function cloneCSSStyle(nativeNode, clonedNode, options) {
const targetStyle = clonedNode.style;
if (!targetStyle) {
return;
}
const sourceStyle = window.getComputedStyle(nativeNode);
if (sourceStyle.cssText) {
targetStyle.cssText = sourceStyle.cssText;
targetStyle.transformOrigin = sourceStyle.transformOrigin;
}
else {
getStyleProperties(options).forEach((name) => {
let value = sourceStyle.getPropertyValue(name);
if (name === 'font-size' && value.endsWith('px')) {
const reducedFont = Math.floor(parseFloat(value.substring(0, value.length - 2))) - 0.1;
value = `${reducedFont}px`;
}
if (isInstanceOfElement(nativeNode, HTMLIFrameElement) &&
name === 'display' &&
value === 'inline') {
value = 'block';
}
if (name === 'd' && clonedNode.getAttribute('d')) {
value = `path(${clonedNode.getAttribute('d')})`;
}
targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name));
});
}
}
function cloneInputValue(nativeNode, clonedNode) {
if (isInstanceOfElement(nativeNode, HTMLTextAreaElement)) {
clonedNode.innerHTML = nativeNode.value;
}
if (isInstanceOfElement(nativeNode, HTMLInputElement)) {
clonedNode.setAttribute('value', nativeNode.value);
}
}
function cloneSelectValue(nativeNode, clonedNode) {
if (isInstanceOfElement(nativeNode, HTMLSelectElement)) {
const clonedSelect = clonedNode;
const selectedOption = Array.from(clonedSelect.children).find((child) => nativeNode.value === child.getAttribute('value'));
if (selectedOption) {
selectedOption.setAttribute('selected', '');
}
}
}
function decorate(nativeNode, clonedNode, options) {
if (isInstanceOfElement(clonedNode, Element)) {
cloneCSSStyle(nativeNode, clonedNode, options);
clonePseudoElements(nativeNode, clonedNode, options);
cloneInputValue(nativeNode, clonedNode);
cloneSelectValue(nativeNode, clonedNode);
}
return clonedNode;
}
async function ensureSVGSymbols(clone, options) {
const uses = clone.querySelectorAll ? clone.querySelectorAll('use') : [];
if (uses.length === 0) {
return clone;
}
const processedDefs = {};
for (let i = 0; i < uses.length; i++) {
const use = uses[i];
const id = use.getAttribute('xlink:href');
if (id) {
const exist = clone.querySelector(id);
const definition = document.querySelector(id);
if (!exist && definition && !processedDefs[id]) {
// eslint-disable-next-line no-await-in-loop
processedDefs[id] = (await cloneNode(definition, options, true));
}
}
}
const nodes = Object.values(processedDefs);
if (nodes.length) {
const ns = 'http://www.w3.org/1999/xhtml';
const svg = document.createElementNS(ns, 'svg');
svg.setAttribute('xmlns', ns);
svg.style.position = 'absolute';
svg.style.width = '0';
svg.style.height = '0';
svg.style.overflow = 'hidden';
svg.style.display = 'none';
const defs = document.createElementNS(ns, 'defs');
svg.appendChild(defs);
for (let i = 0; i < nodes.length; i++) {
defs.appendChild(nodes[i]);
}
clone.appendChild(svg);
}
return clone;
}
export async function cloneNode(node, options, isRoot) {
if (!isRoot && options.filter && !options.filter(node)) {
return null;
}
return Promise.resolve(node)
.then((clonedNode) => cloneSingleNode(clonedNode, options))
.then((clonedNode) => cloneChildren(node, clonedNode, options))
.then((clonedNode) => decorate(node, clonedNode, options))
.then((clonedNode) => ensureSVGSymbols(clonedNode, options));
}
//# sourceMappingURL=clone-node.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
import type { Options } from './types';
export declare function clonePseudoElements<T extends HTMLElement>(nativeNode: T, clonedNode: T, options: Options): void;
+43
View File
@@ -0,0 +1,43 @@
import { uuid, getStyleProperties } from './util';
function formatCSSText(style) {
const content = style.getPropertyValue('content');
return `${style.cssText} content: '${content.replace(/'|"/g, '')}';`;
}
function formatCSSProperties(style, options) {
return getStyleProperties(options)
.map((name) => {
const value = style.getPropertyValue(name);
const priority = style.getPropertyPriority(name);
return `${name}: ${value}${priority ? ' !important' : ''};`;
})
.join(' ');
}
function getPseudoElementStyle(className, pseudo, style, options) {
const selector = `.${className}:${pseudo}`;
const cssText = style.cssText
? formatCSSText(style)
: formatCSSProperties(style, options);
return document.createTextNode(`${selector}{${cssText}}`);
}
function clonePseudoElement(nativeNode, clonedNode, pseudo, options) {
const style = window.getComputedStyle(nativeNode, pseudo);
const content = style.getPropertyValue('content');
if (content === '' || content === 'none') {
return;
}
const className = uuid();
try {
clonedNode.className = `${clonedNode.className} ${className}`;
}
catch (err) {
return;
}
const styleElement = document.createElement('style');
styleElement.appendChild(getPseudoElementStyle(className, pseudo, style, options));
clonedNode.appendChild(styleElement);
}
export function clonePseudoElements(nativeNode, clonedNode, options) {
clonePseudoElement(nativeNode, clonedNode, ':before', options);
clonePseudoElement(nativeNode, clonedNode, ':after', options);
}
//# sourceMappingURL=clone-pseudos.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"clone-pseudos.js","sourceRoot":"","sources":["../src/clone-pseudos.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAA;AAIjD,SAAS,aAAa,CAAC,KAA0B;IAC/C,MAAM,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAA;IACjD,OAAO,GAAG,KAAK,CAAC,OAAO,cAAc,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAA;AACtE,CAAC;AAED,SAAS,mBAAmB,CAAC,KAA0B,EAAE,OAAgB;IACvE,OAAO,kBAAkB,CAAC,OAAO,CAAC;SAC/B,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACZ,MAAM,KAAK,GAAG,KAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;QAC1C,MA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,OAAO,CAAC,CACzD,CAAA;IACD,UAAU,CAAC,WAAW,CAAC,YAAY,CAAC,CAAA;AACtC,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,UAAa,EACb,UAAa,EACb,OAAgB;IAEhB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,CAAC,CAAA;IAC9D,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAA;AAC/D,CAAC"}
+8
View File
@@ -0,0 +1,8 @@
import { Options } from './types';
export declare function isDataUrl(url: string): boolean;
export declare function makeDataUrl(content: string, mimeType: string): string;
export declare function fetchAsDataURL<T>(url: string, init: RequestInit | undefined, process: (data: {
result: string;
res: Response;
}) => T): Promise<T>;
export declare function resourceToDataURL(resourceUrl: string, contentType: string | undefined, options: Options): Promise<string>;
+76
View File
@@ -0,0 +1,76 @@
function getContentFromDataUrl(dataURL) {
return dataURL.split(/,/)[1];
}
export function isDataUrl(url) {
return url.search(/^(data:)/) !== -1;
}
export function makeDataUrl(content, mimeType) {
return `data:${mimeType};base64,${content}`;
}
export async function fetchAsDataURL(url, init, process) {
const res = await fetch(url, init);
if (res.status === 404) {
throw new Error(`Resource "${res.url}" not found`);
}
const blob = await res.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onloadend = () => {
try {
resolve(process({ res, result: reader.result }));
}
catch (error) {
reject(error);
}
};
reader.readAsDataURL(blob);
});
}
const cache = {};
function getCacheKey(url, contentType, includeQueryParams) {
let key = url.replace(/\?.*/, '');
if (includeQueryParams) {
key = url;
}
// font resource
if (/ttf|otf|eot|woff2?/i.test(key)) {
key = key.replace(/.*\//, '');
}
return contentType ? `[${contentType}]${key}` : key;
}
export async function resourceToDataURL(resourceUrl, contentType, options) {
const cacheKey = getCacheKey(resourceUrl, contentType, options.includeQueryParams);
if (cache[cacheKey] != null) {
return cache[cacheKey];
}
// ref: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
if (options.cacheBust) {
// eslint-disable-next-line no-param-reassign
resourceUrl += (/\?/.test(resourceUrl) ? '&' : '?') + new Date().getTime();
}
let dataURL;
try {
const content = await fetchAsDataURL(resourceUrl, options.fetchRequestInit, ({ res, result }) => {
if (!contentType) {
// eslint-disable-next-line no-param-reassign
contentType = res.headers.get('Content-Type') || '';
}
return getContentFromDataUrl(result);
});
dataURL = makeDataUrl(content, contentType);
}
catch (error) {
dataURL = options.imagePlaceholder || '';
let msg = `Failed to fetch resource: ${resourceUrl}`;
if (error) {
msg = typeof error === 'string' ? error : error.message;
}
if (msg) {
console.warn(msg);
}
}
cache[cacheKey] = dataURL;
return dataURL;
}
//# sourceMappingURL=dataurl.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"dataurl.js","sourceRoot":"","sources":["../src/dataurl.ts"],"names":[],"mappings":"AAEA,SAAS,qBAAqB,CAAC,OAAe;IAC5C,OAAO,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;AAC9B,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,OAAO,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAA;AACtC,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,QAAgB;IAC3D,OAAO,QAAQ,QAAQ,WAAW,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,GAAW,EACX,IAA6B,EAC7B,OAAuD;IAEvD,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAClC,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE;QACtB,MAAM,IAAI,KAAK,CAAC,aAAa,GAAG,CAAC,GAAG,aAAa,CAAC,CAAA;KACnD;IACD,MAAM,IAAI,GAAG,MAAM,GAAG,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E;QAC3B,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAA;KACvB;IAED,6GAA6G;IAC7G,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,6CAA6C;QAC7C,WAAW,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;KAC3E;IAED,IAAI,OAAe,CAAA;IACnB,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,cAAc,CAClC,WAAW,EACX,OAAO,CAAC,gBAAgB,EACxB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;YAClB,IAAI,CAAC,WAAW,EAAE;gBAChB,6CAA6C;gBAC7C,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAA;aACpD;YACD,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAA;QACtC,CAAC,CACF,CAAA;QACD,OAAO,GAAG,WAAW,CAAC,OAAO,EAAE,WAAY,CAAC,CAAA;KAC7C;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,GAAG,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAA;QAExC,IAAI,GAAG,GAAG,6BAA6B,WAAW,EAAE,CAAA;QACpD,IAAI,KAAK,EAAE;YACT,GAAG,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAA;SACxD;QAED,IAAI,GAAG,EAAE;YACP,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;SAClB;KACF;IAED,KAAK,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAA;IACzB,OAAO,OAAO,CAAA;AAChB,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
import { Options } from './types';
export declare function embedImages<T extends HTMLElement>(clonedNode: T, options: Options): Promise<void>;
+73
View File
@@ -0,0 +1,73 @@
import { embedResources } from './embed-resources';
import { toArray, isInstanceOfElement } from './util';
import { isDataUrl, resourceToDataURL } from './dataurl';
import { getMimeType } from './mimes';
async function embedProp(propName, node, options) {
var _a;
const propValue = (_a = node.style) === null || _a === void 0 ? void 0 : _a.getPropertyValue(propName);
if (propValue) {
const cssString = await embedResources(propValue, null, options);
node.style.setProperty(propName, cssString, node.style.getPropertyPriority(propName));
return true;
}
return false;
}
async function embedBackground(clonedNode, options) {
;
(await embedProp('background', clonedNode, options)) ||
(await embedProp('background-image', clonedNode, options));
(await embedProp('mask', clonedNode, options)) ||
(await embedProp('-webkit-mask', clonedNode, options)) ||
(await embedProp('mask-image', clonedNode, options)) ||
(await embedProp('-webkit-mask-image', clonedNode, options));
}
async function embedImageNode(clonedNode, options) {
const isImageElement = isInstanceOfElement(clonedNode, HTMLImageElement);
if (!(isImageElement && !isDataUrl(clonedNode.src)) &&
!(isInstanceOfElement(clonedNode, SVGImageElement) &&
!isDataUrl(clonedNode.href.baseVal))) {
return;
}
const url = isImageElement ? clonedNode.src : clonedNode.href.baseVal;
const dataURL = await resourceToDataURL(url, getMimeType(url), options);
await new Promise((resolve, reject) => {
clonedNode.onload = resolve;
clonedNode.onerror = options.onImageErrorHandler
? (...attributes) => {
try {
resolve(options.onImageErrorHandler(...attributes));
}
catch (error) {
reject(error);
}
}
: reject;
const image = clonedNode;
if (image.decode) {
image.decode = resolve;
}
if (image.loading === 'lazy') {
image.loading = 'eager';
}
if (isImageElement) {
clonedNode.srcset = '';
clonedNode.src = dataURL;
}
else {
clonedNode.href.baseVal = dataURL;
}
});
}
async function embedChildren(clonedNode, options) {
const children = toArray(clonedNode.childNodes);
const deferreds = children.map((child) => embedImages(child, options));
await Promise.all(deferreds).then(() => clonedNode);
}
export async function embedImages(clonedNode, options) {
if (isInstanceOfElement(clonedNode, Element)) {
await embedBackground(clonedNode, options);
await embedImageNode(clonedNode, options);
await embedChildren(clonedNode, options);
}
}
//# sourceMappingURL=embed-images.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"embed-images.js","sourceRoot":"","sources":["../src/embed-images.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAClD,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAA;AACrD,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAErC,KAAK,UAAU,SAAS,CACtB,QAAgB,EAChB,IAAiB,EACjB,OAAgB;;IAEhB,MAAM,SAAS,GAAG,MAAA,IAAI,CAAC,KAAK,0CAAE,gBAAgB,CAAC,QAAQ,CAAC,CAAA;IACxD,IAAI,SAAS,EAAE;QACb,MAAM,SAAS,GAAG,MAAM,cAAc,CAAC,SAAS,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QAChE,IAAI,CAAC,KAAK,CAAC,WAAW,CACpB,QAAQ,EACR,SAAS,EACT,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CACzC,CAAA;QACD,OAAO,IAAI,CAAA;KACZ;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,KAAK,UAAU,eAAe,CAC5B,UAAa,EACb,OAAgB;IAEhB,CAAC;IAAA,CAAC,MAAM,SAAS,CAAC,YAAY,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QACnD,CAAC,MAAM,SAAS,CAAC,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAC3D;IAAA,CAAC,MAAM,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QAC7C,CAAC,MAAM,SAAS,CAAC,cAAc,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QACtD,CAAC,MAAM,SAAS,CAAC,YAAY,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QACp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AM,EAAE;YAC5B,KAAK,CAAC,OAAO,GAAG,OAAO,CAAA;SACxB;QAED,IAAI,cAAc,EAAE;YAClB,UAAU,CAAC,MAAM,GAAG,EAAE,CAAA;YACtB,UAAU,CAAC,GAAG,GAAG,OAAO,CAAA;SACzB;aAAM;YACL,UAAU,CAAC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;SAClC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,KAAK,UAAU,aAAa,CAC1B,UAAa,EACb,OAAgB;IAEhB,MAAM,QAAQ,GAAG,OAAO,CAAc,UAAU,CAAC,UAAU,CAAC,CAAA;IAC5D,MAAM,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;IACtE,MAAM,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,CAAA;AACrD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,UAAa,EACb,OAAgB;IAEhB,IAAI,mBAAmB,CAAC,UAAU,EAAE,OAAO,CAAC,EAAE;QAC5C,MAAM,eAAe,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;QAC1C,MAAM,cAAc,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;QACzC,MAAM,aAAa,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;KACzC;AACH,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
import { Options } from './types';
export declare function parseURLs(cssText: string): string[];
export declare function embed(cssText: string, resourceURL: string, baseURL: string | null, options: Options, getContentFromUrl?: (url: string) => Promise<string>): Promise<string>;
export declare function shouldEmbed(url: string): boolean;
export declare function embedResources(cssText: string, baseUrl: string | null, options: Options): Promise<string>;
+66
View File
@@ -0,0 +1,66 @@
import { resolveUrl } from './util';
import { getMimeType } from './mimes';
import { isDataUrl, makeDataUrl, resourceToDataURL } from './dataurl';
const URL_REGEX = /url\((['"]?)([^'"]+?)\1\)/g;
const URL_WITH_FORMAT_REGEX = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g;
const FONT_SRC_REGEX = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;
function toRegex(url) {
// eslint-disable-next-line no-useless-escape
const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, 'g');
}
export function parseURLs(cssText) {
const urls = [];
cssText.replace(URL_REGEX, (raw, quotation, url) => {
urls.push(url);
return raw;
});
return urls.filter((url) => !isDataUrl(url));
}
export async function embed(cssText, resourceURL, baseURL, options, getContentFromUrl) {
try {
const resolvedURL = baseURL ? resolveUrl(resourceURL, baseURL) : resourceURL;
const contentType = getMimeType(resourceURL);
let dataURL;
if (getContentFromUrl) {
const content = await getContentFromUrl(resolvedURL);
dataURL = makeDataUrl(content, contentType);
}
else {
dataURL = await resourceToDataURL(resolvedURL, contentType, options);
}
return cssText.replace(toRegex(resourceURL), `$1${dataURL}$3`);
}
catch (error) {
// pass
}
return cssText;
}
function filterPreferredFontFormat(str, { preferredFontFormat }) {
return !preferredFontFormat
? str
: str.replace(FONT_SRC_REGEX, (match) => {
// eslint-disable-next-line no-constant-condition
while (true) {
const [src, , format] = URL_WITH_FORMAT_REGEX.exec(match) || [];
if (!format) {
return '';
}
if (format === preferredFontFormat) {
return `src: ${src};`;
}
}
});
}
export function shouldEmbed(url) {
return url.search(URL_REGEX) !== -1;
}
export async function embedResources(cssText, baseUrl, options) {
if (!shouldEmbed(cssText)) {
return cssText;
}
const filteredCSSText = filterPreferredFontFormat(cssText, options);
const urls = parseURLs(filteredCSSText);
return urls.reduce((deferred, url) => deferred.then((css) => embed(css, url, baseUrl, options)), Promise.resolve(filteredCSSText));
}
//# sourceMappingURL=embed-resources.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"embed-resources.js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ED,MAAM,eAAe,GAAG,yBAAyB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IACnE,MAAM,IAAI,GAAG,SAAS,CAAC,eAAe,CAAC,CAAA;IACvC,OAAO,IAAI,CAAC,MAAM,CAChB,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,CAChB,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAC3D,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CACjC,CAAA;AACH,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
import type { Options } from './types';
export declare function getWebFontCSS<T extends HTMLElement>(node: T, options: Options): Promise<string>;
export declare function embedWebFonts<T extends HTMLElement>(clonedNode: T, options: Options): Promise<void>;
+205
View File
@@ -0,0 +1,205 @@
import { toArray } from './util';
import { fetchAsDataURL } from './dataurl';
import { shouldEmbed, embedResources } from './embed-resources';
const cssFetchCache = {};
async function fetchCSS(url) {
let cache = cssFetchCache[url];
if (cache != null) {
return cache;
}
const res = await fetch(url);
const cssText = await res.text();
cache = { url, cssText };
cssFetchCache[url] = cache;
return cache;
}
async function embedFonts(data, options) {
let cssText = data.cssText;
const regexUrl = /url\(["']?([^"')]+)["']?\)/g;
const fontLocs = cssText.match(/url\([^)]+\)/g) || [];
const loadFonts = fontLocs.map(async (loc) => {
let url = loc.replace(regexUrl, '$1');
if (!url.startsWith('https://')) {
url = new URL(url, data.url).href;
}
return fetchAsDataURL(url, options.fetchRequestInit, ({ result }) => {
cssText = cssText.replace(loc, `url(${result})`);
return [loc, result];
});
});
return Promise.all(loadFonts).then(() => cssText);
}
function parseCSS(source) {
if (source == null) {
return [];
}
const result = [];
const commentsRegex = /(\/\*[\s\S]*?\*\/)/gi;
// strip out comments
let cssText = source.replace(commentsRegex, '');
// eslint-disable-next-line prefer-regex-literals
const keyframesRegex = new RegExp('((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})', 'gi');
// eslint-disable-next-line no-constant-condition
while (true) {
const matches = keyframesRegex.exec(cssText);
if (matches === null) {
break;
}
result.push(matches[0]);
}
cssText = cssText.replace(keyframesRegex, '');
const importRegex = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi;
// to match css & media queries together
const combinedCSSRegex = '((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]' +
'*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})';
// unified regex
const unifiedRegex = new RegExp(combinedCSSRegex, 'gi');
// eslint-disable-next-line no-constant-condition
while (true) {
let matches = importRegex.exec(cssText);
if (matches === null) {
matches = unifiedRegex.exec(cssText);
if (matches === null) {
break;
}
else {
importRegex.lastIndex = unifiedRegex.lastIndex;
}
}
else {
unifiedRegex.lastIndex = importRegex.lastIndex;
}
result.push(matches[0]);
}
return result;
}
async function getCSSRules(styleSheets, options) {
const ret = [];
const deferreds = [];
// First loop inlines imports
styleSheets.forEach((sheet) => {
if ('cssRules' in sheet) {
try {
toArray(sheet.cssRules || []).forEach((item, index) => {
if (item.type === CSSRule.IMPORT_RULE) {
let importIndex = index + 1;
const url = item.href;
const deferred = fetchCSS(url)
.then((metadata) => embedFonts(metadata, options))
.then((cssText) => parseCSS(cssText).forEach((rule) => {
try {
sheet.insertRule(rule, rule.startsWith('@import')
? (importIndex += 1)
: sheet.cssRules.length);
}
catch (error) {
console.error('Error inserting rule from remote css', {
rule,
error,
});
}
}))
.catch((e) => {
console.error('Error loading remote css', e.toString());
});
deferreds.push(deferred);
}
});
}
catch (e) {
const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0];
if (sheet.href != null) {
deferreds.push(fetchCSS(sheet.href)
.then((metadata) => embedFonts(metadata, options))
.then((cssText) => parseCSS(cssText).forEach((rule) => {
inline.insertRule(rule, inline.cssRules.length);
}))
.catch((err) => {
console.error('Error loading remote stylesheet', err);
}));
}
console.error('Error inlining remote css file', e);
}
}
});
return Promise.all(deferreds).then(() => {
// Second loop parses rules
styleSheets.forEach((sheet) => {
if ('cssRules' in sheet) {
try {
toArray(sheet.cssRules || []).forEach((item) => {
ret.push(item);
});
}
catch (e) {
console.error(`Error while reading CSS rules from ${sheet.href}`, e);
}
}
});
return ret;
});
}
function getWebFontRules(cssRules) {
return cssRules
.filter((rule) => rule.type === CSSRule.FONT_FACE_RULE)
.filter((rule) => shouldEmbed(rule.style.getPropertyValue('src')));
}
async function parseWebFontRules(node, options) {
if (node.ownerDocument == null) {
throw new Error('Provided element is not within a Document');
}
const styleSheets = toArray(node.ownerDocument.styleSheets);
const cssRules = await getCSSRules(styleSheets, options);
return getWebFontRules(cssRules);
}
function normalizeFontFamily(font) {
return font.trim().replace(/["']/g, '');
}
function getUsedFonts(node) {
const fonts = new Set();
function traverse(node) {
const fontFamily = node.style.fontFamily || getComputedStyle(node).fontFamily;
fontFamily.split(',').forEach((font) => {
fonts.add(normalizeFontFamily(font));
});
Array.from(node.children).forEach((child) => {
if (child instanceof HTMLElement) {
traverse(child);
}
});
}
traverse(node);
return fonts;
}
export async function getWebFontCSS(node, options) {
const rules = await parseWebFontRules(node, options);
const usedFonts = getUsedFonts(node);
const cssTexts = await Promise.all(rules
.filter((rule) => usedFonts.has(normalizeFontFamily(rule.style.fontFamily)))
.map((rule) => {
const baseUrl = rule.parentStyleSheet
? rule.parentStyleSheet.href
: null;
return embedResources(rule.cssText, baseUrl, options);
}));
return cssTexts.join('\n');
}
export async function embedWebFonts(clonedNode, options) {
const cssText = options.fontEmbedCSS != null
? options.fontEmbedCSS
: options.skipFonts
? null
: await getWebFontCSS(clonedNode, options);
if (cssText) {
const styleNode = document.createElement('style');
const sytleContent = document.createTextNode(cssText);
styleNode.appendChild(sytleContent);
if (clonedNode.firstChild) {
clonedNode.insertBefore(styleNode, clonedNode.firstChild);
}
else {
clonedNode.appendChild(styleNode);
}
}
}
//# sourceMappingURL=embed-webfonts.js.map
File diff suppressed because one or more lines are too long
+8
View File
@@ -0,0 +1,8 @@
import { Options } from './types';
export declare function toSvg<T extends HTMLElement>(node: T, options?: Options): Promise<string>;
export declare function toCanvas<T extends HTMLElement>(node: T, options?: Options): Promise<HTMLCanvasElement>;
export declare function toPixelData<T extends HTMLElement>(node: T, options?: Options): Promise<Uint8ClampedArray>;
export declare function toPng<T extends HTMLElement>(node: T, options?: Options): Promise<string>;
export declare function toJpeg<T extends HTMLElement>(node: T, options?: Options): Promise<string>;
export declare function toBlob<T extends HTMLElement>(node: T, options?: Options): Promise<Blob | null>;
export declare function getFontEmbedCSS<T extends HTMLElement>(node: T, options?: Options): Promise<string>;
+60
View File
@@ -0,0 +1,60 @@
import { cloneNode } from './clone-node';
import { embedImages } from './embed-images';
import { applyStyle } from './apply-style';
import { embedWebFonts, getWebFontCSS } from './embed-webfonts';
import { getImageSize, getPixelRatio, createImage, canvasToBlob, nodeToDataURL, checkCanvasDimensions, } from './util';
export async function toSvg(node, options = {}) {
const { width, height } = getImageSize(node, options);
const clonedNode = (await cloneNode(node, options, true));
await embedWebFonts(clonedNode, options);
await embedImages(clonedNode, options);
applyStyle(clonedNode, options);
const datauri = await nodeToDataURL(clonedNode, width, height);
return datauri;
}
export async function toCanvas(node, options = {}) {
const { width, height } = getImageSize(node, options);
const svg = await toSvg(node, options);
const img = await createImage(svg);
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const ratio = options.pixelRatio || getPixelRatio();
const canvasWidth = options.canvasWidth || width;
const canvasHeight = options.canvasHeight || height;
canvas.width = canvasWidth * ratio;
canvas.height = canvasHeight * ratio;
if (!options.skipAutoScale) {
checkCanvasDimensions(canvas);
}
canvas.style.width = `${canvasWidth}`;
canvas.style.height = `${canvasHeight}`;
if (options.backgroundColor) {
context.fillStyle = options.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas;
}
export async function toPixelData(node, options = {}) {
const { width, height } = getImageSize(node, options);
const canvas = await toCanvas(node, options);
const ctx = canvas.getContext('2d');
return ctx.getImageData(0, 0, width, height).data;
}
export async function toPng(node, options = {}) {
const canvas = await toCanvas(node, options);
return canvas.toDataURL();
}
export async function toJpeg(node, options = {}) {
const canvas = await toCanvas(node, options);
return canvas.toDataURL('image/jpeg', options.quality || 1);
}
export async function toBlob(node, options = {}) {
const canvas = await toCanvas(node, options);
const blob = await canvasToBlob(canvas);
return blob;
}
export async function getFontEmbedCSS(node, options = {}) {
return getWebFontCSS(node, options);
}
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAC/D,OAAO,EACL,YAAY,EACZ,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EACb,qBAAqB,GACtB,MAAM,QAAQ,CAAA;AAEf,MAAM,CAAC,KAAK,UAAU,KAAK,CACzB,IAAO,EACP,UAAmB,EAAE;IAErB,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACrD,MAAM,UAAU,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAgB,CAAA;IACxE,MAAM,aAAa,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IACxC,MAAM,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IACtC,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM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AK,UAAU,eAAe,CACnC,IAAO,EACP,UAAmB,EAAE;IAErB,OAAO,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;AACrC,CAAC"}
+1
View File
@@ -0,0 +1 @@
export declare function getMimeType(url: string): string;
+24
View File
@@ -0,0 +1,24 @@
const WOFF = 'application/font-woff';
const JPEG = 'image/jpeg';
const mimes = {
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',
webp: 'image/webp',
};
function getExtension(url) {
const match = /\.([^./]*?)$/g.exec(url);
return match ? match[1] : '';
}
export function getMimeType(url) {
const extension = getExtension(url).toLowerCase();
return mimes[extension] || '';
}
//# sourceMappingURL=mimes.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"mimes.js","sourceRoot":"","sources":["../src/mimes.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,GAAG,uBAAuB,CAAA;AACpC,MAAM,IAAI,GAAG,YAAY,CAAA;AACzB,MAAM,KAAK,GAA8B;IACvC,IAAI,EAAE,IAAI;IACV,KAAK,EAAE,IAAI;IACX,GAAG,EAAE,2BAA2B;IAChC,GAAG,EAAE,+BAA+B;IACpC,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,eAAe;IACpB,IAAI,EAAE,YAAY;CACnB,CAAA;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IACvC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AAC9B,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAA;IACjD,OAAO,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,CAAA;AAC/B,CAAC"}
+96
View File
@@ -0,0 +1,96 @@
export interface Options {
/**
* Width in pixels to be applied to node before rendering.
*/
width?: number;
/**
* Height in pixels to be applied to node before rendering.
*/
height?: number;
/**
* A string value for the background color, any valid CSS color value.
*/
backgroundColor?: string;
/**
* Width in pixels to be applied to canvas on export.
*/
canvasWidth?: number;
/**
* Height in pixels to be applied to canvas on export.
*/
canvasHeight?: number;
/**
* An object whose properties to be copied to node's style before rendering.
*/
style?: Partial<CSSStyleDeclaration>;
/**
* An array of style properties to be copied to node's style before rendering.
* For performance-critical scenarios, users may want to specify only the
* required properties instead of all styles.
*/
includeStyleProperties?: string[];
/**
* A function taking DOM node as argument. Should return `true` if passed
* node should be included in the output. Excluding node means excluding
* it's children as well.
*/
filter?: (domNode: HTMLElement) => boolean;
/**
* A number between `0` and `1` indicating image quality (e.g. 0.92 => 92%)
* of the JPEG image.
*/
quality?: number;
/**
* Set to `true` to append the current time as a query string to URL
* requests to enable cache busting.
*/
cacheBust?: boolean;
/**
* Set false to use all URL as cache key.
* Default: false | undefined - which strips away the query parameters
*/
includeQueryParams?: boolean;
/**
* A data URL for a placeholder image that will be used when fetching
* an image fails. Defaults to an empty string and will render empty
* areas for failed images.
*/
imagePlaceholder?: string;
/**
* The pixel ratio of captured image. Defalut is the actual pixel ratio of
* the device. Set 1 to use as initial-scale 1 for the image
*/
pixelRatio?: number;
/**
* Option to skip the fonts download and embed.
*/
skipFonts?: boolean;
/**
* The preferred font format. If specified all other font formats are ignored.
*/
preferredFontFormat?: 'woff' | 'woff2' | 'truetype' | 'opentype' | 'embedded-opentype' | 'svg' | string;
/**
* A CSS string to specify for font embeds. If specified only this CSS will
* be present in the resulting image. Use with `getFontEmbedCSS()` to
* create embed CSS for use across multiple calls to library functions.
*/
fontEmbedCSS?: string;
/**
* A boolean to turn off auto scaling for truly massive images..
*/
skipAutoScale?: boolean;
/**
* A string indicating the image format. The default type is image/png; that type is also used if the given type isn't supported.
*/
type?: string;
/**
*
*the second parameter of window.fetch (Promise<Response> fetch(input[, init]))
*
*/
fetchRequestInit?: RequestInit;
/**
* An event handler for the error event when any image in html has problem with loading.
*/
onImageErrorHandler?: OnErrorEventHandler;
}
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
+26
View File
@@ -0,0 +1,26 @@
import type { Options } from './types';
export declare function resolveUrl(url: string, baseUrl: string | null): string;
export declare const uuid: () => string;
export declare function delay<T>(ms: number): (args: T) => Promise<T>;
export declare function toArray<T>(arrayLike: any): T[];
export declare function getStyleProperties(options?: Options): string[];
export declare function getImageSize(targetNode: HTMLElement, options?: Options): {
width: number;
height: number;
};
export declare function getPixelRatio(): number;
export declare function checkCanvasDimensions(canvas: HTMLCanvasElement): void;
export declare function canvasToBlob(canvas: HTMLCanvasElement, options?: Options): Promise<Blob | null>;
export declare function createImage(url: string): Promise<HTMLImageElement>;
export declare function svgToDataURL(svg: SVGElement): Promise<string>;
export declare function nodeToDataURL(node: HTMLElement, width: number, height: number): Promise<string>;
export declare const isInstanceOfElement: <T extends {
new (): Element;
prototype: Element;
} | {
new (): HTMLElement;
prototype: HTMLElement;
} | {
new (): SVGImageElement;
prototype: SVGImageElement;
}>(node: Element | HTMLElement | SVGImageElement, instance: T) => node is T["prototype"];
+193
View File
@@ -0,0 +1,193 @@
export function resolveUrl(url, baseUrl) {
// url is absolute already
if (url.match(/^[a-z]+:\/\//i)) {
return url;
}
// url is absolute already, without protocol
if (url.match(/^\/\//)) {
return window.location.protocol + url;
}
// dataURI, mailto:, tel:, etc.
if (url.match(/^[a-z]+:/i)) {
return url;
}
const doc = document.implementation.createHTMLDocument();
const base = doc.createElement('base');
const a = doc.createElement('a');
doc.head.appendChild(base);
doc.body.appendChild(a);
if (baseUrl) {
base.href = baseUrl;
}
a.href = url;
return a.href;
}
export const uuid = (() => {
// generate uuid for className of pseudo elements.
// We should not use GUIDs, otherwise pseudo elements sometimes cannot be captured.
let counter = 0;
// ref: http://stackoverflow.com/a/6248722/2519373
const random = () =>
// eslint-disable-next-line no-bitwise
`0000${((Math.random() * 36 ** 4) << 0).toString(36)}`.slice(-4);
return () => {
counter += 1;
return `u${random()}${counter}`;
};
})();
export function delay(ms) {
return (args) => new Promise((resolve) => {
setTimeout(() => resolve(args), ms);
});
}
export function toArray(arrayLike) {
const arr = [];
for (let i = 0, l = arrayLike.length; i < l; i++) {
arr.push(arrayLike[i]);
}
return arr;
}
let styleProps = null;
export function getStyleProperties(options = {}) {
if (styleProps) {
return styleProps;
}
if (options.includeStyleProperties) {
styleProps = options.includeStyleProperties;
return styleProps;
}
styleProps = toArray(window.getComputedStyle(document.documentElement));
return styleProps;
}
function px(node, styleProperty) {
const win = node.ownerDocument.defaultView || window;
const val = win.getComputedStyle(node).getPropertyValue(styleProperty);
return val ? parseFloat(val.replace('px', '')) : 0;
}
function getNodeWidth(node) {
const leftBorder = px(node, 'border-left-width');
const rightBorder = px(node, 'border-right-width');
return node.clientWidth + leftBorder + rightBorder;
}
function getNodeHeight(node) {
const topBorder = px(node, 'border-top-width');
const bottomBorder = px(node, 'border-bottom-width');
return node.clientHeight + topBorder + bottomBorder;
}
export function getImageSize(targetNode, options = {}) {
const width = options.width || getNodeWidth(targetNode);
const height = options.height || getNodeHeight(targetNode);
return { width, height };
}
export function getPixelRatio() {
let ratio;
let FINAL_PROCESS;
try {
FINAL_PROCESS = process;
}
catch (e) {
// pass
}
const val = FINAL_PROCESS && FINAL_PROCESS.env
? FINAL_PROCESS.env.devicePixelRatio
: null;
if (val) {
ratio = parseInt(val, 10);
if (Number.isNaN(ratio)) {
ratio = 1;
}
}
return ratio || window.devicePixelRatio || 1;
}
// @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size
const canvasDimensionLimit = 16384;
export function checkCanvasDimensions(canvas) {
if (canvas.width > canvasDimensionLimit ||
canvas.height > canvasDimensionLimit) {
if (canvas.width > canvasDimensionLimit &&
canvas.height > canvasDimensionLimit) {
if (canvas.width > canvas.height) {
canvas.height *= canvasDimensionLimit / canvas.width;
canvas.width = canvasDimensionLimit;
}
else {
canvas.width *= canvasDimensionLimit / canvas.height;
canvas.height = canvasDimensionLimit;
}
}
else if (canvas.width > canvasDimensionLimit) {
canvas.height *= canvasDimensionLimit / canvas.width;
canvas.width = canvasDimensionLimit;
}
else {
canvas.width *= canvasDimensionLimit / canvas.height;
canvas.height = canvasDimensionLimit;
}
}
}
export function canvasToBlob(canvas, options = {}) {
if (canvas.toBlob) {
return new Promise((resolve) => {
canvas.toBlob(resolve, options.type ? options.type : 'image/png', options.quality ? options.quality : 1);
});
}
return new Promise((resolve) => {
const binaryString = window.atob(canvas
.toDataURL(options.type ? options.type : undefined, options.quality ? options.quality : undefined)
.split(',')[1]);
const len = binaryString.length;
const binaryArray = new Uint8Array(len);
for (let i = 0; i < len; i += 1) {
binaryArray[i] = binaryString.charCodeAt(i);
}
resolve(new Blob([binaryArray], {
type: options.type ? options.type : 'image/png',
}));
});
}
export function createImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
img.decode().then(() => {
requestAnimationFrame(() => resolve(img));
});
};
img.onerror = reject;
img.crossOrigin = 'anonymous';
img.decoding = 'async';
img.src = url;
});
}
export async function svgToDataURL(svg) {
return Promise.resolve()
.then(() => new XMLSerializer().serializeToString(svg))
.then(encodeURIComponent)
.then((html) => `data:image/svg+xml;charset=utf-8,${html}`);
}
export async function nodeToDataURL(node, width, height) {
const xmlns = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(xmlns, 'svg');
const foreignObject = document.createElementNS(xmlns, 'foreignObject');
svg.setAttribute('width', `${width}`);
svg.setAttribute('height', `${height}`);
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
foreignObject.setAttribute('width', '100%');
foreignObject.setAttribute('height', '100%');
foreignObject.setAttribute('x', '0');
foreignObject.setAttribute('y', '0');
foreignObject.setAttribute('externalResourcesRequired', 'true');
svg.appendChild(foreignObject);
foreignObject.appendChild(node);
return svgToDataURL(svg);
}
export const isInstanceOfElement = (node, instance) => {
if (node instanceof instance)
return true;
const nodePrototype = Object.getPrototypeOf(node);
if (nodePrototype === null)
return false;
return (nodePrototype.constructor.name === instance.name ||
isInstanceOfElement(nodePrototype, instance));
};
//# sourceMappingURL=util.js.map
File diff suppressed because one or more lines are too long