2020-09-09 21:18:08 +08:00
|
|
|
import { watch } from 'vue'
|
|
|
|
import { on } from '@element-plus/utils/dom'
|
|
|
|
import { EVENT_CODE } from '@element-plus/utils/aria'
|
|
|
|
import isServer from '@element-plus/utils/isServer'
|
|
|
|
|
|
|
|
import type { Ref, ComputedRef } from 'vue'
|
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default (
|
|
|
|
instance: ModalInstance,
|
2021-09-04 19:29:28 +08:00
|
|
|
visibleRef: Ref<boolean> | ComputedRef
|
2020-09-09 21:18:08 +08:00
|
|
|
) => {
|
|
|
|
watch(
|
|
|
|
() => visibleRef.value,
|
2021-09-04 19:29:28 +08:00
|
|
|
(val) => {
|
2020-09-09 21:18:08 +08:00
|
|
|
if (val) {
|
|
|
|
modalStack.push(instance)
|
|
|
|
} else {
|
|
|
|
modalStack.splice(
|
2021-09-04 19:29:28 +08:00
|
|
|
modalStack.findIndex((modal) => modal === instance),
|
|
|
|
1
|
2020-09-09 21:18:08 +08:00
|
|
|
)
|
|
|
|
}
|
2021-09-04 19:29:28 +08:00
|
|
|
}
|
2020-09-09 21:18:08 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isServer) {
|
|
|
|
on(document, 'keydown', closeModal)
|
|
|
|
}
|