'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
var Compressor = require('compressorjs');
var BytemdVueNext = require('@bytemd/vue-next');
var gfm = require('@bytemd/plugin-gfm');
var gemoji = require('@bytemd/plugin-gemoji');
var highlight = require('@bytemd/plugin-highlight');
var frontmatter = require('@bytemd/plugin-frontmatter');
var mediumZoom = require('@bytemd/plugin-medium-zoom');
var breaks = require('@bytemd/plugin-breaks');
var mermaid = require('@bytemd/plugin-mermaid');
var math = require('@bytemd/plugin-math');
var zh_Hans = require('../../../../node_modules/.pnpm/bytemd@1.22.0/node_modules/bytemd/locales/zh_Hans.json.js');
var gfmZhHans = require('@bytemd/plugin-gfm/locales/zh_Hans.json');
require('../../../utils/index.js');
require('./config/index.js');
var createNamespace = require('../../../utils/create-namespace.js');
var markdownEditor = require('./config/markdown-editor.js');

"use strict";
var _sfc_main = /* @__PURE__ */ vue.defineComponent({
  ...{ name: "LlMarkdownEditor" },
  __name: "markdown-editor",
  props: markdownEditor.llMarkdownEditorProps,
  emits: markdownEditor.llMarkdownEditorEmits,
  setup(__props, { emit: __emit }) {
    const pluginsList = [
      gfm({ locale: gfmZhHans }),
      gemoji(),
      highlight(),
      frontmatter(),
      mediumZoom(),
      breaks(),
      mermaid(),
      math()
    ];
    const props = __props;
    const emits = __emit;
    const bem = createNamespace.createNamespace("markdown-editor");
    const components = [BytemdVueNext.Editor];
    const markDownRef = vue.ref();
    const innerValue = vue.ref(props.value);
    const plugins = vue.markRaw(pluginsList);
    const zh = vue.ref(zh_Hans.default);
    const attrs = vue.useAttrs();
    vue.watch(
      () => props.value,
      (n) => {
        innerValue.value = n;
      }
    );
    const handleChange = async (val) => {
      emits("update:value", val);
      emits("change", val);
    };
    const compressImage = (file) => {
      return new Promise((resolve, reject) => {
        new Compressor(file, {
          quality: 0.6,
          // 设置压缩质量
          maxWidth: 400,
          // 设置图片最大宽度
          maxHeight: 400,
          // 设置图片最大高度
          ...props.imageQuality,
          success(result) {
            resolve(result);
          },
          error(error) {
            reject(error);
          }
        });
      });
    };
    const handleUploadImages = async (files) => {
      try {
        const compressImages = [];
        if (props.compress) {
          await Promise.all(
            files.map(async (file) => {
              const compressedFile = await compressImage(file);
              compressImages.push(compressedFile);
            })
          );
        }
        const showImages = await props.uploadImage(
          props.compress ? compressImages : files
        );
        return showImages.map((e, i) => ({
          title: files[i].name,
          url: e
        }));
      } catch (error) {
        console.error("\u538B\u7F29\u548C\u4E0A\u4F20\u56FE\u50CF\u65F6\u51FA\u9519:", error);
      }
    };
    const sanitize = (schema) => {
      const config = JSON.parse(JSON.stringify(schema));
      if (config.protocols && config.protocols.src) {
        if (!config.protocols.src.includes("data")) {
          config.protocols.src.push("data");
        }
      }
      if (config.attributes && config.attributes.img) {
        const imgAttributes = config.attributes.img;
        if (!imgAttributes.includes("src")) {
          imgAttributes.push("src");
        }
        if (!imgAttributes.includes("alt")) {
          imgAttributes.push("alt");
        }
        if (!imgAttributes.includes("title")) {
          imgAttributes.push("title");
        }
      }
      if (config.attributes && config.attributes["*"]) {
        const globalAttributes = config.attributes["*"];
        const neededAttributes = ["width", "height"];
        neededAttributes.forEach((attr) => {
          if (!globalAttributes.includes(attr)) {
            globalAttributes.push(attr);
          }
        });
      }
      config.customFilters = {
        // 对 img 标签的 src 属性进行额外验证
        img: (element) => {
          const src = element.getAttribute("src");
          if (src && src.startsWith("data:")) {
            const allowedImageTypes = [
              "image/jpeg",
              "image/jpg",
              "image/png",
              "image/gif",
              "image/webp",
              "image/svg+xml"
            ];
            const isSafeImageType = allowedImageTypes.some(
              (type) => src.startsWith(`data:${type}`)
            );
            if (!isSafeImageType) {
              element.removeAttribute("src");
            }
            const base64Match = src.match(/data:[^,]+,(.+)/);
            if (base64Match && base64Match[1]) {
              const base64Data = base64Match[1];
              if (base64Data.length > 1.5 * 1024 * 1024) {
                element.removeAttribute("src");
              }
            }
          }
          return element;
        }
      };
      return config;
    };
    return (_ctx, _cache) => {
      return vue.openBlock(), vue.createElementBlock(
        "div",
        {
          class: vue.normalizeClass(vue.unref(bem).b())
        },
        [
          (vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent(components[0]), vue.mergeProps({
            ref_key: "markDownRef",
            ref: markDownRef,
            class: vue.unref(bem).e("container")
          }, vue.unref(attrs), {
            locale: zh.value,
            value: innerValue.value,
            plugins: vue.unref(plugins),
            "upload-images": handleUploadImages,
            sanitize: vue.unref(attrs).sanitize || sanitize,
            mode: _ctx.mode,
            onChange: handleChange
          }), null, 16, ["class", "locale", "value", "plugins", "sanitize", "mode"]))
        ],
        2
        /* CLASS */
      );
    };
  }
});

exports.default = _sfc_main;
//# sourceMappingURL=markdown-editor.vue2.js.map
