diff --git a/src/index.ts b/src/index.ts
index aa1abec..6fa3e0e 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -52,8 +52,7 @@ function keyDownHandler(event: KeyboardEvent) {
}
if (elementToFire && shouldFire) {
- fireDeterminedAction(elementToFire, sequenceTracker.path)
- event.preventDefault()
+ if (fireDeterminedAction(elementToFire, sequenceTracker.path)) event.preventDefault()
}
sequenceTracker.reset()
diff --git a/src/utils.ts b/src/utils.ts
index d0aab12..5a96a38 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -21,15 +21,17 @@ export function isFormField(element: Node): boolean {
)
}
-export function fireDeterminedAction(el: HTMLElement, path: readonly NormalizedHotkeyString[]): void {
+export function fireDeterminedAction(el: HTMLElement, path: readonly NormalizedHotkeyString[]): boolean {
const delegateEvent = new CustomEvent('hotkey-fire', {cancelable: true, detail: {path}})
const cancelled = !el.dispatchEvent(delegateEvent)
- if (cancelled) return
+ if (cancelled) return false
+
if (isFormField(el)) {
el.focus()
} else {
el.click()
}
+ return true
}
export function expandHotkeyToEdges(hotkey: string): NormalizedHotkeyString[][] {
diff --git a/test/test.js b/test/test.js
index 5119ded..753e0ed 100644
--- a/test/test.js
+++ b/test/test.js
@@ -46,8 +46,10 @@ describe('hotkey', function () {
describe('single key support', function () {
it('triggers buttons that have a `data-hotkey` attribute', function () {
setHTML('')
- document.dispatchEvent(new KeyboardEvent('keydown', {key: 'b'}))
+ const event = new KeyboardEvent('keydown', {cancelable: true, key: 'b'})
+ document.dispatchEvent(event)
assert.include(elementsActivated, 'button1')
+ assert.ok(event.defaultPrevented, 'should call preventDefault on keydown event')
})
it('triggers buttons that get hotkey passed in as second argument', function () {
@@ -118,8 +120,10 @@ describe('hotkey', function () {
it('wont trigger action if the hotkey-fire event is cancelled', function () {
setHTML('')
document.querySelector('#button1').addEventListener('hotkey-fire', event => event.preventDefault())
- document.dispatchEvent(new KeyboardEvent('keydown', {shiftKey: true, code: 'KeyB', key: 'B'}))
+ const event = new KeyboardEvent('keydown', {cancelable: true, shiftKey: true, code: 'KeyB', key: 'B'})
+ document.dispatchEvent(event)
assert.notInclude(elementsActivated, 'button1')
+ assert.equal(event.defaultPrevented, false, 'should not prevent the keydown event when cancelled')
})
it('supports comma as a hotkey', function () {