Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: add compound hotkey support (Cmd+Shift+K style)

Claudedbb4fb8bee93
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 144cb2e83..895a5e8da 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -38,8 +38,10 @@ import LanguageSelector from "./ui/LanguageSelector";
import { UnifiedModelPickerCompact } from "./UnifiedModelPicker";
const InteractiveKeyboard = React.lazy(() => import("./ui/Keyboard"));
import { setAgentName as saveAgentName } from "../utils/agentName";
-import { formatHotkeyLabel } from "../utils/hotkeys";
+import { formatHotkeyLabel, getDefaultHotkey } from "../utils/hotkeys";
import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
+import { HotkeyInput } from "./ui/HotkeyInput";
+import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";
interface OnboardingFlowProps {
onComplete: () => void;
@@ -100,6 +102,20 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
} = useDialogs();
const practiceTextareaRef = useRef<HTMLInputElement>(null);
+ // Ref to prevent React.StrictMode double-invocation of auto-registration
+ const autoRegisterInFlightRef = useRef(false);
+ const hotkeyStepInitializedRef = useRef(false);
+
+ // Shared hotkey registration hook
+ const { registerHotkey, isRegistering: isHotkeyRegistering } = useHotkeyRegistration({
+ onSuccess: (registeredHotkey) => {
+ setHotkey(registeredHotkey);
+ setDictationKey(registeredHotkey);
+ },
+ showSuccessToast: false, // Don't show toast during onboarding auto-registration
+ showErrorToast: false,
+ });
+
const trimmedReasoningBase = (reasoningBaseUrl || "").trim();
const normalizedReasoningBaseUrl = useMemo(
() => normalizeBaseUrl(trimmedReasoningBase),
@@ -326,6 +342,45 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}
}, [currentStep]);
+ // Auto-register default hotkey when entering the hotkey step (step 4)
+ useEffect(() => {
+ if (currentStep !== 4) {
+ // Reset initialization flag when leaving step 4
+ hotkeyStepInitializedRef.current = false;
+ return;
+ }
+
+ // Prevent double-invocation from React.StrictMode
+ if (autoRegisterInFlightRef.current || hotkeyStepInitializedRef.current) {
+ return;
+ }
+
+ const autoRegisterDefaultHotkey = async () => {
+ autoRegisterInFlightRef.current = true;
+ hotkeyStepInitializedRef.current = true;
+
+ try {
+ // Get platform-appropriate default hotkey
+ const defaultHotkey = getDefaultHotkey();
+
+ // Only auto-register if no hotkey is currently set or it's the old default
+ if (!hotkey || hotkey === "`" || hotkey === "GLOBE") {
+ // Try to register the default hotkey silently
+ const success = await registerHotkey(defaultHotkey);
+ if (success) {
+ setHotkey(defaultHotkey);
+ }
+ }
+ } catch (error) {
+ console.error("Failed to auto-register default hotkey:", error);
+ } finally {
+ autoRegisterInFlightRef.current = false;
+ }
+ };
+
+ void autoRegisterDefaultHotkey();
+ }, [currentStep, hotkey, registerHotkey]);
+
const ensureHotkeyRegistered = useCallback(async () => {
if (!window.electronAPI?.updateHotkey) {
return true;
@@ -889,7 +944,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
Choose Your Hotkey
</h2>
<p className="text-gray-600">
- Select which key you want to press to start/stop dictation
+ Press any key or key combination (like Cmd+Shift+K) to set your dictation hotkey
</p>
</div>
@@ -898,23 +953,48 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<label className="block text-sm font-medium text-gray-700 mb-2">
Activation Key
</label>
- <Input
- placeholder="Default: ` (backtick)"
+ <HotkeyInput
value={hotkey}
- onChange={(e) => setHotkey(e.target.value)}
- className="text-center text-lg font-mono"
+ onChange={async (newHotkey) => {
+ // Immediately register the new hotkey
+ const success = await registerHotkey(newHotkey);
+ if (success) {
+ setHotkey(newHotkey);
+ }
+ }}
+ placeholder="Click here and press a key combination..."
+ disabled={isHotkeyRegistering}
/>
- <p className="text-xs text-gray-500 mt-2">
- Press this key from anywhere to start/stop dictation
+ <p className="text-xs text-gray-500 mt-6">
+ Supports single keys (F1, `) or combinations (Cmd+Shift+K)
</p>
</div>
+ <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-200">
+ <h4 className="font-medium text-indigo-900 mb-3">
+ Current hotkey:
+ </h4>
+ <div className="flex items-center justify-center">
+ <kbd className="px-4 py-2 bg-white border-2 border-indigo-300 rounded-lg font-mono text-xl font-semibold text-indigo-900 shadow-sm">
+ {formatHotkeyLabel(hotkey)}
+ </kbd>
+ </div>
+ </div>
+
<div className="bg-gray-50 p-4 rounded-lg">
<h4 className="font-medium text-gray-900 mb-3">
- Click any key to select it:
+ Or click a key on the keyboard:
</h4>
<React.Suspense fallback={<div>Loading keyboard...</div>}>
- <InteractiveKeyboard selectedKey={hotkey} setSelectedKey={setHotkey} />
+ <InteractiveKeyboard
+ selectedKey={hotkey}
+ setSelectedKey={async (key) => {
+ const success = await registerHotkey(key);
+ if (success) {
+ setHotkey(key);
+ }
+ }}
+ />
</React.Suspense>
</div>
</div>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 13e6b5022..7efb0c62e 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -19,6 +19,8 @@ import PromptStudio from "./ui/PromptStudio";
import { API_ENDPOINTS } from "../config/constants";
import AIModelSelectorEnhanced from "./AIModelSelectorEnhanced";
import type { UpdateInfoResult } from "../types/electron";
+import { HotkeyInput } from "./ui/HotkeyInput";
+import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";
const InteractiveKeyboard = React.lazy(() => import("./ui/Keyboard"));
export type SettingsSectionType =
@@ -115,6 +117,16 @@ export default function SettingsPage({
const { agentName, setAgentName } = useAgentName();
const installTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Shared hotkey registration hook
+ const { registerHotkey, isRegistering: isHotkeyRegistering } = useHotkeyRegistration({
+ onSuccess: (registeredHotkey) => {
+ setDictationKey(registeredHotkey);
+ },
+ showSuccessToast: true,
+ showErrorToast: true,
+ showAlert: showAlertDialog,
+ });
+
const subscribeToUpdates = useCallback(() => {
if (!window.electronAPI) return () => {};
@@ -437,33 +449,6 @@ export default function SettingsPage({
});
};
- const saveKey = async () => {
- try {
- const result = await window.electronAPI?.updateHotkey(dictationKey);
-
- if (!result?.success) {
- showAlertDialog({
- title: "Hotkey Not Saved",
- description:
- result?.message ||
- "This key could not be registered. Please choose a different key.",
- });
- return;
- }
-
- showAlertDialog({
- title: "Key Saved",
- description: `Dictation key saved: ${formatHotkeyLabel(dictationKey)}`,
- });
- } catch (error) {
- console.error("Failed to update hotkey:", error);
- showAlertDialog({
- title: "Error",
- description: `Failed to update hotkey: ${error.message}`,
- });
- }
- };
-
const handleRemoveModels = useCallback(() => {
if (isRemovingModels) return;
@@ -734,7 +719,7 @@ export default function SettingsPage({
Dictation Hotkey
</h3>
<p className="text-sm text-gray-600 mb-6">
- Configure the key you press to start and stop voice dictation.
+ Configure the key or key combination you press to start and stop voice dictation.
</p>
</div>
<div className="space-y-4">
@@ -742,19 +727,33 @@ export default function SettingsPage({
<label className="block text-sm font-medium text-gray-700 mb-2">
Activation Key
</label>
- <Input
- placeholder="Default: ` (backtick)"
+ <HotkeyInput
value={dictationKey}
- onChange={(e) => setDictationKey(e.target.value)}
- className="text-center text-lg font-mono"
+ onChange={async (newHotkey) => {
+ await registerHotkey(newHotkey);
+ }}
+ placeholder="Click here and press a key combination..."
+ disabled={isHotkeyRegistering}
/>
- <p className="text-xs text-gray-500 mt-2">
- Press this key from anywhere to start/stop dictation
+ <p className="text-xs text-gray-500 mt-6">
+ Supports single keys (F1, `) or combinations (Cmd+Shift+K)
</p>
</div>
+
+ <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-200">
+ <h4 className="font-medium text-indigo-900 mb-3">
+ Current hotkey:
+ </h4>
+ <div className="flex items-center justify-center">
+ <kbd className="px-4 py-2 bg-white border-2 border-indigo-300 rounded-lg font-mono text-xl font-semibold text-indigo-900 shadow-sm">
+ {formatHotkeyLabel(dictationKey)}
+ </kbd>
+ </div>
+ </div>
+
<div className="bg-gray-50 p-4 rounded-lg">
<h4 className="font-medium text-gray-900 mb-3">
- Click any key to select it:
+ Or click a key on the keyboard:
</h4>
<React.Suspense
fallback={
@@ -765,17 +764,12 @@ export default function SettingsPage({
>
<InteractiveKeyboard
selectedKey={dictationKey}
- setSelectedKey={setDictationKey}
+ setSelectedKey={async (key) => {
+ await registerHotkey(key);
+ }}
/>
</React.Suspense>
</div>
- <Button
- onClick={saveKey}
- disabled={!dictationKey.trim()}
- className="w-full"
- >
- Save Hotkey
- </Button>
</div>
</div>
diff --git a/src/components/ui/HotkeyInput.tsx b/src/components/ui/HotkeyInput.tsx
new file mode 100644
index 000000000..436358587
--- /dev/null
+++ b/src/components/ui/HotkeyInput.tsx
@@ -0,0 +1,281 @@
+import React, { useState, useCallback, useRef, useEffect } from "react";
+import { formatHotkeyLabel } from "../../utils/hotkeys";
+
+/**
+ * Layout-independent key code to key name mapping.
+ * Uses e.code (physical key) instead of e.key (layout-dependent character)
+ * to ensure hotkeys work correctly across different keyboard layouts.
+ */
+const CODE_TO_KEY: Record<string, string> = {
+ // Number row
+ Backquote: "`",
+ Digit1: "1",
+ Digit2: "2",
+ Digit3: "3",
+ Digit4: "4",
+ Digit5: "5",
+ Digit6: "6",
+ Digit7: "7",
+ Digit8: "8",
+ Digit9: "9",
+ Digit0: "0",
+ Minus: "-",
+ Equal: "=",
+
+ // QWERTY row
+ KeyQ: "Q",
+ KeyW: "W",
+ KeyE: "E",
+ KeyR: "R",
+ KeyT: "T",
+ KeyY: "Y",
+ KeyU: "U",
+ KeyI: "I",
+ KeyO: "O",
+ KeyP: "P",
+ BracketLeft: "[",
+ BracketRight: "]",
+ Backslash: "\\",
+
+ // ASDF row
+ KeyA: "A",
+ KeyS: "S",
+ KeyD: "D",
+ KeyF: "F",
+ KeyG: "G",
+ KeyH: "H",
+ KeyJ: "J",
+ KeyK: "K",
+ KeyL: "L",
+ Semicolon: ";",
+ Quote: "'",
+
+ // ZXCV row
+ KeyZ: "Z",
+ KeyX: "X",
+ KeyC: "C",
+ KeyV: "V",
+ KeyB: "B",
+ KeyN: "N",
+ KeyM: "M",
+ Comma: ",",
+ Period: ".",
+ Slash: "/",
+
+ // Special keys
+ Space: "Space",
+ Escape: "Esc",
+ Tab: "Tab",
+ Enter: "Enter",
+ Backspace: "Backspace",
+
+ // Function keys
+ F1: "F1",
+ F2: "F2",
+ F3: "F3",
+ F4: "F4",
+ F5: "F5",
+ F6: "F6",
+ F7: "F7",
+ F8: "F8",
+ F9: "F9",
+ F10: "F10",
+ F11: "F11",
+ F12: "F12",
+
+ // Arrow keys
+ ArrowUp: "Up",
+ ArrowDown: "Down",
+ ArrowLeft: "Left",
+ ArrowRight: "Right",
+
+ // Other common keys
+ Insert: "Insert",
+ Delete: "Delete",
+ Home: "Home",
+ End: "End",
+ PageUp: "PageUp",
+ PageDown: "PageDown",
+};
+
+/**
+ * Keys that should be ignored when pressed alone (modifier-only presses)
+ */
+const MODIFIER_CODES = new Set([
+ "ShiftLeft",
+ "ShiftRight",
+ "ControlLeft",
+ "ControlRight",
+ "AltLeft",
+ "AltRight",
+ "MetaLeft",
+ "MetaRight",
+ "CapsLock",
+]);
+
+export interface HotkeyInputProps {
+ value: string;
+ onChange: (hotkey: string) => void;
+ onBlur?: () => void;
+ placeholder?: string;
+ className?: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+}
+
+/**
+ * Maps a keyboard event to an Electron-compatible accelerator string.
+ * Uses physical key codes for layout independence.
+ *
+ * @example
+ * // Returns "CommandOrControl+Shift+K" when Cmd+Shift+K is pressed on macOS
+ * // Returns "CommandOrControl+Shift+K" when Ctrl+Shift+K is pressed on Windows/Linux
+ */
+export function mapKeyboardEventToHotkey(e: KeyboardEvent): string | null {
+ // Ignore modifier-only key presses
+ if (MODIFIER_CODES.has(e.code)) {
+ return null;
+ }
+
+ // Get the base key from code
+ const baseKey = CODE_TO_KEY[e.code];
+ if (!baseKey) {
+ return null;
+ }
+
+ // Build modifier array using Electron's cross-platform convention
+ const modifiers: string[] = [];
+
+ // CommandOrControl: Cmd on macOS, Ctrl on Windows/Linux
+ if (e.ctrlKey || e.metaKey) {
+ modifiers.push("CommandOrControl");
+ }
+
+ if (e.altKey) {
+ modifiers.push("Alt");
+ }
+
+ if (e.shiftKey) {
+ modifiers.push("Shift");
+ }
+
+ // Combine modifiers and base key
+ if (modifiers.length > 0) {
+ return [...modifiers, baseKey].join("+");
+ }
+
+ // Single key (no modifiers)
+ return baseKey;
+}
+
+/**
+ * HotkeyInput - A keyboard capture component for compound hotkeys.
+ *
+ * Supports:
+ * - Single keys (e.g., "F1", "`")
+ * - Compound keys (e.g., "CommandOrControl+Shift+K")
+ * - Layout-independent key detection using e.code
+ * - Cross-platform compatibility with Electron's accelerator format
+ */
+export function HotkeyInput({
+ value,
+ onChange,
+ onBlur,
+ placeholder = "Press a key combination...",
+ className = "",
+ disabled = false,
+ autoFocus = false,
+}: HotkeyInputProps) {
+ const [isFocused, setIsFocused] = useState(false);
+ const [isCapturing, setIsCapturing] = useState(false);
+ const inputRef = useRef<HTMLDivElement>(null);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (disabled) return;
+
+ // Prevent default behavior for most keys
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Convert keyboard event to native KeyboardEvent for mapping
+ const nativeEvent = e.nativeEvent;
+ const hotkey = mapKeyboardEventToHotkey(nativeEvent);
+
+ if (hotkey) {
+ onChange(hotkey);
+ setIsCapturing(false);
+ }
+ },
+ [disabled, onChange]
+ );
+
+ const handleFocus = useCallback(() => {
+ setIsFocused(true);
+ setIsCapturing(true);
+ }, []);
+
+ const handleBlur = useCallback(() => {
+ setIsFocused(false);
+ setIsCapturing(false);
+ onBlur?.();
+ }, [onBlur]);
+
+ // Auto-focus support
+ useEffect(() => {
+ if (autoFocus && inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, [autoFocus]);
+
+ const displayValue = value ? formatHotkeyLabel(value) : "";
+ const isMac =
+ typeof navigator !== "undefined" && /Mac|Darwin/.test(navigator.platform);
+
+ return (
+ <div
+ ref={inputRef}
+ tabIndex={disabled ? -1 : 0}
+ role="button"
+ aria-label="Press a key combination to set hotkey"
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
+ className={`
+ relative flex items-center justify-center
+ w-full px-4 py-3
+ text-center text-lg font-mono
+ border-2 rounded-lg
+ transition-all duration-200
+ cursor-pointer select-none
+ focus:outline-none
+ ${
+ disabled
+ ? "bg-gray-100 border-gray-200 text-gray-400 cursor-not-allowed"
+ : isFocused
+ ? "bg-indigo-50 border-indigo-400 ring-2 ring-indigo-200"
+ : "bg-white border-gray-300 hover:border-gray-400"
+ }
+ ${className}
+ `}
+ >
+ {isCapturing && !displayValue ? (
+ <span className="text-indigo-600 animate-pulse">{placeholder}</span>
+ ) : displayValue ? (
+ <span className="text-gray-900">{displayValue}</span>
+ ) : (
+ <span className="text-gray-400">{placeholder}</span>
+ )}
+
+ {isFocused && (
+ <div className="absolute -bottom-6 left-0 right-0 text-center">
+ <span className="text-xs text-indigo-600">
+ {isMac ? "Try Cmd+Shift+K or any key" : "Try Ctrl+Shift+K or any key"}
+ </span>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default HotkeyInput;
diff --git a/src/hooks/useHotkeyRegistration.ts b/src/hooks/useHotkeyRegistration.ts
new file mode 100644
index 000000000..236ba151d
--- /dev/null
+++ b/src/hooks/useHotkeyRegistration.ts
@@ -0,0 +1,182 @@
+import { useState, useCallback, useRef } from "react";
+import { formatHotkeyLabel } from "../utils/hotkeys";
+
+export interface UseHotkeyRegistrationOptions {
+ /**
+ * Callback fired when hotkey is successfully registered
+ */
+ onSuccess?: (hotkey: string) => void;
+
+ /**
+ * Callback fired when hotkey registration fails
+ */
+ onError?: (error: string, hotkey: string) => void;
+
+ /**
+ * Show toast notification on success (default: true)
+ */
+ showSuccessToast?: boolean;
+
+ /**
+ * Show toast notification on error (default: true)
+ */
+ showErrorToast?: boolean;
+
+ /**
+ * Custom toast/alert function for showing messages
+ */
+ showAlert?: (options: { title: string; description: string }) => void;
+}
+
+export interface UseHotkeyRegistrationResult {
+ /**
+ * Register a new hotkey with the system
+ */
+ registerHotkey: (hotkey: string) => Promise<boolean>;
+
+ /**
+ * Whether a registration is currently in progress
+ */
+ isRegistering: boolean;
+
+ /**
+ * The last error message, if any
+ */
+ lastError: string | null;
+
+ /**
+ * Clear the last error
+ */
+ clearError: () => void;
+}
+
+/**
+ * Shared hook for hotkey registration with consistent error handling
+ * and success/failure notifications.
+ *
+ * @example
+ * const { registerHotkey, isRegistering } = useHotkeyRegistration({
+ * onSuccess: (hotkey) => setDictationKey(hotkey),
+ * showAlert: showAlertDialog,
+ * });
+ *
+ * // Later, when user selects a hotkey:
+ * await registerHotkey("CommandOrControl+Shift+K");
+ */
+export function useHotkeyRegistration(
+ options: UseHotkeyRegistrationOptions = {}
+): UseHotkeyRegistrationResult {
+ const {
+ onSuccess,
+ onError,
+ showSuccessToast = true,
+ showErrorToast = true,
+ showAlert,
+ } = options;
+
+ const [isRegistering, setIsRegistering] = useState(false);
+ const [lastError, setLastError] = useState<string | null>(null);
+
+ // Use ref to track in-flight requests and prevent double registration
+ const registrationInFlightRef = useRef(false);
+
+ const clearError = useCallback(() => {
+ setLastError(null);
+ }, []);
+
+ const registerHotkey = useCallback(
+ async (hotkey: string): Promise<boolean> => {
+ // Prevent double registration
+ if (registrationInFlightRef.current) {
+ return false;
+ }
+
+ // Validate hotkey format
+ if (!hotkey || hotkey.trim() === "") {
+ const errorMsg = "Please enter a valid hotkey";
+ setLastError(errorMsg);
+ if (showErrorToast && showAlert) {
+ showAlert({
+ title: "Invalid Hotkey",
+ description: errorMsg,
+ });
+ }
+ onError?.(errorMsg, hotkey);
+ return false;
+ }
+
+ // Check if Electron API is available
+ if (!window.electronAPI?.updateHotkey) {
+ // In non-Electron environment, just succeed silently
+ onSuccess?.(hotkey);
+ return true;
+ }
+
+ try {
+ registrationInFlightRef.current = true;
+ setIsRegistering(true);
+ setLastError(null);
+
+ const result = await window.electronAPI.updateHotkey(hotkey);
+
+ if (!result?.success) {
+ const errorMsg =
+ result?.message ||
+ "This key could not be registered. Please choose a different key.";
+ setLastError(errorMsg);
+
+ if (showErrorToast && showAlert) {
+ showAlert({
+ title: "Hotkey Not Registered",
+ description: errorMsg,
+ });
+ }
+
+ onError?.(errorMsg, hotkey);
+ return false;
+ }
+
+ // Success!
+ if (showSuccessToast && showAlert) {
+ const displayLabel = formatHotkeyLabel(hotkey);
+ showAlert({
+ title: "Hotkey Saved",
+ description: `Now using ${displayLabel} for dictation`,
+ });
+ }
+
+ onSuccess?.(hotkey);
+ return true;
+ } catch (error) {
+ const errorMsg =
+ error instanceof Error
+ ? error.message
+ : "Failed to register hotkey. Please try again.";
+ setLastError(errorMsg);
+
+ if (showErrorToast && showAlert) {
+ showAlert({
+ title: "Hotkey Error",
+ description: errorMsg,
+ });
+ }
+
+ onError?.(errorMsg, hotkey);
+ return false;
+ } finally {
+ setIsRegistering(false);
+ registrationInFlightRef.current = false;
+ }
+ },
+ [onSuccess, onError, showSuccessToast, showErrorToast, showAlert]
+ );
+
+ return {
+ registerHotkey,
+ isRegistering,
+ lastError,
+ clearError,
+ };
+}
+
+export default useHotkeyRegistration;
diff --git a/src/utils/hotkeys.ts b/src/utils/hotkeys.ts
index f5fa575a2..5f7e32c86 100644
--- a/src/utils/hotkeys.ts
+++ b/src/utils/hotkeys.ts
@@ -1,11 +1,154 @@
+/**
+ * Hotkey utilities for formatting and displaying keyboard shortcuts.
+ * Supports both single keys and compound hotkeys (e.g., "CommandOrControl+Shift+K").
+ */
+
+/**
+ * Detects if the current platform is macOS.
+ */
+function isMacPlatform(): boolean {
+ if (typeof navigator === "undefined") return false;
+ return /Mac|Darwin/.test(navigator.platform);
+}
+
+/**
+ * Maps Electron accelerator parts to user-friendly labels.
+ * Automatically adapts to the current platform (macOS vs Windows/Linux).
+ */
+function formatModifierPart(part: string, isMac: boolean): string {
+ switch (part) {
+ case "CommandOrControl":
+ return isMac ? "Cmd" : "Ctrl";
+ case "Command":
+ case "Cmd":
+ return "Cmd";
+ case "Control":
+ case "Ctrl":
+ return "Ctrl";
+ case "Alt":
+ return isMac ? "Option" : "Alt";
+ case "Option":
+ return "Option";
+ case "Shift":
+ return "Shift";
+ case "Super":
+ case "Meta":
+ return isMac ? "Cmd" : "Win";
+ default:
+ return part;
+ }
+}
+
+/**
+ * Formats an Electron accelerator string into a user-friendly display label.
+ *
+ * @param hotkey - The hotkey string in Electron accelerator format
+ * @returns User-friendly label (e.g., "Cmd+Shift+K" on macOS, "Ctrl+Shift+K" on Windows)
+ *
+ * @example
+ * formatHotkeyLabel("CommandOrControl+Shift+K") // "Cmd+Shift+K" on macOS, "Ctrl+Shift+K" on Windows
+ * formatHotkeyLabel("GLOBE") // "Globe"
+ * formatHotkeyLabel("`") // "`"
+ * formatHotkeyLabel(null) // "`"
+ */
export function formatHotkeyLabel(hotkey?: string | null): string {
+ // Handle empty/null values - return default backtick
if (!hotkey || hotkey.trim() === "") {
return "`";
}
+ // Handle special GLOBE key for macOS
if (hotkey === "GLOBE") {
- return "🌐 Globe";
+ return "Globe";
+ }
+
+ // Handle compound hotkeys (contains "+")
+ if (hotkey.includes("+")) {
+ const isMac = isMacPlatform();
+ const parts = hotkey.split("+");
+
+ const formattedParts = parts.map((part) => formatModifierPart(part, isMac));
+
+ return formattedParts.join("+");
}
+ // Single key - return as-is
return hotkey;
}
+
+/**
+ * Parses a hotkey string to extract modifiers and the base key.
+ *
+ * @param hotkey - The hotkey string in Electron accelerator format
+ * @returns Object with modifiers array and baseKey
+ *
+ * @example
+ * parseHotkey("CommandOrControl+Shift+K")
+ * // { modifiers: ["CommandOrControl", "Shift"], baseKey: "K" }
+ */
+export function parseHotkey(hotkey: string): {
+ modifiers: string[];
+ baseKey: string;
+} {
+ if (!hotkey || !hotkey.includes("+")) {
+ return { modifiers: [], baseKey: hotkey || "" };
+ }
+
+ const parts = hotkey.split("+");
+ const baseKey = parts[parts.length - 1];
+ const modifiers = parts.slice(0, -1);
+
+ return { modifiers, baseKey };
+}
+
+/**
+ * Checks if a hotkey is a compound hotkey (has modifiers).
+ *
+ * @param hotkey - The hotkey string
+ * @returns True if the hotkey includes modifiers
+ */
+export function isCompoundHotkey(hotkey: string): boolean {
+ return hotkey?.includes("+") || false;
+}
+
+/**
+ * Gets the default hotkey for the current platform.
+ * - macOS: GLOBE key (Fn key on modern Macs)
+ * - Windows/Linux: Backtick (`)
+ */
+export function getDefaultHotkey(): string {
+ const isMac = isMacPlatform();
+ return isMac ? "GLOBE" : "`";
+}
+
+/**
+ * Validates if a hotkey string is in a valid format.
+ * Valid formats include single keys and Electron accelerator strings.
+ *
+ * @param hotkey - The hotkey string to validate
+ * @returns True if the hotkey format is valid
+ */
+export function isValidHotkeyFormat(hotkey: string): boolean {
+ if (!hotkey || hotkey.trim() === "") {
+ return false;
+ }
+
+ // Special keys are always valid
+ if (hotkey === "GLOBE") {
+ return true;
+ }
+
+ // Single character or word keys are valid
+ if (!hotkey.includes("+")) {
+ return true;
+ }
+
+ // Compound hotkey: must have at least one modifier and one base key
+ const parts = hotkey.split("+");
+ if (parts.length < 2) {
+ return false;
+ }
+
+ // Check that all parts are non-empty
+ return parts.every((part) => part.trim().length > 0);
+}