Skip to content

Commit

Permalink
Merge pull request #126 from github/cbodfield/localized-mod-ssr
Browse files Browse the repository at this point in the history
Make localizeMod SSR safe
  • Loading branch information
dgreif authored May 6, 2024
2 parents a2e0df9 + d7504ac commit 63d60c5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/hotkey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const modifierKeyNames: string[] = ['Control', 'Alt', 'Meta', 'Shift']
* platforms.
* - Ensures modifiers are sorted in a consistent order
* @param hotkey a hotkey string
* @param platform NOTE: this param is only intended to be used to mock `navigator.platform` in tests
* @param platform NOTE: this param is only intended to be used to mock `navigator.platform` in tests. `window.navigator.platform` is used by default.
* @returns {string} normalized representation of the given hotkey string
*/
export function normalizeHotkey(hotkey: string, platform?: string | undefined): NormalizedHotkeyString {
Expand All @@ -88,8 +88,11 @@ export function normalizeHotkey(hotkey: string, platform?: string | undefined):

const matchApplePlatform = /Mac|iPod|iPhone|iPad/i

function localizeMod(hotkey: string, platform: string = navigator.platform): string {
const localModifier = matchApplePlatform.test(platform) ? 'Meta' : 'Control'
function localizeMod(hotkey: string, platform?: string | undefined): string {
const ssrSafeWindow = typeof window === 'undefined' ? undefined : window
const safePlatform = platform ?? ssrSafeWindow?.navigator.platform ?? ''

const localModifier = matchApplePlatform.test(safePlatform) ? 'Meta' : 'Control'
return hotkey.replace('Mod', localModifier)
}

Expand Down
2 changes: 2 additions & 0 deletions test/test-normalize-hotkey.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ describe('normalizeHotkey', () => {
['Mod+)', 'Meta+)', 'mac'], // TODO: on a mac upper-case keys are lowercased when Meta is pressed
['Mod+Alt+a', 'Control+Alt+a', 'win / linux'],
['Mod+Alt+a', 'Alt+Meta+a', 'mac'],
// undefined platform doesn't localize and falls back to windows (SSR)
['Mod+a', 'Control+a', undefined],
// Modifier sorting
['Shift+Alt+Meta+Control+m', 'Control+Alt+Meta+Shift+m'],
['Shift+Alt+Mod+m', 'Control+Alt+Shift+m', 'win']
Expand Down

0 comments on commit 63d60c5

Please sign in to comment.