LexicalChatInput.tsx 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. /* eslint-disable max-lines */
  2. /**
  3. * LexicalChatInput — 基于 Lexical 的聊天输入框
  4. *
  5. * 基于 Lexical 的聊天输入框,支持 slash command 和 mention tag。
  6. * - Enter 发送,Shift+Enter 换行
  7. * - 支持 IME 输入
  8. * - 自动高度(默认显示 3 行,超出后滚动)
  9. * - disabled 状态
  10. * - 通过 SlashCommandPlugin / MentionPlugin 支持 `/` / `@` 的触发面板
  11. *
  12. * 独立输入展示壳,不承载会话编排逻辑,仅做三处适配:
  13. * 1. useChatViewActiveTaskProvider 来自 @/v4/activeTaskProvider.js(配置面读取);
  14. * 2. ChatComposerPasteEvent 收口为本文件导出的结构类型;
  15. * 3. mention 面板用 enableMentionPanel 控制;slash command 始终读取 CLI workspace catalog。
  16. */
  17. import { $getPromptMarkdown } from "@/mentions/promptSerialization.js";
  18. import { PromptClipboardPlugin } from "@/mentions/PromptClipboardPlugin.js";
  19. import {
  20. resolveComposerKeyAction,
  21. shouldBareEnterFallThroughToNewline,
  22. } from "@/shortcuts/composerShortcuts.js";
  23. import { useEffectiveShortcutBindings } from "@/shortcuts/useShortcutBindings.js";
  24. import { useCallback, useEffect, useMemo, useRef } from "react";
  25. import { LexicalComposer } from "@lexical/react/LexicalComposer";
  26. import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
  27. import { ContentEditable } from "@lexical/react/LexicalContentEditable";
  28. import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
  29. import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
  30. import {
  31. $createParagraphNode,
  32. $createTextNode,
  33. $getSelection,
  34. $getNodeByKey,
  35. $setSelection,
  36. $getRoot,
  37. $isParagraphNode,
  38. $isRangeSelection,
  39. $isTextNode,
  40. KEY_ARROW_DOWN_COMMAND,
  41. KEY_ARROW_UP_COMMAND,
  42. KEY_BACKSPACE_COMMAND,
  43. COMMAND_PRIORITY_HIGH,
  44. KEY_ENTER_COMMAND,
  45. type EditorState,
  46. type LexicalEditor,
  47. } from "lexical";
  48. import { SlashCommandPlugin } from "./SlashCommandPlugin.js";
  49. import type { AppSlashCommand } from "./slashCommandHelpers.js";
  50. import { MentionPlugin } from "./mentions/MentionPlugin.js";
  51. import { useChatViewActiveTaskProvider } from "@/v4/activeTaskProvider.js";
  52. import {
  53. $createPromptMentionNode,
  54. $isPromptMentionNode,
  55. PromptMentionNode,
  56. } from "./mentions/nodes/PromptMentionNode.js";
  57. import { logger } from "./logger.js";
  58. import { recordInputLag } from "./lib/uiPerfArmsTelemetry.js";
  59. import { navigatePromptHistory } from "./lib/promptHistory.js";
  60. import { resolveMobileInputTextSizeClassName } from "@/lib/mobileTextInput.js";
  61. import type { MentionItemData } from "@/mentions/mentionTypes.js";
  62. import type { ComposerMentionPrefill } from "@/store/zcodeSessionStoreTypes.js";
  63. /** 旧 useChatComposer 已删;粘贴事件收口为最小结构类型(ClipboardEvent 结构兼容)。 */
  64. export interface ChatComposerPasteEvent {
  65. clipboardData: DataTransfer | null;
  66. preventDefault: () => void;
  67. stopPropagation?: () => void;
  68. }
  69. export interface LexicalChatInputHandle {
  70. clear: () => void;
  71. focus: () => void;
  72. getEditorState: () => EditorState;
  73. getMarkdown: () => string;
  74. getText: () => string;
  75. appendText: (text: string) => void;
  76. appendFileMention: (
  77. label: string,
  78. value: string,
  79. markdown: string,
  80. data?: MentionItemData,
  81. trailingText?: string,
  82. ) => void;
  83. prependMentionIfMissing: (mention: ComposerMentionPrefill) => boolean;
  84. setMention: (mention: ComposerMentionPrefill, trailingText?: string) => void;
  85. insertMention: (mention: ComposerMentionPrefill, selectionState?: EditorState) => void;
  86. setText: (text: string) => void;
  87. setTextWithPluginMentions: (text: string) => void;
  88. setEditorStateJson: (editorStateJson: string) => void;
  89. setSkillMention: (skillName: string, markdown?: string, trailingText?: string) => void;
  90. setSlashCommandMention: (commandName: string, markdown?: string, trailingText?: string) => void;
  91. }
  92. interface LexicalEnterSubmitOptions {
  93. allowSubmitWhenEmpty?: boolean;
  94. ctrlKey?: boolean;
  95. enterSubmits: boolean;
  96. isComposing?: boolean;
  97. metaKey?: boolean;
  98. shiftKey?: boolean;
  99. text: string;
  100. }
  101. interface LexicalModifiedEnterSubmitOptions {
  102. allowSubmitWhenEmpty?: boolean;
  103. ctrlKey?: boolean;
  104. isComposing?: boolean;
  105. metaKey?: boolean;
  106. modifiedEnterSubmits: boolean;
  107. shiftKey?: boolean;
  108. text: string;
  109. }
  110. export type LexicalSubmitResult = boolean | void;
  111. interface LeadingChineseSlashAliasInputOptions {
  112. data: string | null;
  113. inputType: string;
  114. isAtEditorStart: boolean;
  115. isComposing?: boolean;
  116. }
  117. const CHINESE_SLASH_ALIAS = "、";
  118. const STANDARD_SLASH_TRIGGER = "/";
  119. import { HISTORY_NAVIGATION_UPDATE_TAG, PROGRAMMATIC_UPDATE_TAG } from "./lib/editorUpdateTags.js";
  120. export function shouldSubmitLexicalEnter({
  121. allowSubmitWhenEmpty = false,
  122. ctrlKey = false,
  123. enterSubmits,
  124. isComposing = false,
  125. metaKey = false,
  126. shiftKey = false,
  127. text,
  128. }: LexicalEnterSubmitOptions): boolean {
  129. if (!enterSubmits) {
  130. return false;
  131. }
  132. if (shiftKey || ctrlKey || metaKey || isComposing) {
  133. return false;
  134. }
  135. return Boolean(text.trim() || allowSubmitWhenEmpty);
  136. }
  137. export function shouldSubmitLexicalModifiedEnter({
  138. allowSubmitWhenEmpty = false,
  139. ctrlKey = false,
  140. isComposing = false,
  141. metaKey = false,
  142. modifiedEnterSubmits,
  143. shiftKey = false,
  144. text,
  145. }: LexicalModifiedEnterSubmitOptions): boolean {
  146. return (
  147. modifiedEnterSubmits &&
  148. (ctrlKey || metaKey) &&
  149. !shiftKey &&
  150. !isComposing &&
  151. Boolean(text.trim() || allowSubmitWhenEmpty)
  152. );
  153. }
  154. export function shouldResetLexicalEditorAfterSubmit(result: LexicalSubmitResult): boolean {
  155. return result !== false;
  156. }
  157. export function shouldNormalizeLeadingChineseSlashAliasInput({
  158. data,
  159. inputType,
  160. isAtEditorStart,
  161. isComposing = false,
  162. }: LeadingChineseSlashAliasInputOptions): boolean {
  163. return (
  164. data === CHINESE_SLASH_ALIAS && inputType === "insertText" && isAtEditorStart && !isComposing
  165. );
  166. }
  167. /** 提取编辑器内容;mention 节点会在这里输出 markdown */
  168. function getEditorMarkdown(editorState: EditorState): string {
  169. let text = "";
  170. editorState.read(() => {
  171. text = $getPromptMarkdown();
  172. });
  173. return text;
  174. }
  175. function replaceEditorText(editor: LexicalEditor, text: string) {
  176. editor.update(
  177. () => {
  178. const root = $getRoot();
  179. root.clear();
  180. // Lexical getTextContent() 用 \n\n 分隔段落,对称处理防止换行翻倍
  181. for (const line of text.split("\n\n")) {
  182. const paragraph = $createParagraphNode();
  183. if (line) {
  184. paragraph.append($createTextNode(line));
  185. }
  186. root.append(paragraph);
  187. }
  188. root.getLastChild()?.selectEnd();
  189. },
  190. { tag: PROGRAMMATIC_UPDATE_TAG },
  191. );
  192. }
  193. const INLINE_PLUGIN_MENTION_PATTERN =
  194. /\[@((?:\\.|[^\]])+)\]\(plugin:\/\/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+)\)/g;
  195. function replaceEditorTextWithPluginMentions(editor: LexicalEditor, text: string) {
  196. editor.update(
  197. () => {
  198. const root = $getRoot();
  199. root.clear();
  200. for (const line of text.split("\n\n")) {
  201. const paragraph = $createParagraphNode();
  202. let cursor = 0;
  203. for (const match of line.matchAll(INLINE_PLUGIN_MENTION_PATTERN)) {
  204. const start = match.index ?? 0;
  205. if (start > cursor) paragraph.append($createTextNode(line.slice(cursor, start)));
  206. const markdown = match[0];
  207. const label = match[1]?.replaceAll("\\]", "]").replaceAll("\\[", "[") ?? "";
  208. const pluginId = match[2] ?? "";
  209. paragraph.append(
  210. $createPromptMentionNode({
  211. id: `plugin:${pluginId}`,
  212. category: "plugins",
  213. label,
  214. value: pluginId,
  215. markdown,
  216. data: { pluginId },
  217. }),
  218. );
  219. cursor = start + markdown.length;
  220. }
  221. if (cursor < line.length || paragraph.getChildrenSize() === 0) {
  222. paragraph.append($createTextNode(line.slice(cursor)));
  223. }
  224. root.append(paragraph);
  225. }
  226. root.getLastChild()?.selectEnd();
  227. },
  228. { tag: PROGRAMMATIC_UPDATE_TAG },
  229. );
  230. }
  231. export function replaceEditorWithMention(
  232. editor: LexicalEditor,
  233. mention: ComposerMentionPrefill,
  234. trailingText = " ",
  235. ) {
  236. editor.update(
  237. () => {
  238. const root = $getRoot();
  239. root.clear();
  240. const paragraph = $createParagraphNode();
  241. // 预填后保留空格供用户直接继续输入;选区正确性由 TextNode 文本/DOM 契约保证。
  242. const trailing = $createTextNode(trailingText || " ");
  243. paragraph.append($createPromptMentionNode(mention), trailing);
  244. root.append(paragraph);
  245. trailing.selectEnd();
  246. },
  247. { tag: PROGRAMMATIC_UPDATE_TAG },
  248. );
  249. }
  250. /**
  251. * 在草稿开头插入结构化 mention,同时保留已有 Lexical 节点和段落。
  252. *
  253. * 不能通过 getMarkdown → setMention 重建:setMention 是替换型预填,会把旧 mention
  254. * 序列化后作为普通 TextNode 放回编辑器,导致已有 Plugin / 文件 / Skill chip 降级。
  255. */
  256. export function prependEditorMentionIfMissing(
  257. editor: LexicalEditor,
  258. mention: ComposerMentionPrefill,
  259. ): boolean {
  260. let inserted = false;
  261. editor.update(
  262. () => {
  263. const root = $getRoot();
  264. const alreadyPresent = root
  265. .getAllTextNodes()
  266. .some(
  267. (node) =>
  268. $isPromptMentionNode(node) &&
  269. node.getMention().category === mention.category &&
  270. node.getMention().value === mention.value,
  271. );
  272. if (alreadyPresent) return;
  273. const mentionNode = $createPromptMentionNode(mention);
  274. const separator = $createTextNode(" ");
  275. const firstBlock = root.getFirstChild();
  276. if ($isParagraphNode(firstBlock)) {
  277. const firstInline = firstBlock.getFirstChild();
  278. if (firstInline) {
  279. firstInline.insertBefore(mentionNode);
  280. mentionNode.insertAfter(separator);
  281. } else {
  282. firstBlock.append(mentionNode, separator);
  283. }
  284. } else {
  285. const paragraph = $createParagraphNode().append(mentionNode, separator);
  286. if (firstBlock) firstBlock.insertBefore(paragraph);
  287. else root.append(paragraph);
  288. }
  289. separator.selectEnd();
  290. inserted = true;
  291. },
  292. { discrete: true, tag: PROGRAMMATIC_UPDATE_TAG },
  293. );
  294. return inserted;
  295. }
  296. function replaceEditorStateJson(editor: LexicalEditor, editorStateJson: string) {
  297. const editorState = editor.parseEditorState(editorStateJson);
  298. editor.setEditorState(editorState, { tag: PROGRAMMATIC_UPDATE_TAG });
  299. }
  300. function resetEditor(editor: LexicalEditor) {
  301. replaceEditorText(editor, "");
  302. }
  303. function replaceEditorWithSkillMention(
  304. editor: LexicalEditor,
  305. skillName: string,
  306. markdown = `$${skillName}`,
  307. trailingText = " ",
  308. ) {
  309. editor.update(
  310. () => {
  311. const root = $getRoot();
  312. root.clear();
  313. const paragraph = $createParagraphNode();
  314. paragraph.append(
  315. $createPromptMentionNode({
  316. id: `prefill-skill:${skillName}`,
  317. category: "skills",
  318. // 预填入口之前虽然会插入 skill node,但节点里保存的 markdown 仍固定成 `$slug`,
  319. // 导致像 New Skill 这种入口即使理论上有完整转译内容,进入输入框后也会被悄悄降级。
  320. // 这里显式透传原始 markdown,并直接显示 frontmatter name,避免 UI 再加工 skill 标题。
  321. label: skillName,
  322. value: skillName,
  323. markdown,
  324. }),
  325. $createTextNode(trailingText),
  326. );
  327. root.append(paragraph);
  328. root.getLastChild()?.selectEnd();
  329. },
  330. { tag: PROGRAMMATIC_UPDATE_TAG },
  331. );
  332. }
  333. function replaceEditorWithSlashCommandMention(
  334. editor: LexicalEditor,
  335. commandName: string,
  336. markdown = `/${commandName}`,
  337. trailingText = " ",
  338. ) {
  339. editor.update(
  340. () => {
  341. const root = $getRoot();
  342. root.clear();
  343. const paragraph = $createParagraphNode();
  344. paragraph.append(
  345. $createPromptMentionNode({
  346. id: `prefill-slash:${commandName}`,
  347. category: "commands",
  348. label: commandName,
  349. value: commandName,
  350. markdown,
  351. }),
  352. $createTextNode(trailingText),
  353. );
  354. root.append(paragraph);
  355. root.getLastChild()?.selectEnd();
  356. },
  357. { tag: PROGRAMMATIC_UPDATE_TAG },
  358. );
  359. }
  360. function appendEditorFileMention(
  361. editor: LexicalEditor,
  362. label: string,
  363. value: string,
  364. markdown: string,
  365. data?: MentionItemData,
  366. trailingText = " ",
  367. ) {
  368. editor.update(
  369. () => {
  370. const root = $getRoot();
  371. const lastChild = root.getLastChild();
  372. const paragraph = $isParagraphNode(lastChild) ? lastChild : $createParagraphNode();
  373. if (!$isParagraphNode(lastChild)) {
  374. root.append(paragraph);
  375. }
  376. const currentText = paragraph.getTextContent();
  377. if (currentText.length > 0 && !/\s$/.test(currentText)) {
  378. paragraph.append($createTextNode(" "));
  379. }
  380. paragraph.append(
  381. $createPromptMentionNode({
  382. id: `dropped-file:${value}`,
  383. category: "files",
  384. label,
  385. value,
  386. markdown,
  387. data,
  388. }),
  389. $createTextNode(trailingText),
  390. );
  391. paragraph.selectEnd();
  392. },
  393. { tag: PROGRAMMATIC_UPDATE_TAG },
  394. );
  395. }
  396. function appendEditorPlainText(editor: LexicalEditor, text: string) {
  397. editor.update(
  398. () => {
  399. const root = $getRoot();
  400. const lastChild = root.getLastChild();
  401. const paragraph = $isParagraphNode(lastChild) ? lastChild : $createParagraphNode();
  402. if (!$isParagraphNode(lastChild)) {
  403. root.append(paragraph);
  404. }
  405. const currentText = paragraph.getTextContent();
  406. if (currentText.length > 0 && !/\s$/.test(currentText)) {
  407. paragraph.append($createTextNode(" "));
  408. }
  409. paragraph.append($createTextNode(text));
  410. paragraph.selectEnd();
  411. },
  412. { tag: PROGRAMMATIC_UPDATE_TAG },
  413. );
  414. }
  415. function getPromptMentionIdAfterDomSelection(rootElement: HTMLElement): string | null {
  416. const selection = window.getSelection();
  417. if (!selection?.isCollapsed || !selection.anchorNode) {
  418. return null;
  419. }
  420. const anchorNode = selection.anchorNode;
  421. if (!rootElement.contains(anchorNode)) {
  422. return null;
  423. }
  424. if (anchorNode.nodeType === Node.ELEMENT_NODE) {
  425. const child = anchorNode.childNodes.item(selection.anchorOffset);
  426. return getPromptMentionIdFromBoundaryNode(child);
  427. }
  428. if (anchorNode.nodeType !== Node.TEXT_NODE) {
  429. return null;
  430. }
  431. if (selection.anchorOffset !== (anchorNode.textContent ?? "").length) {
  432. return null;
  433. }
  434. return getPromptMentionIdFromBoundaryNode(anchorNode.nextSibling);
  435. }
  436. function getPromptMentionIdFromBoundaryNode(node: Node | null): string | null {
  437. if (!(node instanceof HTMLElement) || !node.matches("[data-mention-id]")) {
  438. return null;
  439. }
  440. return node.dataset.mentionId ?? null;
  441. }
  442. function selectAfterPromptMentionById(mentionId: string): boolean {
  443. const mentionNode = $getRoot()
  444. .getAllTextNodes()
  445. .find(
  446. (node): node is PromptMentionNode =>
  447. $isPromptMentionNode(node) && node.getMention().id === mentionId,
  448. );
  449. if (!mentionNode) {
  450. return false;
  451. }
  452. const nextSibling = mentionNode.getNextSibling();
  453. if ($isTextNode(nextSibling)) {
  454. const text = nextSibling.getTextContent();
  455. const offset = /^\s/.test(text) ? Math.min(1, text.length) : 0;
  456. nextSibling.select(offset, offset);
  457. return true;
  458. }
  459. mentionNode.selectNext(0, 0);
  460. return true;
  461. }
  462. /**
  463. * 键盘行为插件:Enter 发送,Shift+Enter 换行
  464. *
  465. * 用 COMMAND_PRIORITY_HIGH 截获 Enter 按键,
  466. * 阻止 Lexical 默认的段落插入行为。
  467. */
  468. function KeyboardPlugin({
  469. onSubmit,
  470. onModifiedSubmit,
  471. disabled,
  472. submitDisabled,
  473. allowSubmitWhenEmpty,
  474. enterSubmits,
  475. }: {
  476. onSubmit: (text: string) => LexicalSubmitResult;
  477. onModifiedSubmit?: (text: string) => LexicalSubmitResult;
  478. disabled?: boolean;
  479. submitDisabled?: boolean;
  480. allowSubmitWhenEmpty?: boolean;
  481. enterSubmits: boolean;
  482. }) {
  483. const [editor] = useLexicalComposerContext();
  484. // 作用域改绑层:读生效表的 composer 命令切片;ref 透传避免按键监听重挂。
  485. const effectiveShortcutBindings = useEffectiveShortcutBindings();
  486. const composerEffectiveRef = useRef({
  487. composerSend: effectiveShortcutBindings.composerSend ?? [],
  488. composerInsertNewline: effectiveShortcutBindings.composerInsertNewline ?? [],
  489. });
  490. composerEffectiveRef.current = {
  491. composerSend: effectiveShortcutBindings.composerSend ?? [],
  492. composerInsertNewline: effectiveShortcutBindings.composerInsertNewline ?? [],
  493. };
  494. useEffect(() => {
  495. const unregisterEnter = editor.registerCommand(
  496. KEY_ENTER_COMMAND,
  497. (event: KeyboardEvent | null) => {
  498. if (!event) return false;
  499. if (disabled) {
  500. event.preventDefault();
  501. return true;
  502. }
  503. // IME 正在组合中(如中文输入法),不拦截
  504. if (event.isComposing) {
  505. return false;
  506. }
  507. const text = getEditorMarkdown(editor.getEditorState());
  508. // 作用域改绑层:用户键位表优先于内置默认。
  509. // 命中换行 → 放行 Lexical 插段落;命中发送 → 走与主链等价的门禁分支;
  510. // 未命中 → 落到下方主链(含反转投递 / 修饰组合换行 / 视口门禁)。
  511. const composerEffective = composerEffectiveRef.current;
  512. const scopedAction = resolveComposerKeyAction(event, composerEffective);
  513. if (scopedAction === "newline") {
  514. return false;
  515. }
  516. if (scopedAction === "send") {
  517. const modifiedScopedEnter = event.shiftKey || event.ctrlKey || event.metaKey;
  518. // 反转投递开启时带修饰组合让位主链(Ctrl+Enter = 反向 delivery,交付语义比键位更具体)
  519. if (!(modifiedScopedEnter && onModifiedSubmit)) {
  520. // 与主链裸 Enter 等价的门禁:无修饰组合受 submitDisabled / 手机视口 enterSubmits;
  521. // 带修饰组合不受视口门禁(与主链 onModifiedSubmit 路径一致)。
  522. if (submitDisabled || (!modifiedScopedEnter && !enterSubmits)) {
  523. return false;
  524. }
  525. event.preventDefault();
  526. if (
  527. shouldSubmitLexicalEnter({
  528. allowSubmitWhenEmpty,
  529. enterSubmits: modifiedScopedEnter ? true : enterSubmits,
  530. text,
  531. })
  532. ) {
  533. const submitResult = onSubmit(text);
  534. if (shouldResetLexicalEditorAfterSubmit(submitResult)) {
  535. resetEditor(editor);
  536. }
  537. }
  538. return true;
  539. }
  540. }
  541. // 主链前置检查:composerSend 已改绑走(生效绑定不含裸 Enter)时,
  542. // 裸 Enter 不再代表发送,放行 Lexical 换行("Ctrl+Enter 党"改绑后的预期行为)。
  543. if (
  544. !event.shiftKey &&
  545. !event.ctrlKey &&
  546. !event.metaKey &&
  547. shouldBareEnterFallThroughToNewline(composerEffective)
  548. ) {
  549. return false;
  550. }
  551. if (
  552. !submitDisabled &&
  553. onModifiedSubmit &&
  554. shouldSubmitLexicalModifiedEnter({
  555. allowSubmitWhenEmpty,
  556. ctrlKey: event.ctrlKey,
  557. metaKey: event.metaKey,
  558. modifiedEnterSubmits: true,
  559. shiftKey: event.shiftKey,
  560. text,
  561. })
  562. ) {
  563. event.preventDefault();
  564. const submitResult = onModifiedSubmit(text);
  565. if (shouldResetLexicalEditorAfterSubmit(submitResult)) {
  566. resetEditor(editor);
  567. }
  568. return true;
  569. }
  570. // Shift+Enter,以及未启用反转投递时的 Ctrl/Meta+Enter 继续换行。
  571. if (event.shiftKey || event.ctrlKey || event.metaKey) {
  572. return false;
  573. }
  574. // 当前请求进行中时,输入框仍允许继续编辑草稿,但此时不能再次提交。
  575. // 之前把状态直接映射成 disabled,导致输入和联想面板一起失效;如果只去掉 disabled,
  576. // Enter 又会误触发 submit 并清空草稿。这里在 submitDisabled 时把 Enter 退回给 Lexical 处理换行。
  577. if (submitDisabled || !enterSubmits) {
  578. return false;
  579. }
  580. event.preventDefault();
  581. if (
  582. shouldSubmitLexicalEnter({
  583. allowSubmitWhenEmpty,
  584. enterSubmits,
  585. text,
  586. })
  587. ) {
  588. const submitResult = onSubmit(text);
  589. // 业务层可能拒绝本次提交并要求草稿留在输入框。
  590. // Enter 键盘层不能无条件 reset,否则即使业务层未发送,用户输入也会被吃掉。
  591. if (shouldResetLexicalEditorAfterSubmit(submitResult)) {
  592. resetEditor(editor);
  593. }
  594. }
  595. return true;
  596. },
  597. COMMAND_PRIORITY_HIGH,
  598. );
  599. const unregisterBackspace = editor.registerCommand(
  600. KEY_BACKSPACE_COMMAND,
  601. (event: KeyboardEvent | null) => {
  602. const selection = $getSelection();
  603. if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
  604. return false;
  605. }
  606. const anchor = selection.anchor;
  607. if (anchor.type !== "text") {
  608. return false;
  609. }
  610. const node = anchor.getNode();
  611. if (!$isTextNode(node)) {
  612. return false;
  613. }
  614. const text = node.getTextContent();
  615. if (anchor.offset !== 1 || text !== " ") {
  616. return false;
  617. }
  618. const previousSibling = node.getPreviousSibling();
  619. if (!$isPromptMentionNode(previousSibling)) {
  620. return false;
  621. }
  622. // mention 插入时会自动补一个空格用于继续输入,
  623. // 之前 Backspace 会先删这个空格,再删 token,用户体感是“要按两次才删掉标签”。
  624. // 这里在“光标正好位于补位空格后”时,直接一次性删除空格 + mention token。
  625. event?.preventDefault();
  626. previousSibling.remove();
  627. node.remove();
  628. node.getParent()?.selectEnd();
  629. return true;
  630. },
  631. COMMAND_PRIORITY_HIGH,
  632. );
  633. const handleRootKeyDownCapture = (event: KeyboardEvent) => {
  634. if (
  635. disabled ||
  636. event.key !== "ArrowRight" ||
  637. !event.altKey ||
  638. event.shiftKey ||
  639. event.ctrlKey ||
  640. event.metaKey ||
  641. event.isComposing
  642. ) {
  643. return;
  644. }
  645. const rootElement = editor.getRootElement();
  646. if (!rootElement) {
  647. return;
  648. }
  649. const mentionId = getPromptMentionIdAfterDomSelection(rootElement);
  650. if (!mentionId) {
  651. return;
  652. }
  653. // macOS Option+ArrowRight 会按 DOM 文本做词级跳转,之前会把光标落进
  654. // mention token 内部的文件名文本;下一次输入时 Lexical 会把 token 当作被替换内容删除。
  655. // 在 token 左边界显式把 selection 移到 token 后侧,保持 mention 的原子编辑语义。
  656. event.preventDefault();
  657. event.stopImmediatePropagation();
  658. editor.update(
  659. () => {
  660. selectAfterPromptMentionById(mentionId);
  661. },
  662. { tag: PROGRAMMATIC_UPDATE_TAG },
  663. );
  664. };
  665. // 作用域改绑层·非 Enter 分发(统一开放策略):KEY_ENTER_COMMAND 只对 Enter
  666. // 派发,用户把发送/换行绑成非 Enter 键(如 F9)时由 root keydown capture 分发,
  667. // 否则改绑是死绑定,且裸 Enter 回退换行会让键盘发送能力整体丢失。
  668. // 非 Enter 物理键不存在手机软键盘误发问题,send 不受 enterSubmits 视口门禁;
  669. // 与反转投递(仅响应 Ctrl/Meta+Enter)无交集,无需让位。
  670. const handleNonEnterScopedKeydown = (event: KeyboardEvent) => {
  671. if (disabled || event.repeat || event.isComposing || event.key === "Enter") {
  672. return;
  673. }
  674. const scopedAction = resolveComposerKeyAction(event, composerEffectiveRef.current);
  675. if (!scopedAction) {
  676. return;
  677. }
  678. if (scopedAction === "newline") {
  679. event.preventDefault();
  680. editor.update(() => {
  681. const selection = $getSelection();
  682. if ($isRangeSelection(selection)) {
  683. selection.insertLineBreak();
  684. }
  685. });
  686. return;
  687. }
  688. if (submitDisabled) {
  689. return;
  690. }
  691. event.preventDefault();
  692. const text = getEditorMarkdown(editor.getEditorState());
  693. if (shouldSubmitLexicalEnter({ allowSubmitWhenEmpty, enterSubmits: true, text })) {
  694. const submitResult = onSubmit(text);
  695. if (shouldResetLexicalEditorAfterSubmit(submitResult)) {
  696. resetEditor(editor);
  697. }
  698. }
  699. };
  700. const unregisterRootListener = editor.registerRootListener(
  701. (rootElement, previousRootElement) => {
  702. previousRootElement?.removeEventListener("keydown", handleRootKeyDownCapture, {
  703. capture: true,
  704. });
  705. rootElement?.addEventListener("keydown", handleRootKeyDownCapture, {
  706. capture: true,
  707. });
  708. previousRootElement?.removeEventListener("keydown", handleNonEnterScopedKeydown, {
  709. capture: true,
  710. });
  711. rootElement?.addEventListener("keydown", handleNonEnterScopedKeydown, {
  712. capture: true,
  713. });
  714. },
  715. );
  716. return () => {
  717. unregisterEnter();
  718. unregisterBackspace();
  719. unregisterRootListener();
  720. editor.getRootElement()?.removeEventListener("keydown", handleRootKeyDownCapture, {
  721. capture: true,
  722. });
  723. editor.getRootElement()?.removeEventListener("keydown", handleNonEnterScopedKeydown, {
  724. capture: true,
  725. });
  726. };
  727. }, [
  728. allowSubmitWhenEmpty,
  729. disabled,
  730. editor,
  731. enterSubmits,
  732. onModifiedSubmit,
  733. onSubmit,
  734. submitDisabled,
  735. ]);
  736. return null;
  737. }
  738. /**
  739. * 文本变化插件
  740. *
  741. * 直接用 Lexical 自带的 OnChangePlugin 时,第一次从空编辑器输入字符会被内部的
  742. * `prevEditorState.isEmpty()` 直接跳过,父组件的 input 状态拿不到首字符,发送按钮和输入内容会错位。
  743. * 这里改成自己监听 update,只在序列化后的 markdown 真正变化时同步,首字符输入也能稳定回传。
  744. */
  745. function TextContentPlugin({
  746. onChange,
  747. taskId,
  748. }: {
  749. onChange?: (text: string) => void;
  750. taskId?: string | null;
  751. }) {
  752. const [editor] = useLexicalComposerContext();
  753. // IME 组合态标记:不直接依赖 editor.isComposing(),因为它在 update listener 同步执行时
  754. // 是否已反映组合态存在时序不确定性,读不到 true 会把中文/日文长文本组合的高耗时误报成打字卡顿。
  755. // 改由 compositionstart/compositionend 事件自行维护,稳健可控。
  756. const composingRef = useRef(false);
  757. useEffect(() => {
  758. const handleCompositionStart = () => {
  759. composingRef.current = true;
  760. };
  761. const handleCompositionEnd = () => {
  762. // compositionend 触发时组合刚结束,但「组合提交」这一拍的 update listener 通常在同一轮
  763. // 任务里同步执行,若立即置 false,这次高耗时会被误判为打字卡顿。用 queueMicrotask 把置 false
  764. // 延后到当前同步任务之后,确保组合提交那一拍仍按组合态短路,再恢复正常计入。
  765. queueMicrotask(() => {
  766. composingRef.current = false;
  767. });
  768. };
  769. // root 会重挂,用 registerRootListener 在新旧 root 上正确解绑/绑定。
  770. return editor.registerRootListener((rootElement, previousRootElement) => {
  771. previousRootElement?.removeEventListener("compositionstart", handleCompositionStart);
  772. previousRootElement?.removeEventListener("compositionend", handleCompositionEnd);
  773. rootElement?.addEventListener("compositionstart", handleCompositionStart);
  774. rootElement?.addEventListener("compositionend", handleCompositionEnd);
  775. });
  776. }, [editor]);
  777. useEffect(() => {
  778. if (!onChange) {
  779. return;
  780. }
  781. return editor.registerUpdateListener(
  782. ({ dirtyElements, dirtyLeaves, editorState, prevEditorState, tags }) => {
  783. if (dirtyElements.size === 0 && dirtyLeaves.size === 0) {
  784. return;
  785. }
  786. // 输入卡顿计时:包住「全量序列化 + onChange 同步重渲染」这段处理热点。
  787. const startedAt = performance.now();
  788. const nextText = getEditorMarkdown(editorState);
  789. const previousText = getEditorMarkdown(prevEditorState);
  790. if (nextText === previousText) {
  791. return;
  792. }
  793. onChange(nextText);
  794. const lagMs = performance.now() - startedAt;
  795. // 程序化改写与 IME 组合态不算打字卡顿(判定在 recordInputLag 内统一短路)。
  796. recordInputLag({
  797. lagMs,
  798. textLength: nextText.length,
  799. isProgrammatic: tags.has(PROGRAMMATIC_UPDATE_TAG),
  800. isComposing: composingRef.current,
  801. taskId: taskId ?? undefined,
  802. });
  803. },
  804. );
  805. }, [editor, onChange, taskId]);
  806. return null;
  807. }
  808. /** 编辑器可编辑状态控制插件 */
  809. function EditablePlugin({ editable }: { editable: boolean }) {
  810. const [editor] = useLexicalComposerContext();
  811. useEffect(() => {
  812. editor.setEditable(editable);
  813. }, [editor, editable]);
  814. return null;
  815. }
  816. function E2ELexicalInputBridgePlugin({ inputTestId }: { inputTestId?: string }) {
  817. const [editor] = useLexicalComposerContext();
  818. useEffect(() => {
  819. if (!inputTestId || typeof document === "undefined") {
  820. return;
  821. }
  822. const bridge = {
  823. focus: () => editor.focus(),
  824. getEditorState: () => editor.getEditorState(),
  825. getText: () => getEditorMarkdown(editor.getEditorState()),
  826. setText: (text: string) => replaceEditorText(editor, text),
  827. setTextWithPluginMentions: (text: string) => replaceEditorTextWithPluginMentions(editor, text),
  828. setEditorStateJson: (editorStateJson: string) =>
  829. replaceEditorStateJson(editor, editorStateJson),
  830. };
  831. let attachedInput: HTMLElement | null = null;
  832. const detachBridge = (input: HTMLElement | null) => {
  833. if (
  834. input &&
  835. (input as { __zcodeLexicalInputE2E?: typeof bridge }).__zcodeLexicalInputE2E === bridge
  836. ) {
  837. delete (input as { __zcodeLexicalInputE2E?: typeof bridge }).__zcodeLexicalInputE2E;
  838. }
  839. input?.removeAttribute("data-e2e-lexical-bridge");
  840. };
  841. const attachBridge = (input: HTMLElement | null) => {
  842. if (attachedInput && attachedInput !== input) {
  843. detachBridge(attachedInput);
  844. }
  845. attachedInput = input;
  846. if (!input) {
  847. return;
  848. }
  849. // E2E 需要驱动真实 Lexical state;只改 DOM contenteditable 会绕过 editor update,
  850. // 容易把文本误打到主输入框,导致测试结论和产品行为脱节。
  851. Object.defineProperty(input, "__zcodeLexicalInputE2E", {
  852. configurable: true,
  853. value: bridge,
  854. });
  855. input.setAttribute("data-e2e-lexical-bridge", "ready");
  856. };
  857. const resolveInput = (rootElement: HTMLElement | null) => {
  858. if (rootElement?.getAttribute("data-testid") === inputTestId) {
  859. return rootElement;
  860. }
  861. return document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  862. };
  863. let retryTimer: number | null = null;
  864. const tryAttachBridge = () => {
  865. const nextInput = resolveInput(editor.getRootElement());
  866. attachBridge(nextInput);
  867. if (nextInput && retryTimer !== null) {
  868. window.clearInterval(retryTimer);
  869. retryTimer = null;
  870. }
  871. };
  872. const unregisterRoot = editor.registerRootListener((rootElement, previousRootElement) => {
  873. if (previousRootElement !== rootElement) {
  874. detachBridge(previousRootElement);
  875. }
  876. // E2E bridge 之前只在 effect 里查询一次 DOM。
  877. // 编辑器 root 如果比插件晚挂载或被 Lexical 重挂载,bridge 会永久缺失。
  878. attachBridge(resolveInput(rootElement));
  879. });
  880. tryAttachBridge();
  881. // edit 场景里 ChatPromptEditor 的 initialValue 回填、Lexical root 注册、
  882. // React DOM 提交顺序可能跨多个帧。短轮询只负责补挂测试 bridge,不参与产品行为。
  883. retryTimer = window.setInterval(tryAttachBridge, 100);
  884. return () => {
  885. unregisterRoot();
  886. if (retryTimer !== null) {
  887. window.clearInterval(retryTimer);
  888. }
  889. detachBridge(attachedInput);
  890. };
  891. }, [editor, inputTestId]);
  892. return null;
  893. }
  894. function PromptHistoryPlugin({
  895. entries,
  896. disabled,
  897. }: {
  898. entries: readonly string[];
  899. disabled?: boolean;
  900. }) {
  901. const [editor] = useLexicalComposerContext();
  902. const historyIndexRef = useRef<number | null>(null);
  903. const applyingHistoryRef = useRef(false);
  904. useEffect(() => {
  905. if (historyIndexRef.current !== null && entries[historyIndexRef.current] === undefined) {
  906. historyIndexRef.current = null;
  907. }
  908. }, [entries]);
  909. useEffect(() => {
  910. return editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, editorState }) => {
  911. if (dirtyElements.size === 0 && dirtyLeaves.size === 0) {
  912. return;
  913. }
  914. if (applyingHistoryRef.current) {
  915. applyingHistoryRef.current = false;
  916. return;
  917. }
  918. const currentIndex = historyIndexRef.current;
  919. if (currentIndex === null) {
  920. return;
  921. }
  922. if (entries[currentIndex] === undefined) {
  923. historyIndexRef.current = null;
  924. return;
  925. }
  926. if (getEditorMarkdown(editorState) !== entries[currentIndex]) {
  927. historyIndexRef.current = null;
  928. }
  929. });
  930. }, [editor, entries]);
  931. const applyHistoryEntry = useCallback(
  932. (nextIndex: number | null, nextValue: string) => {
  933. historyIndexRef.current = nextIndex;
  934. applyingHistoryRef.current = true;
  935. // 使用专用 HISTORY_NAVIGATION_UPDATE_TAG 而非通用 PROGRAMMATIC_UPDATE_TAG,
  936. // 使 SlashCommandPlugin 能区分"历史回填"与"用户正在输入 slash 查询",
  937. // 防止回填含 / 的历史条目时面板重新打开并以 COMMAND_PRIORITY_CRITICAL 吞掉后续方向键。
  938. editor.update(
  939. () => {
  940. const root = $getRoot();
  941. root.clear();
  942. for (const line of nextValue.split("\n\n")) {
  943. const paragraph = $createParagraphNode();
  944. if (line) {
  945. paragraph.append($createTextNode(line));
  946. }
  947. root.append(paragraph);
  948. }
  949. root.getLastChild()?.selectEnd();
  950. },
  951. { tag: HISTORY_NAVIGATION_UPDATE_TAG },
  952. );
  953. },
  954. [editor],
  955. );
  956. const handleHistoryNavigation = useCallback(
  957. (direction: "up" | "down") => (event: KeyboardEvent | null) => {
  958. if (!event) return false;
  959. if (
  960. disabled ||
  961. event.shiftKey ||
  962. event.ctrlKey ||
  963. event.metaKey ||
  964. event.altKey ||
  965. event.isComposing
  966. ) {
  967. return false;
  968. }
  969. const text = getEditorMarkdown(editor.getEditorState());
  970. const currentIndex = historyIndexRef.current;
  971. // 历史导航只在“空输入”或“已经进入历史浏览态”时接管上下键,
  972. // 避免抢走多行输入原本的光标移动行为。
  973. if (currentIndex === null && text.length > 0) {
  974. return false;
  975. }
  976. const result = navigatePromptHistory(entries, currentIndex, direction);
  977. if (!result.shouldHandle) {
  978. return false;
  979. }
  980. event.preventDefault();
  981. applyHistoryEntry(result.nextIndex, result.nextValue);
  982. return true;
  983. },
  984. [applyHistoryEntry, disabled, editor, entries],
  985. );
  986. useEffect(() => {
  987. const unregisterUp = editor.registerCommand(
  988. KEY_ARROW_UP_COMMAND,
  989. handleHistoryNavigation("up"),
  990. COMMAND_PRIORITY_HIGH,
  991. );
  992. const unregisterDown = editor.registerCommand(
  993. KEY_ARROW_DOWN_COMMAND,
  994. handleHistoryNavigation("down"),
  995. COMMAND_PRIORITY_HIGH,
  996. );
  997. return () => {
  998. unregisterUp();
  999. unregisterDown();
  1000. };
  1001. }, [editor, handleHistoryNavigation]);
  1002. return null;
  1003. }
  1004. function isCollapsedSelectionAtEditorStart(): boolean {
  1005. const selection = $getSelection();
  1006. if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
  1007. return false;
  1008. }
  1009. const [startPoint] = selection.getStartEndPoints() ?? [];
  1010. if (!startPoint || startPoint.offset !== 0) {
  1011. return false;
  1012. }
  1013. const root = $getRoot();
  1014. const startNode = startPoint.getNode();
  1015. if (startPoint.type === "text") {
  1016. const firstTextNode = root.getAllTextNodes()[0] ?? null;
  1017. return firstTextNode?.is(startNode) ?? root.getTextContentSize() === 0;
  1018. }
  1019. if (startNode.is(root)) {
  1020. return true;
  1021. }
  1022. const firstDescendant = root.getFirstDescendant();
  1023. return firstDescendant?.is(startNode) ?? root.getTextContentSize() === 0;
  1024. }
  1025. function LeadingChineseSlashAliasPlugin({ disabled }: { disabled?: boolean }) {
  1026. const [editor] = useLexicalComposerContext();
  1027. useEffect(() => {
  1028. if (disabled) {
  1029. return;
  1030. }
  1031. const handleBeforeInput = (event: InputEvent) => {
  1032. let shouldNormalize = false;
  1033. editor.getEditorState().read(() => {
  1034. shouldNormalize = shouldNormalizeLeadingChineseSlashAliasInput({
  1035. data: event.data,
  1036. inputType: event.inputType,
  1037. isAtEditorStart: isCollapsedSelectionAtEditorStart(),
  1038. isComposing: event.isComposing,
  1039. });
  1040. });
  1041. if (!shouldNormalize) {
  1042. return;
  1043. }
  1044. // 中文输入法下用户在输入框第一位想打 `/` 唤起命令时,
  1045. // 可能会实际输入顿号 `、`。这里只拦截真实手输且位于全文开头的顿号,
  1046. // 立即归一成标准 `/`,避免把顿号扩散成 slash command 的另一套匹配语法。
  1047. event.preventDefault();
  1048. editor.update(
  1049. () => {
  1050. if (!isCollapsedSelectionAtEditorStart()) {
  1051. return;
  1052. }
  1053. const selection = $getSelection();
  1054. if (!$isRangeSelection(selection)) {
  1055. return;
  1056. }
  1057. selection.insertText(STANDARD_SLASH_TRIGGER);
  1058. },
  1059. { tag: PROGRAMMATIC_UPDATE_TAG },
  1060. );
  1061. };
  1062. return editor.registerRootListener((rootElement, previousRootElement) => {
  1063. previousRootElement?.removeEventListener("beforeinput", handleBeforeInput as EventListener);
  1064. rootElement?.addEventListener("beforeinput", handleBeforeInput as EventListener);
  1065. });
  1066. }, [disabled, editor]);
  1067. return null;
  1068. }
  1069. function PasteCapturePlugin({
  1070. disabled,
  1071. onPaste,
  1072. }: {
  1073. disabled?: boolean;
  1074. onPaste?: (event: ChatComposerPasteEvent) => void;
  1075. }) {
  1076. const [editor] = useLexicalComposerContext();
  1077. useEffect(() => {
  1078. if (!onPaste) {
  1079. return;
  1080. }
  1081. const handlePaste = (event: ClipboardEvent) => {
  1082. if (disabled) {
  1083. return;
  1084. }
  1085. const wasDefaultPrevented = event.defaultPrevented;
  1086. onPaste(event);
  1087. if (event.defaultPrevented && !wasDefaultPrevented) {
  1088. // 长文本已经被转成附件后,必须阻断 Lexical 后续 paste command,
  1089. // 否则会出现“附件有了,正文也被插入”的双份内容。
  1090. event.stopImmediatePropagation();
  1091. }
  1092. };
  1093. return editor.registerRootListener((rootElement, previousRootElement) => {
  1094. previousRootElement?.removeEventListener("paste", handlePaste, {
  1095. capture: true,
  1096. });
  1097. rootElement?.addEventListener("paste", handlePaste, { capture: true });
  1098. });
  1099. }, [disabled, editor, onPaste]);
  1100. return null;
  1101. }
  1102. /** 暴露 focus / clear / getText 给外部 */
  1103. export function insertEditorMention(
  1104. editor: LexicalEditor,
  1105. mention: ComposerMentionPrefill,
  1106. selectionState?: EditorState,
  1107. ) {
  1108. const selection = selectionState?.read(() => $getSelection()?.clone() ?? null);
  1109. editor.update(
  1110. () => {
  1111. // 浮层获取焦点后 Lexical 选区会丢失,恢复打开菜单前的光标,避免覆盖整份草稿。
  1112. // 草稿可能在菜单打开期间被替换;旧节点不存在时不能恢复选区,否则 Lexical 会抛错。
  1113. if ($isRangeSelection(selection)) {
  1114. if ($getNodeByKey(selection.anchor.key) && $getNodeByKey(selection.focus.key)) {
  1115. $setSelection(selection);
  1116. } else {
  1117. $getRoot().selectEnd();
  1118. }
  1119. }
  1120. let target = $getSelection();
  1121. if (!$isRangeSelection(target)) target = $getRoot().selectEnd();
  1122. const trailing = $createTextNode(" ");
  1123. target.insertNodes([$createPromptMentionNode(mention), trailing]);
  1124. trailing.selectEnd();
  1125. },
  1126. { tag: PROGRAMMATIC_UPDATE_TAG },
  1127. );
  1128. }
  1129. function EditorApiPlugin({
  1130. editorApiRef,
  1131. }: {
  1132. editorApiRef?: React.MutableRefObject<LexicalChatInputHandle | null>;
  1133. }) {
  1134. const [editor] = useLexicalComposerContext();
  1135. useEffect(() => {
  1136. if (!editorApiRef) {
  1137. return;
  1138. }
  1139. editorApiRef.current = {
  1140. clear: () => resetEditor(editor),
  1141. focus: () => editor.focus(),
  1142. getEditorState: () => editor.getEditorState(),
  1143. getMarkdown: () => getEditorMarkdown(editor.getEditorState()),
  1144. getText: () => getEditorMarkdown(editor.getEditorState()),
  1145. appendText: (text: string) => appendEditorPlainText(editor, text),
  1146. appendFileMention: (
  1147. label: string,
  1148. value: string,
  1149. markdown: string,
  1150. data?: MentionItemData,
  1151. trailingText = " ",
  1152. ) => appendEditorFileMention(editor, label, value, markdown, data, trailingText),
  1153. insertMention: (mention, selectionState) =>
  1154. insertEditorMention(editor, mention, selectionState),
  1155. prependMentionIfMissing: (mention) => prependEditorMentionIfMissing(editor, mention),
  1156. setMention: (mention, trailingText) =>
  1157. replaceEditorWithMention(editor, mention, trailingText),
  1158. setText: (text: string) => replaceEditorText(editor, text),
  1159. setTextWithPluginMentions: (text: string) => replaceEditorTextWithPluginMentions(editor, text),
  1160. setEditorStateJson: (editorStateJson: string) =>
  1161. replaceEditorStateJson(editor, editorStateJson),
  1162. setSkillMention: (skillName: string, markdown = `$${skillName}`, trailingText = " ") =>
  1163. replaceEditorWithSkillMention(editor, skillName, markdown, trailingText),
  1164. setSlashCommandMention: (
  1165. commandName: string,
  1166. markdown = `/${commandName}`,
  1167. trailingText = " ",
  1168. ) => replaceEditorWithSlashCommandMention(editor, commandName, markdown, trailingText),
  1169. };
  1170. return () => {
  1171. editorApiRef.current = null;
  1172. };
  1173. }, [editor, editorApiRef]);
  1174. return null;
  1175. }
  1176. interface LexicalChatInputProps {
  1177. placeholder?: string;
  1178. disabled?: boolean;
  1179. submitDisabled?: boolean;
  1180. allowSubmitWhenEmpty?: boolean;
  1181. enterSubmits?: boolean;
  1182. onSubmit: (text: string) => LexicalSubmitResult;
  1183. onModifiedSubmit?: (text: string) => LexicalSubmitResult;
  1184. onChange?: (text: string) => void;
  1185. onFocus?: () => void;
  1186. triggerPanelContainer?: HTMLElement | null;
  1187. workspacePath: string;
  1188. workspaceIdentity?: string;
  1189. taskId: string | null;
  1190. /** 仅影响 Skill 引用目录;草稿可使用 prewarm Session runtime。 */
  1191. skillCatalogSessionId?: string | null;
  1192. inputTestId?: string;
  1193. editorApiRef?: React.MutableRefObject<LexicalChatInputHandle | null>;
  1194. promptHistory?: readonly string[];
  1195. avoidIosInputFocusZoom?: boolean;
  1196. compactPlaceholder?: boolean;
  1197. onWhiteboardMentionSelected?: (boardId: string) => void | Promise<void>;
  1198. onPaste?: (event: ChatComposerPasteEvent) => void;
  1199. excludedSlashCommandNames?: readonly string[];
  1200. /** App 层本地斜杠命令(如 `/side`),选中即执行 UI 行为,不发送。 */
  1201. appSlashCommands?: readonly AppSlashCommand[];
  1202. /** mention(@/#)面板开关。v4 数据面未就绪时显式关闭,入口保留。 */
  1203. enableMentionPanel?: boolean;
  1204. }
  1205. const EDITOR_THEME = {
  1206. paragraph: "m-0",
  1207. };
  1208. export function LexicalChatInput({
  1209. placeholder,
  1210. disabled = false,
  1211. submitDisabled = false,
  1212. allowSubmitWhenEmpty = false,
  1213. enterSubmits = true,
  1214. onSubmit,
  1215. onModifiedSubmit,
  1216. onChange,
  1217. onFocus,
  1218. triggerPanelContainer,
  1219. workspacePath,
  1220. workspaceIdentity,
  1221. taskId,
  1222. skillCatalogSessionId,
  1223. inputTestId,
  1224. editorApiRef,
  1225. promptHistory = [],
  1226. avoidIosInputFocusZoom = false,
  1227. compactPlaceholder = false,
  1228. onWhiteboardMentionSelected,
  1229. onPaste,
  1230. excludedSlashCommandNames,
  1231. appSlashCommands,
  1232. enableMentionPanel = true,
  1233. }: LexicalChatInputProps) {
  1234. const inputMountedAtRef = useRef(Date.now());
  1235. const lastReadyLogKeyRef = useRef<string | null>(null);
  1236. const activeTaskProvider = useChatViewActiveTaskProvider(
  1237. taskId,
  1238. workspacePath,
  1239. workspaceIdentity,
  1240. );
  1241. useEffect(() => {
  1242. const readyLogKey = [
  1243. workspaceIdentity ?? workspacePath,
  1244. taskId ?? "draft",
  1245. activeTaskProvider,
  1246. triggerPanelContainer ? "trigger-ready" : "trigger-missing",
  1247. ].join("|");
  1248. if (lastReadyLogKeyRef.current === readyLogKey) {
  1249. return;
  1250. }
  1251. lastReadyLogKeyRef.current = readyLogKey;
  1252. let frameId: number | null = null;
  1253. const logReady = () => {
  1254. logger.info("[LexicalChatInput] 输入编辑器首帧完成", {
  1255. durationMs: Date.now() - inputMountedAtRef.current,
  1256. activeTaskProvider,
  1257. disabled,
  1258. hasPromptHistory: promptHistory.length > 0,
  1259. submitDisabled,
  1260. taskId,
  1261. triggerPanelReady: Boolean(triggerPanelContainer),
  1262. workspaceIdentity: workspaceIdentity ?? null,
  1263. workspacePath,
  1264. });
  1265. };
  1266. // Lexical 编辑器初始化、slash/mention plugin 和外部 portal 分属不同组件。
  1267. // 这里等浏览器下一帧再打点,才能和 composer shell 首帧、toolbar portal ready 对齐。
  1268. if (typeof requestAnimationFrame === "function") {
  1269. frameId = requestAnimationFrame(logReady);
  1270. } else {
  1271. logReady();
  1272. }
  1273. return () => {
  1274. if (frameId !== null) {
  1275. cancelAnimationFrame(frameId);
  1276. }
  1277. };
  1278. }, [
  1279. activeTaskProvider,
  1280. disabled,
  1281. promptHistory.length,
  1282. submitDisabled,
  1283. taskId,
  1284. triggerPanelContainer,
  1285. workspaceIdentity,
  1286. workspacePath,
  1287. ]);
  1288. const handleSubmit = useCallback(
  1289. (text: string) => {
  1290. const submitResult = onSubmit(text);
  1291. requestAnimationFrame(() => {
  1292. editorApiRef?.current?.focus();
  1293. });
  1294. return submitResult;
  1295. },
  1296. [editorApiRef, onSubmit],
  1297. );
  1298. // Lexical 的 ContentEditable props 是一个互斥联合类型,
  1299. // aria-placeholder 一旦出现就要求 placeholder 同时存在。
  1300. // 之前直接写三元 JSX,TypeScript 在合并两条分支时没有正确保留这组联动约束,导致误报缺少 placeholder。
  1301. const contentEditableProps: React.ComponentProps<typeof ContentEditable> = placeholder
  1302. ? {
  1303. "aria-placeholder": placeholder,
  1304. placeholder: (
  1305. <div
  1306. className={`pointer-events-none absolute left-0 top-0 ${compactPlaceholder ? "line-clamp-2" : ""} ${resolveMobileInputTextSizeClassName(
  1307. {
  1308. avoidIosInputFocusZoom,
  1309. },
  1310. )} text-foreground-subtlest`}
  1311. >
  1312. {placeholder}
  1313. </div>
  1314. ),
  1315. }
  1316. : {
  1317. placeholder: null,
  1318. };
  1319. const contentEditable = (
  1320. <ContentEditable
  1321. // Bugfix: mention node 使用固定行高的 inline-flex chip,普通正文如果继承浏览器 normal line-height,
  1322. // 在 token 后继续输入文字时会按不同 line box 计算基线;这里显式收口正文行高,并允许手机远控使用 16px 防止 iOS 聚焦放大。
  1323. className={`min-h-10 max-h-40 overflow-y-auto ${resolveMobileInputTextSizeClassName({
  1324. avoidIosInputFocusZoom,
  1325. })} text-foreground outline-none`}
  1326. data-testid={inputTestId}
  1327. onFocus={onFocus}
  1328. {...contentEditableProps}
  1329. />
  1330. );
  1331. const initialConfig = useMemo(
  1332. () => ({
  1333. namespace: "ChatInput",
  1334. theme: EDITOR_THEME,
  1335. nodes: [PromptMentionNode],
  1336. // LexicalComposer initialConfig 每次 render 新建会让输入区子树被记录为 props 变化;
  1337. // 配置内容本身是静态的,固定引用能避免无关状态更新触发 composer 子树冒泡。
  1338. onError: (error: Error) => {
  1339. logger.error("[LexicalChatInput] editor error:", error);
  1340. },
  1341. }),
  1342. [],
  1343. );
  1344. return (
  1345. <div className="relative flex-1">
  1346. <LexicalComposer initialConfig={initialConfig}>
  1347. <div className="relative">
  1348. <PlainTextPlugin contentEditable={contentEditable} ErrorBoundary={LexicalErrorBoundary} />
  1349. <HistoryPlugin />
  1350. <PromptClipboardPlugin />
  1351. <TextContentPlugin onChange={onChange} taskId={taskId} />
  1352. <KeyboardPlugin
  1353. onSubmit={handleSubmit}
  1354. onModifiedSubmit={onModifiedSubmit}
  1355. disabled={disabled}
  1356. submitDisabled={submitDisabled}
  1357. allowSubmitWhenEmpty={allowSubmitWhenEmpty}
  1358. enterSubmits={enterSubmits}
  1359. />
  1360. <PromptHistoryPlugin entries={promptHistory} disabled={disabled} />
  1361. <EditablePlugin editable={!disabled} />
  1362. <E2ELexicalInputBridgePlugin inputTestId={inputTestId} />
  1363. <EditorApiPlugin editorApiRef={editorApiRef} />
  1364. <LeadingChineseSlashAliasPlugin disabled={disabled} />
  1365. <PasteCapturePlugin disabled={disabled} onPaste={onPaste} />
  1366. </div>
  1367. <SlashCommandPlugin
  1368. workspacePath={workspacePath}
  1369. workspaceIdentity={workspaceIdentity}
  1370. sessionId={skillCatalogSessionId ?? taskId}
  1371. provider={activeTaskProvider}
  1372. container={triggerPanelContainer}
  1373. disabled={disabled}
  1374. excludedCommandNames={excludedSlashCommandNames}
  1375. appCommands={appSlashCommands}
  1376. />
  1377. {enableMentionPanel ? (
  1378. <MentionPlugin
  1379. workspacePath={workspacePath}
  1380. workspaceIdentity={workspaceIdentity}
  1381. sessionId={skillCatalogSessionId ?? taskId}
  1382. provider={activeTaskProvider}
  1383. container={triggerPanelContainer}
  1384. disabled={disabled}
  1385. onWhiteboardMentionSelected={onWhiteboardMentionSelected}
  1386. />
  1387. ) : null}
  1388. </LexicalComposer>
  1389. </div>
  1390. );
  1391. }
  1392. /** 简单的错误边界 */
  1393. function LexicalErrorBoundary({ children }: { children: React.ReactNode }) {
  1394. return <>{children}</>;
  1395. }