Files
kandev/apps/web/components/task/changes-panel-timeline.tsx
T
2026-08-22 20:45:13 +00:00

633 lines
22 KiB
TypeScript

"use client";
import { useState, useMemo, useCallback } from "react";
import { IconChevronDown, IconChevronRight } from "@tabler/icons-react";
import { useMultiSelect } from "@/hooks/use-multi-select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import type { FileInfo } from "@/lib/state/store";
import { useDockviewStore } from "@/lib/state/dockview-store";
import { useAppStore } from "@/components/state-provider";
import { FileRow, BulkActionBar } from "./changes-panel-file-row";
import { ChangesTree, RepoTreeGroup } from "./changes-panel-tree";
import type { ChangedFile } from "./changes-panel-helpers";
import { type CommitItem } from "./commit-row";
import { groupByRepositoryName, isSingleRepoGroup } from "@/lib/group-by-repo";
import {
CommitsGroupActions,
CommitsRepoGroup,
FileSectionActions,
RepoGroupItem,
} from "./changes-panel-repo-groups";
import { PRFilesGroupedList } from "./changes-panel-pr-files";
import type { CommitDetailTarget, OpenDiffOptions } from "./changes-diff-target";
import { useTranslation } from "react-i18next";
// --- Timeline visual components ---
// Per-repo grouping is shared with the Review dialog — see @/lib/group-by-repo.
// --- Timeline section dot colors ---
const DOT_COLORS = {
unstaged: "bg-yellow-500",
staged: "bg-emerald-500",
commits: "bg-blue-500",
pr: "bg-purple-500",
} as const;
function TimelineDot({ color }: { color: string }) {
return <div className={cn("relative z-10 size-1.5 rounded-full shrink-0 mt-[5px]", color)} />;
}
function TimelineSection({
dotColor,
label,
count,
action,
children,
collapsible = true,
defaultCollapsed = false,
"data-testid": testId,
}: {
dotColor: string;
label?: string;
count?: number;
action?: React.ReactNode;
children?: React.ReactNode;
collapsible?: boolean;
defaultCollapsed?: boolean;
"data-testid": string;
}) {
const [collapsed, setCollapsed] = useState(defaultCollapsed);
// Git data arrives in separate async store updates, so `defaultCollapsed`
// (derived from which section is first-visible) can flip after mount. Re-sync
// to it whenever it changes — but stop once the user has manually toggled, so
// their choice is never clobbered by a later data update. Adjusting state
// during render (storing the previous prop in state) is the React-recommended
// pattern and avoids both the setState-in-effect and ref-during-render lint
// rules.
const [userToggled, setUserToggled] = useState(false);
const [prevDefaultCollapsed, setPrevDefaultCollapsed] = useState(defaultCollapsed);
if (prevDefaultCollapsed !== defaultCollapsed) {
setPrevDefaultCollapsed(defaultCollapsed);
if (!userToggled) setCollapsed(defaultCollapsed);
}
const canCollapse = collapsible && !!label;
return (
<div className="relative flex gap-2.5" data-testid={testId}>
{/* Vertical line + dot */}
<div className="flex flex-col items-center">
<TimelineDot color={dotColor} />
</div>
{/* Content */}
<div className="flex-1 min-w-0 pb-3">
{/* Header */}
{label && (
<div className="flex items-center justify-between gap-2 -mt-0.5 mb-1">
{canCollapse ? (
<button
type="button"
className="flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-foreground/70 cursor-pointer hover:text-foreground/90"
onClick={() => {
setUserToggled(true);
setCollapsed((c) => !c);
}}
aria-expanded={!collapsed}
data-testid={`${testId}-collapse-toggle`}
>
{label}
{typeof count === "number" && (
<span className="text-muted-foreground/50 font-normal">({count})</span>
)}
{collapsed ? (
<IconChevronRight className="h-3 w-3 text-muted-foreground/50" />
) : (
<IconChevronDown className="h-3 w-3 text-muted-foreground/50" />
)}
</button>
) : (
<span className="text-[11px] font-medium uppercase tracking-wider text-foreground/70">
{label}
{typeof count === "number" && (
<span className="ml-1 text-muted-foreground/50 font-normal">({count})</span>
)}
</span>
)}
{action}
</div>
)}
{/* Children (file list, buttons, etc.) */}
{!collapsed && children}
</div>
</div>
);
}
// --- Commits section ---
type CommitsSectionProps = {
commits: CommitItem[];
onOpenCommitDetail?: (target: CommitDetailTarget) => void;
// Handlers receive the commit's repository_name so amend/revert/reset land
// in the right git repo. The empty string routes to the workspace root for
// single-repo workspaces.
onRevertCommit?: (sha: string, repo?: string) => void;
onAmendCommit?: (currentMessage: string, repo?: string) => void;
onResetToCommit?: (sha: string, repo?: string) => void;
/** Per-repo Push button rendered in each commits group header. */
onRepoPush?: (repo: string) => void;
/** Per-repo Create PR button rendered in each commits group header. */
onRepoCreatePR?: (repo: string) => void;
/** Maps a repository_name to its display label (used for the empty single-repo case). */
repoDisplayName?: (repositoryName: string) => string | undefined;
/** The session's base branch — passed through to the per-repo PR dialog. */
repoBaseBranch?: string;
/** Per-repo branch / upstream summary; used for the Push indicator. */
perRepoStatus?: Array<{ repository_name: string; pushAhead?: number; ahead?: number }>;
/** Existing PR URL keyed by repository_name; "" key for single-repo. */
prByRepo?: Record<string, string | undefined>;
/** Initial collapse state. Defaults to collapsed; the panel expands it when it is the first visible section. */
defaultCollapsed?: boolean;
label?: string;
testId?: string;
pushDisabled?: boolean;
showActions?: boolean;
};
// Commits grouping shares the helper above with files — see @/lib/group-by-repo.
export function CommitsSection({
commits,
onOpenCommitDetail,
onRevertCommit,
onAmendCommit,
onResetToCommit,
onRepoPush,
onRepoCreatePR,
repoDisplayName,
repoBaseBranch,
perRepoStatus,
prByRepo,
defaultCollapsed = true,
label,
testId = "commits-section",
pushDisabled = false,
showActions = true,
}: CommitsSectionProps) {
const { t } = useTranslation();
const groups = groupByRepositoryName(commits, (c) => c.repository_name);
const aheadByRepo = new Map(
(perRepoStatus ?? []).map((s) => [s.repository_name, s.pushAhead ?? s.ahead ?? 0]),
);
// Single-repo: drop the per-repo sub-header (CommitsRepoGroup with
// showHeader=false renders flat) and lift the Push / PR buttons into the
// section header.
const isSingleRepo = isSingleRepoGroup(groups);
const sectionAction = isSingleRepo ? (
<CommitsGroupActions
repositoryName=""
aheadCount={aheadByRepo.get("") ?? 0}
prExists={!!prByRepo?.[""]}
canCreatePR={!!onRepoCreatePR && !prByRepo?.[""]}
onRepoPush={showActions && !pushDisabled ? onRepoPush : undefined}
onRepoCreatePR={showActions ? onRepoCreatePR : undefined}
stop={(e) => e.stopPropagation()}
/>
) : undefined;
return (
<TimelineSection
dotColor={DOT_COLORS.commits}
label={label ?? t("task:commits")}
count={commits.length}
defaultCollapsed={defaultCollapsed}
data-testid={testId}
action={sectionAction}
>
<ul data-testid="commits-list" className="space-y-0.5">
{groups.map((g) => (
<CommitsRepoGroup
key={g.repositoryName || "__no_repo__"}
repositoryName={g.repositoryName}
displayName={repoDisplayName?.(g.repositoryName)}
groupCommits={g.items}
aheadCount={aheadByRepo.get(g.repositoryName) ?? 0}
existingPrUrl={prByRepo?.[g.repositoryName] ?? prByRepo?.[""]}
showHeader={!isSingleRepo}
baseBranch={repoBaseBranch}
onOpenCommitDetail={onOpenCommitDetail}
onAmendCommit={onAmendCommit}
onRevertCommit={onRevertCommit}
onResetToCommit={onResetToCommit}
onRepoPush={showActions && !pushDisabled ? onRepoPush : undefined}
onRepoCreatePR={showActions ? onRepoCreatePR : undefined}
/>
))}
</ul>
</TimelineSection>
);
}
// --- File list sections (Unstaged / Staged) ---
type FileListSectionProps = {
variant: "unstaged" | "staged";
files: ChangedFile[];
pendingStageFiles: Set<string>;
actionLabel: string;
isActionLoading?: boolean;
onAction: () => void;
secondaryActionLabel?: string;
isSecondaryActionLoading?: boolean;
onSecondaryAction?: () => void;
onOpenDiff: (path: string, options?: OpenDiffOptions) => void;
onEditFile: (path: string, repo?: string) => void;
// Multi-repo: handlers receive the file's repositoryName so each per-file op
// hits the right git repo. Same-named files across repos collide by path.
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string, anchor?: HTMLElement) => void;
onBulkStage?: (paths: string[]) => void;
onBulkUnstage?: (paths: string[]) => void;
onBulkDiscard?: (paths: string[], anchor?: HTMLElement) => void;
// Per-repo action handlers shown inline with each repo group header. Always
// rendered, including single-repo (with one entry pre-selected) — the empty
// `repo` argument routes ops to the workspace root in that case.
onRepoAction?: (repo: string) => void;
onRepoSecondaryAction?: (repo: string) => void;
/** Maps a repository_name to its display label; called per group header. */
repoDisplayName?: (repositoryName: string) => string | undefined;
/** Disable section and per-repository actions while another git operation runs. */
disabled?: boolean;
};
/**
* Renders the body of a file-list section. For multi-repo workspaces it
* groups files by repository under per-repo subheaders; single-repo
* workspaces fall back to a flat list (no header) so the existing UI is
* unchanged.
*/
type FileListBodyProps = {
variant: "unstaged" | "staged";
files: ChangedFile[];
pendingStageFiles: Set<string>;
multiSelect: ReturnType<typeof useMultiSelect>;
onKeyDown: (e: React.KeyboardEvent) => void;
onOpenDiff: (path: string, options?: OpenDiffOptions) => void;
onEditFile: (path: string, repo?: string) => void;
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string, anchor?: HTMLElement) => void;
/** Per-repo group header actions; primary = Stage all (unstaged) / Commit (staged). */
onRepoAction?: (repo: string) => void;
onRepoSecondaryAction?: (repo: string) => void;
primaryLabel: string;
secondaryLabel?: string;
/** Maps a repository_name to its display label (e.g. "" → workspace primary repo name). */
repoDisplayName?: (repositoryName: string) => string | undefined;
disabled?: boolean;
};
function FileListBody(props: FileListBodyProps) {
const { files, pendingStageFiles, multiSelect } = props;
// Multi-repo nuance: activeFilePath carries the path but not repo; same path
// in two repos will light up both rows. Matches existing routing limit noted
// in FileRowProps comments.
const activeFilePath = useDockviewStore((s) => s.activeFilePath);
const layout = useAppStore((s) => s.userSettings.changesPanelLayout);
const groups = useMemo(() => groupByRepositoryName(files, (f) => f.repositoryName), [files]);
// Per-repo collapsed state: keyed by repositoryName. Default expanded;
// setting an entry to true collapses that group. Persists across re-renders
// for the lifetime of this section instance (resets on unmount).
const [collapsedRepos, setCollapsedRepos] = useState<Set<string>>(() => new Set());
const toggleRepo = useCallback((name: string) => {
setCollapsedRepos((prev) => {
const next = new Set(prev);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
}, []);
const renderRow = (file: ChangedFile) => (
<FileRow
key={`${file.repositoryName ?? ""}:${file.path}`}
file={file}
isPending={pendingStageFiles.has(`${file.repositoryName ?? ""}::${file.path}`)}
isSelected={multiSelect.isSelected(file.path)}
isActive={file.path === activeFilePath}
onSelect={multiSelect.handleClick}
onOpenDiff={props.onOpenDiff}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
onEditFile={props.onEditFile}
/>
);
// Single-repo: drop the per-repo sub-header. The action buttons (Stage all
// / Commit / Unstage all) move up to the section header — see FileListSection.
const isSingleRepo = isSingleRepoGroup(groups);
if (layout === "tree") {
return (
<TreeFileListBody
{...props}
groups={groups}
isSingleRepo={isSingleRepo}
collapsedRepos={collapsedRepos}
toggleRepo={toggleRepo}
/>
);
}
return (
<FlatFileListBody
{...props}
groups={groups}
isSingleRepo={isSingleRepo}
collapsedRepos={collapsedRepos}
toggleRepo={toggleRepo}
renderRow={renderRow}
/>
);
}
type FileListBranchProps = FileListBodyProps & {
groups: ReturnType<typeof groupByRepositoryName<ChangedFile>>;
isSingleRepo: boolean;
collapsedRepos: Set<string>;
toggleRepo: (name: string) => void;
};
function TreeFileListBody(props: FileListBranchProps) {
const {
variant,
groups,
isSingleRepo,
collapsedRepos,
toggleRepo,
pendingStageFiles,
multiSelect,
} = props;
return (
<div tabIndex={-1} onKeyDown={props.onKeyDown}>
{isSingleRepo ? (
<ChangesTree
files={groups[0].items}
pendingStageFiles={pendingStageFiles}
onOpenDiff={props.onOpenDiff}
onEditFile={props.onEditFile}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
variant={variant}
multiSelect={multiSelect}
/>
) : (
groups.map((group) => (
<RepoTreeGroup
key={group.repositoryName || "__no_repo__"}
variant={variant}
repositoryName={group.repositoryName}
displayName={props.repoDisplayName?.(group.repositoryName)}
files={group.items}
pendingStageFiles={pendingStageFiles}
collapsed={collapsedRepos.has(group.repositoryName)}
onToggle={() => toggleRepo(group.repositoryName)}
onOpenDiff={props.onOpenDiff}
onEditFile={props.onEditFile}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
primaryLabel={props.primaryLabel}
secondaryLabel={props.secondaryLabel}
onRepoAction={props.onRepoAction}
onRepoSecondaryAction={props.onRepoSecondaryAction}
disabled={props.disabled}
multiSelect={multiSelect}
/>
))
)}
</div>
);
}
function FlatFileListBody(
props: FileListBranchProps & { renderRow: (file: ChangedFile) => React.ReactNode },
) {
const { variant, groups, isSingleRepo, collapsedRepos, toggleRepo, renderRow } = props;
return (
<div>
<ul
data-testid={`${variant}-file-list`}
className="space-y-0.5"
tabIndex={-1}
onKeyDown={props.onKeyDown}
>
{isSingleRepo
? groups[0].items.map(renderRow)
: groups.map((group) => (
<RepoGroupItem
key={group.repositoryName || "__no_repo__"}
group={group}
collapsed={collapsedRepos.has(group.repositoryName)}
onToggle={() => toggleRepo(group.repositoryName)}
renderRow={renderRow}
primaryLabel={props.primaryLabel}
secondaryLabel={props.secondaryLabel}
onRepoAction={props.onRepoAction}
onRepoSecondaryAction={props.onRepoSecondaryAction}
displayName={props.repoDisplayName?.(group.repositoryName)}
disabled={props.disabled}
/>
))}
</ul>
</div>
);
}
export function FileListSection(props: FileListSectionProps) {
const {
variant,
files,
pendingStageFiles,
onOpenDiff,
onEditFile,
onStage,
onUnstage,
onDiscard,
} = props;
const dotColor = variant === "unstaged" ? DOT_COLORS.unstaged : DOT_COLORS.staged;
const label = variant === "unstaged" ? "Unstaged" : "Staged";
const filePaths = useMemo(() => files.map((f) => f.path), [files]);
const multiSelect = useMultiSelect({ items: filePaths });
const hasSelection = multiSelect.selectedPaths.size > 0;
// Multi-repo when any file has a repositoryName. Per-repo group headers
// own the action buttons in this case; in single-repo we render them in
// the section header instead. Compute via the shared helper against the
// grouped output so the three sites (commits + file-list body + this
// section) stay in sync.
const groups = useMemo(() => groupByRepositoryName(files, (f) => f.repositoryName), [files]);
const isSingleRepo = files.length > 0 && isSingleRepoGroup(groups);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Escape" && hasSelection) multiSelect.clearSelection();
},
[hasSelection, multiSelect],
);
return (
<TimelineSection
dotColor={dotColor}
label={label}
count={files.length}
data-testid={`${variant}-files-section`}
action={
isSingleRepo ? (
<FileSectionActions
primaryLabel={props.actionLabel}
secondaryLabel={props.secondaryActionLabel}
onAction={props.onRepoAction}
onSecondaryAction={props.onRepoSecondaryAction}
disabled={props.isActionLoading || props.isSecondaryActionLoading}
/>
) : undefined
}
>
{files.length > 0 && (
<FileListBody
variant={variant}
files={files}
pendingStageFiles={pendingStageFiles}
multiSelect={multiSelect}
onKeyDown={handleKeyDown}
onOpenDiff={onOpenDiff}
onStage={onStage}
onUnstage={onUnstage}
onDiscard={onDiscard}
onEditFile={onEditFile}
primaryLabel={props.actionLabel}
secondaryLabel={props.secondaryActionLabel}
onRepoAction={props.onRepoAction}
onRepoSecondaryAction={props.onRepoSecondaryAction}
repoDisplayName={props.repoDisplayName}
disabled={props.isActionLoading || props.isSecondaryActionLoading}
/>
)}
{files.length > 0 && hasSelection && (
<div className="mt-1.5 flex items-center gap-1.5">
<BulkActionBar
variant={variant}
selectionCount={multiSelect.selectedPaths.size}
selectedPaths={multiSelect.selectedPaths}
onBulkStage={props.onBulkStage}
onBulkUnstage={props.onBulkUnstage}
onBulkDiscard={props.onBulkDiscard}
/>
</div>
)}
</TimelineSection>
);
}
// --- PR files section (read-only, from GitHub PR diff) ---
export type PRChangedFile = {
path: string;
/** Stable owner/repo/number identity for the PR that produced this row. */
prKey?: string;
status: FileInfo["status"];
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
/**
* The repository the file belongs to. Empty string for single-repo tasks
* (the section header alone is enough). Multi-repo tasks stamp this so
* `PRFilesSection` can group rows under per-repo subheaders, mirroring
* how the Commits and Changes sections render.
*/
repository_name?: string;
};
type PRFilesSectionProps = {
files: PRChangedFile[];
onOpenDiff: (path: string, options?: OpenDiffOptions) => void;
/** Maps a repository_name to a human-readable label (used for the per-repo header). */
repoDisplayName?: (repositoryName: string) => string | undefined;
/** Initial collapse state. Defaults to collapsed; the panel expands it when it is the first visible section. */
defaultCollapsed?: boolean;
};
export function PRFilesSection({
files,
onOpenDiff,
repoDisplayName,
defaultCollapsed = true,
}: PRFilesSectionProps) {
const { t } = useTranslation();
return (
<TimelineSection
dotColor={DOT_COLORS.pr}
label={t("task:prChanges")}
count={files.length}
defaultCollapsed={defaultCollapsed}
data-testid="pr-changes-section"
>
{files.length > 0 && (
<PRFilesGroupedList
files={files}
onOpenDiff={onOpenDiff}
repoDisplayName={repoDisplayName}
/>
)}
</TimelineSection>
);
}
// --- Review progress bar ---
type ReviewProgressBarProps = {
reviewedCount: number;
totalFileCount: number;
onOpenReview?: () => void;
};
export function ReviewProgressBar({
reviewedCount,
totalFileCount,
onOpenReview,
}: ReviewProgressBarProps) {
const { t } = useTranslation();
const progressPercent = totalFileCount > 0 ? (reviewedCount / totalFileCount) * 100 : 0;
if (totalFileCount <= 0) return null;
return (
<Tooltip>
<TooltipTrigger asChild>
<div
className="shrink-0 flex items-center gap-2 pt-2 border-t border-border/40 cursor-pointer transition-colors"
onClick={onOpenReview}
>
<div className="flex-1 h-0.5 rounded-full bg-muted-foreground/10 overflow-hidden">
<div
className="h-full bg-muted-foreground/25 rounded-full transition-all duration-300"
style={{ width: `${progressPercent}%` }}
/>
</div>
<span className="text-[10px] text-muted-foreground/40 whitespace-nowrap">
{reviewedCount}/{totalFileCount} reviewed
</span>
</div>
</TooltipTrigger>
<TooltipContent>
{t("task:filesReviewedCount", { reviewedCount, totalFileCount })}
</TooltipContent>
</Tooltip>
);
}