/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

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);

// main.ts
var main_exports = {};
__export(main_exports, {
  default: () => PasteImageIntoProperty
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");
var PasteImageIntoProperty = class extends import_obsidian.Plugin {
  async onload() {
    this.registerDomEvent(document, "paste", (evt) => this.handlePaste(evt), true);
  }
  handlePaste(evt) {
    var _a;
    const activeEl = document.activeElement;
    if (!evt.clipboardData || evt.clipboardData.types[0] != "Files")
      return false;
    const isFrontmatterFieldSupported = this.isSupportedFrontmatterField(activeEl);
    if (isFrontmatterFieldSupported)
      this.handleImagePaste(evt, activeEl);
    else if (this.isFrontmatterField(activeEl.parentElement) || this.isFrontmatterField((_a = activeEl.parentElement) == null ? void 0 : _a.parentElement))
      new import_obsidian.Notice(`Pasting images is only supported in property type "Text"!`);
  }
  isFrontmatterField(element) {
    if (!element)
      return false;
    return element.matches(".metadata-property-value");
  }
  isSupportedFrontmatterField(element) {
    if (!element)
      return false;
    return element.matches(".metadata-input-longtext");
  }
  async handleImagePaste(evt, target) {
    const items = evt.clipboardData.items;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.kind === "file" && item.type.startsWith("image/")) {
        const file = item.getAsFile();
        if (file) {
          await this.saveImageAndWriteLink(file, target);
          evt.preventDefault();
          break;
        }
      }
    }
  }
  async saveImageAndWriteLink(file, target) {
    var _a;
    const arrayBuffer = await file.arrayBuffer();
    const fileExtension = file.type.split("/")[1] || "png";
    const fileName = `Pasted image ${Date.now()}.${fileExtension}`;
    const activeFile = this.app.workspace.getActiveFile();
    if (!activeFile) {
      new import_obsidian.Notice(`No active file!`);
      return;
    }
    const savePath = await this.app.fileManager.getAvailablePathForAttachment(fileName, activeFile.path);
    const activeEl = document.activeElement;
    const propertyName = (_a = activeEl.closest(".metadata-property")) == null ? void 0 : _a.getAttribute("data-property-key");
    const newFile = await this.app.vault.createBinary(savePath, arrayBuffer);
    const linkName = savePath.split("/").last();
    await this.writeLinkIntoFrontmatter(activeFile, `[[${linkName}]]`, activeEl, propertyName, newFile);
  }
  async writeLinkIntoFrontmatter(activeFile, filePath, activeEl, propertyName, newFile) {
    if (document.activeElement == activeEl)
      activeEl.blur();
    await new Promise((resolve) => setTimeout(resolve, 50));
    try {
      if (!propertyName)
        throw new Error("data-property-key attribute not found on the expected element.");
      await this.app.fileManager.processFrontMatter(activeFile, (frontmatter) => {
        frontmatter[propertyName] = filePath;
      });
      new import_obsidian.Notice(`Image added to frontmatter: ${filePath}`);
    } catch (error) {
      await this.app.vault.delete(newFile);
      new import_obsidian.Notice(`Failed to update frontmatter!
${error}`);
      console.error("Error updating frontmatter:", error);
    }
  }
};


/* nosourcemap */