MDL-54687 core_message: added ability to delete messages
[moodle.git] / lib / amd / src / templates.js
CommitLineData
9bdcf579
DW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Template renderer for Moodle. Load and render Moodle templates with Mustache.
18 *
19 * @module core/templates
20 * @package core
21 * @class templates
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since 2.9
25 */
35be5826 26define(['core/mustache',
9bdcf579
DW
27 'jquery',
28 'core/ajax',
29 'core/str',
30 'core/notification',
31 'core/url',
4b9e5326 32 'core/config',
28de7771 33 'core/localstorage',
1fca8a7b 34 'core/event',
29879f8f
FM
35 'core/yui',
36 'core/log'
9bdcf579 37 ],
29879f8f 38 function(mustache, $, ajax, str, notification, coreurl, config, storage, event, Y, Log) {
9bdcf579 39
8d00afb1
DW
40 // Module variables.
41 /** @var {Number} uniqInstances Count of times this constructor has been called. */
42 var uniqInstances = 0;
9bdcf579
DW
43
44 /** @var {string[]} templateCache - Cache of already loaded templates */
45 var templateCache = {};
46
8d00afb1
DW
47 /**
48 * Constructor
49 *
50 * Each call to templates.render gets it's own instance of this class.
51 */
52 var Renderer = function() {
53 this.requiredStrings = [];
54 this.requiredJS = [];
55 this.currentThemeName = '';
56 };
57 // Class variables and functions.
58
9bdcf579 59 /** @var {string[]} requiredStrings - Collection of strings found during the rendering of one template */
8d00afb1 60 Renderer.prototype.requiredStrings = null;
9bdcf579
DW
61
62 /** @var {string[]} requiredJS - Collection of js blocks found during the rendering of one template */
8d00afb1 63 Renderer.prototype.requiredJS = null;
9bdcf579
DW
64
65 /** @var {String} themeName for the current render */
8d00afb1 66 Renderer.prototype.currentThemeName = '';
9bdcf579 67
f992dcf6
DP
68 /**
69 * Load a template from the cache or local storage or ajax request.
70 *
71 * @method getTemplate
72 * @private
73 * @param {string} templateName - should consist of the component and the name of the template like this:
74 * core/menu (lib/templates/menu.mustache) or
75 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
c96f55e6 76 * @param {Boolean} async If false - this function will not return until the promises are resolved.
f992dcf6
DP
77 * @return {Promise} JQuery promise object resolved when the template has been fetched.
78 */
8d00afb1 79 Renderer.prototype.getTemplate = function(templateName, async) {
f992dcf6
DP
80 var deferred = $.Deferred();
81 var parts = templateName.split('/');
82 var component = parts.shift();
83 var name = parts.shift();
84
8d00afb1 85 var searchKey = this.currentThemeName + '/' + templateName;
f992dcf6
DP
86
87 // First try request variables.
88 if (searchKey in templateCache) {
89 deferred.resolve(templateCache[searchKey]);
90 return deferred.promise();
91 }
92
93 // Now try local storage.
94 var cached = storage.get('core_template/' + searchKey);
95
96 if (cached) {
97 deferred.resolve(cached);
98 templateCache[searchKey] = cached;
99 return deferred.promise();
100 }
101
102 // Oh well - load via ajax.
103 var promises = ajax.call([{
104 methodname: 'core_output_load_template',
35be5826 105 args: {
f992dcf6
DP
106 component: component,
107 template: name,
8d00afb1 108 themename: this.currentThemeName
f992dcf6
DP
109 }
110 }], async, false);
111
112 promises[0].done(
35be5826 113 function(templateSource) {
f992dcf6
DP
114 storage.set('core_template/' + searchKey, templateSource);
115 templateCache[searchKey] = templateSource;
116 deferred.resolve(templateSource);
117 }
118 ).fail(
35be5826 119 function(ex) {
f992dcf6
DP
120 deferred.reject(ex);
121 }
122 );
123 return deferred.promise();
124 };
125
126 /**
127 * Load a partial from the cache or ajax.
128 *
129 * @method partialHelper
130 * @private
131 * @param {string} name The partial name to load.
132 * @return {string}
133 */
8d00afb1 134 Renderer.prototype.partialHelper = function(name) {
f992dcf6
DP
135 var template = '';
136
8d00afb1 137 this.getTemplate(name, false).done(
f992dcf6
DP
138 function(source) {
139 template = source;
140 }
141 ).fail(notification.exception);
142
143 return template;
144 };
145
9bdcf579
DW
146 /**
147 * Render image icons.
148 *
149 * @method pixHelper
150 * @private
8d00afb1 151 * @param {object} context The mustache context
9bdcf579 152 * @param {string} sectionText The text to parse arguments from.
e37d53da 153 * @param {function} helper Used to render the alt attribute of the text.
9bdcf579
DW
154 * @return {string}
155 */
8d00afb1 156 Renderer.prototype.pixHelper = function(context, sectionText, helper) {
9bdcf579
DW
157 var parts = sectionText.split(',');
158 var key = '';
159 var component = '';
160 var text = '';
161 var result;
162
163 if (parts.length > 0) {
164 key = parts.shift().trim();
165 }
166 if (parts.length > 0) {
167 component = parts.shift().trim();
168 }
169 if (parts.length > 0) {
170 text = parts.join(',').trim();
171 }
172 var url = coreurl.imageUrl(key, component);
173
174 var templatecontext = {
175 attributes: [
9f5f3dcc
DP
176 {name: 'src', value: url},
177 {name: 'alt', value: helper(text)},
8354d12d 178 {name: 'title', value: helper(text)},
9f5f3dcc 179 {name: 'class', value: 'smallicon'}
9bdcf579
DW
180 ]
181 };
182 // We forced loading of this early, so it will be in the cache.
8d00afb1
DW
183 var template = templateCache[this.currentThemeName + '/core/pix_icon'];
184 result = mustache.render(template, templatecontext, this.partialHelper.bind(this));
9bdcf579
DW
185 return result.trim();
186 };
187
9bdcf579
DW
188 /**
189 * Render blocks of javascript and save them in an array.
190 *
191 * @method jsHelper
192 * @private
8d00afb1 193 * @param {object} context The current mustache context.
9bdcf579
DW
194 * @param {string} sectionText The text to save as a js block.
195 * @param {function} helper Used to render the block.
196 * @return {string}
197 */
8d00afb1
DW
198 Renderer.prototype.jsHelper = function(context, sectionText, helper) {
199 this.requiredJS.push(helper(sectionText, context));
9bdcf579
DW
200 return '';
201 };
202
203 /**
204 * String helper used to render {{#str}}abd component { a : 'fish'}{{/str}}
205 * into a get_string call.
206 *
207 * @method stringHelper
208 * @private
8d00afb1 209 * @param {object} context The current mustache context.
9bdcf579
DW
210 * @param {string} sectionText The text to parse the arguments from.
211 * @param {function} helper Used to render subsections of the text.
212 * @return {string}
213 */
8d00afb1 214 Renderer.prototype.stringHelper = function(context, sectionText, helper) {
9bdcf579
DW
215 var parts = sectionText.split(',');
216 var key = '';
217 var component = '';
218 var param = '';
219 if (parts.length > 0) {
220 key = parts.shift().trim();
221 }
222 if (parts.length > 0) {
223 component = parts.shift().trim();
224 }
225 if (parts.length > 0) {
226 param = parts.join(',').trim();
227 }
228
229 if (param !== '') {
230 // Allow variable expansion in the param part only.
8d00afb1 231 param = helper(param, context);
9bdcf579
DW
232 }
233 // Allow json formatted $a arguments.
234 if ((param.indexOf('{') === 0) && (param.indexOf('{{') !== 0)) {
235 param = JSON.parse(param);
236 }
237
8d00afb1
DW
238 var index = this.requiredStrings.length;
239 this.requiredStrings.push({key: key, component: component, param: param});
9bdcf579
DW
240 return '{{_s' + index + '}}';
241 };
242
0b4bff8c
AN
243 /**
244 * Quote helper used to wrap content in quotes, and escape all quotes present in the content.
245 *
246 * @method quoteHelper
247 * @private
8d00afb1 248 * @param {object} context The current mustache context.
0b4bff8c
AN
249 * @param {string} sectionText The text to parse the arguments from.
250 * @param {function} helper Used to render subsections of the text.
251 * @return {string}
252 */
8d00afb1
DW
253 Renderer.prototype.quoteHelper = function(context, sectionText, helper) {
254 var content = helper(sectionText.trim(), context);
0b4bff8c
AN
255
256 // Escape the {{ and the ".
257 // This involves wrapping {{, and }} in change delimeter tags.
258 content = content
259 .replace('"', '\\"')
260 .replace(/([\{\}]{2,3})/g, '{{=<% %>=}}$1<%={{ }}=%>')
261 ;
262 return '"' + content + '"';
263 };
264
9bdcf579
DW
265 /**
266 * Add some common helper functions to all context objects passed to templates.
267 * These helpers match exactly the helpers available in php.
268 *
269 * @method addHelpers
270 * @private
271 * @param {Object} context Simple types used as the context for the template.
272 * @param {String} themeName We set this multiple times, because there are async calls.
273 */
8d00afb1
DW
274 Renderer.prototype.addHelpers = function(context, themeName) {
275 this.currentThemeName = themeName;
276 this.requiredStrings = [];
277 this.requiredJS = [];
278 context.uniqid = (uniqInstances++);
c96f55e6 279 context.str = function() {
8d00afb1
DW
280 return this.stringHelper.bind(this, context);
281 }.bind(this);
c96f55e6 282 context.pix = function() {
8d00afb1
DW
283 return this.pixHelper.bind(this, context);
284 }.bind(this);
c96f55e6 285 context.js = function() {
8d00afb1
DW
286 return this.jsHelper.bind(this, context);
287 }.bind(this);
c96f55e6 288 context.quote = function() {
8d00afb1
DW
289 return this.quoteHelper.bind(this, context);
290 }.bind(this);
9f5f3dcc 291 context.globals = {config: config};
9bdcf579
DW
292 context.currentTheme = themeName;
293 };
294
295 /**
296 * Get all the JS blocks from the last rendered template.
297 *
298 * @method getJS
299 * @private
300 * @param {string[]} strings Replacement strings.
301 * @return {string}
302 */
8d00afb1 303 Renderer.prototype.getJS = function(strings) {
9bdcf579 304 var js = '';
8d00afb1
DW
305 if (this.requiredJS.length > 0) {
306 js = this.requiredJS.join(";\n");
9bdcf579
DW
307 }
308
9bdcf579 309 // Re-render to get the final strings.
8d00afb1 310 return this.treatStringsInContent(js, strings);
29879f8f
FM
311 };
312
313 /**
314 * Treat strings in content.
315 *
316 * The purpose of this method is to replace the placeholders found in a string
317 * with the their respective translated strings.
318 *
319 * Previously we were relying on String.replace() but the complexity increased with
320 * the numbers of strings to replace. Now we manually walk the string and stop at each
321 * placeholder we find, only then we replace it. Most of the time we will
322 * replace all the placeholders in a single run, at times we will need a few
323 * more runs when placeholders are replaced with strings that contain placeholders
324 * themselves.
325 *
326 * @param {String} content The content in which string placeholders are to be found.
327 * @param {Array} strings The strings to replace with.
328 * @return {String} The treated content.
329 */
8d00afb1 330 Renderer.prototype.treatStringsInContent = function(content, strings) {
29879f8f
FM
331 var pattern = /{{_s\d+}}/,
332 treated,
333 index,
334 strIndex,
335 walker,
336 char,
337 strFinal;
338
339 do {
340 treated = '';
341 index = content.search(pattern);
342 while (index > -1) {
343
344 // Copy the part prior to the placeholder to the treated string.
345 treated += content.substring(0, index);
346 content = content.substr(index);
347 strIndex = '';
348 walker = 4; // 4 is the length of '{{_s'.
349
350 // Walk the characters to manually extract the index of the string from the placeholder.
351 char = content.substr(walker, 1);
352 do {
353 strIndex += char;
354 walker++;
355 char = content.substr(walker, 1);
356 } while (char != '}');
357
358 // Get the string, add it to the treated result, and remove the placeholder from the content to treat.
359 strFinal = strings[parseInt(strIndex, 10)];
360 if (typeof strFinal === 'undefined') {
361 Log.debug('Could not find string for pattern {{_s' + strIndex + '}}.');
362 strFinal = '';
363 }
364 treated += strFinal;
365 content = content.substr(6 + strIndex.length); // 6 is the length of the placeholder without the index: '{{_s}}'.
366
367 // Find the next placeholder.
368 index = content.search(pattern);
369 }
370
371 // The content becomes the treated part with the rest of the content.
372 content = treated + content;
373
374 // Check if we need to walk the content again, in case strings contained placeholders.
375 index = content.search(pattern);
376
377 } while (index > -1);
378
379 return content;
9bdcf579
DW
380 };
381
382 /**
383 * Render a template and then call the callback with the result.
384 *
385 * @method doRender
386 * @private
387 * @param {string} templateSource The mustache template to render.
388 * @param {Object} context Simple types used as the context for the template.
389 * @param {String} themeName Name of the current theme.
390 * @return {Promise} object
391 */
8d00afb1 392 Renderer.prototype.doRender = function(templateSource, context, themeName) {
9bdcf579
DW
393 var deferred = $.Deferred();
394
8d00afb1 395 this.currentThemeName = themeName;
9bdcf579
DW
396
397 // Make sure we fetch this first.
8d00afb1 398 var loadPixTemplate = this.getTemplate('core/pix_icon', true);
9bdcf579
DW
399
400 loadPixTemplate.done(
401 function() {
8d00afb1 402 this.addHelpers(context, themeName);
9bdcf579
DW
403 var result = '';
404 try {
8d00afb1 405 result = mustache.render(templateSource, context, this.partialHelper.bind(this));
9bdcf579
DW
406 } catch (ex) {
407 deferred.reject(ex);
408 }
409
8d00afb1
DW
410 if (this.requiredStrings.length > 0) {
411 str.get_strings(this.requiredStrings)
29879f8f
FM
412 .then(function(strings) {
413
414 // Why do we not do another call the render here?
415 //
416 // Because that would expose DOS holes. E.g.
417 // I create an assignment called "{{fish" which
418 // would get inserted in the template in the first pass
419 // and cause the template to die on the second pass (unbalanced).
420
8d00afb1
DW
421 result = this.treatStringsInContent(result, strings);
422 deferred.resolve(result, this.getJS(strings));
423 }.bind(this))
29879f8f 424 .fail(deferred.reject);
9bdcf579 425 } else {
8d00afb1 426 deferred.resolve(result.trim(), this.getJS([]));
9bdcf579 427 }
8d00afb1 428 }.bind(this)
29879f8f 429 ).fail(deferred.reject);
9bdcf579
DW
430 return deferred.promise();
431 };
432
28de7771
DW
433 /**
434 * Execute a block of JS returned from a template.
435 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
436 *
437 * @method runTemplateJS
438 * @param {string} source - A block of javascript.
439 */
440 var runTemplateJS = function(source) {
441 if (source.trim() !== '') {
35be5826 442 var newscript = $('<script>').attr('type', 'text/javascript').html(source);
28de7771
DW
443 $('head').append(newscript);
444 }
445 };
446
447 /**
448 * Do some DOM replacement and trigger correct events and fire javascript.
449 *
450 * @method domReplace
451 * @private
452 * @param {JQuery} element - Element or selector to replace.
453 * @param {String} newHTML - HTML to insert / replace.
454 * @param {String} newJS - Javascript to run after the insertion.
455 * @param {Boolean} replaceChildNodes - Replace only the childnodes, alternative is to replace the entire node.
456 */
457 var domReplace = function(element, newHTML, newJS, replaceChildNodes) {
458 var replaceNode = $(element);
459 if (replaceNode.length) {
460 // First create the dom nodes so we have a reference to them.
461 var newNodes = $(newHTML);
1fca8a7b 462 var yuiNodes = null;
28de7771
DW
463 // Do the replacement in the page.
464 if (replaceChildNodes) {
1fca8a7b
DW
465 // Cleanup any YUI event listeners attached to any of these nodes.
466 yuiNodes = new Y.NodeList(replaceNode.children().get());
467 yuiNodes.destroy(true);
468
469 // JQuery will cleanup after itself.
28de7771
DW
470 replaceNode.empty();
471 replaceNode.append(newNodes);
472 } else {
1fca8a7b
DW
473 // Cleanup any YUI event listeners attached to any of these nodes.
474 yuiNodes = new Y.NodeList(replaceNode.get());
475 yuiNodes.destroy(true);
476
477 // JQuery will cleanup after itself.
28de7771
DW
478 replaceNode.replaceWith(newNodes);
479 }
480 // Run any javascript associated with the new HTML.
481 runTemplateJS(newJS);
482 // Notify all filters about the new content.
483 event.notifyFilterContentUpdated(newNodes);
484 }
485 };
486
8d00afb1
DW
487 /**
488 * Load a template and call doRender on it.
489 *
490 * @method render
491 * @private
492 * @param {string} templateName - should consist of the component and the name of the template like this:
493 * core/menu (lib/templates/menu.mustache) or
494 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
495 * @param {Object} context - Could be array, string or simple value for the context of the template.
496 * @param {string} themeName - Name of the current theme.
497 * @return {Promise} JQuery promise object resolved when the template has been rendered.
498 */
499 Renderer.prototype.render = function(templateName, context, themeName) {
500 var deferred = $.Deferred();
501
502 if (typeof (themeName) === "undefined") {
503 // System context by default.
504 themeName = config.theme;
505 }
506
507 this.currentThemeName = themeName;
508
509 var loadTemplate = this.getTemplate(templateName, true);
510
511 loadTemplate.done(
512 function(templateSource) {
513 var renderPromise = this.doRender(templateSource, context, themeName);
514
515 renderPromise.done(
516 function(result, js) {
517 deferred.resolve(result, js);
518 }
519 ).fail(
520 function(ex) {
521 deferred.reject(ex);
522 }
523 );
524 }.bind(this)
525 ).fail(
526 function(ex) {
527 deferred.reject(ex);
528 }
529 );
530 return deferred.promise();
531 };
532
28de7771 533
9bdcf579
DW
534 return /** @alias module:core/templates */ {
535 // Public variables and functions.
536 /**
8d00afb1
DW
537 * Every call to render creates a new instance of the class and calls render on it. This
538 * means each render call has it's own class variables.
9bdcf579
DW
539 *
540 * @method render
541 * @private
542 * @param {string} templateName - should consist of the component and the name of the template like this:
543 * core/menu (lib/templates/menu.mustache) or
544 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
545 * @param {Object} context - Could be array, string or simple value for the context of the template.
546 * @param {string} themeName - Name of the current theme.
547 * @return {Promise} JQuery promise object resolved when the template has been rendered.
548 */
549 render: function(templateName, context, themeName) {
8d00afb1
DW
550 var renderer = new Renderer();
551 return renderer.render(templateName, context, themeName);
9bdcf579
DW
552 },
553
554 /**
555 * Execute a block of JS returned from a template.
556 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
557 *
558 * @method runTemplateJS
9bdcf579
DW
559 * @param {string} source - A block of javascript.
560 */
28de7771
DW
561 runTemplateJS: runTemplateJS,
562
563 /**
564 * Replace a node in the page with some new HTML and run the JS.
565 *
566 * @method replaceNodeContents
c96f55e6
DP
567 * @param {JQuery} element - Element or selector to replace.
568 * @param {String} newHTML - HTML to insert / replace.
569 * @param {String} newJS - Javascript to run after the insertion.
28de7771
DW
570 */
571 replaceNodeContents: function(element, newHTML, newJS) {
c96f55e6 572 domReplace(element, newHTML, newJS, true);
28de7771
DW
573 },
574
575 /**
576 * Insert a node in the page with some new HTML and run the JS.
577 *
578 * @method replaceNode
c96f55e6
DP
579 * @param {JQuery} element - Element or selector to replace.
580 * @param {String} newHTML - HTML to insert / replace.
581 * @param {String} newJS - Javascript to run after the insertion.
28de7771
DW
582 */
583 replaceNode: function(element, newHTML, newJS) {
c96f55e6 584 domReplace(element, newHTML, newJS, false);
9bdcf579
DW
585 }
586 };
587});