wrapperComponent.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* eslint-disable @typescript-eslint/quotes */
  2. import path from 'path'
  3. import { cwd } from 'process'
  4. import { isObject } from '@antfu/utils'
  5. import fg from 'fast-glob'
  6. import type { WrapperComponent, WrapperComponentData } from './type'
  7. const c = cwd()
  8. export async function getWrapperComponent(option: WrapperComponent): Promise<WrapperComponentData> {
  9. if (option === true)
  10. option = `${c}/**/*.{jsx,tsx}`
  11. if (typeof option === 'string') {
  12. const data = await getComponent(option)
  13. return data
  14. }
  15. else if (Array.isArray(option)) {
  16. const allWrapperData = await Promise.all(option.map(getWrapperComponent))
  17. return allWrapperData.reduce((prev, next) => {
  18. return { ...prev, ...next }
  19. }, {})
  20. }
  21. else if (isObject(option)) {
  22. return option
  23. } else {
  24. return {}
  25. }
  26. }
  27. export async function getComponent(path: string): Promise<WrapperComponentData> {
  28. const component = await fg(path, { ignore: [`${c}/node_modules`] })
  29. const data: WrapperComponentData = {}
  30. component.forEach((item) => {
  31. let componentName = item.match(/\/([a-zA-Z0-9]+).[jt]sx/)?.[1]
  32. if (componentName) {
  33. componentName = handleComponentName(componentName)
  34. data[componentName] = item.replace('.[jt]sx', '')
  35. }
  36. })
  37. return data
  38. }
  39. function handleComponentName(str: string): string {
  40. if (/^[A-Z]/.test(str))
  41. return str
  42. else if (/^[a-z]/.test(str))
  43. return initialUpperCase(str)
  44. else
  45. return str
  46. }
  47. function initialUpperCase(str: string): string {
  48. return str[0].toUpperCase() + str.slice(1)
  49. }
  50. export function getComponentPath(markdownPath: string, componentPath: string): string {
  51. if (!path.isAbsolute(componentPath))
  52. componentPath = path.resolve(c, componentPath)
  53. const relPath = path.relative(path.dirname(markdownPath), componentPath)
  54. const fixedPath = relPath.startsWith(".") ? relPath : `./${relPath}`
  55. const finalPath = fixedPath.replace(/\\/g, "/") // for multi-platform support, use slashes
  56. return finalPath
  57. }