-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathMediaHandler.vue
More file actions
205 lines (184 loc) Β· 5.71 KB
/
MediaHandler.vue
File metadata and controls
205 lines (184 loc) Β· 5.71 KB
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
202
203
204
205
<!--
- SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<div class="editor editor-media-handler"
data-text-el="editor-media-handler"
:class="{ draggedOver }"
@image-paste="onPaste"
@dragover.prevent.stop="setDraggedOver(true)"
@dragleave.prevent.stop="setDraggedOver(false)"
@drop.prevent.stop="setDraggedOver(false)"
@file-drop="onEditorDrop">
<input v-show="false"
ref="attachmentFileInput"
data-text-el="attachment-file-input"
type="file"
accept="*/*"
multiple
@change="onAttachmentUploadFilePicked">
<slot />
</div>
</template>
<script>
import { getCurrentUser } from '@nextcloud/auth'
import { showError } from '@nextcloud/dialogs'
import { emit } from '@nextcloud/event-bus'
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)
},
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 attachments failed', { error })
showError(t('text', 'Uploading multiple attachments failed.'))
})
.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 attachment failed', { error })
if (error.response?.data.error) {
showError(t('text', 'Uploading attachment failed: {error}', { error: error.response.data.error }))
} else {
showError(t('text', 'Uploading attachment failed.'))
}
})
.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 from Files', { error })
showError(t('text', 'Failed to insert from Files'))
}).then(() => {
this.state.isUploadingAttachments = false
})
},
insertAttachment(name, fileId, mimeType, position = null, dirname = '') {
const sanitizedName = name.replaceAll('\u202E', '')
// inspired by the fixedEncodeURIComponent function suggested in
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
const src = dirname + '/'
+ encodeURIComponent(sanitizedName).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 = sanitizedName.replaceAll(/[[\]]/g, '')
const chain = position
? this.$editor.chain().focus(position)
: this.$editor.chain()
chain.setImage({ src, alt }).run()
const selection = this.$editor.view.state.selection
if (!selection.empty) {
// If inserted image is first element, it is selected and would get overwritten by
// subsequent editor inserts (see tiptap#3355). So unselect the image by placing
// the cursor at the end of the selection.
this.$editor.commands.focus(selection.to)
}
// Scroll image into view
this.$editor.commands.scrollIntoView()
// Store last inserted attachment src to focus it in ImageView.vue
this.$editor.commands.setMeta('insertedAttachmentSrc', { src })
emit('text:image-node:add', null)
},
},
}
</script>