Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(syncRef): avoid infinite sync #3312

Merged
merged 5 commits into from
Aug 25, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 20 additions & 14 deletions packages/shared/syncRef/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { pausableWatch } from '@vueuse/core'
import type { WatchPausableReturn } from '@vueuse/core'
import type { Ref } from 'vue-demi'
import type { Ref, WatchStopHandle } from 'vue-demi'
import { watch } from 'vue-demi'
import type { ConfigurableFlushSync } from '../utils'

export interface SyncRefOptions<L, R = L> extends ConfigurableFlushSync {
Expand Down Expand Up @@ -38,7 +37,6 @@ export interface SyncRefOptions<L, R = L> extends ConfigurableFlushSync {
*
* @param left
* @param right
* @param options
*/
export function syncRef<L, R = L>(left: Ref<L>, right: Ref<R>, options: SyncRefOptions<L, R> = {}) {
const {
Expand All @@ -49,38 +47,46 @@ export function syncRef<L, R = L>(left: Ref<L>, right: Ref<R>, options: SyncRefO
transform = {},
} = options

let watchLeft: WatchPausableReturn
let watchRight: WatchPausableReturn
let watchLeft: WatchStopHandle
let watchRight: WatchStopHandle

let stop = false

const transformLTR = transform.ltr ?? (v => v)
const transformRTL = transform.rtl ?? (v => v)

if (direction === 'both' || direction === 'ltr') {
watchLeft = pausableWatch(
watchLeft = watch(
left,
(newValue) => {
watchRight?.pause()
if (stop)
return

stop = true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the flush paramter of options is 'post', dose it work properly?

right.value = transformLTR(newValue) as R
watchRight?.resume()
stop = false
},
{ flush, deep, immediate },
)
}

if (direction === 'both' || direction === 'rtl') {
watchRight = pausableWatch(
watchRight = watch(
right,
(newValue) => {
watchLeft?.pause()
if (stop)
return

stop = true
left.value = transformRTL(newValue) as L
watchLeft?.resume()
stop = false
},
{ flush, deep, immediate },
)
}

return () => {
watchLeft?.stop()
watchRight?.stop()
watchLeft?.()
watchRight?.()
}
}