/
fxos-fastlist.js
3485 lines (2969 loc) · 85.9 KB
/
fxos-fastlist.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
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("fxos-component"));
else if(typeof define === 'function' && define.amd)
define(["fxos-component"], factory);
else if(typeof exports === 'object')
exports["FXOSFastlist"] = factory(require("fxos-component"));
else
root["FXOSFastlist"] = factory(root["fxosComponent"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Dependencies
*/
var component = __webpack_require__(1);
var FastList = __webpack_require__(2);
var scheduler = FastList.scheduler;
var popel = __webpack_require__(4);
__webpack_require__(6);
/**
* Pointer abstractions
*/
var isTouch = 'ontouchstart' in window;
var touchcancel = isTouch ? 'touchcancel' : 'mousecancel';
var touchstart = isTouch ? 'touchstart' : 'mousedown';
var touchmove = isTouch ? 'touchmove' : 'mousemove';
var touchend = isTouch ? 'touchend' : 'mouseup';
/**
* Mini Logger
*
* @type {Function}
*/
var debug = 0 ? (...args) => console.log('[fxos-fastlist]', ...args) : () => {};
/**
* Cache to persist content.
*
* We open ASAP as we need the cached
* HTML content for the first-paint.
* As it's async it can be done in
* the background.
*
* @type {Promise}
*/
var cachesOpen = caches.open('gfl');
/**
* Used to hide private properties behind.
*
* @type {Symbol}
*/
var keys = {
internal: Symbol(),
first: Symbol(),
img: Symbol()
};
/**
* Public prototype.
*
* @type {Object}
*/
var FXOSFastlistProto = {
extensible: false,
/**
* Default store up to 5mb of images.
*
* @type {Number}
*/
imageCacheSize: 5e6,
/**
* Default store up to 500 images
* before entries start getting
* discarded.
*
* @type {Number}
*/
imageCacheLength: 500,
/**
* Called when the component is first created.
*
* @private
*/
created() {
debug('create');
this.setupShadowRoot();
this.caching = this.getAttribute('caching');
this.offset = this.getAttribute('offset');
this.picker = this.getAttribute('picker');
this.bottom = this.getAttribute('bottom');
this.top = this.getAttribute('top');
this[keys.internal] = new Internal(this);
},
/**
* Used to define configuration passed
* to internal FastList instantiation.
*
* NOTE: Must be called before `model`
* if defined.
*
* @param {Object} props
* @public
*/
configure(props) {
debug('configure');
this[keys.internal].configure(props);
},
/**
* Set a data model for the list to render.
*
* The returned Promise will resolve
* when rendering has *fully* completed.
*
* The `.rendered` Promise can be used
* to determine when the list is *visually*
* complete.
*
* @param {Array} value
* @return {Promise}
* @public
*/
setModel(value) {
return this[keys.internal].setModel(value);
},
/**
* Should be called by the user when
* they have finished incrementally
* updating there model.
*
* This acts as an internal hook used
* for updating caches.
*
* This only really concerns users
* who are using caching and fetching
* their model in chunks.
*
* @public
*/
cache() {
debug('cache');
if (!this.caching) return;
this[keys.internal].cachedHeight = null;
return this[keys.internal].updateCache();
},
/**
* Clear cached height and html.
*
* @public
*/
clearCache() {
debug('clear cache');
this[keys.internal].clearCache();
},
/**
* Smooth scrolls to the given position.
*
* @param {Number} y
* @return {Promise}
*/
scrollTo(y) {
return this[keys.internal].scrollTo(y);
},
/**
* Permanently destroy the component.
*
* @public
*/
destroy() {
this[keys.internal].destroy();
},
/**
* Public attributes/properties configuration
* used by fxos-component.js.
*
* @type {Object}
*/
attrs: {
rendered: {
get() { return this[keys.internal].rendered.promise; }
},
top: {
get() { return this._top; },
set(value) {
debug('set top', value);
if (value == null) return;
value = Number(value);
if (value === this._top) return;
this.setAttribute('top', value);
this._top = value;
}
},
bottom: {
get() { return this._bottom; },
set(value) {
debug('set bottom', value);
if (value == null) return;
value = Number(value);
if (value === this._bottom) return;
this.setAttribute('bottom', value);
this._bottom = value;
}
},
caching: {
get() { return this._caching; },
set(value) {
value = value || value === '';
if (value === this._caching) return;
if (value) this.setAttribute('caching', '');
else this.removeAttribute('caching');
this._caching = value;
}
},
offset: {
get() { return this._offset || 0; },
set(value) {
if (value == this._offset) return;
if (value) this.setAttribute('offset', value);
else this.removeAttribute('offset');
this._offset = Number(value);
}
},
scrollTop: {
get() { return this[keys.internal].getScrollTop(); },
set(value) { this[keys.internal].setScrollTop(value); }
},
minScrollHeight: {
get() { return this[keys.internal].list.style.minHeight; },
set(value) { this[keys.internal].list.style.minHeight = value; }
},
picker: {
get() { return this._picker; },
set(value) {
value = value || value === '';
if (value === this._picker) return;
if (value) this.setAttr('picker', '');
else this.removeAttr('picker');
this._picker = value;
}
}
},
/*jshint ignore:start*/
template: `
<div class="inner">
<div class="picker"><content select="[picker-item]"></content></div>
<div class="overlay"><div class="text">X</div><div class="icon">search</div></div>
<div class="fastlist">
<ul><content></content></ul>
</div>
</div>
<style>
:host {
display: block;
height: 100%;
overflow: hidden;
text-align: match-parent;
color:
var(--fxos-fastlist-color,
var(--fxos-color));
}
.inner {
position: relative;
height: 100%;
}
.fastlist {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
padding: 0 17px;
}
[picker] .fastlist {
offset-inline-end: 26px; /* picker width */
padding-inline-end: 12px;
}
.fastlist ul {
position: relative;
padding: 0;
margin: 0;
list-style: none;
}
::content .gfl-header {
position: sticky;
top: -20px;
z-index: 100;
margin: 0 !important;
padding-top: 20px;
padding-bottom: 1px;
margin-bottom: -1px !important;
width: calc(100% + 1px);
}
::content .gfl-item {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
height: 60px;
padding: 0 9px;
overflow: hidden;
box-sizing: border-box;
list-style-type: none;
text-decoration: none;
-moz-user-select: none;
border-top: solid 1px
var(--fxos-fastlist-border-color,
var(--fxos-border-color,
#e7e7e7));
background:
var(--fxos-fastlist-background,
var(--fxos-background));
}
::content .gfl-item.first {
border-top-color: transparent;
}
::content .gfl-item[unread=true],
::content .gfl-item[unread=false] {
-moz-padding-start: 18px;
}
::content .gfl-item[unread=true]:before,
::content .gfl-item[unread=false]:before {
content: '';
position: absolute;
offset-inline-start: 0;
top: 50%;
display: block;
width: 8px;
height: 8px;
margin-top: -4px;
border-radius: 50%;
background-color:
var(--fxos-fastlist-unread-color,
var(--fxos-brand-color,
currentColor));
}
::content .gfl-item[unread=false]:before {
visibility: hidden;
}
::content .image {
position: absolute;
top: 8px;
offset-inline-end: 7px;
width: 44px;
height: 44px;
}
::content .image.round,
::content .image.round > img {
width: 42px;
height: 42px;
border-radius: 50%;
}
::content .gfl-item .image.round {
top: 8.5px;
offset-inline-end: 0;
background:
var(--fxos-fastlist-border-color,
var(--fxos-border-color));
}
::content .gfl-item img {
position: absolute;
left: 0;
top: 0;
width: 44px;
height: 44px;
opacity: 0;
}
::content .cached .gfl-item img {
display: none;
}
::content h3,
::content p {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
::content :-moz-dir(ltr) .image ~ h3,
::content :-moz-dir(ltr) .image ~ p {
padding-right: 52px;
}
::content :-moz-dir(rtl) .image ~ h3,
::content :-moz-dir(rtl) .image ~ p {
padding-left: 52px;
}
::content :-moz-dir(ltr) .image.round ~ h3,
::content :-moz-dir(ltr) .image.round ~ p {
padding-right: 42px;
}
::content :-moz-dir(rtl) .image.round ~ h3,
::content :-moz-dir(rtl) .image.round ~ p {
padding-left: 42px;
}
::content h3 {
margin: 0;
font-size: 20px;
font-weight: 400;
font-style: normal;
color:
var(--fxos-title-color,
var(--fxos-color));
}
::content p {
margin: 0;
font-size: 15px;
line-height: 1.35em;
}
::content a {
color: inherit;
}
.picker {
display: none;
}
[picker] .picker {
position: absolute;
right: 0;
top: 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 35px;
height: 100%;
padding: 2px 0;
}
::content [picker-item] {
display: flex;
justify-content: center;
align-items: center;
flex: 1;
min-height: 0;
text-decoration: none;
text-align: center;
color: inherit;
}
::content [picker-item][data-icon] {
font-size: 0; /* hide icon text-label */
}
::content [picker-item]:before {
font-size: 19px;
-moz-user-select: none;
}
.picker a {
display: flex;
justify-content: center;
align-items: center;
flex: 1;
text-decoration: none;
text-align: center;
font-size: 13px;
color: inherit;
text-transform: uppercase;
-moz-user-select: none;
}
.overlay {
position: absolute;
left: 50%;
top: 50%;
z-index: 200;
display: none;
width: 1.8em;
height: 1.8em;
margin: -1em 0 0 -1em;
font-size: 70px;
text-align: center;
line-height: 1.8;
font-weight: 300;
border-radius: 50%;
opacity: 0;
pointer-events: none;
transition: opacity 400ms;
text-transform: uppercase;
background:
var(--fxos-fastlist-overlay-background,
currentColor);
}
[picker] .overlay {
display: block;
}
.overlay.visible {
opacity: 1;
transition: opacity 100ms;
}
.overlay > .icon,
.overlay > .text {
color: #fff;
}
.overlay > .icon {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
font-family: "fxos-icons";
font-weight: 500;
text-transform: none;
text-rendering: optimizeLegibility;
}
</style>`,
/*jshint ignore:end*/
// test hooks
FastList: FastList
};
/**
* Private internals.
* @param {FXOSFastlist} el
*/
function Internal(el) {
var shadow = el.shadowRoot;
this.el = el;
this.renderedCache = this.renderCache();
this.listCreated = new Deferred();
this.rendered = new Deferred();
this.images = {
list: [],
hash: {},
bytes: 0
};
this.els = {
list: shadow.querySelector('ul'),
picker: shadow.querySelector('.picker'),
overlay: shadow.querySelector('.overlay'),
overlayIcon: shadow.querySelector('.overlay > .icon'),
overlayText: shadow.querySelector('.overlay > .text'),
container: shadow.querySelector('.fastlist'),
listContent: shadow.querySelector('.fastlist content'),
pickerItems: []
};
// define property names for FastList
this.container = this.els.container;
this.list = this.els.list;
this.itemContainer = el;
this.configureTemplates();
this.setupPicker();
// don't memory leak ObjectURLs
addEventListener('pagehide', () => this.emptyImageCache());
debug('initialized');
}
Internal.prototype = {
headerHeight: 40,
itemHeight: 60,
/**
* Setting the model for the first
* time creates a new FastList. Setting
* it subsequent times rerenders
* the FastList with the new data.
*
* @param {Array} model
* @private
*/
setModel(model) {
debug('set model');
if (!model) return Promise.reject(new Error('model undefined'));
this.sections = this.sectionize(model);
this.model = model;
return !this.fastList
? this.createList()
: this.reloadData();
},
/**
* Creates the FastList.
*
* We add the fast-gradient last as it's
* expensive to paint (50-80ms) and only
* required for scrolling, not first paint.
*
* @return {Promise}
* @private
*/
createList() {
return this.renderedCache
.then(() => {
debug('create list');
this.fastList = new this.el.FastList(this);
return this.fastList.rendered;
})
.then(() => {
this.rendered.resolve();
this.els.list.style.transform = '';
this.removeCachedRender();
return this.fastList.complete;
})
.then(() => {
this.updateFastGradient();
this.listCreated.resolve();
});
},
/**
* Reloading the list will completely
* re-render the list.
*
* We must empty the image cache as data
* may have changed or item indexed
* may not longer map to new model.
*
* We must update the fast-gradient
* as scrollHeight determines whether
* fast-gradient needs to be painted.
*
* @private
*/
reloadData() {
return this.listCreated.promise
.then(() => {
debug('reload data');
this.emptyImageCache();
return this.fastList.reloadData();
})
.then(() => this.updateFastGradient());
},
/**
* Sorts items into sections using
* the user provided getSectionName()
*
* @param {Array} items
* @return {Object}
*/
sectionize(items) {
debug('sectionize');
var sectioned = !!this.getSectionName;
var count = 0;
var result = {};
for (var i = 0, l = items.length; i < l; i++) {
var item = items[i];
var section = sectioned && this.getSectionName(item);
// When a section is not defined, flag
// first list items and skip logic
if (!section) {
if (i === 0) item[keys.first] = true;
else if (item[keys.first]) delete item[keys.first];
continue;
}
// When there is no section yet
// we can assume that this item
// is the first item in the section.
if (!result[section]) {
result[section] = [];
item[keys.first] = true;
// Make sure that any previously
// assigned flags are removed as
// order of items can be changed.
} else if (item[keys.first]) {
delete item[keys.first];
}
result[section].push(item);
count++;
}
this.hasSections = !!count;
return this.hasSections && result;
},
/**
* Mixin properties/methods into the
* 'data-source' object passed to FastList.
*
* @param {Object} props
*/
configure(props) {
Object.assign(this, props);
},
/**
* Defines the templates to be used
* for the sections and items.
*
* Users can provide templates by
* placing <template> in the root
* of their <fxos-fastlist>
*
* @private
*/
configureTemplates() {
var templateHeader = this.el.querySelector('template[header]');
var templateItem = this.el.querySelector('template[item]');
var noTemplates = !templateItem && !templateHeader;
// If no exact templates found, use unlabeled <template> for item
if (noTemplates) templateItem = this.el.querySelector('template');
if (templateHeader) {
this.templateHeader = templateHeader.innerHTML;
templateHeader.remove();
}
if (templateItem) {
this.templateItem = templateItem.innerHTML;
templateItem.remove();
}
},
/**
* Called by FastList when it needs
* to create a list-item element.
*
* @return {HTMLElement}
*/
createItem() {
debug('create item');
this.parsedItem = this.parsedItem || popel.parse(this.templateItem);
var el = popel.create(this.parsedItem.cloneNode(true));
el[keys.img] = el.querySelector('img');
el.classList.add('gfl-item');
return el;
},
/**
* Called by FastList when it needs
* to create a section element.
*
* @return {HTMLElement}
*/
createSection(name) {
this.parsedSection = this.parsedSection
|| popel.parse(this.templateHeader);
var header = popel.create(this.parsedSection.cloneNode(true));
var section = document.createElement('div');
header.classList.add('gfl-header');
section.appendChild(header);
section.classList.add('gfl-section');
section.id = `gfl-section-${name}`;
return section;
},
/**
* Populates a list-item with data.
*
* If items were inflated from the HTML cache
* they won't yet be popel elements; in
* which case we have to replace them
* before we can populate them with data.
*
* @param {HTMLElement} el
* @param {Number} i
*/
populateItem(el, i) {
var record = this.getRecordAt(i);
popel.populate(el, record);
el.classList.toggle('first', !!record[keys.first]);
},
/**
* Populates the list-item image if one is
* present in the template and the user
* has configured `getItemImageSrc()`.
*
* .populateItemDetail() is run only when the
* list is 'idle' (stopped or slow) so that
* we don't harm scrolling performance.
*
* NOTE: It seems sometimes fastlist may
* be calling this function more than
* once per item. Need to look into this.
*
* @param {HTMLElement} el list-item node
* @param {Number} i index
* @private
*/
populateItemDetail(el, i) {
if (!this.getItemImageSrc) return;
debug('populate item detail', i);
var img = el[keys.img];
if (!img) return;
var record = this.getRecordAt(i);
var cached = this.getCachedImage(i);
// if we have the image cached
// we can just load it sync
if (cached) {
load(cached);
return;
}
// if we don't have the image we
// run the user's getter function
Promise.resolve(this.getItemImageSrc(record, i))
.then(result => {
if (!result) return;
// There is a chance that the item could have
// been recycled before the user was able to
// fetch the image. Abort here if that's the case.
if (el.dataset.index != i) return debug('item recycled');
var image = {
src: normalizeImageSrc(result),
bytes: result.size || result.length
};
this.cacheImage(image, i);
load(image);
}).catch(e => { throw e; });
/**
* Loads
* @param {[type]} image [description]
* @return {[type]} [description]
*/
function load(image) {
debug('load image', image);
img.src = image.src;
img.onload = () => {
debug('image loaded', i);
img.raf = requestAnimationFrame(() => {
img.raf = null;
img.style.transition = 'opacity 500ms';
img.style.opacity = 1;
});
};
}
},
/**
* Hides the <img> ready for it to be
* recycled for the next item.
*
* @param {HTMLElement} el list-item
* @param {Number} i index
* @private
*/
unpopulateItemDetail(el, i) {
if (!this.getItemImageSrc) return;
debug('unpopulate item detail');
var img = el[keys.img];
if (!img) return;
// Hide image instantly
img.style.transition = 'none';
img.style.opacity = 0;
debug('raf', img.raf);
// Clear any pending callbacks
if (img.raf) cancelAnimationFrame(img.raf);
img.onload = img.raf = null;
},
/**
* Cache an image in memory so that
* is can be quickly retrieved next
* time the list-item needs to be
* rendered.
*
* If the user has set the length/size