Keep the scratch language chooser usable in short windows (#4750)

The scratch file language chooser keeps its search field and list usable in short windows instead of overflowing.
This commit is contained in:
l0ng-ai
2026-11-20 19:40:24 +08:00
committed by GitHub
parent a1ab5b6c29
commit 844e290729
3 changed files with 144 additions and 31 deletions
+86
View File
@@ -0,0 +1,86 @@
import { expect, test } from "./fixtures";
test("the scratch language chooser fits short windows and keeps recents separate from search results", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 470, height: 400 });
const long = "Zebra Configuration Language for Regional Settlement and Reconciliation Pipelines";
await page.evaluate(async (long) => {
const scratch = "/src/features/scratch/scratches.ts";
const store = "/src/features/scratch/store.ts";
const actions = "/src/platform/actions.ts";
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
dataDir: async () => "/test-app-data",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
const n = String(i + 1).padStart(2, "0");
return { id: `config-${n}`, name: `Configuration ${n}`, ext: `cfg${n}` };
}),
{ id: "json", name: "JSON", ext: "json" },
{ id: "python", name: "Python", ext: "py" },
{ id: "zebra", name: long, ext: "zebra" },
],
open: async (path: string) => localStorage.setItem("scratch-layout-opened", path),
});
rememberLanguage("json");
rememberLanguage("python");
await (await import(/* @vite-ignore */ actions)).executeAction("file.newScratchFile");
}, long);
const dialog = page.getByRole("dialog", { name: "New Scratch File", exact: true });
const input = dialog.getByRole("textbox", { name: "Filter languages" });
await expect(input).toBeFocused();
const list = dialog.getByRole("listbox", { name: "Languages" });
for (let i = 0; i < 3; i++) await input.press("PageDown");
const last = list.getByRole("option", { name: long, exact: true });
await expect(last).toHaveAttribute("aria-selected", "true");
await expect
.poll(async () => {
const popup = (await dialog.boundingBox())!;
const item = (await last.boundingBox())!;
return item.y + item.height - popup.y - popup.height;
})
.toBeLessThanOrEqual(1);
await expect(last).toBeInViewport({ ratio: 0.99 });
await expect(last.getByTitle(long)).toBeVisible();
await expect(input).toBeInViewport({ ratio: 1 });
await input.fill("python");
const python = list.getByRole("option", { name: "Python", exact: true });
await expect(python).toHaveAttribute("aria-selected", "true");
await expect(list.getByRole("separator")).toHaveCount(0);
await input.fill("");
const divider = list.getByRole("separator");
await expect(divider).toBeVisible();
await expect(python).toHaveAttribute("aria-selected", "true");
await input.press("ArrowDown");
const json = list.getByRole("option", { name: "JSON", exact: true });
await expect(json).toHaveAttribute("aria-selected", "true");
await input.press("ArrowDown");
const first = list.getByRole("option", { name: "Configuration 01", exact: true });
await expect(first).toHaveAttribute("aria-selected", "true");
expect((await divider.boundingBox())!.y).toBeLessThan((await first.boundingBox())!.y);
expect(await input.getAttribute("aria-activedescendant")).toBe(await first.getAttribute("id"));
await page.setViewportSize({ width: 640, height: 520 });
await expect
.poll(async () => {
const bounds = (await dialog.boundingBox())!;
return Math.abs(bounds.x + bounds.width / 2 - 320);
})
.toBeLessThanOrEqual(1);
await expect(input).toBeFocused();
await input.fill("zzz");
await expect(dialog.getByText("No matching languages")).toBeVisible();
await input.fill("json");
await input.press("Enter");
await expect(dialog).toBeHidden();
await expect
.poll(() => page.evaluate(() => localStorage.getItem("scratch-layout-opened")))
.toBe("/test-app-data/scratches/scratch.json");
});
+22 -13
View File
@@ -1,31 +1,36 @@
.popup {
width: 280px;
width: 320px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
display: flex;
flex-direction: column;
outline: none;
padding-bottom: 4px;
min-height: 0;
padding-bottom: var(--space-1);
font-size: var(--fs-ui);
}
.header {
flex: none;
display: flex;
align-items: center;
height: var(--h-row);
padding: 0 10px;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.title {
flex: 1;
padding: var(--space-2) var(--space-3) var(--space-1);
color: var(--fg-strong);
line-height: 1.4;
}
.search {
margin: 0 8px 4px;
flex: none;
margin: 0 var(--space-2) var(--space-1);
border-bottom: 1px solid var(--border-popup);
}
.list {
max-height: 360px;
height: auto;
max-height: calc(20 * var(--h-list-row) + var(--space-2));
}
.divider {
width: 100%;
height: 1px;
background: var(--border-popup);
}
.row {
display: flex;
@@ -35,11 +40,15 @@
flex: 1;
}
.label {
min-width: 0;
color: var(--fg-emphasis);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.icon {
flex: none;
}
.active .label {
color: var(--fg-strong);
}
+36 -18
View File
@@ -1,4 +1,4 @@
import { useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { HighlightedText, Icon, List, Popup, SearchField, fileIconName, listNavigate, T } from "@/ui";
import { chooserRows, type LanguageRow, type ScratchLanguage } from "./model";
@@ -6,6 +6,8 @@ import { closeChooser, rememberLanguage, useScratch } from "./store";
import { createScratch } from "./scratches";
import styles from "./ScratchChooser.module.css";
const isDivider = (row: LanguageRow | null) => row === null;
/** Overlay: IDEA's "New Scratch File" popup — searchable languages, recent first. */
export function ScratchChooserHost() {
const languages = useScratch((s) => s.languages);
@@ -17,13 +19,22 @@ export function ScratchChooserHost() {
function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }) {
const recent = useScratch((s) => s.recent);
const inputRef = useRef<HTMLInputElement>(null);
const listId = useId();
const [filter, setFilter] = useState("");
const [active, setActive] = useState(0);
const rows = useMemo(() => chooserRows(languages, recent, filter), [languages, recent, filter]);
const rows = useMemo(() => {
const options = chooserRows(languages, recent, filter);
if (filter.trim()) return options;
const firstOther = options.findIndex(({ lang }) => !recent.includes(lang.id));
return firstOther > 0 ? [...options.slice(0, firstOther), null, ...options.slice(firstOther)] : options;
}, [languages, recent, filter]);
const current = Math.min(active, rows.length - 1);
const anchor = useMemo(() => ({ x: Math.max(16, window.innerWidth / 2 - 140), y: window.innerHeight / 5 }), []);
const anchor = useMemo(
() => ({ getBoundingClientRect: () => new DOMRect(window.innerWidth / 2, window.innerHeight / 5, 0, 0) }),
[],
);
const pick = (row: LanguageRow | undefined) => {
const pick = (row: LanguageRow | null | undefined) => {
if (!row) return;
closeChooser();
rememberLanguage(row.lang.id);
@@ -35,6 +46,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
const next = listNavigate(e.key === "Home" || e.key === "End" ? "" : e.key, {
items: rows,
active: current,
isSection: isDivider,
wrap: true,
});
if (next !== null) {
@@ -50,7 +62,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
<Popup
open
anchor={anchor}
placement="bottom-start"
placement="bottom"
onClose={closeChooser}
role="dialog"
aria-label="New Scratch File"
@@ -58,9 +70,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
>
<div className={styles.body}>
<div className={styles.header}>
<span className={styles.title}>
<T>New Scratch File</T>
</span>
<T>New Scratch File</T>
</div>
<SearchField
ref={inputRef}
@@ -69,6 +79,8 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
value={filter}
placeholder="Filter languages"
aria-label="Filter languages"
aria-controls={listId}
aria-activedescendant={rows[current] ? `${listId}-${current}` : undefined}
className={styles.search}
onChange={(value) => {
setFilter(value);
@@ -78,11 +90,15 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
onKeyDown={onKeyDown}
/>
<List
id={listId}
items={rows}
getKey={(r) => r.lang.id}
getKey={(r) => (r ? `language:${r.lang.id}` : "recent-divider")}
activeIndex={current}
onActiveChange={setActive}
onActivate={(r) => pick(r)}
onActivate={pick}
isSection={isDivider}
sectionHeight={8}
renderSection={() => <span role="separator" className={styles.divider} />}
focusable={false}
hoverSelects
className={styles.list}
@@ -92,14 +108,16 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
<T>No matching languages</T>
</div>
}
renderItem={(r, state) => (
<div className={clsx(styles.row, state.active && styles.active)} data-language={r.lang.id}>
<Icon name={fileIconName(`scratch.${r.lang.ext}`)} size={16} />
<span className={styles.label}>
<HighlightedText text={r.lang.name} indices={r.matches ?? undefined} />
</span>
</div>
)}
renderItem={(r, state) =>
r && (
<div className={clsx(styles.row, state.active && styles.active)} data-language={r.lang.id}>
<Icon name={fileIconName(`scratch.${r.lang.ext}`)} size={16} className={styles.icon} />
<span className={styles.label} title={r.lang.name}>
<HighlightedText text={r.lang.name} indices={r.matches ?? undefined} />
</span>
</div>
)
}
/>
</div>
</Popup>