useSyncAssetsFile.ts 1.81 KB
import { useGlobSetting } from "@/hooks/external/setting"
import { SelectOption } from "naive-ui"
import { ProjectRuntimeEnvEnum } from "../../../build/external/envEnum"

export const useSyncAssetsFile = () => {
  const { publicPath } = useGlobSetting()
  const staticDir = 'static'
  const isDev = [ProjectRuntimeEnvEnum.DEV, ProjectRuntimeEnvEnum.DEV_ALONE].includes(import.meta.env.MODE as ProjectRuntimeEnvEnum)
  const jpgModules = import.meta.glob('../../assets/**/*.jpg')
  const pngModules = import.meta.glob('../../assets/**/*.png')
  const imagesModules = { ...jpgModules, ...pngModules }

  const getFileInfo = (filePath: string) => {
    const filePathArr = filePath.split('/')
    const fileName = filePathArr.at(-1)
    const fileExt = fileName?.split('.').at(-1)
    return { fileName, fileExt }
  }

  const buildFilePath = (fileExt: string, fileName: string) => {
    return `${publicPath}${staticDir}/${fileExt}/${fileName}`
  }

  const setPath = (filePath: string) => {
    if (isDev && filePath) {
      const { fileExt, fileName } = getFileInfo(filePath)
      return buildFilePath(fileExt!, fileName!)
    }
    return filePath
  }

  const getPath = (filePath: string) => {
    if (isDev && filePath) {
      const { fileName } = getFileInfo(filePath)
      const imagesKeys = Object.keys(imagesModules)
      const path = imagesKeys.find(key => key.includes(fileName!))
      return `/src/${path?.replaceAll('../', '')}`
    }

    return filePath ?? ''
  }

  const transformPath = (filesPath: string[]) => {
    const _filesPath: SelectOption[] = []

    for (const file of filesPath) {
      const { fileExt, fileName } = getFileInfo(file)
      _filesPath.push({
        label: fileName,
        value: buildFilePath(fileExt!, fileName!)
      })
    }

    return _filesPath
  }

  return { setPath, getPath, transformPath }
}