ftt-ui-components
Version:
some components for vuetify3/element-plus/... with vue3.
57 lines (47 loc) • 1.46 kB
text/typescript
import { getCurrentInstance, inject, computed, ref, provide, unref } from 'vue'
import { configProviderContextKey, ConfigProviderContext } from '../../utils'
import type { MaybeRef } from '@vueuse/core'
const globalConfig = ref<ConfigProviderContext>()
export function useGlobalConfig(
key?: keyof ConfigProviderContext,
defaultValue = undefined
) {
const config = getCurrentInstance()
? inject(configProviderContextKey, globalConfig)
: globalConfig
if (key) {
return computed(() => config.value?.[key] ?? defaultValue)
}
return config
}
export const provideGlobalConfig = (
config: MaybeRef<ConfigProviderContext>,
app?: App,
global = false
) => {
const inSetup = !!getCurrentInstance()
const oldConfig = inSetup ? useGlobalConfig() : undefined
const provideFn = app?.provide ?? (inSetup ? provide : undefined)
if (!provideFn) return
const context = computed(() => {
const cfg = unref(config)
if (!oldConfig.value) return cfg
return mergeConfig(oldConfig.value, cfg)
})
provideFn(configProviderContextKey, context)
if (global || !globalConfig.value) {
globalConfig.value = context.value
}
return context
}
const mergeConfig = (
a: ConfigProviderContext,
b: ConfigProviderContext
): ConfigProviderContext => {
const keys = [...new Set([...keysOf(a), ...keysOf(b)])]
const obj: Record<string, any> = {}
for (const key of keys) {
obj[key] = b[key] ?? a[key]
}
return obj
}