Skip to content

Commit d537923

Browse files
CvXchriskrycho
authored andcommittedDec 15, 2022
Correctly handle special char keyCodes with Shift
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)
1 parent 64f40d5 commit d537923

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed
 

‎addon-test-support/@ember/test-helpers/dom/trigger-key-event.ts

+28-4
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,29 @@ const keyFromKeyCode: { [key: number]: string } = {
100100
222: "'",
101101
};
102102

103+
const keyFromKeyCodeWithShift: { [key: number]: string } = {
104+
48: ')',
105+
49: '!',
106+
50: '@',
107+
51: '#',
108+
52: '$',
109+
53: '%',
110+
54: '^',
111+
55: '&',
112+
56: '*',
113+
57: '(',
114+
186: ':',
115+
187: '+',
116+
188: '<',
117+
189: '_',
118+
190: '>',
119+
191: '?',
120+
219: '{',
121+
220: '|',
122+
221: '}',
123+
222: '"',
124+
};
125+
103126
/**
104127
Calculates the value of KeyboardEvent#key given a keycode and the modifiers.
105128
Note that this works if the key is pressed in combination with the shift key, but it cannot
@@ -119,10 +142,11 @@ function keyFromKeyCodeAndModifiers(
119142
return String.fromCharCode(keycode).toLocaleLowerCase();
120143
}
121144
}
122-
let key = keyFromKeyCode[keycode];
123-
if (key) {
124-
return key;
125-
}
145+
146+
return (
147+
(modifiers.shiftKey && keyFromKeyCodeWithShift[keycode]) ||
148+
keyFromKeyCode[keycode]
149+
);
126150
}
127151

128152
/**

‎tests/unit/dom/trigger-key-event-test.js

+6
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,12 @@ module('DOM Helper: triggerKeyEvent', function (hooks) {
241241
await checkKey(90, 'z');
242242
await checkKey(65, 'A', { shiftKey: true });
243243
await checkKey(90, 'Z', { shiftKey: true });
244+
await checkKey(49, '!', { shiftKey: true });
245+
await checkKey(187, '+', { shiftKey: true });
246+
await checkKey(38, 'ArrowUp', { shiftKey: true });
247+
248+
// an invalid keyCode
249+
await checkKey(999, '');
244250
});
245251

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

0 commit comments

Comments
 (0)
Please sign in to comment.