2022-03-25 15:35:56 +08:00
|
|
|
import { onBeforeUnmount, onMounted } from 'vue'
|
2022-05-20 18:13:27 +08:00
|
|
|
import { isClient } from '@vueuse/core'
|
2022-02-11 11:03:15 +08:00
|
|
|
import { EVENT_CODE } from '@element-plus/constants'
|
2022-01-04 09:15:15 +08:00
|
|
|
|
2022-05-20 18:13:27 +08:00
|
|
|
let registeredEscapeHandlers: ((e: KeyboardEvent) => void)[] = []
|
|
|
|
|
|
|
|
export const useEscapeKeydown = (handler: (e: KeyboardEvent) => void) => {
|
2022-01-04 09:15:15 +08:00
|
|
|
const cachedHandler = (e: Event) => {
|
|
|
|
const event = e as KeyboardEvent
|
|
|
|
if (event.key === EVENT_CODE.esc) {
|
2022-05-20 18:13:27 +08:00
|
|
|
registeredEscapeHandlers.forEach((registeredHandler) =>
|
|
|
|
registeredHandler(event)
|
|
|
|
)
|
2022-01-04 09:15:15 +08:00
|
|
|
}
|
|
|
|
}
|
2022-05-20 18:13:27 +08:00
|
|
|
|
2022-01-04 09:15:15 +08:00
|
|
|
onMounted(() => {
|
2022-05-20 18:13:27 +08:00
|
|
|
if (registeredEscapeHandlers.length === 0) {
|
|
|
|
document.addEventListener('keydown', cachedHandler)
|
|
|
|
}
|
|
|
|
if (isClient) registeredEscapeHandlers.push(handler)
|
2022-01-04 09:15:15 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
onBeforeUnmount(() => {
|
2022-05-20 18:13:27 +08:00
|
|
|
registeredEscapeHandlers = registeredEscapeHandlers.filter(
|
|
|
|
(registeredHandler) => registeredHandler !== handler
|
|
|
|
)
|
|
|
|
if (registeredEscapeHandlers.length === 0) {
|
|
|
|
if (isClient) document.removeEventListener('keydown', cachedHandler)
|
|
|
|
}
|
2022-01-04 09:15:15 +08:00
|
|
|
})
|
|
|
|
}
|