diff --git a/mobile/src/session/native-chat/transcript/persistence/mobile-native-chat-transcript-cache.ts b/mobile/src/session/native-chat/transcript/persistence/mobile-native-chat-transcript-cache.ts index d4436a212c3..8819acdeb0a 100644 --- a/mobile/src/session/native-chat/transcript/persistence/mobile-native-chat-transcript-cache.ts +++ b/mobile/src/session/native-chat/transcript/persistence/mobile-native-chat-transcript-cache.ts @@ -3,7 +3,8 @@ import type { NativeChatMessage } from '../../../../../../src/shared/native-chat import type { NativeChatResumePoint } from '../../../../../../src/shared/rpc-contract/native-chat/native-chat-params' import { peekStoredChatTranscript } from './mobile-native-chat-transcript-store' -const MAX_CACHED_TRANSCRIPTS = 8 +/** Chats whose rows, row keys and reading state the page keeps between visits. */ +export const MAX_CACHED_TRANSCRIPTS = 8 export type MobileNativeChatCachedTranscript = { messages: NativeChatMessage[] diff --git a/mobile/src/session/native-chat/transcript/projection/mobile-native-chat-row-keys.ts b/mobile/src/session/native-chat/transcript/projection/mobile-native-chat-row-keys.ts index 0d382581621..65ae8f4395d 100644 --- a/mobile/src/session/native-chat/transcript/projection/mobile-native-chat-row-keys.ts +++ b/mobile/src/session/native-chat/transcript/projection/mobile-native-chat-row-keys.ts @@ -1,4 +1,6 @@ import { useLayoutEffect, useMemo, useRef } from 'react' +import { setBoundedScopeCacheEntry } from '../../../../../../src/shared/native-chat/native-chat-scope-cache' +import { MAX_CACHED_TRANSCRIPTS } from '../persistence/mobile-native-chat-transcript-cache' import { distinctMobileNativeChatRunIdentities, sameMobileNativeChatRun, @@ -201,19 +203,22 @@ export function useMobileNativeChatRowKeys( runOwners: ReadonlyMap runPlacements: ReadonlyMap } { - // Commit snapshots only: discarded React renders must not become the next baseline. - const committed = useRef< - | (Assigned & + // Commit snapshots only: discarded React renders must not become the next baseline. Kept per chat, so a + // return keeps the keys its disclosures and reading place were saved under. + const committed = useRef( + new Map< + string, + Assigned & MobileNativeChatRunHistory & { scope: string displayed: Assigned & { distinct: boolean } serial: number runPlacements: ReadonlyMap - }) - | null - >(null) + } + >() + ) const assigned = useMemo(() => { - const previous = committed.current?.scope === scope ? committed.current : null + const previous = committed.current.get(scope) ?? null const sourceOf = prepareMobileNativeChatRowSources(messages) const prepareSources = () => rows.map(sourceOf) const physical = assignMobileNativeChatRowKeys( @@ -265,7 +270,7 @@ export function useMobileNativeChatRowKeys( } }, [rows, messages, scope, presentation]) useLayoutEffect(() => { - committed.current = assigned + setBoundedScopeCacheEntry(committed.current, assigned.scope, assigned, MAX_CACHED_TRANSCRIPTS) }, [assigned]) return useMemo(() => { let idByKey: Map | undefined diff --git a/mobile/src/session/native-chat/transcript/viewport/MobileNativeChatPageList.tsx b/mobile/src/session/native-chat/transcript/viewport/MobileNativeChatPageList.tsx index a6f7dfd2f76..b42f1652dac 100644 --- a/mobile/src/session/native-chat/transcript/viewport/MobileNativeChatPageList.tsx +++ b/mobile/src/session/native-chat/transcript/viewport/MobileNativeChatPageList.tsx @@ -21,17 +21,20 @@ import type { NativeChatMessage } from '../../../../../../src/shared/native-chat import type { MobileNativeChatRowKeys } from '../projection/mobile-native-chat-row-keys' import { MobileNativeChatPageScroll } from './MobileNativeChatPageScroll' import { - mobileNativeChatReadingDrift, - mobileNativeChatReadingPlace, + DRAW_AHEAD_SCREENS, mobileNativeChatRowAbove, mobileNativeChatRowBoxProps, mobileNativeChatRowOffset, - type MobileNativeChatReadingUnit, type MobileNativeChatScrollNode } from './mobile-native-chat-reading-place' import type { MobileNativeChatListHandle } from './use-mobile-native-chat-tail-follow' import type { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' import { scrollWritesStopMomentum } from './mobile-native-chat-scroll-motion' +import { + savedMobileNativeChatDrawn, + useMobileNativeChatPlaceKeeper, + type MobileNativeChatDrawn +} from './use-mobile-native-chat-place-keeper' import { createMobileNativeChatGrowthHold, MobileNativeChatGrowthHoldContext @@ -39,7 +42,6 @@ import { const FIRST_ROWS = 24 const DRAW_BATCH = 12 -const DRAW_AHEAD_SCREENS = 3 // While following, rows drawn past this many screens above the tail are dropped. const TRIM_SCREENS = 6 // Fetch ahead far enough for multi-screen phone flicks. @@ -76,6 +78,8 @@ type Props = { ref: Ref isFollowing: () => boolean onEndDistance: (fromEnd: number, byReader: boolean) => void + /** The reader is back where they left `scope`, away from its tail. */ + onPlaceRestored: (scope: string) => void rows: readonly NativeChatMessage[] rowKeys: Pick renderItem: (row: Row) => ReactElement @@ -90,15 +94,13 @@ type Props = { onNearTop?: () => void } -// Anchor by key so streaming rows below cannot move the drawn range. -type Drawn = { scope: string; firstKey: string | null; count: number } - // End anchoring preserves position when history prepends; restore after below-reader changes only at rest or on regroup. export function MobileNativeChatPageList({ ref, roots, isFollowing, onEndDistance, + onPlaceRestored, rows: liveRows, rowKeys, renderItem, @@ -153,8 +155,15 @@ export function MobileNativeChatPageList({ const keys = useMemo(() => rows.map(rowKeys.keyOf), [rows, rowKeys.keyOf]) const indexOf = useMemo(() => new Map(keys.map((key, at) => [key, at])), [keys]) const n = keys.length - const [drawn, setDrawn] = useState({ scope: rowKeys.scope, firstKey: null, count: 0 }) - const kept = drawn.scope === rowKeys.scope ? drawn : null + const [drawn, setDrawn] = useState( + () => + savedMobileNativeChatDrawn(rowKeys.scope) ?? { + scope: rowKeys.scope, + firstKey: null, + count: 0 + } + ) + const kept = drawn.scope === rowKeys.scope ? drawn : savedMobileNativeChatDrawn(rowKeys.scope) const opening = Math.max(0, n - FIRST_ROWS) const firstKey = kept?.firstKey ?? null const first = @@ -167,8 +176,6 @@ export function MobileNativeChatPageList({ const own = useRef(null) const touching = useRef(false) const readerScrolledAt = useRef(0) - const place = useRef(null) - const placedLayout = useRef(layoutKey) const settleTimer = useRef | undefined>(undefined) const live = useRef({ rows: liveRows, footer: liveFooter, renderItem }) const ask = useRef(onNearTop) @@ -193,34 +200,16 @@ export function MobileNativeChatPageList({ [] ) - // Keep one reading anchor so whole-pixel corrections cannot accumulate rounding drift. - const notePlace = useCallback( - (s: Scroller) => { - place.current = isFollowing() ? null : mobileNativeChatReadingPlace(s, latest.current.rowKeys) - placedLayout.current = latest.current.layoutKey - }, - [isFollowing] - ) - - const keepPlace = useCallback( - (s: Scroller) => { - const held = place.current - const regrouped = placedLayout.current !== latest.current.layoutKey - if (!held || isFollowing() || !(regrouped || resting())) { - notePlace(s) - return - } - const drift = mobileNativeChatReadingDrift(held, s, latest.current.rowKeys, roots) - if (Math.abs(drift) >= 0.5) { - write(s, s.scrollTop + drift) - } - // A regroup draws other parts: the line is re-read from them. - if (regrouped) { - notePlace(s) - } - }, - [isFollowing, notePlace, resting, roots, write] - ) + const { notePlace, keepPlace } = useMobileNativeChatPlaceKeeper({ + latest, + roots, + isFollowing, + resting, + write, + setDrawn, + onEndDistance, + onPlaceRestored + }) const settle = useRef(() => {}) const [growth] = useState(createMobileNativeChatGrowthHold) diff --git a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-disclosure-store.ts b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-disclosure-store.ts index a2bb914cbce..f71c737deeb 100644 --- a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-disclosure-store.ts +++ b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-disclosure-store.ts @@ -1,7 +1,9 @@ // Store disclosures above recycled transcript rows so opened tools remain open when rows remount. import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react' +import { setBoundedScopeCacheEntry } from '../../../../../../src/shared/native-chat/native-chat-scope-cache' import { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' +import { MAX_CACHED_TRANSCRIPTS } from '../persistence/mobile-native-chat-transcript-cache' import type { MobileNativeChatRootPosition } from './mobile-native-chat-scroll-root-handle' export type MobileNativeChatRunScroll = MobileNativeChatRootPosition @@ -29,23 +31,31 @@ type ScopedDisclosures = { roots: MobileNativeChatScrollRoots } -function emptyDisclosures(scopeKey: string): ScopedDisclosures { - const runScroll = new Map() +type KeptDisclosures = Map> + +function chatDisclosuresOf(kept: KeptDisclosures, scopeKey: string): ScopedDisclosures { + const chat = kept.get(scopeKey) + const runScroll = chat?.runScroll ?? new Map() return { scopeKey, - open: new Map(), + open: chat?.open ?? new Map(), runScroll, roots: new MobileNativeChatScrollRoots(runScroll, MAX_DISCLOSURES) } } export function useMobileNativeChatDisclosures(scopeKey: string): MobileNativeChatDisclosureStore { - const [state, setState] = useState(() => emptyDisclosures(scopeKey)) + // One view serves every tab, so each chat keeps what the reader opened, under the run keys this view gave it. + const [kept] = useState(() => new Map()) + const [state, setState] = useState(() => chatDisclosuresOf(kept, scopeKey)) if (state.scopeKey !== scopeKey) { - setState(emptyDisclosures(scopeKey)) + setState(chatDisclosuresOf(kept, scopeKey)) } const { open, runScroll, roots } = state useLayoutEffect(() => () => roots.dispose(), [roots]) + useLayoutEffect(() => { + setBoundedScopeCacheEntry(kept, state.scopeKey, { open, runScroll }, MAX_CACHED_TRANSCRIPTS) + }, [kept, state.scopeKey, open, runScroll]) const write = useCallback( (key: string, next: boolean) => { if (!next) { diff --git a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-reading-place.ts b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-reading-place.ts index f0bd8f5679b..8cb4808db92 100644 --- a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-reading-place.ts +++ b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-reading-place.ts @@ -25,11 +25,15 @@ type Keys = Pick export type MobileNativeChatReadingUnit = { key: string + /** From the scroller's top, so a place saved on an earlier visit holds if the scroller moved. */ top: number member?: string placed: string } +/** How many screens of rows the page list draws above the view. */ +export const DRAW_AHEAD_SCREENS = 3 + const ROW = 'chat-row:' const MEMBER = 'chat-member:' const ROWS = 'data-chat-rows' @@ -80,7 +84,7 @@ function unitsOf( break } if (id === 'run' ? box.top >= view.top : onScreen(box, view)) { - shown.push({ ...self, top: box.top, member: id }) + shown.push({ ...self, top: box.top - view.top, member: id }) } } const lines = shown.filter((unit) => unit.member !== 'run') @@ -169,7 +173,7 @@ export function mobileNativeChatReadingPlace( } const unit = ({ id, node }: { id: string; node: Tagged }): MobileNativeChatReadingUnit => ({ key: id, - top: node.getBoundingClientRect().top, + top: node.getBoundingClientRect().top - view.top, placed: placement(id) }) const units = rows.slice(low, end).flatMap((node) => { @@ -200,12 +204,13 @@ function drawn( return row && tagged(row, MEMBER).find((m) => m.id === member || m.id === paired)?.node } +/** How far the place's first still-drawn unit moved; undefined when none of it is drawn. */ export function mobileNativeChatReadingDrift( place: readonly MobileNativeChatReadingUnit[], scroller: MobileNativeChatScrollNode, keys: Keys, roots?: MobileNativeChatScrollRoots -): number { +): number | undefined { const rows = new Map( drawnRows(scroller).flatMap((node) => { const id = rowIdOf(node) @@ -215,8 +220,8 @@ export function mobileNativeChatReadingDrift( for (const unit of place) { const node = drawn(unit, rows, keys, roots) if (node) { - return node.getBoundingClientRect().top - unit.top + return node.getBoundingClientRect().top - scroller.getBoundingClientRect().top - unit.top } } - return 0 + return undefined } diff --git a/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-place-keeper.ts b/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-place-keeper.ts new file mode 100644 index 00000000000..33ba827856c --- /dev/null +++ b/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-place-keeper.ts @@ -0,0 +1,137 @@ +import { useCallback, useRef, type Dispatch, type RefObject, type SetStateAction } from 'react' +import { setBoundedScopeCacheEntry } from '../../../../../../src/shared/native-chat/native-chat-scope-cache' +import type { MobileNativeChatRowKeys } from '../projection/mobile-native-chat-row-keys' +import { + DRAW_AHEAD_SCREENS, + mobileNativeChatReadingDrift, + mobileNativeChatReadingPlace, + mobileNativeChatRowAbove, + type MobileNativeChatReadingUnit, + type MobileNativeChatScrollNode +} from './mobile-native-chat-reading-place' +import type { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' +import { MAX_CACHED_TRANSCRIPTS } from '../persistence/mobile-native-chat-transcript-cache' + +// Anchor by key so streaming rows below cannot move the drawn range. +export type MobileNativeChatDrawn = { scope: string; firstKey: string | null; count: number } + +type SavedPlace = Omit & { place: MobileNativeChatReadingUnit[] } + +// One chat view serves every tab, so each chat's place lives here, for the page's lifetime. +const savedPlaces = new Map() + +/** The rows a chat drew when the reader left it away from its tail, so its place can be put back. */ +export function savedMobileNativeChatDrawn(scope: string): MobileNativeChatDrawn | null { + const saved = savedPlaces.get(scope) + return saved ? { scope, firstKey: saved.firstKey, count: saved.count } : null +} + +/** The reader went back to the chat's tail, even while its list is not mounted to see it. */ +export function forgetMobileNativeChatPlace(scope: string): void { + savedPlaces.delete(scope) +} + +type Committed = { + first: number + n: number + keys: readonly string[] + indexOf: ReadonlyMap + layoutKey: string + rowKeys: Pick +} + +/** Keeps the reader's place through list changes, and per chat, so returning to a chat puts it back. */ +export function useMobileNativeChatPlaceKeeper(args: { + latest: RefObject + roots?: MobileNativeChatScrollRoots + isFollowing: () => boolean + resting: () => boolean + write: (scroller: S, to: number) => void + setDrawn: Dispatch> + onEndDistance: (fromEnd: number, byReader: boolean) => void + onPlaceRestored: (scope: string) => void +}): { notePlace: (scroller: S) => void; keepPlace: (scroller: S) => void } { + const { latest, roots, isFollowing, resting, write, setDrawn } = args + const { onEndDistance, onPlaceRestored } = args + const place = useRef(null) + // The chat whose place `place` holds; until its saved place is put back, nothing may overwrite it. + const placedScope = useRef(null) + const placedLayout = useRef(latest.current.layoutKey) + + // Keep one reading anchor so whole-pixel corrections cannot accumulate rounding drift. + const notePlace = useCallback( + (s: S) => { + const { rowKeys, layoutKey, keys, indexOf, first, n } = latest.current + if (placedScope.current !== rowKeys.scope) { + return + } + place.current = isFollowing() ? null : mobileNativeChatReadingPlace(s, rowKeys) + placedLayout.current = layoutKey + if (place.current) { + // A return draws from just above the place, not every row drawn while reading further up. + const head = mobileNativeChatRowAbove(s, DRAW_AHEAD_SCREENS * s.clientHeight) + const from = Math.max(first, indexOf.get(head ?? '') ?? first) + const saved = { firstKey: keys[from] ?? null, count: n - from, place: place.current } + setBoundedScopeCacheEntry(savedPlaces, rowKeys.scope, saved, MAX_CACHED_TRANSCRIPTS) + } else { + savedPlaces.delete(rowKeys.scope) + } + }, + [isFollowing, latest] + ) + + // With nothing saved, or its rows gone, the chat opens following. + const restorePlace = useCallback( + (s: S, scope: string) => { + placedScope.current = scope + placedLayout.current = latest.current.layoutKey + const saved = savedPlaces.get(scope) + const drift = + saved && mobileNativeChatReadingDrift(saved.place, s, latest.current.rowKeys, roots) + if (!saved || drift === undefined) { + place.current = null + savedPlaces.delete(scope) + return + } + place.current = saved.place + write(s, s.scrollTop + drift) + setDrawn((was) => + was.scope === scope ? was : { scope, firstKey: saved.firstKey, count: saved.count } + ) + onEndDistance(Math.max(0, -s.scrollTop), false) + onPlaceRestored(scope) + }, + [latest, onEndDistance, onPlaceRestored, roots, setDrawn, write] + ) + + const keepPlace = useCallback( + (s: S) => { + const { rowKeys, n, layoutKey } = latest.current + if (placedScope.current !== rowKeys.scope) { + // An empty chat shown meanwhile must not leave the last one placed, or a return would overwrite it. + placedScope.current = null + if (n > 0) { + restorePlace(s, rowKeys.scope) + } + return + } + const held = place.current + const regrouped = placedLayout.current !== layoutKey + if (!held || isFollowing() || !(regrouped || resting())) { + notePlace(s) + return + } + const drift = mobileNativeChatReadingDrift(held, s, rowKeys, roots) ?? 0 + if (Math.abs(drift) >= 0.5) { + write(s, s.scrollTop + drift) + } + // A regroup draws other parts: the line is re-read from them. + if (regrouped) { + notePlace(s) + } + }, + [isFollowing, latest, notePlace, resting, restorePlace, roots, write] + ) + + return { notePlace, keepPlace } +} diff --git a/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-tail-follow.ts b/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-tail-follow.ts index 17011430b28..2c1d7d642c3 100644 --- a/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-tail-follow.ts +++ b/mobile/src/session/native-chat/transcript/viewport/use-mobile-native-chat-tail-follow.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { Platform, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native' +import { forgetMobileNativeChatPlace } from './use-mobile-native-chat-place-keeper' const AT_TAIL_SLOP = 80 @@ -38,6 +39,7 @@ export type MobileNativeChatTailFollow = { ref: (list: MobileNativeChatListHandle | null) => void isFollowing: () => boolean onEndDistance: (fromEnd: number, byReader: boolean) => void + onPlaceRestored: (scope: string) => void } showJumpToTail: boolean pinToTail: () => void @@ -56,7 +58,7 @@ export type MobileNativeChatTailFollow = { // Reader gestures and explicit jumps own follow intent; correction metrics must not change it. export function useMobileNativeChatTailFollow(args: { hasItems: boolean - /** The chat shown; another one opens following, whatever the reader did here. */ + /** The chat shown; another one opens following unless the list puts back where the reader left it. */ scopeKey: string }): MobileNativeChatTailFollow { const { hasItems, scopeKey } = args @@ -69,6 +71,7 @@ export function useMobileNativeChatTailFollow(args: { const userScrollActiveRef = useRef(false) const userScrollSettleFrameRef = useRef(null) const scopeKeyRef = useRef(scopeKey) + const restoredScopeRef = useRef(null) // Single writer, so the event-time ref and the render flag cannot disagree. const setFollowing = useCallback((next: boolean) => { @@ -133,7 +136,7 @@ export function useMobileNativeChatTailFollow(args: { [setAtTail, setFollowing] ) - const jumpToTail = useCallback(() => { + const followTail = useCallback(() => { clearUserScrollSettle() userScrollActiveRef.current = false setAtTail(true) @@ -141,6 +144,12 @@ export function useMobileNativeChatTailFollow(args: { pinToTail() }, [clearUserScrollSettle, pinToTail, setAtTail, setFollowing]) + // The reader chose the tail (send, jump to latest), even while the chat's rows are still loading. + const jumpToTail = useCallback(() => { + forgetMobileNativeChatPlace(scopeKeyRef.current) + followTail() + }, [followTail]) + // Release the follow first, as desktop's scrollMessageToTop does, so streaming cannot pull the row away. const scrollRowToTop = useCallback( (key: string) => { @@ -208,20 +217,36 @@ export function useMobileNativeChatTailFollow(args: { const isFollowing = useCallback(() => followingRef.current, []) + // The list commits before this view's chat-change effect, so the scope says which chat it restored. + const onPlaceRestored = useCallback( + (scope: string) => { + restoredScopeRef.current = scope + clearUserScrollSettle() + userScrollActiveRef.current = false + setFollowing(false) + }, + [clearUserScrollSettle, setFollowing] + ) + // Reset before paint on chat changes so a mounted view cannot expose the previous reader position. useLayoutEffect(() => { if (scopeKeyRef.current === scopeKey) { return } scopeKeyRef.current = scopeKey - jumpToTail() - }, [scopeKey, jumpToTail]) + const restored = restoredScopeRef.current === scopeKey + restoredScopeRef.current = null + // Rows still loading keep the chat's saved place, for the list to put back once they draw. + if (!restored) { + followTail() + } + }, [scopeKey, followTail]) useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]) return { listProps: { ref: attachList }, - pageListProps: { ref: attachList, isFollowing, onEndDistance }, + pageListProps: { ref: attachList, isFollowing, onEndDistance, onPlaceRestored }, showJumpToTail: !following && !atTail, pinToTail, pinToTailAfterContentResize,