image.js 4.42 KB
Newer Older
1
import { Image } from '@tiptap/extension-image';
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import { VueNodeViewRenderer } from '@tiptap/vue-2';
import { Plugin, PluginKey } from 'prosemirror-state';
import { __ } from '~/locale';
import ImageWrapper from '../components/wrappers/image.vue';
import { uploadFile } from '../services/upload_file';
import { getImageAlt, readFileAsDataURL } from '../services/utils';

export const acceptedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];

const resolveImageEl = (element) =>
  element.nodeName === 'IMG' ? element : element.querySelector('img');

const startFileUpload = async ({ editor, file, uploadsPath, renderMarkdown }) => {
  const encodedSrc = await readFileAsDataURL(file);
  const { view } = editor;

  editor.commands.setImage({ uploading: true, src: encodedSrc });

  const { state } = view;
  const position = state.selection.from - 1;
  const { tr } = state;

  try {
    const { src, canonicalSrc } = await uploadFile({ file, uploadsPath, renderMarkdown });

    view.dispatch(
      tr.setNodeMarkup(position, undefined, {
        uploading: false,
        src: encodedSrc,
        alt: getImageAlt(src),
        canonicalSrc,
      }),
    );
  } catch (e) {
    editor.commands.deleteRange({ from: position, to: position + 1 });
    editor.emit('error', __('An error occurred while uploading the image. Please try again.'));
  }
};

const handleFileEvent = ({ editor, file, uploadsPath, renderMarkdown }) => {
  if (acceptedMimes.includes(file?.type)) {
    startFileUpload({ editor, file, uploadsPath, renderMarkdown });

    return true;
  }

  return false;
};
50 51

const ExtendedImage = Image.extend({
52 53 54 55 56
  defaultOptions: {
    ...Image.options,
    uploadsPath: null,
    renderMarkdown: null,
  },
57 58 59
  addAttributes() {
    return {
      ...this.parent?.(),
60 61 62
      uploading: {
        default: false,
      },
63 64 65 66
      src: {
        default: null,
        /*
         * GitLab Flavored Markdown provides lazy loading for rendering images. As
67
         * as result, the src attribute of the image may contain an embedded resource
68 69 70 71
         * instead of the actual image URL. The image URL is moved to the data-src
         * attribute.
         */
        parseHTML: (element) => {
72
          const img = resolveImageEl(element);
73 74 75 76 77 78

          return {
            src: img.dataset.src || img.getAttribute('src'),
          };
        },
      },
79 80 81 82 83 84 85 86
      canonicalSrc: {
        default: null,
        parseHTML: (element) => {
          return {
            canonicalSrc: element.dataset.canonicalSrc,
          };
        },
      },
87 88 89
      alt: {
        default: null,
        parseHTML: (element) => {
90
          const img = resolveImageEl(element);
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

          return {
            alt: img.getAttribute('alt'),
          };
        },
      },
    };
  },
  parseHTML() {
    return [
      {
        priority: 100,
        tag: 'a.no-attachment-icon',
      },
      {
        tag: 'img[src]',
      },
    ];
  },
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  addCommands() {
    return {
      ...this.parent(),
      uploadImage: ({ file }) => () => {
        const { uploadsPath, renderMarkdown } = this.options;

        handleFileEvent({ file, uploadsPath, renderMarkdown, editor: this.editor });
      },
    };
  },
  addProseMirrorPlugins() {
    const { editor } = this;

    return [
      new Plugin({
        key: new PluginKey('handleDropAndPasteImages'),
        props: {
          handlePaste: (_, event) => {
            const { uploadsPath, renderMarkdown } = this.options;

            return handleFileEvent({
              editor,
              file: event.clipboardData.files[0],
              uploadsPath,
              renderMarkdown,
            });
          },
          handleDrop: (_, event) => {
            const { uploadsPath, renderMarkdown } = this.options;

            return handleFileEvent({
              editor,
              file: event.dataTransfer.files[0],
              uploadsPath,
              renderMarkdown,
            });
          },
        },
      }),
    ];
  },
  addNodeView() {
    return VueNodeViewRenderer(ImageWrapper);
  },
154
});
155

156 157 158 159 160 161
const serializer = (state, node) => {
  const { alt, canonicalSrc, src, title } = node.attrs;
  const quotedTitle = title ? ` ${state.quote(title)}` : '';

  state.write(`![${state.esc(alt || '')}](${state.esc(canonicalSrc || src)}${quotedTitle})`);
};
162 163 164 165 166 167 168

export const configure = ({ renderMarkdown, uploadsPath }) => {
  return {
    tiptapExtension: ExtendedImage.configure({ inline: true, renderMarkdown, uploadsPath }),
    serializer,
  };
};