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

PullRequestMarkdownEditor.browser.test.tsx

234 lines8.3 KB

1import { act, render, type Screen } from "../../../test/render";
2import { AuthSourceControlWriteScope, EnvironmentId, ProjectId } from "@t3tools/contracts";
3import { useState } from "react";
4import { expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6​
7const permissions = vi.hoisted(() => ({
8 allowed: new Set<string>(),
9 listeners: new Set<() => void>(),
10}));
11​
12vi.mock(import("~/state/session"), async (original) => {
13 const { useSyncExternalStore } = await import("react");
14 const canWrite = (environmentId: string | null, scope: string) =>
15 scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId ?? "");
16 return {
17 ...(await original()),
18 readEnvironmentScope: canWrite,
19 useEnvironmentScope: (environmentId, scope) =>
20 useSyncExternalStore(
21 (listener) => {
22 permissions.listeners.add(listener);
23 return () => permissions.listeners.delete(listener);
24 },
25 () => canWrite(environmentId, scope),
26 ),
27 };
28});
29​
30vi.mock(import("~/state/pullRequests"), async (original) => ({
31 ...(await original()),
32 usePullRequestFilterOptions: (targets: ReadonlyArray<unknown>) => ({
33 labels: [],
34 authors:
35 targets.length === 0
36 ? []
37 : [
38 { login: "julius", name: "Julius", avatarUrl: null },
39 { login: "theo", name: "Theo", avatarUrl: null },
40 ],
41 references:
42 targets.length === 0
43 ? []
44 : [
45 { reference: "#12", kind: "issue", number: 12, title: "Crash", state: "open" },
46 { reference: "!12", kind: "change-request", number: 12, title: "Fix", state: "open" },
47 ],
48 error: null,
49 isPending: false,
50 }),
51}));
52​
53import { RightPanelSheet } from "../RightPanelSheet";
54import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
55​
56const secondary = EnvironmentId.make("secondary");
57const onSave = vi.fn<(next: string) => void>();
58const onCancel = vi.fn<() => void>();
59​
60function setup() {
61 permissions.allowed.clear();
62 permissions.listeners.clear();
63 onSave.mockReset();
64 onCancel.mockReset();
66​
67async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
68 return render(
69 <PullRequestMarkdownEditor
70 value={options?.value ?? "Original description"}
71 cwd="/repo"
72 environmentId={secondary}
73 completionScope={{
74 environmentId: secondary,
75 projectId: ProjectId.make("project"),
76 support: { mentions: true, referenceSigils: ["#", "!"] },
77 }}
78 label="Pull request description"
79 saving={false}
80 allowEmpty={options?.allowEmpty ?? false}
81 onSave={onSave}
82 onCancel={onCancel}
83 />,
84 );
86​
87function button(screen: Screen, label: string) {
88 const match = [...screen.container.querySelectorAll("button")].find(
89 (element) => element.textContent === label,
90 );
91 expect(match, `button ${label}`).toBeDefined();
92 return match!;
94​
95const clickSave = (screen: Screen) => act(async () => button(screen, "Save").click());
96​
97async function grant(allowed: boolean) {
98 await act(async () => {
99 if (allowed) permissions.allowed.add(secondary);
100 else permissions.allowed.delete(secondary);
101 permissions.listeners.forEach((listener) => listener());
102 });
104​
105it("updates the draft direction as the prose changes", async () => {
106 setup();
107 permissions.allowed.add(secondary);
108 await using screen = await openEditor({ value: "Review the changes." });
109 const textarea = screen.container.querySelector("textarea")!;
110​
111 expect(getComputedStyle(textarea).direction).toBe("ltr");
112​
113 const hebrew = "Review בבקשה בדוק את התיקון לפני המיזוג.";
114 await userEvent.fill(textarea, hebrew);
115 expect(textarea.value).toBe(hebrew);
116 expect(getComputedStyle(textarea).direction).toBe("rtl");
117​
118 const english = "Review the example `בבקשה בדוק את התיקון לפני המיזוג`.";
119 await userEvent.fill(textarea, english);
120 expect(textarea.value).toBe(english);
121 expect(getComputedStyle(textarea).direction).toBe("ltr");
122});
123​
124it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
125 setup();
126 permissions.allowed.add(secondary);
127 await using screen = await openEditor();
128 const textarea = screen.container.querySelector("textarea")!;
129 await userEvent.clear(textarea);
130 await userEvent.type(textarea, "Keep these unsaved edits");
131​
132 await grant(false);
133 expect(button(screen, "Save").disabled).toBe(true);
134 expect(screen.container.querySelector("textarea")).toBe(textarea);
135​
136 await grant(true);
137 await clickSave(screen);
138 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
139});
140​
141it("completes @mentions and !references on Enter, and Escape closes the list until the next keystroke", async () => {
142 setup();
143 permissions.allowed.add(secondary);
144 await using screen = await openEditor({ value: "" });
145 const textarea = screen.container.querySelector("textarea")!;
146 await userEvent.type(textarea, "Thanks @ju");
147 await expect.element(page.getByRole("option", { name: /julius/ })).toBeVisible();
148​
149 await userEvent.keyboard("{Enter}");
150 expect(textarea.value).toBe("Thanks @julius ");
151 await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
152​
153 await userEvent.type(textarea, "and @");
154 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
155 await userEvent.keyboard("{Escape}");
156 await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
157 await userEvent.type(textarea, "t");
158 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
159​
160 await userEvent.type(textarea, " fixes !1");
161 await expect.element(page.getByRole("option", { name: /Fix/ })).toBeVisible();
162 await userEvent.keyboard("{Enter}");
163 expect(textarea.value).toBe("Thanks @julius and @t fixes !12 ");
164 expect(onCancel).not.toHaveBeenCalled();
165 expect(onSave).not.toHaveBeenCalled();
166});
167​
168it.each(["ArrowUp", "ArrowDown"])(
169 "keeps Shift+%s available for native selection while completing mentions",
170 async (key) => {
171 setup();
172 permissions.allowed.add(secondary);
173 await using screen = await openEditor({ value: "previous line\n\nnext line" });
174 const textarea = screen.container.querySelector("textarea")!;
175 await userEvent.click(textarea);
176 const middle = "previous line\n".length;
177 textarea.setSelectionRange(middle, middle);
178 await userEvent.keyboard("@");
179 const first = page.getByRole("option", { name: /julius/ });
180 const second = page.getByRole("option", { name: /theo/ });
181 await expect.element(first).toHaveAttribute("aria-selected", "true");
182 await userEvent.keyboard("{ArrowDown}");
183 await expect.element(second).toHaveAttribute("aria-selected", "true");
184 await userEvent.keyboard("{ArrowUp}");
185 await expect.element(first).toHaveAttribute("aria-selected", "true");
186​
187 await userEvent.keyboard(`{Shift>}{${key}}{/Shift}`);
188​
189 expect(textarea.selectionStart).toBeLessThan(textarea.selectionEnd);
190 expect(textarea.value).toBe("previous line\n@\nnext line");
191 expect(onSave).not.toHaveBeenCalled();
192 expect(onCancel).not.toHaveBeenCalled();
193 },
194);
195​
196it("Escape cancels the edit without closing the right panel sheet", async () => {
197 setup();
198 permissions.allowed.add(secondary);
199 const onCloseSheet = vi.fn();
200 function EditableComment() {
201 const [editing, setEditing] = useState(true);
202 if (!editing) return <p>Original description</p>;
203 return (
204 <PullRequestMarkdownEditor
205 value="Original description"
206 cwd="/repo"
207 environmentId={secondary}
208 completionScope={null}
209 label="Pull request description"
210 saving={false}
211 onSave={onSave}
212 onCancel={() => {
213 onCancel();
214 setEditing(false);
215 }}
216 />
217 );
218 }
219 await using _screen = await render(
220 <RightPanelSheet animationDurationMs={0} open onClose={onCloseSheet}>
221 <EditableComment />
222 </RightPanelSheet>,
223 );
224 const textarea = page.getByRole("textbox", { name: "Pull request description" });
225 await expect.element(textarea).toHaveFocus();
226​
227 await userEvent.keyboard("{Escape}");
228 await expect.element(textarea).not.toBeInTheDocument();
229 expect(onCancel).toHaveBeenCalledTimes(1);
230 expect(onCloseSheet).not.toHaveBeenCalled();
231​
232 await userEvent.keyboard("{Escape}");
233 expect(onCloseSheet).toHaveBeenCalledTimes(1);
234});