fix(ai): auto track scrolling

- Replaced manual checks for editable elements in global shortcuts with a utility function `detectIsEditableElement` for cleaner code and better maintainability.
- Updated `AIChatRoot` to use `LexicalRichEditorRef` for the input reference, enhancing type safety and consistency in the chat input handling.
- Integrated `AIPanelRefsContext` in `ChatInput` and `ChatInterfaceContent` to streamline access to the input reference across components.
- Removed the deprecated `animatedPlugin` file to clean up unused code.

These changes aim to enhance the overall structure and functionality of the AI chat interface, improving user experience and code maintainability.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-09-23 22:43:54 +08:00
parent d4ec031b23
commit a2eb94528d
11 changed files with 90 additions and 61 deletions
@@ -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
}
@@ -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<AIChatRootProps> = ({ children, chatId: externalChatId
}
}, [currentChatId, externalChatId, chatActions])
const panelRef = useRef<HTMLDivElement>(null!)
const inputRef = useRef<HTMLTextAreaElement>(null!)
const refsContext = useMemo<AIPanelRefs>(() => ({ panelRef, inputRef }), [panelRef, inputRef])
const inputRef = useRef<LexicalRichEditorRef>(null!)
const refsContext = useMemo<AIPanelRefs>(() => ({ inputRef }), [inputRef])
useAIShortcut()
if (!currentChatId) {
@@ -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<LexicalRichEditorRef>(null)
const aiPanelRefs = use(AIPanelRefsContext)
if (editorRef.current) {
aiPanelRefs.inputRef.current = editorRef.current
}
const [isEmpty, setIsEmpty] = useState(true)
const [currentEditor, setCurrentEditor] = useState<LexicalEditor | null>(null)
@@ -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) => {
<div
ref={bottomPanelRef}
className={cn(
"absolute mx-auto duration-500 ease-in-out",
"absolute z-10 mx-auto duration-500 ease-in-out",
hasMessages && "inset-x-0 bottom-0 max-w-4xl px-6 pb-6",
!hasMessages && "inset-x-0 bottom-0 max-w-3xl px-6 pb-6 duration-200",
centerInputOnEmpty &&
@@ -1,3 +1,4 @@
import { Kbd } from "@follow/components/ui/kbd/Kbd.js"
import type { LexicalRichEditorRef } from "@follow/components/ui/lexical-rich-editor/index.js"
import { LexicalRichEditor } from "@follow/components/ui/lexical-rich-editor/index.js"
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
@@ -151,9 +152,11 @@ export const EditableMessage = ({
</div>
{/* Helper text */}
<div className="text-text-tertiary mt-2 text-xs">
Press <kbd className="bg-fill text-text-secondary rounded px-1 py-0.5">Enter</kbd> to save,{" "}
<kbd className="bg-fill text-text-secondary rounded px-1 py-0.5">Esc</kbd> to cancel
<div className="relative mt-2">
<div className="bg-background absolute -inset-x-2 -bottom-2 -top-8 z-[-1]" />
<div className="text-text-secondary relative z-[1] text-xs">
Press <Kbd abbr="Enter">Enter</Kbd> to save, <Kbd abbr="Esc">Esc</Kbd> to cancel
</div>
</div>
</div>
)
@@ -184,7 +184,7 @@ export const UserChatMessage: React.FC<UserChatMessageProps> = React.memo(({ mes
<AnimatePresence>
{isEditing && (
<m.div
className="absolute inset-x-0 bottom-0 z-10 flex"
className="absolute inset-x-0 bottom-0 z-[1] flex"
style={{
top: dataBlockHeight > 0 ? `${dataBlockHeight}px` : 0,
}}
@@ -15,7 +15,7 @@ export const UserMessageParts: React.FC<UserMessagePartsProps> = React.memo(({ m
switch (part.type) {
case "text": {
return <AIMarkdownStreamingMessage key={partKey} text={part.text} />
return <AIMarkdownStreamingMessage isStreaming={false} key={partKey} text={part.text} />
}
case "data-block": {
@@ -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<ElementContent> = []
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<Root, "element">)
}
}
@@ -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)
@@ -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<HTMLDivElement>
inputRef: React.RefObject<HTMLTextAreaElement>
inputRef: React.RefObject<LexicalRichEditorRef>
}
export const AIPanelRefsContext = createContext<AIPanelRefs>(null!)
+9
View File
@@ -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
)
}