mirror of
https://github.com/element-plus/element-plus.git
synced 2024-12-27 03:01:14 +08:00
e1b88263e3
* feat(components): [popper] fix focus traps * feat(components): [popper] add focus trap tests Co-authored-by: JeremyWuuuuu <15975785+JeremyWuuuuu@users.noreply.github.com>
33 lines
1004 B
TypeScript
33 lines
1004 B
TypeScript
import { onBeforeUnmount, onMounted } from 'vue'
|
|
import { isClient } from '@vueuse/core'
|
|
import { EVENT_CODE } from '@element-plus/constants'
|
|
|
|
let registeredEscapeHandlers: ((e: KeyboardEvent) => void)[] = []
|
|
|
|
export const useEscapeKeydown = (handler: (e: KeyboardEvent) => void) => {
|
|
const cachedHandler = (e: Event) => {
|
|
const event = e as KeyboardEvent
|
|
if (event.key === EVENT_CODE.esc) {
|
|
registeredEscapeHandlers.forEach((registeredHandler) =>
|
|
registeredHandler(event)
|
|
)
|
|
}
|
|
}
|
|
|
|
onMounted(() => {
|
|
if (registeredEscapeHandlers.length === 0) {
|
|
document.addEventListener('keydown', cachedHandler)
|
|
}
|
|
if (isClient) registeredEscapeHandlers.push(handler)
|
|
})
|
|
|
|
onBeforeUnmount(() => {
|
|
registeredEscapeHandlers = registeredEscapeHandlers.filter(
|
|
(registeredHandler) => registeredHandler !== handler
|
|
)
|
|
if (registeredEscapeHandlers.length === 0) {
|
|
if (isClient) document.removeEventListener('keydown', cachedHandler)
|
|
}
|
|
})
|
|
}
|