You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB

4 years ago
  1. "use strict";
  2. var cssesc = require("cssesc");
  3. var stringify;
  4. function escape(str, stringType) {
  5. return cssesc(str, {
  6. quotes: stringType === "\"" ? "double" : "single"
  7. });
  8. }
  9. function stringifyWithoutBeforeAfter(tree) {
  10. switch(tree.type) {
  11. case "values":
  12. return tree.nodes.map(stringify).join(",");
  13. case "value":
  14. return tree.nodes.map(stringify).join("");
  15. case "item":
  16. return tree.name;
  17. case "nested-item":
  18. return tree.name + "(" + tree.nodes.map(stringify).join(",") + ")";
  19. case "invalid":
  20. return tree.value;
  21. case "comment":
  22. return "/*" + tree.content + "*/";
  23. case "string":
  24. switch(tree.stringType) {
  25. case "'":
  26. return "'" + escape(tree.value, "'") + "'";
  27. case "\"":
  28. return "\"" + escape(tree.value, "\"") + "\"";
  29. }
  30. /* istanbul ignore next */
  31. throw new Error("Invalid stringType");
  32. case "url":
  33. var start = "url(" + (tree.innerSpacingBefore || "");
  34. var end = (tree.innerSpacingAfter || "") + ")";
  35. switch(tree.stringType) {
  36. case "'":
  37. return start + "'" + tree.url.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'") + "'" + end;
  38. case "\"":
  39. return start + "\"" + tree.url.replace(/(\\)/g, "\\$1").replace(/"/g, "\\\"") + "\"" + end;
  40. default:
  41. return start + tree.url.replace(/("|'|\)|\\)/g, "\\$1") + end;
  42. }
  43. }
  44. }
  45. stringify = function stringify(tree) {
  46. var str = stringifyWithoutBeforeAfter(tree);
  47. if(tree.before) {
  48. str = tree.before + str;
  49. }
  50. if(tree.after) {
  51. str = str + tree.after;
  52. }
  53. return str;
  54. };
  55. module.exports = stringify;