diff --git a/apps/desktop/layer/renderer/src/initialize/global-shortcuts.ts b/apps/desktop/layer/renderer/src/initialize/global-shortcuts.ts index c982dcb35..df10f7f6a 100644 --- a/apps/desktop/layer/renderer/src/initialize/global-shortcuts.ts +++ b/apps/desktop/layer/renderer/src/initialize/global-shortcuts.ts @@ -1,4 +1,5 @@ import { callWindowExposeRenderer } from "@follow/shared/bridge" +import { detectIsEditableElement } from "@follow/utils" interface ShortcutDefinition { accelerator: string @@ -45,11 +46,7 @@ export const registerAppGlobalShortcuts = () => { const handleKeydown = (e: KeyboardEvent) => { shortcuts.forEach(({ accelerator, action, inputBypass }) => { // Prevent on input, textarea, [contenteditable] - if ( - !inputBypass && - (["INPUT", "TEXTAREA"].includes((e.target as HTMLElement)?.tagName) || - (e.target as HTMLElement)?.contentEditable === "true") - ) { + if (!inputBypass && detectIsEditableElement(e.target as HTMLElement)) { return } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx index f923b5026..7ab2755d1 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx @@ -1,3 +1,4 @@ +import type { LexicalRichEditorRef } from "@follow/components/ui/lexical-rich-editor/types.js" import { atom } from "jotai" import type { FC, PropsWithChildren } from "react" import { useEffect, useMemo, useRef } from "react" @@ -32,9 +33,8 @@ const AIChatRootInner: FC = ({ children, chatId: externalChatId } }, [currentChatId, externalChatId, chatActions]) - const panelRef = useRef(null!) - const inputRef = useRef(null!) - const refsContext = useMemo(() => ({ panelRef, inputRef }), [panelRef, inputRef]) + const inputRef = useRef(null!) + const refsContext = useMemo(() => ({ inputRef }), [inputRef]) useAIShortcut() if (!currentChatId) { 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 06baf5283..8df8d4115 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 @@ -7,11 +7,12 @@ import { cva } from "class-variance-authority" import { noop } from "es-toolkit" import type { EditorState, LexicalEditor } from "lexical" import { $getRoot } from "lexical" -import { memo, useCallback, useRef, useState } from "react" +import { memo, use, useCallback, useRef, useState } from "react" import { AIChatContextBar } from "~/modules/ai-chat/components/layouts/AIChatContextBar" import { FileUploadPlugin, MentionPlugin } from "../../editor" +import { AIPanelRefsContext } from "../../store/AIChatContext" import { useChatActions, useChatStatus } from "../../store/hooks" import { AIChatSendButton } from "./AIChatSendButton" import { AIModelIndicator } from "./AIModelIndicator" @@ -48,6 +49,11 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { }, [chatActions]) const editorRef = useRef(null) + + const aiPanelRefs = use(AIPanelRefsContext) + if (editorRef.current) { + aiPanelRefs.inputRef.current = editorRef.current + } const [isEmpty, setIsEmpty] = useState(true) const [currentEditor, setCurrentEditor] = useState(null) 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 a56b97163..b23766e0f 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 @@ -1,16 +1,17 @@ +import { useFocusable } from "@follow/components/common/Focusable/hooks.js" import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" import { getCategoryFeedIds } from "@follow/store/subscription/getter" import { usePrefetchSummary } from "@follow/store/summary/hooks" import { tracker } from "@follow/tracker" -import { clsx, cn, nextFrame } from "@follow/utils" +import { clsx, cn, detectIsEditableElement, nextFrame } from "@follow/utils" import type { BizUIMessage } from "@folo-services/ai-tools" import { ErrorBoundary } from "@sentry/react" import type { EditorState, LexicalEditor } from "lexical" import { AnimatePresence } from "motion/react" import { nanoid } from "nanoid" import type { FC, Ref } from "react" -import { Suspense, useEffect, useLayoutEffect, useRef, useState } from "react" -import { useEventCallback } from "usehooks-ts" +import { Suspense, use, useEffect, useLayoutEffect, useRef, useState } from "react" +import { useEventCallback, useEventListener } from "usehooks-ts" import { useAISettingKey } from "~/atoms/settings/ai" import { useActionLanguage } from "~/atoms/settings/general" @@ -35,6 +36,7 @@ import { } from "~/modules/ai-chat/store/hooks" import { useAttachScrollBeyond } from "../../hooks/useAttachScrollBeyond" +import { AIPanelRefsContext } from "../../store/AIChatContext" import type { AIChatContextBlock } from "../../store/types" import { convertLexicalToMarkdown } from "../../utils/lexical-markdown" import { GlobalFileDropZone } from "../file/GlobalFileDropZone" @@ -51,6 +53,21 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const chatActions = useChatActions() const error = useChatError() + const isFocusWithIn = useFocusable() + + const aiPanelRefs = use(AIPanelRefsContext) + + useEventListener("keydown", () => { + if (isFocusWithIn) { + const currentActiveElement = document.activeElement + + if (detectIsEditableElement(currentActiveElement as HTMLElement)) { + return + } + aiPanelRefs.inputRef?.current?.focus() + } + }) + useEffect(() => { if (error) { console.error("AIChat Error:", error) @@ -331,7 +348,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => {
{/* Helper text */} -
- Press Enter to save,{" "} - Esc to cancel +
+
+
+ Press Enter to save, Esc to cancel +
) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx index 277eb70db..51b3b9e78 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx @@ -184,7 +184,7 @@ export const UserChatMessage: React.FC = React.memo(({ mes {isEditing && ( 0 ? `${dataBlockHeight}px` : 0, }} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserMessageParts.tsx index 640ac066f..90c001176 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserMessageParts.tsx @@ -15,7 +15,7 @@ export const UserMessageParts: React.FC = React.memo(({ m switch (part.type) { case "text": { - return + return } case "data-block": { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animatedPlugin.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animatedPlugin.ts deleted file mode 100644 index 21a2d4013..000000000 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animatedPlugin.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { Element, ElementContent, Root } from "hast" -import type { BuildVisitor } from "unist-util-visit" -import { visit } from "unist-util-visit" - -export const animatedPlugin = () => { - return (tree: Root) => { - visit(tree, "element", ((node: Element) => { - if ( - ["p", "h1", "h2", "h3", "h4", "h5", "h6", "li", "strong"].includes(node.tagName) && - node.children - ) { - const newChildren: Array = [] - for (const child of node.children) { - if (child.type === "text") { - const segmenter = new Intl.Segmenter("zh", { granularity: "word" }) - const segments = segmenter.segment(child.value) - const words = [...segments].map((segment) => segment.segment).filter(Boolean) - words.forEach((word: string) => { - newChildren.push({ - children: [{ type: "text", value: word }], - properties: { - className: tw`fade-in duration-1000 ease-in-out animate-in`, - }, - tagName: "span", - type: "element", - }) - }) - } else { - newChildren.push(child) - } - } - node.children = newChildren - } - }) as BuildVisitor) - } -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx index 9f3b0ef5f..833dfcd82 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx @@ -15,8 +15,6 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => isAtBottomRef.current = isAtBottom }, [isAtBottom]) - // cancellation is tracked purely via ref to avoid re-renders while user interacts - const scrollToBottom = useCallback( (force = false) => { if (!viewport) return @@ -26,8 +24,26 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => } if (force || (isAtBottomRef.current && !isAutoScrollCancelledRef.current)) { + const { scrollTop, scrollHeight, clientHeight } = viewport + const targetScrollTop = scrollHeight - clientHeight + const distance = Math.abs(targetScrollTop - scrollTop) + + // If the jump is very large, set immediately to avoid the animation falling behind + const MAX_ANIMATED_DISTANCE = clientHeight * 1.5 + if (distance > MAX_ANIMATED_DISTANCE) { + isAutoScrollingRef.current = true + viewport.scrollTop = targetScrollTop + // After immediate jump, update state + const atBottom = scrollHeight - viewport.scrollTop - clientHeight <= BOTTOM_THRESHOLD + if (isAtBottomRef.current !== atBottom) { + setIsAtBottom(atBottom) + } + isAutoScrollingRef.current = false + scrollAnimationRef.current = null + return + } + isAutoScrollingRef.current = true - const targetScrollTop = viewport.scrollHeight - viewport.clientHeight const animation = springScrollTo(targetScrollTop, viewport) scrollAnimationRef.current = animation @@ -35,8 +51,8 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => scrollAnimationRef.current = null isAutoScrollingRef.current = false // After animation, re-evaluate position - const { scrollTop, scrollHeight, clientHeight } = viewport - const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD + const { scrollTop: st, scrollHeight: sh, clientHeight: ch } = viewport + const atBottom = sh - st - ch <= BOTTOM_THRESHOLD if (isAtBottomRef.current !== atBottom) { setIsAtBottom(atBottom) } @@ -54,6 +70,15 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => if (isAutoScrollingRef.current) { return } + const { scrollTop, scrollHeight, clientHeight } = viewport + const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD + if (atBottom !== isAtBottomRef.current) { + setIsAtBottom(atBottom) + } + // If user scrolled back to bottom, resume auto-scroll + if (atBottom) { + isAutoScrollCancelledRef.current = false + } }, 100) const cancelAutoScroll = () => { @@ -109,6 +134,14 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => } }, [viewport, enabled, scrollToBottom]) + // Ensure we start at bottom on mount/enable + useEffect(() => { + if (!viewport || !enabled) return + requestAnimationFrame(() => { + scrollToBottom(true) + }) + }, [viewport, enabled, scrollToBottom]) + const resetScrollState = useCallback(() => { isAutoScrollCancelledRef.current = false setIsAtBottom(true) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/AIChatContext.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/AIChatContext.ts index 03181c769..5c9d335f2 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/AIChatContext.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/AIChatContext.ts @@ -1,3 +1,4 @@ +import type { LexicalRichEditorRef } from "@follow/components/ui/lexical-rich-editor/types.js" import type { PrimitiveAtom } from "jotai" import { createContext, use } from "react" import type { StoreApi } from "zustand" @@ -6,8 +7,7 @@ import type { UseBoundStoreWithEqualityFn } from "zustand/traditional" import type { AiChatStore } from "./store" export type AIPanelRefs = { - panelRef: React.RefObject - inputRef: React.RefObject + inputRef: React.RefObject } export const AIPanelRefsContext = createContext(null!) diff --git a/packages/internal/utils/src/dom.ts b/packages/internal/utils/src/dom.ts index 1f6b39564..07000251f 100644 --- a/packages/internal/utils/src/dom.ts +++ b/packages/internal/utils/src/dom.ts @@ -93,3 +93,12 @@ export const checkIsEditableElement = (element: HTMLElement) => { element instanceof HTMLTextAreaElement ) } + +export const detectIsEditableElement = (element: HTMLElement) => { + return ( + element.isContentEditable || + element.getAttribute("contenteditable") === "true" || + (element instanceof HTMLInputElement && element.type === "text") || + element instanceof HTMLTextAreaElement + ) +}