forked from BorisMoore/jsrender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsrender.js
1984 lines (1778 loc) · 68.3 KB
/
jsrender.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
/*! JsRender v1.0.0-rc.69 (Beta - Release Candidate): http://jsviews.com/#jsrender */
/*! **VERSION FOR WEB** (For NODE.JS see http://jsviews.com/download/jsrender-node.js) */
/*
* Best-of-breed templating in browser or on Node.js.
* Does not require jQuery, or HTML DOM
* Integrates with JsViews (http://jsviews.com/#jsviews)
*
* Copyright 2015, Boris Moore
* Released under the MIT License.
*/
//jshint -W018, -W041
(function(factory) {
// global var is the this object, which is window when running in the usual browser environment
var global = (0, eval)('this'), // jshint ignore:line
$ = global.jQuery;
if (typeof define === "function" && define.amd) { // AMD script loader, e.g. RequireJS
define(factory);
} else if (typeof exports === "object") { // CommonJS e.g. Browserify
module.exports = $
? factory($)
: function($) { // If no global jQuery, take optional jQuery passed as parameter: require('jsrender')(jQuery)
if ($ && !$.fn) {
throw "Provide jQuery or null";
}
return factory($);
};
} else { // Browser using plain <script> tag
factory(false);
}
} (
// factory (for jquery.views.js)
function($) {
"use strict";
//========================== Top-level vars ==========================
// global var is the this object, which is window when running in the usual browser environment
var global = (0, eval)('this'), // jshint ignore:line
setGlobals = $ === false; // Only set globals if script block in browser (not AMD and not CommonJS)
$ = $ && $.fn ? $ : global.jQuery; // $ is jQuery passed in by CommonJS loader (Browserify), or global jQuery.
var versionNumber = "v1.0.0-beta",
jsvStoreName, rTag, rTmplString, topView, $views,
//TODO tmplFnsCache = {},
$isFunction, $isArray, $templates, $converters, $helpers, $tags, $sub, $viewsSettings,
delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^",
rPath = /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
// not object helper view viewProperty pathTokens leafToken
rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*[.^]|\s*$|[^\(\[])|[)\]])([([]?))|(\s+)/g,
// lftPrn0 lftPrn bound path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space
// (left paren? followed by (path? followed by operator) or (path followed by left paren?)) or comma or apos or quot or right paren or space
isRenderCall,
rNewLine = /[ \t]*(\r\n|\n|\r)/g,
rUnescapeQuotes = /\\(['"])/g,
rEscapeQuotes = /['"\\]/g, // Escape quotes and \ character
rBuildHash = /(?:\x08|^)(onerror:)?(?:(~?)(([\w$_\.]+):)?([^\x08]+))\x08(,)?([^\x08]+)/gi,
rTestElseIf = /^if\s/,
rFirstElem = /<(\w+)[>\s]/,
rAttrEncode = /[\x00`><"'&]/g, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings
rIsHtml = /[\x00`><\"'&]/,
rHasHandlers = /^on[A-Z]|^convert(Back)?$/,
rHtmlEncode = rAttrEncode,
viewId = 0,
charEntities = {
"&": "&",
"<": "<",
">": ">",
"\x00": "�",
"'": "'",
'"': """,
"`": "`"
},
HTML = "html",
OBJECT = "object",
tmplAttr = "data-jsv-tmpl",
jsvTmpl = "jsvTmpl",
indexStr = "For #index in nested block use #getIndex().",
$render = {},
jsr = global.jsrender,
jsrToJq = jsr && $ && !$.render, // JsRender already loaded, without jQuery. but we will re-load it now to attach to jQuery
jsvStores = {
template: {
compile: compileTmpl
},
tag: {
compile: compileTag
},
helper: {},
converter: {}
};
// views object ($.views if jQuery is loaded, jsrender.views if no jQuery, e.g. in Node.js)
$views = {
jsviews: versionNumber,
settings: function(settings) {
$extend($viewsSettings, settings);
dbgMode($viewsSettings._dbgMode);
if ($viewsSettings.jsv) {
$viewsSettings.jsv();
}
},
sub: {
// subscription, e.g. JsViews integration
View: View,
Err: JsViewsError,
tmplFn: tmplFn,
parse: parseParams,
extend: $extend,
extendCtx: extendCtx,
syntaxErr: syntaxError,
onStore: {},
_ths: tagHandlersFromProps,
_tg: function() {} // Constructor for tagDef
},
map: dataMap, // If jsObservable loaded first, use that definition of dataMap
_cnvt: convertVal,
_tag: renderTag,
_err: error
};
function getDerivedMethod(baseMethod, method) {
return function() {
var ret,
tag = this,
prevBase = tag.base;
tag.base = baseMethod; // Within method call, calling this.base will call the base method
ret = method.apply(tag, arguments); // Call the method
tag.base = prevBase; // Replace this.base to be the base method of the previous call, for chained calls
return ret;
};
}
function getMethod(baseMethod, method) {
// For derived methods (or handlers declared declaratively as in {{:foo onChange=~fooChanged}} replace by a derived method, to allow using this.base(...)
// or this.baseApply(arguments) to call the base implementation. (Equivalent to this._super(...) and this._superApply(arguments) in jQuery UI)
if ($isFunction(method)) {
method = getDerivedMethod(
!baseMethod
? noop // no base method implementation, so use noop as base method
: baseMethod._d
? baseMethod // baseMethod is a derived method, so us it
: getDerivedMethod(noop, baseMethod), // baseMethod is not derived so make its base method be the noop method
method
);
method._d = 1; // Add flag that this is a derived method
}
return method;
}
function tagHandlersFromProps(tag, tagCtx) {
for (var prop in tagCtx.props) {
if (rHasHandlers.test(prop)) {
tag[prop] = getMethod(tag[prop], tagCtx.props[prop]);
// Copy over the onFoo props, convert and convertBack from tagCtx.props to tag (overrides values in tagDef).
// Note: unsupported scenario: if handlers are dynamically added ^onFoo=expression this will work, but dynamically removing will not work.
}
}
}
function retVal(val) {
return val;
}
function noop() {
return "";
}
function dbgBreak(val) {
// Usage examples: {{dbg:...}}, {{:~dbg(...)}}, {{for ... onAfterLink=~dbg}}, {{dbg .../}} etc.
// To break here, stop on caught exceptions.
try {
debugger;
throw "dbg breakpoint";
}
catch (e) {}
return this.base ? this.baseApply(arguments) : val;
}
function dbgMode(debugMode) {
$viewsSettings._dbgMode = debugMode !== false; // Pass in false to unset. Otherwise sets to true.
}
function JsViewsError(message) {
// Error exception type for JsViews/JsRender
// Override of $.views.sub.Error is possible
this.name = ($.link ? "JsViews" : "JsRender") + " Error";
this.message = message || this.name;
}
function $extend(target, source) {
var name;
for (name in source) {
target[name] = source[name];
}
return target;
}
(JsViewsError.prototype = new Error()).constructor = JsViewsError;
//========================== Top-level functions ==========================
//===================
// views.delimiters
//===================
function $viewsDelimiters(openChars, closeChars, link) {
// Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
// openChars, closeChars: opening and closing strings, each with two characters
if (this !== 0 || openChars) {
delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1;
delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0;
delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1;
linkChar = link || linkChar;
openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{"
closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}"
// Build regex with new delimiters
// tag (followed by / space or }) or cvtr+colon or html or code
rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))"
+ "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";
// make rTag available to JsViews (or other components) for parsing binding expressions
$sub.rTag = rTag + ")";
rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g");
// Default: bind tag converter colon html comment code params slash closeBlock
// /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
// rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered
// NOT to be jQuery selectors
}
return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar];
}
//=========
// View.get
//=========
function getView(inner, type) { //view.get(inner, type)
if (!type) {
// view.get(type)
type = inner;
inner = undefined;
}
var views, i, l, found,
view = this,
root = !type || type === "root";
// If type is undefined, returns root view (view under top view).
if (inner) {
// Go through views - this one, and all nested ones, depth-first - and return first one with given type.
found = view.type === type ? view : undefined;
if (!found) {
views = view.views;
if (view._.useKey) {
for (i in views) {
if (found = views[i].get(inner, type)) {
break;
}
}
} else {
for (i = 0, l = views.length; !found && i < l; i++) {
found = views[i].get(inner, type);
}
}
}
} else if (root) {
// Find root view. (view whose parent is top view)
while (view.parent.parent) {
found = view = view.parent;
}
} else {
while (view && !found) {
// Go through views - this one, and all parent ones - and return first one with given type.
found = view.type === type ? view : undefined;
view = view.parent;
}
}
return found;
}
function getNestedIndex() {
var view = this.get("item");
return view ? view.index : undefined;
}
getNestedIndex.depends = function() {
return [this.get("item"), "index"];
};
function getIndex() {
return this.index;
}
getIndex.depends = "index";
//==========
// View.hlp
//==========
function getHelper(helper) {
// Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo
var wrapped,
view = this,
ctx = view.linkCtx,
res = (view.ctx || {})[helper];
if (res === undefined && ctx && ctx.ctx) {
res = ctx.ctx[helper];
}
if (res === undefined) {
res = $helpers[helper];
}
if (res) {
if ($isFunction(res) && !res._wrp) {
// If it is of type function, and not already wrapped, we will wrap it, so if called with no this pointer it will be called with the
// view as 'this' context. If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too.
// Note that helper functions on deeper paths will have specific this pointers, from the preceding path.
// For example, ~util.foo() will have the ~util object as 'this' pointer
wrapped = function() {
return res.apply((!this || this === global) ? view : this, arguments);
};
wrapped._wrp = true;
$extend(wrapped, res); // Attach same expandos (if any) to the wrapped function
}
}
return wrapped || res;
}
//==============
// views._cnvt
//==============
function convertVal(converter, view, tagCtx, onError) {
// self is template object or linkCtx object
var tag, value,
// if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtx
boundTag = typeof tagCtx === "number" && view.tmpl.bnds[tagCtx-1],
linkCtx = view.linkCtx; // For data-link="{cvt:...}"...
if (onError !== undefined) {
tagCtx = onError = {props: {}, args: [onError]};
} else if (boundTag) {
tagCtx = boundTag(view.data, view, $views);
}
value = tagCtx.args[0];
if (converter || boundTag) {
tag = linkCtx && linkCtx.tag;
if (!tag) {
tag = $extend(new $sub._tg(), {
_: {
inline: !linkCtx,
bnd: boundTag,
unlinked: true
},
tagName: ":",
cvt: converter,
flow: true,
tagCtx: tagCtx,
});
if (linkCtx) {
linkCtx.tag = tag;
tag.linkCtx = linkCtx;
}
tagCtx.ctx = extendCtx(tagCtx.ctx, (linkCtx ? linkCtx.view : view).ctx);
}
tag._er = onError && value;
tagHandlersFromProps(tag, tagCtx);
tagCtx.view = view;
tag.ctx = tagCtx.ctx || {};
tagCtx.ctx = undefined;
// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
view._.tag = tag;
value = tag.cvtArgs(tag.convert || converter !== "true" && converter)[0]; // If there is a convertBack but no convert, converter will be "true"
// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
value = boundTag && view._.onRender
? view._.onRender(value, view, boundTag)
: value;
view._.tag = undefined;
}
return value != undefined ? value : "";
}
function convertArgs(converter) {
var tag = this,
tagCtx = tag.tagCtx,
view = tagCtx.view,
args = tagCtx.args;
converter = tag.convert || converter;
converter = converter && ("" + converter === converter
? (view.getRsc("converters", converter) || error("Unknown converter: '" + converter + "'"))
: converter);
args = !args.length && !tagCtx.index // On the opening tag with no args, bind to the current data context
? [view.data]
: converter
? args.slice() // If there is a converter, use a copy of the tagCtx.args array for rendering, and replace the args[0] in
// the copied array with the converted value. But we do not modify the value of tag.tagCtx.args[0] (the original args array)
: args; // If no converter, get the original tagCtx.args
if (converter) {
if (converter.depends) {
tag.depends = $sub.getDeps(tag.depends, tag, converter.depends, converter);
}
args[0] = converter.apply(tag, args);
}
return args;
}
//=============
// views._tag
//=============
function getResource(resourceType, itemName) {
var res, store,
view = this;
while ((res === undefined) && view) {
store = view.tmpl && view.tmpl[resourceType];
res = store && store[itemName];
view = view.parent;
}
return res || $views[resourceType][itemName];
}
function renderTag(tagName, parentView, tmpl, tagCtxs, isUpdate, onError) {
parentView = parentView || topView;
var tag, tag_, tagDef, template, tags, attr, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, callInit, mapDef, thisMap, args, props, initialTmpl, tagDataMap,
ret = "",
linkCtx = parentView.linkCtx || 0,
ctx = parentView.ctx,
parentTmpl = tmpl || parentView.tmpl,
// if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtxs
boundTag = typeof tagCtxs === "number" && parentView.tmpl.bnds[tagCtxs-1];
if (tagName._is === "tag") {
tag = tagName;
tagName = tag.tagName;
tagCtxs = tag.tagCtxs;
template = tag.template;
} else {
tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{" + tagName + "}} ");
template = tagDef.template;
}
if (onError !== undefined) {
ret += onError;
tagCtxs = onError = [{props: {}, args: []}];
} else if (boundTag) {
tagCtxs = boundTag(parentView.data, parentView, $views);
}
l = tagCtxs.length;
for (i = 0; i < l; i++) {
tagCtx = tagCtxs[i];
if (!linkCtx || !linkCtx.tag || i && !linkCtx.tag._.inline || tag._er) {
// Initialize tagCtx
// For block tags, tagCtx.tmpl is an integer > 0
if (content = tagCtx.tmpl) {
content = tagCtx.content = parentTmpl.tmpls[content - 1];
}
tagCtx.index = i;
tagCtx.tmpl = template || content; // Set the tmpl property to the content of the block tag
tagCtx.render = renderContent;
tagCtx.view = parentView;
tagCtx.ctx = extendCtx(tagCtx.ctx, ctx); // Clone and extend parentView.ctx
}
if (tmpl = tagCtx.props.tmpl) {
// If the tmpl property is overridden, set the value (when initializing, or, in case of binding: ^tmpl=..., when updating)
tmpl = "" + tmpl === tmpl // if a string
? parentView.getRsc("templates", tmpl) || $templates(tmpl)
: tmpl;
tagCtx.tmpl = tmpl;
}
if (!tag) {
// This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet
// Instantiate tag if it does not yet exist
// If the tag has not already been instantiated, we will create a new instance.
// ~tag will access the tag, even within the rendering of the template content of this tag.
// From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName
tag = new tagDef._ctr();
callInit = !!tag.init;
tag.parent = parentTag = ctx && ctx.tag;
tag.tagCtxs = tagCtxs;
tagDataMap = tag.dataMap;
if (linkCtx) {
tag._.inline = false;
linkCtx.tag = tag;
tag.linkCtx = linkCtx;
}
if (tag._.bnd = boundTag || linkCtx.fn) {
// Bound if {^{tag...}} or data-link="{tag...}"
tag._.arrVws = {};
} else if (tag.dataBoundOnly) {
error("{^{" + tagName + "}} tag must be data-bound");
}
//TODO better perf for childTags() - keep child tag.tags array, (and remove child, when disposed)
// tag.tags = [];
}
tagCtxs = tag.tagCtxs;
tagDataMap = tag.dataMap;
tagCtx.tag = tag;
if (tagDataMap && tagCtxs) {
tagCtx.map = tagCtxs[i].map; // Copy over the compiled map instance from the previous tagCtxs to the refreshed ones
}
if (!tag.flow) {
tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {};
// tags hash: tag.ctx.tags, merged with parentView.ctx.tags,
tags = tag.parents = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {};
if (parentTag) {
tags[parentTag.tagName] = parentTag;
//TODO better perf for childTags: parentTag.tags.push(tag);
}
tags[tag.tagName] = tagCtxCtx.tag = tag;
}
}
if (boundTag || linkCtx) {
// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id
parentView._.tag = tag;
}
if (!(tag._er = onError)) {
tagHandlersFromProps(tag, tagCtxs[0]);
tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...)
for (i = 0; i < l; i++) {
tagCtx = tag.tagCtx = tagCtxs[i];
props = tagCtx.props;
args = tag.cvtArgs();
if (mapDef = props.dataMap || tagDataMap) {
if (args.length || props.dataMap) {
thisMap = tagCtx.map;
if (!thisMap || thisMap.src !== args[0] || isUpdate) {
if (thisMap && thisMap.src) {
thisMap.unmap(); // only called if observable map - not when only used in JsRender, e.g. by {{props}}
}
thisMap = tagCtx.map = mapDef.map(args[0], props, undefined, !tag._.bnd);
}
args = [thisMap.tgt];
}
}
tag.ctx = tagCtx.ctx;
if (!i) {
if (callInit) {
initialTmpl = tag.template;
tag.init(tagCtx, linkCtx, tag.ctx);
callInit = undefined;
if (tag.template !== initialTmpl) {
tag._.tmpl = tag.template; // This will override the tag.template and also tagCtx.props.tmpl for all tagCtxs
}
}
if (linkCtx) {
// Set attr on linkCtx to ensure outputting to the correct target attribute.
// Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib.
linkCtx.attr = tag.attr = linkCtx.attr || tag.attr;
}
attr = tag.attr;
tag._.noVws = attr && attr !== HTML;
}
itemRet = undefined;
if (tag.render) {
itemRet = tag.render.apply(tag, args);
}
if (!args.length) {
args = [parentView]; // no arguments - get data context from view.
}
if (itemRet === undefined) {
itemRet = tagCtx.render(args.length ? args[0] : parentView, true) || (isUpdate ? undefined : "");
}
// No return value from render, and no template/content tagCtx.render(...), so return undefined
ret = ret ? ret + (itemRet || "") : itemRet; // If no rendered content, this will be undefined
}
tag.rendering = undefined;
}
tag.tagCtx = tagCtxs[0];
tag.ctx = tag.tagCtx.ctx;
if (tag._.noVws) {
if (tag._.inline) {
// inline tag with attr set to "text" will insert HTML-encoded content - as if it was element-based innerText
ret = attr === "text"
? $converters.html(ret)
: "";
}
}
return boundTag && parentView._.onRender
// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
? parentView._.onRender(ret, parentView, boundTag)
: ret;
}
//=================
// View constructor
//=================
function View(context, type, parentView, data, template, key, contentTmpl, onRender) {
// Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
var views, parentView_, tag, self_,
self = this,
isArray = type === "array";
self.content = contentTmpl;
self.views = isArray ? [] : {};
self.parent = parentView;
self.type = type || "top";
self.data = data;
self.tmpl = template;
// If the data is an array, this is an 'array view' with a views array for each child 'item view'
// If the data is not an array, this is an 'item view' with a views 'hash' object for any child nested views
// ._.useKey is non zero if is not an 'array view' (owning a data array). Use this as next key for adding to child views hash
self_ = self._ = {
key: 0,
useKey: isArray ? 0 : 1,
id: "" + viewId++,
onRender: onRender,
bnds: {}
};
self.linked = !!onRender;
if (parentView) {
views = parentView.views;
parentView_ = parentView._;
if (parentView_.useKey) {
// Parent is an 'item view'. Add this view to its views object
// self._key = is the key in the parent view hash
views[self_.key = "_" + parentView_.useKey++] = self;
self.index = indexStr;
self.getIndex = getNestedIndex;
tag = parentView_.tag;
self_.bnd = isArray && (!tag || !!tag._.bnd && tag); // For array views that are data bound for collection change events, set the
// view._.bnd property to true for top-level link() or data-link="{for}", or to the tag instance for a data-bound tag, e.g. {^{for ...}}
} else if (views.length === (self_.key = self.index = key)) { // Parent is an 'array view'. Add this view to its views array
views.push(self); // Use push when possible (better perf than splice)
} else {
views.splice(key, 0, self);
}
// If no context was passed in, use parent context
// If context was passed in, it should have been merged already with parent context
self.ctx = context || parentView.ctx;
} else {
self.ctx = context;
}
}
View.prototype = {
get: getView,
getIndex: getIndex,
getRsc: getResource,
hlp: getHelper,
_is: "view"
};
//=============
// Registration
//=============
function compileChildResources(parentTmpl) {
var storeName, resources, resourceName, resource, settings, compile, onStore;
for (storeName in jsvStores) {
settings = jsvStores[storeName];
if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) {
for (resourceName in resources) {
// compile child resource declarations (templates, tags, tags["for"] or helpers)
resource = resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, 0);
resource._is = storeName; // Only do this for compiled objects (tags, templates...)
if (resource && (onStore = $sub.onStore[storeName])) {
// e.g. JsViews integration
onStore(resourceName, resource, compile);
}
}
}
}
}
function compileTag(name, tagDef, parentTmpl) {
var tmpl, baseTag, prop,
compiledDef = new $sub._tg();
function Tag() {
var tag = this;
tag._ = {
inline: true,
unlinked: true
};
tag.tagName = name;
}
if ($isFunction(tagDef)) {
// Simple tag declared as function. No presenter instantation.
tagDef = {
depends: tagDef.depends,
render: tagDef
};
} else if ("" + tagDef === tagDef) {
tagDef = {template: tagDef};
}
if (baseTag = tagDef.baseTag) {
tagDef.flow = !!tagDef.flow; // Set flow property, so defaults to false even if baseTag has flow=true
tagDef.baseTag = baseTag = "" + baseTag === baseTag
? (parentTmpl && parentTmpl.tags[baseTag] || $tags[baseTag])
: baseTag;
compiledDef = $extend(compiledDef, baseTag);
for (prop in tagDef) {
compiledDef[prop] = getMethod(baseTag[prop], tagDef[prop]);
}
} else {
compiledDef = $extend(compiledDef, tagDef);
}
// Tag declared as object, used as the prototype for tag instantiation (control/presenter)
if ((tmpl = compiledDef.template) !== undefined) {
compiledDef.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl;
}
if (compiledDef.init !== false) {
// Set init: false on tagDef if you want to provide just a render method, or render and template, but no constuctor or prototype.
// so equivalent to setting tag to render function, except you can also provide a template.
(Tag.prototype = compiledDef).constructor = compiledDef._ctr = Tag;
}
if (parentTmpl) {
compiledDef._parentTmpl = parentTmpl;
}
return compiledDef;
}
function baseApply(args) {
// In derived method (or handler declared declaratively as in {{:foo onChange=~fooChanged}} can call base method,
// using this.baseApply(arguments) (Equivalent to this._superApply(arguments) in jQuery UI)
return this.base.apply(this, args);
}
function compileTmpl(name, tmpl, parentTmpl, options) {
// tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object
//==== nested functions ====
function lookupTemplate(value) {
// If value is of type string - treat as selector, or name of compiled template
// Return the template object, if already compiled, or the markup string
var currentName, tmpl;
if (("" + value === value) || value.nodeType > 0 && (elem = value)) {
if (!elem) {
if (/^\.\/[^\\:*?"<>]*$/.test(value)) {
// tmpl="./some/file.html"
// If the template is not named, use "./some/file.html" as name.
if (tmpl = $templates[name = name || value]) {
value = tmpl;
} else {
// BROWSER-SPECIFIC CODE (not on Node.js):
// Look for server-generated script block with id "./some/file.html"
elem = document.getElementById(value);
}
} else if ($.fn && !rTmplString.test(value)) {
try {
elem = $(document).find(value)[0]; // if jQuery is loaded, test for selector returning elements, and get first element
} catch (e) {}
}// END BROWSER-SPECIFIC CODE
} //BROWSER-SPECIFIC CODE
if (elem) {
// Generally this is a script element.
// However we allow it to be any element, so you can for example take the content of a div,
// use it as a template, and replace it by the same content rendered against data.
// e.g. for linking the content of a div to a container, and using the initial content as template:
// $.link("#content", model, {tmpl: "#content"});
if (options) {
// We will compile a new template using the markup in the script element
value = elem.innerHTML;
} else {
// We will cache a single copy of the compiled template, and associate it with the name
// (renaming from a previous name if there was one).
currentName = elem.getAttribute(tmplAttr);
if (currentName) {
if (currentName !== jsvTmpl) {
value = $templates[currentName];
delete $templates[currentName];
} else if ($.fn) {
value = $.data(elem)[jsvTmpl];
}
} else {
name = name || ($.fn ? jsvTmpl : value);
value = compileTmpl(name, elem.innerHTML, parentTmpl, options);
}
value.tmplName = name = name || currentName;
if (name !== jsvTmpl) {
$templates[name] = value;
}
elem.setAttribute(tmplAttr, name);
if ($.fn) {
$.data(elem, jsvTmpl, value);
}
}
} // END BROWSER-SPECIFIC CODE
elem = undefined;
} else if (!value.fn) {
value = undefined;
// If value is not a string. HTML element, or compiled template, return undefined
}
return value;
}
var elem, compiledTmpl,
tmplOrMarkup = tmpl = tmpl || "";
//==== Compile the template ====
if (options === 0) {
options = undefined;
tmplOrMarkup = lookupTemplate(tmplOrMarkup); // Top-level compile so do a template lookup
}
// If options, then this was already compiled from a (script) element template declaration.
// If not, then if tmpl is a template object, use it for options
options = options || (tmpl.markup ? tmpl : {});
options.tmplName = name;
if (parentTmpl) {
options._parentTmpl = parentTmpl;
}
// If tmpl is not a markup string or a selector string, then it must be a template object
// In that case, get it from the markup property of the object
if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = lookupTemplate(tmpl.markup))) {
if (tmplOrMarkup.fn) {
// If the string references a compiled template object, need to recompile to merge any modified options
tmplOrMarkup = tmplOrMarkup.markup;
}
}
if (tmplOrMarkup !== undefined) {
if (tmplOrMarkup.fn || tmpl.fn) {
// tmpl is already compiled, so use it
if (tmplOrMarkup.fn) {
compiledTmpl = tmplOrMarkup;
}
} else {
// tmplOrMarkup is a markup string, not a compiled template
// Create template object
tmpl = tmplObject(tmplOrMarkup, options);
// Compile to AST and then to compiled function
tmplFn(tmplOrMarkup.replace(rEscapeQuotes, "\\$&"), tmpl);
}
if (!compiledTmpl) {
compileChildResources(options);
compiledTmpl = $extend(function() {
return tmpl.render.apply(tmpl, arguments);
}, tmpl);
}
if (name && !parentTmpl && name !== jsvTmpl) {
$render[name] = compiledTmpl;
}
return compiledTmpl;
}
}
//==== /end of function compileTmpl ====
function dataMap(mapDef) {
function Map(source, options) {
this.tgt = mapDef.getTgt(source, options);
}
if ($isFunction(mapDef)) {
// Simple map declared as function
mapDef = {
getTgt: mapDef
};
}
if (mapDef.baseMap) {
mapDef = $extend($extend({}, mapDef.baseMap), mapDef);
}
mapDef.map = function(source, options) {
return new Map(source, options);
};
return mapDef;
}
function tmplObject(markup, options) {
// Template object constructor
var htmlTag,
wrapMap = $viewsSettings.wrapMap || {}, // Only used in JsViews. Otherwise empty: {}
tmpl = $extend(
{
tmpls: [],
links: {}, // Compiled functions for link expressions
bnds: [],
_is: "template",
render: renderContent
},
options
);
tmpl.markup = markup;
if (!options.htmlTag) {
// Set tmpl.tag to the top-level HTML tag used in the template, if any...
htmlTag = rFirstElem.exec(markup);
tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : "";
}
htmlTag = wrapMap[tmpl.htmlTag];
if (htmlTag && htmlTag !== wrapMap.div) {
// When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content').
// Currently not trimmed for <li> tag. (Not worth adding perf cost)
tmpl.markup = $.trim(tmpl.markup);
}
return tmpl;
}
function registerStore(storeName, storeSettings) {
function theStore(name, item, parentTmpl) {
// The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags
// For store of name 'thing', Call as:
// $.views.things(items[, parentTmpl]),
// or $.views.things(name, item[, parentTmpl])
var onStore, compile, itemName, thisStore;
if (name && typeof name === OBJECT && !name.nodeType && !name.markup && !name.getTgt) {
// Call to $.views.things(items[, parentTmpl]),
// Adding items to the store
// If name is a hash, then item is parentTmpl. Iterate over hash and call store for key.
for (itemName in name) {
theStore(itemName, name[itemName], item);
}
return $views;
}
// Adding a single unnamed item to the store
if (item === undefined) {
item = name;
name = undefined;
}
if (name && "" + name !== name) { // name must be a string
parentTmpl = item;
item = name;
name = undefined;
}
thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore;
compile = storeSettings.compile;
if (item === null) {
// If item is null, delete this entry
if (name) {
delete thisStore[name];
}
} else {
item = compile ? compile(name, item, parentTmpl, 0) : item;
if (name) {
thisStore[name] = item;
}
}
if (compile && item) {
item._is = storeName; // Only do this for compiled objects (tags, templates...)
}
if (item && (onStore = $sub.onStore[storeName])) {
// e.g. JsViews integration
onStore(name, item, compile);
}
return item;
}
var storeNames = storeName + "s";
$views[storeNames] = theStore;
}
//==============
// renderContent
//==============
function renderContent(data, context, noIteration, parentView, key, onRender) {