import { TIPTAP_FIGURE_TYPE, TIPTAP_IMAGE_TYPE } from "./../../ricos-content/index.js";
import { findParentNodeClosestToPos } from "./../../tiptap/index.js";
import { createRicosNodeExtension } from "./../../plugin-commons/index.js";
import { handleImageUpload } from "./../handle-image-upload.js";
import { Image } from "./image.js";
const imageTiptapExtension = createRicosNodeExtension({
  type: "react-node",
  name: TIPTAP_IMAGE_TYPE,
  groups: [
    "not-overtypable",
    "spoilerable",
    {
      group: "resizable",
      options: {
        verticallyResizable: true,
        lockAspectRatio: true,
        expandToFullWidthOnOverdrag: true
      }
    },
    "custom-styles",
    "shortcuts-enabled"
  ],
  reconfigure: (config, _extensions, _props, settings, services) => ({
    ...config,
    addOptions: () => ({
      services,
      ...settings
    })
  }),
  Component: Image,
  createExtensionConfig({ Plugin, PluginKey }) {
    const settings = this.settings;
    return {
      name: this.name,
      /*
       * Priority should be higher than ricos-common-plugin list-item extension in order
       * to shortcuts to work
       */
      priority: 102,
      group: "block figureFirstChildContent",
      selectable: true,
      draggable: true,
      addAttributes: () => {
        return {
          image: null,
          link: null,
          disableExpand: { default: settings?.disableExpand ?? null },
          altText: null,
          disableDownload: { default: settings?.disableDownload ?? null },
          containerData: null,
          decorative: null,
          loading: {
            default: false
          },
          error: null,
          loadingPercentage: {
            default: null
          },
          tempData: {
            default: null
          },
          styles: null
        };
      },
      addProseMirrorPlugins() {
        return [
          new Plugin({
            key: new PluginKey("handlePasteImage"),
            props: {
              handlePaste: (_editor, event) => {
                if (event?.clipboardData?.types.includes("text/plain")) {
                  return false;
                }
                const publicCommands = this.options.services.plugins.getPublicCommands();
                const files = Array.from(event?.clipboardData?.files || []).filter(
                  (file) => file.type.startsWith("image")
                );
                handleImageUpload({
                  services: this.options.services,
                  config: this.options,
                  publicCommands,
                  files
                });
                if (files.length > 0) {
                  event.preventDefault();
                  return true;
                }
                return false;
              },
              handleDrop: (view, event, _slice, moved) => {
                if (moved) {
                  return false;
                }
                const files = Array.from(event?.dataTransfer?.files || []).filter(
                  (file) => file.type.startsWith("image")
                );
                if (files.length === 0) {
                  return false;
                }
                const coordinates = view.posAtCoords({
                  left: event.clientX,
                  top: event.clientY
                });
                if (!coordinates) {
                  return false;
                }
                const publicCommands = this.options.services.plugins.getPublicCommands();
                handleImageUpload({
                  services: this.options.services,
                  config: this.options,
                  publicCommands,
                  files,
                  pos: coordinates.pos
                });
                event.preventDefault();
                return true;
              }
            }
          })
        ];
      },
      addCommands() {
        return {
          setImageUrl: (url) => ({ commands }) => {
            return commands.updateAttributes(this.name, { image: { src: { custom: url } } });
          },
          setImageLoading: (loading) => ({ commands }) => {
            return commands.updateAttributes(this.name, { loading });
          },
          insertImageFromFile: (file, insertPosition, publicCommands) => ({ tr }) => {
            let position;
            const from = tr.selection.from;
            const to = tr.selection.to;
            const blockRange = tr.selection.$from.blockRange(tr.selection.$to);
            if (insertPosition === "above") {
              const depth = tr.selection.$from.depth;
              const adjustedPos = blockRange?.start ?? tr.doc.resolve(from).start(depth);
              position = Math.max(adjustedPos, 0);
            } else {
              const depth = tr.selection.$to.depth;
              const pos = blockRange?.end ?? tr.doc.resolve(to).end(depth);
              position = pos + (blockRange ? 0 : 1);
            }
            handleImageUpload({
              services: this.options.services,
              config: this.options,
              publicCommands,
              files: [file],
              pos: position
            });
            return true;
          }
        };
      },
      addKeyboardShortcuts() {
        const newLine = ({ editor }) => {
          const imageFigure = getImageFigure(editor);
          if (!imageFigure) {
            return false;
          }
          editor.chain().setTextSelection(imageFigure.start + imageFigure.node.nodeSize - 1).createParagraphNear().focus().run();
          return true;
        };
        const tiptapKeyboardShortcuts = {
          Enter: newLine
        };
        const newLineShortcuts = [];
        this.options.services.shortcuts.shortcuts.forEach((shortcut) => {
          if (shortcut.shortcut.name === "NewLine") {
            newLineShortcuts.push(shortcut);
          }
        });
        newLineShortcuts.forEach((newLineShortcut) => {
          const modifier = newLineShortcut.keys.macOs.modifiers[0];
          const key = newLineShortcut.keys.macOs.key;
          const shortcutKey = modifier ? `${modifier}-${key}` : key;
          tiptapKeyboardShortcuts[shortcutKey] = newLine;
        });
        return tiptapKeyboardShortcuts;
      }
    };
  }
});
const getImageFigure = (editor) => findParentNodeClosestToPos(
  editor.state.selection.$from,
  (node) => node.type.name === TIPTAP_FIGURE_TYPE
);
export {
  imageTiptapExtension
};
//# sourceMappingURL=image-tiptap-extension.js.map
