script.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. export default Icon
  59. `.trim())
  60. await writeFile(path.resolve(currentPath, `${fileName}.json`), JSON.stringify(svgData, '', '\t'))
  61. await writeFile(path.resolve(currentPath, `${fileName}.tsx`), `${componentRender({ svgName: fileName })}\n`)
  62. const indexingRender = template(`
  63. export { default as <%= svgName %> } from './<%= svgName %>'
  64. `.trim())
  65. await appendFile(path.resolve(currentPath, 'index.ts'), `${indexingRender({ svgName: fileName })}\n`)
  66. }
  67. const generateImageComponent = async (entry, pathList) => {
  68. const currentPath = path.resolve(__dirname, 'src', ...pathList.slice(2))
  69. try {
  70. await access(currentPath)
  71. }
  72. catch {
  73. await generateDir(currentPath)
  74. }
  75. const prefixFileName = camelCase(entry.split('.')[0])
  76. const fileName = prefixFileName.charAt(0).toUpperCase() + prefixFileName.slice(1)
  77. const componentCSSRender = template(`
  78. .wrapper {
  79. display: inline-flex;
  80. background: url(<%= assetPath %>) center center no-repeat;
  81. background-size: contain;
  82. }
  83. `.trim())
  84. await writeFile(path.resolve(currentPath, `${fileName}.module.css`), `${componentCSSRender({ assetPath: path.join('~@/app/components/base/icons/assets', ...pathList.slice(2), entry) })}\n`)
  85. const componentRender = template(`
  86. // GENERATE BY script
  87. // DON NOT EDIT IT MANUALLY
  88. import * as React from 'react'
  89. import cn from 'classnames'
  90. import s from './<%= fileName %>.module.css'
  91. const Icon = React.forwardRef<HTMLSpanElement, React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>>((
  92. { className, ...restProps },
  93. ref,
  94. ) => <span className={cn(s.wrapper, className)} {...restProps} ref={ref} />)
  95. export default Icon
  96. `.trim())
  97. await writeFile(path.resolve(currentPath, `${fileName}.tsx`), `${componentRender({ fileName })}\n`)
  98. const indexingRender = template(`
  99. export { default as <%= fileName %> } from './<%= fileName %>'
  100. `.trim())
  101. await appendFile(path.resolve(currentPath, 'index.ts'), `${indexingRender({ fileName })}\n`)
  102. }
  103. const walk = async (entry, pathList, replaceFillOrStrokeColor) => {
  104. const currentPath = path.resolve(...pathList, entry)
  105. let fileHandle
  106. try {
  107. fileHandle = await open(currentPath)
  108. const stat = await fileHandle.stat()
  109. if (stat.isDirectory()) {
  110. const files = await readdir(currentPath)
  111. for (const file of files)
  112. await walk(file, [...pathList, entry], replaceFillOrStrokeColor)
  113. }
  114. if (stat.isFile() && /.+\.svg$/g.test(entry))
  115. await generateSvgComponent(fileHandle, entry, pathList, replaceFillOrStrokeColor)
  116. if (stat.isFile() && /.+\.png$/g.test(entry))
  117. await generateImageComponent(entry, pathList)
  118. }
  119. finally {
  120. fileHandle?.close()
  121. }
  122. }
  123. (async () => {
  124. await rm(path.resolve(__dirname, 'src'), { recursive: true, force: true })
  125. await walk('public', [__dirname, 'assets'])
  126. await walk('vender', [__dirname, 'assets'], true)
  127. await walk('image', [__dirname, 'assets'])
  128. })()