template-tokenize.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const tokenize = require('postcss/lib/tokenize');
  3. function templateTokenize(input) {
  4. let pos = input.quasis[0].start;
  5. const quasis = input.quasis.filter((quasi) => quasi.start !== quasi.end);
  6. const tokenizer = tokenize.apply(this, arguments);
  7. function tokenInExpressions(token, returned) {
  8. const start = pos;
  9. pos += token[1].length;
  10. if (
  11. !quasis.some((quasi) => start >= quasi.start && pos <= quasi.end) ||
  12. (returned.length && token[0] === returned[0][0])
  13. ) {
  14. return true;
  15. } else if (returned.length) {
  16. back(token);
  17. }
  18. }
  19. function back(token) {
  20. pos -= token[1].length;
  21. return tokenizer.back.apply(tokenizer, arguments);
  22. }
  23. function nextToken() {
  24. const args = arguments;
  25. const returned = [];
  26. let token;
  27. let line;
  28. let column;
  29. while (
  30. (token = tokenizer.nextToken.apply(tokenizer, args)) &&
  31. tokenInExpressions(token, returned)
  32. ) {
  33. line = token[4] || token[2] || line;
  34. column = token[5] || token[3] || column;
  35. returned.push(token);
  36. }
  37. if (returned.length) {
  38. token = [
  39. returned[0][0],
  40. returned.map((token) => token[1]).join(''),
  41. returned[0][2],
  42. returned[0][3],
  43. line,
  44. column,
  45. ];
  46. }
  47. return token;
  48. }
  49. return Object.assign({}, tokenizer, {
  50. back,
  51. nextToken,
  52. });
  53. }
  54. module.exports = templateTokenize;