import { useCallback, useEffect, useRef, useState } from "react"; import { ArrowDown } from "lucide-react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { Button } from "@/components/ui/button"; import type { CanvasArtifactText } from "../../types/artifact"; import { TiptapEditor } from "../../editor/TiptapEditor"; import { useWritingEditor } from "../../hooks/useWritingEditor"; import { useWritingRewrite } from "../../hooks/useWritingRewrite"; import { WritingToolbar } from "./WritingToolbar"; import { WritingBubbleMenu } from "./WritingBubbleMenu"; import { WritingParagraphMenu } from "./WritingParagraphMenu"; import { WritingAiMenu } from "./WritingAiMenu"; import { WritingRewritePreview } from "./WritingRewritePreview"; import { DraftOutlineSidebar } from "./DraftOutlineSidebar"; import { useCanvasGraphContext } from "../../contexts/CanvasGraphContext"; import { useCanvasUIContext } from "../../contexts/CanvasUIContext"; import { applyReplace, applyInsert } from "../../utils/apply-rewrite"; import type { RewriteAction, RewriteTone } from "../../api/rewrite"; interface TextArtifactRendererProps { content: CanvasArtifactText; isStreaming?: boolean; /** 完成态只读(如历史回看):保留目录 + 排版,禁用编辑与 AI 润色 */ readOnly?: boolean; /** 历史回看可编辑场景:提供后工具栏出现「保存」按钮,把修改持久化回会话 */ onSaveDraft?: (markdown: string, title?: string) => Promise; } interface PanelPos { x: number; y: number; } /** Phase of the AI rewrite flow */ type FlowPhase = "idle" | "menu" | "preview"; interface LastAction { action: RewriteAction; tone?: RewriteTone; customInstruction?: string; referenceText?: string; } export function TextArtifactRenderer({ content, isStreaming, readOnly = false, onSaveDraft }: TextArtifactRendererProps) { const { artifact, setArtifact } = useCanvasGraphContext(); const { writingSelection } = useCanvasUIContext(); const scrollRef = useRef(null); const [showScrollBtn, setShowScrollBtn] = useState(false); const autoScrollRef = useRef(true); // 编辑模式文档滚动容器:用 state 而非 ref,使目录栏在容器挂载后能拿到它 const [docScrollEl, setDocScrollEl] = useState(null); // ── AI rewrite flow state ────────────────────────────────────────────── const [phase, setPhase] = useState("idle"); const [panelPos, setPanelPos] = useState({ x: 0, y: 0 }); const lastActionRef = useRef(null); const handleEditorChange = useCallback( (markdown: string) => { if (!artifact) return; setArtifact({ ...artifact, contents: artifact.contents.map((c) => c.index === artifact.currentIndex && c.type === "text" ? { ...c, fullMarkdown: markdown } : c, ), }); }, [artifact, setArtifact], ); const editor = useWritingEditor({ markdown: content.fullMarkdown, onChange: handleEditorChange, editable: !isStreaming && !readOnly, placeholder: "开始写作…", }); const { status, result, thinking, error, rewrite, rewriteFollowUp, reset } = useWritingRewrite(editor); // ── Streaming auto-scroll ────────────────────────────────────────────── useEffect(() => { if (!isStreaming) { autoScrollRef.current = true; setShowScrollBtn(false); return; } if (!autoScrollRef.current) return; const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [isStreaming, content.fullMarkdown]); const handleScroll = useCallback(() => { if (!isStreaming) return; const el = scrollRef.current; if (!el) return; const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40; autoScrollRef.current = atBottom; setShowScrollBtn(!atBottom); }, [isStreaming]); const handleScrollToBottom = useCallback(() => { const el = scrollRef.current; if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); autoScrollRef.current = true; setShowScrollBtn(false); }, []); // ── AI rewrite flow handlers ─────────────────────────────────────────── /** Compute anchor position from current DOM selection */ const computePos = useCallback((): PanelPos => { const sel = window.getSelection(); if (sel && sel.rangeCount > 0) { const rect = sel.getRangeAt(0).getBoundingClientRect(); if (rect.width || rect.height) { return { x: rect.left, y: rect.bottom + 6 }; } } return { x: window.innerWidth / 2 - 90, y: window.innerHeight / 2 }; }, []); const openAiMenu = useCallback(() => { reset(); setPanelPos(computePos()); setPhase("menu"); }, [reset, computePos]); const closeAll = useCallback(() => { editor?.commands.clearAiHighlight(); setPhase("idle"); reset(); }, [reset, editor]); const handleAction = useCallback( (action: RewriteAction, tone?: RewriteTone, customInstruction?: string, referenceText?: string) => { lastActionRef.current = { action, tone, customInstruction, referenceText }; rewrite(action, tone, customInstruction, referenceText); setPhase("preview"); }, [rewrite], ); const handleRetry = useCallback(() => { if (!lastActionRef.current) return; const { action, tone, customInstruction, referenceText } = lastActionRef.current; rewrite(action, tone, customInstruction, referenceText); }, [rewrite]); const handleFollowUp = useCallback( (instruction: string) => { if (!lastActionRef.current) return; const { action, tone, referenceText } = lastActionRef.current; rewriteFollowUp(instruction, action, tone, referenceText); }, [rewriteFollowUp], ); const handleReplace = useCallback(() => { if (!editor || !writingSelection || !result) return; applyReplace(editor, writingSelection, result); closeAll(); }, [editor, writingSelection, result, closeAll]); const handleInsert = useCallback(() => { if (!editor || !writingSelection || !result) return; applyInsert(editor, writingSelection, result); closeAll(); }, [editor, writingSelection, result, closeAll]); // ── Empty state ──────────────────────────────────────────────────────── if (!content.fullMarkdown && !isStreaming) { return (

空白文档,发送消息让 AI 填充内容

); } // ── Streaming mode ──────────────────────────────────────────────────── if (isStreaming) { return (
(

{children}

), h2: ({ children }) => (

{children}

), h3: ({ children }) => (

{children}

), p: ({ children }) => (

{children}

), ul: ({ children }) => (
    {children}
), ol: ({ children }) => (
    {children}
), li: ({ children }) =>
  • {children}
  • , blockquote: ({ children }) => (
    {children}
    ), pre: ({ children }) => (
                        {children}
                      
    ), code: ({ className, children }) => { const isBlock = Boolean(className?.startsWith("language-")); return isBlock ? ( {children} ) : ( {children} ); }, }} > {content.fullMarkdown}
    {showScrollBtn && (
    )}
    ); } // ── Edit mode(写作完成态 / 历史回看只读)──────────────────────────────── return (
    {/* 左侧目录栏(仿豆包):文档标题层级导航 */} {/* 文档滚动区 */}
    {editor && !readOnly && ( <> )}
    {/* Phase: AI action menu */} {!readOnly && phase === "menu" && ( )} {/* Phase: result preview */} {!readOnly && phase === "preview" && ( )}
    ); }