fixup: improve auto scroll algo

This commit is contained in:
Yidadaa 2023-08-04 02:39:32 +08:00
parent 203067c936
commit bc5ddc4541

View File

@ -390,7 +390,6 @@ function useScrollToBottom() {
// auto scroll // auto scroll
useEffect(() => { useEffect(() => {
console.log("auto scroll", autoScroll);
if (autoScroll) { if (autoScroll) {
scrollDomToBottom(); scrollDomToBottom();
} }
@ -919,9 +918,15 @@ function _Chat() {
userInput, userInput,
]); ]);
const [msgRenderIndex, setMsgRenderIndex] = useState( const [msgRenderIndex, _setMsgRenderIndex] = useState(
renderMessages.length - CHAT_PAGE_SIZE, 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 messages = useMemo(() => {
const endRenderIndex = Math.min( const endRenderIndex = Math.min(
msgRenderIndex + 3 * CHAT_PAGE_SIZE, msgRenderIndex + 3 * CHAT_PAGE_SIZE,
@ -931,21 +936,20 @@ function _Chat() {
}, [msgRenderIndex, renderMessages]); }, [msgRenderIndex, renderMessages]);
const onChatBodyScroll = (e: HTMLElement) => { const onChatBodyScroll = (e: HTMLElement) => {
const EDGE_THRESHOLD = 100;
const bottomHeight = e.scrollTop + e.clientHeight; const bottomHeight = e.scrollTop + e.clientHeight;
const isTouchTopEdge = e.scrollTop <= EDGE_THRESHOLD; const edgeThreshold = e.clientHeight;
const isTouchBottomEdge = bottomHeight >= e.scrollHeight - EDGE_THRESHOLD;
const isTouchTopEdge = e.scrollTop <= edgeThreshold;
const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
const isHitBottom = bottomHeight >= e.scrollHeight - 10; const isHitBottom = bottomHeight >= e.scrollHeight - 10;
const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
if (isTouchTopEdge) { if (isTouchTopEdge) {
setMsgRenderIndex(Math.max(0, msgRenderIndex - CHAT_PAGE_SIZE)); setMsgRenderIndex(prevPageMsgIndex);
} else if (isTouchBottomEdge) { } else if (isTouchBottomEdge) {
setMsgRenderIndex( setMsgRenderIndex(nextPageMsgIndex);
Math.min(
msgRenderIndex + CHAT_PAGE_SIZE,
renderMessages.length - CHAT_PAGE_SIZE,
),
);
} }
setHitBottom(isHitBottom); setHitBottom(isHitBottom);