-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCombover.js
More file actions
662 lines (505 loc) · 14.8 KB
/
Combover.js
File metadata and controls
662 lines (505 loc) · 14.8 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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
var Combover = {};
/**
* Initialize Combover
*
*/
(function(exports) {
/*
* Stores helper callbacks
* @property-private
*/
var helpers = [];
/*
* Stores helper callbacks
* @property-private
*/
var renders = [];
/**
* Whether to display debug statements
*/
exports.debug = false;
/**
* Array of all templates
*/
exports.templates = [];
/**
*
* @param name
*/
exports.addHelper = function(name, fn) {
helpers[name] = fn;
}
/**
*
* @param name
*/
exports.addRenderer = function(name, fn) {
renders[name] = fn;
}
/**
* Formats a number
* @param
* @link {http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript}
*/
function formatNumber(n, c, d, t){
var c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
/**
* Debug method. Send as many args you want into debug to print them out
*
*/
function debug() {
if ( console && exports.debug )
console.log.apply(console, arguments);
}
/**
* Gets a variables type
* Array, Object, String, etc
*
* @param
*
* @return String the object type
*/
function getType(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
/**
*
*/
function hasAttribute(source, name) {
var attr = source.attr(name);
return typeof attr !== 'undefined' && attr !== false;
}
/**
* Determines if a variable is primitive
*
* @param data Mixed
*
* @return Boolean
*/
function isPrimitive(data) {
var type = typeof(data);
switch ( typeof data ) {
case 'boolean':
case 'number':
case 'string':
case 'undefined':
case null:
return true;
}
return false;
}
/**
* Just like Array.map but provides the current index
*
* @param arr Array
* @param callback Function
*/
function map(arr, callback) {
switch (typeof arr) {
case 'string':
for ( var i=0; i<arr.length; i++ ) {
if ( callback.call(this, arr[i], i) === false )
return false;
}
}
return true;
}
/**
* Gets the outerHtml for a JQuery object
*
* @param source JQuery
*
* @return String
*/
function oHtml(source) {
return source.get(0).outerHTML;
}
/**
* Parses the combs in the "comb" HTML attribute and
* returns an array of Combs which houses the member,
* attribute, renders & helpers
*
* @param txt String
*
* @return Array of combs
*/
function parseCombs(txt) {
debug('*** Being parseCombs: ' + txt );
var matches, combs = [];
if ( txt )
txt.split(/\s+/).map(function(item) {
var comb = item.split('@');
comb = {
escape: true,
member: comb[0],
attribute: comb[1],
renders: [],
helpers: []
}
if (! comb.attribute )
combs['TargetingInnerHtml'] = true;
// Shorthands - Remove & Parse them
//-----------------------------------------
var modifiers = comb.member.match(/^\W*/);
map(modifiers[0], function(char) {
if ( char == '<' )
comb.escape = false;
else if ( renders[char] )
comb.renders.push( renders[char] )
else if ( helpers[char] )
comb.helpers.push( helpers[char] );
});
comb.member = comb.member.replace(/^\W*/, '') ;
combs.push(comb);
});
debug('---- End parseCombs: ', combs);
return combs;
}
/**
*
*/
function hideComb(data, comb, is_direct) {
var render = false;
data = is_direct ? data : data[comb.member];
comb.renders.map(function(fn) {
if (! fn.call(this, data, comb.member) )
render = true;
})
return render;
}
/**
* Encodes text to HTML
*
* @param
*
* @return String the encode HTML
*/
function htmlEncode(value) {
var el = document.createElement("div");
el.innerText = el.textContent = value;
return el.innerHTML;
}
/**
*
*/
function toHtml(data, comb, html) {
var val = data;
// Apply Renders & Format Data
//---------------------------------------
if ( val == undefined )
val = '';
comb.helpers.map(function(fn) {
val = fn.call(this, val);
});
if ( comb.escape )
val = htmlEncode(val);
// Get Text to replace
//------------------------------
var text = comb.attribute
? html.attr( comb.attribute )
: html.html();
// Replace empty text and text with no expression with a simple expression
// ex: comb="id@value" value="impression" we will replace 'impression' with id
if ( text == undefined || text.indexOf('{.}') == -1 )
text = '{.}';
var source = html.clone();
var val = text.replace('{.}', val);
if ( comb.attribute )
if ( comb.attribute == 'checked' || comb.attribute == 'disabled' ) {
if ( data )
source.attr(comb.attribute, val);
} else
source.attr(comb.attribute, val);
else
source.html(val);
return oHtml( source );
}
/**
*
* @param source string Either JQuery ID Selector or direct HTML
*
* @note If sending direct HTML it CANNOT start with '#'
*/
exports.compile = function(source) {
// Initialize the source
if ( typeof source == "string" ) {
var temp = $(source);
source = temp.length == 1
? temp
: $('<div>' + source + '</div>');
}
// Set up the source
// We use the outer template tag as a excluded behavior tag
source = source.clone();
source.attr('comb', 'root');
source.attr('comb-exclude', '');
debug('*** Compiling: ' + source.html());
var template3 = new template(source);
var container = {
object: template3,
renderer: template3.render.bind(template3),
};
exports.templates.push( container );
debug('*** End Compile\n\n\n');
return container.renderer;
}
/**
*
*/
function template(source, inherit) {
// Members
//-------------------------------------
this.attr = null;
this.holder = null;
this.children = [];
this.isNested = source.children().length > 0;
this.combs = parseCombs( source.attr('comb') );
this.exclude = hasAttribute(source, 'comb-exclude');
this.container = hasAttribute(source, 'comb-container');
this.renderOnly = hasAttribute(source, 'comb-renderOnly');
// Add Renderer
//-------------------------------------
source.removeAttr('comb');
source.removeAttr('comb-exclude');
source.removeAttr('comb-container');
source.removeAttr('comb-renderOnly');
// Add inheritance
if ( inherit ) {
this.combs[0].renders.push(renders[inherit]);
inherit = null;
}
if ( source.attr('render') ) {
var renderer = source.attr('render');
debug('*** Renderer: ' + renderer);
// Allow > in renderer to apply to all children
if ( renderer[0] == '>' ) {
renderer = renderer.substring(1);
inherit = renderer;
} else {
this.combs[0].renders.push(renders[renderer]);
}
}
this.source = source;
// Handle Expression Markup
//--------------------------------------
if (! this.isNested ) {
// Only blow out inner HTML when we're targeting it
if ( this.combs['TargetingInnerHtml'] && this.renderOnly == false )
if ( this.source.html().indexOf('{.}') == -1 )
this.source.html('{.}');
}
// Parse the source
//-------------------------------------
var self = this;
(function parse(source) {
source.children().each( function(index) {
var o = $(this),
comb = o.attr('comb');
// comb (NO) - Continue down the DOM
//-----------------------------------------
if (! comb ) {
debug('*** sss' );
return parse( o );
}
debug('*** Parsing Comb: ' + oHtml(o) );
debug(comb);
var child = new template( o.clone(), inherit );
//self.map[comb] = new Combover.template( o.clone() );
child.holder = '{-{' + self.children.length + '}-}';
self.children.push( child );
o.replaceWith( child.holder );
})
})(source);
debug('*** Property: ' + this.property + ' ' + oHtml(this.source) );
};
/**
*
*/
template.prototype.renderComb = function(comb, data, source, is_direct) {
// Figure out the value to render & type
//------------------------------------------------
var val = is_direct
? data
: data[comb.member];
var type = getType( val );
debug('--- RenderComb: ' + comb.member + ' ' + type, val, data);
// Simple Rending
//------------------------------------------------
if (! this.isNested && isPrimitive(val) ) {
debug(' Simple ' + oHtml(source));
return toHtml(val, comb, source);
}
// Render Objects
//------------------------------------------------
var html = '';
if ( type == 'Object' ) {
debug(' Object ' + oHtml(source));
html = oHtml( source );
this.children.map(function(t) {
debug(' Child: ', t.combs);
html = html.replace(t.holder, t._render(val) );
debug('*** Partial HTML: ' + html);
});
debug('*** Final HTML: ' + html);
return html;
}
// Render Arrays
//------------------------------------------------
if ( type == 'Array' ) {
debug(' Array ' + oHtml(source));
val.map(function(item){
debug(' Array.Item: ', item);
html += this.renderComb(comb, item, source, true);
}, this);
return html;
}
// Nested Primitives
//-----------------------------------
debug(' Nested Primitive ' + oHtml(source));
html = oHtml( source );
this.children.map(function(t) {
debug(' Child: ', t.combs);
html = html.replace(t.holder, t._render(data, false) );
debug(' Partial HTML: ' + html);
});
html = toHtml(val, comb, $(html));
debug(' Final HTML: ' + html);
return html;
}
/**
* Arrays filled w/ primitives are different
*
* they need to loop through all combs when iterating
* through each value. How do we handle this?
*
* Right now its hacked w/ a seperate function
*
* @temp perhaps return an array instead of string from renderComb
* then just apply each additional comb to each element of of the array?
*/
template.prototype.renderArray = function(data, source) {
debug(' RenderArray ' + oHtml(source));
var html = ''
var self = this;
var item_html;
data.map(function(item){
// Apply Render
if ( hideComb(item, self.combs[0], true) ) {
debug('*** Not Rendering', self.combs[0]);
return;
}
// Apply each comb
item_html = source;
self.combs.map(function(comb) {
item_html = $( self.renderComb(comb, item, $( item_html ), true) );
});
// @todo should/can there be higher level property to mark behavior?
html += self.exclude || self.container
? item_html.html()
: oHtml( item_html );
});
// Handle empty arrays
// ----------------------------
if (! item_html )
return self.exclude
? html
: oHtml( source.html('') );
if ( self.container )
html = ! item_html
? oHtml( source.html('') )
: oHtml( item_html.html( html ) );
return html;
}
/**
* Internal render, which is called for each template
* except for the first one (that's what .render is for)
*
* @param
*
* @return String the html to render
*/
template.prototype._render = function(data) {
var html = this.source;
// Handle Render Only
// These are tags that don't work with properties
// but use peroperties to determine if the tag should render
// --------------------------------------------------------------
if ( this.renderOnly ) {
// Apply Render
if ( hideComb(data[ this.combs[0].member ], this.combs[0], true) ) {
debug('*** Not Rendering', this.combs[0]);
return '';
}
return oHtml( html );
}
// Handle Arrays
//
// @temp currently not sure how to handle Arrays filled w/ primities
//------------------------------------------------
if ( data[ this.combs[0].member ] instanceof Array )
return this.renderArray( data[ this.combs[0].member ], html );
// All other types
//--------------------------------------------------
// Apply Renders
if ( hideComb(data, this.combs[0]) ) {
debug('*** Not Rendering', this.combs[0]);
return '';
}
this.combs.map(function(comb) {
debug('*** _Render: ' + comb.member + ( comb.attribute ? '@' + comb.attribute : ''));
html = comb.attribute
? toHtml( data[comb.member], comb, $(html) )
: this.renderComb(comb, data, $(html));
}, this);
return html;
}
/**
* Method called to render the root template
*
* @param
*
* @return String the html to render
*/
template.prototype.render = function(data) {
var html = this.source.html();
debug('*** Render ' + html);
debug('**** ', this);
// @Hack
// If the data is an array, what do we do? How do we start an array?
if ( data instanceof Array ) {
data = {root: data};
html = this._render(data);
}
this.children.map(function(t) {
debug(' Child: ', t.combs);
html = html.replace(t.holder, t._render(data) );
});
// @Hack
// We've replaced empty tags with {.}, what if they are only targeting attributes? {.} doesn't get replaced
// Because the expression can be replaced with an older comb
// We could choose not to replace empty tags w/ the expression?
html = html.replace('>{.}<', '><');
return html;
}
//---------------------------------------------------------------------------------------------------------------------
// Initialize
//---------------------------------------------------------------------------------------------------------------------
exports.addHelper('^', function(val) { return new String(val).toUpperCase(); });
exports.addHelper('$', function(val) { return '$' + formatNumber(val, 2); });
exports.addHelper('%', function(val) { return formatNumber(val*100, 0) + '%' });
exports.addHelper('#', function(val) { return formatNumber(val, 2) });
exports.addHelper(',', function(val) { return formatNumber(val, 0) });
exports.addRenderer('?', function(val) { return val !== undefined });
exports.addRenderer('!', function(val) {
return val instanceof Array
? val.length > 0
: val != '' && val != null && val != undefined && val != false;
});
})(Combover);