-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhaiku.js
executable file
·525 lines (446 loc) · 19.6 KB
/
haiku.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//
// Haiku.js: lightweight DOM node creation using Zen Coding syntax
// (see http://code.google.com/p/zen-coding/)
//
// author: Rylee Corradini
// last update: 10 July 2016
// license: MIT
//
/*
Example, from the Zen Coding homepage:
var dom_fragment = haiku.expand("div#page>div.logo+ul#navigation>li*5>a");
dom_fragment.toString():
<div id="page">
<div class="logo"></div>
<ul id="navigation">
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</div>
*/
/*jshint browser: true, quotmark:false, laxcomma:true */
/*global define,console */
define([],
function() {
"use strict";
// PRIVATE CLOSURE GLOBALS
var _tagRex = /^[a-z]+[1-6]?/i,
_posRex = /[><\+]/g,
_idRex = /#[_a-z]+[_a-z0-9-]*/i,
_classRex = /\.-?[_a-z]+[_a-z0-9-]*/gi,
_textRex = /{[^}]+}/,
_attrsRex = /\[[^\]]*\]/;
var _templateMap = {};
var _conditionalsMaps = {};
// HELPER FUNCTIONS
function _supplant(str, args, defaultVal) {
// adapted from Douglas Crockford's Remedial JavaScript
if ((str.indexOf("%self") > -1) && args) {
// special case: if the expression includes the special string "%self",
// it should be replaced by the entire (stringified) value of 'args'
str = str.replace(/%self/g, args.toString());
}
return str.replace(/\$([^$]*);/g,
function (a, b) {
var r = args[b];
if (_isNullOrUndef(r)) r = defaultVal;
var rtype = typeof r;
return rtype === "string" || rtype === "number" ? r : "("+rtype+")";
}
);
}
/** Mixes attributes from one object into another.
* Useful for overriding function defaults with an arguments property bag
*
* @param intoObj: target object to receive the new stuff
* @param fromObj: source object to provide the new stuff
* @return: the modified object
*/
function _mixin(intoObj, fromObj) {
for (var k in fromObj) {
if (fromObj.hasOwnProperty(k)) {
if (fromObj[k] !== undefined) intoObj[k] = fromObj[k];
}
}
return intoObj;
}
function toArray(arraylike) {
return arraylike && [].slice.call(arraylike);
}
function _each(arraylike, fn) {
if (arraylike && fn) [].forEach.call(arraylike, fn);
}
function _filter(arraylike, fn) {
return (arraylike && fn) ? [].filter.call(arraylike, fn) : null;
}
function _map(arraylike, fn) {
return (arraylike && fn) ? [].map.call(arraylike, fn) : null;
}
/**
* Return an array with those elements present in
* input array, but not in blacklist array
* @param {Array} array [collection of values to filter]
* @param {Array} blacklist [array of values to exclude]
* @return {Array} [a smaller array, elements from input not in blacklist]
*/
function _arrayDiff(input, blacklist) {
var A = (Array.isArray(input) ? input : toArray(input));
var B = (Array.isArray(blacklist) ? blacklist : toArray(blacklist));
return A.filter(function(value){
return B.indexOf(value) == -1;
});
}
function _setNodeValue(node, value) {
if (!node) return new Error("setNodeValue :: No node specified.");
switch (node.tagName) {
case "INPUT":
case "TEXTAREA":
case "SELECT":
if (node.type === "checkbox" || node.type === "radio") {
node.checked = value;
} else {
node.value = value;
}
break;
default:
node.textContent = value;
break;
}
}
function _escapeControlChars(str) {
var working = str.replace(/\+/gi, "__PLUS__");
working = working.replace(/\{/gi, "__OPENBRACE__");
working = working.replace(/\}/gi, "__CLOSEBRACE__");
return working.replace(/\]/gi, "__CLOSEBRACKET__");
}
function _unescapeControlChars(str) {
var working = str.replace(/__PLUS__/gi, "+");
working = working.replace(/__OPENBRACE__/gi, "{");
working = working.replace(/__CLOSEBRACE__/gi, "}");
return working.replace(/__CLOSEBRACKET__/gi, "]");
}
function _isNullOrUndef(o) {
return (o===null || o===undefined);
}
function _sanitizeData(obj, depthLimit) {
var sanitized = null;
if (_isNullOrUndef(obj)) return null;
if (obj.__SANITIZED) return obj;
if (Array.isArray(obj)) {
sanitized = [];
for (var i=0; i<obj.length; i++) {
sanitized[i] = _sanitizeData(obj[i], depthLimit);
}
} else {
switch (typeof obj) {
case "string":
sanitized = _escapeControlChars(_stripHtml(obj));
break;
case "object":
sanitized = {
__SANITIZED: true
};
if (depthLimit > 0) {
Object.keys(obj).forEach(function sanitizeKeyVal(key){
sanitized[key] = _sanitizeData(obj[key], depthLimit-1);
});
} else {
sanitized.__NORECURSE = true;
}
break;
default:
// any other data types can stay as they are
sanitized = obj;
break;
}
}
return sanitized;
}
// code for stripping all HTML tags from an input string
// taken from http://stackoverflow.com/a/430240/7542
var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
var tagOrComment = new RegExp(
'<(?:' +
// Comment body.
'!--(?:(?:-*[^->])*--+|-?)' +
// Special "raw text" elements whose content should be elided.
'|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' +
'|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' +
// Regular name
'|/?[a-z]' +
tagBody +
')>',
'gi');
function _stripHtml(html) {
var oldHtml;
do {
oldHtml = html;
html = html.replace(tagOrComment, '');
} while (html !== oldHtml);
return html.replace(/</g, '<');
}
// end of html tag stripper
function _expandValueString(valueStr, data) {
if (!valueStr || !data) return null;
var tmpl = "span{" + valueStr.replace(/%/g, "$") + "}";
var span = _createElement( tmpl, data );
return span ? span.textContent : null;
}
function _buildElement(spec) {
var tag = _tagRex.exec(spec),
i, matches, specFragment, val,
el = tag ? document.createElement(tag[0]) : null;
if (el) {
// add element text node(s)
if (_textRex.test(spec)) {
matches = _textRex.exec(spec);
specFragment = _unescapeControlChars(matches[0].slice(1, -1));
el.appendChild(document.createTextNode(specFragment));
}
// add element attributes
if (_attrsRex.test(spec)) {
// only one; if there are multiples, they're ignored
matches = _attrsRex.exec(spec);
specFragment = _unescapeControlChars(matches[0].slice(1, -1));
// strip out the attrs clause from the spec so its contents don't get mistaken for a class or id
spec = spec.slice(0,matches.index) + spec.slice(matches.index+matches[0].length);
matches = specFragment.split(',');
for (i=0; i<matches.length; i++) {
val = matches[i].split('=');
if (val.length == 2) {
el.setAttribute(val[0], val[1]);
} else if (val.length > 2) {
el.setAttribute(val[0], val.slice(1).join('='));
}
}
}
// add element id
if (_idRex.test(spec)) {
matches = _idRex.exec(spec);
el.id = matches[0].slice(1);
}
// add element class(es)
matches = _classRex.exec(spec);
while (matches && matches.length) {
for (i=0; i< matches.length; i++) {
el.classList.add(matches[i].slice(1));
}
matches = _classRex.exec(spec);
}
// TBD: check for element multipliers (e.g. ul>li*5)
} else {
// no tag; maybe it's a bare text node?
if (_textRex.test(spec)) {
matches = _textRex.exec(spec);
specFragment = _unescapeControlChars(matches[0].slice(1, -1));
el = document.createTextNode(specFragment);
}
}
return el;
}
// EXTERNAL FUNCTIONS (TO EXPOSE VIA THE API)
function _expand(expression, dataObj, serialize) {
var _frag = (serialize) ? document.createElement('div') : document.createDocumentFragment(),
_cur = _frag,
child = null,
exp_with_values = _supplant( expression, _sanitizeData(dataObj, 1), ""),
i, posCode, tags = exp_with_values.split(_posRex);
for (i=0; i<tags.length; i++) {
child = _buildElement(tags[i].trim());
if (child) {
_cur.appendChild(child);
}
posCode = _posRex.exec(exp_with_values);
if (posCode && posCode.length) {
switch (posCode[0]) {
case '<':
// jump back up to the previous insertion level
_cur = _cur.parentNode;
break;
case '>':
// insert next element into this new child
_cur = child;
break;
case '+':
// no change in insert level
break;
default:
// unrecognized insert level operation
console.warn('unrecognized position delimiter:', posCode);
}
}
}
return (serialize) ? _frag.innerHTML : _frag;
}
function _createElement(expression, dataObj) {
var expanded = _expand(expression, dataObj);
_bindToRecord(expanded, dataObj);
return (expanded && expanded.childNodes.length) ? expanded.childNodes[0] : null;
}
function _addTemplate(templateId, body) {
if (!templateId || !body) return;
if (_templateMap.hasOwnProperty(templateId)) {
throw new Error("Template '" + templateId + "' already exists.");
}
else {
_templateMap[templateId] = body;
}
}
function _lookupTemplate(templateId) {
var tmpl = _templateMap[templateId];
if (!tmpl) console.warn("Haiku: Cannot find named template '" + templateId + "'");
return tmpl || null;
}
function _lookupTemplateByMap(mapId, record) {
var map = _conditionalsMaps[mapId];
var checkValue;
if (!map || !record) return null;
if (record && map.fieldName) checkValue = record[map.fieldName];
if (checkValue.toString() && map.valueMap.hasOwnProperty(checkValue)) {
return _lookupTemplate(map.valueMap[checkValue]);
}
return _lookupTemplate(map.defaultTemplate) || null;
}
function _evaluateTemplateContext(contextString) {
// context e.g. "id:123|groupId:456"
var contextDict = {};
if (contextString) contextString.split("|").forEach(function(argPair) {
var keyval = argPair.split(":");
contextDict[keyval[0]] = keyval[1];
});
return contextDict;
}
function _getBindingContext(containerContext, childObject) {
var compositeContext = null;
if (!containerContext) return childObject;
if (childObject) {
if (typeof childObject == "object") {
compositeContext = _mixin((containerContext || {}), childObject);
} else {
compositeContext = childObject;
}
}
return compositeContext;
}
function _bindChildNodes(nd, record) {
var fieldName = nd.getAttribute("data-children-binding");
var i, tmpl, value, fragment, containerContext, bindingContext;
if (nd.hasAttribute("data-template-context")) {
containerContext = _evaluateTemplateContext(nd.getAttribute("data-template-context"), record);
}
nd.innerHTML = "";
if (nd.hasAttribute("data-children-prelude")) {
tmpl = _lookupTemplate(nd.getAttribute("data-children-prelude"));
if (tmpl) {
bindingContext = _getBindingContext(containerContext, record);
fragment = _createElement(tmpl, bindingContext);
nd.appendChild( fragment );
}
}
if (fieldName && record.hasOwnProperty(fieldName)) {
value = record[fieldName];
if (value && value.length !== undefined) {
if (nd.hasAttribute("data-template")) {
tmpl = _lookupTemplate(nd.getAttribute("data-template"));
if (tmpl) {
for (i=0; i<value.length; i++) {
bindingContext = _getBindingContext(containerContext, value[i]);
fragment = _createElement(tmpl, bindingContext);
nd.appendChild( fragment );
}
}
} else if (nd.hasAttribute("data-template-map")) {
var tmplMap = nd.getAttribute("data-template-map");
for (i=0; i<value.length; i++) {
bindingContext = _getBindingContext(containerContext, value[i]);
tmpl = _lookupTemplateByMap(tmplMap, bindingContext);
if (tmpl) {
fragment = _createElement(tmpl, bindingContext);
nd.appendChild( fragment );
}
}
}
}
} else {
// console.warn("Data children binding: '" + fieldName + "' not found.");
}
if (nd.hasAttribute("data-children-footer")) {
tmpl = _lookupTemplate(nd.getAttribute("data-children-footer"));
if (tmpl) {
bindingContext = _getBindingContext(containerContext, record);
fragment = _createElement(tmpl, bindingContext);
nd.appendChild( fragment );
}
}
}
function _bindField(nd, record) {
var fieldName = nd.getAttribute("data-binding");
var value, valueStr;
if (fieldName === "%self") {
if (nd.hasAttribute("data-value-string")) {
valueStr = nd.getAttribute("data-value-string");
_setNodeValue(nd, _expandValueString(valueStr, record));
} else if (typeof record !== "object") {
_setNodeValue(nd, record);
}
} else {
if (fieldName && record.hasOwnProperty(fieldName)) {
value = record[fieldName];
if (value !== undefined) {
_setNodeValue(nd, value);
}
} else {
// console.warn("Data binding: '" + fieldName + "' ");
}
}
return nd;
}
function _bindToRecord(view, record) {
var bindings;
if (!view || !record) return;
// mark every bound element as "pending" (so things only get touched once)
bindings = view.querySelectorAll("[data-binding]");
_each(bindings, _markPending);
// data-children-binding (templatized child nodes, bound to an array)
bindings = view.querySelectorAll("[data-children-binding]");
_each(bindings, function(nd) { _bindChildNodes(nd, record); });
// data-binding (single node values; non-subordinate only)
bindings = view.querySelectorAll("[data-binding]");
_each(
_map(
_filter(bindings, _onlyPending)
, function(nd) { return _bindField(nd, record); }
)
, _clearPending
);
}
function _markPending(node) {
if (node && node.setAttribute) node.setAttribute("data-binding-pending", true);
return node;
}
function _clearPending(node) {
if (node && node.removeAttribute) node.removeAttribute("data-binding-pending");
return node;
}
function _onlyPending(node) {
return (node && node.getAttribute) ? node.getAttribute("data-binding-pending") : false;
}
function _addConditionalsMap(name, map) {
if (!_conditionalsMaps.hasOwnProperty(name)) {
_conditionalsMaps[name] = map;
}
}
// return available generator functions
return {
expand : _expand
, create : _createElement
, bind : _bindToRecord
, addTemplate : _addTemplate
, getTemplate : _lookupTemplate
, addConditionalsMap: _addConditionalsMap
};
}
);