MDL-65758 library: Update mustache.js to 3.0.1
[moodle.git] / lib / amd / src / mustache.js
CommitLineData
9bdcf579
DW
1/*!
2 * mustache.js - Logic-less {{mustache}} templates with JavaScript
3 * http://github.com/janl/mustache.js
4 */
841e689a 5
a5410e13 6/*global define: false Mustache: true*/
9bdcf579 7
841e689a
DW
8(function defineMustache (global, factory) {
9 if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
9bdcf579 10 factory(exports); // CommonJS
841e689a 11 } else if (typeof define === 'function' && define.amd) {
9bdcf579
DW
12 define(['exports'], factory); // AMD
13 } else {
841e689a 14 global.Mustache = {};
1549528a 15 factory(global.Mustache); // script, wsh, asp
9bdcf579 16 }
841e689a 17}(this, function mustacheFactory (mustache) {
9bdcf579 18
841e689a
DW
19 var objectToString = Object.prototype.toString;
20 var isArray = Array.isArray || function isArrayPolyfill (object) {
21 return objectToString.call(object) === '[object Array]';
9bdcf579
DW
22 };
23
841e689a 24 function isFunction (object) {
9bdcf579
DW
25 return typeof object === 'function';
26 }
27
841e689a
DW
28 /**
29 * More correct typeof string handling array
30 * which normally returns typeof 'object'
31 */
32 function typeStr (obj) {
33 return isArray(obj) ? 'array' : typeof obj;
34 }
35
36 function escapeRegExp (string) {
37 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
38 }
39
40 /**
41 * Null safe way of checking whether or not an object,
42 * including its prototype, has a given property
43 */
44 function hasProperty (obj, propName) {
45 return obj != null && typeof obj === 'object' && (propName in obj);
9bdcf579
DW
46 }
47
a5410e13
MM
48 /**
49 * Safe way of detecting whether or not the given thing is a primitive and
50 * whether it has the given property
51 */
52 function primitiveHasOwnProperty (primitive, propName) {
53 return (
54 primitive != null
55 && typeof primitive !== 'object'
56 && primitive.hasOwnProperty
57 && primitive.hasOwnProperty(propName)
58 );
59 }
60
9bdcf579
DW
61 // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
62 // See https://github.com/janl/mustache.js/issues/189
841e689a
DW
63 var regExpTest = RegExp.prototype.test;
64 function testRegExp (re, string) {
65 return regExpTest.call(re, string);
9bdcf579
DW
66 }
67
68 var nonSpaceRe = /\S/;
841e689a 69 function isWhitespace (string) {
9bdcf579
DW
70 return !testRegExp(nonSpaceRe, string);
71 }
72
73 var entityMap = {
841e689a
DW
74 '&': '&',
75 '<': '&lt;',
76 '>': '&gt;',
9bdcf579
DW
77 '"': '&quot;',
78 "'": '&#39;',
1549528a
AG
79 '/': '&#x2F;',
80 '`': '&#x60;',
81 '=': '&#x3D;'
9bdcf579
DW
82 };
83
841e689a 84 function escapeHtml (string) {
1549528a 85 return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
9bdcf579
DW
86 return entityMap[s];
87 });
88 }
89
90 var whiteRe = /\s*/;
91 var spaceRe = /\s+/;
92 var equalsRe = /\s*=/;
93 var curlyRe = /\s*\}/;
a5410e13 94 var tagRe = /#|\^|\/|>|\{|&|=|!/;
9bdcf579
DW
95
96 /**
97 * Breaks up the given `template` string into a tree of tokens. If the `tags`
98 * argument is given here it must be an array with two string values: the
99 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
100 * course, the default is to use mustaches (i.e. mustache.tags).
101 *
102 * A token is an array with at least 4 elements. The first element is the
103 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
104 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
105 * all text that appears outside a symbol this element is "text".
106 *
107 * The second element of a token is its "value". For mustache tags this is
108 * whatever else was inside the tag besides the opening symbol. For text tokens
109 * this is the text itself.
110 *
111 * The third and fourth elements of the token are the start and end indices,
112 * respectively, of the token in the original template.
113 *
114 * Tokens that are the root node of a subtree contain two more elements: 1) an
115 * array of tokens in the subtree and 2) the index in the original template at
116 * which the closing tag for that section begins.
117 */
841e689a 118 function parseTemplate (template, tags) {
9bdcf579
DW
119 if (!template)
120 return [];
121
122 var sections = []; // Stack to hold section tokens
123 var tokens = []; // Buffer to hold the tokens
124 var spaces = []; // Indices of whitespace tokens on the current line
125 var hasTag = false; // Is there a {{tag}} on the current line?
126 var nonSpace = false; // Is there a non-space char on the current line?
127
128 // Strips all whitespace tokens array for the current line
129 // if there was a {{#tag}} on it and otherwise only space.
841e689a 130 function stripSpace () {
9bdcf579
DW
131 if (hasTag && !nonSpace) {
132 while (spaces.length)
133 delete tokens[spaces.pop()];
134 } else {
135 spaces = [];
136 }
137
138 hasTag = false;
139 nonSpace = false;
140 }
141
142 var openingTagRe, closingTagRe, closingCurlyRe;
841e689a
DW
143 function compileTags (tagsToCompile) {
144 if (typeof tagsToCompile === 'string')
145 tagsToCompile = tagsToCompile.split(spaceRe, 2);
9bdcf579 146
841e689a
DW
147 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
148 throw new Error('Invalid tags: ' + tagsToCompile);
9bdcf579 149
841e689a
DW
150 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
151 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
152 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
9bdcf579
DW
153 }
154
155 compileTags(tags || mustache.tags);
156
157 var scanner = new Scanner(template);
158
159 var start, type, value, chr, token, openSection;
160 while (!scanner.eos()) {
161 start = scanner.pos;
162
163 // Match any text between tags.
164 value = scanner.scanUntil(openingTagRe);
165
166 if (value) {
167 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
168 chr = value.charAt(i);
169
170 if (isWhitespace(chr)) {
171 spaces.push(tokens.length);
172 } else {
173 nonSpace = true;
174 }
175
176 tokens.push([ 'text', chr, start, start + 1 ]);
177 start += 1;
178
179 // Check for whitespace on the current line.
180 if (chr === '\n')
181 stripSpace();
182 }
183 }
184
185 // Match the opening tag.
186 if (!scanner.scan(openingTagRe))
187 break;
188
189 hasTag = true;
190
191 // Get the tag type.
192 type = scanner.scan(tagRe) || 'name';
193 scanner.scan(whiteRe);
194
195 // Get the tag value.
196 if (type === '=') {
197 value = scanner.scanUntil(equalsRe);
198 scanner.scan(equalsRe);
199 scanner.scanUntil(closingTagRe);
200 } else if (type === '{') {
201 value = scanner.scanUntil(closingCurlyRe);
202 scanner.scan(curlyRe);
203 scanner.scanUntil(closingTagRe);
204 type = '&';
205 } else {
206 value = scanner.scanUntil(closingTagRe);
207 }
208
209 // Match the closing tag.
210 if (!scanner.scan(closingTagRe))
211 throw new Error('Unclosed tag at ' + scanner.pos);
212
213 token = [ type, value, start, scanner.pos ];
214 tokens.push(token);
215
a5410e13 216 if (type === '#' || type === '^') {
9bdcf579
DW
217 sections.push(token);
218 } else if (type === '/') {
219 // Check section nesting.
220 openSection = sections.pop();
221
222 if (!openSection)
223 throw new Error('Unopened section "' + value + '" at ' + start);
224
225 if (openSection[1] !== value)
226 throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
227 } else if (type === 'name' || type === '{' || type === '&') {
228 nonSpace = true;
229 } else if (type === '=') {
230 // Set the tags for the next time around.
231 compileTags(value);
232 }
233 }
234
235 // Make sure there are no open sections when we're done.
236 openSection = sections.pop();
237
238 if (openSection)
239 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
240
241 return nestTokens(squashTokens(tokens));
242 }
243
244 /**
245 * Combines the values of consecutive text tokens in the given `tokens` array
246 * to a single token.
247 */
841e689a 248 function squashTokens (tokens) {
9bdcf579
DW
249 var squashedTokens = [];
250
251 var token, lastToken;
252 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
253 token = tokens[i];
254
255 if (token) {
256 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
257 lastToken[1] += token[1];
258 lastToken[3] = token[3];
259 } else {
260 squashedTokens.push(token);
261 lastToken = token;
262 }
263 }
264 }
265
266 return squashedTokens;
267 }
268
269 /**
270 * Forms the given array of `tokens` into a nested tree structure where
271 * tokens that represent a section have two additional items: 1) an array of
272 * all tokens that appear in that section and 2) the index in the original
273 * template that represents the end of that section.
274 */
841e689a 275 function nestTokens (tokens) {
9bdcf579
DW
276 var nestedTokens = [];
277 var collector = nestedTokens;
278 var sections = [];
279
280 var token, section;
281 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
282 token = tokens[i];
283
284 switch (token[0]) {
1549528a
AG
285 case '#':
286 case '^':
287 collector.push(token);
288 sections.push(token);
289 collector = token[4] = [];
290 break;
291 case '/':
292 section = sections.pop();
293 section[5] = token[2];
294 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
295 break;
296 default:
297 collector.push(token);
9bdcf579
DW
298 }
299 }
300
301 return nestedTokens;
302 }
303
304 /**
305 * A simple string scanner that is used by the template parser to find
306 * tokens in template strings.
307 */
841e689a 308 function Scanner (string) {
9bdcf579
DW
309 this.string = string;
310 this.tail = string;
311 this.pos = 0;
312 }
313
314 /**
315 * Returns `true` if the tail is empty (end of string).
316 */
841e689a
DW
317 Scanner.prototype.eos = function eos () {
318 return this.tail === '';
9bdcf579
DW
319 };
320
321 /**
322 * Tries to match the given regular expression at the current position.
323 * Returns the matched text if it can match, the empty string otherwise.
324 */
841e689a 325 Scanner.prototype.scan = function scan (re) {
9bdcf579
DW
326 var match = this.tail.match(re);
327
328 if (!match || match.index !== 0)
329 return '';
330
331 var string = match[0];
332
333 this.tail = this.tail.substring(string.length);
334 this.pos += string.length;
335
336 return string;
337 };
338
339 /**
340 * Skips all text until the given regular expression can be matched. Returns
341 * the skipped string, which is the entire tail if no match can be made.
342 */
841e689a 343 Scanner.prototype.scanUntil = function scanUntil (re) {
9bdcf579
DW
344 var index = this.tail.search(re), match;
345
346 switch (index) {
1549528a
AG
347 case -1:
348 match = this.tail;
349 this.tail = '';
350 break;
351 case 0:
352 match = '';
353 break;
354 default:
355 match = this.tail.substring(0, index);
356 this.tail = this.tail.substring(index);
9bdcf579
DW
357 }
358
359 this.pos += match.length;
360
361 return match;
362 };
363
364 /**
365 * Represents a rendering context by wrapping a view object and
366 * maintaining a reference to the parent context.
367 */
841e689a
DW
368 function Context (view, parentContext) {
369 this.view = view;
9bdcf579
DW
370 this.cache = { '.': this.view };
371 this.parent = parentContext;
372 }
373
374 /**
375 * Creates a new context using the given view with this context
376 * as the parent.
377 */
841e689a 378 Context.prototype.push = function push (view) {
9bdcf579
DW
379 return new Context(view, this);
380 };
381
382 /**
383 * Returns the value of the given name in this context, traversing
384 * up the context hierarchy if the value is absent in this context's view.
385 */
841e689a 386 Context.prototype.lookup = function lookup (name) {
9bdcf579
DW
387 var cache = this.cache;
388
389 var value;
841e689a 390 if (cache.hasOwnProperty(name)) {
9bdcf579
DW
391 value = cache[name];
392 } else {
a5410e13 393 var context = this, intermediateValue, names, index, lookupHit = false;
9bdcf579
DW
394
395 while (context) {
396 if (name.indexOf('.') > 0) {
a5410e13 397 intermediateValue = context.view;
9bdcf579
DW
398 names = name.split('.');
399 index = 0;
400
841e689a
DW
401 /**
402 * Using the dot notion path in `name`, we descend through the
403 * nested objects.
404 *
405 * To be certain that the lookup has been successful, we have to
406 * check if the last object in the path actually has the property
407 * we are looking for. We store the result in `lookupHit`.
408 *
409 * This is specially necessary for when the value has been set to
410 * `undefined` and we want to avoid looking up parent contexts.
a5410e13
MM
411 *
412 * In the case where dot notation is used, we consider the lookup
413 * to be successful even if the last "object" in the path is
414 * not actually an object but a primitive (e.g., a string, or an
415 * integer), because it is sometimes useful to access a property
416 * of an autoboxed primitive, such as the length of a string.
841e689a 417 **/
a5410e13 418 while (intermediateValue != null && index < names.length) {
841e689a 419 if (index === names.length - 1)
a5410e13
MM
420 lookupHit = (
421 hasProperty(intermediateValue, names[index])
422 || primitiveHasOwnProperty(intermediateValue, names[index])
423 );
841e689a 424
a5410e13 425 intermediateValue = intermediateValue[names[index++]];
841e689a
DW
426 }
427 } else {
a5410e13
MM
428 intermediateValue = context.view[name];
429
430 /**
431 * Only checking against `hasProperty`, which always returns `false` if
432 * `context.view` is not an object. Deliberately omitting the check
433 * against `primitiveHasOwnProperty` if dot notation is not used.
434 *
435 * Consider this example:
436 * ```
437 * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
438 * ```
439 *
440 * If we were to check also against `primitiveHasOwnProperty`, as we do
441 * in the dot notation case, then render call would return:
442 *
443 * "The length of a football field is 9."
444 *
445 * rather than the expected:
446 *
447 * "The length of a football field is 100 yards."
448 **/
841e689a 449 lookupHit = hasProperty(context.view, name);
9bdcf579
DW
450 }
451
a5410e13
MM
452 if (lookupHit) {
453 value = intermediateValue;
9bdcf579 454 break;
a5410e13 455 }
9bdcf579
DW
456
457 context = context.parent;
458 }
459
460 cache[name] = value;
461 }
462
463 if (isFunction(value))
464 value = value.call(this.view);
465
466 return value;
467 };
468
469 /**
470 * A Writer knows how to take a stream of tokens and render them to a
471 * string, given a context. It also maintains a cache of templates to
472 * avoid the need to parse the same template twice.
473 */
841e689a 474 function Writer () {
9bdcf579
DW
475 this.cache = {};
476 }
477
478 /**
479 * Clears all cached templates in this writer.
480 */
841e689a 481 Writer.prototype.clearCache = function clearCache () {
9bdcf579
DW
482 this.cache = {};
483 };
484
485 /**
a5410e13
MM
486 * Parses and caches the given `template` according to the given `tags` or
487 * `mustache.tags` if `tags` is omitted, and returns the array of tokens
9bdcf579
DW
488 * that is generated from the parse.
489 */
841e689a 490 Writer.prototype.parse = function parse (template, tags) {
9bdcf579 491 var cache = this.cache;
a5410e13
MM
492 var cacheKey = template + ':' + (tags || mustache.tags).join(':');
493 var tokens = cache[cacheKey];
9bdcf579
DW
494
495 if (tokens == null)
a5410e13 496 tokens = cache[cacheKey] = parseTemplate(template, tags);
9bdcf579
DW
497
498 return tokens;
499 };
500
501 /**
502 * High-level method that is used to render the given `template` with
503 * the given `view`.
504 *
505 * The optional `partials` argument may be an object that contains the
506 * names and templates of partials that are used in the template. It may
507 * also be a function that is used to load partial templates on the fly
508 * that takes a single argument: the name of the partial.
a5410e13
MM
509 *
510 * If the optional `tags` argument is given here it must be an array with two
511 * string values: the opening and closing tags used in the template (e.g.
512 * [ "<%", "%>" ]). The default is to mustache.tags.
9bdcf579 513 */
a5410e13
MM
514 Writer.prototype.render = function render (template, view, partials, tags) {
515 var tokens = this.parse(template, tags);
9bdcf579 516 var context = (view instanceof Context) ? view : new Context(view);
a5410e13 517 return this.renderTokens(tokens, context, partials, template, tags);
9bdcf579
DW
518 };
519
520 /**
521 * Low-level method that renders the given array of `tokens` using
522 * the given `context` and `partials`.
523 *
524 * Note: The `originalTemplate` is only ever used to extract the portion
525 * of the original template that was contained in a higher-order section.
526 * If the template doesn't use higher-order sections, this argument may
527 * be omitted.
528 */
a5410e13 529 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
9bdcf579
DW
530 var buffer = '';
531
841e689a 532 var token, symbol, value;
9bdcf579 533 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
841e689a 534 value = undefined;
9bdcf579 535 token = tokens[i];
841e689a
DW
536 symbol = token[0];
537
538 if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
539 else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
a5410e13 540 else if (symbol === '>') value = this.renderPartial(token, context, partials, tags);
841e689a
DW
541 else if (symbol === '&') value = this.unescapedValue(token, context);
542 else if (symbol === 'name') value = this.escapedValue(token, context);
543 else if (symbol === 'text') value = this.rawValue(token);
544
545 if (value !== undefined)
546 buffer += value;
547 }
9bdcf579 548
841e689a
DW
549 return buffer;
550 };
9bdcf579 551
841e689a
DW
552 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
553 var self = this;
554 var buffer = '';
555 var value = context.lookup(token[1]);
9bdcf579 556
841e689a
DW
557 // This function is used to render an arbitrary template
558 // in the current context by higher-order sections.
559 function subRender (template) {
560 return self.render(template, context, partials);
561 }
9bdcf579 562
841e689a 563 if (!value) return;
9bdcf579 564
841e689a
DW
565 if (isArray(value)) {
566 for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
567 buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
568 }
569 } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
570 buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
571 } else if (isFunction(value)) {
572 if (typeof originalTemplate !== 'string')
573 throw new Error('Cannot use higher-order sections without the original template');
9bdcf579 574
841e689a
DW
575 // Extract the portion of the original template that the section contains.
576 value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
9bdcf579 577
841e689a
DW
578 if (value != null)
579 buffer += value;
580 } else {
581 buffer += this.renderTokens(token[4], context, partials, originalTemplate);
582 }
583 return buffer;
584 };
9bdcf579 585
841e689a
DW
586 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
587 var value = context.lookup(token[1]);
9bdcf579 588
841e689a
DW
589 // Use JavaScript's definition of falsy. Include empty arrays.
590 // See https://github.com/janl/mustache.js/issues/186
591 if (!value || (isArray(value) && value.length === 0))
592 return this.renderTokens(token[4], context, partials, originalTemplate);
593 };
9bdcf579 594
a5410e13 595 Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
841e689a 596 if (!partials) return;
9bdcf579 597
841e689a
DW
598 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
599 if (value != null)
a5410e13 600 return this.renderTokens(this.parse(value, tags), context, partials, value);
dc9c4c51
AG
601 };
602
841e689a
DW
603 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
604 var value = context.lookup(token[1]);
605 if (value != null)
606 return value;
607 };
608
609 Writer.prototype.escapedValue = function escapedValue (token, context) {
610 var value = context.lookup(token[1]);
611 if (value != null)
612 return mustache.escape(value);
9bdcf579
DW
613 };
614
841e689a
DW
615 Writer.prototype.rawValue = function rawValue (token) {
616 return token[1];
617 };
618
619 mustache.name = 'mustache.js';
a5410e13 620 mustache.version = '3.0.1';
841e689a 621 mustache.tags = [ '{{', '}}' ];
9bdcf579
DW
622
623 // All high-level mustache.* functions use this writer.
624 var defaultWriter = new Writer();
625
626 /**
627 * Clears all cached templates in the default writer.
628 */
841e689a 629 mustache.clearCache = function clearCache () {
9bdcf579
DW
630 return defaultWriter.clearCache();
631 };
632
633 /**
634 * Parses and caches the given template in the default writer and returns the
635 * array of tokens it contains. Doing this ahead of time avoids the need to
636 * parse templates on the fly as they are rendered.
637 */
841e689a 638 mustache.parse = function parse (template, tags) {
9bdcf579
DW
639 return defaultWriter.parse(template, tags);
640 };
641
642 /**
643 * Renders the `template` with the given `view` and `partials` using the
a5410e13
MM
644 * default writer. If the optional `tags` argument is given here it must be an
645 * array with two string values: the opening and closing tags used in the
646 * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
9bdcf579 647 */
a5410e13 648 mustache.render = function render (template, view, partials, tags) {
841e689a
DW
649 if (typeof template !== 'string') {
650 throw new TypeError('Invalid template! Template should be a "string" ' +
651 'but "' + typeStr(template) + '" was given as the first ' +
652 'argument for mustache#render(template, view, partials)');
653 }
654
a5410e13 655 return defaultWriter.render(template, view, partials, tags);
9bdcf579
DW
656 };
657
841e689a
DW
658 // This is here for backwards compatibility with 0.4.x.,
659 /*eslint-disable */ // eslint wants camel cased function name
660 mustache.to_html = function to_html (template, view, partials, send) {
661 /*eslint-enable*/
662
9bdcf579
DW
663 var result = mustache.render(template, view, partials);
664
665 if (isFunction(send)) {
666 send(result);
667 } else {
668 return result;
669 }
670 };
671
672 // Export the escaping function so that the user may override it.
673 // See https://github.com/janl/mustache.js/issues/244
674 mustache.escape = escapeHtml;
675
676 // Export these mainly for testing, but also for advanced usage.
677 mustache.Scanner = Scanner;
678 mustache.Context = Context;
679 mustache.Writer = Writer;
680
5adc70b7 681 return mustache;
9bdcf579 682}));