-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoxygen.js
executable file
·635 lines (520 loc) · 14.5 KB
/
oxygen.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
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
// +--------------------------------------------------------------------+ \\
// ¦ OxygenJS 0.2.6 - High Performance JavaScript MicroTemplating ¦ \\
// +--------------------------------------------------------------------+ \\
// ¦ Copyright © 2016 Vincent Fontaine ¦ \\
// +---------+----------------------------------------------------------+ \\
// ¦ CREDITS | ¦ \\
// +---------+ ¦ \\
// ¦ * Kru for the reduce tip ¦ \\
// ¦ * NunJucks for the Jinja like filters ¦ \\
// ¦ * John Resig for his excellent work (http://ejohn.org/) ¦ \\
// +--------------------------------------------------------------------+ \\
(function(target){
var c = {},
d = document,
opts = Object.prototype.toString,
html = function(id){
return d.getElementById(id) ? d.getElementById(id).innerHTML : '';
};
var safeString = function(val){
if (typeof val != 'string'){ return val; }
this.toString = function(){ return val; };
this.length = val.length;
var methods = [
'charAt', 'charCodeAt', 'concat', 'contains', 'endsWith',
'fromCharCode', 'indexOf', 'lastIndexOf', 'length', 'localeCompare',
'match', 'quote', 'replace', 'search', 'slice', 'split',
'startsWith', 'substr', 'substring', 'toLocaleLowerCase',
'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim',
'trimLeft', 'trimRight'
];
for (var i = 0; i < methods.length; i++) {
this[methods[i]] = proxyStr(val[methods[i]]);
}
};
var safeCopy = function(dest, target){
if (dest instanceof safeString) return new safeString(target);
return target.toString();
};
var normalize = function(value, defaultValue){
return (value === null || value === undefined || value === false) ? defaultValue : value;
};
var escapeMap = {
'&' : '&',
'"' : '"',
"'" : ''',
"<" : '<',
">" : '>'
};
var lib = {
escape : function(val){
return val.replace(/[&"'<>]/g, function(ch){
return escapeMap[ch];
});
},
isFunction : function(obj){
return opts.call(obj) == '[object Function]';
},
isArray : Array.isArray || function(obj){
return opts.call(obj) == '[object Array]';
},
isString : function(obj){
return opts.call(obj) == '[object String]';
},
isObject : function(obj){
return obj === Object(obj);
},
repeat : function(c, n){
var str = '';
for (var i=0; i<n; i++) str += c;
return str;
},
map : function(obj, func){
var results = [];
if (obj == null) return results;
if(Array.prototype.map && obj.map === Array.prototype.map){
return obj.map(func);
}
for (var i=0; i<obj.length; i++){
results[results.length] = func(obj[i], i);
}
if (obj.length === +obj.length){
results.length = obj.length;
}
return results;
}
};
var filter = function(match, p1){
var r = p1.split('|').reduce(function(txt, f){
var par = (f.indexOf("(") + 1) || f.length,
pl = (par == f.length);
return "Object.O2.filters." + f.substring(0, par)
+ (pl ? "(" : "")
+ txt
+ (pl ? ")" : ", ") + f.substring(par);
});
return "', " + r + ", '";
};
Object.O2 = function tmpl(id, data){
if (id==='' && id === undefined) return '';
var z = !/\W/.test(id) ? c[id] = c[id] || Object.O2(html(id)) : new Function("obj",
"var p=[];with(obj){p.push('" +
id
.replace(/{%[ ]*for ([$a-zA-Z_]+) in ([$a-zA-Z_]+([.][$a-zA-Z_]+)*)[ ]*%}/g, "{% for (var $1=0; $1<$2.length; $1++) { %}")
.replace(/{%[ ]*if (((?!%}).)*[^ ])\s*%}/g, '{% if ($1) { %}')
.replace(/{%[ ]*end[if|for]*[ ]*%}/g, '{% } %}')
.replace(/{%[ ]*else[ ]*%}/g, '{% } else { %}')
.replace(/[\r\t\n]/g, " ")
.split("{%").join("\t")
.replace(/((^|%})[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%}/g, "',$1,'")
.split("\t").join("');")
.split("%}").join("p.push('")
.split("\r").join("\\'")
.replace(/{{2}[ ]*([^{}, ]*[^{}]*[^{}, ]+)[ ]*}{2}/g, filter)
+ "');}return p.join('');"
);
return data ? z(data) : z;
};
Object.O2.filters = {
abs : function(n){
return Math.abs(n);
},
batch : function(arr, linecount, fill_with){
var res = [],
tmp = [];
for (var i=0; i<arr.length; i++){
if (i % linecount === 0 && tmp.length){
res.push(tmp);
tmp = [];
}
tmp.push(arr[i]);
}
if (tmp.length) {
if (fill_with) {
for(var i=tmp.length; i<linecount; i++) {
tmp.push(fill_with);
}
}
res.push(tmp);
}
return res;
},
capitalize : function(str){
str = normalize(str, '');
var ret = str.toLowerCase();
return safeCopy(str, ret.charAt(0).toUpperCase() + ret.slice(1));
},
center : function(str, width){
str = normalize(str, '');
width = width || 80;
if (str.length >= width) {
return str;
}
var spaces = width - str.length,
pre = lib.repeat(" ", spaces/2 - spaces % 2),
post = lib.repeat(" ", spaces/2);
return safeCopy(str, pre + str + post);
},
"default" : function(val, def, bool){
if (bool) {
return val ? val : def;
} else {
return (val !== undefined) ? val : def;
}
},
dictsort : function(val, case_sensitive, by){
if (!lib.isObject(val)) {
throw new ("dictsort filter: val must be an object");
}
var array = [];
for (var k in val) {
array.push([k,val[k]]);
}
var si;
if (by === undefined || by === "key") {
si = 0;
} else if (by === "value") {
si = 1;
} else {
throw new ("dictsort filter: You can only sort by either key or value");
}
array.sort(function(t1, t2){
var a = t1[si];
var b = t2[si];
if (!case_sensitive) {
if (lib.isString(a)) {
a = a.toUpperCase();
}
if (lib.isString(b)) {
b = b.toUpperCase();
}
}
return a > b ? 1 : (a === b ? 0 : -1);
});
return array;
},
dump : function(obj){
return JSON.stringify(obj);
},
escape : function(str){
if (typeof str == 'string' || str instanceof safeString){
return lib.escape(str);
}
return str;
},
safe : function(str){
return new safeString(str);
},
first : function(arr){
return arr[0];
},
groupby : function(obj, val){
var result = {},
iterator = lib.isFunction(val) ? val : function(obj){
return obj[val];
};
for (var i=0; i<obj.length; i++){
var value = obj[i],
key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
},
indent : function(str, width, indentfirst){
str = normalize(str, '');
if (str === '') return '';
width = width || 4;
var res = '',
lines = str.split('\n'),
sp = lib.repeat(' ', width);
for (var i=0; i<lines.length; i++) {
if (i === 0 && !indentfirst) {
res += lines[i] + '\n';
} else {
res += sp + lines[i] + '\n';
}
}
return safeCopy(str, res);
},
join : function(arr, del, attr){
del = del || '';
if (attr){
arr = lib.map(arr, function(v){
return v[attr];
});
}
return arr.join(del);
},
last : function(arr){
return arr[arr.length-1];
},
length : function(arr){
var value = normalize(val, '');
return value !== undefined ? value.length : 0;
},
list : function(val){
if (lib.isString(val)) {
return val.split('');
}
else if (lib.isObject(val)) {
var keys = [];
if (Object.keys) {
keys = Object.keys(val);
} else {
for (var k in val) {
keys.push(k);
}
}
return lib.map(keys, function(k){
return {
key: k,
value: val[k]
};
});
}
else if (lib.isArray(val)) {
return val;
}
else {
throw new ("list filter: type not iterable");
}
},
lower : function(str){
str = normalize(str, '');
return str.toLowerCase();
},
random : function(arr){
return arr[Math.floor(Math.random() * arr.length)];
},
rejectattr : function(arr, attr){
return arr.filter(function(item){
return !item[attr];
});
},
selectattr : function(arr, attr){
return arr.filter(function(item){
return !!item[attr];
});
},
replace : function(str, old, new_, maxCount){
var res = ''; // Output
var originalStr = str;
if (old instanceof RegExp) {
return str.replace(old, new_);
}
if (typeof maxCount === 'undefined'){
maxCount = -1;
}
// Cast Numbers in the search term to string
if (typeof old === 'number'){
old = old + '';
} else if (typeof old !== 'string') {
return str;
}
// Cast numbers in the replacement to string
if (typeof str === 'number'){
str = str + '';
}
// If by now, we don't have a string, throw it back
if (typeof str !== 'string' && !(str instanceof safeString)){
return str;
}
// ShortCircuits
if (old === '') {
// Mimic the python behaviour: empty string is replaced
// by replacement e.g. "abc"|replace("", ".") -> .a.b.c.
res = new_ + str.split('').join(new_) + new_;
return safeCopy(str, res);
}
var nextIndex = str.indexOf(old);
// if # of replacements to perform is 0, or the string to does
// not contain the old value, return the string
if (maxCount === 0 || nextIndex === -1){
return str;
}
var pos = 0;
var count = 0; // # of replacements made
while (nextIndex > -1 && (maxCount === -1 || count < maxCount)){
// Grab the next chunk of src string and add it with the
// replacement, to the result
res += str.substring(pos, nextIndex) + new_;
// Increment our pointer in the src string
pos = nextIndex + old.length;
count++;
// See if there are any more replacements to be made
nextIndex = str.indexOf(old, pos);
}
// We've either reached the end, or done the max # of
// replacements, tack on any remaining string
if (pos < str.length) {
res += str.substring(pos);
}
return safeCopy(originalStr, res);
},
reverse : function(val){
var arr;
if (lib.isString(val)) {
arr = this.list(val);
} else {
arr = lib.map(val, function(v){
return v;
});
}
arr.reverse();
return (lib.isString(val)) ? safeCopy(val, arr.join('')) : arr;
},
round : function(val, precision, method){
precision = precision || 0;
var factor = Math.pow(10, precision),
rounder;
switch (method) {
case "ceil" : rounder = Math.ceil; break;
case "floor" : rounder = Math.floor; break;
default : rounder = Math.round;
}
return rounder(val * factor) / factor;
},
slice : function(arr, slices, fillWith){
var sliceLength = Math.floor(arr.length / slices),
extra = arr.length % slices,
offset = 0,
res = [];
for (var i=0; i<slices; i++){
var start = offset + i * sliceLength;
if (i < extra) offset++;
var end = offset + (i + 1) * sliceLength,
slice = arr.slice(start, end);
if (fillWith && i >= extra) slice.push(fillWith);
res.push(slice);
}
return res;
},
sum : function(arr, attr, start){
var sum = 0;
if (typeof start === 'number'){
sum += start;
}
if (attr){
arr = lib.map(arr, function(v){
return v[attr];
});
}
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
return sum;
},
sort : function(arr, reverse, caseSens, attr){
arr = lib.map(arr, function(v){
return v;
});
arr.sort(function(a, b){
var x, y;
if (attr){
x = a[attr];
y = b[attr];
} else {
x = a;
y = b;
}
if (!caseSens && lib.isString(x) && lib.isString(y)) {
x = x.toLowerCase();
y = y.toLowerCase();
}
if (x < y) {
return reverse ? 1 : -1;
} else if (x > y) {
return reverse ? -1: 1;
} else {
return 0;
}
});
return arr;
},
string : function(obj){
return safeCopy(obj, obj);
},
striptags: function(input, preserve_linebreaks) {
input = normalize(input, '');
preserve_linebreaks = preserve_linebreaks || false;
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|<!--[\s\S]*?-->/gi;
var trimmedInput = filters.trim(input.replace(tags, ''));
var res = '';
if (preserve_linebreaks) {
res = trimmedInput
.replace(/^ +| +$/gm, '')
.replace(/ +/g, ' ')
.replace(/(\r\n)/g, '\n')
.replace(/\n\n\n+/g, '\n\n');
} else {
res = trimmedInput.replace(/\s+/gi, ' ');
}
return safeCopy(input, res);
},
title : function(str){
str = normalize(str, '');
var words = str.split(' ');
for (var i=0; i<words.length; i++) {
words[i] = this.capitalize(words[i]);
}
return safeCopy(str, words.join(' '));
},
trim : function(str){
return safeCopy(str, str.replace(/^\s*|\s*$/g, ''));
},
truncate : function(input, length, killwords, end){
var orig = input;
input = normalize(input, '');
length = length || 255;
if (input.length <= length) return input;
if (killwords) {
input = input.substring(0, length);
} else {
var idx = input.lastIndexOf(' ', length);
if (idx === -1) {
idx = length;
}
input = input.substring(0, idx);
}
input += (end !== undefined && end !== null) ? end : '...';
return safeCopy(orig, input);
},
upper : function(str){
str = normalize(str, '');
return str.toUpperCase();
},
urlencode : function(obj){
var parts, enc = encodeURIComponent;
if (lib.isString(obj)) {
return enc(obj);
}
if (lib.isArray(obj)) {
parts = obj.map(function(item){
return enc(item[0]) + '=' + enc(item[1]);
});
} else {
parts = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
parts.push(enc(k) + '=' + enc(obj[k]));
}
}
}
return parts.join('&');
},
wordcount : function(str){
str = normalize(str, '');
return str.match(/\w+/g).length;
},
'float' : function(val, def){
var res = parseFloat(val);
return isNaN(res) ? def : res;
},
'int' : function(val, def){
var res = parseInt(val, 10);
return isNaN(res) ? def : res;
}
};
target.O2 = Object.O2;
})(window);