Repository navigation
Expand file tree
/
Copy pathcompose.js
More file actions
592 lines (509 loc) · 17.5 KB
/
Copy pathcompose.js
File metadata and controls
592 lines (509 loc) · 17.5 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
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'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,
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'
};
// anytime content changes - takes a parameter to check for image resizing
function onContentChanged(duck) {
// if the duck is an image attachment, handle resizes
if (duck instanceof Attachment && duck.type === 'img') {
return imageAttachmentsHandling();
}
var textLength = dom.message.textContent.length;
var empty = !textLength;
var hasFrames = !!dom.message.querySelector('iframe');
if (empty) {
var brs = dom.message.getElementsByTagName('br');
// firefox will keep an extra <br> in there
if (brs.length > 1 || hasFrames) {
empty = false;
}
}
var placeholding = dom.message.classList.contains(placeholderClass);
if (placeholding && !empty) {
dom.message.classList.remove(placeholderClass);
compose.disable(false);
state.empty = false;
}
if (!placeholding && empty) {
dom.message.classList.add(placeholderClass);
compose.disable(true);
state.empty = true;
}
if (hasFrames && state.type === 'sms') {
compose.type = 'mms';
}
if (!hasFrames && state.type === 'mms') {
compose.type = 'sms';
}
trigger.call(this, '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(this, 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') {
var container = document.createElement('div');
container.innerHTML = item;
[].forEach.call(container.childNodes, function(node) {
if (node.nodeName === 'BR') {
fragment.appendChild(document.createElement('br'));
}
else if (node.nodeType === Node.TEXT_NODE) {
fragment.appendChild(node);
}
});
}
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.sendButton = document.getElementById('messages-send-button');
dom.attachButton = document.getElementById('messages-attach-button');
dom.optionsMenu = document.getElementById('attachment-options-menu');
// update the placeholder after input
dom.message.addEventListener('input', onContentChanged);
// we need to bind to keydown & keypress because of #870120
dom.message.addEventListener('keydown', 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;
var i;
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;
},
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>';
state.resizing = state.full = false;
state.size = 0;
state.empty = true;
onContentChanged();
return this;
},
focus: function() {
dom.message.focus();
return this;
},
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') {
var originalBlob = result.blob;
var attachmentOptions = {
name: result.name,
isDraft: true
};
// We ought to just be able to call the onsuccess function now.
// But to workaround bug 944276, if we get a blob that is not a File
// and is not a big image that we are going to resize we need to
// make a private copy of it. Otherwise, it won't work if we
// pass it to another activity (like the open activity of Gallery).
if (originalBlob instanceof File ||
(originalBlob.type.startsWith('image/') &&
Settings.mmsSizeLimitation &&
originalBlob.size > Settings.mmsSizeLimitation)) {
// Safe to call onsuccess with the original blob in this case
requestProxy.onsuccess(new Attachment(originalBlob,
attachmentOptions));
} else {
// Make a local copy of the blob before calling onsuccess
// to workaround bug 944276.
var reader = new FileReader();
reader. {
var buffer = reader.result;
var copyBlob = new Blob([buffer], { type: originalBlob.type });
requestProxy.onsuccess(new Attachment(copyBlob,
attachmentOptions));
};
reader. {
// This should never happen, but if it does, we'll try
// to use the original blob for lack of any better alternative.
console.error('Failed to copy blob.');
requestProxy.onsuccess(new Attachment(originalBlob,
attachmentOptions));
};
reader.readAsArrayBuffer(originalBlob);
}
}
};
// 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) {
return state.size;
}
return state.size = this.getContent().reduce(function(sum, content) {
if (typeof content === 'string') {
return sum + content.length;
} else {
return sum + content.size;
}
}, 0);
}
});
Object.defineProperty(compose, 'isResizing', {
get: function composeGetResizeState() {
return state.resizing;
}
});
return compose;
}());