Skip to content

Commit

Permalink
Add focusInInput check to key_events handle
Browse files Browse the repository at this point in the history
Closes #60
  • Loading branch information
Kent C. Dodds committed Dec 4, 2016
1 parent 348ad8b commit f9781aa
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/libs/key_events.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,22 @@ export function isModifierPressed(e) {
return (e.ctrlKey || e.keyCode === 91 || e.metaKey) && e.shiftKey;
}

function focusInInput(e) {
return /input|textarea/i.test(e.target.tagName) ||
e.target.getAttribute('contenteditable') !== null;
}

export default function handle(e) {
if (e.keyCode === keycode('escape')) {
// We don't need to preventDefault escape.
// Just getting the event is enough for us.
return features.ESCAPE;
}
if (focusInInput(e)) {
// if we're focused in an element that accepts input,
// then we shouldn't perform a shortcut action
return false;
}

if (!isModifierPressed(e)) return false;

Expand Down
60 changes: 60 additions & 0 deletions src/modules/ui/configs/__tests__/handle_keyevents.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,71 @@ describe('manager.ui.config.handle_keyevents', () => {
shiftKey: true,
keyCode: keycode('F'),
preventDefault() {},
target: {
tagName: 'DIV',
getAttribute() { return null; },
},
};

window.onkeydown(e);

window.onkeydown = originalOnkeydown;
expect(actions.shortcuts.handleEvent.callCount).to.be.equal(1);
});

it('should not call any actions if the event target is an input', () => {
const actions = {
shortcuts: {
handleEvent: sinon.mock(),
},
};

const originalOnkeydown = window.onkeydown;
handleKeyEvents(actions);

const e = {
ctrlKey: true,
shiftKey: true,
keyCode: keycode('F'),
preventDefault() {},
target: {
tagName: 'INPUT',
getAttribute() { return null; },
},
};

window.onkeydown(e);

window.onkeydown = originalOnkeydown;
expect(actions.shortcuts.handleEvent.callCount).to.be.equal(0);
});

it('should not call any actions if the event target has contenteditable enabled', () => {
const actions = {
shortcuts: {
handleEvent: sinon.mock(),
},
};

const originalOnkeydown = window.onkeydown;
handleKeyEvents(actions);

const e = {
ctrlKey: true,
shiftKey: true,
keyCode: keycode('F'),
preventDefault() {},
target: {
tagName: 'DIV',
getAttribute(attr) {
return /contenteditable/i.test(attr) ? '' : null;
},
},
};

window.onkeydown(e);

window.onkeydown = originalOnkeydown;
expect(actions.shortcuts.handleEvent.callCount).to.be.equal(0);
});
});

0 comments on commit f9781aa

Please sign in to comment.