-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathcompose_area.ts
811 lines (714 loc) · 36 KB
/
compose_area.ts
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
/**
* This file is part of Threema Web.
*
* Threema Web 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 Threema Web. If not, see <http://www.gnu.org/licenses/>.
*/
import {ComposeArea} from '@threema/compose-area';
import {isActionTrigger} from '../helpers';
import {parseEmoji, shortnameToUtf8} from '../helpers/emoji';
import {BrowserService} from '../services/browser';
import {LogService} from '../services/log';
import {ReceiverService} from '../services/receiver';
import {SettingsService} from '../services/settings';
import {StringService} from '../services/string';
import {TimeoutService} from '../services/timeout';
import {isEmojiInfo, isKeyboardEvent} from '../typeguards';
/**
* The compose area where messages are written.
*/
export default [
'BrowserService',
'LogService',
'StringService',
'TimeoutService',
'ReceiverService',
'SettingsService',
'$timeout',
'$translate',
'$mdDialog',
'$filter',
'$rootScope',
function(
browserService: BrowserService,
logService: LogService,
stringService: StringService,
timeoutService: TimeoutService,
receiverService: ReceiverService,
settingsService: SettingsService,
$timeout: ng.ITimeoutService,
$translate: ng.translate.ITranslateService,
$mdDialog: ng.material.IDialogService,
$filter: ng.IFilterService,
$rootScope: ng.IRootScopeService
) {
const log = logService.getLogger('ComposeArea-C');
return {
restrict: 'EA',
scope: {
// Callback to get a reference to the initialized ComposeArea instance.
onInit: '=',
// Callback to submit text or file data
submit: '=',
// Callbacks to update typing information
startTyping: '=',
stopTyping: '=',
onTyping: '=',
onKeyDown: '=',
// Reference to initial text and draft
initialData: '=',
// Callback that is called when uploading files
onUploading: '=',
maxTextLength: '=',
receiver: '<receiver',
},
link: function(scope: any, wrapper: JQLite) {
// Constants
const TRIGGER_ENABLED_CSS_CLASS = 'is-enabled';
const TRIGGER_ACTIVE_CSS_CLASS = 'is-active';
// Elements
const select = (selector) => angular.element(wrapper[0].querySelector(selector));
const composeDiv = select('div.compose') as JQuery<HTMLElement>;
const emojiTrigger = select('i.emoji-trigger') as JQuery<HTMLElement>;
const emojiKeyboard = select('.emoji-keyboard') as JQuery<HTMLElement>;
const sendTrigger = select('i.send-trigger') as JQuery<HTMLElement>;
const fileTrigger = select('i.file-trigger') as JQuery<HTMLElement>;
const fileInput = select('input.file-input') as JQuery<HTMLInputElement>;
// Config
// tslint:disable-next-line: no-string-literal
const userConfig: threema.UserConfig = window['UserConfig'];
// Initialize compose area lib
const composeArea = ComposeArea.bind_to(composeDiv[0], userConfig.COMPOSE_AREA_LOG_LEVEL);
if (scope.onInit) {
scope.onInit(composeArea);
}
// Set initial text
if (scope.initialData.initialText) {
composeDiv[0].innerText = scope.initialData.initialText;
scope.initialData.initialText = '';
} else if (scope.initialData.draft !== undefined) {
composeDiv[0].innerText = scope.initialData.draft;
}
let chatBlocked = false;
// Function to update blocking state
function setChatBlocked(blocked: boolean) {
chatBlocked = blocked;
log.debug('Receiver blocked:', blocked);
if (blocked) {
sendTrigger.removeClass(TRIGGER_ENABLED_CSS_CLASS);
emojiTrigger.removeClass(TRIGGER_ENABLED_CSS_CLASS);
fileTrigger.removeClass(TRIGGER_ENABLED_CSS_CLASS);
composeDiv.attr('contenteditable', 'false');
if (emojiKeyboard.hasClass('active')) {
hideEmojiPicker();
}
} else {
if (composeAreaIsEmpty()) {
sendTrigger.removeClass(TRIGGER_ENABLED_CSS_CLASS);
} else {
sendTrigger.addClass(TRIGGER_ENABLED_CSS_CLASS);
}
emojiTrigger.addClass(TRIGGER_ENABLED_CSS_CLASS);
fileTrigger.addClass(TRIGGER_ENABLED_CSS_CLASS);
composeDiv.attr('contenteditable', 'true');
}
}
// Initialize blocking state
setChatBlocked(receiverService.isBlocked(scope.receiver));
// Watch `isBlocked` flag for changes
scope.$watch(
(_scope) => receiverService.isBlocked(_scope.receiver),
(isBlocked: boolean, wasBlocked: boolean) => {
if (isBlocked !== wasBlocked) {
setChatBlocked(isBlocked);
}
},
);
// Typing events
let stopTypingTimer: ng.IPromise<void> = null;
// Callbacks to unsubscribe listeners in $destroy
const unsubscribeListeners = [];
// Determine submit key and listen for changes
let submitKey: threema.ComposeAreaSubmitKey = settingsService.composeArea.getSubmitKey();
const settingsChangedEventHandler = () => {
submitKey = settingsService.composeArea.getSubmitKey();
};
settingsService.settingsChangedEvent.attach(settingsChangedEventHandler);
unsubscribeListeners.push(() => settingsService.settingsChangedEvent.detach(settingsChangedEventHandler));
function stopTyping() {
// We can only stop typing of the timer is set (meaning
// that we started typing earlier)
if (stopTypingTimer !== null) {
// Cancel timer
timeoutService.cancel(stopTypingTimer);
stopTypingTimer = null;
// Send stop typing message
scope.stopTyping();
}
}
function startTyping() {
if (stopTypingTimer === null) {
// If the timer wasn't set previously, we just
// started typing!
scope.startTyping();
} else {
// Cancel timer, we'll re-create it
timeoutService.cancel(stopTypingTimer);
}
// Define a timeout to send the stopTyping event
stopTypingTimer = timeoutService.register(stopTyping, 10000, true, 'stopTyping');
}
// Determine whether field is empty
function composeAreaIsEmpty() {
return composeArea.get_text().length === 0;
}
// Submit the text from the compose area.
//
// Emoji images are converted to their alt text in this process.
function submitText(): Promise<any> {
const text = composeArea.get_text().replace(/\r/g, '');
return new Promise((resolve, reject) => {
const submitTexts = (strings: string[]) => {
const messages: threema.TextMessageData[] = [];
for (const piece of strings) {
messages.push({
text: piece,
});
}
scope.submit('text', messages)
.then(resolve)
.catch(reject);
};
// Check for max length
//
// Note: Messages that use the entire available message size become a
// problem when being quoted, since the quote also becomes part of the
// message. As a workaround, until a better quote system is implemented,
// reduce the max length and the chunk size to counter this. (If the
// message text + quote text are too long, then the quote will be shortened
// in WebClientService.)
const byteLength = (new TextEncoder().encode(text)).length;
const reducedMaxLength = scope.maxTextLength - 30;
if (byteLength > reducedMaxLength) {
const chunkSize = scope.maxTextLength * 0.85;
const pieces: string[] = stringService.byteChunk(text, chunkSize, 50);
const confirm = $mdDialog.confirm()
.title($translate.instant('messenger.MESSAGE_TOO_LONG_SPLIT_SUBJECT'))
.textContent($translate.instant('messenger.MESSAGE_TOO_LONG_SPLIT_BODY', {
max: scope.maxTextLength,
count: pieces.length,
}))
.ok($translate.instant('common.YES'))
.cancel($translate.instant('common.NO'));
$mdDialog.show(confirm).then(function() {
submitTexts(pieces);
}, () => {
reject();
});
} else {
submitTexts([text]);
}
});
}
function sendText(): boolean {
if (!composeAreaIsEmpty()) {
submitText().then(() => {
// Clear compose div
composeArea.clear();
composeArea.focus();
// Send stopTyping event
stopTyping();
// Clear draft
scope.onTyping('');
updateView();
}).catch(() => {
// do nothing
log.warn('Failed to submit text');
});
return true;
}
return false;
}
// Handle typing events
let isComposing = false;
let compositionHasJustEnded = false; // We all love Safari!
function onCompositionStart(ev: CompositionEvent): void {
isComposing = true;
}
function onCompositionEnd(ev: CompositionEvent): void {
isComposing = false;
compositionHasJustEnded = true;
}
function onKeyDown(ev: KeyboardEvent): void {
let submit = false;
switch (submitKey) {
case threema.ComposeAreaSubmitKey.CtrlEnter:
submit = ev.key === 'Enter' && ev.ctrlKey;
break;
case threema.ComposeAreaSubmitKey.Enter: // fallthrough
default:
submit = ev.key === 'Enter' && !ev.shiftKey;
}
// Prevent new-line when submitting
if (submit) {
ev.preventDefault();
}
// If the keydown is handled and aborted outside
if (scope.onKeyDown && scope.onKeyDown(ev) !== true) {
ev.preventDefault();
return;
}
// If the enter key is part of a composition (e.g. when
// entering text with an IME), don't submit the text.
// See https://github.com/threema-ch/threema-web/issues/777
if ((ev as any).isComposing || isComposing || compositionHasJustEnded) {
return;
}
// If a : is pressed, possibly insert emoji
if (ev.key === ':') {
const modified = onEmojiShortcodeKeyPressed(ev, ':', false);
if (modified) {
ev.preventDefault();
return;
}
}
// At link time, the element is not yet evaluated.
// Therefore add following code to end of event loop.
$timeout(() => {
// Check if the text should be submitted
if (submit) {
if (sendText()) {
return;
}
}
updateView();
}, 0);
}
function onKeyUp(ev: KeyboardEvent): void {
compositionHasJustEnded = false;
// If the compose area contains only a single <br>, make it fully empty.
// See also: https://stackoverflow.com/q/14638887/284318
const html = composeDiv[0].innerHTML.trim();
if (html === '<br>') {
composeDiv[0].innerText = '';
}
// Update typing information
const text = composeArea.get_text(true);
if (text.trim().length === 0) {
stopTyping();
scope.onTyping('');
} else {
startTyping();
scope.onTyping(text.trim());
}
updateView();
}
// Function to fetch file contents
// Resolve to ArrayBuffer or reject to ErrorEvent.
function fetchFileListContents(fileList: FileList): Promise<Map<File, ArrayBuffer>> {
return new Promise((resolve) => {
const buffers = new Map<File, ArrayBuffer>();
const fileCounter = fileList.length;
const next = (file: File, res: ArrayBuffer | null, error: any) => {
buffers.set(file, res);
if (buffers.size >= fileCounter) {
resolve(buffers);
}
};
for (let n = 0; n < fileCounter; n++) {
const reader = new FileReader();
const file = fileList.item(n);
reader.onload = function(ev: ProgressEvent) {
next(file, this.result as ArrayBuffer, ev);
};
reader.onerror = function(ev: ProgressEvent) {
// set a null object
next(file, null, ev);
};
reader.onprogress = function(ev: ProgressEvent) {
if (ev.lengthComputable) {
const progress = ((ev.loaded / ev.total) * 100);
scope.onUploading(true, progress, 100 / fileCounter * n);
}
};
reader.readAsArrayBuffer(file);
}
});
}
function uploadFiles(fileList: FileList): void {
scope.onUploading(true, 0, 0);
fetchFileListContents(fileList).then((data: Map<File, ArrayBuffer>) => {
const fileMessages = [];
data.forEach((buffer, file) => {
const fileMessageData: threema.FileMessageData = {
name: file.name,
fileType: file.type,
size: file.size,
data: buffer,
};
// Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1240259
if (browserService.getBrowser().isFirefox(false)) {
if (fileMessageData.name.endsWith('.ogg') && fileMessageData.fileType === 'video/ogg') {
fileMessageData.fileType = 'audio/ogg';
}
}
fileMessages.push(fileMessageData);
});
scope
.submit('file', fileMessages)
.catch((e) => log.error('Could not send file:', e));
scope.onUploading(false);
}).catch((ev: ErrorEvent) => {
log.error('Could not load file:', ev.message);
});
}
// Handle pasting
function onPaste(ev: ClipboardEvent) {
ev.preventDefault();
// If no clipboard data is available, do nothing.
if (!ev.clipboardData) {
return;
}
// Extract pasted items
const items: DataTransferItemList = ev.clipboardData.items;
if (!items) {
return;
}
// Find available types
let fileIdx: number | null = null;
let textIdx: number | null = null;
for (let i = 0; i < items.length; i++) {
if (items[i].kind === 'file' && (items[i].type.indexOf('image/') !== -1 || items[i].type === 'application/x-moz-file')) {
fileIdx = i;
} else if (items[i].kind === 'string' && items[i].type === 'text/plain') {
textIdx = i;
}
}
// Handle pasting of files
if (fileIdx !== null) {
// Read clipboard data as blob
const blob: Blob | null = items[fileIdx].getAsFile();
if (blob !== null) {
// Convert blob to arraybuffer
const reader = new FileReader();
reader.onload = function(progressEvent: ProgressEvent) {
const buffer: ArrayBuffer = this.result as ArrayBuffer;
// Construct file name
let fileName: string;
if ((blob as any).name) {
fileName = (blob as any).name;
} else if (blob.type && blob.type.match(/^[^;]*\//) !== null) {
const fileExt = blob.type.split(';')[0].split('/')[1];
fileName = 'clipboard.' + fileExt;
} else {
log.warn('Pasted file has an invalid MIME type: "' + blob.type + '"');
return;
}
// Send data as file
const fileMessageData: threema.FileMessageData = {
name: fileName,
fileType: blob.type,
size: blob.size,
data: buffer,
};
scope
.submit('file', [fileMessageData])
.catch((msg) => log.error('Could not send file:', msg));
};
reader.readAsArrayBuffer(blob);
} else {
log.error('Could not get item as a blob');
}
// Handle pasting of text
} else if (textIdx !== null) {
const text = ev.clipboardData.getData('text/plain');
if (text) {
const tokens = parseEmoji(text);
for (const token of tokens) {
if (isEmojiInfo(token)) {
insertEmoji(token);
} else {
composeArea.insert_text(token);
}
}
updateView();
}
} else {
log.warn('Nothing pastable found we currently support.')
}
}
// Translate placeholder texts
let regularPlaceholder = '';
let dragoverPlaceholder = '';
$translate('messenger.COMPOSE_MESSAGE').then((translated) => regularPlaceholder = translated);
$translate('messenger.COMPOSE_MESSAGE_DRAGOVER').then((translated) => dragoverPlaceholder = translated);
// Show emoji picker element
function showEmojiPicker() {
// If the emoji picker is triggered too early, it's possible that the picker element
// has not yet been fully loaded (e.g. during UI tests). Therefore enqueue the event
// handler at the end of the event loop.
$timeout(() => {
const emojiPicker = wrapper[0].querySelector('div.twemoji-picker');
// Show
emojiKeyboard.addClass('active');
emojiKeyboard.attr('aria-expanded', 'true');
emojiTrigger.attr('aria-pressed', 'true');
emojiTrigger.addClass(TRIGGER_ACTIVE_CSS_CLASS);
// Find some selectors
const allEmoji = angular.element(emojiPicker.querySelectorAll('.content .em'));
const allEmojiTabs = angular.element(emojiPicker.querySelectorAll('.tab label img'));
const skinSelectors = angular.element(emojiPicker.querySelectorAll('.skins img'));
// Add event handlers
allEmoji.on('click', onEmojiChosen as any);
allEmoji.on('keydown', onEmojiChosen as any);
allEmojiTabs.on('keydown', onEmojiTabSelected as any);
skinSelectors.on('click', onSkintoneSelected as any);
skinSelectors.on('keydown', onSkintoneSelected as any);
// Focus compose area again
composeArea.focus();
});
}
// Hide emoji picker element
function hideEmojiPicker() {
const emojiPicker = wrapper[0].querySelector('div.twemoji-picker');
// Hide
emojiKeyboard.removeClass('active');
emojiKeyboard.attr('aria-expanded', 'false');
emojiTrigger.attr('aria-pressed', 'false');
emojiTrigger.removeClass(TRIGGER_ACTIVE_CSS_CLASS);
// Find some selectors
const allEmoji = angular.element(emojiPicker.querySelectorAll('.content .em'));
const allEmojiTabs = angular.element(emojiPicker.querySelectorAll('.tab label img'));
// Remove event handlers
allEmoji.off('click', onEmojiChosen as any);
allEmoji.off('keydown', onEmojiChosen as any);
allEmojiTabs.off('keydown', onEmojiTabSelected as any);
}
// Emoji trigger is clicked
function onEmojiTrigger(ev: KeyboardEvent): void {
ev.stopPropagation();
if (chatBlocked) {
hideEmojiPicker();
return;
}
// Toggle visibility of picker
if (emojiKeyboard.hasClass('active')) {
hideEmojiPicker();
} else {
showEmojiPicker();
}
}
// Emoji is chosen
function onEmojiChosen(ev: MouseEvent | KeyboardEvent): void {
if (ev.type === 'click' || (isKeyboardEvent(ev) && isActionTrigger(ev))) {
ev.stopPropagation();
if (isKeyboardEvent(ev)) {
ev.preventDefault();
}
insertSingleEmojiString((ev.target as Element).textContent);
updateView();
}
}
// Skintone is chosen
function onSkintoneSelected(ev: MouseEvent | KeyboardEvent): void {
if (ev.type === 'click' || (isKeyboardEvent(ev) && isActionTrigger(ev))) {
ev.stopPropagation();
if (isKeyboardEvent(ev)) {
ev.preventDefault();
}
const tone: string = (ev.target as Element).getAttribute('data-tone');
log.debug(`Skintone selected: Tone ${tone}`);
const emojiPicker = wrapper[0].querySelector('div.twemoji-picker');
emojiPicker.setAttribute('data-skintone', tone);
}
}
// Emoji tab is selected
function onEmojiTabSelected(ev: KeyboardEvent): void {
if (isActionTrigger(ev)) {
// Warning: Hacky
(ev.target as any).parentElement.previousElementSibling.checked = true;
}
}
// Insert a single emoji, passed in as string
function insertSingleEmojiString(emojiString: string): void {
const tokens = parseEmoji(emojiString);
if (tokens.length !== 1) {
throw new Error(`Emoji parsing failed: Expected 1 element, found ${tokens.length}`);
}
const emoji = tokens[0];
if (!isEmojiInfo(emoji)) {
throw new Error(`Emoji parsing failed: Returned text, not emoji info`);
}
insertEmoji(emoji);
}
// Insert a single emoji
function insertEmoji(emoji: threema.EmojiInfo): void {
const img: HTMLElement = composeArea.insert_image(emoji.imgPath, emoji.emojiString, 'em');
img.setAttribute('data-c', emoji.codepoint);
img.draggable = false;
img.ondragstart = () => false;
}
// The emoji shortcode trigger (:) was inserted. Return a boolean
// indicating whether the compose area contents were modified.
//
// The `alreadyProcessed` indicates whether the key has already
// been processed in the DOM (onKeyUp) or not (onKeyDown).
function onEmojiShortcodeKeyPressed(ev, trigger: string, alreadyProcessed: boolean): boolean {
const word = composeArea.get_word_at_caret();
if (word === undefined) {
return false;
}
let before = word.before();
const after = word.after();
if (!alreadyProcessed) {
before += trigger;
}
if (after.length === 0 && before.length > 2) {
if (before.startsWith(trigger) && before.endsWith(trigger)) {
const trimmed = before.substr(1, before.length - 2);
const unicodeEmoji = shortnameToUtf8(trimmed);
if (unicodeEmoji !== null) {
composeArea.select_word_at_caret();
composeArea.store_selection_range();
insertSingleEmojiString(unicodeEmoji);
return true;
}
}
}
return false;
}
// TODO
// function insertMention(mentionString, posFrom?: number, posTo?: number): void {
// const mentionElement = ($filter('mentionify') as any)(mentionString) as string;
// insertHTMLElement(mentionString, mentionElement, posFrom, posTo);
// }
// File trigger is clicked
function onFileTrigger(ev: UIEvent): void {
ev.preventDefault();
ev.stopPropagation();
if (chatBlocked) {
return;
}
const input = wrapper[0].querySelector('.file-input') as HTMLInputElement;
input.click();
}
function onSendTrigger(ev: UIEvent): boolean {
ev.preventDefault();
ev.stopPropagation();
if (chatBlocked) {
return;
}
return sendText();
}
// File(s) are uploaded via input field
function onFileSelected() {
uploadFiles(this.files);
fileInput.val('');
}
// Set all correct styles
function updateView() {
if (composeAreaIsEmpty()) {
sendTrigger.removeClass(TRIGGER_ENABLED_CSS_CLASS);
} else {
sendTrigger.addClass(TRIGGER_ENABLED_CSS_CLASS);
}
}
// Handle typing events
composeDiv.on('compositionstart', onCompositionStart as any);
composeDiv.on('compositionend', onCompositionEnd as any);
composeDiv.on('keydown', onKeyDown as any);
composeDiv.on('keyup', onKeyUp as any);
// Handle selection change
document.addEventListener('selectionchange', () => {
composeArea.store_selection_range();
});
// Handle paste event
composeDiv.on('paste', onPaste as any);
// Handle click on emoji trigger
emojiTrigger.on('click', onEmojiTrigger as any);
emojiTrigger[0].addEventListener('keypress', (ev: KeyboardEvent) => {
if (isActionTrigger(ev)) {
$rootScope.$apply(() => {
onEmojiTrigger(ev);
});
}
});
// Handle click on file trigger
fileTrigger.on('click', onFileTrigger as any);
fileTrigger[0].addEventListener('keypress', (ev: any) => {
if (isActionTrigger(ev)) {
$rootScope.$apply(() => {
onFileTrigger(ev);
});
}
});
// Handle file uploads
fileInput.on('change', onFileSelected);
// Handle click on send trigger
sendTrigger.on('click', onSendTrigger as any);
sendTrigger[0].addEventListener('keypress', (ev: any) => {
if (isActionTrigger(ev)) {
$rootScope.$apply(() => {
onSendTrigger(ev);
});
}
});
updateView();
// Send "stop typing" message when switching tab or window
const stopTypingOnBlur = () => stopTyping();
window.addEventListener('blur', stopTypingOnBlur);
unsubscribeListeners.push(() => window.removeEventListener('blur', stopTypingOnBlur));
// Listen to broadcasts
unsubscribeListeners.push($rootScope.$on('onQuoted', (event: ng.IAngularEvent, args: any) => {
composeArea.focus();
}));
// When closing the chat view...
scope.$on('$destroy', () => {
// ...unsubscribe listeners...
unsubscribeListeners.forEach((u) => u());
// ...and send "stop typing" message.
stopTyping();
});
},
// tslint:disable:max-line-length
template: `
<div>
<div>
<i class="md-primary emoji-trigger trigger is-enabled material-icons" role="button" aria-label="emoji" aria-pressed="false" tabindex="0">tag_faces</i>
</div>
<div>
<div
class="compose"
id="composeDiv"
contenteditable
autofocus
data-gramm="false"
translate
translate-attr-data-placeholder="messenger.COMPOSE_MESSAGE"
translate-attr-aria-label="messenger.COMPOSE_MESSAGE"
tabindex="0"
></div>
</div>
<div>
<i class="md-primary send-trigger trigger material-icons" role="button" aria-label="send" tabindex="0">send</i>
<i class="md-primary file-trigger trigger is-enabled material-icons" role="button" aria-label="attach file" tabindex="0">attach_file</i>
<input class="file-input" type="file" style="visibility: hidden" multiple>
</div>
</div>
<div class="emoji-keyboard" aria-expanded="false">
<ng-include src="'partials/emoji-picker.html'" include-replace></ng-include>
</div>
`,
};
},
];