"use client"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { AlertTriangle, Bookmark, Download, Loader2, Pencil, Plus, Search, Trash2, X, } from "lucide-react"; import { useTranslation } from "react-i18next"; import Tooltip from "@/shared/ui/Tooltip"; import { ConfirmDialog } from "@/components/ui/ConfirmDialog"; import { FeaturePage, PageHeader, pageActionClass, } from "@/components/layout/FeaturePage"; import { PageBarSlot } from "@/components/layout/PageChrome"; import { InstanceCrumb, type CrumbItem, } from "@/components/layout/LocationCrumbs"; import "@/components/notebook/favorites.css"; import NotebookRecordRow from "@/components/notebook/NotebookRecordRow"; import PickerShell from "@/components/common/PickerShell"; import { FolderGlyph } from "@/components/reading/library/FolderGlyph"; import { FavoriteKindIcon, favoriteLabel, } from "@/components/notebook/favorite-kinds"; import { favoriteKind } from "@/lib/favorite-content"; import { RecordTime } from "@/components/sidebar/RecordList"; import { useNotebookLibrary } from "@/components/notebook/useNotebookLibrary"; import { notify } from "@/lib/notifications"; import { exportNotebookMarkdown, getNotebook, listNotebooks, locateFavoriteRecord, type NotebookRecordItem, type NotebookSummary, } from "@/lib/notebook-api"; import { notebookRoute } from "@/lib/resource-routes"; // Indigo first: it is what every notebook was created with before colours // could be picked. The rest follow the folder palette in globals.css. const SWATCHES = [ "#6366F1", "#4F86F7", "#1FB5A8", "#43B05C", "#EAA221", "#F07B3F", "#E8577A", "#8E6CF0", "#6B7A90", ]; const DEFAULT_COLOR = SWATCHES[0]; interface NotebookConsoleProps { /** Notebook to open on arrival from `/notebooks/`; none is the list. */ initialNotebookId?: string | null; initialRecordId?: string | null; /** Arrive with the new-notebook form open (`/notebooks?create=1`). */ startCreating?: boolean; } /** * 收藏夹, as every feature reads: `/notebooks` lists the notebooks, and * `/notebooks/` is one of them — 「收藏夹 / its name」 in the page bar, * where the name switches to the others. Notebooks are created and edited * from the list; the open one can be edited, exported or deleted from its * own header. */ export default function NotebookConsole({ initialNotebookId, initialRecordId = null, startCreating = false, }: NotebookConsoleProps) { const { t } = useTranslation(); const router = useRouter(); const library = useNotebookLibrary(initialNotebookId); const [banner, setBanner] = useState(null); const fail = useCallback( (err: unknown) => setBanner(err instanceof Error ? err.message : String(err)), [], ); if (library.loading) { return (
); } const bannerNode = banner ? (
{banner}
) : null; if (library.error) { return ( void library.reload()} className="rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)]" > {t("Retry")} } /> ); } if (!initialNotebookId) { return ( router.push(notebookRoute(id))} /> ); } return ( ); } type Library = ReturnType; // ── The list ─────────────────────────────────────────────────────────── /** A peek inside each collection: its newest items and what kinds it holds. * Collections are few and small, so one detail read each is cheap; a failed * read just leaves that card without its peek. */ function useCollectionPeeks(notebooks: NotebookSummary[]) { const [peeks, setPeeks] = useState>({}); const signature = notebooks .map( (notebook) => `${notebook.id}:${notebook.record_count ?? 0}:${notebook.updated_at ?? 0}`, ) .join("|"); useEffect(() => { let cancelled = false; const readable = notebooks.filter( (notebook) => !notebook.unreadable && (notebook.record_count ?? 0) > 0, ); void Promise.all( readable.map((notebook) => getNotebook(notebook.id) .then((detail) => [notebook.id, detail.records] as const) .catch(() => [notebook.id, [] as NotebookRecordItem[]] as const), ), ).then((rows) => { if (!cancelled) setPeeks(Object.fromEntries(rows)); }); return () => { cancelled = true; }; // Re-read when a collection's contents change, not on every render. // eslint-disable-next-line react-hooks/exhaustive-deps }, [signature]); return peeks; } function NotebookList({ library, startCreating, banner, onError, onOpen, }: { library: Library; startCreating: boolean; banner: React.ReactNode; onError: (err: unknown) => void; onOpen: (id: string) => void; }) { const { t } = useTranslation(); const router = useRouter(); const { notebooks } = library; const [query, setQuery] = useState(""); const [creating, setCreating] = useState(startCreating); const [editingId, setEditingId] = useState(null); const peeks = useCollectionPeeks(notebooks); const editing = notebooks.find((notebook) => notebook.id === editingId); const visible = useMemo(() => { const needle = query.trim().toLowerCase(); const sorted = [...notebooks].sort( (a, b) => (b.updated_at ?? 0) - (a.updated_at ?? 0), ); if (!needle) return sorted; return sorted.filter((notebook) => [ notebook.name, notebook.description ?? "", ...(peeks[notebook.id] ?? []).map((record) => record.title), ] .join(" ") .toLowerCase() .includes(needle), ); }, [notebooks, peeks, query]); const total = notebooks.reduce( (sum, notebook) => sum + (notebook.record_count ?? 0), 0, ); return ( setCreating(true)} aria-expanded={creating} className={pageActionClass("primary")} > {t("New notebook")} } /> {banner} {notebooks.length > 0 && (
{t("{{folders}} folders · {{items}} items", { folders: notebooks.length, items: total, })}
)} {creating && ( setCreating(false)} onSubmit={async ({ name, description, color }) => { try { const createdId = await library.create(name, description, color); setCreating(false); if (createdId) router.push(notebookRoute(createdId)); } catch (err) { onError(err); } }} /> )} {editing && ( setEditingId(null)} onSubmit={async (changes) => { try { await library.rename(editing.id, changes); setEditingId(null); } catch (err) { onError(err); } }} /> )}
); } /** A collection as a folder of files: what is inside, newest first. */ function CollectionCard({ notebook, records, onOpen, onEdit, }: { notebook: NotebookSummary; records?: NotebookRecordItem[]; onOpen: () => void; onEdit: () => void; }) { const { t } = useTranslation(); const count = notebook.record_count ?? records?.length ?? 0; const newest = [...(records ?? [])] .sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)) .slice(0, 3); const tone = notebook.color || DEFAULT_COLOR; return (
  • ); } // ── One notebook ─────────────────────────────────────────────────────── function NotebookDetail({ library, notebookId, initialRecordId, banner, onError, }: { library: Library; notebookId: string; initialRecordId: string | null; banner: React.ReactNode; onError: (err: unknown) => void; }) { const { t } = useTranslation(); const router = useRouter(); const { notebooks, selected, selectedId } = library; const [recordQuery, setRecordQuery] = useState(""); const [recordKind, setRecordKind] = useState(""); const [recordError, setRecordError] = useState(null); const [editing, setEditing] = useState(false); const [confirmingDelete, setConfirmingDelete] = useState(false); const [deleting, setDeleting] = useState(false); const recordRef = useRef(null); const handledRecordRouteRef = useRef(null); const expandedRecordId = initialRecordId; const summary = notebooks.find((notebook) => notebook.id === notebookId); const name = selected?.name ?? summary?.name ?? ""; const color = selected?.color ?? summary?.color ?? DEFAULT_COLOR; // Resolve moved favorites only after the requested collection has loaded. // Never silently open an unrelated record when a saved source is gone. useEffect(() => { let cancelled = false; setRecordError(null); if (!initialRecordId) { handledRecordRouteRef.current = null; return; } if ( library.loading || library.detailLoading || selectedId !== notebookId ) return; if ( selected?.id === notebookId && selected.records.some((record) => record.id === initialRecordId) ) { const route = notebookRoute(notebookId, initialRecordId); // Locate incoming source links once. In-place toggles mark their route // as handled so neither opening nor refreshing a record moves the page. if (handledRecordRouteRef.current !== route && recordRef.current) { handledRecordRouteRef.current = route; recordRef.current.scrollIntoView({ block: "start" }); } return; } if (selected && selected.id !== notebookId) return; if (!selected && !library.detailError) return; void locateFavoriteRecord(initialRecordId, notebookId) .then((collectionId) => { if (cancelled) return; if (collectionId && collectionId !== notebookId) { router.replace(notebookRoute(collectionId, initialRecordId)); } else { setRecordError(t("This favorite is no longer available.")); } }) .catch(() => { if (!cancelled) setRecordError( t("Could not locate this favorite. Try reopening the source link."), ); }); return () => { cancelled = true; }; }, [ initialRecordId, notebookId, library.loading, library.detailLoading, library.detailError, selected, selectedId, router, t, ]); const kinds = useMemo( () => [ ...new Set( (selected?.records ?? []).map((record) => favoriteKind(record.type, record.metadata), ), ), ], [selected], ); const visibleRecords = useMemo(() => { const records = selected?.records ?? []; const needle = recordQuery.trim().toLowerCase(); if (!needle && !recordKind) return records; return records.filter( (record) => record.id === initialRecordId || ((!recordKind || favoriteKind(record.type, record.metadata) === recordKind) && `${record.title} ${record.summary ?? ""} ${record.output ?? ""}` .toLowerCase() .includes(needle)), ); }, [selected, recordQuery, recordKind, initialRecordId]); const loadNotebooks = useCallback( async (): Promise => (await listNotebooks()).map((notebook) => ({ id: notebook.id, label: notebook.name, href: notebookRoute(notebook.id), color: notebook.color || DEFAULT_COLOR, detail: String(notebook.record_count ?? 0), })), [], ); const handleDelete = useCallback(async () => { setDeleting(true); try { await library.remove(notebookId); router.replace(notebookRoute()); notify(t('Deleted "{{name}}"', { name }), { tone: "success" }); setConfirmingDelete(false); } catch (err) { onError(err); } finally { setDeleting(false); } }, [library, name, notebookId, onError, router, t]); const handleExport = useCallback(async () => { try { const markdown = await exportNotebookMarkdown(notebookId); const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8", }); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `${name || notebookId}.md`; anchor.click(); URL.revokeObjectURL(url); notify(t("Notebook exported"), { tone: "success" }); } catch (err) { onError(err); } }, [name, notebookId, onError, t]); const openSession = useCallback( (sessionId: string) => router.push(`/chat/${encodeURIComponent(sessionId)}`), [router], ); const missing = !selected && !library.detailLoading; return ( setEditing(true) : undefined} /> {banner} {recordError && (

    {recordError}

    )} {missing ? ( ) : ( <> {name} } description={selected?.description || undefined} meta={ {t("{{count}} items", { count: selected?.records.length ?? 0 })} } action={
    setEditing(true)} /> void handleExport()} /> setConfirmingDelete(true)} />
    } /> {editing && selected && ( setEditing(false)} onSubmit={async (changes) => { try { await library.rename(notebookId, changes); setEditing(false); } catch (err) { onError(err); } }} /> )} {(selected?.records.length ?? 0) > 0 && (
    {kinds.length > 1 && (
    {kinds.map((value) => ( ))}
    )}
    )} {library.detailLoading ? (
    ) : visibleRecords.length ? (
    {visibleRecords.map((record) => (
    { const route = notebookRoute( notebookId, expandedRecordId === record.id ? null : record.id, ); handledRecordRouteRef.current = route; router.replace(route, { scroll: false }); }} onEdit={library.editRecord} onDelete={library.removeRecord} onRelocate={library.relocateRecord} onOpenSession={openSession} />
    ))}
    ) : ( )} )} void handleDelete()} onCancel={() => setConfirmingDelete(false)} >

    {(selected?.record_count ?? 0) > 0 ? t( '"{{name}}" and its {{count}} records will be deleted. This cannot be undone.', { name, count: selected?.record_count ?? 0 }, ) : t('"{{name}}" will be deleted.', { name })}

    ); } // ── Pieces ───────────────────────────────────────────────────────────── /** Create or edit a notebook: name, description and folder colour, with the * folder drawn as it will appear on the list. */ function NotebookMetaDialog({ label, submitLabel, initial, onCancel, onSubmit, }: { label: string; submitLabel: string; initial?: NotebookSummary; onCancel: () => void; onSubmit: (changes: { name: string; description: string; color: string; }) => void | Promise; }) { const { t } = useTranslation(); const [name, setName] = useState(initial?.name ?? ""); const [description, setDescription] = useState(initial?.description ?? ""); const [color, setColor] = useState(initial?.color ?? DEFAULT_COLOR); const [busy, setBusy] = useState(false); const swatches = SWATCHES.includes(color) ? SWATCHES : [color, ...SWATCHES]; return (
    { event.preventDefault(); if (!name.trim() || busy) return; setBusy(true); void Promise.resolve( onSubmit({ name: name.trim(), description: description.trim(), color, }), ).finally(() => setBusy(false)); }} >

    {label}

    {t("Colour")}
    {swatches.map((swatch) => (
    ); } function HeaderAction({ label, icon: Icon, onClick, tone = "default", }: { label: string; icon: typeof Pencil; onClick: () => void; tone?: "default" | "danger"; }) { return ( ); } function ConsoleNotice({ tone, title, detail, action, }: { tone: "empty" | "error"; title: string; detail: string; action?: React.ReactNode; }) { const Icon = tone === "error" ? AlertTriangle : Bookmark; return (

    {title}

    {detail}

    {action}
    ); }