-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathteddy.js
1143 lines (1086 loc) · 46.2 KB
/
teddy.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// #region globals
import fs from 'fs' // node filesystem module
import path from 'path' // node path module
import { load as cheerioLoad } from 'cheerio/slim' // dom parser
const cheerioOptions = { xml: { xmlMode: false, lowerCaseAttributeNames: false, decodeEntities: false } }
const browser = cheerioLoad.isCheerioPolyfill // true if we are executing in the browser context
const params = {} // teddy parameters
setDefaultParams() // set params to the defaults
const templates = {} // loaded templates are stored as object collections, e.g. { "myTemplate.html": "<p>some markup</p>"}
const caches = {} // a place to store cached portions of templates
const templateCaches = {} // a place to store cached full templates
// #endregion
// #region private methods
// loads the template from the filesystem
function loadTemplate (template) {
// ensure template is a string
if (typeof template !== 'string') {
if (params.verbosity > 1) console.warn('teddy.loadTemplate attempted to load a template which is not a string.')
return ''
}
const name = template
let register = false
if (!templates[template] && template.indexOf('<') === -1 && fs && fs.readFileSync) {
// template is not found, it is not code, and we're in the node.js context
register = true
// append extension if not present
if (template.slice(-5) !== '.html') template += '.html'
try {
template = fs.readFileSync(template, 'utf8')
} catch (e) {
try {
template = fs.readFileSync(params.templateRoot + template, 'utf8')
} catch (e) {
try {
template = fs.readFileSync(params.templateRoot + '/' + template, 'utf8')
} catch (e) {
// do nothing, attempt to render it as code
register = false
}
}
}
} else {
if (templates[template]) {
template = templates[template]
register = true
} else {
// didn't find it; append extension if not present and check it again
if (template.slice(-5) !== '.html') {
template += '.html'
}
if (templates[template]) {
template = templates[template]
register = true
}
template = removeTeddyComments(template)
}
}
if (register) {
// register the new template and return the code
template = removeTeddyComments(template)
templates[name] = template
return template
} else {
// return the template name which is presumed to be code
return template.slice(-5) === '.html' ? template.substring(0, template.length - 5) : template
}
}
// remove teddy {! comments !}
function removeTeddyComments (renderedTemplate) {
let oldTemplate
do {
oldTemplate = renderedTemplate
let vars
try {
vars = matchByDelimiter(renderedTemplate, '{!', '!}')
} catch (e) {
return renderedTemplate // it will match {! comments {! with comments in them !} !} but if there are unbalanced brackets, just return the original text
}
const varsLength = vars.length
for (let i = 0; i < varsLength; i++) renderedTemplate = renderedTemplate.replace(`{!${vars[i]}!}`, '')
} while (oldTemplate !== renderedTemplate)
return renderedTemplate
}
// find all cache elements and replace them with the rendered contents of their cache, then remove the cache element
function replaceCacheElements (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('cache:not([defer])')
if (tags.length > 0) {
for (const el of tags) {
if (browser) el.attribs = getAttribs(el)
const name = el.attribs.name
if (name.includes('{')) continue
const key = el.attribs.key || 'none'
if (key.includes('{')) continue
const cache = caches[name]
if (cache && cache.entries) {
const keyVal = el.attribs.key ? getOrSetObjectByDotNotation(model, key) : 'none'
if (cache.entries[keyVal]) {
const now = Date.now()
// if max age is not set, then there is no max age and the cache content is still valid
// or if last accessed + max age > now then the cache is not stale and the cache is still valid
if (!(cache.maxAge && !cache.maxage) || cache.entries[keyVal].lastAccessed + (cache.maxAge || cache.maxage) > now) {
const cacheContent = cache.entries[keyVal].markup
cache.entries[keyVal].lastAccessed = now
dom(el).replaceWith(cacheContent)
} else {
// if last accessed + max age <= now then the cache is stale and the cache is no longer valid
delete caches[name].entries[keyVal]
dom(el).attr('defer', 'true') // create a new cache
}
} else dom(el).attr('defer', 'true') // no cache exists for this yet; create after the template renders
} else dom(el).attr('defer', 'true') // no cache exists for this yet; create after the template renders
parsedTags++
}
}
} while (parsedTags)
return dom
}
// add an id to all <noteddy> or <noparse> tags, then remove their content temporarily until the template is fully parsed
function tagNoParseBlocks (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('noteddy:not([id]), noparse:not([id])')
if (tags.length > 0) {
for (const el of tags) {
const id = model._noTeddyBlocks.push(dom(el).html()) - 1
dom(el).replaceWith(`<noteddy id="${id}"></noteddy>`)
parsedTags++
}
}
} while (parsedTags)
return dom
}
// parse <include> tags
function parseIncludes (dom, model, dynamic) {
let parsedTags
let passes = 0
do {
passes++
if (passes > params.maxPasses) throw new Error(`teddy could not finish rendering the template because the max number of passes over the template (${params.maxPasses}) was exceeded; there may be an infinite loop in your template logic.`)
parsedTags = 0
let tags
// dynamic includes are includes like <include src="{sourcedFromVariable}"></include>
if (dynamic) tags = dom('include') // parse all includes
else tags = dom('include:not([teddydeferreddynamicinclude])') // parse only includes that aren't dynamic
if (tags.length > 0) {
for (const el of tags) {
// ensure this isn't the child of a no parse block
let foundBody = false
let next = false
let parent = el.parent || el.parentNode
while (!foundBody) {
let parentName
if (!parent) parentName = 'body'
else parentName = parent.nodeName?.toLowerCase() || parent.name
if (parentName === 'noparse' || parentName === 'noteddy') {
next = true
break
} else if (parentName === 'body') foundBody = true
else parent = parent.parent || parent.parentNode
}
if (next) continue
// get attributes
if (browser) el.attribs = getAttribs(el)
const src = el.attribs.src
if (!src) {
if (params.verbosity > 1) console.warn('teddy encountered an include tag with no src attribute.')
continue
}
if (src.includes('{')) {
dom(el).attr('teddydeferreddynamicinclude', 'true') // mark it dynamic and then skip it
continue
}
loadTemplate(src) // load the partial into the template list
const contents = templates[src]
const localModel = Object.assign({}, model)
for (const arg of dom(el).children()) {
const argName = browser ? arg.nodeName?.toLowerCase() : arg.name
if (argName === 'arg') {
if (browser) arg.attribs = getAttribs(arg)
const argval = Object.keys(arg.attribs)[0]
getOrSetObjectByDotNotation(localModel, argval, dom(arg).html())
}
}
const localMarkup = parseVars(contents, localModel)
let localDom = cheerioLoad(localMarkup || '', cheerioOptions)
localDom = parseConditionals(localDom, localModel)
localDom = parseOneLineConditionals(localDom, localModel)
localDom = parseLoops(localDom, localModel)
dom(el).replaceWith(localDom.html())
parsedTags++
}
}
} while (parsedTags)
return dom
}
// parse <if>, <elseif>, <unless>, <elseunless>, and <else> tags
function parseConditionals (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('if, unless')
if (tags.length > 0) {
for (const el of tags) {
// ensure this isn't the child of a loop or a no parse block
let foundBody = false
let next = false
let parent = el.parent || el.parentNode
while (!foundBody) {
let parentName
if (!parent) parentName = 'body'
else parentName = parent.nodeName?.toLowerCase() || parent.name
if (parentName === 'loop' || parentName === 'noparse' || parentName === 'noteddy') {
next = true
break
} else if (parentName === 'body') foundBody = true
else parent = parent.parent || parent.parentNode
}
if (next) continue
// get conditions
let args = []
if (browser) el.attribs = getAttribs(el)
for (let attr in el.attribs) {
if (attr.includes('-teddyduplicate')) attr = attr.split('-teddyduplicate')[0] // the condition is a duplicate, so remove the `-teddyduplicate1` from `conditionName-teddyduplicate1`, `conditionName-teddyduplicate2`, etc
const val = el.attribs[attr]
if (val) args.push(`${attr}=${val}`)
else args.push(attr)
}
// check if it's an if tag and not an unless tag
let isIf = true
const elName = browser ? el.nodeName?.toLowerCase() : el.name
if (elName === 'unless') isIf = false
// evaluate conditional
const condResult = evaluateConditional(args, model)
if ((isIf && condResult) || ((!isIf && !condResult))) {
// render the true block and discard the elseif, elseunless, and else blocks
let nextSibling = el.nextSibling
const removeStack = []
while (nextSibling) {
const nextSiblingName = browser ? nextSibling.nodeName?.toLowerCase() : nextSibling.name
switch (nextSiblingName) {
case 'elseif':
case 'elseunless':
case 'else':
removeStack.push(nextSibling)
nextSibling = nextSibling.nextSibling
break
case 'if':
case 'unless':
nextSibling = false
break
default:
nextSibling = nextSibling.nextSibling
}
}
for (const element of removeStack) dom(element).replaceWith('')
dom(el).replaceWith(el.childNodes || el.children)
parsedTags++
} else {
// true block is false; find the next elseif, elseunless, or else tag to evaluate
let nextSibling = el.nextSibling
while (nextSibling) {
const nextSiblingName = browser ? nextSibling.nodeName?.toLowerCase() : nextSibling.name
switch (nextSiblingName) {
case 'elseif':
// get conditions
args = []
if (browser) nextSibling.attribs = getAttribs(nextSibling)
for (const attr in nextSibling.attribs) {
const val = nextSibling.attribs[attr]
if (val) args.push(`${attr}=${val}`)
else args.push(attr)
}
if (evaluateConditional(args, model)) {
// render the true block and discard the elseif, elseunless, and else blocks
const replaceSibling = nextSibling
dom(replaceSibling).replaceWith(replaceSibling.childNodes || replaceSibling.children)
nextSibling = el.nextSibling
const removeStack = []
while (nextSibling) {
const nextSiblingName = browser ? nextSibling.nodeName?.toLowerCase() : nextSibling.name
switch (nextSiblingName) {
case 'elseif':
case 'elseunless':
case 'else':
removeStack.push(nextSibling)
nextSibling = nextSibling.nextSibling
break
case 'if':
case 'unless':
nextSibling = false
break
default:
nextSibling = nextSibling.nextSibling
}
}
for (const element of removeStack) dom(element).replaceWith('')
nextSibling = false
parsedTags++
} else {
// true block is false; find the next elseif, elseunless, or else tag to evaluate
const siblingToWipe = nextSibling
nextSibling = nextSibling.nextSibling
dom(siblingToWipe).replaceWith('')
}
break
case 'elseunless':
// get conditions
args = []
if (browser) nextSibling.attribs = getAttribs(nextSibling)
for (const attr in nextSibling.attribs) {
const val = nextSibling.attribs[attr]
if (val) args.push(`${attr}=${val}`)
else args.push(attr)
}
if (!evaluateConditional(args, model)) {
// render the true block and discard the elseif, elseunless, and else blocks
const replaceSibling = nextSibling
dom(replaceSibling).replaceWith(replaceSibling.childNodes || replaceSibling.children)
nextSibling = el.nextSibling
const removeStack = []
while (nextSibling) {
const nextSiblingName = browser ? nextSibling.nodeName?.toLowerCase() : nextSibling.name
switch (nextSiblingName) {
case 'elseif':
case 'elseunless':
case 'else':
removeStack.push(nextSibling)
nextSibling = nextSibling.nextSibling
break
case 'if':
case 'unless':
nextSibling = false
break
default:
nextSibling = nextSibling.nextSibling
}
}
for (const element of removeStack) dom(element).replaceWith('')
nextSibling = false
parsedTags++
} else {
// true block is false; find the next elseif, elseunless, or else tag to evaluate
const siblingToWipe = nextSibling
nextSibling = nextSibling.nextSibling
dom(siblingToWipe).replaceWith('')
}
break
case 'else':
// else is always true, so if we've gotten here, then there's nothing to evaluate and we've reached the end of the conditional blocks
dom(nextSibling).replaceWith(nextSibling.childNodes || nextSibling.children)
nextSibling = false
parsedTags++
break
case 'if':
case 'unless':
// if we encounter another fresh if statement or unless statement, then there's nothing left to evaluate and we've reached the end of this conditional's blocks
nextSibling = false
break
default:
// if we encounter any other element or a text node we assume there could still be more elseif, elseunless, or else tags ahead so we keep going
nextSibling = nextSibling.nextSibling
}
}
dom(el).replaceWith('') // remove the original if statement once done with finding its siblings
}
}
}
} while (parsedTags)
return dom
}
// evaluates a single <if> or <unless> tag
function evaluateConditional (conditions, model) {
const conditionsLength = conditions.length
// loop through conditions and reduce them to booleans
for (let i = 0; i < conditionsLength; i++) {
const condition = conditions[i]
if (typeof condition === 'boolean') continue // if the condition is already a boolean then we don't need to reduce it to a boolean to evaluate it
// reject conditions with invalid formatting
if (condition.startsWith('=') || condition.endsWith('=')) {
if (params.verbosity > 1) console.warn('teddy encountered a conditional statement with "=" at the beginning or end of a condition.')
return false
}
if (condition.includes(':') && !condition.startsWith('not:')) {
if (params.verbosity > 1) console.warn('teddy encountered a conditional statement with a "not:" that isn\'t at the beginning of a condition.')
return false
}
// deal with boolean logic
if (condition === 'and') {
if (conditions[i - 1] && evaluateCondition(conditions[i + 1], model)) {
// if both sides of an and are true, then reduce all 3 condition blocks to true
conditions[i - 1] = true
conditions[i] = true
conditions[i + 1] = true
} else {
// if either side of an and is false, then reduce all 3 condition blocks to false
conditions[i - 1] = false
conditions[i] = false
conditions[i + 1] = false
}
} else if (condition === 'or') {
if (conditions[i - 1] || evaluateCondition(conditions[i + 1], model)) {
// if either side of an or is true, then reduce all 3 condition blocks to true, as well as all condition blocks that precded this or
conditions.fill(true, 0, i + 2)
} else {
// if both sides of an or are false, then reduce all 3 condition blocks to false
conditions[i - 1] = false
conditions[i] = false
conditions[i + 1] = false
}
} else if (condition === 'xor') {
if (!!conditions[i - 1] === !!evaluateCondition(conditions[i + 1], model)) {
// if both sides of an xor are equal to each other, then reduce all 3 condition blocks to false
conditions[i - 1] = false
conditions[i] = false
conditions[i + 1] = false
} else {
// if the two sides of an xor are not equal to each other, then reduce all 3 condition blocks to true
conditions[i - 1] = true
conditions[i] = true
conditions[i + 1] = true
}
} else conditions[i] = evaluateCondition(condition, model)
}
return conditions.every(item => item === true) || false // if any of the booleans are false, then return false. otherwise return true
}
// determines whether a single condition in a teddy conditional is true or false
function evaluateCondition (condition, model) {
let not // stores whether the :not modifier is present
if (typeof condition === 'string' && condition.includes('=')) { // it's an equality check condition
not = !!condition.startsWith('not:') // true if "not:" is present
if (not) condition = condition.slice(4) // remove the :not prefix
const parts = condition.split('=') // something="Some content"
const cond = parts[0] // something
delete parts[0] // remove the something=
const val = parts.join('') // "Some content" — the path.join method ensures the string gets rebuilt even if it contains another = character
const lookup = getOrSetObjectByDotNotation(model, cond)
// the == is necessary because teddy does type-insensitive equality checks
if (lookup == val) return !not // eslint-disable-line
else return not // false
} else { // it's a presence check
not = typeof condition === 'string' ? !!condition.startsWith('not:') : false // true if "not:" is present
if (not) condition = condition.slice(4) // remove the :not prefix
const lookup = getOrSetObjectByDotNotation(model, condition)
if (lookup) {
if (typeof lookup === 'object' && Object.keys(lookup).length === 0) return not // false; empty object or array
return !not // true; var is present
} else return not // false; var is not present
}
}
// render one-line if attributes, e.g. <p if-something="value" true="class='class-applied-if-true'" false="class='class-applied-if-false'">hello</p>
function parseOneLineConditionals (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('[true], [false]')
if (tags.length > 0) {
for (const el of tags) {
// skip parsing this if it uses variables as part of its conditions; it will get caught in the next pass after parseVars runs
let defer = false
if (browser) el.attribs = getAttribs(el)
for (const attr in el.attribs) {
const val = el.attribs[attr]
if (val.includes('{')) {
defer = true
break
}
}
if (defer) {
dom(el).attr('teddydeferredonelineconditional', 'true')
continue
}
// ensure this isn't the child of a loop or a no parse block
let foundBody = false
let next = false
let parent = el.parent || el.parentNode
while (!foundBody) {
let parentName
if (!parent) parentName = 'body'
else parentName = parent.nodeName?.toLowerCase() || parent.name
if (parentName === 'loop' || parentName === 'noparse' || parentName === 'noteddy') {
next = true
break
} else if (parentName === 'body') foundBody = true
else parent = parent.parent || parent.parentNode
}
if (next) continue
// get conditions
let cond
let ifTrue
let ifFalse
if (browser) el.attribs = getAttribs(el)
for (const origAttr in el.attribs) {
let attr = origAttr
const val = el.attribs[attr]
if (attr.includes('-teddyduplicate')) attr = attr.split('-teddyduplicate')[0] // the condition is a duplicate, so remove the `-teddyduplicate1` from `conditionName-teddyduplicate1`, `conditionName-teddyduplicate2`, etc
if (attr.startsWith('if-')) {
const parts = attr.split('if-')
if (val) cond = [`${[parts[1]]}=${val}`] // if-something="Some content"
else cond = [`${[parts[1]]}`] // if-something
dom(el).removeAttr(origAttr)
} else if (attr === 'true') {
ifTrue = val.replaceAll('"', '"') // true="class='blah'"
dom(el).removeAttr(origAttr)
} else if (attr === 'false') {
ifFalse = val.replaceAll('"', '"') // false="class='blah'"
dom(el).removeAttr(origAttr)
}
}
// evaluate conditional
if (evaluateConditional(cond, model)) {
if (ifTrue) {
const parts = ifTrue.split('=')
dom(el).attr(parts[0], parts[1] ? parts[1].replace(/["']/g, '') : '')
}
parsedTags++
} else if (ifFalse) {
if (ifFalse) {
const parts = ifFalse.split('=')
dom(el).attr(parts[0], parts[1] ? parts[1].replace(/["']/g, '') : '')
}
parsedTags++
}
}
}
} while (parsedTags)
return dom
}
// render <loop> tags
function parseLoops (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('loop')
if (tags.length > 0) {
for (const el of tags) {
// get attributes
let loopThrough
let keyName
let valName
if (browser) el.attribs = getAttribs(el)
for (const attr in el.attribs) {
if (attr === 'through') loopThrough = getOrSetObjectByDotNotation(model, el.attribs[attr])
else if (attr === 'key') keyName = el.attribs[attr]
else if (attr === 'val') valName = el.attribs[attr]
}
// reject the loop if it has invalid attributes
if (!loopThrough) {
if (params.verbosity > 1) console.warn('teddy encountered a loop without a through attribute.')
dom(el).replaceWith('')
continue
}
if (!keyName && !valName) {
if (params.verbosity > 1) console.warn('teddy encountered a loop without a key or a val attribute.')
dom(el).replaceWith('')
continue
}
// loop through model[loopThrough] and parse teddy tags within the loop's iteration against the local model
let newMarkup = ''
const loopContents = dom(el).html()
if (loopThrough instanceof Set) loopThrough = [...loopThrough] // convert Sets to arrays
for (const key in loopThrough) {
const val = loopThrough[key]
const localModel = Object.assign({}, model)
getOrSetObjectByDotNotation(localModel, keyName, key)
getOrSetObjectByDotNotation(localModel, valName, val)
const localMarkup = parseVars(loopContents, localModel)
let localDom = cheerioLoad(localMarkup || '', cheerioOptions)
localDom = parseConditionals(localDom, localModel)
localDom = parseOneLineConditionals(localDom, localModel)
localDom = parseLoops(localDom, localModel)
newMarkup += localDom.html()
}
const newDom = cheerioLoad(newMarkup || '', cheerioOptions)
dom(el).replaceWith(newDom.html())
parsedTags++
}
}
} while (parsedTags)
return dom
}
// render {variables}
function parseVars (templateString, model) {
let vars
try {
vars = matchByDelimiter(templateString, '{', '}')
} catch (e) {
return templateString // it will match {vars{withVarsInThem}} but if there are unbalanced brackets, just return the original text
}
const varsLength = vars.length
for (let i = 0; i < varsLength; i++) {
let match = vars[i]
if (match === '') continue // empty {}
if (match.includes('{')) {
// there's a variable inside the variable name
const originalMatch = match
match = parseVars(match, model)
try {
templateString = templateString.replace(new RegExp(`\${${originalMatch}}`, 'i'), () => `\${${match}}`)
templateString = templateString.replace(new RegExp(`{${originalMatch}}`, 'i'), () => `{${match}}`)
} catch (e) {
if (params.verbosity > 2) console.warn(`teddy.parseVars encountered a {variable} that could not be parsed: {${originalMatch}}`)
}
}
const lastFourChars = match.slice(-4)
if (lastFourChars.includes('|p')) {
// no parse flag is set; also handles if no escape flag is set as well
const originalMatch = match
match = match.substring(0, match.length - (lastFourChars.split('|').length - 1 > 1 ? 4 : 2)) // remove last 2-4 char
let parsed = getOrSetObjectByDotNotation(model, match)
if (params.emptyVarBehavior === 'hide' && !parsed) parsed = '' // display empty string instead of the variable text verbatim if this setting is set
if (parsed || parsed === '') {
const id = model._noTeddyBlocks.push(parsed) - 1
try {
try {
templateString = templateString.replace(new RegExp(`\${${originalMatch}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), `<noteddy id="${id}"></noteddy>`)
templateString = templateString.replace(new RegExp(`{${originalMatch}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), `<noteddy id="${id}"></noteddy>`)
} catch (e) {
if (params.verbosity > 2) console.warn(`teddy.parseVars encountered a {variable} that could not be parsed: {${originalMatch}}`)
}
} catch (e) {
return templateString
}
}
} else if (lastFourChars.includes('|s')) {
// no escape flag is set
const originalMatch = match
match = match.substring(0, match.length - (lastFourChars.split('|').length - 1 > 1 ? 4 : 2)) // remove last 2-4 char
let parsed = getOrSetObjectByDotNotation(model, match)
if (params.emptyVarBehavior === 'hide' && !parsed) parsed = '' // display empty string instead of the variable text verbatim if this setting is set
else if (!parsed && parsed !== '') parsed = `{${originalMatch}}`
try {
templateString = templateString.replace(new RegExp(`\${${originalMatch}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), () => parsed)
templateString = templateString.replace(new RegExp(`{${originalMatch}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), () => parsed)
} catch (e) {
return templateString
}
} else {
// no flags are set
let parsed = getOrSetObjectByDotNotation(model, match)
if (params.emptyVarBehavior === 'hide' && !parsed) parsed = '' // display empty string instead of the variable text verbatim if this setting is set
else if (parsed || parsed === '') parsed = escapeEntities(parsed)
else if (parsed === 0) parsed = '0'
else parsed = `{${match}}`
try {
templateString = templateString.replace(new RegExp(`\${${match}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), () => parsed)
templateString = templateString.replace(new RegExp(`{${match}}`.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'), 'i'), () => parsed)
} catch (e) {
return templateString
}
}
}
return templateString
}
// once the template is fully rendered, find all cache elements that still exist and cache their contents
function defineNewCaches (dom, model) {
let parsedTags
do {
parsedTags = 0
const tags = dom('cache[defer]')
if (tags.length > 0) {
for (const el of tags) {
if (browser) el.attribs = getAttribs(el)
const name = el.attribs.name
const key = el.attribs.key || 'none'
const maxAge = parseInt(el.attribs.maxAge || el.attribs.maxage) || 0
const maxCaches = parseInt(el.attribs.maxCaches || el.attribs.maxcaches) || 1000
const timestamp = Date.now()
const markup = dom(el).html()
if (!caches[name]) {
caches[name] = {
key,
maxAge,
maxCaches,
entries: {}
}
}
caches[name].entries[el.attribs.key ? getOrSetObjectByDotNotation(model, key) : 'none'] = {
lastAccessed: timestamp,
created: timestamp,
markup
}
// invalidate oldest cache if we've reached max caches limit
if (Object.keys(caches[name].entries).length > maxCaches) {
const lowestKeyVal = Object.keys(caches[name].entries).reduce((a, b) => caches[name].entries[a].lastAccessed < caches[name].entries[b].lastAccessed ? a : b)
delete caches[name].entries[lowestKeyVal]
}
dom(el).replaceWith(markup)
parsedTags++
}
}
} while (parsedTags)
return dom
}
// removes any remaining teddy tags from the dom before returning the parsed html to the user
function cleanupStrayTeddyTags (dom) {
let parsedTags
do {
parsedTags = 0
const tags = dom('[teddydeferredonelineconditional], include, arg, if, unless, elseif, elseunless, else, loop, cache')
if (tags.length > 0) {
for (const el of tags) {
const tagName = browser ? el.nodeName?.toLowerCase() : el.name
if (tagName === 'include' || tagName === 'arg' || tagName === 'if' || tagName === 'unless' || tagName === 'elseif' || tagName === 'elseunless' || tagName === 'else' || tagName === 'loop' || tagName === 'cache') {
dom(el).remove()
}
if (browser) el.attribs = getAttribs(el)
for (const attr in el.attribs) {
if (attr === 'true' || attr === 'false' || attr === 'teddydeferredonelineconditional' || attr.startsWith('if-')) {
dom(el).removeAttr(attr)
}
}
}
}
} while (parsedTags)
return dom
}
// escapes sensitive characters to prevent xss
const escapeHtmlEntities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
const entityKeys = Object.keys(escapeHtmlEntities)
const ekl = entityKeys.length
function escapeEntities (value) {
let escapedEntity = false
let newValue = ''
let i
let j
if (typeof value === 'object') { // cannot escape on this value
if (!value) return false // it is falsey to return false
else if (Array.isArray(value)) {
if (value.length === 0) return false // empty arrays are falsey
else return '[Array]' // print that it is an array with content in it, but do not print the contents
}
return '[Object]' // just print that it is an object, do not print the contents
} else if (value === undefined) return false // cannot escape on this value; undefined is falsey
else if (typeof value === 'boolean' || typeof value === 'number') return value // cannot escape on these values; if it's already a boolean or a number just return it
else {
// loop through value to find html entities
for (i = 0; i < value.length; i++) {
escapedEntity = false
// loop through list of html entities to escape
for (j = 0; j < ekl; j++) {
if (value[i] === entityKeys[j]) { // alter value to show escaped html entities
newValue += escapeHtmlEntities[entityKeys[j]]
escapedEntity = true
break
}
}
if (!escapedEntity) newValue += value[i]
}
}
return newValue
}
// match strings by a custom delimiter
function matchByDelimiter (input, openDelimiter, closeDelimiter) {
const stack = []
const result = []
const openLength = openDelimiter.length
const closeLength = closeDelimiter.length
for (let i = 0; i < input.length; i++) {
if (input.substring(i, i + openLength) === openDelimiter) {
stack.push(i + openLength)
i += openLength - 1
} else if (input.substring(i, i + closeLength) === closeDelimiter) {
const start = stack.pop()
if (stack.length === 0) {
result.push(input.substring(start, i))
}
i += closeLength - 1
}
}
const individualSegments = []
const regex = /{!([^{}]*)!}/g
let match
for (const segment of result) {
while ((match = regex.exec(segment)) !== null) {
individualSegments.push(match[1])
}
individualSegments.push(segment)
}
return individualSegments
}
// gets or sets an object by dot notation, e.g. thing.nestedThing.furtherNestedThing: two arguments gets, three arguments sets
function getOrSetObjectByDotNotation (obj, dotNotation, value) {
if (!obj) return false
if (!dotNotation || typeof dotNotation === 'boolean' || typeof dotNotation === 'number') return dotNotation
if (typeof dotNotation === 'string') return getOrSetObjectByDotNotation(obj, dotNotation.split('.'), value)
else if (dotNotation.length === 1 && value !== undefined) {
obj[dotNotation[0]] = value
return obj[dotNotation[0]]
} else if (dotNotation.length === 0) return obj
else if (dotNotation.length === 1) {
if (obj) {
if (browser) return caseInsensitiveLookup(obj, dotNotation[0])
else return obj[dotNotation[0]]
}
return false
} else {
if (browser) obj = caseInsensitiveLookup(obj, dotNotation[0])
else obj = obj[dotNotation[0]]
return getOrSetObjectByDotNotation(obj, dotNotation.slice(1), value)
}
function caseInsensitiveLookup (obj, key) {
if (key === 'length') return obj.length
const lowerCaseKey = key.toLowerCase()
const normalizedObj = Object.keys(obj).reduce((acc, k) => {
acc[k.toLowerCase()] = obj[k]
return acc
}, {})
return normalizedObj[lowerCaseKey]
}
}
// cheerio polyfill
function getAttribs (element) {
const attributes = element.attributes
const attributesObject = {}
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i]
attributesObject[attr.name] = attr.value
}
return attributesObject
}
// #endregion
// #region public methods
// set params to the defaults
function setDefaultParams () {
params.verbosity = 1
params.templateRoot = './'
params.maxPasses = 1000
params.emptyVarBehavior = 'display' // or 'hide'
}
// mutator method to set verbosity param. takes human-readable string argument and converts it to an integer for more efficient checks against the setting
function setVerbosity (v) {
switch (v) {
case 'none':
case 0:
v = 0
break
case 'verbose':
case 2:
v = 2
break
case 'DEBUG':
case 3:
v = 3
break
default: // concise
v = 1
}
params.verbosity = v
}
// mutator method to set template root param; must be a string
function setTemplateRoot (v) {
params.templateRoot = String(v)
}
// mutator method to set max passes param: the number of times the parser can iterate over the template
function setMaxPasses (v) {
params.maxPasses = Number(v)
}
// mutator method to set empty var behavior param: whether to display {variables} that don't resolve as text ('display') or as an empty string ('hide')
function setEmptyVarBehavior (v) {
if (v === 'hide') params.emptyVarBehavior = 'hide'
else params.emptyVarBehavior = 'display'
}
// access templates
function getTemplates () {
return templates
}
// takes in a template string and outputs a function which when given data will render out html
function compile (templateString) {
return function (model) {
return render(templateString, model)
}
}
// mutator method to cache template
function setTemplate (file, template) {
templates[file] = template
}
function setCache (params) {
if (!templateCaches[params.template]) templateCaches[params.template] = {}
if (params.key) {
templateCaches[params.template][params.key] = {
maxAge: params.maxAge || params.maxage,
maxCaches: (params.maxCaches || params.maxcaches) || 1000,
entries: {}
}
} else {
templateCaches[params.template].none = {
maxAge: params.maxAge || params.maxage,
markup: null,
created: null
}
}
}
// delete one or more cached templates
// 1 string argument deletes the whole cache at that name for template partial caches
// 2 arguments deletes just the value at that keyVal for template partial caches
// 1 object argument assumes we're clearing whole template level cache
function clearCache (name, keyVal) {
if (typeof name === 'string') {
if (keyVal) delete caches[name].entries[keyVal]
else delete caches[name]
} else if (typeof name === 'object') {
const params = name
if (params.key) delete templateCaches[params.template][params.key]
else delete templateCaches[params.template]
} else if (params.verbosity > 0) console.error('teddy: invalid params passed to clearCache.')
}
// parses a template
function render (template, model, callback) {
// ensure template is a string
if (typeof template !== 'string') {
if (params.verbosity > 1) console.warn('teddy.render attempted to render a template which is not a string.')
if (typeof callback === 'function') return callback(null, '')
else return ''
}
// ensure model is an object
if (typeof model !== 'object') {
if (params.verbosity > 1) console.warn('teddy.render was passed an invalid model.')
model = {} // allow the template to render if an invalid model is supplied, but it will have an empty model
}
// declare vars
let dom
let renderedTemplate
model._noTeddyBlocks = [] // will store code blocks exempt from teddy parsing
// express.js support
if (model.settings && model.settings.views && path) params.templateRoot = path.resolve(model.settings.views)
// remove templateRoot from template name if necessary
if (template.slice(params.templateRoot.length) === params.templateRoot) template = template.replace(params.templateRoot, '')
// whole template caching
const templateCache = templateCaches[template]
let cacheKey = null
let cacheKeyModelVal = null
if (templateCache) {
const singletonCache = templateCache.none
if (singletonCache) {
// check if the timestamp exceeds max age
if (!singletonCache.created) cacheKey = 'none'
else if (!singletonCache.maxAge && singletonCache.maxage) {
// if no max age is set, then this cache doesn't expire
if (typeof callback === 'function') return callback(null, singletonCache.markup)
else return singletonCache.markup
} else if (singletonCache.created + (singletonCache.maxAge || singletonCache.maxage) < Date.now()) cacheKey = 'none' // if yes re-render the template and cache it again