diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx index ea2f3496f..a7743268d 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx @@ -43,6 +43,7 @@ import { imageActions } from "~/store/image" import { useEntriesState } from "../context/EntriesContext" import { batchMarkRead } from "../hooks/useEntryMarkReadHandler" import { useScrollMarkReadEndPadding } from "../hooks/useScrollMarkReadEndPadding" +import { shouldApplyScrollResetSignal } from "../scroll-reset" import { PictureWaterFallItem } from "./picture-item" // grid grid-cols-1 @lg:grid-cols-2 @3xl:grid-cols-3 @6xl:grid-cols-4 @7xl:grid-cols-5 px-4 gap-1.5 @@ -53,7 +54,7 @@ const FirstScreenReadyContext = createContext(false) const gutter = 24 export const PictureMasonry: FC = (props) => { - const { data } = props + const { appliedResetScrollSignal, data, onResetScrollSignalConsumed, resetScrollSignal } = props const entriesState = useEntriesState() const pauseScrollMarkRead = useScrollMarkReadGracePeriod( entriesState.isFetching && !entriesState.isFetchingNextPage, @@ -146,6 +147,27 @@ export const PictureMasonry: FC = (props) => { hasNextPage: props.hasNextPage, }) const endSpacerHeight = useScrollMarkReadEndPadding(scrollElement, hasEndSpacer) + const isResetScrollPending = shouldApplyScrollResetSignal({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }) + useLayoutEffect(() => { + if (!scrollElement) return + if (!isInitDim || !deferIsInitLayout) return + if (!isResetScrollPending) return + if (resetScrollSignal === undefined) return + + scrollElement.scrollTop = 0 + scrollElement.scrollLeft = 0 + onResetScrollSignalConsumed?.(resetScrollSignal) + }, [ + onResetScrollSignalConsumed, + deferIsInitLayout, + isInitDim, + isResetScrollPending, + resetScrollSignal, + scrollElement, + ]) const handleRender = useCallback( (startIndex: number, stopIndex: number, items: any[]) => { currentRange.current = { start: startIndex, end: stopIndex } @@ -161,6 +183,7 @@ export const PictureMasonry: FC = (props) => { const dataRef = useRefValue(data) useEffect(() => { if (!renderMarkRead && !scrollMarkRead) return + if (props.suspendMarkRead) return if (!scrollElement) return const observer = new IntersectionObserver( @@ -224,7 +247,14 @@ export const PictureMasonry: FC = (props) => { return () => { observer.disconnect() } - }, [dataRef, pauseScrollMarkRead, renderMarkRead, scrollElement, scrollMarkRead]) + }, [ + dataRef, + pauseScrollMarkRead, + props.suspendMarkRead, + renderMarkRead, + scrollElement, + scrollMarkRead, + ]) const [firstScreenReady, setFirstScreenReady] = useState(false) useEffect(() => { @@ -328,6 +358,10 @@ interface MasonryProps { endReached: () => any hasNextPage: boolean Footer?: FC | ReactNode + appliedResetScrollSignal?: number + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean } const LoadingSkeletonItem = () => { diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/grid.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/grid.tsx index 053b7ec84..56b8ade7d 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/grid.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/grid.tsx @@ -25,6 +25,7 @@ import { useScrollMarkReadEndPadding } from "./hooks/useScrollMarkReadEndPadding import { EntryItem } from "./item" import { PictureMasonry } from "./Items/picture-masonry" import type { EntryListProps } from "./list" +import { getInitialScrollOffset, shouldApplyScrollResetSignal } from "./scroll-reset" export const EntryColumnGrid: FC = (props) => { const { entriesIds, feedId, hasNextPage, view, fetchNextPage } = props @@ -40,6 +41,10 @@ export const EntryColumnGrid: FC = (props) => { endReached={fetchNextPage} data={entriesIds} Footer={props.Footer} + appliedResetScrollSignal={props.appliedResetScrollSignal} + onResetScrollSignalConsumed={props.onResetScrollSignalConsumed} + resetScrollSignal={props.resetScrollSignal} + suspendMarkRead={props.suspendMarkRead} /> ) } @@ -102,6 +107,9 @@ const VirtualGridImpl: FC< listRef, measureRef, containerWidth, + appliedResetScrollSignal, + onResetScrollSignalConsumed, + resetScrollSignal, } = props const scrollRef = useScrollViewElement() @@ -136,6 +144,10 @@ const VirtualGridImpl: FC< const rowCacheKey = `${feedId}-row` const columnCacheKey = `${feedId}-column` + const isResetScrollPending = shouldApplyScrollResetSignal({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }) const footerRowIndex = rows.length + (hasNextPage ? 1 : 0) const rowCount = footerRowIndex + (Footer ? 1 : 0) const estimatedRowHeight = columns[0]! / (ratioMap[view] ?? 1) + (!isImageOnly ? 58 : 0) @@ -146,7 +158,11 @@ const VirtualGridImpl: FC< getScrollElement: () => scrollRef, estimateSize: (i) => columns[i]!, overscan: 5, - initialOffset: offsetCache.get(columnCacheKey) ?? 0, + initialOffset: getInitialScrollOffset({ + cachedOffset: offsetCache.get(columnCacheKey), + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }), initialMeasurementsCache: measurementsCache.get(columnCacheKey) ?? [], onChange: useTypeScriptHappyCallback( (virtualizer: Virtualizer) => { @@ -165,7 +181,11 @@ const VirtualGridImpl: FC< overscan: 5, gap: 8, getScrollElement: () => scrollRef, - initialOffset: offsetCache.get(rowCacheKey) ?? 0, + initialOffset: getInitialScrollOffset({ + cachedOffset: offsetCache.get(rowCacheKey), + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }), initialMeasurementsCache: measurementsCache.get(rowCacheKey) ?? [], paddingEnd: 32, onChange: useTypeScriptHappyCallback( @@ -194,6 +214,29 @@ const VirtualGridImpl: FC< listRef.current = rowVirtualizer }, [rowVirtualizer, listRef]) + useLayoutEffect(() => { + if (!scrollRef) return + if (!isResetScrollPending) return + if (resetScrollSignal === undefined) return + + rowVirtualizer.scrollToOffset(0) + columnVirtualizer.scrollToOffset(0) + scrollRef.scrollTop = 0 + scrollRef.scrollLeft = 0 + offsetCache.put(rowCacheKey, 0) + offsetCache.put(columnCacheKey, 0) + onResetScrollSignalConsumed?.(resetScrollSignal) + }, [ + columnCacheKey, + columnVirtualizer, + isResetScrollPending, + onResetScrollSignalConsumed, + resetScrollSignal, + rowCacheKey, + rowVirtualizer, + scrollRef, + ]) + useLayoutEffect(() => { measureRef.current = () => { rowVirtualizer.measure() diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx index d6fb07aaf..e3e386021 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx @@ -9,7 +9,7 @@ import { useIsLoggedIn } from "@follow/store/user/hooks" import { isBizId } from "@follow/utils/utils" import type { Range, Virtualizer } from "@tanstack/react-virtual" import { atom, useAtomValue } from "jotai" -import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react" +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react" import { useTranslation } from "react-i18next" import { useGeneralSettingKey } from "~/atoms/settings/general" @@ -35,6 +35,7 @@ import { useNavigateFirstEntry } from "./hooks/useNavigateFirstEntry" import { EntryListHeader } from "./layouts/EntryListHeader" import { EntryEmptyList, EntryList } from "./list" import { shouldScrollTimelineToTopOnRefreshStateChange } from "./refresh-reset" +import { shouldSuspendMarkReadForScrollReset } from "./scroll-reset" import { EntryRootStateContext } from "./store/EntryColumnContext" function EntryColumnContent() { @@ -53,8 +54,20 @@ function EntryColumnContent() { }, []) const actions = useEntriesActions() + const [resetScrollSignal, setResetScrollSignal] = useState() + const [appliedResetScrollSignal, setAppliedResetScrollSignal] = useState() + const isScrollResetPending = shouldSuspendMarkReadForScrollReset({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }) + const handleResetScrollSignalConsumed = useCallback((signal: number) => { + setAppliedResetScrollSignal((currentSignal) => + currentSignal === signal ? currentSignal : signal, + ) + }, []) const scrollTimelineToTop = useCallback(() => { resetScrollInteractionState() + setResetScrollSignal((signal) => (signal ?? 0) + 1) const runScrollToTop = () => { listRef.current?.scrollToOffset(0) @@ -155,6 +168,10 @@ function EntryColumnContent() { ) const handleScroll = useCallback(() => { + if (isScrollResetPending) { + return + } + if (!isInteracted.current) { isInteracted.current = true } @@ -162,7 +179,7 @@ function EntryColumnContent() { if (latestRangeStartIndexRef.current !== null) { flushScrollMarkRead(latestRangeStartIndexRef.current) } - }, [flushScrollMarkRead]) + }, [flushScrollMarkRead, isScrollResetPending]) const { handleScroll: handleScrollBeyond } = useAttachScrollBeyond() const handleCombinedScroll = useCallback( @@ -185,6 +202,10 @@ function EntryColumnContent() { } latestRangeStartIndexRef.current = e.startIndex + if (isScrollResetPending) { + return + } + if (scrollMarkReadAnchorIndexRef.current === null) { scrollMarkReadAnchorIndexRef.current = e.startIndex } else if (isInteracted.current) { @@ -198,7 +219,7 @@ function EntryColumnContent() { // For gird, render as mark read logic handleRenderMarkRead?.(e, isInteracted.current) }, - [flushScrollMarkRead, handleRenderMarkRead, renderAsRead, view], + [flushScrollMarkRead, handleRenderMarkRead, isScrollResetPending, renderAsRead, view], ) const fetchNextPage = useCallback(() => { @@ -257,6 +278,10 @@ function EntryColumnContent() { fetchNextPage={fetchNextPage} refetch={actions.refetch} groupCounts={groupedCounts} + appliedResetScrollSignal={appliedResetScrollSignal} + onResetScrollSignalConsumed={handleResetScrollSignalConsumed} + resetScrollSignal={resetScrollSignal} + suspendMarkRead={isScrollResetPending} syncType={state.type} Footer={ isCollection ? void 0 : diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/list.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/list.tsx index a6748179a..705eceb42 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/list.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/list.tsx @@ -8,7 +8,7 @@ import type { Range, VirtualItem, Virtualizer } from "@tanstack/react-virtual" import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual" import type { HTMLMotionProps } from "motion/react" import type { FC, MutableRefObject, ReactNode } from "react" -import { memo, startTransition, useEffect, useMemo, useRef, useState } from "react" +import { memo, startTransition, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react" import { useTranslation } from "react-i18next" import { useEventCallback } from "usehooks-ts" @@ -20,6 +20,7 @@ import { VirtualRowItem } from "./components/VirtualRowItem" import { EntryColumnShortcutHandler } from "./EntryColumnShortcutHandler" import { EntryItemSkeleton } from "./EntryItemSkeleton" import { useScrollMarkReadEndPadding } from "./hooks/useScrollMarkReadEndPadding" +import { getInitialScrollOffset, shouldApplyScrollResetSignal } from "./scroll-reset" export const EntryEmptyList = ({ ref, @@ -66,6 +67,10 @@ export type EntryListProps = { onRangeChange?: (range: Range) => void listRef?: MutableRefObject | undefined> + appliedResetScrollSignal?: number + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean } const capacity = 3 @@ -91,6 +96,9 @@ export const EntryList: FC = memo( onRangeChange, gap, syncType, + appliedResetScrollSignal, + onResetScrollSignalConsumed, + resetScrollSignal, }) => { const scrollRef = useScrollViewElement() const hasEndSpacer = shouldRenderScrollMarkReadEndSpacer({ @@ -114,13 +122,21 @@ export const EntryList: FC = memo( ) const cacheKey = `${view}-${feedId}` + const isResetScrollPending = shouldApplyScrollResetSignal({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }) const rowVirtualizer = useVirtualizer({ count: entriesIds.length + 1, estimateSize: () => 112, overscan: 5, gap, getScrollElement: () => scrollRef, - initialOffset: offsetCache.get(cacheKey) ?? 0, + initialOffset: getInitialScrollOffset({ + cachedOffset: offsetCache.get(cacheKey), + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }), initialMeasurementsCache: measurementsCache.get(cacheKey) ?? [], onChange: useTypeScriptHappyCallback( (virtualizer: Virtualizer) => { @@ -151,6 +167,25 @@ export const EntryList: FC = memo( listRef.current = rowVirtualizer }, [rowVirtualizer, listRef]) + useLayoutEffect(() => { + if (!scrollRef) return + if (!isResetScrollPending) return + if (resetScrollSignal === undefined) return + + rowVirtualizer.scrollToOffset(0) + scrollRef.scrollTop = 0 + scrollRef.scrollLeft = 0 + offsetCache.put(cacheKey, 0) + onResetScrollSignalConsumed?.(resetScrollSignal) + }, [ + cacheKey, + isResetScrollPending, + onResetScrollSignalConsumed, + resetScrollSignal, + rowVirtualizer, + scrollRef, + ]) + const handleScrollTo = useEventCallback((index: number) => { rowVirtualizer.scrollToIndex(index) }) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.test.ts b/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.test.ts new file mode 100644 index 000000000..20161efe1 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "vitest" + +import { + getInitialScrollOffset, + shouldApplyScrollResetSignal, + shouldSuspendMarkReadForScrollReset, +} from "./scroll-reset" + +describe("shouldApplyScrollResetSignal", () => { + test("applies a new reset signal that has not been flushed yet", () => { + expect(shouldApplyScrollResetSignal({ resetSignal: 1, appliedResetSignal: undefined })).toBe( + true, + ) + expect(shouldApplyScrollResetSignal({ resetSignal: 2, appliedResetSignal: 1 })).toBe(true) + }) + + test("does not apply missing or already flushed reset signals", () => { + expect( + shouldApplyScrollResetSignal({ + resetSignal: undefined, + appliedResetSignal: undefined, + }), + ).toBe(false) + expect(shouldApplyScrollResetSignal({ resetSignal: 1, appliedResetSignal: 1 })).toBe(false) + }) + + test("uses top offset while reset is pending", () => { + expect( + getInitialScrollOffset({ + cachedOffset: 320, + resetSignal: 1, + appliedResetSignal: undefined, + }), + ).toBe(0) + + expect( + getInitialScrollOffset({ + cachedOffset: 320, + resetSignal: 1, + appliedResetSignal: 1, + }), + ).toBe(320) + }) + + test("suspends mark-read while reset is pending", () => { + expect( + shouldSuspendMarkReadForScrollReset({ + resetSignal: 1, + appliedResetSignal: undefined, + }), + ).toBe(true) + expect( + shouldSuspendMarkReadForScrollReset({ + resetSignal: 1, + appliedResetSignal: 1, + }), + ).toBe(false) + }) +}) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.ts b/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.ts new file mode 100644 index 000000000..a75d9ae1a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/scroll-reset.ts @@ -0,0 +1,25 @@ +type ScrollResetSignalState = { + resetSignal?: number + appliedResetSignal?: number +} + +export const shouldApplyScrollResetSignal = ({ + resetSignal, + appliedResetSignal, +}: ScrollResetSignalState) => resetSignal !== undefined && resetSignal !== appliedResetSignal + +export const shouldSuspendMarkReadForScrollReset = shouldApplyScrollResetSignal + +export const getInitialScrollOffset = ({ + cachedOffset, + resetSignal, + appliedResetSignal, +}: ScrollResetSignalState & { + cachedOffset: number | undefined +}) => + shouldApplyScrollResetSignal({ + resetSignal, + appliedResetSignal, + }) + ? 0 + : (cachedOffset ?? 0) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx index fef47f284..ed19fccf1 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx @@ -36,8 +36,14 @@ export const EntryListContentArticle = ({ entryIds, active, view, + onResetScrollSignalConsumed, + resetScrollSignal, + suspendMarkRead, }: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & { ref?: React.Ref | null> + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean }) => { const extraData: EntryExtraData = useMemo(() => ({ entryIds }), [entryIds]) const readableItemStyle = useReadableContainerStyle(860, 16) @@ -88,7 +94,7 @@ export const EntryListContentArticle = ({ const ref = useRef>(null) const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ - disabled: active === false || isFetching, + disabled: active === false || isFetching || suspendMarkRead, refreshing: isFetching && !isFetchingNextPage, }) @@ -129,6 +135,8 @@ export const EntryListContentArticle = ({ ref={ref} onRefresh={refetch} isRefetching={isRefetching} + onResetScrollSignalConsumed={onResetScrollSignalConsumed} + resetScrollSignal={resetScrollSignal} data={entryIds} extraData={extraData} keyExtractor={defaultKeyExtractor} diff --git a/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx b/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx index 85adc9efa..602123ea9 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx @@ -35,11 +35,19 @@ export const EntryListContentPicture = ({ entryIds, active, view, + onResetScrollSignalConsumed, + resetScrollSignal, + suspendMarkRead, ...rest }: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & Omit< FlashListProps, "data" | "renderItem" -> & { ref?: React.Ref | null> }) => { +> & { + ref?: React.Ref | null> + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean + }) => { const ref = useRef>(null) const isTablet = useIsTabletLayout() @@ -57,7 +65,7 @@ export const EntryListContentPicture = ({ active, }) const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ - disabled: active === false || isFetching, + disabled: active === false || isFetching || suspendMarkRead, refreshing: isFetching && !isFetchingNextPage, }) const translation = useGeneralSettingKey("translation") @@ -114,6 +122,8 @@ export const EntryListContentPicture = ({ | null> + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean }) => { const { fetchNextPage, @@ -69,7 +75,7 @@ export const EntryListContentSocial = ({ ) const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ - disabled: active === false || isFetching, + disabled: active === false || isFetching || suspendMarkRead, refreshing: isFetching && !isFetchingNextPage, }) @@ -92,6 +98,8 @@ export const EntryListContentSocial = ({ {}} isRefetching={false} + onResetScrollSignalConsumed={onResetScrollSignalConsumed} + resetScrollSignal={resetScrollSignal} data={Array.from({ length: 5 }).map((_, index) => `skeleton-${index}`)} keyExtractor={(id) => id} renderItem={EntryItemSkeleton} @@ -107,6 +115,8 @@ export const EntryListContentSocial = ({ refetch() }} isRefetching={isRefetching} + onResetScrollSignalConsumed={onResetScrollSignalConsumed} + resetScrollSignal={resetScrollSignal} data={entryIds} extraData={extraData} keyExtractor={(id) => id} diff --git a/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx b/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx index b6ddc7fa2..b66181aaf 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx @@ -28,11 +28,19 @@ export const EntryListContentVideo = ({ entryIds, active, view, + onResetScrollSignalConsumed, + resetScrollSignal, + suspendMarkRead, ...rest }: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & Omit< FlashListProps, "data" | "renderItem" -> & { ref?: React.Ref | null> }) => { +> & { + ref?: React.Ref | null> + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number + suspendMarkRead?: boolean + }) => { const ref = useRef>(null) useImperativeHandle(forwardRef, () => ref.current!) const isTablet = useIsTabletLayout() @@ -49,7 +57,7 @@ export const EntryListContentVideo = ({ active, }) const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ - disabled: active === false || isFetching, + disabled: active === false || isFetching || suspendMarkRead, refreshing: isFetching && !isFetchingNextPage, }) @@ -120,6 +128,8 @@ export const EntryListContentVideo = ({ >(active) + const [resetScrollSignal, setResetScrollSignal] = useState() + const [appliedResetScrollSignal, setAppliedResetScrollSignal] = useState() + const isScrollResetPending = shouldSuspendMarkReadForScrollReset({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignal, + }) + const requestScrollToTop = useCallback(() => { + setResetScrollSignal((signal) => (signal ?? 0) + 1) + }, []) + const handleResetScrollSignalConsumed = useCallback((signal: number) => { + setAppliedResetScrollSignal((currentSignal) => + currentSignal === signal ? currentSignal : signal, + ) + }, []) let ContentComponent: | typeof EntryListContentSocial @@ -65,11 +80,8 @@ function EntryListSelectorImpl({ entryIds, viewId, active = true }: EntryListSel const unreadOnly = useGeneralSettingKey("unreadOnly") useEffect(() => { - ref?.current?.scrollToOffset({ - offset: 0, - animated: false, - }) - }, [unreadOnly, ref]) + requestScrollToTop() + }, [requestScrollToTop, unreadOnly]) const { isFetching, isFetchingNextPage, isReady } = useEntries({ viewId, active }) const isRefreshing = isFetching && !isFetchingNextPage @@ -89,11 +101,8 @@ function EntryListSelectorImpl({ entryIds, viewId, active = true }: EntryListSel return } - ref?.current?.scrollToOffset({ - offset: 0, - animated: false, - }) - }, [active, isRefreshing, ref]) + requestScrollToTop() + }, [active, isRefreshing, requestScrollToTop]) const hasResetAfterReadyRef = useRef(false) useEffect(() => { @@ -105,37 +114,29 @@ function EntryListSelectorImpl({ entryIds, viewId, active = true }: EntryListSel if (!entryIds?.length) return if (hasResetAfterReadyRef.current) return - const frameId = requestAnimationFrame(() => { - ref?.current?.scrollToOffset({ - offset: 0, - animated: false, - }) - }) + requestScrollToTop() hasResetAfterReadyRef.current = true - - return () => { - cancelAnimationFrame(frameId) - } - }, [active, entryIds, isReady, ref, viewId]) + }, [active, entryIds, isReady, requestScrollToTop, viewId]) useEffect(() => { if (!active) return - const frameId = requestAnimationFrame(() => { - ref?.current?.scrollToOffset({ - offset: 0, - animated: false, - }) - }) - - return () => { - cancelAnimationFrame(frameId) - } - }, [active, ref, viewId]) + requestScrollToTop() + }, [active, requestScrollToTop, viewId]) useAutoScrollToEntryAfterPullUpToNext(ref, entryIds || []) - return + return ( + + ) } export const EntryListSelector = withErrorBoundary( diff --git a/apps/mobile/src/modules/entry-list/hooks.ts b/apps/mobile/src/modules/entry-list/hooks.ts index a6f5851a8..06188176c 100644 --- a/apps/mobile/src/modules/entry-list/hooks.ts +++ b/apps/mobile/src/modules/entry-list/hooks.ts @@ -8,6 +8,8 @@ import type { NativeScrollEvent, NativeSyntheticEvent } from "react-native" import { useGeneralSettingKey } from "@/src/atoms/settings/general" +import { shouldCollectViewableItemsForMarkRead } from "./viewable-mark-read" + const defaultIdExtractor = (item: ViewToken) => item.key export function useOnViewableItemsChanged({ disabled, @@ -42,9 +44,21 @@ export function useOnViewableItemsChanged({ debouncedFetchEntryContentByStream(viewableItems.map((item) => stableIdExtractor(item))) const removed = changed.filter((item) => !item.isViewable) + if (disabled) { + setLastRemovedItems(null) + setLastViewableItems(null) + return + } + // Only when the scroll direction is down and the current offset is a positive number, is it marked as read. // This can avoid misjudgment during the rebound of the pull-to-refresh (because the offset will change from negative to zero during the rebound). - if (orientation.current === "down" && lastOffset.current > 0) { + if ( + shouldCollectViewableItemsForMarkRead({ + disabled, + isScrollingDown: orientation.current === "down", + offset: lastOffset.current, + }) + ) { setLastViewableItems(viewableItems) if (pauseScrollMarkRead) { setLastRemovedItems(null) diff --git a/apps/mobile/src/modules/entry-list/viewable-mark-read.test.ts b/apps/mobile/src/modules/entry-list/viewable-mark-read.test.ts new file mode 100644 index 000000000..cf6f40600 --- /dev/null +++ b/apps/mobile/src/modules/entry-list/viewable-mark-read.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "vitest" + +import { shouldCollectViewableItemsForMarkRead } from "./viewable-mark-read" + +describe("shouldCollectViewableItemsForMarkRead", () => { + test("does not collect viewable items while disabled", () => { + expect( + shouldCollectViewableItemsForMarkRead({ + disabled: true, + isScrollingDown: true, + offset: 120, + }), + ).toBe(false) + }) + + test("collects viewable items only when scrolling down beyond the top", () => { + expect( + shouldCollectViewableItemsForMarkRead({ + disabled: false, + isScrollingDown: true, + offset: 120, + }), + ).toBe(true) + expect( + shouldCollectViewableItemsForMarkRead({ + disabled: false, + isScrollingDown: false, + offset: 120, + }), + ).toBe(false) + expect( + shouldCollectViewableItemsForMarkRead({ + disabled: false, + isScrollingDown: true, + offset: 0, + }), + ).toBe(false) + }) +}) diff --git a/apps/mobile/src/modules/entry-list/viewable-mark-read.ts b/apps/mobile/src/modules/entry-list/viewable-mark-read.ts new file mode 100644 index 000000000..7be7642ac --- /dev/null +++ b/apps/mobile/src/modules/entry-list/viewable-mark-read.ts @@ -0,0 +1,9 @@ +export const shouldCollectViewableItemsForMarkRead = ({ + disabled, + isScrollingDown, + offset, +}: { + disabled?: boolean + isScrollingDown: boolean + offset: number +}) => !disabled && isScrollingDown && offset > 0 diff --git a/apps/mobile/src/modules/screen/TimelineSelectorList.tsx b/apps/mobile/src/modules/screen/TimelineSelectorList.tsx index affac8f9e..11133427b 100644 --- a/apps/mobile/src/modules/screen/TimelineSelectorList.tsx +++ b/apps/mobile/src/modules/screen/TimelineSelectorList.tsx @@ -5,7 +5,7 @@ import { nextFrame } from "@follow/utils" import type { FlashListProps, FlashListRef } from "@shopify/flash-list" import { FlashList } from "@shopify/flash-list" import * as Haptics from "expo-haptics" -import { use, useCallback, useImperativeHandle, useRef } from "react" +import { use, useCallback, useEffect, useImperativeHandle, useRef } from "react" import type { NativeScrollEvent, NativeSyntheticEvent } from "react-native" import { RefreshControl, View } from "react-native" import { useSafeAreaInsets } from "react-native-safe-area-context" @@ -16,16 +16,59 @@ import { ScreenItemContext } from "@/src/lib/navigation/ScreenItemContext" import { useHeaderHeight } from "@/src/modules/screen/hooks/useHeaderHeight" import { EntryListEmpty } from "../entry-list/EntryListEmpty" +import { shouldApplyScrollResetSignal } from "./scroll-reset" type Props = { onRefresh: () => void isRefetching: boolean + onResetScrollSignalConsumed?: (signal: number) => void + resetScrollSignal?: number +} + +const usePendingScrollReset = ( + resetScrollSignal: number | undefined, + scrollToTop: () => boolean, + onResetScrollSignalConsumed?: (signal: number) => void, +) => { + const appliedResetScrollSignalRef = useRef(undefined) + const canApplyScrollResetRef = useRef(false) + const flushPendingScrollReset = useCallback(() => { + if (!canApplyScrollResetRef.current) return + if ( + !shouldApplyScrollResetSignal({ + resetSignal: resetScrollSignal, + appliedResetSignal: appliedResetScrollSignalRef.current, + }) + ) { + return + } + + requestAnimationFrame(() => { + if (scrollToTop()) { + appliedResetScrollSignalRef.current = resetScrollSignal + if (resetScrollSignal !== undefined) { + onResetScrollSignalConsumed?.(resetScrollSignal) + } + } + }) + }, [onResetScrollSignalConsumed, resetScrollSignal, scrollToTop]) + + useEffect(() => { + flushPendingScrollReset() + }, [flushPendingScrollReset]) + + return useCallback(() => { + canApplyScrollResetRef.current = true + flushPendingScrollReset() + }, [flushPendingScrollReset]) } export const TimelineSelectorList = ({ ref: forwardedRef, onRefresh, isRefetching, + onResetScrollSignalConsumed, + resetScrollSignal, ...props }: Props & Omit, "onRefresh"> & { ref?: React.Ref | null> }) => { @@ -38,6 +81,23 @@ export const TimelineSelectorList = ({ const { scrollViewHeight, scrollViewContentHeight, reAnimatedScrollY } = use(ScreenItemContext)! const tabBarHeight = useBottomTabBarHeight() + const scrollToTop = useCallback(() => { + const scroller = ref.current + if (!scroller) return false + + scroller.scrollToOffset({ + offset: 0, + animated: false, + }) + reAnimatedScrollY.value = 0 + return true + }, [reAnimatedScrollY]) + const markScrollResetReady = usePendingScrollReset( + resetScrollSignal, + scrollToTop, + onResetScrollSignalConsumed, + ) + const onScroll = useCallback( (e: NativeSyntheticEvent) => { props.onScroll?.(e) @@ -50,17 +110,31 @@ export const TimelineSelectorList = ({ const onLayout = useTypeScriptHappyCallback( (e) => { + props.onLayout?.(e) scrollViewHeight.value = e.nativeEvent.layout.height - headerHeight - tabBarHeight }, - [scrollViewHeight], + [headerHeight, props, scrollViewHeight, tabBarHeight], ) as FlashListProps["onLayout"] const onContentSizeChange = useTypeScriptHappyCallback( (w, h) => { + props.onContentSizeChange?.(w, h) scrollViewContentHeight.value = h + markScrollResetReady() }, - [scrollViewContentHeight], + [markScrollResetReady, props, scrollViewContentHeight], ) as FlashListProps["onContentSizeChange"] + const onLoad = useTypeScriptHappyCallback( + (info) => { + props.onLoad?.(info) + markScrollResetReady() + }, + [markScrollResetReady, props], + ) as FlashListProps["onLoad"] + const onCommitLayoutEffect = useTypeScriptHappyCallback(() => { + props.onCommitLayoutEffect?.() + markScrollResetReady() + }, [markScrollResetReady, props]) as FlashListProps["onCommitLayoutEffect"] if (props.data?.length === 0) { return @@ -72,8 +146,6 @@ export const TimelineSelectorList = ({ automaticallyAdjustsScrollIndicatorInsets={false} automaticallyAdjustContentInsets={false} ref={ref} - onLayout={onLayout} - onContentSizeChange={onContentSizeChange} refreshControl={ { nextFrame(() => { @@ -109,9 +185,11 @@ export const TimelineSelectorList = ({ } export const TimelineSelectorMasonryList = ({ - ref, + ref: forwardedRef, onRefresh, isRefetching, + onResetScrollSignalConsumed, + resetScrollSignal, ...props }: Props & Omit, "onRefresh"> & { @@ -119,12 +197,30 @@ export const TimelineSelectorMasonryList = ({ }) => { const { refetch: unreadRefetch } = usePrefetchUnread() const { refetch: subscriptionRefetch } = usePrefetchSubscription() + const ref = useRef>(null) + useImperativeHandle(forwardedRef, () => ref.current!) const insets = useSafeAreaInsets() const headerHeight = useHeaderHeight() const { reAnimatedScrollY } = use(ScreenItemContext)! + const scrollToTop = useCallback(() => { + const scroller = ref.current + if (!scroller) return false + + scroller.scrollToOffset({ + offset: 0, + animated: false, + }) + reAnimatedScrollY.value = 0 + return true + }, [reAnimatedScrollY]) + const markScrollResetReady = usePendingScrollReset( + resetScrollSignal, + scrollToTop, + onResetScrollSignalConsumed, + ) const onScroll = useCallback( (e: NativeSyntheticEvent) => { @@ -135,6 +231,24 @@ export const TimelineSelectorMasonryList = ({ ) const tabBarHeight = useBottomTabBarHeight() + const onContentSizeChange = useTypeScriptHappyCallback( + (w, h) => { + props.onContentSizeChange?.(w, h) + markScrollResetReady() + }, + [markScrollResetReady, props], + ) as FlashListProps["onContentSizeChange"] + const onLoad = useTypeScriptHappyCallback( + (info) => { + props.onLoad?.(info) + markScrollResetReady() + }, + [markScrollResetReady, props], + ) as FlashListProps["onLoad"] + const onCommitLayoutEffect = useTypeScriptHappyCallback(() => { + props.onCommitLayoutEffect?.() + markScrollResetReady() + }, [markScrollResetReady, props]) as FlashListProps["onCommitLayoutEffect"] const systemFill = useColor("secondaryLabel") @@ -160,6 +274,9 @@ export const TimelineSelectorMasonryList = ({ /> } {...props} + onLoad={onLoad} + onCommitLayoutEffect={onCommitLayoutEffect} + onContentSizeChange={onContentSizeChange} contentContainerStyle={[ { paddingTop: headerHeight, diff --git a/apps/mobile/src/modules/screen/scroll-reset.test.ts b/apps/mobile/src/modules/screen/scroll-reset.test.ts new file mode 100644 index 000000000..164fef019 --- /dev/null +++ b/apps/mobile/src/modules/screen/scroll-reset.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from "vitest" + +import { shouldApplyScrollResetSignal, shouldSuspendMarkReadForScrollReset } from "./scroll-reset" + +describe("shouldApplyScrollResetSignal", () => { + test("applies a new reset signal that has not been flushed yet", () => { + expect(shouldApplyScrollResetSignal({ resetSignal: 1, appliedResetSignal: undefined })).toBe( + true, + ) + expect(shouldApplyScrollResetSignal({ resetSignal: 2, appliedResetSignal: 1 })).toBe(true) + }) + + test("does not apply missing or already flushed reset signals", () => { + expect( + shouldApplyScrollResetSignal({ + resetSignal: undefined, + appliedResetSignal: undefined, + }), + ).toBe(false) + expect(shouldApplyScrollResetSignal({ resetSignal: 1, appliedResetSignal: 1 })).toBe(false) + }) + + test("suspends mark-read while reset is pending", () => { + expect( + shouldSuspendMarkReadForScrollReset({ + resetSignal: 1, + appliedResetSignal: undefined, + }), + ).toBe(true) + expect( + shouldSuspendMarkReadForScrollReset({ + resetSignal: 1, + appliedResetSignal: 1, + }), + ).toBe(false) + }) +}) diff --git a/apps/mobile/src/modules/screen/scroll-reset.ts b/apps/mobile/src/modules/screen/scroll-reset.ts new file mode 100644 index 000000000..92a6c32f1 --- /dev/null +++ b/apps/mobile/src/modules/screen/scroll-reset.ts @@ -0,0 +1,11 @@ +type ScrollResetSignalState = { + resetSignal?: number + appliedResetSignal?: number +} + +export const shouldApplyScrollResetSignal = ({ + resetSignal, + appliedResetSignal, +}: ScrollResetSignalState) => resetSignal !== undefined && resetSignal !== appliedResetSignal + +export const shouldSuspendMarkReadForScrollReset = shouldApplyScrollResetSignal