unesc.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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); // check to see if we are dealing with a valid hex char [a-f|0-9]
  17. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  18. spaceTerminated = code === 32;
  19. if (!valid) {
  20. break;
  21. }
  22. hex += lower[i];
  23. }
  24. if (hex.length === 0) {
  25. return undefined;
  26. }
  27. var codePoint = parseInt(hex, 16);
  28. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  29. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  30. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  31. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  32. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  33. }
  34. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  35. }
  36. var CONTAINS_ESCAPE = /\\/;
  37. function unesc(str) {
  38. var needToProcess = CONTAINS_ESCAPE.test(str);
  39. if (!needToProcess) {
  40. return str;
  41. }
  42. var ret = "";
  43. for (var i = 0; i < str.length; i++) {
  44. if (str[i] === "\\") {
  45. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  46. if (gobbled !== undefined) {
  47. ret += gobbled[0];
  48. i += gobbled[1];
  49. continue;
  50. } // Retain a pair of \\ if double escaped `\\\\`
  51. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  52. if (str[i + 1] === "\\") {
  53. ret += "\\";
  54. i++;
  55. continue;
  56. } // if \\ is at the end of the string retain it
  57. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  58. if (str.length === i + 1) {
  59. ret += str[i];
  60. }
  61. continue;
  62. }
  63. ret += str[i];
  64. }
  65. return ret;
  66. }
  67. module.exports = exports.default;