This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
router.js
147 lines (131 loc) · 4.16 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
import { hydrate, render } from 'preact';
import { toVdom, hydratedIslands } from './vdom';
import { createRootFragment } from './utils';
import { csnMetaTagItemprop, directivePrefix } from './constants';
// The root to render the vdom (document.body).
let rootFragment;
// The cache of visited and prefetched pages, stylesheets and scripts.
const pages = new Map();
const stylesheets = new Map();
const scripts = new Map();
// Helper to remove domain and hash from the URL. We are only interesting in
// caching the path and the query.
const cleanUrl = (url) => {
const u = new URL(url, window.location);
return u.pathname + u.search;
};
// Helper to check if a page can do client-side navigation.
export const canDoClientSideNavigation = (dom) =>
dom
.querySelector(`meta[itemprop='${csnMetaTagItemprop}']`)
?.getAttribute('content') === 'active';
// Fetch styles of a new page.
const fetchHead = async (head) => {
const sheets = await Promise.all(
[].map.call(head.querySelectorAll("link[rel='stylesheet']"), (link) => {
const href = link.getAttribute('href');
if (!stylesheets.has(href))
stylesheets.set(
href,
fetch(href).then((r) => r.text())
);
return stylesheets.get(href);
})
);
const stylesFromSheets = sheets.map((sheet) => {
const style = document.createElement('style');
style.textContent = sheet;
return style;
});
const scriptsToLoad = await Promise.all(
[].map.call(head.querySelectorAll('script[src]'), (script) => {
const src = script.getAttribute('src');
if (!scripts.has(src))
scripts.set(
src,
fetch(src).then((r) => r.text())
);
return scripts.get(src);
})
);
const scriptTags = scriptsToLoad.map((script) => {
const scriptEl = document.createElement('script');
scriptEl.textContent = script;
return scriptEl;
});
return [
...scriptTags,
head.querySelector('title'),
...head.querySelectorAll('style'),
...stylesFromSheets,
];
};
// Fetch a new page and convert it to a static virtual DOM.
const fetchPage = async (url) => {
const html = await window.fetch(url).then((r) => r.text());
const dom = new window.DOMParser().parseFromString(html, 'text/html');
if (!canDoClientSideNavigation(dom.head)) return false;
const head = await fetchHead(dom.head);
return { head, body: toVdom(dom.body) };
};
// Prefetch a page. We store the promise to avoid triggering a second fetch for
// a page if a fetching has already started.
export const prefetch = (url) => {
url = cleanUrl(url);
if (!pages.has(url)) {
pages.set(url, fetchPage(url));
}
};
// Navigate to a new page.
export const navigate = async (href) => {
const url = cleanUrl(href);
prefetch(url);
const page = await pages.get(url);
if (page) {
document.head.replaceChildren(...page.head);
render(page.body, rootFragment);
window.history.pushState({}, '', href);
} else {
window.location.assign(href);
}
};
// Listen to the back and forward buttons and restore the page if it's in the
// cache.
window.addEventListener('popstate', async () => {
const url = cleanUrl(window.location); // Remove hash.
const page = pages.has(url) && (await pages.get(url));
if (page) {
document.head.replaceChildren(...page.head);
render(page.body, rootFragment);
} else {
window.location.reload();
}
});
// Initialize the router with the initial DOM.
export const init = async () => {
if (canDoClientSideNavigation(document.head)) {
// Create the root fragment to hydrate everything.
rootFragment = createRootFragment(
document.documentElement,
document.body
);
const body = toVdom(document.body);
hydrate(body, rootFragment);
// Cache the scripts. Has to be called before fetching the head.
[].map.call(document.head.querySelectorAll('script[src]'), (script) => {
scripts.set(script.getAttribute('src'), script.textContent);
});
const head = await fetchHead(document.head);
pages.set(cleanUrl(window.location), Promise.resolve({ body, head }));
} else {
document
.querySelectorAll(`[${directivePrefix}island]`)
.forEach((node) => {
if (!hydratedIslands.has(node)) {
const fragment = createRootFragment(node.parentNode, node);
const vdom = toVdom(node);
hydrate(vdom, fragment);
}
});
}
};