UNPKG

2.88 kBJavaScriptView Raw
1/**
2@license
3Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
4This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
5The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
6The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
7Code distributed by Google as part of the polymer project is also
8subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
9*/
10/**
11 Basic router that calls a callback whenever the location is updated.
12
13 Example:
14
15 import { installRouter } from 'pwa-helpers/router.js';
16
17 installRouter((location) => handleNavigation(location));
18
19 For example, if you're using this router in a Redux-connected component,
20 you could dispatch an action in the callback:
21
22 import { installRouter } from 'pwa-helpers/router.js';
23 import { navigate } from '../actions/app.js';
24
25 installRouter((location) => store.dispatch(navigate(location)))
26
27 If you need to force a navigation to a new location programmatically, you can
28 do so by pushing a new state using the History API, and then manually
29 calling the callback with the new location:
30
31 window.history.pushState({}, '', '/new-route');
32 handleNavigation(window.location);
33
34 Optionally, you can use the second argument to read the event that caused the
35 navigation. For example, you may want to scroll to top only after a link click.
36
37 installRouter((location, event) => {
38 // Only scroll to top on link clicks, not popstate events.
39 if (event && event.type === 'click') {
40 window.scrollTo(0, 0);
41 }
42 handleNavigation(location);
43 });
44*/
45export const installRouter = (locationUpdatedCallback) => {
46 document.body.addEventListener('click', e => {
47 if (e.defaultPrevented || e.button !== 0 ||
48 e.metaKey || e.ctrlKey || e.shiftKey)
49 return;
50 const anchor = e.composedPath().filter(n => n.tagName === 'A')[0];
51 if (!anchor || anchor.target ||
52 anchor.hasAttribute('download') ||
53 anchor.getAttribute('rel') === 'external')
54 return;
55 const href = anchor.href;
56 if (!href || href.indexOf('mailto:') !== -1)
57 return;
58 const location = window.location;
59 const origin = location.origin || location.protocol + '//' + location.host;
60 if (href.indexOf(origin) !== 0)
61 return;
62 e.preventDefault();
63 if (href !== location.href) {
64 window.history.pushState({}, '', href);
65 locationUpdatedCallback(location, e);
66 }
67 });
68 window.addEventListener('popstate', e => locationUpdatedCallback(window.location, e));
69 locationUpdatedCallback(window.location, null /* event */);
70};
71//# sourceMappingURL=router.js.map
\No newline at end of file