"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var export_exports = {};
__export(export_exports, {
  downloadDataURLAsFile: () => downloadDataURLAsFile,
  getSvgAsDataUrl: () => getSvgAsDataUrl,
  getSvgAsDataUrlSync: () => getSvgAsDataUrlSync,
  getSvgAsImage: () => getSvgAsImage,
  getSvgAsString: () => getSvgAsString,
  getTextBoundingBox: () => getTextBoundingBox
});
module.exports = __toCommonJS(export_exports);
var import_editor = require("@tldraw/editor");
var import_getBrowserCanvasMaxSize = require("../shapes/shared/getBrowserCanvasMaxSize");
function getSvgAsString(svg) {
  const clone = svg.cloneNode(true);
  svg.setAttribute("width", +svg.getAttribute("width") + "");
  svg.setAttribute("height", +svg.getAttribute("height") + "");
  const out = new XMLSerializer().serializeToString(clone).replaceAll("&#10;      ", "").replaceAll(/((\s|")[0-9]*\.[0-9]{2})([0-9]*)(\b|"|\))/g, "$1");
  return out;
}
async function getSvgAsImage(svg, options) {
  const { type, quality, scale } = options;
  const width = +svg.getAttribute("width");
  const height = +svg.getAttribute("height");
  let scaledWidth = width * scale;
  let scaledHeight = height * scale;
  const dataUrl = await getSvgAsDataUrl(svg);
  const canvasSizes = await (0, import_getBrowserCanvasMaxSize.getBrowserCanvasMaxSize)();
  if (width > canvasSizes.maxWidth) {
    scaledWidth = canvasSizes.maxWidth;
    scaledHeight = scaledWidth / width * height;
  }
  if (height > canvasSizes.maxHeight) {
    scaledHeight = canvasSizes.maxHeight;
    scaledWidth = scaledHeight / height * width;
  }
  if (scaledWidth * scaledHeight > canvasSizes.maxArea) {
    const ratio = Math.sqrt(canvasSizes.maxArea / (scaledWidth * scaledHeight));
    scaledWidth *= ratio;
    scaledHeight *= ratio;
  }
  scaledWidth = Math.floor(scaledWidth);
  scaledHeight = Math.floor(scaledHeight);
  const effectiveScale = scaledWidth / width;
  const canvas = await new Promise((resolve) => {
    const image = new Image();
    image.crossOrigin = "anonymous";
    image.onload = async () => {
      await new Promise((resolve2) => setTimeout(resolve2, 250));
      const canvas2 = document.createElement("canvas");
      const ctx = canvas2.getContext("2d");
      canvas2.width = scaledWidth;
      canvas2.height = scaledHeight;
      ctx.imageSmoothingEnabled = true;
      ctx.imageSmoothingQuality = "high";
      ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight);
      URL.revokeObjectURL(dataUrl);
      resolve(canvas2);
    };
    image.onerror = () => {
      resolve(null);
    };
    image.src = dataUrl;
  });
  if (!canvas)
    return null;
  const blob = await new Promise(
    (resolve) => canvas.toBlob(
      (blob2) => {
        if (!blob2 || import_editor.debugFlags.throwToBlob.value) {
          resolve(null);
        }
        resolve(blob2);
      },
      "image/" + type,
      quality
    )
  );
  if (!blob)
    return null;
  const view = new DataView(await blob.arrayBuffer());
  return import_editor.PngHelpers.setPhysChunk(view, effectiveScale, {
    type: "image/" + type
  });
}
async function getSvgAsDataUrl(svg) {
  const clone = svg.cloneNode(true);
  clone.setAttribute("encoding", 'UTF-8"');
  const fileReader = new FileReader();
  const imgs = Array.from(clone.querySelectorAll("image"));
  for (const img of imgs) {
    const src = img.getAttribute("xlink:href");
    if (src) {
      if (!src.startsWith("data:")) {
        const blob = await (await fetch(src)).blob();
        const base64 = await new Promise((resolve, reject) => {
          fileReader.onload = () => resolve(fileReader.result);
          fileReader.onerror = () => reject(fileReader.error);
          fileReader.readAsDataURL(blob);
        });
        img.setAttribute("xlink:href", base64);
      }
    }
  }
  return getSvgAsDataUrlSync(clone);
}
function getSvgAsDataUrlSync(node) {
  const svgStr = new XMLSerializer().serializeToString(node);
  const base64SVG = window.btoa(unescape(encodeURIComponent(svgStr)));
  return `data:image/svg+xml;base64,${base64SVG}`;
}
function downloadDataURLAsFile(dataUrl, filename) {
  const link = document.createElement("a");
  link.href = dataUrl;
  link.download = filename;
  link.click();
}
function getTextBoundingBox(text) {
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.appendChild(text);
  document.body.appendChild(svg);
  const bbox = text.getBoundingClientRect();
  document.body.removeChild(svg);
  return bbox;
}
//# sourceMappingURL=export.js.map
