objectifier.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. let camelcase = require('camelcase-css')
  2. let UNITLESS = {
  3. boxFlex: true,
  4. boxFlexGroup: true,
  5. columnCount: true,
  6. flex: true,
  7. flexGrow: true,
  8. flexPositive: true,
  9. flexShrink: true,
  10. flexNegative: true,
  11. fontWeight: true,
  12. lineClamp: true,
  13. lineHeight: true,
  14. opacity: true,
  15. order: true,
  16. orphans: true,
  17. tabSize: true,
  18. widows: true,
  19. zIndex: true,
  20. zoom: true,
  21. fillOpacity: true,
  22. strokeDashoffset: true,
  23. strokeOpacity: true,
  24. strokeWidth: true
  25. }
  26. function atRule(node) {
  27. if (typeof node.nodes === 'undefined') {
  28. return true
  29. } else {
  30. return process(node)
  31. }
  32. }
  33. function process(node) {
  34. let name
  35. let result = {}
  36. node.each(child => {
  37. if (child.type === 'atrule') {
  38. name = '@' + child.name
  39. if (child.params) name += ' ' + child.params
  40. if (typeof result[name] === 'undefined') {
  41. result[name] = atRule(child)
  42. } else if (Array.isArray(result[name])) {
  43. result[name].push(atRule(child))
  44. } else {
  45. result[name] = [result[name], atRule(child)]
  46. }
  47. } else if (child.type === 'rule') {
  48. let body = process(child)
  49. if (result[child.selector]) {
  50. for (let i in body) {
  51. result[child.selector][i] = body[i]
  52. }
  53. } else {
  54. result[child.selector] = body
  55. }
  56. } else if (child.type === 'decl') {
  57. if (child.prop[0] === '-' && child.prop[1] === '-') {
  58. name = child.prop
  59. } else if (child.parent && child.parent.selector === ':export') {
  60. name = child.prop
  61. } else {
  62. name = camelcase(child.prop)
  63. }
  64. let value = child.value
  65. if (!isNaN(child.value) && UNITLESS[name]) {
  66. value = parseFloat(child.value)
  67. }
  68. if (child.important) value += ' !important'
  69. if (typeof result[name] === 'undefined') {
  70. result[name] = value
  71. } else if (Array.isArray(result[name])) {
  72. result[name].push(value)
  73. } else {
  74. result[name] = [result[name], value]
  75. }
  76. }
  77. })
  78. return result
  79. }
  80. module.exports = process