summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/components/toolbar_image_button.vue
blob: ebeee16dbec343add9927e5faafa169cb0a661cf (plain)
1
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<script>
import {
  GlDropdown,
  GlDropdownForm,
  GlButton,
  GlFormInputGroup,
  GlDropdownDivider,
  GlDropdownItem,
  GlTooltipDirective as GlTooltip,
} from '@gitlab/ui';
import { Editor as TiptapEditor } from '@tiptap/vue-2';
import { acceptedMimes } from '../extensions/image';
import { getImageAlt } from '../services/utils';

export default {
  components: {
    GlDropdown,
    GlDropdownForm,
    GlFormInputGroup,
    GlDropdownDivider,
    GlDropdownItem,
    GlButton,
  },
  directives: {
    GlTooltip,
  },
  props: {
    tiptapEditor: {
      type: TiptapEditor,
      required: true,
    },
  },
  data() {
    return {
      imgSrc: '',
    };
  },
  methods: {
    resetFields() {
      this.imgSrc = '';
      this.$refs.fileSelector.value = '';
    },
    insertImage() {
      this.tiptapEditor
        .chain()
        .focus()
        .setImage({
          src: this.imgSrc,
          canonicalSrc: this.imgSrc,
          alt: getImageAlt(this.imgSrc),
        })
        .run();

      this.resetFields();
      this.emitExecute();
    },
    emitExecute(source = 'url') {
      this.$emit('execute', { contentType: 'image', value: source });
    },
    openFileUpload() {
      this.$refs.fileSelector.click();
    },
    onFileSelect(e) {
      this.tiptapEditor
        .chain()
        .focus()
        .uploadImage({
          file: e.target.files[0],
        })
        .run();

      this.resetFields();
      this.emitExecute('upload');
    },
  },
  acceptedMimes,
};
</script>
<template>
  <gl-dropdown
    v-gl-tooltip
    :aria-label="__('Insert image')"
    :title="__('Insert image')"
    size="small"
    category="tertiary"
    icon="media"
    @hidden="resetFields()"
  >
    <gl-dropdown-form class="gl-px-3!">
      <gl-form-input-group v-model="imgSrc" :placeholder="__('Image URL')">
        <template #append>
          <gl-button variant="confirm" @click="insertImage">{{ __('Insert') }}</gl-button>
        </template>
      </gl-form-input-group>
    </gl-dropdown-form>
    <gl-dropdown-divider />
    <gl-dropdown-item @click="openFileUpload">
      {{ __('Upload image') }}
    </gl-dropdown-item>

    <input
      ref="fileSelector"
      type="file"
      name="content_editor_image"
      :accept="$options.acceptedMimes"
      class="gl-display-none"
      @change="onFileSelect"
    />
  </gl-dropdown>
</template>