This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
index.ts
241 lines (195 loc) · 6.48 KB
/
index.ts
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
import {
ScrollPosition,
Target
} from '../types';
import {
ignore,
routes
} from '@sapper/internal/manifest-client';
import find_anchor from './find_anchor';
import { Page, Query } from '@sapper/common';
export let uid = 1;
export function set_uid(n: number) {
uid = n;
}
export let cid: number;
export function set_cid(n: number) {
cid = n;
}
const _history: History = typeof history !== 'undefined' ? history : {
pushState: () => {},
replaceState: () => {},
scrollRestoration: 'auto'
} as Partial<History> as any;
export { _history as history };
export const scroll_history: Record<string, ScrollPosition> = {};
export function load_current_page(): Promise<void> {
return Promise.resolve().then(() => {
const { hash, href } = location;
_history.replaceState({ id: uid }, '', href);
const target = select_target(new URL(location.href));
if (target) return navigate(target, uid, true, hash);
});
}
let base_url: string;
let handle_target: (dest: Target) => Promise<void>;
export function init(base: string, handler: (dest: Target) => Promise<void>): void {
base_url = base;
handle_target = handler;
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';
});
addEventListener('click', handle_click);
addEventListener('popstate', handle_popstate);
}
// IE11 does not support URLSearchParams so we'll fall back to a custom
// RegExp that mimics the standard URLSearchParams method
const _get_query_array = (search: string): string[][] => {
if (typeof URLSearchParams !== 'undefined') {
return [...new URLSearchParams(search).entries()];
}
return search.slice(1).split('&').map(searchParam => {
// Instead of `.*` we'll use \s\S to allow characters and non characters
// such as [\r\n\v\f]
const [, key, value = ''] = /([^=]*)(?:=([\S\s]*))?/.exec(decodeURIComponent(searchParam.replace(/\+/g, ' ')));
return [ key, value ];
});
};
export function extract_query(search: string): Query {
const query: Query = Object.create(null);
return search.length ? _get_query_array(search).reduce(
(query, [key, value]) => {
if (typeof query[key] === 'string') query[key] = [<string>query[key]];
if (typeof query[key] === 'object') (query[key] as string[]).push(value);
else query[key] = value;
return query;
}, query) :
query;
}
export function select_target(url: URL): Target {
if (url.origin !== location.origin) return null;
if (!url.pathname.startsWith(base_url)) return null;
let path = url.pathname.slice(base_url.length);
if (path === '') {
path = '/';
}
// avoid accidental clashes between server routes and page routes
if (ignore.some(pattern => pattern.test(path))) return;
for (let i = 0; i < routes.length; i += 1) {
const route = routes[i];
const match = route.pattern.exec(path);
if (match) {
const query = extract_query(url.search);
const part = route.parts[route.parts.length - 1];
const params = part.params ? part.params(match) : {};
const page: Page = { host: location.host, path, query, params };
return { href: url.href, route, match, page };
}
}
}
function handle_click(event: MouseEvent) {
// Adapted from https://github.com/visionmedia/page.js
// MIT license https://github.com/visionmedia/page.js#license
if (which(event) !== 1) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
if (event.defaultPrevented) return;
const a: HTMLAnchorElement | SVGAElement = <HTMLAnchorElement | SVGAElement>find_anchor(<Node>event.target);
if (!a) return;
if (!a.href) return;
// check if link is inside an svg
// in this case, both href and target are always inside an object
const svg = typeof a.href === 'object' && a.href.constructor.name === 'SVGAnimatedString';
const href = String(svg ? (<SVGAElement>a).href.baseVal : a.href);
if (href === location.href) {
if (!location.hash) event.preventDefault();
return;
}
// Ignore if tag has
// 1. 'download' attribute
// 2. rel='external' attribute
if (a.hasAttribute('download') || a.getAttribute('rel') === 'external') return;
// Ignore if <a> has a target
if (svg ? (<SVGAElement>a).target.baseVal : a.target) return;
const url = new URL(href);
// Don't handle hash changes
if (url.pathname === location.pathname && url.search === location.search) return;
const target = select_target(url);
if (target) {
const noscroll = a.hasAttribute('sapper:noscroll');
navigate(target, null, noscroll, url.hash);
event.preventDefault();
_history.pushState({ id: cid }, '', url.href);
}
}
function which(event: MouseEvent) {
return event.which === null ? event.button : event.which;
}
function scroll_state() {
return {
x: pageXOffset,
y: pageYOffset
};
}
function handle_popstate(event: PopStateEvent) {
scroll_history[cid] = scroll_state();
if (event.state) {
const url = new URL(location.href);
const target = select_target(url);
if (target) {
navigate(target, event.state.id);
} else {
// eslint-disable-next-line
location.href = location.href; // nosonar
}
} else {
// hashchange
set_uid(uid + 1);
set_cid(uid);
_history.replaceState({ id: cid }, '', location.href);
}
}
export async function navigate(dest: Target, id: number, noscroll?: boolean, hash?: string): Promise<void> {
const popstate = !!id;
if (popstate) {
cid = id;
} else {
const current_scroll = scroll_state();
// clicked on a link. preserve scroll state
scroll_history[cid] = current_scroll;
cid = id = ++uid;
scroll_history[cid] = noscroll ? current_scroll : { x: 0, y: 0 };
}
await handle_target(dest);
if (document.activeElement && (document.activeElement instanceof HTMLElement)) document.activeElement.blur();
if (!noscroll) {
let scroll = scroll_history[id];
let deep_linked;
if (hash) {
// scroll is an element id (from a hash), we need to compute y.
deep_linked = document.getElementById(hash.slice(1));
if (deep_linked) {
scroll = {
x: 0,
y: deep_linked.getBoundingClientRect().top + scrollY
};
}
}
scroll_history[cid] = scroll;
if (scroll && (popstate || deep_linked)) {
scrollTo(scroll.x, scroll.y);
} else {
scrollTo(0, 0);
}
}
}