The platform for continuously improving AI agents.
// Source supplied by the project owner. See NOTICE.md for adaptations.
"use client";
import type { ReactNode } from "react";
import { useEffect, useId, useMemo, useState, useSyncExternalStore } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Icon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";
interface CommitTag {
label: string;
tone: "done" | "neutral";
}
interface CommitFileRef {
path: string;
label?: string;
}
type CommitTitlePart =
| string
| { type: "file"; path: string; label?: string }
| { type: "branch"; name: string };
export interface CommitEntry {
id: string;
title?: string | readonly CommitTitlePart[];
content?: ReactNode;
timestamp?: Date | string | number;
tag?: CommitTag;
commits?: readonly CommitEntry[];
}
interface CommitBranch {
name: string;
commits: readonly CommitEntry[];
commitCount?: number;
}
interface CommitHistoryClassNames {
header?: string;
list?: string;
}
interface CommitHistoryProps {
disabled?: boolean;
branch: string;
branches?: readonly CommitBranch[];
commits?: readonly CommitEntry[];
onBranchChange?: (branch: string) => void;
emptyMessage?: string;
className?: string;
classNames?: CommitHistoryClassNames;
}
const MINUTE_MS = 60_000;
const HOUR_MS = 60 * MINUTE_MS;
const DAY_MS = 24 * HOUR_MS;
const MONTH_MS = 30 * DAY_MS;
const TICK_MS = 30_000;
const RAIL_WIDTH = 32;
const MAIN_X = 11;
const BRANCH_X = 21;
const CHILD_NODE_Y = 16;
const RAIL_STROKE = 1.5;
const EASE_OUT = [0.25, 1, 0.5, 1] as const;
const EASE_DRAW = [0.22, 1, 0.36, 1] as const;
const EASE_EXPO = [0.19, 1, 0.22, 1] as const;
const ENTER_CLASS =
"fade-in-0 slide-in-from-bottom-2 animate-in fill-mode-both duration-300 ease-out motion-reduce:animate-none";
const FOCUS_CLASS = "focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none";
const THEME_VARS =
"[--commit-history-accent:var(--foreground)] [--commit-history-node-bg:var(--muted)] [--commit-history-pending-rail:var(--border)] [--commit-history-added:var(--success)] [--commit-history-removed:var(--destructive)] [--commit-history-error:var(--destructive)] [--commit-history-tag-warn:var(--warning)] [--commit-history-tag-plum:var(--cat-3)] [--commit-history-tag-done:var(--success)] [--commit-history-tag-neutral:var(--muted-foreground)]";
const BACKTICK_RE = /`([^`]+)`/gu;
const MERGE_TITLE_RE = /^Merge\s+([^\s]+)\s+into\s+([^\s]+)$/iu;
const FILE_TOKEN_RE = /(?:^|\/)[\w.-]+\.[A-Za-z\d]{1,8}$/u;
const toEpochMs = (value: Date | string | number): number =>
value instanceof Date ? value.getTime() : new Date(value).getTime();
const fileBaseName = (filePath: string): string => {
const normalized = filePath.replaceAll("\\", "/").replace(/\/+$/u, "");
const slash = normalized.lastIndexOf("/");
return slash === -1 ? normalized : normalized.slice(slash + 1);
};
const formatCommitAge = (at: Date | string | number, now: Date | number = Date.now()): string => {
const time = toEpochMs(at);
const from = toEpochMs(now);
if (Number.isNaN(time) || Number.isNaN(from)) {
return "";
}
const age = Math.max(0, from - time);
if (age < MINUTE_MS) {
return "now";
}
if (age < HOUR_MS) {
return `${Math.floor(age / MINUTE_MS)}m`;
}
if (age < DAY_MS) {
return `${Math.floor(age / HOUR_MS)}h`;
}
if (age < MONTH_MS) {
return `${Math.floor(age / DAY_MS)}d`;
}
return new Intl.DateTimeFormat("en-US", {
day: "numeric",
month: "short",
}).format(time);
};
const formatCommitDate = (at: Date | string | number): string => {
const time = toEpochMs(at);
if (Number.isNaN(time)) {
return "";
}
return new Intl.DateTimeFormat("en-US", {
day: "numeric",
hour: "numeric",
minute: "2-digit",
month: "short",
year: "numeric",
}).format(time);
};
const resolveTitleParts = (commit: CommitEntry): CommitTitlePart[] => {
if (Array.isArray(commit.title)) {
return [...commit.title];
}
const raw = typeof commit.title === "string" ? commit.title : "";
if (!raw) {
return ["Commit"];
}
const mergeMatch = MERGE_TITLE_RE.exec(raw.trim());
if (mergeMatch && !raw.includes("`")) {
const [, source, target] = mergeMatch;
if (source && target) {
return [
"Merge ",
{ name: source, type: "branch" },
" into ",
{ name: target, type: "branch" },
];
}
}
const parts: CommitTitlePart[] = [];
let cursor = 0;
for (const match of raw.matchAll(BACKTICK_RE)) {
const start = match.index ?? 0;
const token = match[1] ?? "";
if (start > cursor) {
parts.push(raw.slice(cursor, start));
}
const file = FILE_TOKEN_RE.test(token) ? { label: fileBaseName(token), path: token } : null;
if (file) {
parts.push({ label: file.label, path: file.path, type: "file" });
} else {
parts.push({ name: token, type: "branch" });
}
cursor = start + match[0].length;
}
if (cursor < raw.length) {
parts.push(raw.slice(cursor));
}
return parts;
};
const plainTitleText = (parts: readonly CommitTitlePart[]): string =>
parts
.map((part) => {
if (typeof part === "string") {
return part;
}
return part.type === "file" ? (part.label ?? fileBaseName(part.path)) : part.name;
})
.join("");
const isMergeCommit = (commit: CommitEntry): boolean => (commit.commits?.length ?? 0) > 0;
const hasCommitDetails = (commit: CommitEntry): boolean => commit.timestamp !== undefined;
const countCommittedEntries = (commits: readonly CommitEntry[]): number =>
commits.reduce((total, commit) => total + 1 + countCommittedEntries(commit.commits ?? []), 0);
const pluralize = (count: number, singular: string, plural?: string): string =>
`${count} ${count === 1 ? singular : (plural ?? `${singular}s`)}`;
const noop = () => {
// No external event source; ticks are managed in useClock.
};
const emptySubscribe = () => noop;
const useClock = (): number | null => {
const hydrated = useSyncExternalStore(
emptySubscribe,
() => true,
() => false
);
const [tick, setTick] = useState(0);
useEffect(() => {
const id = window.setInterval(() => {
setTick((current) => current + 1);
}, TICK_MS);
return () => {
window.clearInterval(id);
};
}, []);
if (!hydrated) {
return null;
}
// `tick` forces a fresh reading every 30s without writing state in an effect.
return tick >= 0 ? Date.now() : Date.now();
};
const AnimatedCheckmark = ({
className,
delay = 0.04,
reduce,
strokeWidth = 2.15,
}: {
className?: string;
delay?: number;
reduce: boolean | null;
strokeWidth?: number;
}) => (
<svg
aria-hidden="true"
className={cn("overflow-visible", className)}
fill="none"
viewBox="0 0 16 16"
>
<motion.path
animate={{ opacity: 1, pathLength: 1 }}
d="M3.25 8.5L6.35 11.6L12.75 4.6"
initial={reduce ? { opacity: 1, pathLength: 1 } : { opacity: 0, pathLength: 0 }}
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={strokeWidth}
transition={{
opacity: { delay: reduce ? 0 : delay, duration: reduce ? 0 : 0.04 },
pathLength: {
delay: reduce ? 0 : delay,
duration: reduce ? 0 : 0.24,
ease: EASE_DRAW,
},
}}
/>
</svg>
);
const StatusNode = ({ reduce }: { reduce: boolean | null }) => (
<span
aria-hidden="true"
className={cn(
"relative z-10 inline-flex size-5 flex-none items-center justify-center rounded-full bg-card transition-shadow duration-200 ease-out motion-reduce:transition-none"
)}
data-slot="commit-history-node"
data-status="committed"
>
{/* Subtle expanding confirmation ring timed to the checkmark's apex */}
<AnimatePresence initial={false}>
{!reduce ? (
<motion.span
animate={{ opacity: 0, scale: 1.55 }}
aria-hidden="true"
className="pointer-events-none absolute inset-0 rounded-full ring-1 ring-(--commit-history-accent)/45"
exit={{ opacity: 0, transition: { delay: 0, duration: 0.08 } }}
initial={{ opacity: 0.55, scale: 0.92 }}
key="committed-pulse"
transition={{ delay: 0.16, duration: 0.42, ease: EASE_EXPO }}
/>
) : null}
</AnimatePresence>
{/* Tinted badge fill that blooms smoothly under the drawing checkmark */}
<AnimatePresence initial={false}>
{
<motion.span
animate={{ opacity: 1, scale: 1 }}
aria-hidden="true"
className="pointer-events-none absolute inset-0 rounded-full bg-(--commit-history-node-bg)"
exit={{
opacity: 0,
scale: 0.7,
transition: { delay: 0, duration: reduce ? 0 : 0.12 },
}}
initial={reduce ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.62 }}
key="committed-bg"
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
/>
}
</AnimatePresence>
<AnimatePresence initial={false} mode="popLayout">
{
<motion.span
animate={reduce ? { opacity: 1, scale: 1 } : { opacity: 1, scale: [0.94, 1.05, 1] }}
className="relative z-10 inline-flex size-full items-center justify-center text-(--commit-history-accent)"
exit={{
opacity: 0,
scale: 0.75,
transition: { delay: 0, duration: reduce ? 0 : 0.12 },
}}
initial={reduce ? { opacity: 1, scale: 1 } : { opacity: 1, scale: 0.94 }}
key="committed"
transition={{
duration: reduce ? 0 : 0.3,
ease: EASE_OUT,
times: [0, 0.5, 1],
}}
>
<AnimatedCheckmark className="size-3" delay={0.04} reduce={reduce} />
</motion.span>
}
</AnimatePresence>
</span>
);
const VerticalRail = ({
x,
drawDelay = 0.14,
drawDuration = 0.16,
reduce = false,
className,
}: {
x: number;
drawDelay?: number;
drawDuration?: number;
reduce?: boolean | null;
className?: string;
}) => (
<motion.span
animate={{ opacity: 1 }}
aria-hidden="true"
className={cn("pointer-events-none relative block w-8", className)}
initial={reduce ? false : { opacity: 0 }}
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
>
<svg
aria-hidden="true"
className={cn(
"block size-full text-(--commit-history-pending-rail) transition-opacity delay-200 duration-200 motion-reduce:transition-none",
"opacity-0"
)}
fill="none"
preserveAspectRatio="none"
viewBox={`0 0 ${RAIL_WIDTH} 10`}
>
<line
stroke="currentColor"
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
vectorEffect="non-scaling-stroke"
x1={x}
x2={x}
y1={0}
y2={10}
/>
</svg>
<AnimatePresence initial={false}>
{
<motion.span
animate={{ opacity: 1, scaleY: 1 }}
className="absolute inset-0 block origin-top text-(--commit-history-accent)"
exit={{
opacity: 0,
transition: { delay: 0, duration: reduce ? 0 : 0.12 },
}}
initial={reduce ? { opacity: 1, scaleY: 1 } : { opacity: 1, scaleY: 0 }}
key="committed-rail"
transition={{
delay: reduce ? 0 : drawDelay,
duration: reduce ? 0 : drawDuration,
ease: EASE_DRAW,
}}
>
<svg
aria-hidden="true"
className="block size-full"
fill="none"
preserveAspectRatio="none"
viewBox={`0 0 ${RAIL_WIDTH} 10`}
>
<line
stroke="currentColor"
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
vectorEffect="non-scaling-stroke"
x1={x}
x2={x}
y1={0}
y2={10}
/>
</svg>
</motion.span>
}
</AnimatePresence>
</motion.span>
);
const BranchCurveTop = () => (
<svg
aria-hidden="true"
className="pointer-events-none block h-3.5 w-8 text-(--commit-history-accent)"
fill="none"
viewBox={`0 0 ${RAIL_WIDTH} 14`}
>
<path
d={`M ${MAIN_X} 0 C ${MAIN_X} 7, ${BRANCH_X} 7, ${BRANCH_X} 14`}
stroke="currentColor"
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
/>
</svg>
);
const BranchCurveBottom = ({ fadeOut, fadeId }: { fadeOut: boolean; fadeId: string }) => {
if (fadeOut) {
return (
<svg
aria-hidden="true"
className="pointer-events-none block h-6 w-8 text-(--commit-history-accent)"
fill="none"
viewBox={`0 0 ${RAIL_WIDTH} 24`}
>
<defs>
<linearGradient gradientUnits="userSpaceOnUse" id={fadeId} x1={0} x2={0} y1={0} y2={24}>
<stop offset="0%" stopColor="currentColor" stopOpacity={1} />
<stop offset="55%" stopColor="currentColor" stopOpacity={0.65} />
<stop offset="100%" stopColor="currentColor" stopOpacity={0} />
</linearGradient>
</defs>
<path
d={`M ${BRANCH_X} 0 C ${BRANCH_X} 8, ${MAIN_X} 8, ${MAIN_X} 16 L ${MAIN_X} 24`}
stroke={`url(#${fadeId})`}
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
/>
</svg>
);
}
return (
<svg
aria-hidden="true"
className="pointer-events-none block h-3.5 w-8 text-(--commit-history-accent)"
fill="none"
viewBox={`0 0 ${RAIL_WIDTH} 14`}
>
<path
d={`M ${BRANCH_X} 0 C ${BRANCH_X} 7, ${MAIN_X} 7, ${MAIN_X} 14`}
stroke="currentColor"
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
/>
</svg>
);
};
const MainTailFade = ({ fadeId }: { fadeId: string }) => (
<svg
aria-hidden="true"
className={cn(
"pointer-events-none block h-5 w-8 transition-colors duration-200 ease-out motion-reduce:transition-none",
"text-(--commit-history-accent)"
)}
fill="none"
viewBox={`0 0 ${RAIL_WIDTH} 20`}
>
<defs>
<linearGradient
gradientUnits="userSpaceOnUse"
id={fadeId}
x1={MAIN_X}
x2={MAIN_X}
y1={0}
y2={20}
>
<stop offset="0%" stopColor="currentColor" stopOpacity={1} />
<stop offset="100%" stopColor="currentColor" stopOpacity={0} />
</linearGradient>
</defs>
<line
stroke={`url(#${fadeId})`}
strokeLinecap="butt"
strokeWidth={RAIL_STROKE}
x1={MAIN_X}
x2={MAIN_X}
y1={0}
y2={20}
/>
</svg>
);
const CHIP_CLASS =
"mx-0.5 inline-flex max-w-[60%] align-bottom items-center gap-1 rounded-[5px] bg-foreground/[0.045] px-1.5 py-[1px] font-mono text-[12px] leading-[18px] text-card-foreground/85 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none";
const FileChip = ({
file,
onRowToggle,
className,
}: {
file: CommitFileRef;
onRowToggle?: () => void;
className?: string;
}) => {
const label = file.label ?? fileBaseName(file.path);
const interactive = Boolean(onRowToggle);
return (
<button
className={cn(
CHIP_CLASS,
"pointer-events-auto relative z-10 border-0 hover:bg-foreground/9",
interactive ? "cursor-pointer" : "cursor-default",
FOCUS_CLASS,
className
)}
data-kind="file"
data-slot="commit-history-chip"
onClick={(event) => {
if (onRowToggle) {
event.stopPropagation();
onRowToggle();
}
}}
type="button"
>
<Icon.file aria-hidden="true" className="size-3 flex-none text-muted-foreground/80" />
<span className="truncate">{label}</span>
</button>
);
};
const BranchChip = ({ name }: { name: string }) => (
<span className={CHIP_CLASS} data-kind="branch" data-slot="commit-history-chip">
<Icon.gitBranch aria-hidden="true" className="size-3 flex-none text-muted-foreground/80" />
<span className="truncate">{name}</span>
</span>
);
const keyedTitleParts = (parts: readonly CommitTitlePart[]) => {
const counts = new Map<string, number>();
return parts.map((part) => {
let base: string;
if (typeof part === "string") {
base = `t:${part}`;
} else if (part.type === "file") {
base = `f:${part.path}`;
} else {
base = `b:${part.name}`;
}
const count = (counts.get(base) ?? 0) + 1;
counts.set(base, count);
return { key: `${base}#${count}`, part };
});
};
const CommitTitle = ({
parts,
onRowToggle,
}: {
parts: readonly CommitTitlePart[];
onRowToggle?: () => void;
}) => (
<>
{keyedTitleParts(parts).map(({ key, part }) => {
if (typeof part === "string") {
return (
<span className="max-w-[70%] shrink-0 truncate" key={key}>
{part}
</span>
);
}
if (part.type === "file") {
return (
<FileChip
file={{ label: part.label, path: part.path }}
key={key}
onRowToggle={onRowToggle}
/>
);
}
return <BranchChip key={key} name={part.name} />;
})}
</>
);
const TagPill = ({ tag, className }: { tag: CommitTag; className?: string }) => (
<span
className={cn(
"inline-flex h-5 flex-none items-center rounded-[5px] bg-[color-mix(in_oklab,var(--commit-history-tone)_12%,var(--card))] px-1.5 text-[11px] leading-none font-medium text-(--commit-history-tone) [--commit-history-tone:var(--commit-history-accent)] data-[tone=done]:[--commit-history-tone:var(--commit-history-tag-done)] data-[tone=neutral]:[--commit-history-tone:var(--commit-history-tag-neutral)] data-[tone=plum]:[--commit-history-tone:var(--commit-history-tag-plum)] data-[tone=warn]:[--commit-history-tone:var(--commit-history-tag-warn)]",
className
)}
data-slot="commit-history-tag"
data-tone={tag.tone ?? "accent"}
>
{tag.label}
</span>
);
const CommitDetailsPanel = ({
commit,
indentClass,
}: {
commit: CommitEntry;
indentClass: string;
}) => {
const formattedDate = commit.timestamp === undefined ? "" : formatCommitDate(commit.timestamp);
return (
<div
className={cn("flex flex-col gap-2 pt-1.5 pr-2 pb-3", indentClass)}
data-slot="commit-history-details"
>
{formattedDate ? (
<div className="flex flex-wrap items-center gap-x-1.5 text-xs leading-4 text-muted-foreground tabular-nums">
<span>{formattedDate}</span>
</div>
) : null}
</div>
);
};
interface RowDisplayContext {
hasSpotlight: boolean;
now: number | null;
onToggleDetails: (id: string) => void;
onToggleMerge: (id: string) => void;
reduce: boolean | null;
selectedId: string | null;
}
const formatRowAge = (commit: CommitEntry, now: number | null): string => {
if (commit.timestamp === undefined || now === null) {
return "";
}
return formatCommitAge(commit.timestamp, now);
};
const ChildCommitRow = ({
commit,
context,
}: {
commit: CommitEntry;
context: RowDisplayContext;
}) => {
const {
hasSpotlight,
now,
onToggleDetails,
reduce,
selectedId,
} = context;
const expandable = hasCommitDetails(commit);
const isSelected = expandable && selectedId === commit.id;
const dimmed = hasSpotlight && !isSelected;
const parts = resolveTitleParts(commit);
const label = plainTitleText(parts);
const tag = commit.tag;
const age = formatRowAge(commit, now);
const toggle = expandable
? () => {
onToggleDetails(commit.id);
}
: undefined;
return (
<motion.li
animate={{
height: "auto",
opacity: 1,
transitionEnd: { overflow: "visible" },
}}
className="relative -mx-2 px-2"
data-dimmed={dimmed ? "true" : undefined}
data-expanded={isSelected ? "true" : "false"}
data-kind="branch-commit"
data-slot="commit-history-row"
data-status="committed"
exit={{
height: 0,
opacity: 0,
overflow: "hidden",
transition: { duration: reduce ? 0 : 0.18, ease: EASE_OUT },
}}
initial={{ height: 0, opacity: 0, overflow: "hidden" }}
transition={{ duration: reduce ? 0 : 0.26, ease: EASE_DRAW }}
>
<motion.div
animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
className="relative"
initial={reduce ? { opacity: 1, y: 0 } : { filter: "blur(2px)", opacity: 0, y: -6 }}
transition={{ duration: reduce ? 0 : 0.24, ease: EASE_DRAW }}
>
{/* Continuous branch vertical rail stretched to full row + details height */}
<div
aria-hidden="true"
className={cn("pointer-events-none absolute inset-y-0 left-0 w-8")}
data-slot="commit-history-rail"
>
<VerticalRail className="h-full" reduce={reduce} x={BRANCH_X} />
<svg
aria-hidden="true"
className="absolute top-0 left-0 h-8 w-8 text-(--commit-history-accent)"
fill="none"
viewBox={`0 0 ${RAIL_WIDTH} 32`}
>
<motion.circle
animate={{ opacity: 1, scale: 1 }}
cx={BRANCH_X}
cy={CHILD_NODE_Y}
fill="currentColor"
initial={reduce ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
r={2.5}
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
/>
</svg>
</div>
{/* Header hit row */}
<div
className={cn(
"group/row relative -mx-1.5 flex min-h-8 items-start rounded-lg px-1.5 py-1.5 transition-[background-color] duration-150 ease-out motion-reduce:transition-none",
isSelected && "bg-foreground/[0.045]",
expandable && "hover:bg-foreground/[0.045]",
commit.content && !commit.title && "hidden"
)}
>
{expandable ? (
<button
aria-expanded={isSelected}
aria-label={label}
className={cn(
"peer absolute inset-0 cursor-pointer rounded-lg border-0 bg-transparent",
FOCUS_CLASS
)}
onClick={toggle}
type="button"
/>
) : null}
<div
className={cn(
"pointer-events-none relative flex min-w-0 flex-1 items-baseline gap-2 pl-10 transition-opacity duration-150 ease-out motion-reduce:transition-none",
dimmed && "opacity-40 group-hover/row:opacity-90 peer-focus-visible:opacity-100"
)}
>
<div
className={cn(
"flex min-w-0 flex-1 items-center truncate text-[13px] leading-5 text-muted-foreground",
isSelected && "text-card-foreground"
)}
data-slot="commit-history-title"
>
<CommitTitle onRowToggle={toggle} parts={parts} />
</div>
{tag || age ? (
<div className="ml-auto flex flex-none items-center gap-2 pl-1">
{tag ? <TagPill tag={tag} /> : null}
{age ? (
<span
className={cn(
"min-w-7 text-right text-xs leading-5 text-muted-foreground/85 tabular-nums @max-[20rem]/commit-history:hidden"
)}
data-slot="commit-history-timestamp"
>
{age}
</span>
) : null}
</div>
) : null}
</div>
</div>
{commit.content && <div className="pb-3 pl-8 pr-2">{commit.content}</div>}
{/* Optional expanded details for a branch commit */}
<AnimatePresence initial={false}>
{isSelected ? (
<motion.div
animate={{ height: "auto", opacity: 1 }}
className="overflow-hidden"
exit={{ height: 0, opacity: 0 }}
initial={{ height: 0, opacity: 0 }}
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
>
<CommitDetailsPanel commit={commit} indentClass="pl-10" />
</motion.div>
) : null}
</AnimatePresence>
</motion.div>
</motion.li>
);
};
const MainCommitRow = ({
commit,
context,
fadeId,
isBranchOpen,
isFirst,
isLast,
}: {
commit: CommitEntry;
context: RowDisplayContext;
fadeId: string;
isBranchOpen: boolean;
isFirst: boolean;
isLast: boolean;
}) => {
const {
hasSpotlight,
now,
onToggleDetails,
onToggleMerge,
reduce,
selectedId,
} = context;
const merge = isMergeCommit(commit);
const expandableDetails = !merge && hasCommitDetails(commit);
const interactive = merge || expandableDetails;
const isSelected = expandableDetails && selectedId === commit.id;
const dimmed = hasSpotlight && !isSelected;
const parts = resolveTitleParts(commit);
const label = plainTitleText(parts);
const tag = commit.tag;
const age = formatRowAge(commit, now);
const childCommits = commit.commits ?? [];
const handleToggle = () => {
if (merge) {
onToggleMerge(commit.id);
} else if (expandableDetails) {
onToggleDetails(commit.id);
}
};
return (
<motion.li
animate={{
height: "auto",
opacity: 1,
transitionEnd: { overflow: "visible" },
}}
className="relative -mx-2 px-2"
data-dimmed={dimmed ? "true" : undefined}
data-expanded={merge ? String(isBranchOpen) : String(isSelected)}
data-kind={merge ? "merge" : "commit"}
data-slot="commit-history-row"
data-status="committed"
exit={{
height: 0,
opacity: 0,
overflow: "hidden",
transition: { duration: reduce ? 0 : 0.18, ease: EASE_OUT },
}}
initial={{ height: 0, opacity: 0, overflow: "hidden" }}
transition={{ duration: reduce ? 0 : 0.34, ease: EASE_DRAW }}
>
{/* Header + optional commit details wrapper (owns main-lane vertical rail) */}
<motion.div
animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
className="relative"
initial={reduce ? { opacity: 1, y: 0 } : { filter: "blur(3px)", opacity: 0, y: -8 }}
transition={{ duration: reduce ? 0 : 0.32, ease: EASE_DRAW }}
>
{/* Main-lane rail behind the header row (and commit details when open) */}
<div
aria-hidden="true"
className={cn("pointer-events-none absolute inset-y-0 left-0 w-8")}
data-slot="commit-history-rail"
>
{isFirst ? null : (
<VerticalRail
className="absolute top-0 left-0 h-[18px]"
drawDelay={0.24}
drawDuration={0.14}
reduce={reduce}
x={MAIN_X}
/>
)}
<VerticalRail
className="absolute top-[18px] left-0 h-[calc(100%-18px)]"
drawDelay={0.14}
drawDuration={0.14}
reduce={reduce}
x={MAIN_X}
/>
<div className="absolute top-[8px] left-[1px]">
<StatusNode reduce={reduce} />
</div>
</div>
{/* Clickable header row */}
<div
className={cn(
"group/row relative -mx-1.5 flex min-h-9 items-start rounded-lg px-1.5 py-2 transition-[background-color] duration-300 ease-out motion-reduce:transition-none",
isSelected && "bg-foreground/[0.045]",
interactive && "hover:bg-foreground/[0.045]"
)}
>
{interactive ? (
<button
aria-expanded={merge ? isBranchOpen : isSelected}
aria-label={merge ? `${label}, ${pluralize(childCommits.length, "change")}` : label}
className={cn(
"peer absolute inset-0 cursor-pointer rounded-lg border-0 bg-transparent",
FOCUS_CLASS
)}
onClick={handleToggle}
type="button"
/>
) : null}
<div
className={cn(
"pointer-events-none relative flex min-w-0 flex-1 items-baseline gap-2 pl-9 transition-opacity duration-150 ease-out motion-reduce:transition-none",
dimmed && "opacity-40 group-hover/row:opacity-90 peer-focus-visible:opacity-100"
)}
>
<div
className={cn(
"flex min-w-0 flex-1 items-center truncate text-[13px] leading-5 text-card-foreground"
)}
data-slot="commit-history-title"
>
<CommitTitle onRowToggle={interactive ? handleToggle : undefined} parts={parts} />
{merge ? (
<Icon.chevronDown
aria-hidden="true"
className={cn(
"ml-2 inline-block size-3 align-middle text-muted-foreground/65 transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none",
isBranchOpen
? "rotate-0 opacity-60 group-hover/row:opacity-100"
: "-rotate-90 opacity-60 group-hover/row:opacity-100"
)}
/>
) : null}
</div>
<div className="relative ml-auto flex flex-none items-center justify-end pl-1">
<AnimatePresence initial={false} mode="popLayout">
{
<motion.span
animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
className="flex origin-right items-center gap-2"
exit={
reduce
? { opacity: 0, transition: { delay: 0, duration: 0 } }
: {
filter: "blur(2px)",
opacity: 0,
transition: {
delay: 0,
duration: 0.14,
ease: EASE_OUT,
},
y: -5,
}
}
initial={reduce ? { opacity: 1 } : { filter: "blur(2px)", opacity: 0, y: 5 }}
key="status-committed"
transition={{
delay: reduce ? 0 : 0.05,
duration: reduce ? 0 : 0.22,
ease: EASE_OUT,
}}
>
{tag ? <TagPill tag={tag} /> : null}
{age ? (
<span
className={cn(
"min-w-7 text-right text-xs leading-5 text-muted-foreground/85 tabular-nums @max-[20rem]/commit-history:hidden"
)}
data-slot="commit-history-timestamp"
>
{age}
</span>
) : null}
</motion.span>
}
</AnimatePresence>
</div>
</div>
</div>
{/* Expanded commit details for non-merge commits */}
<AnimatePresence initial={false}>
{isSelected ? (
<motion.div
animate={{ height: "auto", opacity: 1 }}
className="overflow-hidden"
exit={{ height: 0, opacity: 0 }}
initial={{ height: 0, opacity: 0 }}
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
>
<CommitDetailsPanel commit={commit} indentClass="pl-9" />
</motion.div>
) : null}
</AnimatePresence>
</motion.div>
{/* Expandable branched child commits for merge commits */}
{merge ? (
<AnimatePresence initial={false}>
{isBranchOpen ? (
<motion.div
animate={{
height: "auto",
opacity: 1,
transitionEnd: { overflow: "visible" },
}}
className="overflow-hidden"
data-slot="commit-history-branch-commits"
exit={{ height: 0, opacity: 0, overflow: "hidden" }}
initial={{ height: 0, opacity: 0, overflow: "hidden" }}
transition={{ duration: reduce ? 0 : 0.24, ease: EASE_OUT }}
>
<BranchCurveTop />
<ol className={cn("m-0 flex list-none flex-col p-0")}>
<AnimatePresence initial={false}>
{childCommits.map((child) => (
<ChildCommitRow commit={child} context={context} key={child.id} />
))}
</AnimatePresence>
</ol>
<BranchCurveBottom fadeId={fadeId} fadeOut={isLast} />
</motion.div>
) : null}
</AnimatePresence>
) : null}
{/* Fading vertical tail below the final commit when no branch return curve handles it */}
{isLast && !(merge && isBranchOpen) ? <MainTailFade fadeId={fadeId} /> : null}
</motion.li>
);
};
export const CommitHistory = ({
disabled = false,
branch,
branches,
commits,
onBranchChange,
emptyMessage = "No commits on this branch yet.",
className,
classNames,
}: CommitHistoryProps) => {
const baseId = useId();
const reduce = useReducedMotion();
const now = useClock();
const normalizedBranches = useMemo<readonly CommitBranch[]>(
() => (branches?.length ? branches : [{ commits: commits ?? [], name: branch }]),
[branch, branches, commits]
);
const activeBranch =
normalizedBranches.find((item) => item.name === branch) ?? normalizedBranches[0];
const [selectedId, setSelectedId] = useState<string | null>(null);
const [expandedMergeIds, setExpandedMergeIds] = useState<string[]>([]);
const setBranch = (next: string) => {
setSelectedId(null);
onBranchChange?.(next);
};
const toggleDetails = (id: string) => setSelectedId(selectedId === id ? null : id);
const toggleMerge = (id: string) =>
setExpandedMergeIds(
expandedMergeIds.includes(id)
? expandedMergeIds.filter((item) => item !== id)
: [...expandedMergeIds, id]
);
const totalCommits = activeBranch.commitCount ?? countCommittedEntries(activeBranch.commits);
const canSwitchBranch = normalizedBranches.length > 1;
const expandedSet = useMemo(() => new Set(expandedMergeIds), [expandedMergeIds]);
const hasVisibleSelection = useMemo(() => {
if (!selectedId) {
return false;
}
for (const entry of activeBranch.commits) {
if (entry.id === selectedId) {
return true;
}
if (expandedSet.has(entry.id) && entry.commits?.some((child) => child.id === selectedId)) {
return true;
}
}
return false;
}, [activeBranch.commits, expandedSet, selectedId]);
const rowContext: RowDisplayContext = {
hasSpotlight: hasVisibleSelection,
now,
onToggleDetails: toggleDetails,
onToggleMerge: toggleMerge,
reduce,
selectedId: hasVisibleSelection ? selectedId : null,
};
return (
<section
aria-label={`${activeBranch.name} version history, ${pluralize(totalCommits, "version")}`}
className={cn(
THEME_VARS,
ENTER_CLASS,
"@container/commit-history flex w-full max-w-full min-w-0 flex-col gap-3 rounded-2xl bg-card px-4 pt-3.5 pb-2.5 text-card-foreground transition-shadow duration-150 ease-out motion-reduce:transition-none",
className
)}
data-branch={activeBranch.name}
data-committing="false"
data-slot="commit-history"
data-state={hasVisibleSelection ? "inspecting" : "idle"}
>
<header
className={cn("flex h-6 min-w-0 items-center justify-between gap-2", classNames?.header)}
data-slot="commit-history-header"
>
{canSwitchBranch ? (
<DropdownMenu>
<DropdownMenuTrigger
className={cn(
"relative -ml-1.5 inline-flex h-6 min-w-0 cursor-pointer items-center gap-1 rounded-md border-0 bg-transparent px-1.5 text-[13px] leading-tight font-medium tracking-[-0.01em] text-card-foreground transition-[background-color,transform] duration-150 ease-out after:absolute after:inset-x-0 after:-inset-y-2 after:content-[''] hover:bg-foreground/6 active:scale-[0.97] data-popup-open:bg-foreground/8 motion-reduce:transition-none",
FOCUS_CLASS
)}
data-slot="commit-history-branch-trigger"
disabled={disabled}
>
<span className="truncate">{activeBranch.name}</span>
<Icon.chevronDown
aria-hidden="true"
className="size-3 flex-none text-muted-foreground/75"
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-44 rounded-xl p-1 ">
{normalizedBranches.map((item) => {
const selected = item.name === activeBranch.name;
const count = item.commitCount ?? countCommittedEntries(item.commits);
return (
<DropdownMenuItem
className="flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-xs"
key={item.name}
onClick={() => {
setBranch(item.name);
}}
>
<Icon.gitBranch
aria-hidden="true"
className="size-3.5 flex-none text-muted-foreground"
/>
<span className="min-w-0 flex-1 truncate font-mono text-[12px] font-medium">
{item.name}
</span>
<span className="flex-none text-[11px] text-muted-foreground tabular-nums">
{count}
</span>
<Icon.success
aria-hidden="true"
className={cn(
"size-3 flex-none text-card-foreground",
selected ? "opacity-100" : "opacity-0"
)}
/>
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
) : (
<div
className={cn(
"flex min-w-0 items-center gap-1.5 text-[13px] leading-tight font-medium tracking-[-0.01em] text-card-foreground"
)}
data-slot="commit-history-branch-trigger"
>
<span className="truncate">{activeBranch.name}</span>
</div>
)}
<span
className={cn(
"inline-flex flex-none items-baseline gap-1 text-xs leading-4 text-muted-foreground tabular-nums"
)}
data-slot="commit-history-count"
>
<span className="relative inline-flex overflow-hidden">
<AnimatePresence initial={false} mode="popLayout">
<motion.span
animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
className="inline-block"
exit={reduce ? { opacity: 0 } : { filter: "blur(2px)", opacity: 0, y: 6 }}
initial={reduce ? { opacity: 1 } : { filter: "blur(2px)", opacity: 0, y: -6 }}
key={totalCommits}
transition={{ duration: reduce ? 0 : 0.22, ease: EASE_OUT }}
>
{totalCommits}
</motion.span>
</AnimatePresence>
</span>
<span>{totalCommits === 1 ? "version" : "versions"}</span>
</span>
</header>
<ol
className={cn("m-0 flex list-none flex-col p-0", classNames?.list)}
data-slot="commit-history-list"
key={activeBranch.name}
>
<AnimatePresence initial={false}>
{activeBranch.commits.map((commit, index) => {
return (
<MainCommitRow
commit={commit}
context={rowContext}
fadeId={`${baseId}-fade-${commit.id}`}
isBranchOpen={expandedSet.has(commit.id)}
isFirst={index === 0}
isLast={index === activeBranch.commits.length - 1}
key={commit.id}
/>
);
})}
</AnimatePresence>
</ol>
{activeBranch.commits.length === 0 && emptyMessage ? (
<p className="m-0 py-4 text-center text-xs text-muted-foreground">{emptyMessage}</p>
) : null}
</section>
);
};