fix(timeline): guard mark read during scroll reset

This commit is contained in:
DIYgod
2026-06-02 10:04:30 +08:00
parent fe1fcff315
commit 2ed4ac546b
17 changed files with 543 additions and 56 deletions
@@ -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<MasonryProps> = (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<MasonryProps> = (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<MasonryProps> = (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<MasonryProps> = (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 = () => {
@@ -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<EntryListProps> = (props) => {
const { entriesIds, feedId, hasNextPage, view, fetchNextPage } = props
@@ -40,6 +41,10 @@ export const EntryColumnGrid: FC<EntryListProps> = (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<HTMLElement, Element>) => {
@@ -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()
@@ -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<number>()
const [appliedResetScrollSignal, setAppliedResetScrollSignal] = useState<number>()
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 : <FooterMarkItem view={view} fetchedTime={state.fetchedTime} />
@@ -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<Virtualizer<HTMLElement, Element> | undefined>
appliedResetScrollSignal?: number
onResetScrollSignalConsumed?: (signal: number) => void
resetScrollSignal?: number
suspendMarkRead?: boolean
}
const capacity = 3
@@ -91,6 +96,9 @@ export const EntryList: FC<EntryListProps> = memo(
onRangeChange,
gap,
syncType,
appliedResetScrollSignal,
onResetScrollSignalConsumed,
resetScrollSignal,
}) => {
const scrollRef = useScrollViewElement()
const hasEndSpacer = shouldRenderScrollMarkReadEndSpacer({
@@ -114,13 +122,21 @@ export const EntryList: FC<EntryListProps> = 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<HTMLElement, Element>) => {
@@ -151,6 +167,25 @@ export const EntryList: FC<EntryListProps> = 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)
})
@@ -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)
})
})
@@ -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)
@@ -36,8 +36,14 @@ export const EntryListContentArticle = ({
entryIds,
active,
view,
onResetScrollSignalConsumed,
resetScrollSignal,
suspendMarkRead,
}: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & {
ref?: React.Ref<ElementRef<typeof TimelineSelectorList> | 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<FlashListRef<any>>(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}
@@ -35,11 +35,19 @@ export const EntryListContentPicture = ({
entryIds,
active,
view,
onResetScrollSignalConsumed,
resetScrollSignal,
suspendMarkRead,
...rest
}: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & Omit<
FlashListProps<string>,
"data" | "renderItem"
> & { ref?: React.Ref<ElementRef<typeof TimelineSelectorMasonryList> | null> }) => {
> & {
ref?: React.Ref<ElementRef<typeof TimelineSelectorMasonryList> | null>
onResetScrollSignalConsumed?: (signal: number) => void
resetScrollSignal?: number
suspendMarkRead?: boolean
}) => {
const ref = useRef<FlashListRef<any>>(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 = ({
<TimelineSelectorMasonryList
ref={ref}
isRefetching={isRefetching}
onResetScrollSignalConsumed={onResetScrollSignalConsumed}
resetScrollSignal={resetScrollSignal}
data={entryIds}
renderItem={renderItem}
keyExtractor={defaultKeyExtractor}
@@ -24,8 +24,14 @@ export const EntryListContentSocial = ({
entryIds,
active,
view,
onResetScrollSignalConsumed,
resetScrollSignal,
suspendMarkRead,
}: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & {
ref?: React.Ref<ElementRef<typeof TimelineSelectorList> | 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 = ({
<TimelineSelectorList
onRefresh={() => {}}
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}
@@ -28,11 +28,19 @@ export const EntryListContentVideo = ({
entryIds,
active,
view,
onResetScrollSignalConsumed,
resetScrollSignal,
suspendMarkRead,
...rest
}: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & Omit<
FlashListProps<string>,
"data" | "renderItem"
> & { ref?: React.Ref<ElementRef<typeof TimelineSelectorMasonryList> | null> }) => {
> & {
ref?: React.Ref<ElementRef<typeof TimelineSelectorMasonryList> | null>
onResetScrollSignalConsumed?: (signal: number) => void
resetScrollSignal?: number
suspendMarkRead?: boolean
}) => {
const ref = useRef<FlashListRef<any>>(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 = ({
<TimelineSelectorMasonryList
ref={ref}
isRefetching={isRefetching}
onResetScrollSignalConsumed={onResetScrollSignalConsumed}
resetScrollSignal={resetScrollSignal}
data={entryIds}
renderItem={renderItem}
keyExtractor={defaultKeyExtractor}
@@ -2,7 +2,7 @@ import { FeedViewType } from "@follow/constants"
import { useWhoami } from "@follow/store/user/hooks"
import type { FlashListRef } from "@shopify/flash-list"
import type { RefObject } from "react"
import { useEffect, useRef } from "react"
import { useCallback, useEffect, useRef, useState } from "react"
import { useGeneralSettingKey } from "@/src/atoms/settings/general"
import { withErrorBoundary } from "@/src/components/common/ErrorBoundary"
@@ -14,6 +14,7 @@ import { EntryListContentPicture } from "@/src/modules/entry-list/EntryListConte
import { EntryDetailScreen } from "@/src/screens/(stack)/entries/[entryId]/EntryDetailScreen"
import { useEntries, useEntryListContext } from "../screen/atoms"
import { shouldSuspendMarkReadForScrollReset } from "../screen/scroll-reset"
import { EntryListContentArticle } from "./EntryListContentArticle"
import { EntryListContentSocial } from "./EntryListContentSocial"
import { EntryListContentVideo } from "./EntryListContentVideo"
@@ -38,6 +39,20 @@ type EntryListSelectorProps = {
function EntryListSelectorImpl({ entryIds, viewId, active = true }: EntryListSelectorProps) {
const ref = useRegisterNavigationScrollView<FlashListRef<any>>(active)
const [resetScrollSignal, setResetScrollSignal] = useState<number>()
const [appliedResetScrollSignal, setAppliedResetScrollSignal] = useState<number>()
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 <ContentComponent ref={ref} entryIds={entryIds} active={active} view={viewId} />
return (
<ContentComponent
ref={ref}
entryIds={entryIds}
active={active}
view={viewId}
onResetScrollSignalConsumed={handleResetScrollSignalConsumed}
resetScrollSignal={resetScrollSignal}
suspendMarkRead={isScrollResetPending}
/>
)
}
export const EntryListSelector = withErrorBoundary(
+15 -1
View File
@@ -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<string>) => 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)
@@ -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)
})
})
@@ -0,0 +1,9 @@
export const shouldCollectViewableItemsForMarkRead = ({
disabled,
isScrollingDown,
offset,
}: {
disabled?: boolean
isScrollingDown: boolean
offset: number
}) => !disabled && isScrollingDown && offset > 0
@@ -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<number | undefined>(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<FlashListProps<any>, "onRefresh"> & { ref?: React.Ref<FlashListRef<any> | 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<NativeScrollEvent>) => {
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<any>["onLayout"]
const onContentSizeChange = useTypeScriptHappyCallback(
(w, h) => {
props.onContentSizeChange?.(w, h)
scrollViewContentHeight.value = h
markScrollResetReady()
},
[scrollViewContentHeight],
[markScrollResetReady, props, scrollViewContentHeight],
) as FlashListProps<any>["onContentSizeChange"]
const onLoad = useTypeScriptHappyCallback(
(info) => {
props.onLoad?.(info)
markScrollResetReady()
},
[markScrollResetReady, props],
) as FlashListProps<any>["onLoad"]
const onCommitLayoutEffect = useTypeScriptHappyCallback(() => {
props.onCommitLayoutEffect?.()
markScrollResetReady()
}, [markScrollResetReady, props]) as FlashListProps<any>["onCommitLayoutEffect"]
if (props.data?.length === 0) {
return <EntryListEmpty />
@@ -72,8 +146,6 @@ export const TimelineSelectorList = ({
automaticallyAdjustsScrollIndicatorInsets={false}
automaticallyAdjustContentInsets={false}
ref={ref}
onLayout={onLayout}
onContentSizeChange={onContentSizeChange}
refreshControl={
<RefreshControl
progressViewOffset={headerHeight}
@@ -97,6 +169,10 @@ export const TimelineSelectorList = ({
paddingBottom: tabBarHeight,
}}
{...props}
onLayout={onLayout}
onLoad={onLoad}
onCommitLayoutEffect={onCommitLayoutEffect}
onContentSizeChange={onContentSizeChange}
onScroll={onScroll}
onEndReached={() => {
nextFrame(() => {
@@ -109,9 +185,11 @@ export const TimelineSelectorList = ({
}
export const TimelineSelectorMasonryList = ({
ref,
ref: forwardedRef,
onRefresh,
isRefetching,
onResetScrollSignalConsumed,
resetScrollSignal,
...props
}: Props &
Omit<FlashListProps<any>, "onRefresh"> & {
@@ -119,12 +197,30 @@ export const TimelineSelectorMasonryList = ({
}) => {
const { refetch: unreadRefetch } = usePrefetchUnread()
const { refetch: subscriptionRefetch } = usePrefetchSubscription()
const ref = useRef<FlashListRef<any>>(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<NativeScrollEvent>) => {
@@ -135,6 +231,24 @@ export const TimelineSelectorMasonryList = ({
)
const tabBarHeight = useBottomTabBarHeight()
const onContentSizeChange = useTypeScriptHappyCallback(
(w, h) => {
props.onContentSizeChange?.(w, h)
markScrollResetReady()
},
[markScrollResetReady, props],
) as FlashListProps<any>["onContentSizeChange"]
const onLoad = useTypeScriptHappyCallback(
(info) => {
props.onLoad?.(info)
markScrollResetReady()
},
[markScrollResetReady, props],
) as FlashListProps<any>["onLoad"]
const onCommitLayoutEffect = useTypeScriptHappyCallback(() => {
props.onCommitLayoutEffect?.()
markScrollResetReady()
}, [markScrollResetReady, props]) as FlashListProps<any>["onCommitLayoutEffect"]
const systemFill = useColor("secondaryLabel")
@@ -160,6 +274,9 @@ export const TimelineSelectorMasonryList = ({
/>
}
{...props}
onLoad={onLoad}
onCommitLayoutEffect={onCommitLayoutEffect}
onContentSizeChange={onContentSizeChange}
contentContainerStyle={[
{
paddingTop: headerHeight,
@@ -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)
})
})
@@ -0,0 +1,11 @@
type ScrollResetSignalState = {
resetSignal?: number
appliedResetSignal?: number
}
export const shouldApplyScrollResetSignal = ({
resetSignal,
appliedResetSignal,
}: ScrollResetSignalState) => resetSignal !== undefined && resetSignal !== appliedResetSignal
export const shouldSuspendMarkReadForScrollReset = shouldApplyScrollResetSignal