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

Sidebar.shortcuts.browser.test.tsx

203 lines9.0 KB

1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
4import type * as Context from "effect/Context";
5import { expect, it, vi } from "vite-plus/test";
6import { page, userEvent } from "vite-plus/test/browser";
7​
8import { AppRoot } from "~/AppRoot";
9// The thread route loads ChatView lazily; its first transform would eat the test's timeout.
10import "~/components/ChatView";
11import { __setClientSettingsForTests } from "~/hooks/useSettings";
12import { useRightPanelStore } from "~/rightPanelStore";
13import { getRouter } from "~/router";
14import {
15 ENVIRONMENT_ID,
16 installFakeEnvironment,
17 threadWithHistory,
18 type FakeDriver,
19} from "../../test/fakeEnvironment";
20import { act, render } from "../../test/render";
21​
22// The socket is the only fake layer.
23vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
24 const [actual, { fakeDriver }, Layer] = await Promise.all([
25 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
26 import("../../test/fakeEnvironment"),
27 import("effect/Layer"),
28 ]);
29 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
30});
31​
32vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
33 ...(await original()),
34 trackRpcRequestSent: () => {},
35}));
36​
37vi.mock(import("~/state/server"), async (original) => {
38 const actual = await original();
39 const { Atom } = await import("effect/reactivity");
40 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
41 const keybindings = compileResolvedKeybindingsConfig([
42 { key: "mod+shift+]", command: "thread.next", when: "!previewFocus && !previewOpen" },
43 { key: "mod+1", command: "thread.jump.1", when: "!previewFocus" },
44 { key: "ctrl+e", command: "thread.next", when: "!terminalFocus" },
45 { key: "ctrl+q", command: "thread.previous", when: "!terminalFocus" },
46 ]);
47 return { ...actual, primaryServerKeybindingsAtom: Atom.make(keybindings) };
48});
49​
50it("keeps custom thread shortcuts working after the composer takes focus", async () => {
51 const first = threadWithHistory("thread-a", 1);
52 const second = threadWithHistory("thread-b", 1);
53 const third = threadWithHistory("thread-c", 1);
54 const threads = [first, second, third];
55 using _environment = installFakeEnvironment(threads);
56 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
57 __setClientSettingsForTests({
58 ...DEFAULT_CLIENT_SETTINGS,
59 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
60 });
61 await page.viewport(1400, 900);
62 const path = (id: string) => `/${ENVIRONMENT_ID}/${id}`;
63 const router = getRouter(createMemoryHistory({ initialEntries: [path(first.id)] }));
64 await router.load();
65 await using _app = await render(<AppRoot router={router} />, {
66 // AppRoot brings its own router.
67 router: false,
68 });
69 const composer = page.getByTestId("composer-editor");
70 await userEvent.click(composer);
71 await userEvent.keyboard("{Control>}e{/Control}");
72 await vi.waitFor(() => expect(router.history.location.pathname).toBe(path(second.id)));
73 await userEvent.click(composer);
74 await userEvent.keyboard("{Control>}e{/Control}");
75 await vi.waitFor(() => expect(router.history.location.pathname).toBe(path(third.id)));
76 await userEvent.click(composer);
77 await userEvent.keyboard("{Control>}q{/Control}");
78 await vi.waitFor(() => expect(router.history.location.pathname).toBe(path(second.id)));
79​
80 const input = document.createElement("input");
81 document.body.append(input);
82 using _input = { [Symbol.dispose]: () => input.remove() };
83 for (const attribute of ["data-keybinding-capture", "data-terminal-owner"]) {
84 input.setAttribute(attribute, attribute === "data-terminal-owner" ? "drawer" : "");
85 input.focus();
86 await userEvent.keyboard("{Control>}e{/Control}");
87 expect(router.history.location.pathname).toBe(path(second.id));
88 input.removeAttribute(attribute);
89 }
90​
91 // A focused widget that claims a thread jump (the SSH host suggestions) keeps it.
92 input.addEventListener("keydown", (event) => event.stopPropagation());
93 input.focus();
94 await userEvent.keyboard("{Meta>}1{/Meta}");
95 expect(router.history.location.pathname).toBe(path(second.id));
96});
97​
98it("leaves thread shortcuts and their hints to the preview when their rules exclude it", async () => {
99 const [first, second] = [threadWithHistory("thread-a", 1), threadWithHistory("thread-b", 1)];
100 using _environment = installFakeEnvironment([first, second]);
101 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
102 __setClientSettingsForTests({
103 ...DEFAULT_CLIENT_SETTINGS,
104 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
105 });
106 await page.viewport(1400, 900);
107 const router = getRouter(
108 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
109 );
110 await router.load();
111 await using _app = await render(<AppRoot router={router} />, {
112 // AppRoot brings its own router.
113 router: false,
114 });
115 await expect.element(page.getByText(`Thread ${second.id}`).first()).toBeVisible();
116​
117 const previewChrome = document.createElement("div");
118 previewChrome.dataset.previewPanelMode = "browser";
119 previewChrome.innerHTML = '<button type="button">Reload</button>';
120 document.body.append(previewChrome);
121 using _chrome = { [Symbol.dispose]: () => previewChrome.remove() };
122​
123 const press = () => userEvent.keyboard("{Control>}{Shift>}]{/Shift}{/Control}");
124 const jumpHint = () => document.querySelector("[data-jump-hint]");
125 const whileHoldingControl = async (assertJumpHints: () => void) => {
126 // Every deadline reads as due on subscribe, so hints skip the hold delay.
127 let now = Date.parse("2026-01-01T00:00:00.000Z");
128 using _clock = vi.spyOn(Date, "now").mockImplementation(() => (now += 1000));
129 await userEvent.keyboard("{Control>}");
130 await act(() => {});
131 await vi.waitFor(assertJumpHints);
132 await userEvent.keyboard("{/Control}");
133 };
134 const firstPath = `/${ENVIRONMENT_ID}/${first.id}`;
135​
136 await userEvent.click(page.getByRole("button", { name: "Reload" }));
137 await press();
138 expect(router.history.location.pathname).toBe(firstPath);
139 await whileHoldingControl(() => expect(jumpHint()).toBeNull());
140​
141 const firstRef = scopeThreadRef(ENVIRONMENT_ID, first.id);
142 await act(() => useRightPanelStore.getState().openBrowser(firstRef, null));
143 if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
144 await press();
145 expect(router.history.location.pathname).toBe(firstPath);
146​
147 await act(() => useRightPanelStore.getState().close(firstRef));
148 await press();
149 await vi.waitFor(() =>
150 expect(router.history.location.pathname).toBe(`/${ENVIRONMENT_ID}/${second.id}`),
151 );
152 await whileHoldingControl(() => expect(jumpHint()).not.toBeNull());
153});
154​
155it("waits on thread navigation shortcuts while a confirmation dialog is open", async () => {
156 const [first, second] = [threadWithHistory("thread-a", 1), threadWithHistory("thread-b", 1)];
157 using _environment = installFakeEnvironment([first, second]);
158 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
159 __setClientSettingsForTests({
160 ...DEFAULT_CLIENT_SETTINGS,
161 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
162 });
163 await page.viewport(1400, 900);
164 const firstPath = `/${ENVIRONMENT_ID}/${first.id}`;
165 const secondPath = `/${ENVIRONMENT_ID}/${second.id}`;
166 const router = getRouter(createMemoryHistory({ initialEntries: [firstPath] }));
167 await router.load();
168 await using _app = await render(<AppRoot router={router} />, {
169 // AppRoot brings its own router.
170 router: false,
171 });
172 await expect.element(page.getByText(`Thread ${second.id}`).first()).toBeVisible();
173​
174 const dialog = document.createElement("div");
175 dialog.setAttribute("role", "alertdialog");
176 dialog.innerHTML = '<button type="button">Cancel</button>';
177 document.body.append(dialog);
178 using _dialog = { [Symbol.dispose]: () => dialog.remove() };
179​
180 const events: KeyboardEvent[] = [];
181 const onKeyDown = (event: KeyboardEvent) => {
182 if (event.key === "]" || event.key === "}" || event.key === "1") {
183 events.push(event);
184 }
185 };
186 window.addEventListener("keydown", onKeyDown);
187 using _listener = { [Symbol.dispose]: () => window.removeEventListener("keydown", onKeyDown) };
188​
189 await userEvent.click(page.getByRole("button", { name: "Cancel" }));
190 await userEvent.keyboard("{Control>}{Shift>}]{/Shift}{/Control}");
191 expect(router.history.location.pathname).toBe(firstPath);
192 expect(events.at(-1)?.defaultPrevented).toBe(true);
193​
194 dialog.remove();
195 await userEvent.keyboard("{Control>}{Shift>}]{/Shift}{/Control}");
196 await vi.waitFor(() => expect(router.history.location.pathname).toBe(secondPath));
197​
198 document.body.append(dialog);
199 await userEvent.click(page.getByRole("button", { name: "Cancel" }));
200 await userEvent.keyboard("{Control>}1{/Control}");
201 expect(router.history.location.pathname).toBe(secondPath);
202 expect(events.at(-1)?.defaultPrevented).toBe(true);
203});