From e77a986125d9b76a47358c489e4372c49cb1b857 Mon Sep 17 00:00:00 2001 From: infinite-persistence Date: Wed, 14 Jul 2021 11:06:47 +0800 Subject: [PATCH] Load comments if spinner is visible from the start It was previously only responding to scroll events. --- ui/component/commentsList/view.jsx | 35 +++++++++++++++++++----------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/ui/component/commentsList/view.jsx b/ui/component/commentsList/view.jsx index 4d7c00256..a4714bca8 100644 --- a/ui/component/commentsList/view.jsx +++ b/ui/component/commentsList/view.jsx @@ -153,6 +153,7 @@ function CommentList(props: Props) { fetchingChannels, ]); + // Scroll to linked-comment useEffect(() => { if (readyToDisplayComments && linkedCommentId && commentRef && commentRef.current) { commentRef.current.scrollIntoView({ block: 'start' }); @@ -160,17 +161,18 @@ function CommentList(props: Props) { } }, [readyToDisplayComments, linkedCommentId]); + // Infinite scroll useEffect(() => { - const handleCommentScroll = debounce(() => { - // $FlowFixMe - const rect = spinnerRef.current.getBoundingClientRect(); - // $FlowFixMe - const windowH = window.innerHeight || document.documentElement.clientHeight; - // $FlowFixMe - const windowW = window.innerWidth || document.documentElement.clientWidth; + function shouldFetchNextPage(page, topLevelTotalPages, window, document, yPrefetchPx = 1000) { + if (!spinnerRef || !spinnerRef.current) { + return false; + } - const Y_OFFSET_PX = 1000; - const isApproachingViewport = Y_OFFSET_PX && rect.top < windowH + scaleToDevicePixelRatio(Y_OFFSET_PX); + const rect = spinnerRef.current.getBoundingClientRect(); // $FlowFixMe + const windowH = window.innerHeight || document.documentElement.clientHeight; // $FlowFixMe + const windowW = window.innerWidth || document.documentElement.clientWidth; // $FlowFixMe + + const isApproachingViewport = yPrefetchPx !== 0 && rect.top < windowH + scaleToDevicePixelRatio(yPrefetchPx); const isInViewport = rect.width > 0 && @@ -182,16 +184,23 @@ function CommentList(props: Props) { // $FlowFixMe rect.left <= windowW; - if ((isInViewport || isApproachingViewport) && page < topLevelTotalPages) { + return (isInViewport || isApproachingViewport) && page < topLevelTotalPages; + } + + const handleCommentScroll = debounce(() => { + if (shouldFetchNextPage(page, topLevelTotalPages, window, document)) { setPage(page + 1); } }, DEBOUNCE_SCROLL_HANDLER_MS); if (!isFetchingComments && readyToDisplayComments && moreBelow && spinnerRef && spinnerRef.current) { - window.addEventListener('scroll', handleCommentScroll); + if (shouldFetchNextPage(page, topLevelTotalPages, window, document, 0)) { + setPage(page + 1); + } else { + window.addEventListener('scroll', handleCommentScroll); + return () => window.removeEventListener('scroll', handleCommentScroll); + } } - - return () => window.removeEventListener('scroll', handleCommentScroll); }, [ page, moreBelow,