-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
78 lines (67 loc) · 1.88 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { hydrateRoot } from "react-dom/client";
const root = hydrateRoot(document, getInitialClientJSX());
let currentPathname = window.location.pathname;
function randomColor() {
const r = Math.floor(Math.random() * 256)
.toString(16)
.padStart(2, "0")
const g = Math.floor(Math.random() * 256)
.toString(16)
.padStart(2, "0")
const b = Math.floor(Math.random() * 256)
.toString(16)
.padStart(2, "0")
return "#" + r + g + b
}
// const body = document.querySelector("body")
// body.style.backgroundColor = randomColor()
// body.style.transition = "background-color 2s ease-in"
async function navigate(pathname) {
currentPathname = pathname;
const clientJSX = await fetchClientJSX(pathname);
if (pathname === currentPathname) {
root.render(clientJSX);
// body.style.backgroundColor = randomColor()
}
}
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);
});