/** * ============================================================ * src/ui/hooks/usePasteHandler.ts —— 粘贴检测 Hook(v0.3 最终版) * ------------------------------------------------------------ * 功能: * 1. 检测粘贴输入(通过内容长度阈值) * 2. 收集多 Chunk 粘贴内容(处理 stdin 分块到达) * 3. ✨ 粘贴期间拦截所有 Enter(防止多行内容被误发送) * 4. 跨平台兼容:Win / Mac / Linux * * v0.3 核心设计原则(符合用户直觉): * - Enter(单独按):始终返回 'continue' → 调用方处理为**发送消息** * - Alt+Enter(Mac: Option+Enter):返回 'enter-newline' → 调用方处理为**插入换行** * - Ctrl+Enter:空闲时发送;缓冲尚未插入时先完成粘贴,避免发送旧草稿。 * - 粘贴期间普通 Enter 作为换行收集,不提交;修饰键与导航先 flush 再处理。 * * 工作原理: * 当用户粘贴多行内容时,stdin 可能分多个 chunk 到达。 * 如果不处理,粘贴内容中的 \n 会被解析为 Enter 键, * 导致只有最后一个换行之前的内容被保留,或者直接触发了发送。 * ============================================================ */ import { useCallback, useEffect, useRef, useState } from 'react'; import { looksLikePaste, normalizePaste } from '../pasteText.js'; // 多 Chunk 等待超时:100ms 内收到的内容视为同一批粘贴 const PASTE_TIMEOUT_MS = 100; interface PasteState { chunks: string[]; timeoutId: ReturnType | null; } interface UsePasteHandlerOptions { /** 粘贴完成时的回调(传入合并后的完整文本) */ onPasteComplete: (text: string) => void; /** 是否启用多行模式(启用后支持 Alt+Enter 换行)默认 false */ multiline?: boolean; } interface UsePasteHandlerResult { /** * 处理输入的包装函数 * @returns 处理结果: * - 'paste': 已作为粘贴处理,不继续 * - 'enter-in-paste': Enter 在粘贴期间被忽略,不提交也不换行 * - 'enter-newline': Alt+Enter(Mac: Option+Enter)被转换为换行符(用于编辑时手动换行) * - 'continue': 继续普通输入处理(包括 Enter 发送、Ctrl+Enter 强制发送等) */ handleInput: ( input: string, key: { return?: boolean; ctrl?: boolean; shift?: boolean; meta?: boolean; [key: string]: unknown; } ) => 'paste' | 'enter-in-paste' | 'enter-newline' | 'continue'; /** 当前是否处于粘贴状态 */ isPasting: boolean; } /** * 粘贴检测 Hook(v0.3 最终版) * * @example * ```tsx * const { handleInput } = usePasteHandler({ * onPasteComplete: (text) => { * buf.insert(text); * forceRefresh(); * }, * multiline: true, * }); * * useInput((input, key) => { * const result = handleInput(input, key); * if (result === 'paste') return; // 粘贴已处理 * if (result === 'enter-in-paste') return; // 粘贴中的 Enter 忽略 * if (result === 'enter-newline') { // Alt+Enter → 换行 * buf.insert('\n'); * forceRefresh(); * return; * } * // result === 'continue': 正常处理 * // 包括:Enter 发送、Ctrl+Enter 发送、普通字符输入等 * }); * ``` */ export function usePasteHandler({ onPasteComplete, multiline = false, }: UsePasteHandlerOptions): UsePasteHandlerResult { const [isPasting, setIsPasting] = useState(false); const pasteStateRef = useRef({ chunks: [], timeoutId: null, }); // 卸载清理:粘贴中途组件被切走(SessionPicker/ConfigMenu/AskQuestion 顶替)时 // 取消挂起的 flush 定时器,防止回调打到已卸载组件。 useEffect(() => { return () => { if (pasteStateRef.current.timeoutId) { clearTimeout(pasteStateRef.current.timeoutId); pasteStateRef.current.timeoutId = null; } // Preserve pending input in the session-owned draft before the editor disappears. const chunks = pasteStateRef.current.chunks; pasteStateRef.current.chunks = []; if (chunks.length) onPasteCompleteRef.current(normalizePaste(chunks.join(''))); }; }, []); /** * 刷新 UI 的引用(避免闭包问题) */ const onPasteCompleteRef = useRef(onPasteComplete); onPasteCompleteRef.current = onPasteComplete; /** * 刷新 isPasting 状态的引用 */ const setIsPastingRef = useRef(setIsPasting); setIsPastingRef.current = setIsPasting; /** * 将收集的 chunks 合并并触发回调 */ const flushPaste = useCallback(() => { const { chunks } = pasteStateRef.current; if (chunks.length === 0) return; // 合并所有 chunks const rawText = chunks.join(''); // 仅统一行尾,保留缩进、空格及所有空行。 const cleanedText = normalizePaste(rawText); // 清除状态 pasteStateRef.current = { chunks: [], timeoutId: null }; setIsPastingRef.current(false); // 触发回调 onPasteCompleteRef.current(cleanedText); }, []); /** * 处理输入(v0.3:Enter 始终发送,Alt+Enter 换行,粘贴期间拦截) */ const handleInput = useCallback( ( input: string, key: { return?: boolean; ctrl?: boolean; shift?: boolean; meta?: boolean; [key: string]: unknown; } ): 'paste' | 'enter-in-paste' | 'enter-newline' | 'continue' => { // ---- 1. 粘贴期间的任何 Enter 键:全部拦截 ---- // 这是最关键的防御!防止多行粘贴内容中的 \n 触发发送 const collecting = pasteStateRef.current.chunks.length > 0; if (collecting && (key.ctrl || key.meta || key.escape || key.backspace || key.delete || key.upArrow || key.downArrow || key.leftArrow || key.rightArrow)) { if (pasteStateRef.current.timeoutId) clearTimeout(pasteStateRef.current.timeoutId); flushPaste(); if (key.return) return multiline && key.meta && !key.ctrl ? 'enter-newline' : 'enter-in-paste'; return 'continue'; } // ---- 2. Alt+Enter(Mac: Option+Enter):插入换行符(用于编辑时手动换行)---- // multiline=false 时不识别 Alt+Enter,让它走到下面的普通 Enter 分支(提交) if (multiline && key.return && key.meta && !key.ctrl) { return 'enter-newline'; } // ---- 3. Enter(包括 Ctrl+Enter):始终返回 continue → 让调用方处理为发送 ---- // 不管是单行还是多行内容,Enter 的默认行为都是发送 // 只有 Alt+Enter 才是换行 if (key.return && !collecting && !looksLikePaste(input)) { return 'continue'; // 调用方会执行 onSubmit() } // ---- 4. 检测是否为粘贴输入 ---- const isLongInput = looksLikePaste(input); if (isLongInput || collecting) { // 进入或继续粘贴状态 setIsPasting(true); // 清除之前的超时 if (pasteStateRef.current.timeoutId) { clearTimeout(pasteStateRef.current.timeoutId); } // 收集这个 chunk pasteStateRef.current.chunks.push(key.return && input.length <= 1 ? '\n' : input); // 设置新的超时,超时后 flush pasteStateRef.current.timeoutId = setTimeout(() => { flushPaste(); }, PASTE_TIMEOUT_MS); return 'paste'; } // ---- 5. 普通输入,继续处理 ---- return 'continue'; }, [multiline, flushPaste] ); return { handleInput, isPasting, }; }