comments.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. module.exports = function Comments(keepSpecialComments, keepBreaks, lineBreak) {
  2. var comments = [];
  3. return {
  4. // Strip special comments (/*! ... */) by replacing them by __CSSCOMMENT__ marker
  5. // for further restoring. Plain comments are removed. It's done by scanning data using
  6. // String#indexOf scanning instead of regexps to speed up the process.
  7. escape: function(data) {
  8. var tempData = [];
  9. var nextStart = 0;
  10. var nextEnd = 0;
  11. var cursor = 0;
  12. for (; nextEnd < data.length; ) {
  13. nextStart = data.indexOf('/*', nextEnd);
  14. nextEnd = data.indexOf('*/', nextStart + 2);
  15. if (nextStart == -1 || nextEnd == -1)
  16. break;
  17. tempData.push(data.substring(cursor, nextStart));
  18. if (data[nextStart + 2] == '!') {
  19. // in case of special comments, replace them with a placeholder
  20. comments.push(data.substring(nextStart, nextEnd + 2));
  21. tempData.push('__CSSCOMMENT__');
  22. }
  23. cursor = nextEnd + 2;
  24. }
  25. return tempData.length > 0 ?
  26. tempData.join('') + data.substring(cursor, data.length) :
  27. data;
  28. },
  29. restore: function(data) {
  30. var commentsCount = comments.length;
  31. var breakSuffix = keepBreaks ? lineBreak : '';
  32. return data.replace(new RegExp('__CSSCOMMENT__(' + lineBreak + '| )?', 'g'), function() {
  33. switch (keepSpecialComments) {
  34. case '*':
  35. return comments.shift() + breakSuffix;
  36. case 1:
  37. case '1':
  38. return comments.length == commentsCount ?
  39. comments.shift() + breakSuffix :
  40. '';
  41. case 0:
  42. case '0':
  43. return '';
  44. }
  45. });
  46. }
  47. };
  48. };