Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ function keyDownHandler(event: KeyboardEvent) {
if (isFormField(event.target)) {
const target = event.target as HTMLElement
if (!target.id) return
if (!target.ownerDocument.querySelector(`[data-hotkey-scope="${target.id}"]`)) return
const hasScope =
typeof CSS !== 'undefined' && CSS.escape
? target.ownerDocument.querySelector(`[data-hotkey-scope="${CSS.escape(target.id)}"]`)
: Array.from(target.ownerDocument.querySelectorAll('[data-hotkey-scope]')).some(
element => element.getAttribute('data-hotkey-scope') === target.id
)
if (!hasScope) return
}

// If the user presses a hotkey that doesn't exist in the Trie,
Expand Down
28 changes: 28 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,34 @@ describe('hotkey', function () {
})

describe('data-hotkey-scope', function () {
it('matches scoped form fields without CSS.escape', function () {
setHTML('<button id="button1" data-hotkey="Meta+b">Button 1</button><input id="textfield" />')
const field = document.getElementById('textfield')
field.id = 'field"one'
document.getElementById('button1').setAttribute('data-hotkey-scope', field.id)
const original = CSS.escape
try {
CSS.escape = undefined
field.dispatchEvent(new KeyboardEvent('keydown', {bubbles: true, key: 'b', metaKey: true}))
expect(elementsActivated).toEqual(['button1'])
} finally {
CSS.escape = original
}
})

it.each(['field"one', 'field\\one'])('matches a scope whose ID contains CSS escapes: %s', function (id) {
setHTML(`
<button id="button1" data-hotkey-scope="textfield" data-hotkey="Meta+b">Button 1</button>
<input id="textfield" />`)
const field = document.getElementById('textfield')
field.id = id
document.getElementById('button1').setAttribute('data-hotkey-scope', id)

field.dispatchEvent(new KeyboardEvent('keydown', {bubbles: true, key: 'b', metaKey: true}))

expect(elementsActivated).toEqual(['button1'])
})

it('allows hotkey action from form field', function () {
setHTML(`
<button id="button1" data-hotkey-scope="textfield" data-hotkey="Meta+b">Button 1</button>
Expand Down