index.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { ref, getCurrentInstance, inject, computed, provide, unref } from 'vue';
  2. import '../../tokens/index.mjs';
  3. import '../../utils/index.mjs';
  4. import { configProviderContextKey } from '../../tokens/config-provider.mjs';
  5. import { debugWarn } from '../../utils/error.mjs';
  6. import { keysOf } from '../../utils/objects.mjs';
  7. const globalConfig = ref();
  8. function useGlobalConfig(key, defaultValue = void 0) {
  9. const config = getCurrentInstance() ? inject(configProviderContextKey, globalConfig) : globalConfig;
  10. if (key) {
  11. return computed(() => {
  12. var _a, _b;
  13. return (_b = (_a = config.value) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
  14. });
  15. } else {
  16. return config;
  17. }
  18. }
  19. const provideGlobalConfig = (config, app, global = false) => {
  20. var _a;
  21. const inSetup = !!getCurrentInstance();
  22. const oldConfig = inSetup ? useGlobalConfig() : void 0;
  23. const provideFn = (_a = app == null ? void 0 : app.provide) != null ? _a : inSetup ? provide : void 0;
  24. if (!provideFn) {
  25. debugWarn("provideGlobalConfig", "provideGlobalConfig() can only be used inside setup().");
  26. return;
  27. }
  28. const context = computed(() => {
  29. const cfg = unref(config);
  30. if (!(oldConfig == null ? void 0 : oldConfig.value))
  31. return cfg;
  32. return mergeConfig(oldConfig.value, cfg);
  33. });
  34. provideFn(configProviderContextKey, context);
  35. if (global || !globalConfig.value) {
  36. globalConfig.value = context.value;
  37. }
  38. return context;
  39. };
  40. const mergeConfig = (a, b) => {
  41. var _a;
  42. const keys = [.../* @__PURE__ */ new Set([...keysOf(a), ...keysOf(b)])];
  43. const obj = {};
  44. for (const key of keys) {
  45. obj[key] = (_a = b[key]) != null ? _a : a[key];
  46. }
  47. return obj;
  48. };
  49. export { provideGlobalConfig, useGlobalConfig };
  50. //# sourceMappingURL=index.mjs.map