Skip to content

Commit

Permalink
A utility function to map event codes to an english string of English…
Browse files Browse the repository at this point in the history
…StringToCodeMap
  • Loading branch information
jessegreenberg committed Dec 22, 2023
1 parent 7908d37 commit 3bbb4c9
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion js/listeners/KeyboardListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@

import CallbackTimer from '../../../axon/js/CallbackTimer.js';
import optionize from '../../../phet-core/js/optionize.js';
import { EnglishStringToCodeMap, FocusManager, globalKeyStateTracker, scenery, SceneryEvent, TInputListener } from '../imports.js';
import { EnglishKey, EnglishStringToCodeMap, FocusManager, globalKeyStateTracker, scenery, SceneryEvent, TInputListener } from '../imports.js';
import KeyboardUtils from '../accessibility/KeyboardUtils.js';

// NOTE: The typing for ModifierKey and OneKeyStroke is limited TypeScript, there is a limitation to the number of
Expand Down Expand Up @@ -552,6 +552,29 @@ class KeyboardListener<Keys extends readonly OneKeyStroke[]> implements TInputLi

return keyGroups;
}

/**
* Returns the first EnglishStringToCodeMap that corresponds to the provided event.code. Null if no match is found.
* Useful when matching an english string used by KeyboardListener to the event code from a
* SceneryEvent.domEvent.code.
*
* For example:
*
* KeyboardUtils.eventCodeToEnglishString( 'KeyA' ) === 'a'
* KeyboardUtils.eventCodeToEnglishString( 'Numpad0' ) === '0'
* KeyboardUtils.eventCodeToEnglishString( 'Digit0' ) === '0'
*
* NOTE: This cannot be in KeyboardUtils because it would create a circular dependency.
*/
public static eventCodeToEnglishString( eventCode: string ): EnglishKey | null {
for ( const key in EnglishStringToCodeMap ) {
if ( EnglishStringToCodeMap.hasOwnProperty( key ) &&
( EnglishStringToCodeMap[ key as EnglishKey ] ).includes( eventCode ) ) {
return key as EnglishKey;
}
}
return null;
}
}

scenery.register( 'KeyboardListener', KeyboardListener );
Expand Down

0 comments on commit 3bbb4c9

Please sign in to comment.