koel/resources/assets/js/utils/helpers.ts

71 lines
2.1 KiB
TypeScript
Raw Normal View History

import { isObject, without } from 'lodash'
2024-03-19 22:48:12 +00:00
import { inject, InjectionKey, isRef, provide, readonly, shallowReadonly } from 'vue'
2022-07-20 08:00:02 +00:00
import { ReadonlyInjectionKey } from '@/symbols'
2024-03-19 22:48:12 +00:00
import { logger, md5 } from '@/utils'
2022-07-20 08:00:02 +00:00
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)
}
export const arrayify = <T> (maybeArray: T | Array<T>) => Array.isArray(maybeArray) ? maybeArray : [maybeArray]
2022-04-20 09:37:22 +00:00
// @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') {
throw new Error(`Missing injection: ${key.toString()}`)
2022-07-20 08:00:02 +00:00
}
return value
}
2022-11-02 19:25:22 +00:00
export const dbToGain = (db: number) => Math.pow(10, db / 20) || 0
export const moveItemsInList = <T> (list: T[], items: T | T[], target: T, type: MoveType) => {
if (list.indexOf(target) === -1) {
throw 'Target not found in list'
}
const subset = arrayify(items)
const isTargetAdjacent = type === 'before'
? list.indexOf(subset[subset.length - 1]) + 1 === list.indexOf(target)
: list.indexOf(subset[0]) - 1 === list.indexOf(target)
if (isTargetAdjacent) {
return list
}
const updatedList = without(list, ...subset)
const targetIndex = updatedList.indexOf(target);
updatedList.splice(type === 'before' ? targetIndex : targetIndex + 1, 0, ...subset)
return updatedList
}
2024-03-19 22:48:12 +00:00
export const gravatar = (email: string, size = 192) => {
const hash = md5(email.trim().toLowerCase())
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=robohash`
}