Open History to see the last commit
1import type { CodeViewDiffItem, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
2import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
3import { StrictMode, type ComponentProps } from "react";
4import { describe, expect, it, vi } from "vite-plus/test";
5
6import { act, render } from "../../../test/render";
7
8import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
9import { buildFileDiffIdentityKey } from "~/lib/diffRendering";
10
11type ViewerProps = Omit<ComponentProps<typeof StyledDiffCodeView<unknown>>, "options"> & {
12 options: {
13 enableLineSelection: boolean;
14 enableGutterUtility: boolean;
15 onGutterUtilityClick: (
16 range: SelectedLineRange,
17 context: { item: CodeViewDiffItem<unknown> },
18 ) => void;
19 };
20};
21
22// Replace only the virtualized viewer; comment editing and submission use the real components.
23vi.mock("./StyledDiffCodeView", () => ({
24 StyledDiffCodeView: (props: ViewerProps) =>
25 props.items
26 ?.filter((item) => item.type === "diff")
27 .map((item) => (
28 <section key={item.id}>
29 <button
30 disabled={!props.options?.enableLineSelection || !props.options?.enableGutterUtility}
31 onClick={() => {
32 props.onSelectedLinesChange?.({ id: item.id, range });
33 props.options?.onGutterUtilityClick?.(range, { item });
34 }}
35 >
36 Comment on {item.fileDiff.name}
37 </button>
38 {props.selectedLines?.id === item.id ? (
39 <mark>Line {props.selectedLines.range.start}</mark>
40 ) : null}
41 {item.annotations?.map((annotation) => (
42 <div
43 key={`${annotation.side}:${annotation.lineNumber}`}
44 data-annotation={`${annotation.side}:${annotation.lineNumber}`}
45 >
46 {props.renderAnnotation?.(annotation, item.fileDiff, item)}
47 </div>
48 ))}
49 </section>
50 )),
51}));
52
53import { AnnotatableCodeView } from "./AnnotatableCodeView";
54import type { StyledDiffCodeView } from "./StyledDiffCodeView";
55
56const target = DraftId.make("diff-draft-test");
57const defaultRange: SelectedLineRange = { start: 1, end: 1, side: "additions" };
58let range: SelectedLineRange = defaultRange;
59let container: HTMLDivElement;
60
61function file(
62 name: string,
63 fileVersion = 1,
64 type: FileDiffMetadata["type"] = "change",
65 prevName?: string,
66 patchBody = "@@ -1 +1 @@\n-old\n+new\n",
67) {
68 const fileDiff = parsePatchFiles(
69 `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n${patchBody}`,
70 { cacheKeyPrefix: name },
71 )[0]!.files[0]!;
72 fileDiff.type = type;
73 if (prevName) fileDiff.prevName = prevName;
74 return {
75 fileDiff,
76 filePath: name,
77 fileKey: buildFileDiffIdentityKey(fileDiff),
78 fileVersion,
79 collapsed: false,
80 };
81}
82
83function view(
84 files: ReturnType<typeof file>[],
85 codeViewKey = "initial",
86 pendingFiles: FileDiffMetadata[] = [],
87) {
88 return (
89 <StrictMode>
90 <AnnotatableCodeView
91 codeViewKey={codeViewKey}
92 files={files}
93 pendingFiles={pendingFiles}
94 sectionId="unstaged"
95 sectionTitle="Uncommitted"
96 composerDraftTarget={target}
97 options={{}}
98 renderHeaderFilenameSuffix={() => null}
99 renderHeaderPrefix={() => null}
100 onFileCollapsedChange={() => {}}
101 />
102 </StrictMode>
103 );
104}
105
106function click(label: string) {
107 const button = Array.from(container.querySelectorAll("button")).find(
108 (node) => node.textContent === label,
109 );
110 if (!button) throw new Error(`Missing button: ${label}`);
111 return act(() => button.click());
112}
113
114function editor() {
115 const textarea = container.querySelector("textarea");
116 if (!textarea) throw new Error("Comment editor is not available");
117 return textarea;
118}
119
120function typeComment(text: string) {
121 return act(() => {
122 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
123 editor(),
124 text,
125 );
126 editor().dispatchEvent(new Event("input", { bubbles: true }));
127 });
128}
129
130function setup(nextRange: SelectedLineRange = defaultRange): Disposable {
131 const reset = () => {
132 range = defaultRange;
133 useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
134 };
135 reset();
136 range = nextRange;
137 container = document.createElement("div");
138 return { [Symbol.dispose]: reset };
139}
140
141describe("diff comment drafts", () => {
142 it("keeps the text and selected line through refresh and a provisional lazy patch", async () => {
143 using _drafts = setup();
144 const original = file("shared.ts", 1, "rename-pure", "old.ts");
145 await using screen = await render(view([original]), { container });
146 await click("Comment on shared.ts");
147 await typeComment("Keep this draft");
148 const refreshed = file("shared.ts", 2, "rename-pure", "old.ts");
149 await screen.rerender(view([refreshed], "refreshed"));
150 expect(editor().value).toBe("Keep this draft");
151 expect(container.querySelector("mark")?.textContent).toBe("Line 1");
152
153 await screen.rerender(
154 view([], "loading", [
155 { ...refreshed.fileDiff, type: "rename-changed", hunks: [], cacheKey: "shared:pending" },
156 ]),
157 );
158 expect(container.querySelector("textarea")).toBeNull();
159 await screen.rerender(view([refreshed], "loaded"));
160 expect(editor().value).toBe("Keep this draft");
161 expect(container.querySelector("mark")?.textContent).toBe("Line 1");
162 await click("Comment");
163 expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
164 expect.objectContaining({
165 filePath: "shared.ts",
166 text: "Keep this draft",
167 selection: { ...range, endSide: "additions" },
168 }),
169 ]);
170 expect(container.querySelector("p")?.textContent).toBe("Keep this draft");
171 });
172
173 it("anchors upward-dragged drafts and submitted comments below the bottom line", async () => {
174 using _drafts = setup({ start: 3, end: 1, side: "additions" });
175 const entry = file(
176 "upward.ts",
177 1,
178 "change",
179 undefined,
180 "@@ -1,3 +1,3 @@\n one\n-two\n+TWO\n three\n",
181 );
182 await using _screen = await render(view([entry]), { container });
183 await click("Comment on upward.ts");
184 expect(container.querySelector("[data-annotation]")?.getAttribute("data-annotation")).toBe(
185 "additions:3",
186 );
187 await typeComment("Check lines 1-3");
188 await click("Comment");
189 expect(container.querySelector("[data-annotation]")?.getAttribute("data-annotation")).toBe(
190 "additions:3",
191 );
192 expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
193 expect.objectContaining({
194 filePath: "upward.ts",
195 text: "Check lines 1-3",
196 selection: { start: 1, side: "additions", end: 3, endSide: "additions" },
197 }),
198 ]);
199 });
200});