Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 3 additions & 17 deletions src/components/ai-edition/v4/EditorTopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand All @@ -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. */}
Expand Down
19 changes: 18 additions & 1 deletion src/components/launch/HudControls.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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}
Expand All @@ -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}
Expand Down
45 changes: 43 additions & 2 deletions src/components/launch/LaunchWindow.test.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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", () => ({
Expand Down Expand Up @@ -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();
Expand Down
19 changes: 19 additions & 0 deletions src/lib/menuKeyboard.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Loading