-
Notifications
You must be signed in to change notification settings - Fork 437
/
NewMessageForm.vue
1031 lines (908 loc) · 30.3 KB
/
NewMessageForm.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
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
<!--
- @copyright Copyright (c) 2019 Marco Ambrosini <marcoambrosini@icloud.com>
-
- @author Marco Ambrosini <marcoambrosini@icloud.com>
-
- @license GNU AGPL version 3 or any later version
-
- 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="wrapper">
<!--native file picker, hidden -->
<input id="file-upload"
ref="fileUploadInput"
multiple
type="file"
tabindex="-1"
aria-hidden="true"
class="hidden-visually"
@change="handleFileInput">
<div class="new-message">
<form class="new-message-form"
@submit.prevent>
<!-- Attachments menu -->
<div v-if="showAttachmentsMenu"
class="new-message-form__upload-menu">
<NcActions ref="attachmentsMenu"
:container="container"
:boundaries-element="containerElement"
:disabled="disabled"
:aria-label="t('spreed', 'Share files to the conversation')"
:aria-haspopup="true">
<template #icon>
<Paperclip :size="16" />
</template>
<NcActionButton v-if="canUploadFiles"
:close-after-click="true"
@click.prevent="clickImportInput">
<template #icon>
<Upload :size="20" />
</template>
{{ t('spreed', 'Upload from device') }}
</NcActionButton>
<NcActionButton v-if="canShareFiles"
:close-after-click="true"
@click.prevent="handleFileShare">
<template #icon>
<Folder :size="20" />
</template>
{{ shareFromNextcloudLabel }}
</NcActionButton>
<template v-if="canShareFiles">
<NcActionButton v-for="(provider, i) in fileTemplateOptions"
:key="i"
:close-after-click="true"
:icon="provider.iconClass"
@click.prevent="showTextFileDialog = i">
{{ provider.label }}
</NcActionButton>
</template>
<NcActionButton v-if="canCreatePoll"
:close-after-click="true"
@click.prevent="toggleSimplePollsEditor(true)">
<template #icon>
<Poll :size="20" />
</template>
{{ t('spreed', 'Create new poll') }}
</NcActionButton>
</NcActions>
</div>
<!-- Input area -->
<div class="new-message-form__input">
<div class="new-message-form__emoji-picker">
<NcEmojiPicker v-if="!disabled"
:container="container"
:close-on-select="false"
@select="addEmoji">
<NcButton :disabled="disabled"
:aria-label="t('spreed', 'Add emoji')"
type="tertiary-no-background"
:aria-haspopup="true">
<template #icon>
<EmoticonOutline :size="16" />
</template>
</NcButton>
</NcEmojiPicker>
<!-- Disabled emoji picker placeholder button -->
<NcButton v-else
type="tertiary"
:aria-label="t('spreed', 'Add emoji')"
:disabled="true">
<template #icon>
<EmoticonOutline :size="16" />
</template>
</NcButton>
</div>
<div v-if="messageToBeReplied" class="new-message-form__quote">
<Quote :is-new-message-form-quote="true"
:parent-id="messageToBeReplied.id"
v-bind="messageToBeReplied" />
</div>
<NcRichContenteditable ref="richContenteditable"
v-shortkey.once="$options.disableKeyboardShortcuts ? null : ['c']"
class="new-message-form__richContenteditable"
:value.sync="text"
:auto-complete="autoComplete"
:disabled="disabled"
:user-data="userData"
:menu-container="containerElement"
:placeholder="placeholderText"
:aria-label="placeholderText"
@shortkey="focusInput"
@keydown.esc.prevent="handleInputEsc"
@tribute-active-true.native="isTributePickerActive = true"
@tribute-active-false.native="isTributePickerActive = false"
@paste="handlePastedFiles"
@submit="handleSubmit({ silent: false })" />
</div>
<AudioRecorder v-if="showAudioRecorder"
:disabled="disabled"
@recording="handleRecording"
@audio-file="handleAudioFile" />
<!-- Send buttons -->
<template v-else>
<NcActions v-if="!broadcast"
:force-menu="true">
<!-- Silent send -->
<NcActionButton :close-after-click="true"
icon="icon-upload"
:title="t('spreed', 'Send without notification')"
@click.prevent="handleSubmit({ silent: true })">
{{ silentSendInfo }}
<BellOff slot="icon"
:size="16" />
</NcActionButton>
</NcActions>
<!-- Send -->
<NcButton :disabled="disabled"
type="tertiary"
native-type="submit"
:title="t('spreed', 'Send message')"
:aria-label="t('spreed', 'Send message')"
@click.prevent="handleSubmit({ silent: false })">
<template #icon>
<Send :size="16" />
</template>
</NcButton>
</template>
</form>
</div>
<SimplePollsEditor v-if="showSimplePollsEditor"
:token="token"
@close="toggleSimplePollsEditor(false)" />
<!-- Text file creation dialog -->
<NcModal v-if="showTextFileDialog !== false"
size="normal"
:container="container"
class="templates-picker"
@close="dismissTextFileCreation">
<div class="new-text-file">
<h2>
{{ t('spreed', 'Create and share a new file') }}
</h2>
<form class="new-text-file__form templates-picker__form"
:style="style"
@submit.prevent="handleCreateTextFile">
<NcTextField id="new-file-form-name"
ref="textFileTitleInput"
:error="!!newFileError"
:helper-text="newFileError"
:label="t('spreed', 'Name of the new file')"
:placeholder="textFileTitle"
:value.sync="textFileTitle" />
<template v-if="fileTemplate.templates.length">
<ul class="templates-picker__list">
<TemplatePreview v-bind="emptyTemplate"
:checked="checked === emptyTemplate.fileid"
@check="onCheck" />
<TemplatePreview v-for="template in fileTemplate.templates"
:key="template.fileid"
v-bind="template"
:checked="checked === template.fileid"
:ratio="fileTemplate.ratio"
@check="onCheck" />
</ul>
</template>
<div class="new-text-file__buttons">
<NcButton type="tertiary"
@click="dismissTextFileCreation">
{{ t('spreed', 'Close') }}
</NcButton>
<NcButton type="primary"
@click="handleCreateTextFile">
{{ t('spreed', 'Create file') }}
</NcButton>
</div>
</form>
</div>
</NcModal>
</div>
</template>
<script>
import BellOff from 'vue-material-design-icons/BellOff.vue'
import EmoticonOutline from 'vue-material-design-icons/EmoticonOutline.vue'
import Folder from 'vue-material-design-icons/Folder.vue'
import Paperclip from 'vue-material-design-icons/Paperclip.vue'
import Poll from 'vue-material-design-icons/Poll.vue'
import Send from 'vue-material-design-icons/Send.vue'
import Upload from 'vue-material-design-icons/Upload.vue'
import { getCapabilities } from '@nextcloud/capabilities'
import { getFilePickerBuilder, showError } from '@nextcloud/dialogs'
import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js'
import NcActions from '@nextcloud/vue/dist/Components/NcActions.js'
import NcButton from '@nextcloud/vue/dist/Components/NcButton.js'
import NcEmojiPicker from '@nextcloud/vue/dist/Components/NcEmojiPicker.js'
import NcModal from '@nextcloud/vue/dist/Components/NcModal.js'
import NcRichContenteditable from '@nextcloud/vue/dist/Components/NcRichContenteditable.js'
import NcTextField from '@nextcloud/vue/dist/Components/NcTextField.js'
import Quote from '../Quote.vue'
import AudioRecorder from './AudioRecorder/AudioRecorder.vue'
import SimplePollsEditor from './SimplePollsEditor/SimplePollsEditor.vue'
import TemplatePreview from './TemplatePreview.vue'
import { CONVERSATION, PARTICIPANT } from '../../constants.js'
import { EventBus } from '../../services/EventBus.js'
import { shareFile, createTextFile } from '../../services/filesSharingServices.js'
import { searchPossibleMentions } from '../../services/mentionsService.js'
import { fetchClipboardContent } from '../../utils/clipboard.js'
const picker = getFilePickerBuilder(t('spreed', 'File to share'))
.setMultiSelect(false)
.setModal(true)
.setType(1)
.allowDirectories()
.build()
const border = 2
const margin = 8
const width = margin * 20
const disableKeyboardShortcuts = OCP.Accessibility.disableKeyboardShortcuts()
export default {
name: 'NewMessageForm',
disableKeyboardShortcuts,
components: {
Quote,
NcActions,
NcActionButton,
NcButton,
Paperclip,
NcEmojiPicker,
NcRichContenteditable,
EmoticonOutline,
Send,
AudioRecorder,
BellOff,
SimplePollsEditor,
Poll,
NcModal,
Folder,
Upload,
TemplatePreview,
NcTextField,
},
props: {
/**
* The current conversation token or the breakout room token.
*/
token: {
type: String,
required: true,
},
/**
* When this component is used to send message to a breakout room we
* adapt the layout and remove some functionality.
*/
breakoutRoom: {
type: Boolean,
default: false,
},
/**
* When this component is used to send message to a breakout room we
* pass an id of modal containing component to render properly.
*/
containerId: {
type: String,
default: null,
},
/**
* Broadcast messages to all breakout rooms of a given conversation.
*/
broadcast: {
type: Boolean,
default: false,
},
},
data() {
return {
text: '',
conversationIsFirstInList: false,
// True when the audiorecorder component is recording
isRecordingAudio: false,
showSimplePollsEditor: false,
showTextFileDialog: false,
textFileTitle: t('spreed', 'New file'),
newFileError: '',
isTributePickerActive: false,
// Check empty template by default
checked: -1,
userData: {},
}
},
computed: {
conversation() {
return this.$store.getters.conversation(this.token) || {
readOnly: CONVERSATION.STATE.READ_WRITE,
}
},
isReadOnly() {
return this.conversation.readOnly === CONVERSATION.STATE.READ_ONLY
},
noChatPermission() {
return (this.conversation.permissions & PARTICIPANT.PERMISSIONS.CHAT) === 0
},
disabled() {
return this.isReadOnly || this.noChatPermission || !this.currentConversationIsJoined || this.isRecordingAudio
},
placeholderText() {
if (this.isReadOnly) {
return t('spreed', 'This conversation has been locked')
} else if (this.noChatPermission) {
return t('spreed', 'No permission to post messages in this conversation')
} else if (!this.currentConversationIsJoined) {
return t('spreed', 'Joining conversation …')
} else {
return t('spreed', 'Write message, @ to mention someone …')
}
},
messageToBeReplied() {
return this.$store.getters.getMessageToBeReplied(this.token)
},
currentUserIsGuest() {
return this.$store.getters.getUserId() === null
},
canShareFiles() {
return !this.currentUserIsGuest
},
canUploadFiles() {
const allowed = getCapabilities()?.spreed?.config?.attachments?.allowed
return allowed
&& this.attachmentFolderFreeSpace !== 0
&& this.canShareFiles
},
canCreatePoll() {
return !this.isOneToOne && !this.noChatPermission
},
attachmentFolderFreeSpace() {
return this.$store.getters.getAttachmentFolderFreeSpace()
},
currentConversationIsJoined() {
return this.$store.getters.currentConversationIsJoined
},
hasText() {
return this.text !== ''
},
container() {
return this.containerId ?? this.$store.getters.getMainContainerSelector()
},
containerElement() {
// TODO can't find DOM element by #content-vue. undefined is passed
// for NcRichContenteditable to use 'document.body' by default
return document.querySelector(this.container) ?? undefined
},
isOneToOne() {
return this.conversation.type === CONVERSATION.TYPE.ONE_TO_ONE
|| this.conversation.type === CONVERSATION.TYPE.ONE_TO_ONE_FORMER
},
silentSendInfo() {
if (this.isOneToOne) {
return t('spreed', 'The participant will not be notified about this message')
} else {
return t('spreed', 'The participants will not be notified about this message')
}
},
shareFromNextcloudLabel() {
return t('spreed', 'Share from {nextcloud}', { nextcloud: OC.theme.productName })
},
fileTemplateOptions() {
return this.$store.getters.getFileTemplates()
},
fileTemplate() {
return this.fileTemplateOptions[this.showTextFileDialog]
},
emptyTemplate() {
return {
basename: t('files', 'Blank'),
fileid: -1,
filename: t('files', 'Blank'),
hasPreview: false,
mime: this.fileTemplate?.mimetypes[0] || this.fileTemplate?.mimetypes,
}
},
selectedTemplate() {
return this.fileTemplate.templates.find(template => template.fileid === this.checked)
},
style() {
return {
'--margin': margin + 'px',
'--width': width + 'px',
'--border': border + 'px',
'--fullwidth': width + 2 * margin + 2 * border + 'px',
'--height': this.fileTemplate.ratio ? Math.round(width / this.fileTemplate.ratio) + 'px' : null,
}
},
showAttachmentsMenu() {
return (this.canUploadFiles || this.canShareFiles) && !this.broadcast
},
showAudioRecorder() {
return !this.hasText && this.canUploadFiles && !this.broadcast
},
},
watch: {
currentConversationIsJoined() {
this.focusInput()
},
text(newValue) {
this.$store.dispatch('setCurrentMessageInput', { token: this.token, text: newValue })
},
token(token) {
if (token) {
this.text = this.$store.getters.currentMessageInput(token) || ''
} else {
this.text = ''
}
},
showTextFileDialog(newValue) {
if (newValue !== false) {
const fileTemplate = this.fileTemplateOptions[newValue]
this.textFileTitle = fileTemplate.label + fileTemplate.extension
this.$nextTick(() => {
this.focusTextDialogInput()
})
}
},
},
mounted() {
EventBus.$on('focus-chat-input', this.focusInput)
EventBus.$on('upload-start', this.handleUploadStart)
EventBus.$on('retry-message', this.handleRetryMessage)
this.text = this.$store.getters.currentMessageInput(this.token) || ''
if (!this.$store.getters.areFileTemplatesInitialised) {
this.$store.dispatch('getFileTemplates')
}
},
beforeDestroy() {
EventBus.$off('focus-chat-input', this.focusInput)
EventBus.$off('upload-start', this.handleUploadStart)
EventBus.$off('retry-message', this.handleRetryMessage)
},
methods: {
handleUploadStart() {
// refocus on upload start as the user might want to type again
// while the upload is running
this.focusInput()
},
/**
* Sends the new message
*
* @param {object} options the submit options
*/
async handleSubmit(options) {
if (OC.debug && this.text.startsWith('/spam ')) {
const pattern = /^\/spam (\d+) messages$/i
const match = pattern.exec(this.text)
// Escape HTML
if (match) {
await this.handleSubmitSpam(match[1])
return
}
}
if (this.text !== '') {
// FIXME: remove after issue is resolved: https://github.com/nextcloud/nextcloud-vue/issues/3264
const temp = document.createElement('textarea')
temp.innerHTML = this.text
this.text = temp.value
const temporaryMessage = await this.$store.dispatch('createTemporaryMessage', { text: this.text, token: this.token })
// FIXME: move "addTemporaryMessage" into "postNewMessage" as it's a pre-requisite anyway ?
if (!this.broadcast) {
await this.$store.dispatch('addTemporaryMessage', temporaryMessage)
}
this.text = ''
this.userData = {}
// Scrolls the message list to the last added message
EventBus.$emit('smooth-scroll-chat-to-bottom')
// Also remove the message to be replied for this conversation
await this.$store.dispatch('removeMessageToBeReplied', this.token)
this.breakoutRoom
? await this.broadcastMessage(temporaryMessage, options)
: await this.postMessage(temporaryMessage, options)
}
},
// Post message to conversation
async postMessage(temporaryMessage, options) {
try {
await this.$store.dispatch('postNewMessage', { temporaryMessage, options })
this.$emit('sent')
} catch {
this.$emit('failure')
}
},
// Broadcast message to all breakout rooms
async broadcastMessage(temporaryMessage, options) {
try {
await this.$store.dispatch('broadcastMessageToBreakoutRoomsAction', { temporaryMessage, options })
this.$emit('sent')
} catch {
this.$emit('failure')
}
},
async handleSubmitSpam(numberOfMessages) {
console.debug('Sending ' + numberOfMessages + ' lorem ipsum messages')
for (let i = 0; i < numberOfMessages; i++) {
const randomNumber = parseInt(Math.random() * 500, 10)
console.debug('[' + i + '/' + numberOfMessages + '] Sleeping ' + randomNumber + 'ms')
await this.sleep(randomNumber)
const loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n\nDuis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.'
this.text = loremIpsum.slice(0, 25 + randomNumber)
await this.handleSubmit()
}
},
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
},
handleRetryMessage(temporaryMessageId) {
if (this.text === '') {
const temporaryMessage = this.$store.getters.message(this.token, temporaryMessageId)
if (temporaryMessage) {
this.text = temporaryMessage.message || this.text
// Restore the parent/quote message
if (temporaryMessage.parent) {
const temporaryParent = this.$store.getters.message(this.token, temporaryMessage.parent)
this.$store.dispatch('addMessageToBeReplied', {
id: temporaryParent.id,
actorId: temporaryParent.actorId,
actorType: temporaryParent.actorType,
actorDisplayName: temporaryParent.actorDisplayName,
timestamp: temporaryParent.timestamp,
systemMessage: temporaryParent.systemMessage,
messageType: temporaryParent.messageType,
message: temporaryParent.message,
messageParameters: temporaryParent.messageParameters,
token: temporaryParent.token,
previousMessageId: temporaryParent.previousMessageId,
})
}
this.$store.dispatch('removeTemporaryMessageFromStore', temporaryMessage)
}
}
},
handleFileShare() {
picker.pick()
.then((path) => {
console.debug(`path ${path} selected for sharing`)
if (!path.startsWith('/')) {
throw new Error(t('files', 'Invalid path selected'))
}
this.focusInput()
return shareFile(path, this.token)
})
// FIXME Remove this hack once it is possible to set the parent
// element of the file picker.
// By default the file picker is a sibling of the fullscreen
// element, so it is not visible when in fullscreen mode. It is not
// possible to specify the parent nor to know when the file picker
// was actually opened, so for the time being it is reparented if
// needed shortly after calling it.
setTimeout(() => {
if (this.$store.getters.isFullscreen()) {
document.getElementById('content-vue').appendChild(document.querySelector('.oc-dialog'))
}
}, 1000)
},
/**
* Clicks the hidden file input when clicking the correspondent NcActionButton,
* thus opening the file-picker
*/
clickImportInput() {
this.$refs.fileUploadInput.click()
},
handleFileInput(event) {
const files = Object.values(event.target.files)
this.handleFiles(files)
// Clear input to ensure that the change event will be emitted if
// the same file is picked again.
event.target.value = ''
},
/**
* Handles files pasting event
*
* @param {ClipboardEvent} e native paste event
*/
async handlePastedFiles(e) {
e.preventDefault()
const content = fetchClipboardContent(e)
if (content.kind === 'file') {
this.handleFiles(content.files, true)
}
},
/**
* Handles file upload
*
* @param {File[] | FileList} files pasted files list
* @param {boolean} rename whether to rename the files
* @param {boolean} isVoiceMessage indicates whether the file is a vooicemessage
*/
async handleFiles(files, rename = false, isVoiceMessage) {
// Create a unique id for the upload operation
const uploadId = new Date().getTime()
// Uploads and shares the files
await this.$store.dispatch('initialiseUpload', { files, token: this.token, uploadId, rename, isVoiceMessage })
},
/**
* Add selected emoji to text input area
*
* The emoji will be added at the current caret position, and any text
* currently selected will be replaced by the emoji. If the input area
* does not have the focus there will be no caret or selection; in that
* case the emoji will be added at the end.
*
* @param {string} emoji Emoji object
*/
addEmoji(emoji) {
const selection = document.getSelection()
const contentEditable = this.$refs.richContenteditable.$refs.contenteditable
// There is no select, or current selection does not start in the
// content editable element, so just append the emoji at the end.
if (!contentEditable.isSameNode(selection.anchorNode) && !contentEditable.contains(selection.anchorNode)) {
// Browsers add a "<br>" element as soon as some rich text is
// written in a content editable div (for example, if a new line
// is added the div content will be "<br><br>"), so the emoji
// has to be added before the last "<br>" (if any).
if (this.text.endsWith('<br>')) {
this.text = this.text.slice(0, this.text.lastIndexOf('<br>')) + emoji + '<br>'
} else {
this.text += emoji
}
return
}
// Although due to legacy reasons the API allows several ranges the
// specification requires the selection to always have a single
// range.
// https://developer.mozilla.org/en-US/docs/Web/API/Selection#Multiple_ranges_in_a_selection
const range = selection.getRangeAt(0)
// Deleting the contents also collapses the range to the start.
range.deleteContents()
const emojiTextNode = document.createTextNode(emoji)
range.insertNode(emojiTextNode)
this.text = contentEditable.innerHTML
range.setStartAfter(emojiTextNode)
},
handleAudioFile(payload) {
this.handleFiles([payload], false, true)
},
handleRecording(payload) {
this.isRecordingAudio = payload
},
toggleSimplePollsEditor(value) {
this.showSimplePollsEditor = value
},
/**
* Manages the radio template picker change
*
* @param {number} fileid the selected template file id
*/
onCheck(fileid) {
this.checked = fileid
},
// Create text file and share it to a conversation
async handleCreateTextFile() {
this.newFileError = ''
let filePath = this.$store.getters.getAttachmentFolder() + '/' + this.textFileTitle.replace('/', '')
if (!filePath.endsWith(this.fileTemplate.extension)) {
filePath += this.fileTemplate.extension
}
let fileData
try {
const response = await createTextFile(
filePath,
this.selectedTemplate?.filename,
this.selectedTemplate?.templateType,
)
fileData = response.data.ocs.data
} catch (error) {
console.error('Error while creating file', error)
if (error?.response?.data?.ocs?.meta?.message) {
showError(error.response.data.ocs.meta.message)
this.newFileError = error.response.data.ocs.meta.message
} else {
showError(t('spreed', 'Error while creating file'))
}
return
}
await shareFile(filePath, this.token, '', '')
// The Viewer expects a file to be set in the sidebar if the sidebar
// is open.
if (this.$store.getters.getSidebarStatus) {
OCA.Files.Sidebar.state.file = filePath
}
OCA.Viewer.open({
// Viewer expects an internal absolute path starting with "/".
path: filePath,
list: [
fileData,
],
})
// FIXME Remove this hack once it is possible to set the parent
// element of the viewer.
// By default the viewer is a sibling of the fullscreen element, so
// it is not visible when in fullscreen mode. It is not possible to
// specify the parent nor to know when the viewer was actually
// opened, so for the time being it is reparented if needed shortly
// after calling it.
setTimeout(() => {
if (this.$store.getters.isFullscreen()) {
document.getElementById('content-vue').appendChild(document.getElementById('viewer'))
}
}, 1000)
this.dismissTextFileCreation()
},
dismissTextFileCreation() {
this.showTextFileDialog = false
this.textFileTitle = t('spreed', 'New file')
this.newFileError = ''
},
// Focus and select the text within the input field
focusTextDialogInput() {
// this.$refs.textFileTitleInput.$refs.inputField.$refs.input.focus()
this.$refs.textFileTitleInput.$refs.inputField.$refs.input.select()
},
async autoComplete(search, callback) {
const response = await searchPossibleMentions(this.token, search)
if (!response) {
// It was not possible to get the candidate mentions, so just
// keep the previous ones.
return
}
const possibleMentions = response.data.ocs.data
possibleMentions.forEach(possibleMention => {
// Wrap mention ids with spaces in quotes.
if (possibleMention.id.indexOf(' ') !== -1
|| possibleMention.id.indexOf('/') !== -1) {
possibleMention.id = '"' + possibleMention.id + '"'
}
// Set icon for candidate mentions that are not for users.
if (possibleMention.source === 'calls') {
possibleMention.icon = 'icon-group-forced-white'
} else if (possibleMention.source === 'guests') {
possibleMention.icon = 'icon-user-forced-white'
} else {
// The avatar is automatically shown for users, but an icon
// is nevertheless required as fallback.
possibleMention.icon = 'icon-user-forced-white'
}
// Convert status properties to an object.
if (possibleMention.status) {
const status = {
status: possibleMention.status,
icon: possibleMention.statusIcon,
}
possibleMention.status = status
possibleMention.subline = possibleMention.statusMessage
}
// Caching the user id data for each possible mention
this.userData[possibleMention.id] = possibleMention
})
callback(possibleMentions)
},
focusInput() {
if (this.isMobile()) {
return
}
this.$nextTick().then(() => {
this.$refs.richContenteditable.$refs.contenteditable.focus()
})
},
blurInput() {
document.activeElement.blur()
},
handleInputEsc() {
// When the tribute picker (e.g. emoji picker or mentions) is open
// ESC should only close the picker but not blur
if (!this.isTributePickerActive) {
this.blurInput()
}
},
isMobile() {
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent)
},
},
}
</script>
<style lang="scss" scoped>
@import '../../assets/variables';
.wrapper {
display: flex;
justify-content: center;
padding: 12px 0;
min-height: 69px;
}
.new-message {
width: 100%;
display: flex;
justify-content: center;
&-form {
align-items: flex-end;
display: flex;
position:relative;
flex: 0 1 700px;
margin: 0 4px;
&__emoji-picker {
position: absolute;
bottom: 1px;
z-index: 1;
}
&__input {
flex-grow: 1;
overflow: hidden;
position: relative;
}
// Override NcRichContenteditable styles
& &__richContenteditable {
border: 1px solid var(--color-border-dark);
border-radius: calc(var(--default-clickable-area) / 2);
padding: 8px 16px 8px 44px;
max-height: 180px;
&:hover,
&:focus,
&:active {
border: 1px solid var(--color-primary-element);
}
}
&__quote {
margin: 0 16px 12px 24px;
background-color: var(--color-background-hover);
padding: 8px;
border-radius: var(--border-radius-large);
}
// put a grey round background when popover is opened
// or hover-focused
&__icon:hover,
&__icon:focus,
&__icon:active {
opacity: $opacity_full;
// good looking on dark AND white bg
background-color: $icon-focus-bg;
}
}
}
// Override actions styles TODO: upstream this change
// Targeting two classess for specificity
::v-deep .action-item__menutoggle.action-item__menutoggle--with-icon-slot {
opacity: 1 !important;
&:hover,
&:focus {
background-color: var(--color-background-hover) !important;
}
&:disabled {
opacity: .5 !important;
}
}
.new-text-file {
display: flex;
justify-content: center;