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

ThreadStatusIndicators.subscriptions.browser.test.tsx

176 lines6.0 KB

1import { ProjectId, ThreadId, type VcsStatusResult } from "@t3tools/contracts";
2import { act } from "react";
3import { createRoot } from "react-dom/client";
4import { afterEach, expect, it, vi } from "vite-plus/test";
5​
6import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
7import { makeThreadFixture } from "../test-fixtures";
8​
9const state = vi.hoisted(() => ({ queries: [] as string[] }));
10​
11vi.mock(import("../state/entities"), async (original) => ({
12 ...(await original()),
13 useProject: () => null,
14 useServerConfigs: () => new Map(),
15}));
16vi.mock(import("../state/vcs"), async (original) => {
17 const { AsyncResult, Atom } = await import("effect/reactivity");
18 const statuses = Atom.family((cwd: string) =>
19 Atom.make(() => {
20 state.queries.push(`vcs:${cwd}`);
21 return AsyncResult.success({
22 isRepo: true,
23 hasPrimaryRemote: true,
24 isDefaultRef: false,
25 refName: "feature/test",
26 hasWorkingTreeChanges: false,
27 workingTree: { files: [], insertions: 0, deletions: 0 },
28 hasUpstream: true,
29 aheadCount: 0,
30 behindCount: 0,
31 pr: {
32 number: 42,
33 title: "Observed worktree PR",
34 url: "https://github.com/example/repo/pull/42",
35 baseRef: "main",
36 headRef: "feature/test",
37 state: "open",
38 },
39 } satisfies VcsStatusResult);
40 }),
41 );
42 const actual = await original();
43 return {
44 ...actual,
45 vcsEnvironment: {
46 ...actual.vcsEnvironment,
47 status: (({ input }: { input: { cwd: string } }) => statuses(input.cwd)) as never,
48 },
49 };
50});
51vi.mock(import("../state/pullRequests"), async (importOriginal) => {
52 const original = await importOriginal();
53 const { AsyncResult, Atom } = await import("effect/reactivity");
54 const { ProjectId } = await import("@t3tools/contracts");
55 const summaries = Atom.family((number: number) =>
56 Atom.make(() => {
57 state.queries.push(`pr:${number}`);
58 return AsyncResult.success({
59 provider: "github" as const,
60 projectId: ProjectId.make("project-test"),
61 repository: "example/repo",
62 number,
63 title: "Observed linked PR",
64 url: `https://github.com/example/repo/pull/${number}`,
65 state: "open" as const,
66 headBranch: "feature/test",
67 baseBranch: "main",
68 updatedAt: "2026-09-04T00:00:00.000Z",
69 });
70 }),
71 );
72 return {
73 ...original,
74 linkedPullRequestDetailAtom: (({ input }: { input: { number: number } }) =>
75 summaries(input.number)) as never,
76 };
77});
78import { ThreadRowLeadingStatus } from "./ThreadStatusIndicators";
79​
80afterEach(() => {
81 vi.unstubAllGlobals();
82});
83​
84// The lease overscans 160px around a 20px viewport, a 340px band. With 45px rows the band
85// covers exactly 8 rows at each scroll position below.
86const ROW_HEIGHT = 45;
87const SPACER = 1000;
88​
89it("leases only visible palette results while retaining observed and cached PR badges", async () => {
90 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
91 const threads = Array.from({ length: 128 }, (_, index) =>
92 makeThreadFixture({
93 id: ThreadId.make(`palette-thread-${index}`),
94 branch: "feature/test",
95 worktreePath: `/test/worktree-${index}`,
96 linkedPullRequest:
97 index % 2 === 0
98 ? null
99 : {
100 projectId: ProjectId.make("project-test"),
101 repository: "example/repo",
102 number: index,
103 url: `https://github.com/example/repo/pull/${index}`,
104 },
105 }),
106 );
107 const container = document.createElement("div");
108 document.body.append(container);
109 const root = createRoot(container);
110 state.queries.length = 0;
111 const viewport = () =>
112 container.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
113 const scrollTo = async (top: number) => {
114 await act(async () => {
115 viewport().scrollTop = top;
116 await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 50)));
117 });
118 };
119 const badgeCount = () =>
120 [...container.querySelectorAll("[aria-label]")].filter((node) =>
121 node.getAttribute("aria-label")!.startsWith("PR #"),
122 ).length;
123 try {
124 await act(async () =>
125 root.render(
126 <AppAtomRegistryProvider>
127 <div data-slot="scroll-area-viewport" style={{ height: 20, overflowY: "auto" }}>
128 <div style={{ height: SPACER }} />
129 {threads.map((thread, index) => (
130 <div key={thread.id} style={{ height: ROW_HEIGHT, overflow: "hidden" }}>
131 <ThreadRowLeadingStatus
132 thread={thread}
133 snapshot={
134 index === 126
135 ? {
136 branch: "feature/test",
137 sourceControlProvider: undefined,
138 pr: {
139 number: 126,
140 title: "Cached badge",
141 url: "https://github.com/example/repo/pull/126",
142 baseRef: "main",
143 headRef: "feature/test",
144 state: "open",
145 },
146 }
147 : undefined
148 }
149 />
150 {thread.title}
151 </div>
152 ))}
153 </div>
154 </AppAtomRegistryProvider>,
155 ),
156 );
157 await scrollTo(0);
158 expect(state.queries).toEqual([]);
159 expect(badgeCount()).toBe(1);
160​
161 // Band [1000, 1340]: rows 0..7.
162 await scrollTo(SPACER + 160);
163 expect(state.queries).toHaveLength(8);
164 expect(state.queries.filter((key) => key.startsWith("vcs:"))).toHaveLength(4);
165 expect(state.queries.filter((key) => key.startsWith("pr:"))).toHaveLength(4);
166 expect(badgeCount()).toBe(9);
167​
168 // Band [1370, 1710]: rows 8..15.
169 await scrollTo(SPACER + 8 * ROW_HEIGHT + 10 + 160);
170 expect(state.queries).toHaveLength(16);
171 expect(badgeCount()).toBe(17);
172 } finally {
173 await act(async () => root.unmount());
174 container.remove();
175 }
176});