Skip to content

Commit

Permalink
chore(use-composable): add new useEscapeKeydown (oku-ui#248)
Browse files Browse the repository at this point in the history
* feat: add useEscapeKeydown

* add a cleanup callback

* add test

* cleanup
  • Loading branch information
Cr0zy07 authored Jul 27, 2023
1 parent 2f44a96 commit b971406
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/core/use-composable/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export { usePrevious } from './usePrevious'
export { useRef } from './useRef'
export { unrefElement } from './unrefElement'
export { useId } from './useId'
export { useEscapeKeydown } from './useEscapeKeydown'
export type { MaybeComputedElementRef } from './unrefElement'

export { computedEager, syncRef }
34 changes: 34 additions & 0 deletions packages/core/use-composable/src/useEscapeKeydown.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useEscapeKeydown } from './useEscapeKeydown'

describe('useEscapeKeydown', () => {
let onEscapeKeyDown: any
let ownerDocument: Document

beforeEach(() => {
onEscapeKeyDown = vi.fn()
ownerDocument = globalThis.document
})

it('should call onEscapeKeyDown when the escape key is pressed', () => {
onEscapeKeyDown = vi.fn()
ownerDocument = globalThis.document

useEscapeKeydown(onEscapeKeyDown, ownerDocument)

const escapeKeyEvent = new KeyboardEvent('keydown', { key: 'Escape' })
ownerDocument.dispatchEvent(escapeKeyEvent)

expect(onEscapeKeyDown).toHaveBeenCalledTimes(1)
expect(onEscapeKeyDown).toHaveBeenCalledWith(escapeKeyEvent)
})

it('should not call onEscapeKeyDown for other key presses', () => {
useEscapeKeydown(onEscapeKeyDown, ownerDocument)

const otherKeyEvent = new KeyboardEvent('keydown', { key: 'Enter' })
ownerDocument.dispatchEvent(otherKeyEvent)

expect(onEscapeKeyDown).not.toHaveBeenCalled()
})
})
23 changes: 23 additions & 0 deletions packages/core/use-composable/src/useEscapeKeydown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { watchEffect } from 'vue'
import { useCallbackRef } from './useCallbackRef'

/**
* Listens for when the escape key is down
*/
function useEscapeKeydown(
onEscapeKeyDownProp?: (event: KeyboardEvent) => void,
ownerDocument: Document = globalThis?.document,
) {
const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp)

watchEffect((onInvalidate) => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape')
onEscapeKeyDown(event)
}
ownerDocument.addEventListener('keydown', handleKeyDown)
onInvalidate(() => ownerDocument.removeEventListener('keydown', handleKeyDown))
})
}

export { useEscapeKeydown }

0 comments on commit b971406

Please sign in to comment.