MentionPlugin.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /* eslint-disable max-lines */
  2. import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
  3. import type { ZCodeProvider } from "@zcode/shared";
  4. import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
  5. import { createPortal } from "react-dom";
  6. import { PaletteIcon, WandSparkles } from "lucide-react";
  7. import {
  8. $createTextNode,
  9. $getSelection,
  10. $isRangeSelection,
  11. BLUR_COMMAND,
  12. COMMAND_PRIORITY_CRITICAL,
  13. COMMAND_PRIORITY_LOW,
  14. KEY_ARROW_DOWN_COMMAND,
  15. KEY_ARROW_UP_COMMAND,
  16. KEY_ENTER_COMMAND,
  17. KEY_ESCAPE_COMMAND,
  18. KEY_TAB_COMMAND,
  19. } from "lexical";
  20. import { useZCodeIntl } from "../i18n/IntlProvider.js";
  21. import {
  22. extractActivePromptInputTrigger,
  23. getActivePromptInputTokenTailLength,
  24. getPromptInputTriggerSignature,
  25. type ActivePromptInputTrigger,
  26. } from "../lib/promptInputTriggers.js";
  27. import { ContextMentionOptionContent } from "@/mentions/components/ContextMentionOptionContent.js";
  28. import { PluginMentionOptionContent } from "@/mentions/components/PluginMentionOptionContent.js";
  29. import {
  30. MentionPanel,
  31. type MentionPanelOption,
  32. type MentionPanelSection,
  33. } from "./components/MentionPanel.js";
  34. import {
  35. buildVisibleMentionGroups,
  36. hasMentionQuery,
  37. MENTION_DEFAULT_GROUP_PREVIEW_LIMIT,
  38. MENTION_FILES_ONLY_DEFAULT_PREVIEW_LIMIT,
  39. type MentionResultGroup,
  40. } from "./mentionSearch.js";
  41. import {
  42. getMentionPanelGroupOrder,
  43. getSessionMentionWorkspaceScope,
  44. type MentionPanelGroupId,
  45. } from "./mentionPanelRouting.js";
  46. import { $createPromptMentionNode } from "./nodes/PromptMentionNode.js";
  47. import { useFileMentionProvider } from "./providers/fileMentionProvider.js";
  48. import { usePluginsMentionProvider } from "./providers/pluginsMentionProvider.js";
  49. import { useSessionsMentionProvider } from "./providers/sessionsMentionProvider.js";
  50. import { useSkillsMentionProvider } from "./providers/skillsMentionProvider.js";
  51. import { useWhiteboardMentionProvider } from "./providers/whiteboardMentionProvider.js";
  52. import type { MentionItem } from "./mentionTypes.js";
  53. import {
  54. getActivePromptInputTokenReplacementRange,
  55. reconcileActivePromptInputTokenSnapshot,
  56. type ActivePromptInputTokenSnapshot,
  57. } from "./activePromptInputToken.js";
  58. import { getCurrentTextNodeSelection } from "./mentionHelpers.js";
  59. interface MentionPluginProps {
  60. container?: HTMLElement | null;
  61. workspacePath: string;
  62. workspaceIdentity?: string;
  63. /** 已有 Session 的 id;null/undefined = 新建草稿。决定 Plugins 分组的 catalog authority。 */
  64. sessionId?: string | null;
  65. disabled?: boolean;
  66. onWhiteboardMentionSelected?: (boardId: string) => void | Promise<void>;
  67. }
  68. export function getWrappedMentionIndex(
  69. currentIndex: number,
  70. delta: number,
  71. itemCount: number,
  72. ): number {
  73. if (itemCount <= 0) {
  74. return 0;
  75. }
  76. // mention 面板的上下键导航以前会把边界直接 clamp 到首/尾项。
  77. // 这里改成循环取模,保证按上键能从第一项跳到最后一项,按下键也能从最后一项回到第一项。
  78. return (currentIndex + delta + itemCount) % itemCount;
  79. }
  80. /**
  81. * 在循环导航的基础上跳过禁选项(V1 同名 Plugin 冲突项)。
  82. * 全部禁选时保持原地不动,Enter/Tab 的选择守卫会拒绝插入。
  83. */
  84. export function getNextEnabledMentionIndex(
  85. currentIndex: number,
  86. delta: number,
  87. items: ReadonlyArray<Pick<MentionItem, "disabled">>,
  88. ): number {
  89. if (items.length === 0) {
  90. return 0;
  91. }
  92. let next = getWrappedMentionIndex(currentIndex, delta, items.length);
  93. for (let step = 0; step < items.length; step++) {
  94. if (!items[next]?.disabled) {
  95. return next;
  96. }
  97. next = getWrappedMentionIndex(next, delta >= 0 ? 1 : -1, items.length);
  98. }
  99. return currentIndex;
  100. }
  101. /**
  102. * 候选首次出现或异步分组更新时,把选中项收敛到可选条目。
  103. * 根因:冲突 Plugin 保持可见后可能占据 flatItems[0];若仍默认选中 0,
  104. * 第一次 Enter/Tab 会命中禁选项并回落编辑器默认行为,而不是继续键盘导航。
  105. */
  106. export function coerceEnabledMentionIndex(
  107. currentIndex: number,
  108. items: ReadonlyArray<Pick<MentionItem, "disabled">>,
  109. ): number {
  110. if (items.length === 0) {
  111. return 0;
  112. }
  113. const boundedIndex = Math.min(Math.max(currentIndex, 0), items.length - 1);
  114. if (!items[boundedIndex]?.disabled) {
  115. return boundedIndex;
  116. }
  117. const firstEnabledIndex = items.findIndex((item) => !item.disabled);
  118. return firstEnabledIndex >= 0 ? firstEnabledIndex : boundedIndex;
  119. }
  120. /**
  121. * IME 组合期间(拼音未上屏)是否冻结 @ 面板重算:中间态字母会被当作 query 逐字过滤一轮,
  122. * 面板闪烁且中间态结果错误;composition 提交后 Lexical 会再派发一次 update 完成重算。
  123. * Android 例外:Chrome + Gboard 对拉丁词也走 composition(整词到空格才 compositionend),
  124. * 冻结会让手机 Web 的 @ 面板失去逐字过滤,因此 Android 保持实时重算。
  125. */
  126. export function shouldFreezeMentionRecalcWhileComposing(
  127. isComposing: boolean,
  128. userAgent: string,
  129. ): boolean {
  130. return isComposing && !/Android/i.test(userAgent);
  131. }
  132. export function MentionPlugin({
  133. workspacePath,
  134. workspaceIdentity,
  135. sessionId,
  136. provider,
  137. container,
  138. disabled = false,
  139. onWhiteboardMentionSelected,
  140. }: MentionPluginProps & { provider: ZCodeProvider }) {
  141. const [editor] = useLexicalComposerContext();
  142. const { intl } = useZCodeIntl();
  143. const [activeTrigger, setActiveTrigger] = useState<ActivePromptInputTrigger | null>(null);
  144. const [selectedIndex, setSelectedIndex] = useState(0);
  145. const dismissedSignatureRef = useRef<string | null>(null);
  146. const activeSignatureRef = useRef<string | null>(null);
  147. const activeTokenRef = useRef<ActivePromptInputTokenSnapshot | null>(null);
  148. const activeQuery = activeTrigger?.query ?? "";
  149. // 候选过滤会在渲染线程扫描大型 workspace;输入框与搜索共用同一个 query
  150. // 时,快速输入/删除会让每次按键都同步承担搜索成本。deferred query 只延后候选派生,
  151. // 不延后编辑器 token、触发器和最终插入,因此输入始终跟手,结果最终收敛到最新 query。
  152. const deferredActiveQuery = useDeferredValue(activeQuery);
  153. const hasActiveQuery = hasMentionQuery(activeQuery);
  154. const activeSignature = useMemo(
  155. () => getPromptInputTriggerSignature(activeTrigger),
  156. [activeTrigger],
  157. );
  158. const isOpen =
  159. !disabled &&
  160. (activeTrigger?.trigger === "@" ||
  161. activeTrigger?.trigger === "$" ||
  162. activeTrigger?.trigger === "#");
  163. const isContextTrigger = activeTrigger?.trigger === "@";
  164. const isSessionTrigger = activeTrigger?.trigger === "#";
  165. const isSkillTrigger = activeTrigger?.trigger === "$";
  166. // 修复说明:之前把 @ 面板拆成了两层,导致用户输入 query 后还要再确认一次,
  167. // 实际感受像“按回车之后才开始搜”。现在改成单层分组面板,query 一变化就直接展示各分组结果。
  168. const skillsResult = useSkillsMentionProvider(
  169. workspacePath,
  170. workspaceIdentity,
  171. sessionId ?? null,
  172. provider,
  173. deferredActiveQuery,
  174. isOpen && isSkillTrigger,
  175. false,
  176. intl.formatMessage({ id: "chat.mention.skills.empty" }),
  177. intl.formatMessage({ id: "chat.mention.skills.title" }),
  178. );
  179. const fileDefaultPreviewLimit = !hasActiveQuery
  180. ? MENTION_FILES_ONLY_DEFAULT_PREVIEW_LIMIT
  181. : MENTION_DEFAULT_GROUP_PREVIEW_LIMIT;
  182. const fileResult = useFileMentionProvider(
  183. workspacePath,
  184. workspaceIdentity,
  185. deferredActiveQuery,
  186. isOpen && isContextTrigger,
  187. intl.formatMessage({ id: "chat.mention.files.empty" }),
  188. intl.formatMessage({ id: "chat.mention.files.title" }),
  189. fileDefaultPreviewLimit,
  190. );
  191. const whiteboardResult = useWhiteboardMentionProvider(
  192. workspacePath,
  193. workspaceIdentity,
  194. deferredActiveQuery,
  195. isOpen && isContextTrigger && Boolean(onWhiteboardMentionSelected),
  196. intl.formatMessage({ id: "chat.mention.whiteboards.empty" }),
  197. intl.formatMessage({ id: "chat.mention.whiteboards.title" }),
  198. );
  199. const sessionsResult = useSessionsMentionProvider(
  200. provider,
  201. workspacePath,
  202. workspaceIdentity,
  203. deferredActiveQuery,
  204. isOpen && (isContextTrigger || isSessionTrigger),
  205. getSessionMentionWorkspaceScope(activeTrigger?.trigger),
  206. intl.formatMessage({ id: "chat.mention.sessions.empty" }),
  207. intl.formatMessage({ id: "chat.mention.sessions.title" }),
  208. );
  209. // Plugins 分组:新建草稿(sessionId=null)读 workspace
  210. // 当前 catalog,已有 Session 读 session-owned 冻结 catalog;冲突项由 provider 标记禁选。
  211. const pluginsResult = usePluginsMentionProvider(
  212. workspacePath,
  213. workspaceIdentity,
  214. sessionId ?? null,
  215. deferredActiveQuery,
  216. isOpen && isContextTrigger,
  217. intl.formatMessage({ id: "chat.mention.plugins.empty" }),
  218. intl.formatMessage({ id: "chat.mention.plugins.title" }),
  219. );
  220. const panelGroups = useMemo<MentionResultGroup<MentionItem>[]>(() => {
  221. const groupsById = {
  222. files: {
  223. id: "files",
  224. title: fileResult.title,
  225. items: fileResult.items,
  226. loading: fileResult.loading,
  227. errorText: fileResult.error?.message ?? null,
  228. emptyText: fileResult.emptyText,
  229. },
  230. plugins: {
  231. id: "plugins",
  232. title: pluginsResult.title,
  233. items: pluginsResult.items,
  234. loading: pluginsResult.loading,
  235. errorText: pluginsResult.error?.message ?? null,
  236. emptyText: pluginsResult.emptyText,
  237. },
  238. sessions: {
  239. id: "sessions",
  240. title: sessionsResult.title,
  241. items: sessionsResult.items,
  242. loading: sessionsResult.loading,
  243. errorText: sessionsResult.error?.message ?? null,
  244. emptyText: sessionsResult.emptyText,
  245. },
  246. skills: {
  247. id: "skills",
  248. title: skillsResult.title,
  249. items: skillsResult.items,
  250. loading: skillsResult.loading,
  251. errorText: skillsResult.error?.message ?? null,
  252. emptyText: skillsResult.emptyText,
  253. },
  254. whiteboards: {
  255. id: "whiteboards",
  256. title: whiteboardResult.title,
  257. items: whiteboardResult.items,
  258. loading: whiteboardResult.loading,
  259. errorText: whiteboardResult.error?.message ?? null,
  260. emptyText: whiteboardResult.emptyText,
  261. },
  262. } satisfies Record<MentionPanelGroupId, MentionResultGroup<MentionItem>>;
  263. // 产品约束:@ 固定为 Plugin → 文件 → 对话 → 画板;旧 # / $ 面板继续走
  264. // 原单分组 provider。这里仅重排发现入口,候选自身的 canonical markdown 不变。
  265. return buildVisibleMentionGroups(
  266. getMentionPanelGroupOrder(activeTrigger?.trigger).map((groupId) => groupsById[groupId]),
  267. );
  268. }, [
  269. fileResult.emptyText,
  270. fileResult.error,
  271. fileResult.items,
  272. fileResult.loading,
  273. fileResult.title,
  274. activeTrigger?.trigger,
  275. pluginsResult.emptyText,
  276. pluginsResult.error,
  277. pluginsResult.items,
  278. pluginsResult.loading,
  279. pluginsResult.title,
  280. sessionsResult.emptyText,
  281. sessionsResult.error,
  282. sessionsResult.items,
  283. sessionsResult.loading,
  284. sessionsResult.title,
  285. whiteboardResult.emptyText,
  286. whiteboardResult.error,
  287. whiteboardResult.items,
  288. whiteboardResult.loading,
  289. whiteboardResult.title,
  290. skillsResult.emptyText,
  291. skillsResult.error,
  292. skillsResult.items,
  293. skillsResult.loading,
  294. skillsResult.title,
  295. ]);
  296. const flatItems = useMemo(() => panelGroups.flatMap((group) => group.items), [panelGroups]);
  297. const panelSections = useMemo<MentionPanelSection[]>(
  298. () =>
  299. panelGroups.map((group) => ({
  300. id: group.id,
  301. title: group.title,
  302. options: group.items.map<MentionPanelOption>((item) => ({
  303. id: item.id,
  304. label: item.displayLabel ?? item.label,
  305. description: item.description,
  306. // 冲突 Plugin 等禁选项:面板可见但不可选择,行内展示原因(V1 fail closed)。
  307. disabled: item.disabled,
  308. disabledReason: item.disabledReason,
  309. // @ 面板之前只用 label/description 自己拼文件行,导致图标、文件名和路径展示
  310. // 跟输入框里的 mention token 不一致。这里统一复用 fileDisplay,让面板和 token 使用同一套文件语义展示。
  311. content:
  312. item.category === "files" ? (
  313. <ContextMentionOptionContent item={item} workspacePath={workspacePath} />
  314. ) : item.category === "skills" ? (
  315. <span className="min-w-0 flex flex-1 items-center gap-2">
  316. {/* Bugfix: skills 候选项需要和命令类项保持一致的主次信息密度,
  317. 这里保留图标 + 名称主文案,再把描述压成右侧弱信息,而不是额外占第二行。 */}
  318. <WandSparkles className="size-3.5 shrink-0 text-foreground" />
  319. <span className="shrink-0 whitespace-nowrap text-ui-base font-medium text-foreground">
  320. {item.label}
  321. </span>
  322. <span className="min-w-0 truncate text-ui-xs text-foreground-subtlest">
  323. {item.description}
  324. </span>
  325. </span>
  326. ) : item.category === "whiteboards" ? (
  327. <span className="min-w-0 flex flex-1 items-center gap-2">
  328. <PaletteIcon className="size-3.5 shrink-0 text-foreground" />
  329. <span className="shrink-0 whitespace-nowrap text-ui-base font-medium text-foreground">
  330. {item.label}
  331. </span>
  332. <span className="min-w-0 truncate text-ui-xs text-foreground-subtlest">
  333. {intl.formatMessage(
  334. { id: "chat.mention.whiteboards.strokeCount" },
  335. { count: item.description },
  336. )}
  337. </span>
  338. </span>
  339. ) : item.category === "sessions" ? (
  340. <ContextMentionOptionContent item={item} workspacePath={workspacePath} />
  341. ) : item.category === "plugins" ? (
  342. <PluginMentionOptionContent item={item} />
  343. ) : undefined,
  344. })),
  345. loading: group.loading,
  346. loadingText: intl.formatMessage({
  347. id: "chat.mention.category.loading",
  348. }),
  349. errorText: group.errorText,
  350. emptyText: group.emptyText,
  351. })),
  352. [intl, panelGroups, workspacePath],
  353. );
  354. useEffect(() => {
  355. activeSignatureRef.current = activeSignature;
  356. }, [activeSignature]);
  357. useEffect(() => {
  358. setSelectedIndex(0);
  359. }, [activeSignature]);
  360. useEffect(() => {
  361. setSelectedIndex((current) => coerceEnabledMentionIndex(current, flatItems));
  362. }, [flatItems]);
  363. useEffect(() => {
  364. if (!disabled) {
  365. return;
  366. }
  367. setActiveTrigger(null);
  368. setSelectedIndex(0);
  369. activeTokenRef.current = null;
  370. }, [disabled]);
  371. useEffect(() => {
  372. return editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, editorState }) => {
  373. if (
  374. shouldFreezeMentionRecalcWhileComposing(
  375. editor.isComposing(),
  376. typeof navigator === "undefined" ? "" : navigator.userAgent,
  377. )
  378. ) {
  379. return;
  380. }
  381. editorState.read(() => {
  382. if (disabled) {
  383. activeTokenRef.current = null;
  384. setActiveTrigger(null);
  385. return;
  386. }
  387. const selectionState = getCurrentTextNodeSelection();
  388. if (!selectionState) {
  389. activeTokenRef.current = null;
  390. dismissedSignatureRef.current = null;
  391. setActiveTrigger(null);
  392. return;
  393. }
  394. const nextActiveToken = reconcileActivePromptInputTokenSnapshot(
  395. activeTokenRef.current,
  396. selectionState,
  397. dirtyElements.size === 0 && dirtyLeaves.size === 0,
  398. );
  399. if (
  400. !nextActiveToken ||
  401. (nextActiveToken.trigger !== "@" &&
  402. nextActiveToken.trigger !== "$" &&
  403. nextActiveToken.trigger !== "#")
  404. ) {
  405. activeTokenRef.current = null;
  406. dismissedSignatureRef.current = null;
  407. setActiveTrigger(null);
  408. return;
  409. }
  410. activeTokenRef.current = nextActiveToken;
  411. const nextSignature = getPromptInputTriggerSignature(nextActiveToken);
  412. if (
  413. dismissedSignatureRef.current !== null &&
  414. dismissedSignatureRef.current !== nextSignature
  415. ) {
  416. dismissedSignatureRef.current = null;
  417. }
  418. if (dismissedSignatureRef.current === nextSignature) {
  419. setActiveTrigger(null);
  420. return;
  421. }
  422. setActiveTrigger((current) => {
  423. if (
  424. current?.trigger === nextActiveToken.trigger &&
  425. current.query === nextActiveToken.query
  426. ) {
  427. return current;
  428. }
  429. return {
  430. query: nextActiveToken.query,
  431. trigger: nextActiveToken.trigger,
  432. };
  433. });
  434. });
  435. });
  436. }, [disabled, editor]);
  437. const insertMentionItem = useCallback(
  438. (item: MentionItem) => {
  439. if (item.category === "whiteboards" && onWhiteboardMentionSelected) {
  440. editor.update(() => {
  441. const selectionState = getCurrentTextNodeSelection();
  442. if (!selectionState) {
  443. return;
  444. }
  445. const snapshotRange = getActivePromptInputTokenReplacementRange(
  446. activeTokenRef.current,
  447. selectionState,
  448. );
  449. const activeMentionTrigger = snapshotRange
  450. ? activeTokenRef.current
  451. : extractActivePromptInputTrigger(selectionState.textBeforeCursor);
  452. if (
  453. !activeMentionTrigger ||
  454. (activeMentionTrigger.trigger !== "@" && activeMentionTrigger.trigger !== "$")
  455. ) {
  456. return;
  457. }
  458. const tokenStart =
  459. snapshotRange?.start ??
  460. selectionState.cursorOffset - activeMentionTrigger.query.length - 1;
  461. const tokenEnd =
  462. snapshotRange?.end ??
  463. selectionState.cursorOffset +
  464. getActivePromptInputTokenTailLength(
  465. activeMentionTrigger,
  466. selectionState.textAfterCursor,
  467. [item.label, item.value, item.markdown],
  468. );
  469. selectionState.selection.setTextNodeRange(
  470. selectionState.node,
  471. tokenStart,
  472. selectionState.node,
  473. tokenEnd,
  474. );
  475. selectionState.selection.insertText("");
  476. });
  477. dismissedSignatureRef.current = null;
  478. activeTokenRef.current = null;
  479. setActiveTrigger(null);
  480. setSelectedIndex(0);
  481. void onWhiteboardMentionSelected(item.value);
  482. requestAnimationFrame(() => {
  483. editor.focus();
  484. });
  485. return;
  486. }
  487. editor.update(() => {
  488. const selectionState = getCurrentTextNodeSelection();
  489. if (!selectionState) {
  490. return;
  491. }
  492. const snapshotRange = getActivePromptInputTokenReplacementRange(
  493. activeTokenRef.current,
  494. selectionState,
  495. );
  496. const activeMentionTrigger = snapshotRange
  497. ? activeTokenRef.current
  498. : extractActivePromptInputTrigger(selectionState.textBeforeCursor);
  499. if (
  500. !activeMentionTrigger ||
  501. (activeMentionTrigger.trigger !== "@" &&
  502. activeMentionTrigger.trigger !== "$" &&
  503. activeMentionTrigger.trigger !== "#")
  504. ) {
  505. return;
  506. }
  507. const tokenStart =
  508. snapshotRange?.start ??
  509. selectionState.cursorOffset - activeMentionTrigger.query.length - 1;
  510. const tokenEnd =
  511. snapshotRange?.end ??
  512. selectionState.cursorOffset +
  513. getActivePromptInputTokenTailLength(
  514. activeMentionTrigger,
  515. selectionState.textAfterCursor,
  516. [item.label, item.value, item.markdown],
  517. );
  518. selectionState.selection.setTextNodeRange(
  519. selectionState.node,
  520. tokenStart,
  521. selectionState.node,
  522. tokenEnd,
  523. );
  524. const trailingWhitespace = $createTextNode(" ");
  525. selectionState.selection.insertNodes([
  526. $createPromptMentionNode({
  527. id: item.id,
  528. category: item.category,
  529. label: item.label,
  530. value: item.value,
  531. markdown: item.markdown,
  532. description: item.description,
  533. data: item.data,
  534. }),
  535. trailingWhitespace,
  536. ]);
  537. trailingWhitespace.selectEnd();
  538. });
  539. dismissedSignatureRef.current = null;
  540. activeTokenRef.current = null;
  541. setActiveTrigger(null);
  542. setSelectedIndex(0);
  543. requestAnimationFrame(() => {
  544. editor.focus();
  545. });
  546. },
  547. [editor, onWhiteboardMentionSelected],
  548. );
  549. const selectOption = useCallback(
  550. (index: number) => {
  551. const nextItem = flatItems[index];
  552. if (!nextItem) {
  553. return false;
  554. }
  555. // 禁选项(同名冲突 Plugin)不可插入:键盘 Enter/Tab 与鼠标点击都走这里统一拒绝。
  556. if (nextItem.disabled) {
  557. return false;
  558. }
  559. insertMentionItem(nextItem);
  560. return true;
  561. },
  562. [flatItems, insertMentionItem],
  563. );
  564. useEffect(() => {
  565. if (!isOpen) {
  566. return;
  567. }
  568. const unregisterDown = editor.registerCommand(
  569. KEY_ARROW_DOWN_COMMAND,
  570. (event) => {
  571. if (flatItems.length === 0) {
  572. return false;
  573. }
  574. event?.preventDefault();
  575. event?.stopPropagation();
  576. setSelectedIndex((prev) => getNextEnabledMentionIndex(prev, 1, flatItems));
  577. return true;
  578. },
  579. COMMAND_PRIORITY_CRITICAL,
  580. );
  581. const unregisterUp = editor.registerCommand(
  582. KEY_ARROW_UP_COMMAND,
  583. (event) => {
  584. if (flatItems.length === 0) {
  585. return false;
  586. }
  587. event?.preventDefault();
  588. event?.stopPropagation();
  589. setSelectedIndex((prev) => getNextEnabledMentionIndex(prev, -1, flatItems));
  590. return true;
  591. },
  592. COMMAND_PRIORITY_CRITICAL,
  593. );
  594. const unregisterEnter = editor.registerCommand(
  595. KEY_ENTER_COMMAND,
  596. (event) => {
  597. if (!selectOption(selectedIndex)) {
  598. return false;
  599. }
  600. event?.preventDefault();
  601. event?.stopPropagation();
  602. return true;
  603. },
  604. COMMAND_PRIORITY_CRITICAL,
  605. );
  606. const unregisterTab = editor.registerCommand(
  607. KEY_TAB_COMMAND,
  608. (event) => {
  609. if (!selectOption(selectedIndex)) {
  610. return false;
  611. }
  612. event?.preventDefault();
  613. event?.stopPropagation();
  614. return true;
  615. },
  616. COMMAND_PRIORITY_CRITICAL,
  617. );
  618. const unregisterEscape = editor.registerCommand(
  619. KEY_ESCAPE_COMMAND,
  620. (event) => {
  621. event?.preventDefault();
  622. event?.stopPropagation();
  623. dismissedSignatureRef.current = activeSignatureRef.current;
  624. setActiveTrigger(null);
  625. setSelectedIndex(0);
  626. return true;
  627. },
  628. COMMAND_PRIORITY_CRITICAL,
  629. );
  630. // 调试说明:先注释掉 blur 自动关闭逻辑,方便观察 panel 在焦点切换时的实际行为。
  631. // 当前只移除“失焦即消失”这一路径,Esc / 选中项 / trigger 失效等关闭逻辑仍然保留。
  632. const unregisterBlur = editor.registerCommand(
  633. BLUR_COMMAND,
  634. () => {
  635. dismissedSignatureRef.current = null;
  636. activeTokenRef.current = null;
  637. setActiveTrigger(null);
  638. setSelectedIndex(0);
  639. return false;
  640. },
  641. COMMAND_PRIORITY_LOW,
  642. );
  643. return () => {
  644. unregisterDown();
  645. unregisterUp();
  646. unregisterEnter();
  647. unregisterTab();
  648. unregisterEscape();
  649. unregisterBlur();
  650. };
  651. }, [editor, flatItems, isOpen, selectOption, selectedIndex]);
  652. const panelTitle = intl.formatMessage({ id: "chat.mention.title" });
  653. const panelDescription = hasActiveQuery
  654. ? ""
  655. : activeTrigger?.trigger === "#"
  656. ? intl.formatMessage({ id: "chat.mention.sessions.searchHint" })
  657. : activeTrigger?.trigger === "$"
  658. ? intl.formatMessage({ id: "chat.mention.skills.searchHint" })
  659. : intl.formatMessage({ id: "chat.mention.searchHint" });
  660. const panelEmptyText = hasActiveQuery
  661. ? intl.formatMessage({ id: "chat.mention.emptyResults" })
  662. : "";
  663. if (!isOpen || !container) {
  664. return null;
  665. }
  666. return createPortal(
  667. <MentionPanel
  668. title={panelTitle}
  669. description={panelDescription}
  670. trigger={activeTrigger?.trigger ?? "@"}
  671. sections={panelSections}
  672. emptyText={panelEmptyText}
  673. selectedIndex={selectedIndex}
  674. hasActiveQuery={hasActiveQuery}
  675. onSelect={selectOption}
  676. />,
  677. container,
  678. );
  679. }