{
  "name": "ai-branches",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: AI Conversation Branches\n * @version: 1.1.0\n * @date: 2026-10-21\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { ChevronLeft, ChevronRight, Pencil } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface BranchMessage {\n  id: string;\n  role: \"user\" | \"assistant\";\n  text: string;\n  /** Id of the message this one answers or follows. Leave out for the first. */\n  parent?: string;\n}\n\n/** A reply: the text, a Promise of it, or a stream of text deltas. */\nexport type BranchReply = string | Promise<string> | AsyncIterable<string>;\n\nexport interface AIBranchesProps {\n  title?: string;\n  /** Every message on every branch, read once on mount. Siblings form a fork. */\n  messages?: BranchMessage[];\n  /**\n   * Writes the reply to an edited message. It gets the edit and the messages\n   * above it on that branch, and returns the reply, a Promise of it, or a\n   * stream of deltas (like the AI SDK's `textStream`). Throw and the reply\n   * shows the error's message. Demo text when omitted.\n   */\n  reply?: (\n    prompt: string,\n    history: BranchMessage[],\n    signal: AbortSignal\n  ) => BranchReply;\n  /** Every message on every branch, once a new branch's reply is in. */\n  onChange?: (messages: BranchMessage[]) => void;\n  className?: string;\n}\n\ninterface Node {\n  id: string;\n  role: \"root\" | \"user\" | \"assistant\";\n  text: string;\n  parent: string | null;\n  children: string[];\n  /** The reply failed; text says why. */\n  error?: boolean;\n}\n\ntype Tree = Record<string, Node>;\n\nconst ROOT = \"root\";\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst ROW = 30;\nconst LANE = 18;\nconst PAD = 12;\nconst WORD_GAP = /(\\s+)/;\n\nconst DEMO_MESSAGES: BranchMessage[] = [\n  {\n    id: \"u1\",\n    role: \"user\",\n    text: \"Plan three days in Lisbon for early March.\",\n  },\n  {\n    id: \"a1\",\n    role: \"assistant\",\n    parent: \"u1\",\n    text: \"Day 1: Alfama, the castle at sunset, dinner in Mouraria.\\nDay 2: Belém in the morning, then LX Factory.\\nDay 3: the train to Sintra for Pena Palace and Quinta da Regaleira.\",\n  },\n  {\n    id: \"u2\",\n    role: \"user\",\n    parent: \"a1\",\n    text: \"Make day 3 less touristy.\",\n  },\n  {\n    id: \"a2\",\n    role: \"assistant\",\n    parent: \"u2\",\n    text: \"Skip Sintra. Take the train to Cascais, walk the coast path out to Guincho, and have grilled fish at a beach shack before heading back.\",\n  },\n  {\n    id: \"u2b\",\n    role: \"user\",\n    parent: \"a1\",\n    text: \"Give day 3 a food focus.\",\n  },\n  {\n    id: \"a2b\",\n    role: \"assistant\",\n    parent: \"u2b\",\n    text: \"Spend day 3 eating: custard tarts at Manteigaria, lunch at the Time Out Market, then a petiscos crawl through Bairro Alto.\",\n  },\n  {\n    id: \"u1b\",\n    role: \"user\",\n    text: \"Plan three days in Porto for early March.\",\n  },\n  {\n    id: \"a1b\",\n    role: \"assistant\",\n    parent: \"u1b\",\n    text: \"Day 1: Ribeira and a port lodge in Gaia.\\nDay 2: Livraria Lello early, then the Serralves gardens.\\nDay 3: a day on the Douro valley train.\",\n  },\n];\n\nconst TRAILING_STOP = /[.!?]+$/;\n\nconst demoReply = (prompt: string) => {\n  const quoted = prompt.replace(TRAILING_STOP, \"\");\n  const short = quoted.length > 48 ? `${quoted.slice(0, 48)}…` : quoted;\n  return `Here is a version built around “${short}”. I kept it to three days and put the busiest stops in the mornings, so the afternoons stay free for wandering.`;\n};\n\nconst isStream = (value: BranchReply): value is AsyncIterable<string> =>\n  typeof value === \"object\" && Symbol.asyncIterator in value;\n\n/** Reads a reply, calling `onText` with all the text so far. */\nasync function readReply(reply: BranchReply, onText: (text: string) => void) {\n  if (!isStream(reply)) {\n    onText(await reply);\n    return;\n  }\n  let text = \"\";\n  for await (const delta of reply) {\n    text += delta;\n    onText(text);\n  }\n}\n\nconst reasonOf = (error: unknown) =>\n  error instanceof Error && error.message\n    ? error.message\n    : \"Couldn’t write a reply. Try again.\";\n\n/** The tree back as a flat list, the shape `messages` takes. */\nconst flatten = (tree: Tree): BranchMessage[] =>\n  Object.values(tree)\n    .filter((n) => n.role !== \"root\" && !n.error)\n    .map((n) => ({\n      id: n.id,\n      role: n.role as BranchMessage[\"role\"],\n      text: n.text,\n      parent: n.parent === ROOT ? undefined : (n.parent ?? undefined),\n    }));\n\n/** The messages from the top of the tree down to `id`, not including it. */\nconst historyOf = (tree: Tree, id: string): BranchMessage[] => {\n  const out: BranchMessage[] = [];\n  let at = tree[id].parent;\n  while (at && at !== ROOT) {\n    const n = tree[at];\n    out.unshift({\n      id: n.id,\n      role: n.role as BranchMessage[\"role\"],\n      text: n.text,\n      parent: n.parent === ROOT ? undefined : (n.parent ?? undefined),\n    });\n    at = n.parent;\n  }\n  return out;\n};\n\nconst buildTree = (messages: BranchMessage[]): Tree => {\n  const tree: Tree = {\n    [ROOT]: { id: ROOT, role: \"root\", text: \"\", parent: null, children: [] },\n  };\n  for (const m of messages) {\n    tree[m.id] = {\n      id: m.id,\n      role: m.role,\n      text: m.text,\n      parent: m.parent ?? ROOT,\n      children: [],\n    };\n  }\n  for (const m of messages) {\n    tree[m.parent ?? ROOT]?.children.push(m.id);\n  }\n  return tree;\n};\n\n/** Follow the picked child at every fork, from the top to a leaf. */\nconst pathOf = (tree: Tree, picked: Record<string, number>) => {\n  const path: string[] = [];\n  let node = tree[ROOT];\n  while (node.children.length > 0) {\n    const next =\n      node.children[Math.min(picked[node.id] ?? 0, node.children.length - 1)];\n    path.push(next);\n    node = tree[next];\n  }\n  return path;\n};\n\n/** Rows by depth; the first child keeps its parent's lane, others branch right. */\nconst layout = (tree: Tree) => {\n  const pos: Record<string, { row: number; lane: number }> = {};\n  let lanes = 1;\n  let rows = 1;\n  const visit = (id: string, row: number, lane: number) => {\n    pos[id] = { row, lane };\n    rows = Math.max(rows, row + 1);\n    tree[id].children.forEach((child, i) => {\n      if (i === 0) {\n        visit(child, row + 1, lane);\n      } else {\n        visit(child, row + 1, lanes);\n        lanes += 1;\n      }\n    });\n  };\n  visit(ROOT, 0, 0);\n  return { pos, lanes, rows };\n};\n\n/** How much of a reply to show: a demo reply types in, a live one shows all. */\nconst wordsFor = (\n  id: string,\n  writing: { id: string; words: number } | null,\n  answering: string | null\n) => {\n  if (writing?.id === id) {\n    return writing.words;\n  }\n  return answering === id ? Number.POSITIVE_INFINITY : undefined;\n};\n\nexport default function AIBranches({\n  title = \"Trip planning\",\n  messages = DEMO_MESSAGES,\n  reply = demoReply,\n  onChange,\n  className,\n}: AIBranchesProps) {\n  const reduceMotion = useReducedMotion();\n  const [tree, setTree] = useState(() => buildTree(messages));\n  const [picked, setPicked] = useState<Record<string, number>>({});\n  const [dir, setDir] = useState(1);\n  const [hover, setHover] = useState<string | null>(null);\n  const [editing, setEditing] = useState<string | null>(null);\n  const [writing, setWriting] = useState<{ id: string; words: number } | null>(\n    null\n  );\n  // Switching version or sending an edit swaps the message, and the button\n  // pressed goes with it. The control to focus in its replacement:\n  const [refocus, setRefocus] = useState<{\n    id: string;\n    control: Control;\n  } | null>(null);\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const count = useRef(0);\n  // A reply still arriving from your model, shown with a caret.\n  const [answering, setAnswering] = useState<string | null>(null);\n  const abortRef = useRef<AbortController>(undefined);\n  // Counts replies that finished, so the app hears about the new tree.\n  const [settled, setSettled] = useState(0);\n  const latest = useRef({ tree, onChange });\n  latest.current = { tree, onChange };\n  useEffect(() => {\n    if (settled > 0) {\n      latest.current.onChange?.(flatten(latest.current.tree));\n    }\n  }, [settled]);\n\n  const path = useMemo(() => pathOf(tree, picked), [tree, picked]);\n  const map = useMemo(() => layout(tree), [tree]);\n  const leaves = Object.values(tree).filter(\n    (n) => n.children.length === 0 && n.id !== ROOT\n  ).length;\n\n  // Stream an edited branch's reply in, a word at a time.\n  useEffect(() => {\n    if (!writing) {\n      return;\n    }\n    const total = tree[writing.id].text.split(WORD_GAP).length;\n    if (reduceMotion || writing.words >= total) {\n      setWriting(null);\n      return;\n    }\n    const id = setTimeout(\n      () => setWriting((w) => w && { ...w, words: w.words + 2 }),\n      45\n    );\n    return () => clearTimeout(id);\n  }, [writing, tree, reduceMotion]);\n\n  // Keep the newest message in view while a reply streams.\n  const answerText = answering ? tree[answering]?.text : undefined;\n  useEffect(() => {\n    if (writing || answerText !== undefined) {\n      const el = scrollRef.current;\n      el?.scrollTo({ top: el.scrollHeight });\n    }\n  }, [writing, answerText]);\n\n  /** Point every fork above `id` at it, so the chat shows that branch. */\n  const show = (id: string, by?: number) => {\n    const lane = (n?: string) => (n ? (map.pos[n]?.lane ?? 0) : 0);\n    setDir(by ?? (lane(id) >= lane(path.at(-1)) ? 1 : -1));\n    setPicked((current) => {\n      const next = { ...current };\n      let child = id;\n      let parent = tree[id].parent;\n      while (parent) {\n        next[parent] = tree[parent].children.indexOf(child);\n        child = parent;\n        parent = tree[parent].parent;\n      }\n      return next;\n    });\n  };\n\n  const step = (id: string, by: number) => {\n    const parent = tree[id].parent ?? ROOT;\n    const siblings = tree[parent].children;\n    const next = siblings[siblings.indexOf(id) + by];\n    if (next) {\n      show(next, by);\n      setRefocus({ id: next, control: by < 0 ? \"prev\" : \"next\" });\n    }\n  };\n\n  const submitEdit = (id: string, text: string) => {\n    setEditing(null);\n    const trimmed = text.trim();\n    if (!trimmed || trimmed === tree[id].text) {\n      return;\n    }\n    count.current += 1;\n    const user = `edit-${count.current}`;\n    const answer = `${user}-reply`;\n    const parent = tree[id].parent ?? ROOT;\n    abortRef.current?.abort();\n    const controller = new AbortController();\n    abortRef.current = controller;\n    const result = reply(trimmed, historyOf(tree, id), controller.signal);\n    const sync = typeof result === \"string\";\n    setTree((t) => ({\n      ...t,\n      [parent]: { ...t[parent], children: [...t[parent].children, user] },\n      [user]: {\n        id: user,\n        role: \"user\",\n        text: trimmed,\n        parent,\n        children: [answer],\n      },\n      [answer]: {\n        id: answer,\n        role: \"assistant\",\n        text: sync ? result : \"\",\n        parent: user,\n        children: [],\n      },\n    }));\n    setPicked((p) => ({ ...p, [parent]: tree[parent].children.length }));\n    setDir(1);\n    setRefocus({ id: user, control: \"edit\" });\n    if (sync) {\n      setWriting({ id: answer, words: 0 });\n      setSettled((n) => n + 1);\n      return;\n    }\n    const write = (text: string, error?: boolean) =>\n      setTree((t) => ({ ...t, [answer]: { ...t[answer], text, error } }));\n    setAnswering(answer);\n    readReply(result, write)\n      .then(\n        () => setSettled((n) => n + 1),\n        (e: unknown) => {\n          if (!controller.signal.aborted) {\n            write(reasonOf(e), true);\n          }\n        }\n      )\n      .finally(() =>\n        setAnswering((current) => (current === answer ? null : current))\n      );\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\n          \"flex h-[460px] w-full max-w-xl flex-col overflow-hidden rounded-2xl bg-white ring-1 ring-black/[0.08] dark:bg-zinc-900 dark:ring-white/10\",\n          className\n        )}\n        data-state={answering || writing ? \"streaming\" : \"idle\"}\n      >\n        <header className=\"flex items-center justify-between border-black/[0.06] border-b px-4 py-3 dark:border-white/[0.08]\">\n          <h2 className=\"font-medium text-sm text-zinc-900 dark:text-zinc-100\">\n            {title}\n          </h2>\n          <p className=\"text-xs text-zinc-500 tabular-nums dark:text-zinc-400\">\n            {leaves} {leaves === 1 ? \"branch\" : \"branches\"}\n          </p>\n        </header>\n\n        <div className=\"relative flex min-h-0 flex-1\">\n          <div\n            className=\"min-w-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4\"\n            ref={scrollRef}\n          >\n            <ol className=\"space-y-4\">\n              <AnimatePresence custom={dir} initial={false} mode=\"popLayout\">\n                {path.map((id) => (\n                  <motion.li\n                    animate=\"in\"\n                    custom={dir}\n                    exit=\"out\"\n                    initial=\"from\"\n                    key={id}\n                    onPointerEnter={() => setHover(id)}\n                    onPointerLeave={() => setHover(null)}\n                    transition={{ duration: 0.28, ease: EASE_OUT }}\n                    variants={slide}\n                  >\n                    <MessageView\n                      editing={editing === id}\n                      focus={refocus?.id === id ? refocus.control : undefined}\n                      lit={hover === id}\n                      node={tree[id]}\n                      onCancel={() => setEditing(null)}\n                      onEdit={() => setEditing(id)}\n                      onFocused={() => setRefocus(null)}\n                      onStep={(by) => step(id, by)}\n                      onSubmit={(text) => submitEdit(id, text)}\n                      siblings={tree[tree[id].parent ?? ROOT].children}\n                      words={wordsFor(id, writing, answering)}\n                    />\n                  </motion.li>\n                ))}\n              </AnimatePresence>\n            </ol>\n          </div>\n\n          <AnimatePresence>\n            {hover && !path.includes(hover) && tree[hover] && (\n              <motion.p\n                animate={{ opacity: 1, x: 0 }}\n                className=\"pointer-events-none absolute right-[84px] z-10 line-clamp-3 w-52 rounded-lg bg-white px-3 py-2 text-[12px] text-zinc-600 leading-snug shadow-[0_8px_24px_-10px_rgb(0_0_0/0.3)] ring-1 ring-black/[0.08] sm:right-[100px] dark:bg-zinc-800 dark:text-zinc-300 dark:ring-white/10\"\n                exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                initial={{ opacity: 0, x: 4 }}\n                key={hover}\n                style={{ top: PAD + (map.pos[hover]?.row ?? 0) * ROW - 6 }}\n                transition={{ duration: 0.15, ease: EASE_OUT }}\n              >\n                <span className=\"mb-0.5 block font-medium text-[11px] text-zinc-900 dark:text-zinc-100\">\n                  {tree[hover].role === \"user\" ? \"You asked\" : \"Reply\"}\n                </span>\n                {tree[hover].text}\n              </motion.p>\n            )}\n          </AnimatePresence>\n          <Rail\n            hover={hover}\n            map={map}\n            onHover={setHover}\n            onPick={show}\n            path={path}\n            tree={tree}\n          />\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n\ntype Control = \"prev\" | \"next\" | \"edit\";\n\nconst slide = {\n  from: (dir: number) => ({ opacity: 0, x: dir * 18 }),\n  in: { opacity: 1, x: 0 },\n  out: (dir: number) => ({ opacity: 0, x: dir * -18 }),\n};\n\nfunction MessageView({\n  node,\n  siblings,\n  editing,\n  focus,\n  lit,\n  words,\n  onEdit,\n  onCancel,\n  onFocused,\n  onSubmit,\n  onStep,\n}: {\n  node: Node;\n  siblings: string[];\n  editing: boolean;\n  /** Takes focus on mount: the pager arrow or Edit that brought it here. */\n  focus?: Control;\n  lit: boolean;\n  words?: number;\n  onFocused: () => void;\n  onEdit: () => void;\n  onCancel: () => void;\n  onSubmit: (text: string) => void;\n  onStep: (by: number) => void;\n}) {\n  const editRef = useRef<HTMLButtonElement>(null);\n  const prevRef = useRef<HTMLButtonElement>(null);\n  const nextRef = useRef<HTMLButtonElement>(null);\n  const wasEditing = useRef(editing);\n\n  useEffect(() => {\n    if (!focus) {\n      return;\n    }\n    // At the first or last version that arrow is disabled; use the other.\n    const order =\n      focus === \"edit\"\n        ? [editRef]\n        : [\n            focus === \"prev\" ? prevRef : nextRef,\n            focus === \"prev\" ? nextRef : prevRef,\n            editRef,\n          ];\n    order\n      .map((ref) => ref.current)\n      .find((button) => button && !button.disabled)\n      ?.focus({ preventScroll: true });\n    onFocused();\n  }, [focus, onFocused]);\n  // Cancelling unmounts the text box, so focus goes back to Edit.\n  useEffect(() => {\n    if (wasEditing.current && !editing) {\n      editRef.current?.focus();\n    }\n    wasEditing.current = editing;\n  }, [editing]);\n\n  if (node.role === \"assistant\") {\n    const text =\n      words === undefined\n        ? node.text\n        : node.text.split(WORD_GAP).slice(0, words).join(\"\");\n    return (\n      <p\n        className={cn(\n          \"-mx-2 whitespace-pre-line rounded-lg px-2 py-1 text-[14px] leading-relaxed transition-colors duration-150\",\n          node.error\n            ? \"text-rose-600 dark:text-rose-400\"\n            : \"text-zinc-700 dark:text-zinc-300\",\n          lit && \"bg-zinc-900/[0.03] dark:bg-white/[0.04]\"\n        )}\n        role={node.error ? \"alert\" : undefined}\n      >\n        {text}\n        {words !== undefined && (\n          <span\n            aria-hidden=\"true\"\n            className=\"ml-0.5 inline-block h-3.5 w-1.5 translate-y-[2px] animate-pulse rounded-[2px] bg-zinc-700 dark:bg-zinc-300\"\n          />\n        )}\n      </p>\n    );\n  }\n\n  const index = siblings.indexOf(node.id);\n  return (\n    <div className=\"group flex flex-col items-end gap-1\">\n      {editing ? (\n        <EditBox initial={node.text} onCancel={onCancel} onSubmit={onSubmit} />\n      ) : (\n        <p\n          className={cn(\n            \"max-w-[85%] rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-[14px] text-zinc-800 leading-snug transition-colors duration-150 dark:bg-zinc-800 dark:text-zinc-100\",\n            lit && \"bg-zinc-200/80 dark:bg-zinc-700/80\"\n          )}\n        >\n          {node.text}\n        </p>\n      )}\n      {!editing && (\n        <div className=\"flex h-6 items-center gap-0.5 text-zinc-400 dark:text-zinc-500\">\n          <button\n            aria-label=\"Edit message\"\n            className=\"flex size-6 items-center justify-center rounded-md opacity-0 transition-[opacity,color,background-color] duration-150 hover:bg-zinc-100 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:hover:bg-white/[0.07] dark:hover:text-zinc-200 [@media(hover:none)]:opacity-100\"\n            onClick={onEdit}\n            ref={editRef}\n            type=\"button\"\n          >\n            <Pencil className=\"size-3\" />\n          </button>\n          {siblings.length > 1 && (\n            <>\n              <button\n                aria-label=\"Previous version\"\n                className=\"flex size-6 items-center justify-center rounded-md transition-colors duration-150 enabled:hover:bg-zinc-100 enabled:hover:text-zinc-700 disabled:opacity-40 dark:enabled:hover:bg-white/[0.07] dark:enabled:hover:text-zinc-200\"\n                disabled={index === 0}\n                onClick={() => onStep(-1)}\n                ref={prevRef}\n                type=\"button\"\n              >\n                <ChevronLeft className=\"size-3.5\" />\n              </button>\n              <span className=\"min-w-7 text-center font-mono text-[11px] tabular-nums\">\n                {index + 1}/{siblings.length}\n              </span>\n              <button\n                aria-label=\"Next version\"\n                className=\"flex size-6 items-center justify-center rounded-md transition-colors duration-150 enabled:hover:bg-zinc-100 enabled:hover:text-zinc-700 disabled:opacity-40 dark:enabled:hover:bg-white/[0.07] dark:enabled:hover:text-zinc-200\"\n                disabled={index === siblings.length - 1}\n                onClick={() => onStep(1)}\n                ref={nextRef}\n                type=\"button\"\n              >\n                <ChevronRight className=\"size-3.5\" />\n              </button>\n            </>\n          )}\n        </div>\n      )}\n    </div>\n  );\n}\n\nfunction EditBox({\n  initial,\n  onCancel,\n  onSubmit,\n}: {\n  initial: string;\n  onCancel: () => void;\n  onSubmit: (text: string) => void;\n}) {\n  const [draft, setDraft] = useState(initial);\n  const ref = useRef<HTMLTextAreaElement>(null);\n\n  useEffect(() => {\n    const el = ref.current;\n    el?.focus();\n    el?.setSelectionRange(el.value.length, el.value.length);\n  }, []);\n\n  const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n    // Enter that confirms an IME candidate must not send.\n    if (event.nativeEvent.isComposing) {\n      return;\n    }\n    if (event.key === \"Enter\" && !event.shiftKey) {\n      event.preventDefault();\n      onSubmit(draft);\n    } else if (event.key === \"Escape\") {\n      onCancel();\n    }\n  };\n\n  return (\n    <div className=\"w-full max-w-[85%] rounded-2xl bg-zinc-100 p-2 dark:bg-zinc-800\">\n      <textarea\n        aria-label=\"Edit message\"\n        className=\"block w-full resize-none bg-transparent px-1.5 py-1 text-[14px] text-zinc-900 leading-snug outline-hidden dark:text-zinc-100 [@media(pointer:coarse)]:text-base\"\n        onChange={(e) => setDraft(e.target.value)}\n        onKeyDown={onKeyDown}\n        ref={ref}\n        rows={2}\n        value={draft}\n      />\n      <div className=\"mt-1 flex items-center justify-between gap-2\">\n        <p className=\"pl-1.5 text-[11px] text-zinc-500 dark:text-zinc-400\">\n          Sending starts a new branch\n        </p>\n        <div className=\"flex gap-1.5\">\n          <button\n            className=\"h-7 rounded-lg px-2.5 text-[12px] text-zinc-600 transition-colors duration-150 hover:bg-white hover:text-zinc-900 dark:text-zinc-300 dark:hover:bg-white/[0.07] dark:hover:text-white\"\n            onClick={onCancel}\n            type=\"button\"\n          >\n            Cancel\n          </button>\n          <button\n            className=\"h-7 rounded-lg bg-zinc-900 px-2.5 font-medium text-[12px] text-white transition-colors duration-150 hover:bg-zinc-700 disabled:opacity-40 dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-200\"\n            disabled={!draft.trim()}\n            onClick={() => onSubmit(draft)}\n            type=\"button\"\n          >\n            Send\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction Rail({\n  tree,\n  map,\n  path,\n  hover,\n  onHover,\n  onPick,\n}: {\n  tree: Tree;\n  map: ReturnType<typeof layout>;\n  path: string[];\n  hover: string | null;\n  onHover: (id: string | null) => void;\n  onPick: (id: string) => void;\n}) {\n  const on = new Set([ROOT, ...path]);\n  const width = PAD * 2 + (map.lanes - 1) * LANE;\n  const height = PAD * 2 + (map.rows - 1) * ROW;\n  const at = (id: string) => ({\n    x: PAD + map.pos[id].lane * LANE,\n    y: PAD + map.pos[id].row * ROW,\n  });\n  const nodes = Object.values(tree);\n  const edges = nodes.flatMap((n) =>\n    n.children.map((child) => ({ from: n.id, to: child }))\n  );\n\n  return (\n    <nav\n      aria-label=\"Branches\"\n      className=\"relative w-[76px] shrink-0 overflow-auto border-black/[0.06] border-l bg-zinc-50/60 [scrollbar-width:none] sm:w-[92px] dark:border-white/[0.08] dark:bg-white/[0.02]\"\n    >\n      <div className=\"relative mx-auto\" style={{ width, height }}>\n        <svg\n          aria-hidden=\"true\"\n          className=\"block overflow-visible\"\n          height={height}\n          width={width}\n        >\n          {edges.map(({ from, to }) => {\n            const a = at(from);\n            const b = at(to);\n            const lit = on.has(from) && on.has(to);\n            const d =\n              a.x === b.x\n                ? `M ${a.x} ${a.y} L ${b.x} ${b.y}`\n                : `M ${a.x} ${a.y} C ${a.x} ${a.y + ROW * 0.7} ${b.x} ${b.y - ROW * 0.7} ${b.x} ${b.y}`;\n            return (\n              <motion.path\n                animate={{ pathLength: 1, opacity: 1 }}\n                className={cn(\n                  \"fill-none transition-[stroke,stroke-width] duration-300\",\n                  lit\n                    ? \"stroke-zinc-900 dark:stroke-zinc-100\"\n                    : \"stroke-zinc-300 dark:stroke-zinc-700\"\n                )}\n                d={d}\n                initial={{ pathLength: 0, opacity: 0 }}\n                key={`${from}-${to}`}\n                strokeWidth={lit ? 1.75 : 1.25}\n                transition={{ duration: 0.4, ease: EASE_OUT }}\n              />\n            );\n          })}\n          {nodes.map((n) => {\n            const p = at(n.id);\n            const lit = on.has(n.id);\n            return (\n              <motion.circle\n                animate={{ scale: hover === n.id ? 1.45 : 1, opacity: 1 }}\n                className={cn(\n                  \"transition-[fill,stroke] duration-300\",\n                  lit\n                    ? \"stroke-zinc-900 dark:stroke-zinc-100\"\n                    : \"stroke-zinc-300 dark:stroke-zinc-700\",\n                  n.role === \"assistant\" &&\n                    lit &&\n                    \"fill-zinc-900 dark:fill-zinc-100\",\n                  n.role === \"assistant\" &&\n                    !lit &&\n                    \"fill-zinc-300 dark:fill-zinc-700\",\n                  n.role !== \"assistant\" && \"fill-zinc-50 dark:fill-zinc-900\"\n                )}\n                cx={p.x}\n                cy={p.y}\n                initial={{ scale: 0.5, opacity: 0 }}\n                key={n.id}\n                r={n.role === ROOT ? 2.5 : 3.5}\n                strokeWidth={1.5}\n                transition={{ duration: 0.2, ease: EASE_OUT }}\n              />\n            );\n          })}\n        </svg>\n        {nodes\n          .filter((n) => n.role !== ROOT)\n          .map((n) => {\n            const p = at(n.id);\n            return (\n              <button\n                aria-current={on.has(n.id) ? \"step\" : undefined}\n                aria-label={`${n.role === \"user\" ? \"You\" : \"Reply\"}: ${n.text.slice(0, 60)}`}\n                className=\"absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-zinc-900/30 dark:focus-visible:ring-white/30\"\n                key={n.id}\n                onBlur={() => onHover(null)}\n                onClick={() => onPick(n.id)}\n                onFocus={() => onHover(n.id)}\n                onPointerEnter={() => onHover(n.id)}\n                onPointerLeave={() => onHover(null)}\n                style={{ left: p.x, top: p.y }}\n                type=\"button\"\n              />\n            );\n          })}\n      </div>\n    </nav>\n  );\n}\n",
      "path": "/components/kokonutui/ai-branches.tsx",
      "target": "components/kokonutui/ai-branches.tsx"
    }
  ]
}