diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx
index 6d6c5f4f3..4af6b940b 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx
@@ -15,7 +15,7 @@ import { COMMAND_ID } from "~/modules/command/commands/id"
import { getCommand } from "~/modules/command/hooks/use-command"
import { useCommandShortcut } from "~/modules/command/hooks/use-command-binding"
-import { FileUploadPlugin, MentionPlugin } from "../../editor"
+import { FileUploadPlugin, MentionPlugin, ShortcutPlugin } from "../../editor"
import { AIPanelRefsContext } from "../../store/AIChatContext"
import { useChatActions, useChatScene, useChatStatus } from "../../store/hooks"
import { AIChatSendButton } from "./AIChatSendButton"
@@ -138,7 +138,7 @@ export const ChatInput = memo(({ onSend, variant, ref: forwardedRef }: ChatInput
{/* Input Area */}
-
+
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx
index 19721800d..ca79a57f5 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx
@@ -11,7 +11,7 @@ import { tracker } from "@follow/tracker"
import { clsx, cn, detectIsEditableElement, nextFrame } from "@follow/utils"
import { ErrorBoundary } from "@sentry/react"
import type { EditorState } from "lexical"
-import { createEditor } from "lexical"
+import { $createParagraphNode, $getRoot, createEditor } from "lexical"
import { AnimatePresence } from "motion/react"
import { nanoid } from "nanoid"
import type { FC, RefObject } from "react"
@@ -41,7 +41,7 @@ import {
useMessages,
} from "~/modules/ai-chat/store/hooks"
-import { LexicalAIEditorNodes } from "../../editor"
+import { LexicalAIEditorNodes, ShortcutNode } from "../../editor"
import { useAttachScrollBeyond } from "../../hooks/useAttachScrollBeyond"
import { AIPanelRefsContext, useAIChatStore } from "../../store/AIChatContext"
import type { AIChatContextBlock, BizUIMessage, SendingUIMessage } from "../../store/types"
@@ -394,7 +394,30 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => {
)}
>
{error && }
- handleSendMessage(prompt)} />
+ {
+ const tempEditor = createEditor({
+ nodes: LexicalAIEditorNodes,
+ })
+
+ tempEditor.update(
+ () => {
+ const root = $getRoot()
+ root.clear()
+ const paragraph = $createParagraphNode()
+ const shortcutNode = new ShortcutNode(shortcutData)
+ paragraph.append(shortcutNode)
+ root.append(paragraph)
+ },
+ {
+ discrete: true,
+ },
+ )
+
+ const editorState = tempEditor.getEditorState()
+ handleSendMessage(editorState)
+ }}
+ />
{(!centerInputOnEmpty || hasMessages) && (
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatShortcutsRow.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatShortcutsRow.tsx
index 5b57de933..0e5e3c170 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatShortcutsRow.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatShortcutsRow.tsx
@@ -8,11 +8,12 @@ import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack
import { AI_SETTING_SECTION_IDS } from "~/modules/settings/tabs/ai"
import { useCreateAIShortcutModal } from "~/modules/settings/tabs/ai/shortcuts/hooks"
+import type { ShortcutData } from "../../editor/plugins/shortcut/types"
import { useMainEntryId } from "../../hooks/useMainEntryId"
import { AIShortcutButton } from "../ui/AIShortcutButton"
interface ChatShortcutsRowProps {
- onSelect: (prompt: string) => void
+ onSelect: (shortcutData: ShortcutData) => void
}
export const ChatShortcutsRow: React.FC = ({ onSelect }) => {
@@ -65,7 +66,7 @@ export const ChatShortcutsRow: React.FC = ({ onSelect })
{shortcutsToDisplay.map((shortcut) => (
onSelect(shortcut.prompt)}
+ onClick={() => onSelect(shortcut)}
animationDelay={0}
size="sm"
title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx
index d748f707a..c170b782a 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx
@@ -10,7 +10,7 @@ import { RelativeTime } from "~/components/ui/datetime"
import { copyToClipboard } from "~/lib/clipboard"
import type { BizUIMessage } from "~/modules/ai-chat/store/types"
-import { MentionPlugin } from "../../editor"
+import { MentionPlugin, ShortcutPlugin } from "../../editor"
import { AIMessageParts } from "./AIMessageParts"
import { TokenUsagePill } from "./TokenUsagePill"
@@ -38,7 +38,7 @@ const useMessageMarkdownFormat = (message: BizUIMessage) => {
break
}
case "data-rich-text": {
- lexicalEditor ||= createDefaultLexicalEditor([MentionPlugin])
+ lexicalEditor ||= createDefaultLexicalEditor([MentionPlugin, ShortcutPlugin])
lexicalEditor.setEditorState(lexicalEditor.parseEditorState(part.data.state))
content += convertLexicalToMarkdown(lexicalEditor)
break
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/EditableMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/EditableMessage.tsx
index ffd35f294..e618b8480 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/EditableMessage.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/EditableMessage.tsx
@@ -12,7 +12,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai-chat/atoms/session"
import { useChatStatus } from "~/modules/ai-chat/store/hooks"
-import { MentionPlugin } from "../../editor"
+import { MentionPlugin, ShortcutPlugin } from "../../editor"
interface EditableMessageProps {
messageId: string
@@ -39,7 +39,7 @@ export const EditableMessage = ({
const initialEditorState = useMemo(() => {
return (parts.find((part) => part.type === "data-rich-text") as any)?.data
.state as SerializedEditorState
- }, [])
+ }, [parts])
const isEditing = editingMessageId === messageId
const isProcessing = status === "submitted" || status === "streaming"
@@ -116,7 +116,7 @@ export const EditableMessage = ({
{/* Edit input */}
-
+
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserRichTextMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserRichTextMessage.tsx
index 87292b7e6..4575721b4 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserRichTextMessage.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserRichTextMessage.tsx
@@ -10,15 +10,43 @@ import type { SerializedEditorState } from "lexical"
import * as React from "react"
import isEqual from "react-fast-compare"
-import { useAISettingValue } from "~/atoms/settings/ai"
-
import { LexicalAIEditorNodes } from "../../editor"
-import { MentionComponent } from "../../editor/plugins/mention"
+import { getShortcutMarkdownValue } from "../../editor/plugins/shortcut/utils/shortcutTextValue"
function onError(error: Error) {
console.error("Lexical Read-Only Editor Error:", error)
}
+function replaceShortcutTagsWithMarkdown(state: string): string {
+ try {
+ const parsed = JSON.parse(state) as Record
+ const textNodes: Array<{ text: string }> = []
+
+ const traverse = (node: any) => {
+ if (!node) return
+ if (Array.isArray(node.children)) {
+ node.children.forEach(traverse)
+ }
+ if (node.type === "text" && typeof node.text === "string") {
+ textNodes.push(node)
+ }
+ }
+
+ traverse(parsed.root)
+
+ textNodes.forEach((node) => {
+ node.text = node.text.replaceAll(/<\/shortcut>/g, (_, id: string) => {
+ return getShortcutMarkdownValue(id)
+ })
+ })
+
+ return JSON.stringify(parsed)
+ } catch (error) {
+ console.error("Failed to transform shortcut tags to markdown:", error)
+ return state
+ }
+}
+
interface UserRichTextMessageProps {
data: {
state: SerializedEditorState | string // Serialized editor state as a JSON string
@@ -29,49 +57,12 @@ interface UserRichTextMessageProps {
export const UserRichTextMessage: React.FC = React.memo(
({ data, className }) => {
- const aiSettings = useAISettingValue()
- const { shortcuts } = aiSettings
+ const sanitizedState = React.useMemo(() => {
+ const rawState = typeof data.state === "string" ? data.state : JSON.stringify(data.state)
+ return replaceShortcutTagsWithMarkdown(rawState)
+ }, [data.state])
- const shortcutMention = React.useMemo(() => {
- const rawText = data.text
- const normalizedText = rawText.trim()
- if (!normalizedText) {
- return null
- }
-
- const matchedShortcut = shortcuts.find((shortcut) => {
- if (!shortcut.enabled) {
- return false
- }
-
- if (shortcut.prompt === rawText) {
- return true
- }
-
- return shortcut.prompt.trim() === normalizedText
- })
-
- if (!matchedShortcut) {
- return null
- }
-
- return {
- id: matchedShortcut.id,
- name: matchedShortcut.name,
- type: "shortcut" as const,
- value: matchedShortcut.prompt,
- }
- }, [data.text, shortcuts])
-
- if (shortcutMention) {
- return (
-
-
-
- )
- }
-
- const editorState = typeof data.state === "object" ? JSON.stringify(data.state) : data.state
+ const editorState = sanitizedState
let initialConfig: InitialConfigType = null!
if (!initialConfig) {
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts
index 8fbec9ba9..4e02f832c 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts
@@ -1,7 +1,12 @@
import { LexicalRichEditorNodes } from "@follow/components/ui/lexical-rich-editor/nodes.js"
-import { FileAttachmentNode, MentionNode } from "./plugins"
+import { FileAttachmentNode, MentionNode, ShortcutNode } from "./plugins"
export * from "./plugins"
-export const LexicalAIEditorNodes = [...LexicalRichEditorNodes, MentionNode, FileAttachmentNode]
+export const LexicalAIEditorNodes = [
+ ...LexicalRichEditorNodes,
+ MentionNode,
+ ShortcutNode,
+ FileAttachmentNode,
+]
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx
index 14a91d1b3..768bd804d 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx
@@ -1,2 +1,3 @@
export * from "./file-upload"
export * from "./mention"
+export * from "./shortcut"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionComponent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionComponent.tsx
index d81826da9..d5c605c22 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionComponent.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionComponent.tsx
@@ -14,6 +14,7 @@ import { $getNodeByKey } from "lexical"
import * as React from "react"
import { useTranslation } from "react-i18next"
+import { MentionLikePill } from "../../shared/components/MentionLikePill"
import { RANGE_WITH_LABEL_KEY } from "../hooks/dateMentionConfig"
import {
createDateMentionData,
@@ -53,9 +54,6 @@ const MentionTooltipContent = ({ mentionData }: { mentionData: MentionData }) =>
case "date": {
return "bg-purple"
}
- case "shortcut": {
- return "bg-amber-700"
- }
}
}
@@ -114,9 +112,6 @@ const getMentionStyles = (mentionData: MentionData) => {
const viewDef = getView(value as number)
return cn(baseStyles, viewDef!.mentionClassName)
}
- case "shortcut": {
- return cn(baseStyles, "text-amber-700 border-amber-700/20", "hover:border-amber-700/30")
- }
}
}
@@ -133,11 +128,7 @@ export const MentionComponent: React.FC = ({
if (mentionData.type === "date") {
return getDateMentionDisplayName(mentionData, t, language, RANGE_WITH_LABEL_KEY)
}
- if (mentionData.type === "shortcut") {
- return mentionData.name
- } else {
- return `@${mentionData.name}`
- }
+ return `@${mentionData.name}`
}, [mentionData, t, language])
const handleDateRangeChange = React.useCallback(
@@ -180,14 +171,14 @@ export const MentionComponent: React.FC = ({
const mentionSpan = (
-
-
- {displayName}
-
+
+ }
+ >
+ {displayName}
+
)
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionDropdown.tsx
index 5956e2996..5e761ee6d 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionDropdown.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/MentionDropdown.tsx
@@ -1,25 +1,13 @@
-import {
- autoUpdate,
- flip,
- offset,
- shift,
- useDismiss,
- useFloating,
- useInteractions,
- useRole,
-} from "@floating-ui/react"
-import { RootPortal } from "@follow/components/ui/portal/index.js"
import { cn, thenable } from "@follow/utils"
-import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
import * as React from "react"
-import { useCallback, useEffect, useRef, useState } from "react"
+import { useCallback } from "react"
import { useTranslation } from "react-i18next"
+import { TypeaheadDropdown } from "../../shared/components/TypeaheadDropdown"
import { MENTION_TRIGGER_PATTERN } from "../constants"
import { RANGE_WITH_LABEL_KEY } from "../hooks/dateMentionConfig"
import { getDateMentionDisplayName } from "../hooks/dateMentionUtils"
import type { MentionData } from "../types"
-import { calculateDropdownPosition } from "../utils/positioning"
import { MentionTypeIcon } from "./shared/MentionTypeIcon"
interface MentionDropdownProps {
@@ -100,15 +88,7 @@ const MentionSuggestionItem = React.memo(
{...props}
>
{/* Icon */}
-
+
@@ -140,153 +120,29 @@ export const MentionDropdown: React.FC = ({
}) => {
if (!isVisible) throw thenable
- const [editor] = useLexicalComposerContext()
- const dropdownRef = useRef(null)
- const [referenceWidth, setReferenceWidth] = useState(320)
-
- // Create virtual reference element based on cursor position
- const virtualReference = useRef({
- getBoundingClientRect: () => {
- const position = calculateDropdownPosition(editor)
- const editorElement = editor.getRootElement()
-
- if (!position || !editorElement) {
- // Fallback to editor element
- return (
- editorElement?.getBoundingClientRect() || {
- top: 0,
- left: 0,
- bottom: 0,
- right: 0,
- width: 0,
- height: 0,
- x: 0,
- y: 0,
- }
- )
- }
-
- const editorRect = editorElement.getBoundingClientRect()
-
- return {
- top: editorRect.top + position.top,
- left: editorRect.left + position.left,
- bottom: editorRect.top + position.top,
- right: editorRect.left + position.left,
- width: 0,
- height: 0,
- x: editorRect.left + position.left,
- y: editorRect.top + position.top,
- }
- },
- })
-
- const { refs, floatingStyles, context } = useFloating({
- open: isVisible,
- onOpenChange: (open) => {
- if (!open) onClose()
- },
- middleware: [
- offset(8),
- flip({ fallbackPlacements: ["bottom-start", "top-start", "bottom-end", "top-end"] }),
- shift({ padding: 8 }),
- ],
- whileElementsMounted: autoUpdate,
- placement: "bottom-start",
- })
-
- const dismiss = useDismiss(context, {
- enabled: isVisible,
- })
-
- const role = useRole(context, {
- role: "listbox",
- })
-
- const { getFloatingProps } = useInteractions([dismiss, role])
-
- // Handle scroll to keep selected item in view
- useEffect(() => {
- if (isVisible && dropdownRef.current && selectedIndex >= 0) {
- const listContainer = dropdownRef.current.querySelector('[role="listbox"]')
- if (listContainer) {
- const selectedElement = listContainer.children[selectedIndex] as HTMLElement
- if (selectedElement) {
- selectedElement.scrollIntoView({
- block: "nearest",
- behavior: "smooth",
- })
- }
- }
- }
- }, [selectedIndex, isVisible])
-
- // Set virtual reference element based on cursor position and calculate width
- useEffect(() => {
- if (isVisible) {
- refs.setReference(virtualReference.current)
-
- const editorElement = editor.getRootElement()
- if (editorElement) {
- const rect = editorElement.getBoundingClientRect()
- setReferenceWidth(rect.width || 320)
- }
- }
- }, [editor, refs, isVisible, query]) // Add query as dependency to update position when typing
-
return (
-
- {isVisible && (
-
-
- {isLoading ? (
-
-
- Searching...
-
- ) : suggestions.length === 0 ? (
-
-
No matches found
- {query && (
-
- Try a different search term
-
- )}
-
- ) : (
-
- {suggestions.map((mention, index) => (
- onSetSelectIndex(index)}
- onClick={onSelect}
- query={query}
- />
- ))}
-
- )}
-
-
+ `${m.type}-${m.id}`}
+ renderItem={(mention, _index, isSelected, handlers) => (
+ handlers.onClick()}
+ query={query}
+ />
)}
-
+ />
)
}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/shared/MentionTypeIcon.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/shared/MentionTypeIcon.tsx
index 770100cce..cf70cc74b 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/shared/MentionTypeIcon.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/components/shared/MentionTypeIcon.tsx
@@ -36,9 +36,6 @@ export const MentionTypeIcon: React.FC = ({
}
return
}
- case "shortcut": {
- return
- }
default: {
return
}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionKeyboard.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionKeyboard.ts
index e0efc9307..16ac7f13c 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionKeyboard.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionKeyboard.ts
@@ -1,15 +1,6 @@
-import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
-import {
- COMMAND_PRIORITY_HIGH,
- COMMAND_PRIORITY_LOW,
- KEY_ARROW_DOWN_COMMAND,
- KEY_ARROW_UP_COMMAND,
- KEY_ENTER_COMMAND,
- KEY_ESCAPE_COMMAND,
- KEY_TAB_COMMAND,
-} from "lexical"
-import { useCallback, useEffect } from "react"
+import { useCallback } from "react"
+import { useListKeyboardNavigation } from "../../shared/hooks/useListKeyboardNavigation"
import type { MentionData } from "../types"
interface UseMentionKeyboardOptions {
@@ -29,133 +20,19 @@ export const useMentionKeyboard = ({
onEnterKey,
onEscapeKey,
}: UseMentionKeyboardOptions) => {
- const [editor] = useLexicalComposerContext()
-
- // Handle keyboard navigation
- const handleArrowKey = useCallback(
- (isUp: boolean) => {
- if (!isActive || suggestions.length === 0) return false
- onArrowKey(isUp)
- return true
- },
- [isActive, suggestions.length, onArrowKey],
- )
-
- // Handle enter key
- const handleEnterKey = useCallback(() => {
- if (
- !isActive ||
- suggestions.length === 0 ||
- selectedIndex < 0 ||
- selectedIndex >= suggestions.length
- ) {
- return false
- }
- onEnterKey()
- return true
- }, [isActive, suggestions.length, selectedIndex, onEnterKey])
-
- // Handle escape key
- const handleEscapeKey = useCallback(() => {
- if (!isActive) return false
- onEscapeKey()
- return true
- }, [isActive, onEscapeKey])
-
- // Register keyboard commands
- useEffect(() => {
- const removeCommands = [
- // Arrow key navigation
- editor.registerCommand(
- KEY_ARROW_UP_COMMAND,
- (event) => {
- if (isActive && suggestions.length > 0) {
- event.preventDefault()
- return handleArrowKey(true)
- }
- return false
- },
- COMMAND_PRIORITY_LOW,
- ),
-
- editor.registerCommand(
- KEY_ARROW_DOWN_COMMAND,
- (event) => {
- if (isActive && suggestions.length > 0) {
- event.preventDefault()
- return handleArrowKey(false)
- }
- return false
- },
- COMMAND_PRIORITY_LOW,
- ),
-
- // Enter key
- editor.registerCommand(
- KEY_ENTER_COMMAND,
- (event) => {
- if (
- isActive &&
- suggestions.length > 0 &&
- selectedIndex >= 0 &&
- selectedIndex < suggestions.length
- ) {
- event?.preventDefault()
- return handleEnterKey()
- }
- return false
- },
- COMMAND_PRIORITY_HIGH,
- ),
-
- // Tab key (same as enter)
- editor.registerCommand(
- KEY_TAB_COMMAND,
- (event) => {
- if (
- isActive &&
- suggestions.length > 0 &&
- selectedIndex >= 0 &&
- selectedIndex < suggestions.length
- ) {
- event.preventDefault()
- return handleEnterKey()
- }
- return false
- },
- COMMAND_PRIORITY_HIGH,
- ),
-
- // Escape key
- editor.registerCommand(
- KEY_ESCAPE_COMMAND,
- (event) => {
- if (isActive) {
- event.preventDefault()
- return handleEscapeKey()
- }
- return false
- },
- COMMAND_PRIORITY_LOW,
- ),
- ]
-
- return () => {
- removeCommands.forEach((remove) => remove())
- }
- }, [
- editor,
+ const handleMove = useCallback((isUp: boolean) => onArrowKey(isUp), [onArrowKey])
+ const {
+ handleCancel,
+ handleConfirm,
+ handleMove: _,
+ } = useListKeyboardNavigation({
isActive,
- suggestions.length,
+ itemCount: suggestions.length,
selectedIndex,
- handleArrowKey,
- handleEnterKey,
- handleEscapeKey,
- ])
+ onMove: handleMove,
+ onConfirm: onEnterKey,
+ onCancel: onEscapeKey,
+ })
- return {
- handleArrowKey,
- handleEnterKey,
- handleEscapeKey,
- }
+ return { handleArrowKey: _, handleEnterKey: handleConfirm, handleEscapeKey: handleCancel }
}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSelection.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSelection.ts
index 9582f528a..7c6ddb74e 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSelection.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSelection.ts
@@ -1,7 +1,4 @@
-import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
-import { COMMAND_PRIORITY_LOW } from "lexical"
-import { useCallback, useEffect } from "react"
-
+import { useTypeaheadSelection } from "../../shared/hooks/useTypeaheadSelection"
import { MENTION_COMMAND } from "../constants"
import type { MentionData, MentionMatch } from "../types"
import { insertMentionNode } from "../utils/textReplacement"
@@ -17,52 +14,13 @@ export const useMentionSelection = ({
onMentionInsert,
onSelectionComplete,
}: UseMentionSelectionOptions) => {
- const [editor] = useLexicalComposerContext()
+ const { selectItem } = useTypeaheadSelection({
+ match: mentionMatch,
+ command: MENTION_COMMAND,
+ replaceWith: (item, match) => insertMentionNode(item, match),
+ onInsert: onMentionInsert,
+ onComplete: onSelectionComplete,
+ })
- const selectMention = useCallback(
- (mentionData: MentionData) => {
- if (!mentionMatch) return false
-
- let result: ReturnType = {
- success: false,
- nodeKey: undefined as string | undefined,
- }
- editor.update(() => {
- result = insertMentionNode(mentionData, mentionMatch)
-
- if (result.success && result.nodeKey) {
- // Call onMentionInsert immediately within the same editor update
- // to ensure the node tracking happens before any mutations
- onMentionInsert?.(mentionData, result.nodeKey)
- }
- })
-
- // Call onSelectionComplete after the editor update is complete
- if (result.success) {
- setTimeout(() => {
- onSelectionComplete?.()
- }, 0)
- }
-
- return result.success
- },
- [editor, mentionMatch, onMentionInsert, onSelectionComplete],
- )
-
- // Register mention command
- useEffect(() => {
- const removeMentionCommand = editor.registerCommand(
- MENTION_COMMAND,
- (mentionData: MentionData) => {
- return selectMention(mentionData)
- },
- COMMAND_PRIORITY_LOW,
- )
-
- return removeMentionCommand
- }, [editor, selectMention])
-
- return {
- selectMention,
- }
+ return { selectMention: selectItem }
}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionTrigger.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionTrigger.ts
index 7b35b8da1..a57f49a72 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionTrigger.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionTrigger.ts
@@ -1,8 +1,6 @@
-import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
import type { LexicalEditor } from "lexical"
-import { $getSelection, $isRangeSelection, $isTextNode } from "lexical"
-import { useCallback, useEffect, useState } from "react"
+import { useTextTrigger } from "../../shared/hooks/useTextTrigger"
import type { MentionMatch } from "../types"
import { defaultTriggerFn } from "../utils/triggerDetection"
@@ -15,51 +13,6 @@ export const useMentionTrigger = ({
triggerFn = defaultTriggerFn,
onTrigger,
}: UseMentionTriggerOptions = {}) => {
- const [editor] = useLexicalComposerContext()
- const [mentionMatch, setMentionMatch] = useState(null)
-
- const updateMentionMatch = useCallback(
- (match: MentionMatch | null) => {
- setMentionMatch(match)
- onTrigger?.(match)
- },
- [onTrigger],
- )
-
- const clearMentionMatch = useCallback(() => {
- updateMentionMatch(null)
- }, [updateMentionMatch])
-
- // Monitor text changes for mention triggers
- useEffect(() => {
- const removeUpdateListener = editor.registerUpdateListener(({ editorState }) => {
- editorState.read(() => {
- const selection = $getSelection()
- if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
- updateMentionMatch(null)
- return
- }
-
- const { anchor } = selection
- const anchorNode = anchor.getNode()
-
- if (!$isTextNode(anchorNode)) {
- updateMentionMatch(null)
- return
- }
-
- const textContent = anchorNode.getTextContent()
- const match = triggerFn(textContent, editor)
- updateMentionMatch(match)
- })
- })
-
- return removeUpdateListener
- }, [editor, triggerFn, updateMentionMatch])
-
- return {
- mentionMatch,
- isActive: mentionMatch !== null,
- clearMentionMatch,
- }
+ const { match, isActive, clear } = useTextTrigger({ triggerFn, onTrigger })
+ return { mentionMatch: match as MentionMatch | null, isActive, clearMentionMatch: clear }
}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/types.ts
index 399d339d5..6aec8a0f3 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/types.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/types.ts
@@ -36,11 +36,6 @@ export interface CategoryMentionData extends MentionBaseData {
value: string
}
-export interface ShortcutMentionData extends MentionBaseData {
- type: "shortcut"
- value: string
-}
-
export interface ViewMentionData extends MentionBaseData {
type: "view"
value: FeedViewType
@@ -51,7 +46,6 @@ export type MentionData =
| FeedMentionData
| DateMentionData
| CategoryMentionData
- | ShortcutMentionData
| ViewMentionData
export type MentionType = MentionData["type"]
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/MentionLikePill.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/MentionLikePill.tsx
new file mode 100644
index 000000000..0bc5d8025
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/MentionLikePill.tsx
@@ -0,0 +1,35 @@
+import { clsx, cn } from "@follow/utils"
+import * as React from "react"
+
+export interface MentionLikePillProps extends React.HTMLAttributes {
+ icon?: React.ReactNode
+}
+
+export const MentionLikePill = ({
+ className,
+ icon,
+ children,
+ ref,
+ ...rest
+}: MentionLikePillProps & {
+ ref?: React.RefObject
+}) => {
+ return (
+
+ {icon ? (
+
+ {icon}
+
+ ) : null}
+ {children}
+
+ )
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/TypeaheadDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/TypeaheadDropdown.tsx
new file mode 100644
index 000000000..f474acbae
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/TypeaheadDropdown.tsx
@@ -0,0 +1,228 @@
+import {
+ autoUpdate,
+ flip,
+ offset,
+ shift,
+ useDismiss,
+ useFloating,
+ useInteractions,
+ useRole,
+} from "@floating-ui/react"
+import { RootPortal } from "@follow/components/ui/portal/index.js"
+import { cn, thenable } from "@follow/utils"
+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
+import * as React from "react"
+import { useEffect, useMemo, useRef, useState } from "react"
+
+import { calculateDropdownPosition } from "../utils/positioning"
+
+export interface TypeaheadDropdownProps {
+ isVisible: boolean
+ items: TItem[]
+ selectedIndex: number
+ isLoading: boolean
+ onSelect: (item: TItem) => void
+ onSetSelectIndex: (index: number) => void
+ onClose: () => void
+ query: string
+ ariaLabel: string
+ renderItem: (
+ item: TItem,
+ index: number,
+ isSelected: boolean,
+ handlers: { onMouseMove: () => void; onClick: () => void },
+ ) => React.ReactNode
+ getKey: (item: TItem) => string
+ loadingMessage?: string
+ emptyMessage?: string
+ emptyHint?: string
+}
+
+export function TypeaheadDropdown({
+ isVisible,
+ items,
+ selectedIndex,
+ isLoading,
+ onSelect,
+ onSetSelectIndex,
+ onClose,
+ query,
+ ariaLabel,
+ renderItem,
+ getKey,
+ loadingMessage = "Searching...",
+ emptyMessage = "No matches found",
+ emptyHint = "Try a different search term",
+}: TypeaheadDropdownProps) {
+ if (!isVisible) throw thenable
+
+ const [editor] = useLexicalComposerContext()
+ const dropdownRef = useRef(null)
+ const [referenceWidth, setReferenceWidth] = useState(320)
+
+ const virtualReference = useRef({
+ getBoundingClientRect: () => {
+ const position = calculateDropdownPosition(editor)
+ const editorElement = editor.getRootElement()
+
+ if (!position || !editorElement) {
+ return (
+ editorElement?.getBoundingClientRect() || {
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: 0,
+ width: 0,
+ height: 0,
+ x: 0,
+ y: 0,
+ }
+ )
+ }
+
+ const editorRect = editorElement.getBoundingClientRect()
+
+ return {
+ top: editorRect.top + position.top,
+ left: editorRect.left + position.left,
+ bottom: editorRect.top + position.top,
+ right: editorRect.left + position.left,
+ width: 0,
+ height: 0,
+ x: editorRect.left + position.left,
+ y: editorRect.top + position.top,
+ }
+ },
+ })
+
+ const { refs, floatingStyles, context } = useFloating({
+ open: isVisible,
+ onOpenChange: (open) => {
+ if (!open) onClose()
+ },
+ middleware: [
+ offset(8),
+ flip({ fallbackPlacements: ["bottom-start", "top-start", "bottom-end", "top-end"] }),
+ shift({ padding: 8 }),
+ ],
+ whileElementsMounted: autoUpdate,
+ placement: "bottom-start",
+ })
+
+ const dismiss = useDismiss(context, {
+ enabled: isVisible,
+ })
+
+ const role = useRole(context, {
+ role: "listbox",
+ })
+
+ const { getFloatingProps } = useInteractions([dismiss, role])
+
+ useEffect(() => {
+ if (isVisible && dropdownRef.current && selectedIndex >= 0) {
+ const listContainer = dropdownRef.current.querySelector('[role="listbox"]')
+ if (listContainer) {
+ const selectedElement = listContainer.children[selectedIndex] as HTMLElement
+ if (selectedElement) {
+ selectedElement.scrollIntoView({
+ block: "nearest",
+ behavior: "smooth",
+ })
+ }
+ }
+ }
+ }, [selectedIndex, isVisible])
+
+ useEffect(() => {
+ if (isVisible) {
+ refs.setReference(virtualReference.current)
+
+ const editorElement = editor.getRootElement()
+ if (editorElement) {
+ const rect = editorElement.getBoundingClientRect()
+ setReferenceWidth(rect.width || 320)
+ }
+ }
+ }, [editor, refs, isVisible, query])
+
+ const content = useMemo(() => {
+ if (isLoading) {
+ return (
+
+
+ {loadingMessage}
+
+ )
+ }
+
+ if (items.length === 0) {
+ return (
+
+
{emptyMessage}
+ {query &&
{emptyHint}
}
+
+ )
+ }
+
+ return (
+
+ {items.map((item, index) => {
+ const isSelected = index === selectedIndex
+ const handlers = {
+ onMouseMove: () => onSetSelectIndex(index),
+ onClick: () => onSelect(item),
+ }
+ return (
+
+ {renderItem(item, index, isSelected, handlers)}
+
+ )
+ })}
+
+ )
+ }, [
+ isLoading,
+ items,
+ selectedIndex,
+ renderItem,
+ getKey,
+ ariaLabel,
+ query,
+ loadingMessage,
+ emptyMessage,
+ emptyHint,
+ onSetSelectIndex,
+ onSelect,
+ ])
+
+ return (
+
+ {isVisible && (
+
+ )}
+
+ )
+}
+
+TypeaheadDropdown.displayName = "TypeaheadDropdown"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/index.ts
new file mode 100644
index 000000000..07a4a4086
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/components/index.ts
@@ -0,0 +1 @@
+export * from "./MentionLikePill"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useListKeyboardNavigation.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useListKeyboardNavigation.ts
new file mode 100644
index 000000000..667b8fc33
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useListKeyboardNavigation.ts
@@ -0,0 +1,118 @@
+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
+import {
+ COMMAND_PRIORITY_HIGH,
+ COMMAND_PRIORITY_LOW,
+ KEY_ARROW_DOWN_COMMAND,
+ KEY_ARROW_UP_COMMAND,
+ KEY_ENTER_COMMAND,
+ KEY_ESCAPE_COMMAND,
+ KEY_TAB_COMMAND,
+} from "lexical"
+import { useCallback, useEffect } from "react"
+
+interface UseListKeyboardNavigationOptions {
+ isActive: boolean
+ itemCount: number
+ selectedIndex: number
+ onMove: (isUp: boolean) => void
+ onConfirm: () => void
+ onCancel: () => void
+}
+
+export const useListKeyboardNavigation = ({
+ isActive,
+ itemCount,
+ selectedIndex,
+ onMove,
+ onConfirm,
+ onCancel,
+}: UseListKeyboardNavigationOptions) => {
+ const [editor] = useLexicalComposerContext()
+
+ const handleMove = useCallback(
+ (isUp: boolean) => {
+ if (!isActive || itemCount === 0) return false
+ onMove(isUp)
+ return true
+ },
+ [isActive, itemCount, onMove],
+ )
+
+ const handleConfirm = useCallback(() => {
+ if (!isActive || itemCount === 0 || selectedIndex < 0 || selectedIndex >= itemCount) {
+ return false
+ }
+ onConfirm()
+ return true
+ }, [isActive, itemCount, selectedIndex, onConfirm])
+
+ const handleCancel = useCallback(() => {
+ if (!isActive) return false
+ onCancel()
+ return true
+ }, [isActive, onCancel])
+
+ useEffect(() => {
+ const remove = [
+ editor.registerCommand(
+ KEY_ARROW_UP_COMMAND,
+ (event) => {
+ if (isActive && itemCount > 0) {
+ event.preventDefault()
+ return handleMove(true)
+ }
+ return false
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand(
+ KEY_ARROW_DOWN_COMMAND,
+ (event) => {
+ if (isActive && itemCount > 0) {
+ event.preventDefault()
+ return handleMove(false)
+ }
+ return false
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ (event) => {
+ if (isActive && itemCount > 0 && selectedIndex >= 0 && selectedIndex < itemCount) {
+ event?.preventDefault()
+ return handleConfirm()
+ }
+ return false
+ },
+ COMMAND_PRIORITY_HIGH,
+ ),
+ editor.registerCommand(
+ KEY_TAB_COMMAND,
+ (event) => {
+ if (isActive && itemCount > 0 && selectedIndex >= 0 && selectedIndex < itemCount) {
+ event.preventDefault()
+ return handleConfirm()
+ }
+ return false
+ },
+ COMMAND_PRIORITY_HIGH,
+ ),
+ editor.registerCommand(
+ KEY_ESCAPE_COMMAND,
+ (event) => {
+ if (isActive) {
+ event.preventDefault()
+ return handleCancel()
+ }
+ return false
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ ]
+
+ return () => remove.forEach((fn) => fn())
+ }, [editor, isActive, itemCount, selectedIndex, handleMove, handleConfirm, handleCancel])
+
+ return { handleMove, handleConfirm, handleCancel }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTextTrigger.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTextTrigger.ts
new file mode 100644
index 000000000..53ebc8e93
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTextTrigger.ts
@@ -0,0 +1,54 @@
+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
+import type { LexicalEditor } from "lexical"
+import { $getSelection, $isRangeSelection, $isTextNode } from "lexical"
+import { useCallback, useEffect, useState } from "react"
+
+export interface TriggerMatch {
+ leadOffset: number
+ matchingString: string
+ replaceableString: string
+}
+
+export interface UseTextTriggerOptions {
+ triggerFn: (text: string, editor: LexicalEditor) => TriggerMatch | null
+ onTrigger?: (match: TriggerMatch | null) => void
+}
+
+export const useTextTrigger = ({ triggerFn, onTrigger }: UseTextTriggerOptions) => {
+ const [editor] = useLexicalComposerContext()
+ const [match, setMatch] = useState(null)
+
+ const update = useCallback(
+ (m: TriggerMatch | null) => {
+ setMatch(m)
+ onTrigger?.(m)
+ },
+ [onTrigger],
+ )
+
+ const clear = useCallback(() => update(null), [update])
+
+ useEffect(() => {
+ const remove = editor.registerUpdateListener(({ editorState }) => {
+ editorState.read(() => {
+ const selection = $getSelection()
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
+ update(null)
+ return
+ }
+ const { anchor } = selection
+ const anchorNode = anchor.getNode()
+ if (!$isTextNode(anchorNode)) {
+ update(null)
+ return
+ }
+ const textContent = anchorNode.getTextContent()
+ const m = triggerFn(textContent, editor)
+ update(m)
+ })
+ })
+ return remove
+ }, [editor, triggerFn, update])
+
+ return { match, isActive: match !== null, clear }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTypeaheadSelection.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTypeaheadSelection.ts
new file mode 100644
index 000000000..d0d96066e
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/hooks/useTypeaheadSelection.ts
@@ -0,0 +1,56 @@
+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
+import type { LexicalCommand } from "lexical"
+import { COMMAND_PRIORITY_LOW } from "lexical"
+import { useCallback, useEffect } from "react"
+
+export interface ReplaceHandlerResult {
+ success: boolean
+ nodeKey?: string
+}
+
+export interface UseTypeaheadSelectionOptions {
+ match: TMatch | null
+ command: string | LexicalCommand
+ replaceWith: (item: TItem, match: TMatch) => ReplaceHandlerResult
+ onInsert?: (item: TItem, nodeKey?: string) => void
+ onComplete?: () => void
+}
+
+export const useTypeaheadSelection = ({
+ match,
+ command,
+ replaceWith,
+ onInsert,
+ onComplete,
+}: UseTypeaheadSelectionOptions) => {
+ const [editor] = useLexicalComposerContext()
+
+ const selectItem = useCallback(
+ (item: TItem) => {
+ if (!match) return false
+
+ let result: ReplaceHandlerResult = { success: false, nodeKey: undefined }
+ editor.update(() => {
+ result = replaceWith(item, match)
+ if (result.success && result.nodeKey) onInsert?.(item, result.nodeKey)
+ })
+ if (result.success) {
+ setTimeout(() => onComplete?.(), 0)
+ }
+ return result.success
+ },
+ [editor, match, onInsert, onComplete, replaceWith],
+ )
+
+ useEffect(() => {
+ const remove = editor.registerCommand(
+ // Support both LexicalCommand and string keys (cast for string case)
+ command as unknown as any,
+ (item: TItem) => selectItem(item),
+ COMMAND_PRIORITY_LOW,
+ )
+ return remove
+ }, [editor, command, selectItem])
+
+ return { selectItem }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/utils/positioning.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/utils/positioning.ts
similarity index 57%
rename from apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/utils/positioning.ts
rename to apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/utils/positioning.ts
index 96615def5..a585472ac 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/utils/positioning.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shared/utils/positioning.ts
@@ -1,6 +1,6 @@
import type { LexicalEditor } from "lexical"
-import type { MentionDropdownPosition } from "../types"
+import type { MentionDropdownPosition } from "../../mention/types"
export const calculateDropdownPosition = (
editor: LexicalEditor,
@@ -21,18 +21,3 @@ export const calculateDropdownPosition = (
left: rect.left - editorRect.left,
}
}
-
-export const scrollSelectedItemIntoView = (
- containerRef: React.RefObject,
- selectedIndex: number,
-): void => {
- if (!containerRef.current || selectedIndex < 0) return
-
- const selectedElement = containerRef.current.children[selectedIndex] as HTMLElement
- if (selectedElement) {
- selectedElement.scrollIntoView({
- block: "nearest",
- behavior: "smooth",
- })
- }
-}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutNode.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutNode.tsx
new file mode 100644
index 000000000..cd3647f6b
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutNode.tsx
@@ -0,0 +1,142 @@
+import type {
+ DOMConversionMap,
+ DOMExportOutput,
+ EditorConfig,
+ LexicalEditor,
+ LexicalNode,
+ NodeKey,
+ SerializedLexicalNode,
+ Spread,
+} from "lexical"
+import { $applyNodeReplacement, DecoratorNode } from "lexical"
+import * as React from "react"
+
+import { ShortcutComponent } from "./components/ShortcutComponent"
+import type { ShortcutData } from "./types"
+import { getShortcutTextValue } from "./utils/shortcutTextValue"
+
+export type SerializedShortcutNode = Spread<
+ {
+ shortcutData: ShortcutData
+ },
+ SerializedLexicalNode
+>
+
+export class ShortcutNode extends DecoratorNode {
+ __shortcutData: ShortcutData
+
+ static override getType(): string {
+ return "shortcut"
+ }
+
+ static override clone(node: ShortcutNode): ShortcutNode {
+ return new ShortcutNode(node.__shortcutData, node.__key)
+ }
+
+ constructor(shortcutData: ShortcutData, key?: NodeKey) {
+ super(key)
+ this.__shortcutData = shortcutData
+ }
+
+ getShortcutData(): ShortcutData {
+ return this.__shortcutData
+ }
+
+ setShortcutData(shortcutData: ShortcutData): void {
+ const writable = this.getWritable()
+ writable.__shortcutData = shortcutData
+ }
+
+ override createDOM(config: EditorConfig): HTMLElement {
+ const dom = document.createElement("span")
+ dom.className = config.theme.mention || "shortcut-node"
+ dom.dataset.lexicalShortcut = "true"
+ dom.dataset.shortcutId = this.__shortcutData.id
+ return dom
+ }
+
+ override updateDOM(): false {
+ return false
+ }
+
+ static override importDOM(): DOMConversionMap | null {
+ return {
+ span: () => {
+ throw new Error("Not implemented")
+ },
+ }
+ }
+
+ static override importJSON(serializedNode: SerializedShortcutNode): ShortcutNode {
+ const { shortcutData } = serializedNode
+ return $createShortcutNode(shortcutData)
+ }
+
+ override exportDOM(): DOMExportOutput {
+ const element = document.createElement("span")
+ element.dataset.lexicalShortcut = "true"
+ element.dataset.shortcutId = this.__shortcutData.id
+ element.textContent = `#${this.__shortcutData.name}`
+ element.className = "shortcut-node"
+ return { element }
+ }
+
+ override exportJSON(): SerializedShortcutNode {
+ return {
+ shortcutData: this.__shortcutData,
+ type: "shortcut",
+ version: 1,
+ }
+ }
+
+ override getTextContent(): string {
+ return getShortcutTextValue(this.__shortcutData)
+ }
+
+ override decorate(_editor: LexicalEditor): React.JSX.Element {
+ const dataKey = this.__shortcutData.id
+
+ return (
+
+
+
+ )
+ }
+
+ override isInline(): boolean {
+ return true
+ }
+
+ override isKeyboardSelectable(): boolean {
+ return false
+ }
+
+ canInsertTextBefore(): boolean {
+ return false
+ }
+
+ canInsertTextAfter(): boolean {
+ return true
+ }
+
+ canBeEmpty(): boolean {
+ return false
+ }
+
+ isSegmented(): boolean {
+ return true
+ }
+
+ extractWithChild(): boolean {
+ return false
+ }
+}
+
+export function $createShortcutNode(shortcutData: ShortcutData): ShortcutNode {
+ const shortcutNode = new ShortcutNode(shortcutData)
+ return $applyNodeReplacement(shortcutNode)
+}
+
+export function $isShortcutNode(node: LexicalNode | null | undefined): node is ShortcutNode {
+ return node instanceof ShortcutNode
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutPlugin.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutPlugin.tsx
new file mode 100644
index 000000000..60fe355cd
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/ShortcutPlugin.tsx
@@ -0,0 +1,120 @@
+import * as React from "react"
+import { Suspense, useMemo } from "react"
+
+import { ShortcutDropdown } from "./components/ShortcutDropdown"
+import { DEFAULT_MAX_SHORTCUT_SUGGESTIONS } from "./constants"
+import { useShortcutKeyboard } from "./hooks/useShortcutKeyboard"
+import { useShortcutSearch } from "./hooks/useShortcutSearch"
+import { useShortcutSearchService } from "./hooks/useShortcutSearchService"
+import { useShortcutSelection } from "./hooks/useShortcutSelection"
+import { useShortcutTrigger } from "./hooks/useShortcutTrigger"
+import { ShortcutNode } from "./ShortcutNode"
+
+export function ShortcutPlugin() {
+ const { searchShortcuts } = useShortcutSearchService()
+
+ const { shortcutMatch, isActive, clearShortcutMatch } = useShortcutTrigger()
+
+ const {
+ suggestions,
+ selectedIndex,
+ isLoading,
+ searchShortcuts: performSearch,
+ clearSuggestions,
+ setSelectedIndex,
+ hasResults,
+ } = useShortcutSearch({
+ onSearch: searchShortcuts,
+ maxSuggestions: DEFAULT_MAX_SHORTCUT_SUGGESTIONS,
+ })
+
+ const { selectShortcut } = useShortcutSelection({
+ shortcutMatch,
+ onSelectionComplete: () => {
+ clearShortcutMatch()
+ clearSuggestions()
+ },
+ })
+
+ const handleArrowKey = React.useCallback(
+ (isUp: boolean) => {
+ if (!hasResults) return
+
+ const newIndex = isUp
+ ? selectedIndex <= 0
+ ? suggestions.length - 1
+ : selectedIndex - 1
+ : selectedIndex >= suggestions.length - 1
+ ? 0
+ : selectedIndex + 1
+
+ setSelectedIndex(newIndex)
+ },
+ [hasResults, suggestions.length, selectedIndex, setSelectedIndex],
+ )
+
+ const handleEnterKey = React.useCallback(() => {
+ if (hasResults && selectedIndex >= 0 && selectedIndex < suggestions.length) {
+ const shortcut = suggestions[selectedIndex]
+ if (shortcut) {
+ selectShortcut(shortcut)
+ }
+ }
+ }, [hasResults, selectedIndex, suggestions, selectShortcut])
+
+ const handleEscapeKey = React.useCallback(() => {
+ clearShortcutMatch()
+ clearSuggestions()
+ }, [clearShortcutMatch, clearSuggestions])
+
+ useShortcutKeyboard({
+ isActive,
+ suggestions,
+ selectedIndex,
+ onArrowKey: handleArrowKey,
+ onEnterKey: handleEnterKey,
+ onEscapeKey: handleEscapeKey,
+ })
+
+ React.useEffect(() => {
+ if (shortcutMatch) {
+ performSearch(shortcutMatch.matchingString)
+ } else {
+ clearSuggestions()
+ }
+ }, [shortcutMatch, performSearch, clearSuggestions])
+
+ const dropdownProps = useMemo(() => {
+ if (!isActive || !hasResults) return null
+
+ return {
+ isVisible: true,
+ suggestions,
+ selectedIndex,
+ isLoading,
+ onSetSelectIndex: setSelectedIndex,
+ onSelect: selectShortcut,
+ onClose: handleEscapeKey,
+ query: shortcutMatch?.matchingString || "",
+ }
+ }, [
+ isActive,
+ hasResults,
+ suggestions,
+ selectedIndex,
+ isLoading,
+ setSelectedIndex,
+ selectShortcut,
+ handleEscapeKey,
+ shortcutMatch?.matchingString,
+ ])
+
+ return dropdownProps ? (
+
+
+
+ ) : null
+}
+
+ShortcutPlugin.id = "shortcut"
+ShortcutPlugin.nodes = [ShortcutNode]
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutComponent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutComponent.tsx
new file mode 100644
index 000000000..698bb8193
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutComponent.tsx
@@ -0,0 +1,63 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipPortal,
+ TooltipRoot,
+ TooltipTrigger,
+} from "@follow/components/ui/tooltip/index.js"
+import * as React from "react"
+
+import { MentionLikePill } from "../../shared/components/MentionLikePill"
+import type { ShortcutData } from "../types"
+
+interface ShortcutComponentProps {
+ shortcutData: ShortcutData
+ className?: string
+ onSelect?: (shortcut: ShortcutData) => void
+}
+
+export const ShortcutComponent: React.FC = ({
+ shortcutData,
+ className,
+ onSelect,
+}) => {
+ const handleClick = React.useCallback(() => {
+ onSelect?.(shortcutData)
+ }, [onSelect, shortcutData])
+
+ return (
+
+
+
+
+ #
+
+ }
+ data-shortcut-id={shortcutData.id}
+ onClick={handleClick}
+ >
+ {shortcutData.name}
+
+
+
+
+
+ {shortcutData.name}
+
+ {shortcutData.prompt ? (
+
+ {shortcutData.prompt}
+
+ ) : null}
+
+
+
+
+
+ )
+}
+
+ShortcutComponent.displayName = "ShortcutComponent"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutDropdown.tsx
new file mode 100644
index 000000000..7f8e29e3c
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/components/ShortcutDropdown.tsx
@@ -0,0 +1,138 @@
+import { cn, thenable } from "@follow/utils"
+import * as React from "react"
+import { useCallback } from "react"
+
+import { TypeaheadDropdown } from "../../shared/components/TypeaheadDropdown"
+import type { ShortcutData } from "../types"
+
+interface ShortcutDropdownProps {
+ isVisible: boolean
+ suggestions: ShortcutData[]
+ selectedIndex: number
+ isLoading: boolean
+ onSelect: (shortcut: ShortcutData) => void
+ onSetSelectIndex: (index: number) => void
+ onClose: () => void
+ query: string
+}
+
+const ShortcutSuggestionItem = React.memo(
+ ({
+ shortcut,
+ isSelected,
+ onClick,
+ query,
+ ...props
+ }: {
+ shortcut: ShortcutData
+ isSelected: boolean
+ onClick: (shortcut: ShortcutData) => void
+ query: string
+ } & Omit, "onClick">) => {
+ const handleClick = useCallback(() => {
+ onClick(shortcut)
+ }, [shortcut, onClick])
+
+ const highlightText = useCallback(
+ (text: string, rawQuery: string) => {
+ const cleanQuery = rawQuery.replace(/^#/, "").toLowerCase()
+ if (!cleanQuery) return text
+
+ const parts = text.split(new RegExp(`(${cleanQuery})`, "gi"))
+ return parts.map((part, index) => {
+ const isMatch = part.toLowerCase() === cleanQuery
+
+ if (!part) {
+ return null
+ }
+
+ return (
+
+ {part}
+
+ )
+ })
+ },
+ [shortcut.id],
+ )
+
+ return (
+
+
+
+ #
+
+
+ {highlightText(shortcut.name, query)}
+ {shortcut.hotkey && (
+ {shortcut.hotkey}
+ )}
+ {isSelected && (
+
+
+
+ )}
+
+ )
+ },
+)
+
+ShortcutSuggestionItem.displayName = "ShortcutSuggestionItem"
+
+export const ShortcutDropdown: React.FC = ({
+ isVisible,
+ suggestions,
+ selectedIndex,
+ isLoading,
+ onSelect,
+ onSetSelectIndex,
+ onClose,
+ query,
+}) => {
+ if (!isVisible) throw thenable
+
+ return (
+ s.id}
+ loadingMessage="Searching..."
+ emptyMessage="No shortcuts found"
+ emptyHint="Try a different search term"
+ renderItem={(shortcut, _index, isSelected, handlers) => (
+ handlers.onClick()}
+ query={query}
+ />
+ )}
+ />
+ )
+}
+
+ShortcutDropdown.displayName = "ShortcutDropdown"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/constants.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/constants.ts
new file mode 100644
index 000000000..f2d600846
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/constants.ts
@@ -0,0 +1,10 @@
+import { createCommand } from "lexical"
+
+import type { ShortcutData } from "./types"
+
+export const SHORTCUT_COMMAND = createCommand("SHORTCUT_COMMAND")
+
+export const DEFAULT_MAX_SHORTCUT_SUGGESTIONS = 10
+
+export const SHORTCUT_TRIGGER_PATTERN =
+ /(?:^|\s)(#[\w\-\s\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]*)$/
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutKeyboard.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutKeyboard.ts
new file mode 100644
index 000000000..1ae40db47
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutKeyboard.ts
@@ -0,0 +1,38 @@
+import { useCallback } from "react"
+
+import { useListKeyboardNavigation } from "../../shared/hooks/useListKeyboardNavigation"
+import type { ShortcutData } from "../types"
+
+interface UseShortcutKeyboardOptions {
+ isActive: boolean
+ suggestions: ShortcutData[]
+ selectedIndex: number
+ onArrowKey: (isUp: boolean) => void
+ onEnterKey: () => void
+ onEscapeKey: () => void
+}
+
+export const useShortcutKeyboard = ({
+ isActive,
+ suggestions,
+ selectedIndex,
+ onArrowKey,
+ onEnterKey,
+ onEscapeKey,
+}: UseShortcutKeyboardOptions) => {
+ const handleMove = useCallback((isUp: boolean) => onArrowKey(isUp), [onArrowKey])
+ const {
+ handleCancel,
+ handleConfirm,
+ handleMove: _,
+ } = useListKeyboardNavigation({
+ isActive,
+ itemCount: suggestions.length,
+ selectedIndex,
+ onMove: handleMove,
+ onConfirm: onEnterKey,
+ onCancel: onEscapeKey,
+ })
+
+ return { handleArrowKey: _, handleEnterKey: handleConfirm, handleEscapeKey: handleCancel }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearch.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearch.ts
new file mode 100644
index 000000000..61a984df7
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearch.ts
@@ -0,0 +1,89 @@
+import { useCallback, useRef, useState, useTransition } from "react"
+
+import { DEFAULT_MAX_SHORTCUT_SUGGESTIONS } from "../constants"
+import type { ShortcutData, ShortcutSearchState } from "../types"
+import { cleanShortcutQuery, shouldTriggerShortcut } from "../utils/triggerDetection"
+
+interface UseShortcutSearchOptions {
+ onSearch?: (query: string) => Promise | ShortcutData[]
+ maxSuggestions?: number
+}
+
+const defaultSearchFn = async (): Promise => []
+
+export const useShortcutSearch = ({
+ onSearch = defaultSearchFn,
+ maxSuggestions = DEFAULT_MAX_SHORTCUT_SUGGESTIONS,
+}: UseShortcutSearchOptions = {}) => {
+ const [searchState, setSearchState] = useState({
+ suggestions: [],
+ selectedIndex: -1,
+ isLoading: false,
+ })
+
+ const [isPending, startTransition] = useTransition()
+ const onSearchRef = useRef(onSearch)
+ const maxSuggestionsRef = useRef(maxSuggestions)
+
+ onSearchRef.current = onSearch
+ maxSuggestionsRef.current = maxSuggestions
+
+ const searchShortcuts = useCallback(async (query: string) => {
+ if (!shouldTriggerShortcut(query)) {
+ setSearchState((prev) => ({
+ ...prev,
+ suggestions: [],
+ selectedIndex: -1,
+ isLoading: false,
+ }))
+ return
+ }
+
+ startTransition(() => {
+ setSearchState((prev) => ({ ...prev, isLoading: true }))
+ })
+
+ try {
+ const cleanQuery = cleanShortcutQuery(query)
+ const results = await onSearchRef.current(cleanQuery)
+
+ startTransition(() => {
+ setSearchState({
+ suggestions: results.slice(0, maxSuggestionsRef.current),
+ selectedIndex: results.length > 0 ? 0 : -1,
+ isLoading: false,
+ })
+ })
+ } catch (error) {
+ console.error("Error searching shortcuts:", error)
+ startTransition(() => {
+ setSearchState({
+ suggestions: [],
+ selectedIndex: -1,
+ isLoading: false,
+ })
+ })
+ }
+ }, [])
+
+ const clearSuggestions = useCallback(() => {
+ setSearchState({
+ suggestions: [],
+ selectedIndex: -1,
+ isLoading: false,
+ })
+ }, [])
+
+ const setSelectedIndex = useCallback((index: number) => {
+ setSearchState((prev) => ({ ...prev, selectedIndex: index }))
+ }, [])
+
+ return {
+ ...searchState,
+ searchShortcuts,
+ clearSuggestions,
+ setSelectedIndex,
+ hasResults: searchState.suggestions.length > 0,
+ isLoading: searchState.isLoading || isPending,
+ }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearchService.ts
new file mode 100644
index 000000000..29651bdbc
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSearchService.ts
@@ -0,0 +1,36 @@
+import { useMemo } from "react"
+
+import { useAISettingValue } from "~/atoms/settings/ai"
+
+import type { ShortcutData } from "../types"
+
+export const useShortcutSearchService = () => {
+ const aiSettings = useAISettingValue()
+
+ const searchShortcuts = useMemo(() => {
+ const shortcuts = (aiSettings.shortcuts ?? []).filter((shortcut) => shortcut.enabled)
+
+ const normalizedShortcuts: ShortcutData[] = shortcuts.map((shortcut) => ({
+ id: shortcut.id,
+ name: shortcut.name,
+ prompt: shortcut.prompt,
+ hotkey: shortcut.hotkey,
+ displayTargets: shortcut.displayTargets,
+ }))
+
+ return async (query: string): Promise => {
+ const trimmedQuery = query.trim().toLowerCase()
+
+ if (!trimmedQuery) {
+ return normalizedShortcuts
+ }
+
+ return normalizedShortcuts.filter((shortcut) => {
+ const normalizedName = shortcut.name.toLowerCase()
+ return normalizedName.includes(trimmedQuery)
+ })
+ }
+ }, [aiSettings.shortcuts])
+
+ return { searchShortcuts }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSelection.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSelection.ts
new file mode 100644
index 000000000..ae04eae67
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutSelection.ts
@@ -0,0 +1,26 @@
+import { useTypeaheadSelection } from "../../shared/hooks/useTypeaheadSelection"
+import { SHORTCUT_COMMAND } from "../constants"
+import type { ShortcutData, ShortcutMatch } from "../types"
+import { insertShortcutNode } from "../utils/textReplacement"
+
+interface UseShortcutSelectionOptions {
+ shortcutMatch: ShortcutMatch | null
+ onShortcutInsert?: (shortcut: ShortcutData, nodeKey?: string) => void
+ onSelectionComplete?: () => void
+}
+
+export const useShortcutSelection = ({
+ shortcutMatch,
+ onShortcutInsert,
+ onSelectionComplete,
+}: UseShortcutSelectionOptions) => {
+ const { selectItem } = useTypeaheadSelection({
+ match: shortcutMatch,
+ command: SHORTCUT_COMMAND,
+ replaceWith: (item, match) => insertShortcutNode(item, match),
+ onInsert: onShortcutInsert,
+ onComplete: onSelectionComplete,
+ })
+
+ return { selectShortcut: selectItem }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutTrigger.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutTrigger.ts
new file mode 100644
index 000000000..9523abb45
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/hooks/useShortcutTrigger.ts
@@ -0,0 +1,18 @@
+import type { LexicalEditor } from "lexical"
+
+import { useTextTrigger } from "../../shared/hooks/useTextTrigger"
+import type { ShortcutMatch } from "../types"
+import { defaultShortcutTriggerFn } from "../utils/triggerDetection"
+
+interface UseShortcutTriggerOptions {
+ triggerFn?: (text: string, editor: LexicalEditor) => ShortcutMatch | null
+ onTrigger?: (match: ShortcutMatch | null) => void
+}
+
+export const useShortcutTrigger = ({
+ triggerFn = defaultShortcutTriggerFn,
+ onTrigger,
+}: UseShortcutTriggerOptions = {}) => {
+ const { match, isActive, clear } = useTextTrigger({ triggerFn, onTrigger })
+ return { shortcutMatch: match as ShortcutMatch | null, isActive, clearShortcutMatch: clear }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/index.ts
new file mode 100644
index 000000000..0028689fd
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/index.ts
@@ -0,0 +1,11 @@
+export { ShortcutComponent } from "./components/ShortcutComponent"
+export { ShortcutDropdown } from "./components/ShortcutDropdown"
+export { useShortcutSearchService } from "./hooks/useShortcutSearchService"
+export { $createShortcutNode, $isShortcutNode, ShortcutNode } from "./ShortcutNode"
+export { ShortcutPlugin } from "./ShortcutPlugin"
+export type {
+ ShortcutData,
+ ShortcutMatch,
+ ShortcutSearchState,
+ ShortcutTriggerState,
+} from "./types"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/types.ts
new file mode 100644
index 000000000..249c6ffd2
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/types.ts
@@ -0,0 +1,31 @@
+import type { AIShortcutTarget } from "@follow/shared/settings/interface"
+
+export interface ShortcutData {
+ id: string
+ name: string
+ prompt: string
+
+ displayTargets?: readonly AIShortcutTarget[]
+}
+
+export interface ShortcutMetadata {
+ id: string
+ name: string
+}
+
+export interface ShortcutMatch {
+ leadOffset: number
+ matchingString: string
+ replaceableString: string
+}
+
+export interface ShortcutSearchState {
+ suggestions: ShortcutData[]
+ selectedIndex: number
+ isLoading: boolean
+}
+
+export interface ShortcutTriggerState {
+ shortcutMatch: ShortcutMatch | null
+ isActive: boolean
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/index.ts
new file mode 100644
index 000000000..226906076
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/index.ts
@@ -0,0 +1,4 @@
+export * from "./positioning"
+export * from "./shortcutTextValue"
+export * from "./textReplacement"
+export * from "./triggerDetection"
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/positioning.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/positioning.ts
new file mode 100644
index 000000000..069a610fc
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/positioning.ts
@@ -0,0 +1,6 @@
+import type { LexicalEditor } from "lexical"
+
+import { calculateDropdownPosition } from "../../shared/utils/positioning"
+
+export const calculateShortcutDropdownPosition = (editor: LexicalEditor) =>
+ calculateDropdownPosition(editor)
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/shortcutTextValue.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/shortcutTextValue.ts
new file mode 100644
index 000000000..d91fbbc20
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/shortcutTextValue.ts
@@ -0,0 +1,19 @@
+import { getAISettings } from "~/atoms/settings/ai"
+
+import type { ShortcutData } from "../types"
+
+export function getShortcutTextValue(shortcutData: ShortcutData): string {
+ return shortcutData.prompt
+}
+
+export function getShortcutDisplayTextValue(shortcutData: ShortcutData): string {
+ const allShortcuts = getAISettings().shortcuts ?? []
+ const matchedShortcut = allShortcuts.find((shortcut) => shortcut.id === shortcutData.id)
+ return matchedShortcut?.name ?? shortcutData.name
+}
+
+export function getShortcutMarkdownValue(shortcutId: string): string {
+ const allShortcuts = getAISettings().shortcuts ?? []
+ const matchedShortcut = allShortcuts.find((shortcut) => shortcut.id === shortcutId)
+ return matchedShortcut ? `#${matchedShortcut.name}` : `#${shortcutId}`
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/textReplacement.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/textReplacement.ts
new file mode 100644
index 000000000..7c1d56428
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/textReplacement.ts
@@ -0,0 +1,47 @@
+import { $createTextNode, $getSelection, $isRangeSelection, $isTextNode } from "lexical"
+
+import { $createShortcutNode } from "../ShortcutNode"
+import type { ShortcutData, ShortcutMatch } from "../types"
+
+export const insertShortcutNode = (
+ shortcutData: ShortcutData,
+ shortcutMatch: ShortcutMatch,
+): { success: boolean; nodeKey?: string } => {
+ const selection = $getSelection()
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return { success: false }
+
+ const { anchor } = selection
+ const anchorNode = anchor.getNode()
+
+ if (!$isTextNode(anchorNode)) return { success: false }
+
+ const textContent = anchorNode.getTextContent()
+ const { leadOffset, replaceableString } = shortcutMatch
+
+ const beforeText = textContent.slice(0, leadOffset)
+ const afterText = textContent.slice(leadOffset + replaceableString.length)
+
+ const beforeNode = beforeText ? $createTextNode(beforeText) : null
+ const shortcutNode = $createShortcutNode(shortcutData)
+ const afterNode = afterText ? $createTextNode(afterText) : null
+
+ if (beforeNode) {
+ anchorNode.insertBefore(beforeNode)
+ }
+ anchorNode.insertBefore(shortcutNode)
+ if (afterNode) {
+ anchorNode.insertBefore(afterNode)
+ }
+
+ anchorNode.remove()
+
+ if (afterNode) {
+ afterNode.select(0, 0)
+ } else {
+ const spaceNode = $createTextNode(" ")
+ shortcutNode.insertAfter(spaceNode)
+ spaceNode.select(1, 1)
+ }
+
+ return { success: true, nodeKey: shortcutNode.getKey() }
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/triggerDetection.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/triggerDetection.ts
new file mode 100644
index 000000000..3588dfb89
--- /dev/null
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/shortcut/utils/triggerDetection.ts
@@ -0,0 +1,44 @@
+import { $getSelection, $isRangeSelection, $isTextNode } from "lexical"
+
+import { SHORTCUT_TRIGGER_PATTERN } from "../constants"
+import type { ShortcutMatch } from "../types"
+
+export const defaultShortcutTriggerFn = (): ShortcutMatch | null => {
+ const selection = $getSelection()
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
+ return null
+ }
+
+ const { anchor, focus } = selection
+ const anchorNode = anchor.getNode()
+
+ if (!$isTextNode(anchorNode) || anchor.key !== focus.key || anchor.offset !== focus.offset) {
+ return null
+ }
+
+ const textContent = anchorNode.getTextContent()
+ const cursorOffset = anchor.offset
+ const match = textContent.slice(0, cursorOffset).match(SHORTCUT_TRIGGER_PATTERN)
+
+ if (!match) {
+ return null
+ }
+
+ const matchingString = match[1] || ""
+ const replaceableString = matchingString
+ const leadOffset = (match.index ?? 0) + (match[0]?.startsWith(" ") ? 1 : 0)
+
+ return {
+ leadOffset,
+ matchingString,
+ replaceableString,
+ }
+}
+
+export const cleanShortcutQuery = (query: string): string => {
+ return query.replace(/^#/, "").trim()
+}
+
+export const shouldTriggerShortcut = (query: string): boolean => {
+ return query.startsWith("#") && query.length > 0
+}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoTimelineSummaryShortcut.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoTimelineSummaryShortcut.ts
index 0aef09038..728a43faa 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoTimelineSummaryShortcut.ts
+++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoTimelineSummaryShortcut.ts
@@ -1,7 +1,9 @@
-import { getEditorStateJSONString } from "@follow/components/ui/lexical-rich-editor/utils.js"
+import { convertLexicalToMarkdown } from "@follow/components/ui/lexical-rich-editor/utils.js"
import { FeedViewType } from "@follow/constants"
import { DEFAULT_SUMMARIZE_TIMELINE_SHORTCUT_ID } from "@follow/shared/settings/defaults"
import { getCategoryFeedIds } from "@follow/store/subscription/getter"
+import type { LexicalEditor } from "lexical"
+import { $createParagraphNode, $getRoot, createEditor } from "lexical"
import { nanoid } from "nanoid"
import { useEffect, useMemo, useRef } from "react"
@@ -11,6 +13,7 @@ import { ROUTE_FEED_IN_FOLDER, ROUTE_FEED_PENDING } from "~/constants"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { AI_CHAT_SPECIAL_ID_PREFIX } from "../constants"
+import { LexicalAIEditorNodes, ShortcutNode } from "../editor"
import { AIPersistService } from "../services"
import { useAIChatStore } from "../store/AIChatContext"
import { useBlockActions, useChatActions, useCurrentChatId } from "../store/hooks"
@@ -21,7 +24,7 @@ import { isTimelineSummaryAutoContext } from "./useTimelineSummaryAutoContext"
const ONE_HOUR = 60 * 60 * 1000
const buildSummaryMessage = (
- prompt: string,
+ editor: LexicalEditor,
contextBlocks: AIChatContextBlock[],
messageId: string,
): SendingUIMessage => {
@@ -37,8 +40,8 @@ const buildSummaryMessage = (
parts.push({
type: "data-rich-text",
data: {
- state: getEditorStateJSONString(prompt),
- text: prompt,
+ state: JSON.stringify(editor.getEditorState().toJSON()),
+ text: convertLexicalToMarkdown(editor),
},
})
@@ -214,7 +217,7 @@ export const useAutoTimelineSummaryShortcut = () => {
const run = async () => {
try {
- const prompt = defaultShortcut.prompt.trim()
+ const { prompt, id, name } = defaultShortcut
if (!prompt) {
return
}
@@ -253,7 +256,25 @@ export const useAutoTimelineSummaryShortcut = () => {
await chatActions.switchToChat(timelineSummaryChatId)
blockActions.clearBlocks({ keepSpecialTypes: true })
- const message = buildSummaryMessage(prompt, contextBlocks, nanoid())
+ const tempEditor = createEditor({
+ nodes: LexicalAIEditorNodes,
+ })
+
+ tempEditor.update(
+ () => {
+ const root = $getRoot()
+ root.clear()
+ const paragraph = $createParagraphNode()
+ const shortcutNode = new ShortcutNode({ id, name, prompt })
+ paragraph.append(shortcutNode)
+ root.append(paragraph)
+ },
+ {
+ discrete: true,
+ },
+ )
+
+ const message = buildSummaryMessage(tempEditor, contextBlocks, nanoid())
await chatActions.sendMessage(message, {
body: { scene: "general" },
diff --git a/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-task-modal.tsx b/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-task-modal.tsx
index 174d62a44..6d375387b 100644
--- a/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-task-modal.tsx
+++ b/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-task-modal.tsx
@@ -20,7 +20,7 @@ import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
-import { MentionPlugin } from "~/modules/ai-chat/editor"
+import { MentionPlugin, ShortcutPlugin } from "~/modules/ai-chat/editor"
import { AIPersistService } from "~/modules/ai-chat/services"
import { useCreateAITaskMutation, useUpdateAITaskMutation } from "~/modules/ai-task/query"
import type { ScheduleType, TaskFormData } from "~/modules/ai-task/types"
@@ -242,7 +242,7 @@ export const AITaskModal = ({ task, prompt, showSettingsTip = false }: AITaskMod
onLengthChange={(textLength) => {
setPromptTextLength(textLength)
}}
- plugins={[MentionPlugin]}
+ plugins={[MentionPlugin, ShortcutPlugin]}
namespace="AITaskPromptEditor"
placeholder={t("tasks.prompt_placeholder")}
className="min-h-[120px] resize-none text-sm leading-relaxed"