stringify.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. var stringify;
  3. var regexpu = require("regexpu-core");
  4. var identifierEscapeRegexp = new RegExp(
  5. regexpu("(^[^A-Za-z_\\-\\u{00a0}-\\u{10ffff}]|^\\-\\-|[^A-Za-z_0-9\\-\\u{00a0}-\\u{10ffff}])", "ug"),
  6. "g"
  7. );
  8. function escape(str, identifier) {
  9. if(str === "*") {
  10. return "*";
  11. }
  12. if (identifier) {
  13. return str.replace(identifierEscapeRegexp, "\\$1");
  14. } else {
  15. return str.replace(/(^[^A-Za-z_\\-]|^\-\-|[^A-Za-z_0-9\\-])/g, "\\$1");
  16. }
  17. }
  18. function stringifyWithoutBeforeAfter(tree) {
  19. switch(tree.type) {
  20. case "selectors":
  21. return tree.nodes.map(stringify).join(",");
  22. case "selector":
  23. return tree.nodes.map(stringify).join("");
  24. case "element":
  25. return (typeof tree.namespace === "string" ? escape(tree.namespace) + "|" : "") + escape(tree.name);
  26. case "class":
  27. return "." + escape(tree.name, true);
  28. case "id":
  29. return "#" + escape(tree.name, true);
  30. case "attribute":
  31. return "[" + tree.content + "]";
  32. case "spacing":
  33. return tree.value;
  34. case "pseudo-class":
  35. return ":" + escape(tree.name) + (typeof tree.content === "string" ? "(" + tree.content + ")" : "");
  36. case "nested-pseudo-class":
  37. return ":" + escape(tree.name) + "(" + tree.nodes.map(stringify).join(",") + ")";
  38. case "pseudo-element":
  39. return "::" + escape(tree.name);
  40. case "universal":
  41. return (typeof tree.namespace === "string" ? escape(tree.namespace) + "|" : "") + "*";
  42. case "operator":
  43. return tree.operator;
  44. case "comment":
  45. return "/*" + tree.content + "*/";
  46. case "invalid":
  47. return tree.value;
  48. }
  49. }
  50. stringify = function stringify(tree) {
  51. var str = stringifyWithoutBeforeAfter(tree);
  52. if(tree.before) {
  53. str = tree.before + str;
  54. }
  55. if(tree.after) {
  56. str = str + tree.after;
  57. }
  58. return str;
  59. };
  60. module.exports = stringify;