The platform for continuously improving AI agents.
import { useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type FileDiffLine = {
old: number | null;
cur: number | null;
type: "ctx" | "add" | "del";
text: string;
};
export function FileDiff({
before,
after,
file = "evaluate.py",
embedded = false,
}: {
before: string;
after: string;
file?: string;
embedded?: boolean;
}) {
const [open, setOpen] = useState(false);
const reduce = useReducedMotion();
const oldLines = before.split("\n");
const newLines = after.split("\n");
let prefix = 0;
while (
prefix < oldLines.length &&
prefix < newLines.length &&
oldLines[prefix] === newLines[prefix]
)
prefix++;
let suffix = 0;
while (
suffix < oldLines.length - prefix &&
suffix < newLines.length - prefix &&
oldLines.at(-1 - suffix) === newLines.at(-1 - suffix)
)
suffix++;
const rows: FileDiffLine[] = [
...oldLines
.slice(0, prefix)
.map((text, i) => ({ cur: i + 1, old: i + 1, text, type: "ctx" as const })),
...oldLines
.slice(prefix, oldLines.length - suffix)
.map((text, i) => ({ cur: null, old: prefix + i + 1, text, type: "del" as const })),
...newLines
.slice(prefix, newLines.length - suffix)
.map((text, i) => ({ cur: prefix + i + 1, old: null, text, type: "add" as const })),
...newLines.slice(newLines.length - suffix).map((text, i) => ({
cur: newLines.length - suffix + i + 1,
old: oldLines.length - suffix + i + 1,
text,
type: "ctx" as const,
})),
];
return (
<section
aria-label={`${file} changes`}
className={cn(
"overflow-hidden",
embedded ? "border-t border-border/70" : "rounded-sm border border-border"
)}
data-slot="file-diff"
>
<Button
aria-expanded={open}
className="w-full justify-start rounded-none text-xs text-muted-foreground no-underline hover:bg-wash-subtle hover:text-foreground"
onClick={() => setOpen(!open)}
size="sm"
variant="link"
>
{open ? "Hide" : "Review"} changes · {file}
</Button>
<AnimatePresence initial={false}>
{open && (
<motion.div
animate={{ height: "auto", opacity: 1 }}
className="overflow-x-auto border-t border-border font-mono text-xs"
exit={{ height: 0, opacity: 0 }}
initial={{ height: 0, opacity: 0 }}
transition={{ duration: reduce ? 0 : 0.2, ease: [0.25, 1, 0.5, 1] }}
>
{rows.map((row, i) => (
<div
className={cn(
"flex min-w-max leading-6",
row.type === "add" && "bg-success/10 text-success",
row.type === "del" && "bg-error/10 text-error"
)}
key={i}
>
<span
aria-hidden
className="sticky left-0 w-10 shrink-0 bg-card px-2 text-right text-muted-foreground"
>
{row.old}
</span>
<span
aria-hidden
className="sticky left-10 w-10 shrink-0 bg-card px-2 text-right text-muted-foreground"
>
{row.cur}
</span>
<pre className="px-3">
{row.type === "add" ? "+" : row.type === "del" ? "−" : " "} {row.text}
</pre>
</div>
))}
</motion.div>
)}
</AnimatePresence>
</section>
);
}