/
index.ts
85 lines (75 loc) · 1.81 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Ref } from 'vue-demi'
import type { ConfigurableFlushSync } from '../utils'
import type { WatchPausableReturn } from '../watchPausable'
import { pausableWatch } from '../watchPausable'
export interface SyncRefOptions<L, R = L> extends ConfigurableFlushSync {
/**
* Watch deeply
*
* @default false
*/
deep?: boolean
/**
* Sync values immediately
*
* @default true
*/
immediate?: boolean
/**
* Direction of syncing. Value will be redefined if you define syncConvertors
*
* @default 'both'
*/
direction?: 'ltr' | 'rtl' | 'both'
/**
* Custom transform function
*/
transform?: {
ltr?: (left: L) => R
rtl?: (right: R) => L
}
}
/**
* Two-way refs synchronization.
*
* @param left
* @param right
*/
export function syncRef<L, R = L>(left: Ref<L>, right: Ref<R>, options: SyncRefOptions<L, R> = {}) {
const {
flush = 'sync',
deep = false,
immediate = true,
direction = 'both',
transform = {},
} = options
const watchers: WatchPausableReturn[] = []
const transformLTR = transform.ltr ?? (v => v)
const transformRTL = transform.rtl ?? (v => v)
if (direction === 'both' || direction === 'ltr') {
watchers.push(pausableWatch(
left,
(newValue) => {
watchers.forEach(w => w.pause())
right.value = transformLTR(newValue) as R
watchers.forEach(w => w.resume())
},
{ flush, deep, immediate },
))
}
if (direction === 'both' || direction === 'rtl') {
watchers.push(pausableWatch(
right,
(newValue) => {
watchers.forEach(w => w.pause())
left.value = transformRTL(newValue) as L
watchers.forEach(w => w.resume())
},
{ flush, deep, immediate },
))
}
const stop = () => {
watchers.forEach(w => w.stop())
}
return stop
}