
これは何か
Cursor のエージェント履歴のような、黒いパネルの AI チャット履歴です。上の細いバーには+と時計のボタンが並び、時計を押すと同じ幅の履歴パネルが下に開きます。パネルは時計のボタンから広がるように開き、外を押すか Esc で閉じます。会話を選んでもパネルは閉じます。パネルの上には「Search Agents...」の検索欄があり、会話は Today・Yesterday・Older の見出しごとに並びます。各行の頭には完了のチェックが付き、実行中の会話は回るアイコンになります。行にホバーすると出る鉛筆とゴミ箱で、名前の変更と削除ができます。消した行はその場で抜け、下の行がすぐに詰まり、下から出る Undo で戻せます。矢印キーで検索欄から行へ移れます。会話の一覧を差し替えて、AI アプリやエディタの履歴メニューにそのまま置けます。
TSX の全文です。アカウントは不要です。
chat-history-sidebar.tsx
"use client"; import * as React from "react";import { AnimatePresence, motion, useIsPresent, useReducedMotion, type HTMLMotionProps } from "motion/react";import { CircleCheck, Clock, LoaderCircle, Pencil, Plus, Search, Trash2, X } from "lucide-react";import { cn } from "@/lib/utils"; export type ChatHistoryItem = { id: string; title: string; /** Date bucket shown as a small heading, e.g. "Today". Groups appear in the order they first occur. */ group: string; /** Icon at the start of the row. "running" shows a spinner. Defaults to "done". */ status?: "done" | "running";}; export type ChatHistorySidebarLabels = { newChat: string; history: string; search: string; clearSearch: string; noMatches: string; empty: string; /** Title given to a chat made with the New button. */ untitled: string; /** Group a new chat goes into. */ today: string; rename: string; delete: string; deleted: string; /** Shown after a count when several deletes share one undo window, e.g. "2 agents deleted". */ deletedMany: string; undo: string; restored: string; running: string; done: string; navLabel: string;}; export type ChatHistorySidebarProps = Omit<React.ComponentPropsWithoutRef<"div">, "children"> & { /** Starting list, newest first. The component keeps its own copy after that. */ chats?: readonly ChatHistoryItem[]; /** Controlled selection. `null` selects nothing. */ activeId?: string | null; defaultActiveId?: string | null; onActiveChange?: (id: string) => void; /** Controlled open state of the history panel. */ open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; onNewChat?: (chat: ChatHistoryItem) => void; onRename?: (id: string, title: string) => void; /** Fires once the undo window closes without Undo, so the chat is really gone. */ onDelete?: (id: string) => void; /** How long Undo stays available, in ms. Paused while hovered, focused, or the tab is hidden. */ undoDuration?: number; labels?: Partial<ChatHistorySidebarLabels>;}; const DEFAULT_LABELS: ChatHistorySidebarLabels = { newChat: "New agent", history: "Agent history", search: "Search Agents...", clearSearch: "Clear search", noMatches: "No agents match", empty: "No agents yet", untitled: "New agent", today: "Today", rename: "Rename", delete: "Delete", deleted: "Agent deleted", deletedMany: "agents deleted", undo: "Undo", restored: "Agent restored", running: "Running", done: "Done", navLabel: "Agent history",}; const DEFAULT_CHATS: readonly ChatHistoryItem[] = [ { id: "flaky-checkout", title: "Fix the flaky checkout test", group: "Today", status: "running" }, { id: "settings-dark", title: "Add dark mode to settings", group: "Today" }, { id: "auth-middleware", title: "Refactor the auth middleware", group: "Today" }, { id: "catalog-migration", title: "Catalog category migration", group: "Yesterday" }, { id: "orders-docs", title: "Write API docs for /v2/orders", group: "Yesterday" }, { id: "codebase-audit", title: "Codebase audit report", group: "Older" }, { id: "permissions", title: "Permissions matrix for admin roles", group: "Older" }, { id: "preview-deploy", title: "Deploy preview for PR #482", group: "Older" }, { id: "pricing-split", title: "Split the pricing section", group: "Older" }, { id: "export-pipeline", title: "Component export pipeline", group: "Older" }, { id: "debounce-search", title: "Debounce the search input", group: "Older" },]; /** Strong ease-out; the panel, rows, headings and the undo bar share it so one action reads as one motion. */const EASE_OUT = [0.23, 1, 0.32, 1] as const;const FOCUS = "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-[#0078d4]";const PRESS = "transition-transform duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] active:scale-[0.94] motion-reduce:transition-none motion-reduce:active:scale-100"; type Pending = { entries: { item: ChatHistoryItem; index: number }[]; key: number };/** How the panel's last open / close was triggered: keyboard toggles skip the animation. */type Motion = { instant: boolean; reduced: boolean }; /** * Opens out of the history button and closes back into it. The panel is the one entrance: * its rows arrive with it rather than staggering in, since this opens many times a day. */const PANEL_VARIANTS = { shown: ({ instant }: Motion) => ({ opacity: 1, scale: 1, y: 0, transition: instant ? { duration: 0 } : { duration: 0.16, ease: EASE_OUT }, }), hidden: ({ instant, reduced }: Motion) => ({ opacity: 0, scale: reduced ? 1 : 0.97, y: reduced ? 0 : -4, transition: instant ? { duration: 0 } : { duration: 0.12, ease: EASE_OUT }, }),}; function groupChats(chats: readonly ChatHistoryItem[]) { const groups: { label: string; items: ChatHistoryItem[] }[] = []; for (const chat of chats) { const last = groups.find((group) => group.label === chat.group); if (last) last.items.push(chat); else groups.push({ label: chat.group, items: [chat] }); } return groups;} /** * A motion.div that goes inert while it animates out. With popLayout the leaving row still sits * under the pointer for its fade, and its handlers hold the state from before the delete. */const Presence = React.forwardRef<HTMLDivElement, HTMLMotionProps<"div">>(function Presence(props, ref) { const present = useIsPresent(); return <motion.div ref={ref} inert={!present} {...props} />;}); function IconButton({ label, onClick, tone = "default", buttonRef, expanded, children,}: { label: string; onClick: (event: React.MouseEvent<HTMLButtonElement>) => void; tone?: "default" | "danger"; buttonRef?: React.Ref<HTMLButtonElement>; expanded?: boolean; children: React.ReactNode;}) { return ( <button ref={buttonRef} type="button" aria-label={label} aria-expanded={expanded} title={label} onClick={onClick} className={cn( "grid size-6 shrink-0 cursor-pointer place-items-center rounded-[5px] border-0 bg-transparent text-[#9d9d9d]", tone === "danger" ? "hover:bg-red-500/15 hover:text-red-400" : "hover:bg-white/10 hover:text-[#e4e4e4]", "aria-expanded:bg-white/10 aria-expanded:text-[#e4e4e4]", PRESS, FOCUS, )} > {children} </button> );} export const ChatHistorySidebar = React.forwardRef<HTMLDivElement, ChatHistorySidebarProps>( ( { chats: initialChats = DEFAULT_CHATS, activeId, defaultActiveId = "settings-dark", onActiveChange, open: openProp, defaultOpen = true, onOpenChange, onNewChat, onRename, onDelete, undoDuration = 5000, labels, className, ...props }, ref, ) => { const text = { ...DEFAULT_LABELS, ...labels }; const reduced = useReducedMotion() === true; const [chats, setChats] = React.useState<ChatHistoryItem[]>(() => [...initialChats]); const [ownActive, setOwnActive] = React.useState<string | null>(defaultActiveId); const currentActive = activeId !== undefined ? activeId : ownActive; const [ownOpen, setOwnOpen] = React.useState(defaultOpen); const open = openProp !== undefined ? openProp : ownOpen; const [instant, setInstant] = React.useState(false); const [query, setQuery] = React.useState(""); const [editingId, setEditingId] = React.useState<string | null>(null); const [pending, setPending] = React.useState<Pending | null>(null); const [undoHeld, setUndoHeld] = React.useState(false); const [tabHidden, setTabHidden] = React.useState(false); const [announce, setAnnounce] = React.useState(""); const root = React.useRef<HTMLDivElement | null>(null); const counter = React.useRef(0); const rowButtons = React.useRef(new Map<string, HTMLButtonElement>()); const searchInput = React.useRef<HTMLInputElement>(null); const historyButton = React.useRef<HTMLButtonElement>(null); const focusAfter = React.useRef<string | null | undefined>(undefined); const focusSearchOnOpen = React.useRef(false); const renameDone = React.useRef<string | null>(null); const remaining = React.useRef(undoDuration); const onDeleteRef = React.useRef(onDelete); onDeleteRef.current = onDelete; const pendingRef = React.useRef(pending); pendingRef.current = pending; // Handlers read these instead of the render's values, so two clicks in one frame can't act twice. const chatsRef = React.useRef(chats); chatsRef.current = chats; const setRootRef = (node: HTMLDivElement | null) => { root.current = node; if (typeof ref === "function") ref(node); else if (ref) ref.current = node; }; // Move focus to the row that took the removed row's place (or back to a restored / renamed row). React.useEffect(() => { if (focusAfter.current === undefined) return; const target = focusAfter.current; focusAfter.current = undefined; const el = target ? rowButtons.current.get(target) : null; (el ?? searchInput.current)?.focus({ preventScroll: false }); }); React.useEffect(() => { if (!open || !focusSearchOnOpen.current) return; focusSearchOnOpen.current = false; searchInput.current?.focus({ preventScroll: true }); }, [open]); React.useEffect(() => { const sync = () => setTabHidden(document.visibilityState === "hidden"); sync(); document.addEventListener("visibilitychange", sync); return () => document.removeEventListener("visibilitychange", sync); }, []); // Chats still waiting on Undo are really deleted if the component goes away. React.useEffect( () => () => { pendingRef.current?.entries.forEach(({ item }) => onDeleteRef.current?.(item.id)); }, [], ); React.useEffect(() => { remaining.current = undoDuration; setUndoHeld(false); }, [pending?.key, undoDuration]); React.useEffect(() => { if (!pending || undoHeld || tabHidden) return; const startedAt = Date.now(); const timer = setTimeout(() => { pending.entries.forEach(({ item }) => onDeleteRef.current?.(item.id)); setPending(null); }, remaining.current); return () => { clearTimeout(timer); remaining.current = Math.max(0, remaining.current - (Date.now() - startedAt)); }; }, [pending, undoHeld, tabHidden]); const setOpen = (next: boolean, { keyboard = false, focusTrigger = false } = {}) => { setInstant(keyboard); if (next) focusSearchOnOpen.current = true; else { setQuery(""); setEditingId(null); // The undo bar leaves with the panel, so its hover can't keep the timer paused. setUndoHeld(false); if (focusTrigger) historyButton.current?.focus({ preventScroll: true }); } if (openProp === undefined) setOwnOpen(next); onOpenChange?.(next); }; // A press anywhere outside closes the panel, animated, without moving focus. React.useEffect(() => { if (!open) return; const onPointerDown = (event: PointerEvent) => { if (root.current && !root.current.contains(event.target as Node)) setOpen(false); }; document.addEventListener("pointerdown", onPointerDown); return () => document.removeEventListener("pointerdown", onPointerDown); }); const needle = query.trim().toLowerCase(); const visible = needle ? chats.filter((chat) => chat.title.toLowerCase().includes(needle)) : chats; const groups = groupChats(visible); const order = visible.map((chat) => chat.id); const select = (id: string) => { if (activeId === undefined) setOwnActive(id); onActiveChange?.(id); }; // Picking a chat closes the panel; keyboard picks (click detail 0) close without animating. const pick = (id: string, keyboard: boolean) => { select(id); setOpen(false, { keyboard, focusTrigger: true }); }; const focusRow = (id: string | undefined) => { if (id) rowButtons.current.get(id)?.focus(); }; const createChat = () => { counter.current += 1; const chat: ChatHistoryItem = { id: `new-chat-${counter.current}`, title: text.untitled, group: text.today }; setChats((current) => [chat, ...current]); setQuery(""); setEditingId(null); select(chat.id); onNewChat?.(chat); }; const remove = (id: string) => { const list = chatsRef.current; const index = list.findIndex((chat) => chat.id === id); if (index < 0) return; chatsRef.current = list.filter((chat) => chat.id !== id); const at = order.indexOf(id); focusAfter.current = order[at + 1] ?? order[at - 1] ?? null; counter.current += 1; setChats(chatsRef.current); // The next row slides under the pointer, so a double click can delete two chats. // Every delete inside the undo window joins one batch, and Undo brings the whole batch back. const entry = { item: list[index], index }; const next = { entries: [...(pendingRef.current?.entries ?? []), entry], key: counter.current }; pendingRef.current = next; setPending(next); setAnnounce(`${text.deleted}: ${list[index].title}`); if (currentActive === id && activeId === undefined) setOwnActive(null); }; const undo = () => { const batch = pendingRef.current; if (!batch) return; pendingRef.current = null; const { entries } = batch; // Reinsert newest-deleted first; each index was taken from the list as it was at that delete. const restored = [...chatsRef.current]; for (const { item, index } of [...entries].reverse()) { restored.splice(Math.min(index, restored.length), 0, item); } chatsRef.current = restored; setChats(restored); setPending(null); focusAfter.current = entries[0].item.id; setAnnounce( entries.length === 1 ? `${text.restored}: ${entries[0].item.title}` : `${text.restored}: ${entries.length}`, ); }; const finishRename = (id: string, value: string | null) => { // Enter, Escape and the blur that follows can all land here; only the first one counts. if (editingId !== id || renameDone.current === id) return; renameDone.current = id; setEditingId(null); focusAfter.current = id; const title = value?.trim(); const current = chats.find((chat) => chat.id === id); if (!title || !current || current.title === title) return; setChats((list) => list.map((chat) => (chat.id === id ? { ...chat, title } : chat))); onRename?.(id, title); }; // Arrow keys walk from the search field through the rows, like a command menu. const onRowKeyDown = (event: React.KeyboardEvent, id: string) => { const at = order.indexOf(id); if (event.key === "ArrowDown") { event.preventDefault(); focusRow(order[at + 1]); } else if (event.key === "ArrowUp") { event.preventDefault(); if (at <= 0) searchInput.current?.focus(); else focusRow(order[at - 1]); } else if (event.key === "Delete") { event.preventDefault(); remove(id); } else if (event.key === "F2") { event.preventDefault(); renameDone.current = null; setEditingId(id); } }; const enter = reduced ? { opacity: { duration: 0.15 } } : { duration: 0.2, ease: EASE_OUT, layout: { duration: 0.2, ease: EASE_OUT } }; const exit = { opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }; const layout = reduced ? false : ("position" as const); const panelMotion: Motion = { instant, reduced }; return ( <div ref={setRootRef} data-tsuna-id="chat-history-sidebar" data-count={chats.length} data-state={open ? "open" : "closed"} className={cn("relative h-[488px] w-[280px] max-w-full text-[#cccccc] antialiased", className)} {...props} > <div className="flex h-9 items-center justify-end gap-1 px-1.5"> <IconButton label={text.newChat} onClick={createChat}> <Plus aria-hidden className="size-4" /> </IconButton> <IconButton label={text.history} buttonRef={historyButton} expanded={open} onClick={(event) => setOpen(!open, { keyboard: event.detail === 0 })} > <Clock aria-hidden className="size-[15px]" /> </IconButton> </div> <AnimatePresence initial={false} custom={panelMotion}> {open ? ( <motion.nav key="panel" aria-label={text.navLabel} custom={panelMotion} variants={PANEL_VARIANTS} initial="hidden" animate="shown" exit="hidden" // The panel grows out of the history button, which sits at the right of the bar. style={{ transformOrigin: "calc(100% - 18px) -8px" }} onKeyDown={(event) => { // Rename and the search field claim Escape first (they call preventDefault). if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); setOpen(false, { keyboard: true, focusTrigger: true }); } }} className={cn( "absolute inset-x-0 top-11 flex h-[440px] flex-col overflow-hidden rounded-[10px] border border-[#3a3a3a] bg-[#202020]", "shadow-[0_16px_40px_-12px_rgba(0,0,0,0.7),0_2px_6px_rgba(0,0,0,0.35)]", )} > <div className="flex h-10 shrink-0 items-center gap-2 border-b border-[#2f2f2f] pr-1.5 pl-3"> <Search aria-hidden className="size-[15px] shrink-0 text-[#9d9d9d]" strokeWidth={2} /> <input ref={searchInput} type="text" value={query} onChange={(event) => setQuery(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape" && query) { event.preventDefault(); setQuery(""); } else if (event.key === "ArrowDown") { event.preventDefault(); focusRow(order[0]); } else if (event.key === "Enter" && order[0]) { event.preventDefault(); pick(order[0], true); } }} placeholder={text.search} aria-label={text.search} className="h-full min-w-0 flex-1 border-0 bg-transparent p-0 text-[13px] text-[#e4e4e4] caret-[#e4e4e4] outline-none placeholder:text-[#8b8b8b]" /> {query ? ( <IconButton label={text.clearSearch} onClick={() => setQuery("")}> <X aria-hidden className="size-3.5" /> </IconButton> ) : null} </div> <motion.div layoutScroll className="min-h-0 flex-1 overflow-y-auto px-1.5 pt-1 pb-14 [scrollbar-color:#424242_transparent] [scrollbar-width:thin]" > {/* Filtering is typed, so it never animates: a new query remounts the list in place. */} <div key={needle} className="relative"> <AnimatePresence mode="popLayout" initial={false}> {groups.flatMap((group) => [ <Presence key={`group:${group.label}`} layout={layout} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={exit} transition={enter} className="px-2 pt-3 pb-1 first:pt-2" > <h3 className="m-0 text-[12px] font-normal text-[#8b8b8b]">{group.label}</h3> </Presence>, ...group.items.map((chat) => { const active = chat.id === currentActive; const editing = chat.id === editingId; const running = chat.status === "running"; return ( <Presence key={chat.id} layout={layout} initial={reduced ? { opacity: 0 } : { opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} exit={exit} transition={enter} className="group/row relative" > {editing ? ( <input autoFocus defaultValue={chat.title} aria-label={text.rename} onFocus={(event) => event.currentTarget.select()} onBlur={(event) => finishRename(chat.id, event.currentTarget.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); finishRename(chat.id, event.currentTarget.value); } else if (event.key === "Escape") { event.preventDefault(); finishRename(chat.id, null); } }} className="h-[30px] w-full rounded-[5px] border-0 bg-[#181818] pr-2 pl-[30px] text-[13px] text-[#e4e4e4] ring-1 ring-[#0078d4] outline-none ring-inset" /> ) : ( <> <button ref={(el) => { if (el) rowButtons.current.set(chat.id, el); else rowButtons.current.delete(chat.id); }} type="button" title={chat.title} aria-current={active ? "page" : undefined} data-active={active ? "" : undefined} onClick={(event) => pick(chat.id, event.detail === 0)} onKeyDown={(event) => onRowKeyDown(event, chat.id)} className={cn( "flex h-[30px] w-full cursor-pointer items-center gap-2 rounded-[5px] border-0 bg-transparent px-2 text-left text-[13px] text-[#cccccc]", "group-hover/row:bg-[#2a2a2a] group-focus-within/row:bg-[#2a2a2a]", "data-[active]:bg-[#2a2a2a] data-[active]:text-[#f0f0f0]", FOCUS, )} > {running ? ( <LoaderCircle aria-label={text.running} className="size-[15px] shrink-0 animate-spin text-[#9d9d9d] [animation-duration:900ms] motion-reduce:animate-none" strokeWidth={1.75} /> ) : ( <CircleCheck aria-label={text.done} className="size-[15px] shrink-0 text-[#9d9d9d]" strokeWidth={1.75} /> )} <span className="min-w-0 flex-1 truncate">{chat.title}</span> </button> <div className={cn( "pointer-events-none absolute inset-y-0 right-0 flex items-center gap-0.5 rounded-r-[5px] pr-1 pl-6 opacity-0", "bg-gradient-to-l from-[#2a2a2a] from-[62%] to-transparent", "group-hover/row:pointer-events-auto group-hover/row:opacity-100", "group-focus-within/row:pointer-events-auto group-focus-within/row:opacity-100", )} > <IconButton label={`${text.rename}: ${chat.title}`} onClick={() => { renameDone.current = null; setEditingId(chat.id); }} > <Pencil aria-hidden className="size-3.5" /> </IconButton> <IconButton label={`${text.delete}: ${chat.title}`} tone="danger" onClick={() => remove(chat.id)} > <Trash2 aria-hidden className="size-3.5" /> </IconButton> </div> </> )} </Presence> ); }), ])} </AnimatePresence> {visible.length === 0 ? ( <p className="m-0 px-2 py-8 text-center text-[13px] text-[#8b8b8b]"> {needle ? `${text.noMatches} “${query.trim()}”` : text.empty} </p> ) : null} </div> </motion.div> <AnimatePresence> {pending ? ( <Presence key="undo" initial={reduced ? { opacity: 0 } : { opacity: 0, y: "100%" }} animate={{ opacity: 1, y: 0 }} exit={ reduced ? { opacity: 0, transition: { duration: 0.15 } } : { opacity: 0, y: "100%", transition: { duration: 0.15, ease: EASE_OUT } } } transition={reduced ? { duration: 0.15 } : { duration: 0.2, ease: EASE_OUT }} onPointerEnter={() => setUndoHeld(true)} onPointerLeave={() => setUndoHeld(false)} onFocus={() => setUndoHeld(true)} onBlur={() => setUndoHeld(false)} className="absolute inset-x-2 bottom-2 flex h-10 items-center justify-between gap-2 rounded-lg border border-[#3a3a3a] bg-[#2b2b2b] pr-1 pl-3 text-[13px] text-[#e4e4e4] shadow-[0_10px_24px_-10px_rgba(0,0,0,0.8)]" > <span className="min-w-0 truncate tabular-nums"> {pending.entries.length === 1 ? text.deleted : `${pending.entries.length} ${text.deletedMany}`} </span> <button type="button" onClick={undo} className={cn( "h-8 shrink-0 cursor-pointer rounded-[5px] border-0 bg-transparent px-2.5 text-[13px] font-medium text-[#4daafc] hover:bg-white/[0.08]", PRESS, FOCUS, )} > {text.undo} </button> </Presence> ) : null} </AnimatePresence> </motion.nav> ) : null} </AnimatePresence> <p className="sr-only" aria-live="polite"> {announce} </p> </div> ); },); ChatHistorySidebar.displayName = "ChatHistorySidebar";AI チャット履歴サイドバー
Cursor のエージェント履歴のような、黒いパネルの AI チャット履歴です。上の細いバーには+と時計のボタンが並び、時計を押すと同じ幅の履歴パネルが下に開きます。パネルは時計のボタンから広がるように開き、外を押すか Esc で閉じます。会話を選んでもパネルは閉じます。パネルの上には「Search Agents...」の検索欄があり、会話は Today・Yesterday・Older の見出しごとに並びます。各行の頭には完了のチェックが付き、実行中の会話は回るアイコンになります。行にホバーすると出る鉛筆とゴミ箱で、名前の変更と削除ができます。消した行はその場で抜け、下の行がすぐに詰まり、下から出る Undo で戻せます。矢印キーで検索欄から行へ移れます。会話の一覧を差し替えて、AI アプリやエディタの履歴メニューにそのまま置けます。
Verified Technical Spec
- アニメーション
- Framer Motion
- Reduced motion
- 確認済み
- キーボードフォーカス
- 確認済み
- 対応環境
- Tailwind CSS v3.4 + v4 · React 19 / Next.js 15 App Router + Vite / Remix 対応
含まれるもの
- ソースを Cursor / Claude に渡してエージェントに組み込める
- React · TypeScript · Tailwind CSS · Motion · Lucide の完成 UI
依存パッケージ
- React 19.0.0
- Typescript 5.7.2
- Tailwindcss 3.4.16
- Lucide-react 1.23.0
- Motion 12.42.2
技術スタック
- React
- TypeScript
- Tailwind CSS
- Motion
- Lucide
バージョン 1.0.0





