-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.ts
49 lines (42 loc) · 1.87 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type { MaybeRef, MaybeRefOrGetter } from '@vueuse/shared'
import type { Options } from 'change-case'
import type { ComputedRef, WritableComputedRef } from 'vue-demi'
import { toValue } from '@vueuse/shared'
import * as changeCase from 'change-case'
import { computed, ref } from 'vue-demi'
type EndsWithCase<T> = T extends `${infer _}Case` ? T : never
type FilterKeys<T> = { [K in keyof T as K extends string ? K : never]: EndsWithCase<K> }
type ChangeCaseKeys = FilterKeys<typeof changeCase>
export type ChangeCaseType = ChangeCaseKeys[keyof ChangeCaseKeys]
const changeCaseTransforms: any = /* @__PURE__ */ Object.entries(changeCase)
.filter(([name, fn]) => typeof fn === 'function' && name.endsWith('Case'))
.reduce((acc, [name, fn]) => {
acc[name] = fn
return acc
}, {} as any)
export function useChangeCase(input: MaybeRef<string>, type: MaybeRefOrGetter<ChangeCaseType>, options?: MaybeRefOrGetter<Options> | undefined): WritableComputedRef<string>
export function useChangeCase(input: MaybeRefOrGetter<string>, type: MaybeRefOrGetter<ChangeCaseType>, options?: MaybeRefOrGetter<Options> | undefined): ComputedRef<string>
/**
* Reactive wrapper for `change-case`
*
* @see https://vueuse.org/useChangeCase
*/
export function useChangeCase(input: MaybeRefOrGetter<string>, type: MaybeRefOrGetter<ChangeCaseType>, options?: MaybeRefOrGetter<Options> | undefined) {
const typeRef = computed(() => {
const t = toValue(type)
if (!changeCaseTransforms[t])
throw new Error(`Invalid change case type "${t}"`)
return t
})
if (typeof input === 'function')
return computed(() => changeCaseTransforms[typeRef.value](toValue(input), toValue(options)))
const text = ref(input)
return computed<string>({
get() {
return changeCaseTransforms[typeRef.value](text.value, toValue(options))
},
set(value) {
text.value = value
},
})
}