-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
58 lines (51 loc) · 1.38 KB
/
client.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
import { hydrateRoot } from 'react-dom/client';
const root = hydrateRoot(document, getInitialClientJSX());
let currentPathname = window.location.pathname;
async function navigate(pathname) {
currentPathname = pathname;
const clientJSX = await fetchClientJSX(pathname);
if (pathname === currentPathname) {
root.render(clientJSX);
}
}
function getInitialClientJSX() {
const clientJSX = JSON.parse(window.__INITIAL_CLIENT_JSX_STRING__, parseJSX);
return clientJSX;
}
async function fetchClientJSX(pathname) {
const response = await fetch(pathname + '?jsx');
const clientJSXString = await response.text();
const clientJSX = JSON.parse(clientJSXString, parseJSX);
return clientJSX;
}
function parseJSX(key, value) {
if (value === '$RE') {
return Symbol.for('react.element');
} else if (typeof value === 'string' && value.startsWith('$$')) {
return value.slice(1);
} else {
return value;
}
}
window.addEventListener(
'click',
e => {
if (e.target.tagName !== 'A') {
return;
}
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
return;
}
const href = e.target.getAttribute('href');
if (!href.startsWith('/')) {
return;
}
e.preventDefault();
window.history.pushState(null, null, href);
navigate(href);
},
true
);
window.addEventListener('popstate', () => {
navigate(window.location.pathname);
});