forked from CyCraft/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.ts
56 lines (48 loc) · 1.17 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
50
51
52
53
54
55
56
import { Ref, WatchOptions, watch } from 'vue-demi'
import { promiseTimeout } from '../utils'
interface WhenToMatchOptions {
flush?: WatchOptions['flush']
timeout?: number
}
export function when<T>(r: Ref<T>) {
function toMatch(
condition: (v: T) => boolean,
{ flush = 'post', timeout }: WhenToMatchOptions = {},
): Promise<void> {
let stop: Function | null = null
const watcher = new Promise<void>((resolve) => {
stop = watch(r, (v) => {
if (condition(v)) {
stop?.()
resolve()
}
}, {
flush,
immediate: true,
})
})
const promises = [watcher]
if (timeout) {
promises.push(
promiseTimeout(timeout)
.finally(() => { stop?.() }),
)
}
return Promise.any(promises)
}
function toBe(value: T, options?: WhenToMatchOptions) {
return toMatch(v => v === value, options)
}
function toBeTruthy(options?: WhenToMatchOptions) {
return toMatch(v => Boolean(v), options)
}
function toNotNull(options?: WhenToMatchOptions) {
return toMatch(v => v != null, options)
}
return {
toMatch,
toBe,
toBeTruthy,
toNotNull,
}
}