Skip to content

Commit 63d60c5

Browse files
authored
Merge pull request #126 from github/cbodfield/localized-mod-ssr
Make localizeMod SSR safe
2 parents a2e0df9 + d7504ac commit 63d60c5

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/hotkey.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ const modifierKeyNames: string[] = ['Control', 'Alt', 'Meta', 'Shift']
7676
* platforms.
7777
* - Ensures modifiers are sorted in a consistent order
7878
* @param hotkey a hotkey string
79-
* @param platform NOTE: this param is only intended to be used to mock `navigator.platform` in tests
79+
* @param platform NOTE: this param is only intended to be used to mock `navigator.platform` in tests. `window.navigator.platform` is used by default.
8080
* @returns {string} normalized representation of the given hotkey string
8181
*/
8282
export function normalizeHotkey(hotkey: string, platform?: string | undefined): NormalizedHotkeyString {
@@ -88,8 +88,11 @@ export function normalizeHotkey(hotkey: string, platform?: string | undefined):
8888

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

91-
function localizeMod(hotkey: string, platform: string = navigator.platform): string {
92-
const localModifier = matchApplePlatform.test(platform) ? 'Meta' : 'Control'
91+
function localizeMod(hotkey: string, platform?: string | undefined): string {
92+
const ssrSafeWindow = typeof window === 'undefined' ? undefined : window
93+
const safePlatform = platform ?? ssrSafeWindow?.navigator.platform ?? ''
94+
95+
const localModifier = matchApplePlatform.test(safePlatform) ? 'Meta' : 'Control'
9396
return hotkey.replace('Mod', localModifier)
9497
}
9598

test/test-normalize-hotkey.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ describe('normalizeHotkey', () => {
2525
['Mod+)', 'Meta+)', 'mac'], // TODO: on a mac upper-case keys are lowercased when Meta is pressed
2626
['Mod+Alt+a', 'Control+Alt+a', 'win / linux'],
2727
['Mod+Alt+a', 'Alt+Meta+a', 'mac'],
28+
// undefined platform doesn't localize and falls back to windows (SSR)
29+
['Mod+a', 'Control+a', undefined],
2830
// Modifier sorting
2931
['Shift+Alt+Meta+Control+m', 'Control+Alt+Meta+Shift+m'],
3032
['Shift+Alt+Mod+m', 'Control+Alt+Shift+m', 'win']

0 commit comments

Comments
 (0)