diff --git a/src/features/followingV2/home/FeedPage.tsx b/src/features/followingV2/home/FeedPage.tsx index 64a0cc218..c5f2b1422 100644 --- a/src/features/followingV2/home/FeedPage.tsx +++ b/src/features/followingV2/home/FeedPage.tsx @@ -9,7 +9,11 @@ import { import {View} from 'react-native' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' -import {type NavigationProp, useNavigation} from '@react-navigation/native' +import { + type NavigationProp, + useIsFocused, + useNavigation, +} from '@react-navigation/native' import {DISCOVER_FEED_URI, VIDEO_FEED_URIS} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -64,6 +68,7 @@ export function FeedPage({ const {hasSession} = useSession() const {_} = useLingui() const navigation = useNavigation>() + const isScreenFocused = useIsFocused() const {openComposer} = useOpenComposer() const [isScrolledDown, setIsScrolledDown] = useState(false) const headerOffset = useHeaderOffset() @@ -146,6 +151,7 @@ export function FeedPage({ enabled?: boolean + /** + * Whether this is the feed on screen: the focused page of a focused Home. + * Only then does it offer restored posts with the pill. + */ + isActive?: boolean pollInterval?: number disablePoll?: boolean scrollElRef?: ListRef @@ -390,16 +399,8 @@ let PostFeed = ({ const settleAtTop = useSettleAtTop(feed, feedParams, { enabled: isAnchored && enabled !== false, }) - /** - * The list's scroll handlers. Settling judges the offset as the list reports - * it, as it has to know whether the list is really at the top. The Home - * header sees it with the corrections anchoring makes taken out, so they - * can't hide or show it. - */ - const scrollHandlers = useSettleScrollHandlers( - listRest.scrollHandlers, - isAnchored ? settleAtTop : undefined, - ) + /** The list's scroll offset, which its scroll handlers keep. */ + const listOffsetY = useSharedValue(0) /** * The top page a refresh from this view wrote, to take the reader up to once @@ -912,6 +913,43 @@ let PostFeed = ({ trendingIndices, ]) + const restorePill = useRestorePill({ + enabled: isAnchored, + isActive, + prependedAt: restore.prependedAt, + rows: feedItems, + // Without samples, which the pill never offers. + pages: feedData?.pages, + offsetY: listOffsetY, + scrollToTop: () => { + scrollElRef?.current?.scrollToOffset({ + animated: true, + offset: -headerOffset, + }) + }, + }) + const onRestorePillItemSeen = useNonReactiveCallback(restorePill.onItemSeen) + /** + * The list's scroll handlers. Settling and the pill judge the offset as the + * list reports it, as they have to know where the list really is. The Home + * header sees it with the corrections anchoring makes taken out, so they + * can't hide or show it. + */ + const scrollHandlers = useSettleScrollHandlers( + listRest.scrollHandlers, + isAnchored + ? { + ...settleAtTop, + onBeginDrag: () => { + settleAtTop.onBeginDrag() + restorePill.onBeginDrag() + }, + onReachTop: restorePill.onReachTop, + } + : undefined, + listOffsetY, + ) + // events // = // @@ -1207,6 +1245,7 @@ let PostFeed = ({ const onItemSeen = useCallback( (item: FeedRow) => { feedFeedback.onItemSeen(item) + onRestorePillItemSeen(item) // Events that should fire exactly once for every new post, regardless of // its position within a slice or video grid row. @@ -1327,7 +1366,14 @@ let PostFeed = ({ } } }, - [feedFeedback, feed, liveNowConfig, getPostPosition, ax], + [ + feedFeedback, + onRestorePillItemSeen, + feed, + liveNowConfig, + getPostPosition, + ax, + ], ) return ( @@ -1367,6 +1413,14 @@ let PostFeed = ({ onLayout={isAnchored ? listRest.onLayout : undefined} /> + {isAnchored && ( + + )} ) } diff --git a/src/features/followingV2/home/RestorePill.tsx b/src/features/followingV2/home/RestorePill.tsx new file mode 100644 index 000000000..5f102b448 --- /dev/null +++ b/src/features/followingV2/home/RestorePill.tsx @@ -0,0 +1,84 @@ +import Animated, {useAnimatedStyle} from 'react-native-reanimated' +import {useSafeAreaInsets} from 'react-native-safe-area-context' +import {plural} from '@lingui/core/macro' + +import {HITSLOP_20} from '#/lib/constants' +import {useShellLayout} from '#/state/shell/shell-layout' +import {useHomeHeaderMode} from '#/view/com/util/MainScrollProvider' +import {atoms as a} from '#/alf' +import {NewPostsPill, type NewPostsPillAuthor} from '#/components/NewPostsPill' +import {IS_LIQUID_GLASS} from '#/env' + +/** Space between the bottom edge of the Home header and the pill. */ +const HEADER_GAP = 16 + +/* + * A full-width strip whose top edge sits on the header's bottom edge. It + * clips, so the pill slides out from behind that edge, and back behind it, + * even under liquid glass, where the collapsed header leaves only a + * transparent strip under the status bar. The bottom padding keeps the pill's + * hit slop inside the clip. The strip itself takes no touches. + */ +const strip = [ + a.absolute, + a.overflow_hidden, + a.z_10, + { + top: 0, + left: 0, + right: 0, + paddingTop: HEADER_GAP, + paddingBottom: HITSLOP_20.bottom, + }, +] + +/** + * The new posts pill for restored Following on Home (see `useRestorePill`), + * beneath the Home header. It follows the header as it collapses, as + * `useHomeHeaderTransform` moves it, and comes to rest under the part of the + * header that stays on screen rather than hiding with it. Render it in a Home + * feed page, after its list. + * + * @platform ios, android + */ +export function RestorePill({ + visible, + count, + authors, + onPress, +}: { + visible: boolean + count: number + authors: NewPostsPillAuthor[] + onPress: () => void +}) { + const mode = useHomeHeaderMode() + const {headerHeight} = useShellLayout() + const {top: topInset} = useSafeAreaInsets() + // As `useHomeHeaderTransform` has it. + const pinnedHeight = IS_LIQUID_GLASS ? topInset : 0 + // Translate only: a transform moves it without a layout pass every frame. + const follow = useAnimatedStyle(() => { + const height = headerHeight.get() + return { + transform: [{translateY: height + mode.get() * (pinnedHeight - height)}], + } + }) + + return ( + + + + ) +} diff --git a/src/features/followingV2/home/queries/postFeed.test.tsx b/src/features/followingV2/home/queries/postFeed.test.tsx index cf362e9cb..8cbbb2a91 100644 --- a/src/features/followingV2/home/queries/postFeed.test.tsx +++ b/src/features/followingV2/home/queries/postFeed.test.tsx @@ -1107,6 +1107,7 @@ describe('usePostFeedRestorePrepend', () => { expect(writes).toHaveLength(0) expect(cached()).toBe(before) expect(hook.result.current.restore.isOwed()).toBe(false) + expect(hook.result.current.restore.prependedAt).toBeUndefined() }) it('puts a contiguous page on top, which the page below continues from', async () => { @@ -1122,6 +1123,10 @@ describe('usePostFeedRestorePrepend', () => { startCursor: 'start:0', since: 'start:1', }) + // The view knows which page it put on top, for the pill to offer. + expect(hook.result.current.restore.prependedAt).toBe( + cached().pages[0].fetchedAt, + ) expect(cached().pageParams).toEqual([ undefined, {cursor: 'start:1'}, @@ -1230,6 +1235,7 @@ describe('usePostFeedRestorePrepend', () => { expect(cached()).toBe(refreshed) expect(postsOf(cached())).toEqual([['fresh']]) + expect(hook.result.current.restore.prependedAt).toBeUndefined() }) it('while it holds what it found', async () => { @@ -1251,6 +1257,7 @@ describe('usePostFeedRestorePrepend', () => { expect(cached()).toBe(refreshed) expect(postsOf(cached())).toEqual([['fresh']]) expect(hook.result.current.restore.isOwed()).toBe(false) + expect(hook.result.current.restore.prependedAt).toBeUndefined() }) }) diff --git a/src/features/followingV2/home/queries/postFeed.ts b/src/features/followingV2/home/queries/postFeed.ts index d69caa691..63c676a55 100644 --- a/src/features/followingV2/home/queries/postFeed.ts +++ b/src/features/followingV2/home/queries/postFeed.ts @@ -561,7 +561,8 @@ const RESTORE_PREPEND_LIMIT = 100 * resolves, so the list takes it laid out and still, however long the reader * keeps it moving. It runs once per view, whatever it finds. `isOwed` says * whether it has yet to finish, holding a page included, for checks for new - * posts to wait for it. + * posts to wait for it, and `prependedAt` is the `fetchedAt` of the page it + * put on top, once it has. * * It fetches with `since` set to the top page's `startCursor`. Nothing newer * writes nothing. Anything newer goes on top as a page of its own, with the @@ -595,6 +596,7 @@ export function usePostFeedRestorePrepend( const queryKey = RQKEY(feedDesc, params) /** How far this view has got with its one go. */ const stage = useRef<'unstarted' | 'started' | 'finished'>('unstarted') + const [prependedAt, setPrependedAt] = useState() const isTopRestored = isRestored(topFetchedAt) const isOwed = () => { @@ -633,10 +635,18 @@ export function usePostFeedRestorePrepend( return } await listAtRest() - await commit(queryClient, queryKey, before, (data = before) => ({ - pages: [page, ...data.pages], - pageParams: [undefined, {cursor}, ...data.pageParams.slice(1)], - })) + const wrote = await commit( + queryClient, + queryKey, + before, + (data = before) => ({ + pages: [page, ...data.pages], + pageParams: [undefined, {cursor}, ...data.pageParams.slice(1)], + }), + ) + if (wrote) { + setPrependedAt(page.fetchedAt) + } } catch (e) { if (!isNetworkError(e)) { logger.error('Failed to fetch posts newer than a restored feed', { @@ -657,7 +667,7 @@ export function usePostFeedRestorePrepend( } }, [enabled, isTopRestored]) - return {isOwed} + return {isOwed, prependedAt} } /** diff --git a/src/features/followingV2/home/useRestorePill.test.ts b/src/features/followingV2/home/useRestorePill.test.ts new file mode 100644 index 000000000..a7dd05b48 --- /dev/null +++ b/src/features/followingV2/home/useRestorePill.test.ts @@ -0,0 +1,408 @@ +import {act, renderHook} from '@testing-library/react-native' + +import {newPostsPillPresentation} from '#/components/NewPostsPill/presentation' +import {type FeedPostSlice} from './queries/postFeed' +import { + getRestoreOffer, + liveRestoreOffer, + useRestorePill, +} from './useRestorePill' + +// Only its constant: its hooks need queries this doesn't set up. +jest.mock('./useSettleAtTop', () => ({SETTLE_AT_TOP_LIMIT: 5})) + +const RESTORED_AT = 1000 +const PREPENDED_AT = 2000 + +/** + * A feed item by `did`, whose own post is the last of `context` posts before + * it in its thread. + */ +function slice( + rkey: string, + { + did = `did:plc:${rkey}`, + avatar = `https://cdn.test/${rkey}.jpg`, + blur = false, + filter = false, + context = 0, + }: { + did?: string + avatar?: string + blur?: boolean + filter?: boolean + context?: number + } = {}, +): FeedPostSlice { + const uris = [ + ...Array.from( + {length: context}, + (_, i) => `at://did:plc:context/app.bsky.feed.post/${rkey}-${i}`, + ), + `at://${did}/app.bsky.feed.post/${rkey}`, + ] + return { + _isFeedPostSlice: true, + _reactKey: `slice-${rkey}`, + isIncompleteThread: false, + isFallbackMarker: false, + feedContext: undefined, + reqId: undefined, + feedPostUri: uris[uris.length - 1], + items: uris.map((uri, i) => ({ + _reactKey: `slice-${rkey}-${i}`, + uri, + post: { + uri, + author: i === context ? {did, avatar} : {did: 'did:plc:context'}, + }, + record: {}, + moderation: { + ui: (context: string) => + context === 'avatar' ? {blur, filter} : {blur: false, filter: false}, + }, + })), + } as unknown as FeedPostSlice +} + +/** The rows the list renders for `slices`: one per post. */ +function rowsOf(slices: FeedPostSlice[]) { + return slices.flatMap(slice => + slice.items.map((item, indexInSlice) => ({ + type: 'sliceItem', + key: item._reactKey, + slice, + indexInSlice, + })), + ) +} + +function page(fetchedAt: number, slices: FeedPostSlice[]) { + return {fetchedAt, slices} +} + +describe('getRestoreOffer', () => { + it('offers the posts from the page the prepend put on top', () => { + const fresh = [slice('a'), slice('b')] + const restored = [slice('old')] + const offer = getRestoreOffer( + rowsOf([...fresh, ...restored]), + page(PREPENDED_AT, fresh), + ) + + expect(offer).toEqual({ + topFetchedAt: PREPENDED_AT, + keys: ['slice-a-0', 'slice-b-0'], + count: 2, + authors: [ + {did: 'did:plc:a', avatar: 'https://cdn.test/a.jpg'}, + {did: 'did:plc:b', avatar: 'https://cdn.test/b.jpg'}, + ], + }) + }) + + it('counts a reply once, with its thread context', () => { + const reply = slice('reply', {context: 2}) + const offer = getRestoreOffer(rowsOf([reply]), page(PREPENDED_AT, [reply])) + + expect(offer?.count).toBe(1) + expect(offer?.keys).toEqual([ + 'slice-reply-0', + 'slice-reply-1', + 'slice-reply-2', + ]) + // The face is the reply's author, not the thread's. + expect(offer?.authors.map(author => author.did)).toEqual(['did:plc:reply']) + }) + + it('never offers saved-feed samples, the gap row or rows the list leaves out', () => { + const fresh = [slice('a'), slice('muted'), slice('b')] + const sample = slice('sample') + const rows = [ + ...rowsOf([fresh[0], sample, fresh[2]]), + {type: 'gap', key: 'gap-cursor'}, + ...rowsOf([slice('old')]), + ] + // The page is the one without samples, as PostFeed has it. + const offer = getRestoreOffer(rows, page(PREPENDED_AT, fresh)) + + expect(offer?.count).toBe(2) + expect(offer?.keys).toEqual(['slice-a-0', 'slice-b-0']) + expect(offer?.authors.map(author => author.did)).toEqual([ + 'did:plc:a', + 'did:plc:b', + ]) + }) + + it('offers nothing when none of the page renders', () => { + const fresh = [slice('muted')] + expect( + getRestoreOffer(rowsOf([slice('old')]), page(PREPENDED_AT, fresh)), + ).toBeUndefined() + }) + + it('shows up to three distinct faces, safe to show, in order', () => { + const fresh = [ + slice('a'), + slice('a2', {did: 'did:plc:a'}), + slice('noAvatar', {avatar: ''}), + slice('blurred', {blur: true}), + slice('filtered', {filter: true}), + slice('b'), + slice('c'), + slice('d'), + ] + const offer = getRestoreOffer(rowsOf(fresh), page(PREPENDED_AT, fresh)) + + expect(offer?.count).toBe(8) + expect(offer?.authors.map(author => author.did)).toEqual([ + 'did:plc:a', + 'did:plc:b', + 'did:plc:c', + ]) + }) + + it('makes a facepile from four posts with a face to show', () => { + const presentation = (slices: FeedPostSlice[]) => { + const offer = getRestoreOffer(rowsOf(slices), page(PREPENDED_AT, slices))! + return newPostsPillPresentation({ + variant: 'newPosts', + count: offer.count, + faceCount: offer.authors.length, + }) + } + + expect(presentation([slice('a'), slice('b'), slice('c')])).toBe('generic') + expect(presentation([slice('a'), slice('b'), slice('c'), slice('d')])).toBe( + 'facepile', + ) + expect( + presentation(['a', 'b', 'c', 'd'].map(rkey => slice(rkey, {blur: true}))), + ).toBe('generic') + }) +}) + +describe('liveRestoreOffer', () => { + const fresh = [slice('a'), slice('b'), slice('c')] + const offer = getRestoreOffer(rowsOf(fresh), page(PREPENDED_AT, fresh))! + + it('follows the rows that still render', () => { + expect(liveRestoreOffer(offer, rowsOf(fresh))).toEqual({ + topKey: 'slice-a-0', + authors: offer.authors, + }) + + // A or its author muted, and a label on C's avatar. + const now = liveRestoreOffer( + offer, + rowsOf([fresh[1], slice('c', {blur: true})]), + ) + expect(now.topKey).toBe('slice-b-0') + expect(now.authors.map(author => author.did)).toEqual(['did:plc:b']) + }) + + it('has no top once none of them render', () => { + expect(liveRestoreOffer(offer, rowsOf([slice('old')])).topKey).toBe( + undefined, + ) + }) +}) + +describe('useRestorePill', () => { + const fresh = [slice('a'), slice('b'), slice('c'), slice('d')] + const old = [slice('old')] + const restoredPages = [page(RESTORED_AT, old)] + const prependedPages = [page(PREPENDED_AT, fresh), page(RESTORED_AT, old)] + + type Props = { + enabled?: boolean + isActive?: boolean + prependedAt?: number + pages?: ReturnType[] + } + + function renderPill(initialProps: Props = {}) { + const offsetY = {value: 400, get: () => offsetY.value} + const scrollToTop = jest.fn() + const hook = renderHook( + ({ + enabled = true, + isActive = true, + prependedAt, + pages = restoredPages, + }: Props) => + useRestorePill({ + enabled, + isActive, + prependedAt, + pages, + rows: rowsOf(pages.flatMap(page => page.slices)), + offsetY, + scrollToTop, + }), + {initialProps}, + ) + /** The prepend's commit, then the render that has its page. */ + const prepend = (props: Props = {}) => { + hook.rerender({...props, prependedAt: PREPENDED_AT}) + hook.rerender({ + ...props, + prependedAt: PREPENDED_AT, + pages: prependedPages, + }) + } + return {hook, offsetY, scrollToTop, prepend} + } + + describe('shows', () => { + it('once the posts a prepend put above the restored top render', () => { + const {hook} = renderPill() + expect(hook.result.current.visible).toBe(false) + + // Committed, but not yet rendered. + hook.rerender({prependedAt: PREPENDED_AT}) + expect(hook.result.current.visible).toBe(false) + + hook.rerender({prependedAt: PREPENDED_AT, pages: prependedPages}) + expect(hook.result.current).toMatchObject({ + visible: true, + count: 4, + authors: [{did: 'did:plc:a'}, {did: 'did:plc:b'}, {did: 'did:plc:c'}], + }) + }) + + it('never without a prepend', () => { + const {hook} = renderPill() + hook.rerender({pages: prependedPages}) + expect(hook.result.current.visible).toBe(false) + }) + + it('never for a prepend none of whose posts render', () => { + const {hook} = renderPill() + hook.rerender({prependedAt: PREPENDED_AT}) + hook.rerender({ + prependedAt: PREPENDED_AT, + // Rows built from these pages leave out the duplicate's page. + pages: [page(PREPENDED_AT, []), page(RESTORED_AT, old)], + }) + expect(hook.result.current.visible).toBe(false) + }) + + it('only while the view is active, including after a prepend in the background', () => { + const {hook, prepend} = renderPill({isActive: false}) + prepend({isActive: false}) + expect(hook.result.current.visible).toBe(false) + + hook.rerender({ + isActive: true, + prependedAt: PREPENDED_AT, + pages: prependedPages, + }) + expect(hook.result.current.visible).toBe(true) + + hook.rerender({ + isActive: false, + prependedAt: PREPENDED_AT, + pages: prependedPages, + }) + expect(hook.result.current.visible).toBe(false) + }) + + it('with what it first offered, not a live count', () => { + const {hook, prepend} = renderPill() + prepend() + expect(hook.result.current.count).toBe(4) + + // Some of the posts go, as a mute takes them out. + hook.rerender({ + prependedAt: PREPENDED_AT, + pages: [page(PREPENDED_AT, fresh.slice(2)), page(RESTORED_AT, old)], + }) + expect(hook.result.current.visible).toBe(true) + expect(hook.result.current.count).toBe(4) + // Their faces go with them. + expect(hook.result.current.authors.map(author => author.did)).toEqual([ + 'did:plc:c', + ]) + }) + + it('not with following v2 off, or on web', () => { + const {hook, prepend} = renderPill({enabled: false}) + prepend({enabled: false}) + expect(hook.result.current.visible).toBe(false) + }) + }) + + describe('hides for good', () => { + it('once the topmost new post is seen after a drag', () => { + const {hook, prepend} = renderPill() + prepend() + + // Seen without a drag, the row is behind the header. + act(() => hook.result.current.onItemSeen({key: 'slice-a-0'})) + expect(hook.result.current.visible).toBe(true) + + act(() => hook.result.current.onBeginDrag()) + act(() => hook.result.current.onItemSeen({key: 'slice-d-0'})) + expect(hook.result.current.visible).toBe(true) + + act(() => hook.result.current.onItemSeen({key: 'slice-a-0'})) + expect(hook.result.current.visible).toBe(false) + }) + + it('once the list reaches its top', () => { + const {hook, prepend} = renderPill() + prepend() + + act(() => hook.result.current.onReachTop()) + + expect(hook.result.current.visible).toBe(false) + }) + + it('once a refresh replaces the top page', () => { + const {hook, prepend} = renderPill() + prepend() + + hook.rerender({ + prependedAt: PREPENDED_AT, + pages: [page(PREPENDED_AT + 1, [slice('fresh')])], + }) + + expect(hook.result.current.visible).toBe(false) + }) + + it('but not when the reader reaches the top before the prepend', () => { + const {hook, prepend} = renderPill() + act(() => hook.result.current.onReachTop()) + prepend() + expect(hook.result.current.visible).toBe(true) + }) + }) + + describe('pressed', () => { + it('scrolls up to the top, which hides it', () => { + const {hook, offsetY, scrollToTop, prepend} = renderPill() + prepend() + offsetY.value = 10_000 + + act(() => hook.result.current.onPress()) + + expect(scrollToTop).toHaveBeenCalled() + // The press alone doesn't, but the scroll reaching the top does. + expect(hook.result.current.visible).toBe(true) + act(() => hook.result.current.onReachTop()) + expect(hook.result.current.visible).toBe(false) + }) + + it('hides it already at the top, where no scroll reaches it', () => { + const {hook, offsetY, scrollToTop, prepend} = renderPill() + prepend() + offsetY.value = 0 + + act(() => hook.result.current.onPress()) + + expect(scrollToTop).toHaveBeenCalled() + expect(hook.result.current.visible).toBe(false) + }) + }) +}) diff --git a/src/features/followingV2/home/useRestorePill.ts b/src/features/followingV2/home/useRestorePill.ts new file mode 100644 index 000000000..4e07f57ab --- /dev/null +++ b/src/features/followingV2/home/useRestorePill.ts @@ -0,0 +1,236 @@ +import {useRef, useState} from 'react' + +import {type NewPostsPillAuthor} from '#/components/NewPostsPill' +import {type FeedPostSlice} from './queries/postFeed' +import {SETTLE_AT_TOP_LIMIT} from './useSettleAtTop' + +/** How many faces the pill shows. */ +const FACE_LIMIT = 3 + +/** The parts of a feed row that the pill reads. */ +type Row = { + type: string + key: string + slice?: FeedPostSlice +} + +/** The parts of a rendered feed page that the pill reads. */ +type Page = { + fetchedAt: number + slices: readonly FeedPostSlice[] +} + +/** + * What the pill offers: the posts a restore prepend put above the restored + * top, as they first rendered. It's a snapshot, so its count stays as it was + * however the rows change, while its faces only ever drop out (see + * {@link liveRestoreOffer}). + */ +export type RestoreOffer = { + /** + * The `fetchedAt` of the page the prepend put on top. The offer lasts while + * it's still the top page, so a refresh, or anything else that replaces it, + * ends it. + */ + topFetchedAt: number + /** The keys of the offered rows, top first. */ + keys: string[] + /** + * How many posts are offered: one per feed item, as a reply's thread + * context isn't a new post of its own. + */ + count: number + /** + * Up to {@link FACE_LIMIT} of the posts' authors, distinct and in order, + * leaving out any whose avatar isn't safe to show. + */ + authors: NewPostsPillAuthor[] +} + +/** + * The author of a feed item's own post, if their avatar is safe to show: they + * have one, and moderation neither blurs nor filters it. + */ +function faceOf(slice: FeedPostSlice): NewPostsPillAuthor | undefined { + const item = slice.items.find(item => item.uri === slice.feedPostUri) + if (!item) { + return undefined + } + const {did, avatar} = item.post.author + const ui = item.moderation.ui('avatar') + if (!avatar || ui.blur || ui.filter) { + return undefined + } + return {did, avatar} +} + +/** + * What a restore prepend's `page` offers, as the list renders it: the post rows + * from that page, which are the rows above the restored top. Rows the list + * leaves out, such as muted authors', aren't offered. Neither are saved-feed + * samples, as `page` is the page without them, nor the gap row below it. + * `undefined` when none of the page's posts render. + */ +export function getRestoreOffer( + rows: readonly Row[], + page: Page, +): RestoreOffer | undefined { + const slices = new Set(page.slices) + const counted = new Set() + const keys: string[] = [] + const authors: NewPostsPillAuthor[] = [] + for (const row of rows) { + if (row.type !== 'sliceItem' || !row.slice || !slices.has(row.slice)) { + continue + } + keys.push(row.key) + if (counted.has(row.slice)) { + continue + } + counted.add(row.slice) + const face = faceOf(row.slice) + if ( + face && + authors.length < FACE_LIMIT && + !authors.some(author => author.did === face.did) + ) { + authors.push(face) + } + } + if (!counted.size) { + return undefined + } + return {topFetchedAt: page.fetchedAt, keys, count: counted.size, authors} +} + +/** + * The parts of `offer` that follow the rows as they are now: the topmost of + * its rows that still renders, `undefined` once none do, and the faces whose + * posts still render with an avatar that's safe to show, as a deletion, a mute + * or a block can take a post away and a label can make an avatar unsafe. + */ +export function liveRestoreOffer( + offer: RestoreOffer, + rows: readonly Row[], +): {topKey: string | undefined; authors: NewPostsPillAuthor[]} { + const keys = new Set(offer.keys) + const faces = new Set() + let topKey: string | undefined + for (const row of rows) { + if (row.type !== 'sliceItem' || !row.slice || !keys.has(row.key)) { + continue + } + topKey ??= row.key + const face = faceOf(row.slice) + if (face) { + faces.add(face.did) + } + } + return { + topKey, + authors: offer.authors.filter(author => faces.has(author.did)), + } +} + +/** + * The new posts pill for a view's restore prepend (see + * `usePostFeedRestorePrepend`). Once the posts the prepend put above the + * restored top render, it takes a snapshot of them as its offer (see + * {@link getRestoreOffer}). There's at most one, as the prepend runs once per + * view. + * + * The pill shows while the view is active, the offer's page is still on top + * and some of its rows still render, which includes a view that prepended in + * the background becoming active. It hides for good when the reader reaches + * the posts: + * + * - The topmost offered row is seen, if the reader has dragged the list since + * the offer. Until they have, the only rows the list reports as seen are + * the ones behind the header, just above the row the anchor kept on screen. + * - The list reaches its top, by any means, including the scroll a press of + * the pill makes. A press alone doesn't hide it. + * + * Pressing it scrolls up to the top, without fetching. + */ +export function useRestorePill({ + enabled, + isActive, + prependedAt, + rows, + pages, + offsetY, + scrollToTop, +}: { + /** Whether the view offers restored posts at all. */ + enabled: boolean + /** Whether the view is the one on screen. */ + isActive: boolean + /** + * The `fetchedAt` of the page the view's restore prepend put on top, once + * it has. + */ + prependedAt: number | undefined + /** The rows the list renders. */ + rows: readonly Row[] + /** The feed's pages as they render, without saved-feed samples. */ + pages: readonly Page[] | undefined + /** The list's scroll offset. */ + offsetY: {get(): number} + /** Scrolls the list to its true top. */ + scrollToTop: () => void +}) { + const [offer, setOffer] = useState() + const [isDone, setIsDone] = useState(false) + /** Whether the reader has dragged the list since the offer was made. */ + const hasDragged = useRef(false) + + const top = pages?.[0] + // The rows from the prepend's page render after it commits. + if ( + enabled && + !offer && + !isDone && + prependedAt !== undefined && + top?.fetchedAt === prependedAt + ) { + const next = getRestoreOffer(rows, top) + if (next) { + setOffer(next) + } else { + setIsDone(true) + } + } + + const live = + offer && top?.fetchedAt === offer.topFetchedAt + ? liveRestoreOffer(offer, rows) + : undefined + + return { + visible: enabled && isActive && !isDone && live?.topKey !== undefined, + count: offer?.count ?? 0, + authors: live?.authors ?? [], + onPress: () => { + // Already at the top, there's no scroll to report reaching it. + if (offsetY.get() <= SETTLE_AT_TOP_LIMIT) { + setIsDone(true) + } + scrollToTop() + }, + onBeginDrag: () => { + if (offer) { + hasDragged.current = true + } + }, + onItemSeen: (row: {key: string}) => { + if (hasDragged.current && row.key === live?.topKey) { + setIsDone(true) + } + }, + onReachTop: () => { + if (prependedAt !== undefined) { + setIsDone(true) + } + }, + } +} diff --git a/src/features/followingV2/home/useSettleScrollHandlers.ts b/src/features/followingV2/home/useSettleScrollHandlers.ts index 51eb382eb..812309c98 100644 --- a/src/features/followingV2/home/useSettleScrollHandlers.ts +++ b/src/features/followingV2/home/useSettleScrollHandlers.ts @@ -1,23 +1,38 @@ import {useCallback} from 'react' -import {type ScrollHandlers, useSharedValue} from 'react-native-reanimated' +import { + type ScrollHandlers, + type SharedValue, + useSharedValue, +} from 'react-native-reanimated' import {type ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/hook/commonTypes' import {scheduleOnRN} from 'react-native-worklets' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {SETTLE_AT_TOP_LIMIT, type SettleAtTopHandlers} from './useSettleAtTop' +/** + * What the list reports on the JS thread: what {@link SettleAtTopHandlers} + * need, and when it reaches its top, which the restore pill needs. + */ +export type ListScrollReports = SettleAtTopHandlers & { + /** A scroll event found the list at the top where the last one didn't. */ + onReachTop: () => void +} + /** * The scroll handlers `inner`, such as those from context, for a list to take - * from a `ScrollProvider` around it, with what {@link SettleAtTopHandlers} - * need reported to them as well, on the JS thread. They're reported from each - * event as the list sent it, whatever `inner` passes on. A scroll event is - * reported only when it finds the list off the top where the last event found - * it at the top, so not every frame, and a rest at the top is always followed - * by a report of leaving it. Without `handlers`, they're `inner` as they are. + * from a `ScrollProvider` around it, with what `handlers` need reported to them + * as well, on the JS thread, and `offsetY` kept at the list's offset. Both + * come from each event as the list sent it, whatever `inner` passes on. A + * scroll event is reported only when it finds the list at the top, or off it, + * where the last event didn't, so not every frame, and a rest at the top is + * always followed by a report of leaving it. Without `handlers`, they're + * `inner` as they are. */ export function useSettleScrollHandlers( inner: ScrollHandlers>, - handlers: SettleAtTopHandlers | undefined, + handlers: ListScrollReports | undefined, + offsetY: SharedValue, ): ScrollHandlers> { // Destructured outside the worklets, as `List` does (see #4108). const { @@ -31,46 +46,57 @@ export function useSettleScrollHandlers( const onEndDragJS = useNonReactiveCallback(handlers?.onEndDrag) const onMomentumEndJS = useNonReactiveCallback(handlers?.onMomentumEnd) const onLeaveTopJS = useNonReactiveCallback(handlers?.onLeaveTop) + const onReachTopJS = useNonReactiveCallback(handlers?.onReachTop) const onBeginDrag = useCallback( (e: ReanimatedScrollEvent, ctx: Record) => { 'worklet' onBeginDragInner?.(e, ctx) + offsetY.set(e.contentOffset.y) scheduleOnRN(onBeginDragJS) }, - [onBeginDragInner, onBeginDragJS], + [onBeginDragInner, offsetY, onBeginDragJS], ) const onEndDrag = useCallback( (e: ReanimatedScrollEvent, ctx: Record) => { 'worklet' onEndDragInner?.(e, ctx) - isAtTop.set(e.contentOffset.y <= SETTLE_AT_TOP_LIMIT) + offsetY.set(e.contentOffset.y) + const atTop = e.contentOffset.y <= SETTLE_AT_TOP_LIMIT + if (atTop && !isAtTop.get()) { + scheduleOnRN(onReachTopJS) + } + isAtTop.set(atTop) scheduleOnRN(onEndDragJS, e.contentOffset.y, e.velocity?.y ?? 0) }, - [onEndDragInner, isAtTop, onEndDragJS], + [onEndDragInner, offsetY, isAtTop, onReachTopJS, onEndDragJS], ) const onMomentumEnd = useCallback( (e: ReanimatedScrollEvent, ctx: Record) => { 'worklet' onMomentumEndInner?.(e, ctx) - isAtTop.set(e.contentOffset.y <= SETTLE_AT_TOP_LIMIT) + offsetY.set(e.contentOffset.y) + const atTop = e.contentOffset.y <= SETTLE_AT_TOP_LIMIT + if (atTop && !isAtTop.get()) { + scheduleOnRN(onReachTopJS) + } + isAtTop.set(atTop) scheduleOnRN(onMomentumEndJS, e.contentOffset.y) }, - [onMomentumEndInner, isAtTop, onMomentumEndJS], + [onMomentumEndInner, offsetY, isAtTop, onReachTopJS, onMomentumEndJS], ) const onScroll = useCallback( (e: ReanimatedScrollEvent, ctx: Record) => { 'worklet' onScrollInner?.(e, ctx) + offsetY.set(e.contentOffset.y) const atTop = e.contentOffset.y <= SETTLE_AT_TOP_LIMIT if (atTop !== isAtTop.get()) { isAtTop.set(atTop) - if (!atTop) { - scheduleOnRN(onLeaveTopJS) - } + scheduleOnRN(atTop ? onReachTopJS : onLeaveTopJS) } }, - [onScrollInner, isAtTop, onLeaveTopJS], + [onScrollInner, offsetY, isAtTop, onReachTopJS, onLeaveTopJS], ) if (!handlers) {