Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
feat(desktop): settings phase 3a - keyboard layout strategy (#6289)
Shreyase04ef445c4ba
diff --git a/packages/hoppscotch-common/locales/en.json b/packages/hoppscotch-common/locales/en.jsonindex 2a73e6e47..e44b6607c 100644--- a/packages/hoppscotch-common/locales/en.json+++ b/packages/hoppscotch-common/locales/en.json@@ -1289,7 +1289,16 @@"delete_account": "Delete account","delete_account_description": "Once you delete your account, all your data will be permanently deleted. This action cannot be undone.","desktop": "Desktop",- "desktop_description": "Preferences that apply only to the Hoppscotch desktop app.",+ "desktop_description": "Update behavior and keyboard handling for the Hoppscotch desktop app.",+ "desktop_keyboard": "Keyboard",+ "desktop_keyboard_strategy_label": "Match shortcuts by typed letter or physical position",+ "desktop_keyboard_strategy_description": "On non-QWERTY layouts, the same letter can come from different physical keys. The default works for most layouts; switch options if shortcuts don't fire as expected on yours.",+ "desktop_keyboard_strategy_hybrid": "Smart (recommended)",+ "desktop_keyboard_strategy_hybrid_description": "Use the typed letter for Latin characters; fall back to the physical key position for non-Latin layouts (Cyrillic, CJK).",+ "desktop_keyboard_strategy_key": "Typed letter",+ "desktop_keyboard_strategy_key_description": "Always use the typed letter. Pick this if shortcuts don't work as expected on your layout.",+ "desktop_keyboard_strategy_code": "Physical key position",+ "desktop_keyboard_strategy_code_description": "Always use the US-QWERTY physical position. Pick this if you have QWERTY muscle memory on a non-Latin layout.","desktop_updates": "Updates","disable_encode_mode_tooltip": "Never encode the parameters in the request","disable_update_checks": "Disable automatic update checks",diff --git a/packages/hoppscotch-common/src/components.d.ts b/packages/hoppscotch-common/src/components.d.tsindex 5cf1795bf..357e22406 100644--- a/packages/hoppscotch-common/src/components.d.ts+++ b/packages/hoppscotch-common/src/components.d.ts@@ -201,6 +201,7 @@ declare module 'vue' {HttpExampleResponseTab: typeof import('./components/http/example/ResponseTab.vue')['default']HttpHeaders: typeof import('./components/http/Headers.vue')['default']HttpImportCurl: typeof import('./components/http/ImportCurl.vue')['default']+ HttpInheritedScriptsModal: typeof import('./components/http/InheritedScriptsModal.vue')['default']HttpKeyValue: typeof import('./components/http/KeyValue.vue')['default']HttpParameters: typeof import('./components/http/Parameters.vue')['default']HttpPreRequestScript: typeof import('./components/http/PreRequestScript.vue')['default']@@ -245,7 +246,6 @@ declare module 'vue' {IconLucideChevronRight: typeof import('~icons/lucide/chevron-right')['default']IconLucideCircleCheck: typeof import('~icons/lucide/circle-check')['default']IconLucideFileQuestion: typeof import('~icons/lucide/file-question')['default']- IconLucideFileSymlink: typeof import('~icons/lucide/file-symlink')['default']IconLucideFileText: typeof import('~icons/lucide/file-text')['default']IconLucideFileX: typeof import('~icons/lucide/file-x')['default']IconLucideFolder: typeof import('~icons/lucide/folder')['default']@@ -257,7 +257,6 @@ declare module 'vue' {IconLucideLayers: typeof import('~icons/lucide/layers')['default']IconLucideListEnd: typeof import('~icons/lucide/list-end')['default']IconLucideLoader2: typeof import('~icons/lucide/loader2')['default']- IconLucideLock: typeof import('~icons/lucide/lock')['default']IconLucideMinus: typeof import('~icons/lucide/minus')['default']IconLucidePlusCircle: typeof import('~icons/lucide/plus-circle')['default']IconLucideRefreshCw: typeof import('~icons/lucide/refresh-cw')['default']diff --git a/packages/hoppscotch-common/src/components/settings/Desktop.vue b/packages/hoppscotch-common/src/components/settings/Desktop.vueindex 659dae2f9..a7384e0b4 100644--- a/packages/hoppscotch-common/src/components/settings/Desktop.vue+++ b/packages/hoppscotch-common/src/components/settings/Desktop.vue@@ -71,14 +71,58 @@</p></div></section>++ <!-- Keyboard layout strategy. Three radios, each with a one-line+ description so the user can pick without trial and error.+ Selection writes to `keyboardLayoutStrategy` through the+ desktop settings composable, which mirrors it into the+ keyboard-strategy holder so the next keypress respects the+ change. -->+ <section>+ <h4 class="font-semibold text-secondaryDark">+ {{ t("settings.desktop_keyboard") }}+ </h4>++ <div class="mt-4">+ <p class="text-secondaryLight">+ {{ t("settings.desktop_keyboard_strategy_label") }}+ </p>+ <p class="mt-1 text-xs text-secondaryLight">+ {{ t("settings.desktop_keyboard_strategy_description") }}+ </p>++ <div class="mt-4 space-y-4">+ <div v-for="option in keyboardStrategyOptions" :key="option.value">+ <HoppSmartRadio+ :value="option.value"+ :label="option.label"+ :selected="+ desktopSettings.settings.keyboardLayoutStrategy ===+ option.value+ "+ class="!px-0 hover:bg-transparent"+ @change="setKeyboardStrategy(option.value)"+ />+ <p class="ml-8 mt-1 text-xs text-secondaryLight">+ {{ option.description }}+ </p>+ </div>+ </div>+ </div>+ </section></div></div></template><script setup lang="ts">import { computed, onBeforeUnmount, ref, watch, type Component } from "vue"-import { HoppButtonSecondary, HoppSmartToggle } from "@hoppscotch/ui"+import {+ HoppButtonSecondary,+ HoppSmartRadio,+ HoppSmartToggle,+} from "@hoppscotch/ui"import { useI18n } from "~/composables/i18n"+import type { DesktopSettings } from "~/platform/desktop-settings"import IconLucideDownload from "~icons/lucide/download"import IconLucideRefreshCw from "~icons/lucide/refresh-cw"@@ -268,6 +312,36 @@ async function toggleDisableUpdateChecks(): Promise<void> {!desktopSettings.settings.disableUpdateChecks)}++// Keyboard layout strategy radios. Order is recommended-first so users+// without a preference get the smart default. Labels and descriptions+// are i18n keys, rebuilt as a `computed` so a locale change updates+// the rendered text.+type KeyboardStrategy = DesktopSettings["keyboardLayoutStrategy"]++const keyboardStrategyOptions = computed<+ Array<{ value: KeyboardStrategy; label: string; description: string }>+>(() => [+ {+ value: "hybrid",+ label: t("settings.desktop_keyboard_strategy_hybrid"),+ description: t("settings.desktop_keyboard_strategy_hybrid_description"),+ },+ {+ value: "key",+ label: t("settings.desktop_keyboard_strategy_key"),+ description: t("settings.desktop_keyboard_strategy_key_description"),+ },+ {+ value: "code",+ label: t("settings.desktop_keyboard_strategy_code"),+ description: t("settings.desktop_keyboard_strategy_code_description"),+ },+])++async function setKeyboardStrategy(value: KeyboardStrategy): Promise<void> {+ await desktopSettings.update("keyboardLayoutStrategy", value)+}</script><style scoped>diff --git a/packages/hoppscotch-common/src/composables/desktop-settings.ts b/packages/hoppscotch-common/src/composables/desktop-settings.tsindex c8f66f8bf..6baa1db22 100644--- a/packages/hoppscotch-common/src/composables/desktop-settings.ts+++ b/packages/hoppscotch-common/src/composables/desktop-settings.ts@@ -16,6 +16,7 @@ import {parseDesktopSettings,type DesktopSettings,} from "~/platform/desktop-settings"+import { setKeyboardLayoutStrategy } from "~/helpers/keyboard-strategy"import { Log } from "~/kernel/log"const LOG_TAG = "useDesktopSettings"@@ -74,6 +75,7 @@ async function loadInitial(): Promise<void> {)const raw = E.isRight(result) ? result.right : undefinedObject.assign(settings, parseDesktopSettings(raw))+ setKeyboardLayoutStrategy(settings.keyboardLayoutStrategy)loaded.value = true// Subscribe to external writes (for example the Tauri shell's portable@@ -88,6 +90,7 @@ async function loadInitial(): Promise<void> {emitter.on("change", ({ value }: { value?: unknown }) => {if (value !== undefined) {Object.assign(settings, parseDesktopSettings(value))+ setKeyboardLayoutStrategy(settings.keyboardLayoutStrategy)}})} catch (err) {@@ -161,6 +164,15 @@ export function useDesktopSettings(): {const previous = settings[key]settings[key] = value+ // Mirror the change into the keyboard-strategy holder eagerly so the+ // next keypress respects the new strategy without waiting for the+ // store-watch callback to round-trip. The watch fires later with the+ // same value, and the redundant write is cheap.+ if (key === "keyboardLayoutStrategy") {+ setKeyboardLayoutStrategy(+ value as DesktopSettings["keyboardLayoutStrategy"]+ )+ }try {await persist()} catch (err) {@@ -168,6 +180,11 @@ export function useDesktopSettings(): {// actually in the store. Without this, a failed persist leaves the// settings object holding a value the next app start will not find.settings[key] = previous+ if (key === "keyboardLayoutStrategy") {+ setKeyboardLayoutStrategy(+ previous as DesktopSettings["keyboardLayoutStrategy"]+ )+ }throw err}}diff --git a/packages/hoppscotch-common/src/helpers/__tests__/keybindings.spec.ts b/packages/hoppscotch-common/src/helpers/__tests__/keybindings.spec.tsnew file mode 100644index 000000000..7b02e4bfd--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/__tests__/keybindings.spec.ts@@ -0,0 +1,198 @@+import { describe, expect, test } from "vitest"+import { resolvePressedKey } from "../keybindings"++// Fixture builder to keep individual cases readable. Layout name in the+// describe block is the conceptual layout; `key` and `code` are what the+// browser actually emits when the user presses a given physical key on+// that layout.+const ev = (key: string, code: string) => ({ key, code })++describe("resolvePressedKey: letter dispatch", () => {+ describe("strategy: 'key' (typed letter)", () => {+ test("US-QWERTY Q resolves to q", () => {+ expect(resolvePressedKey(ev("q", "KeyQ"), "key")).toBe("q")+ })++ test("AZERTY 'A' keycap (physical Q position) resolves to a", () => {+ // On AZERTY the physical KeyQ position types "a"; the user pressing+ // the keycap labelled A expects Ctrl+A behaviour.+ expect(resolvePressedKey(ev("a", "KeyQ"), "key")).toBe("a")+ })++ test("QWERTZ 'Z' keycap (physical Y position) resolves to z", () => {+ expect(resolvePressedKey(ev("z", "KeyY"), "key")).toBe("z")+ })++ test("Cyrillic Q (typed 'й') falls through to non-letter handling", () => {+ // 'й' is not a-z so the letter branch returns null and the rest+ // of the resolver doesn't recognise it either.+ expect(resolvePressedKey(ev("й", "KeyQ"), "key")).toBeNull()+ })++ test("Mac Option+Q (typed 'œ') falls through", () => {+ expect(resolvePressedKey(ev("œ", "KeyQ"), "key")).toBeNull()+ })+ })++ describe("strategy: 'code' (physical position)", () => {+ test("US-QWERTY Q resolves to q", () => {+ expect(resolvePressedKey(ev("q", "KeyQ"), "code")).toBe("q")+ })++ test("AZERTY 'A' keycap (physical Q position) resolves to q", () => {+ // Pure physical strategy; whatever the user typed is ignored.+ expect(resolvePressedKey(ev("a", "KeyQ"), "code")).toBe("q")+ })++ test("Cyrillic physical Q (typed 'й') resolves to q", () => {+ expect(resolvePressedKey(ev("й", "KeyQ"), "code")).toBe("q")+ })++ test("Mac Option+Q (typed 'œ') resolves to q", () => {+ expect(resolvePressedKey(ev("œ", "KeyQ"), "code")).toBe("q")+ })+ })++ describe("strategy: 'hybrid' (key first, code fallback)", () => {+ test("US-QWERTY Q resolves to q", () => {+ expect(resolvePressedKey(ev("q", "KeyQ"), "hybrid")).toBe("q")+ })++ test("AZERTY 'A' keycap (physical Q position) resolves to a", () => {+ // Latin glyph available, so use it.+ expect(resolvePressedKey(ev("a", "KeyQ"), "hybrid")).toBe("a")+ })++ test("Cyrillic physical Q (typed 'й') falls back to code → q", () => {+ // Non-Latin glyph, fall back to physical position.+ expect(resolvePressedKey(ev("й", "KeyQ"), "hybrid")).toBe("q")+ })++ test("Mac Option+Q (typed 'œ') falls back to code → q", () => {+ // 'œ' is not in [a-z] so hybrid falls through to code.+ expect(resolvePressedKey(ev("œ", "KeyQ"), "hybrid")).toBe("q")+ })++ test("Dvorak 'Q' keycap typing 'q' resolves to q", () => {+ // Dvorak users with Dvorak software remapping see the typed+ // letter match the keycap; hybrid uses event.key directly.+ expect(resolvePressedKey(ev("q", "KeyX"), "hybrid")).toBe("q")+ })+ })+})++describe("resolvePressedKey: digit dispatch", () => {+ test("'key' uses event.key for digits", () => {+ expect(resolvePressedKey(ev("1", "Digit1"), "key")).toBe("1")+ })++ test("'code' uses event.code for digits", () => {+ expect(resolvePressedKey(ev("1", "Digit1"), "code")).toBe("1")+ })++ test("AZERTY digit row (typed '&', code Digit1) resolves to 1 under hybrid", () => {+ expect(resolvePressedKey(ev("&", "Digit1"), "hybrid")).toBe("1")+ })++ test("AZERTY digit row resolves to 1 under code", () => {+ expect(resolvePressedKey(ev("&", "Digit1"), "code")).toBe("1")+ })++ test("AZERTY digit row falls through under key (no Latin digit typed)", () => {+ expect(resolvePressedKey(ev("&", "Digit1"), "key")).toBeNull()+ })+})++describe("resolvePressedKey: layout-stable keys", () => {+ // These keys produce the same event.key regardless of layout, so+ // every strategy resolves them identically.+ const strategies = ["key", "code", "hybrid"] as const++ for (const strategy of strategies) {+ describe(`strategy: '${strategy}'`, () => {+ test("ArrowUp resolves to up", () => {+ expect(resolvePressedKey(ev("ArrowUp", "ArrowUp"), strategy)).toBe("up")+ })++ test("Tab resolves to tab", () => {+ expect(resolvePressedKey(ev("Tab", "Tab"), strategy)).toBe("tab")+ })++ test("Enter resolves to enter", () => {+ expect(resolvePressedKey(ev("Enter", "Enter"), strategy)).toBe("enter")+ })++ test("Shift+/ (typed '?') maps to /", () => {+ expect(resolvePressedKey(ev("?", "Slash"), strategy)).toBe("/")+ })++ test("[ resolves to [", () => {+ expect(resolvePressedKey(ev("[", "BracketLeft"), strategy)).toBe("[")+ })++ test("Cyrillic physical [ key (typed 'х') falls back to [", () => {+ // On Russian Cyrillic the physical KeyBracketLeft position+ // types "х"; the resolver falls back to the bracket code so+ // the shortcut still fires.+ expect(resolvePressedKey(ev("х", "BracketLeft"), strategy)).toBe("[")+ })++ test("Cyrillic physical ] key (typed 'ъ') falls back to ]", () => {+ expect(resolvePressedKey(ev("ъ", "BracketRight"), strategy)).toBe("]")+ })+ })+ }+})++describe("resolvePressedKey: synthetic-event fallback", () => {+ // Synthetic events (programmatic dispatch, certain older environments)+ // can arrive without `event.code` set. The resolver falls back to+ // `event.key` for ASCII letters under every strategy so the shortcut+ // still resolves rather than being silently dropped.+ test("'code' strategy falls back to event.key when code is empty", () => {+ expect(resolvePressedKey(ev("a", ""), "code")).toBe("a")+ })++ test("'key' strategy resolves Latin letter without needing code", () => {+ expect(resolvePressedKey(ev("a", ""), "key")).toBe("a")+ })++ test("'hybrid' strategy resolves Latin letter without needing code", () => {+ expect(resolvePressedKey(ev("a", ""), "hybrid")).toBe("a")+ })+})++describe("resolvePressedKey: edge cases", () => {+ test("empty event returns null", () => {+ expect(resolvePressedKey(ev("", ""), "hybrid")).toBeNull()+ })++ test("uppercase letter is normalised to lowercase under 'key'", () => {+ expect(resolvePressedKey(ev("Q", "KeyQ"), "key")).toBe("q")+ })++ test("numpad branch resolves under 'code' strategy when NumLock is on", () => {+ // The digit branch normally picks up key="1" before the numpad+ // branch sees the event. Strategy "code" suppresses that path+ // (event.code "Numpad1" isn't "Digit1"), so resolution falls to+ // the numpad branch, which gates on NumLock.+ expect(+ resolvePressedKey(+ { key: "1", code: "Numpad1", getModifierState: () => true },+ "code"+ )+ ).toBe("1")+ })++ test("numpad digit returns null without NumLock when key is navigational", () => {+ // Without NumLock, browsers send the navigation function ("End"+ // for Numpad1) in event.key, so neither the digit nor the numpad+ // branch can resolve.+ expect(+ resolvePressedKey(+ { key: "End", code: "Numpad1", getModifierState: () => false },+ "hybrid"+ )+ ).toBeNull()+ })+})diff --git a/packages/hoppscotch-common/src/helpers/keybindings.ts b/packages/hoppscotch-common/src/helpers/keybindings.tsindex 954e099be..6dd00ec1a 100644--- a/packages/hoppscotch-common/src/helpers/keybindings.ts+++ b/packages/hoppscotch-common/src/helpers/keybindings.ts@@ -1,5 +1,9 @@import { onBeforeUnmount, onMounted } from "vue"import { HoppActionWithOptionalArgs, invokeAction } from "./actions"+import {+ getKeyboardLayoutStrategy,+ type KeyboardLayoutStrategy,+} from "./keyboard-strategy"import { isAppleDevice } from "./platformutils"import {isCodeMirrorEditor,@@ -175,6 +179,18 @@ function handleKeyDown(ev: KeyboardEvent) {// Do not check keybinds if the mode is disabledif (!keybindingsEnabled) return+ // Skip during IME composition (CJK input). Modern browsers report+ // `isComposing`. Older ones use the sentinel `keyCode === 229`.+ // Either way the keystroke belongs to a composition, not a shortcut.+ if (ev.isComposing || ev.keyCode === 229) return++ // Skip when AltGr is the modifier. Browsers report AltGr as Ctrl+Alt+ // on Windows, so QWERTZ users typing `[` via AltGr+8 would otherwise+ // match Ctrl+Alt+[ (the MRU tab shortcut) and steal the keystroke.+ // `getModifierState("AltGraph")` is true only for AltGr, not for+ // genuine Ctrl+Alt presses.+ if (ev.getModifierState("AltGraph")) return+const binding = generateKeybindingString(ev)if (!binding) return@@ -307,29 +323,61 @@ function generateKeybindingString(ev: KeyboardEvent): ShortcutKey | null {}function getPressedKey(ev: KeyboardEvent): Key | null {+ return resolvePressedKey(ev, getKeyboardLayoutStrategy())+}++// Minimal subset of `KeyboardEvent` so unit tests can construct fixtures+// without a JSDOM event. `getModifierState` is optional because the only+// call site (numpad detection) tolerates its absence.+export type KeyboardEventLike = Pick<KeyboardEvent, "key" | "code"> & {+ getModifierState?: KeyboardEvent["getModifierState"]+}++/**+ * Resolves a keyboard event into the registered shortcut key, dispatching+ * letter and digit lookups through the active layout strategy.+ *+ * Strategies only affect the letter and digit branches because those are+ * the keys whose `event.key` and `event.code` diverge across layouts.+ * Arrow keys, Tab, Enter, brackets, and the "?" → "/" mapping are layout+ * stable, so the same checks apply regardless of strategy.+ *+ * `"key"` uses `event.key` (the typed character), which suits AZERTY,+ * QWERTZ, and Dvorak users whose keycap labels match the shortcut they+ * want to fire. `"code"` uses `event.code` (the physical key position),+ * which suits Cyrillic and CJK users with US-QWERTY muscle memory.+ * `"hybrid"` prefers `event.key` when it produces a Latin glyph and+ * falls back to `event.code` otherwise, covering both populations.+ *+ * Both `getPressedKey` (the in-page handler entry) and the capture-phase+ * listener in `selfhost-web/main.ts` call this with the active strategy+ * from `getKeyboardLayoutStrategy`.+ */+export function resolvePressedKey(+ ev: KeyboardEventLike,+ strategy: KeyboardLayoutStrategy+): Key | null {const key = (ev.key ?? "").toLowerCase()const code = ev.code ?? ""- // Use event.code for letters and digits so shortcuts work regardless of- // the active keyboard layout (Cyrillic, CJK, Dvorak, etc). event.key- // returns the character produced by the layout, event.code returns the- // physical key position.- //- // TODO: Several component-level keydown handlers still use event.key- // (spotlight, EnvInput, SchemaSearch, AI modals). Those need the- // same migration but are lower priority since they only check- // arrow/Enter/Escape which are layout-stable.-- // Letter keys (KeyA–KeyZ)- if (code.startsWith("Key") && code.length === 4) {- return code[3].toLowerCase() as Key- }-- // ev.code can be empty in synthetic events or older environments. Fall back- // to ev.key for ASCII letters so shortcuts don't silently stop working.- // This reintroduces layout-dependence for that edge case, but that's better- // than dropping the shortcut entirely.- if (!code && key.length === 1 && key >= "a" && key <= "z") return key as Key+ // Letters+ const letterFromKey =+ key.length === 1 && key >= "a" && key <= "z" ? (key as Key) : null+ const letterFromCode =+ code.startsWith("Key") && code.length === 4+ ? (code[3].toLowerCase() as Key)+ : null+ // The "code" branch falls back to event.key when event.code is empty+ // (synthetic events, certain older environments) so a Latin-letter+ // shortcut still resolves rather than silently dropping. Matches the+ // pre-strategy resolver's contract.+ const letter =+ strategy === "key"+ ? letterFromKey+ : strategy === "code"+ ? (letterFromCode ?? (!code ? letterFromKey : null))+ : (letterFromKey ?? letterFromCode)+ if (letter) return letter// Arrow keys (ArrowUp → up, etc)if (key.startsWith("arrow")) {@@ -343,16 +391,31 @@ function getPressedKey(ev: KeyboardEvent): Key | null {// Shift+/ produces "?" on most layouts but the shortcut is registered as "/"if (key === "?") return "/"- // Punctuation and special keys checked before digit codes because some- // layouts produce these characters from physical digit keys (e.g. AZERTY- // produces [ via AltGr+5 which has code "Digit5").+ // Punctuation checked before digit codes because some layouts produce+ // these characters from physical digit keys (e.g. AZERTY produces [+ // via AltGr+5 which has code "Digit5").if (key === "/" || key === "." || key === "enter") return keyif (key === "[" || key === "]") return key- // Digit keys (Digit0–Digit9)- if (code.startsWith("Digit") && code.length === 6) {- return code[5] as Key- }+ // Bracket fallback for non-Latin layouts where the physical bracket+ // keys don't type [/] (e.g. Russian Cyrillic where KeyBracketLeft+ // types "х"). The shortcut is registered as ctrl-alt-[ so users+ // pressing the keycap labelled [ still fire it regardless of layout.+ if (code === "BracketLeft") return "["+ if (code === "BracketRight") return "]"++ // Digits+ const digitFromKey =+ key.length === 1 && key >= "0" && key <= "9" ? (key as Key) : null+ const digitFromCode =+ code.startsWith("Digit") && code.length === 6 ? (code[5] as Key) : null+ const digit =+ strategy === "key"+ ? digitFromKey+ : strategy === "code"+ ? digitFromCode+ : (digitFromKey ?? digitFromCode)+ if (digit) return digit// Numpad digits (Numpad0–Numpad9), only when NumLock is on.// When NumLock is off the physical keys act as navigation (Home, End, etc)@@ -360,7 +423,7 @@ function getPressedKey(ev: KeyboardEvent): Key | null {if (code.startsWith("Numpad") &&code.length === 7 &&- ev.getModifierState("NumLock")+ ev.getModifierState?.("NumLock")) {return code.slice(6) as Key}diff --git a/packages/hoppscotch-common/src/helpers/keyboard-strategy.ts b/packages/hoppscotch-common/src/helpers/keyboard-strategy.tsnew file mode 100644index 000000000..44d5d1045--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/keyboard-strategy.ts@@ -0,0 +1,30 @@+import type { DesktopSettings } from "~/platform/desktop-settings"++/**+ * Web-safe holder for the keyboard layout strategy.+ *+ * The desktop settings composable is the only writer: it calls+ * `setKeyboardLayoutStrategy` after the initial settings load and from+ * its store-watch callback when the user changes the radio. Keeping+ * the holder out of the composable lets `keybindings.ts` read the+ * strategy without pulling in Tauri-only imports, so the same+ * `getPressedKey` works on web builds where Tauri isn't available.+ *+ * The default `"hybrid"` matches the schema default, so a keypress+ * before the composable finishes loading still resolves through the+ * recommended strategy.+ */++export type KeyboardLayoutStrategy = DesktopSettings["keyboardLayoutStrategy"]++let currentStrategy: KeyboardLayoutStrategy = "hybrid"++export function getKeyboardLayoutStrategy(): KeyboardLayoutStrategy {+ return currentStrategy+}++export function setKeyboardLayoutStrategy(+ strategy: KeyboardLayoutStrategy+): void {+ currentStrategy = strategy+}diff --git a/packages/hoppscotch-common/src/platform/desktop-settings.ts b/packages/hoppscotch-common/src/platform/desktop-settings.tsindex 696a86a4c..a3655fb21 100644--- a/packages/hoppscotch-common/src/platform/desktop-settings.ts+++ b/packages/hoppscotch-common/src/platform/desktop-settings.ts@@ -55,6 +55,14 @@ export const DESKTOP_SETTINGS_SCHEMA = z.object({// Display and UX. User-facing zoom control is future scope.zoomLevel: z.number().positive().default(1.0),++ // Keyboard shortcut dispatch strategy. The hybrid strategy prefers+ // event.key when it produces a Latin glyph (so AZERTY's "A" key fires+ // Ctrl+A regardless of physical position) and falls back to event.code+ // for non-Latin layouts (Cyrillic, CJK). The `key` and `code` strategies+ // are escape valves for users on layouts where the hybrid heuristic+ // guesses wrong.+ keyboardLayoutStrategy: z.enum(["key", "code", "hybrid"]).default("hybrid"),})export type DesktopSettings = z.infer<typeof DESKTOP_SETTINGS_SCHEMA>diff --git a/packages/hoppscotch-selfhost-web/src/main.ts b/packages/hoppscotch-selfhost-web/src/main.tsindex b03f7ee5f..6a5041043 100644--- a/packages/hoppscotch-selfhost-web/src/main.ts+++ b/packages/hoppscotch-selfhost-web/src/main.ts@@ -2,6 +2,9 @@ import { nextTick, ref, watch } from "vue"import { emit, listen } from "@tauri-apps/api/event"import { createHoppApp } from "@hoppscotch/common"import { useSettingStatic } from "@hoppscotch/common/composables/settings"+import { useDesktopSettings } from "@hoppscotch/common/composables/desktop-settings"+import { resolvePressedKey } from "@hoppscotch/common/helpers/keybindings"+import { getKeyboardLayoutStrategy } from "@hoppscotch/common/helpers/keyboard-strategy"import { getKernelMode } from "@hoppscotch/kernel"import { def as stdBackendDef } from "@hoppscotch/common/platform/std/backend"@@ -78,6 +81,15 @@ const headerPaddingLeft = ref("0px")const headerPaddingTop = ref("0px")function setupDesktopUI() {+ // Hydrate the keyboard-layout-strategy holder at desktop bootstrap.+ // The composable's first call triggers loadInitial, which reads the+ // persisted strategy from tauri-plugin-store and writes it into the+ // shared holder. Without this call the holder stays at its module-+ // level default ("hybrid") until Desktop.vue mounts, so a persisted+ // "key" or "code" choice would be dormant on every restart until the+ // user opened the settings page.+ useDesktopSettings()+headerPaddingTop.value = "0px"headerPaddingLeft.value = "80px"@@ -282,130 +294,72 @@ async function initApp() {return}+ // Skip during IME composition (CJK input). Modern browsers report+ // `isComposing`. Older ones use the sentinel `keyCode === 229`.+ if (e.isComposing || e.keyCode === 229) return++ // Skip when AltGr is the modifier. Browsers report AltGr as+ // Ctrl+Alt on Windows, so QWERTZ users typing `[` via AltGr+8+ // would otherwise match Ctrl+Alt+[ and get hijacked into the+ // MRU tab shortcut. `getModifierState("AltGraph")` is true only+ // for AltGr, not for genuine Ctrl+Alt.+ if (e.getModifierState("AltGraph")) return+const isCtrlOrCmd = e.ctrlKey || e.metaKey+ if (!isCtrlOrCmd) return++ // Resolve the pressed key through the active layout strategy so+ // AZERTY's "A" keycap (physical KeyQ position) fires Ctrl+A,+ // not Ctrl+Q. The in-page handler uses the same resolver, so+ // routing the capture phase through it keeps both paths+ // consistent and lets the user's strategy choice take effect+ // everywhere, including for the desktop-shell shortcuts the+ // capture phase pre-empts.+ const key = resolvePressedKey(e, getKeyboardLayoutStrategy())+ if (!key) return+let shortcutEvent: string | null = null- if (isCtrlOrCmd && !e.shiftKey && !e.altKey && e.code === "KeyQ") {+ if (!e.shiftKey && !e.altKey && key === "q") {// Ctrl/Cmd + Q - Quit Application- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-q"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- !e.altKey &&- e.code === "KeyT"- ) {+ } else if (!e.shiftKey && !e.altKey && key === "t") {// Ctrl/Cmd + T - New Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-t"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- !e.altKey &&- e.code === "KeyW"- ) {+ } else if (!e.shiftKey && !e.altKey && key === "w") {// Ctrl/Cmd + W - Close Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-w"- } else if (- isCtrlOrCmd &&- e.shiftKey &&- !e.altKey &&- e.code === "KeyT"- ) {+ } else if (e.shiftKey && !e.altKey && key === "t") {// Ctrl/Cmd + Shift + T - Reopen Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-shift-t"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- e.key === "ArrowRight"- ) {+ } else if (!e.shiftKey && e.altKey && key === "right") {// Ctrl/Cmd + Alt + Right - Next Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-right"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- e.key === "ArrowLeft"- ) {+ } else if (!e.shiftKey && e.altKey && key === "left") {// Ctrl/Cmd + Alt + Left - Previous Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-left"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- (e.code === "Digit9" ||- (e.code === "Numpad9" && e.getModifierState("NumLock")))- ) {+ } else if (!e.shiftKey && e.altKey && key === "9") {// Ctrl/Cmd + Alt + 9 - First Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-9"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- (e.code === "Digit0" ||- (e.code === "Numpad0" && e.getModifierState("NumLock")))- ) {+ } else if (!e.shiftKey && e.altKey && key === "0") {// Ctrl/Cmd + Alt + 0 - Last Tab- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-0"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- e.code === "KeyU"- ) {+ } else if (!e.shiftKey && e.altKey && key === "u") {// Ctrl/Cmd + Alt + U - Focus URL Bar- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-u"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- e.code === "BracketRight"- ) {+ } else if (!e.shiftKey && e.altKey && key === "]") {// Ctrl/Cmd + Alt + ] - MRU Tab Switch- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-]"- } else if (- isCtrlOrCmd &&- !e.shiftKey &&- e.altKey &&- e.code === "BracketLeft"- ) {+ } else if (!e.shiftKey && e.altKey && key === "[") {// Ctrl/Cmd + Alt + [ - MRU Tab Switch (Reverse)- e.preventDefault()- e.stopPropagation()- e.stopImmediatePropagation()shortcutEvent = "ctrl-alt-["}if (shortcutEvent) {+ e.preventDefault()+ e.stopPropagation()+ e.stopImmediatePropagation()+setTimeout(() => {emit("hoppscotch_desktop_shortcut", shortcutEvent).catch((error) => {