-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.js
More file actions
80 lines (66 loc) · 1.79 KB
/
replace.js
File metadata and controls
80 lines (66 loc) · 1.79 KB
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
/**
* replace is a valid handler for routing, and bundles up the functionality of
* replacing the headers and content of a page
*
* @param {string} url - the url to replace the current url with
*/
export async function replace(url) {
return loadDocument(url);
}
async function loadDocument(href) {
const resp = await fetch(href);
await replaceDocument(resp);
return resp.url;
}
/**
* Replace a document with a response's content
*
* @param {Response} resp - fetch response
*/
export async function replaceDocument(resp) {
const html = await resp.text();
const parser = new DOMParser();
const newDoc = parser.parseFromString(html, "text/html");
mergeBody(newDoc);
mergeHeaders(newDoc);
}
function mergeBody(newDoc) {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.classList = newDoc.body.classList;
for (const element of Array.from(newDoc.body.childNodes)) {
document.body.appendChild(element);
}
}
function mergeHeaders(newDoc) {
const newChildren = Array.from(newDoc.head.children);
for (const element of Array.from(document.head.children)) {
if (element.tagName === "TITLE") {
continue;
}
const sticky = element.hasAttribute("data-client-router-sticky");
const matches = newChildren.filter((newChild) =>
newChild.isEqualNode(element),
);
// if it's not in the new head, remove it from head
if (matches.length === 0 && !sticky) {
document.head.removeChild(element);
} else {
for (const match of matches) {
try {
newDoc.head.removeChild(match);
} catch {
// if no match, ignore
}
}
}
}
for (const element of Array.from(newDoc.head.children)) {
if (element.tagName === "TITLE") {
document.title = newDoc.title;
} else {
document.head.appendChild(element);
}
}
}