From 12d40713a946111e7ea35ca93dadde000515426f Mon Sep 17 00:00:00 2001 From: kangfenmao Date: Tue, 11 Mar 2025 20:57:42 +0800 Subject: [PATCH] refactor(ChatNavigation): Optimize document element retrieval and remove unnecessary useMemo - Remove useMemo for container element - Dynamically retrieve container element in each method - Simplify scroll and message finding logic - Improve performance by avoiding unnecessary memoization --- .../src/pages/home/Messages/ChatNavigation.tsx | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/pages/home/Messages/ChatNavigation.tsx b/src/renderer/src/pages/home/Messages/ChatNavigation.tsx index e0f6012a..05fca990 100644 --- a/src/renderer/src/pages/home/Messages/ChatNavigation.tsx +++ b/src/renderer/src/pages/home/Messages/ChatNavigation.tsx @@ -1,6 +1,6 @@ import { DownOutlined, UpOutlined } from '@ant-design/icons' import { Button, Tooltip } from 'antd' -import { FC, useCallback, useEffect, useMemo, useState } from 'react' +import { FC, useCallback, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import styled from 'styled-components' @@ -13,8 +13,6 @@ const ChatNavigation: FC = ({ containerId }) => { const [isVisible, setIsVisible] = useState(false) const [hideTimer, setHideTimer] = useState(null) - const container = useMemo(() => document.getElementById(containerId), [containerId]) - const resetHideTimer = useCallback(() => { if (hideTimer) { clearTimeout(hideTimer) @@ -27,6 +25,7 @@ const ChatNavigation: FC = ({ containerId }) => { }, [hideTimer]) const findUserMessages = () => { + const container = document.getElementById(containerId) if (!container) return [] const userMessages = Array.from(container.getElementsByClassName('message-user')) @@ -34,6 +33,8 @@ const ChatNavigation: FC = ({ containerId }) => { } const findAssistantMessages = () => { + const container = document.getElementById(containerId) + if (!container) return [] const assistantMessages = Array.from(container.getElementsByClassName('message-assistant')) @@ -45,18 +46,20 @@ const ChatNavigation: FC = ({ containerId }) => { } const scrollToTop = () => { - if (!container) return - container.scrollTo({ top: 0, behavior: 'smooth' }) + const container = document.getElementById(containerId) + container && container.scrollTo({ top: 0, behavior: 'smooth' }) } const scrollToBottom = () => { - if (!container) return - container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' }) + const container = document.getElementById(containerId) + container && container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' }) } const getCurrentVisibleIndex = (direction: 'up' | 'down') => { const userMessages = findUserMessages() const assistantMessages = findAssistantMessages() + const container = document.getElementById(containerId) + if (!container) return -1 const containerRect = container.getBoundingClientRect()