2020-09-09 21:18:08 +08:00
|
|
|
import { watch } from 'vue'
|
2021-11-29 15:58:44 +08:00
|
|
|
import { isClient, useEventListener } from '@vueuse/core'
|
2020-09-09 21:18:08 +08:00
|
|
|
import { EVENT_CODE } from '@element-plus/utils/aria'
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
import type { Ref } from 'vue'
|
2020-09-09 21:18:08 +08:00
|
|
|
|
|
|
|
type ModalInstance = {
|
|
|
|
handleClose: () => void
|
2021-09-04 19:29:28 +08:00
|
|
|
}
|
2020-09-09 21:18:08 +08:00
|
|
|
|
|
|
|
const modalStack: ModalInstance[] = []
|
|
|
|
|
|
|
|
const closeModal = (e: KeyboardEvent) => {
|
|
|
|
if (modalStack.length === 0) return
|
|
|
|
if (e.code === EVENT_CODE.esc) {
|
2021-01-14 17:01:37 +08:00
|
|
|
e.stopPropagation()
|
2020-09-09 21:18:08 +08:00
|
|
|
const topModal = modalStack[modalStack.length - 1]
|
|
|
|
topModal.handleClose()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
export const useModal = (instance: ModalInstance, visibleRef: Ref<boolean>) => {
|
|
|
|
watch(visibleRef, (val) => {
|
|
|
|
if (val) {
|
|
|
|
modalStack.push(instance)
|
|
|
|
} else {
|
|
|
|
modalStack.splice(
|
|
|
|
modalStack.findIndex((modal) => modal === instance),
|
|
|
|
1
|
|
|
|
)
|
2021-09-04 19:29:28 +08:00
|
|
|
}
|
2021-11-29 15:58:44 +08:00
|
|
|
})
|
2020-09-09 21:18:08 +08:00
|
|
|
}
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
if (isClient) useEventListener(document, 'keydown', closeModal)
|