"use client"; import type { Message } from "@langchain/langgraph-sdk"; import { ChevronsRightIcon, ListIcon } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { Sheet, SheetContent, SheetHeader, SheetTitle, } from "@/components/ui/sheet"; import { extractContentFromMessage, stripArtifactTag, stripUploadedFilesTag, } from "@/core/messages/utils"; import { cn } from "@/lib/utils"; import { Tooltip } from "./tooltip"; /** Width of the expanded floating panel, in px. */ const PANEL_WIDTH = 300; /** Minimum side gutter (beyond the panel itself) required to float the panel. */ const PANEL_GUTTER_MARGIN = 24; /** Max characters kept in a question summary card. */ const SUMMARY_MAX_LENGTH = 80; /** Questions needed before the navigator shows up at all. */ const MIN_QUESTIONS = 2; const COLLAPSE_STORAGE_KEY = "deerflow.question-navigator.collapsed"; /** * Stable DOM anchor id for a message. Prefers the server-side message id and * falls back to the render index so messages without ids still get a target * (requirement: `message-${index}` style fallback). */ export function getQuestionAnchorId( message: Pick, index: number, ): string { return `message-${message.id ?? index}`; } /** * Turn the raw markdown of a user question into a short plain-text summary: * strips upload/artifact/page-context envelopes and common Markdown syntax, * collapses whitespace, and truncates with an ellipsis. */ function summarizeQuestion(raw: string): string { let text = stripArtifactTag(stripUploadedFilesTag(raw)); text = text .replace(/[\s\S]*?<\/page_context>/gi, " ") .replace(/```[\s\S]*?(```|$)/g, " ") .replace(/!\[[^\]]*\]\([^)]*\)/g, " ") .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") .replace(/`([^`]*)`/g, "$1") .replace(/^#{1,6}\s+/gm, "") .replace(/^\s*>\s?/gm, "") .replace(/^\s*[-*+]\s+/gm, "") .replace(/^\s*\d+\.\s+/gm, "") .replace(/(\*\*|__|~~)/g, "") .replace(/\s+/g, " ") .trim(); if (text.length > SUMMARY_MAX_LENGTH) { return `${text.slice(0, SUMMARY_MAX_LENGTH)}…`; } return text; } type QuestionItem = { anchorId: string; summary: string; }; /** Walk up from a message anchor to the element that actually scrolls. */ function findScrollParent(el: HTMLElement | null): HTMLElement | null { let node = el?.parentElement ?? null; while (node) { const overflowY = window.getComputedStyle(node).overflowY; if ( (overflowY === "auto" || overflowY === "scroll") && node.scrollHeight > node.clientHeight ) { return node; } node = node.parentElement; } return null; } function readCollapsedPreference(): boolean { if (typeof window === "undefined") return false; try { return window.localStorage.getItem(COLLAPSE_STORAGE_KEY) === "1"; } catch { return false; } } /** * ChatGPT-style question index floating at the right edge of the conversation * column. Reads questions straight from the live `messages` array (no global * state copy), so it stays in sync with streaming, history switches and new * turns for free. * * Layout contract: render inside a `relative` ancestor that spans the chat * content area, and pass the inset via `className` (e.g. `top-16 bottom-48 * left-0 right-0`). The component measures its own width: when the side gutter * next to the centered message column is wide enough it floats an expandable * panel there, vertically centered in the available chat area; on narrower * viewports it degrades to a small pill button that opens a right-side drawer, * so it never covers the chat body or input box. */ export function QuestionNavigator({ messages, className, contentMaxWidth = 1024, }: { messages: Message[]; className?: string; /** Max width (px) of the centered message column, used to size the gutter. */ contentMaxWidth?: number; }) { const rootRef = useRef(null); const [panelFits, setPanelFits] = useState(false); const [collapsed, setCollapsed] = useState(readCollapsedPreference); const [sheetOpen, setSheetOpen] = useState(false); const [activeId, setActiveId] = useState(null); const questions = useMemo(() => { const items: QuestionItem[] = []; messages.forEach((message, index) => { if (message.type !== "human") return; const summary = summarizeQuestion(extractContentFromMessage(message)); if (!summary) return; items.push({ anchorId: getQuestionAnchorId(message, index), summary }); }); return items; }, [messages]); const visible = questions.length >= MIN_QUESTIONS; // Decide between floating panel and drawer mode from the actual gutter width // next to the centered message column — not from the browser viewport — so // opening the artifact preview or the sidebar reflows the mode correctly. useEffect(() => { if (!visible) return; const root = rootRef.current; if (!root) return; const update = () => { const gutter = (root.clientWidth - contentMaxWidth) / 2; setPanelFits(gutter >= PANEL_WIDTH + PANEL_GUTTER_MARGIN); }; update(); const observer = new ResizeObserver(update); observer.observe(root); return () => observer.disconnect(); }, [visible, contentMaxWidth]); // Highlight the question nearest the top of the chat viewport. A plain // rAF-throttled scroll listener over a handful of anchors is cheaper and // more predictable here than juggling IntersectionObserver thresholds. useEffect(() => { if (!visible) { setActiveId(null); return; } const firstAnchor = document.getElementById(questions[0]!.anchorId); const scroller = findScrollParent(firstAnchor); if (!scroller) return; let raf = 0; const update = () => { raf = 0; const viewportTop = scroller.getBoundingClientRect().top; let current = questions[0]!.anchorId; for (const question of questions) { const el = document.getElementById(question.anchorId); if (!el) continue; if (el.getBoundingClientRect().top - viewportTop <= 140) { current = question.anchorId; } else { break; } } setActiveId(current); }; const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); }; update(); scroller.addEventListener("scroll", onScroll, { passive: true }); return () => { scroller.removeEventListener("scroll", onScroll); if (raf) cancelAnimationFrame(raf); }; }, [visible, questions]); const scrollToQuestion = useCallback((anchorId: string) => { document .getElementById(anchorId) ?.scrollIntoView({ behavior: "smooth", block: "start" }); setActiveId(anchorId); }, []); const toggleCollapsed = useCallback(() => { setCollapsed((prev) => { const next = !prev; try { window.localStorage.setItem(COLLAPSE_STORAGE_KEY, next ? "1" : "0"); } catch { // localStorage unavailable (private mode) — keep in-memory state only. } return next; }); }, []); if (!visible) return null; const pillButton = (label: string, onClick: () => void) => ( ); return (
{panelFits ? ( collapsed ? ( pillButton("展开问题导航", toggleCollapsed) ) : (
本轮问题 {questions.length}
) ) : ( <> {pillButton("打开问题导航", () => setSheetOpen(true))} 本轮问题({questions.length}) { setSheetOpen(false); scrollToQuestion(anchorId); }} className="min-h-0 flex-1" /> )}
); } function QuestionCardList({ questions, activeId, onSelect, className, }: { questions: QuestionItem[]; activeId: string | null; onSelect: (anchorId: string) => void; className?: string; }) { const itemRefs = useRef(new Map()); // Keep the active card visible as the chat scrolls. `block: "nearest"` only // nudges this inner list — the card is already inside the on-screen panel, // so no outer container moves. useEffect(() => { if (!activeId) return; itemRefs.current.get(activeId)?.scrollIntoView({ block: "nearest" }); }, [activeId]); return ( ); }