2022-07-20 08:00:02 +00:00
|
|
|
import { isObject } from 'lodash'
|
|
|
|
import { inject, InjectionKey, isRef, provide, readonly, shallowReadonly } from 'vue'
|
|
|
|
import { ReadonlyInjectionKey } from '@/symbols'
|
|
|
|
import { logger } from '@/utils'
|
|
|
|
|
2022-04-20 09:37:22 +00:00
|
|
|
export const use = <T> (value: T, cb: (arg: T) => void) => {
|
2022-04-15 14:24:30 +00:00
|
|
|
if (typeof value === 'undefined' || value === null) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
cb(value)
|
|
|
|
}
|
|
|
|
|
2022-04-20 09:37:22 +00:00
|
|
|
export const arrayify = <T> (maybeArray: T | Array<T>) => ([] as Array<T>).concat(maybeArray)
|
|
|
|
|
|
|
|
// @ts-ignore
|
2022-05-14 15:13:29 +00:00
|
|
|
export const noop = () => {
|
|
|
|
}
|
|
|
|
|
2022-05-14 15:51:47 +00:00
|
|
|
export const limitBy = <T> (arr: T[], count: number, offset: number = 0): T[] => arr.slice(offset, offset + count)
|
2022-07-20 08:00:02 +00:00
|
|
|
|
|
|
|
export const provideReadonly = <T> (key: ReadonlyInjectionKey<T>, value: T, deep = true, mutator?: Closure) => {
|
|
|
|
mutator = mutator || (v => isRef(value) ? (value.value = v) : (value = v))
|
|
|
|
|
|
|
|
if (!isObject(value)) {
|
|
|
|
logger.warn(`value cannot be made readonly: ${value}`)
|
|
|
|
provide(key, [value, mutator])
|
|
|
|
} else {
|
|
|
|
provide(key, [deep ? readonly(value) : shallowReadonly(value), mutator])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const requireInjection = <T> (key: InjectionKey<T>, defaultValue?: T) => {
|
|
|
|
const value = inject(key, defaultValue)
|
|
|
|
|
|
|
|
if (typeof value === 'undefined') {
|
2022-07-20 21:20:43 +00:00
|
|
|
throw new Error(`Missing injection: ${key.toString()}`)
|
2022-07-20 08:00:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return value
|
|
|
|
}
|