This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 171
/
App.js
1365 lines (1221 loc) · 37.1 KB
/
App.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';
import { addClasses, delegate, match, on, removeClasses } from 'metal-dom';
import { array, async, isDefAndNotNull, isString, object } from 'metal';
import { EventEmitter, EventHandler } from 'metal-events';
import globals from '../globals/globals';
import Route from '../route/Route';
import Screen from '../screen/Screen';
import Surface from '../surface/Surface';
import Uri from 'metal-uri';
import utils from '../utils/utils';
const NavigationStrategy = {
IMMEDIATE: 'immediate',
SCHEDULE_LAST: 'scheduleLast'
};
class App extends EventEmitter {
/**
* App class that handle routes and screens lifecycle.
* @constructor
* @extends {EventEmitter}
*/
constructor() {
super();
/**
* Holds the active screen.
* @type {?Screen}
* @protected
*/
this.activeScreen = null;
/**
* Holds the active path containing the query parameters.
* @type {?string}
* @protected
*/
this.activePath = null;
/**
* Allows prevent navigate from dom prevented event.
* @type {boolean}
* @default true
* @protected
*/
this.allowPreventNavigate = true;
/**
* Holds link base path.
* @type {!string}
* @default ''
* @protected
*/
this.basePath = '';
/**
* Holds the value of the browser path before a navigation is performed.
* @type {!string}
* @default the current browser path.
* @protected
*/
this.browserPathBeforeNavigate = utils.getCurrentBrowserPathWithoutHash();
/**
* Captures scroll position from scroll event.
* @type {!boolean}
* @default true
* @protected
*/
this.captureScrollPositionFromScrollEvent = true;
/**
* Holds the default page title.
* @type {string}
* @default null
* @protected
*/
this.defaultTitle = globals.document.title;
/**
* Holds the form selector to define forms that are routed.
* @type {!string}
* @default form[enctype="multipart/form-data"]:not([data-senna-off])
* @protected
*/
this.formSelector = 'form[enctype="multipart/form-data"]:not([data-senna-off])';
/**
* When enabled, the route matching ignores query string from the path.
* @type {boolean}
* @default false
* @protected
*/
this.ignoreQueryStringFromRoutePath = false;
/**
* Holds the link selector to define links that are routed.
* @type {!string}
* @default a:not([data-senna-off])
* @protected
*/
this.linkSelector = 'a:not([data-senna-off]):not([target="_blank"])';
/**
* Holds the loading css class.
* @type {!string}
* @default senna-loading
* @protected
*/
this.loadingCssClass = 'senna-loading';
/**
* Using the History API to manage your URLs is awesome and, as it happens,
* a crucial feature of good web apps. One of its downsides, however, is
* that scroll positions are stored and then, more importantly, restored
* whenever you traverse the history. This often means unsightly jumps as
* the scroll position changes automatically, and especially so if your app
* does transitions, or changes the contents of the page in any way.
* Ultimately this leads to an horrible user experience. The good news is,
* however, that there’s a potential fix: history.scrollRestoration.
* https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
* @type {boolean}
* @protected
*/
this.nativeScrollRestorationSupported = ('scrollRestoration' in globals.window.history);
/**
* When set to NavigationStrategy.SCHEDULE_LAST means that the current navigation
* cannot be Cancelled to start another and will be queued in
* scheduledNavigationQueue. When NavigationStrategy.IMMEDIATE means that all
* navigation will be cancelled to start another.
* @type {!string}
* @default immediate
* @protected
*/
this.navigationStrategy = NavigationStrategy.IMMEDIATE;
/**
* When set to true there is a pendingNavigate that has not yet been
* resolved or rejected.
* @type {boolean}
* @default false
* @protected
*/
this.isNavigationPending = false;
/**
* Holds a deferred with the current navigation.
* @type {?Promise}
* @default null
* @protected
*/
this.pendingNavigate = null;
/**
* Holds the window horizontal scroll position when the navigation using
* back or forward happens to be restored after the surfaces are updated.
* @type {!Number}
* @default 0
* @protected
*/
this.popstateScrollLeft = 0;
/**
* Holds the window vertical scroll position when the navigation using
* back or forward happens to be restored after the surfaces are updated.
* @type {!Number}
* @default 0
* @protected
*/
this.popstateScrollTop = 0;
/**
* Holds the redirect path containing the query parameters.
* @type {?string}
* @protected
*/
this.redirectPath = null;
/**
* Holds the screen routes configuration.
* @type {?Array}
* @default []
* @protected
*/
this.routes = [];
/**
* Holds a queue that stores every DOM event that can initiate a navigation.
* @type {!Event}
* @default []
* @protected
*/
this.scheduledNavigationQueue = [];
/**
* Maps the screen instances by the url containing the parameters.
* @type {?Object}
* @default {}
* @protected
*/
this.screens = {};
/**
* When set to true the first erroneous popstate fired on page load will be
* ignored, only if <code>globals.window.history.state</code> is also
* <code>null</code>.
* @type {boolean}
* @default false
* @protected
*/
this.skipLoadPopstate = false;
/**
* Maps that index the surfaces instances by the surface id.
* @type {?Object}
* @default {}
* @protected
*/
this.surfaces = {};
/**
* When set to true, moves the scroll position after popstate, or to the
* top of the viewport for new navigation. If false, the browser will
* take care of scroll restoration.
* @type {!boolean}
* @default true
* @protected
*/
this.updateScrollPosition = true;
this.appEventHandlers_ = new EventHandler();
this.appEventHandlers_.add(
on(globals.window, 'scroll', utils.debounce(this.onScroll_.bind(this), 100)),
on(globals.window, 'load', this.onLoad_.bind(this)),
on(globals.window, 'popstate', this.onPopstate_.bind(this))
);
this.on('startNavigate', this.onStartNavigate_);
this.on('beforeNavigate', this.onBeforeNavigate_);
this.on('beforeNavigate', this.onBeforeNavigateDefault_, true);
this.on('beforeUnload', this.onBeforeUnloadDefault_);
this.setLinkSelector(this.linkSelector);
this.setFormSelector(this.formSelector);
this.maybeOverloadBeforeUnload_();
}
/**
* Adds one or more screens to the application.
*
* Example:
*
* <code>
* app.addRoutes({ path: '/foo', handler: FooScreen });
* or
* app.addRoutes([{ path: '/foo', handler: function(route) { return new FooScreen(); } }]);
* </code>
*
* @param {Object} or {Array} routes Single object or an array of object.
* Each object should contain <code>path</code> and <code>screen</code>.
* The <code>path</code> should be a string or a regex that maps the
* navigation route to a screen class definition (not an instance), e.g:
* <code>{ path: "/home:param1", handler: MyScreen }</code>
* <code>{ path: /foo.+/, handler: MyScreen }</code>
* @chainable
*/
addRoutes(routes) {
if (!Array.isArray(routes)) {
routes = [routes];
}
routes.forEach((route) => {
if (!(route instanceof Route)) {
route = new Route(route.path, route.handler);
}
this.routes.push(route);
});
return this;
}
/**
* Adds one or more surfaces to the application.
* @param {Surface|String|Array.<Surface|String>} surfaces
* Surface element id or surface instance. You can also pass an Array
* whichcontains surface instances or id. In case of ID, these should be
* the id of surface element.
* @chainable
*/
addSurfaces(surfaces) {
if (!Array.isArray(surfaces)) {
surfaces = [surfaces];
}
surfaces.forEach((surface) => {
if (isString(surface)) {
surface = new Surface(surface);
}
this.surfaces[surface.getId()] = surface;
});
return this;
}
/**
* Returns if can navigate to path.
* @param {!string} url
* @return {boolean}
*/
canNavigate(url) {
const uri = utils.isWebUri(url);
if (!uri) {
return false;
}
const path = utils.getUrlPath(url);
if (!this.isLinkSameOrigin_(uri.getHost())) {
console.log('Offsite link clicked');
return false;
}
if (!this.isSameBasePath_(path)) {
console.log('Link clicked outside app\'s base path');
return false;
}
// Prevents navigation if it's a hash change on the same url.
if (uri.getHash() && utils.isCurrentBrowserPath(path)) {
return false;
}
if (!this.findRoute(path)) {
console.log('No route for ' + path);
return false;
}
return true;
}
/**
* Clear screens cache.
* @chainable
*/
clearScreensCache() {
Object.keys(this.screens).forEach((path) => {
if (path === this.activePath) {
this.activeScreen.clearCache();
} else if (!(this.isNavigationPending && this.pendingNavigate.path === path)) {
this.removeScreen(path);
}
});
}
/**
* Retrieves or create a screen instance to a path.
* @param {!string} path Path containing the querystring part.
* @return {Screen}
*/
createScreenInstance(path, route) {
if (!this.pendingNavigate && path === this.activePath) {
console.log('Already at destination, refresh navigation');
return this.activeScreen;
}
/* jshint newcap: false */
var screen = this.screens[path];
if (!screen) {
var handler = route.getHandler();
if (handler === Screen || Screen.isImplementedBy(handler.prototype)) {
screen = new handler();
} else {
screen = handler(route) || new Screen();
}
console.log('Create screen for [' + path + '] [' + screen + ']');
}
return screen;
}
/**
* @inheritDoc
*/
disposeInternal() {
if (this.activeScreen) {
this.removeScreen(this.activePath);
}
this.clearScreensCache();
this.formEventHandler_.removeListener();
this.linkEventHandler_.removeListener();
this.appEventHandlers_.removeAllListeners();
super.disposeInternal();
}
/**
* Dispatches to the first route handler that matches the current path, if
* any.
* @return {Promise} Returns a pending request promise.
*/
dispatch() {
return this.navigate(utils.getCurrentBrowserPath(), true);
}
/**
* Starts navigation to a path.
* @param {!string} path Path containing the querystring part.
* @param {boolean=} opt_replaceHistory Replaces browser history.
* @return {Promise} Returns a pending request promise.
*/
doNavigate_(path, opt_replaceHistory) {
var route = this.findRoute(path);
if (!route) {
this.pendingNavigate = Promise.reject(new Error('No route for ' + path));
return this.pendingNavigate;
}
console.log('Navigate to [' + path + ']');
this.stopPendingNavigate_();
this.isNavigationPending = true;
var nextScreen = this.createScreenInstance(path, route);
const finalize = () => {
this.navigationStrategy = NavigationStrategy.IMMEDIATE;
if (this.scheduledNavigationQueue.length) {
const scheduledNavigation = this.scheduledNavigationQueue.shift();
this.maybeNavigate_(scheduledNavigation.href, scheduledNavigation);
}
};
return this.maybePreventDeactivate_()
.then(() => this.maybePreventActivate_(nextScreen))
.then(() => nextScreen.load(path))
.then(() => {
// At this point we cannot stop navigation and all received
// navigate candidates will be queued at scheduledNavigationQueue.
this.navigationStrategy = NavigationStrategy.SCHEDULE_LAST;
if (this.activeScreen) {
this.activeScreen.deactivate();
}
this.prepareNavigateHistory_(path, nextScreen, opt_replaceHistory);
this.prepareNavigateSurfaces_(
nextScreen,
this.surfaces,
this.extractParams(route, path)
);
})
.then(() => nextScreen.evaluateStyles(this.surfaces))
.then(() => nextScreen.flip(this.surfaces))
.then(() => nextScreen.evaluateScripts(this.surfaces))
.then(() => this.maybeUpdateScrollPositionState_())
.then(() => this.syncScrollPositionSyncThenAsync_())
.then(() => this.finalizeNavigate_(path, nextScreen))
.then(() => this.maybeOverloadBeforeUnload_())
.then(() => {
finalize();
})
.catch((reason) => {
this.isNavigationPending = false;
this.handleNavigateError_(path, nextScreen, reason);
finalize();
throw reason;
});
}
/**
* Extracts params according to the given path and route.
* @param {!Route} route
* @param {string} path
* @param {!Object}
*/
extractParams(route, path) {
return route.extractParams(this.getRoutePath(path));
}
/**
* Finalizes a screen navigation.
* @param {!string} path Path containing the querystring part.
* @param {!Screen} nextScreen
* @protected
*/
finalizeNavigate_(path, nextScreen) {
nextScreen.activate();
if (this.activeScreen && !this.activeScreen.isCacheable()) {
if (this.activeScreen !== nextScreen) {
this.removeScreen(this.activePath);
}
}
this.activePath = path;
this.activeScreen = nextScreen;
this.browserPathBeforeNavigate = utils.getCurrentBrowserPathWithoutHash();
this.screens[path] = nextScreen;
this.isNavigationPending = false;
this.pendingNavigate = null;
globals.capturedFormElement = null;
globals.capturedFormButtonElement = null;
console.log('Navigation done');
}
/**
* Finds a route for the test path. Returns true if matches has a route,
* otherwise returns null.
* @param {!string} path Path containing the querystring part.
* @return {?Object} Route handler if match any or <code>null</code> if the
* path is the same as the current url and the path contains a fragment.
*/
findRoute(path) {
path = this.getRoutePath(path);
for (var i = 0; i < this.routes.length; i++) {
var route = this.routes[i];
if (route.matchesPath(path)) {
return route;
}
}
return null;
}
/**
* Gets allow prevent navigate.
* @return {boolean}
*/
getAllowPreventNavigate() {
return this.allowPreventNavigate;
}
/**
* Gets link base path.
* @return {!string}
*/
getBasePath() {
return this.basePath;
}
/**
* Gets the default page title.
* @return {string} defaultTitle
*/
getDefaultTitle() {
return this.defaultTitle;
}
/**
* Gets the form selector.
* @return {!string}
*/
getFormSelector() {
return this.formSelector;
}
/**
* Check if route matching is ignoring query string from the route path.
* @return {boolean}
*/
getIgnoreQueryStringFromRoutePath() {
return this.ignoreQueryStringFromRoutePath;
}
/**
* Gets the link selector.
* @return {!string}
*/
getLinkSelector() {
return this.linkSelector;
}
/**
* Gets the loading css class.
* @return {!string}
*/
getLoadingCssClass() {
return this.loadingCssClass;
}
/**
* Returns the given path formatted to be matched by a route. This will,
* for example, remove the base path from it, but make sure it will end
* with a '/'.
* @param {string} path
* @return {string}
*/
getRoutePath(path) {
if (this.getIgnoreQueryStringFromRoutePath()) {
path = utils.getUrlPathWithoutHashAndSearch(path);
return utils.getUrlPathWithoutHashAndSearch(path.substr(this.basePath.length));
}
path = utils.getUrlPathWithoutHash(path);
return utils.getUrlPathWithoutHash(path.substr(this.basePath.length));
}
/**
* Gets the update scroll position value.
* @return {boolean}
*/
getUpdateScrollPosition() {
return this.updateScrollPosition;
}
/**
* Handle navigation error.
* @param {!string} path Path containing the querystring part.
* @param {!Screen} nextScreen
* @param {!Error} error
* @protected
*/
handleNavigateError_(path, nextScreen, error) {
console.log('Navigation error for [' + nextScreen + '] (' + error.stack + ')');
this.emit('navigationError', {
error,
nextScreen,
path
});
if (!utils.isCurrentBrowserPath(path)) {
if (this.isNavigationPending && this.pendingNavigate) {
this.pendingNavigate
.then(() => this.removeScreen(path))
.catch(error => {
this.removeScreen(path);
throw error;
});
} else {
this.removeScreen(path);
}
}
}
/**
* Checks if app has routes.
* @return {boolean}
*/
hasRoutes() {
return this.routes.length > 0;
}
/**
* Tests if host is an offsite link.
* @param {!string} host Link host to compare with
* <code>globals.window.location.host</code>.
* @return {boolean}
* @protected
*/
isLinkSameOrigin_(host) {
const hostUri = new Uri(host);
const locationHostUri = new Uri(globals.window.location.host);
return hostUri.getPort() === locationHostUri.getPort() && hostUri.getHostname() === locationHostUri.getHostname();
}
/**
* Tests if link element has the same app's base path.
* @param {!string} path Link path containing the querystring part.
* @return {boolean}
* @protected
*/
isSameBasePath_(path) {
return path.indexOf(this.basePath) === 0;
}
/**
* Lock the document scroll in order to avoid the browser native back and
* forward navigation to change the scroll position. In the end of
* navigation lifecycle scroll is repositioned.
* @protected
*/
lockHistoryScrollPosition_() {
var state = globals.window.history.state;
if (!state) {
return;
}
// Browsers are inconsistent when re-positioning the scroll history on
// popstate. At some browsers, history scroll happens before popstate, then
// lock the scroll on the last known position as soon as possible after the
// current JS execution context and capture the current value. Some others,
// history scroll happens after popstate, in this case, we bind an once
// scroll event to lock the las known position. Lastly, the previous two
// behaviors can happen even on the same browser, hence the race will decide
// the winner.
var winner = false;
var switchScrollPositionRace = function() {
globals.document.removeEventListener('scroll', switchScrollPositionRace, false);
if (!winner) {
globals.window.scrollTo(state.scrollLeft, state.scrollTop);
winner = true;
}
};
async.nextTick(switchScrollPositionRace);
globals.document.addEventListener('scroll', switchScrollPositionRace, false);
}
/**
* If supported by the browser, disables native scroll restoration and
* stores current value.
*/
maybeDisableNativeScrollRestoration() {
if (this.nativeScrollRestorationSupported) {
this.nativeScrollRestoration_ = globals.window.history.scrollRestoration;
globals.window.history.scrollRestoration = 'manual';
}
}
/**
* This method is used to evaluate if is possible to queue received
* dom event to scheduleNavigationQueue and enqueue it.
* @param {string} href Information about the link's href.
* @param {Event} event Dom event that initiated the navigation.
*/
maybeScheduleNavigation_(href, event) {
if (this.isNavigationPending && this.navigationStrategy === NavigationStrategy.SCHEDULE_LAST) {
this.scheduledNavigationQueue = [object.mixin({
href,
isScheduledNavigation: true
}, event)];
return true;
}
return false;
}
/**
* Maybe navigate to a path.
* @param {string} href Information about the link's href.
* @param {Event} event Dom event that initiated the navigation.
*/
maybeNavigate_(href, event) {
if (!this.canNavigate(href)) {
return;
}
const isNavigationScheduled = this.maybeScheduleNavigation_(href, event);
if (isNavigationScheduled) {
event.preventDefault();
return;
}
var navigateFailed = false;
try {
this.navigate(utils.getUrlPath(href), false, event);
} catch (err) {
// Do not prevent link navigation in case some synchronous error occurs
navigateFailed = true;
}
if (!navigateFailed && !event.isScheduledNavigation) {
event.preventDefault();
}
}
/**
* Checks whether the onbeforeunload global event handler is overloaded
* by client code. If so, it replaces with a function that halts the normal
* event flow in relation with the client onbeforeunload function.
* This can be in most part used to prematurely terminate navigation to other pages
* according to the given constrait(s).
* @protected
*/
maybeOverloadBeforeUnload_() {
if ('function' === typeof window.onbeforeunload) {
window._onbeforeunload = window.onbeforeunload;
window.onbeforeunload = event => {
this.emit('beforeUnload', event);
if (event && event.defaultPrevented) {
return true;
}
};
// mark the updated handler due unwanted recursion
window.onbeforeunload._overloaded = true;
}
}
/**
* Cancels navigation if nextScreen's beforeActivate lifecycle method
* resolves to true.
* @param {!Screen} nextScreen
* @return {!Promise}
*/
maybePreventActivate_(nextScreen) {
return Promise.resolve()
.then(() => {
return nextScreen.beforeActivate();
})
.then(prevent => {
if (prevent) {
this.pendingNavigate = Promise.reject('Cancelled by next screen');
return this.pendingNavigate;
}
});
}
/**
* Cancels navigation if activeScreen's beforeDeactivate lifecycle
* method resolves to true.
* @return {!Promise}
*/
maybePreventDeactivate_() {
return Promise.resolve()
.then(() => {
if (this.activeScreen) {
return this.activeScreen.beforeDeactivate();
}
})
.then(prevent => {
if (prevent) {
this.pendingNavigate = Promise.reject(new Error('Cancelled by active screen'));
return this.pendingNavigate;
}
});
}
/**
* Maybe reposition scroll to hashed anchor.
*/
maybeRepositionScrollToHashedAnchor() {
const hash = globals.window.location.hash;
if (hash) {
let anchorElement = globals.document.getElementById(hash.substring(1));
if (anchorElement) {
const {offsetLeft, offsetTop} = utils.getNodeOffset(anchorElement);
globals.window.scrollTo(offsetLeft, offsetTop);
}
}
}
/**
* If supported by the browser, restores native scroll restoration to the
* value captured by `maybeDisableNativeScrollRestoration`.
*/
maybeRestoreNativeScrollRestoration() {
if (this.nativeScrollRestorationSupported && this.nativeScrollRestoration_) {
globals.window.history.scrollRestoration = this.nativeScrollRestoration_;
}
}
/**
* Maybe restore redirected path hash in case both the current path and
* the given path are the same.
* @param {!string} path Path before navigation.
* @param {!string} redirectPath Path after navigation.
* @param {!string} hash Hash to be added to the path.
* @return {!string} Returns the path with the hash restored.
*/
maybeRestoreRedirectPathHash_(path, redirectPath, hash) {
if (redirectPath === utils.getUrlPathWithoutHash(path)) {
return redirectPath + hash;
}
return redirectPath;
}
/**
* Maybe update scroll position in history state to anchor on path.
* @param {!string} path Path containing anchor
*/
maybeUpdateScrollPositionState_() {
var hash = globals.window.location.hash;
var anchorElement = globals.document.getElementById(hash.substring(1));
if (anchorElement) {
const {offsetLeft, offsetTop} = utils.getNodeOffset(anchorElement);
this.saveHistoryCurrentPageScrollPosition_(offsetTop, offsetLeft);
}
}
/**
* Navigates to the specified path if there is a route handler that matches.
* @param {!string} path Path to navigate containing the base path.
* @param {boolean=} opt_replaceHistory Replaces browser history.
* @param {Event=} event Optional event object that triggered the navigation.
* @return {Promise} Returns a pending request promise.
*/
navigate(path, opt_replaceHistory, opt_event) {
if (!utils.isHtml5HistorySupported()) {
throw new Error('HTML5 History is not supported. Senna will not intercept navigation.');
}
if (opt_event) {
globals.capturedFormElement = opt_event.capturedFormElement;
globals.capturedFormButtonElement = opt_event.capturedFormButtonElement;
}
// When reloading the same path do replaceState instead of pushState to
// avoid polluting history with states with the same path.
if (path === this.activePath) {
opt_replaceHistory = true;
}
this.emit('beforeNavigate', {
event: opt_event,
path: path,
replaceHistory: !!opt_replaceHistory
});
return this.pendingNavigate;
}
/**
* Befores navigation to a path.
* @param {!Event} event Event facade containing <code>path</code> and
* <code>replaceHistory</code>.
* @protected
*/
onBeforeNavigate_(event) {
if (globals.capturedFormElement) {
event.form = globals.capturedFormElement;
}
}
/**
* Befores navigation to a path. Runs after external listeners.
* @param {!Event} event Event facade containing <code>path</code> and
* <code>replaceHistory</code>.
* @protected
*/
onBeforeNavigateDefault_(event) {
if (this.pendingNavigate) {
if (this.pendingNavigate.path === event.path || this.navigationStrategy === NavigationStrategy.SCHEDULE_LAST) {
console.log('Waiting...');
return;
}
}
this.emit('beforeUnload', event);
this.emit('startNavigate', {
form: event.form,
path: event.path,
replaceHistory: event.replaceHistory
});
}
/**
* Custom event handler that executes the original listener that has been
* added by the client code and terminates the navigation accordingly.
* @param {!Event} event original Event facade.
* @protected
*/
onBeforeUnloadDefault_(event) {
var func = window._onbeforeunload;
if (func && !func._overloaded && func()) {
event.preventDefault();
}
}
/**
* Intercepts document clicks and test link elements in order to decide
* whether Surface app can navigate.
* @param {!Event} event Event facade
* @protected
*/
onDocClickDelegate_(event) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.button) {
console.log('Navigate aborted, invalid mouse button or modifier key pressed.');
return;
}
this.maybeNavigate_(event.delegateTarget.href, event);
}
/**
* Intercepts document form submits and test action path in order to decide
* whether Surface app can navigate.
* @param {!Event} event Event facade
* @protected
*/
onDocSubmitDelegate_(event) {
var form = event.delegateTarget;
if (form.method === 'get') {
console.log('GET method not supported');
return;
}
event.capturedFormElement = form;
const buttonSelector = 'button:not([type]),button[type=submit],input[type=submit]';
if (match(globals.document.activeElement, buttonSelector)) {
event.capturedFormButtonElement = globals.document.activeElement;
} else {
event.capturedFormButtonElement = form.querySelector(buttonSelector);
}
this.maybeNavigate_(form.action, event);
}
/**
* Listens to the window's load event in order to avoid issues with some browsers
* that trigger popstate calls on the first load. For more information see
* http://stackoverflow.com/questions/6421769/popstate-on-pages-load-in-chrome.
* @protected
*/
onLoad_() {
this.skipLoadPopstate = true;
setTimeout(() => {
// The timeout ensures that popstate events will be unblocked right
// after the load event occured, but not in the same event-loop cycle.
this.skipLoadPopstate = false;
}, 0);
// Try to reposition scroll to the hashed anchor when page loads.
this.maybeRepositionScrollToHashedAnchor();
}
/**
* Handles browser history changes and fires app's navigation if the state