fix: display correct keys for international keyboards

Updates the ShortcutsModal to dynamically display the correct physical keys for users with non-US keyboard layouts.

The `ShortcutItem` component now uses `navigator.keyboard.getLayoutMap()` to resolve `KeyboardEvent.code` values (e.g., "Slash") to the character they produce on the user's active keyboard layout (e.g., "-").

This ensures the displayed shortcuts match the keys the user needs to press. A fallback is included for older browsers that do not support this API.
This commit is contained in:
silentoplayz 2025-10-23 05:40:31 -04:00
parent 6eecade06e
commit 02a2683eb0

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { getContext } from 'svelte'; import { getContext, onMount } from 'svelte';
import Tooltip from '../common/Tooltip.svelte'; import Tooltip from '../common/Tooltip.svelte';
import type { Shortcut } from '$lib/shortcuts'; import type { Shortcut } from '$lib/shortcuts';
@ -7,17 +7,39 @@
export let isMac: boolean; export let isMac: boolean;
const i18n = getContext('i18n'); const i18n = getContext('i18n');
let keyboardLayoutMap: Map<string, string> | undefined;
onMount(async () => {
if (navigator.keyboard && 'getLayoutMap' in navigator.keyboard) {
try {
keyboardLayoutMap = await navigator.keyboard.getLayoutMap();
} catch (error) {
console.error('Failed to get keyboard layout map:', error);
}
}
});
function formatKey(key: string): string { function formatKey(key: string): string {
const lowerKey = key.toLowerCase(); // First, handle special modifier keys which are defined in lowercase
switch (key) {
switch (lowerKey) {
case 'mod': case 'mod':
return isMac ? '⌘' : 'Ctrl'; return isMac ? '⌘' : 'Ctrl';
case 'shift': case 'shift':
return isMac ? '⇧' : 'Shift'; return isMac ? '⇧' : 'Shift';
case 'alt': case 'alt':
return isMac ? '⌥' : 'Alt'; return isMac ? '⌥' : 'Alt';
}
// Next, try to use the layout map with the raw KeyboardEvent.code (e.g., "Slash")
if (keyboardLayoutMap && keyboardLayoutMap.has(key)) {
const mappedKey = keyboardLayoutMap.get(key) ?? key;
// For single characters, make them uppercase. For others (like 'CapsLock'), leave as is.
return mappedKey.length === 1 ? mappedKey.toUpperCase() : mappedKey;
}
// Finally, provide a fallback for browsers without getLayoutMap or for keys not in the map
const lowerKey = key.toLowerCase();
switch (lowerKey) {
case 'backspace': case 'backspace':
case 'delete': case 'delete':
return isMac ? '⌫' : 'Delete'; return isMac ? '⌫' : 'Delete';
@ -40,8 +62,11 @@
case 'semicolon': case 'semicolon':
return ';'; return ';';
default: default:
if (lowerKey.startsWith('key')) return key.slice(-1); // For 'KeyA', 'Digit1', etc., extract the last character.
if (lowerKey.startsWith('digit')) return key.slice(-1); if (lowerKey.startsWith('key') || lowerKey.startsWith('digit')) {
return key.slice(-1).toUpperCase();
}
// For anything else, just uppercase it.
return key.toUpperCase(); return key.toUpperCase();
} }
} }