refactor(ai): shortcut node (#4580)

* init

Signed-off-by: Innei <tukon479@gmail.com>

* refactor(ai-chat): improve layout and styling in ChatInput and EditableMessage components

Updated the ChatInput and EditableMessage components to enhance their layout by adjusting padding and margins for better visual consistency. Refactored the MentionLikePill component to streamline its structure and improve styling, including the use of clsx for conditional class names. Removed unused hotkey properties from ShortcutData and ShortcutMetadata interfaces to simplify type definitions.

Signed-off-by: Innei <tukon479@gmail.com>

* refactor(ai-chat): enhance shortcut handling and editor integration

Updated the ChatShortcutsRow and ChatInterface components to improve shortcut selection and integration with the Lexical editor. The onSelect prop in ChatShortcutsRow now accepts ShortcutData, allowing for more detailed shortcut handling. Refactored the ChatInterface to create a temporary editor instance for processing shortcuts, enhancing the user experience. Additionally, modified the getShortcutTextValue utility to return the prompt directly, simplifying shortcut text retrieval.

Signed-off-by: Innei <tukon479@gmail.com>

* refactor(ai-chat): enhance auto timeline summary shortcut with Lexical editor integration

Updated the useAutoTimelineSummaryShortcut hook to improve the handling of timeline summary shortcuts. Refactored the buildSummaryMessage function to utilize the Lexical editor for generating summary messages, allowing for better integration with the editor's state. Introduced a temporary editor instance to manage shortcut nodes effectively, enhancing the overall functionality and user experience.

Signed-off-by: Innei <tukon479@gmail.com>

---------

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-10-21 01:24:03 +08:00
committed by GitHub
parent e008dfa016
commit 68478b436f
41 changed files with 1508 additions and 519 deletions
@@ -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
<div className={cn(chatInputVariants({ variant }))}>
{/* Input Area */}
<div className="relative z-10 flex items-end" onContextMenu={stopPropagation}>
<ScrollArea rootClassName="mx-5 my-3.5 mr-14 flex-1 overflow-auto">
<ScrollArea rootClassName="mr-14 flex-1 overflow-auto" viewportClassName="px-5 py-3.5">
<LexicalRichEditor
ref={editorRef}
placeholder={scene === "onboarding" ? "Enter your message" : "Message, @ for context"}
@@ -146,7 +146,9 @@ export const ChatInput = memo(({ onSend, variant, ref: forwardedRef }: ChatInput
onChange={handleEditorChange}
onKeyDown={handleKeyDown}
autoFocus
plugins={scene === "onboarding" ? [] : [MentionPlugin, FileUploadPlugin]}
plugins={
scene === "onboarding" ? [] : [MentionPlugin, ShortcutPlugin, FileUploadPlugin]
}
namespace="AIChatRichEditor"
/>
</ScrollArea>
@@ -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 && <CollapsibleError error={error} />}
<ChatShortcutsRow onSelect={(prompt) => handleSendMessage(prompt)} />
<ChatShortcutsRow
onSelect={(shortcutData) => {
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)
}}
/>
<ChatInput onSend={handleSendMessage} variant={!hasMessages ? "minimal" : "default"} />
{(!centerInputOnEmpty || hasMessages) && (
@@ -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<ChatShortcutsRowProps> = ({ onSelect }) => {
@@ -65,7 +66,7 @@ export const ChatShortcutsRow: React.FC<ChatShortcutsRowProps> = ({ onSelect })
{shortcutsToDisplay.map((shortcut) => (
<AIShortcutButton
key={shortcut.id}
onClick={() => onSelect(shortcut.prompt)}
onClick={() => onSelect(shortcut)}
animationDelay={0}
size="sm"
title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name}
@@ -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
@@ -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 = ({
<div className={cn("relative", className)}>
{/* Edit input */}
<div className="bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80 relative overflow-hidden rounded-xl border backdrop-blur-xl duration-200 focus-within:ring-2">
<ScrollArea rootClassName="mx-5 my-3.5 mr-20 flex-1 overflow-auto">
<ScrollArea rootClassName="mr-20 flex-1 overflow-auto" viewportClassName="px-5 py-3.5">
<LexicalRichEditor
ref={editorRef}
placeholder="Edit your message..."
@@ -124,7 +124,7 @@ export const EditableMessage = ({
onChange={handleEditorChange}
onKeyDown={handleKeyDown}
namespace="EditableMessageRichEditor"
plugins={[MentionPlugin]}
plugins={[MentionPlugin, ShortcutPlugin]}
/>
</ScrollArea>
@@ -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<string, any>
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 id="([^"]+)"><\/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<UserRichTextMessageProps> = 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 (
<div className={cn("text-text relative cursor-text text-sm", className)}>
<MentionComponent mentionData={shortcutMention} />
</div>
)
}
const editorState = typeof data.state === "object" ? JSON.stringify(data.state) : data.state
const editorState = sanitizedState
let initialConfig: InitialConfigType = null!
if (!initialConfig) {
@@ -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,
]
@@ -1,2 +1,3 @@
export * from "./file-upload"
export * from "./mention"
export * from "./shortcut"
@@ -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<MentionComponentProps> = ({
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<MentionComponentProps> = ({
const mentionSpan = (
<TooltipTrigger asChild>
<span className={cn(getMentionStyles(mentionData), className)}>
<MentionTypeIcon
type={mentionData.type}
value={mentionData.value}
className="mr-1 translate-y-[2px]"
/>
<span>{displayName}</span>
</span>
<MentionLikePill
className={cn(getMentionStyles(mentionData), className)}
icon={
<MentionTypeIcon type={mentionData.type} value={mentionData.value} className="size-3" />
}
>
{displayName}
</MentionLikePill>
</TooltipTrigger>
)
@@ -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 */}
<span
className={cn(
"mr-1.5 inline-flex size-4 items-center justify-center",
mention.type === "entry" && "text-blue-500",
mention.type === "feed" && "text-orange-500",
mention.type === "category" && "text-green-500",
mention.type === "date" && "text-purple-500",
)}
>
<span className="mr-1.5 inline-flex size-4 items-center justify-center">
<MentionTypeIcon type={mention.type} value={mention.value} />
</span>
@@ -140,153 +120,29 @@ export const MentionDropdown: React.FC<MentionDropdownProps> = ({
}) => {
if (!isVisible) throw thenable
const [editor] = useLexicalComposerContext()
const dropdownRef = useRef<HTMLDivElement>(null)
const [referenceWidth, setReferenceWidth] = useState<number>(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 (
<RootPortal>
{isVisible && (
<div
ref={refs.setFloating}
style={floatingStyles}
className="z-[1000]"
{...getFloatingProps()}
>
<div
ref={dropdownRef}
className={cn(
"bg-material-medium backdrop-blur-background text-text shadow-context-menu",
"min-w-32 overflow-hidden rounded-[6px] border p-1",
"text-body",
)}
style={{
width: Math.max(referenceWidth, 200),
maxWidth: 320,
}}
>
{isLoading ? (
<div className="text-text-secondary flex items-center gap-2 px-2.5 py-1.5">
<i className="i-mgc-loading-3-cute-re size-4 animate-spin" />
<span className="text-sm">Searching...</span>
</div>
) : suggestions.length === 0 ? (
<div className="text-text-tertiary px-2.5 py-1.5 text-center">
<span className="text-sm">No matches found</span>
{query && (
<div className="text-text-quaternary mt-1 text-xs">
Try a different search term
</div>
)}
</div>
) : (
<div role="listbox" aria-label="Mention suggestions">
{suggestions.map((mention, index) => (
<MentionSuggestionItem
key={`${mention.type}-${mention.id}`}
mention={mention}
isSelected={index === selectedIndex}
onMouseMove={() => onSetSelectIndex(index)}
onClick={onSelect}
query={query}
/>
))}
</div>
)}
</div>
</div>
<TypeaheadDropdown
isVisible={isVisible}
items={suggestions}
selectedIndex={selectedIndex}
isLoading={isLoading}
onSelect={onSelect}
onSetSelectIndex={onSetSelectIndex}
onClose={onClose}
query={query}
ariaLabel="Mention suggestions"
getKey={(m) => `${m.type}-${m.id}`}
renderItem={(mention, _index, isSelected, handlers) => (
<MentionSuggestionItem
key={`${mention.type}-${mention.id}`}
mention={mention}
isSelected={isSelected}
onMouseMove={handlers.onMouseMove}
onClick={() => handlers.onClick()}
query={query}
/>
)}
</RootPortal>
/>
)
}
@@ -36,9 +36,6 @@ export const MentionTypeIcon: React.FC<MentionTypeIconProps> = ({
}
return <i className={`i-mgc-grid-cute-re ${className}`} />
}
case "shortcut": {
return <i className={`i-mgc-ai-cute-re ${className}`} />
}
default: {
return <i className={`i-mgc-ai-cute-re ${className}`} />
}
@@ -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 }
}
@@ -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<MentionMatch, MentionData>({
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<typeof insertMentionNode> = {
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 }
}
@@ -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<MentionMatch | null>(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 }
}
@@ -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"]
@@ -0,0 +1,35 @@
import { clsx, cn } from "@follow/utils"
import * as React from "react"
export interface MentionLikePillProps extends React.HTMLAttributes<HTMLSpanElement> {
icon?: React.ReactNode
}
export const MentionLikePill = ({
className,
icon,
children,
ref,
...rest
}: MentionLikePillProps & {
ref?: React.RefObject<HTMLSpanElement>
}) => {
return (
<span
ref={ref}
className={cn(
"relative inline-flex -translate-y-px select-none items-center rounded-md border-[0.5px] px-2 py-0.5 text-xs font-medium",
"bg-fill-secondary hover:bg-fill transition-colors",
className,
)}
{...rest}
>
{icon ? (
<span className="absolute left-0.5 top-0 flex size-5 items-center justify-center">
{icon}
</span>
) : null}
<span className={clsx("truncate text-xs", icon && "ml-3.5")}>{children}</span>
</span>
)
}
@@ -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<TItem> {
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<TItem>({
isVisible,
items,
selectedIndex,
isLoading,
onSelect,
onSetSelectIndex,
onClose,
query,
ariaLabel,
renderItem,
getKey,
loadingMessage = "Searching...",
emptyMessage = "No matches found",
emptyHint = "Try a different search term",
}: TypeaheadDropdownProps<TItem>) {
if (!isVisible) throw thenable
const [editor] = useLexicalComposerContext()
const dropdownRef = useRef<HTMLDivElement>(null)
const [referenceWidth, setReferenceWidth] = useState<number>(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 (
<div className="text-text-secondary flex items-center gap-2 px-2.5 py-1.5">
<i className="i-mgc-loading-3-cute-re size-4 animate-spin" />
<span className="text-sm">{loadingMessage}</span>
</div>
)
}
if (items.length === 0) {
return (
<div className="text-text-tertiary px-2.5 py-1.5 text-center">
<span className="text-sm">{emptyMessage}</span>
{query && <div className="text-text-quaternary mt-1 text-xs">{emptyHint}</div>}
</div>
)
}
return (
<div role="listbox" aria-label={ariaLabel}>
{items.map((item, index) => {
const isSelected = index === selectedIndex
const handlers = {
onMouseMove: () => onSetSelectIndex(index),
onClick: () => onSelect(item),
}
return (
<React.Fragment key={getKey(item)}>
{renderItem(item, index, isSelected, handlers)}
</React.Fragment>
)
})}
</div>
)
}, [
isLoading,
items,
selectedIndex,
renderItem,
getKey,
ariaLabel,
query,
loadingMessage,
emptyMessage,
emptyHint,
onSetSelectIndex,
onSelect,
])
return (
<RootPortal>
{isVisible && (
<div
ref={refs.setFloating}
style={floatingStyles}
className="z-[1000]"
{...getFloatingProps()}
>
<div
ref={dropdownRef}
className={cn(
"bg-material-medium backdrop-blur-background text-text shadow-context-menu",
"min-w-32 overflow-hidden rounded-[6px] border p-1",
"text-body",
)}
style={{
width: Math.max(referenceWidth, 200),
maxWidth: 320,
}}
>
{content}
</div>
</div>
)}
</RootPortal>
)
}
TypeaheadDropdown.displayName = "TypeaheadDropdown"
@@ -0,0 +1 @@
export * from "./MentionLikePill"
@@ -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 }
}
@@ -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<TriggerMatch | null>(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 }
}
@@ -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<TMatch, TItem> {
match: TMatch | null
command: string | LexicalCommand<TItem>
replaceWith: (item: TItem, match: TMatch) => ReplaceHandlerResult
onInsert?: (item: TItem, nodeKey?: string) => void
onComplete?: () => void
}
export const useTypeaheadSelection = <TMatch, TItem>({
match,
command,
replaceWith,
onInsert,
onComplete,
}: UseTypeaheadSelectionOptions<TMatch, TItem>) => {
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 }
}
@@ -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<HTMLElement>,
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",
})
}
}
@@ -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<React.JSX.Element> {
__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 (
<React.Suspense fallback={null}>
<ShortcutComponent shortcutData={this.__shortcutData} key={`${this.__key}-${dataKey}`} />
</React.Suspense>
)
}
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
}
@@ -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 ? (
<Suspense fallback={null}>
<ShortcutDropdown {...dropdownProps} />
</Suspense>
) : null
}
ShortcutPlugin.id = "shortcut"
ShortcutPlugin.nodes = [ShortcutNode]
@@ -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<ShortcutComponentProps> = ({
shortcutData,
className,
onSelect,
}) => {
const handleClick = React.useCallback(() => {
onSelect?.(shortcutData)
}, [onSelect, shortcutData])
return (
<Tooltip>
<TooltipRoot>
<TooltipTrigger asChild>
<MentionLikePill
className={className}
icon={
<span className="text-blue bg-blue/10 inline-flex size-4 items-center justify-center rounded-full text-[11px] font-semibold leading-none">
#
</span>
}
data-shortcut-id={shortcutData.id}
onClick={handleClick}
>
{shortcutData.name}
</MentionLikePill>
</TooltipTrigger>
<TooltipPortal>
<TooltipContent side="top" className="max-w-[320px]">
<div className="flex flex-col gap-1 p-1">
<span className="text-text text-sm font-medium">{shortcutData.name}</span>
{shortcutData.prompt ? (
<span className="text-text-tertiary line-clamp-3 text-xs leading-snug">
{shortcutData.prompt}
</span>
) : null}
</div>
</TooltipContent>
</TooltipPortal>
</TooltipRoot>
</Tooltip>
)
}
ShortcutComponent.displayName = "ShortcutComponent"
@@ -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<React.HTMLAttributes<HTMLDivElement>, "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 (
<span
key={`${shortcut.id}-${index}`}
className={isMatch ? "text-text-vibrant font-semibold" : ""}
>
{part}
</span>
)
})
},
[shortcut.id],
)
return (
<div
className={cn(
"cursor-menu relative flex select-none items-center rounded-[5px] px-2.5 py-1 outline-none",
"focus-within:outline-transparent",
"data-[highlighted]:bg-theme-selection-hover focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[highlighted]:text-theme-selection-foreground",
"h-[28px]",
isSelected && "bg-theme-selection-active text-theme-selection-foreground",
)}
onClick={handleClick}
role="option"
aria-selected={isSelected}
{...props}
>
<span className="text-blue mr-1.5 inline-flex size-4 items-center justify-center">
<span className="bg-blue/10 inline-flex size-4 items-center justify-center rounded-full text-xs font-semibold leading-none">
#
</span>
</span>
<span className="flex-1 truncate leading-tight">{highlightText(shortcut.name, query)}</span>
{shortcut.hotkey && (
<span className="text-text-tertiary ml-2 text-xs">{shortcut.hotkey}</span>
)}
{isSelected && (
<span className="ml-1.5 inline-flex size-4 items-center justify-center">
<i className="i-mgc-check-cute-re size-3" />
</span>
)}
</div>
)
},
)
ShortcutSuggestionItem.displayName = "ShortcutSuggestionItem"
export const ShortcutDropdown: React.FC<ShortcutDropdownProps> = ({
isVisible,
suggestions,
selectedIndex,
isLoading,
onSelect,
onSetSelectIndex,
onClose,
query,
}) => {
if (!isVisible) throw thenable
return (
<TypeaheadDropdown
isVisible={isVisible}
items={suggestions}
selectedIndex={selectedIndex}
isLoading={isLoading}
onSelect={onSelect}
onSetSelectIndex={onSetSelectIndex}
onClose={onClose}
query={query}
ariaLabel="Shortcut suggestions"
getKey={(s) => s.id}
loadingMessage="Searching..."
emptyMessage="No shortcuts found"
emptyHint="Try a different search term"
renderItem={(shortcut, _index, isSelected, handlers) => (
<ShortcutSuggestionItem
key={shortcut.id}
shortcut={shortcut}
isSelected={isSelected}
onMouseMove={handlers.onMouseMove}
onClick={() => handlers.onClick()}
query={query}
/>
)}
/>
)
}
ShortcutDropdown.displayName = "ShortcutDropdown"
@@ -0,0 +1,10 @@
import { createCommand } from "lexical"
import type { ShortcutData } from "./types"
export const SHORTCUT_COMMAND = createCommand<ShortcutData>("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]*)$/
@@ -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 }
}
@@ -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[]> | ShortcutData[]
maxSuggestions?: number
}
const defaultSearchFn = async (): Promise<ShortcutData[]> => []
export const useShortcutSearch = ({
onSearch = defaultSearchFn,
maxSuggestions = DEFAULT_MAX_SHORTCUT_SUGGESTIONS,
}: UseShortcutSearchOptions = {}) => {
const [searchState, setSearchState] = useState<ShortcutSearchState>({
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,
}
}
@@ -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<ShortcutData[]> => {
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 }
}
@@ -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<ShortcutMatch, ShortcutData>({
match: shortcutMatch,
command: SHORTCUT_COMMAND,
replaceWith: (item, match) => insertShortcutNode(item, match),
onInsert: onShortcutInsert,
onComplete: onSelectionComplete,
})
return { selectShortcut: selectItem }
}
@@ -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 }
}
@@ -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"
@@ -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
}
@@ -0,0 +1,4 @@
export * from "./positioning"
export * from "./shortcutTextValue"
export * from "./textReplacement"
export * from "./triggerDetection"
@@ -0,0 +1,6 @@
import type { LexicalEditor } from "lexical"
import { calculateDropdownPosition } from "../../shared/utils/positioning"
export const calculateShortcutDropdownPosition = (editor: LexicalEditor) =>
calculateDropdownPosition(editor)
@@ -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}`
}
@@ -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() }
}
@@ -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
}
@@ -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" },
@@ -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"