From bc5ddc4541a54fe2796e6fe6c9a1a8439a68416b Mon Sep 17 00:00:00 2001 From: Yidadaa Date: Fri, 4 Aug 2023 02:39:32 +0800 Subject: [PATCH] fixup: improve auto scroll algo --- app/components/chat.tsx | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/app/components/chat.tsx b/app/components/chat.tsx index 4ab963679..1ed878481 100644 --- a/app/components/chat.tsx +++ b/app/components/chat.tsx @@ -390,7 +390,6 @@ function useScrollToBottom() { // auto scroll useEffect(() => { - console.log("auto scroll", autoScroll); if (autoScroll) { scrollDomToBottom(); } @@ -919,9 +918,15 @@ function _Chat() { userInput, ]); - const [msgRenderIndex, setMsgRenderIndex] = useState( - renderMessages.length - CHAT_PAGE_SIZE, + const [msgRenderIndex, _setMsgRenderIndex] = useState( + Math.max(0, renderMessages.length - CHAT_PAGE_SIZE), ); + function setMsgRenderIndex(newIndex: number) { + newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex); + newIndex = Math.max(0, newIndex); + _setMsgRenderIndex(newIndex); + } + const messages = useMemo(() => { const endRenderIndex = Math.min( msgRenderIndex + 3 * CHAT_PAGE_SIZE, @@ -931,21 +936,20 @@ function _Chat() { }, [msgRenderIndex, renderMessages]); const onChatBodyScroll = (e: HTMLElement) => { - const EDGE_THRESHOLD = 100; const bottomHeight = e.scrollTop + e.clientHeight; - const isTouchTopEdge = e.scrollTop <= EDGE_THRESHOLD; - const isTouchBottomEdge = bottomHeight >= e.scrollHeight - EDGE_THRESHOLD; + const edgeThreshold = e.clientHeight; + + const isTouchTopEdge = e.scrollTop <= edgeThreshold; + const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold; const isHitBottom = bottomHeight >= e.scrollHeight - 10; + const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE; + const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE; + if (isTouchTopEdge) { - setMsgRenderIndex(Math.max(0, msgRenderIndex - CHAT_PAGE_SIZE)); + setMsgRenderIndex(prevPageMsgIndex); } else if (isTouchBottomEdge) { - setMsgRenderIndex( - Math.min( - msgRenderIndex + CHAT_PAGE_SIZE, - renderMessages.length - CHAT_PAGE_SIZE, - ), - ); + setMsgRenderIndex(nextPageMsgIndex); } setHitBottom(isHitBottom);