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

useThreadHeaderOptions.test.tsx

194 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("../../native/useOpenPullRequest", () => ({ useOpenPullRequest: () => () => {} }));
35​
36vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
37vi.mock("../../components/ui/AppBar", async () => {
38 const { NativeStackScreenOptions } = await import("../../native/StackHeader");
39 return {
40 AppBar: (props: import("../../components/ui/AppBar.types").AppBarProps) => (
41 <NativeStackScreenOptions options={props.options} optionsVersion={props.optionsVersion} />
42 ),
43 };
44});
45vi.mock("react-native", () => ({ Alert: { alert: () => {} }, Linking: {}, Platform: {} }));
46vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
47 useAdaptiveWorkspaceLayout: () => ({
48 layout: { usesSplitView: false },
49 panes: { primarySidebarVisible: false, auxiliaryPaneVisible: false },
50 togglePrimarySidebar: () => {},
51 toggleAuxiliaryPane: () => {},
52 }),
53}));
54vi.mock("../layout/native-mail-search-toolbar", () => ({
55 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED: true,
56 createNativeMailSearchToolbarItem: () => ({}),
57}));
58vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
59 useAppearancePreferences: () => ({ themeVariables: {} }),
60}));
61​
62import { ThreadHeader } from "./ThreadHeader";
63​
64const projectScripts: never[] = [];
65​
66function status(
67 files: ReadonlyArray<string>,
68 overrides: Partial<VcsStatusResult> = {},
69): VcsStatusResult {
70 return {
71 isRepo: true,
72 hasPrimaryRemote: false,
73 isDefaultRef: true,
74 refName: "master",
75 hasWorkingTreeChanges: files.length > 0,
76 workingTree: {
77 files: files.map((path) => ({ path, insertions: 0, deletions: 0 })),
78 insertions: 0,
79 deletions: 0,
80 },
81 hasUpstream: false,
82 aheadCount: 0,
83 behindCount: 0,
84 pr: null,
85 ...overrides,
86 } as unknown as VcsStatusResult;
88​
89function Header(props: { readonly gitStatus: VcsStatusResult | null; readonly title?: string }) {
90 return (
91 <ThreadHeader
92 title={props.title ?? "Thread"}
93 subtitle=""
94 headerColor="#000"
95 usesNativeHeaderGlass
96 gitControls={{
97 environmentId: "environment-1",
98 threadId: "thread-1",
99 currentBranch: "master",
100 gitStatus: props.gitStatus,
101 gitOperationLabel: null,
102 onPull: async () => {},
103 onRunAction: async () => null,
104 canOpenTerminal: true,
105 canOperateTerminal: true,
106 canOpenFiles: true,
107 projectScripts,
108 terminalSessions: [],
109 onOpenTerminal: () => {},
110 onOpenNewTerminal: () => {},
111 onRunProjectScript: async () => {},
112 }}
113 hasThreadCwd
114 hasWorkspaceRoot
115 fileInspectorSupported={false}
116 inspectorMode={null}
117 onToggleInspector={() => {}}
118 onOpenGitInspector={() => {}}
119 onOpenFilesInspector={() => {}}
120 />
121 );
123​
124function renderedGitMenuItems(): Array<{
125 description?: unknown;
126 label?: unknown;
127 onPress?: () => void;
128}> {
129 const items = harness.renderedRightItems.at(-1) ?? [];
130 const git = items.find((item) => item.identifier === "thread-right-git") as
131 | { menu: { items: Array<{ description?: unknown; label?: unknown; onPress?: () => void }> } }
132 | undefined;
133 return git?.menu.items ?? [];
135​
136function renderedGitStatusDescription(): unknown {
137 return renderedGitMenuItems()[0]?.description;
139​
140let root: Root | null = null;
141​
142function render(element: React.ReactElement) {
143 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
144 root ??= createRoot(document.createElement("div"));
145 act(() => root!.render(element));
147​
148afterEach(() => {
149 act(() => root?.unmount());
150 root = null;
151 harness.setOptionsCalls = 0;
152 harness.renderedRightItems = [];
153 harness.navigatedRoutes = [];
154});
155​
156describe("ThreadHeader", () => {
157 it("re-applies native header items when Git status changes", () => {
158 render(<Header gitStatus={status([])} />);
159 expect(renderedGitStatusDescription()).toBe("Clean");
160​
161 render(<Header gitStatus={status(["audit.txt"])} />);
162 expect(renderedGitStatusDescription()).toBe("1 changed");
163​
164 render(<Header gitStatus={status([])} />);
165 expect(renderedGitStatusDescription()).toBe("Clean");
166 });
167​
168 it("does not re-apply options for re-renders with equivalent header content", () => {
169 render(<Header gitStatus={status([])} />);
170 const applied = harness.setOptionsCalls;
171​
172 for (let index = 0; index < 20; index += 1) {
173 render(<Header gitStatus={status([])} />);
174 }
175 expect(harness.setOptionsCalls).toBe(applied);
176 });
177​
178 it("re-applies menu actions when the default ref changes behind the same label", async () => {
179 const pushable = (isDefaultRef: boolean) =>
180 status([], {
181 isDefaultRef,
182 aheadCount: 1,
183 hasPrimaryRemote: true,
184 pr: { state: "open", url: "https://example.com/pr/1" },
185 } as Partial<VcsStatusResult>);
186 render(<Header gitStatus={pushable(false)} />);
187 expect(renderedGitMenuItems()[1]?.label).toBe("Push");
188​
189 render(<Header gitStatus={pushable(true)} />);
190 expect(renderedGitMenuItems()[1]?.label).toBe("Push");
191 await act(async () => renderedGitMenuItems()[1]?.onPress?.());
192 expect(harness.navigatedRoutes).toEqual(["GitConfirm"]);
193 });
194});