Skip to content

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

2.4 KB
Raw Blame
// @vitest-environment jsdom

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

/** jsdom 不做排版,滚动尺寸按测试需要直接钉死。 */
function sizeScroller(el: HTMLElement, { scrollHeight, clientHeight }: { scrollHeight: number; clientHeight: number }) {
	Object.defineProperty(el, "scrollHeight", { configurable: true, value: scrollHeight });
	Object.defineProperty(el, "clientHeight", { configurable: true, value: clientHeight });
}

async function scrollTo(el: HTMLElement, top: number): Promise<void> {
	el.scrollTop = top;
	await act(async () => {
		el.dispatchEvent(new Event("scroll"));
		await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined)));
	});
}

describe("ScrollFade", () => {
	let root: Root;
	let host: HTMLDivElement;

	beforeEach(() => {
		(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
		host = document.createElement("div");
		document.body.append(host);
		root = createRoot(host);
		vi.stubGlobal(
			"ResizeObserver",
			class {
				observe(): void {}
				unobserve(): void {}
				disconnect(): void {}
			},
		);
	});
	afterEach(() => {
		act(() => root.unmount());
		host.remove();
		vi.unstubAllGlobals();
	});

	function renderScroller(edges?: "bottom" | "both"): HTMLElement {
		act(() =>
			root.render(
				<ScrollFade data-testid="scroller" fadeSize={20} {...(edges ? { edges } : {})}>
					<div />
				</ScrollFade>,
			),
		);
		const el = host.querySelector<HTMLElement>('[data-testid="scroller"]');
		if (!el) throw new Error("scroller not rendered");
		sizeScroller(el, { scrollHeight: 300, clientHeight: 100 });
		return el;
	}

	it("fades both edges in the middle of the list and only the top at the end", async () => {
		const el = renderScroller("both");

		await scrollTo(el, 100);
		expect(el.style.maskImage).toBe(
			"linear-gradient(to bottom, transparent 0%, black 20px, black calc(100% - 20px), transparent 100%)",
		);

		await scrollTo(el, 200);
		expect(el.style.maskImage).toBe("linear-gradient(to bottom, transparent 0%, black 20px, black 100%)");
	});

	it("keeps the top edge sharp by default", async () => {
		const el = renderScroller();

		await scrollTo(el, 200);
		expect(el.style.maskImage).toBe("");
	});
});