Open History to see the last commit
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();
65}
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 );
85}
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!;
93}
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 });
103}
104
105it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
106 setup();
107 permissions.allowed.add(secondary);
108 await using screen = await openEditor();
109 const textarea = screen.container.querySelector("textarea")!;
110 await userEvent.clear(textarea);
111 await userEvent.type(textarea, "Keep these unsaved edits");
112
113 await grant(false);
114 expect(button(screen, "Save").disabled).toBe(true);
115 expect(screen.container.querySelector("textarea")).toBe(textarea);
116
117 await grant(true);
118 await clickSave(screen);
119 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
120});
121
122it("completes @mentions and !references on Enter, and Escape closes the list until the next keystroke", async () => {
123 setup();
124 permissions.allowed.add(secondary);
125 await using screen = await openEditor({ value: "" });
126 const textarea = screen.container.querySelector("textarea")!;
127 await userEvent.type(textarea, "Thanks @ju");
128 await expect.element(page.getByRole("option", { name: /julius/ })).toBeVisible();
129
130 await userEvent.keyboard("{Enter}");
131 expect(textarea.value).toBe("Thanks @julius ");
132 await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
133
134 await userEvent.type(textarea, "and @");
135 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
136 await userEvent.keyboard("{Escape}");
137 await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
138 await userEvent.type(textarea, "t");
139 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
140
141 await userEvent.type(textarea, " fixes !1");
142 await expect.element(page.getByRole("option", { name: /Fix/ })).toBeVisible();
143 await userEvent.keyboard("{Enter}");
144 expect(textarea.value).toBe("Thanks @julius and @t fixes !12 ");
145 expect(onCancel).not.toHaveBeenCalled();
146 expect(onSave).not.toHaveBeenCalled();
147});
148
149it.each(["ArrowUp", "ArrowDown"])(
150 "keeps Shift+%s available for native selection while completing mentions",
151 async (key) => {
152 setup();
153 permissions.allowed.add(secondary);
154 await using screen = await openEditor({ value: "previous line\n\nnext line" });
155 const textarea = screen.container.querySelector("textarea")!;
156 await userEvent.click(textarea);
157 const middle = "previous line\n".length;
158 textarea.setSelectionRange(middle, middle);
159 await userEvent.keyboard("@");
160 const first = page.getByRole("option", { name: /julius/ });
161 const second = page.getByRole("option", { name: /theo/ });
162 await expect.element(first).toHaveAttribute("aria-selected", "true");
163 await userEvent.keyboard("{ArrowDown}");
164 await expect.element(second).toHaveAttribute("aria-selected", "true");
165 await userEvent.keyboard("{ArrowUp}");
166 await expect.element(first).toHaveAttribute("aria-selected", "true");
167
168 await userEvent.keyboard(`{Shift>}{${key}}{/Shift}`);
169
170 expect(textarea.selectionStart).toBeLessThan(textarea.selectionEnd);
171 expect(textarea.value).toBe("previous line\n@\nnext line");
172 expect(onSave).not.toHaveBeenCalled();
173 expect(onCancel).not.toHaveBeenCalled();
174 },
175);
176
177it("Escape cancels the edit without closing the right panel sheet", async () => {
178 setup();
179 permissions.allowed.add(secondary);
180 const onCloseSheet = vi.fn();
181 function EditableComment() {
182 const [editing, setEditing] = useState(true);
183 if (!editing) return <p>Original description</p>;
184 return (
185 <PullRequestMarkdownEditor
186 value="Original description"
187 cwd="/repo"
188 environmentId={secondary}
189 completionScope={null}
190 label="Pull request description"
191 saving={false}
192 onSave={onSave}
193 onCancel={() => {
194 onCancel();
195 setEditing(false);
196 }}
197 />
198 );
199 }
200 await using _screen = await render(
201 <RightPanelSheet animationDurationMs={0} open onClose={onCloseSheet}>
202 <EditableComment />
203 </RightPanelSheet>,
204 );
205 const textarea = page.getByRole("textbox", { name: "Pull request description" });
206 await expect.element(textarea).toHaveFocus();
207
208 await userEvent.keyboard("{Escape}");
209 await expect.element(textarea).not.toBeInTheDocument();
210 expect(onCancel).toHaveBeenCalledTimes(1);
211 expect(onCloseSheet).not.toHaveBeenCalled();
212
213 await userEvent.keyboard("{Escape}");
214 expect(onCloseSheet).toHaveBeenCalledTimes(1);
215});