Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make localizeMod SSR safe #126

Merged
merged 10 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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