diff --git a/packages/x-components/src/composables/index.ts b/packages/x-components/src/composables/index.ts index 13ead653d3..f9bdc3b07b 100644 --- a/packages/x-components/src/composables/index.ts +++ b/packages/x-components/src/composables/index.ts @@ -5,3 +5,4 @@ export * from './use-on-display'; export * from './use-store'; export * from './use-state'; export * from './use-getter'; +export * from './use-hybrid-inject'; diff --git a/packages/x-components/src/composables/use-hybrid-inject.ts b/packages/x-components/src/composables/use-hybrid-inject.ts new file mode 100644 index 0000000000..c41f2cdb8a --- /dev/null +++ b/packages/x-components/src/composables/use-hybrid-inject.ts @@ -0,0 +1,26 @@ +import { computed, ComputedRef, inject } from 'vue'; + +/** + * Function to use a hybrid inject, which allows to inject a value provided by the regular provide + * of vue or by the XProvide decorator. + * + * @param key - The key of the value to inject. + * @param defaultValue - The default value to use if the value is not provided. + * @returns The computed value of the injected value. + */ +export function useHybridInject( + key: string, + defaultValue?: SomeValue +): ComputedRef { + type WrappedValue = { value: SomeValue }; + + return computed(() => { + const injectedValue = defaultValue + ? inject(key, defaultValue) + : inject(key); + + return injectedValue && typeof injectedValue === 'object' && 'value' in injectedValue + ? injectedValue.value + : injectedValue; + }); +}