Skip to content

Open-source, local-first AI agent for real work.

6.6 KB
Raw Blame
// @vitest-environment jsdom

import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { StorageSettingsView, type StorageSettingsViewProps } from "./StorageSettingsView";

Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });

const mounted: Array<{ root: Root; container: HTMLDivElement }> = [];

afterEach(() => {
	for (const { root, container } of mounted.splice(0)) {
		act(() => root.unmount());
		container.remove();
	}
});

function render(overrides: Partial<StorageSettingsViewProps> = {}): HTMLDivElement {
	const props: StorageSettingsViewProps = {
		labels: {
			title: "Storage",
			description: "What Vetta keeps",
			total: "Total",
			scanning: "Calculating",
			rescan: "Recalculate",
			cleaning: "Clearing",
			clean: (size) => `Clear ${size}`,
			cleanEmpty: "Clear",
			inUse: "In use",
			nothingToClean: "Nothing to clear",
			afterClean: (size) => `${size} after clearing`,
			selectHint: "Select items",
			assistTitle: "Clean up with Vetta",
			assistDescription: "Vetta lists items",
			assistAction: "Start chat",
			open: "Open",
			reveal: "Show location",
			delete: "Delete",
			sections: { overview: "Overview", clean: "Clean up", largest: "Largest" },
			largestDescription: "Your content",
			tabs: { overview: "Overview", content: "Chats" },
			view: "View",
			all: "All",
			rest: "Smaller items",
			empty: "Nothing yet",
		},
		overviewSection: { id: "storage-overview" },
		cleanSection: { id: "storage-clean" },
		largestSection: { id: "storage-largest" },
		overview: {
			totalBytes: 3072,
			capacityBytes: 3072,
			shares: [
				{ kind: "yours", label: "Yours", bytes: 2048, items: [{ id: "projects", label: "Projects", bytes: 2048 }] },
				{ kind: "cleanable", label: "Clearable", bytes: 1024, items: [{ id: "downloads", label: "Download cache", bytes: 1024 }] },
			],
		},
		assistPotential: null,
		cleanActions: [
			{ id: "downloads", title: "Download cache", description: "npm", bytes: 1024, blocked: false, selected: true },
			{ id: "interface", title: "Interface cache", description: "ui", bytes: 0, blocked: true, selected: true },
		],
		tab: "overview",
		onTabChange: () => {},
		explorer: { totalBytes: 0, owners: [] },
		onReveal: () => {},
		scanning: false,
		cleaning: false,
		cleanResult: null,
		error: null,
		onRescan: () => {},
		onToggleClean: () => {},
		onClean: () => {},
		onAssist: () => {},
		...overrides,
	};
	const container = document.createElement("div");
	document.body.append(container);
	const root = createRoot(container);
	mounted.push({ root, container });
	act(() => root.render(<StorageSettingsView {...props} />));
	return container;
}

const button = (container: HTMLElement, label: string) =>
	[...container.querySelectorAll("button")].find((item) => item.textContent === label);

describe("StorageSettingsView", () => {
	it("预告清理后的占用;使用中的条目不能勾选", () => {
		const container = render();
		expect(container.textContent).toContain("2.00 KB after clearing");
		expect(container.textContent).toContain("In use");
		expect([...container.querySelectorAll("input")].map((box) => [box.checked, box.disabled])).toEqual([
			[true, false],
			[false, true],
		]);
		expect(button(container, "Clear 1.00 KB")?.disabled).toBe(false);
	});

	it("聚焦清理色块时在标题下读出说明,移开后恢复清理后的占用", () => {
		const container = render();
		const box = container.querySelector("input");
		const status = container.querySelector('[role="status"]');
		act(() => box?.focus());
		expect(status?.nextElementSibling?.textContent).toBe("npm");
		act(() => box?.blur());
		expect(status?.nextElementSibling).toBeNull();
		expect(status?.textContent).toBe("2.00 KB after clearing");
	});

	it("聚焦图例时读出该类的占比,移开后恢复总占用", () => {
		const container = render();
		const legend = button(container, "Clearable1.00 KB");
		act(() => legend?.focus());
		expect(container.textContent).toContain("33%");
		act(() => legend?.blur());
		expect(container.textContent).not.toContain("33%");
		expect(container.textContent).toContain("Total3.00 KB");
	});

	it("清理中或重新计算中不能再发起清理", () => {
		expect(button(render({ cleaning: true }), "Clearing")?.disabled).toBe(true);
		expect(button(render({ scanning: true }), "Clear 1.00 KB")?.disabled).toBe(true);
	});

	it("没有可清理内容时只留一句说明,不显示清理按钮", () => {
		const container = render({ cleanActions: [] });
		expect(container.textContent).toContain("Nothing to clear");
		expect(button(container, "Clear")).toBeUndefined();
	});

	it("点开项目进入下一层,点面包屑返回;不能再展开的内容显示位置", () => {
		const revealed: string[] = [];
		const container = render({
			tab: "content",
			explorer: {
				totalBytes: 4096,
				owners: [owner("Site", 4096, [{ name: "video.mp4", bytes: 3072, directory: false }])],
			},
			onReveal: (path) => revealed.push(path),
		});
		expect(rows(container)).toEqual(["SiteProject4.00 KB"]);
		click(container, "View Site");
		expect(rows(container)).toEqual(["video.mp43.00 KB", "Smaller items1.00 KB"]);
		click(container, "Show location video.mp4");
		expect(revealed).toEqual(["workspace/Site/video.mp4"]);
		act(() => button(container, "All")?.click());
		expect(rows(container)).toEqual(["SiteProject4.00 KB"]);
	});

	it("较小的项目合成一项,点开后可以继续查看和删除", () => {
		const deleted: string[] = [];
		const owners = Array.from({ length: 15 }, (_, index) => ({
			...owner(`P${index}`, 2048, [{ name: "a.md", bytes: 2048, directory: false }]),
			onDelete: () => deleted.push(`P${index}`),
		}));
		const container = render({ tab: "content", explorer: { totalBytes: 15 * 2048, owners } });
		expect(rows(container)).toHaveLength(13);
		click(container, "View Smaller items");
		expect(rows(container)).toEqual(["P12Project2.00 KB", "P13Project2.00 KB", "P14Project2.00 KB"]);
		click(container, "Delete P13");
		expect(deleted).toEqual(["P13"]);
		click(container, "View P14");
		expect(rows(container)).toEqual(["a.md2.00 KB"]);
	});
});

type Owner = NonNullable<StorageSettingsViewProps["explorer"]>["owners"][number];

const owner = (title: string, bytes: number, children: Owner["children"]): Owner => ({
	id: `workspace/${title}`,
	kind: "projects",
	title,
	meta: "Project",
	bytes,
	children,
});
const rows = (container: HTMLElement) => [...container.querySelectorAll("li")].map((row) => row.textContent);
const click = (container: HTMLElement, label: string) =>
	act(() => container.querySelector<HTMLElement>(`[aria-label="${label}"]`)?.click());