/
customized_eta.ts
433 lines (376 loc) · 14.9 KB
/
customized_eta.ts
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
import { Eta } from 'eta'
import { EtaConfig } from 'eta/dist/types/config'
import * as Sherlock from 'sherlockjs'
import { dayjs } from '../context'
import { IBlockNode, walkBlockTree } from '../utils'
class CustomizedEta extends Eta {
constructor(customConfig?: object) {
super(customConfig)
this.compileBody = compileBody
this.parse = parse
}
}
const etaForCompatibility = new Eta({
useWith: true, /** Make data available on the global object instead of `varName` */
varName: 'fh', /** Name of the data object. Default "it" */
// functionHeader: 'const c = fh.c', /** Raw JS code inserted in the template function. Useful for declaring global variables */
autoEscape: false, /** Automatically XML-escape interpolations */
// escapeFunction: eta.XMLEscape,
autoFilter: true, /** Apply a `filterFunction` to every interpolation or raw interpolation */
filterFunction: function (value: any): string {
if (value instanceof dayjs)
// @ts-expect-error
return value.toPage()
if (typeof value === 'string')
return value
return String(value)
},
/** Configure automatic whitespace trimming: left & right */
/** values:
* "nl" - trim new lines
* "slurp" - trim whitespaces
* false — no trimming
* */
autoTrim: [false, false],
tags: ['``{', '}``'],
parse: {
exec: '!',
interpolate: '',
raw: '~',
},
plugins: [], // [{processFnString: null, processAST: null, processTemplate: null}],
// TODO: https://github.com/nebrelbug/eta_plugin_mixins
cache: false, /** cache templates if `name` or `filename` is passed */
cacheFilepaths: false, /** Holds cache of resolved filepaths */
views: '', /** Directory that contains templates */
debug: false, /** Pretty-format error messages (adds runtime penalties) */
})
const eta = new CustomizedEta({
useWith: true, /** Make data available on the global object instead of `varName` */
varName: 'fh', /** Name of the data object. Default "it" */
// functionHeader: 'const c = fh.c', /** Raw JS code inserted in the template function. Useful for declaring global variables */
autoEscape: false, /** Automatically XML-escape interpolations */
// escapeFunction: eta.XMLEscape,
autoFilter: true, /** Apply a `filterFunction` to every interpolation or raw interpolation */
filterFunction: function (value: any): string {
if (value instanceof dayjs)
// @ts-expect-error
return value.toPage()
if (typeof value === 'string')
return value
return String(value)
},
/** Configure automatic whitespace trimming: left & right */
/** values:
* "nl" - trim new lines
* "slurp" - trim whitespaces
* false — no trimming
* */
autoTrim: [false, false],
/*
trim: [false, 'nl'],
parseFunction: null,
compileFunction: null,
autoFilter: false,
filterFunction: null,
*/
parseTags: {
'``{...}``': {
trimRight: 'nl',
autoFilter: false,
parseFunction: (content) => ({isStatement: true}),
compileFunction: (meta, content) => (content + '\n'),
},
'``[...]``': {
trimRight: false,
autoFilter: true,
compileFunction: (meta, content) => `ref(${content})`,
},
'``...``': {
trimRight: false,
autoFilter: true,
},
'<%...%>': {
trimRight: false,
autoFilter: false,
compileFunction: (meta, content_) => {
const content = content_.trim().toLowerCase()
if (content === 'current page')
return '`[[${c.currentPage.name}]]`'
else if (content === 'today')
return 'ref(date.today)'
else if (content === 'yesterday')
return 'ref(date.yesterday)'
else if (content === 'tomorrow')
return 'ref(date.tomorrow)'
else if (content === 'time')
return 'time'
// try NLP
Sherlock._setNow(null)
const parsed = Sherlock.parse(content)
const { isAllDay, eventTitle, startDate, endDate } = parsed
if (startDate) {
const day = dayjs(startDate).format('page')
return `'[[${day}]]'`
}
return '\'' + content_ + '\''
},
},
},
plugins: [], // [{processFnString: null, processAST: null, processTemplate: null}],
// TODO: https://github.com/nebrelbug/eta_plugin_mixins
cache: false, /** cache templates if `name` or `filename` is passed */
cacheFilepaths: false, /** Holds cache of resolved filepaths */
views: '', /** Directory that contains templates */
debug: false, /** Pretty-format error messages (adds runtime penalties) */
})
export async function isOldSyntax(block: IBlockNode) {
let useOldSyntax = false
const openTag_ = '``{'
const [ openTag, closeTag ] = [ escapeRegExp(openTag_), escapeRegExp('}``') ]
const prefix = escapeRegExp('!')
const openTagWithPrefixRegexp = new RegExp(openTag + '(-|_)?\\s*(' + prefix + ')\\s', 'g')
const statementsSignsRegexp = new RegExp(openTag + '(?<code>.*)(?<!.*\\b(=|var|let|const|return|if|switch|for|function|try|class|while)\\b.*)' + closeTag, 'gs')
const captureInsideRegexp = new RegExp(openTag + '(?<code>.*)' + closeTag, 'gs')
await walkBlockTree(block, async (b, lvl) => {
if (b.content.indexOf(openTag_) === -1)
return
let m = openTagWithPrefixRegexp.exec(b.content)
if (m) {
useOldSyntax = true
return
}
m = statementsSignsRegexp.exec(b.content)
if (m) {
m = captureInsideRegexp.exec(b.content)
// has no single «=»
if (!(m && m.groups && (m.groups.code.indexOf('=') !== -1 && m.groups.code.indexOf('==') === -1)))
useOldSyntax = true
}
})
return useOldSyntax
}
export class RenderingSyntax {
static latest(): Eta {
return eta
}
static async autoSelect(block: IBlockNode): Promise<Eta> {
return (await isOldSyntax(block)) ? etaForCompatibility : eta
}
}
function compileBody(buff) {
// @ts-expect-error
const config = this.config
let returnStr = ''
for (const currentBlock of buff) {
if (typeof currentBlock === 'string') {
const str = currentBlock
// we know string exists
returnStr += '__eta.res+=\'' + str + '\'\n'
} else {
if (config.debug)
returnStr += '__eta.line=' + currentBlock.lineNo + '\n'
let content = currentBlock.val || ''
const parseInfo = config.parseTags[currentBlock.t]
const { parseFunction, compileFunction, filterFunction } = parseInfo
const autoFilter = parseInfo.autoFilter ?? config.autoFilter
let meta: any = {}
if (parseFunction)
meta = parseFunction(content)
if (compileFunction)
content = compileFunction(meta, content)
if (meta.isStatement) {
returnStr += content
continue
}
if (filterFunction)
content = `this.config.parseTags['${currentBlock.t}'].filterFunction('` + content + '\')'
if (autoFilter)
content = '__eta.f(' + content + ')'
returnStr += '__eta.res+=' + content + '\n'
}
}
return returnStr
}
function parse(str) {
// @ts-expect-error
const config = this.config;
let buffer: any[] = [];
let trimLeftOfNextStr = false;
let lastIndex = 0;
for (const [ tags, info ] of Object.entries(config.parseTags)) {
// @ts-expect-error
info.tags = tags.split('...')
}
if (config.plugins) {
for (let i = 0; i < config.plugins.length; i++) {
const plugin = config.plugins[i];
if (plugin.processTemplate) {
str = plugin.processTemplate(str, config);
}
}
}
templateLitReg.lastIndex = 0;
singleQuoteReg.lastIndex = 0;
doubleQuoteReg.lastIndex = 0;
function pushString(strng, shouldTrimRightOfString) {
if (strng) {
// if string is truthy it must be of type 'string'
strng = trimWS(strng, config, trimLeftOfNextStr,
// this will only be false on the first str, the next ones will be null or undefined
shouldTrimRightOfString);
if (strng) {
// replace \ with \\, ' with \'
// we're going to convert all CRLF to LF so it doesn't take more than one replace
strng = strng.replace(/\\|'/g, "\\$&").replace(/\r\n|\n|\r/g, "\\n");
buffer.push(strng);
}
}
}
const openTagsReg = Object.values(config.parseTags).map((v: any) => escapeRegExp(v.tags[0])).join("|");
const parseOpenReg = new RegExp("(" + openTagsReg + ")" + "(-|_)?\\s*", "g");
let m: RegExpExecArray | null;
while (m = parseOpenReg.exec(str)) {
const precedingString = str.slice(lastIndex, m.index);
lastIndex = m[0].length + m.index;
const tagOpen = m[1];
const wsLeft = m[2];
pushString(precedingString, wsLeft);
const closeTagsReg = Object.values(config.parseTags)
.filter((v: any) => (v.tags[0] === tagOpen))
.map((v: any) => escapeRegExp(v.tags[1])).join("|");
const parseCloseReg = new RegExp("'|\"|\\/\\*|(\\s*(-|_)?" + "(?<tag>" + closeTagsReg + "))", "g");
parseCloseReg.lastIndex = lastIndex;
let closeTag: RegExpExecArray | null;
let currentObj: any = false;
while (closeTag = parseCloseReg.exec(str)) {
if (closeTag[1]) {
const content = str.slice(lastIndex, closeTag.index);
parseOpenReg.lastIndex = lastIndex = parseCloseReg.lastIndex;
const tagClose = closeTag.groups!.tag
const currentTags = [tagOpen, tagClose].join("...");
trimLeftOfNextStr = closeTag[2] || config.parseTags[currentTags].trimRight;
currentObj = {
t: currentTags,
val: content
};
break;
} else {
const char = closeTag[0];
if (char === "/*") {
const commentCloseInd = str.indexOf("*/", parseCloseReg.lastIndex);
if (commentCloseInd === -1) {
ParseErr("unclosed comment", str, closeTag.index);
}
parseCloseReg.lastIndex = commentCloseInd;
} else if (char === "'") {
singleQuoteReg.lastIndex = closeTag.index;
const singleQuoteMatch = singleQuoteReg.exec(str);
if (singleQuoteMatch) {
parseCloseReg.lastIndex = singleQuoteReg.lastIndex;
} else {
ParseErr("unclosed string", str, closeTag.index);
}
} else if (char === '"') {
doubleQuoteReg.lastIndex = closeTag.index;
const doubleQuoteMatch = doubleQuoteReg.exec(str);
if (doubleQuoteMatch) {
parseCloseReg.lastIndex = doubleQuoteReg.lastIndex;
} else {
ParseErr("unclosed string", str, closeTag.index);
}
} else if (char === "`") {
templateLitReg.lastIndex = closeTag.index;
const templateLitMatch = templateLitReg.exec(str);
if (templateLitMatch) {
parseCloseReg.lastIndex = templateLitReg.lastIndex;
} else {
ParseErr("unclosed string", str, closeTag.index);
}
}
}
}
if (currentObj) {
if (config.debug) {
currentObj.lineNo = getLineNo(str, m.index);
}
buffer.push(currentObj);
} else {
ParseErr("unclosed tag", str, m.index);
}
}
pushString(str.slice(lastIndex, str.length), false);
if (config.plugins) {
for (let i = 0; i < config.plugins.length; i++) {
const plugin = config.plugins[i];
if (plugin.processAST) {
buffer = plugin.processAST(buffer, config);
}
}
}
return buffer;
}
/* START copy from eta source code: just to support extension-ability */
const templateLitReg = /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g;
const singleQuoteReg = /'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g;
const doubleQuoteReg = /"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;
class EtaError extends Error {
constructor(message) {
super(message);
this.name = "Eta Error";
}
}
function ParseErr(message, str, indx) {
const whitespace = str.slice(0, indx).split(/\n/);
const lineNo = whitespace.length;
const colNo = whitespace[lineNo - 1].length + 1;
message += " at line " + lineNo + " col " + colNo + ":\n\n" + " " + str.split(/\n/)[lineNo - 1] + "\n" + " " + Array(colNo).join(" ") + "^";
throw new EtaError(message);
}
function trimWS(str, config, wsLeft, wsRight) {
let leftTrim: string;
let rightTrim: string;
if (Array.isArray(config.autoTrim)) {
// Slightly confusing,
// but _}} will trim the left side of the following string
leftTrim = config.autoTrim[1];
rightTrim = config.autoTrim[0];
} else {
leftTrim = rightTrim = config.autoTrim;
}
if (wsLeft || wsLeft === false) {
leftTrim = wsLeft;
}
if (wsRight || wsRight === false) {
rightTrim = wsRight;
}
if (!rightTrim && !leftTrim) {
return str;
}
if (leftTrim === "slurp" && rightTrim === "slurp") {
return str.trim();
}
if (leftTrim === "_" || leftTrim === "slurp") {
// full slurp
str = str.trimStart();
} else if (leftTrim === "-" || leftTrim === "nl") {
// nl trim
str = str.replace(/^(?:\r\n|\n|\r)/, "");
}
if (rightTrim === "_" || rightTrim === "slurp") {
// full slurp
str = str.trimEnd();
} else if (rightTrim === "-" || rightTrim === "nl") {
// nl trim
str = str.replace(/(?:\r\n|\n|\r)$/, "");
}
return str;
}
function escapeRegExp(string) {
// From MDN
return string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
function getLineNo(str, index) {
return str.slice(0, index).split("\n").length;
}
/* END copy from eta source code */