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

useThreadHeaderOptions.test.tsx

190 lines6.3 KB

1// @vitest-environment jsdom
2import type { VcsStatusResult } from "@t3tools/contracts";
3import { act } from "react";
4import { createRoot, type Root } from "react-dom/client";
5import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6​
7// Native header item factories are only read when options are applied, so the fake
8// navigation snapshots the right items at each setOptions, as native-stack does.
9const harness = vi.hoisted(() => ({
10 setOptionsCalls: 0,
11 renderedRightItems: [] as Array<ReadonlyArray<Record<string, unknown>>>,
12 navigatedRoutes: [] as string[],
13}));
14​
15vi.mock("@react-navigation/native", () => {
16 const navigation = {
17 canGoBack: () => true,
18 dispatch: () => {},
19 goBack: () => {},
20 navigate: (route: string) => {
21 harness.navigatedRoutes.push(route);
22 },
23 addListener: () => () => {},
24 setOptions: (options: { unstable_headerRightItems?: () => Array<Record<string, unknown>> }) => {
25 harness.setOptionsCalls += 1;
26 harness.renderedRightItems.push(options.unstable_headerRightItems?.() ?? []);
27 },
28 };
29 return {
30 StackActions: { replace: () => ({}) },
31 useNavigation: () => navigation,
32 };
33});
34vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
35vi.mock("react-native", () => ({ Alert: { alert: () => {} }, Linking: {}, Platform: {} }));
36vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
37 useAdaptiveWorkspaceLayout: () => ({
38 layout: { usesSplitView: false },
39 panes: { primarySidebarVisible: false, auxiliaryPaneVisible: false },
40 togglePrimarySidebar: () => {},
41 toggleAuxiliaryPane: () => {},
42 }),
43}));
44vi.mock("../layout/native-mail-search-toolbar", () => ({
45 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED: true,
46 createNativeMailSearchToolbarItem: () => ({}),
47}));
48vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
49 useAppearancePreferences: () => ({ themeVariables: {} }),
50}));
51​
52import { ThreadHeader } from "./ThreadHeader";
53​
54const projectScripts: never[] = [];
55​
56function status(
57 files: ReadonlyArray<string>,
58 overrides: Partial<VcsStatusResult> = {},
59): VcsStatusResult {
60 return {
61 isRepo: true,
62 hasPrimaryRemote: false,
63 isDefaultRef: true,
64 refName: "master",
65 hasWorkingTreeChanges: files.length > 0,
66 workingTree: {
67 files: files.map((path) => ({ path, insertions: 0, deletions: 0 })),
68 insertions: 0,
69 deletions: 0,
70 },
71 hasUpstream: false,
72 aheadCount: 0,
73 behindCount: 0,
74 pr: null,
75 ...overrides,
76 } as unknown as VcsStatusResult;
78​
79// Mirrors the route screen: every render passes fresh gitControls callbacks.
80function Header(props: { readonly gitStatus: VcsStatusResult | null; readonly title?: string }) {
81 return (
82 <ThreadHeader
83 title={props.title ?? "Thread"}
84 subtitle=""
85 headerColor="#000"
86 usesNativeHeaderGlass
87 gitControls={{
88 environmentId: "environment-1",
89 threadId: "thread-1",
90 currentBranch: "master",
91 gitStatus: props.gitStatus,
92 gitOperationLabel: null,
93 onPull: async () => {},
94 onRunAction: async () => null,
95 canOpenTerminal: true,
96 canOperateTerminal: true,
97 canOpenFiles: true,
98 projectScripts,
99 terminalSessions: [],
100 onOpenTerminal: () => {},
101 onOpenNewTerminal: () => {},
102 onRunProjectScript: async () => {},
103 }}
104 hasThreadCwd
105 hasWorkspaceRoot
106 fileInspectorSupported={false}
107 inspectorMode={null}
108 onToggleInspector={() => {}}
109 onOpenGitInspector={() => {}}
110 onOpenFilesInspector={() => {}}
111 />
112 );
114​
115function renderedGitMenuItems(): Array<{
116 description?: unknown;
117 label?: unknown;
118 onPress?: () => void;
119}> {
120 const items = harness.renderedRightItems.at(-1) ?? [];
121 const git = items.find((item) => item.identifier === "thread-right-git") as
122 | { menu: { items: Array<{ description?: unknown; label?: unknown; onPress?: () => void }> } }
123 | undefined;
124 return git?.menu.items ?? [];
126​
127function renderedGitStatusDescription(): unknown {
128 return renderedGitMenuItems()[0]?.description;
130​
131let root: Root | null = null;
132​
133function render(element: React.ReactElement) {
134 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
135 root ??= createRoot(document.createElement("div"));
136 act(() => root!.render(element));
138​
139afterEach(() => {
140 act(() => root?.unmount());
141 root = null;
142 harness.setOptionsCalls = 0;
143 harness.renderedRightItems = [];
144 harness.navigatedRoutes = [];
145});
146​
147describe("ThreadHeader", () => {
148 it("re-applies native header items when Git status changes", () => {
149 render(<Header gitStatus={status([])} />);
150 expect(renderedGitStatusDescription()).toBe("Clean");
151​
152 // A refreshed status (e.g. after reconnect) must reach the Git popover even
153 // though nothing else in the header changed.
154 render(<Header gitStatus={status(["audit.txt"])} />);
155 expect(renderedGitStatusDescription()).toBe("1 changed");
156​
157 render(<Header gitStatus={status([])} />);
158 expect(renderedGitStatusDescription()).toBe("Clean");
159 });
160​
161 it("does not re-apply options for re-renders with equivalent header content", () => {
162 render(<Header gitStatus={status([])} />);
163 const applied = harness.setOptionsCalls;
164​
165 // Streaming re-renders the route with fresh callbacks and equal Git content.
166 for (let index = 0; index < 20; index += 1) {
167 render(<Header gitStatus={status([])} />);
168 }
169 expect(harness.setOptionsCalls).toBe(applied);
170 });
171​
172 it("re-applies menu actions when the default ref changes behind the same label", async () => {
173 // An unpushed commit on a branch with an open PR shows "Push" whether or not the
174 // branch is the default one, but only the default branch asks for confirmation.
175 const pushable = (isDefaultRef: boolean) =>
176 status([], {
177 isDefaultRef,
178 aheadCount: 1,
179 hasPrimaryRemote: true,
180 pr: { state: "open", url: "https://example.com/pr/1" },
181 } as Partial<VcsStatusResult>);
182 render(<Header gitStatus={pushable(false)} />);
183 expect(renderedGitMenuItems()[1]?.label).toBe("Push");
184​
185 render(<Header gitStatus={pushable(true)} />);
186 expect(renderedGitMenuItems()[1]?.label).toBe("Push");
187 await act(async () => renderedGitMenuItems()[1]?.onPress?.());
188 expect(harness.navigatedRoutes).toEqual(["GitConfirm"]);
189 });
190});