Created
April 2, 2024 14:37
-
-
Save IARI/aad137f60f24427c9ac40b8ffaee1b7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type NativeType = null | number | string | boolean | symbol | Function; | |
type InferDefault<P, T> = ((props: P) => T & {}) | (T extends NativeType ? T : never); | |
function getDefault<P, K extends keyof P>(defaults: DefaultProps<P>, k: K, injected?: DefaultProps<P>): InferDefault<P, P[K]> | undefined { | |
return (p) => { | |
const t: InferDefault<P, P[K]> | undefined = (injected && k in injected) ? injected[k] : defaults[k] | |
if (typeof t === 'function') return t(p) | |
return t | |
} | |
} | |
export function makeInjectDefaults<T, K extends string = 'fs'>(defaults: DefaultProps<T>, key: K = 'fs' as K) { | |
const injectionKey: InjectionKey<DefaultProps<T>> = Symbol(`${key}-vue-props`) | |
//const provideFun = | |
return () => ({ | |
[`provide${key}Props`]: (v: DefaultProps<T>, injectBase = true) => { | |
console.log(`provide${key}Props`, v) | |
if (injectBase) { | |
const injected = inject(injectionKey) | |
provide(injectionKey, Object.assign({}, injected, v)) | |
//console.log(`provide${key}Props injected`, Object.assign({}, injected, v)) | |
} else provide(injectionKey, v) | |
}, | |
[`getInjected${key}Defaults`]: () => { | |
const injected = inject(injectionKey) | |
console.log(`getInjected${key}Defaults`, injected) | |
return Object.fromEntries( | |
Object.keys(defaults) | |
.map(k => ([k, getDefault(defaults, k as keyof T, injected)])) | |
) as DefaultProps<T> | |
} | |
} as Record<`provide${K}Props`, (v: DefaultProps<T>, injectBase?: boolean) => void> & Record<`getInjected${K}Defaults`, () => DefaultProps<T>>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment