"use client"; import { useRef, useState } from "react"; import "./branch-switcher.css"; /** * Branch Switcher * Editing a message doesn't overwrite it — it starts a branch. Step between versions with the * pager under the message; the question and its answer slide together in the direction you * moved, and a small tree shows where you are among the branches. */ export type Version = { prompt: string; answer: string }; type Props = { versions: Version[]; reply?: (prompt: string) => string; theme?: "paper" | "night"; className?: string }; export function BranchSwitcher({ versions: initial, reply = () => "Here's a version that takes that into account.", theme = "paper", className = "" }: Props) { const [versions, setVersions] = useState(initial); const [at, setAt] = useState(initial.length - 1); const [dir, setDir] = useState<1 | -1>(1); const [beat, setBeat] = useState(0); const [editing, setEditing] = useState(false); const draft = useRef(null); const go = (n: number) => { if (n < 0 || n >= versions.length || n === at) return; setDir(n > at ? 1 : -1); setAt(n); setBeat((b) => b + 1); }; const save = () => { const p = draft.current?.value.trim(); setEditing(false); if (!p || p === versions[at].prompt) return; setVersions((v) => [...v, { prompt: p, answer: reply(p) }]); setDir(1); setAt(versions.length); setBeat((b) => b + 1); }; const v = versions[at]; return (
0 ? "next" : "prev"}>
{editing ? (
{ e.preventDefault(); save(); }} >