stringify.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. var __spreadArrays = (this && this.__spreadArrays) || function () {
  3. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  4. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  5. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  6. r[k] = a[j];
  7. return r;
  8. };
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. var actionTypes = {
  11. equals: "",
  12. element: "~",
  13. start: "^",
  14. end: "$",
  15. any: "*",
  16. not: "!",
  17. hyphen: "|",
  18. };
  19. var charsToEscape = new Set(__spreadArrays(Object.keys(actionTypes)
  20. .map(function (typeKey) { return actionTypes[typeKey]; })
  21. .filter(Boolean), [
  22. ":",
  23. "[",
  24. "]",
  25. " ",
  26. "\\",
  27. ]));
  28. function stringify(token) {
  29. return token.map(stringifySubselector).join(", ");
  30. }
  31. exports.default = stringify;
  32. function stringifySubselector(token) {
  33. return token.map(stringifyToken).join("");
  34. }
  35. function stringifyToken(token) {
  36. switch (token.type) {
  37. // Simple types
  38. case "child":
  39. return " > ";
  40. case "parent":
  41. return " < ";
  42. case "sibling":
  43. return " ~ ";
  44. case "adjacent":
  45. return " + ";
  46. case "descendant":
  47. return " ";
  48. case "universal":
  49. return "*";
  50. case "tag":
  51. return escapeName(token.name);
  52. case "pseudo-element":
  53. return "::" + escapeName(token.name);
  54. case "pseudo":
  55. if (token.data === null)
  56. return ":" + escapeName(token.name);
  57. if (typeof token.data === "string") {
  58. return ":" + escapeName(token.name) + "(" + token.data + ")";
  59. }
  60. return ":" + escapeName(token.name) + "(" + stringify(token.data) + ")";
  61. case "attribute":
  62. if (token.action === "exists") {
  63. return "[" + escapeName(token.name) + "]";
  64. }
  65. if (token.name === "id" &&
  66. token.action === "equals" &&
  67. !token.ignoreCase) {
  68. return "#" + escapeName(token.value);
  69. }
  70. if (token.name === "class" &&
  71. token.action === "element" &&
  72. !token.ignoreCase) {
  73. return "." + escapeName(token.value);
  74. }
  75. return "[" + escapeName(token.name) + actionTypes[token.action] + "='" + escapeName(token.value) + "'" + (token.ignoreCase ? "i" : "") + "]";
  76. }
  77. }
  78. function escapeName(str) {
  79. return str
  80. .split("")
  81. .map(function (c) { return (charsToEscape.has(c) ? "\\" + c : c); })
  82. .join("");
  83. }