mirror of https://github.com/nocodb/nocodb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
968 B
38 lines
968 B
2 years ago
|
import type { InjectionKey } from 'vue'
|
||
|
import { inject, provide, tryOnScopeDispose } from '#imports'
|
||
2 years ago
|
|
||
|
export function useInjectionState<Arguments extends any[], Return>(
|
||
|
composable: (...args: Arguments) => Return,
|
||
2 years ago
|
keyName = 'InjectionState',
|
||
2 years ago
|
): readonly [useInjectionState: (...args: Arguments) => Return, useInjectedState: () => Return | undefined] {
|
||
2 years ago
|
const key: string | InjectionKey<Return> = Symbol(keyName)
|
||
|
|
||
|
let providableState: Return | undefined
|
||
2 years ago
|
|
||
|
const useProvidingState = (...args: Arguments) => {
|
||
|
const providedState = composable(...args)
|
||
|
|
||
|
provide(key, providedState)
|
||
|
|
||
2 years ago
|
providableState = providedState
|
||
|
|
||
2 years ago
|
return providedState
|
||
|
}
|
||
|
|
||
2 years ago
|
const useInjectedState = () => {
|
||
|
let injection = inject(key, undefined)
|
||
|
|
||
|
if (typeof injection === 'undefined') {
|
||
2 years ago
|
injection = providableState
|
||
2 years ago
|
}
|
||
|
|
||
|
return injection
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
tryOnScopeDispose(() => {
|
||
|
providableState = undefined
|
||
|
})
|
||
|
|
||
2 years ago
|
return [useProvidingState, useInjectedState]
|
||
|
}
|