index.ts 2.15 KB
import type { PackageCategoryEnum } from './enum'
import { FetchComFlagTypeEnum } from './enum'
import type { ComponentConfigModuleType, CreateComponentParamsType, FetchComponentFileType } from './types'

const viewModules = import.meta.glob('./packages/**/index.vue', { eager: true })
const configModules = import.meta.glob('./packages/**/config.vue', { eager: true })
const createInstaceModules = import.meta.glob<ComponentConfigModuleType>('./packages/**/config.ts', { eager: true })

const findModule = (componentKey: string, categoryKey: string, module: Recordable) => {
  for (const key in module) {
    const urlSplit = key.split('/')
    const _componentKey = urlSplit[urlSplit.length - 2]
    const _cagegoryKey = urlSplit[urlSplit.length - 3]
    if (_componentKey.toUpperCase() === componentKey?.toUpperCase() && _cagegoryKey?.toUpperCase() === categoryKey.toUpperCase())
      return module[key] as Record<'default', any>
  }
}

export const fetchComponent = (componentKey: string, categoryKey: PackageCategoryEnum, flag: FetchComFlagTypeEnum) => {
  const module = flag === FetchComFlagTypeEnum.VIEW ? viewModules : configModules

  return findModule(componentKey, categoryKey, module)
}

export const fetchViewComponent = (configType: FetchComponentFileType) => {
  const { key, category } = configType
  return fetchComponent(key, category, FetchComFlagTypeEnum.VIEW)?.default
}

export const fetchConfigComponent = (configType: FetchComponentFileType) => {
  const { key, category } = configType
  return fetchComponent(key, category, FetchComFlagTypeEnum.CONFIG)?.default
}

export const createComponentInstance = (targetData: FetchComponentFileType, options?: CreateComponentParamsType) => {
  const { key, category } = targetData
  const module = findModule(key, category, createInstaceModules)
  const Instance = module?.default

  if (Instance)
    return new Instance(options || {})
}

export const fetchComponentDataSubscribers = (configType: FetchComponentFileType) => {
  const { key, category } = configType
  const module = findModule(key, category, createInstaceModules) as ComponentConfigModuleType
  if (module && module.dataSubscribers)
    return module.dataSubscribers
}