-
Notifications
You must be signed in to change notification settings - Fork 638
/
filters.js
648 lines (504 loc) · 14.2 KB
/
filters.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
636
637
638
639
640
641
642
643
644
645
646
647
648
'use strict';
var lib = require('./lib');
var r = require('./runtime');
var exports = module.exports = {};
function normalize(value, defaultValue) {
if (value === null || value === undefined || value === false) {
return defaultValue;
}
return value;
}
exports.abs = Math.abs;
function isNaN(num) {
return num !== num; // eslint-disable-line no-self-compare
}
function batch(arr, linecount, fillWith) {
var i;
var res = [];
var tmp = [];
for (i = 0; i < arr.length; i++) {
if (i % linecount === 0 && tmp.length) {
res.push(tmp);
tmp = [];
}
tmp.push(arr[i]);
}
if (tmp.length) {
if (fillWith) {
for (i = tmp.length; i < linecount; i++) {
tmp.push(fillWith);
}
}
res.push(tmp);
}
return res;
}
exports.batch = batch;
function capitalize(str) {
str = normalize(str, '');
const ret = str.toLowerCase();
return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1));
}
exports.capitalize = capitalize;
function center(str, width) {
str = normalize(str, '');
width = width || 80;
if (str.length >= width) {
return str;
}
const spaces = width - str.length;
const pre = lib.repeat(' ', (spaces / 2) - (spaces % 2));
const post = lib.repeat(' ', spaces / 2);
return r.copySafeness(str, pre + str + post);
}
exports.center = center;
function default_(val, def, bool) {
if (bool) {
return val || def;
} else {
return (val !== undefined) ? val : def;
}
}
// TODO: it is confusing to export something called 'default'
exports['default'] = default_; // eslint-disable-line dot-notation
function dictsort(val, caseSensitive, by) {
if (!lib.isObject(val)) {
throw new lib.TemplateError('dictsort filter: val must be an object');
}
let array = [];
// deliberately include properties from the object's prototype
for (let k in val) { // eslint-disable-line guard-for-in, no-restricted-syntax
array.push([k, val[k]]);
}
let si;
if (by === undefined || by === 'key') {
si = 0;
} else if (by === 'value') {
si = 1;
} else {
throw new lib.TemplateError(
'dictsort filter: You can only sort by either key or value');
}
array.sort((t1, t2) => {
var a = t1[si];
var b = t2[si];
if (!caseSensitive) {
if (lib.isString(a)) {
a = a.toUpperCase();
}
if (lib.isString(b)) {
b = b.toUpperCase();
}
}
return a > b ? 1 : (a === b ? 0 : -1); // eslint-disable-line no-nested-ternary
});
return array;
}
exports.dictsort = dictsort;
function dump(obj, spaces) {
return JSON.stringify(obj, null, spaces);
}
exports.dump = dump;
function escape(str) {
if (str instanceof r.SafeString) {
return str;
}
str = (str === null || str === undefined) ? '' : str;
return r.markSafe(lib.escape(str.toString()));
}
exports.escape = escape;
function safe(str) {
if (str instanceof r.SafeString) {
return str;
}
str = (str === null || str === undefined) ? '' : str;
return r.markSafe(str.toString());
}
exports.safe = safe;
function first(arr) {
return arr[0];
}
exports.first = first;
function forceescape(str) {
str = (str === null || str === undefined) ? '' : str;
return r.markSafe(lib.escape(str.toString()));
}
exports.forceescape = forceescape;
function groupby(arr, attr) {
return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined);
}
exports.groupby = groupby;
function indent(str, width, indentfirst) {
str = normalize(str, '');
if (str === '') {
return '';
}
width = width || 4;
// let res = '';
const lines = str.split('\n');
const sp = lib.repeat(' ', width);
const res = lines.map((l, i) => {
return (i === 0 && !indentfirst) ? l : `${sp}${l}`;
}).join('\n');
return r.copySafeness(str, res);
}
exports.indent = indent;
function join(arr, del, attr) {
del = del || '';
if (attr) {
arr = lib.map(arr, (v) => v[attr]);
}
return arr.join(del);
}
exports.join = join;
function last(arr) {
return arr[arr.length - 1];
}
exports.last = last;
function lengthFilter(val) {
var value = normalize(val, '');
if (value !== undefined) {
if (
(typeof Map === 'function' && value instanceof Map) ||
(typeof Set === 'function' && value instanceof Set)
) {
// ECMAScript 2015 Maps and Sets
return value.size;
}
if (lib.isObject(value) && !(value instanceof r.SafeString)) {
// Objects (besides SafeStrings), non-primative Arrays
return lib.keys(value).length;
}
return value.length;
}
return 0;
}
exports.length = lengthFilter;
function list(val) {
if (lib.isString(val)) {
return val.split('');
} else if (lib.isObject(val)) {
return lib._entries(val || {}).map(([key, value]) => ({key, value}));
} else if (lib.isArray(val)) {
return val;
} else {
throw new lib.TemplateError('list filter: type not iterable');
}
}
exports.list = list;
function lower(str) {
str = normalize(str, '');
return str.toLowerCase();
}
exports.lower = lower;
function nl2br(str) {
if (str === null || str === undefined) {
return '';
}
return r.copySafeness(str, str.replace(/\r\n|\n/g, '<br />\n'));
}
exports.nl2br = nl2br;
function random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
exports.random = random;
/**
* Construct select or reject filter
*
* @param {boolean} expectedTestResult
* @returns {function(array, string, *): array}
*/
function getSelectOrReject(expectedTestResult) {
function filter(arr, testName = 'truthy', secondArg) {
const context = this;
const test = context.env.getTest(testName);
return lib.toArray(arr).filter(function examineTestResult(item) {
return test.call(context, item, secondArg) === expectedTestResult;
});
}
return filter;
}
exports.reject = getSelectOrReject(false);
function rejectattr(arr, attr) {
return arr.filter((item) => !item[attr]);
}
exports.rejectattr = rejectattr;
exports.select = getSelectOrReject(true);
function selectattr(arr, attr) {
return arr.filter((item) => !!item[attr]);
}
exports.selectattr = selectattr;
function replace(str, old, new_, maxCount) {
var originalStr = str;
if (old instanceof RegExp) {
return str.replace(old, new_);
}
if (typeof maxCount === 'undefined') {
maxCount = -1;
}
let res = ''; // Output
// Cast Numbers in the search term to string
if (typeof old === 'number') {
old = '' + old;
} else if (typeof old !== 'string') {
// If it is something other than number or string,
// return the original 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 r.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 r.copySafeness(str, res);
}
let 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;
}
let pos = 0;
let 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 r.copySafeness(originalStr, res);
}
exports.replace = replace;
function reverse(val) {
var arr;
if (lib.isString(val)) {
arr = list(val);
} else {
// Copy it
arr = lib.map(val, v => v);
}
arr.reverse();
if (lib.isString(val)) {
return r.copySafeness(val, arr.join(''));
}
return arr;
}
exports.reverse = reverse;
function round(val, precision, method) {
precision = precision || 0;
const factor = Math.pow(10, precision);
let rounder;
if (method === 'ceil') {
rounder = Math.ceil;
} else if (method === 'floor') {
rounder = Math.floor;
} else {
rounder = Math.round;
}
return rounder(val * factor) / factor;
}
exports.round = round;
function slice(arr, slices, fillWith) {
const sliceLength = Math.floor(arr.length / slices);
const extra = arr.length % slices;
const res = [];
let offset = 0;
for (let i = 0; i < slices; i++) {
const start = offset + (i * sliceLength);
if (i < extra) {
offset++;
}
const end = offset + ((i + 1) * sliceLength);
const currSlice = arr.slice(start, end);
if (fillWith && i >= extra) {
currSlice.push(fillWith);
}
res.push(currSlice);
}
return res;
}
exports.slice = slice;
function sum(arr, attr, start = 0) {
if (attr) {
arr = lib.map(arr, (v) => v[attr]);
}
return start + arr.reduce((a, b) => a + b, 0);
}
exports.sum = sum;
exports.sort = r.makeMacro(
['value', 'reverse', 'case_sensitive', 'attribute'], [],
function sortFilter(arr, reversed, caseSens, attr) {
// Copy it
let array = lib.map(arr, v => v);
let getAttribute = lib.getAttrGetter(attr);
array.sort((a, b) => {
let x = (attr) ? getAttribute(a) : a;
let y = (attr) ? getAttribute(b) : b;
if (
this.env.opts.throwOnUndefined &&
attr && (x === undefined || y === undefined)
) {
throw new TypeError(`sort: attribute "${attr}" resolved to undefined`);
}
if (!caseSens && lib.isString(x) && lib.isString(y)) {
x = x.toLowerCase();
y = y.toLowerCase();
}
if (x < y) {
return reversed ? 1 : -1;
} else if (x > y) {
return reversed ? -1 : 1;
} else {
return 0;
}
});
return array;
});
function string(obj) {
return r.copySafeness(obj, obj);
}
exports.string = string;
function striptags(input, preserveLinebreaks) {
input = normalize(input, '');
let tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|<!--[\s\S]*?-->/gi;
let trimmedInput = trim(input.replace(tags, ''));
let res = '';
if (preserveLinebreaks) {
res = trimmedInput
.replace(/^ +| +$/gm, '') // remove leading and trailing spaces
.replace(/ +/g, ' ') // squash adjacent spaces
.replace(/(\r\n)/g, '\n') // normalize linebreaks (CRLF -> LF)
.replace(/\n\n\n+/g, '\n\n'); // squash abnormal adjacent linebreaks
} else {
res = trimmedInput.replace(/\s+/gi, ' ');
}
return r.copySafeness(input, res);
}
exports.striptags = striptags;
function title(str) {
str = normalize(str, '');
let words = str.split(' ').map(word => capitalize(word));
return r.copySafeness(str, words.join(' '));
}
exports.title = title;
function trim(str) {
return r.copySafeness(str, str.replace(/^\s*|\s*$/g, ''));
}
exports.trim = trim;
function truncate(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 {
let idx = input.lastIndexOf(' ', length);
if (idx === -1) {
idx = length;
}
input = input.substring(0, idx);
}
input += (end !== undefined && end !== null) ? end : '...';
return r.copySafeness(orig, input);
}
exports.truncate = truncate;
function upper(str) {
str = normalize(str, '');
return str.toUpperCase();
}
exports.upper = upper;
function urlencode(obj) {
var enc = encodeURIComponent;
if (lib.isString(obj)) {
return enc(obj);
} else {
let keyvals = (lib.isArray(obj)) ? obj : lib._entries(obj);
return keyvals.map(([k, v]) => `${enc(k)}=${enc(v)}`).join('&');
}
}
exports.urlencode = urlencode;
// For the jinja regexp, see
// https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23
const puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/;
// from http://blog.gerv.net/2011/05/html5_email_address_regexp/
const emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i;
const httpHttpsRe = /^https?:\/\/.*$/;
const wwwRe = /^www\./;
const tldRe = /\.(?:org|net|com)(?:\:|\/|$)/;
function urlize(str, length, nofollow) {
if (isNaN(length)) {
length = Infinity;
}
const noFollowAttr = (nofollow === true ? ' rel="nofollow"' : '');
const words = str.split(/(\s+)/).filter((word) => {
// If the word has no length, bail. This can happen for str with
// trailing whitespace.
return word && word.length;
}).map((word) => {
var matches = word.match(puncRe);
var possibleUrl = (matches) ? matches[1] : word;
var shortUrl = possibleUrl.substr(0, length);
// url that starts with http or https
if (httpHttpsRe.test(possibleUrl)) {
return `<a href="${possibleUrl}"${noFollowAttr}>${shortUrl}</a>`;
}
// url that starts with www.
if (wwwRe.test(possibleUrl)) {
return `<a href="http://${possibleUrl}"${noFollowAttr}>${shortUrl}</a>`;
}
// an email address of the form username@domain.tld
if (emailRe.test(possibleUrl)) {
return `<a href="mailto:${possibleUrl}">${possibleUrl}</a>`;
}
// url that ends in .com, .org or .net that is not an email address
if (tldRe.test(possibleUrl)) {
return `<a href="http://${possibleUrl}"${noFollowAttr}>${shortUrl}</a>`;
}
return word;
});
return words.join('');
}
exports.urlize = urlize;
function wordcount(str) {
str = normalize(str, '');
const words = (str) ? str.match(/\w+/g) : null;
return (words) ? words.length : null;
}
exports.wordcount = wordcount;
function float(val, def) {
var res = parseFloat(val);
return (isNaN(res)) ? def : res;
}
exports.float = float;
const intFilter = r.makeMacro(
['value', 'default', 'base'],
[],
function doInt(value, defaultValue, base = 10) {
var res = parseInt(value, base);
return (isNaN(res)) ? defaultValue : res;
}
);
exports.int = intFilter;
// Aliases
exports.d = exports.default;
exports.e = exports.escape;