This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
sms.js
1654 lines (1475 loc) · 53.2 KB
/
sms.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: */
'use strict';
var MessageManager = {
init: function mm_init() {
this.initialized = true;
// Init PhoneNumberManager for solving country code issue.
PhoneNumberManager.init();
MessageManager.getThreads(ThreadListUI.renderThreads);
// Init UI Managers
ThreadUI.init();
ThreadListUI.init();
if (navigator.mozSms) {
navigator.mozSms.addEventListener('received',
this.onMessageReceived.bind(this));
navigator.mozSms.addEventListener('sending', this.onMessageSending);
navigator.mozSms.addEventListener('sent', this.onMessageSent);
navigator.mozSms.addEventListener('failed', this.onMessageFailed);
}
window.addEventListener('hashchange', this.onHashChange.bind(this));
document.addEventListener('mozvisibilitychange',
this.onVisibilityChange.bind(this));
},
onMessageSending: function mm_onMessageSending(e) {
var message = e.message;
ThreadUI.appendMessage(message);
MessageManager.getThreads(ThreadListUI.renderThreads);
},
onMessageFailed: function mm_onMessageFailed(e) {
ThreadUI.onMessageFailed(e.message);
},
onMessageSent: function mm_onMessageSent(e) {
ThreadUI.onMessageSent(e.message);
},
onMessageReceived: function mm_onMessageReceived(e) {
if (window.location.hash === '#edit') {
return;
}
var message = e.message;
var num;
if (this.currentNum) {
num = this.currentNum;
}
var sender = message.sender;
if (num && num === sender) {
//Append message and mark as unread
this.markMessagesRead([message.id], true, function() {
MessageManager.getThreads(ThreadListUI.renderThreads);
});
ThreadUI.appendMessage(message);
Utils.updateTimeHeaders();
} else {
this.getThreads(ThreadListUI.renderThreads);
}
},
slide: function mm_slide(callback) {
var mainWrapper = document.getElementById('main-wrapper');
mainWrapper.classList.toggle('to-left');
mainWrapper.addEventListener('transitionend', function slideTransition() {
mainWrapper.removeEventListener('transitionend', slideTransition);
if (callback) {
callback();
}
});
},
onHashChange: function mm_onHashChange(e) {
var mainWrapper = document.getElementById('main-wrapper');
var threadMessages = document.getElementById('thread-messages');
switch (window.location.hash) {
case '#new':
var messageInput = document.getElementById('message-to-send');
var receiverInput = document.getElementById('receiver-input');
//Keep the visible button the :last-child
var contactButton = document.getElementById('icon-contact');
contactButton.parentNode.appendChild(contactButton);
document.getElementById('messages-container').innerHTML = '';
ThreadUI.cleanFields();
MessageManager.currentNum = null;
threadMessages.classList.add('new');
MessageManager.slide(function() {
receiverInput.focus();
});
break;
case '#thread-list':
//Keep the visible button the :last-child
var editButton = document.getElementById('icon-edit');
editButton.parentNode.appendChild(editButton);
MessageManager.currentNum = null;
if (mainWrapper.classList.contains('edit')) {
if (ThreadListUI.editDone) {
ThreadListUI.editDone = false;
this.getThreads(ThreadListUI.renderThreads);
}
mainWrapper.classList.remove('edit');
} else if (threadMessages.classList.contains('new')) {
MessageManager.slide(function() {
threadMessages.classList.remove('new');
});
} else {
MessageManager.slide(function() {
ThreadUI.view.innerHTML = '';
if (MessageManager.activityTarget) {
window.location.hash =
'#num=' + MessageManager.activityTarget;
delete MessageManager.activityTarget;
delete MessageManager.lockActivity;
}
});
}
break;
case '#edit':
ThreadListUI.cleanForm();
ThreadUI.cleanForm();
mainWrapper.classList.toggle('edit');
break;
default:
var num = this.getNumFromHash();
if (num) {
var filter = this.createFilter(num);
var messageInput = document.getElementById('message-to-send');
var numNormalized =
PhoneNumberManager.getNormalizedInternationalNumber(num);
MessageManager.currentNum = numNormalized;
if (mainWrapper.classList.contains('edit')) {
this.getMessages(ThreadUI.renderMessages, filter);
mainWrapper.classList.remove('edit');
} else if (threadMessages.classList.contains('new')) {
this.getMessages(ThreadUI.renderMessages, filter, true);
threadMessages.classList.remove('new');
messageInput.focus();
} else {
// As soon as we click in the thread, we visually mark it
// as read.
var threadRead = document.getElementById('thread_' + num);
if (threadRead) {
threadRead.getElementsByTagName('a')[0].classList
.remove('unread');
}
this.getMessages(ThreadUI.renderMessages,
filter, true, function() {
MessageManager.slide(function() {
messageInput.focus();
});
});
}
}
break;
}
},
onVisibilityChange: function mm_onVisibilityChange(e) {
if (!document.mozHidden) {
if (window.location.hash == '#edit') {
return;
}
this.getThreads(ThreadListUI.renderThreads);
if (!MessageManager.lockActivity) {
var num = this.currentNum;
if (num) {
var filter = this.createFilter(num);
var typedText = ThreadUI.input.value;
this.getMessages(ThreadUI.renderMessages, filter, true,
function() {
// Restored previous typed text.
ThreadUI.input.value = typedText;
ThreadUI.input.focus();
ThreadUI.enableSend();
});
}
}
}
},
createFilter: function mm_createFilter(num) {
var filter = new MozSmsFilter();
if (num) {
num = PhoneNumberManager.getNormalizedInternationalNumber(num);
} else {
num = '';
}
filter.numbers = [num];
return filter;
},
getNumFromHash: function mm_getNumFromHash() {
var num = /\bnum=(.+)(&|$)/.exec(window.location.hash);
return num ? num[1] : null;
},
getThreads: function mm_getThreads(callback, extraArg) {
var request = navigator.mozSms.getThreadList();
request.onsuccess = function onsuccess(evt) {
var threads = evt.target.result;
if (callback) {
callback(threads, extraArg);
}
};
request.onerror = function onerror() {
var msg = 'Reading the database. Error: ' + request.errorCode;
console.log(msg);
};
},
// Retrieve messages from DB and execute callback
getMessages: function mm_getMessages(callback, filter, invert, callbackArgs) {
var request = navigator.mozSms.getMessages(filter, !invert);
var self = this;
var messages = [];
request.onsuccess = function onsuccess() {
var cursor = request.result;
if (cursor.message) {
messages.push(cursor.message);
cursor.continue();
} else {
callback(messages, callbackArgs);
}
};
request.onerror = function onerror() {
var msg = 'Reading the database. Error: ' + request.errorCode;
console.log(msg);
};
},
send: function mm_send(number, text, callback, errorHandler) {
var req = navigator.mozSms.send(number, text);
req.onsuccess = function onsuccess(e) {
callback && callback(req.result);
};
req.onerror = function onerror(e) {
errorHandler && errorHandler(number);
};
},
deleteMessage: function mm_deleteMessage(id, callback) {
var req = navigator.mozSms.delete(id);
req.onsuccess = function onsuccess() {
callback && callback(req.result);
};
req.onerror = function onerror() {
var msg = 'Deleting in the database. Error: ' + req.errorCode;
console.log(msg);
callback && callback(null);
};
},
/*
TODO: If the messages could not be deleted completely,
conversation list page will also update without notification currently.
May need more infomation for user that the messages were not
removed completely.
*/
deleteMessages: function mm_deleteMessages(list, callback) {
if (list.length > 0) {
this.deleteMessage(list.shift(), function(result) {
this.deleteMessages(list, callback);
}.bind(this));
} else
callback();
},
markMessagesRead: function mm_markMessagesRead(list, value, callback) {
if (!navigator.mozSms || !list.length) {
return;
}
// We chain the calls to the API in a way that we make no call to
// 'markMessageRead' until a previous call is completed. This way any
// other potential call to the API, like the one for getting a message
// list, could be done within the calls to mark the messages as read.
var req = navigator.mozSms.markMessageRead(list.pop(), value);
req.onsuccess = (function onsuccess() {
if (!list.length && callback) {
callback(req.result);
return;
}
this.markMessagesRead(list, value, callback);
}).bind(this);
req.onerror = function onerror() {
if (callback) {
callback(null);
}
};
}
};
var ThreadListUI = {
get view() {
delete this.view;
return this.view = document.getElementById('thread-list-container');
},
get selectAllButton() {
delete this.selectAllButton;
return this.selectAllButton = document.getElementById('select-all-threads');
},
get deselectAllButton() {
delete this.deselectAllButton;
return this.deselectAllButton =
document.getElementById('deselect-all-threads');
},
get deleteButton() {
delete this.deleteButton;
return this.deleteButton = document.getElementById('threads-delete-button');
},
get cancelButton() {
delete this.cancelButton;
return this.cancelButton = document.getElementById('threads-cancel-button');
},
get iconEdit() {
delete this.iconEdit;
return this.iconEdit = document.getElementById('icon-edit-threads');
},
get pageHeader() {
delete this.pageHeader;
return this.pageHeader = document.getElementById('list-edit-title');
},
get editForm() {
delete this.editForm;
return this.editForm = document.getElementById('threads-edit-form');
},
init: function thlui_init() {
this.delNumList = [];
this.selectedInputList = [];
this.selectAllButton.addEventListener('click',
this.selectAllThreads.bind(this));
this.deselectAllButton.addEventListener('click',
this.deselectAllThreads.bind(this));
this.deleteButton.addEventListener('click',
this.executeDeletion.bind(this));
this.cancelButton.addEventListener('click', this.cancelEditMode.bind(this));
this.view.addEventListener('click', this);
this.editForm.addEventListener('submit', this);
},
updateThreadWithContact:
function thlui_updateThreadWithContact(number, thread) {
ContactDataManager.getContactData(number,
function gotContact(contacts) {
if (!contacts || ! Array.isArray(contacts) || contacts.length < 1) {
return;
}
// If there is contact with the phone number requested, we
// update the info in the thread
var nameContainer = thread.getElementsByClassName('name')[0];
var contact = contacts[0];
// Update contact phone number
var contactName = contact.name;
if (contacts.length > 1) {
// If there are more than one contact with same phone number
var others = contacts.length - 1;
nameContainer.innerHTML = _('others', {
name: contactName,
n: others
});
}else {
nameContainer.innerHTML = contactName;
}
// Do we have to update photo?
if (contact.photo && contact.photo[0]) {
var photo = thread.getElementsByTagName('img')[0];
var photoURL = URL.createObjectURL(contact.photo[0]);
photo.src = photoURL;
}
});
},
handleEvent: function thlui_handleEvent(evt) {
switch (evt.type) {
case 'click':
if (evt.target.type == 'checkbox') {
ThreadListUI.clickInput(evt.target);
ThreadListUI.checkInputs();
}
break;
case 'submit':
evt.preventDefault();
return false;
break;
}
},
clickInput: function thlui_clickInput(target) {
if (target.checked) {
ThreadListUI.selectedInputList.push(target);
} else {
ThreadListUI.selectedInputList.splice(
ThreadListUI.selectedInputList.indexOf(target), 1);
}
},
checkInputs: function thlui_checkInputs() {
var selected = ThreadListUI.selectedInputList.length;
var allInputs =
ThreadListUI.view.querySelectorAll('input[type="checkbox"]');
if (selected == allInputs.length) {
ThreadListUI.selectAllButton.classList.add('disabled');
} else {
ThreadListUI.selectAllButton.classList.remove('disabled');
}
if (selected > 0) {
ThreadListUI.deselectAllButton.classList.remove('disabled');
ThreadListUI.deleteButton.classList.remove('disabled');
this.pageHeader.innerHTML = _('selected', {n: selected});
} else {
ThreadListUI.deselectAllButton.classList.add('disabled');
ThreadListUI.deleteButton.classList.add('disabled');
this.pageHeader.innerHTML = _('editMode');
}
},
cleanForm: function thlui_cleanForm() {
var inputs = this.view.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
inputs[i].parentNode.parentNode.classList.remove('undo-candidate');
}
this.delNumList = [];
this.selectedInputList = [];
this.pageHeader.innerHTML = _('editMode');
this.checkInputs();
},
selectAllThreads: function thlui_selectAllThreads() {
var inputs =
this.view.querySelectorAll('input[type="checkbox"]:not(:checked)');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
ThreadListUI.clickInput(inputs[i]);
}
ThreadListUI.checkInputs();
},
deselectAllThreads: function thlui_deselectAllThreads() {
var inputs = this.view.querySelectorAll('input[type="checkbox"]:checked');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
ThreadListUI.clickInput(inputs[i]);
}
ThreadListUI.checkInputs();
},
executeDeletion: function thlui_executeDeletion() {
var response = window.confirm(_('deleteThreads-confirmation2'));
if (response) {
WaitingScreen.show();
var inputs = ThreadListUI.selectedInputList;
var nums = inputs.map(function(input) {
return input.value;
});
var filter = new MozSmsFilter();
filter.numbers = nums;
MessageManager.getMessages(function gotMessages(messages) {
var delNumList = messages.map(function(message) {
return message.id;
});
MessageManager.deleteMessages(delNumList,
function() {
MessageManager.getThreads(function recoverThreads(threads) {
ThreadListUI.renderThreads(threads);
WaitingScreen.hide();
ThreadListUI.editDone = true;
window.location.hash = '#thread-list';
});
});
}, filter);
}
},
cancelEditMode: function thlui_cancelEditMode() {
window.location.hash = '#thread-list';
},
renderThreads: function thlui_renderThreads(threads, callback) {
ThreadListUI.view.innerHTML = '';
if (threads.length > 0) {
document.getElementById('threads-fixed-container').
classList.remove('hide');
FixedHeader.init('#thread-list-container',
'#threads-fixed-container',
'header');
// Edit mode available
ThreadListUI.iconEdit.classList.remove('disabled');
var threadIds = [],
dayHeaderIndex = 0,
unreadThreads = [];
for (var i = threads.length - 1; i >= 0; i--) {
var thread = threads[i];
var time = thread.timestamp.getTime();
var num = thread.senderOrReceiver;
var numNormalized =
PhoneNumberManager.getNormalizedInternationalNumber(num);
if (thread.unreadCount) {
unreadThreads.push(numNormalized);
}
if (threadIds.indexOf(numNormalized) == -1) {
var thread = {
'body': thread.body,
'name': numNormalized,
'num': numNormalized,
'timestamp': time,
'unreadCount': thread.unreadCount,
'id': numNormalized
};
if (threadIds.length == 0) {
dayHeaderIndex = Utils.getDayDate(time);
ThreadListUI.createNewHeader(time);
} else {
var tmpDayIndex = Utils.getDayDate(time);
if (tmpDayIndex < dayHeaderIndex) {
ThreadListUI.createNewHeader(time);
dayHeaderIndex = tmpDayIndex;
}
}
threadIds.push(numNormalized);
ThreadListUI.appendThread(thread);
}
}
// Update threads with 'unread' if some was missing
for (var i = 0; i < unreadThreads.length; i++) {
document.getElementById('thread_' + unreadThreads[i]).
getElementsByTagName('a')[0].classList.add('unread');
}
// Boot update of headers
Utils.updateTimeHeaderScheduler();
} else {
document.getElementById('threads-fixed-container').classList.add('hide');
var noResultHTML = '<div id="no-result-container">' +
' <div id="no-result-message">' +
' <p>' + _('noMessages-title') + '</p>' +
' <p>' + _('noMessages-text') + '</p>' +
' </div>' +
'</div>';
ThreadListUI.view.innerHTML = noResultHTML;
ThreadListUI.iconEdit.classList.add('disabled');
}
// Callback when every thread is appended
if (callback) {
callback();
}
},
appendThread: function thlui_appendThread(thread) {
// Retrieve ThreadsContainer
var threadsContainerID = 'threadsContainer_' +
Utils.getDayDate(thread.timestamp);
var threadsContainer = document.getElementById(threadsContainerID);
if (!threadsContainer) {
return;
}
// Create DOM element
var threadDOM = document.createElement('li');
threadDOM.id = 'thread_' + thread.num;
// Retrieving params from thread
var bodyText = (thread.body || '').split('\n')[0];
var formattedDate = Utils.getFormattedHour(thread.timestamp);
// Create HTML Structure
var structureHTML = '<label class="danger">' +
'<input type="checkbox" value="' + thread.num + '">' +
'<span></span>' +
'</label>' +
'<a href="#num=' + thread.num +
'" class="' +
(thread.unreadCount > 0 ? 'unread' : '') + '">' +
'<aside class="icon icon-unread">unread</aside>' +
'<aside class="pack-end">' +
'<img src="">' +
'</aside>' +
'<p class="name">' + thread.num + '</p>' +
'<p><time>' + formattedDate +
'</time>' + bodyText + '</p>' +
'</a>';
// Update HTML
threadDOM.innerHTML = structureHTML;
// Append Element
threadsContainer.appendChild(threadDOM);
// Update info given a number
ThreadListUI.updateThreadWithContact(thread.num, threadDOM);
},
// Adds a new grouping header if necessary (today, tomorrow, ...)
createNewHeader: function thlui_createNewHeader(timestamp) {
// Create Header DOM Element
var headerDOM = document.createElement('header');
// Append 'time-update' state
headerDOM.dataset.timeUpdate = true;
headerDOM.dataset.time = timestamp;
// Create UL DOM Element
var threadsContainerDOM = document.createElement('ul');
threadsContainerDOM.id = 'threadsContainer_' +
Utils.getDayDate(timestamp);
// Add text
headerDOM.innerHTML = Utils.getHeaderDate(timestamp);
// Add to DOM all elements
ThreadListUI.view.appendChild(headerDOM);
ThreadListUI.view.appendChild(threadsContainerDOM);
// Refresh fixed header logic
FixedHeader.refresh();
},
// Method for updating all contact info after creating a contact
updateContactsInfo: function mm_updateContactsInfo() {
// Retrieve all 'li' elements and getting the phone numbers
var threads = ThreadListUI.view.getElementsByTagName('li');
for (var i = 0; i < threads.length; i++) {
var thread = threads[i];
var num = thread.id.replace('thread_', '');
// Update info of the contact given a number
ThreadListUI.updateThreadWithContact(num, thread);
}
}
};
var ThreadUI = {
get view() {
delete this.view;
return this.view = document.getElementById('messages-container');
},
get contactInput() {
delete this.contactInput;
return this.contactInput = document.getElementById('receiver-input');
},
get clearButton() {
delete this.clearButton;
return this.clearButton = document.getElementById('clear-search');
},
get title() {
delete this.title;
return this.title = document.getElementById('header-text');
},
get input() {
delete this.input;
return this.input = document.getElementById('message-to-send');
},
get sendButton() {
delete this.sendButton;
return this.sendButton = document.getElementById('send-message');
},
get pickButton() {
delete this.pickButton;
return this.pickButton = document.getElementById('icon-contact');
},
get selectAllButton() {
delete this.deleteAllButton;
return this.deleteAllButton =
document.getElementById('select-all-messages');
},
get deselectAllButton() {
delete this.deselectAllButton;
return this.deselectAllButton =
document.getElementById('deselect-all-messages');
},
get deleteButton() {
delete this.doneButton;
return this.doneButton = document.getElementById('messages-delete-button');
},
get cancelButton() {
delete this.cancelButton;
return this.cancelButton =
document.getElementById('messages-cancel-button');
},
get pageHeader() {
delete this.pageHeader;
return this.pageHeader = document.getElementById('messages-edit-title');
},
get editForm() {
delete this.editForm;
return this.editForm = document.getElementById('messages-edit-form');
},
get telForm() {
delete this.telForm;
return this.telForm = document.getElementById('messages-tel-form');
},
get sendForm() {
delete this.sendForm;
return this.sendForm = document.getElementById('new-sms-form');
},
init: function thui_init() {
this.sendButton.addEventListener('click', this.sendMessage.bind(this));
// Prevent sendbutton to hide the keyboard:
this.sendButton.addEventListener('mousedown',
function btnDown(event) {
event.preventDefault();
event.target.classList.add('active');
}
);
this.sendButton.addEventListener('mouseup',
function btnUp(event) {
event.target.classList.remove('active');
}
);
this.sendButton.addEventListener('mouseout',
function mouseOut(event) {
event.target.classList.remove('active');
}
);
this.pickButton.addEventListener('click', this.pickContact.bind(this));
this.selectAllButton.addEventListener('click',
this.selectAllMessages.bind(this));
this.deselectAllButton.addEventListener('click',
this.deselectAllMessages.bind(this));
this.cancelButton.addEventListener('click', this.cancelEditMode.bind(this));
this.input.addEventListener('input', this.updateInputHeight.bind(this));
this.input.addEventListener('input', this.enableSend.bind(this));
this.contactInput.addEventListener('input', this.searchContact.bind(this));
this.contactInput.addEventListener('input', this.enableSend.bind(this));
this.deleteButton.addEventListener('click',
this.executeDeletion.bind(this));
this.title.addEventListener('click', this.activateContact.bind(this));
this.clearButton.addEventListener('click', this.clearContact.bind(this));
this.view.addEventListener('click', this);
this.editForm.addEventListener('submit', this);
this.telForm.addEventListener('submit', this);
this.sendForm.addEventListener('submit', this);
},
enableSend: function thui_enableSend() {
if (this.input.value.length > 0) {
this.updateCounter();
}
if (window.location.hash == '#new' && this.contactInput.value.length == 0) {
this.sendButton.disabled = true;
return;
}
this.sendButton.disabled = !(this.input.value.length > 0);
},
scrollViewToBottom: function thui_scrollViewToBottom(animateFromPos) {
if (!animateFromPos) {
this.view.scrollTop = this.view.scrollHeight;
return;
}
clearInterval(this.viewScrollingTimer);
this.view.scrollTop = animateFromPos;
this.viewScrollingTimer = setInterval((function scrollStep() {
var view = this.view;
var height = view.scrollHeight - view.offsetHeight;
if (view.scrollTop === height) {
clearInterval(this.viewScrollingTimer);
return;
}
view.scrollTop += Math.ceil((height - view.scrollTop) / 2);
}).bind(this), 100);
},
updateCounter: function thui_updateCount(evt) {
var value = this.input.value;
// 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 = navigator.mozSms.getSegmentInfoForText(value);
var segments = smsInfo.segments;
var availableChars = smsInfo.charsAvailableInLastSegment;
var counter = '';
if (segments > 1) {
counter = availableChars + '/' + segments;
}
this.sendButton.dataset.counter = counter;
this.sendButton.disabled = (segments > kMaxConcatenatedMessages);
},
updateInputHeight: function thui_updateInputHeight() {
var input = this.input;
var inputCss = window.getComputedStyle(input, null);
var inputMaxHeight = parseInt(inputCss.getPropertyValue('max-height'), 10);
//Constant difference of height beteween button and growing input
var deviationHeight = 30;
if (input.scrollHeight > inputMaxHeight) {
return;
}
input.style.height = null;
// 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.
input.style.height = input.offsetHeight > input.scrollHeight ?
input.offsetHeight / Utils.getFontSize() + 'rem' :
input.scrollHeight / Utils.getFontSize() + 'rem';
var newHeight = input.getBoundingClientRect().height;
// Add 0.7 rem that are equal to the message box vertical padding
var bottomToolbarHeight = (newHeight / Utils.getFontSize() + 0.7) + 'rem';
var sendButtonTranslate = (input.offsetHeight - deviationHeight) /
Utils.getFontSize() + 'rem';
var bottomToolbar =
document.querySelector('#new-sms-form');
bottomToolbar.style.height = bottomToolbarHeight;
ThreadUI.sendButton.style.marginTop = sendButtonTranslate;
this.view.style.bottom = bottomToolbarHeight;
this.scrollViewToBottom();
},
// Adds a new grouping header if necessary (today, tomorrow, ...)
createTimeHeader: function thui_createTimeHeader(timestamp, hourOnly) {
// Create DOM Element for header
var headerDOM = document.createElement('header');
// Append 'time-update' state
headerDOM.dataset.timeUpdate = true;
headerDOM.dataset.time = timestamp;
// Add text
var content;
if (!hourOnly) {
content = Utils.getHeaderDate(timestamp) + ' ' +
Utils.getFormattedHour(timestamp);
} else {
content = Utils.getFormattedHour(timestamp);
headerDOM.dataset.hourOnly = 'true';
}
headerDOM.innerHTML = content;
// Append to DOM
ThreadUI.view.appendChild(headerDOM);
// Create list element for ul
var messagesContainerDOM = document.createElement('ul');
// Append to DOM
ThreadUI.view.appendChild(messagesContainerDOM);
},
// Method for updating the header with the info retrieved from Contacts API
updateHeaderData: function thui_updateHeaderData() {
var number = MessageManager.currentNum;
var self = this;
// Add data to contact activity interaction
this.title.dataset.phoneNumber = number;
ContactDataManager.getContactData(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 name of the first contact and how many other contacts
* share that same number. We thing it's user's responsability to correct
* this mess with the agenda.
*/
if (contacts.length > 1) {
self.title.dataset.isContact = true;
var contactName = contacts[0].name;
var numOthers = contacts.length - 1;
self.title.innerHTML = _('others', {
name: contactName,
n: numOthers
});
carrierTag.classList.add('hide');
} else {
Utils.getPhoneDetails(number,
contacts[0],
function returnedDetails(details) {
if (details.isContact) {
self.title.dataset.isContact = true;
} else {
delete self.title.dataset.isContact;
}
self.title.innerHTML = details.title || number;
if (details.carrier) {
carrierTag.innerHTML = details.carrier;
carrierTag.classList.remove('hide');
} else {
carrierTag.classList.add('hide');
}
});
}
});
},
renderMessages: function thui_renderMessages(messages, callback) {
// Clean fields
ThreadUI.cleanFields();
// Reset vars for 'Deleting'
ThreadUI.delNumList = [];
ThreadUI.checkInputs();
// Update Header
ThreadUI.updateHeaderData();
// Clean list of messages
ThreadUI.view.innerHTML = '';
// Update header index
ThreadUI.dayHeaderIndex = 0;
ThreadUI.timeHeaderIndex = 0;
// Init readMessages array
ThreadUI.readMessages = [];
// Per each message I will append DOM element
messages.forEach(ThreadUI.appendMessage);
// Update read messages if necessary
if (ThreadUI.readMessages.length > 0) {
MessageManager.markMessagesRead(ThreadUI.readMessages, 'true',
function() {
MessageManager.getThreads(ThreadListUI.renderThreads);
});
}
// Boot update of headers
Utils.updateTimeHeaderScheduler();
// Callback when every message is appended
if (callback) {
callback();
}
},
appendMessage: function thui_appendMessage(message) {
if (!message.read) {
ThreadUI.readMessages.push(message.id);
}
// Retrieve all data from message
var id = message.id;
var bodyText = message.body;
var bodyHTML = Utils.escapeHTML(bodyText);
var messageClass = message.delivery;
var messageDOM = document.createElement('li');
messageDOM.classList.add('bubble');
messageDOM.id = 'message-' + id;
var inputValue = id;
var asideHTML = '';
// Do we have to add some error/sending icon?
switch (message.delivery) {
case 'error':
asideHTML = '<aside class="pack-end"></aside>';
ThreadUI.addResendHandler(message, messageDOM);
break;
case 'sending':
asideHTML = '<aside class="pack-end">' +
'<progress></progress></aside>';
break;
}
// Create HTML content
var messageHTML = '<label class="danger">' +
'<input type="checkbox" value="' + inputValue + '">' +
'<span></span>' +
'</label>' +
'<a class="' + messageClass + '">';
messageHTML += asideHTML;
messageHTML += '<p>' + bodyHTML + '</p></a>';
// Add structure to DOM element
messageDOM.innerHTML = messageHTML;