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
|
<!--
- @copyright Copyright (c) 2019 Marco Ambrosini <marcoambrosini@pm.me>
-
- @author Marco Ambrosini <marcoambrosini@pm.me>
-
- @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"
:class="{'wrapper--chatScrolledToBottom': isChatScrolledToBottom}">
<!--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>
<div
v-if="canUploadFiles || canShareFiles">
<Actions
ref="uploadMenu"
container="#content-vue"
:disabled="disabled"
default-icon="icon-clip-add-file"
:aria-label="t('spreed', 'Share files to the conversation')"
:aria-haspopup="true">
<ActionButton
v-if="canUploadFiles"
:close-after-click="true"
icon="icon-upload"
@click.prevent="clickImportInput">
{{ t('spreed', 'Upload new files') }}
</ActionButton>
<ActionButton
v-if="canShareFiles"
:close-after-click="true"
icon="icon-folder"
@click.prevent="handleFileShare">
{{ t('spreed', 'Share from Files') }}
</ActionButton>
</Actions>
</div>
<div>
<EmojiPicker
container="#content-vue"
@select="addEmoji">
<button
type="button"
:disabled="disabled"
class="nc-button nc-button__main"
:aria-label="t('spreed', 'Add emoji')"
:aria-haspopup="true">
<EmoticonOutline
:size="16"
decorative
title="" />
</button>
</EmojiPicker>
</div>
<div class="new-message-form__input">
<div v-if="messageToBeReplied" class="new-message-form__quote">
<Quote
:is-new-message-form-quote="true"
:parent-id="messageToBeReplied.id"
v-bind="messageToBeReplied" />
</div>
<AdvancedInput
ref="advancedInput"
v-model="text"
:token="token"
:active-input="!disabled"
:placeholder-text="placeholderText"
:aria-label="placeholderText"
@update:contentEditable="contentEditableToParsed"
@submit="handleSubmit"
@files-pasted="handlePastedFiles" />
</div>
<button
:disabled="disabled"
type="submit"
:aria-label="t('spreed', 'Send message')"
class="nc-button nc-button__main"
@click.prevent="handleSubmit">
<Send
title=""
:size="16"
decorative />
</button>
</form>
</div>
</div>
</template>
<script>
import AdvancedInput from './AdvancedInput/AdvancedInput'
import { getFilePickerBuilder } from '@nextcloud/dialogs'
import { getCapabilities } from '@nextcloud/capabilities'
import Quote from '../Quote'
import Actions from '@nextcloud/vue/dist/Components/Actions'
import ActionButton from '@nextcloud/vue/dist/Components/ActionButton'
import EmojiPicker from '@nextcloud/vue/dist/Components/EmojiPicker'
import { EventBus } from '../../services/EventBus'
import { shareFile } from '../../services/filesSharingServices'
import { CONVERSATION } from '../../constants'
import EmoticonOutline from 'vue-material-design-icons/EmoticonOutline'
import Send from 'vue-material-design-icons/Send'
const picker = getFilePickerBuilder(t('spreed', 'File to share'))
.setMultiSelect(false)
.setModal(true)
.setType(1)
.allowDirectories()
.build()
export default {
name: 'NewMessageForm',
components: {
AdvancedInput,
Quote,
Actions,
ActionButton,
EmojiPicker,
EmoticonOutline,
Send,
},
props: {
isChatScrolledToBottom: {
type: Boolean,
required: true,
},
},
data: function() {
return {
text: '',
parsedText: '',
conversationIsFirstInList: false,
}
},
computed: {
/**
* The current conversation token
*
* @returns {String}
*/
token() {
return this.$store.getters.getToken()
},
conversation() {
return this.$store.getters.conversation(this.token) || {
readOnly: CONVERSATION.STATE.READ_WRITE,
}
},
isReadOnly() {
return this.conversation.readOnly === CONVERSATION.STATE.READ_ONLY
},
disabled() {
return this.isReadOnly || !this.currentConversationIsJoined
},
placeholderText() {
if (this.isReadonly) {
return t('spreed', 'This conversation has been locked')
} 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
},
attachmentFolderFreeSpace() {
return this.$store.getters.getAttachmentFolderFreeSpace()
},
currentConversationIsJoined() {
return this.$store.getters.currentConversationIsJoined
},
},
watch: {
disabled(newValue) {
// the menu is not always available
if (!this.$refs.uploadMenu) {
return
}
this.$refs.uploadMenu.$refs.menuButton.disabled = newValue
},
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 = ''
}
},
},
mounted() {
EventBus.$on('uploadStart', this.handleUploadStart)
EventBus.$on('retryMessage', this.handleRetryMessage)
this.text = this.$store.getters.currentMessageInput(this.token) || ''
},
beforeDestroy() {
EventBus.$off('uploadStart', this.handleUploadStart)
EventBus.$off('retryMessage', this.handleRetryMessage)
},
methods: {
handleUploadStart() {
// refocus on upload start as the user might want to type again
// while the upload is running
this.$refs.advancedInput.focusInput()
},
contentEditableToParsed(contentEditable) {
const mentions = contentEditable.querySelectorAll('span[data-at-embedded]')
mentions.forEach(mention => {
// FIXME Adding a space after the mention should be improved to
// do it or not based on the next element instead of always
// adding it.
mention.replaceWith('@' + mention.firstElementChild.attributes['data-mention-id'].value + ' ')
})
this.parsedText = this.rawToParsed(contentEditable.innerHTML)
},
/**
* Returns a parsed version of the given raw text of the content
* editable div.
*
* The given raw text contains a plain text representation of HTML
* content (like "first line<br>second line"). The returned
* parsed text replaces the (known) HTML content with the format
* expected by the server (like "first line\nsecond line").
*
* The parsed text is also trimmed.
*
* @param {String} text the raw text
* @returns {String} the parsed text
*/
rawToParsed(text) {
text = text.replace(/<br>/g, '\n')
text = text.replace(/ /g, ' ')
// Since we used innerHTML to get the content of the div.contenteditable
// it is escaped. With this little trick from https://stackoverflow.com/a/7394787
// We unescape the code again, so if you write `<strong>` we can display
// it again instead of `<strong>`
const temp = document.createElement('textarea')
temp.innerHTML = text
text = temp.value
// Although the text is fully trimmed, at the very least the last
// "\n" occurrence should be always removed, as 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>").
return text.trim()
},
/**
* Sends the new message
*/
async handleSubmit() {
if (this.parsedText !== '') {
const temporaryMessage = await this.$store.dispatch('createTemporaryMessage', { text: this.parsedText, token: this.token })
// FIXME: move "addTemporaryMessage" into "postNewMessage" as it's a pre-requisite anyway ?
this.$store.dispatch('addTemporaryMessage', temporaryMessage)
this.text = ''
this.parsedText = ''
// Scrolls the message list to the last added message
EventBus.$emit('smoothScrollChatToBottom')
// Also remove the message to be replied for this conversation
this.$store.dispatch('removeMessageToBeReplied', this.token)
await this.$store.dispatch('postNewMessage', temporaryMessage)
}
},
handleRetryMessage(temporaryMessageId) {
if (this.parsedText === '') {
const temporaryMessage = this.$store.getters.message(this.token, temporaryMessageId)
if (temporaryMessage) {
this.text = temporaryMessage.message || this.text
this.parsedText = temporaryMessage.message || this.parsedText
this.$store.dispatch('deleteMessage', temporaryMessage)
}
}
},
async handleFileShare() {
picker.pick()
.then(async(path) => {
console.debug(`path ${path} selected for sharing`)
if (!path.startsWith('/')) {
throw new Error(t('files', 'Invalid path selected'))
}
shareFile(path, this.token)
this.$refs.advancedInput.focusInput()
})
},
/**
* Clicks the hidden file input when clicking the correspondent ActionButton,
* 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 {File[] | FileList} files pasted files list
*/
async handlePastedFiles(files) {
this.handleFiles(files, true)
},
/**
* Handles file upload
*
* @param {File[] | FileList} files pasted files list
* @param {bool} rename whether to rename the files
*/
async handleFiles(files, rename = false) {
// 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 })
},
/**
* 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 {Emoji} emoji Emoji object
*/
addEmoji(emoji) {
const selection = document.getSelection()
const contentEditable = this.$refs.advancedInput.$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.substr(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)
},
},
}
</script>
<style lang="scss" scoped>
@import '../../assets/buttons';
.wrapper {
display: flex;
justify-content: center;
padding: 12px 0;
border-top: 1px solid var(--color-border);
&--chatScrolledToBottom {
border-top: none;
}
}
.new-message {
max-width: $messages-list-max-width + 145px;
flex: 1 1 100%;
&-form {
display: flex;
align-items: flex-end;
&__input {
flex-grow: 1;
max-height: $message-form-max-height;
overflow-y: auto;
overflow-x: hidden;
max-width: 638px;
}
&__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
::v-deep .action-item__menutoggle {
opacity: .8 !important;
&:hover,
&:focus {
background-color: var(--color-background-hover) !important;
opacity: .8 !important;
}
}
</style>
|