directive-stripper.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var tokenize = require("html-tokenize");
  2. var through2 = require("through2");
  3. var vinyl = require("vinyl");
  4. var select = require("html-select");
  5. /**
  6. * @param config
  7. * @param item
  8. * @param markup
  9. * @param done
  10. */
  11. function directiveStripper(config, item, markup, done) {
  12. var replacer = getReplacer(item, config);
  13. var chunks = [];
  14. new vinyl({
  15. contents: new Buffer(markup)
  16. })
  17. .pipe(tokenize())
  18. .pipe(replacer)
  19. .pipe(through2.obj(function (row, buf, next) {
  20. chunks.push(row[1]);
  21. next();
  22. }, function () {
  23. done(null, chunks.join(""));
  24. }));
  25. replacer.resume();
  26. }
  27. /**
  28. * @param name
  29. * @param item
  30. * @returns {*|exports}
  31. */
  32. function getReplacer (name, markup) {
  33. return select(name, function (e) {
  34. var tr = through2.obj(function (row, buf, next) {
  35. if (row[0] === "open") {
  36. this.push([row[0], directive(name, String(row[1]), markup)]);
  37. } else {
  38. this.push([ row[0], "" ]);
  39. }
  40. next();
  41. });
  42. tr.pipe(e.createStream()).pipe(tr);
  43. });
  44. }
  45. /**
  46. * @param name
  47. * @param content
  48. * @param item
  49. * @returns {*|string}
  50. */
  51. function directive (name, content, item) {
  52. var angularDir;
  53. try {
  54. angularDir = require("../src/scripts/directives/" + name)();
  55. } catch (e) {
  56. console.log("Directive not found, cannot re-use");
  57. return content;
  58. }
  59. var scope = item;
  60. scope = angularDir.link(scope, {}, {});
  61. return angularDir.template.replace(/\{\{(.+?)\}\}/, function ($1, $2) {
  62. if ($2 in scope) {
  63. return scope[$2];
  64. }
  65. return $1;
  66. });
  67. }
  68. module.exports.getReplacer = getReplacer;
  69. module.exports.directive = directive;
  70. module.exports.directiveStripper = directiveStripper;