raster.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * Render a live DOM element to a PNG without network access: the element is cloned with its
  3. * ancestors' class context, canvases and images are inlined as data: URLs, and the result is drawn
  4. * through an SVG <foreignObject>. Used by the capture_view page tool.
  5. */
  6. const imageCache = new Map<string, Promise<string | null>>();
  7. function loadImage(src: string): Promise<HTMLImageElement> {
  8. return new Promise((resolve, reject) => {
  9. const image = new Image();
  10. image.onload = () => resolve(image);
  11. image.onerror = () => reject(new Error("image failed to load"));
  12. image.src = src;
  13. });
  14. }
  15. /** Turn a blob:/same-origin image URL into a data: URL by drawing it on a canvas. */
  16. function inlineImage(src: string): Promise<string | null> {
  17. if (src.startsWith("data:")) return Promise.resolve(src);
  18. let cached = imageCache.get(src);
  19. if (!cached) {
  20. cached = loadImage(src)
  21. .then((image) => {
  22. const canvas = document.createElement("canvas");
  23. canvas.width = image.naturalWidth || 1;
  24. canvas.height = image.naturalHeight || 1;
  25. canvas.getContext("2d")!.drawImage(image, 0, 0);
  26. return canvas.toDataURL("image/png");
  27. })
  28. .catch(() => null);
  29. imageCache.set(src, cached);
  30. }
  31. return cached;
  32. }
  33. function cssText(): string {
  34. const parts: string[] = [];
  35. for (const sheet of Array.from(document.styleSheets)) {
  36. try {
  37. for (const rule of Array.from(sheet.cssRules)) parts.push(rule.cssText);
  38. } catch {
  39. // Cross-origin sheets cannot be read; there are none in the sandbox.
  40. }
  41. }
  42. return parts.join("\n");
  43. }
  44. const URL_IN_CSS = /url\((['"]?)(blob:[^'")]+)\1\)/g;
  45. async function inlineTree(original: Element, clone: Element) {
  46. const jobs: Promise<void>[] = [];
  47. const walk = (source: Element, target: Element) => {
  48. if (source instanceof HTMLCanvasElement) {
  49. try {
  50. const image = document.createElement("img");
  51. image.src = source.toDataURL("image/png");
  52. image.setAttribute(
  53. "style",
  54. (source.getAttribute("style") ?? "") +
  55. `;width:${source.offsetWidth}px;height:${source.offsetHeight}px`,
  56. );
  57. image.className = source.className;
  58. target.replaceWith(image);
  59. } catch {
  60. // A tainted or WebGL canvas without a preserved buffer: leave it blank.
  61. }
  62. return;
  63. }
  64. if (source instanceof HTMLImageElement && target instanceof HTMLImageElement) {
  65. const src = source.currentSrc || source.src;
  66. jobs.push(
  67. inlineImage(src).then((data) => {
  68. if (data) target.src = data;
  69. target.removeAttribute("srcset");
  70. }),
  71. );
  72. }
  73. if (source instanceof SVGImageElement) {
  74. const href = source.href.baseVal;
  75. jobs.push(
  76. inlineImage(href).then((data) => {
  77. if (data) {
  78. target.setAttribute("href", data);
  79. target.removeAttributeNS("http://www.w3.org/1999/xlink", "href");
  80. }
  81. }),
  82. );
  83. }
  84. const style = target.getAttribute("style");
  85. if (style?.includes("blob:")) {
  86. const urls = [...style.matchAll(URL_IN_CSS)].map((match) => match[2]);
  87. jobs.push(
  88. Promise.all(urls.map(inlineImage)).then((data) => {
  89. let next = style;
  90. urls.forEach((url, i) => {
  91. next = next.split(url).join(data[i] ?? "");
  92. });
  93. target.setAttribute("style", next);
  94. }),
  95. );
  96. }
  97. const sourceChildren = source.children;
  98. const targetChildren = Array.from(target.children);
  99. for (let i = 0; i < sourceChildren.length && i < targetChildren.length; i++)
  100. walk(sourceChildren[i], targetChildren[i]);
  101. };
  102. walk(original, clone);
  103. await Promise.all(jobs);
  104. }
  105. /** Recreate the ancestor chain (tags and classes only) so scoped selectors still match. */
  106. function wrapInAncestors(element: Element, clone: Element, stopAt: Element | null): Element {
  107. let inner: Element = clone;
  108. for (
  109. let node = element.parentElement;
  110. node && node !== stopAt?.parentElement && node !== document.body;
  111. node = node.parentElement
  112. ) {
  113. const shell = document.createElement(
  114. node.tagName.toLowerCase() === "body" ? "div" : node.tagName.toLowerCase(),
  115. );
  116. if (node.className && typeof node.className === "string") shell.className = node.className;
  117. for (const name of node.getAttributeNames())
  118. if (name.startsWith("data-")) shell.setAttribute(name, node.getAttribute(name)!);
  119. shell.setAttribute(
  120. "style",
  121. "display:block;margin:0;padding:0;border:0;background:none;width:auto;height:auto;transform:none;overflow:visible;position:static",
  122. );
  123. shell.append(inner);
  124. inner = shell;
  125. }
  126. return inner;
  127. }
  128. export interface Raster {
  129. data: string;
  130. width: number;
  131. height: number;
  132. }
  133. export async function rasterize(
  134. element: HTMLElement,
  135. options: { maxWidth: number; context?: Element | null; background?: string },
  136. ): Promise<Raster> {
  137. const width = Math.max(1, element.offsetWidth);
  138. const height = Math.max(1, element.offsetHeight);
  139. const clone = element.cloneNode(true) as HTMLElement;
  140. clone.style.transform = "none";
  141. clone.style.margin = "0";
  142. await inlineTree(element, clone);
  143. const computed = getComputedStyle(element);
  144. const root = document.createElement("div");
  145. root.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
  146. root.setAttribute(
  147. "style",
  148. `width:${width}px;height:${height}px;overflow:hidden;font-family:${computed.fontFamily};color:${computed.color};background:${options.background ?? "#fff"}`,
  149. );
  150. const style = document.createElement("style");
  151. style.textContent = cssText();
  152. root.append(style, wrapInAncestors(element, clone, options.context ?? null));
  153. const markup = new XMLSerializer().serializeToString(root);
  154. const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject x="0" y="0" width="100%" height="100%">${markup}</foreignObject></svg>`;
  155. const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`);
  156. const scale = Math.min(2, options.maxWidth / width);
  157. const canvas = document.createElement("canvas");
  158. canvas.width = Math.max(1, Math.round(width * scale));
  159. canvas.height = Math.max(1, Math.round(height * scale));
  160. const context = canvas.getContext("2d")!;
  161. context.fillStyle = options.background ?? "#fff";
  162. context.fillRect(0, 0, canvas.width, canvas.height);
  163. context.drawImage(image, 0, 0, canvas.width, canvas.height);
  164. return {
  165. data: canvas.toDataURL("image/png").split(",")[1],
  166. width: canvas.width,
  167. height: canvas.height,
  168. };
  169. }
  170. /** Scale a canvas down to `maxWidth` and encode it. */
  171. export function canvasToPng(source: HTMLCanvasElement, maxWidth: number): Raster {
  172. const scale = Math.min(1, maxWidth / source.width);
  173. const canvas = document.createElement("canvas");
  174. canvas.width = Math.max(1, Math.round(source.width * scale));
  175. canvas.height = Math.max(1, Math.round(source.height * scale));
  176. canvas.getContext("2d")!.drawImage(source, 0, 0, canvas.width, canvas.height);
  177. return {
  178. data: canvas.toDataURL("image/png").split(",")[1],
  179. width: canvas.width,
  180. height: canvas.height,
  181. };
  182. }