utils.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. let { list } = require('postcss')
  2. /**
  3. * Throw special error, to tell beniary,
  4. * that this error is from Autoprefixer.
  5. */
  6. module.exports.error = function (text) {
  7. let err = new Error(text)
  8. err.autoprefixer = true
  9. throw err
  10. }
  11. /**
  12. * Return array, that doesn’t contain duplicates.
  13. */
  14. module.exports.uniq = function (array) {
  15. return [...new Set(array)]
  16. }
  17. /**
  18. * Return "-webkit-" on "-webkit- old"
  19. */
  20. module.exports.removeNote = function (string) {
  21. if (!string.includes(' ')) {
  22. return string
  23. }
  24. return string.split(' ')[0]
  25. }
  26. /**
  27. * Escape RegExp symbols
  28. */
  29. module.exports.escapeRegexp = function (string) {
  30. return string.replace(/[$()*+-.?[\\\]^{|}]/g, '\\$&')
  31. }
  32. /**
  33. * Return regexp to check, that CSS string contain word
  34. */
  35. module.exports.regexp = function (word, escape = true) {
  36. if (escape) {
  37. word = this.escapeRegexp(word)
  38. }
  39. return new RegExp(`(^|[\\s,(])(${word}($|[\\s(,]))`, 'gi')
  40. }
  41. /**
  42. * Change comma list
  43. */
  44. module.exports.editList = function (value, callback) {
  45. let origin = list.comma(value)
  46. let changed = callback(origin, [])
  47. if (origin === changed) {
  48. return value
  49. }
  50. let join = value.match(/,\s*/)
  51. join = join ? join[0] : ', '
  52. return changed.join(join)
  53. }
  54. /**
  55. * Split the selector into parts.
  56. * It returns 3 level deep array because selectors can be comma
  57. * separated (1), space separated (2), and combined (3)
  58. * @param {String} selector selector string
  59. * @return {Array<Array<Array>>} 3 level deep array of split selector
  60. * @see utils.test.js for examples
  61. */
  62. module.exports.splitSelector = function (selector) {
  63. return list.comma(selector).map(i => {
  64. return list.space(i).map(k => {
  65. return k.split(/(?=\.|#)/g)
  66. })
  67. })
  68. }
  69. /**
  70. * Return true if a given value only contains numbers.
  71. * @param {*} value
  72. * @returns {boolean}
  73. */
  74. module.exports.isPureNumber = function (value) {
  75. if (typeof value === 'number') {
  76. return true
  77. }
  78. if (typeof value === 'string') {
  79. return /^[0-9]+$/.test(value)
  80. }
  81. return false
  82. }