Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(chat-input): full-width slash/mention menus via upstream (#16438)

Innei805b15a73e35
diff --git a/package.json b/package.json
index 27ba6bfb0e5..954b863174e 100644
--- a/package.json
+++ b/package.json
@@ -291,7 +291,7 @@
"@lobehub/analytics": "^1.6.2",
"@lobehub/charts": "^5.0.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
- "@lobehub/editor": "^4.17.1",
+ "@lobehub/editor": "^4.18.1",
"@lobehub/icons": "^5.0.0",
"@lobehub/market-sdk": "0.39.1",
"@lobehub/tts": "^5.1.2",
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/CategoryView.tsx b/src/features/ChatInput/InputEditor/MentionMenu/CategoryView.tsx
deleted file mode 100644
index b7c706ac826..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/CategoryView.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { ISlashMenuOption } from '@lobehub/editor';
-import { ArrowLeft } from 'lucide-react';
-import type { MouseEvent } from 'react';
-import { memo } from 'react';
-
-import MenuItem from './MenuItem';
-import { styles } from './style';
-import type { MentionCategory } from './types';
-
-interface CategoryViewProps {
- activeKey: string | null;
- category: MentionCategory;
- onBack: () => void;
- onSelectItem: (item: ISlashMenuOption) => void;
-}
-
-const CategoryView = memo<CategoryViewProps>(({ category, activeKey, onSelectItem, onBack }) => {
- const handleMouseDown = (event: MouseEvent<HTMLDivElement>) => {
- event.preventDefault();
- };
-
- return (
- <>
- <div
- className={styles.backHeader}
- role="presentation"
- onClick={onBack}
- onMouseDown={handleMouseDown}
- >
- <ArrowLeft size={14} />
- {category.label}
- </div>
- <div className={styles.divider} />
- <div className={styles.scrollArea}>
- {category.items.map((item) => (
- <MenuItem
- active={String(item.key) === activeKey}
- item={item}
- key={item.key}
- onClick={onSelectItem}
- />
- ))}
- </div>
- </>
- );
-});
-
-CategoryView.displayName = 'CategoryView';
-
-export default CategoryView;
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/HomeView.tsx b/src/features/ChatInput/InputEditor/MentionMenu/HomeView.tsx
deleted file mode 100644
index cdb060f82be..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/HomeView.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { ISlashMenuOption } from '@lobehub/editor';
-import { ChevronRight } from 'lucide-react';
-import { memo } from 'react';
-
-import MenuItem from './MenuItem';
-import { styles } from './style';
-import { isCategoryEntry } from './types';
-
-interface HomeViewProps {
- activeKey: string | null;
- dividerIndex: number;
- onSelectItem: (item: ISlashMenuOption) => void;
- visibleItems: ISlashMenuOption[];
-}
-
-const HomeView = memo<HomeViewProps>(({ visibleItems, activeKey, onSelectItem, dividerIndex }) => {
- return (
- <div className={styles.scrollArea}>
- {visibleItems.map((item, idx) => {
- const isCategory = isCategoryEntry(String(item.key));
- const showDivider = idx === dividerIndex && dividerIndex > 0;
-
- return (
- <div key={item.key}>
- {showDivider && <div className={styles.divider} />}
- <MenuItem
- active={String(item.key) === activeKey}
- item={item}
- extra={
- isCategory ? (
- <span className={styles.categoryExtra}>
- {(item as any).metadata?.count}
- <ChevronRight size={14} />
- </span>
- ) : undefined
- }
- onClick={onSelectItem}
- />
- </div>
- );
- })}
- </div>
- );
-});
-
-HomeView.displayName = 'HomeView';
-
-export default HomeView;
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/MenuItem.tsx b/src/features/ChatInput/InputEditor/MentionMenu/MenuItem.tsx
deleted file mode 100644
index a7a43ef170b..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/MenuItem.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import type { ISlashMenuOption } from '@lobehub/editor';
-import { cx } from 'antd-style';
-import { createElement, isValidElement, type MouseEvent, type ReactNode } from 'react';
-import { memo } from 'react';
-
-import { compactDirectoryTail, compactFileName } from './localFileDisplay';
-import { styles } from './style';
-
-interface MenuItemProps {
- active?: boolean;
- extra?: ReactNode;
- item: ISlashMenuOption;
- onClick: (item: ISlashMenuOption) => void;
-}
-
-const MenuItem = memo<MenuItemProps>(({ item, active, extra, onClick }) => {
- const handleMouseDown = (event: MouseEvent<HTMLDivElement>) => {
- event.preventDefault();
- };
- const metadata = item.metadata as Record<string, unknown> | undefined;
- const isLocalFile = metadata?.type === 'localFile';
- const localFileName = String(metadata?.name ?? item.label);
- const localFilePath =
- typeof metadata?.relativePath === 'string'
- ? metadata.relativePath
- : typeof metadata?.path === 'string'
- ? metadata.path
- : '';
- const directoryTail = isLocalFile
- ? compactDirectoryTail(localFilePath, localFileName, metadata?.isDirectory === true)
- : '';
-
- return (
- <div
- aria-selected={active}
- data-key={item.key}
- id={`mention-item-${item.key}`}
- role="option"
- className={cx(
- styles.item,
- active ? styles.itemActive : undefined,
- extra ? styles.itemWithCategoryExtra : undefined,
- )}
- onClick={() => onClick(item)}
- onMouseDown={handleMouseDown}
- >
- {item.icon && (
- <span className={styles.itemIcon}>
- {isValidElement(item.icon)
- ? item.icon
- : typeof item.icon === 'function'
- ? createElement(item.icon)
- : item.icon}
- </span>
- )}
- {isLocalFile ? (
- <>
- <span className={styles.localFileName} title={localFileName}>
- {compactFileName(localFileName)}
- </span>
- {directoryTail && (
- <span className={styles.localFilePath} title={localFilePath}>
- {directoryTail}
- </span>
- )}
- </>
- ) : (
- <>
- <span className={styles.itemLabel}>{item.label}</span>
- {extra}
- </>
- )}
- </div>
- );
-});
-
-MenuItem.displayName = 'MenuItem';
-
-export default MenuItem;
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx b/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx
deleted file mode 100644
index 800b313cdca..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import type { ISlashMenuOption } from '@lobehub/editor';
-import { memo } from 'react';
-
-import MenuItem from './MenuItem';
-import { styles } from './style';
-
-interface SearchViewProps {
- activeKey: string | null;
- onSelectItem: (item: ISlashMenuOption) => void;
- options: ISlashMenuOption[];
-}
-
-const SEARCH_RESULT_CATEGORY_LABEL: Record<string, string> = {
- agent: 'Agent',
- localFile: 'File',
- member: 'Member',
- skill: 'Skill',
- tool: 'Tool',
- topic: 'Topic',
-};
-
-const getSearchResultCategoryLabel = (item: ISlashMenuOption): string | undefined => {
- const metadata = item.metadata as Record<string, unknown> | undefined;
- const type = metadata?.type;
-
- if (type === 'localFile') {
- if (typeof metadata?.relativePath === 'string') return metadata.relativePath;
- if (typeof metadata?.path === 'string') return metadata.path;
- }
-
- return typeof type === 'string' ? SEARCH_RESULT_CATEGORY_LABEL[type] : undefined;
-};
-
-const SearchView = memo<SearchViewProps>(({ options, activeKey, onSelectItem }) => {
- if (options.length === 0) {
- return <div className={styles.empty}>No results</div>;
- }
-
- return (
- <div className={styles.scrollArea}>
- {options.map((item) => {
- const categoryLabel = getSearchResultCategoryLabel(item);
- const isLocalFile = item.metadata?.type === 'localFile';
-
- return (
- <MenuItem
- active={String(item.key) === activeKey}
- item={item}
- key={item.key}
- extra={
- categoryLabel && !isLocalFile ? (
- <span className={styles.categoryExtra}>{categoryLabel}</span>
- ) : undefined
- }
- onClick={onSelectItem}
- />
- );
- })}
- </div>
- );
-});
-
-SearchView.displayName = 'SearchView';
-
-export default SearchView;
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/index.tsx b/src/features/ChatInput/InputEditor/MentionMenu/index.tsx
deleted file mode 100644
index cf582db86c1..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/index.tsx
+++ /dev/null
@@ -1,195 +0,0 @@
-import type { ISlashMenuOption, ISlashOption } from '@lobehub/editor';
-import { LOBE_THEME_APP_ID } from '@lobehub/ui';
-import type { FC, RefObject } from 'react';
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
-
-import CategoryView from './CategoryView';
-import HomeView from './HomeView';
-import SearchView from './SearchView';
-import { styles } from './style';
-import type { MentionCategory, MentionCategoryId, MentionMenuState } from './types';
-import { CATEGORY_KEY_PREFIX, getCategoryIdFromKey, isCategoryEntry } from './types';
-import { useKeyboardNav } from './useKeyboardNav';
-import { useMenuPosition } from './useMenuPosition';
-
-const RECENT_COUNT = 8;
-
-interface MenuRenderProps {
- activeKey: string | null;
- loading?: boolean;
- onSelect?: (option: ISlashMenuOption) => void;
- open?: boolean;
- options: Array<ISlashOption>;
- setActiveKey: (key: string | null) => void;
-}
-
-const getRecentItems = (options: ISlashMenuOption[], count: number): ISlashMenuOption[] => {
- return [...options]
- .sort((a, b) => {
- const ta = (a as any).metadata?.timestamp || 0;
- const tb = (b as any).metadata?.timestamp || 0;
- return tb - ta;
- })
- .slice(0, count);
-};
-
-const buildCategoryEntries = (categories: MentionCategory[]): ISlashMenuOption[] =>
- categories
- .filter((c) => c.items.length > 0)
- .map((cat) => ({
- icon: cat.icon,
- key: `${CATEGORY_KEY_PREFIX}${cat.id}`,
- label: cat.label,
- metadata: { categoryId: cat.id, count: cat.items.length, type: '__category__' },
- }));
-
-export const createMentionMenu = (
- stateRef: RefObject<MentionMenuState>,
- categoriesRef: RefObject<MentionCategory[]>,
-): FC<MenuRenderProps> => {
- const MentionMenu: FC<MenuRenderProps> = memo(
- ({ activeKey, onSelect, open, options, setActiveKey }) => {
- const menuRef = useRef<HTMLDivElement>(null);
- const [viewMode, setViewMode] = useState<'home' | 'category'>('home');
- const [selectedCategoryId, setSelectedCategoryId] = useState<MentionCategoryId | null>(null);
-
- const isSearch = stateRef.current.isSearch;
- const categories = categoriesRef.current;
-
- const position = useMenuPosition(menuRef, !!open);
-
- // Reset on open
- useEffect(() => {
- if (open) {
- setViewMode('home');
- setSelectedCategoryId(null);
- }
- }, [open]);
-
- // Filter options to only ISlashMenuOption (exclude dividers)
- const menuOptions = useMemo(
- () => options.filter((o): o is ISlashMenuOption => 'key' in o && !!o.key),
- [options],
- );
-
- // Category entries as pseudo-items for keyboard navigation
- const categoryEntries = useMemo(() => buildCategoryEntries(categories), [categories]);
-
- // Derive visible items for current view
- const visibleItems = useMemo((): ISlashMenuOption[] => {
- if (isSearch) return menuOptions;
-
- if (viewMode === 'category' && selectedCategoryId) {
- const cat = categories.find((c) => c.id === selectedCategoryId);
- return cat?.items || [];
- }
-
- // Home: recent items + category entries (unified list)
- const recent = getRecentItems(menuOptions, RECENT_COUNT);
- return [...recent, ...categoryEntries];
- }, [menuOptions, isSearch, viewMode, selectedCategoryId, categories, categoryEntries]);
-
- // Sync activeKey on view/options change
- useEffect(() => {
- if (open && visibleItems.length > 0) {
- setActiveKey(String(visibleItems[0].key));
- }
- }, [open, viewMode, selectedCategoryId, isSearch, visibleItems, setActiveKey]);
-
- const handleSelectCategory = useCallback((id: MentionCategoryId) => {
- setViewMode('category');
- setSelectedCategoryId(id);
- }, []);
-
- const handleBack = useCallback(() => {
- setViewMode('home');
- setSelectedCategoryId(null);
- }, []);
-
- // Item selection — intercept category entries
- const handleSelectItem = useCallback(
- (item: ISlashMenuOption) => {
- const key = String(item.key);
- if (isCategoryEntry(key)) {
- handleSelectCategory(getCategoryIdFromKey(key));
- return;
- }
- onSelect?.(item);
- },
- [onSelect, handleSelectCategory],
- );
-
- const effectiveMode = isSearch ? 'search' : viewMode;
-
- useKeyboardNav({
- activeKey,
- mode: effectiveMode === 'search' ? 'search' : viewMode,
- onBack: handleBack,
- onSelect: handleSelectItem,
- open: !!open,
- setActiveKey,
- visibleItems,
- });
-
- const lobeApp = useMemo(
- () => document.getElementById(LOBE_THEME_APP_ID) ?? document.body,
- [],
- );
- if (!open) return null;
-
- const selectedCategory = selectedCategoryId
- ? categories.find((c) => c.id === selectedCategoryId)
- : null;
-
- // Index where category entries start (for divider placement in HomeView)
- const recentCount =
- effectiveMode === 'home' ? visibleItems.length - categoryEntries.length : 0;
-
- const menu = (
- <div
- aria-activedescendant={activeKey ? `mention-item-${activeKey}` : undefined}
- className={styles.container}
- ref={menuRef}
- role="listbox"
- style={{
- left: position.x,
- opacity: position.visible ? 1 : 0,
- pointerEvents: position.visible ? 'auto' : 'none',
- top: position.y,
- visibility: position.visible ? 'visible' : 'hidden',
- }}
- >
- {effectiveMode === 'home' && (
- <HomeView
- activeKey={activeKey}
- dividerIndex={recentCount}
- visibleItems={visibleItems}
- onSelectItem={handleSelectItem}
- />
- )}
- {effectiveMode === 'category' && selectedCategory && (
- <CategoryView
- activeKey={activeKey}
- category={selectedCategory}
- onBack={handleBack}
- onSelectItem={handleSelectItem}
- />
- )}
- {effectiveMode === 'search' && (
- <SearchView
- activeKey={activeKey}
- options={visibleItems}
- onSelectItem={handleSelectItem}
- />
- )}
- </div>
- );
-
- return createPortal(menu, lobeApp);
- },
- );
-
- MentionMenu.displayName = 'MentionMenu';
- return MentionMenu;
-};
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/style.ts b/src/features/ChatInput/InputEditor/MentionMenu/style.ts
deleted file mode 100644
index 7e14a013272..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/style.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { createStaticStyles } from 'antd-style';
-
-export const styles = createStaticStyles(({ css, cssVar }) => ({
- backHeader: css`
- cursor: pointer;
-
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 6px;
- padding-inline: 12px;
-
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorTextSecondary};
-
- &:hover {
- color: ${cssVar.colorText};
- }
- `,
- categoryExtra: css`
- overflow: hidden;
- display: flex;
- flex-shrink: 0;
- gap: 2px;
- align-items: center;
-
- max-width: 180px;
-
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- container: css`
- position: fixed;
- z-index: 99999;
-
- display: flex;
- flex-direction: column;
-
- min-width: 260px;
- max-width: 360px;
- max-height: 360px;
- padding: 4px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 10px;
-
- background: ${cssVar.colorBgElevated};
- box-shadow: ${cssVar.boxShadowSecondary};
- `,
- divider: css`
- height: 1px;
- margin-block: 4px;
- margin-inline: 8px;
- background: ${cssVar.colorBorder};
- `,
- empty: css`
- padding-block: 16px;
- padding-inline: 12px;
-
- font-size: 13px;
- color: ${cssVar.colorTextQuaternary};
- text-align: center;
- `,
- item: css`
- cursor: pointer;
-
- display: flex;
- gap: 8px;
- align-items: center;
-
- padding-block: 6px;
- padding-inline: 12px;
- border-radius: 6px;
-
- font-size: 13px;
-
- transition: background 0.1s;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- itemWithCategoryExtra: css`
- padding-inline-end: 6px;
- `,
- itemActive: css`
- background: ${cssVar.colorFillSecondary};
- `,
- itemIcon: css`
- overflow: hidden;
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- width: 24px;
- height: 24px;
- border-radius: 6px;
- `,
- itemLabel: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 0;
-
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- localFileName: css`
- overflow: hidden;
- flex: 1;
-
- min-width: 88px;
-
- font-size: 13px;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- localFilePath: css`
- overflow: hidden;
- flex: 0 1 auto;
-
- max-width: 190px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- text-align: end;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- scrollArea: css`
- overflow-y: auto;
- flex: 1;
- margin: -4px;
- padding: 4px;
- `,
-}));
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/types.ts b/src/features/ChatInput/InputEditor/MentionMenu/types.ts
index 817d1084597..6e21b7a7be9 100644
--- a/src/features/ChatInput/InputEditor/MentionMenu/types.ts
+++ b/src/features/ChatInput/InputEditor/MentionMenu/types.ts
@@ -9,15 +9,3 @@ export interface MentionCategory {
items: ISlashMenuOption[];
label: string;
}
-
-export interface MentionMenuState {
- isSearch: boolean;
- matchingString: string;
-}
-
-export const CATEGORY_KEY_PREFIX = '__category__';
-
-export const isCategoryEntry = (key: string): boolean => key.startsWith(CATEGORY_KEY_PREFIX);
-
-export const getCategoryIdFromKey = (key: string): MentionCategoryId =>
- key.slice(CATEGORY_KEY_PREFIX.length) as MentionCategoryId;
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/useKeyboardNav.ts b/src/features/ChatInput/InputEditor/MentionMenu/useKeyboardNav.ts
deleted file mode 100644
index 89d655630dc..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/useKeyboardNav.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { ISlashMenuOption } from '@lobehub/editor';
-import { useEffect } from 'react';
-
-interface KeyboardNavOptions {
- activeKey: string | null;
- mode: 'home' | 'category' | 'search';
- onBack: () => void;
- onSelect: (option: ISlashMenuOption) => void;
- open: boolean;
- setActiveKey: (key: string | null) => void;
- visibleItems: ISlashMenuOption[];
-}
-
-export const useKeyboardNav = ({
- open,
- visibleItems,
- activeKey,
- setActiveKey,
- onSelect,
- onBack,
- mode,
-}: KeyboardNavOptions) => {
- useEffect(() => {
- if (!open || visibleItems.length === 0) return;
-
- const handler = (e: KeyboardEvent) => {
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
- e.preventDefault();
- e.stopImmediatePropagation();
-
- const idx = visibleItems.findIndex((i) => String(i.key) === activeKey);
- const next =
- e.key === 'ArrowDown'
- ? (idx + 1) % visibleItems.length
- : (idx - 1 + visibleItems.length) % visibleItems.length;
-
- const nextKey = String(visibleItems[next].key);
- setActiveKey(nextKey);
-
- // Scroll active item into view
- requestAnimationFrame(() => {
- document.getElementById(`mention-item-${nextKey}`)?.scrollIntoView({ block: 'nearest' });
- });
- }
-
- if (e.key === 'Enter' || e.key === 'Tab') {
- const item = visibleItems.find((i) => String(i.key) === activeKey);
- if (item) {
- e.preventDefault();
- e.stopImmediatePropagation();
- onSelect(item);
- }
- }
-
- if (e.key === 'Escape' && mode === 'category') {
- e.preventDefault();
- e.stopImmediatePropagation();
- onBack();
- }
- // Home/Search Escape: do NOT intercept → let editor close the menu
- };
-
- document.addEventListener('keydown', handler, true); // capture phase
- return () => document.removeEventListener('keydown', handler, true);
- }, [open, visibleItems, activeKey, setActiveKey, onSelect, onBack, mode]);
-};
diff --git a/src/features/ChatInput/InputEditor/MentionMenu/useMenuPosition.ts b/src/features/ChatInput/InputEditor/MentionMenu/useMenuPosition.ts
deleted file mode 100644
index ccbc5bf15b9..00000000000
--- a/src/features/ChatInput/InputEditor/MentionMenu/useMenuPosition.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import type { VirtualElement } from '@floating-ui/react';
-import { autoUpdate, flip, offset, shift, useFloating } from '@floating-ui/react';
-import type { RefObject } from 'react';
-import { useLayoutEffect, useState } from 'react';
-
-const MENU_GAP = 4;
-const VIEWPORT_MARGIN = 8;
-
-interface MenuPosition {
- visible: boolean;
-}
-
-const getSelectionRect = () => {
- const selection = window.getSelection();
-
- if (!selection?.rangeCount) return new DOMRect();
-
- return selection.getRangeAt(0).getBoundingClientRect();
-};
-
-const hasActiveEditorSelection = () => {
- const selection = window.getSelection();
- if (!selection?.rangeCount) return false;
-
- const activeElement = document.activeElement;
- if (!(activeElement instanceof HTMLElement)) return false;
-
- const editor = activeElement.closest('[data-lexical-editor="true"]');
- if (!(editor instanceof HTMLElement)) return false;
-
- const anchorNode = selection.anchorNode;
- if (!anchorNode) return false;
-
- const anchorElement = anchorNode instanceof Element ? anchorNode : anchorNode.parentElement;
-
- return !!anchorElement && editor.contains(anchorElement);
-};
-
-const createCaretVirtualElement = (): VirtualElement => ({
- getBoundingClientRect: () => getSelectionRect(),
-});
-
-export const useMenuPosition = (menuRef: RefObject<HTMLDivElement | null>, open: boolean) => {
- const { refs, update, x, y } = useFloating({
- middleware: [
- offset(MENU_GAP),
- flip({ fallbackPlacements: ['bottom-start'] }),
- shift({ crossAxis: true, mainAxis: false, padding: VIEWPORT_MARGIN }),
- ],
- placement: 'top-start',
- strategy: 'fixed',
- });
- const [position, setPosition] = useState<MenuPosition>({ visible: false });
-
- useLayoutEffect(() => {
- if (!open || !menuRef.current) {
- setPosition((prev) => ({ ...prev, visible: false }));
- return;
- }
-
- const menu = menuRef.current;
- const reference = createCaretVirtualElement();
- refs.setFloating(menu);
- refs.setPositionReference(reference);
-
- const updatePosition = async () => {
- if (!hasActiveEditorSelection()) {
- setPosition({ visible: false });
- return;
- }
-
- await update();
- setPosition({ visible: true });
- };
-
- const scheduleUpdate = () => {
- requestAnimationFrame(() => {
- void updatePosition();
- });
- };
-
- const cleanupAutoUpdate = autoUpdate(reference, menu, scheduleUpdate, {
- animationFrame: true,
- });
-
- document.addEventListener('focusin', scheduleUpdate);
- document.addEventListener('focusout', scheduleUpdate);
- document.addEventListener('selectionchange', scheduleUpdate);
- scheduleUpdate();
-
- return () => {
- cleanupAutoUpdate();
- document.removeEventListener('focusin', scheduleUpdate);
- document.removeEventListener('focusout', scheduleUpdate);
- document.removeEventListener('selectionchange', scheduleUpdate);
- };
- }, [menuRef, open, refs, update]);
-
- return { visible: position.visible, x: x ?? 0, y: y ?? 0 };
-};
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index 295271a1779..a6cb067ba32 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -100,7 +100,6 @@ vi.mock('@lobehub/editor/react', () => {
return {
Editor,
- FloatMenu: vi.fn(() => null),
useEditorState: vi.fn(() => ({ isEmpty: true })),
};
});
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 2a76a015cc6..f4d3efc5369 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -9,8 +9,8 @@ import {
} from '@lobechat/prompts';
import { isCommandPressed } from '@lobechat/utils';
import type { IEditor } from '@lobehub/editor';
-import { INSERT_MENTION_COMMAND, ReactAutoCompletePlugin, ReactMathPlugin } from '@lobehub/editor';
-import { Editor, FloatMenu, useEditorState } from '@lobehub/editor/react';
+import { INSERT_MENTION_COMMAND, ReactAutoCompletePlugin } from '@lobehub/editor';
+import { Editor, useEditorState } from '@lobehub/editor/react';
import { combineKeys } from '@lobehub/ui';
import { css, cx } from 'antd-style';
import Fuse from 'fuse.js';
@@ -42,8 +42,6 @@ import {
useSlashActionItems,
} from './ActionTag';
import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';
-import { createMentionMenu } from './MentionMenu';
-import type { MentionMenuState } from './MentionMenu/types';
import { mentionFilledClassName } from './mentionStyle';
import Placeholder, { type PlaceholderVariant } from './Placeholder';
import { CHAT_INPUT_EMBED_PLUGINS, createChatInputRichPlugins } from './plugins';
@@ -101,9 +99,6 @@ const InputEditor = memo<{
// --- Category-based mention system ---
const categories = useMentionCategories();
- const stateRef = useRef<MentionMenuState>({ isSearch: false, matchingString: '' });
- const categoriesRef = useRef(categories);
- categoriesRef.current = categories;
// Get agent's model info for vision support check and handle paste upload
const agentId = useAgentId();
@@ -131,7 +126,6 @@ const InputEditor = memo<{
search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
) => {
if (search?.matchingString) {
- stateRef.current = { isSearch: true, matchingString: search.matchingString };
const [localFileItems, mentionItems] = await Promise.all([
searchLocalFiles(search.matchingString),
Promise.resolve(fuse.search(search.matchingString).map((r) => r.item)),
@@ -139,14 +133,11 @@ const InputEditor = memo<{
return [...localFileItems, ...mentionItems];
}
- stateRef.current = { isSearch: false, matchingString: '' };
return [...allMentionItems];
},
[allMentionItems, fuse, searchLocalFiles],
);
- const MentionMenuComp = useMemo(() => createMentionMenu(stateRef, categoriesRef), []);
-
const enableMention = isMentionEnabled && (allMentionItems.length > 0 || enableLocalFileMention);
const heterogeneousName = heterogeneousType
? (HETEROGENEOUS_TYPE_LABELS[heterogeneousType] ?? heterogeneousType)
@@ -410,10 +401,9 @@ const InputEditor = memo<{
markdownWriter: mentionMarkdownWriter,
maxLength: 50,
onSelect: mentionOnSelect,
- renderComp: MentionMenuComp,
}
: undefined,
- [enableMention, mentionItemsFn, mentionMarkdownWriter, mentionOnSelect, MentionMenuComp],
+ [enableMention, mentionItemsFn, mentionMarkdownWriter, mentionOnSelect],
);
const slashOption = useMemo(
@@ -424,23 +414,14 @@ const InputEditor = memo<{
const richRenderProps = useMemo(() => {
const basePlugins = !enableRichRender
? CHAT_INPUT_EMBED_PLUGINS
- : createChatInputRichPlugins({
- linkPlugin: false,
- mathPlugin: Editor.withProps(ReactMathPlugin, {
- renderComp: expand
- ? undefined
- : (props) => (
- <FloatMenu {...props} getPopupContainer={() => (slashMenuRef as any)?.current} />
- ),
- }),
- });
+ : createChatInputRichPlugins({ linkPlugin: false });
const plugins = autoCompletePlugin ? [...basePlugins, autoCompletePlugin] : basePlugins;
return !enableRichRender
? { enablePasteMarkdown: false, markdownOption: false, plugins }
: { plugins };
- }, [enableRichRender, expand, slashMenuRef, autoCompletePlugin]);
+ }, [enableRichRender, autoCompletePlugin]);
const handleEditorInit = useCallback(
(editor: IEditor) => {
@@ -471,6 +452,7 @@ const InputEditor = memo<{
content={''}
editable={canCreateContent}
editor={editor}
+ getPopupContainer={() => (slashMenuRef as any)?.current ?? null}
{...{ slashPlacement }}
{...richRenderProps}
mentionOption={mentionOption}