/
html.js
346 lines (296 loc) · 10.7 KB
/
html.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
import { NodesRange } from './range';
const templatesCache = {};
const NODE_TYPES = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
};
const ITERATIONS_THRESHOLD = 1000;
function same(nodeA, nodeB){
if(!nodeA || !nodeB){
return false;
}
if(nodeA.nodeType !== nodeB.nodeType){
return false;
}
if(nodeA.tagName && nodeB.tagName && nodeA.tagName === nodeB.tagName){
return true;
}
return nodeA.isEqualNode(nodeB);
};
function isSameTextNode(nodeA, nodeB){
if(nodeA.nodeType === NODE_TYPES.TEXT_NODE && nodeA.nodeType === NODE_TYPES.TEXT_NODE && nodeA.textContent === nodeB.textContent){
return true;
}
return false;
};
//hash function taken from https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
var hash = 5381,
i = str.length;
while(i) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}
return hash >>> 0;
};
function regExpEscape(literalString){
return literalString.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
};
function getChunkType(chunk){
if(chunk instanceof Node){
return 'element'
} else if(chunk instanceof Promise){
return 'futureResult'
} else if(chunk instanceof Template){
return 'template'
}
return 'text';
}
export const stopNode = `modulor_stop_node_${+(new Date())}`;
const DEFAULT_PREFIX = `{modulor_html_chunk_${+new Date()}:`;
const DEFAULT_POSTFIX = '}';
const DEFAULT_PARSER = new DOMParser();
export function Template(options){
this.PREFIX = options.PREFIX || DEFAULT_PREFIX;
this.POSTFIX = options.POSTFIX || DEFAULT_POSTFIX;
this.parser = options.parser || DEFAULT_PARSER;
this.replaceChunkRegex = new RegExp(this.getTokenRegExp(), 'ig');
this.matchChunkRegex = new RegExp(`^${this.getTokenRegExp(true)}$`);
return this;
};
Template.prototype.parse = function(...args){
[this.template, this.dataMap] = this.prepareLiterals(...args);
this.templateId = hash(this.template);
const cached = templatesCache[this.templateId];
if(typeof cached === 'undefined'){
this.container = this.generateContainer(this.template);
templatesCache[this.templateId] = this.container;
} else {
this.container = cached;
}
return this;
}
Template.prototype.processTextNodeChunks = function(chunks, dataMap = this.dataMap){
return chunks.reduce((acc, chunk) => {
if(!`${chunk}`.length){
return acc;
}
const match = chunk.match(this.matchChunkRegex);
const value = match ? dataMap[chunk] : chunk;
if(typeof value === 'undefined'){ return acc; }
const chunkType = getChunkType(value);
if(chunkType !== 'text'){
const $el = document.createComment(``);
$el.isSpecialChunk = true;
$el[chunkType] = value;
$el.chunkType = chunkType;
$el.templateId = this.templateId;
$el.chunkId = match[2];
return acc.concat($el);
}
return acc.concat(value);
}, []);
};
Template.prototype.copyTextNodeChunks = function(chunks, dataMap = this.dataMap, container = document.createDocumentFragment()){
return [].concat(chunks).reduce((container, chunk) => {
if(chunk.isSpecialChunk){
container.appendChild(chunk);
return container;
}
const chunkType = getChunkType(chunk);
if(chunkType === 'text'){
container.appendChild(document.createTextNode(chunk));
} else {
const $el = document.createComment(``);
$el[chunkType] = chunk;
$el.isSpecialChunk = true;
$el.chunkType = chunkType;
$el.templateId = this.templateId;
container.appendChild($el);
}
return container;
}, container);
};
//@TODO support promise in attributes
Template.prototype.copyAttributes = function(target, source, dataMap = this.dataMap){
const newAttrs = [];
const attrs = source.attributes;
if(!attrs.length){ return; }
for(let i = 0; i < attrs.length; i++){
const { name, value } = attrs[i];
const preparedName = this.replaceTokens(name);
const preparedValue = this.matchChunkRegex.test(value) ? dataMap[value] : this.replaceTokens(value);
if(preparedName === ''){ return; }
if(preparedName === stopNode){
target.nodeStopper = stopNode;
return;
}
newAttrs.push(preparedName);
if(value !== '' && preparedName in target){
target[preparedName] = preparedValue;
continue;
}
target.setAttribute(preparedName, preparedValue);
}
//@TODO refactor here
const targetAttrs = target.attributes;
for(let j = 0; j < targetAttrs.length; j++){
const attrName = targetAttrs[j].name;
if(!~newAttrs.indexOf(attrName)){
target.removeAttribute(attrName);
}
}
};
Template.prototype.loop = function($source, $target, debug){
for(let i = 0, offset = 0;; i++){
if(i > ITERATIONS_THRESHOLD){
console.log('too much recursion');
break;
}
const $sourceElement = $source.childNodes[i];
const $targetElement = $target.childNodes[i + offset]; //probably offset is not needed
//no further elements, end of loop
if(!$sourceElement && !$targetElement){
break;
}
//element doesn't exist anymore
if(!$sourceElement){
$target.removeChild($targetElement);
i--;
continue;
}
if(!$targetElement || !same($sourceElement, $targetElement)){
//@TODO strange behaviour here, have to make it a closure
const fn = ($target, $targetElement) => ($el) => {
if(!$targetElement){
//element should be newly created
return $target.appendChild($el);
}
//replace old node with new one
return $target.replaceChild($el, $targetElement);
};
const domFn = fn($target, $targetElement);
const getRange = ($targetElement, replacementType) => {
if($targetElement && $targetElement.range && $targetElement.replacementType === replacementType && $targetElement.templateId === this.templateId){
return $targetElement.range;
} else {
const range = new NodesRange(document.createTextNode(''), document.createTextNode(''));
const { startNode } = range;
startNode.range = range;
startNode.replacementType = replacementType;
startNode.templateId = this.templateId;
domFn(range.extractContents());
return range;
}
}
switch($sourceElement.nodeType){
case NODE_TYPES.TEXT_NODE:
const content = $sourceElement.textContent;
const chunks = content.split(this.replaceChunkRegex);
if(chunks.length === 1){
domFn(document.createTextNode($sourceElement.textContent));
break;
}
let range = getRange($targetElement, 'textContent');
const processedChunks = this.processTextNodeChunks(chunks);
const $processedChunksFragment = this.copyTextNodeChunks(processedChunks);
this.loop($processedChunksFragment, range);
offset += range.childNodes.length + 1;
break;
case NODE_TYPES.COMMENT_NODE:
if($sourceElement.isSpecialChunk){
const type = $sourceElement.chunkType;
const range = getRange($targetElement, type);
if(type === 'futureResult'){
$sourceElement.futureResult.then((response) => {
const $frag = this.copyTextNodeChunks(response);
this.loop($frag, range);
//update range for future promise resolves
//@TODO write better explanation
range.update();
return $frag;
});
offset += range.childNodes.length + 1;
break;
}
if(type === 'template'){
$sourceElement.template.render(range);
offset += range.childNodes.length + 1;
break;
}
if(type === 'element'){
const $frag = document.createDocumentFragment();
$frag.appendChild($sourceElement.element);
//@TODO probably better to simply replace elements in range with ones from $frag
this.loop($frag, range);
offset += range.childNodes.length + 1;
break;
}
}
domFn(document.createComment(this.replaceTokens($sourceElement.textContent)));
break;
case NODE_TYPES.ELEMENT_NODE:
const newChild = document.createElement($sourceElement.tagName.toLowerCase());
this.loop($sourceElement, newChild);
domFn(newChild);
//set attributes after whole subtree has build,
//because node content might be needed before setter being executed
this.copyAttributes(newChild, $sourceElement);
break;
}
continue;
}
//at this point we are sure both elements exist
//same text
if(isSameTextNode($sourceElement, $targetElement)){
continue;
}
//same node
if(same($sourceElement, $targetElement)){
($targetElement.nodeStopper !== stopNode) && this.loop($sourceElement, $targetElement);
this.copyAttributes($targetElement, $sourceElement);
continue;
}
}
return $target;
};
Template.prototype.render = function(target = document.createDocumentFragment()){
target.nodeStopper = stopNode;
return this.loop(this.container, target);
};
Template.prototype.generateContainer = function(markup){
return this.parser.parseFromString(markup, "text/html").body;
};
Template.prototype.prepareLiterals = function([firstChunk, ...restChunks], ...interpolations){
return restChunks.reduce(([acc, dataMap], chunk, index) => {
const keyName = this.generateTokenName(index);
dataMap[keyName] = interpolations[index];
return [acc.concat(keyName).concat(chunk), dataMap];
}, [firstChunk, {}]);
};
Template.prototype.generateTokenName = function(index){
return `${this.PREFIX}${index}${this.POSTFIX}`;
};
Template.prototype.replaceTokens = function(text, dataMap = this.dataMap){
return text.replace(this.replaceChunkRegex, (token, index) => {
return dataMap[token];
});
};
Template.prototype.getTokenRegExp = function(groupMatches){
const indexRegex = `${groupMatches ? '(' : ''}\\d+${groupMatches ? ')' : ''}`;
return `(${regExpEscape(this.PREFIX)}${indexRegex}${regExpEscape(this.POSTFIX)})`;
};
export const html = (...args) => (new Template({})).parse(...args);
export const render = (template, target) => template.render(target);
export const r = (...args) => render(html(...args));
//@TODO think about collecting new nodes to append into fragment and appending the whole fragment later
//@TODO maybe converting special nodes to comment and then replacing it is not good idea?