classes.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. export function getClassObject(list, { name, value }) {
  2. return list.map((d, i) => {
  3. const values = typeof value === 'string' ? value.split(',').map(v => {
  4. return `${v}: ${d.value || d.name};`
  5. }) : [...value(d, i)]
  6. return {
  7. ...d,
  8. name: d.name !== '' ? `${name}${d.name}` : `${name.slice(0, name.lastIndexOf('-'))}`,
  9. value: values
  10. }
  11. })
  12. }
  13. export function getClassArray(list, options) {
  14. const { name, value } = options
  15. if ('string' !== typeof name) {
  16. return name.reduce((acc, cur, index) => {
  17. if (acc) {
  18. acc.push(...getClassObject(list, { name: cur, value: value[index] }))
  19. return acc
  20. }
  21. }, [])
  22. }
  23. return getClassObject(list, { name, value })
  24. }
  25. export function getStringList(list) {
  26. return list.split(',').map(d => {
  27. d = d.trim()
  28. const [name, value = d] = d.split(':')
  29. return { name, value }
  30. })
  31. }
  32. export function getClasses(list, options) {
  33. if ('string' === typeof list) {
  34. list = getStringList(list)
  35. }
  36. const result = getClassArray(list, options)
  37. // console.log(result, options);
  38. if (options?.scss) { // 生成scss
  39. createNameValueScss(result, options, list)
  40. }
  41. return result
  42. }
  43. // 驼峰法
  44. function getCamelCaseName(str) {
  45. if (typeof str !== 'string') return ''
  46. let words = str.split('-')
  47. for (let i = 1; i < words.length; i++) {
  48. words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1)
  49. }
  50. return words.join('')
  51. }
  52. function createNameValueScss(list, { name, value, scss }, _list) {
  53. if (typeof value !== 'string') {
  54. let strs = []
  55. list.map(d => {
  56. let className = `.${d.name} {`
  57. let classValue = d.value.join(' ')
  58. strs.push(`${className}${classValue} }\n`)
  59. })
  60. return console.log(`%c${strs.join('\r')}`, 'color: skyblue;')
  61. }
  62. const camelCaseName = getCamelCaseName(value)
  63. let arrValues = []
  64. _list.map(d => {
  65. arrValues.push(`'${name}${d.name}' '${d.value}'`)
  66. })
  67. const arrName = `$${camelCaseName}s`
  68. const arrs = `${arrName}: ${arrValues.join(',')}`
  69. let str = `
  70. // ${camelCaseName}
  71. \r
  72. ${arrs};
  73. \r
  74. @each $name, $val in ${arrName} {
  75. .#{$name} {${value}: #{$val};}
  76. }
  77. `
  78. console.log(`%c${str}`, 'color: skyblue;')
  79. }