-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathweld.js
More file actions
510 lines (438 loc) · 14.7 KB
/
weld.js
File metadata and controls
510 lines (438 loc) · 14.7 KB
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
;(function(exports) {
// shim out Object.keys
// ES5 15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if (typeof object !== "object" &&
typeof object !== "function" ||
object === null)
{
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (object.hasOwnProperty(name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (object.hasOwnProperty(dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
/* Let us play nice with IE
* https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
/* // Start: DEBUGGING
// ----------------
/* Since weld runs browser/server, ensure there is a console implementation.
*/
var logger = (typeof console === 'undefined') ? { log : function(){} } : console;
var nodejs = false;
if (typeof process !== 'undefined' && process.title) {
nodejs = true;
}
var color = {
gray: '\033[37m',
darkgray: '\033[40;30m',
red: '\033[31m',
green: '\033[32m',
yellow: '\033[33m',
lightblue: '\033[1;34m',
cyan: '\033[36m',
white: '\033[1;37m'
};
var inputRegex = /input|select|option|button/i;
var imageRegex = /img/i;
var textareaRegex = /textarea/i;
var truthyRegex = /yes|true|1|ok/i;
var depth = 0; // The current depth of the traversal, used for debugging.
var successIndicator = nodejs ? (color.green + ' ?' + color.gray) : ' Success';
var failureIndicator = nodejs ? (color.red + ' ?' + color.gray) : ' Fail';
var debuggable = function debuggable(name, operation) {
var label = name.toUpperCase();
// All of the ops have the same signature, so this is sane.
return function(parent, element, key, value) {
logger.log(
pad(),
((nodejs ? (color.gray + '+ ') : '+ ') + label + ' -'),
'parent:', colorize(parent) + ',',
'element:', colorize(element) + ',',
'key:', colorize(key) + ',',
'value:', colorize(value)
);
depth+=1;
if (operation) {
var res = operation(parent, element, key, value);
depth-=1;
logger.log(pad(), (nodejs ? '+ ' : '+ ') + element + '' + (res !== false ? successIndicator : failureIndicator));
return res;
}
depth-=1;
d('- OPERATION NOT FOUND: ', label);
};
};
/* Generates padding used for indenting debugger statements.
*/
var pad = function pad() {
var l = depth, ret = '';
while(l--) {
ret += nodejs ? ' Ơ ' : ' | ';
}
return ret;
};
/* Debugger statement, terse, accepts any number of arguments
* that are passed to a logger.log statement.
*/
var d = function d() {
var args = Array.prototype.slice.call(arguments);
// This is done because on the browser you cannot call console.log.apply
logger.log(pad(), args.join(' '));
};
var colorize = function colorize(val) {
var sval = val+'', u='undefined';
if(nodejs) {
if(sval === 'false' || sval === 'null' || sval === '' || sval === u || typeof val === u || val === false) {
if(sval === '') { sval = '(empty string)' };
return color.red + sval + color.gray;
}
else {
return color.yellow + sval + color.gray;
}
}
return sval;
};
// End: DEBUGGING
// -------------- */
/* Weld!
* @param {HTMLElement} DOMTarget
* The target html node that will be used as the subject of data binding.
* @param {Object|Array} data
* The data that will be used.
* @param {Object} pconfig
* The configuration object.
*/
exports.weld = function weld(DOMTarget, data, pconfig) {
var parent = DOMTarget.parentNode;
var currentOpKey, p, fn, debug;
/*
* Configuration Object.
* @member {Object}
* Contains an explicit mapping of data-keys to element name/id/classes
* @member {Boolean}
* Determines if debugging will be enabled.
* @method {Boolean|Function}
* Determines the method of insertion, can be a functon or false.
*/
var config = {
alias : {},
debug : false,
insert: false // Default to append
};
// Merge the user configuration over the existing config
if(pconfig) {
for(p in pconfig) {
if (pconfig.hasOwnProperty(p)) {
config[p] = pconfig[p];
}
}
}
debug = config.debug;
/* An interface to the interal operations, implements common
* debugging output based on a standard set of parameters.
*
* @param {Function} operation
* The function to call in "debug mode"
*/
var ops = {
siblings : function siblings(parent, element, key, value) {
var remove = [],
sibling,
classes,
cc,
match,
siblings = parent.children;
cs = siblings.length; // Current Sibling
element.weld = {
parent : parent,
classes : element.className.split(' ')
};
// Find all siblings that match the exact classes that exist in the originally
// matched element node
while (cs--) {
sibling = siblings[cs];
if (sibling === element) {
// If this is not the last item in the list, store where new items should be inserted
if (cs < siblings.length) {
element.weld.insertBefore = siblings[cs+1];
}
// remove the element here because siblings is a live list.
// which means, if you remove it before hand, the length will mismatch and cause problems
if (debug) {
d('- REMOVE - element:', colorize(element), 'class:', colorize(element.className), 'id:', colorize(element.id));
}
parent.removeChild(element);
// Check for the same class
} else {
classes = sibling.className.split(' ');
cc = classes.length;
match = true;
while (cc--) {
// TODO: optimize
if (element.weld.classes.indexOf(classes[cc]) < 0) {
match = false;
break;
}
}
// This element matched, you win a prize! DIE.
if (match) {
if (debug) {
d('- REMOVE - element:', colorize(sibling), 'class:', colorize(sibling.className), 'id:', colorize(sibling.id));
}
parent.removeChild(sibling);
}
}
}
},
traverse : function traverse(parent, element, key, value, row) {
var type, target, i, keys, l, obj;
var template = element;
var templateParent = element.parentNode;
// LEAF
if(~({}).toString.call(value).indexOf('Date')) {
value = value.toString();
}
if (value.nodeType || typeof value !== 'object') {
ops.set(parent, element, key, value, row);
// ARRAY / NodeList
} else if (value.length && value[0]) {
if (templateParent) {
ops.siblings(templateParent, template, key, value);
} else if (template.weld && template.weld.parent) {
templateParent = template.weld.parent;
}
l = value.length;
for (i=0; i<l; i++) {
if (debug) {
d('- CLONE - element:', colorize(element), 'class:', colorize(element.className), 'id:', colorize(element.id));
}
target = element.cloneNode(true);
target.weld = {};
// Clone weld params
if (element.weld) {
var keys = Object.keys(element.weld), currentKey = keys.length, weldParam;
while(currentKey--) {
weldParam = keys[currentKey];
target.weld[weldParam] = element.weld[weldParam];
}
}
ops.traverse(templateParent, target, i, value[i], value[i]);
ops.insert(templateParent, target, i, value[i]);
}
// OBJECT
} else {
var keys = Object.keys(value), current = keys.length, obj;
while (current--) {
var lkey = keys[current];
obj = value[lkey];
target = ops.match(template, element, lkey, obj);
if (target) {
ops.traverse(template, target, lkey, obj, row);
// Handle the case where a parent data key doesn't
// match a dom node, but the child data object may.
// don't continue traversing if the child data object
// is not an array/object
} else if (target !== false &&
typeof obj === 'object' &&
Object.keys(obj).length > 0) // TODO: optimize
{
ops.traverse(templateParent, template, lkey, obj);
}
}
}
},
elementType : function elementType(parent, element, key, value) {
if (element) {
var nodeName = element.nodeName;
if (typeof nodeName === "string") {
if (inputRegex.test(nodeName)) {
return 'input';
}
if (imageRegex.test(nodeName)) {
return 'image';
}
if (textareaRegex.test(nodeName)) {
return 'textarea';
}
}
}
},
map : false, // this is a user-defined operation
insert : function(parent, element) {
// Insert the template back into document
if (element.weld && element.weld.insertBefore) {
parent.insertBefore(element, element.weld.insertBefore);
} else {
parent.appendChild(element);
}
},
set : function set(parent, element, key, value, row) {
if(ops.map && ops.map(parent, element, key, value, row) === false) {
return false;
}
if(debug) {
d('- SET: value is', value.tagName);
}
var type = ops.elementType(parent, element, key, value), res = false;
if (value && value.nodeType) { // imports.
if (element.ownerDocument !== value.ownerDocument) {
value = element.ownerDocument.importNode(value, true);
} else if (value.parentNode) {
value.parentNode.removeChild(value);
}
while (element.firstChild) { // clean first.
element.removeChild(element.firstChild);
}
element.appendChild(value);
res = true;
}
else if (type === 'input') { // special cases.
if (element.tagName.toLowerCase() === 'select') {
element.value = value;
} else if (element.type.toLowerCase() === 'checkbox') {
if (truthyRegex.test(value)) {
element.setAttribute('checked', true);
} else if (element.hasAttribute('checked')) {
element.removeAttribute('checked');
}
} else {
element.setAttribute('value', value);
}
res = true;
}
else if (type === 'image') {
element.setAttribute('src', value);
res = true;
}
else if (type === 'textarea') {
element.textContent = value;
if (element.value !== value) {
// Here's looking at you Opera.
element.value = value;
}
res = true;
}
else { // simple text assignment.
element.textContent = value;
res = true;
}
return res;
},
match : function match(parent, element, key, value) {
if(typeof config.alias[key] !== 'undefined') {
if(typeof config.alias[key] === 'function') {
key = config.alias[key](parent, element, key, value) || key;
}
else if(config.alias[key] === false) {
return false;
}
else {
key = config.alias[key];
}
}
// Alias can be a node, for explicit binding.
// Alias can also be a method that returns a string or DOMElement
if (key && key.nodeType) {
return key;
}
if(element) {
if(element.querySelector) {
return element.querySelector('.' + key + ',#' + key + ',[name="' + key + '"]');
}
else {
var els = element.getElementsByTagName('*'), l = els.length, e, i;
// find the _first_ best match
for (i=0; i<l; i++) {
e = els[i];
if(e.id === key || e.name === key || e.className.split(' ').indexOf(key) > -1) {
return e;
}
}
}
}
}
};
// Allow the caller to overwrite the internals of weld
for (currentOpKey in ops) {
if (ops.hasOwnProperty(currentOpKey)) {
currentOp = ops[currentOpKey];
fn = config[currentOpKey] || ops[currentOpKey];
if (debug) {
fn = debuggable(currentOpKey, fn);
}
ops[currentOpKey] = fn;
}
}
// Kick it off
ops.traverse(null, DOMTarget, null, data);
if (config.debug) {
logger.log(DOMTarget.outerHTML);
}
};
if (typeof exports.define !== "undefined" && exports.define.amd) {
define('weld',[], function() {return window.weld });
}
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' ? exports : window));