Repository navigation
Expand file tree
/
Copy pathcompose.js
More file actions
720 lines (624 loc) · 20.3 KB
/
Copy pathcompose.js
File metadata and controls
720 lines (624 loc) · 20.3 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
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*global Settings, Utils, Attachment, AttachmentMenu, MozActivity, SMIL,
ThreadUI */
/*exported Compose */
'use strict';
/**
* Handle UI specifics of message composition. Namely,
* resetting (auto manages placeholder text), getting
* message content, and message size
*/
var Compose = (function() {
var placeholderClass = 'placeholder';
var attachmentClass = 'attachment-container';
var slice = Array.prototype.slice;
var attachments = new WeakMap();
// will be defined in init
var dom = {
form: null,
message: null,
subject: null,
sendButton: null,
attachButton: null
};
var handlers = {
input: [],
type: []
};
var state = {
empty: true,
maxLength: null,
size: null,
lastScrollPosition: 0,
resizing: false,
// 'sms' or 'mms'
type: 'sms'
};
var subject = {
isVisible: false,
toggle: function sub_toggle() {
this.isVisible ? this.hide() : this.show();
},
show: function sub_show() {
dom.subject.classList.remove('hide');
this.isVisible = true;
dom.subject.focus();
Compose.updateType();
onContentChanged();
},
hide: function sub_hide() {
dom.subject.classList.add('hide');
this.isVisible = false;
dom.message.focus();
Compose.updateType();
onContentChanged();
},
clear: function sub_clear() {
dom.subject.value = '';
dom.subject.classList.add('hide');
this.isVisible = false;
},
getContent: function sub_getContent() {
// Only send value if subject is showing. If not, send empty string
// We need to transform any linebreak or into a single space
return subject.isShowing ?
dom.subject.value.replace(/\n\s*/g, ' ') : '';
},
setContent: function sub_setContent(content) {
dom.subject.value = content;
},
getMaxLength: function sub_getMaxLength() {
return dom.subject.maxLength;
},
get isEmpty() {
return !dom.subject.value.length;
},
get isShowing() {
return this.isVisible;
}
};
// anytime content changes - takes a parameter to check for image resizing
function onContentChanged(duck) {
// Track when content is edited for draft replacement case
if (ThreadUI.draft) {
ThreadUI.draft.isEdited = true;
}
// if the duck is an image attachment, handle resizes
if (duck instanceof Attachment && duck.type === 'img') {
return imageAttachmentsHandling();
}
var messageHasFrames = !!dom.message.querySelector('iframe');
var isEmptyMessage = !dom.message.textContent.length && !messageHasFrames;
var isEmptySubject = subject.isEmpty;
if (isEmptyMessage) {
var brs = dom.message.getElementsByTagName('br');
// firefox will keep an extra <br> in there
if (brs.length > 1) {
isEmptyMessage = false;
}
}
// Placeholder management
var placeholding = dom.message.classList.contains(placeholderClass);
if (placeholding && !isEmptyMessage) {
dom.message.classList.remove(placeholderClass);
}
if (!placeholding && isEmptyMessage) {
dom.message.classList.add(placeholderClass);
}
// Send button management
/* The send button should be enabled only in the situations where:
* - The subject is showing and is not empty (it has text)
* - The message is not empty (it has text or attachment)
*/
if ((isEmptyMessage && !subject.isShowing) ||
(isEmptyMessage && subject.isShowing && isEmptySubject)) {
8000
compose.disable(true);
state.empty = true;
} else {
compose.disable(false);
state.empty = false;
}
compose.updateType();
trigger.call(compose, 'input', new CustomEvent('input'));
}
function composeKeyEvents(e) {
// if locking and no-backspace pressed, cancel
if (compose.lock && e.which !== 8) {
e.preventDefault();
} else {
// trigger a recompute of size on the keypresses
state.size = null;
compose.lock = false;
}
}
function trigger(type) {
var fns = handlers[type];
var args = slice.call(arguments, 1);
if (fns && fns.length) {
for (var i = 0; i < fns.length; i++) {
fns[i].apply(compose, args);
}
}
}
function insert(item) {
var fragment = document.createDocumentFragment();
// trigger recalc on insert
state.size = null;
if (item.render) { // it's an Attachment
var node = item.render();
attachments.set(node, item);
fragment.appendChild(node);
} else if (item.nodeName === 'IFRAME') {
// this iframe is generated by us
fragment.appendChild(item);
} else if (typeof item === 'string') {
item.split('\n').forEach(function(line) {
fragment.appendChild(document.createTextNode(line));
fragment.appendChild(document.createElement('br'));
});
fragment.lastElementChild.remove();
}
return fragment;
}
function imageAttachmentsHandling() {
// There is need to resize image attachment if total compose
// size doen't exceed mms size limitation.
if (Compose.size < Settings.mmsSizeLimitation) {
onContentChanged();
return;
}
var nodes = dom.message.querySelectorAll('iframe');
var imgNodes = [];
var done = 0;
Array.prototype.forEach.call(nodes, function findImgNodes(node) {
var item = attachments.get(node);
if (item.type === 'img') {
imgNodes.push(node);
}
});
// Total number of images < 3
// => Set max image size to 2/5 message size limitation.
// Total number of images >= 3
// => Set max image size to 1/5 message size limitation.
var images = imgNodes.length;
var limit = images > 2 ? Settings.mmsSizeLimitation * 0.2 :
Settings.mmsSizeLimitation * 0.4;
function imageSized() {
if (++done === images) {
state.resizing = false;
onContentChanged();
}
}
state.resizing = true;
imgNodes.forEach(function(node) {
var item = attachments.get(node);
if (item.blob.size < limit) {
imageSized();
} else {
Utils.getResizedImgBlob(item.blob, limit, function(resizedBlob) {
// trigger recalc when resized
state.size = null;
item.blob = resizedBlob;
var newNode = item.render();
attachments.set(newNode, item);
if (dom.message.contains(node)) {
dom.message.insertBefore(newNode, node);
dom.message.removeChild(node);
}
imageSized();
});
}
});
onContentChanged();
}
var compose = {
init: function composeInit(formId) {
dom.form = document.getElementById(formId);
dom.message = dom.form.querySelector('[contenteditable]');
dom.subject = document.getElementById('messages-subject-input');
dom.sendButton = document.getElementById('messages-send-button');
dom.attachButton = document.getElementById('messages-attach-button');
dom.optionsMenu = document.getElementById('attachment-options-menu');
// update the placeholder, send button and Compose.type
dom.message.addEventListener('input', onContentChanged);
dom.subject.addEventListener('input', onContentChanged);
// we need to bind to keydown & keypress because of #870120
dom.message.addEventListener('keydow
10BC8
n', composeKeyEvents);
dom.message.addEventListener('keypress', composeKeyEvents);
dom.message.addEventListener('click',
this.onAttachmentClick.bind(this));
dom.optionsMenu.addEventListener('click',
this.onAttachmentMenuClick.bind(this));
dom.attachButton.addEventListener('click',
this.onAttachClick.bind(this));
this.clearListeners();
this.clear();
this.on('type', this.onTypeChange);
return this;
},
on: function(type, handler) {
if (handlers[type]) {
handlers[type].push(handler);
}
return this;
},
off: function(type, handler) {
if (handlers[type]) {
var index = handlers[type].indexOf(handler);
if (index !== -1) {
handlers[type].splice(index, 1);
}
}
return this;
},
clearListeners: function() {
for (var type in handlers) {
handlers[type] = [];
}
},
getContent: function() {
var content = [];
var node;
for (node = dom.message.firstChild; node; node = node.nextSibling) {
// hunt for an attachment in the WeakMap and append it
var attachment = attachments.get(node);
if (attachment) {
content.push(attachment);
continue;
}
var last = content.length - 1;
var text = node.textContent;
// Bug 877141 - contenteditable wil insert non-break spaces when
// multiple consecutive spaces are entered, we don't want them.
if (text) {
text = text.replace(/\u00A0/g, ' ');
}
if (node.nodeName == 'BR') {
if (node === dom.message.lastChild) {
continue;
}
text = '\n';
}
// append (if possible) text to the last entry
if (text.length) {
if (typeof content[last] === 'string') {
content[last] += text;
} else {
content.push(text);
}
}
}
return content;
},
getSubject: function() {
return subject.getContent();
},
toggleSubject: function() {
subject.toggle();
},
/** Render draft
*
* @param {Draft} draft Draft to be loaded into the composer.
*
*/
fromDraft: function(draft) {
// Clear out the composer
this.clear();
// If we don't have a draft, return only having cleared the composer
if (!draft) {
return;
}
if (draft.subject) {
dom.subject.value = draft.subject;
subject.toggle();
}
// draft content is an array
draft.content.forEach(function(fragment) {
// If the fragment is an attachment
// use the stored content to instantiate a new Attachment object
// to be properly rendered after a cold start for the app
if (fragment.blob) {
fragment = new Attachment(fragment.blob, {
isDraft: true
});
}
// Append each fragment in order to the composer
Compose.append(fragment);
}, Compose);
this.focus();
},
/** Render message (sms or mms)
*
* @param {message} message Full message to be loaded into the composer.
*
*/
fromMessage: function(message) {
this.clear();
if (message.type === 'mms') {
if (message.subject) {
subject.setContent(message.subject);
subject.show();
}
SMIL.parse(message, function(elements) {
elements.forEach(function(element) {
if (element.blob) {
var attachment = new Attachment(element.blob, {
name: element.name,
isDraft: true
});
this.append(attachment);
}
if (element.text) {
this.append(element.text);
}
}, this);
this.ignoreEvents = false;
this.focus();
}.bind(this));
this.ignoreEvents = true;
} else {
this.append(message.body);
this.focus();
}
},
getText: function() {
var out = this.getContent().filter(function(elem) {
return (typeof elem === 'string');
});
return out.join('');
},
isEmpty: function() {
return state.empty;
},
/** Stop further input because the max size is exceded
*/
lock: false,
disable: function(state) {
dom.sendButton.disabled = state;
return this;
},
scrollToTarget: function(target) {
// target can be an element or a selection range
var targetRect = target.getBoundingClientRect();
// put the middle of the target at the middle of the container box
var containerRect = dom.message.getBoundingClientRect();
var offset = (targetRect.top + targetRect.height / 2) -
(containerRect.top + containerRect.height / 2);
// we += because the scrollTop that was set is already compensated
// with the getBoundingClientRect()
dom.message.scrollTop += offset;
},
scrollMessageContent: function() {
if (document.activeElement === dom.message) {
// we just got the focus: ensure the caret is visible
var range = window.getSelection().getRangeAt(0);
if (range.collapsed) {
// We can't get the bounding client rect of a collapsed range,
// so let's insert a temporary node to get the caret position.
range.insertNode(document.createElement('span'));
this.scrollToTarget(range);
range.deleteContents();
} else {
this.scrollToTarget(range);
}
state.lastScrollPosition = dom.message.scrollTop;
} else {
// we just lost the focus: restore the last scroll position
dom.message.scrollTop = state.lastScrollPosition;
}
},
/** Writes node to composition element
* @param {mixed} item Html, DOMNode, or attachment to add
* to composition element.
* @param {Boolean} position True to append, false to prepend or
* undefined/null for auto (at cursor).
*/
prepend: function(item) {
var fragment = insert(item);
// If the first element is a <br>, it needs to stay first
// insert after it but before everyting else
if (dom.message.firstChild && dom.message.firstChild.nodeName === 'BR') {
dom.message.insertBefore(fragment, dom.message.childNodes[1]);
} else {
dom.message.insertBefore(fragment, dom.message.childNodes[0]);
}
onContentChanged(item);
return this;
},
append: function(item) {
var fragment = insert(item);
if (document.activeElement === dom.message) {
// insert element at caret position
var range = window.getSelection().getRangeAt(0);
var firstNodes = fragment.firstChild;
range.deleteContents();
range.insertNode(fragment);
this.scrollToTarget(range);
dom.message.focus();
range.setStartAfter(firstNodes);
} else {
// insert element at the end of the Compose area
dom.message.insertBefore(fragment, dom.message.lastChild);
this.scrollToTarget(dom.message.lastChild);
}
onContentChanged(item);
return this;
},
clear: function() {
dom.message.innerHTML = '<br>';
subject.clear();
state.resizing = state.full = false;
state.size = 0;
state.empty = true;
onContentChanged();
return this;
},
focus: function() {
dom.message.focus();
return this;
},
updateType: function() {
if ((subject.isShowing && !subject.isEmpty) ||
!!dom.message.querySelector('iframe')) {
this.type = 'mms';
} else {
this.type = 'sms';
}
},
onAttachClick: function thui_onAttachClick(event) {
var request = this.requestAttachment();
request.>
request. {
if (err === 'file too large') {
alert(navigator.mozL10n.get('file-too-large'));
}
};
},
onAttachmentClick: function thui_onAttachmentClick(event) {
if (event.target.classList.contains(attachmentClass) && !state.resizing) {
this.currentAttachmentDOM = event.target;
this.currentAttachment = attachments.get(event.target);
AttachmentMenu.open(this.currentAttachment);
}
},
onAttachmentMenuClick: function thui_onAttachmentMenuClick(event) {
event.preventDefault();
switch (event.target.id) {
case 'attachment-options-view':
this.currentAttachment.view();
break;
case 'attachment-options-remove':
attachments.delete(this.currentAttachmentDOM);
dom.message.removeChild(this.currentAttachmentDOM);
state.size = null;
onContentChanged();
AttachmentMenu.close();
break;
case 'attachment-options-replace':
var request = this.requestAttachment();
request. replaceAttachmentWith(newAttachment) {
var fragment = insert(newAttachment);
dom.message.insertBefore(fragment, this.currentAttachmentDOM);
dom.message.removeChild(this.currentAttachmentDOM);
onContentChanged(newAttachment);
AttachmentMenu.close();
}).bind(this);
request. {
if (err === 'file too large') {
alert(navigator.mozL10n.get('file-too-large'));
}
};
break;
case 'attachment-options-cancel':
AttachmentMenu.close();
break;
}
},
onTypeChange: function c_onTypeChange() {
if (this.type === 'sms') {
dom.message.setAttribute('x-inputmode', '-moz-sms');
} else {
dom.message.removeAttribute('x-inputmode');
}
},
/** Initiates a 'pick' MozActivity allowing the user to create an
* attachment
* @return {Object} requestProxy A proxy for the underlying DOMRequest API.
* An "onsuccess" and/or "onerror" callback
* method may optionally be defined on this
* object.
*/
requestAttachment: function() {
// Mimick the DOMRequest API
var requestProxy = {};
var activityData = {
type: ['image/*', 'audio/*', 'video/*']
};
var activity;
if (Settings.mmsSizeLimitation) {
activityData.maxFileSizeBytes = Settings.mmsSizeLimitation;
}
activity = new MozActivity({
name: 'pick',
data: activityData
});
activity. {
var result = activity.result;
if (Settings.mmsSizeLimitation &&
result.blob.size > Settings.mmsSizeLimitation &&
Utils.typeFromMimeType(result.blob.type) !== 'img') {
if (typeof requestProxy. 'function') {
requestProxy.onerror('file too large');
}
return;
}
if (typeof requestProxy. 'function') {
requestProxy.onsuccess(new Attachment(result.blob, {
name: result.name,
isDraft: true
}));
}
};
// Re-throw Gecko-level errors
activity. {
if (typeof requestProxy. 'function') {
requestProxy.onerror.apply(requestProxy, arguments);
}
};
return requestProxy;
}
};
Object.defineProperty(compose, 'type', {
get: function composeGetType() {
return state.type;
},
set: function composeSetType(value) {
// reject invalid types
if (!(value === 'sms' || value === 'mms')) {
return state.type;
}
if (value !== state.type) {
var event = new CustomEvent('type');
state.type = value;
trigger.call(this, 'type', event);
}
return state.type;
}
});
Object.defineProperty(compose, 'size', {
get: function composeGetSize() {
if (state.size === null) {
state.size = this.getContent().reduce(function(sum, content) {
if (typeof content === 'string') {
return sum + content.length;
} else {
return sum + content.size;
}
}, 0);
}
return state.size;
}
});
Object.defineProperty(compose, 'isResizing', {
get: function composeGetResizeState() {
return state.resizing;
}
});
Object.defineProperty(compose, 'isSubjectVisible', {
get: function composeGetResizeState() {
return subject.isShowing;
}
});
Object.defineProperty(compose, 'subjectMaxLength', {
get: function composeGetResizeState() {
return subject.getMaxLength();
}
});
Object.defineProperty(compose, 'ignoreEvents', {
set: function composeIgnoreEvents(value) {
dom.message.classList.toggle('ignoreEvents', value);
}
});
return compose;
}());