Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

672 lignes
19KB

  1. /* ************************************************************************
  2. qooxdoo - the new era of web development
  3. http://qooxdoo.org
  4. Copyright:
  5. 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de
  6. License:
  7. LGPL: http://www.gnu.org/licenses/lgpl.html
  8. EPL: http://www.eclipse.org/org/documents/epl-v10.php
  9. See the LICENSE file in the project's top-level directory for details.
  10. Authors:
  11. * Martin Wittemann (martinwittemann)
  12. ======================================================================
  13. This class contains code based on the following work:
  14. * Mustache.js version 0.5.0-dev
  15. Code:
  16. https://github.com/janl/mustache.js
  17. Copyright:
  18. (c) 2009 Chris Wanstrath (Ruby)
  19. (c) 2010 Jan Lehnardt (JavaScript)
  20. License:
  21. MIT: http://www.opensource.org/licenses/mit-license.php
  22. ----------------------------------------------------------------------
  23. Copyright (c) 2009 Chris Wanstrath (Ruby)
  24. Copyright (c) 2010 Jan Lehnardt (JavaScript)
  25. Permission is hereby granted, free of charge, to any person obtaining
  26. a copy of this software and associated documentation files (the
  27. "Software"), to deal in the Software without restriction, including
  28. without limitation the rights to use, copy, modify, merge, publish,
  29. distribute, sublicense, and/or sell copies of the Software, and to
  30. permit persons to whom the Software is furnished to do so, subject to
  31. the following conditions:
  32. The above copyright notice and this permission notice shall be
  33. included in all copies or substantial portions of the Software.
  34. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  35. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  36. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  37. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  38. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  39. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  40. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  41. ************************************************************************ */
  42. /**
  43. * The is a template class which can be used for HTML templating. In fact,
  44. * this is a wrapper for mustache.js which is a "framework-agnostic way to
  45. * render logic-free views".
  46. *
  47. * Here is a basic example how to use it:
  48. * Template:
  49. * <pre>
  50. * var template = "Hi, my name is {{name}}!";
  51. * var view = {name: "qooxdoo"};
  52. * qx.bom.Template.toHtml(template, view);
  53. * // return "Hi, my name is qooxdoo!"
  54. * </pre>
  55. *
  56. * For further details, please visit the mustache.js documentation here:
  57. * https://github.com/janl/mustache.js/blob/master/README.md
  58. */
  59. qx.Class.define("qx.bom.Template", {
  60. statics : {
  61. /** Contains the mustache.js version. */
  62. version: null,
  63. /**
  64. * Original and only template method of mustache.js. For further
  65. * documentation, please visit https://github.com/janl/mustache.js
  66. *
  67. * @signature function(template, view, partials, send_fun)
  68. * @param template {String} The String containing the template.
  69. * @param view {Object} The object holding the data to render.
  70. * @param partials {Object} Object holding parts of a template.
  71. * @param send_fun {Function?} Callback function for streaming.
  72. * @return {String} The parsed template.
  73. */
  74. toHtml: null,
  75. /**
  76. * Helper method which provides you with a direct access to templates
  77. * stored as HTML in the DOM. The DOM node with the given ID will be reated
  78. * as a template, parsed and a new DOM node will be returned containing the
  79. * parsed data.
  80. *
  81. * @param id {String} The id of the HTML template in the DOM.
  82. * @param view {Object} The object holding the data to render.
  83. * @param partials {Object} Object holding parts of a template.
  84. * @return {DomNode} A DOM element holding the parsed template data.
  85. */
  86. get : function(id, view, partials) {
  87. var template = document.getElementById(id);
  88. var inner = template.innerHTML;
  89. inner = this.toHtml(inner, view, partials);
  90. var helper = qx.bom.Element.create("div");
  91. helper.innerHTML = inner;
  92. return helper.children[0];
  93. }
  94. }
  95. });
  96. (function() {
  97. /**
  98. * Below is the original mustache.js code. Snapshot date is mentioned in
  99. * the head of this file.
  100. */
  101. /*!
  102. * mustache.js - Logic-less {{mustache}} templates with JavaScript
  103. * http://github.com/janl/mustache.js
  104. */
  105. var Mustache = (typeof module !== "undefined" && module.exports) || {};
  106. (function (exports) {
  107. exports.name = "mustache.js";
  108. exports.version = "0.5.14";
  109. exports.tags = ["{{", "}}"];
  110. exports.parse = parse;
  111. exports.compile = compile;
  112. exports.render = render;
  113. exports.clearCache = clearCache;
  114. // This is here for backwards compatibility with 0.4.x.
  115. exports.to_html = function (template, view, partials, send) {
  116. var result = render(template, view, partials);
  117. if (typeof send === "function") {
  118. send(result);
  119. } else {
  120. return result;
  121. }
  122. };
  123. var _toString = Object.prototype.toString;
  124. var _isArray = Array.isArray;
  125. var _forEach = Array.prototype.forEach;
  126. var _trim = String.prototype.trim;
  127. var isArray;
  128. if (_isArray) {
  129. isArray = _isArray;
  130. } else {
  131. isArray = function (obj) {
  132. return _toString.call(obj) === "[object Array]";
  133. };
  134. }
  135. var forEach;
  136. if (_forEach) {
  137. forEach = function (obj, callback, scope) {
  138. return _forEach.call(obj, callback, scope);
  139. };
  140. } else {
  141. forEach = function (obj, callback, scope) {
  142. for (var i = 0, len = obj.length; i < len; ++i) {
  143. callback.call(scope, obj[i], i, obj);
  144. }
  145. };
  146. }
  147. var spaceRe = /^\s*$/;
  148. function isWhitespace(string) {
  149. return spaceRe.test(string);
  150. }
  151. var trim;
  152. if (_trim) {
  153. trim = function (string) {
  154. return string == null ? "" : _trim.call(string);
  155. };
  156. } else {
  157. var trimLeft, trimRight;
  158. if (isWhitespace("\xA0")) {
  159. trimLeft = /^\s+/;
  160. trimRight = /\s+$/;
  161. } else {
  162. // IE doesn't match non-breaking spaces with \s, thanks jQuery.
  163. trimLeft = /^[\s\xA0]+/;
  164. trimRight = /[\s\xA0]+$/;
  165. }
  166. trim = function (string) {
  167. return string == null ? "" :
  168. String(string).replace(trimLeft, "").replace(trimRight, "");
  169. };
  170. }
  171. var escapeMap = {
  172. "&": "&amp;",
  173. "<": "&lt;",
  174. ">": "&gt;",
  175. '"': '&quot;',
  176. "'": '&#39;'
  177. };
  178. function escapeHTML(string) {
  179. return String(string).replace(/&(?!\w+;)|[<>"']/g, function (s) {
  180. return escapeMap[s] || s;
  181. });
  182. }
  183. /**
  184. * Adds the `template`, `line`, and `file` properties to the given error
  185. * object and alters the message to provide more useful debugging information.
  186. */
  187. function debug(e, template, line, file) {
  188. file = file || "<template>";
  189. var lines = template.split("\n"),
  190. start = Math.max(line - 3, 0),
  191. end = Math.min(lines.length, line + 3),
  192. context = lines.slice(start, end);
  193. var c;
  194. for (var i = 0, len = context.length; i < len; ++i) {
  195. c = i + start + 1;
  196. context[i] = (c === line ? " >> " : " ") + context[i];
  197. }
  198. e.template = template;
  199. e.line = line;
  200. e.file = file;
  201. e.message = [file + ":" + line, context.join("\n"), "", e.message].join("\n");
  202. return e;
  203. }
  204. /**
  205. * Looks up the value of the given `name` in the given context `stack`.
  206. */
  207. function lookup(name, stack, defaultValue) {
  208. if (name === ".") {
  209. return stack[stack.length - 1];
  210. }
  211. var names = name.split(".");
  212. var lastIndex = names.length - 1;
  213. var target = names[lastIndex];
  214. var value, context, i = stack.length, j, localStack;
  215. while (i) {
  216. localStack = stack.slice(0);
  217. context = stack[--i];
  218. j = 0;
  219. while (j < lastIndex) {
  220. context = context[names[j++]];
  221. if (context == null) {
  222. break;
  223. }
  224. localStack.push(context);
  225. }
  226. if (context && typeof context === "object" && target in context) {
  227. value = context[target];
  228. break;
  229. }
  230. }
  231. // If the value is a function, call it in the current context.
  232. if (typeof value === "function") {
  233. value = value.call(localStack[localStack.length - 1]);
  234. }
  235. if (value == null) {
  236. return defaultValue;
  237. }
  238. return value;
  239. }
  240. function renderSection(name, stack, callback, inverted) {
  241. var buffer = "";
  242. var value = lookup(name, stack);
  243. if (inverted) {
  244. // From the spec: inverted sections may render text once based on the
  245. // inverse value of the key. That is, they will be rendered if the key
  246. // doesn't exist, is false, or is an empty list.
  247. if (value == null || value === false || (isArray(value) && value.length === 0)) {
  248. buffer += callback();
  249. }
  250. } else if (isArray(value)) {
  251. forEach(value, function (value) {
  252. stack.push(value);
  253. buffer += callback();
  254. stack.pop();
  255. });
  256. } else if (typeof value === "object") {
  257. stack.push(value);
  258. buffer += callback();
  259. stack.pop();
  260. } else if (typeof value === "function") {
  261. var scope = stack[stack.length - 1];
  262. var scopedRender = function (template) {
  263. return render(template, scope);
  264. };
  265. buffer += value.call(scope, callback(), scopedRender) || "";
  266. } else if (value) {
  267. buffer += callback();
  268. }
  269. return buffer;
  270. }
  271. /**
  272. * Parses the given `template` and returns the source of a function that,
  273. * with the proper arguments, will render the template. Recognized options
  274. * include the following:
  275. *
  276. * - file The name of the file the template comes from (displayed in
  277. * error messages)
  278. * - tags An array of open and close tags the `template` uses. Defaults
  279. * to the value of Mustache.tags
  280. * - debug Set `true` to log the body of the generated function to the
  281. * console
  282. * - space Set `true` to preserve whitespace from lines that otherwise
  283. * contain only a {{tag}}. Defaults to `false`
  284. */
  285. function parse(template, options) {
  286. options = options || {};
  287. var tags = options.tags || exports.tags,
  288. openTag = tags[0],
  289. closeTag = tags[tags.length - 1];
  290. var code = [
  291. 'var buffer = "";', // output buffer
  292. "\nvar line = 1;", // keep track of source line number
  293. "\ntry {",
  294. '\nbuffer += "'
  295. ];
  296. var spaces = [], // indices of whitespace in code on the current line
  297. hasTag = false, // is there a {{tag}} on the current line?
  298. nonSpace = false; // is there a non-space char on the current line?
  299. // Strips all space characters from the code array for the current line
  300. // if there was a {{tag}} on it and otherwise only spaces.
  301. var stripSpace = function () {
  302. if (hasTag && !nonSpace && !options.space) {
  303. while (spaces.length) {
  304. code.splice(spaces.pop(), 1);
  305. }
  306. } else {
  307. spaces = [];
  308. }
  309. hasTag = false;
  310. nonSpace = false;
  311. };
  312. var sectionStack = [], updateLine, nextOpenTag, nextCloseTag;
  313. var setTags = function (source) {
  314. tags = trim(source).split(/\s+/);
  315. nextOpenTag = tags[0];
  316. nextCloseTag = tags[tags.length - 1];
  317. };
  318. var includePartial = function (source) {
  319. code.push(
  320. '";',
  321. updateLine,
  322. '\nvar partial = partials["' + trim(source) + '"];',
  323. '\nif (partial) {',
  324. '\n buffer += render(partial,stack[stack.length - 1],partials);',
  325. '\n}',
  326. '\nbuffer += "'
  327. );
  328. };
  329. var openSection = function (source, inverted) {
  330. var name = trim(source);
  331. if (name === "") {
  332. throw debug(new Error("Section name may not be empty"), template, line, options.file);
  333. }
  334. sectionStack.push({name: name, inverted: inverted});
  335. code.push(
  336. '";',
  337. updateLine,
  338. '\nvar name = "' + name + '";',
  339. '\nvar callback = (function () {',
  340. '\n return function () {',
  341. '\n var buffer = "";',
  342. '\nbuffer += "'
  343. );
  344. };
  345. var openInvertedSection = function (source) {
  346. openSection(source, true);
  347. };
  348. var closeSection = function (source) {
  349. var name = trim(source);
  350. var openName = sectionStack.length != 0 && sectionStack[sectionStack.length - 1].name;
  351. if (!openName || name != openName) {
  352. throw debug(new Error('Section named "' + name + '" was never opened'), template, line, options.file);
  353. }
  354. var section = sectionStack.pop();
  355. code.push(
  356. '";',
  357. '\n return buffer;',
  358. '\n };',
  359. '\n})();'
  360. );
  361. if (section.inverted) {
  362. code.push("\nbuffer += renderSection(name,stack,callback,true);");
  363. } else {
  364. code.push("\nbuffer += renderSection(name,stack,callback);");
  365. }
  366. code.push('\nbuffer += "');
  367. };
  368. var sendPlain = function (source) {
  369. code.push(
  370. '";',
  371. updateLine,
  372. '\nbuffer += lookup("' + trim(source) + '",stack,"");',
  373. '\nbuffer += "'
  374. );
  375. };
  376. var sendEscaped = function (source) {
  377. code.push(
  378. '";',
  379. updateLine,
  380. '\nbuffer += escapeHTML(lookup("' + trim(source) + '",stack,""));',
  381. '\nbuffer += "'
  382. );
  383. };
  384. var line = 1, c, callback;
  385. for (var i = 0, len = template.length; i < len; ++i) {
  386. if (template.slice(i, i + openTag.length) === openTag) {
  387. i += openTag.length;
  388. c = template.substr(i, 1);
  389. updateLine = '\nline = ' + line + ';';
  390. nextOpenTag = openTag;
  391. nextCloseTag = closeTag;
  392. hasTag = true;
  393. switch (c) {
  394. case "!": // comment
  395. i++;
  396. callback = null;
  397. break;
  398. case "=": // change open/close tags, e.g. {{=<% %>=}}
  399. i++;
  400. closeTag = "=" + closeTag;
  401. callback = setTags;
  402. break;
  403. case ">": // include partial
  404. i++;
  405. callback = includePartial;
  406. break;
  407. case "#": // start section
  408. i++;
  409. callback = openSection;
  410. break;
  411. case "^": // start inverted section
  412. i++;
  413. callback = openInvertedSection;
  414. break;
  415. case "/": // end section
  416. i++;
  417. callback = closeSection;
  418. break;
  419. case "{": // plain variable
  420. closeTag = "}" + closeTag;
  421. // fall through
  422. case "&": // plain variable
  423. i++;
  424. nonSpace = true;
  425. callback = sendPlain;
  426. break;
  427. default: // escaped variable
  428. nonSpace = true;
  429. callback = sendEscaped;
  430. }
  431. var end = template.indexOf(closeTag, i);
  432. if (end === -1) {
  433. throw debug(new Error('Tag "' + openTag + '" was not closed properly'), template, line, options.file);
  434. }
  435. var source = template.substring(i, end);
  436. if (callback) {
  437. callback(source);
  438. }
  439. // Maintain line count for \n in source.
  440. var n = 0;
  441. while (~(n = source.indexOf("\n", n))) {
  442. line++;
  443. n++;
  444. }
  445. i = end + closeTag.length - 1;
  446. openTag = nextOpenTag;
  447. closeTag = nextCloseTag;
  448. } else {
  449. c = template.substr(i, 1);
  450. switch (c) {
  451. case '"':
  452. case "\\":
  453. nonSpace = true;
  454. code.push("\\" + c);
  455. break;
  456. case "\r":
  457. // Ignore carriage returns.
  458. break;
  459. case "\n":
  460. spaces.push(code.length);
  461. code.push("\\n");
  462. stripSpace(); // Check for whitespace on the current line.
  463. line++;
  464. break;
  465. default:
  466. if (isWhitespace(c)) {
  467. spaces.push(code.length);
  468. } else {
  469. nonSpace = true;
  470. }
  471. code.push(c);
  472. }
  473. }
  474. }
  475. if (sectionStack.length != 0) {
  476. throw debug(new Error('Section "' + sectionStack[sectionStack.length - 1].name + '" was not closed properly'), template, line, options.file);
  477. }
  478. // Clean up any whitespace from a closing {{tag}} that was at the end
  479. // of the template without a trailing \n.
  480. stripSpace();
  481. code.push(
  482. '";',
  483. "\nreturn buffer;",
  484. "\n} catch (e) { throw {error: e, line: line}; }"
  485. );
  486. // Ignore `buffer += "";` statements.
  487. var body = code.join("").replace(/buffer \+= "";\n/g, "");
  488. if (options.debug) {
  489. if (typeof console != "undefined" && console.log) {
  490. console.log(body);
  491. } else if (typeof print === "function") {
  492. print(body);
  493. }
  494. }
  495. return body;
  496. }
  497. /**
  498. * Used by `compile` to generate a reusable function for the given `template`.
  499. */
  500. function _compile(template, options) {
  501. var args = "view,partials,stack,lookup,escapeHTML,renderSection,render";
  502. var body = parse(template, options);
  503. var fn = new Function(args, body);
  504. // This anonymous function wraps the generated function so we can do
  505. // argument coercion, setup some variables, and handle any errors
  506. // encountered while executing it.
  507. return function (view, partials) {
  508. partials = partials || {};
  509. var stack = [view]; // context stack
  510. try {
  511. return fn(view, partials, stack, lookup, escapeHTML, renderSection, render);
  512. } catch (e) {
  513. throw debug(e.error, template, e.line, options.file);
  514. }
  515. };
  516. }
  517. // Cache of pre-compiled templates.
  518. var _cache = {};
  519. /**
  520. * Clear the cache of compiled templates.
  521. */
  522. function clearCache() {
  523. _cache = {};
  524. }
  525. /**
  526. * Compiles the given `template` into a reusable function using the given
  527. * `options`. In addition to the options accepted by Mustache.parse,
  528. * recognized options include the following:
  529. *
  530. * - cache Set `false` to bypass any pre-compiled version of the given
  531. * template. Otherwise, a given `template` string will be cached
  532. * the first time it is parsed
  533. */
  534. function compile(template, options) {
  535. options = options || {};
  536. // Use a pre-compiled version from the cache if we have one.
  537. if (options.cache !== false) {
  538. if (!_cache[template]) {
  539. _cache[template] = _compile(template, options);
  540. }
  541. return _cache[template];
  542. }
  543. return _compile(template, options);
  544. }
  545. /**
  546. * High-level function that renders the given `template` using the given
  547. * `view` and `partials`. If you need to use any of the template options (see
  548. * `compile` above), you must compile in a separate step, and then call that
  549. * compiled function.
  550. */
  551. function render(template, view, partials) {
  552. return compile(template)(view, partials);
  553. }
  554. })(Mustache);
  555. /**
  556. * Above is the original mustache code.
  557. */
  558. // EXPOSE qooxdoo variant
  559. qx.bom.Template.version = Mustache.version;
  560. qx.bom.Template.toHtml = Mustache.render;
  561. })();