Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MediaHandler.vue « Editor « components « src - github.com/nextcloud/text.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 55d8cd3b79be52bc3af074514b384afeba9d0f98 (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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
<!--
  - @copyright Copyright (c) 2022 Vinicius Reis <vinicius@nextcloud.com>
  -
  - @author Vinicius Reis <vinicius@nextcloud.com>
  -
  - @license AGPL-3.0-or-later
  -
  - This program is free software: you can redistribute it and/or modify
  - it under the terms of the GNU Affero General Public License as
  - published by the Free Software Foundation, either version 3 of the
  - License, or (at your option) any later version.
  -
  - This program is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  - GNU Affero General Public License for more details.
  -
  - You should have received a copy of the GNU Affero General Public License
  - along with this program. If not, see <http://www.gnu.org/licenses/>.
  -
  -->

<template>
	<div class="editor editor-midia-handler"
		data-text-el="editor-midia-handler"
		:class="{ draggedOver }"
		@image-paste="onPaste"
		@dragover.prevent.stop="setDraggedOver(true)"
		@dragleave.prevent.stop="setDraggedOver(false)"
		@file-drop="onEditorDrop">
		<input ref="attachmentFileInput"
			data-text-el="attachment-file-input"
			type="file"
			accept="*/*"
			aria-hidden="true"
			class="hidden-visually"
			multiple
			@change="onAttachmentUploadFilePicked">
		<slot />
	</div>
</template>

<script>
import { getCurrentUser } from '@nextcloud/auth'
import { showError } from '@nextcloud/dialogs'
import { logger } from '../../helpers/logger.js'

import {
	useEditorMixin,
	useFileMixin,
	useSyncServiceMixin,
} from '../Editor.provider.js'

import {
	ACTION_ATTACHMENT_PROMPT,
	ACTION_CHOOSE_LOCAL_ATTACHMENT,
	STATE_UPLOADING,
} from './MediaHandler.provider.js'

const getDir = (val) => val.split('/').slice(0, -1).join('/')

export default {
	name: 'MediaHandler',
	mixins: [useEditorMixin, useFileMixin, useSyncServiceMixin],
	provide() {
		const val = {}

		Object.defineProperties(val, {
			[ACTION_ATTACHMENT_PROMPT]: {
				get: () => this.showAttachmentPrompt,
			},
			[ACTION_CHOOSE_LOCAL_ATTACHMENT]: {
				get: () => this.chooseLocalFile,
			},
			[STATE_UPLOADING]: {
				get: () => this.state,
			},
		})

		return val
	},
	data() {
		return {
			lastFilePath: null,
			draggedOver: false,
			// make it reactive to be used inject/provide
			state: {
				isUploadingAttachments: false,
			},
		}
	},
	computed: {
		initialFilePath() {
			return this.lastFilePath ?? getDir(this.$file.relativePath)
		},
	},
	methods: {
		setDraggedOver(val) {
			this.draggedOver = val
		},
		onPaste(e) {
			this.uploadAttachmentFiles(e.detail.files)
		},
		onEditorDrop(e) {
			this.uploadAttachmentFiles(e.detail.files, e.detail.position)
			this.draggedOver = false
		},
		onAttachmentUploadFilePicked(event) {
			this.uploadAttachmentFiles(event.target.files)
			// Clear input to ensure that the change event will be emitted if
			// the same file is picked again.
			event.target.value = ''
		},
		chooseLocalFile() {
			this.$refs.attachmentFileInput.click()
		},
		async uploadAttachmentFiles(files, position = null) {
			if (!files) {
				return
			}

			this.state.isUploadingAttachments = true

			const uploadPromises = [...files].map((file) => {
				return this.uploadAttachmentFile(file, position)
			})

			return Promise.all(uploadPromises)
				.catch(error => {
					logger.error('Uploading multiple images failed', { error })
					showError(error?.response?.data?.error || error.message)
				})
				.then(() => {
					this.state.isUploadingAttachments = false
				})
		},
		async uploadAttachmentFile(file, position = null) {
			this.state.isUploadingAttachments = true

			return this.$syncService.uploadAttachment(file)
				.then((response) => {
					this.insertAttachment(
						response.data?.name, response.data?.id, file.type,
						position, response.data?.dirname
					)
				})
				.catch((error) => {
					logger.error('Uploading image failed', { error })
					showError(error?.response?.data?.error)
				})
				.then(() => {
					this.state.isUploadingAttachments = false
				})
		},
		showAttachmentPrompt() {
			const currentUser = getCurrentUser()
			if (!currentUser) {
				return
			}

			OC.dialogs.filepicker(t('text', 'Insert an attachment'), (filePath) => {
				this.insertFromPath(filePath)
			}, false, [], true, undefined, this.initialFilePath)
		},
		insertFromPath(filePath) {
			this.lastFilePath = getDir(filePath)

			this.state.isUploadingAttachments = true

			return this.$syncService.insertAttachmentFile(filePath).then((response) => {
				this.insertAttachment(
					response.data?.name, response.data?.id, response.data?.mimetype,
					null, response.data?.dirname
				)
			}).catch((error) => {
				logger.error('Failed to insert image path', { error })
				showError(error?.response?.data?.error || error.message)
			}).then(() => {
				this.state.isUploadingAttachments = false
			})
		},
		insertAttachment(name, fileId, mimeType, position = null, dirname = '') {
			// inspired by the fixedEncodeURIComponent function suggested in
			// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
			const src = dirname + '/'
				+ encodeURIComponent(name).replace(/[!'()*]/g, (c) => {
					return '%' + c.charCodeAt(0).toString(16).toUpperCase()
				})
			// simply get rid of brackets to make sure link text is valid
			// as it does not need to be unique and matching the real file name
			const alt = name.replaceAll(/[[\]]/g, '')

			const chain = position
				? this.$editor.chain().focus(position)
				: this.$editor.chain()

			chain.setImage({ src, alt }).insertContent('<br />').focus().run()
		},
	},
}
</script>