MDL-51579 course: Bump version to update mobile service
[moodle.git] / lib / amd / src / mustache.js
blobafaca9c0ff6b93e58510e0e92ffe04f0ce62f9d5
1 // The MIT License
2 //
3 // Copyright (c) 2009 Chris Wanstrath (Ruby)
4 // Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the
8 // "Software"), to deal in the Software without restriction, including
9 // without limitation the rights to use, copy, modify, merge, publish,
10 // distribute, sublicense, and/or sell copies of the Software, and to
11 // permit persons to whom the Software is furnished to do so, subject to
12 // the following conditions:
14 // The above copyright notice and this permission notice shall be
15 // included in all copies or substantial portions of the Software.
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 // Description of import into Moodle:
27 // Checkout from https://github.com/moodle/custom-mustache.js
28 // Rebase onto latest release tag from https://github.com/janl/mustache.js
29 // Copy mustache.js into lib/amd/src/ in Moodle folder.
30 // Add the license as a comment to the file and these instructions.
31 // Add jshint tags so this file is not linted.
32 // Remove the "global define:" comment (hint for linter)
34 /*!
35  * mustache.js - Logic-less {{mustache}} templates with JavaScript
36  * http://github.com/janl/mustache.js
37  */
39 /* jshint ignore:start */
41 (function defineMustache (global, factory) {
42   if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
43     factory(exports); // CommonJS
44   } else if (typeof define === 'function' && define.amd) {
45     define(['exports'], factory); // AMD
46   } else {
47     global.Mustache = {};
48     factory(Mustache); // script, wsh, asp
49   }
50 }(this, function mustacheFactory (mustache) {
52   var objectToString = Object.prototype.toString;
53   var isArray = Array.isArray || function isArrayPolyfill (object) {
54     return objectToString.call(object) === '[object Array]';
55   };
57   function isFunction (object) {
58     return typeof object === 'function';
59   }
61   /**
62    * More correct typeof string handling array
63    * which normally returns typeof 'object'
64    */
65   function typeStr (obj) {
66     return isArray(obj) ? 'array' : typeof obj;
67   }
69   function escapeRegExp (string) {
70     return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
71   }
73   /**
74    * Null safe way of checking whether or not an object,
75    * including its prototype, has a given property
76    */
77   function hasProperty (obj, propName) {
78     return obj != null && typeof obj === 'object' && (propName in obj);
79   }
81   // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
82   // See https://github.com/janl/mustache.js/issues/189
83   var regExpTest = RegExp.prototype.test;
84   function testRegExp (re, string) {
85     return regExpTest.call(re, string);
86   }
88   var nonSpaceRe = /\S/;
89   function isWhitespace (string) {
90     return !testRegExp(nonSpaceRe, string);
91   }
93   var entityMap = {
94     '&': '&',
95     '<': '&lt;',
96     '>': '&gt;',
97     '"': '&quot;',
98     "'": '&#39;',
99     '/': '&#x2F;'
100   };
102   function escapeHtml (string) {
103     return String(string).replace(/[&<>"'\/]/g, function fromEntityMap (s) {
104       return entityMap[s];
105     });
106   }
108   var whiteRe = /\s*/;
109   var spaceRe = /\s+/;
110   var equalsRe = /\s*=/;
111   var curlyRe = /\s*\}/;
112   var tagRe = /#|\^|\/|>|\{|&|=|!|\$|</;
114   /**
115    * Breaks up the given `template` string into a tree of tokens. If the `tags`
116    * argument is given here it must be an array with two string values: the
117    * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
118    * course, the default is to use mustaches (i.e. mustache.tags).
119    *
120    * A token is an array with at least 4 elements. The first element is the
121    * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
122    * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
123    * all text that appears outside a symbol this element is "text".
124    *
125    * The second element of a token is its "value". For mustache tags this is
126    * whatever else was inside the tag besides the opening symbol. For text tokens
127    * this is the text itself.
128    *
129    * The third and fourth elements of the token are the start and end indices,
130    * respectively, of the token in the original template.
131    *
132    * Tokens that are the root node of a subtree contain two more elements: 1) an
133    * array of tokens in the subtree and 2) the index in the original template at
134    * which the closing tag for that section begins.
135    */
136   function parseTemplate (template, tags) {
137     if (!template)
138       return [];
140     var sections = [];     // Stack to hold section tokens
141     var tokens = [];       // Buffer to hold the tokens
142     var spaces = [];       // Indices of whitespace tokens on the current line
143     var hasTag = false;    // Is there a {{tag}} on the current line?
144     var nonSpace = false;  // Is there a non-space char on the current line?
146     // Strips all whitespace tokens array for the current line
147     // if there was a {{#tag}} on it and otherwise only space.
148     function stripSpace () {
149       if (hasTag && !nonSpace) {
150         while (spaces.length)
151           delete tokens[spaces.pop()];
152       } else {
153         spaces = [];
154       }
156       hasTag = false;
157       nonSpace = false;
158     }
160     var openingTagRe, closingTagRe, closingCurlyRe;
161     function compileTags (tagsToCompile) {
162       if (typeof tagsToCompile === 'string')
163         tagsToCompile = tagsToCompile.split(spaceRe, 2);
165       if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
166         throw new Error('Invalid tags: ' + tagsToCompile);
168       openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
169       closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
170       closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
171     }
173     compileTags(tags || mustache.tags);
175     var scanner = new Scanner(template);
177     var start, type, value, chr, token, openSection;
178     while (!scanner.eos()) {
179       start = scanner.pos;
181       // Match any text between tags.
182       value = scanner.scanUntil(openingTagRe);
184       if (value) {
185         for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
186           chr = value.charAt(i);
188           if (isWhitespace(chr)) {
189             spaces.push(tokens.length);
190           } else {
191             nonSpace = true;
192           }
194           tokens.push([ 'text', chr, start, start + 1 ]);
195           start += 1;
197           // Check for whitespace on the current line.
198           if (chr === '\n')
199             stripSpace();
200         }
201       }
203       // Match the opening tag.
204       if (!scanner.scan(openingTagRe))
205         break;
207       hasTag = true;
209       // Get the tag type.
210       type = scanner.scan(tagRe) || 'name';
211       scanner.scan(whiteRe);
213       // Get the tag value.
214       if (type === '=') {
215         value = scanner.scanUntil(equalsRe);
216         scanner.scan(equalsRe);
217         scanner.scanUntil(closingTagRe);
218       } else if (type === '{') {
219         value = scanner.scanUntil(closingCurlyRe);
220         scanner.scan(curlyRe);
221         scanner.scanUntil(closingTagRe);
222         type = '&';
223       } else {
224         value = scanner.scanUntil(closingTagRe);
225       }
227       // Match the closing tag.
228       if (!scanner.scan(closingTagRe))
229         throw new Error('Unclosed tag at ' + scanner.pos);
231       token = [ type, value, start, scanner.pos ];
232       tokens.push(token);
234       if (type === '#' || type === '^' || type === '$' || type === '<') {
235         sections.push(token);
236       } else if (type === '/') {
237         // Check section nesting.
238         openSection = sections.pop();
240         if (!openSection)
241           throw new Error('Unopened section "' + value + '" at ' + start);
243         if (openSection[1] !== value)
244           throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
245       } else if (type === 'name' || type === '{' || type === '&') {
246         nonSpace = true;
247       } else if (type === '=') {
248         // Set the tags for the next time around.
249         compileTags(value);
250       }
251     }
253     // Make sure there are no open sections when we're done.
254     openSection = sections.pop();
256     if (openSection)
257       throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
259     return nestTokens(squashTokens(tokens));
260   }
262   /**
263    * Combines the values of consecutive text tokens in the given `tokens` array
264    * to a single token.
265    */
266   function squashTokens (tokens) {
267     var squashedTokens = [];
269     var token, lastToken;
270     for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
271       token = tokens[i];
273       if (token) {
274         if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
275           lastToken[1] += token[1];
276           lastToken[3] = token[3];
277         } else {
278           squashedTokens.push(token);
279           lastToken = token;
280         }
281       }
282     }
284     return squashedTokens;
285   }
287   /**
288    * Forms the given array of `tokens` into a nested tree structure where
289    * tokens that represent a section have two additional items: 1) an array of
290    * all tokens that appear in that section and 2) the index in the original
291    * template that represents the end of that section.
292    */
293   function nestTokens (tokens) {
294     var nestedTokens = [];
295     var collector = nestedTokens;
296     var sections = [];
298     var token, section;
299     for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
300       token = tokens[i];
302       switch (token[0]) {
303       case '$':
304       case '<':
305       case '#':
306       case '^':
307         collector.push(token);
308         sections.push(token);
309         collector = token[4] = [];
310         break;
311       case '/':
312         section = sections.pop();
313         section[5] = token[2];
314         collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
315         break;
316       default:
317         collector.push(token);
318       }
319     }
321     return nestedTokens;
322   }
324   /**
325    * A simple string scanner that is used by the template parser to find
326    * tokens in template strings.
327    */
328   function Scanner (string) {
329     this.string = string;
330     this.tail = string;
331     this.pos = 0;
332   }
334   /**
335    * Returns `true` if the tail is empty (end of string).
336    */
337   Scanner.prototype.eos = function eos () {
338     return this.tail === '';
339   };
341   /**
342    * Tries to match the given regular expression at the current position.
343    * Returns the matched text if it can match, the empty string otherwise.
344    */
345   Scanner.prototype.scan = function scan (re) {
346     var match = this.tail.match(re);
348     if (!match || match.index !== 0)
349       return '';
351     var string = match[0];
353     this.tail = this.tail.substring(string.length);
354     this.pos += string.length;
356     return string;
357   };
359   /**
360    * Skips all text until the given regular expression can be matched. Returns
361    * the skipped string, which is the entire tail if no match can be made.
362    */
363   Scanner.prototype.scanUntil = function scanUntil (re) {
364     var index = this.tail.search(re), match;
366     switch (index) {
367     case -1:
368       match = this.tail;
369       this.tail = '';
370       break;
371     case 0:
372       match = '';
373       break;
374     default:
375       match = this.tail.substring(0, index);
376       this.tail = this.tail.substring(index);
377     }
379     this.pos += match.length;
381     return match;
382   };
384   /**
385    * Represents a rendering context by wrapping a view object and
386    * maintaining a reference to the parent context.
387    */
388   function Context (view, parentContext) {
389     this.view = view;
390     this.blocks = {};
391     this.cache = { '.': this.view };
392     this.parent = parentContext;
393   }
395   /**
396    * Creates a new context using the given view with this context
397    * as the parent.
398    */
399   Context.prototype.push = function push (view) {
400     return new Context(view, this);
401   };
403   /**
404    * Set a value in the current block context.
405    */
406   Context.prototype.setBlockVar = function set (name, value) {
407     var blocks = this.blocks;
409     blocks[name] = value;
411     return value;
412   };
414   /**
415    * Clear all current block vars.
416    */
417   Context.prototype.clearBlockVars = function clearBlockVars () {
418     this.blocks = {};
419   };
421   /**
422    * Get a value only from the current block context.
423    */
424   Context.prototype.getBlockVar = function getBlockVar (name) {
425     var blocks = this.blocks;
427     var value;
428     if (blocks.hasOwnProperty(name)) {
429       value = blocks[name];
430     } else {
431       if (this.parent) {
432         value = this.parent.getBlockVar(name);
433       }
434     }
435     // Can return undefined.
436     return value;
437   };
439   /**
440    * Returns the value of the given name in this context, traversing
441    * up the context hierarchy if the value is absent in this context's view.
442    */
443   Context.prototype.lookup = function lookup (name) {
444     var cache = this.cache;
446     var value;
447     if (cache.hasOwnProperty(name)) {
448       value = cache[name];
449     } else {
450       var context = this, names, index, lookupHit = false;
452       while (context) {
453         if (name.indexOf('.') > 0) {
454           value = context.view;
455           names = name.split('.');
456           index = 0;
458           /**
459            * Using the dot notion path in `name`, we descend through the
460            * nested objects.
461            *
462            * To be certain that the lookup has been successful, we have to
463            * check if the last object in the path actually has the property
464            * we are looking for. We store the result in `lookupHit`.
465            *
466            * This is specially necessary for when the value has been set to
467            * `undefined` and we want to avoid looking up parent contexts.
468            **/
469           while (value != null && index < names.length) {
470             if (index === names.length - 1)
471               lookupHit = hasProperty(value, names[index]);
473             value = value[names[index++]];
474           }
475         } else {
476           value = context.view[name];
477           lookupHit = hasProperty(context.view, name);
478         }
480         if (lookupHit)
481           break;
483         context = context.parent;
484       }
486       cache[name] = value;
487     }
489     if (isFunction(value))
490       value = value.call(this.view);
492     return value;
493   };
495   /**
496    * A Writer knows how to take a stream of tokens and render them to a
497    * string, given a context. It also maintains a cache of templates to
498    * avoid the need to parse the same template twice.
499    */
500   function Writer () {
501     this.cache = {};
502   }
504   /**
505    * Clears all cached templates in this writer.
506    */
507   Writer.prototype.clearCache = function clearCache () {
508     this.cache = {};
509   };
511   /**
512    * Parses and caches the given `template` and returns the array of tokens
513    * that is generated from the parse.
514    */
515   Writer.prototype.parse = function parse (template, tags) {
516     var cache = this.cache;
517     var tokens = cache[template];
519     if (tokens == null)
520       tokens = cache[template] = parseTemplate(template, tags);
522     return tokens;
523   };
525   /**
526    * High-level method that is used to render the given `template` with
527    * the given `view`.
528    *
529    * The optional `partials` argument may be an object that contains the
530    * names and templates of partials that are used in the template. It may
531    * also be a function that is used to load partial templates on the fly
532    * that takes a single argument: the name of the partial.
533    */
534   Writer.prototype.render = function render (template, view, partials) {
535     var tokens = this.parse(template);
536     var context = (view instanceof Context) ? view : new Context(view);
537     return this.renderTokens(tokens, context, partials, template);
538   };
540   /**
541    * Low-level method that renders the given array of `tokens` using
542    * the given `context` and `partials`.
543    *
544    * Note: The `originalTemplate` is only ever used to extract the portion
545    * of the original template that was contained in a higher-order section.
546    * If the template doesn't use higher-order sections, this argument may
547    * be omitted.
548    */
549   Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
550     var buffer = '';
552     var token, symbol, value;
553     for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
554       value = undefined;
555       token = tokens[i];
556       symbol = token[0];
558       if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
559       else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
560       else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
561       else if (symbol === '<') value = this.renderBlock(token, context, partials, originalTemplate);
562       else if (symbol === '$') value = this.renderBlockVariable(token, context, partials, originalTemplate);
563       else if (symbol === '&') value = this.unescapedValue(token, context);
564       else if (symbol === 'name') value = this.escapedValue(token, context);
565       else if (symbol === 'text') value = this.rawValue(token);
567       if (value !== undefined)
568         buffer += value;
569     }
571     return buffer;
572   };
574   Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
575     var self = this;
576     var buffer = '';
577     var value = context.lookup(token[1]);
579     // This function is used to render an arbitrary template
580     // in the current context by higher-order sections.
581     function subRender (template) {
582       return self.render(template, context, partials);
583     }
585     if (!value) return;
587     if (isArray(value)) {
588       for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
589         buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
590       }
591     } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
592       buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
593     } else if (isFunction(value)) {
594       if (typeof originalTemplate !== 'string')
595         throw new Error('Cannot use higher-order sections without the original template');
597       // Extract the portion of the original template that the section contains.
598       value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
600       if (value != null)
601         buffer += value;
602     } else {
603       buffer += this.renderTokens(token[4], context, partials, originalTemplate);
604     }
605     return buffer;
606   };
608   Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
609     var value = context.lookup(token[1]);
611     // Use JavaScript's definition of falsy. Include empty arrays.
612     // See https://github.com/janl/mustache.js/issues/186
613     if (!value || (isArray(value) && value.length === 0))
614       return this.renderTokens(token[4], context, partials, originalTemplate);
615   };
617   Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
618     if (!partials) return;
620     var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
621     if (value != null)
622       return this.renderTokens(this.parse(value), context, partials, value);
623   };
625   Writer.prototype.renderBlock = function renderBlock (token, context, partials, originalTemplate) {
626     if (!partials) return;
628     var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
629     if (value != null)
630       // Ignore any wrongly set block vars before we started.
631       context.clearBlockVars();
632       // We are only rendering to record the default block variables.
633       this.renderTokens(token[4], context, partials, originalTemplate);
634       // Now we render and return the result.
635       var result = this.renderTokens(this.parse(value), context, partials, value);
636       // Don't leak the block variables outside this include.
637       context.clearBlockVars();
638       return result;
639   };
641   Writer.prototype.renderBlockVariable = function renderBlockVariable (token, context, partials, originalTemplate) {
642     var value = token[1];
644     var exists = context.getBlockVar(value);
645     if (!exists) {
646       context.setBlockVar(value, originalTemplate.slice(token[3], token[5]));
647       return this.renderTokens(token[4], context, partials, originalTemplate);
648     } else {
649       return this.renderTokens(this.parse(exists), context, partials, exists);
650     }
651   };
653   Writer.prototype.unescapedValue = function unescapedValue (token, context) {
654     var value = context.lookup(token[1]);
655     if (value != null)
656       return value;
657   };
659   Writer.prototype.escapedValue = function escapedValue (token, context) {
660     var value = context.lookup(token[1]);
661     if (value != null)
662       return mustache.escape(value);
663   };
665   Writer.prototype.rawValue = function rawValue (token) {
666     return token[1];
667   };
669   mustache.name = 'mustache.js';
670   mustache.version = '2.1.3';
671   mustache.tags = [ '{{', '}}' ];
673   // All high-level mustache.* functions use this writer.
674   var defaultWriter = new Writer();
676   /**
677    * Clears all cached templates in the default writer.
678    */
679   mustache.clearCache = function clearCache () {
680     return defaultWriter.clearCache();
681   };
683   /**
684    * Parses and caches the given template in the default writer and returns the
685    * array of tokens it contains. Doing this ahead of time avoids the need to
686    * parse templates on the fly as they are rendered.
687    */
688   mustache.parse = function parse (template, tags) {
689     return defaultWriter.parse(template, tags);
690   };
692   /**
693    * Renders the `template` with the given `view` and `partials` using the
694    * default writer.
695    */
696   mustache.render = function render (template, view, partials) {
697     if (typeof template !== 'string') {
698       throw new TypeError('Invalid template! Template should be a "string" ' +
699                           'but "' + typeStr(template) + '" was given as the first ' +
700                           'argument for mustache#render(template, view, partials)');
701     }
703     return defaultWriter.render(template, view, partials);
704   };
706   // This is here for backwards compatibility with 0.4.x.,
707   /*eslint-disable */ // eslint wants camel cased function name
708   mustache.to_html = function to_html (template, view, partials, send) {
709     /*eslint-enable*/
711     var result = mustache.render(template, view, partials);
713     if (isFunction(send)) {
714       send(result);
715     } else {
716       return result;
717     }
718   };
720   // Export the escaping function so that the user may override it.
721   // See https://github.com/janl/mustache.js/issues/244
722   mustache.escape = escapeHtml;
724   // Export these mainly for testing, but also for advanced usage.
725   mustache.Scanner = Scanner;
726   mustache.Context = Context;
727   mustache.Writer = Writer;
729 }));
730 /* jshint ignore:end */