import { forwardRef, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { CSSProperties, ClipboardEvent, KeyboardEvent, MouseEvent, PointerEvent, TextareaHTMLAttributes } from "react"; import { createPortal } from "react-dom"; import { FileText, Image as ImageIcon, Music2, Pencil, Sparkles, UserRound, Video } from "lucide-react"; import { canvasThemes } from "@/lib/canvas-theme"; import { useThemeStore } from "@/stores/use-theme-store"; import { canvasResourceMentionToken, type CanvasResourceReference } from "@/lib/canvas/canvas-resource-references"; import { CanvasNodeType } from "@/types/canvas"; type MentionState = { start: number; query: string; }; type EditableSelection = { start: number; end: number; }; type MentionTextPart = | { type: "text"; text: string; } | { type: "mention"; token: string; reference: CanvasResourceReference; }; type Props = Omit, "onChange" | "value"> & { value: string; references: CanvasResourceReference[]; onChange: (value: string) => void; onSubmit?: () => void; containerClassName?: string; highlightLabels?: boolean; onContentSizeChange?: (height: number) => void; }; export const CanvasResourceMentionTextarea = forwardRef(function CanvasResourceMentionTextarea( { value, references, onChange, onSubmit, onKeyDown, className, containerClassName, style, highlightLabels = true, onContentSizeChange, ...props }, forwardedRef, ) { const theme = canvasThemes[useThemeStore((state) => state.theme)]; const containerRef = useRef(null); const textareaRef = useRef(null); const editorRef = useRef(null); const composingRef = useRef(false); const pendingSelectionRef = useRef(null); const lastRenderedValueRef = useRef(""); const [mention, setMention] = useState(null); const [activeIndex, setActiveIndex] = useState(0); const candidates = useMemo(() => { if (!mention) return []; const query = mention.query.trim().toLowerCase(); const activeItems = references.filter((item) => item.active); if (!query) return activeItems; return activeItems.filter((item) => `${item.label} ${item.title} ${item.kind} ${item.text || ""}`.toLowerCase().includes(query)); }, [mention, references]); const activeReferences = useMemo(() => (highlightLabels ? references.filter((item) => item.active) : []), [highlightLabels, references]); const useRichEditor = Boolean(activeReferences.length); const reportContentSize = useCallback((element: HTMLElement | null) => { if (!element || !onContentSizeChange) return; const previousHeight = element.style.height; element.style.height = "0px"; const height = element.scrollHeight; element.style.height = previousHeight; onContentSizeChange(height); }, [onContentSizeChange]); useLayoutEffect(() => { if (!useRichEditor) return; const editor = editorRef.current; if (!editor || composingRef.current) return; const isFocused = document.activeElement === editor; const currentValue = serializeEditableValue(editor); if (currentValue === value && lastRenderedValueRef.current === value) { pendingSelectionRef.current = null; return; } const selection = pendingSelectionRef.current ?? (isFocused ? getEditableSelection(editor)?.start ?? null : null); renderEditableContent(editor, value, activeReferences); lastRenderedValueRef.current = value; if (isFocused && selection !== null) setEditableSelection(editor, selection); pendingSelectionRef.current = null; reportContentSize(editor); }, [activeReferences, reportContentSize, useRichEditor, value]); useLayoutEffect(() => { const element = useRichEditor ? editorRef.current : textareaRef.current; const container = containerRef.current; if (!element || !container || !onContentSizeChange) return; reportContentSize(element); const observer = new ResizeObserver(() => reportContentSize(element)); observer.observe(container); return () => observer.disconnect(); }, [onContentSizeChange, reportContentSize, useRichEditor]); const focusEditor = (selectionStart?: number) => { requestAnimationFrame(() => { if (useRichEditor) { const editor = editorRef.current; if (!editor) return; editor.focus(); if (typeof selectionStart === "number") setEditableSelection(editor, selectionStart); return; } textareaRef.current?.focus(); if (typeof selectionStart === "number") textareaRef.current?.setSelectionRange(selectionStart, selectionStart); }); }; const updateValue = (next: string, selectionStart?: number) => { if (typeof selectionStart === "number") pendingSelectionRef.current = selectionStart; onChange(next); if (typeof selectionStart === "number") focusEditor(selectionStart); }; const closeMention = () => { setMention(null); setActiveIndex(0); }; const syncMention = (nextValue: string, cursor: number) => { const prefix = nextValue.slice(0, cursor); const match = /@([^\s@,.;:!?,。;:!?、)\]}】)]*)$/.exec(prefix); if (!match || !references.some((item) => item.active)) { closeMention(); return; } const nextMention = { start: match.index, query: match[1] }; const isSameMention = mention?.start === nextMention.start && mention.query === nextMention.query; if (!isSameMention) { setMention(nextMention); setActiveIndex(0); } }; const insertReference = (reference: CanvasResourceReference) => { if (!mention) return; const selection = useRichEditor ? getEditableSelection(editorRef.current) : null; const end = selection?.end ?? textareaRef.current?.selectionStart ?? value.length; const insertText = `${canvasResourceMentionToken(reference)} `; const next = `${value.slice(0, mention.start)}${insertText}${value.slice(end)}`; closeMention(); updateValue(next, mention.start + insertText.length); }; const replaceEditableSelection = (insertText: string) => { const currentValue = editorRef.current ? serializeEditableValue(editorRef.current) : value; const selection = getEditableSelection(editorRef.current) || { start: currentValue.length, end: currentValue.length }; const next = `${currentValue.slice(0, selection.start)}${insertText}${currentValue.slice(selection.end)}`; const cursor = selection.start + insertText.length; updateValue(next, cursor); syncMention(next, cursor); }; const syncEditableValue = () => { if (composingRef.current) return; const editor = editorRef.current; if (!editor) return; const next = serializeEditableValue(editor); const cursor = getEditableSelection(editor)?.start ?? next.length; pendingSelectionRef.current = cursor; lastRenderedValueRef.current = next; onChange(next); syncMention(next, cursor); reportContentSize(editor); }; const syncEditableMentionFromSelection = () => { const editor = editorRef.current; if (!editor) return; const cursor = getEditableSelection(editor)?.start; if (typeof cursor === "number") syncMention(serializeEditableValue(editor), cursor); }; const mergedStyle = { ...(style || {}), caretColor: style?.color || theme.node.text, } as CSSProperties; const menuAnchor = useRichEditor ? editorRef.current : textareaRef.current; const menu = mention && candidates.length && menuAnchor ? : null; if (useRichEditor) { return (
{!value && props.placeholder ? (
{props.placeholder}
) : null}
{ composingRef.current = true; props.onCompositionStart?.(event as unknown as React.CompositionEvent); }} onCompositionEnd={(event) => { composingRef.current = false; syncEditableValue(); props.onCompositionEnd?.(event as unknown as React.CompositionEvent); }} onPaste={(event: ClipboardEvent) => { event.preventDefault(); replaceEditableSelection(event.clipboardData.getData("text/plain")); }} onKeyDown={(event: KeyboardEvent) => { if (mention && candidates.length) { if (event.key === "ArrowDown") { event.preventDefault(); setActiveIndex((index) => (index + 1) % candidates.length); return; } if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((index) => (index - 1 + candidates.length) % candidates.length); return; } if (event.key === "Enter" || event.key === "Tab") { event.preventDefault(); insertReference(candidates[Math.min(activeIndex, candidates.length - 1)]); return; } if (event.key === "Escape") { event.preventDefault(); closeMention(); return; } } if (event.key === "Enter") { event.preventDefault(); if (onSubmit && !event.ctrlKey && !event.metaKey && !event.shiftKey) { onSubmit(); return; } replaceEditableSelection("\n"); return; } onKeyDown?.(event as unknown as React.KeyboardEvent); }} onKeyUp={(event) => { syncEditableMentionFromSelection(); props.onKeyUp?.(event as unknown as React.KeyboardEvent); }} onMouseDown={(event) => props.onMouseDown?.(event as unknown as React.MouseEvent)} onPointerDown={(event) => props.onPointerDown?.(event as unknown as React.PointerEvent)} onPointerUp={(event) => { syncEditableMentionFromSelection(); props.onPointerUp?.(event as unknown as React.PointerEvent); }} onSelect={(event) => props.onSelect?.(event as unknown as React.SyntheticEvent)} onWheel={(event) => { event.stopPropagation(); props.onWheel?.(event as unknown as React.WheelEvent); }} onScroll={(event) => props.onScroll?.(event as unknown as React.UIEvent)} onFocus={(event) => props.onFocus?.(event as unknown as React.FocusEvent)} onBlur={(event) => { window.setTimeout(closeMention, 120); props.onBlur?.(event as unknown as React.FocusEvent); }} >
{menu}
); } return (