/
reload-client.js
248 lines (208 loc) · 7.91 KB
/
reload-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
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
class Util {
static pad(num, digits = 2) {
let zeroes = new Array(digits + 1).join(0);
return `${zeroes}${num}`.slice(-1 * digits);
}
static log(message) {
Util.output("log", message);
}
static error(message, error) {
Util.output("error", message, error);
}
static output(type, ...messages) {
let now = new Date();
let date = `${Util.pad(now.getUTCHours())}:${Util.pad(
now.getUTCMinutes()
)}:${Util.pad(now.getUTCSeconds())}.${Util.pad(
now.getUTCMilliseconds(),
3
)}`;
console[type](`[11ty][${date} UTC]`, ...messages);
}
static capitalize(word) {
return word.substr(0, 1).toUpperCase() + word.substr(1);
}
static matchRootAttributes(htmlContent) {
// Workaround for morphdom bug with attributes on <html> https://github.com/11ty/eleventy-dev-server/issues/6
// Note also `childrenOnly: true` above
const parser = new DOMParser();
let parsed = parser.parseFromString(htmlContent, "text/html");
let parsedDoc = parsed.documentElement;
let newAttrs = parsedDoc.getAttributeNames();
let docEl = document.documentElement;
// Remove old
let removedAttrs = docEl.getAttributeNames().filter(name => !newAttrs.includes(name));
for(let attr of removedAttrs) {
docEl.removeAttribute(attr);
}
// Add new
for(let attr of newAttrs) {
docEl.setAttribute(attr, parsedDoc.getAttribute(attr));
}
}
static isEleventyLinkNodeMatch(from, to) {
// Issue #18 https://github.com/11ty/eleventy-dev-server/issues/18
// Don’t update a <link> if the _11ty searchParam is the only thing that’s different
if(from.tagName !== "LINK" || to.tagName !== "LINK") {
return false;
}
let oldWithoutHref = from.cloneNode();
let newWithoutHref = to.cloneNode();
oldWithoutHref.removeAttribute("href");
newWithoutHref.removeAttribute("href");
// if all other attributes besides href match
if(!oldWithoutHref.isEqualNode(newWithoutHref)) {
return false;
}
let oldUrl = new URL(from.href);
let newUrl = new URL(to.href);
// morphdom wants to force href="style.css?_11ty" => href="style.css"
let isErasing = oldUrl.searchParams.has("_11ty") && !newUrl.searchParams.has("_11ty");
if(!isErasing) {
// not a match if _11ty has a new value (not being erased)
return false;
}
oldUrl.searchParams.set("_11ty", "");
newUrl.searchParams.set("_11ty", "");
// is a match if erasing and the rest of the href matches too
return oldUrl.toString() === newUrl.toString();
}
// https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769
static runScript(source, target) {
let script = document.createElement('script');
//copy over the attributes
for(let attr of [...source.attributes]) {
script.setAttribute(attr.nodeName ,attr.nodeValue);
}
script.innerHTML = source.innerHTML;
(target || source).replaceWith(script);
}
}
class EleventyReload {
static reconnect(e) {
if (document.visibilityState === "visible") {
EleventyReload.init({ mode: "reconnect" });
}
}
static async onreload({ subtype, files, build }) {
if (subtype === "css") {
for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) {
let url = new URL(link.href);
url.searchParams.set("_11ty", Date.now());
link.href = url.toString();
}
Util.log(`CSS updated without page reload.`);
} else {
let morphed = false;
try {
if((build.templates || []).length > 0) {
// Important: using `./` in `./morphdom.js` allows the special `.11ty` folder to be changed upstream
const { default: morphdom } = await import(`./morphdom.js`);
// { url, inputPath, content }
for (let template of build.templates || []) {
if (template.url === document.location.pathname) {
// Importantly, if this does not match but is still relevant (layout/include/etc), a full reload happens below. This could be improved.
if ((files || []).includes(template.inputPath)) {
// Notable limitation: this won’t re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded)
morphed = true;
morphdom(document.documentElement, template.content, {
childrenOnly: true,
onBeforeElUpdated: function (fromEl, toEl) {
if (fromEl.nodeName === "SCRIPT" && toEl.nodeName === "SCRIPT") {
Util.runScript(toEl, fromEl);
return false;
}
// Speed-up trick from morphdom docs
// https://dom.spec.whatwg.org/#concept-node-equals
if (fromEl.isEqualNode(toEl)) {
return false;
}
if(Util.isEleventyLinkNodeMatch(fromEl, toEl)) {
return false;
}
return true;
},
onNodeAdded: function (node) {
if (node.nodeName === 'SCRIPT') {
Util.runScript(node);
}
},
});
Util.matchRootAttributes(template.content);
Util.log(`HTML delta applied without page reload.`);
}
break;
}
}
}
} catch(e) {
Util.error( "Morphdom error", e );
}
if (!morphed) {
Util.log(`Page reload initiated.`);
window.location.reload();
}
}
}
static init(options = {}) {
if (!("WebSocket" in window)) {
return;
}
Util.log("Trying to connect…");
let { protocol, host } = new URL(document.location.href);
// works with http (ws) and https (wss)
let websocketProtocol = protocol.replace("http", "ws");
// TODO add a path here so that it doesn’t collide with any app websockets
let socket = new WebSocket(`${websocketProtocol}//${host}`);
// Related to #26
// socket.addEventListener("error", (e) => {
// Util.error(`Error connecting:`, e);
// });
// TODO add special handling for disconnect or document focus to retry
socket.addEventListener("message", async function (event) {
try {
let data = JSON.parse(event.data);
// Util.log( JSON.stringify(data, null, 2) );
let { type } = data;
if (type === "eleventy.reload") {
await EleventyReload.onreload(data);
} else if (type === "eleventy.msg") {
Util.log(`${data.message}`);
} else if (type === "eleventy.error") {
// Log Eleventy build errors
// Extra parsing for Node Error objects
let e = JSON.parse(data.error);
Util.error(`Build error: ${e.message}`, e);
} else if (type === "eleventy.status") {
// Full page reload on initial reconnect
if (data.status === "connected" && options.mode === "reconnect") {
window.location.reload();
}
Util.log(Util.capitalize(data.status));
} else {
Util.log("Unknown event type", data);
}
} catch (e) {
Util.error(`Error parsing ${event.data}: ${e.message}`, e);
}
});
socket.addEventListener("open", (event) => {
EleventyReload.applyReconnectListeners("remove");
});
socket.addEventListener("close", (event) => {
EleventyReload.applyReconnectListeners("remove");
EleventyReload.applyReconnectListeners("add");
});
}
static applyReconnectListeners(mode) {
let method = "addEventListener";
if (mode === "remove") {
method = "removeEventListener";
}
window[method]("focus", EleventyReload.reconnect);
window[method]("visibilitychange", EleventyReload.reconnect);
}
}
// TODO remove this?
// Util.log("Page reload.", Date.now());
EleventyReload.init();