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

PullRequestMarkdownEditor.browser.test.tsx

187 lines6.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("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("Escape cancels the edit without closing the right panel sheet", async () => {
150 setup();
151 permissions.allowed.add(secondary);
152 const onCloseSheet = vi.fn();
153 function EditableComment() {
154 const [editing, setEditing] = useState(true);
155 if (!editing) return <p>Original description</p>;
156 return (
157 <PullRequestMarkdownEditor
158 value="Original description"
159 cwd="/repo"
160 environmentId={secondary}
161 completionScope={null}
162 label="Pull request description"
163 saving={false}
164 onSave={onSave}
165 onCancel={() => {
166 onCancel();
167 setEditing(false);
168 }}
169 />
170 );
171 }
172 await using _screen = await render(
173 <RightPanelSheet animationDurationMs={0} open onClose={onCloseSheet}>
174 <EditableComment />
175 </RightPanelSheet>,
176 );
177 const textarea = page.getByRole("textbox", { name: "Pull request description" });
178 await expect.element(textarea).toHaveFocus();
179​
180 await userEvent.keyboard("{Escape}");
181 await expect.element(textarea).not.toBeInTheDocument();
182 expect(onCancel).toHaveBeenCalledTimes(1);
183 expect(onCloseSheet).not.toHaveBeenCalled();
184​
185 await userEvent.keyboard("{Escape}");
186 expect(onCloseSheet).toHaveBeenCalledTimes(1);
187});