jsrender-rails 1.0b30 → 1.0b30.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1457 @@
1
+ /*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */
2
+ /*
3
+ * Optimized version of jQuery Templates, for rendering to string.
4
+ * Does not require jQuery, or HTML DOM
5
+ * Integrates with JsViews (http://github.com/BorisMoore/jsviews)
6
+ * Copyright 2013, Boris Moore
7
+ * Released under the MIT License.
8
+ */
9
+ // informal pre beta commit counter: 30 (Beta Candidate)
10
+
11
+ (function(global, jQuery, undefined) {
12
+ // global is the this object, which is window when running in the usual browser environment.
13
+ "use strict";
14
+
15
+ if (jQuery && jQuery.views || global.jsviews) { return; } // JsRender is already loaded
16
+
17
+ //========================== Top-level vars ==========================
18
+
19
+ var versionNumber = "v1.0pre",
20
+
21
+ $, jsvStoreName, rTag, rTmplString,
22
+ //TODO tmplFnsCache = {},
23
+ delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^",
24
+
25
+ rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
26
+ // object helper view viewProperty pathTokens leafToken
27
+
28
+ rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*((\))(?=\s*\.|\s*\^)|\)|\])([([]?))|(\s+)/g,
29
+ // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space
30
+ // (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
31
+
32
+ rNewLine = /\s*\n\s*/g,
33
+ rUnescapeQuotes = /\\(['"])/g,
34
+ // escape quotes and \ character
35
+ rEscapeQuotes = /([\\'"])/g,
36
+ rBuildHash = /\x08(~)?([^\x08]+)\x08/g,
37
+ rTestElseIf = /^if\s/,
38
+ rFirstElem = /<(\w+)[>\s]/,
39
+ rPrevElem = /<(\w+)[^>\/]*>[^>]*$/,
40
+ rAttrEncode = /[<"'&]/g,
41
+ rHtmlEncode = /[><"'&]/g,
42
+ autoTmplName = 0,
43
+ viewId = 0,
44
+ charEntities = {
45
+ "&": "&amp;",
46
+ "<": "&lt;",
47
+ ">": "&gt;",
48
+ "\x00": "&#0;",
49
+ "'": "&#39;",
50
+ '"': "&#34;"
51
+ },
52
+ tmplAttr = "data-jsv-tmpl",
53
+ slice = [].slice,
54
+
55
+ $render = {},
56
+ jsvStores = {
57
+ template: {
58
+ compile: compileTmpl
59
+ },
60
+ tag: {
61
+ compile: compileTag
62
+ },
63
+ helper: {},
64
+ converter: {}
65
+ },
66
+
67
+ // jsviews object ($.views if jQuery is loaded)
68
+ $views = {
69
+ jsviews: versionNumber,
70
+ render: $render,
71
+ View: View,
72
+ settings: {
73
+ delimiters: $viewsDelimiters,
74
+ debugMode: true,
75
+ tryCatch: true
76
+ },
77
+ sub: {
78
+ // subscription, e.g. JsViews integration
79
+ Error: JsViewsError,
80
+ tmplFn: tmplFn,
81
+ parse: parseParams,
82
+ extend: $extend,
83
+ error: error,
84
+ syntaxError: syntaxError
85
+ //TODO invoke: $invoke
86
+ },
87
+ _cnvt: convertVal,
88
+ _tag: renderTag,
89
+
90
+ // TODO provide better debug experience - e.g. support $.views.onError callback
91
+ _err: function(e) {
92
+ // Place a breakpoint here to intercept template rendering errors
93
+ return $viewsSettings.debugMode ? ("Error: " + (e.message || e)) + ". " : '';
94
+ }
95
+ };
96
+
97
+ function JsViewsError(message, object) {
98
+ // Error exception type for JsViews/JsRender
99
+ // Override of $.views.sub.Error is possible
100
+ if (object && object.onError) {
101
+ if (object.onError(message) === false) {
102
+ return;
103
+ }
104
+ }
105
+ this.name = "JsRender Error";
106
+ this.message = message || "JsRender error";
107
+ }
108
+
109
+ function $extend(target, source) {
110
+ var name;
111
+ target = target || {};
112
+ for (name in source) {
113
+ target[name] = source[name];
114
+ }
115
+ return target;
116
+ }
117
+
118
+ //TODO function $invoke() {
119
+ // try {
120
+ // return arguments[1].apply(arguments[0], arguments[2]);
121
+ // }
122
+ // catch(e) {
123
+ // throw new $views.sub.Error(e, arguments[0]);
124
+ // }
125
+ // }
126
+
127
+ (JsViewsError.prototype = new Error()).constructor = JsViewsError;
128
+
129
+ //========================== Top-level functions ==========================
130
+
131
+ //===================
132
+ // jsviews.delimiters
133
+ //===================
134
+ function $viewsDelimiters(openChars, closeChars, link) {
135
+ // Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
136
+ // openChars, closeChars: opening and closing strings, each with two characters
137
+
138
+ if (!$viewsSub.rTag || arguments.length) {
139
+ delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
140
+ delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1;
141
+ delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0;
142
+ delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1;
143
+ linkChar = link || linkChar;
144
+ openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{"
145
+ closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}"
146
+ // Build regex with new delimiters
147
+ // tag (followed by / space or }) or cvtr+colon or html or code
148
+ rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))"
149
+ + "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";
150
+
151
+ // make rTag available to JsViews (or other components) for parsing binding expressions
152
+ $viewsSub.rTag = rTag + ")";
153
+
154
+ rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g");
155
+
156
+ // Default: bind tag converter colon html comment code params slash closeBlock
157
+ // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
158
+
159
+ rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
160
+ // rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered
161
+ // NOT to be jQuery selectors
162
+ }
163
+ return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar];
164
+ }
165
+
166
+ //=========
167
+ // View.get
168
+ //=========
169
+
170
+ function getView(inner, type) { //view.get(inner, type)
171
+ if (!type) {
172
+ // view.get(type)
173
+ type = inner;
174
+ inner = undefined;
175
+ }
176
+
177
+ var views, i, l, found,
178
+ view = this,
179
+ root = !type || type === "root";
180
+ // If type is undefined, returns root view (view under top view).
181
+
182
+ if (inner) {
183
+ // Go through views - this one, and all nested ones, depth-first - and return first one with given type.
184
+ found = view.type === type ? view : undefined;
185
+ if (!found) {
186
+ views = view.views;
187
+ if (view._.useKey) {
188
+ for (i in views) {
189
+ if (found = views[i].get(inner, type)) {
190
+ break;
191
+ }
192
+ }
193
+ } else for (i = 0, l = views.length; !found && i < l; i++) {
194
+ found = views[i].get(inner, type);
195
+ }
196
+ }
197
+ } else if (root) {
198
+ // Find root view. (view whose parent is top view)
199
+ while (view.parent.parent) {
200
+ found = view = view.parent;
201
+ }
202
+ } else while (view && !found) {
203
+ // Go through views - this one, and all parent ones - and return first one with given type.
204
+ found = view.type === type ? view : undefined;
205
+ view = view.parent;
206
+ }
207
+ return found;
208
+ }
209
+
210
+ function getIndex() {
211
+ var view = this.get("item");
212
+ return view ? view.index : undefined;
213
+ }
214
+
215
+ getIndex.depends = function() {
216
+ return [this.get("item"), "index"];
217
+ };
218
+
219
+ //==========
220
+ // View.hlp
221
+ //==========
222
+
223
+ function getHelper(helper) {
224
+ // Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo
225
+ var wrapped,
226
+ view = this,
227
+ res = (view.ctx || {})[helper];
228
+
229
+ res = res === undefined ? view.getRsc("helpers", helper) : res;
230
+
231
+ if (res) {
232
+ if (typeof res === "function") {
233
+ wrapped = function() {
234
+ // If it is of type function, we will wrap it so it gets called with view as 'this' context.
235
+ // If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too.
236
+ // However note that helper functions on deeper paths will not have access to view and tagCtx.
237
+ // For example, ~util.foo() will have the ~util object as 'this' pointer
238
+ return res.apply(view, arguments);
239
+ };
240
+ $extend(wrapped, res);
241
+ }
242
+ }
243
+ return wrapped || res;
244
+ }
245
+
246
+ //==============
247
+ // jsviews._cnvt
248
+ //==============
249
+
250
+ function convertVal(converter, view, tagCtx) {
251
+ // self is template object or linkCtx object
252
+ var tmplConverter, tag, value,
253
+ boundTagCtx = +tagCtx === tagCtx && tagCtx, // if value is an integer, then it is the key for the boundTagCtx
254
+ linkCtx = view.linkCtx;
255
+
256
+ if (boundTagCtx) {
257
+ // Call compiled function which returns the tagCtxs for current data
258
+ tagCtx = (boundTagCtx = view.tmpl.bnds[boundTagCtx-1])(view.data, view, $views);
259
+ }
260
+
261
+ value = tagCtx.args[0];
262
+
263
+ if (converter || boundTagCtx) {
264
+ tag = linkCtx && linkCtx.tag || {
265
+ _: {
266
+ inline: !linkCtx
267
+ },
268
+ tagName: converter + ":",
269
+ flow: true,
270
+ _is: "tag"
271
+ };
272
+
273
+ tag._.bnd = boundTagCtx;
274
+
275
+ if (linkCtx) {
276
+ linkCtx.tag = tag;
277
+ tag.linkCtx = linkCtx;
278
+ tagCtx.ctx = extendCtx(tagCtx.ctx, linkCtx.view.ctx);
279
+ }
280
+ tag.tagCtx = tagCtx;
281
+ tagCtx.view = view;
282
+
283
+ tag.ctx = tagCtx.ctx || {};
284
+ delete tagCtx.ctx;
285
+ // Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
286
+ view._.tag = tag;
287
+
288
+ converter = converter !== "true" && converter; // If there is a convertBack but no convert, converter will be "true"
289
+
290
+ if (converter && ((tmplConverter = view.getRsc("converters", converter)) || error("Unknown converter: {{"+ converter + ":"))) {
291
+ // A call to {{cnvt: ... }} or {^{cnvt: ... }} or data-link="{cnvt: ... }"
292
+ tag.depends = tmplConverter.depends;
293
+ value = tmplConverter.apply(tag, tagCtx.args);
294
+ }
295
+ // Call onRender (used by JsViews if present, to add binding annotations around rendered content)
296
+ value = boundTagCtx && view._.onRender
297
+ ? view._.onRender(value, view, boundTagCtx)
298
+ : value;
299
+ }
300
+ return value;
301
+ }
302
+
303
+ //=============
304
+ // jsviews._tag
305
+ //=============
306
+
307
+ function getResource(storeName, item) {
308
+ var res,
309
+ view = this,
310
+ store = $views[storeName];
311
+
312
+ res = store && store[item];
313
+ while ((res === undefined) && view) {
314
+ store = view.tmpl[storeName];
315
+ res = store && store[item];
316
+ view = view.parent;
317
+ }
318
+ return res;
319
+ }
320
+
321
+ function renderTag(tagName, parentView, tmpl, tagCtxs) {
322
+ // Called from within compiled template function, to render a template tag
323
+ // Returns the rendered tag
324
+
325
+ var render, tag, tags, attr, isElse, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, boundTagFn, tagDef,
326
+ ret = "",
327
+ boundTagKey = +tagCtxs === tagCtxs && tagCtxs, // if tagCtxs is an integer, then it is the boundTagKey
328
+ linkCtx = parentView.linkCtx || 0,
329
+ ctx = parentView.ctx,
330
+ parentTmpl = tmpl || parentView.tmpl,
331
+ parentView_ = parentView._,
332
+ tag = tagName._is === "tag" && tagName;
333
+
334
+ // Provide tagCtx, linkCtx and ctx access from tag
335
+ if (boundTagKey) {
336
+ // if tagCtxs is an integer, we are data binding
337
+ // Call compiled function which returns the tagCtxs for current data
338
+ tagCtxs = (boundTagFn = parentTmpl.bnds[boundTagKey-1])(parentView.data, parentView, $views);
339
+ }
340
+
341
+ l = tagCtxs.length;
342
+ tag = tag || linkCtx.tag;
343
+ for (i = 0; i < l; i++) {
344
+ tagCtx = tagCtxs[i];
345
+
346
+ // Set the tmpl property to the content of the block tag, unless set as an override property on the tag
347
+ content = tagCtx.tmpl;
348
+ content = tagCtx.content = content && parentTmpl.tmpls[content - 1];
349
+ tmpl = tagCtx.props.tmpl;
350
+ if (!i && (!tmpl || !tag)) {
351
+ tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{"+ tagName + "}}");
352
+ }
353
+ tmpl = tmpl || !i && tagDef.template || content;
354
+ tmpl = "" + tmpl === tmpl // if a string
355
+ ? parentView.getRsc("templates", tmpl) || $templates(tmpl)
356
+ : tmpl;
357
+
358
+ $extend( tagCtx, {
359
+ tmpl: tmpl,
360
+ render: renderContent,
361
+ index: i,
362
+ view: parentView,
363
+ ctx: extendCtx(tagCtx.ctx, ctx) // Extend parentView.ctx
364
+ }); // Extend parentView.ctx
365
+
366
+ if (!tag) {
367
+ // This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet
368
+ // Instantiate tag if it does not yet exist
369
+ if (tagDef.init) {
370
+ // If the tag has not already been instantiated, we will create a new instance.
371
+ // ~tag will access the tag, even within the rendering of the template content of this tag.
372
+ // From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName
373
+ // TODO provide error handling owned by the tag - using tag.onError
374
+ // try {
375
+ tag = new tagDef.init(tagCtx, linkCtx, ctx);
376
+ // }
377
+ // catch(e) {
378
+ // tagDef.onError(e);
379
+ // }
380
+ // Set attr on linkCtx to ensure outputting to the correct target attribute.
381
+ tag.attr = tag.attr || tagDef.attr || undefined;
382
+ // Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib.
383
+ } else {
384
+ // This is a simple tag declared as a function. We won't instantiate a specific tag constructor - just a standard instance object.
385
+ tag = {
386
+ // tag instance object if no init constructor
387
+ render: tagDef.render
388
+ };
389
+ }
390
+ tag._ = {
391
+ inline: !linkCtx
392
+ };
393
+ if (linkCtx) {
394
+ // Set attr on linkCtx to ensure outputting to the correct target attribute.
395
+ linkCtx.attr = tag.attr = linkCtx.attr || tag.attr;
396
+ linkCtx.tag = tag;
397
+ tag.linkCtx = linkCtx;
398
+ }
399
+ if (tag._.bnd = boundTagFn || linkCtx) {
400
+ // Bound if {^{tag...}} or data-link="{tag...}"
401
+ tag._.arrVws = {};
402
+ }
403
+ tag.tagName = tagName;
404
+ tag.parent = parentTag = ctx && ctx.tag,
405
+ tag._is = "tag";
406
+ // Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
407
+ }
408
+ parentView_.tag = tag;
409
+ tagCtx.tag = tag;
410
+ tag.tagCtxs = tagCtxs;
411
+ tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...)
412
+
413
+ if (!tag.flow) {
414
+ tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {};
415
+
416
+ // tags hash: tag.ctx.tags, merged with parentView.ctx.tags,
417
+ tags = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {};
418
+ if (parentTag) {
419
+ tags[parentTag.tagName] = parentTag;
420
+ }
421
+ tagCtxCtx.tag = tag;
422
+ }
423
+ }
424
+ for (i = 0; i < l; i++) {
425
+ tagCtx = tag.tagCtx = tagCtxs[i];
426
+ tag.ctx = tagCtx.ctx;
427
+
428
+ if (render = tag.render) {
429
+ itemRet = render.apply(tag, tagCtx.args);
430
+ }
431
+ ret += itemRet !== undefined
432
+ ? itemRet // Return result of render function unless it is undefined, in which case return rendered template
433
+ : tagCtx.tmpl
434
+ // render template/content on the current data item
435
+ ? tagCtx.render()
436
+ : ""; // No return value from render, and no template/content defined, so return ""
437
+ }
438
+ delete tag.rendering;
439
+
440
+ tag.tagCtx = tag.tagCtxs[0];
441
+ tag.ctx= tag.tagCtx.ctx;
442
+
443
+ if (tag._.inline && (attr = tag.attr) && attr !== "html") {
444
+ ret = attr === "text"
445
+ ? $converters.html(ret)
446
+ : "";
447
+ }
448
+ return ret = boundTagKey && parentView._.onRender
449
+ // Call onRender (used by JsViews if present, to add binding annotations around rendered content)
450
+ ? parentView._.onRender(ret, parentView, boundTagKey)
451
+ : ret;
452
+ }
453
+
454
+ //=================
455
+ // View constructor
456
+ //=================
457
+
458
+ function View(context, type, parentView, data, template, key, contentTmpl, onRender) {
459
+ // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
460
+ var views, parentView_, tag,
461
+ isArray = type === "array",
462
+ self_ = {
463
+ key: 0,
464
+ useKey: isArray ? 0 : 1,
465
+ id: "" + viewId++,
466
+ onRender: onRender,
467
+ bnds: {}
468
+ },
469
+ self = {
470
+ data: data,
471
+ tmpl: template,
472
+ content: contentTmpl,
473
+ views: isArray ? [] : {},
474
+ parent: parentView,
475
+ ctx: context,
476
+ type: type,
477
+ // If the data is an array, this is an 'array view' with a views array for each child 'item view'
478
+ // If the data is not an array, this is an 'item view' with a views 'map' object for any child nested views
479
+ // ._.useKey is non zero if is not an 'array view' (owning a data array). Uuse this as next key for adding to child views map
480
+ get: getView,
481
+ getIndex: getIndex,
482
+ getRsc: getResource,
483
+ hlp: getHelper,
484
+ _: self_,
485
+ _is: "view"
486
+ };
487
+ if (parentView) {
488
+ views = parentView.views;
489
+ parentView_ = parentView._;
490
+ if (parentView_.useKey) {
491
+ // Parent is an 'item view'. Add this view to its views object
492
+ // self._key = is the key in the parent view map
493
+ views[self_.key = "_" + parentView_.useKey++] = self;
494
+ tag = parentView_.tag;
495
+ self_.bnd = isArray && (!tag || !!tag._.bnd && tag); // For array views that are data bound for collection change events, set the
496
+ // 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 ...}}
497
+ } else {
498
+ // Parent is an 'array view'. Add this view to its views array
499
+ views.splice(
500
+ // self._.key = self.index - the index in the parent view array
501
+ self_.key = self.index =
502
+ key !== undefined
503
+ ? key
504
+ : views.length,
505
+ 0, self);
506
+ }
507
+ // If no context was passed in, use parent context
508
+ // If context was passed in, it should have been merged already with parent context
509
+ self.ctx = context || parentView.ctx;
510
+ }
511
+ return self;
512
+ }
513
+
514
+ //=============
515
+ // Registration
516
+ //=============
517
+
518
+ function compileChildResources(parentTmpl) {
519
+ var storeName, resources, resourceName, settings, compile;
520
+ for (storeName in jsvStores) {
521
+ settings = jsvStores[storeName];
522
+ if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) {
523
+ for (resourceName in resources) {
524
+ // compile child resource declarations (templates, tags, converters or helpers)
525
+ resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, storeName, settings);
526
+ }
527
+ }
528
+ }
529
+ }
530
+
531
+ function compileTag(name, item, parentTmpl) {
532
+ var init, tmpl;
533
+ if (typeof item === "function") {
534
+ // Simple tag declared as function. No presenter instantation.
535
+ item = {
536
+ depends: item.depends,
537
+ render: item
538
+ };
539
+ } else {
540
+ // Tag declared as object, used as the prototype for tag instantiation (control/presenter)
541
+ if (tmpl = item.template) {
542
+ item.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl;
543
+ }
544
+ if (item.init !== false) {
545
+ init = item.init = item.init || function(tagCtx) {};
546
+ init.prototype = item;
547
+ (init.prototype = item).constructor = init;
548
+ }
549
+ }
550
+ if (parentTmpl) {
551
+ item._parentTmpl = parentTmpl;
552
+ }
553
+ //TODO item.onError = function(e) {
554
+ // var error;
555
+ // if (error = this.prototype.onError) {
556
+ // error.call(this, e);
557
+ // } else {
558
+ // throw e;
559
+ // }
560
+ // }
561
+ return item;
562
+ }
563
+
564
+ function compileTmpl(name, tmpl, parentTmpl, storeName, storeSettings, options) {
565
+ // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object
566
+
567
+ //==== nested functions ====
568
+ function tmplOrMarkupFromStr(value) {
569
+ // If value is of type string - treat as selector, or name of compiled template
570
+ // Return the template object, if already compiled, or the markup string
571
+
572
+ if (("" + value === value) || value.nodeType > 0) {
573
+ try {
574
+ elem = value.nodeType > 0
575
+ ? value
576
+ : !rTmplString.test(value)
577
+ // If value is a string and does not contain HTML or tag content, then test as selector
578
+ && jQuery && jQuery(global.document).find(value)[0];
579
+ // If selector is valid and returns at least one element, get first element
580
+ // If invalid, jQuery will throw. We will stay with the original string.
581
+ } catch (e) {}
582
+
583
+ if (elem) {
584
+ // Generally this is a script element.
585
+ // However we allow it to be any element, so you can for example take the content of a div,
586
+ // use it as a template, and replace it by the same content rendered against data.
587
+ // e.g. for linking the content of a div to a container, and using the initial content as template:
588
+ // $.link("#content", model, {tmpl: "#content"});
589
+
590
+ value = elem.getAttribute(tmplAttr);
591
+ name = name || value;
592
+ value = $templates[value];
593
+ if (!value) {
594
+ // Not already compiled and cached, so compile and cache the name
595
+ // Create a name for compiled template if none provided
596
+ name = name || "_" + autoTmplName++;
597
+ elem.setAttribute(tmplAttr, name);
598
+ // Use tmpl as options
599
+ value = $templates[name] = compileTmpl(name, elem.innerHTML, parentTmpl, storeName, storeSettings, options);
600
+ }
601
+ }
602
+ return value;
603
+ }
604
+ // If value is not a string, return undefined
605
+ }
606
+
607
+ var tmplOrMarkup, elem;
608
+
609
+ //==== Compile the template ====
610
+ tmpl = tmpl || "";
611
+ tmplOrMarkup = tmplOrMarkupFromStr(tmpl);
612
+
613
+ // If options, then this was already compiled from a (script) element template declaration.
614
+ // If not, then if tmpl is a template object, use it for options
615
+ options = options || (tmpl.markup ? tmpl : {});
616
+ options.tmplName = name;
617
+ if (parentTmpl) {
618
+ options._parentTmpl = parentTmpl;
619
+ }
620
+ // If tmpl is not a markup string or a selector string, then it must be a template object
621
+ // In that case, get it from the markup property of the object
622
+ if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr(tmpl.markup))) {
623
+ if (tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode)) {
624
+ // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile
625
+ tmplOrMarkup = tmplOrMarkup.markup;
626
+ }
627
+ }
628
+ if (tmplOrMarkup !== undefined) {
629
+ if (name && !parentTmpl) {
630
+ $render[name] = function() {
631
+ return tmpl.render.apply(tmpl, arguments);
632
+ };
633
+ }
634
+ if (tmplOrMarkup.fn || tmpl.fn) {
635
+ // tmpl is already compiled, so use it, or if different name is provided, clone it
636
+ if (tmplOrMarkup.fn) {
637
+ if (name && name !== tmplOrMarkup.tmplName) {
638
+ tmpl = extendCtx(options, tmplOrMarkup);
639
+ } else {
640
+ tmpl = tmplOrMarkup;
641
+ }
642
+ }
643
+ } else {
644
+ // tmplOrMarkup is a markup string, not a compiled template
645
+ // Create template object
646
+ tmpl = TmplObject(tmplOrMarkup, options);
647
+ // Compile to AST and then to compiled function
648
+ tmplFn(tmplOrMarkup, tmpl);
649
+ }
650
+ compileChildResources(options);
651
+ return tmpl;
652
+ }
653
+ }
654
+ //==== /end of function compile ====
655
+
656
+ function TmplObject(markup, options) {
657
+ // Template object constructor
658
+ var htmlTag,
659
+ wrapMap = $viewsSettings.wrapMap || {},
660
+ tmpl = $extend(
661
+ {
662
+ markup: markup,
663
+ tmpls: [],
664
+ links: {}, // Compiled functions for link expressions
665
+ tags: {}, // Compiled functions for bound tag expressions
666
+ bnds: [],
667
+ _is: "template",
668
+ render: renderContent
669
+ },
670
+ options
671
+ );
672
+
673
+ if (!options.htmlTag) {
674
+ // Set tmpl.tag to the top-level HTML tag used in the template, if any...
675
+ htmlTag = rFirstElem.exec(markup);
676
+ tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : "";
677
+ }
678
+ htmlTag = wrapMap[tmpl.htmlTag];
679
+ if (htmlTag && htmlTag !== wrapMap.div) {
680
+ // When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content').
681
+ tmpl.markup = $.trim(tmpl.markup);
682
+ tmpl._elCnt = true; // element content model (no rendered text nodes), not phrasing content model
683
+ }
684
+
685
+ return tmpl;
686
+ }
687
+
688
+ function registerStore(storeName, storeSettings) {
689
+
690
+ function theStore(name, item, parentTmpl) {
691
+ // The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags
692
+
693
+ // For store of name 'thing', Call as:
694
+ // $.views.things(items[, parentTmpl]),
695
+ // or $.views.things(name, item[, parentTmpl])
696
+
697
+ var onStore, compile, itemName, thisStore;
698
+
699
+ if (name && "" + name !== name && !name.nodeType && !name.markup) {
700
+ // Call to $.views.things(items[, parentTmpl]),
701
+
702
+ // Adding items to the store
703
+ // If name is a map, then item is parentTmpl. Iterate over map and call store for key.
704
+ for (itemName in name) {
705
+ theStore(itemName, name[itemName], item);
706
+ }
707
+ return $views;
708
+ }
709
+ thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore;
710
+
711
+ // Adding a single unnamed item to the store
712
+ if (item === undefined) {
713
+ item = name;
714
+ name = undefined;
715
+ }
716
+ compile = storeSettings.compile;
717
+ if (onStore = $viewsSub.onBeforeStoreItem) {
718
+ // e.g. provide an external compiler or preprocess the item.
719
+ compile = onStore(thisStore, name, item, compile) || compile;
720
+ }
721
+ if (!name) {
722
+ item = compile(undefined, item);
723
+ } else if ("" + name === name) { // name must be a string
724
+ if (item === null) {
725
+ // If item is null, delete this entry
726
+ delete thisStore[name];
727
+ } else {
728
+ thisStore[name] = compile ? (item = compile(name, item, parentTmpl, storeName, storeSettings)) : item;
729
+ }
730
+ }
731
+ if (item) {
732
+ item._is = storeName;
733
+ }
734
+ if (onStore = $viewsSub.onStoreItem) {
735
+ // e.g. JsViews integration
736
+ onStore(thisStore, name, item, compile);
737
+ }
738
+ return item;
739
+ }
740
+
741
+ var storeNames = storeName + "s";
742
+
743
+ $views[storeNames] = theStore;
744
+ jsvStores[storeName] = storeSettings;
745
+ }
746
+
747
+ //==============
748
+ // renderContent
749
+ //==============
750
+
751
+ function renderContent(data, context, parentView, key, isLayout, onRender) {
752
+ // Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template).
753
+ // If the data is the parent view, treat as layout template, re-render with the same data context.
754
+ var i, l, dataItem, newView, childView, itemResult, swapContent, tagCtx, contentTmpl, tag_, outerOnRender, tmplName, tmpl,
755
+ self = this,
756
+ allowDataLink = !self.attr || self.attr === "html",
757
+ result = "";
758
+
759
+ if (key === true) {
760
+ swapContent = true;
761
+ key = 0;
762
+ }
763
+ if (self.tag) {
764
+ // This is a call from renderTag or tagCtx.render()
765
+ tagCtx = self;
766
+ self = self.tag;
767
+ tag_ = self._;
768
+ tmplName = self.tagName;
769
+ tmpl = tagCtx.tmpl;
770
+ context = extendCtx(context, self.ctx);
771
+ contentTmpl = tagCtx.content; // The wrapped content - to be added to views, below
772
+ if ( tagCtx.props.link === false ) {
773
+ // link=false setting on block tag
774
+ // We will override inherited value of link by the explicit setting link=false taken from props
775
+ // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect.
776
+ context = context || {};
777
+ context.link = false;
778
+ }
779
+ parentView = parentView || tagCtx.view;
780
+ data = data === undefined ? parentView : data;
781
+ } else {
782
+ tmpl = self.jquery && (self[0] || error('Unknown template: "' + self.selector + '"')) // This is a call from $(selector).render
783
+ || self;
784
+ }
785
+ if (tmpl) {
786
+ if (!parentView && data && data._is === "view") {
787
+ parentView = data; // When passing in a view to render or link (and not passing in a parent view) use the passed in view as parentView
788
+ }
789
+ if (parentView) {
790
+ contentTmpl = contentTmpl || parentView.content; // The wrapped content - to be added as #content property on views, below
791
+ onRender = onRender || parentView._.onRender;
792
+ if (data === parentView) {
793
+ // Inherit the data from the parent view.
794
+ // This may be the contents of an {{if}} block
795
+ // Set isLayout = true so we don't iterate the if block if the data is an array.
796
+ data = parentView.data;
797
+ isLayout = true;
798
+ }
799
+ context = extendCtx(context, parentView.ctx);
800
+ }
801
+ if (!parentView || parentView.data === undefined) {
802
+ (context = context || {}).root = data; // Provide ~root as shortcut to top-level data.
803
+ }
804
+
805
+ // Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views)
806
+ // Note: If no jQuery, $extend does not support chained copies - so limit extend() to two parameters
807
+
808
+ if (!tmpl.fn) {
809
+ tmpl = $templates[tmpl] || $templates(tmpl);
810
+ }
811
+
812
+ if (tmpl) {
813
+ onRender = (context && context.link) !== false && allowDataLink && onRender;
814
+ // If link===false, do not call onRender, so no data-linking marker nodes
815
+ outerOnRender = onRender;
816
+ if (onRender === true) {
817
+ // Used by view.refresh(). Don't create a new wrapper view.
818
+ outerOnRender = undefined;
819
+ onRender = parentView._.onRender;
820
+ }
821
+ if ($.isArray(data) && !isLayout) {
822
+ // Create a view for the array, whose child views correspond to each data item. (Note: if key and parentView are passed in
823
+ // along with parent view, treat as insert -e.g. from view.addViews - so parentView is already the view item for array)
824
+ newView = swapContent
825
+ ? parentView :
826
+ (key !== undefined && parentView) || View(context, "array", parentView, data, tmpl, key, contentTmpl, onRender);
827
+ for (i = 0, l = data.length; i < l; i++) {
828
+ // Create a view for each data item.
829
+ dataItem = data[i];
830
+ childView = View(context, "item", newView, dataItem, tmpl, (key || 0) + i, contentTmpl, onRender);
831
+ itemResult = tmpl.fn(dataItem, childView, $views);
832
+ result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult;
833
+ }
834
+ } else {
835
+ // Create a view for singleton data object. The type of the view will be the tag name, e.g. "if" or "myTag" except for
836
+ // "item", "array" and "data" views. A "data" view is from programatic render(object) against a 'singleton'.
837
+ newView = swapContent ? parentView : View(context, tmplName||"data", parentView, data, tmpl, key, contentTmpl, onRender);
838
+ if (tag_ && !self.flow) {
839
+ newView.tag = self;
840
+ }
841
+ result += tmpl.fn(data, newView, $views);
842
+ }
843
+ return outerOnRender ? outerOnRender(result, newView) : result;
844
+ }
845
+ }
846
+ return "";
847
+ }
848
+
849
+ //===========================
850
+ // Build and compile template
851
+ //===========================
852
+
853
+ // Generate a reusable function that will serve to render a template against data
854
+ // (Compile AST then build template function)
855
+
856
+ function error(message) {
857
+ if ($viewsSettings.debugMode) {
858
+ throw new $views.sub.Error(message);
859
+ }
860
+ }
861
+
862
+ function syntaxError(message) {
863
+ error("Syntax error\n" + message);
864
+ }
865
+
866
+ function tmplFn(markup, tmpl, isLinkExpr, convertBack) {
867
+ // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes
868
+ // Used for compiling templates, and also by JsViews to build functions for data link expressions
869
+
870
+
871
+ //==== nested functions ====
872
+ function pushprecedingContent(shift) {
873
+ shift -= loc;
874
+ if (shift) {
875
+ content.push(markup.substr(loc, shift).replace(rNewLine, "\\n"));
876
+ }
877
+ }
878
+
879
+ function blockTagCheck(tagName) {
880
+ tagName && syntaxError('Unmatched or missing tag: "{{/' + tagName + '}}" in template:\n' + markup);
881
+ }
882
+
883
+ function parseTag(all, bind, tagName, converter, colon, html, comment, codeTag, params, slash, closeBlock, index) {
884
+
885
+ // bind tag converter colon html comment code params slash closeBlock
886
+ // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
887
+ // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, bindings, contentMarkup ]
888
+ if (html) {
889
+ colon = ":";
890
+ converter = "html";
891
+ }
892
+ slash = slash || isLinkExpr;
893
+ var noError, current0,
894
+ pathBindings = bind && [],
895
+ code = "",
896
+ hash = "",
897
+ passedCtx = "",
898
+ // Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression
899
+ block = !slash && !colon && !comment;
900
+
901
+ //==== nested helper function ====
902
+ tagName = tagName || colon;
903
+ pushprecedingContent(index);
904
+ loc = index + all.length; // location marker - parsed up to here
905
+ if (codeTag) {
906
+ if (allowCode) {
907
+ content.push(["*", "\n" + params.replace(rUnescapeQuotes, "$1") + "\n"]);
908
+ }
909
+ } else if (tagName) {
910
+ if (tagName === "else") {
911
+ if (rTestElseIf.test(params)) {
912
+ syntaxError('for "{{else if expr}}" use "{{else expr}}"');
913
+ }
914
+ pathBindings = current[6];
915
+ current[7] = markup.substring(current[7], index); // contentMarkup for block tag
916
+ current = stack.pop();
917
+ content = current[3];
918
+ block = true;
919
+ }
920
+ if (params) {
921
+ // remove newlines from the params string, to avoid compiled code errors for unterminated strings
922
+ params = params.replace(rNewLine, " ");
923
+ code = parseParams(params, pathBindings)
924
+ .replace(rBuildHash, function(all, isCtx, keyValue) {
925
+ if (isCtx) {
926
+ passedCtx += keyValue + ",";
927
+ } else {
928
+ hash += keyValue + ",";
929
+ }
930
+ return "";
931
+ });
932
+ }
933
+ hash = hash.slice(0, -1);
934
+ code = code.slice(0, -1);
935
+ noError = hash && (hash.indexOf("noerror:true") + 1) && hash || "";
936
+
937
+ newNode = [
938
+ tagName,
939
+ converter || !!convertBack || "",
940
+ code,
941
+ block && [],
942
+ 'params:"' + params + '",props:{' + hash + "}"
943
+ + (passedCtx ? ",ctx:{" + passedCtx.slice(0, -1) + "}" : ""),
944
+ noError,
945
+ pathBindings || 0
946
+ ];
947
+ content.push(newNode);
948
+ if (block) {
949
+ stack.push(current);
950
+ current = newNode;
951
+ current[7] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag
952
+ }
953
+ } else if (closeBlock) {
954
+ current0 = current[0];
955
+ blockTagCheck(closeBlock !== current0 && current0 !== "else" && closeBlock);
956
+ current[7] = markup.substring(current[7], index); // contentMarkup for block tag
957
+ current = stack.pop();
958
+ }
959
+ blockTagCheck(!current && closeBlock);
960
+ content = current[3];
961
+ }
962
+ //==== /end of nested functions ====
963
+
964
+ var newNode,
965
+ allowCode = tmpl && tmpl.allowCode,
966
+ astTop = [],
967
+ loc = 0,
968
+ stack = [],
969
+ content = astTop,
970
+ current = [, , , astTop];
971
+
972
+ markup = markup.replace(rEscapeQuotes, "\\$1");
973
+
974
+ //TODO result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ...,
975
+ //and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c"
976
+ // if (result) {
977
+ // tmpl.fn = result;
978
+ // } else {
979
+
980
+ // result = markup;
981
+
982
+ blockTagCheck(stack[0] && stack[0][3].pop()[0]);
983
+
984
+ // Build the AST (abstract syntax tree) under astTop
985
+ markup.replace(rTag, parseTag);
986
+
987
+ pushprecedingContent(markup.length);
988
+
989
+ if (loc = astTop[astTop.length - 1]) {
990
+ blockTagCheck("" + loc !== loc && (+loc[7] === loc[7]) && loc[0]);
991
+ }
992
+ // result = tmplFnsCache[markup] = buildCode(astTop, tmpl);
993
+ // }
994
+ return buildCode(astTop, tmpl || markup, isLinkExpr);
995
+ }
996
+
997
+ function buildCode(ast, tmpl, isLinkExpr) {
998
+ // Build the template function code from the AST nodes, and set as property on the passed-in template object
999
+ // Used for compiling templates, and also by JsViews to build functions for data link expressions
1000
+ var i, node, tagName, converter, params, hash, hasTag, hasEncoder, getsVal, hasCnvt, tmplBindings, pathBindings, elseStartIndex, elseIndex,
1001
+ nestedTmpls, tmplName, nestedTmpl, tagAndElses, allowCode, content, markup, notElse, nextIsElse, oldCode, isElse, isGetVal, prm, tagCtxFn,
1002
+ tmplBindingKey = 0,
1003
+ code = "",
1004
+ noError = "",
1005
+ tmplOptions = {},
1006
+ l = ast.length;
1007
+
1008
+ if ("" + tmpl === tmpl) {
1009
+ tmplName = isLinkExpr ? 'data-link="' + tmpl.replace(rNewLine, " ").slice(1, -1) + '"' : tmpl;
1010
+ tmpl = 0;
1011
+ } else {
1012
+ tmplName = tmpl.tmplName || "unnamed";
1013
+ if (allowCode = tmpl.allowCode) {
1014
+ tmplOptions.allowCode = true;
1015
+ }
1016
+ if (tmpl.debug) {
1017
+ tmplOptions.debug = true;
1018
+ }
1019
+ tmplBindings = tmpl.bnds;
1020
+ nestedTmpls = tmpl.tmpls;
1021
+ }
1022
+ for (i = 0; i < l; i++) {
1023
+ // AST nodes: [ tagName, converter, params, content, hash, noError, pathBindings, contentMarkup, link ]
1024
+ node = ast[i];
1025
+
1026
+ // Add newline for each callout to t() c() etc. and each markup string
1027
+ if ("" + node === node) {
1028
+ // a markup string to be inserted
1029
+ code += '\nret+="' + node + '";';
1030
+ } else {
1031
+ // a compiled tag expression to be inserted
1032
+ tagName = node[0];
1033
+ if (tagName === "*") {
1034
+ // Code tag: {{* }}
1035
+ code += "" + node[1];
1036
+ } else {
1037
+ converter = node[1];
1038
+ params = node[2];
1039
+ content = node[3];
1040
+ hash = node[4];
1041
+ noError = node[5];
1042
+ markup = node[7];
1043
+
1044
+ if (!(isElse = tagName === "else")) {
1045
+ tmplBindingKey = 0;
1046
+ if (pathBindings = node[6]) { // Array of paths, or false if not data-bound
1047
+ tmplBindingKey = tmplBindings.push(pathBindings);
1048
+ }
1049
+ }
1050
+ if (isGetVal = tagName === ":") {
1051
+ if (converter) {
1052
+ tagName = converter === "html" ? ">" : converter + tagName;
1053
+ }
1054
+ if (noError) {
1055
+ // If the tag includes noerror=true, we will do a try catch around expressions for named or unnamed parameters
1056
+ // passed to the tag, and return the empty string for each expression if it throws during evaluation
1057
+ //TODO This does not work for general case - supporting noError on multiple expressions, e.g. tag args and properties.
1058
+ //Consider replacing with try<a.b.c(p,q) + a.d, xxx> and return the value of the expression a.b.c(p,q) + a.d, or, if it throws, return xxx||'' (rather than always the empty string)
1059
+ prm = "prm" + i;
1060
+ noError = "try{var " + prm + "=[" + params + "][0];}catch(e){" + prm + '="";}\n';
1061
+ params = prm;
1062
+ }
1063
+ } else {
1064
+ if (content) {
1065
+ // Create template object for nested template
1066
+ nestedTmpl = TmplObject(markup, tmplOptions);
1067
+ nestedTmpl.tmplName = tmplName + "/" + tagName;
1068
+ // Compile to AST and then to compiled function
1069
+ buildCode(content, nestedTmpl);
1070
+ nestedTmpls.push(nestedTmpl);
1071
+ }
1072
+
1073
+ if (!isElse) {
1074
+ // This is not an else tag.
1075
+ tagAndElses = tagName;
1076
+ // Switch to a new code string for this bound tag (and its elses, if it has any) - for returning the tagCtxs array
1077
+ oldCode = code;
1078
+ code = "";
1079
+ elseStartIndex = i;
1080
+ }
1081
+ nextIsElse = ast[i + 1];
1082
+ nextIsElse = nextIsElse && nextIsElse[0] === "else";
1083
+ }
1084
+
1085
+ //TODO consider passing in ret to c() and t() so they can look at the previous ret, and detect whether this is a jsrender tag _within_an_HTML_element_tag_
1086
+ // and if so, don't insert marker nodes, add data-link attributes to the HTML element markup... No need for people to set link=false.
1087
+
1088
+ //TODO consider the following approach rather than noerror=true: params.replace(/data.try\([^]*\)/)
1089
+
1090
+ hash += ",args:[" + params + "]}";
1091
+
1092
+ if (isGetVal && pathBindings || converter && tagName !== ">") {
1093
+ // For convertVal we need a compiled function to return the new tagCtx(s)
1094
+ tagCtxFn = new Function("data,view,j,u", " // "
1095
+ + tmplName + " " + tmplBindingKey + " " + tagName + "\n" + noError + "return {" + hash + ";");
1096
+ tagCtxFn.paths = pathBindings;
1097
+ tagCtxFn._ctxs = tagName;
1098
+ if (isLinkExpr) {
1099
+ return tagCtxFn;
1100
+ }
1101
+ hasCnvt = true;
1102
+ }
1103
+
1104
+ code += (isGetVal
1105
+ ? "\n" + (pathBindings ? "" : noError) + (isLinkExpr ? "return " : "ret+=") + (hasCnvt // Call _cnvt if there is a converter: {{cnvt: ... }} or {^{cnvt: ... }}
1106
+ ? (hasCnvt = true, 'c("' + converter + '",view,' + (pathBindings
1107
+ ? ((tmplBindings[tmplBindingKey - 1] = tagCtxFn), tmplBindingKey) // Store the compiled tagCtxFn in tmpl.bnds, and pass the key to convertVal()
1108
+ : "{" + hash) + ");")
1109
+ : tagName === ">"
1110
+ ? (hasEncoder = true, "h(" + params + ");")
1111
+ : (getsVal = true, "(v=" + params + ")!=" + (isLinkExpr ? "=" : "") + 'u?v:"";') // Strict equality just for data-link="title{:expr}" so expr=null will remove title attribute
1112
+ )
1113
+ : (hasTag = true, "{tmpl:" // Add this tagCtx to the compiled code for the tagCtxs to be passed to renderTag()
1114
+ + (content ? nestedTmpls.length: "0") + "," // For block tags, pass in the key (nestedTmpls.length) to the nested content template
1115
+ + hash + ","));
1116
+
1117
+ if (tagAndElses && !nextIsElse) {
1118
+ code = "[" + code.slice(0, -1) + "]"; // This is a data-link expression or the last {{else}} of an inline bound tag. We complete the code for returning the tagCtxs array
1119
+ if (isLinkExpr || pathBindings) {
1120
+ // This is a bound tag (data-link expression or inline bound tag {^{tag ...}}) so we store a compiled tagCtxs function in tmp.bnds
1121
+ code = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagAndElses + "\nreturn " + code + ";");
1122
+ if (pathBindings) {
1123
+ (tmplBindings[tmplBindingKey - 1] = code).paths = pathBindings;
1124
+ }
1125
+ code._ctxs = tagName;
1126
+ if (isLinkExpr) {
1127
+ return code; // For a data-link expression we return the compiled tagCtxs function
1128
+ }
1129
+ }
1130
+
1131
+ // This is the last {{else}} for an inline tag.
1132
+ // For a bound tag, pass the tagCtxs fn lookup key to renderTag.
1133
+ // For an unbound tag, include the code directly for evaluating tagCtxs array
1134
+ code = oldCode + '\nret+=t("' + tagAndElses + '",view,this,' + (tmplBindingKey || code) + ");";
1135
+ pathBindings = 0;
1136
+ tagAndElses = 0;
1137
+ }
1138
+ }
1139
+ }
1140
+ }
1141
+ // Include only the var references that are needed in the code
1142
+ code = "// " + tmplName
1143
+ + "\nvar j=j||" + (jQuery ? "jQuery." : "js") + "views"
1144
+ + (getsVal ? ",v" : "") // gets value
1145
+ + (hasTag ? ",t=j._tag" : "") // has tag
1146
+ + (hasCnvt ? ",c=j._cnvt" : "") // converter
1147
+ + (hasEncoder ? ",h=j.converters.html" : "") // html converter
1148
+ + (isLinkExpr ? ";\n" : ',ret="";\n')
1149
+ + ($viewsSettings.tryCatch ? "try{\n" : "")
1150
+ + (tmplOptions.debug ? "debugger;" : "")
1151
+ + code + (isLinkExpr ? "\n" : "\nreturn ret;\n")
1152
+ + ($viewsSettings.tryCatch ? "\n}catch(e){return j._err(e);}" : "");
1153
+ try {
1154
+ code = new Function("data,view,j,u", code);
1155
+ } catch (e) {
1156
+ syntaxError("Compiled template code:\n\n" + code, e);
1157
+ }
1158
+ if (tmpl) {
1159
+ tmpl.fn = code;
1160
+ }
1161
+ return code;
1162
+ }
1163
+
1164
+ function parseParams(params, bindings) {
1165
+
1166
+ function parseTokens(all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, rtPrnDot, prn2, space, index, full) {
1167
+ // rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:([#~]?[\w$^.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$^.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)
1168
+ // lftPrn0-flwed by (- lftPrn path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space
1169
+ // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space
1170
+ operator = operator || "";
1171
+ lftPrn = lftPrn || lftPrn0 || lftPrn2;
1172
+ path = path || path2;
1173
+ if (bindings && rtPrnDot) {
1174
+ // TODO check for nested call ~foo(~bar().x).y
1175
+ objectCall = bindings.push({_jsvOb: full.slice(pathStart[parenDepth - 1] + 1, index + 1)});
1176
+ }
1177
+ prn = prn || prn2 || "";
1178
+
1179
+ function parsePath(all, object, helper, view, viewProperty, pathTokens, leafToken) {
1180
+ // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
1181
+ // object helper view viewProperty pathTokens leafToken
1182
+ if (object) {
1183
+ bindings && !name && bindings.push(path); // Add path binding for paths on props and args, but not within ~foo=expr (passing in template property aliases).
1184
+ if (object !== ".") {
1185
+ var ret = (helper
1186
+ ? 'view.hlp("' + helper + '")'
1187
+ : view
1188
+ ? "view"
1189
+ : "data")
1190
+ + (leafToken
1191
+ ? (viewProperty
1192
+ ? "." + viewProperty
1193
+ : helper
1194
+ ? ""
1195
+ : (view ? "" : "." + object)
1196
+ ) + (pathTokens || "")
1197
+ : (leafToken = helper ? "" : view ? viewProperty || "" : object, ""));
1198
+
1199
+ ret = ret + (leafToken ? "." + leafToken : "");
1200
+
1201
+ return ret.slice(0, 9) === "view.data"
1202
+ ? ret.slice(5) // convert #view.data... to data...
1203
+ : ret;
1204
+ }
1205
+ }
1206
+ return all;
1207
+ }
1208
+
1209
+ if (err) {
1210
+ syntaxError(params);
1211
+ } else {
1212
+ var tokens = (aposed
1213
+ // within single-quoted string
1214
+ ? (aposed = !apos, (aposed ? all : '"'))
1215
+ : quoted
1216
+ // within double-quoted string
1217
+ ? (quoted = !quot, (quoted ? all : '"'))
1218
+ :
1219
+ (
1220
+ (lftPrn
1221
+ ? (parenDepth++, pathStart[parenDepth] = index, lftPrn)
1222
+ : "")
1223
+ + (space
1224
+ ? (parenDepth
1225
+ ? ""
1226
+ : named
1227
+ ? (named = false, "\b")
1228
+ : ","
1229
+ )
1230
+ : eq
1231
+ // named param
1232
+ // Insert backspace \b (\x08) as separator for named params, used subsequently by rBuildHash
1233
+ ? (parenDepth && syntaxError(params), named = path, '\b' + path + ':')
1234
+ : path
1235
+ // path
1236
+ ? (path.split("^").join(".").replace(rPath, parsePath)
1237
+ + (prn
1238
+ ? (fnCall[++parenDepth] = true, prn)
1239
+ : operator)
1240
+ )
1241
+ : operator
1242
+ ? operator
1243
+ : rtPrn
1244
+ // function
1245
+ ? ((fnCall[parenDepth--] = false, rtPrn)
1246
+ + (prn
1247
+ ? (fnCall[++parenDepth] = true, prn)
1248
+ : "")
1249
+ )
1250
+ : comma
1251
+ ? (fnCall[parenDepth] || syntaxError(params), ",") // We don't allow top-level literal arrays or objects
1252
+ : lftPrn0
1253
+ ? ""
1254
+ : (aposed = apos, quoted = quot, '"')
1255
+ ))
1256
+ );
1257
+ return tokens;
1258
+ }
1259
+ }
1260
+
1261
+ var named, objectCall,
1262
+ fnCall = {},
1263
+ pathStart = {0:-1},
1264
+ parenDepth = 0,
1265
+ quoted = false, // boolean for string content in double quotes
1266
+ aposed = false; // or in single quotes
1267
+
1268
+ return (params + " ").replace(rParams, parseTokens);
1269
+ }
1270
+
1271
+ //==========
1272
+ // Utilities
1273
+ //==========
1274
+
1275
+ // Merge objects, in particular contexts which inherit from parent contexts
1276
+ function extendCtx(context, parentContext) {
1277
+ // Return copy of parentContext, unless context is defined and is different, in which case return a new merged context
1278
+ // If neither context nor parentContext are undefined, return undefined
1279
+ return context && context !== parentContext
1280
+ ? (parentContext
1281
+ ? $extend($extend({}, parentContext), context)
1282
+ : context)
1283
+ : parentContext && $extend({}, parentContext);
1284
+ }
1285
+
1286
+ //========================== Initialize ==========================
1287
+
1288
+ for (jsvStoreName in jsvStores) {
1289
+ registerStore(jsvStoreName, jsvStores[jsvStoreName]);
1290
+ }
1291
+
1292
+ var $templates = $views.templates,
1293
+ $converters = $views.converters,
1294
+ $helpers = $views.helpers,
1295
+ $tags = $views.tags,
1296
+ $viewsSub = $views.sub,
1297
+ $viewsSettings = $views.settings;
1298
+
1299
+ if (jQuery) {
1300
+ ////////////////////////////////////////////////////////////////////////////////////////////////
1301
+ // jQuery is loaded, so make $ the jQuery object
1302
+ $ = jQuery;
1303
+ $.render = $render;
1304
+ $.views = $views;
1305
+ $.templates = $templates = $views.templates;
1306
+ $.fn.render = renderContent;
1307
+
1308
+ } else {
1309
+ ////////////////////////////////////////////////////////////////////////////////////////////////
1310
+ // jQuery is not loaded.
1311
+
1312
+ $ = global.jsviews = $views;
1313
+
1314
+ $.isArray = Array && Array.isArray || function(obj) {
1315
+ return Object.prototype.toString.call(obj) === "[object Array]";
1316
+ };
1317
+ }
1318
+
1319
+ //========================== Register tags ==========================
1320
+
1321
+ $tags({
1322
+ "else": function() {}, // Does nothing but ensures {{else}} tags are recognized as valid
1323
+ "if": {
1324
+ render: function(val) {
1325
+ // This function is called once for {{if}} and once for each {{else}}.
1326
+ // We will use the tag.rendering object for carrying rendering state across the calls.
1327
+ // If not done (a previous block has not been rendered), look at expression for this block and render the block if expression is truey
1328
+ // Otherwise return ""
1329
+ var self = this,
1330
+ ret = (self.rendering.done || !val && (arguments.length || !self.tagCtx.index))
1331
+ ? ""
1332
+ : (self.rendering.done = true, self.selected = self.tagCtx.index,
1333
+ // Test is satisfied, so render content on current context. We call tagCtx.render() rather than return undefined
1334
+ // (which would also render the tmpl/content on the current context but would iterate if it is an array)
1335
+ self.tagCtx.render());
1336
+ return ret;
1337
+ },
1338
+ onUpdate: function(ev, eventArgs, tagCtxs) {
1339
+ var tci, prevArg, different;
1340
+ for (tci = 0; (prevArg = this.tagCtxs[tci]) && prevArg.args.length; tci++) {
1341
+ prevArg = prevArg.args[0];
1342
+ different = !prevArg !== !tagCtxs[tci].args[0];
1343
+ if (!!prevArg || different) {
1344
+ return different;
1345
+ // If newArg and prevArg are both truey, return false to cancel update. (Even if values on later elses are different, we still don't want to update, since rendered output would be unchanged)
1346
+ // If newArg and prevArg are different, return true, to update
1347
+ // If newArg and prevArg are both falsey, move to the next {{else ...}}
1348
+ }
1349
+ }
1350
+ // Boolean value of all args are unchanged (falsey), so return false to cancel update
1351
+ return false;
1352
+ },
1353
+ flow: true
1354
+ },
1355
+ "for": {
1356
+ render: function(val) {
1357
+ // This function is called once for {{for}} and once for each {{else}}.
1358
+ // We will use the tag.rendering object for carrying rendering state across the calls.
1359
+ var i, arg,
1360
+ self = this,
1361
+ tagCtx = self.tagCtx,
1362
+ noArg = !arguments.length,
1363
+ result = "",
1364
+ done = noArg || 0;
1365
+
1366
+ if (!self.rendering.done) {
1367
+ if (noArg) {
1368
+ result = undefined;
1369
+ } else if (val !== undefined) {
1370
+ result += tagCtx.render(val);
1371
+ // {{for}} (or {{else}}) with no argument will render the block content
1372
+ done += $.isArray(val) ? val.length : 1;
1373
+ }
1374
+ if (self.rendering.done = done) {
1375
+ self.selected = tagCtx.index;
1376
+ }
1377
+ // If nothing was rendered we will look at the next {{else}}. Otherwise, we are done.
1378
+ }
1379
+ return result;
1380
+ },
1381
+ onUpdate: function(ev, eventArgs, tagCtxs) {
1382
+ //Consider adding filtering for perf optimization. However the below prevents update on some scenarios which _should_ update - namely when there is another array on which for also depends.
1383
+ //var i, l, tci, prevArg;
1384
+ //for (tci = 0; (prevArg = this.tagCtxs[tci]) && prevArg.args.length; tci++) {
1385
+ // if (prevArg.args[0] !== tagCtxs[tci].args[0]) {
1386
+ // return true;
1387
+ // }
1388
+ //}
1389
+ //return false;
1390
+ },
1391
+ onArrayChange: function(ev, eventArgs) {
1392
+ var arrayView,
1393
+ self = this,
1394
+ change = eventArgs.change;
1395
+ if (this.tagCtxs[1] && (
1396
+ change === "insert" && ev.target.length === eventArgs.items.length // inserting, and new length is same as inserted length, so going from 0 to n
1397
+ || change === "remove" && !ev.target.length // removing , and new length 0, so going from n to 0
1398
+ || change === "refresh" && !eventArgs.oldItems.length !== !ev.target.length // refreshing, and length is going from 0 to n or from n to 0
1399
+ )) {
1400
+ this.refresh();
1401
+ } else {
1402
+ for (arrayView in self._.arrVws) {
1403
+ arrayView = self._.arrVws[arrayView];
1404
+ if (arrayView.data === ev.target) {
1405
+ arrayView._.onArrayChange.apply(arrayView, arguments);
1406
+ }
1407
+ }
1408
+ }
1409
+ ev.done = true;
1410
+ },
1411
+ flow: true
1412
+ },
1413
+ include: {
1414
+ flow: true
1415
+ },
1416
+ "*": {
1417
+ // {{* code... }} - Ignored if template.allowCode is false. Otherwise include code in compiled template
1418
+ render: function(value) {
1419
+ return value; // Include the code.
1420
+ },
1421
+ flow: true
1422
+ }
1423
+ });
1424
+
1425
+ //========================== Register global helpers ==========================
1426
+
1427
+ // $helpers({ // Global helper functions
1428
+ // // TODO add any useful built-in helper functions
1429
+ // });
1430
+
1431
+ //========================== Register converters ==========================
1432
+
1433
+ // Get character entity for HTML and Attribute encoding
1434
+ function getCharEntity(ch) {
1435
+ return charEntities[ch];
1436
+ }
1437
+
1438
+ $converters({
1439
+ html: function(text) {
1440
+ // HTML encode: Replace < > & and ' and " by corresponding entities.
1441
+ return text != undefined ? String(text).replace(rHtmlEncode, getCharEntity) : "";
1442
+ },
1443
+ attr: function(text) {
1444
+ // Attribute encode: Replace < & ' and " by corresponding entities.
1445
+ return text != undefined ? String(text).replace(rAttrEncode, getCharEntity) : "";
1446
+ },
1447
+ url: function(text) {
1448
+ // TODO - support chaining {{attr|url:....}} to protect against injection attacks from url parameters containing " or '.
1449
+ // URL encoding helper.
1450
+ return text != undefined ? encodeURI(String(text)) : "";
1451
+ }
1452
+ });
1453
+
1454
+ //========================== Define default delimiters ==========================
1455
+ $viewsDelimiters();
1456
+
1457
+ })(this, this.jQuery);