mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
Isolate GitHub review drafts by pull request context (#4252)
This commit is contained in:
@@ -26,7 +26,7 @@ import {
|
||||
setPullRequestData,
|
||||
updateTimeline,
|
||||
} from "./pullRequest";
|
||||
import { requireConnection } from "./repository";
|
||||
import { requireConnection, useGhRepository, type GHConnection } from "./repository";
|
||||
|
||||
const settle = (ps: Array<Promise<unknown>>) => Promise.allSettled(ps).then(() => undefined);
|
||||
|
||||
@@ -175,18 +175,26 @@ export async function createReview(
|
||||
return review;
|
||||
}
|
||||
|
||||
/** Submits the pending review `reviewId`. */
|
||||
export async function submitReview(number: number, reviewId: string, event: GHPullRequestReviewEvent, body?: string) {
|
||||
await api.submitReview(reviewId, event, body || null);
|
||||
await refreshReview(number);
|
||||
await reloadPullRequestData(number, "mergeability").catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Submit Review popup: submits the pending review, or creates a submitted one. */
|
||||
export async function submitOrCreateReview(number: number, event: GHPullRequestReviewEvent, body: string) {
|
||||
/** Submits or creates a review; returns false if the connection changed before it could send. */
|
||||
export async function submitOrCreateReview(
|
||||
number: number,
|
||||
event: GHPullRequestReviewEvent,
|
||||
body: string,
|
||||
connection: GHConnection,
|
||||
): Promise<boolean> {
|
||||
const isCurrent = () => useGhRepository.getState().connection === connection;
|
||||
const pending = await loadPullRequestData(number, "pendingReview");
|
||||
if (pending) await submitReview(number, pending.id, event, body);
|
||||
else await createReview(number, { event, body: body || undefined });
|
||||
if (!isCurrent()) return false;
|
||||
if (pending) {
|
||||
await api.submitReview(pending.id, event, body || null);
|
||||
} else {
|
||||
const id = await pullRequestId(number);
|
||||
if (!isCurrent()) return false;
|
||||
await api.createReview({ pullRequestId: id, event, body: body || undefined });
|
||||
}
|
||||
if (isCurrent()) await refreshReview(number);
|
||||
if (pending && isCurrent()) await reloadPullRequestData(number, "mergeability").catch(() => undefined);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Discards a pending review with its comments. */
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* Request Changes (not for the author) and Comment. Shown above the button that opened
|
||||
* it, or centred in the window. 500×200, resizable.
|
||||
*/
|
||||
import { useState, type CSSProperties } from "react";
|
||||
import { useEffect, useState, type CSSProperties } from "react";
|
||||
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
|
||||
import { useTx, tx } from "@/platform/i18n";
|
||||
import { ask } from "@/workbench/messages";
|
||||
@@ -13,40 +13,59 @@ import { errorMessage } from "../api/client";
|
||||
import type { GHPullRequestReviewEvent } from "../api/types";
|
||||
import { deleteReview, submitOrCreateReview } from "../data/operations";
|
||||
import { loadPullRequestData, usePullRequestData } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { openDialog } from "../ui/dialogs";
|
||||
import { setReviewText, useReviewText } from "./state";
|
||||
import { reviewDraftKey, setReviewText, useReviewText } from "./state";
|
||||
import styles from "./Details.module.css";
|
||||
|
||||
/** Opens the popup for pull request `number`; resolves when it closes. */
|
||||
export function showSubmitReview(number: number, anchor?: Element | null): Promise<unknown> {
|
||||
const draftKey = reviewDraftKey(useGhRepository.getState().connection, number);
|
||||
if (draftKey === null) return Promise.resolve(null);
|
||||
// The details and the pending review are needed for the buttons and the header.
|
||||
void loadPullRequestData(number, "details").catch(() => undefined);
|
||||
void loadPullRequestData(number, "pendingReview").catch(() => undefined);
|
||||
const at = anchor?.isConnected
|
||||
? anchor
|
||||
: { x: Math.round(window.innerWidth / 2) - 250, y: Math.round(window.innerHeight / 3) };
|
||||
return openDialog<true>((done) => <SubmitReview number={number} anchor={at} onClose={() => done(null)} />);
|
||||
return openDialog<true>((done) => (
|
||||
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
|
||||
));
|
||||
}
|
||||
|
||||
function SubmitReview(props: { number: number; anchor: Element | { x: number; y: number }; onClose: () => void }) {
|
||||
const { number } = props;
|
||||
function SubmitReview(props: {
|
||||
number: number;
|
||||
draftKey: string;
|
||||
anchor: Element | { x: number; y: number };
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { number, draftKey, onClose } = props;
|
||||
const t = useTx();
|
||||
const details = usePullRequestData(number, "details").value;
|
||||
const pending = usePullRequestData(number, "pendingReview").value;
|
||||
const text = useReviewText((s) => s.text[number] ?? "");
|
||||
const text = useReviewText((s) => s.text[draftKey] ?? "");
|
||||
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (activeDraftKey !== draftKey) onClose();
|
||||
}, [activeDraftKey, draftKey, onClose]);
|
||||
if (activeDraftKey !== draftKey) return null;
|
||||
|
||||
const comments = pending?.commentsCount ?? 0;
|
||||
const hasAnyComment = text.length > 0 || comments > 0;
|
||||
const isAuthor = details?.viewerDidAuthor ?? false;
|
||||
|
||||
const submit = async (event: GHPullRequestReviewEvent) => {
|
||||
const connection = useGhRepository.getState().connection;
|
||||
if (!connection || reviewDraftKey(connection, number) !== draftKey) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitOrCreateReview(number, event, text);
|
||||
setReviewText(number, "");
|
||||
props.onClose();
|
||||
if (await submitOrCreateReview(number, event, text, connection)) {
|
||||
setReviewText(draftKey, "");
|
||||
onClose();
|
||||
}
|
||||
} catch (e) {
|
||||
setError(errorMessage(e));
|
||||
} finally {
|
||||
@@ -54,7 +73,8 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
}
|
||||
};
|
||||
const discard = async () => {
|
||||
if (!pending) return;
|
||||
const connection = useGhRepository.getState().connection;
|
||||
if (!pending || reviewDraftKey(connection, number) !== draftKey) return;
|
||||
const r = await ask({
|
||||
title: tx("Discard Pending Review"),
|
||||
body: tx("Are you sure you want to delete all pending comments?"),
|
||||
@@ -64,7 +84,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
],
|
||||
cancel: false,
|
||||
});
|
||||
if (r.button !== "yes") return;
|
||||
if (r.button !== "yes" || useGhRepository.getState().connection !== connection) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await deleteReview(number, pending.id);
|
||||
@@ -82,7 +102,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
placement={anchored ? "top-start" : "bottom-start"}
|
||||
onClose={(reason) => {
|
||||
// A click outside does not drop a review while it is being sent.
|
||||
if (reason !== "outside" || !busy) props.onClose();
|
||||
if (reason !== "outside" || !busy) onClose();
|
||||
}}
|
||||
role="dialog"
|
||||
aria-label={t("Submit Review")}
|
||||
@@ -100,7 +120,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
{pending && comments > 0 && (
|
||||
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
|
||||
)}
|
||||
<IconButton icon="close" size="small" title="Close" onClick={props.onClose} />
|
||||
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
|
||||
</div>
|
||||
<textarea
|
||||
data-autofocus
|
||||
@@ -110,7 +130,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setError(null);
|
||||
setReviewText(number, e.target.value);
|
||||
setReviewText(draftKey, e.target.value);
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
import type { GHPRMergeabilityState, GHPullRequest, GHRepository, GHUser } from "../api/types";
|
||||
import * as api from "../api/requests";
|
||||
import type {
|
||||
GHPRMergeabilityState,
|
||||
GHPullRequest,
|
||||
GHPullRequestPendingReview,
|
||||
GHRepository,
|
||||
GHUser,
|
||||
} from "../api/types";
|
||||
import { reviewersStates } from "../data/model";
|
||||
import { submitOrCreateReview } from "../data/operations";
|
||||
import { clearPullRequests, setPullRequestData } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { GithubDialogHost } from "../ui/dialogs";
|
||||
import { ReviewActions } from "./ReviewActions";
|
||||
import { useReviewText } from "./state";
|
||||
import { StatusSection } from "./StatusSection";
|
||||
import { showSubmitReview } from "./SubmitReviewPopup";
|
||||
|
||||
const me: GHUser = { __typename: "User", id: "U1", login: "me", url: "", avatarUrl: "", name: null };
|
||||
const bob: GHUser = { __typename: "User", id: "U2", login: "bob", url: "", avatarUrl: "", name: "Bob" };
|
||||
@@ -175,3 +186,112 @@ describe("ReviewActions", () => {
|
||||
expect(screen.getByText("Set Myself as Reviewer")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Submit Review draft", () => {
|
||||
const editor = () => screen.getByRole<HTMLTextAreaElement>("textbox", { name: "Review comment" });
|
||||
const close = () => fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
|
||||
function open(number: number) {
|
||||
act(() => {
|
||||
setPullRequestData(number, "details", () => pr({ number }));
|
||||
setPullRequestData(number, "pendingReview", () => null);
|
||||
void showSubmitReview(number);
|
||||
});
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useReviewText.setState({ text: {} });
|
||||
});
|
||||
|
||||
it("restores the draft only for the same repository, account and pull request", () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
render(<GithubDialogHost />);
|
||||
|
||||
open(7);
|
||||
fireEvent.change(editor(), { target: { value: "Draft for org/app #7" } });
|
||||
close();
|
||||
|
||||
open(8);
|
||||
expect(editor().value).toBe("");
|
||||
close();
|
||||
|
||||
act(() => {
|
||||
useGhRepository.setState({
|
||||
connection: {
|
||||
...connection,
|
||||
coordinates: { owner: "org", name: "other" },
|
||||
repository: { ...repository, id: "R2", nameWithOwner: "org/other" },
|
||||
},
|
||||
});
|
||||
});
|
||||
open(7);
|
||||
const otherRepositoryDraft = editor().value;
|
||||
close();
|
||||
|
||||
act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } }));
|
||||
open(7);
|
||||
const otherAccountDraft = editor().value;
|
||||
close();
|
||||
|
||||
act(() => useGhRepository.setState({ connection }));
|
||||
open(7);
|
||||
const restoredDraft = editor().value;
|
||||
close();
|
||||
|
||||
expect(otherRepositoryDraft).toBe("");
|
||||
expect(otherAccountDraft).toBe("");
|
||||
expect(restoredDraft).toBe("Draft for org/app #7");
|
||||
});
|
||||
|
||||
it("closes an open review popup when its account changes", () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
render(<GithubDialogHost />);
|
||||
open(7);
|
||||
fireEvent.change(editor(), { target: { value: "Draft for me" } });
|
||||
|
||||
act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } }));
|
||||
const remainingEditor = screen.queryByRole("textbox", { name: "Review comment" });
|
||||
if (remainingEditor) close();
|
||||
expect(remainingEditor).toBeNull();
|
||||
});
|
||||
|
||||
it("cancels submission if the account changes during the pull request lookup", async () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
const lookup = deferred<string>();
|
||||
const findPullRequestId = vi.spyOn(api, "findPullRequestId").mockReturnValue(lookup.promise);
|
||||
const createReview = vi.spyOn(api, "createReview").mockRejectedValue(new Error("Unexpected review mutation"));
|
||||
|
||||
const submission = submitOrCreateReview(7, "COMMENT", "Draft for me", connection);
|
||||
await vi.waitFor(() => expect(findPullRequestId).toHaveBeenCalledWith(7));
|
||||
useGhRepository.setState({ connection: { ...connection, currentUser: bob } });
|
||||
lookup.resolve("PR1");
|
||||
|
||||
await expect(submission).resolves.toBe(false);
|
||||
expect(createReview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels submission if the connection closes during the pending review lookup", async () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
setPullRequestData(8, "details", () => pr({ number: 8 }));
|
||||
const lookup = deferred<GHPullRequestPendingReview>();
|
||||
const findPendingReview = vi.spyOn(api, "findPendingReview").mockReturnValue(lookup.promise);
|
||||
const submitReview = vi.spyOn(api, "submitReview").mockRejectedValue(new Error("Unexpected review mutation"));
|
||||
|
||||
const submission = submitOrCreateReview(8, "COMMENT", "Draft for me", connection);
|
||||
await vi.waitFor(() => expect(findPendingReview).toHaveBeenCalledWith("PR1"));
|
||||
useGhRepository.setState({ connection: null });
|
||||
lookup.resolve({ id: "review-1", commentsCount: 0, state: "PENDING" });
|
||||
|
||||
await expect(submission).resolves.toBe(false);
|
||||
expect(submitReview).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
* Client state of the details tab: the changes of single commits (REST `commits/{sha}`,
|
||||
* cached per commit), the changes tree's grouping (`GithubPullRequestsProjectUISettings
|
||||
* .changesGrouping`, kept in local storage) and the Submit Review popup's text, kept per
|
||||
* pull request until the review is submitted (IntelliJ keeps it as the pending review's
|
||||
* comment).
|
||||
* pull request, repository and account until the review is submitted.
|
||||
*/
|
||||
import { useEffect } from "react";
|
||||
import { create } from "zustand";
|
||||
@@ -11,7 +10,7 @@ import { errorMessage } from "../api/client";
|
||||
import { commitChangedFiles } from "../api/requests";
|
||||
import type { GHCommitFile } from "../api/types";
|
||||
import type { Loadable } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { useGhRepository, type GHConnection } from "../data/repository";
|
||||
|
||||
const useCommitFiles = create<{ bySha: Record<string, Loadable<GHCommitFile[]>> }>(() => ({ bySha: {} }));
|
||||
|
||||
@@ -71,9 +70,13 @@ export function setGroupByDirectory(on: boolean) {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** The Submit Review popup's text per pull request. */
|
||||
export const useReviewText = create<{ text: Record<number, string> }>(() => ({ text: {} }));
|
||||
/** The Submit Review popup's text by GitHub account, repository and pull request. */
|
||||
export const useReviewText = create<{ text: Record<string, string> }>(() => ({ text: {} }));
|
||||
|
||||
export function setReviewText(number: number, text: string) {
|
||||
useReviewText.setState((s) => ({ text: { ...s.text, [number]: text } }));
|
||||
export function reviewDraftKey(connection: GHConnection | null, number: number): string | null {
|
||||
return connection ? JSON.stringify([connection.currentUser.id, connection.repository.id, number]) : null;
|
||||
}
|
||||
|
||||
export function setReviewText(key: string, text: string) {
|
||||
useReviewText.setState((s) => ({ text: { ...s.text, [key]: text } }));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user