2021-01-14 17:01:37 +08:00
|
|
|
import { watch } from 'vue'
|
2021-11-29 15:58:44 +08:00
|
|
|
import { useEventListener } from '@vueuse/core'
|
2021-01-14 17:01:37 +08:00
|
|
|
import type { Ref } from 'vue'
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
export const usePreventGlobal = <E extends keyof DocumentEventMap>(
|
2021-09-04 19:29:28 +08:00
|
|
|
indicator: Ref<boolean>,
|
2021-11-29 15:58:44 +08:00
|
|
|
evt: E,
|
|
|
|
cb: (e: DocumentEventMap[E]) => boolean
|
2021-09-04 19:29:28 +08:00
|
|
|
) => {
|
2021-11-29 15:58:44 +08:00
|
|
|
const prevent = (e: DocumentEventMap[E]) => {
|
|
|
|
if (cb(e)) e.stopImmediatePropagation()
|
2021-01-14 17:01:37 +08:00
|
|
|
}
|
2021-11-29 15:58:44 +08:00
|
|
|
let stop: (() => void) | undefined = undefined
|
2021-09-04 19:29:28 +08:00
|
|
|
watch(
|
|
|
|
() => indicator.value,
|
|
|
|
(val) => {
|
|
|
|
if (val) {
|
2021-11-29 15:58:44 +08:00
|
|
|
stop = useEventListener(document, evt, prevent, true)
|
2021-09-04 19:29:28 +08:00
|
|
|
} else {
|
2021-11-29 15:58:44 +08:00
|
|
|
stop?.()
|
2021-09-04 19:29:28 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
{ immediate: true }
|
|
|
|
)
|
2021-01-14 17:01:37 +08:00
|
|
|
}
|