forked from sveltejs/kit
/
router.js
293 lines (243 loc) · 7.97 KB
/
router.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
import { get_base_uri } from './utils';
function scroll_state() {
return {
x: pageXOffset,
y: pageYOffset
};
}
/**
* @param {Event} event
* @returns {HTMLAnchorElement | SVGAElement | undefined}
*/
function find_anchor(event) {
const node = event
.composedPath()
.find((e) => e instanceof Node && e.nodeName.toUpperCase() === 'A'); // SVG <a> elements have a lowercase name
return /** @type {HTMLAnchorElement | SVGAElement | undefined} */ (node);
}
/**
* @param {HTMLAnchorElement | SVGAElement} node
* @returns {URL}
*/
function get_href(node) {
return node instanceof SVGAElement
? new URL(node.href.baseVal, document.baseURI)
: new URL(node.href);
}
export class Router {
/**
* @param {{
* base: string;
* routes: import('types/internal').CSRRoute[];
* trailing_slash: import('types/internal').TrailingSlash;
* renderer: import('./renderer').Renderer
* }} opts
*/
constructor({ base, routes, trailing_slash, renderer }) {
this.base = base;
this.routes = routes;
this.trailing_slash = trailing_slash;
/** Keeps tracks of multiple navigations caused by redirects during rendering */
this.navigating = 0;
/** @type {import('./renderer').Renderer} */
this.renderer = renderer;
renderer.router = this;
this.enabled = true;
// make it possible to reset focus
document.body.setAttribute('tabindex', '-1');
// create initial history entry, so we can return here
history.replaceState(history.state || {}, '', location.href);
}
init_listeners() {
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
// Adopted from Nuxt.js
// Reset scrollRestoration to auto when leaving page, allowing page reload
// and back-navigation from other pages to use the browser to restore the
// scrolling position.
addEventListener('beforeunload', () => {
history.scrollRestoration = 'auto';
});
// Setting scrollRestoration to manual again when returning to this page.
addEventListener('load', () => {
history.scrollRestoration = 'manual';
});
// There's no API to capture the scroll location right before the user
// hits the back/forward button, so we listen for scroll events
/** @type {NodeJS.Timeout} */
let scroll_timer;
addEventListener('scroll', () => {
clearTimeout(scroll_timer);
scroll_timer = setTimeout(() => {
// Store the scroll location in the history
// This will persist even if we navigate away from the site and come back
const new_state = {
...(history.state || {}),
'sveltekit:scroll': scroll_state()
};
history.replaceState(new_state, document.title, window.location.href);
// iOS scroll event intervals happen between 30-150ms, sometimes around 200ms
}, 200);
});
/** @param {Event} event */
const trigger_prefetch = (event) => {
const a = find_anchor(event);
if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
this.prefetch(get_href(a));
}
};
/** @type {NodeJS.Timeout} */
let mousemove_timeout;
/** @param {MouseEvent|TouchEvent} event */
const handle_mousemove = (event) => {
clearTimeout(mousemove_timeout);
mousemove_timeout = setTimeout(() => {
// ensure event.composedPath() in find_anchor(event) returns an array of EventTarget objects
event.target?.dispatchEvent(
new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
);
}, 20);
};
addEventListener('touchstart', trigger_prefetch);
addEventListener('mousemove', handle_mousemove);
addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
/** @param {MouseEvent} event */
addEventListener('click', (event) => {
if (!this.enabled) return;
// Adapted from https://github.com/visionmedia/page.js
// MIT license https://github.com/visionmedia/page.js#license
if (event.button || event.which !== 1) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
if (event.defaultPrevented) return;
const a = find_anchor(event);
if (!a) return;
if (!a.href) return;
const url = get_href(a);
const url_string = url.toString();
if (url_string === location.href) {
if (!location.hash) event.preventDefault();
return;
}
// Ignore if tag has
// 1. 'download' attribute
// 2. 'rel' attribute includes external
const rel = (a.getAttribute('rel') || '').split(/\s+/);
if (a.hasAttribute('download') || (rel && rel.includes('external'))) {
return;
}
// Ignore if <a> has a target
if (a instanceof SVGAElement ? a.target.baseVal : a.target) return;
if (!this.owns(url)) return;
const noscroll = a.hasAttribute('sveltekit:noscroll');
const i1 = url_string.indexOf('#');
const i2 = location.href.indexOf('#');
const u1 = i1 >= 0 ? url_string.substring(0, i1) : url_string;
const u2 = i2 >= 0 ? location.href.substring(0, i2) : location.href;
history.pushState({}, '', url.href);
if (u1 === u2) {
window.dispatchEvent(new HashChangeEvent('hashchange'));
}
this._navigate(url, noscroll ? scroll_state() : null, false, [], url.hash);
event.preventDefault();
});
addEventListener('popstate', (event) => {
if (event.state && this.enabled) {
const url = new URL(location.href);
this._navigate(url, event.state['sveltekit:scroll'], false, []);
}
});
}
/** @param {URL} url */
owns(url) {
return url.origin === location.origin && url.pathname.startsWith(this.base);
}
/**
* @param {URL} url
* @returns {import('./types').NavigationInfo | undefined}
*/
parse(url) {
if (this.owns(url)) {
const path = url.pathname.slice(this.base.length) || '/';
const decoded_path = decodeURI(path);
const routes = this.routes.filter(([pattern]) => pattern.test(decoded_path));
const query = new URLSearchParams(url.search);
const id = `${path}?${query}`;
return { id, routes, path, decoded_path, query };
}
}
/**
* @typedef {Parameters<typeof import('$app/navigation').goto>} GotoParams
*
* @param {GotoParams[0]} href
* @param {GotoParams[1]} opts
* @param {string[]} chain
*/
async goto(
href,
{ noscroll = false, replaceState = false, keepfocus = false, state = {} } = {},
chain
) {
const url = new URL(href, get_base_uri(document));
if (this.enabled && this.owns(url)) {
history[replaceState ? 'replaceState' : 'pushState'](state, '', href);
return this._navigate(url, noscroll ? scroll_state() : null, keepfocus, chain, url.hash);
}
location.href = url.href;
return new Promise(() => {
/* never resolves */
});
}
enable() {
this.enabled = true;
}
disable() {
this.enabled = false;
}
/**
* @param {URL} url
* @returns {Promise<import('./types').NavigationResult>}
*/
async prefetch(url) {
const info = this.parse(url);
if (!info) {
throw new Error('Attempted to prefetch a URL that does not belong to this app');
}
return this.renderer.load(info);
}
/**
* @param {URL} url
* @param {{ x: number, y: number }?} scroll
* @param {boolean} keepfocus
* @param {string[]} chain
* @param {string} [hash]
*/
async _navigate(url, scroll, keepfocus, chain, hash) {
const info = this.parse(url);
if (!info) {
throw new Error('Attempted to navigate to a URL that does not belong to this app');
}
if (!this.navigating) {
dispatchEvent(new CustomEvent('sveltekit:navigation-start'));
}
this.navigating++;
// remove trailing slashes
if (info.path !== '/') {
const has_trailing_slash = info.path.endsWith('/');
const incorrect =
(has_trailing_slash && this.trailing_slash === 'never') ||
(!has_trailing_slash &&
this.trailing_slash === 'always' &&
!(info.path.split('/').pop() || '').includes('.'));
if (incorrect) {
info.path = has_trailing_slash ? info.path.slice(0, -1) : info.path + '/';
history.replaceState({}, '', `${this.base}${info.path}${location.search}`);
}
}
await this.renderer.handle_navigation(info, chain, false, { hash, scroll, keepfocus });
this.navigating--;
if (!this.navigating) {
dispatchEvent(new CustomEvent('sveltekit:navigation-end'));
}
}
}