forked from mozilla-b2g/gaia
/
thread_ui.js
1563 lines (1349 loc) · 48.3 KB
/
thread_ui.js
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
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function(global) {
'use strict';
var attachmentMap = new WeakMap();
function thui_mmsAttachmentClick(target) {
var attachment = attachmentMap.get(target);
if (!attachment) {
return false;
}
var activity = new MozActivity({
name: 'open',
data: {
allowSave: true,
blob: attachment.blob,
filename: attachment.name,
type: attachment.blob.type
}
});
activity.onerror = function() {
console.error('error with open activity', this.error.name);
// TODO: Add an alert here with a string saying something like
// "There is no application available to open this file type"
};
return true;
}
// reduce the Composer.getContent() into slide format used by SMIL.generate some
// day in the future, we should make the SMIL and Compose use the same format
function thui_generateSmilSlides(slides, content) {
var length = slides.length;
if (typeof content === 'string') {
if (!length || slides[length - 1].text) {
slides.push({
text: content
});
} else {
slides[length - 1].text = content;
}
} else {
slides.push({
blob: content.blob,
name: content.name
});
}
return slides;
}
var ThreadUI = global.ThreadUI = {
// Time buffer for the 'last-messages' set. In this case 10 min
LAST_MESSSAGES_BUFFERING_TIME: 10 * 60 * 1000,
CHUNK_SIZE: 10,
// duration of the notification that message type was converted
CONVERTED_MESSAGE_DURATION: 3000,
recipients: null,
init: function thui_init() {
var _ = navigator.mozL10n.get;
var templateIds = ['contact', 'highlight', 'message', 'not-downloaded',
'recipient'];
Compose.init('messages-compose-form');
AttachmentMenu.init('attachment-options-menu');
// Fields with 'messages' label
[
'container', 'to-field', 'recipients-list',
'header-text', 'recipient', 'input', 'compose-form',
'check-all-button', 'uncheck-all-button',
'contact-pick-button', 'back-button', 'send-button', 'attach-button',
'delete-button', 'cancel-button',
'edit-mode', 'edit-form', 'tel-form',
'max-length-notice', 'convert-notice'
].forEach(function(id) {
this[Utils.camelCase(id)] = document.getElementById('messages-' + id);
}, this);
this.mainWrapper = document.getElementById('main-wrapper');
// Allow for stubbing in environments that do not implement the
// `navigator.mozMobileMessage` API
this._mozMobileMessage = navigator.mozMobileMessage ||
window.DesktopMockNavigatormozMobileMessage;
// In case of input, we have to resize the input following UX Specs.
Compose.on('input', this.messageComposerInputHandler.bind(this));
Compose.on('type', this.messageComposerTypeHandler.bind(this));
this.toField.addEventListener(
'keypress', this.toFieldKeypress.bind(this), true
);
this.toField.addEventListener(
'input', this.toFieldInput.bind(this), true
);
// Handlers for send button and avoiding to hide keyboard instead
this.sendButton.addEventListener(
'mousedown', function mouseDown(event) {
event.preventDefault();
event.target.classList.add('active');
}
);
this.sendButton.addEventListener(
'mouseup', function mouseUp(event) {
event.target.classList.remove('active');
}
);
this.sendButton.addEventListener(
'mouseout', function mouseOut(event) {
event.target.classList.remove('active');
}
);
this.sendButton.addEventListener(
'click', this.onSendClick.bind(this)
);
this.container.addEventListener(
'scroll', this.manageScroll.bind(this)
);
this.backButton.addEventListener(
'click', this.back.bind(this)
);
this.checkAllButton.addEventListener(
'click', this.toggleCheckedAll.bind(this, true)
);
this.uncheckAllButton.addEventListener(
'click', this.toggleCheckedAll.bind(this, false)
);
this.cancelButton.addEventListener(
'click', this.cancelEdit.bind(this)
);
this.deleteButton.addEventListener(
'click', this.delete.bind(this)
);
/**
* WARN: This is incorrect. Tapping the header should
* open the participants view:
*
* https://bugzilla.mozilla.org/show_bug.cgi?id=870069
*
*/
this.headerText.addEventListener(
'click', this.activateContact.bind(this)
);
// When 'focus' we have to remove 'edit-mode' in the recipient
this.input.addEventListener(
'focus', this.messageComposerFocusHandler.bind(this)
);
this.container.addEventListener(
'click', this.handleEvent.bind(this)
);
this.container.addEventListener(
'contextmenu', this.handleEvent.bind(this)
);
this.editForm.addEventListener(
'submit', this.handleEvent.bind(this)
);
this.composeForm.addEventListener(
'submit', this.handleEvent.bind(this)
);
// For picking a contact from Contacts. It's mouse down for
// avoiding weird effect of keyboard, as in 'send' button.
this.contactPickButton.addEventListener(
'mousedown', this.requestContact.bind(this)
);
this.tmpl = templateIds.reduce(function(tmpls, name) {
tmpls[Utils.camelCase(name)] =
Utils.Template('messages-' + name + '-tmpl');
return tmpls;
}, {});
Utils.startTimeHeaderScheduler();
this.initRecipients();
// Initialized here, but used in ThreadUI.cleanFields
this.previousHash = null;
// Cache fixed measurement while init
var style = window.getComputedStyle(this.input, null);
this.INPUT_PADDING = parseInt(style.getPropertyValue('padding-top'), 10) +
parseInt(style.getPropertyValue('padding-bottom'), 10);
},
// Initialize Recipients list and Recipients.View (DOM)
initRecipients: function thui_initRecipients() {
function recipientsChanged(count) {
var message = count ?
(count > 1 ? 'recipient[many]' : 'recipient[one]') :
'newMessage';
this.headerText.textContent = navigator.mozL10n.get(message, {
n: count
});
// check for enable send whenever recipients change
this.enableSend();
// Clean search result after recipient count change.
this.container.textContent = '';
}
if (this.recipients) {
this.recipients.length = 0;
this.recipients.focus();
} else {
this.recipients = new Recipients({
outer: 'messages-to-field',
inner: 'messages-recipients-list',
template: this.tmpl.recipient
});
this.recipients.on('add', recipientsChanged.bind(this));
this.recipients.on('remove', recipientsChanged.bind(this));
}
this.container.textContent = '';
},
initSentAudio: function thui_initSentAudio() {
if (this.sentAudio)
return;
this.sentAudioKey = 'message.sent-sound.enabled';
this.sentAudio = new Audio('/sounds/sent.ogg');
this.sentAudio.mozAudioChannelType = 'notification';
this.sentAudioEnabled = false;
// navigator.mozSettings may not be defined in all environments
if (navigator.mozSettings) {
var req = navigator.mozSettings.createLock().get(this.sentAudioKey);
req.onsuccess = (function onsuccess() {
this.sentAudioEnabled = req.result[this.sentAudioKey];
}).bind(this);
navigator.mozSettings.addObserver(this.sentAudioKey, (function(e) {
this.sentAudioEnabled = e.settingValue;
}).bind(this));
}
},
// Method for setting the body of a SMS/MMS from activity
setMessageBody: function thui_setMessageBody(value) {
Compose.clear();
Compose.append(value);
},
messageComposerInputHandler: function thui_messageInputHandler(event) {
this.updateInputHeight();
this.enableSend();
},
messageComposerFocusHandler: function thui_messageInputHandler(event) {
var node = this.recipientsList.lastChild;
var typed;
// Restore the recipients list input area to
// single line view.
this.recipients.visible('singleline', {
refocus: this.input,
noPreserve: true
});
do {
if (node.isPlaceholder) {
typed = node.textContent.trim();
// If the user actually typed something,
// assume it's a manually entered recipient.
// Push a recipient into the recipients
// list with the left behind entry.
if (typed) {
this.recipients.add({
name: typed,
number: typed,
source: 'manual'
});
break;
}
}
} while (node = node.previousSibling);
},
// Message composer type changed:
messageComposerTypeHandler: function thui_messageComposerTypeHandler(event) {
// if we are changing to sms type, we might want to cancel
if (Compose.type === 'sms') {
if (this.updateSmsSegmentLimit()) {
return event.preventDefault();
}
}
var message = navigator.mozL10n.get('converted-to-' + Compose.type);
this.convertNotice.querySelector('p').textContent = message;
this.convertNotice.classList.remove('hide');
if (this._convertNoticeTimeout) {
clearTimeout(this._convertNoticeTimeout);
}
this._convertNoticeTimeout = setTimeout(function hideConvertNotice() {
this.convertNotice.classList.add('hide');
}.bind(this), this.CONVERTED_MESSAGE_DURATION);
},
// Create a recipient from contacts activity.
requestContact: function thui_requestContact() {
if (typeof MozActivity === 'undefined') {
console.log('MozActivity unavailable');
return;
}
var activity = new MozActivity({
name: 'pick',
data: {
type: 'webcontacts/contact'
}
});
activity.onsuccess = (function() {
var details = Utils.getContactDetails('', activity.result);
this.recipients.add({
name: details.title || details.number || activity.result.name[0],
number: details.number || activity.result.number,
source: 'contacts'
});
}).bind(this);
activity.onerror = (function(e) {
console.log('WebActivities unavailable? : ' + e);
}).bind(this);
},
// Method for updating the header when needed
updateComposerHeader: function thui_updateComposerHeader() {
var recipientCount = this.recipients.length;
if (recipientCount > 0) {
this.contactPickButton.classList.add('disabled');
this.headerText.textContent =
navigator.mozL10n.get('recipient', {
n: recipientCount
});
} else {
this.contactPickButton.classList.remove('disabled');
this.headerText.textContent = navigator.mozL10n.get('newMessage');
}
// Check if we need to enable send button.
this.enableSend();
},
// We define an edge for showing the following chunk of elements
manageScroll: function thui_manageScroll(oEvent) {
// kEdge will be the limit (in pixels) for showing the next chunk
var kEdge = 30;
var currentScroll = this.container.scrollTop;
if (currentScroll < kEdge) {
var previous = this.container.scrollHeight;
this.showChunkOfMessages(this.CHUNK_SIZE);
// We update the scroll to the previous position
// taking into account the previous offset to top
// and the current height due to we have added a new
// chunk of visible messages
this.container.scrollTop =
(this.container.scrollHeight - previous) + currentScroll;
}
},
setInputMaxHeight: function thui_setInputMaxHeight() {
// Method for initializing the maximum height
// Set the input height to:
// view height - (vertical padding (+ to field height if edit new message))
var viewHeight = this.container.offsetHeight;
var adjustment = this.INPUT_PADDING;
if (window.location.hash === '#new') {
adjustment += this.toField.offsetHeight;
}
this.input.style.maxHeight = (viewHeight - adjustment) + 'px';
},
back: function thui_back() {
var goBack = (function() {
this.stopRendering();
if (Compose.isEmpty()) {
window.location.hash = '#thread-list';
return;
}
if (window.confirm(navigator.mozL10n.get('discard-sms'))) {
this.cleanFields(true);
window.location.hash = '#thread-list';
}
}).bind(this);
// We're waiting for the keyboard to disappear before animating back
if (this.isKeyboardDisplayed()) {
window.addEventListener('resize', function keyboardHidden() {
window.removeEventListener('resize', keyboardHidden);
window.clearTimeout(setTimer);
goBack();
});
var setTimer = window.setTimeout(goBack, 400);
} else {
goBack();
}
},
isKeyboardDisplayed: function thui_isKeyboardDisplayed() {
// minimal keyboard height is 150px
return (this.container.offsetHeight < ThreadListUI.fullHeight - 150);
},
enableSend: function thui_enableSend() {
this.initSentAudio();
// should disable if we have no message input
var disableSendMessage = Compose.isEmpty();
var messageNotLong = this.updateCounter();
// should disable if the message is too long
disableSendMessage = disableSendMessage || !messageNotLong;
// should disable if we have no recipients in the "new thread" view
disableSendMessage = disableSendMessage ||
(window.location.hash == '#new' && !this.recipients.length);
this.sendButton.disabled = disableSendMessage;
},
scrollViewToBottom: function thui_scrollViewToBottom() {
this.container.scrollTop = this.container.scrollHeight;
},
// updates the counter for sms segments when in text only mode
// returns true when the limit is over the segment limit
updateSmsSegmentLimit: function thui_updateSmsSegmentLimit() {
if (!(this._mozMobileMessage &&
this._mozMobileMessage.getSegmentInfoForText)) {
return false;
}
var value = Compose.getText();
// We set maximum concatenated number of our SMS app to 10 based on:
// https://bugzilla.mozilla.org/show_bug.cgi?id=813686#c0
var kMaxConcatenatedMessages = 10;
// Use backend api for precise sms segmetation information.
var smsInfo = this._mozMobileMessage.getSegmentInfoForText(value);
var segments = smsInfo.segments;
var availableChars = smsInfo.charsAvailableInLastSegment;
// in MMS mode, the counter value isn't used anyway, so we can update this
this.sendButton.dataset.counter = availableChars + '/' + segments;
// if we are going to force MMS, this is true anyway, so adding has-counter
// again doesn't hurt us.
if (segments && (segments > 1 || availableChars <= 10)) {
this.sendButton.classList.add('has-counter');
} else {
this.sendButton.classList.remove('has-counter');
}
return segments > kMaxConcatenatedMessages;
},
// will return true if we can send the message, false if we can't send the
// message
updateCounter: function thui_updateCount() {
var message;
if (Compose.type === 'mms') {
return this.updateCounterForMms();
}
Compose.lock = false;
this.maxLengthNotice.classList.add('hide');
if (this.updateSmsSegmentLimit()) {
Compose.type = 'mms';
}
return true;
},
updateCounterForMms: function thui_updateCounterForMms() {
// always turn on the counter for mms, it just displays "MMS"
this.sendButton.classList.add('has-counter');
if (Settings.mmsSizeLimitation) {
if (Compose.size > Settings.mmsSizeLimitation) {
Compose.lock = true;
this.maxLengthNotice.querySelector('p').textContent =
navigator.mozL10n.get('messages-exceeded-length-text');
this.maxLengthNotice.classList.remove('hide');
return false;
} else if (Compose.size === Settings.mmsSizeLimitation) {
Compose.lock = true;
this.maxLengthNotice.querySelector('p').textContent =
navigator.mozL10n.get('messages-max-length-text');
this.maxLengthNotice.classList.remove('hide');
return true;
}
}
Compose.lock = false;
this.maxLengthNotice.classList.add('hide');
return true;
},
updateInputHeight: function thui_updateInputHeight() {
// First of all we retrieve all CSS info which we need
var inputCss = window.getComputedStyle(this.input, null);
var inputMaxHeight = parseInt(inputCss.getPropertyValue('max-height'), 10);
var verticalPadding = this.INPUT_PADDING;
var buttonHeight = this.sendButton.offsetHeight;
// Retrieve elements useful in growing method
var bottomBar = this.composeForm;
// We need to grow the input step by step
this.input.style.height = null;
// Updating the height if scroll is bigger that height
// This is when we have reached the header (UX requirement)
if (this.input.scrollHeight > inputMaxHeight) {
// Height of the input is the maximum
this.input.style.height = inputMaxHeight + 'px';
// Update the bottom bar height taking into account the padding
bottomBar.style.height = (inputMaxHeight + verticalPadding) + 'px';
// We update the position of the button taking into account the
// new height
this.sendButton.style.marginTop = this.attachButton.style.marginTop =
(this.input.offsetHeight - buttonHeight) + 'px';
return;
}
// If the scroll height is smaller than original offset height, we keep
// offset height to keep original height, otherwise we use scroll height
// with additional margin for preventing scroll bar.
this.input.style.height =
this.input.offsetHeight > this.input.scrollHeight ?
this.input.offsetHeight + 'px' :
(this.input.scrollHeight + verticalPadding) + 'px';
// We retrieve current height of the input
var newHeight = this.input.getBoundingClientRect().height;
// We calculate the height of the bottonBar which contains the input
var bottomBarHeight = (newHeight + verticalPadding) + 'px';
bottomBar.style.height = bottomBarHeight;
// We move the button to the right position
var buttonOffset = (this.input.offsetHeight - buttonHeight) + 'px';
this.sendButton.style.marginTop = this.attachButton.style.marginTop =
buttonOffset;
// Last adjustment to view taking into account the new height of the bar
this.container.style.bottom = bottomBarHeight;
this.scrollViewToBottom();
},
// Adds a new grouping header if necessary (today, tomorrow, ...)
getMessageContainer:
function thui_getMessageContainer(messageTimestamp, hidden) {
var normalizedTimestamp = Utils.getDayDate(messageTimestamp);
var referenceTime = Date.now();
var messageContainer;
// If timestamp belongs to [referenceTime, referenceTime - TimeBuffer]
var isLastMessagesBlock =
(messageTimestamp >= (referenceTime - this.LAST_MESSSAGES_BUFFERING_TIME));
// Is there any container with our requirements?
if (isLastMessagesBlock) {
messageContainer = document.getElementById('last-messages');
} else {
messageContainer = document.getElementById('mc_' + normalizedTimestamp);
}
if (messageContainer) {
return messageContainer;
}
// If there is no messageContainer we have to create it
// Create DOM Element for header
var header = document.createElement('header');
// Append 'time-update' state
header.dataset.timeUpdate = true;
header.dataset.time = messageTimestamp;
if (hidden) {
header.classList.add('hidden');
}
// Add text
var content;
if (!isLastMessagesBlock) {
content = Utils.getHeaderDate(messageTimestamp) + ' ' +
Utils.getFormattedHour(messageTimestamp);
} else {
content = Utils.getFormattedHour(messageTimestamp);
header.dataset.hourOnly = 'true';
}
header.innerHTML = content;
// Create list element for ul
messageContainer = document.createElement('ul');
if (!isLastMessagesBlock) {
messageContainer.id = 'mc_' + normalizedTimestamp;
} else {
messageContainer.id = 'last-messages';
}
messageContainer.dataset.timestamp = normalizedTimestamp;
// Where do I have to append the Container?
// If is the first block or is the 'last-messages' one should be the
// most recent one.
if (isLastMessagesBlock || !ThreadUI.container.firstElementChild) {
ThreadUI.container.appendChild(header);
ThreadUI.container.appendChild(messageContainer);
return messageContainer;
}
// In other case we have to look for the right place for appending
// the message
var messageContainers = ThreadUI.container.getElementsByTagName('ul');
var insertBeforeContainer;
for (var i = 0, l = messageContainers.length; i < l; i++) {
if (normalizedTimestamp < messageContainers[i].dataset.timestamp) {
insertBeforeContainer = messageContainers[i];
break;
}
}
// If is undefined we try witn the 'last-messages' block
if (!insertBeforeContainer) {
insertBeforeContainer = document.getElementById('last-messages');
}
// Finally we append the container & header in the right position
if (insertBeforeContainer) {
ThreadUI.container.insertBefore(messageContainer,
insertBeforeContainer.previousSibling);
ThreadUI.container.insertBefore(header, messageContainer);
} else {
ThreadUI.container.appendChild(header);
ThreadUI.container.appendChild(messageContainer);
}
return messageContainer;
},
// Method for updating the header with the info retrieved from Contacts API
updateHeaderData: function thui_updateHeaderData(callback) {
var thread, number, others;
if (Threads.currentId) {
thread = Threads.active;
}
if (!thread) {
if (callback) {
callback();
}
return;
}
number = thread.participants[0];
others = thread.participants.length - 1;
// For Desktop testing, there is a fake mozContacts but it's not working
// completely. So in the case of Desktop testing we are going to execute
// the callback directly in order to make it work!
// https://bugzilla.mozilla.org/show_bug.cgi?id=836733
if (!navigator.mozMobileMessage && callback) {
this.headerText.textContent = navigator.mozL10n.get(
'thread-header-text', {
name: number,
n: others
});
setTimeout(callback);
return;
}
// Add data to contact activity interaction
this.headerText.dataset.phoneNumber = number;
// For the basic display, we only need the first contact's information --
// e.g. for 3 contacts, the app displays:
//
// Jane Doe (+2)
//
Contacts.findByPhoneNumber(number, function gotContact(contacts) {
var carrierTag = document.getElementById('contact-carrier');
/** If we have more than one contact sharing the same phone number
* we show the title of contact detail with validate name/company
* and how many other contacts share that same number. We think it's
* user's responsability to correct this mess with the agenda.
*/
var details = Utils.getContactDetails(number, contacts);
var contactName = details.title || number;
this.headerText.dataset.isContact = !!details.isContact;
this.headerText.textContent = navigator.mozL10n.get(
'thread-header-text', {
name: contactName,
n: others
});
if (details.carrier) {
carrierTag.textContent = details.carrier;
carrierTag.classList.remove('hide');
} else {
carrierTag.classList.add('hide');
}
if (callback) {
callback();
}
}.bind(this));
},
initializeRendering: function thui_initializeRendering(messages, callback) {
// Clean fields
this.cleanFields();
this.checkInputs();
// Clean list of messages
this.container.innerHTML = '';
// Init readMessages array
this.readMessages = [];
// Initialize infinite scroll params
this.messageIndex = 0;
// reset stopRendering boolean
this._stopRenderingNextStep = false;
},
// Method for stopping the rendering when clicking back
stopRendering: function thui_stopRendering() {
this._stopRenderingNextStep = true;
},
// Method for rendering the first chunk at the beginning
showFirstChunk: function thui_showFirstChunk() {
// Show chunk of messages
ThreadUI.showChunkOfMessages(this.CHUNK_SIZE);
// Boot update of headers
Utils.updateTimeHeaders();
// Go to Bottom
ThreadUI.scrollViewToBottom();
},
createMmsContent: function thui_createMmsContent(dataArray) {
var container = document.createDocumentFragment();
dataArray.forEach(function(attachment) {
var mediaElement, textElement;
if (attachment.name && attachment.blob) {
var type = Utils.typeFromMimeType(attachment.blob.type);
if (type) {
// we special case audio to display an image of an audio attachment
// video currently falls through this path too, we should revisit this
// with #869244
if (type === 'audio' || type === 'video') {
mediaElement = document.createElement('div');
mediaElement.className = type + '-placeholder';
} else {
mediaElement = document.createElement(type);
mediaElement.src = URL.createObjectURL(attachment.blob);
mediaElement.onload = function() {
URL.revokeObjectURL(this.src);
};
}
mediaElement.classList.add('mms-media');
container.appendChild(mediaElement);
attachmentMap.set(mediaElement, attachment);
}
}
if (attachment.text) {
textElement = document.createElement('span');
// escape text for html and look for clickable numbers, etc.
var text = Utils.escapeHTML(attachment.text);
text = LinkHelper.searchAndLinkClickableData(text);
textElement.innerHTML = text;
container.appendChild(textElement);
}
});
return container;
},
// Method for rendering the list of messages using infinite scroll
renderMessages: function thui_renderMessages(filter, callback) {
// We initialize all params before rendering
this.initializeRendering();
// We call getMessages with callbacks
var self = this;
var onMessagesRendered = function messagesRendered() {
if (self.messageIndex < self.CHUNK_SIZE) {
self.showFirstChunk();
}
// Update STATUS of messages if needed
filter.read = false;
if (callback) {
callback();
}
setTimeout(function updatingStatus() {
var messagesUnreadIDs = [];
var changeStatusOptions = {
each: function addUnreadMessage(message) {
messagesUnreadIDs.push(message.id);
return true;
},
filter: filter,
invert: true,
end: function handleUnread() {
MessageManager.markMessagesRead(messagesUnreadIDs, true);
}
};
MessageManager.getMessages(changeStatusOptions);
});
};
var renderingOptions = {
each: function renderMessage(message) {
if (self._stopRenderingNextStep) {
// stop the iteration
return false;
}
self.appendMessage(message,/*hidden*/ true);
self.messageIndex++;
if (self.messageIndex === self.CHUNK_SIZE) {
self.showFirstChunk();
}
return true;
},
filter: filter,
invert: false,
end: onMessagesRendered
};
MessageManager.getMessages(renderingOptions);
},
// generates the html for not-downloaded messages - pushes class names into
// the classNames array also passed in, returns an HTML string
_createNotDownloadedHTML:
function thui_createNotDownloadedHTML(message, classNames) {
var _ = navigator.mozL10n.get;
// default strings:
var messageString = 'not-downloaded-mms';
var downloadString = 'download';
// assuming that incoming message only has one deliveryStatus
var status = message.deliveryStatus[0];
var expireFormatted = Utils.date.format.localeFormat(
message.expiryDate, _('dateTimeFormat_%x')
);
var expired = +message.expiryDate < Date.now();
if (expired) {
classNames.push('expired');
messageString = 'expired-mms';
}
if (status === 'error') {
classNames.push('error');
}
if (status === 'pending') {
downloadString = 'downloading';
classNames.push('pending');
}
messageString = _(messageString, { date: expireFormatted });
return this.tmpl.notDownloaded.interpolate({
message: messageString,
download: _(downloadString)
});
},
buildMessageDOM: function thui_buildMessageDOM(message, hidden) {
var bodyHTML = '';
var delivery = message.delivery;
var messageDOM = document.createElement('li');
var classNames = ['message', message.type, delivery];
var notDownloaded = delivery === 'not-downloaded';
if (delivery === 'received' || notDownloaded) {
classNames.push('incoming');
} else {
classNames.push('outgoing');
}
if (hidden) {
classNames.push('hidden');
}
if (message.type && message.type === 'sms') {
bodyHTML = LinkHelper.searchAndLinkClickableData(
Utils.Message.format(message.body || '')
);
}
if (notDownloaded) {
bodyHTML = this._createNotDownloadedHTML(message, classNames);
}
messageDOM.className = classNames.join(' ');
messageDOM.id = 'message-' + message.id;
messageDOM.dataset.messageId = message.id;
messageDOM.innerHTML = this.tmpl.message.interpolate({
id: String(message.id),
bodyHTML: bodyHTML
}, {
safe: ['bodyHTML']
});
if (message.type === 'mms' && !notDownloaded) { // MMS
var pElement = messageDOM.querySelector('p');
SMIL.parse(message, function(slideArray) {
pElement.appendChild(ThreadUI.createMmsContent(slideArray));
});
}
return messageDOM;
},
appendMessage: function thui_appendMessage(message, hidden) {
var timestamp = message.timestamp.getTime();
// look for an old message and remove it first - prevent anything from ever
// double rendering for now
var messageDOM = this.container.querySelector(
'[data-message-id="' + message.id + '"]');
if (messageDOM) {
this.removeMessageDOM(messageDOM);
}
// build messageDOM adding the links
messageDOM = this.buildMessageDOM(message, hidden);
messageDOM.dataset.timestamp = timestamp;
// Add to the right position
var messageContainer = ThreadUI.getMessageContainer(timestamp, hidden);
if (!messageContainer.firstElementChild) {
messageContainer.appendChild(messageDOM);
} else {
var messages = messageContainer.children;
var appended = false;
for (var i = 0, l = messages.length; i < l; i++) {
if (timestamp < messages[i].dataset.timestamp) {
messageContainer.insertBefore(messageDOM, messages[i]);
appended = true;
break;
}
}
if (!appended) {
messageContainer.appendChild(messageDOM);
}
}
if (this.mainWrapper.classList.contains('edit')) {
this.checkInputs();
}
},
showChunkOfMessages: function thui_showChunkOfMessages(number) {
var elements = ThreadUI.container.getElementsByClassName('hidden');
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].classList.remove('hidden');
}
},
cleanForm: function thui_cleanForm() {
// Reset all inputs
var inputs = this.container.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
inputs[i].parentNode.parentNode.classList.remove('undo-candidate');
}
// Reset vars for deleting methods
this.checkInputs();
},
clear: function thui_clear() {
this.initRecipients();
},
toggleCheckedAll: function thui_select(value) {
var inputs = this.container.querySelectorAll(
'input[type="checkbox"]' +
// value ?