| 1 |
/* global process */ |
| 2 |
|
| 3 |
/****************************************************************************** |
| 4 |
------------------------------------------------------------------------------ |
| 5 |
Build process |
| 6 |
------------------------------------------------------------------------------ |
| 7 |
- Clone https://github.com/bubkoo/html-to-image |
| 8 |
- Install packages with NPM (npm i) |
| 9 |
- Change rollup.config.js and set format to "es" |
| 10 |
- Change tsconfig.json and add |
| 11 |
"compilerOptions": { |
| 12 |
"target": "ES2022", |
| 13 |
"module": "ESNext", |
| 14 |
}, |
| 15 |
- Run the build script (npm run build:umd --no-compact) |
| 16 |
- This file will be in the dist/ folder |
| 17 |
|
| 18 |
------------------------------------------------------------------------------ |
| 19 |
Forks license (https://github.com/bubkoo/html-to-image): |
| 20 |
------------------------------------------------------------------------------ |
| 21 |
|
| 22 |
MIT License |
| 23 |
|
| 24 |
Copyright (c) 2017-2023 W.Y. |
| 25 |
|
| 26 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 27 |
of this software and associated documentation files (the "Software"), to deal |
| 28 |
in the Software without restriction, including without limitation the rights |
| 29 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 30 |
copies of the Software, and to permit persons to whom the Software is |
| 31 |
furnished to do so, subject to the following conditions: |
| 32 |
|
| 33 |
The above copyright notice and this permission notice shall be included in all |
| 34 |
copies or substantial portions of the Software. |
| 35 |
|
| 36 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 37 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 38 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 39 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 40 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 41 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 42 |
SOFTWARE. |
| 43 |
|
| 44 |
------------------------------------------------------------------------------ |
| 45 |
Original license (https://github.com/tsayen/dom-to-image): |
| 46 |
------------------------------------------------------------------------------ |
| 47 |
The MIT License (MIT) |
| 48 |
|
| 49 |
Copyright 2015 Anatolii Saienko |
| 50 |
https://github.com/tsayen |
| 51 |
|
| 52 |
Copyright 2012 Paul Bakaus |
| 53 |
http://paulbakaus.com/ |
| 54 |
|
| 55 |
Permission is hereby granted, free of charge, to any person obtaining |
| 56 |
a copy of this software and associated documentation files (the |
| 57 |
"Software"), to deal in the Software without restriction, including |
| 58 |
without limitation the rights to use, copy, modify, merge, publish, |
| 59 |
distribute, sublicense, and/or sell copies of the Software, and to |
| 60 |
permit persons to whom the Software is furnished to do so, subject to |
| 61 |
the following conditions: |
| 62 |
|
| 63 |
The above copyright notice and this permission notice shall be |
| 64 |
included in all copies or substantial portions of the Software. |
| 65 |
|
| 66 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 67 |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 68 |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 69 |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 70 |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 71 |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 72 |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 73 |
***************************************************************************** */ |
| 74 |
|
| 75 |
function resolveUrl(url, baseUrl) { |
| 76 |
// url is absolute already |
| 77 |
if (url.match(/^[a-z]+:\/\//i)) { |
| 78 |
return url; |
| 79 |
} |
| 80 |
// url is absolute already, without protocol |
| 81 |
if (url.match(/^\/\//)) { |
| 82 |
return window.location.protocol + url; |
| 83 |
} |
| 84 |
// dataURI, mailto:, tel:, etc. |
| 85 |
if (url.match(/^[a-z]+:/i)) { |
| 86 |
return url; |
| 87 |
} |
| 88 |
const doc = document.implementation.createHTMLDocument(); |
| 89 |
const base = doc.createElement("base"); |
| 90 |
const a = doc.createElement("a"); |
| 91 |
doc.head.appendChild(base); |
| 92 |
doc.body.appendChild(a); |
| 93 |
if (baseUrl) { |
| 94 |
base.href = baseUrl; |
| 95 |
} |
| 96 |
a.href = url; |
| 97 |
return a.href; |
| 98 |
} |
| 99 |
const uuid = (() => { |
| 100 |
// generate uuid for className of pseudo elements. |
| 101 |
// We should not use GUIDs, otherwise pseudo elements sometimes cannot be captured. |
| 102 |
let counter = 0; |
| 103 |
// ref: http://stackoverflow.com/a/6248722/2519373 |
| 104 |
const random = () => |
| 105 |
// eslint-disable-next-line no-bitwise |
| 106 |
`0000${((Math.random() * 36 ** 4) << 0).toString(36)}`.slice(-4); |
| 107 |
return () => { |
| 108 |
counter += 1; |
| 109 |
return `u${random()}${counter}`; |
| 110 |
}; |
| 111 |
})(); |
| 112 |
function toArray(arrayLike) { |
| 113 |
const arr = []; |
| 114 |
for (let i = 0, l = arrayLike.length; i < l; i++) { |
| 115 |
arr.push(arrayLike[i]); |
| 116 |
} |
| 117 |
return arr; |
| 118 |
} |
| 119 |
function px(node, styleProperty) { |
| 120 |
const win = node.ownerDocument.defaultView || window; |
| 121 |
const val = win.getComputedStyle(node).getPropertyValue(styleProperty); |
| 122 |
return val ? parseFloat(val.replace("px", "")) : 0; |
| 123 |
} |
| 124 |
function getNodeWidth(node) { |
| 125 |
const leftBorder = px(node, "border-left-width"); |
| 126 |
const rightBorder = px(node, "border-right-width"); |
| 127 |
return node.clientWidth + leftBorder + rightBorder; |
| 128 |
} |
| 129 |
function getNodeHeight(node) { |
| 130 |
const topBorder = px(node, "border-top-width"); |
| 131 |
const bottomBorder = px(node, "border-bottom-width"); |
| 132 |
return node.clientHeight + topBorder + bottomBorder; |
| 133 |
} |
| 134 |
function getImageSize(targetNode, options = {}) { |
| 135 |
const width = options.width || getNodeWidth(targetNode); |
| 136 |
const height = options.height || getNodeHeight(targetNode); |
| 137 |
return { width, height }; |
| 138 |
} |
| 139 |
function getPixelRatio() { |
| 140 |
let ratio; |
| 141 |
let FINAL_PROCESS; |
| 142 |
try { |
| 143 |
FINAL_PROCESS = process; |
| 144 |
} catch { |
| 145 |
// pass |
| 146 |
} |
| 147 |
const val = FINAL_PROCESS && FINAL_PROCESS.env ? FINAL_PROCESS.env.devicePixelRatio : null; |
| 148 |
if (val) { |
| 149 |
ratio = parseInt(val, 10); |
| 150 |
if (Number.isNaN(ratio)) { |
| 151 |
ratio = 1; |
| 152 |
} |
| 153 |
} |
| 154 |
return ratio || window.devicePixelRatio || 1; |
| 155 |
} |
| 156 |
// @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size |
| 157 |
const canvasDimensionLimit = 16384; |
| 158 |
function checkCanvasDimensions(canvas) { |
| 159 |
if (canvas.width > canvasDimensionLimit || canvas.height > canvasDimensionLimit) { |
| 160 |
if (canvas.width > canvasDimensionLimit && canvas.height > canvasDimensionLimit) { |
| 161 |
if (canvas.width > canvas.height) { |
| 162 |
canvas.height *= canvasDimensionLimit / canvas.width; |
| 163 |
canvas.width = canvasDimensionLimit; |
| 164 |
} else { |
| 165 |
canvas.width *= canvasDimensionLimit / canvas.height; |
| 166 |
canvas.height = canvasDimensionLimit; |
| 167 |
} |
| 168 |
} else if (canvas.width > canvasDimensionLimit) { |
| 169 |
canvas.height *= canvasDimensionLimit / canvas.width; |
| 170 |
canvas.width = canvasDimensionLimit; |
| 171 |
} else { |
| 172 |
canvas.width *= canvasDimensionLimit / canvas.height; |
| 173 |
canvas.height = canvasDimensionLimit; |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
function canvasToBlob(canvas, options = {}) { |
| 178 |
if (canvas.toBlob) { |
| 179 |
return new Promise((resolve) => { |
| 180 |
canvas.toBlob( |
| 181 |
resolve, |
| 182 |
options.type ? options.type : "image/png", |
| 183 |
options.quality ? options.quality : 1 |
| 184 |
); |
| 185 |
}); |
| 186 |
} |
| 187 |
return new Promise((resolve) => { |
| 188 |
const binaryString = window.atob( |
| 189 |
canvas |
| 190 |
.toDataURL( |
| 191 |
options.type ? options.type : undefined, |
| 192 |
options.quality ? options.quality : undefined |
| 193 |
) |
| 194 |
.split(",")[1] |
| 195 |
); |
| 196 |
const len = binaryString.length; |
| 197 |
const binaryArray = new Uint8Array(len); |
| 198 |
for (let i = 0; i < len; i += 1) { |
| 199 |
binaryArray[i] = binaryString.charCodeAt(i); |
| 200 |
} |
| 201 |
resolve( |
| 202 |
new Blob([binaryArray], { |
| 203 |
type: options.type ? options.type : "image/png", |
| 204 |
}) |
| 205 |
); |
| 206 |
}); |
| 207 |
} |
| 208 |
function createImage(url) { |
| 209 |
return new Promise((resolve, reject) => { |
| 210 |
const img = new Image(); |
| 211 |
img.onload = () => { |
| 212 |
img.decode().then(() => { |
| 213 |
requestAnimationFrame(() => resolve(img)); |
| 214 |
}); |
| 215 |
}; |
| 216 |
img.onerror = reject; |
| 217 |
img.crossOrigin = "anonymous"; |
| 218 |
img.decoding = "async"; |
| 219 |
img.src = url; |
| 220 |
}); |
| 221 |
} |
| 222 |
async function svgToDataURL(svg) { |
| 223 |
return Promise.resolve() |
| 224 |
.then(() => new XMLSerializer().serializeToString(svg)) |
| 225 |
.then(encodeURIComponent) |
| 226 |
.then((html) => `data:image/svg+xml;charset=utf-8,${html}`); |
| 227 |
} |
| 228 |
async function nodeToDataURL(node, width, height) { |
| 229 |
const xmlns = "http://www.w3.org/2000/svg"; |
| 230 |
const svg = document.createElementNS(xmlns, "svg"); |
| 231 |
const foreignObject = document.createElementNS(xmlns, "foreignObject"); |
| 232 |
svg.setAttribute("width", `${width}`); |
| 233 |
svg.setAttribute("height", `${height}`); |
| 234 |
svg.setAttribute("viewBox", `0 0 ${width} ${height}`); |
| 235 |
foreignObject.setAttribute("width", "100%"); |
| 236 |
foreignObject.setAttribute("height", "100%"); |
| 237 |
foreignObject.setAttribute("x", "0"); |
| 238 |
foreignObject.setAttribute("y", "0"); |
| 239 |
foreignObject.setAttribute("externalResourcesRequired", "true"); |
| 240 |
svg.appendChild(foreignObject); |
| 241 |
foreignObject.appendChild(node); |
| 242 |
return svgToDataURL(svg); |
| 243 |
} |
| 244 |
const isInstanceOfElement = (node, instance) => { |
| 245 |
if (node instanceof instance) { |
| 246 |
return true; |
| 247 |
} |
| 248 |
const nodePrototype = Object.getPrototypeOf(node); |
| 249 |
if (nodePrototype === null) { |
| 250 |
return false; |
| 251 |
} |
| 252 |
return ( |
| 253 |
nodePrototype.constructor.name === instance.name || |
| 254 |
isInstanceOfElement(nodePrototype, instance) |
| 255 |
); |
| 256 |
}; |
| 257 |
|
| 258 |
function formatCSSText(style) { |
| 259 |
const content = style.getPropertyValue("content"); |
| 260 |
return `${style.cssText} content: '${content.replace(/'|"/g, "")}';`; |
| 261 |
} |
| 262 |
function formatCSSProperties(style) { |
| 263 |
return toArray(style) |
| 264 |
.map((name) => { |
| 265 |
const value = style.getPropertyValue(name); |
| 266 |
const priority = style.getPropertyPriority(name); |
| 267 |
return `${name}: ${value}${priority ? " !important" : ""};`; |
| 268 |
}) |
| 269 |
.join(" "); |
| 270 |
} |
| 271 |
function getPseudoElementStyle(className, pseudo, style) { |
| 272 |
const selector = `.${className}:${pseudo}`; |
| 273 |
const cssText = style.cssText ? formatCSSText(style) : formatCSSProperties(style); |
| 274 |
return document.createTextNode(`${selector}{${cssText}}`); |
| 275 |
} |
| 276 |
function clonePseudoElement(nativeNode, clonedNode, pseudo) { |
| 277 |
const style = window.getComputedStyle(nativeNode, pseudo); |
| 278 |
const content = style.getPropertyValue("content"); |
| 279 |
if (content === "" || content === "none") { |
| 280 |
return; |
| 281 |
} |
| 282 |
const className = uuid(); |
| 283 |
try { |
| 284 |
clonedNode.className = `${clonedNode.className} ${className}`; |
| 285 |
} catch { |
| 286 |
return; |
| 287 |
} |
| 288 |
const styleElement = document.createElement("style"); |
| 289 |
styleElement.appendChild(getPseudoElementStyle(className, pseudo, style)); |
| 290 |
clonedNode.appendChild(styleElement); |
| 291 |
} |
| 292 |
function clonePseudoElements(nativeNode, clonedNode) { |
| 293 |
clonePseudoElement(nativeNode, clonedNode, ":before"); |
| 294 |
clonePseudoElement(nativeNode, clonedNode, ":after"); |
| 295 |
} |
| 296 |
|
| 297 |
const WOFF = "application/font-woff"; |
| 298 |
const JPEG = "image/jpeg"; |
| 299 |
const mimes = { |
| 300 |
woff: WOFF, |
| 301 |
woff2: WOFF, |
| 302 |
ttf: "application/font-truetype", |
| 303 |
eot: "application/vnd.ms-fontobject", |
| 304 |
png: "image/png", |
| 305 |
jpg: JPEG, |
| 306 |
jpeg: JPEG, |
| 307 |
gif: "image/gif", |
| 308 |
tiff: "image/tiff", |
| 309 |
svg: "image/svg+xml", |
| 310 |
webp: "image/webp", |
| 311 |
}; |
| 312 |
function getExtension(url) { |
| 313 |
const match = /\.([^./]*?)$/g.exec(url); |
| 314 |
return match ? match[1] : ""; |
| 315 |
} |
| 316 |
function getMimeType(url) { |
| 317 |
const extension = getExtension(url).toLowerCase(); |
| 318 |
return mimes[extension] || ""; |
| 319 |
} |
| 320 |
|
| 321 |
function getContentFromDataUrl(dataURL) { |
| 322 |
return dataURL.split(/,/)[1]; |
| 323 |
} |
| 324 |
function isDataUrl(url) { |
| 325 |
return url.search(/^(data:)/) !== -1; |
| 326 |
} |
| 327 |
function makeDataUrl(content, mimeType) { |
| 328 |
return `data:${mimeType};base64,${content}`; |
| 329 |
} |
| 330 |
async function fetchAsDataURL(url, init, process) { |
| 331 |
const res = await fetch(url, { ...init, mode: "no-cors" }); |
| 332 |
if (res.status === 404) { |
| 333 |
throw new Error(`Resource "${res.url}" not found`); |
| 334 |
} |
| 335 |
const blob = await res.blob(); |
| 336 |
return new Promise((resolve, reject) => { |
| 337 |
const reader = new FileReader(); |
| 338 |
reader.onerror = reject; |
| 339 |
reader.onloadend = () => { |
| 340 |
try { |
| 341 |
resolve(process({ res, result: reader.result })); |
| 342 |
} catch (error) { |
| 343 |
reject(error); |
| 344 |
} |
| 345 |
}; |
| 346 |
reader.readAsDataURL(blob); |
| 347 |
}); |
| 348 |
} |
| 349 |
const cache = {}; |
| 350 |
function getCacheKey(url, contentType, includeQueryParams) { |
| 351 |
let key = url.replace(/\?.*/, ""); |
| 352 |
if (includeQueryParams) { |
| 353 |
key = url; |
| 354 |
} |
| 355 |
// font resource |
| 356 |
if (/ttf|otf|eot|woff2?/i.test(key)) { |
| 357 |
key = key.replace(/.*\//, ""); |
| 358 |
} |
| 359 |
return contentType ? `[${contentType}]${key}` : key; |
| 360 |
} |
| 361 |
async function resourceToDataURL(resourceUrl, contentType, options) { |
| 362 |
const cacheKey = getCacheKey(resourceUrl, contentType, options.includeQueryParams); |
| 363 |
if (cache[cacheKey] != null) { |
| 364 |
return cache[cacheKey]; |
| 365 |
} |
| 366 |
// ref: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache |
| 367 |
if (options.cacheBust) { |
| 368 |
// eslint-disable-next-line no-param-reassign |
| 369 |
resourceUrl += (/\?/.test(resourceUrl) ? "&" : "?") + new Date().getTime(); |
| 370 |
} |
| 371 |
let dataURL; |
| 372 |
try { |
| 373 |
const content = await fetchAsDataURL( |
| 374 |
resourceUrl, |
| 375 |
options.fetchRequestInit, |
| 376 |
({ res, result }) => { |
| 377 |
if (!contentType) { |
| 378 |
// eslint-disable-next-line no-param-reassign |
| 379 |
contentType = res.headers.get("Content-Type") || ""; |
| 380 |
} |
| 381 |
return getContentFromDataUrl(result); |
| 382 |
} |
| 383 |
); |
| 384 |
dataURL = makeDataUrl(content, contentType); |
| 385 |
} catch (error) { |
| 386 |
dataURL = options.imagePlaceholder || ""; |
| 387 |
let msg = `Failed to fetch resource: ${resourceUrl}`; |
| 388 |
if (error) { |
| 389 |
msg = typeof error === "string" ? error : error.message; |
| 390 |
} |
| 391 |
if (msg) { |
| 392 |
console.info(msg); |
| 393 |
} |
| 394 |
} |
| 395 |
cache[cacheKey] = dataURL; |
| 396 |
return dataURL; |
| 397 |
} |
| 398 |
|
| 399 |
async function cloneCanvasElement(canvas) { |
| 400 |
const dataURL = canvas.toDataURL(); |
| 401 |
if (dataURL === "data:,") { |
| 402 |
return canvas.cloneNode(false); |
| 403 |
} |
| 404 |
return createImage(dataURL); |
| 405 |
} |
| 406 |
async function cloneVideoElement(video, options) { |
| 407 |
if (video.currentSrc) { |
| 408 |
const canvas = document.createElement("canvas"); |
| 409 |
const ctx = canvas.getContext("2d"); |
| 410 |
canvas.width = video.clientWidth; |
| 411 |
canvas.height = video.clientHeight; |
| 412 |
ctx?.drawImage(video, 0, 0, canvas.width, canvas.height); |
| 413 |
const dataURL = canvas.toDataURL(); |
| 414 |
return createImage(dataURL); |
| 415 |
} |
| 416 |
const poster = video.poster; |
| 417 |
const contentType = getMimeType(poster); |
| 418 |
const dataURL = await resourceToDataURL(poster, contentType, options); |
| 419 |
return createImage(dataURL); |
| 420 |
} |
| 421 |
async function cloneIFrameElement(iframe) { |
| 422 |
try { |
| 423 |
if (iframe?.contentDocument?.body) { |
| 424 |
return await cloneNode(iframe.contentDocument.body, {}, true); |
| 425 |
} |
| 426 |
} catch { |
| 427 |
// Failed to clone iframe |
| 428 |
} |
| 429 |
return iframe.cloneNode(false); |
| 430 |
} |
| 431 |
async function cloneSingleNode(node, options) { |
| 432 |
if (isInstanceOfElement(node, HTMLCanvasElement)) { |
| 433 |
return cloneCanvasElement(node); |
| 434 |
} |
| 435 |
if (isInstanceOfElement(node, HTMLVideoElement)) { |
| 436 |
return cloneVideoElement(node, options); |
| 437 |
} |
| 438 |
if (isInstanceOfElement(node, HTMLIFrameElement)) { |
| 439 |
return cloneIFrameElement(node); |
| 440 |
} |
| 441 |
return node.cloneNode(false); |
| 442 |
} |
| 443 |
const isSlotElement = (node) => node.tagName != null && node.tagName.toUpperCase() === "SLOT"; |
| 444 |
async function cloneChildren(nativeNode, clonedNode, options) { |
| 445 |
let children = []; |
| 446 |
if (isSlotElement(nativeNode) && nativeNode.assignedNodes) { |
| 447 |
children = toArray(nativeNode.assignedNodes()); |
| 448 |
} else if ( |
| 449 |
isInstanceOfElement(nativeNode, HTMLIFrameElement) && |
| 450 |
nativeNode.contentDocument?.body |
| 451 |
) { |
| 452 |
children = toArray(nativeNode.contentDocument.body.childNodes); |
| 453 |
} else { |
| 454 |
children = toArray((nativeNode.shadowRoot ?? nativeNode).childNodes); |
| 455 |
} |
| 456 |
if (children.length === 0 || isInstanceOfElement(nativeNode, HTMLVideoElement)) { |
| 457 |
return clonedNode; |
| 458 |
} |
| 459 |
await children.reduce( |
| 460 |
(deferred, child) => |
| 461 |
deferred |
| 462 |
.then(() => cloneNode(child, options)) |
| 463 |
.then((clonedChild) => { |
| 464 |
if (clonedChild) { |
| 465 |
clonedNode.appendChild(clonedChild); |
| 466 |
} |
| 467 |
}), |
| 468 |
Promise.resolve() |
| 469 |
); |
| 470 |
return clonedNode; |
| 471 |
} |
| 472 |
function cloneCSSStyle(nativeNode, clonedNode) { |
| 473 |
const targetStyle = clonedNode.style; |
| 474 |
if (!targetStyle) { |
| 475 |
return; |
| 476 |
} |
| 477 |
const sourceStyle = window.getComputedStyle(nativeNode); |
| 478 |
if (sourceStyle.cssText) { |
| 479 |
targetStyle.cssText = sourceStyle.cssText; |
| 480 |
targetStyle.transformOrigin = sourceStyle.transformOrigin; |
| 481 |
} else { |
| 482 |
toArray(sourceStyle).forEach((name) => { |
| 483 |
let value = sourceStyle.getPropertyValue(name); |
| 484 |
if (name === "font-size" && value.endsWith("px")) { |
| 485 |
const reducedFont = |
| 486 |
Math.floor(parseFloat(value.substring(0, value.length - 2))) - 0.1; |
| 487 |
value = `${reducedFont}px`; |
| 488 |
} |
| 489 |
if ( |
| 490 |
isInstanceOfElement(nativeNode, HTMLIFrameElement) && |
| 491 |
name === "display" && |
| 492 |
value === "inline" |
| 493 |
) { |
| 494 |
value = "block"; |
| 495 |
} |
| 496 |
if (name === "d" && clonedNode.getAttribute("d")) { |
| 497 |
value = `path(${clonedNode.getAttribute("d")})`; |
| 498 |
} |
| 499 |
targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name)); |
| 500 |
}); |
| 501 |
} |
| 502 |
} |
| 503 |
function cloneInputValue(nativeNode, clonedNode) { |
| 504 |
if (isInstanceOfElement(nativeNode, HTMLTextAreaElement)) { |
| 505 |
clonedNode.innerHTML = nativeNode.value; |
| 506 |
} |
| 507 |
if (isInstanceOfElement(nativeNode, HTMLInputElement)) { |
| 508 |
clonedNode.setAttribute("value", nativeNode.value); |
| 509 |
} |
| 510 |
} |
| 511 |
function cloneSelectValue(nativeNode, clonedNode) { |
| 512 |
if (isInstanceOfElement(nativeNode, HTMLSelectElement)) { |
| 513 |
const clonedSelect = clonedNode; |
| 514 |
const selectedOption = Array.from(clonedSelect.children).find( |
| 515 |
(child) => nativeNode.value === child.getAttribute("value") |
| 516 |
); |
| 517 |
if (selectedOption) { |
| 518 |
selectedOption.setAttribute("selected", ""); |
| 519 |
} |
| 520 |
} |
| 521 |
} |
| 522 |
function decorate(nativeNode, clonedNode) { |
| 523 |
if (isInstanceOfElement(clonedNode, Element)) { |
| 524 |
cloneCSSStyle(nativeNode, clonedNode); |
| 525 |
clonePseudoElements(nativeNode, clonedNode); |
| 526 |
cloneInputValue(nativeNode, clonedNode); |
| 527 |
cloneSelectValue(nativeNode, clonedNode); |
| 528 |
} |
| 529 |
return clonedNode; |
| 530 |
} |
| 531 |
async function ensureSVGSymbols(clone, options) { |
| 532 |
const uses = clone.querySelectorAll ? clone.querySelectorAll("use") : []; |
| 533 |
if (uses.length === 0) { |
| 534 |
return clone; |
| 535 |
} |
| 536 |
const processedDefs = {}; |
| 537 |
for (let i = 0; i < uses.length; i++) { |
| 538 |
const use = uses[i]; |
| 539 |
const id = use.getAttribute("xlink:href"); |
| 540 |
if (id) { |
| 541 |
const exist = clone.querySelector(id); |
| 542 |
const definition = document.querySelector(id); |
| 543 |
if (!exist && definition && !processedDefs[id]) { |
| 544 |
// eslint-disable-next-line no-await-in-loop |
| 545 |
processedDefs[id] = await cloneNode(definition, options, true); |
| 546 |
} |
| 547 |
} |
| 548 |
} |
| 549 |
const nodes = Object.values(processedDefs); |
| 550 |
if (nodes.length) { |
| 551 |
const ns = "http://www.w3.org/1999/xhtml"; |
| 552 |
const svg = document.createElementNS(ns, "svg"); |
| 553 |
svg.setAttribute("xmlns", ns); |
| 554 |
svg.style.position = "absolute"; |
| 555 |
svg.style.width = "0"; |
| 556 |
svg.style.height = "0"; |
| 557 |
svg.style.overflow = "hidden"; |
| 558 |
svg.style.display = "none"; |
| 559 |
const defs = document.createElementNS(ns, "defs"); |
| 560 |
svg.appendChild(defs); |
| 561 |
for (let i = 0; i < nodes.length; i++) { |
| 562 |
defs.appendChild(nodes[i]); |
| 563 |
} |
| 564 |
clone.appendChild(svg); |
| 565 |
} |
| 566 |
return clone; |
| 567 |
} |
| 568 |
async function cloneNode(node, options, isRoot) { |
| 569 |
if (!isRoot && options.filter && !options.filter(node)) { |
| 570 |
return null; |
| 571 |
} |
| 572 |
return Promise.resolve(node) |
| 573 |
.then((clonedNode) => cloneSingleNode(clonedNode, options)) |
| 574 |
.then((clonedNode) => cloneChildren(node, clonedNode, options)) |
| 575 |
.then((clonedNode) => decorate(node, clonedNode)) |
| 576 |
.then((clonedNode) => ensureSVGSymbols(clonedNode, options)); |
| 577 |
} |
| 578 |
|
| 579 |
const URL_REGEX = /url\((['"]?)([^'"]+?)\1\)/g; |
| 580 |
const URL_WITH_FORMAT_REGEX = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g; |
| 581 |
const FONT_SRC_REGEX = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g; |
| 582 |
function toRegex(url) { |
| 583 |
// eslint-disable-next-line no-useless-escape |
| 584 |
const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"); |
| 585 |
return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g"); |
| 586 |
} |
| 587 |
function parseURLs(cssText) { |
| 588 |
const urls = []; |
| 589 |
cssText.replace(URL_REGEX, (raw, quotation, url) => { |
| 590 |
urls.push(url); |
| 591 |
return raw; |
| 592 |
}); |
| 593 |
return urls.filter((url) => !isDataUrl(url)); |
| 594 |
} |
| 595 |
async function embed(cssText, resourceURL, baseURL, options, getContentFromUrl) { |
| 596 |
try { |
| 597 |
const resolvedURL = baseURL ? resolveUrl(resourceURL, baseURL) : resourceURL; |
| 598 |
const contentType = getMimeType(resourceURL); |
| 599 |
let dataURL; |
| 600 |
if (getContentFromUrl) { |
| 601 |
const content = await getContentFromUrl(resolvedURL); |
| 602 |
dataURL = makeDataUrl(content, contentType); |
| 603 |
} else { |
| 604 |
dataURL = await resourceToDataURL(resolvedURL, contentType, options); |
| 605 |
} |
| 606 |
return cssText.replace(toRegex(resourceURL), `$1${dataURL}$3`); |
| 607 |
} catch { |
| 608 |
// pass |
| 609 |
} |
| 610 |
return cssText; |
| 611 |
} |
| 612 |
function filterPreferredFontFormat(str, { preferredFontFormat }) { |
| 613 |
return !preferredFontFormat |
| 614 |
? str |
| 615 |
: str.replace(FONT_SRC_REGEX, (match) => { |
| 616 |
// eslint-disable-next-line no-constant-condition |
| 617 |
while (true) { |
| 618 |
const [src, , format] = URL_WITH_FORMAT_REGEX.exec(match) || []; |
| 619 |
if (!format) { |
| 620 |
return ""; |
| 621 |
} |
| 622 |
if (format === preferredFontFormat) { |
| 623 |
return `src: ${src};`; |
| 624 |
} |
| 625 |
} |
| 626 |
}); |
| 627 |
} |
| 628 |
function shouldEmbed(url) { |
| 629 |
return url.search(URL_REGEX) !== -1; |
| 630 |
} |
| 631 |
async function embedResources(cssText, baseUrl, options) { |
| 632 |
if (!shouldEmbed(cssText)) { |
| 633 |
return cssText; |
| 634 |
} |
| 635 |
const filteredCSSText = filterPreferredFontFormat(cssText, options); |
| 636 |
const urls = parseURLs(filteredCSSText); |
| 637 |
return urls.reduce( |
| 638 |
(deferred, url) => deferred.then((css) => embed(css, url, baseUrl, options)), |
| 639 |
Promise.resolve(filteredCSSText) |
| 640 |
); |
| 641 |
} |
| 642 |
|
| 643 |
async function embedProp(propName, node, options) { |
| 644 |
const propValue = node.style?.getPropertyValue(propName); |
| 645 |
if (propValue) { |
| 646 |
const cssString = await embedResources(propValue, null, options); |
| 647 |
node.style.setProperty(propName, cssString, node.style.getPropertyPriority(propName)); |
| 648 |
return true; |
| 649 |
} |
| 650 |
return false; |
| 651 |
} |
| 652 |
async function embedBackground(clonedNode, options) { |
| 653 |
if (!(await embedProp("background", clonedNode, options))) { |
| 654 |
await embedProp("background-image", clonedNode, options); |
| 655 |
} |
| 656 |
if (!(await embedProp("mask", clonedNode, options))) { |
| 657 |
await embedProp("mask-image", clonedNode, options); |
| 658 |
} |
| 659 |
} |
| 660 |
async function embedImageNode(clonedNode, options) { |
| 661 |
const isImageElement = isInstanceOfElement(clonedNode, HTMLImageElement); |
| 662 |
if ( |
| 663 |
!(isImageElement && !isDataUrl(clonedNode.src)) && |
| 664 |
!(isInstanceOfElement(clonedNode, SVGImageElement) && !isDataUrl(clonedNode.href.baseVal)) |
| 665 |
) { |
| 666 |
return; |
| 667 |
} |
| 668 |
const url = isImageElement ? clonedNode.src : clonedNode.href.baseVal; |
| 669 |
const dataURL = await resourceToDataURL(url, getMimeType(url), options); |
| 670 |
await new Promise((resolve, reject) => { |
| 671 |
clonedNode.onload = resolve; |
| 672 |
clonedNode.onerror = reject; |
| 673 |
const image = clonedNode; |
| 674 |
if (image.decode) { |
| 675 |
image.decode = resolve; |
| 676 |
} |
| 677 |
if (image.loading === "lazy") { |
| 678 |
image.loading = "eager"; |
| 679 |
} |
| 680 |
if (isImageElement) { |
| 681 |
clonedNode.srcset = ""; |
| 682 |
clonedNode.src = dataURL; |
| 683 |
} else { |
| 684 |
clonedNode.href.baseVal = dataURL; |
| 685 |
} |
| 686 |
}); |
| 687 |
} |
| 688 |
async function embedChildren(clonedNode, options) { |
| 689 |
const children = toArray(clonedNode.childNodes); |
| 690 |
const deferreds = children.map((child) => embedImages(child, options)); |
| 691 |
await Promise.all(deferreds).then(() => clonedNode); |
| 692 |
} |
| 693 |
async function embedImages(clonedNode, options) { |
| 694 |
if (isInstanceOfElement(clonedNode, Element)) { |
| 695 |
await embedBackground(clonedNode, options); |
| 696 |
await embedImageNode(clonedNode, options); |
| 697 |
await embedChildren(clonedNode, options); |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
function applyStyle(node, options) { |
| 702 |
const { style } = node; |
| 703 |
if (options.backgroundColor) { |
| 704 |
style.backgroundColor = options.backgroundColor; |
| 705 |
} |
| 706 |
if (options.width) { |
| 707 |
style.width = `${options.width}px`; |
| 708 |
} |
| 709 |
if (options.height) { |
| 710 |
style.height = `${options.height}px`; |
| 711 |
} |
| 712 |
const manual = options.style; |
| 713 |
if (manual != null) { |
| 714 |
Object.keys(manual).forEach((key) => { |
| 715 |
style[key] = manual[key]; |
| 716 |
}); |
| 717 |
} |
| 718 |
return node; |
| 719 |
} |
| 720 |
|
| 721 |
const cssFetchCache = {}; |
| 722 |
async function fetchCSS(url) { |
| 723 |
let cache = cssFetchCache[url]; |
| 724 |
if (cache != null) { |
| 725 |
return cache; |
| 726 |
} |
| 727 |
const res = await fetch(url); |
| 728 |
const cssText = await res.text(); |
| 729 |
cache = { url, cssText }; |
| 730 |
cssFetchCache[url] = cache; |
| 731 |
return cache; |
| 732 |
} |
| 733 |
async function embedFonts(data, options) { |
| 734 |
let cssText = data.cssText; |
| 735 |
const regexUrl = /url\(["']?([^"')]+)["']?\)/g; |
| 736 |
const fontLocs = cssText.match(/url\([^)]+\)/g) || []; |
| 737 |
const loadFonts = fontLocs.map(async (loc) => { |
| 738 |
let url = loc.replace(regexUrl, "$1"); |
| 739 |
if (!url.startsWith("https://")) { |
| 740 |
url = new URL(url, data.url).href; |
| 741 |
} |
| 742 |
return fetchAsDataURL(url, options.fetchRequestInit, ({ result }) => { |
| 743 |
cssText = cssText.replace(loc, `url(${result})`); |
| 744 |
return [loc, result]; |
| 745 |
}); |
| 746 |
}); |
| 747 |
return Promise.all(loadFonts).then(() => cssText); |
| 748 |
} |
| 749 |
function parseCSS(source) { |
| 750 |
if (source == null) { |
| 751 |
return []; |
| 752 |
} |
| 753 |
const result = []; |
| 754 |
const commentsRegex = /(\/\*[\s\S]*?\*\/)/gi; |
| 755 |
// strip out comments |
| 756 |
let cssText = source.replace(commentsRegex, ""); |
| 757 |
// eslint-disable-next-line prefer-regex-literals |
| 758 |
const keyframesRegex = new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})", "gi"); |
| 759 |
// eslint-disable-next-line no-constant-condition |
| 760 |
while (true) { |
| 761 |
const matches = keyframesRegex.exec(cssText); |
| 762 |
if (matches === null) { |
| 763 |
break; |
| 764 |
} |
| 765 |
result.push(matches[0]); |
| 766 |
} |
| 767 |
cssText = cssText.replace(keyframesRegex, ""); |
| 768 |
const importRegex = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi; |
| 769 |
// to match css & media queries together |
| 770 |
const combinedCSSRegex = |
| 771 |
"((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]" + |
| 772 |
"*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})"; |
| 773 |
// unified regex |
| 774 |
const unifiedRegex = new RegExp(combinedCSSRegex, "gi"); |
| 775 |
// eslint-disable-next-line no-constant-condition |
| 776 |
while (true) { |
| 777 |
let matches = importRegex.exec(cssText); |
| 778 |
if (matches === null) { |
| 779 |
matches = unifiedRegex.exec(cssText); |
| 780 |
if (matches === null) { |
| 781 |
break; |
| 782 |
} else { |
| 783 |
importRegex.lastIndex = unifiedRegex.lastIndex; |
| 784 |
} |
| 785 |
} else { |
| 786 |
unifiedRegex.lastIndex = importRegex.lastIndex; |
| 787 |
} |
| 788 |
result.push(matches[0]); |
| 789 |
} |
| 790 |
return result; |
| 791 |
} |
| 792 |
async function getCSSRules(styleSheets, options) { |
| 793 |
const ret = []; |
| 794 |
const deferreds = []; |
| 795 |
// First loop inlines imports |
| 796 |
styleSheets.forEach((sheet) => { |
| 797 |
if ("cssRules" in sheet) { |
| 798 |
try { |
| 799 |
toArray(sheet.cssRules || []).forEach((item, index) => { |
| 800 |
if (item.type === CSSRule.IMPORT_RULE) { |
| 801 |
let importIndex = index + 1; |
| 802 |
const url = item.href; |
| 803 |
const deferred = fetchCSS(url) |
| 804 |
.then((metadata) => embedFonts(metadata, options)) |
| 805 |
.then((cssText) => |
| 806 |
parseCSS(cssText).forEach((rule) => { |
| 807 |
try { |
| 808 |
sheet.insertRule( |
| 809 |
rule, |
| 810 |
rule.startsWith("@import") |
| 811 |
? (importIndex += 1) |
| 812 |
: sheet.cssRules.length |
| 813 |
); |
| 814 |
} catch (error) { |
| 815 |
console.error("Error inserting rule from remote css", { |
| 816 |
rule, |
| 817 |
error, |
| 818 |
}); |
| 819 |
} |
| 820 |
}) |
| 821 |
) |
| 822 |
.catch((e) => { |
| 823 |
console.error("Error loading remote css", e.toString()); |
| 824 |
}); |
| 825 |
deferreds.push(deferred); |
| 826 |
} |
| 827 |
}); |
| 828 |
} catch (e) { |
| 829 |
const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0]; |
| 830 |
if (sheet.href != null) { |
| 831 |
deferreds.push( |
| 832 |
fetchCSS(sheet.href) |
| 833 |
.then((metadata) => embedFonts(metadata, options)) |
| 834 |
.then((cssText) => |
| 835 |
parseCSS(cssText).forEach((rule) => { |
| 836 |
inline.insertRule(rule, sheet.cssRules.length); |
| 837 |
}) |
| 838 |
) |
| 839 |
.catch((err) => { |
| 840 |
console.error("Error loading remote stylesheet", err); |
| 841 |
}) |
| 842 |
); |
| 843 |
} |
| 844 |
console.error("Error inlining remote css file", e); |
| 845 |
} |
| 846 |
} |
| 847 |
}); |
| 848 |
return Promise.all(deferreds).then(() => { |
| 849 |
// Second loop parses rules |
| 850 |
styleSheets.forEach((sheet) => { |
| 851 |
if ("cssRules" in sheet) { |
| 852 |
try { |
| 853 |
toArray(sheet.cssRules || []).forEach((item) => { |
| 854 |
ret.push(item); |
| 855 |
}); |
| 856 |
} catch (e) { |
| 857 |
console.error(`Error while reading CSS rules from ${sheet.href}`, e); |
| 858 |
} |
| 859 |
} |
| 860 |
}); |
| 861 |
return ret; |
| 862 |
}); |
| 863 |
} |
| 864 |
function getWebFontRules(cssRules) { |
| 865 |
return cssRules |
| 866 |
.filter((rule) => rule.type === CSSRule.FONT_FACE_RULE) |
| 867 |
.filter((rule) => shouldEmbed(rule.style.getPropertyValue("src"))); |
| 868 |
} |
| 869 |
async function parseWebFontRules(node, options) { |
| 870 |
if (node.ownerDocument == null) { |
| 871 |
throw new Error("Provided element is not within a Document"); |
| 872 |
} |
| 873 |
const styleSheets = toArray(node.ownerDocument.styleSheets); |
| 874 |
const cssRules = await getCSSRules(styleSheets, options); |
| 875 |
return getWebFontRules(cssRules); |
| 876 |
} |
| 877 |
async function getWebFontCSS(node, options) { |
| 878 |
const rules = await parseWebFontRules(node, options); |
| 879 |
const cssTexts = await Promise.all( |
| 880 |
rules.map((rule) => { |
| 881 |
const baseUrl = rule.parentStyleSheet ? rule.parentStyleSheet.href : null; |
| 882 |
return embedResources(rule.cssText, baseUrl, options); |
| 883 |
}) |
| 884 |
); |
| 885 |
return cssTexts.join("\n"); |
| 886 |
} |
| 887 |
async function embedWebFonts(clonedNode, options) { |
| 888 |
const cssText = |
| 889 |
options.fontEmbedCSS != null |
| 890 |
? options.fontEmbedCSS |
| 891 |
: options.skipFonts |
| 892 |
? null |
| 893 |
: await getWebFontCSS(clonedNode, options); |
| 894 |
if (cssText) { |
| 895 |
const styleNode = document.createElement("style"); |
| 896 |
const sytleContent = document.createTextNode(cssText); |
| 897 |
styleNode.appendChild(sytleContent); |
| 898 |
if (clonedNode.firstChild) { |
| 899 |
clonedNode.insertBefore(styleNode, clonedNode.firstChild); |
| 900 |
} else { |
| 901 |
clonedNode.appendChild(styleNode); |
| 902 |
} |
| 903 |
} |
| 904 |
} |
| 905 |
|
| 906 |
async function toSvg(node, options = {}) { |
| 907 |
const { width, height } = getImageSize(node, options); |
| 908 |
const clonedNode = await cloneNode(node, options, true); |
| 909 |
await embedWebFonts(clonedNode, options); |
| 910 |
await embedImages(clonedNode, options); |
| 911 |
applyStyle(clonedNode, options); |
| 912 |
const datauri = await nodeToDataURL(clonedNode, width, height); |
| 913 |
return datauri; |
| 914 |
} |
| 915 |
async function toCanvas(node, options = {}) { |
| 916 |
const { width, height } = getImageSize(node, options); |
| 917 |
const svg = await toSvg(node, options); |
| 918 |
const img = await createImage(svg); |
| 919 |
const canvas = document.createElement("canvas"); |
| 920 |
const context = canvas.getContext("2d"); |
| 921 |
const ratio = options.pixelRatio || getPixelRatio(); |
| 922 |
const canvasWidth = options.canvasWidth || width; |
| 923 |
const canvasHeight = options.canvasHeight || height; |
| 924 |
canvas.width = canvasWidth * ratio; |
| 925 |
canvas.height = canvasHeight * ratio; |
| 926 |
if (!options.skipAutoScale) { |
| 927 |
checkCanvasDimensions(canvas); |
| 928 |
} |
| 929 |
canvas.style.width = `${canvasWidth}`; |
| 930 |
canvas.style.height = `${canvasHeight}`; |
| 931 |
if (options.backgroundColor) { |
| 932 |
context.fillStyle = options.backgroundColor; |
| 933 |
context.fillRect(0, 0, canvas.width, canvas.height); |
| 934 |
} |
| 935 |
context.drawImage(img, 0, 0, canvas.width, canvas.height); |
| 936 |
return canvas; |
| 937 |
} |
| 938 |
async function toPixelData(node, options = {}) { |
| 939 |
const { width, height } = getImageSize(node, options); |
| 940 |
const canvas = await toCanvas(node, options); |
| 941 |
const ctx = canvas.getContext("2d"); |
| 942 |
return ctx.getImageData(0, 0, width, height).data; |
| 943 |
} |
| 944 |
async function toPng(node, options = {}) { |
| 945 |
const canvas = await toCanvas(node, options); |
| 946 |
return canvas.toDataURL(); |
| 947 |
} |
| 948 |
async function toJpeg(node, options = {}) { |
| 949 |
const canvas = await toCanvas(node, options); |
| 950 |
return canvas.toDataURL("image/jpeg", options.quality || 1); |
| 951 |
} |
| 952 |
async function toBlob(node, options = {}) { |
| 953 |
const canvas = await toCanvas(node, options); |
| 954 |
const blob = await canvasToBlob(canvas); |
| 955 |
return blob; |
| 956 |
} |
| 957 |
async function getFontEmbedCSS(node, options = {}) { |
| 958 |
return getWebFontCSS(node, options); |
| 959 |
} |
| 960 |
|
| 961 |
export { getFontEmbedCSS, toBlob, toCanvas, toJpeg, toPixelData, toPng, toSvg }; |