-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic-csr.js
239 lines (199 loc) · 6.04 KB
/
static-csr.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
(function () {
/** @type {Record<string, Page>} */
const pages = {};
/** @type {string} */
const route = document.documentElement.getAttribute('data-route');
/** @type {DOMParser} */
const domParser = new DOMParser();
/** @type {string} */
const url = location.origin + location.pathname;
/** @type {string} */
const baseUrl = url.substr(0, url.length - route.length);
/** @type {number} */
let lastTimerId = /** @type {any} */ (setTimeout(null));
/**
* 元素並非靜態
* @param {Node|HTMLElement} node
* @returns {boolean}
*/
const isElementDynamic = (node) =>
node instanceof HTMLElement && !node.hasAttribute('data-static');
/**
* 元素並非腳本
* @param {Node|HTMLElement} node
* @returns {boolean}
*/
const isElementNotScript = (node) => !(node instanceof HTMLScriptElement);
/**
* 深層的複製元素
* @param {Node} node
* @returns {Node}
*/
const cloneNodeDeeply = (node) => node.cloneNode(true);
/**
* 新增到特定節點
* @param {Node} parentNode
* @returns {(node: Node) => void}
*/
const appendTo = (parentNode) => (node) => parentNode.appendChild(node);
/**
* 移除自特定節點
* @param {Node} parentNode
* @returns {(node: Node) => void}
*/
const removeFrom = (parentNode) => (node) => parentNode.removeChild(node);
/**
* 解析HTML文件
* @param {string} htmlText
* @returns {Document}
*/
const toDocument = (htmlText) =>
domParser.parseFromString(htmlText, 'text/html');
/**
* 轉為腳本函數
* @param {string} scriptText
* @returns {(window: Window) => void}
*/
const toScriptFunction = (scriptText) =>
/** @type {(window: Window) => void} */
(Function('window', scriptText));
/**
* 取得腳本文字
* @param {HTMLScriptElement} scriptElement
* @returns {Promise<string>}
*/
const getScriptText = async (scriptElement) =>
scriptElement.src
? (await fetch(scriptElement.src)).text()
: scriptElement.innerText;
/** 頁面 */
class Page {
/**
* @param {Document} sourceDocument
*/
constructor(sourceDocument) {
/** @type {Readonly<Record<'head' | 'body', DocumentFragment>>} */
const fragments = {
head: document.createDocumentFragment(),
body: document.createDocumentFragment(),
};
Array.from(sourceDocument.head.childNodes)
.filter(isElementDynamic)
.filter(isElementNotScript)
.map(cloneNodeDeeply)
.forEach(appendTo(fragments.head));
Array.from(sourceDocument.body.childNodes)
.filter(isElementDynamic)
.filter(isElementNotScript)
.map(cloneNodeDeeply)
.forEach(appendTo(fragments.body));
/** @readonly 各區塊的片段 */
this.fragments = fragments;
/** @type {Promise<string>[]} */
const whenGotScriptTexts = Array.from(sourceDocument.scripts)
.filter(isElementDynamic)
.map(getScriptText);
/** @readonly 所有腳本 */
this.whenGotScriptFunction = Promise.all(whenGotScriptTexts)
.then((scriptTexts) => scriptTexts.join('\n;\n'))
.then(toScriptFunction);
}
/**
* 顯示畫面
*/
render() {
const { fragments, whenGotScriptFunction } = this;
const headFragment = fragments.head.cloneNode(true);
const bodyFragment = fragments.body.cloneNode(true);
const headChildNodes = Array.from(document.head.childNodes).filter(
isElementDynamic
);
const bodyChildNodes = Array.from(document.body.childNodes).filter(
isElementDynamic
);
document.head.appendChild(headFragment);
document.body.appendChild(bodyFragment);
headChildNodes.forEach(removeFrom(document.head));
bodyChildNodes.forEach(removeFrom(document.body));
whenGotScriptFunction.then((whenGotScriptFunction) =>
whenGotScriptFunction.call(window, window)
);
}
/**
* 載入頁面
* @param {string} url 頁面網址
*/
static async load(url) {
const response = await fetch(url);
const htmlText = await response.text();
const document = toDocument(htmlText);
return new Page(document);
}
}
/**
* 切換網址
* @param {string} url
*/
function changeUrl(url) {
if (location.href !== url) {
history.pushState({}, '', url);
}
}
/**
* 切換頁面
* @param {string} route
*/
async function changePage(route) {
const url = baseUrl + route;
let timerId = lastTimerId;
lastTimerId = setTimeout(null);
for (; timerId < lastTimerId; timerId++) {
clearTimeout(timerId);
}
if (!pages[route]) {
const page = await Page.load(url);
pages[route] = page;
}
pages[route].render();
changeUrl(url);
}
/**
* 以網址切換頁面
* @param {string} url
*/
function changePageByUrl(url) {
const route = url.substr(baseUrl.length);
changePage(route);
}
Object.defineProperty(window, 'route', {
get: () => location.href.substr(baseUrl.length),
set: changePage,
});
window.addEventListener('load', function () {
const page = new Page(document);
pages[route] = page;
window.addEventListener('popstate', function () {
changePageByUrl(location.href);
});
window.addEventListener('click', function (event) {
/** @type {EventTarget|HTMLAnchorElement} */
const element = event.target;
if (element instanceof HTMLAnchorElement && element.target === '') {
if (!event.defaultPrevented && element.href.indexOf(baseUrl) === 0) {
event.preventDefault();
changePageByUrl(element.href);
}
}
});
window.addEventListener('submit', function (event) {
/** @type {EventTarget|HTMLFormElement} */
const element = event.target;
if (element instanceof HTMLFormElement && element.target === '') {
if (!event.defaultPrevented && element.action.indexOf(baseUrl) === 0) {
event.preventDefault();
changePageByUrl(element.action);
}
}
});
});
})();