import { Check, ChevronDown, ChevronUp, FileCode2, GitBranch, History, MessageSquare, TriangleAlert, UserPlus, } from "lucide-react"; import * as React from "react"; import { toast } from "sonner"; import { DiscussedInChannels } from "./DiscussionChannels"; import { ProjectOriginReference } from "./ProjectOriginReference"; import { ForumComposer } from "@/features/forum/ui/ForumComposer"; import { type ProjectPullRequest, type Repository as Project, type ProjectPullRequestCommentAnchor, useCreateProjectPullRequestCommentMutation, } from "@/features/projects/hooks"; import { projectPullRequestCommentTimelineKind } from "@/features/projects/projectPullRequests.mjs"; import { entityDiscussionQuery } from "@/features/projects/lib/discussionChannels"; import { pullRequestShareLink } from "@/features/projects/lib/projectShareLinks"; import { formatExactTimestamp, relativeTime, } from "@/features/projects/lib/projectsViewHelpers"; import { canReviewProjectPullRequest } from "@/features/projects/pullRequestReviews"; import type { UserProfileLookup } from "@/features/profile/lib/identity"; import { useIdentityQuery } from "@/shared/api/hooks"; import type { ChannelMember } from "@/shared/api/types"; import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; import { ProjectFeedRow, ProjectFeedRowCluster, ProjectFeedRowMonoCell, } from "./ProjectFeedRow"; import { CopyCommitHashButton } from "./ProjectCommitCopyButton"; import { ProjectDetailSection } from "./ProjectDetailSection"; import type { OpenMergeRecoveryTerminal } from "./MergePullRequestButton"; import { ProfileAuthorName, ProfileIdentityButton, } from "./ProjectProfileIdentity"; import { ProjectRichContent } from "./ProjectRichContent"; import { PullRequestMetaHeader } from "./PullRequestMetaRail"; import { PullRequestReviewCard } from "./PullRequestReviewCard"; import { ShareLinkButton } from "./ShareLinkButton"; import { ProjectStatusProgressIcon, type ProjectStatusProgressState, } from "./ProjectStatusProgressIcon"; import { ProjectWorkItemGroup } from "./ProjectWorkItemGroup"; import { ProjectWorkItemRow } from "./ProjectWorkItemRow"; export { PullRequestMetaHeader } from "./PullRequestMetaRail"; function profileForPubkey(pubkey: string, profiles?: UserProfileLookup) { return profiles?.[normalizePubkey(pubkey)] ?? null; } function labelForPubkey(pubkey: string, profiles?: UserProfileLookup) { const profile = profileForPubkey(pubkey, profiles); return ( profile?.displayName?.trim() || profile?.nip05Handle?.trim() || truncatePubkey(pubkey) ); } function pullRequestStatusClassName(status: ProjectPullRequest["status"]) { if (status === "Closed") return "text-destructive"; if (status === "Draft") return "text-muted-foreground"; if (status === "Merged") return "text-purple-400"; return "text-green-500"; } const PULL_REQUEST_STATUS_ORDER: readonly ProjectPullRequest["status"][] = [ "Open", "Draft", "Merged", "Closed", ]; function pullRequestProgressState( status: ProjectPullRequest["status"], ): ProjectStatusProgressState { if (status === "Draft") return "queued"; if (status === "Merged") return "completed"; if (status === "Closed") return "canceled"; return "review"; } function pullRequestMembers( project: Project, pullRequest: ProjectPullRequest, profiles?: UserProfileLookup, ): ChannelMember[] { return [ ...new Set([ project.owner, pullRequest.author, ...project.contributors, ...pullRequest.recipients, ]), ].map((pubkey) => { const profile = profileForPubkey(pubkey, profiles); return { pubkey, role: "member" as const, isAgent: profile?.isAgent === true, joinedAt: new Date(0).toISOString(), displayName: profile?.displayName?.trim() || profile?.nip05Handle?.trim() || null, }; }); } function AuthorIdentity({ avatarSize = "md", profiles, pubkey, role, showLabel = true, }: { avatarSize?: "xs" | "sm" | "md"; profiles?: UserProfileLookup; pubkey: string; role?: React.ReactNode; showLabel?: boolean; }) { const profile = profileForPubkey(pubkey, profiles); return ( ); } /** Commit hash chip that jumps to the commit detail when a handler is given. */ function CommitHashChip({ hash, onOpenCommit, }: { hash: string; onOpenCommit?: (commitHash: string) => void; }) { const short = hash.slice(0, 7); if (!onOpenCommit) { return ( {short} ); } return ( ); } function PullRequestCommitRow({ author, branch, createdAt, hash, message, onOpenCommit, profiles, }: { author: string; branch: string | null; createdAt: number; hash: string | null; message: string; onOpenCommit?: (commitHash: string) => void; profiles?: UserProfileLookup; }) { const authorProfile = profileForPubkey(author, profiles); const authorLabel = labelForPubkey(author, profiles); const openCommit = hash && onOpenCommit ? () => onOpenCommit(hash) : undefined; return ( {authorLabel}{" "} authored {branch ? ( {branch} ) : null} } onOpen={openCommit} testId="project-pull-request-commit-row" title={message} trailing={ <> {hash ? ( ) : null} {relativeTime(createdAt)} } /> ); } function PullRequestRow({ onOpen, profiles, pullRequest, }: { onOpen: () => void; profiles?: UserProfileLookup; pullRequest: ProjectPullRequest; }) { const authorProfile = profileForPubkey(pullRequest.author, profiles); const authorLabel = labelForPubkey(pullRequest.author, profiles); const statusClassName = pullRequestStatusClassName(pullRequest.status); return ( {pullRequest.branchName} ) : undefined } onOpen={onOpen} statusIcon={ } testId="project-pull-request-row" title={pullRequest.title} trailing={ <> {relativeTime(pullRequest.createdAt)} } /> ); } /** GitHub-style PR title line, rendered as the top of the review detail * card. Status, branches, and dates sit in the meta header below. */ export function PullRequestDetailHeader({ profiles, pullRequest, }: { profiles?: UserProfileLookup; pullRequest: ProjectPullRequest; }) { const authorLabel = labelForPubkey(pullRequest.author, profiles); return (

{pullRequest.title}{" "} #{pullRequest.id.slice(0, 8)}

{authorLabel} {relativeTime(pullRequest.createdAt)}

); } /** Full pull-request conversation, review actions, and comment composer. */ export function ProjectPullRequestDetail({ diffStats, filesChanged, filesCount, forceOpenFiles = false, onOpenInlineComment, onOpenCommit, onOpenTerminal, profiles, project, pullRequest, }: { diffStats?: { additions: number; deletions: number } | null; filesChanged?: React.ReactNode; filesCount?: number; forceOpenFiles?: boolean; onOpenInlineComment?: (anchor: ProjectPullRequestCommentAnchor) => void; onOpenCommit?: (commitHash: string) => void; onOpenTerminal?: OpenMergeRecoveryTerminal; profiles?: UserProfileLookup; project: Project; pullRequest: ProjectPullRequest; }) { const identityQuery = useIdentityQuery(); const commentMutation = useCreateProjectPullRequestCommentMutation(project); const [ expandedReviewHistoryPullRequestIds, setExpandedReviewHistoryPullRequestIds, ] = React.useState>(() => new Set()); const [ collapsedReviewHistoryPullRequestIds, setCollapsedReviewHistoryPullRequestIds, ] = React.useState>(() => new Set()); const [filesOpen, setFilesOpen] = React.useState(forceOpenFiles); const [filesOpenForId, setFilesOpenForId] = React.useState(pullRequest.id); if (filesOpenForId !== pullRequest.id) { setFilesOpenForId(pullRequest.id); setFilesOpen(forceOpenFiles); } const members = React.useMemo( () => pullRequestMembers(project, pullRequest, profiles), [profiles, project, pullRequest], ); React.useEffect(() => { if (forceOpenFiles) setFilesOpen(true); }, [forceOpenFiles]); const submitComment = React.useCallback( async ( content: string, mentionPubkeys: string[], mediaTags?: string[][], decision?: "request-changes", ) => { try { await commentMutation.mutateAsync({ content, decision, mediaTags, mentionPubkeys, pullRequest, }); toast.success( decision === "request-changes" ? "Changes requested." : "Comment posted.", ); } catch (error) { toast.error( error instanceof Error ? error.message : "Failed to post comment.", ); throw error; } }, [commentMutation, pullRequest], ); const handleCommentSubmit = React.useCallback( (content: string, mentionPubkeys: string[], mediaTags?: string[][]) => submitComment(content, mentionPubkeys, mediaTags), [submitComment], ); const handleChangeRequestSubmit = React.useCallback( (content: string, mentionPubkeys: string[], mediaTags?: string[][]) => submitComment(content, mentionPubkeys, mediaTags, "request-changes"), [submitComment], ); const commitCount = Math.max(1, pullRequest.updates.length + 1); const reviewHistory = pullRequest.comments .map((item) => ({ item, timelineKind: projectPullRequestCommentTimelineKind(item), })) .sort( (left, right) => left.item.createdAt - right.item.createdAt || left.item.id.localeCompare(right.item.id), ); const reviewHistoryCollapsed = collapsedReviewHistoryPullRequestIds.has( pullRequest.id, ); const reviewHistoryExpanded = expandedReviewHistoryPullRequestIds.has( pullRequest.id, ); const earlierReviewHistoryCount = Math.max(0, reviewHistory.length - 3); const visibleReviewHistory = reviewHistoryExpanded || earlierReviewHistoryCount === 0 ? reviewHistory : reviewHistory.slice(-3); const displayedReviewHistory = reviewHistoryCollapsed ? [] : visibleReviewHistory; const canRequestChanges = canReviewProjectPullRequest( project, pullRequest, identityQuery.data?.pubkey, ); return (
{pullRequest.content || pullRequest.updates.length > 0 ? ( {pullRequest.content ? ( ) : null} {pullRequest.updates.length > 0 ? (

Updates

{pullRequest.updates.map((update) => (
{relativeTime(update.createdAt)} } /> {update.commit ? ( ) : null}
{update.content ? ( ) : null}
))}
) : null}
) : null} {filesChanged ? (
{filesChanged}
) : null}
{pullRequest.updates.map((update) => ( ))}

No checks have been reported for this review yet.

{reviewHistory.length > 0 ? ( ) : null} {!reviewHistoryCollapsed && earlierReviewHistoryCount > 0 && !reviewHistoryExpanded ? ( ) : null} {displayedReviewHistory.map(({ item, timelineKind }, index) => { const isHistoricalDecision = item.reviewDecisionStatus === "historical"; const trimmedContent = item.content.trim(); const activityContent = timelineKind === null ? trimmedContent : timelineKind === "changes-requested" && !/^requested changes\.?$/i.test(trimmedContent) ? trimmedContent : timelineKind === "approved" && !/^approved (these )?changes\.?$/i.test(trimmedContent) ? trimmedContent : null; return (
{index < displayedReviewHistory.length - 1 ? ( ) : ( )} {timelineKind === "approved" ? ( ) : timelineKind === "changes-requested" ? ( ) : timelineKind === "review-request" ? ( ) : ( )}
{labelForPubkey(item.author, profiles)} {timelineKind ? ( <> {" "} {timelineKind === "approved" ? isHistoricalDecision ? "approved an earlier commit" : "approved these changes" : timelineKind === "changes-requested" ? isHistoricalDecision ? "requested changes on an earlier commit" : "requested changes" : trimmedContent || "requested a review"} ) : null} {relativeTime(item.createdAt)}
{activityContent ? ( ) : null} {item.anchor ? ( ) : null}
); })}
); } export function PullRequestsPanel({ diffStats, error, filesChanged, filesCount, forceOpenFiles, isLoading, onOpenInlineComment, onOpenCommit, onOpenTerminal, onSelectedPullRequestIdChange, profiles, project, pullRequests, selectedPullRequestId, }: { diffStats?: { additions: number; deletions: number } | null; error: unknown; filesChanged?: React.ReactNode; filesCount?: number; forceOpenFiles?: boolean; isLoading: boolean; onOpenInlineComment?: (anchor: ProjectPullRequestCommentAnchor) => void; onOpenCommit?: (commitHash: string) => void; onOpenTerminal?: OpenMergeRecoveryTerminal; onSelectedPullRequestIdChange: (id: string | null) => void; profiles?: UserProfileLookup; project: Project; pullRequests: ProjectPullRequest[]; selectedPullRequestId: string | null; }) { const selectedPullRequest = pullRequests.find((item) => item.id === selectedPullRequestId) ?? null; React.useEffect(() => { if ( selectedPullRequestId && !pullRequests.some((item) => item.id === selectedPullRequestId) ) { onSelectedPullRequestIdChange(null); } }, [onSelectedPullRequestIdChange, pullRequests, selectedPullRequestId]); if (isLoading) { return (

Loading reviews…

); } if (pullRequests.length === 0) { return (

{error ? "Could not load reviews for this repository." : "No reviews yet."}

); } if (selectedPullRequest) { return ( ); } const groups = PULL_REQUEST_STATUS_ORDER.map((status) => ({ items: pullRequests.filter((pullRequest) => pullRequest.status === status), status, })).filter((group) => group.items.length > 0); return (
{groups.map(({ items, status }) => { return ( } key={status} label={status} > {items.map((pullRequest) => ( onSelectedPullRequestIdChange(pullRequest.id)} profiles={profiles} pullRequest={pullRequest} /> ))} ); })}
); }