yanzhen-design-vue
Version:
53 lines (52 loc) • 1.71 kB
JavaScript
import { ref, getCurrentInstance, inject, computed, provide, unref } from "vue";
import { keysOf } from "@yanzhen-libs/utils";
import { warn } from "@yanzhen-lowcode/core";
import { configProviderContextKey } from "../constants.mjs";
const globalConfig = ref();
function useInjectGlobalConfig(key, defaultValue = void 0) {
const config = getCurrentInstance() ? inject(configProviderContextKey, globalConfig) : globalConfig;
if (key) {
return computed(() => {
var _a;
return ((_a = config.value) == null ? void 0 : _a[key]) ?? defaultValue;
});
} else {
return config;
}
}
const message = "provideGlobalConfig() can only be used inside setup().";
const provideGlobalConfig = (config, app, global = false) => {
const inSetup = !!getCurrentInstance();
if (!inSetup) {
warn(`provideGlobalConfig${message}`);
return;
}
const oldConfig = inSetup ? useInjectGlobalConfig() : void 0;
const provideFn = (app == null ? void 0 : app.provide) ?? provide;
if (!provideFn) {
warn(`provideGlobalConfig${message}`);
return;
}
const context = computed(() => {
const cfg = unref(config);
if (!(oldConfig == null ? void 0 : oldConfig.value)) return cfg;
return mergeConfig(oldConfig == null ? void 0 : oldConfig.value, cfg);
});
provideFn(configProviderContextKey, context);
if (global || !globalConfig.value) {
globalConfig.value = context.value;
}
return context;
};
const mergeConfig = (a, b) => {
const keys = [.../* @__PURE__ */ new Set([...keysOf(a), ...keysOf(b)])];
const obj = {};
for (const key of keys) {
obj[key] = b[key] ?? a[key];
}
return obj;
};
export {
provideGlobalConfig,
useInjectGlobalConfig
};