-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathNcRichContenteditable.vue
More file actions
1289 lines (1162 loc) · 34 KB
/
NcRichContenteditable.vue
File metadata and controls
1289 lines (1162 loc) · 34 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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
- SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<docs>
### General description
This component displays contenteditable div with automated `@` [at] autocompletion and `:` [colon] emoji autocompletion.
### Examples
Try mentioning user @Test01 or inserting emoji :smile
```vue
<template>
<div>
<NcRichContenteditable
label="Write a comment"
v-model="message"
:disabled="disabled"
:auto-complete="autoComplete"
:maxlength="100"
:user-data="userData"
@submit="onSubmit" />
<br>
<NcRichContenteditable
v-model="message"
:disabled="!disabled"
:auto-complete="autoComplete"
:maxlength="400"
:multiline="true"
:user-data="userData"
@submit="onSubmit" />
<NcCheckboxRadioSwitch v-model="disabled" type="switch">Toggle disabled state</NcCheckboxRadioSwitch>
<h5>Output - raw</h5>
{{ JSON.stringify(message) }}
<h5>Output - preformatted</h5>
<p class="pre-line">{{ message }}</p>
<h5>Output - in NcRichText with markdown support</h5>
<NcRichText :text="text" :arguments="userMentions" autolink use-markdown />
</div>
</template>
<script>
export default {
data() {
return {
disabled: false,
message: '**Lorem ipsum** dolor sit amet.',
// You need to provide this for the inline mention to understand what to display or not.
// Key should be a string with leading '@', like @Test02 or @"Test Offline"
userData: {
Test01: {
icon: 'icon-user',
id: 'Test01',
label: 'Test01',
source: 'users',
primary: true,
},
Test02: {
icon: 'icon-user',
id: 'Test02',
label: 'Test02',
source: 'users',
status: {
clearAt: null,
icon: '🎡',
message: 'Visiting London',
status: 'away',
},
subline: 'Visiting London',
},
'Test@User': {
icon: 'icon-user',
id: 'Test@User',
label: 'Test 03',
source: 'users',
status: {
clearAt: null,
icon: '🎡',
message: 'Having space in my name',
status: 'online',
},
subline: 'Visiting London',
},
'Test Offline': {
icon: 'icon-user',
id: 'Test Offline',
label: 'Test Offline',
source: 'users',
status: {
clearAt: null,
icon: null,
message: null,
status: 'offline',
},
subline: null,
},
'Test DND': {
icon: 'icon-user',
id: 'Test DND',
label: 'Test DND',
source: 'users',
status: {
clearAt: null,
icon: null,
message: 'Out sick',
status: 'dnd',
},
subline: 'Out sick',
},
},
// To display user bubbles in NcRichText, special format of data should be provided:
// Key should be in curly brackets without '@' and ' ' symbols, like {user-2}
userMentions: {
'user-1': {
component: 'NcUserBubble',
props: {
displayName: 'Test01',
user: 'Test01',
primary: true,
},
},
'user-2': {
component: 'NcUserBubble',
props: {
displayName: 'Test02',
user: 'Test02',
},
},
'user-3': {
component: 'NcUserBubble',
props: {
displayName: 'Test 03',
user: 'Test@User',
},
},
'user-4': {
component: 'NcUserBubble',
props: {
displayName: 'Test Offline',
user: 'Test Offline',
},
},
'user-5': {
component: 'NcUserBubble',
props: {
displayName: 'Test DND',
user: 'Test DND',
},
},
}
}
},
computed: {
text() {
return this.message
.replace('@Test01', '{user-1}')
.replace('@Test02', '{user-2}')
.replace('@Test@User', '{user-3}')
.replace('@"Test Offline"', '{user-4}')
.replace('@"Test DND"', '{user-5}')
},
},
methods: {
/**
* Do your own query to the autocompletion api.
* The returned data bellow is a fake data example.
* The callback expects the same format returned by the core/autocomplete/get ocs api endpoint!
* @see userData example above
*
* @param {string} search the query
* @param {Function} callback the callback to process the results with
*/
autoComplete(search, callback) {
callback(Object.values(this.userData))
},
onSubmit() {
alert(this.message)
}
}
}
</script>
<style lang="scss" scoped>
h5 {
font-weight: bold;
margin: 40px 0 20px;
}
.pre-line {
white-space: pre-line;
}
</style>
```
### Using public methods
```vue
<template>
<div>
<div class="buttons-wrapper">
<NcButton class="show-slash-button" @click="showSlashCommands">Slash commands</NcButton>
<NcButton class="focus-button" @click="focus">Focus on input</NcButton>
</div>
<NcRichContenteditable
ref="contenteditable"
label="Write a comment"
v-model="message"
:maxlength="100"/>
</div>
</template>
<script>
export default {
data() {
return {
message: '**Lorem ipsum** dolor sit amet. ',
}
},
methods: {
showSlashCommands() {
this.$refs.contenteditable.showTribute('/')
},
focus() {
this.$refs.contenteditable.focus()
},
},
}
</script>
<style lang="scss" scoped>
.buttons-wrapper {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
</style>
```
</docs>
<template>
<div class="rich-contenteditable">
<div
:id="id"
ref="contenteditable"
:class="{
'rich-contenteditable__input--empty': isEmptyValue,
'rich-contenteditable__input--multiline': multiline,
'rich-contenteditable__input--has-label': label,
'rich-contenteditable__input--overflow': isOverMaxlength,
'rich-contenteditable__input--disabled': disabled,
}"
:contenteditable="contenteditableAttributeValue"
:aria-labelledby="label ? labelId : undefined"
:aria-placeholder="placeholder"
aria-multiline="true"
class="rich-contenteditable__input"
role="textbox"
aria-haspopup="listbox"
aria-autocomplete="inline"
:aria-controls="tributeId"
:aria-expanded="isAutocompleteOpen ? 'true' : 'false'"
:aria-activedescendant="autocompleteActiveId"
:title="tooltipString"
v-bind="$attrs"
v-on="listeners"
@focus="moveCursorToEnd"
@input="onInput"
@compositionstart="isComposing = true"
@compositionend="isComposing = false"
@keydown.esc.capture="onKeyEsc"
@keydown.enter.exact="onEnter"
@keydown.ctrl.enter.exact.stop.prevent="onCtrlEnter"
@paste="onPaste"
@keyup.stop.prevent.capture="onKeyUp"
@keydown.up.exact.stop="onTributeArrowKeyDown"
@keydown.down.exact.stop="onTributeArrowKeyDown"
@tribute-active-true="onTributeActive(true)"
@tribute-active-false="onTributeActive(false)" />
<div
v-if="label"
:id="labelId"
class="rich-contenteditable__label">
{{ label }}
</div>
</div>
</template>
<script>
import debounce from 'debounce'
import stringLength from 'string-length'
import Tribute from 'tributejs/dist/tribute.esm.js'
import NcAutoCompleteResult from './NcAutoCompleteResult.vue'
import { useModelMigration } from '../../composables/useModelMigration.ts'
import { emojiAddRecent, emojiSearch } from '../../functions/emoji/index.ts'
import { n, t } from '../../l10n.js'
import richEditor from '../../mixins/richEditor/index.js'
import GenRandomId from '../../utils/GenRandomId.js'
import { logger } from '../../utils/logger.ts'
import { getLinkWithPicker, searchProvider } from '../NcRichText/index.js'
/**
* Populate the list of text smiles we want to offer via Tribute.
* We add the colon `:)` and colon-dash `:-)` version for each of them.
*/
const smilesCharacters = ['d', 'D', 'p', 'P', 's', 'S', 'x', 'X', ')', '(', '|', '/']
const textSmiles = []
smilesCharacters.forEach((char) => {
textSmiles.push(':' + char)
textSmiles.push(':-' + char)
})
let isPlaintextOnlySupported = null
export default {
name: 'NcRichContenteditable',
mixins: [richEditor],
inheritAttrs: false,
model: {
prop: 'modelValue',
event: 'update:modelValue',
},
props: {
/**
* The ID attribute of the content editable
*/
id: {
type: String,
default: () => GenRandomId(7),
},
/**
* Visual label of the contenteditable
*/
label: {
type: String,
default: '',
},
/**
* Removed in v9 - use `modelValue` (`v-model`) instead
*
* @deprecated
*/
value: {
type: String,
default: undefined,
},
/**
* The text content
*/
modelValue: {
type: String,
default: '',
},
/**
* Placeholder to be shown if empty
*/
placeholder: {
type: String,
default: t('Write a message …'),
},
/**
* Auto complete function
*/
autoComplete: {
type: Function,
default: () => [],
},
/**
* The containing element or selector for the tribute (menu popover)
* Defaults to `body` element
*/
menuContainer: {
type: [String, Element, null],
default: null,
},
/**
* Make the contenteditable looks like a textarea or not.
* Default looks like a single-line input.
* This also handle the default enter/shift+enter behaviour.
* if multiline, enter = newline; otherwise enter = submit
* shift+enter always add a new line. ctrl+enter always submits
*/
multiline: {
type: Boolean,
default: false,
},
/**
* Is the content editable ?
*/
contenteditable: {
type: Boolean,
// eslint-disable-next-line vue/no-boolean-default
default: true,
},
/**
* Disable the editing and show specific disabled design
*/
disabled: {
type: Boolean,
default: false,
},
/**
* Max allowed length
*/
maxlength: {
type: Number,
default: null,
},
/**
* Enable or disable emoji autocompletion
*/
emojiAutocomplete: {
type: Boolean,
// eslint-disable-next-line vue/no-boolean-default
default: true,
},
/**
* Enable or disable link autocompletion
*/
linkAutocomplete: {
type: Boolean,
// eslint-disable-next-line vue/no-boolean-default
default: true,
},
},
emits: [
'submit',
'paste',
/**
* Removed in v9 - use `update:modelValue` (`v-model`) instead
*
* @deprecated
*/
'update:value',
'update:modelValue',
/** Same as update:modelValue for Vue 2 compatibility */
'update:model-value',
'smart-picker-submit',
],
setup() {
const uid = GenRandomId(5)
const model = useModelMigration('value', 'update:value', true)
// Test whether browser supports 'plaintext-only' attribute
if (isPlaintextOnlySupported === null) {
try {
document.createElement('div').contentEditable = 'plaintext-only'
isPlaintextOnlySupported = true
} catch (error) {
// Keep fallback for unsupported browsers
logger.debug('[NcRichContenteditable] Unsupported attribute value:', { error })
isPlaintextOnlySupported = false
}
}
return {
model,
// Constants
labelId: `nc-rich-contenteditable-${uid}-label`,
tributeId: `nc-rich-contenteditable-${uid}-tribute`,
/**
* Non-reactive property to store Tribute instance
*
* @type {import('tributejs').default | null}
*/
tribute: null,
tributeStyleMutationObserver: null,
}
},
data() {
return {
// Represent the raw untrimmed text of the contenteditable
// serves no other purpose than to check whether the
// content is empty or not
localValue: this.model,
// Is in text composition session in IME
isComposing: false,
// Tribute autocomplete
isAutocompleteOpen: false,
autocompleteActiveId: undefined,
isTributeIntegrationDone: false,
}
},
computed: {
/**
* Is the current trimmed value empty?
*
* @return {boolean}
*/
isEmptyValue() {
return !this.localValue || this.localValue.trim() === ''
},
/**
* Is the current value over maxlength?
*
* @return {boolean}
*/
isOverMaxlength() {
if (this.isEmptyValue || !this.maxlength) {
return false
}
return stringLength(this.localValue) > this.maxlength
},
/**
* Tooltip to show if characters count is over limit
*
* @return {string}
*/
tooltipString() {
if (!this.isOverMaxlength) {
return null
}
return n('Message limit of %n character reached', 'Message limit of %n characters reached', this.maxlength)
},
/**
* Edit is only allowed when contenteditable is:
* 'true' (all browsers since 2015)
* 'plaintext-only' (most browsers since 2015, Firefox since 136+)
*
* @return {string}
*/
contenteditableAttributeValue() {
if (this.contenteditable && !this.disabled) {
return isPlaintextOnlySupported ? 'plaintext-only' : 'true'
}
return 'false'
},
/**
* Proxied native event handlers without custom event handlers
*
* @return {Record<string, Function>}
*/
listeners() {
/**
* All component's event handlers are set as native event handlers with by v-on directive.
* The component also raised custom events manually by $emit for corresponding events.
* As a result, it triggers handlers twice.
* The v-on="listeners" directive should only set proxied native events handler without custom events
*/
const listeners = { ...this.$listeners }
delete listeners.paste
return listeners
},
/**
* Compute debounce function for the autocomplete function
*/
debouncedAutoComplete() {
return debounce(async (search, callback) => {
this.autoComplete(search, callback)
}, 100)
},
},
watch: {
/**
* If the parent value change, we compare the plain text rendering
* If it's different, we render everything and update the main content
*/
model() {
const html = this.$refs.contenteditable.innerHTML
// Compare trimmed versions to be safe
if (this.model.trim() !== this.parseContent(html).trim()) {
this.updateContent(this.model)
}
},
},
mounted() {
this.initializeTribute()
// Update default value
this.updateContent(this.model)
},
beforeDestroy() {
if (this.tribute) {
this.tribute.detach(this.$refs.contenteditable)
}
if (this.tributeStyleMutationObserver) {
this.tributeStyleMutationObserver.disconnect()
}
},
methods: {
/**
* Focus the richContenteditable
*
* @public
*/
focus() {
this.$refs.contenteditable.focus()
},
initializeTribute() {
const renderMenuItem = (content) => `<div id="nc-rich-contenteditable-tribute-item-${GenRandomId(5)}" class="${this.$style['tribute-item']}" role="option">${content}</div>`
const tributesCollection = []
tributesCollection.push({
fillAttr: 'id',
// Search against id and label (display name) (fallback to title for v8.0.0..8.6.1 compatibility)
lookup: (result) => `${result.id} ${result.label ?? result.title}`,
requireLeadingSpace: true,
// Popup mention autocompletion templates
menuItemTemplate: (item) => renderMenuItem(this.renderComponentHtml(item.original, NcAutoCompleteResult)),
// Hide if no results
noMatchTemplate: () => '<span class="hidden"></span>',
// Inner display of mentions
selectTemplate: (item) => this.genSelectTemplate(item?.original?.id),
// Autocompletion results
values: this.debouncedAutoComplete,
// Class added to the menu container
containerClass: `${this.$style['tribute-container']} ${this.$style['tribute-container-autocomplete']}`,
// Class added to each list item
itemClass: this.$style['tribute-container__item'],
})
if (this.emojiAutocomplete) {
tributesCollection.push({
trigger: ':',
// Don't use the tribute search function at all
// We pass search results as values (see below)
lookup: (result, query) => query,
requireLeadingSpace: true,
// Popup mention autocompletion templates
menuItemTemplate: (item) => {
if (textSmiles.includes(item.original)) {
// Display the raw text string for :), :-D, … for non emoji results,
// instead of trying to show an image and their name.
return item.original
}
return renderMenuItem(`<span class="${this.$style['tribute-item__emoji']}">${item.original.native}</span> :${item.original.short_name}`)
},
// Hide if no results
noMatchTemplate: () => t('No emoji found'),
// Display raw emoji along with its name
selectTemplate: (item) => {
if (textSmiles.includes(item.original)) {
// Replace the selection with the raw text string for :), :-D, … for non emoji results
return item.original
}
emojiAddRecent(item.original)
return item.original.native
},
// Pass the search results as values
values: (text, cb) => {
const emojiResults = emojiSearch(text)
if (textSmiles.includes(':' + text)) {
/**
* Prepend text smiles to the search results so that Tribute
* is not interfering with normal writing, aka. "Cocos Island Meme".
* E.g. `:)` and `:-)` got replaced by the flag of Cocos Island,
* when submitting the input with Enter after writing them
*/
emojiResults.unshift(':' + text)
}
cb(emojiResults)
},
// Class added to the menu container
containerClass: `${this.$style['tribute-container']} ${this.$style['tribute-container-emoji']}`,
// Class added to each list item
itemClass: this.$style['tribute-container__item'],
})
}
if (this.linkAutocomplete) {
tributesCollection.push({
trigger: '/',
// Don't use the tribute search function at all
// We pass search results as values (see below)
lookup: (result, query) => query,
requireLeadingSpace: true,
// Popup mention autocompletion templates
menuItemTemplate: (item) => renderMenuItem(`<img class="${this.$style['tribute-item__icon']}" src="${item.original.icon_url}"> <span class="${this.$style['tribute-item__title']}">${item.original.title}</span>`),
// Hide if no results
noMatchTemplate: () => t('No link provider found'),
selectTemplate: this.getLink,
// Pass the search results as values
values: (text, cb) => cb(searchProvider(text)),
// Class added to the menu container
containerClass: `${this.$style['tribute-container']} ${this.$style['tribute-container-link']}`,
// Class added to each list item
itemClass: this.$style['tribute-container__item'],
})
}
// Resolve container for Tribute.js to be mounted to (default - `null`)
const menuContainer = (typeof this.menuContainer === 'string')
? document.querySelector(this.menuContainer)
: this.menuContainer
this.tribute = new Tribute({
collection: tributesCollection,
// FIXME: tributejs doesn't support allowSpaces as a collection option, only as a global one
// Requires to fork a library to allow spaces only in the middle of mentions ('@' trigger)
allowSpaces: false,
// Where to inject the menu popup
menuContainer,
})
this.tribute.attach(this.$refs.contenteditable)
// Tribute.js library v5.1.3 ensures that `el.contentEditable = true` when attaching to element.
// This overwrites the template binding.
// Set the contenteditable attribute to actual value afterward
// TODO remove when Tribute.js library v5.1.4 is published on npm (or fork it)
this.$refs.contenteditable.contentEditable = this.contenteditableAttributeValue
},
getLink(item) {
// there is no way to get a tribute result asynchronously
// so we immediately insert a node and replace it when the result comes
getLinkWithPicker(item.original.id)
.then((result) => {
// replace dummy temp element by a text node which contains the picker result
const tmpElem = document.getElementById('tmp-smart-picker-result-node')
const eventData = {
result,
insertText: true,
}
this.$emit('smart-picker-submit', eventData)
if (eventData.insertText) {
const newElem = document.createTextNode(result)
tmpElem.replaceWith(newElem)
this.setCursorAfter(newElem)
this.updateValue(this.$refs.contenteditable.innerHTML)
} else {
tmpElem.remove()
}
})
.catch((error) => {
logger.debug('Smart picker promise rejected', { error })
const tmpElem = document.getElementById('tmp-smart-picker-result-node')
this.setCursorAfter(tmpElem)
tmpElem.remove()
})
return '<span id="tmp-smart-picker-result-node"></span>'
},
setCursorAfter(element) {
const range = document.createRange()
range.setEndAfter(element)
range.collapse()
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
},
moveCursorToEnd() {
if (!document.createRange) {
return
}
if (window.getSelection().rangeCount > 0
&& this.$refs.contenteditable.contains(window.getSelection().getRangeAt(0).commonAncestorContainer)) {
return
}
const range = document.createRange()
range.selectNodeContents(this.$refs.contenteditable)
range.collapse(false)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
},
/**
* Re-emit the input event to the parent
*
* @param {Event} event the input event
*/
onInput(event) {
this.updateValue(event.target.innerHTML)
},
/**
* When pasting, sanitize the content, extract text
* and render it again
*
* @param {Event} event the paste event
* @fires Event paste the original paste event
*/
onPaste(event) {
// Either disabled or edit deactivated
if (!this.contenteditable || this.disabled) {
return
}
if (isPlaintextOnlySupported) {
this.$emit('paste', event)
} else {
/**
* Fallback for unsupported browsers:
* - patched 'paste' operation to insert only raw text
* - issues with 'undo' and 'redo' operations
*/
event.preventDefault()
const clipboardData = event.clipboardData
/** The original paste event */
this.$emit('paste', event)
// If we have a file or if we don't have any text, ignore
if (clipboardData.files.length !== 0
|| !Object.values(clipboardData.items).find((item) => item?.type.startsWith('text'))) {
return
}
const text = clipboardData.getData('text')
const selection = window.getSelection()
// Generate text and insert
const range = selection.getRangeAt(0)
range.deleteContents()
range.insertNode(document.createTextNode(text))
// Collapse the range to the end position
range.collapse(false)
}
// Propagate data
this.updateValue(this.$refs.contenteditable.innerHTML)
},
/**
* Update the value text from the provided html
*
* @param {string} htmlOrText the html content (or raw text with @mentions)
*/
updateValue(htmlOrText) {
// Browsers keep <br> after erasing contenteditable
const text = this.parseContent(htmlOrText).replace(/^\n$/, '')
this.localValue = text
this.model = text
},
/**
* Update content and local value
*
* @param {string} value the message value
*/
updateContent(value) {
const renderedContent = this.renderContent(value)
this.$refs.contenteditable.innerHTML = renderedContent
this.localValue = value
},
/**
* Enter key pressed. Submits if not multiline
*
* @param {Event} event the keydown event
*/
onEnter(event) {
// Prevent submitting if multiline
// or length is over maxlength
// or autocompletion menu is opened
// or in a text composition session with IME
if (this.multiline
|| this.isOverMaxlength
|| this.tribute.isActive
|| this.isComposing) {
return
}
event.preventDefault()
event.stopPropagation()
this.$emit('submit', event)
},
/**
* Ctrl + Enter key pressed is used to submit
*
* @param {Event} event the keydown event
*/
onCtrlEnter(event) {
if (this.isOverMaxlength) {
return
}
this.$emit('submit', event)
},
onKeyUp(event) {
// prevent tribute from opening on keyup
event.stopImmediatePropagation()
},
onKeyEsc(event) {
// prevent event from bubbling when tribute is open
if (this.tribute && this.isAutocompleteOpen) {
event.stopImmediatePropagation()
this.tribute.hideMenu()
}
},
/**
* Get HTML element with Tribute.js container
*
* @return {HTMLElement}
*/
getTributeContainer() {
return this.tribute.menu
},
/**
* Get the currently selected item element id in Tribute.js container
*
* @return {HTMLElement}
*/
getTributeSelectedItem() {
// Tribute does not provide a way to get the active item, only the data index
// So we have to find it manually by select class
return this.getTributeContainer().querySelector('.highlight [id^="nc-rich-contenteditable-tribute-item-"]')
},
/**
* Handle Tribute activation
*
* @param {boolean} isActive - is active
*/
onTributeActive(isActive) {
this.isAutocompleteOpen = isActive
if (isActive) {
// Tribute.js doesn't support containerClass update when new collection is open
// The first opened collection's containerClass stays forever
// https://github.com/zurb/tribute/issues/595
// https://github.com/zurb/tribute/issues/627
// So we have to manually update the class
// The default class is "tribute-container"
this.getTributeContainer().setAttribute('class', this.tribute.current.collection.containerClass || this.$style['tribute-container'])
this.setupTributeIntegration()
// Remove the event handler if any
document.removeEventListener('click', this.hideTribute, true)
} else {
// Cancel loading data for autocomplete
// Otherwise it could be received when another autocomplete is already opened
this.debouncedAutoComplete.clear()
// Reset active item
this.autocompleteActiveId = undefined
this.setTributeFocusVisible(false)
}
},
onTributeArrowKeyDown() {
if (!this.isAutocompleteOpen) {
return
}
this.setTributeFocusVisible(true)
this.onTributeSelectedItemWillChange()
},
onTributeSelectedItemWillChange() {
// Wait until tribute has updated the selected item
requestAnimationFrame(() => {
this.autocompleteActiveId = this.getTributeSelectedItem()?.id
})
},
setupTributeIntegration() {
// Setup integration only once on the first open
if (this.isTributeIntegrationDone) {
return
}
this.isTributeIntegrationDone = true