Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadStatusIndicators.subscriptions.browser.test.tsx

248 lines8.7 KB

1import {
2 ProjectId,
3 ThreadId,
4 type ThreadPullRequestLink,
5 type VcsStatusResult,
6} from "@t3tools/contracts";
7import { act, type MouseEvent } from "react";
8import { createRoot } from "react-dom/client";
9import { afterEach, expect, it, vi } from "vite-plus/test";
10import { page, userEvent } from "vite-plus/test/browser";
11​
12import "../index.css";
13import { Button } from "./ui/button";
14​
15import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
16import { makeThreadFixture } from "../test-fixtures";
17​
18const state = vi.hoisted(() => ({ queries: [] as string[] }));
19​
20vi.mock(import("../state/entities"), async (original) => ({
21 ...(await original()),
22 useProject: () => null,
23 useServerConfigs: () => new Map(),
24}));
25vi.mock(import("../state/vcs"), async (original) => {
26 const { AsyncResult, Atom } = await import("effect/reactivity");
27 const statuses = Atom.family((cwd: string) =>
28 Atom.make(() => {
29 state.queries.push(`vcs:${cwd}`);
30 return AsyncResult.success({
31 isRepo: true,
32 hasPrimaryRemote: true,
33 isDefaultRef: false,
34 refName: "feature/test",
35 hasWorkingTreeChanges: false,
36 workingTree: { files: [], insertions: 0, deletions: 0 },
37 hasUpstream: true,
38 aheadCount: 0,
39 behindCount: 0,
40 pr: {
41 number: 42,
42 title: "Observed worktree PR",
43 url: "https://github.com/example/repo/pull/42",
44 baseRef: "main",
45 headRef: "feature/test",
46 state: "open",
47 },
48 } satisfies VcsStatusResult);
49 }),
50 );
51 const actual = await original();
52 return {
53 ...actual,
54 vcsEnvironment: {
55 ...actual.vcsEnvironment,
56 status: (({ input }: { input: { cwd: string } }) => statuses(input.cwd)) as never,
57 },
58 };
59});
60vi.mock(import("../state/pullRequests"), async (importOriginal) => {
61 const original = await importOriginal();
62 const { AsyncResult, Atom } = await import("effect/reactivity");
63 const { ProjectId } = await import("@t3tools/contracts");
64 const summaries = Atom.family((number: number) =>
65 Atom.make(() => {
66 state.queries.push(`pr:${number}`);
67 return AsyncResult.success({
68 provider: "github" as const,
69 projectId: ProjectId.make("project-test"),
70 repository: "example/repo",
71 number,
72 title: "Observed linked PR",
73 url: `https://github.com/example/repo/pull/${number}`,
74 state: "open" as const,
75 headBranch: "feature/test",
76 baseBranch: "main",
77 updatedAt: "2026-09-04T00:00:00.000Z",
78 });
79 }),
80 );
81 return {
82 ...original,
83 linkedPullRequestDetailAtom: (({ input }: { input: { number: number } }) =>
84 summaries(input.number)) as never,
85 };
86});
87import { ThreadPullRequestBadgeControl, ThreadRowLeadingStatus } from "./ThreadStatusIndicators";
88​
89afterEach(() => {
90 vi.unstubAllGlobals();
91});
92​
93// The lease overscans 160px around a 20px viewport, a 340px band. With 45px rows the band
94// covers exactly 8 rows at each scroll position below.
95const ROW_HEIGHT = 45;
96const SPACER = 1000;
97​
98it("leases only visible palette results while retaining observed and cached PR badges", async () => {
99 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
100 const threads = Array.from({ length: 128 }, (_, index) =>
101 makeThreadFixture({
102 id: ThreadId.make(`palette-thread-${index}`),
103 branch: "feature/test",
104 worktreePath: `/test/worktree-${index}`,
105 linkedPullRequest:
106 index % 2 === 0
107 ? null
108 : {
109 projectId: ProjectId.make("project-test"),
110 repository: "example/repo",
111 number: index,
112 url: `https://github.com/example/repo/pull/${index}`,
113 },
114 }),
115 );
116 const container = document.createElement("div");
117 document.body.append(container);
118 const root = createRoot(container);
119 state.queries.length = 0;
120 const viewport = () =>
121 container.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
122 const scrollTo = async (top: number) => {
123 await act(async () => {
124 viewport().scrollTop = top;
125 await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 50)));
126 });
127 };
128 const badgeCount = () =>
129 [...container.querySelectorAll("[aria-label]")].filter((node) =>
130 node.getAttribute("aria-label")!.startsWith("PR #"),
131 ).length;
132 try {
133 await act(async () =>
134 root.render(
135 <AppAtomRegistryProvider>
136 <div data-slot="scroll-area-viewport" style={{ height: 20, overflowY: "auto" }}>
137 <div style={{ height: SPACER }} />
138 {threads.map((thread, index) => (
139 <div key={thread.id} style={{ height: ROW_HEIGHT, overflow: "hidden" }}>
140 <ThreadRowLeadingStatus
141 thread={thread}
142 snapshot={
143 index === 126
144 ? {
145 branch: "feature/test",
146 sourceControlProvider: undefined,
147 pr: {
148 number: 126,
149 title: "Cached badge",
150 url: "https://github.com/example/repo/pull/126",
151 baseRef: "main",
152 headRef: "feature/test",
153 state: "open",
154 },
155 }
156 : undefined
157 }
158 />
159 {thread.title}
160 </div>
161 ))}
162 </div>
163 </AppAtomRegistryProvider>,
164 ),
165 );
166 await scrollTo(0);
167 expect(state.queries).toEqual([]);
168 expect(badgeCount()).toBe(1);
169​
170 // Band [1000, 1340]: rows 0..7.
171 await scrollTo(SPACER + 160);
172 expect(state.queries).toHaveLength(8);
173 expect(state.queries.filter((key) => key.startsWith("vcs:"))).toHaveLength(4);
174 expect(state.queries.filter((key) => key.startsWith("pr:"))).toHaveLength(4);
175 expect(badgeCount()).toBe(9);
176​
177 // Band [1370, 1710]: rows 8..15.
178 await scrollTo(SPACER + 8 * ROW_HEIGHT + 10 + 160);
179 expect(state.queries).toHaveLength(16);
180 expect(badgeCount()).toBe(17);
181 } finally {
182 await act(async () => root.unmount());
183 container.remove();
184 }
185});
186​
187it("keeps a long PR hover list in the viewport and lets the last row be selected", async () => {
188 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
189 const previousViewport = { width: window.innerWidth, height: window.innerHeight };
190 await page.viewport(800, 480);
191 const pullRequests = Array.from({ length: 40 }, (_, index): ThreadPullRequestLink => ({
192 host: "github.com",
193 repository: "example/repo",
194 number: index + 1,
195 url: `https://github.com/example/repo/pull/${index + 1}`,
196 source: "manual",
197 linkedAt: "2026-01-01T00:00:00Z",
198 snapshot: null,
199 stack: null,
200 }));
201 const onOpenPullRequest = vi.fn((event: MouseEvent<HTMLElement>) => event.preventDefault());
202 const container = document.createElement("div");
203 document.body.append(container);
204 const root = createRoot(container);
205 try {
206 await act(async () =>
207 root.render(
208 <div style={{ position: "fixed", top: 220, left: 300 }}>
209 <ThreadPullRequestBadgeControl
210 render={<Button size="xs" />}
211 badge={{ kind: "pull-request", others: 39, state: "open" }}
212 pullRequests={pullRequests}
213 number={1}
214 url={pullRequests[0]!.url}
215 status={null}
216 onOpenList={() => {}}
217 onOpenPullRequest={onOpenPullRequest}
218 />
219 </div>,
220 ),
221 );
222 await act(() => userEvent.hover(container.querySelector("button")!));
223 const popup = () => document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]')!;
224 await expect.poll(() => popup()?.querySelectorAll("a").length).toBe(40);
225 await expect.poll(() => popup().getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
226 await expect
227 .poll(() => popup().getBoundingClientRect().bottom)
228 .toBeLessThanOrEqual(window.innerHeight);
229​
230 const lastRow = popup().querySelector<HTMLAnchorElement>("li:last-child a")!;
231 expect(lastRow.getBoundingClientRect().top).toBeGreaterThan(
232 popup().getBoundingClientRect().bottom,
233 );
234 await act(() => userEvent.wheel(popup(), { delta: { y: 10_000 } }));
235 await expect
236 .poll(() => lastRow.getBoundingClientRect().bottom)
237 .toBeLessThanOrEqual(popup().getBoundingClientRect().bottom);
238 expect(lastRow.getBoundingClientRect().top).toBeGreaterThanOrEqual(
239 popup().getBoundingClientRect().top,
240 );
241 await act(() => userEvent.click(lastRow));
242 expect(onOpenPullRequest).toHaveBeenCalledExactlyOnceWith(expect.anything(), lastRow.href);
243 } finally {
244 await act(async () => root.unmount());
245 container.remove();
246 await page.viewport(previousViewport.width, previousViewport.height);
247 }
248});