Skip to content

Commit

Permalink
Correctly handle special char keyCodes with Shift
Browse files Browse the repository at this point in the history
Previously, calling `triggerKeyEvent()` with `shiftKey: true` option would trigger an event with an incorrect `key`.

E.g. `triggerKeyEvent(element, 'keydown', 197, { shiftKey: true })` would have a `=` key, instead of `+`.

(cherry picked from commit 5d3f579)
  • Loading branch information
CvX authored and chriskrycho committed Dec 15, 2022
1 parent 64f40d5 commit d537923
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
32 changes: 28 additions & 4 deletions addon-test-support/@ember/test-helpers/dom/trigger-key-event.ts
Expand Up @@ -100,6 +100,29 @@ const keyFromKeyCode: { [key: number]: string } = {
222: "'",
};

const keyFromKeyCodeWithShift: { [key: number]: string } = {
48: ')',
49: '!',
50: '@',
51: '#',
52: '$',
53: '%',
54: '^',
55: '&',
56: '*',
57: '(',
186: ':',
187: '+',
188: '<',
189: '_',
190: '>',
191: '?',
219: '{',
220: '|',
221: '}',
222: '"',
};

/**
Calculates the value of KeyboardEvent#key given a keycode and the modifiers.
Note that this works if the key is pressed in combination with the shift key, but it cannot
Expand All @@ -119,10 +142,11 @@ function keyFromKeyCodeAndModifiers(
return String.fromCharCode(keycode).toLocaleLowerCase();
}
}
let key = keyFromKeyCode[keycode];
if (key) {
return key;
}

return (
(modifiers.shiftKey && keyFromKeyCodeWithShift[keycode]) ||
keyFromKeyCode[keycode]
);
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/dom/trigger-key-event-test.js
Expand Up @@ -241,6 +241,12 @@ module('DOM Helper: triggerKeyEvent', function (hooks) {
await checkKey(90, 'z');
await checkKey(65, 'A', { shiftKey: true });
await checkKey(90, 'Z', { shiftKey: true });
await checkKey(49, '!', { shiftKey: true });
await checkKey(187, '+', { shiftKey: true });
await checkKey(38, 'ArrowUp', { shiftKey: true });

// an invalid keyCode
await checkKey(999, '');
});

test('The value of the `event.keyCode` is properly inferred from the given key', async function (assert) {
Expand Down

0 comments on commit d537923

Please sign in to comment.