/
navigator.js
872 lines (676 loc) · 22.4 KB
/
navigator.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
/* ========================================================================
* Phonon: navigator.js v1.1
* http://phonon.quarkdev.com
* ========================================================================
* Licensed under MIT (http://phonon.quarkdev.com)
* ======================================================================== */
;(function (window, riot, phonon) {
'use strict';
var pages = [];
var pageHistory = [];
var started = false;
var onActiveTransition = false;
var currentPage = null;
var previousPage = null;
var forward = true;
var safeLink = false;
var riotEnabled = (riot === undefined ? false : true);
var opts = {
defaultPage: null,
hashPrefix: '!',
animatePages: true,
templateRootDirectory: '',
useI18n: true,
enableBrowserBackButton: false,
useHash: true
};
/**
* "Encapsulated" class
* The activity takes care of creating a window for you in which you can place your UI with.
* An activity is based on several window states that we call the activitiy life cycle.
*/
var Activity = (function () {
/**
* @constructor
*/
function Activity() {}
/**
*
* @param {Function} callback
*/
Activity.prototype.onCreate = function (callback) {
this.onCreateCallback = callback;
};
/**
* onReady is called after onCreate and for each page refresh (optional)
* @param {Function} callback
*/
Activity.prototype.onReady = function (callback) {
this.onReadyCallback = callback;
};
/**
* Called when the user leaves the page
* @param {Function} callback
*/
Activity.prototype.onClose = function (callback) {
this.onCloseCallback = function (self) {
callback(self);
};
};
/**
* Called when the page is completely hidden
* @param {Function} callback
*/
Activity.prototype.onHidden = function (callback) {
this.onHiddenCallback = callback;
};
/**
* Called when the page transition is finished
* @param {Function} callback
*/
Activity.prototype.onTransitionEnd = function (callback) {
this.onTransitionEndCallback = callback;
};
/**
* Called when the page hash changes
* @param {Function} callback
*/
Activity.prototype.onHashChanged = function (callback) {
this.onHashChangedCallback = function (req) {
callback(req);
};
};
Activity.prototype.onTabChanged = function (callback) {
this.onTabChangedCallback = function (tabNumber) {
callback(tabNumber);
};
};
return Activity;
})();
/**
* Retrieves the page object
* @param {String} pageName
*/
var getPageObject = function(pageName) {
var page = null;
var i = pages.length - 1;
for (; i >= 0; i--) {
if(pages[i].name === pageName) {
page = pages[i];
break;
}
}
return page;
};
/**
* Retrives the DOM element for a given page
* @param {String} pageName
*/
var getPageEl = function(pageName) {
var pages = document.querySelectorAll('[data-page]');
var i = pages.length - 1;
var elPage = null;
for (; i >= 0; i--) {
if(pages[i].tagName.toLowerCase() === pageName) {
elPage = pages[i];
break;
}
}
return elPage;
};
function forwardAnimation() {
if(opts.animatePages) {
var previousPageEl = this;
previousPageEl.classList.remove('page-sliding');
previousPageEl.classList.remove('left');
previousPageEl.off(phonon.event.animationEnd, forwardAnimation, false);
previousPageEl.classList.remove('app-active');
}
callTransitionEnd(currentPage);
callHiddenCallback(previousPage);
onActiveTransition = false;
}
function previousAnimation() {
if(opts.animatePages) {
var previousPageEl = this;
previousPageEl.classList.remove('page-sliding');
previousPageEl.classList.remove('right');
previousPageEl.off(phonon.event.animationEnd, previousAnimation, false);
previousPageEl.classList.remove('app-active');
}
callTransitionEnd(currentPage);
callHiddenCallback(previousPage);
onActiveTransition = false;
}
function callCreate(pageName) {
if(riotEnabled) {
// Call the "create" event in VM
phonon.tagManager.trigger(pageName, 'create');
}
var page = getPageObject(pageName);
// Page Scope is called once during the onCreate process
if(typeof page.callback === 'function') {
page.callback(page.activity);
}
// Call the onCreate callback
if(page.activity instanceof Activity && typeof page.activity.onCreateCallback === 'function') {
page.activity.onCreateCallback();
}
var pageEvent = new window.CustomEvent('pagecreated', {
detail: { page: pageName },
bubbles: true,
cancelable: true
});
document.dispatchEvent(pageEvent);
}
function callReady(pageName) {
var page = getPageObject(pageName);
window.setTimeout(function() {
if(riotEnabled) {
// Call the "ready" event in VM
phonon.tagManager.trigger(pageName, 'ready');
}
// Call the onReady callback
if(page.activity instanceof Activity && typeof page.activity.onReadyCallback === 'function') {
page.activity.onReadyCallback();
}
// Dispatch the global event pageopened
var pageEvent = new window.CustomEvent('pageopened', {
detail: { page: pageName },
bubbles: true,
cancelable: true
});
document.dispatchEvent(pageEvent);
}, page.readyDelay);
}
function callTransitionEnd(pageName) {
if(riotEnabled) {
phonon.tagManager.trigger(pageName, 'transitionend');
}
var page = getPageObject(pageName);
// Call the onTransitionEnd callback
if(page.activity instanceof Activity && typeof page.activity.onTransitionEndCallback === 'function') {
page.activity.onTransitionEndCallback();
}
}
function callHiddenCallback(pageName) {
if(riotEnabled) {
phonon.tagManager.trigger(pageName, 'hidden');
}
var page = getPageObject(pageName);
// Call the onHidden callback
if(page.activity instanceof Activity && typeof page.activity.onHiddenCallback === 'function') {
page.activity.onHiddenCallback();
}
}
function callTabChanged(pageName, tabNumber) {
if(riotEnabled) {
phonon.tagManager.trigger(pageName, 'tabchanged', tabNumber);
}
var page = getPageObject(pageName);
// Call the onTabChanged callback
if(page.activity instanceof Activity && typeof page.activity.onTabChangedCallback === 'function') {
page.activity.onTabChangedCallback(tabNumber);
}
}
function callClose(pageName, nextPageName, hash) {
function close() {
var currentHash = window.location.hash.split('#')[1];
if(currentHash === hash || !opts.useHash) {
onRoute(hash);
} else {
window.location.hash = hash;
}
}
// cancel the page transition
if(isComponentVisible()) return;
var page = getPageObject(pageName);
// close the page directly
if(!page.async) {
close(true);
return;
}
var api = {close: close};
if(riotEnabled) {
phonon.tagManager.trigger(pageName, 'close', api);
}
// Call the onclose callback
if(page.activity instanceof Activity && typeof page.activity.onCloseCallback === 'function') {
page.activity.onCloseCallback(api);
} else {
if(!riotEnabled) {
throw new Error('The page ' + pageName + ' prevents close, but its callback (onClose) is undefined');
}
}
}
function callHash(pageName, params, action) {
var api = {params: params, action: action};
if(riotEnabled) {
phonon.tagManager.trigger(pageName, 'hashchanged', api);
}
var page = getPageObject(pageName);
// Call the onHashChanged callback
if(page.activity instanceof Activity && typeof page.activity.onHashChangedCallback === 'function') {
page.activity.onHashChangedCallback(api);
}
}
function callCallback(callbackName, options) {
if(callbackName === 'tabchanged') {
callTabChanged(options.page, options.tabNumber);
}
}
function mount(pageName, fn) {
if(riotEnabled) {
riot.compile(function() {
if(opts.useI18n) {
phonon.i18n().getAll(function(json) {
phonon.tagManager.addTag(riot.mount(pageName, {i18n: json}), pageName);
fn();
});
} else {
phonon.tagManager.addTag(riot.mount(pageName, {i18n: null}), pageName);
fn();
}
});
}
if(!riotEnabled) {
var page = getPageObject(pageName);
if(page.content !== null) {
loadContent(page.content, function(template) {
var elPage = getPageEl(pageName);
var virtualDiv = document.createElement('div');
virtualDiv.innerHTML = template;
var virtualElPage = virtualDiv.querySelector(pageName);
if(virtualElPage === null) {
throw new Error('Error with ' + page.content + ' : the template for ' + pageName + ' must start with the parent node <' + pageName + ' class="app-page">');
}
var attrs = virtualElPage.attributes;
var i = attrs.length - 1;
for (; i >= 0; i--) {
var attr = attrs.item(i);
if(attr.nodeName !== 'class' && attr.nodeValue !== 'app-page') elPage.setAttribute(attr.nodeName, attr.nodeValue);
}
if(opts.useI18n) {
phonon.i18n().bind(virtualElPage, function() {
elPage.innerHTML = virtualElPage.innerHTML;
fn();
});
} else {
elPage.innerHTML = virtualElPage.innerHTML;
fn();
}
});
} else {
fn();
}
}
}
function loadContent(url, fn) {
var req = new XMLHttpRequest();
if(req.overrideMimeType) req.overrideMimeType('text/html; charset=utf-8');
req.onreadystatechange = function() {
if (req.readyState === 4 && req.status === 200) fn(req.responseText);
};
req.open('GET', opts.templateRootDirectory + url, true);
req.send('');
}
function addPage(pageName) {
var page = {
name: pageName,
mounted: false,
async: false,
activity: null,
content: null,
readyDelay: 1
};
pages.push(page);
}
/**
* Checks if a "front" UI component is active
* Returns true if an UI component is active, false otherwise
* @return {Boolean}
*/
function isComponentVisible() {
// close active dialogs, popovers, panels and side-panels
if(typeof phonon.dialog !== 'undefined' && phonon.dialog().closeActive()) return true;
if(typeof phonon.popover !== 'undefined' && phonon.popover().closeActive()) return true;
if(typeof phonon.panel !== 'undefined' && phonon.panel().closeActive()) return true;
if(typeof phonon.sidePanel !== 'undefined' && phonon.sidePanel().closeActive()) return true;
return false;
}
function getLastPage() {
var page = {page: opts.defaultPage, params: ''};
if(pageHistory.length > 0) {
var inddex = -1;
var i = pageHistory.length - 1;
for (; i >= 0; i--) {
if(pageHistory[i].page === currentPage) {
inddex = i - 1;
break;
}
}
if(inddex > -1) {
page = pageHistory[inddex];
pageHistory.slice(inddex, 1);
}
}
return page;
}
function navigationListener(evt) {
var target = evt.target;
var nav = null;
var validHref = false;
var params = '';
for (; target && target !== document; target = target.parentNode) {
var dataNav = target.getAttribute('data-navigation');
if(typeof target.href !== 'undefined' && target.href.indexOf('#!') !== -1) {
validHref = true;
break;
}
if(dataNav) {
safeLink = true;
nav = dataNav;
break;
}
}
if(validHref) {
evt.preventDefault();
}
if(nav === null && !validHref) {
return;
}
var page = opts.defaultPage;
if(nav !== null) {
if(nav === '$previous-page') {
var pObj = getLastPage();
page = pObj.page;
params = pObj.params;
} else {
page = nav;
}
} else {
// regex
var match = target.href.match(/#!([A-Za-z0-9\-\.]+)?(.*)/);
if(match) {
page = match[1];
params = match[2];
}
}
callClose(currentPage, page, opts.hashPrefix + page + '/' + params);
}
function startTransition(previousPage, pageName, params, action) {
callReady(pageName);
callHash(pageName, params, action);
var previousPageEl = getPageEl(previousPage);
var elCurrentPage = getPageEl(pageName);
elCurrentPage.classList.add('app-active');
if(opts.animatePages) {
previousPageEl.classList.add('page-sliding');
if(forward) {
previousPageEl.classList.add( 'left' );
previousPageEl.on(phonon.event.animationEnd, forwardAnimation, false);
} else {
previousPageEl.classList.add( 'right' );
previousPageEl.on(phonon.event.animationEnd, previousAnimation, false);
}
} else {
previousPageEl.classList.remove('app-active');
if(forward) {
forwardAnimation();
} else {
previousAnimation();
}
}
// Scroll to top
var contents = elCurrentPage.querySelectorAll('.content');
var i = contents.length - 1;
for (; i >= 0; i--) {
var content = contents[i];
if(content !== null && content.scrollTop !== 0) {
content.scrollTop = 0;
}
}
// delete history if the current page is the default page
if(pageName === opts.defaultPage) {
pageHistory = [];
}
}
function onBeforeTransition(pageName, params, action) {
if(onActiveTransition) return;
var page = getPageObject(pageName);
if(page) {
onActiveTransition = true;
previousPage = currentPage;
currentPage = pageName;
if(!page.mounted) {
mount(page.name, function() {
page.mounted = true;
callCreate(pageName);
startTransition(previousPage, pageName, params, action);
});
} else {
startTransition(previousPage, pageName, params, action);
}
} else {
throw new Error('The following page: ' + pageName + ' does not exists');
}
}
function init(options) {
if(typeof options.templateRootDirectory === 'string' && options.templateRootDirectory !== '') {
options.templateRootDirectory = ( (options.templateRootDirectory.indexOf('/', options.templateRootDirectory.length - '/'.length) !== -1) ? options.templateRootDirectory : options.templateRootDirectory + '/');
}
if(typeof options.hashPrefix === 'object') options.hashPrefix = '';
var prop;
for(prop in options) {
opts[prop] = options[prop];
}
// navigation listeners are accepted (safe)
if(opts.enableBrowserBackButton) {
safeLink = true;
}
// Add page nodes
var pages = document.querySelectorAll('[data-page]');
var i = pages.length - 1;
for (; i >= 0; i--) {
var page = pages[i];
// add the page class
if(!page.classList.contains('app-page')) {
page.classList.add('app-page');
}
addPage( page.tagName.toLowerCase() );
}
}
function start() {
if(started) {
throw new Error('The app has been already started');
}
// Set the default page as current page
currentPage = opts.defaultPage;
// android, ios or browser
var osName = phonon.device.os.toLowerCase();
var osClass = 'web';
if(osName === 'android') {
osClass = 'android';
} else if(osName === 'ios') {
osClass = 'ios';
}
if(!document.body.classList.contains(osClass)) {
document.body.classList.add(osClass);
}
initFirstPage();
}
function initFirstPage() {
mount(currentPage, function() {
// update the mount state
var pageObject = getPageObject(currentPage);
pageObject.mounted = true;
callCreate(currentPage);
if(currentPage === opts.defaultPage && !started) {
var el = getPageEl(currentPage);
started = true;
if(el) {
if(!el.classList.contains('app-active')) {
el.classList.add('app-active');
}
callReady(currentPage);
// Call global-ready callbacks once
phonon.dispatchGlobalReady();
var startHash = opts.hashPrefix + opts.defaultPage;
if(window.location.hash !== startHash && opts.useHash) {
window.location.hash = opts.hashPrefix + opts.defaultPage;
}
} else {
throw new Error('Page does not exists');
}
}
});
}
function changePage(pageName, pageParams) {
var currentPageObject = getPageObject(currentPage);
var pageObject = getPageObject(pageName);
if(pageObject) {
var hash = (typeof pageParams === 'string' ? opts.hashPrefix + pageObject.name + '/' + pageParams : opts.hashPrefix + pageObject.name);
if(currentPageObject.async) {
callClose(currentPage, pageObject.name, hash);
} else {
if(window.location.hash.indexOf(pageObject.name) === -1 && opts.useHash) {
window.location.hash = hash;
}
}
} else {
throw new Error('The following page: ' + pageName + ' does not exists');
}
}
/**
* @param {String | HashEvent} virtualHash
*/
function onRoute(virtualHash) {
var hash = (typeof virtualHash === 'string' ? virtualHash : window.location.href.split('#')[1] || '');
var parsed = hash.split('/');
var page = parsed[0];
var params = (typeof parsed[1] === 'undefined' ? '' : parsed[1]);
var action = (typeof parsed[2] === 'undefined' ? '' : parsed[2]);
// angular hash system
var withSlash = opts.hashPrefix.indexOf('/');
if(withSlash !== -1) {
page = params;
params = action;
action = (typeof parsed[3] === 'undefined' ? '' : parsed[3]);
}
// is page?
var pageName;
if(withSlash !== -1) {
if(page[0] !== opts.hashPrefix[withSlash+1]) {
return;
}
pageName = page.substring(withSlash+1, page.length);
} else {
if(opts.hashPrefix.length > 0 && page[0] !== opts.hashPrefix[0]) {
return;
}
pageName = page.substring(opts.hashPrefix.length, page.length);
}
var pageObject = getPageObject(pageName);
if(pageObject) {
/*
* [1] change page only if changePage() is called programatically
* [2] back button: if UI components are visible like dialogs, cancel the page transition
* [3] the back button can be the physical button on Android or the browser's back button
*/
isComponentVisible();
if(pageObject.name === currentPage) {
if(typeof params !== 'undefined') {
callHash(pageName, params, action);
}
return;
}
if(!safeLink) {
return;
}
var inArray = false;
var i = pageHistory.length - 1;
for (; i >= 0; i--) {
if(pageHistory[i].page === pageObject.name) {
inArray = true;
break;
}
}
if(pageHistory.length > 0) {
if(pageObject.name === opts.defaultPage) {
forward = false;
}
} else {
forward = true;
}
if(pageHistory.length > 1 && pageHistory[pageHistory.length - 2].page === pageObject.name) {
forward = false;
}
if(!inArray) {
pageHistory.push( {page: pageObject.name, params: params + '/' + action} );
}
onBeforeTransition(pageName, params, action);
if(!opts.enableBrowserBackButton) safeLink = false;
}
}
/**
* One listener to navigate through the app pages
*/
document.on('tap', navigationListener);
/*
* we do not call onRoute() directly because it is used in callClose
* in order to prevent the back button on navigator:
* the hash changes, but it is refused by this module (not trusted behavior)
* so we need to call this function with a "virtual hash" as argument
*/
if(opts.useHash) window.on('hashchange', onRoute);
document.on('backbutton', function() {
var pObj = getLastPage();
if(currentPage === opts.defaultPage) {
return;
}
callClose(currentPage, pObj.page, opts.hashPrefix + pObj.page + '/' + pObj.params);
});
phonon.navigator = function(options) {
if(typeof options === 'object') {
init(options);
}
return {
currentPage: currentPage,
start: start,
changePage: function(pageName, pageParams) {
safeLink = true;
/*
* wait the end of front components animations like dialogs, panels, etc before changing the page
* [1] avoid several animations at the same time
* [2] it is more logical to see them disappearing before the page changes
*/
var wait = (isComponentVisible() ? 400 : 1);
window.setTimeout(function() {
changePage(pageName, pageParams);
}, wait);
},
on: function(options, callback) {
if(typeof options.page !== 'string') {
throw new Error('Page name must be a string');
}
if(typeof options.preventClose !== 'undefined' && typeof options.preventClose !== 'boolean') {
throw new Error('preventClose option must be a boolean');
}
if(typeof options.readyDelay !== 'undefined' && typeof options.readyDelay !== 'number') {
throw new Error('readyDelay option must be a number');
}
var p = getPageObject(options.page);
if(p) {
p.activity = (typeof callback === 'function' ? new Activity() : null);
p.callback = callback;
p.async = (typeof options.preventClose === 'boolean' ? options.preventClose : false);
p.content = (typeof options.content === 'string' ? options.content : null);
p.readyDelay = (typeof options.readyDelay === 'number' ? options.readyDelay : 1);
} else {
throw new Error('A namespace for ' + options.page + ' is detected, but the DOM node <' + options.page + '> is not found.');
}
},
callCallback: callCallback
};
};
})(typeof window !== 'undefined' ? window : this, typeof riot !== 'undefined' ? riot : undefined, phonon);