-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathformatters.core.ts
More file actions
435 lines (387 loc) · 12.1 KB
/
formatters.core.ts
File metadata and controls
435 lines (387 loc) · 12.1 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
import { Context } from '../context';
import { partialMissing } from '../errors';
import { isTruthy } from '../node';
import { Formatter, FormatterTable } from '../plugin';
import { MacroCode, RootCode } from '../instructions';
import { MISSING_NODE, Node } from '../node';
import { Variable } from '../variable';
import { Type } from '../types';
import { executeTemplate } from '../exec';
import { splitVariable } from '../util';
import { format } from './util.format';
import { escapeHtmlAttributes, escapeScriptTags, slugify, truncate } from './util.string';
import utf8 from 'utf8';
export class ApplyFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
// Bail if we have no arguments or no engine defined.
if (args.length === 0 || !ctx.engine) {
first.set('');
return;
}
// Get the name of the partial / macro.
const name = args[0];
let argvar: Variable | undefined;
// Set whether the partial / macro's execution context should be private.
// This will block variable resolution from proceeding past the current
// stack frame.
let privateContext = false;
if (args.length > 1) {
const argmap: any = {};
for (let i = 1; i < args.length; i++) {
const arg = args[i];
// Mark the context as private
if (arg === 'private') {
privateContext = true;
continue;
}
// Parse the colon-delimited arguments into key-values
const j = arg.indexOf('=');
if (j !== -1) {
const k = arg.slice(0, j);
const v = arg.slice(j + 1);
argmap[k] = v;
}
}
// Pass formatter's argument to the macro / template
argvar = ctx.newVariable('@args', new Node(argmap));
}
// Retrieve the partial / macro by name, If none defined, bail.
const inst = ctx.getPartial(name);
if (!Array.isArray(inst)) {
ctx.error(partialMissing(name));
first.set('');
return;
}
if (ctx.enterPartial(name)) {
// Execute the template and set the variable to the result.
const text = executeTemplate(ctx, inst as RootCode | MacroCode, first.node, privateContext, argvar);
first.set(text);
ctx.exitPartial(name);
} else {
// Executing the partial failed, so set empty.
first.set('');
}
}
}
export class CountFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const node = first.node;
if (node.type === Type.OBJECT) {
first.set(Object.keys(node.value).length);
} else if (node.type === Type.ARRAY || node.type === Type.STRING) {
first.set(node.value.length);
} else {
first.set(0);
}
}
}
export class CycleFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asNumber();
const count = args.length;
let index = (value - 1) % count;
if (index < 0) {
index += count;
}
first.set(args[index]);
}
}
export class EncodeSpaceFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asString();
first.set(value.replace(/\s/g, ' '));
}
}
export class EncodeUriFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asString();
first.set(encodeURI(value));
}
}
export class EncodeUriComponentFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asString();
first.set(encodeURIComponent(value));
}
}
export class FormatFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const values = args.map((arg) => {
const names = splitVariable(arg);
const parent = ctx.frame().parent;
const node = ctx.resolveFrom(names, parent ? parent : ctx.frame());
return node.type === Type.NULL || node.type === Type.MISSING ? '' : node.value;
});
const fmt = first.node.asString();
const result = format(fmt, values);
first.set(result);
}
}
export class GetFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
let tmp = first.node;
for (const arg of args) {
const path = splitVariable(arg);
const node = ctx.resolve(path);
if (node.type === Type.MISSING) {
tmp = MISSING_NODE;
} else {
const resolved: (number | string)[] =
node.type === Type.ARRAY
? (node.value as (number | string)[])
: node.type === Type.NUMBER
? [node.asNumber()]
: [node.asString()];
tmp = tmp.path(resolved);
}
// Once we hit a missing node, no point continuing
if (tmp.type === Type.MISSING) {
break;
}
}
first.set(tmp);
}
}
export class HtmlFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.replace({
'&': '&',
'<': '<',
'>': '>',
});
first.set(value);
}
}
export class HtmlAttrFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
first.set(escapeHtmlAttributes(first.node.asString()));
}
}
export class IterFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const value = ctx.lookupStack('@index');
vars[0].set(value.asString());
}
}
export class JsonFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
if (first.node.isMissing()) {
first.set('');
} else {
const value = JSON.stringify(first.node.value);
first.set(escapeScriptTags(value));
}
}
}
export class JsonPretty extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
if (first.node.isMissing()) {
first.set('');
} else {
const value = JSON.stringify(first.node.value, undefined, ' ');
first.set(escapeScriptTags(value));
}
}
}
export class KeyByFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const path = args[0];
const keyByMap: { [key: string]: any } = {};
if (first.node.type === Type.ARRAY && path) {
const splitPath = splitVariable(path);
for (const val of first.get()) {
const nodeAtPath = new Node(val).path(splitPath);
if (nodeAtPath.type !== Type.MISSING) {
keyByMap[nodeAtPath.value] = val;
}
}
}
first.set(keyByMap);
}
}
export class LookupFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const key = args[0];
if (key) {
const ref = ctx.resolve(splitVariable(key));
const value = ctx.resolve(splitVariable(ref.asString()));
first.set(value);
} else {
first.set('');
}
}
}
export class ModFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const n = first.node.asNumber();
const divisor = parseInt(args[0], 10) || 2;
first.set(n % (divisor && isFinite(divisor) ? divisor : 2));
}
}
export class OutputFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const value = args.join(' ');
vars[0].set(value);
}
}
export class PluralizeFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
let singular = '';
let plural = 's';
if (args.length === 1) {
plural = args[0];
} else if (args.length >= 2) {
singular = args[0];
plural = args[1];
}
const first = vars[0];
const result = first.node.asNumber() === 1 ? singular : plural;
first.set(result);
}
}
export class PropFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
let tmp = first.node;
for (const arg of args) {
const path = splitVariable(arg);
tmp = tmp.path(path);
if (tmp.type === Type.MISSING) {
break;
}
}
first.set(tmp);
}
}
export class RawFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
first.set(JSON.stringify(first.node.value));
}
}
export class RoundFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asNumber();
first.set(Math.round(value));
}
}
const RE_SAFE = /<[^>]*?>/g;
export class SafeFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
if (isTruthy(first.node)) {
const value = first.node.asString();
first.set(value.replace(RE_SAFE, ''));
}
}
}
export class SlugifyFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asString();
first.set(slugify(value));
}
}
const RE_SMARTY_1 = /(^|[-\u2014\\s(\["])'/gm;
const RE_SMARTY_APOS = /'/gm;
const RE_SMARTY_2 = /(^|[-\u2014/\[(\u2018\s])"/gm;
const RE_SMARTY_QUOTE = /"/gm;
const RE_SMARTY_MDASH = /--/gm;
export class SmartyPantsFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
let value = first.node.asString();
value = value.replace(RE_SMARTY_1, '$1\u2018');
value = value.replace(RE_SMARTY_APOS, '\u2019');
value = value.replace(RE_SMARTY_2, '$1\u201c');
value = value.replace(RE_SMARTY_QUOTE, '\u201d');
value = value.replace(RE_SMARTY_MDASH, '\u2014');
first.set(value);
}
}
export class StrFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
switch (first.node.type) {
case Type.OBJECT:
case Type.ARRAY:
first.set('');
break;
default:
first.set(first.node.asString());
break;
}
}
}
export class TruncateFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
let limit = 100;
let ellipsis = '...';
if (args.length) {
limit = parseInt(args[0], 10);
}
if (args.length > 1) {
ellipsis = args[1];
}
if (isFinite(limit) && limit > 0) {
const first = vars[0];
let value = first.node.asString();
value = truncate(value, limit, ellipsis);
first.set(value);
}
}
}
export class UrlEncodeFormatter extends Formatter {
apply(args: string[], vars: Variable[], ctx: Context): void {
const first = vars[0];
const value = first.node.asString();
const utf = utf8.encode(value);
first.set(escape(utf));
}
}
export const CORE_FORMATTERS: FormatterTable = {
apply: new ApplyFormatter(),
count: new CountFormatter(),
cycle: new CycleFormatter(),
'encode-space': new EncodeSpaceFormatter(),
'encode-uri': new EncodeUriFormatter(),
'encode-uri-component': new EncodeUriComponentFormatter(),
format: new FormatFormatter(),
get: new GetFormatter(),
html: new HtmlFormatter(),
htmlattr: new HtmlAttrFormatter(),
htmltag: new HtmlAttrFormatter(), // same as "htmlattr"
iter: new IterFormatter(),
json: new JsonFormatter(),
'json-pretty': new JsonPretty(),
'key-by': new KeyByFormatter(),
lookup: new LookupFormatter(),
mod: new ModFormatter(),
output: new OutputFormatter(),
pluralize: new PluralizeFormatter(),
prop: new PropFormatter(),
raw: new RawFormatter(),
round: new RoundFormatter(),
safe: new SafeFormatter(),
slugify: new SlugifyFormatter(),
smartypants: new SmartyPantsFormatter(),
str: new StrFormatter(),
truncate: new TruncateFormatter(),
'url-encode': new UrlEncodeFormatter(),
};