feat(ui): uniformise les droplist dynamiques sur le style du picker d'agent

Introduit SmallDropdown comme composant partagé et le fait adopter par
AgentsPanel, ModelServerSelect, OpenCodeModeFields, TemplateEditor et
TicketViewportSelect, pour que toutes les listes déroulantes dynamiques
(agent, modèle, template, viewport) partagent la même apparence que le
sélecteur d'agent de la création de ticket.

Refs #114

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-30 12:55:57 +02:00
parent fda4126a5f
commit 9b1ced50be
14 changed files with 550 additions and 360 deletions

View File

@ -16,7 +16,7 @@
import { useEffect, useState } from "react";
import { Button, Input, Panel, Spinner, cn } from "@/shared";
import { Button, Input, Panel, SmallDropdown, Spinner, cn } from "@/shared";
import { TerminalView } from "@/features/terminals/TerminalView";
import { AnnouncementsPreview } from "@/features/announcements";
import { useDrift } from "@/features/templates/useDrift";
@ -287,25 +287,19 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
>
Template
</label>
<select
<SmallDropdown
id="agent-template-select"
aria-label="agent template"
value={newTemplateId}
onChange={(e) => setNewTemplateId(e.target.value)}
className={cn(
"h-9 w-full rounded-md bg-raised px-3 text-sm text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
onChange={setNewTemplateId}
className="w-full"
disabled={vm.busy}
>
<option value="">(none / from scratch)</option>
{templates.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</select>
size="md"
options={[
{ value: "", label: "(none / from scratch)" },
...templates.map((t) => ({ value: t.id, label: t.name })),
]}
/>
</div>
{/* Profile selector — hidden when a template is chosen */}
@ -321,24 +315,21 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
)}
</label>
{vm.profiles.length > 0 ? (
<select
<SmallDropdown
id="agent-profile-select"
aria-label="agent profile"
value={newProfileId}
onChange={(e) => setNewProfileId(e.target.value)}
className={cn(
"h-9 w-full rounded-md bg-raised px-3 text-sm text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
>
<option value=""> select profile </option>
{vm.profiles.map((p) => (
<option key={p.id} value={p.id}>
{profileLabel(p)}
</option>
))}
</select>
onChange={setNewProfileId}
className="w-full"
size="md"
options={[
{ value: "", label: "— select profile —" },
...vm.profiles.map((p) => ({
value: p.id,
label: profileLabel(p),
})),
]}
/>
) : (
<Input
id="agent-profile-select"
@ -469,31 +460,25 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
{/* Profile hot-swap selector (Chantier A). Changing the
engine abandons the conversation history → confirmation. */}
{vm.profiles.length > 0 && (
<select
<SmallDropdown
aria-label={`profile for ${a.name}`}
value={a.profileId}
disabled={vm.busy}
onChange={(e) => {
const profileId = e.target.value;
onChange={(profileId) => {
if (profileId && profileId !== a.profileId) {
setPendingProfileChange({ agentId: a.id, profileId });
}
}}
className={cn(
"h-8 rounded-md bg-raised px-2 text-xs text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
>
{vm.profiles.every((p) => p.id !== a.profileId) && (
<option value={a.profileId}>{a.profileId}</option>
)}
{vm.profiles.map((p) => (
<option key={p.id} value={p.id}>
{profileLabel(p)}
</option>
))}
</select>
options={[
...(vm.profiles.every((p) => p.id !== a.profileId)
? [{ value: a.profileId, label: a.profileId }]
: []),
...vm.profiles.map((p) => ({
value: p.id,
label: profileLabel(p),
})),
]}
/>
)}
{agentDrift && (
<Button
@ -612,29 +597,26 @@ export function AgentsPanel({ projectId, projectRoot = "" }: AgentsPanelProps) {
{/* Assign selector */}
<div className="flex items-end gap-2">
<select
<SmallDropdown
aria-label="skill to assign"
value={skillToAssign}
onChange={(e) => setSkillToAssign(e.target.value)}
onChange={setSkillToAssign}
disabled={vm.busy}
className={cn(
"h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
>
<option value=""> assign a skill </option>
{skills
className="min-w-0 flex-1"
size="md"
options={[
{ value: "", label: "— assign a skill —" },
...skills
.filter(
(s) =>
!selectedAgent.skills.some((r) => r.skillId === s.id),
)
.map((s) => (
<option key={s.id} value={s.id}>
{s.name} ({s.scope})
</option>
))}
</select>
.map((s) => ({
value: s.id,
label: `${s.name} (${s.scope})`,
})),
]}
/>
<Button
variant="primary"
aria-label="assign skill"

View File

@ -73,6 +73,17 @@ async function waitForIdle() {
});
}
function openDropdown(label: string | RegExp) {
const trigger = screen.getByLabelText(label);
fireEvent.click(trigger);
return trigger;
}
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
openDropdown(label);
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
/** Types a name into the agent name field, optionally selects a profile, and clicks Create. */
async function createAgent(name: string, profileId?: string) {
await waitForIdle();
@ -84,7 +95,7 @@ async function createAgent(name: string, profileId?: string) {
if (profileId) {
const profileInput = screen.queryByLabelText("agent profile");
if (profileInput) {
fireEvent.change(profileInput, { target: { value: profileId } });
chooseDropdownOption("agent profile", profileId);
}
}
@ -169,9 +180,10 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
renderPanel(new MockAgentGateway(), profile);
await waitForIdle();
const labels = Array.from(
screen.getByLabelText("agent profile").querySelectorAll("option"),
).map((option) => option.textContent);
openDropdown("agent profile");
const labels = screen
.getAllByRole("option")
.map((option) => option.textContent);
expect(labels).toContain("Codex fast · gpt-5-mini");
expect(labels).toContain("Claude deep · claude-opus-4-8");
@ -319,8 +331,7 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
await waitForIdle();
// Select the template in the dropdown
const templateSelect = screen.getByLabelText("agent template") as HTMLSelectElement;
fireEvent.change(templateSelect, { target: { value: t.id } });
chooseDropdownOption("agent template", "My Template");
// Fill agent name
fireEvent.change(screen.getByLabelText("agent name"), {
@ -359,9 +370,8 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
renderPanel(new MockAgentGateway(), profile);
await waitForIdle();
// The select element should contain the profile option.
const select = screen.getByLabelText("agent profile") as HTMLSelectElement;
const options = Array.from(select.options).map((o) => o.text);
openDropdown("agent profile");
const options = screen.getAllByRole("option").map((o) => o.textContent);
expect(options).toContain("Claude Code");
});
@ -375,8 +385,8 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
renderPanel(new MockAgentGateway(), profile);
await waitForIdle();
const select = screen.getByLabelText("agent profile") as HTMLSelectElement;
const options = Array.from(select.options).map((o) => o.text);
openDropdown("agent profile");
const options = screen.getAllByRole("option").map((o) => o.textContent ?? "");
expect(options.some((text) => text.includes("OpenCode Local Durable"))).toBe(true);
});
});
@ -506,8 +516,7 @@ describe("AgentsPanel profile hot-swap (A2)", () => {
await waitForIdle();
await screen.findByText("Swap");
const select = screen.getByLabelText("profile for Swap") as HTMLSelectElement;
fireEvent.change(select, { target: { value: "prof-2" } });
chooseDropdownOption("profile for Swap", /Codex CLI/);
// No gateway call yet — only the dialog appears.
expect(swapSpy).not.toHaveBeenCalled();
@ -523,9 +532,7 @@ describe("AgentsPanel profile hot-swap (A2)", () => {
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
chooseDropdownOption("profile for Swap", /Codex CLI/);
fireEvent.click(
screen.getByRole("button", { name: "cancel profile change" }),
);
@ -546,9 +553,7 @@ describe("AgentsPanel profile hot-swap (A2)", () => {
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
chooseDropdownOption("profile for Swap", /Codex CLI/);
fireEvent.click(
screen.getByRole("button", { name: "confirm profile change" }),
);
@ -571,9 +576,7 @@ describe("AgentsPanel profile hot-swap (A2)", () => {
await waitForIdle();
await screen.findByText("Swap");
fireEvent.change(screen.getByLabelText("profile for Swap"), {
target: { value: "prof-2" },
});
chooseDropdownOption("profile for Swap", /Codex CLI/);
const dialog = screen.getByRole("dialog");
const text = dialog.textContent ?? "";

View File

@ -25,6 +25,11 @@ import { DIProvider } from "@/app/di";
import { FirstRunWizard } from "./FirstRunWizard";
import { DETECT_TIMEOUT_MS } from "./useFirstRun";
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
fireEvent.click(screen.getByLabelText(label));
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
function renderWizard(
profile: MockProfileGateway = new MockProfileGateway(),
onDone = vi.fn(),
@ -474,11 +479,11 @@ describe("FirstRunWizard — OpenCode cloud provider (ticket #92)", () => {
await waitForLoaded();
fireEvent.click(screen.getByRole("radio", { name: "Provider cloud" }));
const providerSelect = await screen.findByLabelText(`${OPENCODE} provider`);
const modelSelect = screen.getByLabelText(`${OPENCODE} model`) as HTMLSelectElement;
await screen.findByLabelText(`${OPENCODE} provider`);
const modelSelect = screen.getByLabelText(`${OPENCODE} model`) as HTMLButtonElement;
expect(modelSelect.disabled).toBe(true);
fireEvent.change(providerSelect, { target: { value: "anthropic" } });
chooseDropdownOption(`${OPENCODE} provider`, "Anthropic");
expect(modelSelect.disabled).toBe(false);
const saveButton = screen.getByRole("button", {
@ -486,7 +491,7 @@ describe("FirstRunWizard — OpenCode cloud provider (ticket #92)", () => {
}) as HTMLButtonElement;
expect(saveButton.disabled).toBe(true);
fireEvent.change(modelSelect, { target: { value: "claude-sonnet-5" } });
chooseDropdownOption(`${OPENCODE} model`, "claude-sonnet-5");
expect(saveButton.disabled).toBe(true);
fireEvent.change(screen.getByLabelText(`${OPENCODE} api key`), {
@ -500,12 +505,9 @@ describe("FirstRunWizard — OpenCode cloud provider (ticket #92)", () => {
await waitForLoaded();
fireEvent.click(screen.getByRole("radio", { name: "Provider cloud" }));
fireEvent.change(await screen.findByLabelText(`${OPENCODE} provider`), {
target: { value: "anthropic" },
});
fireEvent.change(screen.getByLabelText(`${OPENCODE} model`), {
target: { value: "claude-sonnet-5" },
});
await screen.findByLabelText(`${OPENCODE} provider`);
chooseDropdownOption(`${OPENCODE} provider`, "Anthropic");
chooseDropdownOption(`${OPENCODE} model`, "claude-sonnet-5");
const apiKeyInput = screen.getByLabelText(
`${OPENCODE} api key`,
) as HTMLInputElement;
@ -547,8 +549,8 @@ describe("FirstRunWizard — OpenCode custom cloud provider (ticket #92, dynamic
async function goToCloudCustomMode() {
fireEvent.click(screen.getByRole("radio", { name: "Provider cloud" }));
const providerSelect = await screen.findByLabelText(`${OPENCODE} provider`);
fireEvent.change(providerSelect, { target: { value: "__custom__" } });
await screen.findByLabelText(`${OPENCODE} provider`);
chooseDropdownOption(`${OPENCODE} provider`, "Autre / personnalisé…");
}
it("selecting 'Autre / personnalisé' swaps the cascade for free-form fields", async () => {
@ -904,8 +906,8 @@ describe("FirstRunWizard — several local OpenCode profiles (F36)", () => {
expect(
screen.queryByLabelText(`${CLONE1} local model server id`),
).toBeNull();
const select = await screen.findByLabelText(`${CLONE1} local model server`);
fireEvent.change(select, { target: { value: server.id } });
await screen.findByLabelText(`${CLONE1} local model server`);
chooseDropdownOption(`${CLONE1} local model server`, /Local A/);
fireEvent.click(screen.getByRole("button", { name: "Save and continue" }));
await waitFor(async () => {

View File

@ -8,7 +8,7 @@ import type {
OpenCodeProviderCatalogEntry,
} from "@/domain";
import { useGateways } from "@/app/di";
import { Button, IconButton, Input, cn } from "@/shared";
import { Button, IconButton, Input, SmallDropdown, cn } from "@/shared";
import { ModelServerSelect } from "@/features/model-servers";
import {
defaultOpenCodeConfig,
@ -300,12 +300,11 @@ function OpenCodeProviderFields({
className="h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"
/>
)}
<select
<SmallDropdown
aria-label={`${profile.name} provider`}
value={providerId}
disabled={!catalogReady}
onChange={(e) => {
const v = e.target.value;
onChange={(v) => {
if (v === CUSTOM_PROVIDER_VALUE) {
setMode("custom");
setProviderId("");
@ -316,22 +315,27 @@ function OpenCodeProviderFields({
}
setFieldErrors((prev) => ({ ...prev, providerId: undefined }));
}}
className={cn(
"h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none",
"disabled:cursor-not-allowed disabled:opacity-50",
fieldErrors.providerId ? "border-danger" : "border-border",
)}
>
<option value="" disabled>
{catalog.loading ? "Chargement des providers…" : "Choisir un provider…"}
</option>
{filteredProviders.map((p) => (
<option key={p.providerId} value={p.providerId}>
{p.displayName}
</option>
))}
<option value={CUSTOM_PROVIDER_VALUE}>Autre / personnalisé</option>
</select>
className="w-full"
size="md"
invalid={Boolean(fieldErrors.providerId)}
options={[
{
value: "",
label: catalog.loading
? "Chargement des providers…"
: "Choisir un provider…",
disabled: true,
},
...filteredProviders.map((p) => ({
value: p.providerId,
label: p.displayName,
})),
{
value: CUSTOM_PROVIDER_VALUE,
label: "Autre / personnalisé…",
},
]}
/>
{fieldErrors.providerId && (
<small className="text-xs text-danger">{fieldErrors.providerId}</small>
)}
@ -339,29 +343,26 @@ function OpenCodeProviderFields({
<label className="flex flex-col gap-1">
<Caption>Modèle</Caption>
<select
<SmallDropdown
aria-label={`${profile.name} model`}
value={model}
disabled={providerId.length === 0}
onChange={(e) => {
setModel(e.target.value);
onChange={(next) => {
setModel(next);
setFieldErrors((prev) => ({ ...prev, model: undefined }));
}}
className={cn(
"h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none",
"disabled:cursor-not-allowed disabled:opacity-50",
fieldErrors.model ? "border-danger" : "border-border",
)}
>
<option value="" disabled>
{providerId.length === 0 ? "—" : "Choisir un modèle…"}
</option>
{models.map((m) => (
<option key={m} value={m}>
{m}
</option>
))}
</select>
className="w-full"
size="md"
invalid={Boolean(fieldErrors.model)}
options={[
{
value: "",
label: providerId.length === 0 ? "—" : "Choisir un modèle…",
disabled: true,
},
...models.map((m) => ({ value: m, label: m })),
]}
/>
{fieldErrors.model && (
<small className="text-xs text-danger">{fieldErrors.model}</small>
)}

View File

@ -22,6 +22,11 @@ function renderSettings(
};
}
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
fireEvent.click(screen.getByLabelText(label));
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
async function waitReady() {
await waitFor(() =>
expect(
@ -191,12 +196,17 @@ describe("ProfilesSettings", () => {
expect(screen.getByText("Local A")).toBeTruthy();
await createProfile();
const select = await screen.findByLabelText(
await screen.findByLabelText(
"OpenCode + llama.cpp copy local model server",
);
fireEvent.change(select, { target: { value: server.id } });
chooseDropdownOption(
"OpenCode + llama.cpp copy local model server",
/Local A/,
);
const profileRow = select.closest("li");
const profileRow = screen
.getByLabelText("OpenCode + llama.cpp copy local model server")
.closest("li");
expect(profileRow).not.toBeNull();
fireEvent.click(
within(profileRow as HTMLElement).getByRole("button", {

View File

@ -6,7 +6,7 @@
*/
import type { LocalModelServerConfig } from "@/domain";
import { cn } from "@/shared";
import { SmallDropdown } from "@/shared";
/** The sentinel option value standing for "no managed server". */
const NONE = "";
@ -34,24 +34,20 @@ export function ModelServerSelect({
value !== undefined && !servers.some((s) => s.id === value);
return (
<select
<SmallDropdown
aria-label={ariaLabel}
value={value ?? NONE}
onChange={(e) => onChange(e.target.value === NONE ? undefined : e.target.value)}
className={cn(
"h-8 rounded-md bg-raised px-2 text-xs text-content",
"border border-border outline-none focus:border-primary",
)}
>
<option value={NONE}>None (external endpoint)</option>
{servers.map((s) => (
<option key={s.id} value={s.id}>
{s.name} {s.servedModelName}
</option>
))}
{missing && (
<option value={value}>{value} (unknown / removed)</option>
)}
</select>
onChange={(next) => onChange(next === NONE ? undefined : next)}
options={[
{ value: NONE, label: "None (external endpoint)" },
...servers.map((s) => ({
value: s.id,
label: `${s.name}${s.servedModelName}`,
})),
...(missing && value !== undefined
? [{ value, label: `${value} (unknown / removed)` }]
: []),
]}
/>
);
}

View File

@ -40,6 +40,11 @@ const SERVER: LocalModelServerConfig = {
stopPolicy: "stopOnAppExit",
};
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
fireEvent.click(screen.getByLabelText(label));
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
function setup(modelServer = new MockModelServerGateway()) {
const gateways = { modelServer } as unknown as Gateways;
const wrapper = ({ children }: { children: React.ReactNode }) => (
@ -433,9 +438,10 @@ describe("ModelServerSelect (F35)", () => {
onChange={(id) => (picked = id)}
/>,
);
const select = screen.getByLabelText("local model server") as HTMLSelectElement;
expect(select.value).toBe("");
fireEvent.change(select, { target: { value: SERVER.id } });
expect(screen.getByLabelText("local model server").textContent).toContain(
"None (external endpoint)",
);
chooseDropdownOption("local model server", /Local A/);
expect(picked).toBe(SERVER.id);
});
@ -448,9 +454,7 @@ describe("ModelServerSelect (F35)", () => {
onChange={(id) => (picked = id)}
/>,
);
fireEvent.change(screen.getByLabelText("local model server"), {
target: { value: "" },
});
chooseDropdownOption("local model server", "None (external endpoint)");
expect(picked).toBeUndefined();
});

View File

@ -58,6 +58,11 @@ async function waitForSkillsIdle() {
});
}
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
fireEvent.click(screen.getByLabelText(label));
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
/** Opens the SkillEditor, fills it, and saves. */
async function createSkill(
name: string,
@ -192,9 +197,7 @@ describe("Skill assignment (AgentsPanel + MockSkillGateway)", () => {
// Choose the skill and assign
const sk = (await skill.listSkills(PROJECT_ID, "project"))[0];
fireEvent.change(screen.getByLabelText("skill to assign"), {
target: { value: sk.id },
});
chooseDropdownOption("skill to assign", "Deploy (project)");
fireEvent.click(screen.getByRole("button", { name: "assign skill" }));
// The agent record now carries the skill ref

View File

@ -16,7 +16,7 @@ import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { AgentProfile, Template } from "@/domain";
import { Button, Input, cn } from "@/shared";
import { Button, Input, SmallDropdown, cn } from "@/shared";
export interface TemplateEditorProps {
/**
@ -114,25 +114,19 @@ export function TemplateEditor({
Default profile
</label>
{profiles.length > 0 ? (
<select
<SmallDropdown
id="te-profile"
aria-label="template default profile"
value={defaultProfileId}
onChange={(e) => setDefaultProfileId(e.target.value)}
onChange={setDefaultProfileId}
disabled={busy}
className={cn(
"h-9 w-full rounded-md bg-raised px-3 text-sm text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
)}
>
<option value=""> none </option>
{profiles.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
className="w-full"
size="md"
options={[
{ value: "", label: "— none —" },
...profiles.map((p) => ({ value: p.id, label: p.name })),
]}
/>
) : (
<Input
id="te-profile"

View File

@ -86,6 +86,11 @@ async function waitForAgentsIdle() {
});
}
function chooseDropdownOption(label: string | RegExp, optionName: string | RegExp) {
fireEvent.click(screen.getByLabelText(label));
fireEvent.click(screen.getByRole("option", { name: optionName }));
}
/**
* Opens the TemplateEditor overlay, fills the create-template form, and saves it.
* Adapted for the new fullscreen-editor flow:
@ -115,9 +120,12 @@ async function createTemplate(
target: { value: content },
});
if (profileId) {
fireEvent.change(screen.getByLabelText("template default profile"), {
target: { value: profileId },
});
const profileField = screen.getByLabelText("template default profile");
if (profileField.tagName === "INPUT") {
fireEvent.change(profileField, { target: { value: profileId } });
} else {
chooseDropdownOption("template default profile", profileId);
}
}
// Save via the "Save template" button (aria-label on the submit button)

View File

@ -1,13 +1,6 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { SmallDropdown, type SmallDropdownOption } from "@/shared";
import { cn, zIndex } from "@/shared";
export interface TicketViewportSelectOption {
value: string;
label: string;
disabled?: boolean;
}
export type TicketViewportSelectOption = SmallDropdownOption;
export interface TicketViewportSelectProps {
ariaLabel?: string;
@ -19,18 +12,6 @@ export interface TicketViewportSelectProps {
disabled?: boolean;
}
interface PopupPosition {
top: number;
left: number;
width: number;
maxHeight: number;
placement: "top" | "bottom";
}
const VIEWPORT_MARGIN = 8;
const MIN_POPUP_HEIGHT = 96;
const MAX_POPUP_HEIGHT = 280;
export function TicketViewportSelect({
ariaLabel: ariaLabelProp,
"aria-label": ariaLabelAttribute,
@ -40,153 +21,14 @@ export function TicketViewportSelect({
className,
disabled = false,
}: TicketViewportSelectProps) {
const triggerRef = useRef<HTMLButtonElement | null>(null);
const popupRef = useRef<HTMLDivElement | null>(null);
const [open, setOpen] = useState(false);
const [position, setPosition] = useState<PopupPosition | null>(null);
const selected = options.find((option) => option.value === value) ?? options[0];
const ariaLabel = ariaLabelAttribute ?? ariaLabelProp ?? "select option";
const updatePosition = useCallback(() => {
const trigger = triggerRef.current;
if (!trigger) return;
const rect = trigger.getBoundingClientRect();
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
const popupWidth = Math.max(rect.width, 160);
const spaceBelow = viewportHeight - rect.bottom - VIEWPORT_MARGIN;
const spaceAbove = rect.top - VIEWPORT_MARGIN;
const placement =
spaceBelow < MIN_POPUP_HEIGHT && spaceAbove > spaceBelow ? "top" : "bottom";
const available = Math.max(
MIN_POPUP_HEIGHT,
placement === "top" ? spaceAbove : spaceBelow,
);
const maxHeight = Math.min(MAX_POPUP_HEIGHT, available);
const left = Math.min(
Math.max(VIEWPORT_MARGIN, rect.left),
Math.max(VIEWPORT_MARGIN, viewportWidth - popupWidth - VIEWPORT_MARGIN),
);
const top =
placement === "top"
? Math.max(VIEWPORT_MARGIN, rect.top - maxHeight - 4)
: Math.min(viewportHeight - VIEWPORT_MARGIN, rect.bottom + 4);
setPosition({ top, left, width: popupWidth, maxHeight, placement });
}, []);
useLayoutEffect(() => {
if (!open) return;
updatePosition();
}, [open, updatePosition]);
useEffect(() => {
if (!open) return;
function onPointerDown(event: PointerEvent) {
const target = event.target as Node | null;
if (
target &&
(triggerRef.current?.contains(target) || popupRef.current?.contains(target))
) {
return;
}
setOpen(false);
}
function onKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
setOpen(false);
triggerRef.current?.focus();
}
}
const onViewportChange = () => {
updatePosition();
};
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
window.addEventListener("resize", onViewportChange);
window.addEventListener("scroll", onViewportChange, true);
window.visualViewport?.addEventListener("resize", onViewportChange);
window.visualViewport?.addEventListener("scroll", onViewportChange);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
window.removeEventListener("resize", onViewportChange);
window.removeEventListener("scroll", onViewportChange, true);
window.visualViewport?.removeEventListener("resize", onViewportChange);
window.visualViewport?.removeEventListener("scroll", onViewportChange);
};
}, [open, updatePosition]);
return (
<>
<button
ref={triggerRef}
type="button"
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
<SmallDropdown
aria-label={ariaLabelAttribute ?? ariaLabelProp}
value={value}
options={options}
onChange={onChange}
className={className}
disabled={disabled}
onClick={() => setOpen((current) => !current)}
className={cn(
"inline-flex h-8 items-center justify-between gap-2 rounded-md bg-raised px-2 text-xs text-content",
"border border-border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
>
<span className="min-w-0 truncate">{selected?.label ?? ""}</span>
<span aria-hidden="true" className="text-muted"></span>
</button>
{open &&
position &&
createPortal(
<div
ref={popupRef}
role="listbox"
aria-label={ariaLabel}
data-placement={position.placement}
className="fixed overflow-y-auto rounded-md border border-border bg-surface py-1 shadow-xl"
style={{
top: position.top,
left: position.left,
width: position.width,
maxHeight: position.maxHeight,
zIndex: zIndex.transientPopup,
}}
>
{options.map((option) => (
<button
key={option.value}
type="button"
role="option"
aria-selected={option.value === value}
disabled={option.disabled}
onClick={() => {
if (option.disabled) return;
onChange(option.value);
setOpen(false);
triggerRef.current?.focus();
}}
className={cn(
"flex min-h-8 w-full items-center px-2 text-left text-xs text-content",
"hover:bg-raised focus:bg-raised focus:outline-none",
option.value === value && "bg-raised",
option.disabled && "cursor-not-allowed opacity-50",
)}
>
<span className="min-w-0 truncate">{option.label}</span>
</button>
))}
</div>,
document.body,
)}
</>
/>
);
}

View File

@ -43,3 +43,6 @@ export type { MenuBarProps, MenuBarMenu, MenuBarItem } from "./ui/MenuBar";
export { DockRegion } from "./ui/DockRegion";
export type { DockRegionProps, DockSide } from "./ui/DockRegion";
export { SmallDropdown } from "./ui/SmallDropdown";
export type { SmallDropdownProps, SmallDropdownOption } from "./ui/SmallDropdown";

View File

@ -0,0 +1,296 @@
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { cn } from "@/shared/lib/cn";
import { zIndex } from "./zIndex";
export interface SmallDropdownOption {
value: string;
label: string;
disabled?: boolean;
}
export interface SmallDropdownProps {
ariaLabel?: string;
"aria-label"?: string;
value: string;
options: SmallDropdownOption[];
onChange: (value: string) => void;
id?: string;
className?: string;
disabled?: boolean;
size?: "sm" | "md";
invalid?: boolean;
}
interface PopupPosition {
top: number;
left: number;
width: number;
maxHeight: number;
placement: "top" | "bottom";
}
const VIEWPORT_MARGIN = 8;
const MIN_POPUP_HEIGHT = 96;
const MAX_POPUP_HEIGHT = 280;
function firstEnabledIndex(options: SmallDropdownOption[]): number {
return options.findIndex((option) => !option.disabled);
}
function nextEnabledIndex(
options: SmallDropdownOption[],
from: number,
direction: 1 | -1,
): number {
if (options.length === 0) return -1;
for (let offset = 1; offset <= options.length; offset += 1) {
const index = (from + offset * direction + options.length) % options.length;
if (!options[index]?.disabled) return index;
}
return -1;
}
export function SmallDropdown({
ariaLabel: ariaLabelProp,
"aria-label": ariaLabelAttribute,
value,
options,
onChange,
id,
className,
disabled = false,
size = "sm",
invalid = false,
}: SmallDropdownProps) {
const idBase = useId();
const triggerRef = useRef<HTMLButtonElement | null>(null);
const popupRef = useRef<HTMLDivElement | null>(null);
const [open, setOpen] = useState(false);
const [position, setPosition] = useState<PopupPosition | null>(null);
const selectedIndex = options.findIndex((option) => option.value === value);
const selected = selectedIndex >= 0 ? options[selectedIndex] : options[0];
const [activeIndex, setActiveIndex] = useState(
selectedIndex >= 0 ? selectedIndex : firstEnabledIndex(options),
);
const ariaLabel = ariaLabelAttribute ?? ariaLabelProp ?? "select option";
const updatePosition = useCallback(() => {
const trigger = triggerRef.current;
if (!trigger) return;
const rect = trigger.getBoundingClientRect();
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
const popupWidth = Math.max(rect.width, 160);
const spaceBelow = viewportHeight - rect.bottom - VIEWPORT_MARGIN;
const spaceAbove = rect.top - VIEWPORT_MARGIN;
const placement =
spaceBelow < MIN_POPUP_HEIGHT && spaceAbove > spaceBelow ? "top" : "bottom";
const available = Math.max(
MIN_POPUP_HEIGHT,
placement === "top" ? spaceAbove : spaceBelow,
);
const maxHeight = Math.min(MAX_POPUP_HEIGHT, available);
const left = Math.min(
Math.max(VIEWPORT_MARGIN, rect.left),
Math.max(VIEWPORT_MARGIN, viewportWidth - popupWidth - VIEWPORT_MARGIN),
);
const top =
placement === "top"
? Math.max(VIEWPORT_MARGIN, rect.top - maxHeight - 4)
: Math.min(viewportHeight - VIEWPORT_MARGIN, rect.bottom + 4);
setPosition({ top, left, width: popupWidth, maxHeight, placement });
}, []);
const openPopup = useCallback(() => {
if (disabled) return;
const nextActive = selectedIndex >= 0 ? selectedIndex : firstEnabledIndex(options);
setActiveIndex(nextActive);
setOpen(true);
}, [disabled, options, selectedIndex]);
const closePopup = useCallback(() => {
setOpen(false);
}, []);
const selectOption = useCallback(
(option: SmallDropdownOption | undefined) => {
if (!option || option.disabled) return;
onChange(option.value);
closePopup();
triggerRef.current?.focus();
},
[closePopup, onChange],
);
useLayoutEffect(() => {
if (!open) return;
updatePosition();
}, [open, updatePosition]);
useEffect(() => {
if (!open) return;
function onPointerDown(event: PointerEvent) {
const target = event.target as Node | null;
if (
target &&
(triggerRef.current?.contains(target) || popupRef.current?.contains(target))
) {
return;
}
closePopup();
}
function onKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
closePopup();
triggerRef.current?.focus();
return;
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
setActiveIndex((current) =>
nextEnabledIndex(options, current, event.key === "ArrowDown" ? 1 : -1),
);
return;
}
if (event.key === "Home") {
event.preventDefault();
setActiveIndex(firstEnabledIndex(options));
return;
}
if (event.key === "End") {
event.preventDefault();
setActiveIndex(nextEnabledIndex(options, 0, -1));
return;
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
selectOption(options[activeIndex]);
}
}
const onViewportChange = () => {
updatePosition();
};
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
window.addEventListener("resize", onViewportChange);
window.addEventListener("scroll", onViewportChange, true);
window.visualViewport?.addEventListener("resize", onViewportChange);
window.visualViewport?.addEventListener("scroll", onViewportChange);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
window.removeEventListener("resize", onViewportChange);
window.removeEventListener("scroll", onViewportChange, true);
window.visualViewport?.removeEventListener("resize", onViewportChange);
window.visualViewport?.removeEventListener("scroll", onViewportChange);
};
}, [activeIndex, closePopup, open, options, selectOption, updatePosition]);
const popupId = `${idBase}-listbox`;
const activeOptionId =
open && activeIndex >= 0 ? `${idBase}-option-${activeIndex}` : undefined;
return (
<>
<button
ref={triggerRef}
id={id}
type="button"
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? popupId : undefined}
aria-activedescendant={activeOptionId}
aria-invalid={invalid ? "true" : undefined}
disabled={disabled}
onClick={() => (open ? closePopup() : openPopup())}
onKeyDown={(event) => {
if (
!open &&
(event.key === "ArrowDown" ||
event.key === "ArrowUp" ||
event.key === "Enter" ||
event.key === " ")
) {
event.preventDefault();
openPopup();
}
}}
className={cn(
"inline-flex items-center justify-between gap-2 rounded-md bg-raised text-content",
"border outline-none transition-colors",
"focus:border-primary disabled:cursor-not-allowed disabled:opacity-50",
invalid ? "border-danger" : "border-border",
size === "md" ? "h-9 px-3 text-sm" : "h-8 px-2 text-xs",
className,
)}
>
<span className="min-w-0 truncate">{selected?.label ?? ""}</span>
<span aria-hidden="true" className="text-muted">
</span>
</button>
{open &&
position &&
createPortal(
<div
ref={popupRef}
id={popupId}
role="listbox"
aria-label={ariaLabel}
data-placement={position.placement}
className="fixed overflow-y-auto rounded-md border border-border bg-surface py-1 shadow-xl"
style={{
top: position.top,
left: position.left,
width: position.width,
maxHeight: position.maxHeight,
zIndex: zIndex.transientPopup,
}}
>
{options.map((option, index) => (
<button
key={`${option.value}-${index}`}
id={`${idBase}-option-${index}`}
type="button"
role="option"
aria-selected={option.value === value}
disabled={option.disabled}
onMouseEnter={() => {
if (!option.disabled) setActiveIndex(index);
}}
onClick={() => selectOption(option)}
className={cn(
"flex min-h-8 w-full items-center px-2 text-left text-content",
"hover:bg-raised focus:bg-raised focus:outline-none",
size === "md" ? "text-sm" : "text-xs",
(option.value === value || index === activeIndex) && "bg-raised",
option.disabled && "cursor-not-allowed opacity-50",
)}
>
<span className="min-w-0 truncate">{option.label}</span>
</button>
))}
</div>,
document.body,
)}
</>
);
}

View File

@ -11,6 +11,7 @@ import { render, screen, fireEvent } from "@testing-library/react";
import { Button } from "./Button";
import { Input } from "./Input";
import { Field } from "./Field";
import { SmallDropdown } from "./SmallDropdown";
import { Tabs } from "./Tabs";
describe("Button", () => {
@ -115,3 +116,48 @@ describe("Tabs", () => {
expect(onClose).toHaveBeenCalledWith("b");
});
});
describe("SmallDropdown", () => {
const options = [
{ value: "", label: "None" },
{ value: "a", label: "Alpha" },
{ value: "b", label: "Beta", disabled: true },
];
it("opens a listbox and reports the selected value", () => {
const onChange = vi.fn();
render(
<SmallDropdown
aria-label="test dropdown"
value=""
options={options}
onChange={onChange}
/>,
);
fireEvent.click(screen.getByLabelText("test dropdown"));
fireEvent.click(screen.getByRole("option", { name: "Alpha" }));
expect(onChange).toHaveBeenCalledWith("a");
expect(screen.queryByRole("listbox")).toBeNull();
});
it("supports keyboard selection and ignores disabled options", () => {
const onChange = vi.fn();
render(
<SmallDropdown
aria-label="test dropdown"
value=""
options={options}
onChange={onChange}
/>,
);
const trigger = screen.getByLabelText("test dropdown");
fireEvent.keyDown(trigger, { key: "ArrowDown" });
fireEvent.keyDown(document, { key: "ArrowDown" });
fireEvent.keyDown(document, { key: "Enter" });
expect(onChange).toHaveBeenCalledWith("a");
});
});