/
FieldEditorInput.vue
364 lines (325 loc) · 10 KB
/
FieldEditorInput.vue
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
<!-- Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/ -->
<script setup lang="ts">
import type { FormFieldContext } from '#shared/components/Form/types/field.ts'
import type { Editor } from '@tiptap/vue-3'
import { useEditor, EditorContent } from '@tiptap/vue-3'
import { useEventListener } from '@vueuse/core'
import { computed, onMounted, onUnmounted, ref, toRef, watch } from 'vue'
import testFlags from '#shared/utils/testFlags.ts'
import { htmlCleanup } from '#shared/utils/htmlCleanup.ts'
import useValue from '../../composables/useValue.ts'
import {
getCustomExtensions,
getHtmlExtensions,
getPlainExtensions,
} from './extensions/list.ts'
import type {
EditorContentType,
EditorCustomPlugins,
FieldEditorContext,
FieldEditorProps,
PossibleSignature,
} from './types.ts'
import FieldEditorActionBar from './FieldEditorActionBar.vue'
import FieldEditorFooter from './FieldEditorFooter.vue'
import { PLUGIN_NAME as userMentionPluginName } from './suggestions/UserMention.ts'
import { getNodeByName } from '../../utils.ts'
import type { FieldFileContext } from '../FieldFile/types.ts'
import { convertInlineImages } from './utils.ts'
interface Props {
context: FormFieldContext<FieldEditorProps>
}
const props = defineProps<Props>()
const reactiveContext = toRef(props, 'context')
const { currentValue } = useValue(reactiveContext)
// TODO: add maybe something to extract the props from the context, instead of using context.XYZ (or props.context.XYZ)
const disabledPlugins = Object.entries(props.context.meta || {})
.filter(([, value]) => value.disabled)
.map(([key]) => key as EditorCustomPlugins)
const contentType = computed<EditorContentType>(
() => props.context.contentType || 'text/html',
)
// remove user mention in plain text mode and inline images
if (contentType.value === 'text/plain') {
disabledPlugins.push(userMentionPluginName, 'image')
}
const editorExtensions =
contentType.value === 'text/plain'
? getPlainExtensions()
: getHtmlExtensions()
getCustomExtensions(reactiveContext).forEach((extension) => {
if (!disabledPlugins.includes(extension.name as EditorCustomPlugins)) {
editorExtensions.push(extension)
}
})
const hasImageExtension = editorExtensions.some(
(extension) => extension.name === 'image',
)
const showActionBar = ref(false)
const editorValue = ref<string>(VITE_TEST_MODE ? props.context._value : '')
interface LoadImagesOptions {
attachNonInlineFiles: boolean
}
// there is also a gif, but desktop only inlines these two for now
const imagesMimeType = ['image/png', 'image/jpeg']
const loadFiles = (
files: FileList | null | undefined,
editor: Editor | undefined,
options: LoadImagesOptions,
) => {
if (!files) {
return false
}
const inlineImages: File[] = []
const otherFiles: File[] = []
for (const file of files) {
if (imagesMimeType.includes(file.type)) {
inlineImages.push(file)
} else {
otherFiles.push(file)
}
}
if (inlineImages.length && editor) {
convertInlineImages(inlineImages, editor.view.dom).then((urls) => {
if (editor?.isDestroyed) return
editor?.commands.setImages(urls)
})
}
if (options.attachNonInlineFiles && otherFiles.length) {
const attachmentsContext = getNodeByName(
props.context.formId,
'attachments',
)?.context as unknown as FieldFileContext | undefined
attachmentsContext?.uploadFiles(otherFiles)
}
return Boolean(
inlineImages.length || (options.attachNonInlineFiles && otherFiles.length),
)
}
const editor = useEditor({
extensions: editorExtensions,
editorProps: {
attributes: {
role: 'textbox',
name: props.context.node.name,
id: props.context.id,
class: 'min-h-[80px]',
'data-value': editorValue.value,
},
// add inlined files
handlePaste(view, event) {
if (!hasImageExtension) {
return
}
const loaded = loadFiles(event.clipboardData?.files, editor.value, {
attachNonInlineFiles: false,
})
if (loaded) {
event.preventDefault()
return true
}
return false
},
handleDrop(view, event) {
if (!hasImageExtension) {
return
}
const e = event as unknown as InputEvent
const files = e.dataTransfer?.files || null
const loaded = loadFiles(files, editor.value, {
attachNonInlineFiles: true,
})
if (loaded) {
event.preventDefault()
return true
}
return false
},
},
editable: props.context.disabled !== true,
content:
currentValue.value && contentType.value === 'text/html'
? htmlCleanup(currentValue.value)
: currentValue.value,
onUpdate({ editor }) {
const content =
contentType.value === 'text/plain' ? editor.getText() : editor.getHTML()
const value = content === '<p></p>' ? '' : content
props.context.node.input(value)
if (!VITE_TEST_MODE) return
editorValue.value = value
},
onFocus() {
showActionBar.value = true
},
onBlur() {
props.context.handlers.blur()
},
})
watch(
() => [props.context.id, editorValue.value],
([id, value]) => {
editor.value?.setOptions({
editorProps: {
attributes: {
role: 'textbox',
name: props.context.node.name,
id,
class: 'min-h-[80px]',
'data-value': value,
},
},
})
},
)
watch(
() => props.context.disabled,
(disabled) => {
editor.value?.setEditable(!disabled, false)
if (disabled && showActionBar.value) {
showActionBar.value = false
}
},
)
// Set the new editor value, when it was changed from outside (e.G. form schema update).
const updateValueKey = props.context.node.on('input', ({ payload: value }) => {
const currentValue =
contentType.value === 'text/plain'
? editor.value?.getText()
: editor.value?.getHTML()
if (editor.value && value !== currentValue) {
editor.value.commands.setContent(
value && contentType.value === 'text/html' ? htmlCleanup(value) : value,
false,
)
}
})
onUnmounted(() => {
props.context.node.off(updateValueKey)
})
const focusEditor = () => {
const view = editor.value?.view
view?.focus()
}
// focus editor when clicked on its label
useEventListener('click', (e) => {
const label = document.querySelector(`label[for="${props.context.id}"]`)
if (label === e.target) focusEditor()
})
// insert signature before full article blockquote or at the end of the document
const resolveSignaturePosition = (editor: Editor) => {
let blockquotePosition: number | null = null
editor.state.doc.descendants((node, pos) => {
if (
(node.type.name === 'paragraph' || node.type.name === 'blockquote') &&
node.attrs['data-marker'] === 'signature-before'
) {
blockquotePosition = pos
return false
}
})
if (blockquotePosition !== null) {
return { position: 'before', from: blockquotePosition }
}
return { position: 'after', from: editor.state.doc.content.size || 0 }
}
const addSignature = (signature: PossibleSignature) => {
if (!editor.value || editor.value.isDestroyed || !editor.value.isEditable)
return
const currentPosition = editor.value.state.selection.anchor
const positionFromEnd = editor.value.state.doc.content.size - currentPosition
// don't use "chain()", because we change positions a lot
// and chain doesn't know about it
editor.value.commands.removeSignature()
const { position, from } = resolveSignaturePosition(editor.value)
editor.value.commands.addSignature({ ...signature, position, from })
const getNewPosition = (editor: Editor) => {
if (signature.position != null) {
return signature.position
}
if (currentPosition < from) {
return currentPosition
}
if (from === 0 && currentPosition <= 1) {
return 1
}
return editor.state.doc.content.size - positionFromEnd
}
// calculate new position from the end of the signature otherwise
editor.value.commands.focus(getNewPosition(editor.value))
requestAnimationFrame(() => {
testFlags.set('editor.signatureAdd')
})
}
const removeSignature = () => {
if (!editor.value || editor.value.isDestroyed || !editor.value.isEditable)
return
const currentPosition = editor.value.state.selection.anchor
editor.value.chain().removeSignature().focus(currentPosition).run()
requestAnimationFrame(() => {
testFlags.set('editor.removeSignature')
})
}
const characters = computed(() => {
if (contentType.value === 'text/plain') {
return currentValue.value?.length || 0
}
if (!editor.value) return 0
return editor.value.storage.characterCount.characters({
node: editor.value.state.doc,
})
})
const editorCustomContext = {
_loaded: true,
getEditorValue: (type: EditorContentType) => {
if (!editor.value) return ''
return type === 'text/plain'
? editor.value.getText()
: editor.value.getHTML()
},
addSignature,
removeSignature,
focus: focusEditor,
}
Object.assign(props.context, editorCustomContext)
onMounted(() => {
const onLoad = props.context.onLoad as ((
context: FieldEditorContext,
) => void)[]
onLoad.forEach((fn) => fn(editorCustomContext))
onLoad.length = 0
if (VITE_TEST_MODE) {
if (!('editors' in globalThis))
Object.defineProperty(globalThis, 'editors', { value: {} })
Object.defineProperty(
Reflect.get(globalThis, 'editors'),
props.context.node.name,
{ value: editor.value, configurable: true },
)
}
})
</script>
<template>
<div class="p-2">
<EditorContent
ref="editorVueInstance"
class="text-base ltr:text-left rtl:text-right"
data-test-id="field-editor"
:editor="editor"
/>
<FieldEditorFooter
v-if="context.meta?.footer && !context.meta.footer.disabled && editor"
:footer="context.meta.footer"
:characters="characters"
/>
</div>
<!-- TODO: questionable usability - it moves, when new line is added -->
<FieldEditorActionBar
:editor="editor"
:content-type="contentType"
:visible="showActionBar"
:disabled-plugins="disabledPlugins"
@hide="showActionBar = false"
@blur="focusEditor"
/>
</template>