Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(hud): arrow-key navigation in the language menu (#1015)

EtienneLescot1c58dad2da87
diff --git a/src/components/ai-edition/v4/EditorTopBar.tsx b/src/components/ai-edition/v4/EditorTopBar.tsx
index ed391cb55..6968b3661 100644
--- a/src/components/ai-edition/v4/EditorTopBar.tsx
+++ b/src/components/ai-edition/v4/EditorTopBar.tsx
@@ -16,13 +16,14 @@ import {
Sun,
Undo2,
} from "lucide-react";
-import { type KeyboardEvent as ReactKeyboardEvent, useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import logoMark from "@/assets/openscreen-mark.png";
import { Tooltip } from "@/components/ui/tooltip";
import { useI18n, useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { useTheme } from "@/hooks/useTheme";
import { getAvailableLocales, getLocaleName } from "@/i18n/loader";
+import { moveMenuFocus } from "@/lib/menuKeyboard";
import { formatFirstFixedBinding } from "@/lib/shortcuts";
import { StylePresetsMenu } from "../StylePresetsMenu";
import styles from "./EditorShellV4.module.css";
@@ -361,21 +362,6 @@ function AppMenu({ actions }: { actions: TopBarActions }) {
menuRef.current?.querySelector<HTMLButtonElement>('[role="menuitem"]')?.focus();
}, [open]);
- const onMenuKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
- if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
- e.preventDefault();
- const items = Array.from(
- menuRef.current?.querySelectorAll<HTMLButtonElement>(
- '[role="menuitem"], [role="menuitemradio"]',
- ) ?? [],
- );
- if (items.length === 0) return;
- const at = items.indexOf(document.activeElement as HTMLButtonElement);
- const next = e.key === "ArrowDown" ? at + 1 : at - 1;
- // Wraps both ways; `at` is -1 when focus escaped the list, and ArrowDown then lands on 0.
- items[(next + items.length) % items.length]?.focus();
- };
-
const run = (action: () => void) => () => {
// Unlike Escape, a click does not hand focus back to the trigger: the pointer user did not
// come from there, and a focus ring appearing under the cursor reads as a bug.
@@ -401,7 +387,7 @@ function AppMenu({ actions }: { actions: TopBarActions }) {
<ChevronDown size={13} className={styles.brandChevron} aria-hidden />
</button>
{open ? (
- <div ref={menuRef} className={styles.appMenu} role="menu" onKeyDown={onMenuKeyDown}>
+ <div ref={menuRef} className={styles.appMenu} role="menu" onKeyDown={moveMenuFocus}>
{/* The file actions that used to be three icons in the bar. Their labels are the
keys those icons carried as tooltips; Ctrl+N / Ctrl+O / Ctrl+S still reach them
through the native menu's accelerators. */}
diff --git a/src/components/launch/HudControls.tsx b/src/components/launch/HudControls.tsx
index 6000d5ab7..2c5fa7df1 100644
--- a/src/components/launch/HudControls.tsx
+++ b/src/components/launch/HudControls.tsx
@@ -1,5 +1,14 @@
import { Check, Languages, NotepadText, Settings } from "lucide-react";
-import { createContext, memo, type ReactElement, useContext, useRef, useState } from "react";
+import {
+ createContext,
+ memo,
+ type ReactElement,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { moveMenuFocus } from "@/lib/menuKeyboard";
import { formatTimePadded } from "../../utils/timeUtils";
import { Button } from "../ui/button";
import { TOOLTIP_GAP_PX, Tooltip } from "../ui/tooltip";
@@ -663,12 +672,19 @@ export const HudLanguageMenu = memo(function HudLanguageMenu({
panelRef: (el: HTMLDivElement | null) => void;
onEnsureInteractive: () => void;
}) {
+ // Into the list as it opens, on the language in use, so the arrows work straight away.
+ const activeItemRef = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ activeItemRef.current?.focus();
+ }, []);
+
return (
<div
ref={panelRef}
data-hud-interactive="true"
data-testid="hud-language-menu"
role="menu"
+ onKeyDown={moveMenuFocus}
className={`${styles.hudPopover} ${styles.hudPopoverScroll} ${styles.hudScrollbar} animate-mic-panel-in ${styles.electronNoDrag}`}
onPointerDown={(event) => event.stopPropagation()}
onPointerEnter={onEnsureInteractive}
@@ -680,6 +696,7 @@ export const HudLanguageMenu = memo(function HudLanguageMenu({
{locales.map((loc) => (
<button
key={loc}
+ ref={loc === activeLocale ? activeItemRef : undefined}
type="button"
role="menuitemradio"
aria-checked={loc === activeLocale}
diff --git a/src/components/launch/LaunchWindow.test.tsx b/src/components/launch/LaunchWindow.test.tsx
index 9036bf774..9ecb4c7b0 100644
--- a/src/components/launch/LaunchWindow.test.tsx
+++ b/src/components/launch/LaunchWindow.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { StrictMode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { nativeBridgeClient } from "@/native";
@@ -157,8 +158,10 @@ const i18nState = vi.hoisted(() => ({
}));
vi.mock("@/i18n/loader", () => ({
- getAvailableLocales: () => ["en"],
- getLocaleName: () => "English",
+ // The active "en" sits between two others, so the arrows have somewhere to go both ways.
+ getAvailableLocales: () => ["de", "en", "fr"],
+ getLocaleName: (locale: string) =>
+ ({ de: "Deutsch", fr: "Français" })[locale as "de" | "fr"] ?? "English",
}));
vi.mock("@/contexts/I18nContext", () => ({
@@ -1533,6 +1536,44 @@ describe("LaunchWindow popover dismissal", () => {
expect(i18nState.value.setLocale).not.toHaveBeenCalled();
});
+ it("focuses the language in use as the menu opens", async () => {
+ renderLaunchWindow();
+ const menu = await openLanguageMenu();
+
+ expect(within(menu).getByRole("menuitemradio", { name: "English" })).toHaveFocus();
+ expect(within(menu).getByRole("menuitemradio", { name: "English" })).toHaveAttribute(
+ "aria-checked",
+ "true",
+ );
+ });
+
+ it("moves between languages with the arrow keys, wrapping at both ends", async () => {
+ renderLaunchWindow();
+ const menu = await openLanguageMenu();
+ const item = (name: string) => within(menu).getByRole("menuitemradio", { name });
+
+ fireEvent.keyDown(document.activeElement as HTMLElement, { key: "ArrowDown" });
+ expect(item("Français")).toHaveFocus();
+ fireEvent.keyDown(document.activeElement as HTMLElement, { key: "ArrowDown" });
+ expect(item("Deutsch")).toHaveFocus();
+ fireEvent.keyDown(document.activeElement as HTMLElement, { key: "ArrowUp" });
+ expect(item("Français")).toHaveFocus();
+ expect(i18nState.value.setLocale).not.toHaveBeenCalled();
+ });
+
+ it("picks the focused language on Enter", async () => {
+ const user = userEvent.setup();
+ renderLaunchWindow();
+ await openLanguageMenu();
+
+ await user.keyboard("{ArrowDown}{Enter}");
+
+ expect(i18nState.value.setLocale).toHaveBeenCalledWith("fr");
+ await waitFor(() => {
+ expect(screen.queryByTestId("hud-language-menu")).not.toBeInTheDocument();
+ });
+ });
+
it("closes the device-settings panel on Escape", async () => {
renderLaunchWindow();
await openDeviceSettings();
diff --git a/src/lib/menuKeyboard.ts b/src/lib/menuKeyboard.ts
new file mode 100644
index 000000000..a2abefb8f
--- /dev/null
+++ b/src/lib/menuKeyboard.ts
@@ -0,0 +1,19 @@
+import type { KeyboardEvent } from "react";
+
+/**
+ * ArrowUp/ArrowDown between the items of the menu the handler sits on, wrapping both ways.
+ * Enter and Space need nothing: the items are buttons. Escape stays with each menu, which
+ * knows where focus goes back to.
+ */
+export function moveMenuFocus(e: KeyboardEvent<HTMLElement>) {
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
+ e.preventDefault();
+ const items = Array.from(
+ e.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"], [role="menuitemradio"]'),
+ );
+ if (items.length === 0) return;
+ const at = items.indexOf(document.activeElement as HTMLElement);
+ const next = e.key === "ArrowDown" ? at + 1 : at - 1;
+ // `at` is -1 when focus escaped the list, and ArrowDown then lands on 0.
+ items[(next + items.length) % items.length]?.focus();
+}