script.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. const path = require('node:path')
  2. const { open, readdir, access, mkdir, writeFile, appendFile, rm } = require('node:fs/promises')
  3. const { parseXml } = require('@rgrove/parse-xml')
  4. const camelCase = require('lodash/camelCase')
  5. const template = require('lodash/template')
  6. const generateDir = async (currentPath) => {
  7. try {
  8. await mkdir(currentPath, { recursive: true })
  9. }
  10. catch (err) {
  11. console.error(err.message)
  12. }
  13. }
  14. const processSvgStructure = (svgStructure, replaceFillOrStrokeColor) => {
  15. if (svgStructure?.children.length) {
  16. svgStructure.children = svgStructure.children.filter(c => c.type !== 'text')
  17. svgStructure.children.forEach((child) => {
  18. if (child?.name === 'path' && replaceFillOrStrokeColor) {
  19. if (child?.attributes?.stroke)
  20. child.attributes.stroke = 'currentColor'
  21. if (child?.attributes.fill)
  22. child.attributes.fill = 'currentColor'
  23. }
  24. if (child?.children.length)
  25. processSvgStructure(child, replaceFillOrStrokeColor)
  26. })
  27. }
  28. }
  29. const generateSvgComponent = async (fileHandle, entry, pathList, replaceFillOrStrokeColor) => {
  30. const currentPath = path.resolve(__dirname, 'src', ...pathList.slice(2))
  31. try {
  32. await access(currentPath)
  33. }
  34. catch {
  35. await generateDir(currentPath)
  36. }
  37. const svgString = await fileHandle.readFile({ encoding: 'utf8' })
  38. const svgJson = parseXml(svgString).toJSON()
  39. const svgStructure = svgJson.children[0]
  40. processSvgStructure(svgStructure, replaceFillOrStrokeColor)
  41. const prefixFileName = camelCase(entry.split('.')[0])
  42. const fileName = prefixFileName.charAt(0).toUpperCase() + prefixFileName.slice(1)
  43. const svgData = {
  44. icon: svgStructure,
  45. name: fileName,
  46. }
  47. const componentRender = template(`
  48. // GENERATE BY script
  49. // DON NOT EDIT IT MANUALLY
  50. import * as React from 'react'
  51. import data from './<%= svgName %>.json'
  52. import IconBase from '@/app/components/base/icons/IconBase'
  53. import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'
  54. const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((
  55. props,
  56. ref,
  57. ) => <IconBase {...props} ref={ref} data={data as IconData} />)
  58. Icon.displayName = '<%= svgName %>'
  59. export default Icon
  60. `.trim())
  61. await writeFile(path.resolve(currentPath, `${fileName}.json`), JSON.stringify(svgData, '', '\t'))
  62. await writeFile(path.resolve(currentPath, `${fileName}.tsx`), `${componentRender({ svgName: fileName })}\n`)
  63. const indexingRender = template(`
  64. export { default as <%= svgName %> } from './<%= svgName %>'
  65. `.trim())
  66. await appendFile(path.resolve(currentPath, 'index.ts'), `${indexingRender({ svgName: fileName })}\n`)
  67. }
  68. const generateImageComponent = async (entry, pathList) => {
  69. const currentPath = path.resolve(__dirname, 'src', ...pathList.slice(2))
  70. try {
  71. await access(currentPath)
  72. }
  73. catch {
  74. await generateDir(currentPath)
  75. }
  76. const prefixFileName = camelCase(entry.split('.')[0])
  77. const fileName = prefixFileName.charAt(0).toUpperCase() + prefixFileName.slice(1)
  78. const componentCSSRender = template(`
  79. .wrapper {
  80. display: inline-flex;
  81. background: url(<%= assetPath %>) center center no-repeat;
  82. background-size: contain;
  83. }
  84. `.trim())
  85. await writeFile(path.resolve(currentPath, `${fileName}.module.css`), `${componentCSSRender({ assetPath: path.join('~@/app/components/base/icons/assets', ...pathList.slice(2), entry) })}\n`)
  86. const componentRender = template(`
  87. // GENERATE BY script
  88. // DON NOT EDIT IT MANUALLY
  89. import * as React from 'react'
  90. import cn from '@/utils/classnames'
  91. import s from './<%= fileName %>.module.css'
  92. const Icon = React.forwardRef<HTMLSpanElement, React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>>((
  93. { className, ...restProps },
  94. ref,
  95. ) => <span className={cn(s.wrapper, className)} {...restProps} ref={ref} />)
  96. Icon.displayName = '<%= fileName %>'
  97. export default Icon
  98. `.trim())
  99. await writeFile(path.resolve(currentPath, `${fileName}.tsx`), `${componentRender({ fileName })}\n`)
  100. const indexingRender = template(`
  101. export { default as <%= fileName %> } from './<%= fileName %>'
  102. `.trim())
  103. await appendFile(path.resolve(currentPath, 'index.ts'), `${indexingRender({ fileName })}\n`)
  104. }
  105. const walk = async (entry, pathList, replaceFillOrStrokeColor) => {
  106. const currentPath = path.resolve(...pathList, entry)
  107. let fileHandle
  108. try {
  109. fileHandle = await open(currentPath)
  110. const stat = await fileHandle.stat()
  111. if (stat.isDirectory()) {
  112. const files = await readdir(currentPath)
  113. for (const file of files)
  114. await walk(file, [...pathList, entry], replaceFillOrStrokeColor)
  115. }
  116. if (stat.isFile() && /.+\.svg$/g.test(entry))
  117. await generateSvgComponent(fileHandle, entry, pathList, replaceFillOrStrokeColor)
  118. if (stat.isFile() && /.+\.png$/g.test(entry))
  119. await generateImageComponent(entry, pathList)
  120. }
  121. finally {
  122. fileHandle?.close()
  123. }
  124. }
  125. (async () => {
  126. await rm(path.resolve(__dirname, 'src'), { recursive: true, force: true })
  127. await walk('public', [__dirname, 'assets'])
  128. await walk('vender', [__dirname, 'assets'], true)
  129. await walk('image', [__dirname, 'assets'])
  130. })()