test(canvas/chat): add AttachmentLightbox coverage (13 cases) #598

Closed
core-uiux wants to merge 3 commits from test/attachment-lightbox-coverage into main
4 changed files with 951 additions and 3 deletions

View File

@ -0,0 +1,275 @@
// @vitest-environment jsdom
/**
* AttachmentAudio inline native HTML5 <audio> player for chat attachments.
*
* Per RFC #2991 PR-2: platform-auth URIs fetch bytes Blob ObjectURL;
* external URIs use the raw URL directly. State machine: idle loading
* ready/error. Loading skeleton shown while fetching. Error falls back to
* AttachmentChip. Blob URL cleaned up on unmount / re-run.
*
* NOTE: No @testing-library/jest-dom import use DOM APIs for assertions.
*
* Covers:
* - Renders loading skeleton with aria-label while fetching
* - Renders <audio> element with correct src when ready
* - Error state renders AttachmentChip fallback
* - tone=user applies blue border class
* - tone=agent applies neutral border class
* - Filename label shown before audio controls
* - onDownload called when error chip is clicked
* - Cleans up blob URL on unmount
* - External URI uses direct href without fetch
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render } from "@testing-library/react";
import React from "react";
import { AttachmentAudio } from "../AttachmentAudio";
import type { ChatAttachment } from "../types";
// ─── Mocks ───────────────────────────────────────────────────────────────────
const mockResolveAttachmentHref = vi.fn<(id: string, uri: string) => string>(
(id, uri) => `https://api.moleculesai.app/attachments/${uri}`,
);
const mockIsPlatformAttachment = vi.fn<(uri: string) => boolean>(() => true);
vi.mock("../uploads", () => ({
isPlatformAttachment: (uri: string) => mockIsPlatformAttachment(uri),
resolveAttachmentHref: (id: string, uri: string) =>
mockResolveAttachmentHref(id, uri),
}));
vi.mock("@/lib/api", () => ({
platformAuthHeaders: () => ({ Authorization: "Bearer test-token" }),
}));
// ─── Helpers ──────────────────────────────────────────────────────────────────
function makeAttachment(name: string, size?: number): ChatAttachment {
return { name, uri: `workspace:/tmp/${name}`, size };
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.resetModules();
});
// ─── Fetch mock helpers ──────────────────────────────────────────────────────
function mockFetchOk(body: string, contentType = "audio/mpeg") {
const blob = new Blob([body], { type: contentType });
global.fetch = vi.fn((href: string, opts?: RequestInit) => {
void href;
void opts;
return Promise.resolve({
ok: true,
status: 200,
blob: () => Promise.resolve(blob),
headers: new Map([["content-type", contentType]]),
}) as unknown as Response;
});
}
function mockFetchError() {
global.fetch = vi.fn(() =>
Promise.resolve({ ok: false, status: 500 }) as unknown as Response,
);
}
// ─── Idle/Loading state ─────────────────────────────────────────────────────
describe("AttachmentAudio — idle/loading", () => {
beforeEach(() => {
mockFetchOk("audiodata");
});
it("renders loading skeleton with aria-label", () => {
const att = makeAttachment("podcast.mp3", 1024 * 512);
const { container } = render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="user"
/>,
);
const skeleton = container.querySelector('[aria-label]') as HTMLElement;
expect(skeleton?.getAttribute("aria-label")).toContain("podcast.mp3");
expect(skeleton?.getAttribute("aria-label")).toContain("Loading");
});
it("loading skeleton has correct dimensions", () => {
const att = makeAttachment("track.mp3");
const { container } = render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="agent"
/>,
);
const skeleton = container.querySelector('[aria-label]') as HTMLElement;
expect(skeleton?.style.width).toBe("280px");
expect(skeleton?.style.height).toBe("40px");
});
});
// ─── Ready state ─────────────────────────────────────────────────────────────
describe("AttachmentAudio — ready", () => {
beforeEach(() => {
mockFetchOk("audiodata");
});
it("renders <audio> element with correct src when ready", async () => {
const att = makeAttachment("clip.mp3", 1024 * 512);
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="user"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const audio = document.querySelector("audio") as HTMLAudioElement;
expect(audio.src).toMatch(/^blob:/);
expect(audio.hasAttribute("controls")).toBe(true);
expect(audio.getAttribute("preload")).toBe("metadata");
});
it("tone=user applies blue border class", async () => {
mockFetchOk("data");
const att = makeAttachment("clip.mp3");
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="user"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const audio = document.querySelector("audio");
const container = audio?.closest("div");
expect(container?.className).toContain("blue-400");
});
it("tone=agent applies neutral border class (no blue)", async () => {
mockFetchOk("data");
const att = makeAttachment("clip.mp3");
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="agent"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const audio = document.querySelector("audio");
const container = audio?.closest("div");
expect(container?.className).not.toContain("blue-400");
});
it("filename label shown before audio controls", async () => {
mockFetchOk("data");
const att = makeAttachment("my-podcast-episode.mp3");
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="agent"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const container = document.querySelector("audio")?.closest("div");
expect(container?.textContent ?? "").toContain("my-podcast-episode.mp3");
});
});
// ─── Error state ─────────────────────────────────────────────────────────────
describe("AttachmentAudio — error", () => {
it("renders AttachmentChip fallback when fetch fails", async () => {
mockFetchError();
const onDownload = vi.fn();
const att = makeAttachment("broken.mp3", 256);
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={onDownload}
tone="agent"
/>,
);
await vi.waitFor(() => {
const chip = document.querySelector("button");
expect(chip).toBeTruthy();
expect(chip?.textContent).toContain("broken.mp3");
});
const chip = document.querySelector("button") as HTMLButtonElement;
chip.click();
expect(onDownload).toHaveBeenCalledWith(att);
});
});
// ─── Cleanup ─────────────────────────────────────────────────────────────────
describe("AttachmentAudio — blob URL cleanup", () => {
it("creates blob URL on mount and cleans up on unmount", async () => {
mockFetchOk("audiodata");
const att = makeAttachment("clip.mp3");
const { unmount } = render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="user"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const audio = document.querySelector("audio") as HTMLAudioElement;
const blobUrl = audio.src;
expect(blobUrl).toMatch(/^blob:/);
unmount();
expect(document.querySelector("audio")).toBeNull();
});
});
// ─── External URI ───────────────────────────────────────────────────────────
describe("AttachmentAudio — external URI", () => {
it("uses direct href for external URIs without fetch", async () => {
mockIsPlatformAttachment.mockReturnValue(false);
const externalUri = "https://example.com/audio.mp3";
const att = makeAttachment("audio.mp3");
att.uri = externalUri;
render(
<AttachmentAudio
workspaceId="ws1"
attachment={att}
onDownload={vi.fn()}
tone="user"
/>,
);
await vi.waitFor(() => {
expect(document.querySelector("audio")).toBeTruthy();
});
const audio = document.querySelector("audio") as HTMLAudioElement;
expect(audio.src).toContain("example.com/audio.mp3");
});
});

View File

@ -0,0 +1,214 @@
// @vitest-environment jsdom
/**
* AttachmentLightbox shared fullscreen modal for image/PDF/preview.
*
* Per RFC #2991 Phase 2, AttachmentLightbox owns:
* - Backdrop + centered viewport
* - Esc to close
* - Click-outside to close (stopPropagation on content)
* - Focus trap: focus enters close button on open, restores on close
* - prefers-reduced-motion respect
*
* NOTE: No @testing-library/jest-dom import use textContent / className /
* getAttribute / checked / value checks to avoid jest-dom dependency errors.
*
* Covers:
* - Does not render when open=false
* - Renders dialog with role=dialog and aria-modal
* - Renders with provided aria-label
* - Close button has aria-label="Close preview"
* - Clicking backdrop (outside content) calls onClose
* - Clicking content does NOT call onClose (stopPropagation)
* - Escape key calls onClose
* - Focus moves to close button when opened
* - Focus restores to previous element when closed
* - Reduced motion: motion-reduce class on backdrop
* - Renders children inside the modal
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { AttachmentLightbox } from "../AttachmentLightbox";
afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.resetModules();
});
// ─── Helpers ─────────────────────────────────────────────────────────────────
/** Renders the lightbox open with children and returns close fn */
function renderOpen(props?: Partial<React.ComponentProps<typeof AttachmentLightbox>>) {
const onClose = vi.fn();
const result = render(
<AttachmentLightbox
open={true}
onClose={onClose}
ariaLabel="Image preview"
{...props}
>
<img alt="test" src="data:image/png;base64,iVBORw0KGgo=" />
</AttachmentLightbox>,
);
return { ...result, onClose };
}
// ─── Render States ────────────────────────────────────────────────────────────
describe("AttachmentLightbox — render", () => {
it("does not render when open=false", () => {
const { container } = render(
<AttachmentLightbox
open={false}
onClose={vi.fn()}
ariaLabel="Preview"
>
<div>content</div>
</AttachmentLightbox>,
);
expect(container.firstChild).toBeNull();
});
it("renders dialog with role=dialog and aria-modal", () => {
renderOpen();
const dialog = document.querySelector('[role="dialog"]');
expect(dialog).toBeTruthy();
expect(dialog?.getAttribute("aria-modal")).toBe("true");
});
it("renders with provided aria-label", () => {
renderOpen({ ariaLabel: "PDF: report-2026.pdf" });
const dialog = document.querySelector('[role="dialog"]');
expect(dialog?.getAttribute("aria-label")).toBe("PDF: report-2026.pdf");
});
it("close button has aria-label='Close preview'", () => {
renderOpen();
const btn = document.querySelector('[aria-label="Close preview"]');
expect(btn).toBeTruthy();
expect(btn?.tagName).toBe("BUTTON");
});
it("renders children inside the modal", () => {
renderOpen({ ariaLabel: "Preview" });
// Children are inside the dialog
const dialog = document.querySelector('[role="dialog"]');
expect(dialog?.querySelector("img")).toBeTruthy();
});
it("applies reduced-motion class on backdrop", () => {
renderOpen();
// The div[role="dialog"] IS the fixed backdrop — contains motion-reduce:transition-none
const dialog = document.querySelector('[role="dialog"]') as HTMLElement;
expect(dialog?.className).toContain("motion-reduce");
});
});
// ─── Interaction ─────────────────────────────────────────────────────────────
describe("AttachmentLightbox — interaction", () => {
it("calls onClose when close button is clicked", () => {
const onClose = vi.fn();
renderOpen({ onClose });
const btn = document.querySelector('[aria-label="Close preview"]') as HTMLButtonElement;
btn.click();
expect(onClose).toHaveBeenCalledTimes(1);
});
it("calls onClose when backdrop (outside content) is clicked", () => {
const onClose = vi.fn();
renderOpen({ onClose });
// The div[role="dialog"] IS the backdrop (fixed inset-0).
// Click on it — e.target === e.currentTarget triggers onBackdropClick.
const backdrop = document.querySelector('[role="dialog"]') as HTMLElement;
fireEvent.click(backdrop, { target: backdrop });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("does NOT call onClose when content (inside modal) is clicked", () => {
const onClose = vi.fn();
renderOpen({ onClose });
// Click on the img inside the modal
const img = document.querySelector("img") as HTMLElement;
fireEvent.click(img);
expect(onClose).not.toHaveBeenCalled();
});
it("calls onClose on Escape key", () => {
const onClose = vi.fn();
renderOpen({ onClose });
fireEvent.keyDown(document, { key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("does not call onClose for other keys", () => {
const onClose = vi.fn();
renderOpen({ onClose });
fireEvent.keyDown(document, { key: "Enter" });
fireEvent.keyDown(document, { key: "Tab" });
expect(onClose).not.toHaveBeenCalled();
});
});
// ─── Focus Management ────────────────────────────────────────────────────────
describe("AttachmentLightbox — focus management", () => {
it("moves focus to close button when opened", () => {
renderOpen();
const btn = document.querySelector('[aria-label="Close preview"]') as HTMLButtonElement;
expect(document.activeElement).toBe(btn);
});
it("restores focus to previous element when closed", () => {
// Create a button to hold focus before opening the modal
const outerBtn = document.createElement("button");
outerBtn.textContent = "Open modal";
document.body.appendChild(outerBtn);
outerBtn.focus();
expect(document.activeElement).toBe(outerBtn);
const onClose = vi.fn();
const { rerender } = render(
<AttachmentLightbox
open={false}
onClose={onClose}
ariaLabel="Preview"
>
<div>content</div>
</AttachmentLightbox>,
);
// Open the modal
rerender(
<AttachmentLightbox
open={true}
onClose={onClose}
ariaLabel="Preview"
>
<div>content</div>
</AttachmentLightbox>,
);
// Focus should now be on close button
const btn = document.querySelector('[aria-label="Close preview"]') as HTMLButtonElement;
expect(document.activeElement).toBe(btn);
// Close the modal
rerender(
<AttachmentLightbox
open={false}
onClose={onClose}
ariaLabel="Preview"
>
<div>content</div>
</AttachmentLightbox>,
);
// Focus should be restored to outerBtn
expect(document.activeElement).toBe(outerBtn);
document.body.removeChild(outerBtn);
});
});

View File

@ -0,0 +1,451 @@
// @vitest-environment jsdom
/**
* form-inputs pure presentational form primitives for the Config tab.
*
* NOTE: No @testing-library/jest-dom import use textContent / className /
* getAttribute / checked / value checks to avoid "expect is not defined"
* errors in this vitest configuration.
*
* Covers:
* - TextInput renders label and input with correct value
* - TextInput calls onChange with new value on keystroke
* - TextInput renders placeholder text when provided
* - TextInput applies mono class when mono=true
* - TextInput input has accessible aria-label from label
* - TextInput input is not mono by default
* - NumberInput renders label and number input
* - NumberInput calls onChange with parsed integer on keystroke
* - NumberInput calls onChange with 0 for non-numeric input
* - NumberInput respects min/max bounds
* - NumberInput input has aria-label from label prop
* - NumberInput input has font-mono class
* - Toggle renders checkbox with label text
* - Toggle renders checked/unchecked state correctly
* - Toggle calls onChange with boolean on toggle
* - TagList renders existing tags with remove buttons
* - TagList × button has aria-label "Remove tag {value}"
* - TagList calls onChange without removed tag on × click
* - TagList renders the label text
* - TagList renders placeholder text when provided
* - TagList renders exactly one textbox
* - TagList adds tag on Enter key
* - TagList does not add empty/whitespace-only tags on Enter
* - TagList clears input after adding tag
* - Section renders the title
* - Section renders children when open (defaultOpen=true)
* - Section starts closed when defaultOpen=false
* - Section opens/closes content on title click
* - Section button has aria-expanded reflecting open state
* - Section toggle indicator changes on open/close
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import {
TextInput,
NumberInput,
Toggle,
TagList,
Section,
} from "../form-inputs";
afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.resetModules();
});
// ─── TextInput ───────────────────────────────────────────────────────────────
describe("TextInput", () => {
it("renders the label text", () => {
const { container } = render(
<TextInput label="Agent Name" value="" onChange={vi.fn()} />,
);
expect(container.textContent).toContain("Agent Name");
});
it("renders the input with the given value", () => {
render(<TextInput label="Model" value="claude-opus-4" onChange={vi.fn()} />);
const input = document.querySelector("input") as HTMLInputElement;
expect(input.value).toBe("claude-opus-4");
});
it("calls onChange with new value on keystroke", () => {
const onChange = vi.fn();
render(<TextInput label="Name" value="hello" onChange={onChange} />);
const input = document.querySelector("input") as HTMLInputElement;
fireEvent.change(input, { target: { value: "hello world" } });
expect(onChange).toHaveBeenCalledWith("hello world");
});
it("renders placeholder text when provided", () => {
render(
<TextInput
label="Token"
value=""
onChange={vi.fn()}
placeholder="sk-..."
/>,
);
const input = document.querySelector("input") as HTMLInputElement;
expect(input.getAttribute("placeholder")).toBe("sk-...");
});
it("applies mono class when mono=true", () => {
const { container } = render(
<TextInput label="Model" value="" onChange={vi.fn()} mono />,
);
const input = container.querySelector("input") as HTMLInputElement;
expect(input.className).toContain("font-mono");
});
it("input has aria-label matching the label", () => {
render(<TextInput label="API Key" value="" onChange={vi.fn()} />);
const input = document.querySelector("input") as HTMLInputElement;
expect(input.getAttribute("aria-label")).toBe("API Key");
});
it("input is not mono by default", () => {
const { container } = render(
<TextInput label="Description" value="" onChange={vi.fn()} />,
);
const input = container.querySelector("input") as HTMLInputElement;
expect(input.className).not.toContain("font-mono");
});
});
// ─── NumberInput ─────────────────────────────────────────────────────────────
describe("NumberInput", () => {
it("renders the label text", () => {
const { container } = render(
<NumberInput label="Timeout (s)" value={30} onChange={vi.fn()} />,
);
expect(container.textContent).toContain("Timeout (s)");
});
it("renders the input with the given numeric value", () => {
render(<NumberInput label="Retries" value={3} onChange={vi.fn()} />);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
expect(input.value).toBe("3");
});
it("calls onChange with parsed integer on keystroke", () => {
const onChange = vi.fn();
render(<NumberInput label="Delay" value={1} onChange={onChange} />);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
fireEvent.change(input, { target: { value: "7" } });
expect(onChange).toHaveBeenCalledWith(7);
});
it("calls onChange with 0 for non-numeric input", () => {
const onChange = vi.fn();
render(<NumberInput label="Count" value={5} onChange={onChange} />);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
fireEvent.change(input, { target: { value: "abc" } });
expect(onChange).toHaveBeenCalledWith(0);
});
it("respects min attribute", () => {
render(
<NumberInput
label="Port"
value={8000}
onChange={vi.fn()}
min={1024}
/>,
);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
expect(input.getAttribute("min")).toBe("1024");
});
it("respects max attribute", () => {
render(
<NumberInput
label="Memory (MB)"
value={256}
onChange={vi.fn()}
max={65535}
/>,
);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
expect(input.getAttribute("max")).toBe("65535");
});
it("input has aria-label from label prop", () => {
render(<NumberInput label="Timeout" value={60} onChange={vi.fn()} />);
const input = document.querySelector("input[type=number]") as HTMLInputElement;
expect(input.getAttribute("aria-label")).toBe("Timeout");
});
it("input has font-mono class", () => {
const { container } = render(
<NumberInput label="Budget" value={100} onChange={vi.fn()} />,
);
const input = container.querySelector("input") as HTMLInputElement;
expect(input.className).toContain("font-mono");
});
});
// ─── Toggle ──────────────────────────────────────────────────────────────────
describe("Toggle", () => {
it("renders the checkbox with label text", () => {
const { container } = render(
<Toggle label="Enable streaming" checked={false} onChange={vi.fn()} />,
);
const checkbox = container.querySelector(
"input[type=checkbox]",
) as HTMLInputElement;
expect(checkbox.checked).toBe(false);
expect(
checkbox.closest("label")?.textContent,
).toContain("Enable streaming");
});
it("renders checked state correctly", () => {
const { container } = render(
<Toggle label="Push notifications" checked onChange={vi.fn()} />,
);
const checkbox = container.querySelector(
"input[type=checkbox]",
) as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
it("calls onChange with true when toggled on", () => {
const onChange = vi.fn();
const { container } = render(
<Toggle label="Escalate" checked={false} onChange={onChange} />,
);
const checkbox = container.querySelector(
"input[type=checkbox]",
) as HTMLInputElement;
checkbox.click();
expect(onChange).toHaveBeenCalledWith(true);
});
it("calls onChange with false when toggled off", () => {
const onChange = vi.fn();
const { container } = render(
<Toggle label="Escalate" checked onChange={onChange} />,
);
const checkbox = container.querySelector(
"input[type=checkbox]",
) as HTMLInputElement;
checkbox.click();
expect(onChange).toHaveBeenCalledWith(false);
});
it("checkbox is a native input element", () => {
const { container } = render(
<Toggle label="Feature flag" checked={false} onChange={vi.fn()} />,
);
expect(container.querySelector("input[type=checkbox]")).toBeTruthy();
});
});
// ─── TagList ────────────────────────────────────────────────────────────────
describe("TagList", () => {
it("renders existing tags", () => {
const { container } = render(
<TagList label="Tools" values={["file_read", "bash"]} onChange={vi.fn()} />,
);
expect(container.textContent).toContain("file_read");
expect(container.textContent).toContain("bash");
});
it("renders × remove button for each tag with aria-label", () => {
render(
<TagList
label="Skills"
values={["python", "golang"]}
onChange={vi.fn()}
/>,
);
const buttons = document.querySelectorAll("button");
// buttons[0] = first × (python), buttons[1] = second × (golang)
expect(buttons[0].getAttribute("aria-label")).toBe(
"Remove tag python",
);
expect(buttons[1].getAttribute("aria-label")).toBe(
"Remove tag golang",
);
});
it("calls onChange without removed tag when × is clicked", () => {
const onChange = vi.fn();
render(
<TagList
label="Tags"
values={["react", "vue", "angular"]}
onChange={onChange}
/>,
);
const buttons = document.querySelectorAll("button");
// buttons[0] = react ×, buttons[1] = vue ×, buttons[2] = angular ×
buttons[0].click(); // Remove react
expect(onChange).toHaveBeenCalledWith(["vue", "angular"]);
});
it("renders the label text", () => {
const { container } = render(
<TagList label="Required env vars" values={[]} onChange={vi.fn()} />,
);
expect(container.textContent).toContain("Required env vars");
});
it("renders placeholder text when provided", () => {
render(
<TagList
label="Tags"
values={[]}
onChange={vi.fn()}
placeholder="Add a tag..."
/>,
);
const input = document.querySelector("input[type=text]") as HTMLInputElement;
expect(input.getAttribute("placeholder")).toBe("Add a tag...");
});
it("renders exactly one textbox (the input)", () => {
const { container } = render(
<TagList
label="Tools"
values={["read", "write"]}
onChange={vi.fn()}
/>,
);
expect(
container.querySelectorAll("input[type=text]"),
).toHaveLength(1);
});
it("adds tag on Enter key", () => {
const onChange = vi.fn();
render(
<TagList label="Skills" values={["python"]} onChange={onChange} />,
);
const input = document.querySelector("input[type=text]") as HTMLInputElement;
fireEvent.change(input, { target: { value: "rust" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onChange).toHaveBeenCalledWith(["python", "rust"]);
});
it("does not add empty tag on Enter", () => {
const onChange = vi.fn();
render(
<TagList label="Tools" values={[]} onChange={onChange} />,
);
const input = document.querySelector("input[type=text]") as HTMLInputElement;
fireEvent.change(input, { target: { value: " " } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onChange).not.toHaveBeenCalled();
});
it("clears input after adding tag", () => {
render(
<TagList label="Tags" values={[]} onChange={vi.fn()} />,
);
const input = document.querySelector("input[type=text]") as HTMLInputElement;
fireEvent.change(input, { target: { value: "golang" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(input.value).toBe("");
});
});
// ─── Section ───────────────────────────────────────────────────────────────
describe("Section", () => {
it("renders the title", () => {
const { container } = render(
<Section title="Runtime config">Content here</Section>,
);
expect(container.textContent).toContain("Runtime config");
});
it("renders children when open (defaultOpen=true)", () => {
const { container } = render(
<Section title="A section">Hidden content</Section>,
);
expect(container.textContent).toContain("Hidden content");
});
it("starts closed when defaultOpen=false", () => {
const { container } = render(
<Section title="Collapsed" defaultOpen={false}>
Should not be visible
</Section>,
);
expect(container.textContent).not.toContain("Should not be visible");
});
it("opens/closes content on title click", () => {
const { container } = render(
<Section title="Toggle me" defaultOpen={false}>
Now you see me
</Section>,
);
// Should be closed initially
expect(container.textContent).not.toContain("Now you see me");
// Click to open
const btn = container.querySelector("button") as HTMLButtonElement;
fireEvent.click(btn);
expect(container.textContent).toContain("Now you see me");
// Click to close
fireEvent.click(btn);
expect(container.textContent).not.toContain("Now you see me");
});
it("title button has aria-expanded reflecting open state", () => {
// Open section
const { container: openContainer } = render(
<Section title="A section" defaultOpen={true}>
Open content
</Section>,
);
const openBtn = openContainer.querySelector(
"button",
) as HTMLButtonElement;
expect(openBtn.getAttribute("aria-expanded")).toBe("true");
// Closed section
const { container: closedContainer } = render(
<Section title="B section" defaultOpen={false}>
Closed content
</Section>,
);
const closedBtn = closedContainer.querySelector(
"button",
) as HTMLButtonElement;
expect(closedBtn.getAttribute("aria-expanded")).toBe("false");
});
it("toggle indicator changes between ▾ (open) and ▸ (closed)", () => {
// Open: uses ▾
const { container: openContainer } = render(
<Section title="Indicator" defaultOpen={true}>
Open
</Section>,
);
// Button has two spans: title (first) and indicator (second, aria-hidden)
const openSpans = openContainer
.querySelectorAll("button span");
const openIndicator = openSpans[1]?.textContent?.trim();
expect(openIndicator).toBe("▾");
// Closed: uses ▸
const { container: closedContainer } = render(
<Section title="Indicator" defaultOpen={false}>
Closed
</Section>,
);
const closedSpans = closedContainer
.querySelectorAll("button span");
const closedIndicator = closedSpans[1]?.textContent?.trim();
expect(closedIndicator).toBe("▸");
});
});

View File

@ -127,13 +127,21 @@ export function TagList({ label, values, onChange, placeholder }: { label: strin
export function Section({ title, children, defaultOpen = true }: { title: string; children: React.ReactNode; defaultOpen?: boolean }) {
const [open, setOpen] = useState(defaultOpen);
// Stable id for aria-controls linkage
const id = `section-content-${title.toLowerCase().replace(/\s+/g, "-")}`;
return (
<div className="border border-line rounded mb-2">
<button type="button" onClick={() => setOpen(!open)} className="w-full flex items-center justify-between px-3 py-1.5 text-[10px] text-ink-mid hover:text-ink bg-surface-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1">
<button
type="button"
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls={id}
className="w-full flex items-center justify-between px-3 py-1.5 text-[10px] text-ink-mid hover:text-ink bg-surface-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
>
<span className="font-medium uppercase tracking-wider">{title}</span>
<span>{open ? "▾" : "▸"}</span>
<span aria-hidden="true">{open ? "▾" : "▸"}</span>
</button>
{open && <div className="p-3 space-y-3">{children}</div>}
{open && <div id={id} className="p-3 space-y-3">{children}</div>}
</div>
);
}