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
3 changes: 3 additions & 0 deletions desktop/e2e/pane-move.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ test("pane moves render and cancel in a narrow candidate with long titles and la
await page.locator(`[data-theme-option="${theme}"]`).click();
await page.locator("[data-interface-language]").click();
await page.locator(`[data-language-option="${language}"]`).click();
// The closing select hands the keyboard back to its trigger from a
// timer; wait for it, or that late hand-back takes the slider's End.
await expect(page.locator("[data-interface-language]")).toBeFocused();
const size = page.locator("[data-font-size] [role=slider]");
await size.focus();
await page.keyboard.press("End");
Expand Down
3 changes: 3 additions & 0 deletions desktop/e2e/project-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ test("Project settings fit a narrow native window in every language and theme",
await page.locator('[data-interface-language]').click();
await page.locator(`[data-language-option="${language}"]`).click();
await expect(page.locator("html")).toHaveAttribute("lang", language);
// The closing select hands the keyboard back to its trigger from a
// timer; wait for it, or that late hand-back takes the slider's End.
await expect(page.locator("[data-interface-language]")).toBeFocused();
await page.locator('[data-settings-tab="general"]').click();
await page.locator('[data-font-size] [role="slider"]').focus();
await page.keyboard.press("End");
Expand Down
3 changes: 3 additions & 0 deletions desktop/e2e/restoration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ test("failed terminals remain legible and keyboard reachable in a narrow native
await page.locator('[data-settings-tab="general"]').click();
await page.locator("[data-interface-language]").click();
await page.locator('[data-language-option="ko"]').click();
// The closing select hands the keyboard back to its trigger from a
// timer; wait for it, or that late hand-back takes the slider's End.
await expect(page.locator("[data-interface-language]")).toBeFocused();
await page.locator(`[data-theme-option="${theme}"]`).click();
const fontSize = page.locator('[data-font-size] [role="slider"]');
await fontSize.focus();
Expand Down
6 changes: 4 additions & 2 deletions web/src/components/ui/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@ export function useReturnFocus(open: boolean, named?: { target: () => HTMLElemen
if (openedAtClose.current !== null && openedAtClose.current !== layersOpened) return;
// Radix hands focus back a tick after the layer closed; an item that
// moved the keyboard on purpose in the meantime (Rename's inline field)
// keeps it, since taking it back would blur and commit that field.
// keeps it, since taking it back would blur and commit that field. A
// surface around the target (a dialog's focus trap, which takes the
// keyboard when the closed layer's focused element leaves) is a fallback.
const now = document.activeElement;
if (now instanceof HTMLElement && now !== document.body && now.isConnected && !named?.within?.()?.contains(now)) return;
if (now instanceof HTMLElement && now !== document.body && now.isConnected && !now.contains(target) && !named?.within?.()?.contains(now)) return;
returnKeyboardFocus(() => restoreFocus(target));
}, []);
}
94 changes: 94 additions & 0 deletions web/src/components/ui/select.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Dialog, DialogContent, DialogTitle } from "./dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./select";

let root: Root | null = null;

beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
// Radix hands the keyboard back from a timer; a fake one lets the test run it at the moment it names.
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
});

afterEach(() => {
const mounted = root;
root = null;
if (mounted) act(() => mounted.unmount());
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllGlobals();
document.body.replaceChildren();
});

/**
* A language select beside the control the operator moves to next, inside a
* dialog as Settings lays them out: the dialog's focus trap takes the keyboard
* when the picked option leaves, before the select's own hand-back runs.
*/
function mountSelect() {
const closeAutoFocus = vi.fn();
const container = document.createElement("div");
document.body.append(container);
const mounted = createRoot(container);
root = mounted;
act(() => mounted.render(
<Dialog open>
<DialogContent aria-describedby={undefined}>
<DialogTitle>Settings</DialogTitle>
<Select defaultValue="en">
<SelectTrigger aria-label="language"><SelectValue /></SelectTrigger>
<SelectContent onCloseAutoFocus={closeAutoFocus}>
<SelectItem value="en">English</SelectItem>
<SelectItem value="ko">Korean</SelectItem>
</SelectContent>
</Select>
<input type="range" aria-label="size" />
</DialogContent>
</Dialog>,
));
const trigger = document.querySelector<HTMLButtonElement>("[aria-label=language]")!;
const next = document.querySelector<HTMLInputElement>("[aria-label=size]")!;
return { trigger, next, closeAutoFocus };
}

/**
* Opens the select from the keyboard and picks Korean; Radix queues its
* hand-back to the trigger on a timer. The microtasks a browser runs before
* that timer (the dialog's focus trap observes the removal) settle here.
*/
async function pickKorean(trigger: HTMLButtonElement) {
trigger.focus();
act(() => { trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });
const option = [...document.querySelectorAll<HTMLElement>("[role=option]")].find((row) => row.textContent === "Korean")!;
act(() => option.focus());
act(() => { option.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });
expect(document.querySelector("[role=option]")).toBeNull();
await act(async () => {});
}

/** Runs the hand-back Radix queued when the select closed. */
const runHandback = () => act(() => { vi.runOnlyPendingTimers(); });

it("hands the keyboard back to its trigger when nothing took it after the pick", async () => {
const { trigger, closeAutoFocus } = mountSelect();
await pickKorean(trigger);
expect(closeAutoFocus).not.toHaveBeenCalled();
expect(document.activeElement?.getAttribute("role")).toBe("dialog");
runHandback();
expect(closeAutoFocus).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(trigger);
});

it("leaves the keyboard on a control focused after the pick when its late hand-back runs", async () => {
const { trigger, next, closeAutoFocus } = mountSelect();
await pickKorean(trigger);
act(() => next.focus());
expect(closeAutoFocus).not.toHaveBeenCalled();
expect(document.activeElement).toBe(next);
runHandback();
expect(closeAutoFocus).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(next);
});
28 changes: 24 additions & 4 deletions web/src/components/ui/select.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import { Select as SelectPrimitive } from "radix-ui";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import type { ComponentProps } from "react";
import { createContext, useContext, useRef, type ComponentProps, type RefObject } from "react";
import { cn } from "../../lib/utils";
import { useLayerOpen } from "./layer";
import { useLayerOpen, useReturnFocus } from "./layer";
import { menuContent, menuItem, menuLabel, menuSeparator } from "./menu-styles";

/** The open state and trigger of one Select, so its content hands the keyboard back through the shell's guard. */
const SelectLayerContext = createContext<{ open: boolean; trigger: RefObject<HTMLButtonElement | null> } | null>(null);

function Select({ open, defaultOpen, onOpenChange, ...props }: ComponentProps<typeof SelectPrimitive.Root>) {
const [current, change] = useLayerOpen(open, defaultOpen, onOpenChange);
return <SelectPrimitive.Root data-slot="select" open={current} onOpenChange={change} {...props} />;
const trigger = useRef<HTMLButtonElement>(null);
return (
<SelectLayerContext.Provider value={{ open: current, trigger }}>
<SelectPrimitive.Root data-slot="select" open={current} onOpenChange={change} {...props} />
</SelectLayerContext.Provider>
);
}

function SelectGroup(props: ComponentProps<typeof SelectPrimitive.Group>) {
Expand All @@ -19,8 +27,10 @@ function SelectValue(props: ComponentProps<typeof SelectPrimitive.Value>) {
}

function SelectTrigger({ className, size = "default", children, ...props }: ComponentProps<typeof SelectPrimitive.Trigger> & { size?: "sm" | "default" }) {
const layer = useContext(SelectLayerContext);
return (
<SelectPrimitive.Trigger
ref={layer?.trigger}
data-slot="select-trigger"
data-size={size}
className={cn(
Expand All @@ -37,14 +47,24 @@ function SelectTrigger({ className, size = "default", children, ...props }: Comp
);
}

function SelectContent({ className, children, position = "popper", ...props }: ComponentProps<typeof SelectPrimitive.Content>) {
function SelectContent({ className, children, position = "popper", onCloseAutoFocus, ...props }: ComponentProps<typeof SelectPrimitive.Content>) {
const layer = useContext(SelectLayerContext);
const surface = useRef<HTMLDivElement>(null);
// Radix hands the keyboard to the trigger from a timer after the close, unconditionally;
// the shell's guard keeps a control or layer that took the keyboard in the meantime.
const returnFocus = useReturnFocus(layer?.open ?? false, { target: () => layer?.trigger.current ?? null, within: () => surface.current });
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={surface}
data-slot="select-content"
className={cn(menuContent, "relative max-h-(--radix-select-content-available-height)", position === "popper" && "w-full min-w-(--radix-select-trigger-width)", className)}
position={position}
sideOffset={position === "popper" ? 4 : undefined}
onCloseAutoFocus={(event) => {
onCloseAutoFocus?.(event);
if (!event.defaultPrevented) returnFocus(event);
}}
{...props}
>
<SelectPrimitive.ScrollUpButton className="flex cursor-default items-center justify-center py-xxs">
Expand Down
Loading