element-plus/packages/hooks/use-modal/index.ts
三咲智子 55348b30b6
style: use prettier (#3228)
* style: use prettier

* style: just prettier format, no code changes

* style: eslint fix
object-shorthand, prefer-const

* style: fix no-void

* style: no-console
2021-09-04 19:29:28 +08:00

45 lines
946 B
TypeScript

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
}
const modalStack: ModalInstance[] = []
const closeModal = (e: KeyboardEvent) => {
if (modalStack.length === 0) return
if (e.code === EVENT_CODE.esc) {
e.stopPropagation()
const topModal = modalStack[modalStack.length - 1]
topModal.handleClose()
}
}
export default (
instance: ModalInstance,
visibleRef: Ref<boolean> | ComputedRef
) => {
watch(
() => visibleRef.value,
(val) => {
if (val) {
modalStack.push(instance)
} else {
modalStack.splice(
modalStack.findIndex((modal) => modal === instance),
1
)
}
}
)
}
if (!isServer) {
on(document, 'keydown', closeModal)
}