inline-comment.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* eslint-disable no-param-reassign */
  2. const tokenizer = require('postcss/lib/tokenize');
  3. const Input = require('postcss/lib/input');
  4. module.exports = {
  5. isInlineComment(token) {
  6. if (token[0] === 'word' && token[1].slice(0, 2) === '//') {
  7. const first = token;
  8. const bits = [];
  9. let last;
  10. let remainingInput;
  11. while (token) {
  12. if (/\r?\n/.test(token[1])) {
  13. // If there are quotes, fix tokenizer creating one token from start quote to end quote
  14. if (/['"].*\r?\n/.test(token[1])) {
  15. // Add string before newline to inline comment token
  16. bits.push(token[1].substring(0, token[1].indexOf('\n')));
  17. // Get remaining input and retokenize
  18. remainingInput = token[1].substring(token[1].indexOf('\n'));
  19. remainingInput += this.input.css.valueOf().substring(this.tokenizer.position());
  20. } else {
  21. // If the tokenizer went to the next line go back
  22. this.tokenizer.back(token);
  23. }
  24. break;
  25. }
  26. bits.push(token[1]);
  27. last = token;
  28. token = this.tokenizer.nextToken({ ignoreUnclosed: true });
  29. }
  30. const newToken = ['comment', bits.join(''), first[2], first[3], last[2], last[3]];
  31. this.inlineComment(newToken);
  32. // Replace tokenizer to retokenize the rest of the string
  33. // we need replace it after we added new token with inline comment because token position is calculated for old input (#145)
  34. if (remainingInput) {
  35. this.input = new Input(remainingInput);
  36. this.tokenizer = tokenizer(this.input);
  37. }
  38. return true;
  39. } else if (token[1] === '/') {
  40. // issue #135
  41. const next = this.tokenizer.nextToken({ ignoreUnclosed: true });
  42. if (next[0] === 'comment' && /^\/\*/.test(next[1])) {
  43. next[0] = 'word';
  44. next[1] = next[1].slice(1);
  45. token[1] = '//';
  46. this.tokenizer.back(next);
  47. return module.exports.isInlineComment.bind(this)(token);
  48. }
  49. }
  50. return false;
  51. }
  52. };