"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 useCopyAs_exports = {};
__export(useCopyAs_exports, {
  useCopyAs: () => useCopyAs
});
module.exports = __toCommonJS(useCopyAs_exports);
var import_editor = require("@tldraw/editor");
var import_react = require("react");
var import_export = require("../../utils/export");
var import_useToastsProvider = require("./useToastsProvider");
var import_useTranslation = require("./useTranslation/useTranslation");
function useCopyAs() {
  const editor = (0, import_editor.useEditor)();
  const { addToast } = (0, import_useToastsProvider.useToasts)();
  const msg = (0, import_useTranslation.useTranslation)();
  return (0, import_react.useCallback)(
    // it's important that this function itself isn't async - we need to
    // create the relevant `ClipboardItem`s synchronously to make sure
    // safari knows that the user _wants_ to copy:
    // https://bugs.webkit.org/show_bug.cgi?id=222262
    //
    // this is fine for navigator.clipboard.write, but for fallbacks it's a
    // little awkward.
    function copyAs(ids = editor.selectedShapeIds, format = "svg") {
      if (ids.length === 0) {
        ids = [...editor.currentPageShapeIds];
      }
      if (ids.length === 0) {
        return;
      }
      switch (format) {
        case "svg": {
          if (window.navigator.clipboard) {
            if (window.navigator.clipboard.write) {
              window.navigator.clipboard.write([
                new ClipboardItem({
                  "text/plain": getExportedSvgBlob(editor, ids)
                })
              ]);
            } else {
              fallbackWriteTextAsync(
                async () => (0, import_export.getSvgAsString)(await getExportSvgElement(editor, ids))
              );
            }
          }
          break;
        }
        case "jpeg":
        case "png": {
          const mimeType = format === "jpeg" ? "image/jpeg" : "image/png";
          const blobPromise = getExportedImageBlob(editor, ids, format).then((blob) => {
            if (blob) {
              if (window.navigator.clipboard) {
                return blob;
              }
              throw new Error("Copy not supported");
            } else {
              addToast({
                id: "copy-fail",
                icon: "warning-triangle",
                title: msg("toast.error.copy-fail.title"),
                description: msg("toast.error.copy-fail.desc")
              });
              throw new Error("Copy not possible");
            }
          });
          window.navigator.clipboard.write([
            new ClipboardItem({
              // Note: This needs to use the promise based approach for safari/ios to not bail on a permissions error.
              [mimeType]: blobPromise
            })
          ]).catch((err) => {
            if (!err.toString().match(/^TypeError: DOMString not supported/)) {
              console.error(err);
            }
            blobPromise.then((blob) => {
              window.navigator.clipboard.write([
                new ClipboardItem({
                  // Note: This needs to use the promise based approach for safari/ios to not bail on a permissions error.
                  [mimeType]: blob
                })
              ]);
            });
          });
          break;
        }
        case "json": {
          const data = editor.getContentFromCurrentPage(ids);
          if (window.navigator.clipboard) {
            const jsonStr = JSON.stringify(data);
            if (window.navigator.clipboard.write) {
              window.navigator.clipboard.write([
                new ClipboardItem({
                  "text/plain": new Blob([jsonStr], { type: "text/plain" })
                })
              ]);
            } else {
              fallbackWriteTextAsync(async () => jsonStr);
            }
          }
          break;
        }
        default:
          throw new Error(`Copy type ${format} not supported.`);
      }
    },
    [editor, addToast, msg]
  );
}
async function getExportSvgElement(editor, ids) {
  const svg = await editor.getSvg(ids, {
    scale: 1,
    background: editor.instanceState.exportBackground
  });
  if (!svg)
    throw new Error("Could not construct SVG.");
  return svg;
}
async function getExportedSvgBlob(editor, ids) {
  return new Blob([(0, import_export.getSvgAsString)(await getExportSvgElement(editor, ids))], {
    type: "text/plain"
  });
}
async function getExportedImageBlob(editor, ids, format) {
  return await (0, import_export.getSvgAsImage)(await getExportSvgElement(editor, ids), {
    type: format,
    quality: 1,
    scale: 2
  });
}
async function fallbackWriteTextAsync(getText) {
  if (!(navigator && navigator.clipboard))
    return;
  navigator.clipboard.writeText(await getText());
}
//# sourceMappingURL=useCopyAs.js.map
