unesc.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = unesc;
  4. // Many thanks for this post which made this migration much easier.
  5. // https://mathiasbynens.be/notes/css-escapes
  6. /**
  7. *
  8. * @param {string} str
  9. * @returns {[string, number]|undefined}
  10. */
  11. function gobbleHex(str) {
  12. var lower = str.toLowerCase();
  13. var hex = '';
  14. var spaceTerminated = false;
  15. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  16. var code = lower.charCodeAt(i);
  17. // check to see if we are dealing with a valid hex char [a-f|0-9]
  18. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  19. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  20. spaceTerminated = code === 32;
  21. if (!valid) {
  22. break;
  23. }
  24. hex += lower[i];
  25. }
  26. if (hex.length === 0) {
  27. return undefined;
  28. }
  29. var codePoint = parseInt(hex, 16);
  30. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  31. // Add special case for
  32. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  33. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  34. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  35. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  36. }
  37. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  38. }
  39. var CONTAINS_ESCAPE = /\\/;
  40. function unesc(str) {
  41. var needToProcess = CONTAINS_ESCAPE.test(str);
  42. if (!needToProcess) {
  43. return str;
  44. }
  45. var ret = "";
  46. for (var i = 0; i < str.length; i++) {
  47. if (str[i] === "\\") {
  48. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  49. if (gobbled !== undefined) {
  50. ret += gobbled[0];
  51. i += gobbled[1];
  52. continue;
  53. }
  54. // Retain a pair of \\ if double escaped `\\\\`
  55. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  56. if (str[i + 1] === "\\") {
  57. ret += "\\";
  58. i++;
  59. continue;
  60. }
  61. // if \\ is at the end of the string retain it
  62. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  63. if (str.length === i + 1) {
  64. ret += str[i];
  65. }
  66. continue;
  67. }
  68. ret += str[i];
  69. }
  70. return ret;
  71. }
  72. module.exports = exports.default;