stubble.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import $ = require('jquery');
  2. /**
  3. * A templating engine for the DOM, with syntax
  4. * loosely inspired by Mustache.
  5. */
  6. export class Template {
  7. static helpers: HashMap<Helper> = {};
  8. private recipes: Recipe[];
  9. constructor(template: string) {
  10. let tokens = parseTokens(template);
  11. let recipes = tokensToRecipes(tokens);
  12. this.recipes = optimizeRecipes(recipes);
  13. }
  14. /**
  15. * Render this template to a JQuery collection.
  16. * @param data Data used to resolve placeholders in the template.
  17. */
  18. render(data: {}) {
  19. let target = document.createElement('div');
  20. for (let recipe of this.recipes) {
  21. recipe.renderInto(target, data);
  22. }
  23. return $(target).contents();
  24. }
  25. }
  26. // The 'each' helper loops over the collection passed to it,
  27. // calling the default branch with the context set to each item
  28. // in turn. If the collection is empty (or isn't a collection),
  29. // then the 'else' branch is called with the original context.
  30. Template.helpers['each'] = {
  31. renderInto: function (target, data, block) {
  32. let collection = resolvePath(block.path, data);
  33. if (hasLength(collection)) {
  34. for (let item of collection) {
  35. for (let recipe of block.defaultBranch) {
  36. recipe.renderInto(target, item);
  37. }
  38. }
  39. } else {
  40. for (let recipe of block.elseBranch) {
  41. recipe.renderInto(target, data);
  42. }
  43. }
  44. }
  45. };
  46. // The 'if' helper checks whether the value passed to it is
  47. // truthy. If it is, then the default branch is called. Otherwise,
  48. // the 'else' branch is called.
  49. Template.helpers['if'] = {
  50. renderInto: function (target, data, block) {
  51. let result = resolvePath(block.path, data);
  52. let branch = block.defaultBranch;
  53. if (!result) {
  54. branch = block.elseBranch;
  55. }
  56. for (let recipe of branch) {
  57. recipe.renderInto(target, data);
  58. }
  59. }
  60. };
  61. // The 'with' helper is very much like the 'if' helper,
  62. // except that before calling its default branch, it sets
  63. // the context to the value being tested. During the 'else'
  64. // branch, the context is unchanged.
  65. Template.helpers['with'] = {
  66. renderInto: function (target, data, block) {
  67. let result = resolvePath(block.path, data);
  68. if (result) {
  69. for (let recipe of block.defaultBranch) {
  70. recipe.renderInto(target, result);
  71. }
  72. } else {
  73. for (let recipe of block.elseBranch) {
  74. recipe.renderInto(target, data);
  75. }
  76. }
  77. }
  78. };
  79. /**
  80. * Quick & dirty lookup table
  81. */
  82. export interface HashMap<T> {
  83. [name: string]: T;
  84. }
  85. /**
  86. * ADVANCED
  87. * Helpers are blocks of logic that can be invoked from templates
  88. * via the {{#block args}}...{{/block}} syntax.
  89. */
  90. export interface Helper {
  91. /**
  92. * Render this helper into the target element with the given data.
  93. * @param target The target element
  94. * @param data Data used to resolve placeholders
  95. * @param block The recipe parsed from the original template.
  96. * This contains the block branches & any arguments.
  97. */
  98. renderInto(target: Element, data: {}, block: BlockRecipe): void;
  99. }
  100. /**
  101. * ADVANCED
  102. * Recipes are what actually render content within a template.
  103. */
  104. export interface Recipe {
  105. renderInto(target: Element, data: {}): void;
  106. }
  107. /**
  108. * ADVANCED
  109. * A block recipe is the parsed version of a helper invocation.
  110. * You should use this class from your helper to execute one of
  111. * its branches (or possibly both).
  112. */
  113. export class BlockRecipe implements Recipe {
  114. name: string;
  115. path: string[];
  116. currentBranch: Recipe[];
  117. defaultBranch: Recipe[];
  118. elseBranch: Recipe[];
  119. helper: Helper;
  120. constructor(block: BlockStartToken) {
  121. this.name = block.name;
  122. this.path = block.path;
  123. this.defaultBranch = [];
  124. this.elseBranch = [];
  125. this.currentBranch = this.defaultBranch;
  126. this.helper = Template.helpers[this.name];
  127. if (!this.helper) {
  128. throw new UnknownHelperError(this.name);
  129. }
  130. }
  131. pushRecipe(recipe: Recipe) {
  132. if (recipe instanceof FieldRecipe
  133. && recipe.path.length === 1
  134. && recipe.path[0] === 'else') {
  135. this.currentBranch = this.elseBranch;
  136. return;
  137. }
  138. this.currentBranch.push(recipe);
  139. }
  140. renderInto(target: Element, data: {}) {
  141. this.helper.renderInto(target, data, this);
  142. }
  143. }
  144. /**
  145. * ADVANCED
  146. * The token that begins a helper invocation.
  147. */
  148. export class BlockStartToken {
  149. name: string;
  150. path: string[];
  151. constructor(text: string) {
  152. let split = text.split(' ');
  153. this.name = split[0].substr(1);
  154. this.path = (split[1] || '').split('.');
  155. }
  156. }
  157. ////////////////////////////////
  158. //// Implementation details ////
  159. ////////////////////////////////
  160. /**
  161. * A token is the first step from raw text to executable template.
  162. * A flat stream of these tokens eventually becomes a tree structure
  163. * of recipes, which is used to render the template.
  164. */
  165. type Token
  166. = NodeToken
  167. | FieldToken
  168. | TextToken
  169. | BlockStartToken
  170. | BlockEndToken;
  171. class NodeToken {
  172. nodeName: string;
  173. attributes: AttributeRecipe[];
  174. childTokens: Token[];
  175. constructor(e: Element) {
  176. this.nodeName = e.nodeName;
  177. this.attributes = [];
  178. for (let attr of slice(e.attributes)) {
  179. this.attributes.push({
  180. name: attr.name,
  181. value: attr.value
  182. });
  183. }
  184. this.childTokens = nodesToTokens(slice(e.childNodes));
  185. }
  186. }
  187. class FieldToken {
  188. path: string[];
  189. constructor(text: string) {
  190. this.path = text.split('.');
  191. }
  192. }
  193. class BlockEndToken {
  194. name: string;
  195. constructor(text: string) {
  196. this.name = text.substr(1);
  197. }
  198. }
  199. class TextToken {
  200. text: string;
  201. constructor(text: string) {
  202. this.text = text;
  203. }
  204. }
  205. interface AttributeRecipe {
  206. name: string;
  207. value: string;
  208. }
  209. /**
  210. * The parse state is used to convert a token stream to
  211. * a recipe stream.
  212. */
  213. class ParseState {
  214. private index: number;
  215. private tokens: Token[];
  216. private recipes: Recipe[];
  217. private length: number;
  218. private blockState: BlockRecipe[];
  219. constructor(tokens: Token[]) {
  220. this.index = 0;
  221. this.tokens = tokens;
  222. this.recipes = [];
  223. this.length = tokens.length;
  224. this.blockState = [];
  225. }
  226. /**
  227. * Consume the tokens in the token stream, producing recipes.
  228. */
  229. parseToEnd() {
  230. while (!this.atEndOfStream()) {
  231. let token = this.nextToken();
  232. if (token instanceof NodeToken) {
  233. this.pushRecipe(new NodeRecipe(token));
  234. } else if (token instanceof FieldToken) {
  235. this.pushRecipe(new FieldRecipe(token));
  236. } else if (token instanceof TextToken) {
  237. this.pushRecipe(new TextRecipe(token.text));
  238. } else if (token instanceof BlockStartToken) {
  239. this.startBlock(token);
  240. } else if (token instanceof BlockEndToken) {
  241. this.endBlock(token);
  242. } else {
  243. throw new InvalidTokenError(token);
  244. }
  245. }
  246. return this.recipes;
  247. }
  248. private endBlock(end: BlockEndToken) {
  249. let block = this.blockState.pop();
  250. if (block.name !== end.name) {
  251. throw new UnexpectedBlockEndError(end.name, block.name);
  252. }
  253. this.pushRecipe(block);
  254. }
  255. private startBlock(block: BlockStartToken) {
  256. let recipe = new BlockRecipe(block);
  257. this.blockState.push(recipe);
  258. }
  259. private atEndOfStream() {
  260. return this.index >= this.length;
  261. }
  262. private nextToken() {
  263. return this.tokens[this.index++];
  264. }
  265. private pushRecipe(recipe: Recipe) {
  266. let length = this.blockState.length;
  267. if (length) {
  268. this.blockState[length - 1].pushRecipe(recipe);
  269. } else {
  270. this.recipes.push(recipe);
  271. }
  272. }
  273. }
  274. /**
  275. * A simple text literal with no placeholders.
  276. */
  277. class TextRecipe implements Recipe {
  278. text: string;
  279. constructor(text: string) {
  280. this.text = text;
  281. }
  282. renderInto(target: Element, data: {}) {
  283. target.appendChild(document.createTextNode(this.text));
  284. }
  285. }
  286. /**
  287. * A placeholder that references a field in the context.
  288. */
  289. class FieldRecipe implements Recipe {
  290. path: string[];
  291. constructor(token: FieldToken) {
  292. this.path = token.path;
  293. }
  294. renderInto(target: Element, data: {}) {
  295. data = resolvePath(this.path, data);
  296. if (data instanceof Node) {
  297. target.appendChild(data);
  298. } else if (isJQuery(data)) {
  299. data.each(function (i, el) {
  300. target.appendChild(el);
  301. });
  302. } else if (data != null) {
  303. target.appendChild(document.createTextNode(data.toString()));
  304. }
  305. }
  306. }
  307. /**
  308. * A node that contains attributes & more recipes.
  309. */
  310. class NodeRecipe implements Recipe {
  311. static placeholderRegex = /{{(.+?)}}/;
  312. nodeName: string;
  313. attributes: AttributeRecipe[];
  314. childRecipes: Recipe[];
  315. constructor(token: NodeToken) {
  316. this.nodeName = token.nodeName;
  317. this.attributes = token.attributes;
  318. this.childRecipes = tokensToRecipes(token.childTokens);
  319. }
  320. renderInto(target: Element, data: {}) {
  321. let element = document.createElement(this.nodeName);
  322. for (let attr of this.attributes) {
  323. let value = NodeRecipe.replacePlaceholders(attr.value, data);
  324. element.setAttribute(attr.name, value);
  325. }
  326. for (let recipe of this.childRecipes) {
  327. recipe.renderInto(element, data);
  328. }
  329. target.appendChild(element);
  330. }
  331. static replacePlaceholders(template: string, data: {}) {
  332. return template.replace(NodeRecipe.placeholderRegex, function (match, path) {
  333. let pieces = path.split('.');
  334. let value = resolvePath(pieces, data);
  335. if (value != null) {
  336. return value.toString();
  337. }
  338. return '';
  339. });
  340. }
  341. }
  342. class UnknownHelperError extends Error {
  343. constructor(name: string) {
  344. this.message = `Unknown helper '${name}'`;
  345. }
  346. }
  347. class InvalidTokenError extends Error {
  348. constructor(token: any) {
  349. let json = JSON.stringify(token);
  350. this.message = `Unknown token: ${json}`;
  351. }
  352. }
  353. class UnexpectedBlockEndError extends Error {
  354. constructor(saw: string, expected: string) {
  355. this.message =
  356. `Unexpected end of block. Saw '${saw}' but expected '${expected}'`;
  357. }
  358. }
  359. /**
  360. * Matches placeholders in text. Returns three captured groups in
  361. * one of two states. In the first state, only group 3 is set. This indicates
  362. * that no placeholder was found. In the second state, group 1 is set to
  363. * the text before the placeholder, and group 2 is set to the text found inside
  364. * the placeholder.
  365. */
  366. const PLACEHOLDER_RX = /(.*?){{(.+?)}}|(.+)/g;
  367. function isJQuery(x: any): x is JQuery {
  368. return x instanceof $;
  369. }
  370. function optimizeRecipes(recipes: Recipe[]) {
  371. return squashTextRecipes(recipes);
  372. }
  373. /**
  374. * Combine all adjacent text recipes.
  375. * @param recipes The recipes to optimize.
  376. */
  377. function squashTextRecipes(recipes: Recipe[]) {
  378. let optimized = [];
  379. let lastTextRecipe = null;
  380. for (let recipe of recipes) {
  381. if (lastTextRecipe) {
  382. if (recipe instanceof TextRecipe) {
  383. lastTextRecipe.text += recipe.text;
  384. } else {
  385. optimized.push(lastTextRecipe);
  386. optimized.push(recipe);
  387. lastTextRecipe = null;
  388. }
  389. } else if (recipe instanceof TextRecipe) {
  390. lastTextRecipe = recipe;
  391. } else {
  392. optimized.push(recipe);
  393. }
  394. }
  395. return optimized;
  396. }
  397. function hasLength(x: any): x is any[] {
  398. return x && x.length;
  399. }
  400. function tokensToRecipes(tokens: Token[]) {
  401. let state = new ParseState(tokens);
  402. return state.parseToEnd();
  403. }
  404. /**
  405. * Given an array of property names, traverse them on
  406. * the given data and return the final value. The special
  407. * property name 'this' does no traversal.
  408. * @param path The path of property names.
  409. * @param data The data to traverse.
  410. */
  411. function resolvePath(path: string[], data: {}) {
  412. for (let piece of path) {
  413. if (piece !== 'this' && data) {
  414. data = data[piece];
  415. }
  416. }
  417. return data;
  418. }
  419. function parseTokens(template: string) {
  420. let nodes = parseDOM(template);
  421. return nodesToTokens(nodes);
  422. }
  423. /**
  424. * Parse a series of nodes into tokens.
  425. * @param nodes The nodes to parse.
  426. */
  427. function nodesToTokens(nodes: Node[]) {
  428. let tokens = [];
  429. for (let node of nodes) {
  430. if (node.nodeType === Node.TEXT_NODE) {
  431. for (let token of parseTextTokens(node.textContent)) {
  432. tokens.push(token);
  433. }
  434. } else if (node.nodeType === Node.ELEMENT_NODE) {
  435. tokens.push(new NodeToken(node as Element));
  436. }
  437. }
  438. return tokens;
  439. }
  440. function parsePlaceholderToken(text: string): Token {
  441. switch (text[0]) {
  442. case '#':
  443. return new BlockStartToken(text);
  444. case '/':
  445. return new BlockEndToken(text);
  446. default:
  447. return new FieldToken(text);
  448. }
  449. }
  450. /**
  451. * Parse the given text into text, block, and field tokens.
  452. * @param text The text to parse.
  453. */
  454. function parseTextTokens(text: string) {
  455. let result = null;
  456. let tokens = [];
  457. while (result = PLACEHOLDER_RX.exec(text)) {
  458. if (result[3]) {
  459. tokens.push(new TextToken(result[3]));
  460. continue;
  461. }
  462. tokens.push(new TextToken(result[1]));
  463. tokens.push(parsePlaceholderToken(result[2]));
  464. }
  465. PLACEHOLDER_RX.lastIndex = 0;
  466. return tokens;
  467. }
  468. /**
  469. * Parse the given raw HTML into a series of nodes.
  470. * @param rawHTML The raw HTML to parse.
  471. */
  472. function parseDOM(rawHTML: string) {
  473. let temp = document.createElement('div');
  474. temp.innerHTML = rawHTML;
  475. return slice(temp.childNodes);
  476. }
  477. /**
  478. * Make a shallow array copy of an array-like object.
  479. * @param array The object to copy.
  480. */
  481. function slice<T>(array: ArrayLike<T>): T[] {
  482. return Array.prototype.slice.call(array);
  483. }