forked from sveltejs/sapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
388 lines (310 loc) · 9.72 KB
/
app.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
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
import { writable } from 'svelte/store';
import App from '@sapper/internal/App.svelte';
import { root_preload, ErrorComponent, ignore, components, routes } from '@sapper/internal/manifest-client';
import {
Target,
ScrollPosition,
Component,
Redirect,
ComponentLoader,
ComponentConstructor,
Route,
Query,
Page
} from './types';
import goto from './goto';
declare const __SAPPER__;
export const initial_data = typeof __SAPPER__ !== 'undefined' && __SAPPER__;
let ready = false;
let root_component: Component;
let current_token: {};
let root_preloaded: Promise<any>;
let current_branch = [];
let current_query = '{}';
const stores = {
page: writable({}),
preloading: writable(null),
session: writable(initial_data && initial_data.session)
};
let $session;
let session_dirty: boolean;
stores.session.subscribe(async value => {
$session = value;
if (!ready) return;
session_dirty = true;
const target = select_target(new URL(location.href));
const token = current_token = {};
const { redirect, props, branch } = await hydrate_target(target);
if (token !== current_token) return; // a secondary navigation happened while we were loading
await render(redirect, branch, props, target.page);
});
export let prefetching: {
href: string;
promise: Promise<{ redirect?: Redirect, data?: any }>;
} = null;
export function set_prefetching(href, promise) {
prefetching = { href, promise };
}
export let target: Node;
export function set_target(element) {
target = element;
}
export let uid = 1;
export function set_uid(n) {
uid = n;
}
export let cid: number;
export function set_cid(n) {
cid = n;
}
const _history = typeof history !== 'undefined' ? history : {
pushState: (state: any, title: string, href: string) => {},
replaceState: (state: any, title: string, href: string) => {},
scrollRestoration: ''
};
export { _history as history };
export const scroll_history: Record<string, ScrollPosition> = {};
export function extract_query(search: string) {
const query = Object.create(null);
if (search.length > 0) {
search.slice(1).split('&').forEach(searchParam => {
let [, key, value = ''] = /([^=]*)(?:=(.*))?/.exec(decodeURIComponent(searchParam.replace(/\+/g, ' ')));
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;
}
export function select_target(url: URL): Target {
if (url.origin !== location.origin) return null;
if (!url.pathname.startsWith(initial_data.baseUrl)) return null;
let path = url.pathname.slice(initial_data.baseUrl.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: Query = extract_query(url.search);
const part = route.parts[route.parts.length - 1];
const params = part.params ? part.params(match) : {};
const page = { host: location.host, path, query, params };
return { href: url.href, route, match, page };
}
}
}
export function handle_error(url: URL) {
const { host, pathname, search } = location;
const { session, preloaded, status, error } = initial_data;
if (!root_preloaded) {
root_preloaded = preloaded && preloaded[0]
}
const props = {
error,
status,
session,
level0: {
props: root_preloaded
},
level1: {
props: {
status,
error
},
component: ErrorComponent
},
segments: ['_error']
}
const query = extract_query(search);
render(null, [], props, { host, path: pathname, query, params: {} });
}
export function scroll_state() {
return {
x: pageXOffset,
y: pageYOffset
};
}
export async function navigate(target: Target, id: number, noscroll?: boolean, hash?: string): Promise<any> {
if (id) {
// popstate or initial navigation
cid = id;
} else {
const current_scroll = scroll_state();
// clicked on a link. preserve scroll state
scroll_history[cid] = current_scroll;
id = cid = ++uid;
scroll_history[cid] = noscroll ? current_scroll : { x: 0, y: 0 };
}
cid = id;
if (root_component) stores.preloading.set(true);
const loaded = prefetching && prefetching.href === target.href ?
prefetching.promise :
hydrate_target(target);
prefetching = null;
const token = current_token = {};
const { redirect, props, branch } = await loaded;
if (token !== current_token) return; // a secondary navigation happened while we were loading
await render(redirect, branch, props, target.page);
if (document.activeElement) document.activeElement.blur();
if (!noscroll) {
let scroll = scroll_history[id];
if (hash) {
// scroll is an element id (from a hash), we need to compute y.
const deep_linked = document.getElementById(hash.slice(1));
if (deep_linked) {
scroll = {
x: 0,
y: deep_linked.getBoundingClientRect().top
};
}
}
scroll_history[cid] = scroll;
if (scroll) scrollTo(scroll.x, scroll.y);
}
}
async function render(redirect: Redirect, branch: any[], props: any, page: Page) {
if (redirect) return goto(redirect.location, { replaceState: true });
stores.page.set(page);
stores.preloading.set(false);
if (root_component) {
root_component.$set(props);
} else {
props.stores = {
page: { subscribe: stores.page.subscribe },
preloading: { subscribe: stores.preloading.subscribe },
session: stores.session
};
props.level0 = {
props: await root_preloaded
};
// first load — remove SSR'd <head> contents
const start = document.querySelector('#sapper-head-start');
const end = document.querySelector('#sapper-head-end');
if (start && end) {
while (start.nextSibling !== end) detach(start.nextSibling);
detach(start);
detach(end);
}
root_component = new App({
target,
props,
hydrate: true
});
}
current_branch = branch;
current_query = JSON.stringify(page.query);
ready = true;
session_dirty = false;
}
function part_changed(i, segment, match, stringified_query) {
// TODO only check query string changes for preload functions
// that do in fact depend on it (using static analysis or
// runtime instrumentation)
if (stringified_query !== current_query) return true;
const previous = current_branch[i];
if (!previous) return false;
if (segment !== previous.segment) return true;
if (previous.match) {
if (JSON.stringify(previous.match.slice(1, i + 2)) !== JSON.stringify(match.slice(1, i + 2))) {
return true;
}
}
}
export async function hydrate_target(target: Target): Promise<{
redirect?: Redirect;
props?: any;
branch?: Array<{ Component: ComponentConstructor, preload: (page) => Promise<any>, segment: string }>;
}> {
const { route, page } = target;
const segments = page.path === '/' ? ['index'] : page.path.split('/').filter(Boolean);
let redirect: Redirect = null;
const props = { error: null, status: 200, segments: [segments[0]] };
const preload_context = {
fetch: (url: string, opts?: any) => fetch(url, opts),
redirect: (statusCode: number, location: string) => {
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
throw new Error(`Conflicting redirects`);
}
redirect = { statusCode, location };
},
error: (status: number, error: Error | string) => {
props.error = typeof error === 'string' ? new Error(error) : error;
props.status = status;
}
};
if (!root_preloaded) {
root_preloaded = initial_data.preloaded[0] || root_preload.call(preload_context, {
host: page.host,
path: page.path,
query: page.query,
params: {}
}, $session);
}
let branch;
let l = 1;
try {
const stringified_query = JSON.stringify(page.query);
const match = route.pattern.exec(page.path);
let segment_dirty = false;
branch = await Promise.all(route.parts.map(async (part, i) => {
const segment = segments[i];
if (part_changed(i, segment, match, stringified_query)) segment_dirty = true;
props.segments[l] = segments[i + 1]; // TODO make this less confusing
if (!part) return { segment };
const j = l++;
if (!session_dirty && !segment_dirty && current_branch[i] && current_branch[i].part === part.i) {
return current_branch[i];
}
segment_dirty = false;
const { default: component, preload } = await load_component(components[part.i]);
let preloaded;
if (ready || !initial_data.preloaded[i + 1]) {
preloaded = preload
? await preload.call(preload_context, {
host: page.host,
path: page.path,
query: page.query,
params: part.params ? part.params(target.match) : {}
}, $session)
: {};
} else {
preloaded = initial_data.preloaded[i + 1];
}
return (props[`level${j}`] = { component, props: preloaded, segment, match, part: part.i });
}));
} catch (error) {
props.error = error;
props.status = 500;
branch = [];
}
return { redirect, props, branch };
}
function load_css(chunk: string) {
const href = `client/${chunk}`;
if (document.querySelector(`link[href="${href}"]`)) return;
return new Promise((fulfil, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
link.onload = () => fulfil();
link.onerror = reject;
document.head.appendChild(link);
});
}
export function load_component(component: ComponentLoader): Promise<{
default: ComponentConstructor,
preload?: (input: any) => any
}> {
// TODO this is temporary — once placeholders are
// always rewritten, scratch the ternary
const promises: Array<Promise<any>> = (typeof component.css === 'string' ? [] : component.css.map(load_css));
promises.unshift(component.js());
return Promise.all(promises).then(values => values[0]);
}
function detach(node: Node) {
node.parentNode.removeChild(node);
}