-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathrender.js
377 lines (338 loc) · 8.41 KB
/
render.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
let xslt = {
/**
* @param {string} xsl
*/
init: function(xsl)
{
xslt.proc = new XSLTProcessor;
xslt.proc['importStylesheet'](xslt.loadXML(xsl));
},
/**
* @param {string} xml
* @return {!Document}
*/
loadXML: function(xml)
{
const dom = (new DOMParser).parseFromString(xml, 'text/xml');
if (!dom)
{
throw 'Cannot parse ' + xml;
}
return dom;
},
/**
* @param {string} paramName Parameter name
* @param {string} paramValue Parameter's value
*/
setParameter: function(paramName, paramValue)
{
xslt.proc['setParameter'](null, paramName, paramValue);
},
/**
* @param {string} xml
* @param {!Document} targetDoc
* @return {!DocumentFragment}
*/
transformToFragment: function(xml, targetDoc)
{
return xslt.proc['transformToFragment'](xslt.loadXML(xml), targetDoc);
}
};
xslt.init(xsl);
/**
* Parse a given text and render it into given HTML element
*
* @param {string} text
* @param {!HTMLElement} target
* @return {!Node}
*/
function preview(text, target)
{
let targetDoc = target.ownerDocument;
if (!targetDoc)
{
throw 'Target does not have a ownerDocument';
}
let resultFragment = xslt.transformToFragment(parse(text).replace(/<[eis]>[^<]*<\/[eis]>/g, ''), targetDoc),
lastUpdated = target;
// https://bugs.chromium.org/p/chromium/issues/detail?id=266305
if (typeof window !== 'undefined' && 'chrome' in window)
{
resultFragment.querySelectorAll('script').forEach(
function (oldScript)
{
let newScript = document.createElement('script');
for (let attribute of oldScript['attributes'])
{
newScript['setAttribute'](attribute.name, attribute.value);
}
newScript.textContent = oldScript.textContent;
oldScript.parentNode.replaceChild(newScript, oldScript);
}
);
}
// Compute and refresh hashes
if (HINT.hash)
{
computeHashes(resultFragment);
}
// Apply post-processing
if (HINT.onRender)
{
executeEvents(resultFragment, 'render');
}
/**
* Compute and set all hashes in given document fragment
*
* @param {!DocumentFragment} fragment
*/
function computeHashes(fragment)
{
let nodes = fragment.querySelectorAll('[data-s9e-livepreview-hash]'),
i = nodes.length;
while (--i >= 0)
{
nodes[i]['setAttribute']('data-s9e-livepreview-hash', hash(nodes[i].outerHTML));
}
}
/**
* Execute an event's code on a given node
*
* @param {!Element} node
* @param {string} eventName
*/
function executeEvent(node, eventName)
{
let code = node.getAttribute('data-s9e-livepreview-on' + eventName),
codeHash = hash(code);
if (!functionCache[codeHash])
{
functionCache[codeHash] = new Function(code);
}
functionCache[codeHash]['call'](node);
}
/**
* Locate and execute an event on given document fragment or element
*
* @param {!DocumentFragment|!Element} root
* @param {string} eventName
*/
function executeEvents(root, eventName)
{
// Execute the event on the root node, as there is no self-or-descendant selector in CSS
if (root instanceof Element && root['hasAttribute']('data-s9e-livepreview-on' + eventName))
{
executeEvent(root, eventName);
}
let nodes = root.querySelectorAll('[data-s9e-livepreview-on' + eventName + ']'),
i = nodes.length;
while (--i >= 0)
{
executeEvent(nodes[i], eventName);
}
}
/**
* Update the content of given node oldParent to match node newParent
*
* @param {!Node} oldParent
* @param {!Node} newParent
*/
function refreshElementContent(oldParent, newParent)
{
let oldNodes = oldParent.childNodes,
newNodes = newParent.childNodes,
oldCnt = oldNodes.length,
newCnt = newNodes.length,
oldNode,
newNode,
left = 0,
right = 0;
// Skip the leftmost matching nodes
while (left < oldCnt && left < newCnt)
{
oldNode = oldNodes[left];
newNode = newNodes[left];
if (!refreshNode(oldNode, newNode))
{
break;
}
++left;
}
// Skip the rightmost matching nodes
let maxRight = Math.min(oldCnt - left, newCnt - left);
while (right < maxRight)
{
oldNode = oldNodes[oldCnt - (right + 1)];
newNode = newNodes[newCnt - (right + 1)];
if (!refreshNode(oldNode, newNode))
{
break;
}
++right;
}
// Remove the old dirty nodes in the middle of the tree
let i = oldCnt - right;
while (--i >= left)
{
oldParent.removeChild(oldNodes[i]);
lastUpdated = oldParent;
}
// Test whether there are any nodes in the new tree between the matching nodes at the left
// and the matching nodes at the right
let rightBoundary = newCnt - right;
if (left >= rightBoundary)
{
return;
}
// Clone the new nodes
let newNodesFragment = targetDoc.createDocumentFragment();
i = left;
do
{
newNode = newNodes[i];
if (HINT.onUpdate && newNode instanceof Element)
{
executeEvents(newNode, 'update');
}
lastUpdated = newNodesFragment.appendChild(newNode);
}
while (i < --rightBoundary);
// If we haven't skipped any nodes to the right, we can just append the fragment
if (!right)
{
oldParent.appendChild(newNodesFragment);
}
else
{
oldParent.insertBefore(newNodesFragment, oldParent.childNodes[left]);
}
}
/**
* Update given node oldNode to make it match newNode
*
* @param {!Node} oldNode
* @param {!Node} newNode
* @return {boolean} Whether the node can be skipped
*/
function refreshNode(oldNode, newNode)
{
if (oldNode.nodeName !== newNode.nodeName || oldNode.nodeType !== newNode.nodeType)
{
return false;
}
if (oldNode instanceof HTMLElement && newNode instanceof HTMLElement)
{
if (!oldNode.isEqualNode(newNode) && !elementHashesMatch(oldNode, newNode))
{
if (HINT.onUpdate && newNode['hasAttribute']('data-s9e-livepreview-onupdate'))
{
executeEvent(newNode, 'update');
}
syncElementAttributes(oldNode, newNode);
refreshElementContent(oldNode, newNode);
}
}
// Node.TEXT_NODE || Node.COMMENT_NODE
else if (oldNode.nodeType === 3 || oldNode.nodeType === 8)
{
if (oldNode.nodeValue !== newNode.nodeValue)
{
oldNode.nodeValue = newNode.nodeValue;
lastUpdated = oldNode;
}
}
return true;
}
/**
* Test whether both given elements have a hash value and both match
*
* @param {!HTMLElement} oldEl
* @param {!HTMLElement} newEl
* @return {boolean}
*/
function elementHashesMatch(oldEl, newEl)
{
if (!HINT.hash)
{
// Hashes can never match if there are no hashes in any template
return false;
}
const attrName = 'data-s9e-livepreview-hash';
return oldEl['hasAttribute'](attrName) && newEl['hasAttribute'](attrName) && oldEl['getAttribute'](attrName) === newEl['getAttribute'](attrName);
}
/**
* Hash given string
*
* @param {string} text
* @return {number}
*/
function hash(text)
{
let pos = text.length, s1 = 0, s2 = 0;
while (--pos >= 0)
{
s1 = (s1 + text.charCodeAt(pos)) % 0xFFFF;
s2 = (s1 + s2) % 0xFFFF;
}
return (s2 << 16) | s1;
}
/**
* Make the set of attributes of given element oldEl match newEl's
*
* @param {!HTMLElement} oldEl
* @param {!HTMLElement} newEl
*/
function syncElementAttributes(oldEl, newEl)
{
let oldAttributes = oldEl['attributes'],
newAttributes = newEl['attributes'],
oldCnt = oldAttributes.length,
newCnt = newAttributes.length,
i = oldCnt,
ignoreAttrs = ' ' + oldEl.getAttribute('data-s9e-livepreview-ignore-attrs') + ' ';
while (--i >= 0)
{
let oldAttr = oldAttributes[i],
namespaceURI = oldAttr['namespaceURI'],
attrName = oldAttr['name'];
if (HINT.ignoreAttrs && ignoreAttrs.indexOf(' ' + attrName + ' ') > -1)
{
continue;
}
if (!newEl.hasAttributeNS(namespaceURI, attrName))
{
oldEl.removeAttributeNS(namespaceURI, attrName);
lastUpdated = oldEl;
}
}
i = newCnt;
while (--i >= 0)
{
let newAttr = newAttributes[i],
namespaceURI = newAttr['namespaceURI'],
attrName = newAttr['name'],
attrValue = newAttr['value'];
if (HINT.ignoreAttrs && ignoreAttrs.indexOf(' ' + attrName + ' ') > -1)
{
continue;
}
if (attrValue !== oldEl.getAttributeNS(namespaceURI, attrName))
{
oldEl.setAttributeNS(namespaceURI, attrName, attrValue);
lastUpdated = oldEl;
}
}
}
refreshElementContent(target, resultFragment);
return lastUpdated;
}
/**
* Set the value of a stylesheet parameter
*
* @param {string} paramName Parameter name
* @param {string} paramValue Parameter's value
*/
function setParameter(paramName, paramValue)
{
xslt.setParameter(paramName, paramValue);
}