This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
page.js
1339 lines (1146 loc) · 38.8 KB
/
page.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';
/*
* Icon constructor
*
* @param {Object} descriptor
* An object that contains the data necessary to draw this
* icon.
* @param {Application} app [optional]
* The Application or Bookmark object corresponding to
* this icon.
*/
function Icon(descriptor, app) {
this.descriptor = descriptor;
this.app = app;
this.updateAppStatus(app);
}
// Support rendering icons for different screens
var SCALE_RATIO = window.devicePixelRatio;
var MAX_ICON_SIZE = 60;
var ICON_PADDING_IN_CANVAS = 4;
var ICONS_PER_ROW = 4;
var DRAGGING_TRANSITION = '-moz-transform .3s';
Icon.prototype = {
MAX_ICON_SIZE: MAX_ICON_SIZE,
// It defines the time (in ms) to ensure that the onDragStop method finishes
FALLBACK_DRAG_STOP_DELAY: 1000,
DEFAULT_BOOKMARK_ICON_URL: window.location.protocol + '//' +
window.location.host + '/style/images/default_favicon.png',
DEFAULT_ICON_URL: window.location.protocol + '//' + window.location.host +
'/style/images/default.png',
DOWNLOAD_ICON_URL: window.location.protocol + '//' + window.location.host +
'/style/images/app_downloading.png',
CANCELED_ICON_URL: window.location.protocol + '//' + window.location.host +
'/style/images/app_paused.png',
// App icons shadow settings
SHADOW_BLUR: 5,
SHADOW_OFFSET_Y: 2,
SHADOW_COLOR: 'rgba(0,0,0,0.15)',
// These properties will be copied from the descriptor onto the icon's HTML
// element dataset and allow us to uniquely look up the Icon object from
// the HTML element.
_descriptorIdentifiers: ['manifestURL', 'entry_point', 'bookmarkURL',
'useAsyncPanZoom', 'desiredPos', 'desiredScreen'],
/**
* The Application (or Bookmark) object corresponding to this icon.
*/
app: null,
/**
* It returns an unique identifier among all icons installed on the homescreen
*/
getUID: function icon_getUID() {
var descriptor = this.descriptor;
return (descriptor.manifestURL || descriptor.bookmarkURL) +
(descriptor.entry_point ? descriptor.entry_point : '');
},
isOfflineReady: function icon_isOfflineReady() {
return this.descriptor.type === GridItemsFactory.TYPE.COLLECTION ||
!(this.descriptor.isHosted &&
!this.descriptor.hasOfflineCache ||
this.descriptor.type === GridItemsFactory.TYPE.BOOKMARK);
},
/*
* Renders the icon into the page
*/
render: function icon_render() {
/*
* <li role="button" aria-label="label" class="icon" data-manifestURL="zzz">
* <div>
* <img role="presentation" src="the icon image path"></img>
* <span class="label">label</span>
* </div>
* <span class="options"></span>
* </li>
*/
var container = this.container = document.createElement('li');
var dataset = container.dataset;
dataset.offlineReady = this.isOfflineReady();
container.className = 'icon';
if (this.descriptor.hidden) {
delete this.descriptor.hidden;
dataset.visible = false;
}
var descriptor = this.descriptor;
dataset.isIcon = true;
this._descriptorIdentifiers.forEach(function(prop) {
var value = descriptor[prop];
if (value || value === 0)
dataset[prop] = value;
});
// Collection (as bookmarks)
if (descriptor.type === GridItemsFactory.TYPE.COLLECTION) {
dataset.isCollection = true;
dataset.collectionId = descriptor.id;
dataset.collectionName = descriptor.name;
}
var localizedName = this.getName();
container.setAttribute('role', 'button');
container.setAttribute('aria-label', localizedName);
// Icon container
var icon = this.icon = document.createElement('div');
// Image
var img = this.img = new Image();
img.setAttribute('role', 'presentation');
img.width = MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS;
img.height = MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS;
img.style.visibility = 'hidden';
if (descriptor.renderedIcon) {
this.displayRenderedIcon();
} else {
this.fetchImageData();
}
icon.appendChild(img);
// Label
// wrapper of the label -> overflow text should be centered
// in draggable mode
var wrapper = document.createElement('span');
wrapper.className = 'labelWrapper';
var label = this.label = document.createElement('span');
label.textContent = localizedName;
wrapper.appendChild(label);
this.applyOverflowTextMask();
icon.appendChild(wrapper);
container.appendChild(icon);
if (descriptor.removable === true) {
this.appendOptions();
}
if (this.downloading) {
//XXX: Bug 816043 We need to force the repaint to show the span
// with the label and the animation (associated to the span)
container.style.visibility = 'visible';
icon.classList.add('loading');
}
},
appendOptions: function icon_appendOptions() {
var options = this.container.querySelector('.options');
if (options) {
return;
}
// Menu button to delete the app
options = document.createElement('span');
options.className = 'options';
options.dataset.isIcon = true;
this.container.appendChild(options);
},
removeOptions: function icon_removeOptions() {
var options = this.container.querySelector('.options');
if (!options) {
return;
}
this.container.removeChild(options);
},
applyOverflowTextMask: function icon_applyOverflowTextMask() {
var label = this.label;
if (TextOverflowDetective.check(label.textContent)) {
label.parentNode.classList.add('mask');
} else {
label.parentNode.classList.remove('mask');
}
},
fetchImageData: function icon_fetchImageData() {
var descriptor = this.descriptor;
var icon = descriptor.icon;
if (!icon) {
this.loadCachedIcon();
return;
}
// Display the default/oldRendered icon before trying to get the icon.
// Sometimes when the network is quite bad the XHR can take time, and we
// have an empty space
this.loadCachedIcon();
IconRetriever.get({
icon: this,
success: function(blob) {
this.loadImageData(blob);
}.bind(this),
error: function() {
if (this.icon && !this.downloading &&
this.icon.classList.contains('loading')) {
this.icon.classList.remove('loading');
this.img.src = null;
}
this.loadCachedIcon();
}.bind(this)
});
},
loadCachedIcon: function icon_loadCachedImage() {
var oldRenderedIcon = this.oldRenderedIcon;
if (oldRenderedIcon && oldRenderedIcon instanceof Blob) {
this.renderBlob(oldRenderedIcon);
} else {
this.loadDefaultIcon();
}
},
loadImageData: function icon_loadImageData(blob) {
var self = this;
var img = new Image();
img.src = window.URL.createObjectURL(blob);
if (this.icon && !this.downloading) {
this.icon.classList.remove('loading');
}
img.onload = function icon_loadSuccess() {
img.onload = img.onerror = null;
window.URL.revokeObjectURL(img.src);
self.renderImage(img);
self.isDefaultIcon = false;
// real icon is ready (not default icon)
if (!self.app.downloading &&
self.descriptor.type !== GridItemsFactory.TYPE.COLLECTION) {
window.dispatchEvent(new CustomEvent('appInstalled', {
'detail': {
'app': self.app
}
}));
}
};
img.onerror = function icon_loadError() {
console.error('error while loading the icon', img.src, '. Falling back ' +
'to default icon.');
window.URL.revokeObjectURL(img.src);
self.loadDefaultIcon(img);
};
},
loadDefaultIcon: function icon_loadDefaultIcon(img) {
var image = img || new Image();
var self = this;
if (self.img && self.img.src) {
// If there is one already loaded, do not continue...
image.onload = image.onerror = null;
return;
}
var blob = GridManager.getBlobByDefault(self.app);
if (blob === null) {
// At this point theoretically the flow shouldn't go because the icons
// by default have to be loaded, but just in case to avoid race conditions
image.src = getDefaultIcon(self.app);
image.onload = function icon_defaultIconLoadSucess() {
image.onload = image.onerror = null;
self.renderImage(image);
};
} else {
self.renderBlob(blob);
image.onload = image.onerror = null;
}
this.isDefaultIcon = true;
},
renderImageForBookMark: function icon_renderImageForBookmark(img) {
var self = this;
var canvas = document.createElement('canvas');
canvas.width = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
canvas.height = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
var ctx = canvas.getContext('2d');
// Draw the background
var background = new Image();
background.src = 'style/images/default_background.png';
background.onload = function icon_loadBackgroundSuccess() {
ctx.shadowColor = self.SHADOW_COLOR;
ctx.shadowBlur = self.SHADOW_BLUR;
ctx.shadowOffsetY = self.SHADOW_OFFSET_Y;
ctx.drawImage(background, 2 * SCALE_RATIO, 2 * SCALE_RATIO,
MAX_ICON_SIZE * SCALE_RATIO, MAX_ICON_SIZE * SCALE_RATIO);
// Disable smoothing on icon resize
ctx.shadowBlur = 0;
ctx.shadowOffsetY = 0;
ctx.mozImageSmoothingEnabled = false;
ctx.drawImage(img, 16 * SCALE_RATIO, 16 * SCALE_RATIO,
32 * SCALE_RATIO, 32 * SCALE_RATIO);
canvas.toBlob(self.renderBlob.bind(self));
};
},
renderImage: function icon_renderImage(img) {
if (this.app && this.app.iconable) {
this.renderImageForBookMark(img);
return;
}
var canvas = this.createCanvas(img, this.descriptor.type);
canvas.toBlob(this.renderBlob.bind(this));
},
createCanvas: function icon_createCanvas(img, type) {
var canvas = document.createElement('canvas');
canvas.width = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
canvas.height = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Collection icons are self contained and should NOT be manipulated
if (type !== GridItemsFactory.TYPE.COLLECTION) {
ctx.shadowColor = this.SHADOW_COLOR;
ctx.shadowBlur = this.SHADOW_BLUR;
ctx.shadowOffsetY = this.SHADOW_OFFSET_Y;
}
// Deal with very small or very large icons
img.width =
Math.min(MAX_ICON_SIZE, Math.max(img.width, MAX_ICON_SIZE));
img.height =
Math.min(MAX_ICON_SIZE, Math.max(img.height, MAX_ICON_SIZE));
var width = Math.min(img.width * SCALE_RATIO,
canvas.width - ICON_PADDING_IN_CANVAS * SCALE_RATIO);
var height = Math.min(img.width * SCALE_RATIO,
canvas.height - ICON_PADDING_IN_CANVAS * SCALE_RATIO);
ctx.drawImage(img,
(canvas.width - width) / 2,
(canvas.height - height) / 2,
width, height);
ctx.fill();
return canvas;
},
// The url that is passed as a parameter to the callback must be revoked
loadRenderedIcon: function icon_loadRenderedIcon(callback) {
var img = this.img;
var blob = this.descriptor.renderedIcon;
if (!blob) {
blob = GridManager.getBlobByDefault(this.app);
}
img.src = window.URL.createObjectURL(blob);
if (callback) {
img.onload = img.onerror = function done() {
callback(this.src);
img.onload = img.onerror = null;
};
}
},
renderBlob: function icon_renderBlob(blob) {
this.descriptor.renderedIcon = blob;
GridManager.markDirtyState();
this.displayRenderedIcon();
},
displayRenderedIcon: function icon_displayRenderedIcon() {
var self = this;
this.loadRenderedIcon(function cleanup(url) {
self.img.style.visibility = 'visible';
window.URL.revokeObjectURL(url);
if (self.needsShow)
self.show();
});
},
show: function icon_show() {
// Wait for the icon image to load until we start the animation.
if (!this.img.naturalWidth) {
this.needsShow = true;
return;
}
this.needsShow = false;
var container = this.container;
container.dataset.visible = true;
container.addEventListener('animationend', function animationEnd(e) {
container.removeEventListener('animationend', animationEnd);
delete container.dataset.visible;
});
},
updateAppStatus: function icon_updateAppStatus(app) {
// change default icon size for tablet+ device
if (!ScreenLayout.getCurrentLayout('tiny')) {
MAX_ICON_SIZE = 90;
}
if (app) {
this.downloading = app.downloading;
this.cancelled = (app.installState === 'pending') && !app.downloading;
} else {
this.downloading = false;
this.cancelled = false;
}
},
update: function icon_update(descriptor, app) {
this.app = app;
this.updateAppStatus(app);
var oldDescriptor = this.descriptor;
this.descriptor = descriptor;
descriptor.removable === true ? this.appendOptions() : this.removeOptions();
// Update dataset properties
this.container.dataset.offlineReady = this.isOfflineReady();
if (descriptor.updateTime == oldDescriptor.updateTime &&
descriptor.icon == oldDescriptor.icon) {
this.descriptor.renderedIcon = oldDescriptor.renderedIcon;
} else {
this.oldRenderedIcon = oldDescriptor.renderedIcon;
this.fetchImageData();
}
if (descriptor.updateTime != oldDescriptor.updateTime ||
descriptor.name != oldDescriptor.name ||
descriptor.localizedName != oldDescriptor.localizedName) {
this.translate();
}
},
showDownloading: function icon_showDownloading() {
this.img.src = this.DOWNLOAD_ICON_URL;
this.container.style.visibility = 'visible';
this.icon.classList.add('loading');
},
showCancelled: function icon_showCancelled() {
this.img.src = this.CANCELED_ICON_URL;
this.container.style.visibility = 'visible';
this.icon.classList.remove('loading');
this.fetchImageData();
},
remove: function icon_remove() {
this.container.parentNode.removeChild(this.container);
},
/*
* Sets a non-translationable name
*
* @param{string} non-translationable name
*/
setName: function icon_setName(name) {
this.label.textContent = this.descriptor.customName = name;
this.applyOverflowTextMask();
GridManager.markDirtyState();
},
/*
* Returns the name icon
*/
getName: function icon_getName() {
var desc = this.descriptor;
return desc.customName || desc.localizedName || desc.name;
},
/*
* Sets the icon's image
*
* @param{string} the new icon
*/
setImage: function icon_setImage(image) {
this.descriptor.icon = image;
this.fetchImageData();
},
/*
* Translates the label of the icon
*/
translate: function icon_translate() {
var descriptor = this.descriptor;
if (descriptor.type === GridItemsFactory.TYPE.BOOKMARK ||
descriptor.customName)
return;
var app = this.app;
if (!app)
return;
var manifest = app.manifest || app.updateManifest;
if (!manifest)
return;
var localizedName;
if (descriptor.type === GridItemsFactory.TYPE.COLLECTION) {
// try to translate, but fall back to current name
// (translation might fail for custom collection name)
localizedName = navigator.mozL10n.get(manifest.name) || manifest.name;
} else {
var iconsAndNameHolder = manifest;
var entryPoint = descriptor.entry_point;
if (entryPoint)
iconsAndNameHolder = manifest.entry_points[entryPoint];
localizedName = new ManifestHelper(iconsAndNameHolder).name;
}
this.label.textContent = localizedName;
if (descriptor.localizedName != localizedName) {
descriptor.localizedName = localizedName;
GridManager.markDirtyState();
}
this.applyOverflowTextMask();
},
/*
* This method is invoked when the drag gesture starts
*
* @param{int} x-coordinate
*
* @param{int} y-coordinate
*/
onDragStart: function icon_onDragStart(x, y) {
this.initX = x;
this.initY = y;
var draggableElem = this.draggableElem = document.createElement('div');
draggableElem.className = 'draggable';
if (this.descriptor.type !== GridItemsFactory.TYPE.COLLECTION) {
// Collections cannot be appended to others so this operation isn't needed
this.savePostion(draggableElem.dataset);
}
// For some reason, cloning and moving a node re-triggers the blob
// URI to be validated. So we assign a new blob URI to the image
// and don't revoke it until we're finished with the animation.
this.loadRenderedIcon();
var icon = this.icon.cloneNode(true);
var img = icon.querySelector('img');
img.style.visibility = 'hidden';
img.onload = img.onerror = function unhide() {
img.style.visibility = 'visible';
};
draggableElem.appendChild(icon);
var container = this.container;
container.dataset.dragging = 'true';
var rectangle = container.getBoundingClientRect();
var style = draggableElem.style;
style.left = rectangle.left + 'px';
style.top = rectangle.top + 'px';
this.initXCenter = (rectangle.left + rectangle.right) / 2;
this.initYCenter = (rectangle.top + rectangle.bottom) / 2;
this.initHeight = rectangle.bottom - rectangle.top;
document.body.appendChild(draggableElem);
},
/*
* Saves the current container (page or dock) and position.
*
* * pageType -> 'dock' or 'page' types
* * pageIndex -> index of page (no needed for dock)
* * iconIndex -> index of icon inside page or dock container
*
* @param{Object} Source object to set results
*/
savePostion: function icon_savePosition(obj) {
var page;
if (this.container.parentNode === DockManager.page.olist) {
page = DockManager.page;
obj.pageType = 'dock';
} else {
page = GridManager.pageHelper.getCurrent();
obj.pageType = 'page';
obj.pageIndex = GridManager.pageHelper.getCurrentPageNumber();
}
obj.iconIndex = page.getIconIndex(this.container);
},
addClassToDragElement: function icon_addStyleToDragElement(className) {
this.draggableElem.classList.add(className);
},
removeClassToDragElement: function icon_addStyleToDragElement(className) {
this.draggableElem.classList.remove(className);
},
/*
* This method is invoked when the drag gesture finishes. If x and y are
* defined, the icon flies to this position
*
* @param{Function} callback will be performed when animations finishes
*
* @param{Integer} x-coordinate
*
* @param{Integer} y-coordinate
*
* @param{Integer} scale factor of the animation
*/
onDragStop: function icon_onDragStop(callback, tx , ty, scale) {
var container = this.container;
var x = tx,
y = ty;
if (typeof x === 'undefined') {
var rect = container.getBoundingClientRect();
x = (Math.abs(rect.left + rect.right) / 2) % window.innerWidth;
x -= this.initXCenter;
y = (rect.top + rect.bottom) / 2 +
(this.initHeight - (rect.bottom - rect.top)) / 2;
y -= this.initYCenter;
}
var draggableElem = this.draggableElem;
var style = draggableElem.style;
style.MozTransition = '-moz-transform .4s';
style.MozTransform = 'translate(' + x + 'px,' + y + 'px)';
var finishDrag = function() {
delete container.dataset.dragging;
if (draggableElem) {
var img = draggableElem.querySelector('img');
window.URL.revokeObjectURL(img.src);
draggableElem.parentNode.removeChild(draggableElem);
}
callback();
};
// We ensure that there is not an icon lost on the grid
var fallbackID = window.setTimeout(function() {
fallbackID = null;
finishDrag();
}, this.FALLBACK_DRAG_STOP_DELAY);
var content = draggableElem.querySelector('div');
scale = typeof scale !== 'undefined' ? scale : 1;
content.style.MozTransform = 'scale(' + scale + ')';
content.addEventListener('transitionend', function tEnd(e) {
e.target.removeEventListener('transitionend', tEnd);
if (fallbackID !== null) {
window.clearTimeout(fallbackID);
finishDrag();
}
});
},
getTop: function icon_getTop() {
return this.container.getBoundingClientRect().top;
},
getLeft: function icon_getLeft() {
return this.container.getBoundingClientRect().left;
},
getWidth: function icon_getWidth() {
return this.container.getBoundingClientRect().width;
},
/*
* Returns the descriptor object
*/
getDescriptor: function icon_getDescriptor() {
if (this.isDefaultIcon) {
delete this.descriptor.renderedIcon;
}
return this.descriptor;
}
};
function TemplateIcon(iconable) {
var descriptor = {
name: 'templateIcon',
hidden: true,
renderedIcon: null
};
var app = {};
if (iconable) {
app.iconable = true;
}
Icon.call(this, descriptor, app);
}
TemplateIcon.prototype = {
__proto__: Icon.prototype,
loadDefaultIcon: function ticon_loadDefaultIcon() {
var image = new Image();
var self = this;
image.src = getDefaultIcon(self.app);
image.onload = function icon_defaultIconLoadSucess() {
image.onload = null;
self.renderImage(image);
};
},
renderBlob: function ticon_renderBlob(blob) {
this.descriptor.renderedIcon = blob;
}
};
/*
* Page constructor
*
* @param {HTMLElement] container
* HTML container element of the page.
*
* @param {Array} icons [optional]
* List of Icon objects.
*/
function Page(container, icons, numberOfIcons) {
this.container = this.movableContainer = container;
if (icons)
this.render(icons);
this.iconsWhileDragging = [];
this.maxIcons = numberOfIcons || GridManager.pageHelper.maxIconsPerPage;
}
Page.prototype = {
FALLBACK_READY_EVENT_DELAY: 1000,
/*
* Renders a page for a list of apps
*
* @param{Array} icons
* List of Icon objects.
*/
render: function pg_render(icons) {
// By default the page is hidden unless it is the current page.
this.container.setAttribute('aria-hidden', true);
this.olist = document.createElement('ol');
for (var i = 0, icon; icon = icons[i++];) {
this.appendIcon(icon);
}
this.container.appendChild(this.olist);
},
/*
* Applies a translation effect to the page
*
* @param{int} scroll X
* @param{int} duration
*/
moveByWithEffect: function pg_moveByWithEffect(scrollX, duration) {
var container = this.movableContainer;
var style = container.style;
style.MozTransform = 'translateX(' + scrollX + 'px)';
style.MozTransition = '-moz-transform ' + duration + 'ms ease';
},
/*
* Applies a translation to the page
*
* @param{int} scroll X
*/
moveBy: function pg_moveBy(scrollX) {
var style = this.movableContainer.style;
style.MozTransform = 'translateX(' + scrollX + 'px)';
style.MozTransition = '';
},
ready: true,
setReady: function pg_setReady(value) {
this.ready = value;
if (value) {
this.container.dispatchEvent(new CustomEvent('onpageready'));
}
},
/*
* Changes position between two icons
*
* @param {Icon} originIcon
* The origin icon that's being dragged.
*
* @param {Icon} targetIcon
* The target icon that is replaced by the origin icon.
*/
drop: function pg_drop(originIcon, targetIcon) {
if (!this.ready || originIcon === targetIcon) {
return;
}
this.setReady(false);
var iconList = this.olist.children;
if (originIcon && targetIcon && iconList.length > 1) {
if (this.iconsWhileDragging.length === 0)
this.iconsWhileDragging = Array.prototype.slice.call(iconList, 0,
iconList.length);
this.animate(this.iconsWhileDragging, originIcon.container,
targetIcon.container);
} else {
setTimeout(this.setReady.bind(this, true));
}
},
animate: function pg_animate(children, draggableNode, targetNode) {
var draggableIndex = children.indexOf(draggableNode);
var targetIndex = children.indexOf(targetNode);
if (draggableIndex < 0 || targetIndex < 0 || targetIndex >= this.maxIcons) {
// Index is outside the bounds of the array, it doesn't make sense
setTimeout(this.setReady.bind(this, true));
return;
}
var upward = draggableIndex < targetIndex;
this.draggableNode = draggableNode;
this.beforeNode = upward ? targetNode.nextSibling : targetNode;
this.placeIcon(draggableNode, draggableIndex, targetIndex);
var self = this;
targetNode.addEventListener('transitionend', function onTransitionEnd(e) {
e.target.removeEventListener('transitionend', onTransitionEnd);
children.splice(draggableIndex, 1);
children.splice(targetIndex, 0, draggableNode);
setTimeout(self.setReady.bind(self, true));
});
if (upward) {
for (var i = draggableIndex + 1; i <= targetIndex; i++)
this.placeIcon(children[i], i, i - 1, DRAGGING_TRANSITION);
} else {
for (var i = targetIndex; i < draggableIndex; i++)
this.placeIcon(children[i], i, i + 1, DRAGGING_TRANSITION);
}
},
doDragLeave: function pg_doReArrange(callback, reflow) {
this.iconsWhileDragging.forEach(function reset(node) {
node.style.MozTransform = node.style.MozTransition = '';
delete node.dataset.posX;
delete node.dataset.posY;
});
this.iconsWhileDragging = [];
if (reflow && this.olist.contains(this.draggableNode))
this.olist.insertBefore(this.draggableNode, this.beforeNode);
callback();
},
onDragLeave: function pg_onDragLeave(callback, reflow) {
if (this.iconsWhileDragging.length === 0) {
setTimeout(callback);
return;
}
if (!this.ready) {
var self = this;
var ensureCallbackID = null;
var onPageReady = function onPageReady(e) {
e.target.removeEventListener('onpageready', onPageReady);
if (ensureCallbackID !== null) {
window.clearTimeout(ensureCallbackID);
self.doDragLeave(callback, reflow);
}
};
self.container.addEventListener('onpageready', onPageReady);
// We ensure that there is not a transitionend lost on dragging
ensureCallbackID = window.setTimeout(function() {
ensureCallbackID = null;
self.container.removeEventListener('onpageready', onPageReady);
self.doDragLeave(function onfinish() {
self.setReady(true);
callback();
}, reflow);
}, this.FALLBACK_READY_EVENT_DELAY);
return;
}
this.doDragLeave(callback, reflow);
},
placeIcon: function pg_placeIcon(node, from, to, transition) {
if (!node)
return;
var x = node.dataset.posX = parseInt(node.dataset.posX || 0) +
((Math.floor(to % ICONS_PER_ROW) -
Math.floor(from % ICONS_PER_ROW)) * 100);
var y = node.dataset.posY = parseInt(node.dataset.posY || 0) +
((Math.floor(to / ICONS_PER_ROW) -
Math.floor(from / ICONS_PER_ROW)) * 100);
window.mozRequestAnimationFrame(function() {
node.style.MozTransform = 'translate(' + x + '%, ' + y + '%)';
if (transition)
node.style.MozTransition = transition;
});
},
/*
* Implements the tap behaviour
*
* @param{Object} DOM element
*
* @param{Function} callback
*/
tap: function pg_tap(elem, callback) {
if (Homescreen.isInEditMode()) {
if (elem.classList.contains('options')) {
var icon = GridManager.getIcon(elem.parentNode.dataset);
if (icon.app)
Homescreen.showAppDialog(icon);
}
callback();
} else if ('isIcon' in elem.dataset && this.olist === elem.parentNode &&
!document.body.hasAttribute('disabled-tapping')) {
var icon = GridManager.getIcon(elem.dataset);
if (!icon.app)
return;
if (icon.descriptor.entry_point) {
this.disableTap(callback);
icon.app.launch(icon.descriptor.entry_point);
return;
}
if (icon.cancelled) {
GridManager.showRestartDownloadDialog(icon);
callback();
return;
}
this.disableTap(callback);
icon.app.launch();
}
},
/*
* Disables the tap event for the page
*
* @param{Function} callback
*/
disableTap: function pg_disableTap(callback) {
document.body.setAttribute('disabled-tapping', true);
var enableTap = function enableTap() {
document.removeEventListener('visibilitychange', enableTap);
document.removeEventListener('collectionopened', enableTap);
window.removeEventListener('hashchange', enableTap);
document.body.removeAttribute('disabled-tapping');
callback && callback();
};
// We are going to enable the tapping feature under these conditions:
// 1. The opened app is in foreground
document.addEventListener('visibilitychange', enableTap);
// 2. The opened collection is in foreground
document.addEventListener('collectionopened', enableTap);
// 3. Users click on home button quickly while app are opening
window.addEventListener('hashchange', enableTap);
},
/*
* Adds an icon at the position specified
*
* @param{Object} icon object
* @param{Number} index to insert at
*/
appendIconAt: function pg_appendIconAt(icon, index) {
var olist = this.olist,
children = this.olist.children;
if (children[index] && children[index] === icon.container) {
return;