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
/
list.js
executable file
·2439 lines (2111 loc) · 71.8 KB
/
list.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
'use strict';
/* global ActivityHandler */
/* global Cache */
/* global ConfirmDialog */
/* global ContactPhotoHelper */
/* global Contacts */
/* global fb */
/* global ICEStore */
/* global ICEData */
/* global ImageLoader */
/* global LazyLoader */
/* global monitorTagVisibility */
/* global Normalizer */
/* global Loader */
/* global utils */
/* global ContactsService */
/* global HeaderUI */
/* global ICEView */
/* global Search */
var contacts = window.contacts || {};
contacts.List = (function() {
var _,
groupsList,
loaded = false,
cancel,
contactsListView,
fastScroll,
scrollable,
settingsView,
noContacts,
imgLoader = null,
needImgLoaderReload = false,
orderByLastName = null,
defaultImage = null,
photoTemplate,
headers = {},
loadedContacts = {},
viewHeight = -1,
rowsPerPage = -1,
monitor = null,
loading = false,
cancelLoadCB = null,
photosById = {},
clonableSelectCheck = null,
deselectAll = null,
selectAll = null,
// Used when we click on select all but the list
// is still loading contacts.
// Will allow new contacts created to be selected
// even if we unselect some of them
selectAllPending = false,
inSelectMode = false,
selectForm = null,
selectActionButton = null,
groupList = null,
searchList = null,
currentlySelected = 0,
currentFilterList = null,
numFilteredContacts = 0,
selectNavigationController = null,
boundSelectAction4Select = null,
// Dictionary by contact id with the rows on screen
rowsOnScreen = {},
selectedContacts = {},
_notifyRowOnScreenCallback = null,
_notifyRowOnScreenUUID = null,
// Will keep an array of contacts ids, not higger than
// 2 contacts with current implementation
iceContacts = [],
iceGroup = null,
forceICEGroupToBeHidden = false;
// Possible values for the configuration field 'defaultContactsOrder'
// config.json file (see bug 841693)
var ORDER_BY_FAMILY_NAME = 'familyName';
var EXPORT_TRANSITION_LEVEL = 2;
var isDangerSelectList = false;
var MAX_INT = 0x7fffffff;
// Specify group short names or "letters" for those groups that have a name
// different from something like "A" or "B".
var GROUP_LETTERS = {
'favorites': '',
'und': '#'
};
// Define the order in which groups should appear in the list. We allow
// arbitrary ordering here in anticipation of additional scripts being added.
var GROUP_ORDER = (function getGroupOrder() {
var letters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + // Roman
'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ' + // Greek
'АБВГДЂЕЁЖЗИЙЈКЛЉМНЊОПРСТЋУФХЦЧЏШЩЭЮЯ'; // Cyrillic (Russian + Serbian)
var order = {
'ice': 0,
'favorites': 1
};
var presetsLength = Object.keys(order).length;
for (var i = 0; i < letters.length; i++) {
order[letters[i]] = i + presetsLength;
}
order.und = i + 1;
return order;
})();
var NOP_FUNCTION = function() {};
var onscreen = function(row) {
var id = row.dataset.uuid;
var group = row.dataset.group;
if (!id || !group) {
return;
}
rowsOnScreen[id] = rowsOnScreen[id] || {};
rowsOnScreen[id][group] = row;
monitor && monitor.pauseMonitoringMutations();
renderLoadedContact(row, id);
updateRowStyle(row, true);
renderPhoto(row, id, false, group);
updateSingleRowSelection(row, id);
// Since imgLoader.reload() causes sync reflows we only want to make this
// call when something happens that affects our onscreen view. Therefore
// we defer the call until here when we know the visibility monitor has
// detected a change and called onscreen().
if (imgLoader && needImgLoaderReload) {
needImgLoaderReload = false;
imgLoader.reload();
}
if (_notifyRowOnScreenUUID === id) {
_notifyRowOnScreenCallback(row);
_clearNotifyRowOnScreenByUUID();
}
monitor && monitor.resumeMonitoringMutations(false);
};
var renderLoadedContact = function(el, id) {
if (el.dataset.rendered) {
return;
}
id = id || el.dataset.uuid;
var group = el.dataset.group;
var contact = loadedContacts[id] ? loadedContacts[id][group] : null;
if (!contact) {
return;
}
renderContact(contact, el);
clearLoadedContact(el, id, group);
};
var clearLoadedContact = function(el, id, group) {
if (!el.dataset.rendered || !el.dataset.order || !el.dataset.search) {
return;
}
id = id || el.dataset.uuid;
group = group || el.dataset.group;
if (loadedContacts[id]) {
loadedContacts[id][group] = null;
}
};
var offscreen = function(row) {
var id = row.dataset.uuid;
var group = row.dataset.group;
if (!id || !group) {
return;
}
if (rowsOnScreen[id]) {
delete rowsOnScreen[id][group];
}
monitor && monitor.pauseMonitoringMutations();
updateRowStyle(row, false);
var search = window.Search;
if (!search || !search.isInSearchMode()) {
releasePhoto(row);
}
monitor && monitor.resumeMonitoringMutations(false);
};
var init = function load(element, reset) {
_ = navigator.mozL10n.get;
cancel = document.getElementById('cancel-search'),
contactsListView = document.getElementById('view-contacts-list'),
fastScroll = document.querySelector('nav[data-type="scrollbar"]'),
scrollable = document.querySelector('#groups-container');
settingsView = document.querySelector('#view-settings .view-body-inner');
noContacts = document.querySelector('#no-contacts');
groupsList = document.getElementById('groups-list');
groupsList.addEventListener('click', onClickHandler);
initConfiguration();
// Test code calls init() directly, so we may have to reset.
if (reset) {
resetDom();
}
window.addEventListener('list-shown', function() {
if (!loading) {
return;
}
ContactsService.resume(function isRendered(contact) {
return !!loadedContacts[contact.id];
});
});
createPhotoTemplate();
Cache.oneviction = onCacheEvicted;
};
function hide() {
contactsListView.classList.add('hide');
if (monitor) {
monitor.pauseMonitoringMutations();
}
}
function show() {
contactsListView.classList.remove('hide');
needImgLoaderReload = true;
if (monitor) {
monitor.resumeMonitoringMutations(true);
}
}
// Define a source adapter object to pass to Search.
//
// Since multiple, separate apps use Search its important for
// the search code to function independently. This adapter object allows
// the search module to access the app's contacts without knowing anything
// about our DOM structure.
//
// Sections marked as 'non searchable' will not display the fields, in this
// case the favourites sections and the ICE section, since will provide
// duplicate results.
var NODE_SELECTOR = 'section:not([data-nonsearchable="true"]) > ol > li';
var searchSource = {
getNodes: function() {
var domNodes = contactsListView.querySelectorAll(NODE_SELECTOR);
return Array.prototype.slice.call(domNodes);
},
getFirstNode: function() {
return contactsListView.querySelector(NODE_SELECTOR);
},
getNextNode: function(contact) {
var out = contact.nextElementSibling;
var nextParent = contact.parentNode.parentNode.nextElementSibling;
while (!out && nextParent) {
out = nextParent.querySelector('ol > li:first-child');
nextParent = nextParent.nextElementSibling;
}
return out;
},
// While loading we expect to feed search more nodes via the
// Search.appendNodes() function.
expectMoreNodes: function() {
return loading;
},
// Contact nodes are not rendered until visible on screen. To avoid
// cloning an empty placeholder try to render the node before calling
// cloneNode().
clone: function(node) {
var id = node.dataset.uuid;
renderLoadedContact(node, id);
updateRowStyle(node, true);
updateSingleRowSelection(node, id);
var out = node.cloneNode(true);
renderPhoto(out, id, true, node.dataset.group);
return out;
},
getNodeById: function(id) {
return contactsListView.querySelector('[data-uuid="' + id + '"]');
},
// The calculation of the search text is delayed until the full list item
// is rendered. Therefore, it may not be available yet. If this is the
// case then calculate the search text before returning the value.
getSearchText: function(node) {
renderSearchString(node);
return node.dataset.search;
},
click: onClickHandler
}; // searchSource
var initSearch = function initSearch(callback) {
Search.init(searchSource, true, selectNavigationController);
if (callback) {
callback();
}
};
var initAlphaScroll = function initAlphaScroll() {
var overlay = document.querySelector('nav[data-type="scrollbar"] p');
var jumper = document.querySelector('nav[data-type="scrollbar"] ol');
var params = {
overlay: overlay,
jumper: jumper,
groupSelector: '#group-',
scrollToCb: scrollToCb
};
utils.alphaScroll.init(params);
if (iceContacts.length > 0) {
utils.alphaScroll.showGroup('ice');
} else {
utils.alphaScroll.hideGroup('ice');
}
};
var scrollToCb = function scrollCb(domTarget, group) {
if (domTarget.offsetTop > 0) {
scrollable.scrollTop = domTarget.offsetTop;
} else if (group === 'search-container') {
scrollable.scrollTop = 0;
}
};
var load = function load(contacts, forceReset, callback) {
var onError = function() {
console.log('ERROR Retrieving contacts');
};
var complete = function complete() {
initConfiguration(function onInitConfiguration() {
getContactsByGroup(onError, contacts).then(() => {
if (typeof callback === 'function') {
callback();
} // Used in unit testing.
});
});
};
if (loaded || forceReset) {
resetDom(complete);
return;
}
complete();
};
function getFbUid(devContact) {
var out;
if (Array.isArray(devContact.category)) {
var idx = devContact.category.indexOf('facebook');
if (idx !== -1) {
out = devContact.category[idx + 2];
}
}
return out;
}
/**
* Reads configuration values setup at build time to change
* behaviour of the contacts list.
* Receives a callback as parameter to call once the
* parameters have been setup.
* Also tries to save from the external file to faster cookie
* values after the first file read.
* @param (Function) callback function to be invoked after process
*/
var initConfiguration = function initConfiguration(callback) {
callback = callback || function() {};
if (orderByLastName !== null && defaultImage !== null) {
callback();
return;
}
var config = utils.cookie.load();
if (config) {
orderByLastName = config.order;
defaultImage = config.defaultImage;
callback();
return;
}
utils.config.load('/contacts/config.json').then(function ready(configData) {
orderByLastName = (configData.defaultContactsOrder ===
ORDER_BY_FAMILY_NAME ? true : false);
defaultImage = configData.defaultImage === true;
utils.cookie.update({
order: orderByLastName,
defaultImage: defaultImage
});
callback();
}, function configError(err) {
window.console.error('Error while reading configuration file');
orderByLastName = utils.cookie.getDefault('order');
defaultImage = utils.cookie.getDefault('defaultImage');
utils.cookie.update({
order: orderByLastName,
defaultImage: defaultImage
});
callback();
});
};
var renderGroupHeader = function renderGroupHeader(group, letter) {
// Create the DOM for the group list
var letteredSection = document.createElement('section');
letteredSection.id = 'section-group-' + group;
letteredSection.className = 'group-section';
var title = document.createElement('header');
title.id = 'group-' + group;
title.className = 'hide';
if (group === 'favorites') {
letteredSection.dataset.nonsearchable = true;
}
var letterAbbr = document.createElement('abbr');
var letterAbbrId = 'contacts-listed-abbr-' + group;
letterAbbr.setAttribute('title', 'Contacts listed ' + group);
letterAbbr.setAttribute('aria-hidden', true);
letterAbbr.id = letterAbbrId;
letterAbbr.textContent = letter;
title.setAttribute('aria-labelledby', letterAbbrId);
title.appendChild(letterAbbr);
var contactsContainer = document.createElement('ol');
contactsContainer.setAttribute('role', 'listbox');
contactsContainer.setAttribute('aria-labelledby', letterAbbrId);
contactsContainer.id = 'contacts-list-' + group;
contactsContainer.dataset.group = group;
letteredSection.appendChild(title);
letteredSection.appendChild(contactsContainer);
// Save the list off for easy access, later
headers[group] = contactsContainer;
// Now we must insert the new <section> into the DOM. Since groups can
// be created at any time we must insert the section in the correct
// order.
// If there are no other groups yet, then its easy. Just append.
if (groupsList.children.length === 0) {
groupsList.appendChild(letteredSection);
return;
}
// Determine the correct position for this group.
var order = GROUP_ORDER[group];
// If we cannot find a defined ordering for this group, then fall back
// on appending.
if (typeof order !== 'number') {
groupsList.appendChild(letteredSection);
return;
}
// Search for the correct insertion point using a simple O(n) iteration.
// Since the number of groups is constrained and relatively small this
// should be reasonable.
//
// As a minor optimization, begin iterating from the back of the list.
// This matches the most common case of appending a new group to the
// end which is what we need to do during first load.
for (var i = groupsList.children.length - 1; i >= 0; --i) {
var node = groupsList.children[i];
var cmpGroup = node.lastChild.dataset.group;
var cmpOrder = GROUP_ORDER[cmpGroup];
if (cmpOrder <= order) {
var next = node.nextSibling;
if (next) {
groupsList.insertBefore(letteredSection, next);
} else {
groupsList.appendChild(letteredSection);
}
break;
}
}
// If we did not already insert the section, then it must belong at the
// front of the groupsList.
if (i < 0) {
groupsList.insertBefore(letteredSection, groupsList.firstChild);
}
};
// Retrieve the list for a given group. Never directly access headers[].
function getGroupList(group) {
// If the group already exists, just return it.
var list = headers[group];
if (list) {
return list;
}
// Otherwise we need to create group list just-in-time.
// Determine the short name or "letter" for the group.
var letter = GROUP_LETTERS[group];
if (typeof letter !== 'string') {
letter = group;
}
renderGroupHeader(group, letter);
// Return the new list created by renderGroupHeader() above
return headers[group];
}
// Render basic DOM structure and text for the contact. If a placeholder
// has already been created then it may be provided in the optional second
// argument. Photos and social marks are lazy loaded.
var renderContact = function renderContact(contact, container) {
container = container || createPlaceholder(contact);
var fbUid = getFbUid(contact);
if (fbUid) {
container.dataset.fbUid = fbUid;
}
container.className = 'contact-item';
container.setAttribute('role', 'option');
var timestampDate = contact.updated || contact.published || new Date();
container.dataset.updated = timestampDate.getTime();
var check = getSelectCheck(contact.id);
container.appendChild(check);
// contactInner is a link with 3 p elements:
// name, social marks and org
var display = getDisplayName(contact);
var nameElement = getHighlightedName(display);
container.appendChild(nameElement);
renderOrg(contact, container, true);
container.dataset.rendered = true;
return container;
};
// "Render" search string into node's data-search attribute. If the
// contact is not already known, try to look it up in our cache of loaded
// contacts. This is used to defer the computation of the search string
// since profiling has shown it to be expensive.
var renderSearchString = function renderSearchString(node, contact) {
if (node.dataset.search) {
return;
}
contact = contact || loadedContacts[node.dataset.uuid][node.dataset.group];
if (!contact) {
return;
}
var display = getDisplayName(contact);
node.dataset.search = getSearchString(contact, display);
clearLoadedContact(node, contact.id, node.dataset.group);
};
var renderOrderString = function renderOrderString(node, contact) {
if (node.dataset.order) {
return;
}
contact = contact || loadedContacts[node.dataset.uuid][node.dataset.group];
if (!contact) {
return;
}
var display = getDisplayName(contact);
node.dataset.order = getStringToBeOrdered(contact, display);
clearLoadedContact(node, contact.id, node.dataset.group);
};
// Create a mostly empty list item as a placeholder for the contact. All
// visibile DOM elements will be rendered later via the visibility monitor.
// This function ensures that necessary meta data is defined in the node
// dataset.
var createPlaceholder = function createPlaceholder(contact, group) {
var ph = document.createElement('li');
ph.dataset.uuid = contact.id;
group = group || getFastGroupName(contact);
var order = null;
if (!group) {
order = getStringToBeOrdered(contact);
group = getGroupNameByOrderString(order);
}
ph.setAttribute('role', 'option');
ph.dataset.group = group;
// NOTE: We want the group value above to be based on the raw data so that
// we get the und group if there is no name. But we want to display
// "noName" if there is nothing reasonable to show. So recalculate
// the order value if we're missing a name. In the common case,
// though, avoid calculating the order string twice.
// If we didn't change the name at all during the refill and we already
// calculated the order string, then go ahead and save it instead of
// recalculating it later.
var display = getDisplayName(contact);
if (!display.modified && order) {
ph.dataset.order = order;
}
return ph;
};
var getStringValue = function getStringValue(contact, field) {
if (contact[field] && contact[field][0]) {
return String(contact[field][0]).trim();
}
return null;
};
var getSearchString = function getSearchString(contact, display) {
display = display || contact;
var searchInfo = [];
var searchable = ['givenName', 'familyName'];
searchable.forEach(function(field) {
var value = getStringValue(display, field);
if (value) {
searchInfo.push(value);
}
});
var value = getStringValue(contact, 'org');
if (value) {
searchInfo.push(value);
}
if (contact.tel && contact.tel.length) {
for (var i = contact.tel.length - 1; i >= 0; i--) {
var current = contact.tel[i];
searchInfo.push(current.value);
}
}
var escapedValue = Normalizer.escapeHTML(searchInfo.join(' '), true);
return Normalizer.toAscii(escapedValue);
};
function getHighlightedName(contact, ele) {
if (!ele) {
ele = document.createElement('p');
}
ele.classList.add('contact-text');
var bdi = document.createElement('bdi');
var givenName = (contact.givenName && contact.givenName[0]) || '';
var familyName = (contact.familyName && contact.familyName[0]) || '';
function createStrongTag(content) {
var fs = document.createElement('strong');
fs.textContent = content;
return fs;
}
if (orderByLastName) {
bdi.appendChild(document.createTextNode(givenName + ' '));
bdi.appendChild(createStrongTag(familyName));
} else {
bdi.appendChild(createStrongTag(givenName));
bdi.appendChild(document.createTextNode(' ' + familyName));
}
ele.appendChild(bdi);
return ele;
}
function createSocialMark() {
var span = document.createElement('span');
span.classList.add('icon-social');
return span;
}
function markAsFb(ele) {
ele.classList.add('icon-fb');
return ele;
}
var CHUNK_SIZE = 20;
function loadChunk(chunk) {
var nodes = [];
for (var i = 0, n = chunk.length; i < n; ++i) {
var newNodes = appendToLists(chunk[i]);
nodes.push.apply(nodes, newNodes);
}
// If the search view has been activated by the user, then send newly
// loaded contacts over to populate any in-progress search. Nothing
// to do if search is not actived.
if (window.Search && Search.appendNodes) {
Search.appendNodes(nodes);
}
}
function loadVisibilityMonitor() {
return new Promise((resolve) => {
LazyLoader.load('/shared/js/tag_visibility_monitor.js', () => {
var scrollMargin = ~~(getViewHeight() * 1.5);
// NOTE: Making scrollDelta too large will cause janky scrolling
// due to bursts of onscreen() calls from the monitor.
var scrollDelta = ~~(scrollMargin / 15);
monitor = monitorTagVisibility(scrollable, 'li', scrollMargin,
scrollDelta, onscreen, offscreen);
resolve();
});
});
}
function getViewHeight(config) {
if (viewHeight < 0) {
config = config || utils.cookie.load();
if (config && config.viewHeight > -1) {
viewHeight = config.viewHeight;
} else {
viewHeight = scrollable.getBoundingClientRect().height;
// If the groups list is hiden, we'll get no height and so we don't
// store it.
if (viewHeight) {
utils.cookie.update({viewHeight: viewHeight});
}
}
}
return viewHeight;
}
function getRowsPerPage() {
if (rowsPerPage < 0) {
var config = utils.cookie.load();
if (config && config.rowsPerPage > -1) {
rowsPerPage = config.rowsPerPage;
}
}
// If we couldn't load from config, then return max int since we can't
// calculate yet
if (rowsPerPage < 0) {
return MAX_INT;
}
// Otherwise return loaded config value
return rowsPerPage;
}
function setRowsPerPage(row) {
if (rowsPerPage > -1) {
return;
}
var rowHeight = row.getBoundingClientRect().height;
rowsPerPage = Math.ceil(getViewHeight() / rowHeight);
utils.cookie.update({rowsPerPage: rowsPerPage});
}
// Utility function for appending a newly loaded contact to both its default
// group and, if necessary, the favorites list.
function appendToLists(contact) {
updatePhoto(contact);
var ph = createPlaceholder(contact);
var groups = [ph.dataset.group];
if (isFavorite(contact)) {
groups.push('favorites');
}
var nodes = [];
for (var i = 0, n = groups.length; i < n; ++i) {
ph = appendToList(contact, groups[i], ph);
nodes.push(ph);
ph = null;
}
selectedContacts[contact.id] = selectAllPending;
return nodes;
}
// Adds each contact to its group container
function appendToList(contact, group, ph) {
ph = ph || createPlaceholder(contact, group);
var list = getGroupList(group);
var inCache = Cache.active &&
(Cache.hasContact(contact.id)) ||
(group == 'favorites' && Cache.hasFavorite(contact.id));
// If above the fold for list or if the contact is in the cache,
// create the DOM node. If the contact is in the cache and has not
// changed, we won't append it to the DOM.
if (list.children.length < getRowsPerPage() || inCache) {
renderContact(contact, ph);
}
if (!loadedContacts[contact.id]) {
loadedContacts[contact.id] = {};
}
loadedContacts[contact.id][group] = contact;
var previousNode;
// If the contact is in the cache but nothing changed, we bail out.
// Otherwise, we remove the DOM node and let the flow continue so we
// can append the new node with the updated information.
if (inCache) {
var cachedContact;
if (group == 'favorites') {
cachedContact = Cache.getFavorite(contact.id);
} else {
cachedContact = Cache.getContact(contact.id);
}
// We don't add Facebook information while creating the placeholder,
// this information is added afterwards in renderFbData.
// Because of that, we need to get rid of the additional information
// from the cached contact before checking against the original contact
// information.
if (contact.category &&
contact.category.indexOf('facebook') != -1) {
var separator =
'<p class="contact-text"><span class="icon-social';
cachedContact = cachedContact.split(separator)[0];
}
if (cachedContact === ph.innerHTML) {
ph = null;
return;
}
var toReplace = list.querySelector('li[data-uuid=\"' +
contact.id + '\"]');
previousNode = toReplace.nextElementSibling;
toReplace.parentNode.removeChild(toReplace);
}
// It is possible that a new contact has been added while the app was
// closed. In that case, we need to check if the new contact needs
// to be inserted in the first chunk so it is later cached.
if (Cache.active && (Cache.updated < contact.updated)) {
renderOrderString(ph, contact);
if (Cache.lastOrderString > ph.dataset.order) {
var listElements = list.getElementsByTagName('li');
var insertAt = searchNodes(listElements, ph.dataset.order);
previousNode = listElements[insertAt];
}
}
if (previousNode) {
list.insertBefore(ph, previousNode);
} else {
list.appendChild(ph);
}
if (list.children.length === 1) {
showGroupByList(list);
setRowsPerPage(list.firstChild);
}
return ph;
}
// Methods executed after rendering the list
// by first time
var onListRendered = function onListRendered() {
// We cancel any pending intent of selection
// Now any new contact added to the list will
// be selected just if we clicked on select all
// and we didn't unselected any other contact
selectAllPending = false;
loadVisibilityMonitor();
// Replacing old message 'startup-path-done'
utils.PerformanceHelper.loadEnd();
LazyLoader.load([
'/contacts/js/fb/fb_init.js',
'/contacts/js/fb_loader.js',
'/shared/js/contacts/utilities/image_loader.js'
], () => {
fb.init(function contacts_init() {
if (fb.isEnabled) {
Contacts.loadFacebook(NOP_FUNCTION);
}
lazyLoadImages();
loaded = true;
});
});
loadICE().then(() => {
if (Cache.enabled) {
// Once we've rendered the whole list, we can check if what we added
// in the cached chunk is valid.
verifyAndRebuildCache();
}
});
};
/**
* Check if we have ICE contacts information
*/
var ICELoaded;
function loadICE() {
if (ICELoaded) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
LazyLoader.load([
'/contacts/js/utilities/ice_data.js',
'/shared/js/contacts/utilities/ice_store.js'],
function() {
ICEStore.getContacts().then((ids) => {
ICELoaded = true;
displayICEIndicator(ids);
resolve();
});
ICEStore.onChange(function() {
ICEStore.getContacts().then(displayICEIndicator);
});
});
});
}
function displayICEIndicator(ids) {
if (!iceGroup) {
buildICEGroup();
} else {
addICEListeners();
}
if (!ids || !ids.length) {
hideICEGroup();
return;
}
iceContacts = ids;
showICEGroup();
}
function toggleICEGroup(show) {
if (!iceGroup) {
return;
}
forceICEGroupToBeHidden = !(!!show);
forceICEGroupToBeHidden ? hideICEGroup() : showICEGroup();
}
function showICEGroup() {
// If the ICE group has been hidden programmatically by means of
// <toggleICEGroup> it will only be displayed again using the same
// mechanism regardless updates.
if (forceICEGroupToBeHidden) {
return;
}
iceGroup.classList.remove('hide');
utils.alphaScroll.showGroup('ice');
}
function hideICEGroup() {
iceGroup.classList.add('hide');
utils.alphaScroll.hideGroup('ice');
}
function buildICEGroup() {
iceGroup = document.createElement('section');
iceGroup.classList.add('group-section');
iceGroup.id = 'section-group-ice';
iceGroup.dataset.nonsearchable = true;
var list = document.createElement('ol');
list.dataset.group = 'ice';
list.id = 'contact-list-ice';
list.role = 'listbox';
var elem = document.createElement('li');
elem.classList.add('contact-item');
elem.dataset.group = 'ice';
var icon = document.createElement('span');
icon.src = '/contacts/style/images/icon_ice.png';
var p = document.createElement('p');
p.classList.add('contact-text');
p.setAttribute('data-l10n-id', 'ICEContactsGroup');
groupsList.insertBefore(iceGroup, groupsList.firstChild)
.appendChild(list).appendChild(elem);
elem.appendChild(icon);
elem.appendChild(p);
addICEListeners();