forked from BorisMoore/jsviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsrender.js
3021 lines (2745 loc) · 102 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.13: 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 2021, Boris Moore
* Released under the MIT License.
*/
//jshint -W018, -W041, -W120
(function(factory, global) {
// global var is the this object, which is window when running in the usual browser environment
var $ = global.jQuery;
if (typeof exports === "object") { // CommonJS e.g. Browserify
module.exports = $
? factory(global, $)
: function($) { // If no global jQuery, take optional jQuery passed as parameter: require('jsrender')(jQuery)
if ($ && !$.fn) {
throw "Provide jQuery or null";
}
return factory(global, $);
};
} else if (typeof define === "function" && define.amd) { // AMD script loader, e.g. RequireJS
define(function() {
return factory(global);
});
} else { // Browser using plain <script> tag
factory(global, false);
}
} (
// factory (for jsrender.js)
function(global, $) {
"use strict";
//========================== Top-level vars ==========================
// global var is the this object, which is window when running in the usual browser environment
var 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.13",
jsvStoreName, rTag, rTmplString, topView, $views, $expando,
_ocp = "_ocp", // Observable contextual parameter
$isFunction, $isArray, $templates, $converters, $helpers, $tags, $sub, $subSettings, $subSettingsAdvanced, $viewsSettings,
delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar, setting, baseOnError,
isRenderCall,
rNewLine = /[ \t]*(\r\n|\n|\r)/g,
rUnescapeQuotes = /\\(['"\\])/g, // Unescape quotes and trim
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)?$/,
rWrappedInViewMarker = /^\#\d+_`[\s\S]*\/\d+_`$/,
rHtmlEncode = rAttrEncode,
rDataEncode = /[&<>]/g,
rDataUnencode = /&(amp|gt|lt);/g,
rBracketQuote = /\[['"]?|['"]?\]/g,
viewId = 0,
charEntities = {
"&": "&",
"<": "<",
">": ">",
"\x00": "�",
"'": "'",
'"': """,
"`": "`",
"=": "="
},
charsFromEntities = {
amp: "&",
gt: ">",
lt: "<"
},
HTML = "html",
STRING = "string",
OBJECT = "object",
tmplAttr = "data-jsv-tmpl",
jsvTmpl = "jsvTmpl",
indexStr = "For #index in nested block use #getIndex().",
cpFnStore = {}, // Compiled furnctions for computed values in template expressions (properties, methods, helpers)
$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
},
viewModel: {
compile: compileViewModel
},
helper: {},
converter: {}
};
// views object ($.views if jQuery is loaded, jsrender.views if no jQuery, e.g. in Node.js)
$views = {
jsviews: versionNumber,
sub: {
// subscription, e.g. JsViews integration
rPath: /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
// not object helper view viewProperty pathTokens leafToken
rPrm: /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(~?[\w$.^]+)?\s*((\+\+|--)|\+|-|~(?![\w$])|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?(@)?[#~]?[\w$.^]+)([([])?)|(,\s*)|(?:(\()\s*)?\\?(?:(')|("))|(?:\s*(([)\]])(?=[.^]|\s*$|[^([])|[)\]])([([]?))|(\s+)/g,
// lftPrn0 lftPrn bound path operator err eq path2 late prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space
View: View,
Err: JsViewsError,
tmplFn: tmplFn,
parse: parseParams,
extend: $extend,
extendCtx: extendCtx,
syntaxErr: syntaxError,
onStore: {
template: function(name, item) {
if (item === null) {
delete $render[name];
} else if (name) {
$render[name] = item;
}
}
},
addSetting: addSetting,
settings: {
allowCode: false
},
advSet: noop, // Update advanced settings
_thp: tagHandlersFromProps,
_gm: getMethod,
_tg: function() {}, // Constructor for tagDef
_cnvt: convertVal,
_tag: renderTag,
_er: error,
_err: onRenderError,
_cp: retVal, // Get observable contextual parameters (or properties) ~foo=expr. In JsRender, simply returns val.
_sq: function(token) {
if (token === "constructor") {
syntaxError("");
}
return token;
}
},
settings: {
delimiters: $viewsDelimiters,
advanced: function(value) {
return value
? (
$extend($subSettingsAdvanced, value),
$sub.advSet(),
$viewsSettings
)
: $subSettingsAdvanced;
}
},
map: dataMap // If jsObservable loaded first, use that definition of dataMap
};
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 use it
: getDerivedMethod(noop, baseMethod), // baseMethod is not derived so make its base method be the noop method
method
);
method._d = (baseMethod && baseMethod._d || 0) + 1; // Add flag for derived method (incremented for derived of derived...)
}
return method;
}
function tagHandlersFromProps(tag, tagCtx) {
var prop,
props = tagCtx.props;
for (prop in props) {
if (rHasHandlers.test(prop) && !(tag[prop] && tag[prop].fix)) { // Don't override handlers with fix expando (used in datepicker and spinner)
tag[prop] = prop !== "convert" ? getMethod(tag.constructor.prototype[prop], props[prop]) : 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(...)}}, {{dbg .../}}, {^{for ... onAfterLink=~dbg}} etc.
try {
console.log("JsRender dbg breakpoint: " + val);
throw "dbg breakpoint"; // To break here, stop on caught exceptions.
}
catch (e) {}
return this.base ? this.baseApply(arguments) : val;
}
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) {
if (target) {
for (var name in source) {
target[name] = source[name];
}
return target;
}
}
(JsViewsError.prototype = new Error()).constructor = JsViewsError;
//========================== Top-level functions ==========================
//===================
// views.delimiters
//===================
/**
* Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
* openChars, closeChars: opening and closing strings, each with two characters
* $.views.settings.delimiters(...)
*
* @param {string} openChars
* @param {string} [closeChars]
* @param {string} [link]
* @returns {Settings}
*
* Get delimiters
* delimsArray = $.views.settings.delimiters()
*
* @returns {string[]}
*/
function $viewsDelimiters(openChars, closeChars, link) {
if (!openChars) {
return $subSettings.delimiters;
}
if ($isArray(openChars)) {
return $viewsDelimiters.apply($views, openChars);
}
linkChar = link ? link[0] : linkChar;
if (!/^(\W|_){5}$/.test(openChars + closeChars + linkChar)) {
error("Invalid delimiters"); // Must be non-word characters, and openChars and closeChars must each be length 2
}
delimOpenChar0 = openChars[0];
delimOpenChar1 = openChars[1];
delimCloseChar0 = closeChars[0];
delimCloseChar1 = closeChars[1];
$subSettings.delimiters = [delimOpenChar0 + delimOpenChar1, delimCloseChar0 + delimCloseChar1, linkChar];
// Escape the characters - since they could be regex special characters
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] followed by space+params then convertBack?
rTag = "(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(\\w+)?(:)|(>)|(\\*))\\s*((?:[^\\"
+ delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";
// Make rTag available to JsViews (or other components) for parsing binding expressions
$sub.rTag = "(?:" + rTag + ")";
// { ^? { tag+params slash? or closingTag or comment
rTag = new RegExp("(?:" + openChars + rTag + "(\\/)?|\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1 + "(?:(?:\\/(\\w+))\\s*|!--[\\s\\S]*?--))" + closeChars, "g");
// Default: bind tagName cvt cln html code params slash bind2 closeBlk comment
// /(?:{(\^)?{(?:(\w+(?=[\/\s}]))|(\w+)?(:)|(>)|(\*))\s*((?:[^}]|}(?!}))*?)(\/)?|{(\^)?{(?:(?:\/(\w+))\s*|!--[\s\S]*?--))}}
$sub.rTmpl = new RegExp("^\\s|\\s$|<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
// $sub.rTmpl looks for initial or final white space, html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}.
// Each of these strings are considered NOT to be jQuery selectors
return $viewsSettings;
}
//=========
// View.get
//=========
function getView(inner, type) { //view.get(inner, type)
if (!type && inner !== true) {
// view.get(type)
type = inner;
inner = undefined;
}
var views, i, l, found,
view = this,
root = type === "root";
// view.get("root") returns view.root, view.get() returns view.parent, view.get(true) returns view.views[0].
if (inner) {
// Go through views - this one, and all nested ones, depth-first - and return first one with given type.
// If type is undefined, i.e. view.get(true), return first child view.
found = type && view.type === type && view;
if (!found) {
views = view.views;
if (view._.useKey) {
for (i in views) {
if (found = type ? views[i].get(inner, type) : views[i]) {
break;
}
}
} else {
for (i = 0, l = views.length; !found && i < l; i++) {
found = type ? views[i].get(inner, type) : views[i];
}
}
}
} else if (root) {
// Find root view. (view whose parent is top view)
found = view.root;
} else if (type) {
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;
}
} else {
found = view.parent;
}
return found || undefined;
}
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.ctxPrm, etc.
//==================
/* Internal private: view._getOb() */
function getPathObject(ob, path, ltOb, fn) {
// Iterate through path to late paths: @a.b.c paths
// Return "" (or noop if leaf is a function @a.b.c(...) ) if intermediate object not yet available
var prevOb, tokens, l,
i = 0;
if (ltOb === 1) {
fn = 1;
ltOb = undefined;
}
// Paths like ^a^b^c or ~^a^b^c will not throw if an object in path is undefined.
if (path) {
tokens = path.split(".");
l = tokens.length;
for (; ob && i < l; i++) {
prevOb = ob;
ob = tokens[i] ? ob[tokens[i]] : ob;
}
}
if (ltOb) {
ltOb.lt = ltOb.lt || i<l; // If i < l there was an object in the path not yet available
}
return ob === undefined
? fn ? noop : ""
: fn ? function() {
return ob.apply(prevOb, arguments);
} : ob;
}
function contextParameter(key, value, get) {
// Helper method called as view.ctxPrm(key) for helpers or template parameters ~foo - from compiled template or from context callback
var wrapped, deps, res, obsCtxPrm, tagElse, callView, newRes,
storeView = this,
isUpdate = !isRenderCall && arguments.length > 1,
store = storeView.ctx;
if (key) {
if (!storeView._) { // tagCtx.ctxPrm() call
tagElse = storeView.index;
storeView = storeView.tag;
}
callView = storeView;
if (store && store.hasOwnProperty(key) || (store = $helpers).hasOwnProperty(key)) {
res = store[key];
if (key === "tag" || key === "tagCtx" || key === "root" || key === "parentTags") {
return res;
}
} else {
store = undefined;
}
if (!isRenderCall && storeView.tagCtx || storeView.linked) { // Data-linked view, or tag instance
if (!res || !res._cxp) {
// Not a contextual parameter
// Set storeView to tag (if this is a tag.ctxPrm() call) or to root view ("data" view of linked template)
storeView = storeView.tagCtx || $isFunction(res)
? storeView // Is a tag, not a view, or is a computed contextual parameter, so scope to the callView, no the 'scope view'
: (storeView = storeView.scope || storeView,
!storeView.isTop && storeView.ctx.tag // If this view is in a tag, set storeView to the tag
|| storeView);
if (res !== undefined && storeView.tagCtx) {
// If storeView is a tag, but the contextual parameter has been set at at higher level (e.g. helpers)...
storeView = storeView.tagCtx.view.scope; // then move storeView to the outer level (scope of tag container view)
}
store = storeView._ocps;
res = store && store.hasOwnProperty(key) && store[key] || res;
if (!(res && res._cxp) && (get || isUpdate)) {
// Create observable contextual parameter
(store || (storeView._ocps = storeView._ocps || {}))[key]
= res
= [{
_ocp: res, // The observable contextual parameter value
_vw: callView,
_key: key
}];
res._cxp = {
path: _ocp,
ind: 0,
updateValue: function(val, path) {
$.observable(res[0]).setProperty(_ocp, val); // Set the value (res[0]._ocp)
return this;
}
};
}
}
if (obsCtxPrm = res && res._cxp) {
// If this helper resource is an observable contextual parameter
if (arguments.length > 2) {
deps = res[1] ? $sub._ceo(res[1].deps) : [_ocp]; // fn deps (with any exprObs cloned using $sub._ceo)
deps.unshift(res[0]); // view
deps._cxp = obsCtxPrm;
// In a context callback for a contextual param, we set get = true, to get ctxPrm [view, dependencies...] array - needed for observe call
return deps;
}
tagElse = obsCtxPrm.tagElse;
newRes = res[1] // linkFn for compiled expression
? obsCtxPrm.tag && obsCtxPrm.tag.cvtArgs
? obsCtxPrm.tag.cvtArgs(tagElse, 1)[obsCtxPrm.ind] // = tag.bndArgs() - for tag contextual parameter
: res[1](res[0].data, res[0], $sub) // = fn(data, view, $sub) for compiled binding expression
: res[0]._ocp; // Observable contextual parameter (uninitialized, or initialized as static expression, so no path dependencies)
if (isUpdate) {
$sub._ucp(key, value, storeView, obsCtxPrm); // Update observable contextual parameter
return storeView;
}
res = newRes;
}
}
if (res && $isFunction(res)) {
// If a helper is of type function 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) ? callView : this, arguments);
};
$extend(wrapped, res); // Attach same expandos (if any) to the wrapped function
}
return wrapped || res;
}
}
/* Internal private: view._getTmpl() */
function getTemplate(tmpl) {
return tmpl && (tmpl.fn
? tmpl
: this.getRsc("templates", tmpl) || $templates(tmpl)); // not yet compiled
}
//==============
// views._cnvt
//==============
function convertVal(converter, view, tagCtx, onError) {
// Called from compiled template code for {{:}}
// self is template object or linkCtx object
var tag, linkCtx, value, argsLen, bindTo,
// 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];
if (onError === undefined && boundTag && boundTag._lr) { // lateRender
onError = "";
}
if (onError !== undefined) {
tagCtx = onError = {props: {}, args: [onError]};
} else if (boundTag) {
tagCtx = boundTag(view.data, view, $sub);
}
boundTag = boundTag._bd && boundTag;
if (converter || boundTag) {
linkCtx = view._lc; // For data-link="{cvt:...}"... See onDataLinkedTagChange
tag = linkCtx && linkCtx.tag;
tagCtx.view = view;
if (!tag) {
tag = $extend(new $sub._tg(), {
_: {
bnd: boundTag,
unlinked: true,
lt: tagCtx.lt // If a late path @some.path has not returned @some object, mark tag as late
},
inline: !linkCtx,
tagName: ":",
convert: converter,
onArrayChange: true,
flow: true,
tagCtx: tagCtx,
tagCtxs: [tagCtx],
_is: "tag"
});
argsLen = tagCtx.args.length;
if (argsLen>1) {
bindTo = tag.bindTo = [];
while (argsLen--) {
bindTo.unshift(argsLen); // Bind to all the arguments - generate bindTo array: [0,1,2...]
}
}
if (linkCtx) {
linkCtx.tag = tag;
tag.linkCtx = linkCtx;
}
tagCtx.ctx = extendCtx(tagCtx.ctx, (linkCtx ? linkCtx.view : view).ctx);
tagHandlersFromProps(tag, tagCtx);
}
tag._er = onError && value;
tag.ctx = tagCtx.ctx || tag.ctx || {};
tagCtx.ctx = undefined;
value = tag.cvtArgs()[0]; // If there is a convertBack but no convert, converter will be "true"
tag._er = onError && value;
} else {
value = tagCtx.args[0];
}
// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
value = boundTag && view._.onRender
? view._.onRender(value, view, tag)
: value;
return value != undefined ? value : "";
}
function convertArgs(tagElse, bound) { // tag.cvtArgs() or tag.cvtArgs(tagElse?, true?)
var l, key, boundArgs, args, bindFrom, tag, converter,
tagCtx = this;
if (tagCtx.tagName) {
tag = tagCtx;
tagCtx = (tag.tagCtxs || [tagCtx])[tagElse||0];
if (!tagCtx) {
return;
}
} else {
tag = tagCtx.tag;
}
bindFrom = tag.bindFrom;
args = tagCtx.args;
if ((converter = tag.convert) && typeof converter === STRING) {
converter = converter === "true"
? undefined
: (tagCtx.view.getRsc("converters", converter) || error("Unknown converter: '" + converter + "'"));
}
if (converter && !bound) { // If there is a converter, use a copy of the tagCtx.args array for rendering, and replace the args[0] in
args = args.slice(); // the copied array with the converted value. But we do not modify the value of tag.tagCtx.args[0] (the original args array)
}
if (bindFrom) { // Get the values of the boundArgs
boundArgs = [];
l = bindFrom.length;
while (l--) {
key = bindFrom[l];
boundArgs.unshift(argOrProp(tagCtx, key));
}
if (bound) {
args = boundArgs; // Call to bndArgs() - returns the boundArgs
}
}
if (converter) {
converter = converter.apply(tag, boundArgs || args);
if (converter === undefined) {
return args; // Returning undefined from a converter is equivalent to not having a converter.
}
bindFrom = bindFrom || [0];
l = bindFrom.length;
if (!$isArray(converter) || (converter.arg0 !== false && (l === 1 || converter.length !== l || converter.arg0))) {
converter = [converter]; // Returning converter as first arg, even if converter value is an array
bindFrom = [0];
l = 1;
}
if (bound) { // Call to bndArgs() - so apply converter to all boundArgs
args = converter; // The array of values returned from the converter
} else { // Call to cvtArgs()
while (l--) {
key = bindFrom[l];
if (+key === key) {
args[key] = converter[l];
}
}
}
}
return args;
}
function argOrProp(context, key) {
context = context[+key === key ? "args" : "props"];
return context && context[key];
}
function convertBoundArgs(tagElse) { // tag.bndArgs()
return this.cvtArgs(tagElse, 1);
}
//=============
// views.tag
//=============
/* view.getRsc() */
function getResource(resourceType, itemName) {
var res, store,
view = this;
if (typeof itemName === STRING) {
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) {
function bindToOrBindFrom(type) {
var bindArray = tag[type];
if (bindArray !== undefined) {
bindArray = $isArray(bindArray) ? bindArray : [bindArray];
m = bindArray.length;
while (m--) {
key = bindArray[m];
if (!isNaN(parseInt(key))) {
bindArray[m] = parseInt(key); // Convert "0" to 0, etc.
}
}
}
return bindArray || [0];
}
parentView = parentView || topView;
var tag, tagDef, template, tags, attr, parentTag, l, m, n, itemRet, tagCtx, tagCtxCtx, ctxPrm, bindTo, bindFrom, initVal,
content, callInit, mapDef, thisMap, args, bdArgs, props, tagDataMap, contentCtx, key, bindFromLength, bindToLength, linkedElement, defaultCtx,
i = 0,
ret = "",
linkCtx = parentView._lc || false, // For data-link="{myTag...}"... See onDataLinkedTagChange
ctx = parentView.ctx,
parentTmpl = tmpl || parentView.tmpl,
// If tagCtxs 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 && boundTag && (boundTag._lr = (tagDef.lateRender && boundTag._lr!== false || boundTag._lr))) {
onError = ""; // If lateRender, set temporary onError, to skip initial rendering (and render just "")
}
if (onError !== undefined) {
ret += onError;
tagCtxs = onError = [{props: {}, args: [], params: {props:{}}}];
} else if (boundTag) {
tagCtxs = boundTag(parentView.data, parentView, $sub);
}
l = tagCtxs.length;
for (; i < l; i++) {
tagCtx = tagCtxs[i];
content = tagCtx.tmpl;
if (!linkCtx || !linkCtx.tag || i && !linkCtx.tag.inline || tag._er || content && +content===content) {
// Initialize tagCtx
// For block tags, tagCtx.tmpl is an integer > 0
if (content && parentTmpl.tmpls) {
tagCtx.tmpl = tagCtx.content = parentTmpl.tmpls[content - 1]; // Set the tmpl property to the content of the block tag
}
tagCtx.index = i;
tagCtx.ctxPrm = contextParameter;
tagCtx.render = renderContent;
tagCtx.cvtArgs = convertArgs;
tagCtx.bndArgs = convertBoundArgs;
tagCtx.view = parentView;
tagCtx.ctx = extendCtx(extendCtx(tagCtx.ctx, tagDef && tagDef.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)
tagCtx.tmpl = parentView._getTmpl(tmpl);
tagCtx.content = tagCtx.content || tagCtx.tmpl;
}
if (!tag) {
// This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet
// 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;
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._.ths = tagCtx.params.props["this"]; // Tag has a this=expr binding, to get javascript reference to tag instance
tag._.lt = tagCtxs.lt; // If a late path @some.path has not returned @some object, mark tag as late
tag._.arrVws = {};
} else if (tag.dataBoundOnly) {
error(tagName + " must be data-bound:\n{^{" + tagName + "}}");
}
//TODO better perf for childTags() - keep child tag.tags array, (and remove child, when disposed)
// tag.tags = [];
} else if (linkCtx && linkCtx.fn._lr) {
callInit = !!tag.init;
}
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;
tagCtxCtx.tagCtx = tagCtx;
}
}
if (!(tag._er = onError)) {
tagHandlersFromProps(tag, tagCtxs[0]);
tag.rendering = {rndr: tag.rendering}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...)
for (i = 0; i < l; i++) { // Iterate tagCtx for each {{else}} block
tagCtx = tag.tagCtx = tagCtxs[i];
props = tagCtx.props;
tag.ctx = tagCtx.ctx;
if (!i) {
if (callInit) {
tag.init(tagCtx, linkCtx, tag.ctx);
callInit = undefined;
}
if (!tagCtx.args.length && tagCtx.argDefault !== false && tag.argDefault !== false) {
tagCtx.args = args = [tagCtx.view.data]; // Missing first arg defaults to the current data context
tagCtx.params.args = ["#data"];
}
bindTo = bindToOrBindFrom("bindTo");
if (tag.bindTo !== undefined) {
tag.bindTo = bindTo;
}
if (tag.bindFrom !== undefined) {
tag.bindFrom = bindToOrBindFrom("bindFrom");
} else if (tag.bindTo) {
tag.bindFrom = tag.bindTo = bindTo;
}
bindFrom = tag.bindFrom || bindTo;
bindToLength = bindTo.length;
bindFromLength = bindFrom.length;
if (tag._.bnd && (linkedElement = tag.linkedElement)) {
tag.linkedElement = linkedElement = $isArray(linkedElement) ? linkedElement: [linkedElement];
if (bindToLength !== linkedElement.length) {
error("linkedElement not same length as bindTo");
}
}
if (linkedElement = tag.linkedCtxParam) {
tag.linkedCtxParam = linkedElement = $isArray(linkedElement) ? linkedElement: [linkedElement];
if (bindFromLength !== linkedElement.length) {
error("linkedCtxParam not same length as bindFrom/bindTo");
}
}
if (bindFrom) {
tag._.fromIndex = {}; // Hash of bindFrom index which has same path value as bindTo index. fromIndex = tag._.fromIndex[toIndex]
tag._.toIndex = {}; // Hash of bindFrom index which has same path value as bindTo index. fromIndex = tag._.fromIndex[toIndex]
n = bindFromLength;
while (n--) {
key = bindFrom[n];
m = bindToLength;
while (m--) {
if (key === bindTo[m]) {
tag._.fromIndex[m] = n;
tag._.toIndex[n] = m;
}
}
}
}
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 || linkCtx._dfAt;
}
attr = tag.attr;
tag._.noVws = attr && attr !== HTML;
}
args = tag.cvtArgs(i);
if (tag.linkedCtxParam) {
bdArgs = tag.cvtArgs(i, 1);
m = bindFromLength;
defaultCtx = tag.constructor.prototype.ctx;
while (m--) {
if (ctxPrm = tag.linkedCtxParam[m]) {
key = bindFrom[m];
initVal = bdArgs[m];
// Create tag contextual parameter
tagCtx.ctx[ctxPrm] = $sub._cp(
defaultCtx && initVal === undefined ? defaultCtx[ctxPrm]: initVal,
initVal !== undefined && argOrProp(tagCtx.params, key),
tagCtx.view,
tag._.bnd && {tag: tag, cvt: tag.convert, ind: m, tagElse: i}
);
}
}
}
if ((mapDef = props.dataMap || tagDataMap) && (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}}
}
mapDef.map(args[0], tagCtx, thisMap, !tag._.bnd);
thisMap = tagCtx.map;
}
args = [thisMap.tgt];
}
itemRet = undefined;
if (tag.render) {
itemRet = tag.render.apply(tag, args);
if (parentView.linked && itemRet && !rWrappedInViewMarker.test(itemRet)) {
// When a tag renders content from the render method, with data linking then we need to wrap with view markers, if absent,
// to provide a contentView for the tag, which will correctly dispose bindings if deleted. The 'tmpl' for this view will
// be a dumbed-down template which will always return the itemRet string (no matter what the data is). The itemRet string
// is not compiled as template markup, so can include "{{" or "}}" without triggering syntax errors
tmpl = { // 'Dumbed-down' template which always renders 'static' itemRet string
links: []
};
tmpl.render = tmpl.fn = function() {
return itemRet;
};
itemRet = renderWithViews(tmpl, parentView.data, undefined, true, parentView, undefined, undefined, tag);
}
}
if (!args.length) {
args = [parentView]; // no arguments - (e.g. {{else}}) get data context from view.
}
if (itemRet === undefined) {
contentCtx = args[0]; // Default data context for wrapped block content is the first argument
if (tag.contentCtx) { // Set tag.contentCtx to true, to inherit parent context, or to a function to provide alternate context.
contentCtx = tag.contentCtx === true ? parentView : tag.contentCtx(contentCtx);
}
itemRet = tagCtx.render(contentCtx, true) || (isUpdate ? undefined : "");
}
ret = ret
? ret + (itemRet || "")
: itemRet !== undefined
? "" + itemRet
: undefined; // If no return value from render, and no template/content tagCtx.render(...), return undefined
}
tag.rendering = tag.rendering.rndr; // Remove tag.rendering object (if this is outermost render call. (In case of nested calls)
}
tag.tagCtx = tagCtxs[0];
tag.ctx = tag.tagCtx.ctx;
if (tag._.noVws && 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, tag)
: ret;
}
//=================
// View constructor
//=================
function View(context, type, parentView, data, template, key, onRender, contentTmpl) {
// Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
var views, parentView_, tag, self_,
self = this,
isArray = type === "array";
// 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
self.content = contentTmpl;
self.views = isArray ? [] : {};
self.data = data;
self.tmpl = template;
self_ = self._ = {
key: 0,
// ._.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
useKey: isArray ? 0 : 1,
id: "" + viewId++,
onRender: onRender,
bnds: {}
};
self.linked = !!onRender;
self.type = type || "top";
if (type) {
self.cache = {_ct: $subSettings._cchCt}; // Used for caching results of computed properties and helpers (view.getCache)
}
if (!parentView || parentView.type === "top") {
(self.ctx = context || {}).root = self.data;
}
if (self.parent = parentView) {
self.root = parentView.root || self; // view whose parent is top view
views = parentView.views;
parentView_ = parentView._;
self.isTop = parentView_.scp; // Is top content view of a link("#container", ...) call
self.scope = (!context.tag || context.tag === parentView.ctx.tag) && !self.isTop && parentView.scope || self;
// Scope for contextParams - closest non flow tag ancestor or root view
if (parentView_.useKey) {
// Parent is not an 'array 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;
} else if (views.length === (self_.key = self.index = key)) { // Parent is an 'array view'. Add this view to its views array
views.push(self); // Adding to end of views array. (Using push when possible - better perf than splice)
} else {
views.splice(key, 0, self); // Inserting in views array
}
// 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 if (type) {
self.root = self; // view whose parent is top view
}
}