index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _browserslist = require('browserslist');
  6. var _browserslist2 = _interopRequireDefault(_browserslist);
  7. var _postcss = require('postcss');
  8. var _postcss2 = _interopRequireDefault(_postcss);
  9. var _postcssValueParser = require('postcss-value-parser');
  10. var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. const regexLowerCaseUPrefix = /^u(?=\+)/;
  13. function unicode(range) {
  14. const values = range.slice(2).split('-');
  15. if (values.length < 2) {
  16. return range;
  17. }
  18. const left = values[0].split('');
  19. const right = values[1].split('');
  20. if (left.length !== right.length) {
  21. return range;
  22. }
  23. let questionCounter = 0;
  24. const merged = left.reduce((group, value, index) => {
  25. if (group === false) {
  26. return false;
  27. }
  28. if (value === right[index] && !questionCounter) {
  29. return group + value;
  30. }
  31. if (value === '0' && right[index] === 'f') {
  32. questionCounter++;
  33. return group + '?';
  34. }
  35. return false;
  36. }, 'u+');
  37. /*
  38. * The maximum number of wildcard characters (?) for ranges is 5.
  39. */
  40. if (merged && questionCounter < 6) {
  41. return merged;
  42. }
  43. return range;
  44. }
  45. /*
  46. * IE and Edge before 16 version ignore the unicode-range if the 'U' is lowercase
  47. *
  48. * https://caniuse.com/#search=unicode-range
  49. */
  50. function hasLowerCaseUPrefixBug(browser) {
  51. return ~(0, _browserslist2.default)('ie <=11, edge <= 15').indexOf(browser);
  52. }
  53. function transform(legacy = false, node) {
  54. node.value = (0, _postcssValueParser2.default)(node.value).walk(child => {
  55. if (child.type === 'word') {
  56. const transformed = unicode(child.value.toLowerCase());
  57. child.value = legacy ? transformed.replace(regexLowerCaseUPrefix, 'U') : transformed;
  58. }
  59. return false;
  60. }).toString();
  61. }
  62. exports.default = _postcss2.default.plugin('postcss-normalize-unicode', () => {
  63. return (css, result) => {
  64. const resultOpts = result.opts || {};
  65. const browsers = (0, _browserslist2.default)(null, {
  66. stats: resultOpts.stats,
  67. path: __dirname,
  68. env: resultOpts.env
  69. });
  70. css.walkDecls(/^unicode-range$/i, transform.bind(null, browsers.some(hasLowerCaseUPrefixBug)));
  71. };
  72. });
  73. module.exports = exports['default'];