Merge remote-tracking branch 'origin/main' into feat/nested-git-repos
# Conflicts: # packages/ui/src/lib/addSelectionToChat.test.ts
This commit is contained in:
@@ -1,938 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
import { MessageFreshnessDetector } from '@/lib/messageFreshness';
|
||||
import { createScrollSpy } from '@/components/chat/lib/scroll/scrollSpy';
|
||||
import { useViewportStore } from '@/sync/viewport-store';
|
||||
|
||||
type AutoFollowState = 'following' | 'released';
|
||||
|
||||
export type ContentChangeReason = 'text' | 'structural' | 'permission' | 'animation';
|
||||
|
||||
export interface AnimationHandlers {
|
||||
onChunk: () => void;
|
||||
onComplete: () => void;
|
||||
onStreamingCandidate?: () => void;
|
||||
onAnimationStart?: () => void;
|
||||
onReservationCancelled?: () => void;
|
||||
onReasoningBlock?: () => void;
|
||||
onAnimatedHeightChange?: (height: number) => void;
|
||||
}
|
||||
|
||||
interface UseChatAutoFollowOptions {
|
||||
currentSessionId: string | null;
|
||||
currentSessionKey: string | null;
|
||||
sessionMessageCount: number;
|
||||
sessionIsWorking: boolean;
|
||||
isMobile: boolean;
|
||||
onActiveTurnChange?: (turnId: string | null) => void;
|
||||
}
|
||||
|
||||
export interface UseChatAutoFollowResult {
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>;
|
||||
state: AutoFollowState;
|
||||
isPinned: boolean;
|
||||
isOverflowing: boolean;
|
||||
isFollowingProgrammatically: boolean;
|
||||
showScrollButton: boolean;
|
||||
notifyContentChange: (reason?: ContentChangeReason) => void;
|
||||
getAnimationHandlers: (messageId: string) => AnimationHandlers;
|
||||
goToBottom: (mode?: 'instant' | 'smooth') => void;
|
||||
scrollToBottomOnSend: () => void;
|
||||
releaseAutoFollow: () => void;
|
||||
saveSnapshotNow: () => void;
|
||||
restoreSnapshot: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Chat auto-follow. The model is deliberately simple, which is what makes it
|
||||
// flicker-free:
|
||||
//
|
||||
// • Auto-follow is on unless the user scrolled up (`released`), AND passive
|
||||
// following only acts while the session is active (working, plus a short
|
||||
// settle window). When idle, content-size changes are layout churn
|
||||
// (virtualizer re-measurement, async tool/code rendering) rather than live
|
||||
// growth, so the hook leaves scroll alone — re-pinning then would fight the
|
||||
// virtualizer and twitch the viewport.
|
||||
// • Following the bottom is INSTANT — `scrollTop = scrollHeight` inside the
|
||||
// content ResizeObserver, which fires after layout and before paint. There
|
||||
// is NO easing loop and NO settle burst, so there are never two writers
|
||||
// racing for `scrollTop` (the root cause of the old jiggle/double-scroll).
|
||||
// • A short-lived "auto" marker (position + 1500ms) lets the scroll handler
|
||||
// distinguish our own programmatic writes from genuine user scrolling, so
|
||||
// a scroll event that lands at our just-written bottom never trips a false
|
||||
// release.
|
||||
//
|
||||
// The public interface below is unchanged from the old implementation so every
|
||||
// consumer (ChatContainer, message parts, the timeline controller) keeps
|
||||
// working without edits.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const BOTTOM_SPACER_DESKTOP_VH = 0.10;
|
||||
const BOTTOM_SPACER_MOBILE_PX = 40;
|
||||
const SAVE_DEBOUNCE_MS = 150;
|
||||
const TOUCH_FINGER_DOWN_THRESHOLD = 2;
|
||||
// How long an "auto" (programmatic) scroll position stays trusted. Browsers can
|
||||
// dispatch the `scroll` event for our write asynchronously, after newer content
|
||||
// has already changed the geometry; the window keeps us from reading that lag as
|
||||
// a user scroll.
|
||||
const AUTO_MARK_TTL_MS = 1500;
|
||||
const AUTO_MATCH_TOLERANCE_PX = 2;
|
||||
// While a tracked height animation runs (e.g. a Thinking block auto-collapsing
|
||||
// mid-stream), the timeline shrinks/grows over a couple hundred ms and the
|
||||
// virtualizer re-measures, producing transient geometry. Browsers dispatch the
|
||||
// resulting `scroll` events asynchronously, so a stale event can land after we
|
||||
// have already re-pinned — its position matching neither the bottom zone nor the
|
||||
// freshly-moved auto marker — and be misread as a user scroll-away. During this
|
||||
// guard window we treat any `following`-state scroll event as our own and never
|
||||
// release via the heuristic. GENUINE user gestures still release instantly
|
||||
// through releaseFromUserIntent, so this is not glue. Sized to the reasoning
|
||||
// animation (200ms) plus headroom for trailing async scroll events.
|
||||
const ANIMATION_GUARD_MS = 350;
|
||||
// After streaming stops, keep following the bottom for a short window so the
|
||||
// final content can settle into place.
|
||||
const SETTLE_MS = 300;
|
||||
// Entry-stick window. On the FIRST open of a session, late async data (most
|
||||
// visibly a task/subagent tool whose nested rows are fetched from the child
|
||||
// session after entry — see useEnsureSessionMessages in ToolPart.tsx) grows the
|
||||
// timeline a beat or two AFTER we have already pinned to the bottom, leaving the
|
||||
// viewport stranded mid-history. The steady-state idle gate deliberately ignores
|
||||
// that growth (it can't tell entry from a user reading idle history). So instead
|
||||
// of weakening the gate, we open a short, gesture-cancellable window on entry
|
||||
// during which we FORCE the bottom on every growth. It ends QUIESCENCE_MS after
|
||||
// growth stops (capped by MAX_MS), or instantly on any real user scroll gesture.
|
||||
const ENTRY_STICK_QUIESCENCE_MS = 600;
|
||||
const ENTRY_STICK_MAX_MS = 8000;
|
||||
|
||||
const now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
|
||||
|
||||
// The bottom of the chat has an empty spacer (10vh on desktop, 40px on mobile)
|
||||
// — its height is exactly how far above scrollHeight the user can be while still
|
||||
// looking at "empty" space. We use that same value as the threshold for both
|
||||
// re-pinning auto-follow and showing the scroll-to-bottom button.
|
||||
const computeBottomZoneThreshold = (isMobile: boolean, container?: HTMLElement | null): number => {
|
||||
if (isMobile) return BOTTOM_SPACER_MOBILE_PX;
|
||||
const height = container?.clientHeight ?? 0;
|
||||
if (height <= 0) return 96;
|
||||
return Math.max(48, height * BOTTOM_SPACER_DESKTOP_VH);
|
||||
};
|
||||
|
||||
const distanceFromBottom = (el: HTMLElement): number => {
|
||||
return el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
};
|
||||
|
||||
const canScroll = (el: HTMLElement): boolean => {
|
||||
return el.scrollHeight - el.clientHeight > 1;
|
||||
};
|
||||
|
||||
const isNearBottom = (el: HTMLElement, isMobile: boolean): boolean => {
|
||||
return distanceFromBottom(el) <= computeBottomZoneThreshold(isMobile, el);
|
||||
};
|
||||
|
||||
const isReleaseKey = (event: KeyboardEvent): boolean => {
|
||||
if (event.altKey || event.ctrlKey || event.metaKey) {
|
||||
return false;
|
||||
}
|
||||
switch (event.key) {
|
||||
case 'ArrowUp':
|
||||
case 'PageUp':
|
||||
case 'Home':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const nestedScrollableTarget = (root: HTMLElement, target: EventTarget | null): HTMLElement | null => {
|
||||
if (!(target instanceof Element)) return null;
|
||||
const nested = target.closest('[data-scrollable]');
|
||||
if (!nested || nested === root || !(nested instanceof HTMLElement)) return null;
|
||||
return nested;
|
||||
};
|
||||
|
||||
const nestedScrollableCanConsumeUp = (root: HTMLElement, target: EventTarget | null): boolean => {
|
||||
const nested = nestedScrollableTarget(root, target);
|
||||
if (!nested) return false;
|
||||
return nested.scrollTop > 0;
|
||||
};
|
||||
|
||||
export const useChatAutoFollow = ({
|
||||
currentSessionId,
|
||||
currentSessionKey,
|
||||
sessionMessageCount,
|
||||
sessionIsWorking,
|
||||
isMobile,
|
||||
onActiveTurnChange,
|
||||
}: UseChatAutoFollowOptions): UseChatAutoFollowResult => {
|
||||
const scrollRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const [containerEl, setContainerEl] = React.useState<HTMLDivElement | null>(null);
|
||||
const lastSeenContainerRef = React.useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const [state, setState] = React.useState<AutoFollowState>('following');
|
||||
const [isOverflowing, setIsOverflowing] = React.useState(false);
|
||||
const [showScrollButton, setShowScrollButton] = React.useState(false);
|
||||
const [isFollowingProgrammatically, setIsFollowingProgrammatically] = React.useState(false);
|
||||
|
||||
// `stateRef` is the single source of truth for follow vs released; the React
|
||||
// state above is a mirror for rendering. `released` means the user scrolled
|
||||
// up and away from the bottom.
|
||||
const stateRef = React.useRef<AutoFollowState>('following');
|
||||
const isMobileRef = React.useRef(isMobile);
|
||||
isMobileRef.current = isMobile;
|
||||
const sessionIsWorkingRef = React.useRef(sessionIsWorking);
|
||||
sessionIsWorkingRef.current = sessionIsWorking;
|
||||
// `settling` keeps passive follow alive for a short window after work stops
|
||||
// so the final content can land at the bottom.
|
||||
const settlingRef = React.useRef(false);
|
||||
const settleTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const sessionMessageCountRef = React.useRef(sessionMessageCount);
|
||||
sessionMessageCountRef.current = sessionMessageCount;
|
||||
const currentSessionIdRef = React.useRef(currentSessionId);
|
||||
currentSessionIdRef.current = currentSessionId;
|
||||
const currentSessionKeyRef = React.useRef(currentSessionKey);
|
||||
currentSessionKeyRef.current = currentSessionKey;
|
||||
|
||||
const lastSessionKeyRef = React.useRef<string | null>(null);
|
||||
|
||||
// Programmatic-scroll marker: the bottom position we last
|
||||
// wrote and when. A scroll event whose scrollTop matches `top` within a few
|
||||
// px while still inside the TTL is OUR write, not the user's.
|
||||
const autoRef = React.useRef<{ top: number; time: number } | null>(null);
|
||||
const autoTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Timestamp until which a tracked height animation is in flight (see
|
||||
// ANIMATION_GUARD_MS). 0 = no animation guard active.
|
||||
const animationGuardUntilRef = React.useRef(0);
|
||||
|
||||
// True while the native (Capacitor iOS) keyboard slide choreography is in
|
||||
// flight (between 'oc:keyboard-anim' and 'oc:keyboard-settled' from
|
||||
// useNativeMobileChrome). During that window the pinned content is moved by a
|
||||
// transform on the inner wrapper, so the ResizeObserver chase must stand down.
|
||||
const keyboardAnimRef = React.useRef(false);
|
||||
|
||||
// Last observed scrollTop, used to derive scroll DIRECTION in the scroll
|
||||
// handler so the bottom-zone re-engage only fires when arriving at the bottom
|
||||
// by scrolling down — never when a user scrolling UP merely lands in the zone.
|
||||
const lastScrollTopRef = React.useRef(0);
|
||||
|
||||
// Entry-stick window state (see ENTRY_STICK_* above).
|
||||
const entryStickRef = React.useRef(false);
|
||||
const entryStickQuietTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const entryStickCapTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const entryStickLastHeightRef = React.useRef(0);
|
||||
|
||||
const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pendingSaveRef = React.useRef<{ sessionId: string; anchor: number } | null>(null);
|
||||
// When restoreSnapshot is invoked while ChatViewport is still hydrating
|
||||
// (skeleton rendered, no scroll container yet), we record the session here
|
||||
// so a follow-up effect can replay the restore once the container mounts.
|
||||
const pendingInitialRestoreRef = React.useRef<string | null>(null);
|
||||
|
||||
const updateViewportAnchor = useViewportStore((s) => s.updateViewportAnchor);
|
||||
|
||||
// Detect when the scroll container DOM element changes (mount, unmount, remount).
|
||||
// Without this, listener-attach effects would only ever bind to the element that
|
||||
// existed at the hook's first render, missing later mounts (e.g. after first send
|
||||
// promotes a draft session to a real chat with messages).
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
React.useLayoutEffect(() => {
|
||||
if (scrollRef.current !== lastSeenContainerRef.current) {
|
||||
lastSeenContainerRef.current = scrollRef.current;
|
||||
setContainerEl(scrollRef.current);
|
||||
}
|
||||
});
|
||||
|
||||
// `active` is `working || settling`. Passive auto-follow
|
||||
// (the ResizeObserver re-pin and any non-forced scrollToBottom) only runs
|
||||
// while active. When the session is idle, content-size changes are layout
|
||||
// churn — virtualizer re-measurement, async tool/code rendering — NOT live
|
||||
// growth, so we must NOT yank the user to the bottom. Forcing this gate is
|
||||
// what stops the twitch when tall items (expanded tools) re-measure as the
|
||||
// user scrolls.
|
||||
const isActive = React.useCallback((): boolean => {
|
||||
return sessionIsWorkingRef.current || settlingRef.current;
|
||||
}, []);
|
||||
|
||||
const setStateValue = React.useCallback((next: AutoFollowState) => {
|
||||
if (stateRef.current === next) return;
|
||||
stateRef.current = next;
|
||||
setState(next);
|
||||
}, []);
|
||||
|
||||
// ── auto marker ────────────────────────────────────────────────────────
|
||||
const markAuto = React.useCallback((el: HTMLElement) => {
|
||||
autoRef.current = {
|
||||
top: Math.max(0, el.scrollHeight - el.clientHeight),
|
||||
time: now(),
|
||||
};
|
||||
if (autoTimerRef.current) clearTimeout(autoTimerRef.current);
|
||||
autoTimerRef.current = setTimeout(() => {
|
||||
autoRef.current = null;
|
||||
autoTimerRef.current = null;
|
||||
}, AUTO_MARK_TTL_MS);
|
||||
}, []);
|
||||
|
||||
const isAuto = React.useCallback((el: HTMLElement): boolean => {
|
||||
const a = autoRef.current;
|
||||
if (!a) return false;
|
||||
if (now() - a.time > AUTO_MARK_TTL_MS) {
|
||||
autoRef.current = null;
|
||||
return false;
|
||||
}
|
||||
return Math.abs(el.scrollTop - a.top) < AUTO_MATCH_TOLERANCE_PX;
|
||||
}, []);
|
||||
|
||||
const isAnimationGuardActive = React.useCallback((): boolean => {
|
||||
return now() < animationGuardUntilRef.current;
|
||||
}, []);
|
||||
|
||||
// ── entry-stick window ───────────────────────────────────────────────────
|
||||
const endEntryStick = React.useCallback(() => {
|
||||
entryStickRef.current = false;
|
||||
if (entryStickQuietTimerRef.current) {
|
||||
clearTimeout(entryStickQuietTimerRef.current);
|
||||
entryStickQuietTimerRef.current = null;
|
||||
}
|
||||
if (entryStickCapTimerRef.current) {
|
||||
clearTimeout(entryStickCapTimerRef.current);
|
||||
entryStickCapTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// (Re)arm the quiescence timer: the window closes this long after the last
|
||||
// growth. Called once on begin and again on every growth-driven re-pin.
|
||||
const armEntryStickQuiet = React.useCallback(() => {
|
||||
if (entryStickQuietTimerRef.current) {
|
||||
clearTimeout(entryStickQuietTimerRef.current);
|
||||
}
|
||||
entryStickQuietTimerRef.current = setTimeout(() => {
|
||||
entryStickQuietTimerRef.current = null;
|
||||
endEntryStick();
|
||||
}, ENTRY_STICK_QUIESCENCE_MS);
|
||||
}, [endEntryStick]);
|
||||
|
||||
const beginEntryStick = React.useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
entryStickRef.current = true;
|
||||
entryStickLastHeightRef.current = el.scrollHeight;
|
||||
armEntryStickQuiet();
|
||||
// Reset the absolute cap fresh on every entry (e.g. session switch) so a
|
||||
// stale cap from a previous open can't cut this window short.
|
||||
if (entryStickCapTimerRef.current) {
|
||||
clearTimeout(entryStickCapTimerRef.current);
|
||||
}
|
||||
entryStickCapTimerRef.current = setTimeout(() => {
|
||||
entryStickCapTimerRef.current = null;
|
||||
endEntryStick();
|
||||
}, ENTRY_STICK_MAX_MS);
|
||||
}, [armEntryStickQuiet, endEntryStick]);
|
||||
|
||||
// ── overflow / scroll-to-bottom button ──────────────────────────────────
|
||||
const updateOverflowAndButton = React.useCallback(() => {
|
||||
const container = scrollRef.current;
|
||||
if (!container) {
|
||||
setIsOverflowing(false);
|
||||
setShowScrollButton(false);
|
||||
return;
|
||||
}
|
||||
const overflowing = canScroll(container);
|
||||
setIsOverflowing(overflowing);
|
||||
if (!overflowing) {
|
||||
setShowScrollButton(false);
|
||||
return;
|
||||
}
|
||||
const showButton = stateRef.current === 'released' && !isNearBottom(container, isMobileRef.current);
|
||||
setShowScrollButton(showButton);
|
||||
}, []);
|
||||
|
||||
// ── core scroll primitives ───────────────────────────────────────────────
|
||||
const scrollToBottomNow = React.useCallback((behavior: ScrollBehavior) => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
markAuto(el);
|
||||
// `scrollHeight` is rounded to an integer while the real content height
|
||||
// is fractional (prose line-heights), so `scrollTop = scrollHeight`
|
||||
// leaves a 0–1px remainder that oscillates per streamed token and makes
|
||||
// bottom-anchored rows jitter vertically. An over-large target clamps to
|
||||
// the exact fractional maximum instead, pinning content to the bottom.
|
||||
const overshootTarget = el.scrollHeight + 4096;
|
||||
if (behavior === 'smooth') {
|
||||
el.scrollTo({ top: overshootTarget, behavior });
|
||||
return;
|
||||
}
|
||||
// Direct `scrollTop` assignment bypasses any CSS `scroll-behavior: smooth`
|
||||
// and lands in the same frame — no visible catch-up animation.
|
||||
el.scrollTop = overshootTarget;
|
||||
}, [markAuto]);
|
||||
|
||||
// `force` true = user-intent jump (clears released and always scrolls).
|
||||
// `force` false = passive follow (only while still following).
|
||||
const scrollToBottom = React.useCallback((force: boolean, behavior: ScrollBehavior = 'auto') => {
|
||||
const el = scrollRef.current;
|
||||
|
||||
// Passive follow only while active (working/settling). Forced jumps
|
||||
// (send, go-to-bottom, session restore) always proceed.
|
||||
if (!force && !isActive()) return;
|
||||
|
||||
if (force && stateRef.current !== 'following') {
|
||||
setStateValue('following');
|
||||
}
|
||||
if (!el) return;
|
||||
if (!force && stateRef.current !== 'following') return;
|
||||
|
||||
// Always re-pin, even when already within tolerance of the bottom.
|
||||
// Sub-tolerance growth (fractional line-height remainders) would
|
||||
// otherwise leave the bottom drifting by up to ±AUTO_MATCH_TOLERANCE_PX
|
||||
// between full re-pins, which reads as 1px vertical jitter on
|
||||
// bottom-anchored rows during streaming. The write happens pre-paint
|
||||
// (ResizeObserver) and is a no-op when the position is unchanged.
|
||||
scrollToBottomNow(force ? behavior : 'auto');
|
||||
}, [isActive, scrollToBottomNow, setStateValue]);
|
||||
|
||||
// User left the bottom — release auto-follow.
|
||||
const stop = React.useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
if (!canScroll(el)) {
|
||||
setStateValue('following');
|
||||
return;
|
||||
}
|
||||
if (stateRef.current === 'released') return;
|
||||
setStateValue('released');
|
||||
updateOverflowAndButton();
|
||||
}, [setStateValue, updateOverflowAndButton]);
|
||||
|
||||
// ── public scroll API (mapped onto the primitives) ───────────────────────
|
||||
const goToBottom = React.useCallback((mode: 'instant' | 'smooth' = 'instant') => {
|
||||
scrollToBottom(true, mode === 'smooth' ? 'smooth' : 'auto');
|
||||
}, [scrollToBottom]);
|
||||
|
||||
const scrollToBottomOnSend = React.useCallback(() => {
|
||||
// Single movement to the just-sent message. Force re-pins to the bottom
|
||||
// whether we were following or scrolled up; the content ResizeObserver
|
||||
// keeps us pinned as the optimistic message and its reply stream in.
|
||||
scrollToBottom(true);
|
||||
}, [scrollToBottom]);
|
||||
|
||||
const releaseAutoFollow = React.useCallback(() => {
|
||||
setStateValue('released');
|
||||
updateOverflowAndButton();
|
||||
}, [setStateValue, updateOverflowAndButton]);
|
||||
|
||||
const releaseFromUserIntent = React.useCallback(() => {
|
||||
// A genuine user gesture (wheel/touch/key/scrollbar) cancels the entry
|
||||
// window immediately so we never fight the user's read position.
|
||||
endEntryStick();
|
||||
stop();
|
||||
}, [endEntryStick, stop]);
|
||||
|
||||
// ── per-session snapshot persistence (kept; restore still goes to bottom) ─
|
||||
const flushSave = React.useCallback(() => {
|
||||
if (saveTimerRef.current !== null) {
|
||||
clearTimeout(saveTimerRef.current);
|
||||
saveTimerRef.current = null;
|
||||
}
|
||||
const pending = pendingSaveRef.current;
|
||||
if (!pending) return;
|
||||
const container = scrollRef.current;
|
||||
if (!container) {
|
||||
pendingSaveRef.current = null;
|
||||
return;
|
||||
}
|
||||
updateViewportAnchor(pending.sessionId, pending.anchor, {
|
||||
scrollTop: container.scrollTop,
|
||||
scrollHeight: container.scrollHeight,
|
||||
clientHeight: container.clientHeight,
|
||||
});
|
||||
pendingSaveRef.current = null;
|
||||
}, [updateViewportAnchor]);
|
||||
|
||||
const queueSave = React.useCallback(() => {
|
||||
const sessionId = currentSessionIdRef.current;
|
||||
if (!sessionId) return;
|
||||
const container = scrollRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const { scrollTop, scrollHeight, clientHeight } = container;
|
||||
const anchorRatio = scrollHeight > 0
|
||||
? (scrollTop + clientHeight / 2) / scrollHeight
|
||||
: 0;
|
||||
const anchor = Math.floor(anchorRatio * sessionMessageCountRef.current);
|
||||
|
||||
pendingSaveRef.current = { sessionId, anchor };
|
||||
if (saveTimerRef.current !== null) return;
|
||||
saveTimerRef.current = setTimeout(() => {
|
||||
saveTimerRef.current = null;
|
||||
flushSave();
|
||||
}, SAVE_DEBOUNCE_MS);
|
||||
}, [flushSave]);
|
||||
|
||||
const saveSnapshotNow = React.useCallback(() => {
|
||||
flushSave();
|
||||
}, [flushSave]);
|
||||
|
||||
const restoreSnapshot = React.useCallback(async (): Promise<boolean> => {
|
||||
const sessionKey = currentSessionKeyRef.current;
|
||||
if (!sessionKey) return false;
|
||||
|
||||
const container = scrollRef.current;
|
||||
if (!container) {
|
||||
// ChatViewport not mounted yet (e.g., session still hydrating).
|
||||
// Record the request so the container-attach effect can replay it.
|
||||
pendingInitialRestoreRef.current = sessionKey;
|
||||
setStateValue('following');
|
||||
return false;
|
||||
}
|
||||
pendingInitialRestoreRef.current = null;
|
||||
|
||||
// Always return to the bottom on session switch. The content
|
||||
// ResizeObserver re-pins instantly as late
|
||||
// history measures in, so there is no smooth scroll-from-mid artifact.
|
||||
setStateValue('following');
|
||||
scrollToBottom(true);
|
||||
// Hold the bottom across late async growth (e.g. task/subagent child
|
||||
// session data landing a beat after entry) until content quiesces or the
|
||||
// user scrolls.
|
||||
beginEntryStick();
|
||||
updateOverflowAndButton();
|
||||
return false;
|
||||
}, [beginEntryStick, scrollToBottom, setStateValue, updateOverflowAndButton]);
|
||||
|
||||
// ── session change ───────────────────────────────────────────────────────
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId || !currentSessionKey || currentSessionKey === lastSessionKeyRef.current) {
|
||||
return;
|
||||
}
|
||||
lastSessionKeyRef.current = currentSessionKey;
|
||||
MessageFreshnessDetector.getInstance().recordSessionStart(currentSessionId);
|
||||
flushSave();
|
||||
autoRef.current = null;
|
||||
// Drop any pending restore request inherited from a different session.
|
||||
if (pendingInitialRestoreRef.current && pendingInitialRestoreRef.current !== currentSessionKey) {
|
||||
pendingInitialRestoreRef.current = null;
|
||||
}
|
||||
}, [currentSessionId, currentSessionKey, flushSave]);
|
||||
|
||||
// When work begins and we are still
|
||||
// following, pin to the bottom. When work stops, keep following alive for a
|
||||
// short settle window so the final content lands at the bottom, then go
|
||||
// idle (after which passive follow is disabled — see `isActive`).
|
||||
React.useEffect(() => {
|
||||
settlingRef.current = false;
|
||||
if (settleTimerRef.current) {
|
||||
clearTimeout(settleTimerRef.current);
|
||||
settleTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (sessionIsWorking) {
|
||||
if (stateRef.current === 'following') {
|
||||
scrollToBottom(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
settlingRef.current = true;
|
||||
settleTimerRef.current = setTimeout(() => {
|
||||
settlingRef.current = false;
|
||||
settleTimerRef.current = null;
|
||||
}, SETTLE_MS);
|
||||
}, [sessionIsWorking, scrollToBottom]);
|
||||
|
||||
// Suppress the overlay scrollbar thumb only while we are actively following a
|
||||
// live stream (the thumb would otherwise jump on every instant re-pin). When
|
||||
// idle or released the scrollbar behaves normally. Stable: changes only when
|
||||
// follow-state or working-state flips, not on every frame.
|
||||
React.useEffect(() => {
|
||||
setIsFollowingProgrammatically(state === 'following' && sessionIsWorking);
|
||||
}, [state, sessionIsWorking]);
|
||||
|
||||
// Replay a deferred restoreSnapshot once ChatViewport mounts.
|
||||
// useLayoutEffect ensures scroll position is set before the browser paints,
|
||||
// preventing a visible flash of content at the wrong scroll position.
|
||||
React.useLayoutEffect(() => {
|
||||
if (!containerEl) return;
|
||||
if (pendingInitialRestoreRef.current && pendingInitialRestoreRef.current === currentSessionKey) {
|
||||
void restoreSnapshot();
|
||||
}
|
||||
}, [containerEl, currentSessionKey, restoreSnapshot]);
|
||||
|
||||
// ── scroll event handling ────────────────────────────────────────────────
|
||||
const handleScrollEvent = React.useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const previousTop = lastScrollTopRef.current;
|
||||
lastScrollTopRef.current = el.scrollTop;
|
||||
const scrollingDown = el.scrollTop > previousTop + 0.5;
|
||||
|
||||
updateOverflowAndButton();
|
||||
|
||||
if (!canScroll(el)) {
|
||||
setStateValue('following');
|
||||
return;
|
||||
}
|
||||
|
||||
// Within the bottom zone → (re-)pin to following. This is how scrolling
|
||||
// back DOWN to the bottom resumes auto-follow. Crucially, re-engage only
|
||||
// when the user arrives by scrolling down (or is already following, or is
|
||||
// essentially at the true bottom). A user scrolling UP that merely lands
|
||||
// in the bottom spacer zone must NOT be yanked back into follow — that is
|
||||
// the dead-zone fight that made small upward scrolls impossible while
|
||||
// content streams.
|
||||
if (isNearBottom(el, isMobileRef.current)) {
|
||||
const atTrueBottom = distanceFromBottom(el) <= AUTO_MATCH_TOLERANCE_PX;
|
||||
if (scrollingDown || stateRef.current === 'following' || atTrueBottom) {
|
||||
setStateValue('following');
|
||||
}
|
||||
queueSave();
|
||||
return;
|
||||
}
|
||||
|
||||
// Our own geometry change (a programmatic write that landed at the bottom
|
||||
// but where content grew between the write and this event, OR a tracked
|
||||
// height animation in flight) — keep following, don't release.
|
||||
if (stateRef.current === 'following' && (isAuto(el) || isAnimationGuardActive())) {
|
||||
scrollToBottom(false);
|
||||
queueSave();
|
||||
return;
|
||||
}
|
||||
|
||||
// Genuine user scroll away from the bottom.
|
||||
stop();
|
||||
queueSave();
|
||||
}, [isAnimationGuardActive, isAuto, queueSave, scrollToBottom, setStateValue, stop, updateOverflowAndButton]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const container = containerEl;
|
||||
if (!container) return;
|
||||
|
||||
lastScrollTopRef.current = container.scrollTop;
|
||||
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
if (event.deltaY >= 0) return;
|
||||
if (nestedScrollableCanConsumeUp(container, event.target)) return;
|
||||
releaseFromUserIntent();
|
||||
};
|
||||
|
||||
let touchLastY: number | null = null;
|
||||
const handleTouchStart = (event: TouchEvent) => {
|
||||
const touch = event.touches.item(0);
|
||||
touchLastY = touch ? touch.clientY : null;
|
||||
};
|
||||
const handleTouchMove = (event: TouchEvent) => {
|
||||
const touch = event.touches.item(0);
|
||||
if (!touch) {
|
||||
touchLastY = null;
|
||||
return;
|
||||
}
|
||||
const previousY = touchLastY;
|
||||
touchLastY = touch.clientY;
|
||||
if (previousY === null) return;
|
||||
const fingerDelta = touch.clientY - previousY;
|
||||
if (fingerDelta <= TOUCH_FINGER_DOWN_THRESHOLD) return;
|
||||
if (nestedScrollableCanConsumeUp(container, event.target)) return;
|
||||
releaseFromUserIntent();
|
||||
};
|
||||
const handleTouchEnd = () => {
|
||||
touchLastY = null;
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (!isReleaseKey(event)) return;
|
||||
releaseFromUserIntent();
|
||||
};
|
||||
|
||||
const handlePointerDownIntent = (event: PointerEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
if (!target.closest('[data-overlay-scrollbar-thumb]')) return;
|
||||
releaseFromUserIntent();
|
||||
};
|
||||
|
||||
container.addEventListener('scroll', handleScrollEvent, { passive: true });
|
||||
container.addEventListener('wheel', handleWheel, { passive: true });
|
||||
container.addEventListener('touchstart', handleTouchStart, { passive: true });
|
||||
container.addEventListener('touchmove', handleTouchMove, { passive: true });
|
||||
container.addEventListener('touchend', handleTouchEnd, { passive: true });
|
||||
container.addEventListener('touchcancel', handleTouchEnd, { passive: true });
|
||||
container.addEventListener('keydown', handleKeyDown);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('pointerdown', handlePointerDownIntent, true);
|
||||
}
|
||||
|
||||
return () => {
|
||||
container.removeEventListener('scroll', handleScrollEvent);
|
||||
container.removeEventListener('wheel', handleWheel);
|
||||
container.removeEventListener('touchstart', handleTouchStart);
|
||||
container.removeEventListener('touchmove', handleTouchMove);
|
||||
container.removeEventListener('touchend', handleTouchEnd);
|
||||
container.removeEventListener('touchcancel', handleTouchEnd);
|
||||
container.removeEventListener('keydown', handleKeyDown);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('pointerdown', handlePointerDownIntent, true);
|
||||
}
|
||||
};
|
||||
}, [containerEl, handleScrollEvent, releaseFromUserIntent]);
|
||||
|
||||
// The heart of the follow behaviour: the content ResizeObserver fires after
|
||||
// layout and before paint, so re-pinning to the bottom here is invisible —
|
||||
// there is no "jump up then catch up". Observe both the container (composer
|
||||
// growth shrinks the viewport) and the inner content (streaming growth).
|
||||
React.useEffect(() => {
|
||||
const container = containerEl;
|
||||
if (!container || typeof ResizeObserver === 'undefined') return;
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
// Keyboard slide in flight: the container/composer resizes it reports
|
||||
// are part of the transform choreography — the settle handler does the
|
||||
// single deterministic re-pin, so chasing here would just fight it.
|
||||
if (keyboardAnimRef.current) {
|
||||
updateOverflowAndButton();
|
||||
return;
|
||||
}
|
||||
const el = scrollRef.current;
|
||||
if (el && !canScroll(el)) {
|
||||
setStateValue('following');
|
||||
updateOverflowAndButton();
|
||||
return;
|
||||
}
|
||||
updateOverflowAndButton();
|
||||
// Entry-stick window: on first session open, FORCE the bottom on
|
||||
// every growth so late async data (task/subagent child rows, code
|
||||
// highlight, mermaid) can't strand the viewport mid-history. Force
|
||||
// overrides any false `released` from the growth itself; only a real
|
||||
// user gesture clears the window (releaseFromUserIntent).
|
||||
if (entryStickRef.current && el) {
|
||||
const grew = el.scrollHeight > entryStickLastHeightRef.current + 1;
|
||||
entryStickLastHeightRef.current = el.scrollHeight;
|
||||
scrollToBottom(true);
|
||||
if (grew) armEntryStickQuiet();
|
||||
return;
|
||||
}
|
||||
// Idle resize = layout churn (virtualizer re-measurement, async
|
||||
// tool/code rendering), NOT live growth. Never re-pin when idle, or
|
||||
// tall items re-measuring as the user scrolls cause an endless
|
||||
// scroll-to-bottom/re-measure twitch.
|
||||
if (!isActive()) return;
|
||||
if (stateRef.current !== 'following') return;
|
||||
scrollToBottom(false);
|
||||
});
|
||||
observer.observe(container);
|
||||
const inner = container.firstElementChild;
|
||||
if (inner instanceof Element) {
|
||||
observer.observe(inner);
|
||||
}
|
||||
return () => observer.disconnect();
|
||||
}, [armEntryStickQuiet, containerEl, isActive, scrollToBottom, setStateValue, updateOverflowAndButton]);
|
||||
|
||||
// ── native keyboard transitions (Capacitor choreography) ────────────────
|
||||
// The chat scroller gets NO transforms during the keyboard transition:
|
||||
// transforming the scroll container (or its content) forces WebKit to
|
||||
// rebuild the composited scrolling layers, which stalls for seconds on
|
||||
// long chats. Instead the chat repositions with instant snaps that hide
|
||||
// behind the keyboard itself:
|
||||
// show: content stays put while the keyboard/composer slide over it; the
|
||||
// settled event (shell layout snap) does ONE instant re-pin.
|
||||
// hide: the shell layout is restored up-front — the scrollTop clamp
|
||||
// happens while the keyboard still covers that region — and the
|
||||
// settled event re-pins once at the end.
|
||||
// During the window we only guard the scroll heuristics and the observer
|
||||
// chase. These events never fire outside the Capacitor app.
|
||||
React.useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const handleKeyboardAnim = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ phase: 'show' | 'hide'; slide: number; durationMs: number; easing: string }>).detail;
|
||||
if (!detail) return;
|
||||
keyboardAnimRef.current = true;
|
||||
// The clamp/resize during the choreography can dispatch scroll events
|
||||
// that land away from the auto marker — never read those as a user
|
||||
// scroll-away.
|
||||
animationGuardUntilRef.current = now() + detail.durationMs + ANIMATION_GUARD_MS;
|
||||
};
|
||||
|
||||
const handleKeyboardSettled = () => {
|
||||
keyboardAnimRef.current = false;
|
||||
const el = scrollRef.current;
|
||||
if (!el) {
|
||||
updateOverflowAndButton();
|
||||
return;
|
||||
}
|
||||
// Single deterministic re-pin, same task as the layout swap → lands
|
||||
// before paint. (scrollToBottomNow, not scrollToBottom: this must not
|
||||
// be gated on working/settling — the keyboard resize is a viewport
|
||||
// change, not content growth.)
|
||||
if (stateRef.current === 'following' && canScroll(el)) {
|
||||
scrollToBottomNow('auto');
|
||||
}
|
||||
updateOverflowAndButton();
|
||||
};
|
||||
|
||||
window.addEventListener('oc:keyboard-anim', handleKeyboardAnim);
|
||||
window.addEventListener('oc:keyboard-settled', handleKeyboardSettled);
|
||||
return () => {
|
||||
window.removeEventListener('oc:keyboard-anim', handleKeyboardAnim);
|
||||
window.removeEventListener('oc:keyboard-settled', handleKeyboardSettled);
|
||||
keyboardAnimRef.current = false;
|
||||
};
|
||||
}, [scrollToBottomNow, updateOverflowAndButton]);
|
||||
|
||||
React.useEffect(() => {
|
||||
updateOverflowAndButton();
|
||||
}, [sessionMessageCount, updateOverflowAndButton]);
|
||||
|
||||
const notifyContentChange = React.useCallback((reason?: ContentChangeReason) => {
|
||||
// A tracked height animation (e.g. Thinking auto-collapse) opens a guard
|
||||
// window so its transient geometry / async scroll events are not misread
|
||||
// as a user scroll-away. Real gestures still release through
|
||||
// releaseFromUserIntent, so the user can always scroll up freely.
|
||||
if (reason === 'animation') {
|
||||
animationGuardUntilRef.current = now() + ANIMATION_GUARD_MS;
|
||||
}
|
||||
updateOverflowAndButton();
|
||||
// Entry-stick window: late structural growth (notably the task/subagent
|
||||
// summary landing from the child session — ToolPart emits 'structural'
|
||||
// here) must keep us pinned and refresh the quiescence timer, even though
|
||||
// the session is idle.
|
||||
if (entryStickRef.current) {
|
||||
scrollToBottom(true);
|
||||
armEntryStickQuiet();
|
||||
return;
|
||||
}
|
||||
if (stateRef.current === 'following') {
|
||||
scrollToBottom(false);
|
||||
}
|
||||
}, [armEntryStickQuiet, scrollToBottom, updateOverflowAndButton]);
|
||||
|
||||
const animationHandlersRef = React.useRef<Map<string, AnimationHandlers>>(new Map());
|
||||
|
||||
const getAnimationHandlers = React.useCallback((messageId: string): AnimationHandlers => {
|
||||
const cached = animationHandlersRef.current.get(messageId);
|
||||
if (cached) return cached;
|
||||
|
||||
const kick = () => {
|
||||
if (stateRef.current === 'following') {
|
||||
scrollToBottom(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlers: AnimationHandlers = {
|
||||
onChunk: kick,
|
||||
onComplete: () => {
|
||||
updateOverflowAndButton();
|
||||
},
|
||||
onStreamingCandidate: () => {},
|
||||
onAnimationStart: () => {},
|
||||
onAnimatedHeightChange: kick,
|
||||
onReservationCancelled: () => {},
|
||||
onReasoningBlock: () => {},
|
||||
};
|
||||
animationHandlersRef.current.set(messageId, handlers);
|
||||
return handlers;
|
||||
}, [scrollToBottom, updateOverflowAndButton]);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
if (autoTimerRef.current) {
|
||||
clearTimeout(autoTimerRef.current);
|
||||
autoTimerRef.current = null;
|
||||
}
|
||||
if (settleTimerRef.current) {
|
||||
clearTimeout(settleTimerRef.current);
|
||||
settleTimerRef.current = null;
|
||||
}
|
||||
endEntryStick();
|
||||
flushSave();
|
||||
if (saveTimerRef.current !== null) {
|
||||
clearTimeout(saveTimerRef.current);
|
||||
saveTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [endEntryStick, flushSave]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!onActiveTurnChange) return;
|
||||
const container = containerEl;
|
||||
if (!container) return;
|
||||
|
||||
let lastActiveTurnId: string | null = null;
|
||||
const spy = createScrollSpy({
|
||||
onActive: (turnId) => {
|
||||
if (turnId === lastActiveTurnId) return;
|
||||
lastActiveTurnId = turnId;
|
||||
onActiveTurnChange(turnId);
|
||||
},
|
||||
});
|
||||
spy.setContainer(container);
|
||||
|
||||
const elementByTurnId = new Map<string, HTMLElement>();
|
||||
const registerTurnNode = (node: HTMLElement) => {
|
||||
const turnId = node.dataset.turnId;
|
||||
if (!turnId) return false;
|
||||
elementByTurnId.set(turnId, node);
|
||||
spy.register(node, turnId);
|
||||
return true;
|
||||
};
|
||||
const unregisterTurnNode = (node: HTMLElement) => {
|
||||
const turnId = node.dataset.turnId;
|
||||
if (!turnId) return false;
|
||||
if (elementByTurnId.get(turnId) !== node) return false;
|
||||
elementByTurnId.delete(turnId);
|
||||
spy.unregister(turnId);
|
||||
return true;
|
||||
};
|
||||
const collectTurnNodes = (node: Node): HTMLElement[] => {
|
||||
if (!(node instanceof HTMLElement)) return [];
|
||||
const collected: HTMLElement[] = [];
|
||||
if (node.matches('[data-turn-id]')) collected.push(node);
|
||||
node.querySelectorAll<HTMLElement>('[data-turn-id]').forEach((el) => collected.push(el));
|
||||
return collected;
|
||||
};
|
||||
|
||||
container.querySelectorAll<HTMLElement>('[data-turn-id]').forEach(registerTurnNode);
|
||||
spy.markDirty();
|
||||
|
||||
const mutationObserver = new MutationObserver((records) => {
|
||||
let changed = false;
|
||||
records.forEach((record) => {
|
||||
record.removedNodes.forEach((node) => {
|
||||
collectTurnNodes(node).forEach((turnNode) => {
|
||||
if (unregisterTurnNode(turnNode)) changed = true;
|
||||
});
|
||||
});
|
||||
record.addedNodes.forEach((node) => {
|
||||
collectTurnNodes(node).forEach((turnNode) => {
|
||||
if (registerTurnNode(turnNode)) changed = true;
|
||||
});
|
||||
});
|
||||
});
|
||||
if (changed) spy.markDirty();
|
||||
});
|
||||
mutationObserver.observe(container, { subtree: true, childList: true });
|
||||
|
||||
const onScroll = () => spy.onScroll();
|
||||
container.addEventListener('scroll', onScroll, { passive: true });
|
||||
|
||||
return () => {
|
||||
container.removeEventListener('scroll', onScroll);
|
||||
mutationObserver.disconnect();
|
||||
spy.destroy();
|
||||
};
|
||||
}, [containerEl, onActiveTurnChange]);
|
||||
|
||||
return {
|
||||
scrollRef,
|
||||
state,
|
||||
isPinned: state === 'following',
|
||||
isOverflowing,
|
||||
isFollowingProgrammatically,
|
||||
showScrollButton,
|
||||
notifyContentChange,
|
||||
getAnimationHandlers,
|
||||
goToBottom,
|
||||
scrollToBottomOnSend,
|
||||
releaseAutoFollow,
|
||||
saveSnapshotNow,
|
||||
restoreSnapshot,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,867 @@
|
||||
import React from 'react';
|
||||
|
||||
import { MessageFreshnessDetector } from '@/lib/messageFreshness';
|
||||
import { createScrollSpy } from '@/components/chat/lib/scroll/scrollSpy';
|
||||
import { useViewportStore } from '@/sync/viewport-store';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import {
|
||||
CHAT_LIST_ANCHOR_OFFSET,
|
||||
getAnchoredTurnMetrics,
|
||||
resolveTimelineIsAtEnd,
|
||||
type TimelineListMeasurementState,
|
||||
type TimelineScrollMode,
|
||||
} from '@/components/chat/lib/scroll/timelineScrollAnchoring';
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Chat timeline scroll ownership.
|
||||
//
|
||||
// The virtualized list owns the scroll position; this hook only decides which
|
||||
// of three mutually exclusive modes is active and, when a mode calls for it,
|
||||
// issues ONE deterministic scroll command:
|
||||
//
|
||||
// • `following-end` — pinned to the live edge. The list keeps us there
|
||||
// through `maintainScrollAtEnd`; we only re-assert after a data change.
|
||||
// • `anchoring-new-turn` — the just-sent user message is parked near the TOP
|
||||
// of the viewport and the reply streams into the reserved end space below
|
||||
// it. The viewport does NOT move while the turn still fits; once the turn
|
||||
// outgrows the usable viewport we scroll by the exact delta needed to keep
|
||||
// its end visible.
|
||||
// • `free-scrolling` — the user took over. Nothing moves until they opt
|
||||
// back in by returning to the end.
|
||||
//
|
||||
// Opting out of automatic movement is driven by REAL gestures (wheel /
|
||||
// touchmove / pointerdown), not by inferring intent from scroll positions. Each
|
||||
// gesture bumps a generation counter; any in-flight automatic movement compares
|
||||
// its captured generation against the current one and aborts if they differ.
|
||||
// That comparison replaces the timer windows the previous implementation needed
|
||||
// to tell its own writes apart from the user's, which is why there are no
|
||||
// guard/settle/entry-stick timers here.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// The subset of the list ref this hook drives. Declared structurally so the
|
||||
// hook stays testable without a renderer and does not hard-depend on the list
|
||||
// implementation.
|
||||
export interface TimelineListHandle {
|
||||
getState: () => TimelineListMeasurementState & {
|
||||
readonly scroll: number;
|
||||
readonly listen?: (
|
||||
listenerType: 'totalSize',
|
||||
callback: (value: number) => void,
|
||||
) => () => void;
|
||||
};
|
||||
getScrollableNode: () => HTMLElement | null;
|
||||
scrollToEnd: (options?: { animated?: boolean }) => unknown;
|
||||
scrollToOffset: (params: { offset: number; animated?: boolean }) => unknown;
|
||||
scrollToIndex: (params: {
|
||||
index: number;
|
||||
animated?: boolean;
|
||||
viewPosition?: number;
|
||||
viewOffset?: number;
|
||||
}) => unknown;
|
||||
}
|
||||
|
||||
interface UseChatTimelineScrollOptions {
|
||||
currentSessionId: string | null;
|
||||
currentSessionKey: string | null;
|
||||
sessionMessageCount: number;
|
||||
composerOverlayHeight: number;
|
||||
// Id of the newest user message in the rendered timeline. When a send has
|
||||
// armed the anchor, the next new id here becomes the anchored row.
|
||||
lastUserMessageId: string | null;
|
||||
onActiveTurnChange?: (turnId: string | null) => void;
|
||||
}
|
||||
|
||||
export interface UseChatTimelineScrollResult {
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>;
|
||||
// The live scroll element, as state, so effects that must re-bind when the
|
||||
// list remounts (session switch) can depend on it.
|
||||
scrollNode: HTMLDivElement | null;
|
||||
isPinned: boolean;
|
||||
registerList: (list: TimelineListHandle | null) => void;
|
||||
anchorMessageId: string | null;
|
||||
onAnchorReady: (messageId: string, anchorIndex: number) => void;
|
||||
onAnchorSizeChanged: (messageId: string) => void;
|
||||
onIsAtEndChange: (isAtEnd: boolean) => void;
|
||||
onManualNavigation: () => void;
|
||||
onTimelineDataChange: () => void;
|
||||
showScrollButton: boolean;
|
||||
/** A real gesture took the scroll; flips back on any explicit opt-in. */
|
||||
userOwnsScroll: boolean;
|
||||
isFollowingProgrammatically: boolean;
|
||||
goToBottom: (mode?: 'instant' | 'smooth') => void;
|
||||
scrollToBottomOnSend: () => void;
|
||||
saveSnapshotNow: () => void;
|
||||
restoreSnapshot: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
// Showing the pill is debounced so it does not flash while a thread switch
|
||||
// settles (the list reports isAtEnd=false until its initial end-scroll lands).
|
||||
// Hiding is always immediate.
|
||||
const SHOW_SCROLL_BUTTON_DELAY_MS = 150;
|
||||
const SAVE_DEBOUNCE_MS = 150;
|
||||
// The anchor scroll is animated; `scrollend` is the authoritative completion
|
||||
// signal, and this bounds the wait for browsers that drop it.
|
||||
const ANCHOR_SETTLE_FALLBACK_MS = 750;
|
||||
// Re-running the anchor positioning while the list is still mounting rows.
|
||||
const ANCHOR_POSITION_ATTEMPTS = 12;
|
||||
// Anchor restores only correct sub-pixel drift; anything larger is the user or
|
||||
// a genuine relayout and must not be undone.
|
||||
const ANCHOR_RESTORE_TOLERANCE_PX = 2;
|
||||
|
||||
export const useChatTimelineScroll = ({
|
||||
currentSessionId,
|
||||
currentSessionKey,
|
||||
sessionMessageCount,
|
||||
composerOverlayHeight,
|
||||
lastUserMessageId,
|
||||
onActiveTurnChange,
|
||||
}: UseChatTimelineScrollOptions): UseChatTimelineScrollResult => {
|
||||
const scrollRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const listRef = React.useRef<TimelineListHandle | null>(null);
|
||||
|
||||
const [scrollNode, setScrollNode] = React.useState<HTMLDivElement | null>(null);
|
||||
const [anchorMessageId, setAnchorMessageId] = React.useState<string | null>(null);
|
||||
const [showScrollButton, setShowScrollButton] = React.useState(false);
|
||||
// "Pinned" is the live edge, which history pagination uses to decide whether
|
||||
// it may load older pages without disturbing the read position.
|
||||
const [isPinned, setIsPinned] = React.useState(true);
|
||||
const [isFollowingProgrammatically, setIsFollowingProgrammatically] = React.useState(false);
|
||||
// True after a real gesture until an explicit opt back in; drives the
|
||||
// overlay scrollbar suppression instead of the anchor's mere existence.
|
||||
const [userOwnsScroll, setUserOwnsScroll] = React.useState(false);
|
||||
|
||||
const modeRef = React.useRef<TimelineScrollMode>('following-end');
|
||||
const isAtEndRef = React.useRef(true);
|
||||
// Incremented by every real user gesture. Automatic movement is only valid
|
||||
// while `liveFollowGenerationRef` still equals it.
|
||||
const userGenerationRef = React.useRef(0);
|
||||
const liveFollowGenerationRef = React.useRef<number | null>(0);
|
||||
// Anchor lifecycle: armed on send → pending until the row exists → positioned
|
||||
// while the animated scroll runs → settled once it has come to rest.
|
||||
const armedForNextUserMessageRef = React.useRef(false);
|
||||
const pendingAnchorRef = React.useRef<string | null>(null);
|
||||
const positionedAnchorRef = React.useRef<string | null>(null);
|
||||
const settledAnchorRef = React.useRef<string | null>(null);
|
||||
const activeAnchorIndexRef = React.useRef<number | null>(null);
|
||||
const pendingAnchorRestoreRef = React.useRef<{
|
||||
readonly messageId: string;
|
||||
readonly offset: number;
|
||||
readonly userGeneration: number;
|
||||
} | null>(null);
|
||||
const anchorRestoreFrameRef = React.useRef<number | null>(null);
|
||||
const showButtonTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const composerOverlayHeightRef = React.useRef(composerOverlayHeight);
|
||||
composerOverlayHeightRef.current = composerOverlayHeight;
|
||||
const sessionMessageCountRef = React.useRef(sessionMessageCount);
|
||||
sessionMessageCountRef.current = sessionMessageCount;
|
||||
const currentSessionIdRef = React.useRef(currentSessionId);
|
||||
currentSessionIdRef.current = currentSessionId;
|
||||
const currentSessionKeyRef = React.useRef(currentSessionKey);
|
||||
currentSessionKeyRef.current = currentSessionKey;
|
||||
|
||||
const updateViewportAnchor = useViewportStore((state) => state.updateViewportAnchor);
|
||||
|
||||
const cancelShowButtonTimer = React.useCallback(() => {
|
||||
if (showButtonTimerRef.current !== null) {
|
||||
clearTimeout(showButtonTimerRef.current);
|
||||
showButtonTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const hideScrollButton = React.useCallback(() => {
|
||||
cancelShowButtonTimer();
|
||||
setShowScrollButton(false);
|
||||
}, [cancelShowButtonTimer]);
|
||||
|
||||
const scheduleShowScrollButton = React.useCallback(() => {
|
||||
if (showButtonTimerRef.current !== null) return;
|
||||
showButtonTimerRef.current = setTimeout(() => {
|
||||
showButtonTimerRef.current = null;
|
||||
setShowScrollButton(true);
|
||||
}, SHOW_SCROLL_BUTTON_DELAY_MS);
|
||||
}, []);
|
||||
|
||||
const clearAnchor = React.useCallback(() => {
|
||||
armedForNextUserMessageRef.current = false;
|
||||
pendingAnchorRef.current = null;
|
||||
positionedAnchorRef.current = null;
|
||||
settledAnchorRef.current = null;
|
||||
activeAnchorIndexRef.current = null;
|
||||
pendingAnchorRestoreRef.current = null;
|
||||
if (anchorRestoreFrameRef.current !== null) {
|
||||
cancelAnimationFrame(anchorRestoreFrameRef.current);
|
||||
anchorRestoreFrameRef.current = null;
|
||||
}
|
||||
setAnchorMessageId(null);
|
||||
}, []);
|
||||
|
||||
// A real gesture: stop every automatic movement until the user opts back
|
||||
// in. The anchored END SPACE stays — collapsing it mid-gesture clamps the
|
||||
// viewport back to the end — only the anchor machinery is disarmed.
|
||||
const onManualNavigation = React.useCallback(() => {
|
||||
userGenerationRef.current += 1;
|
||||
modeRef.current = 'free-scrolling';
|
||||
liveFollowGenerationRef.current = null;
|
||||
setUserOwnsScroll(true);
|
||||
// The end may already have been left by our own movement, in which
|
||||
// case no further at-end transition will fire — and while an animated
|
||||
// follow glide trails the live edge, isAtEndRef is deliberately not
|
||||
// updated, so measure the real distance instead of trusting it. This
|
||||
// is an explicit gesture — show the pill immediately, no debounce.
|
||||
const listState = listRef.current?.getState();
|
||||
const atEndNow = (listState ? resolveTimelineIsAtEnd(listState) : undefined) ?? isAtEndRef.current;
|
||||
isAtEndRef.current = atEndNow;
|
||||
if (!atEndNow) {
|
||||
cancelShowButtonTimer();
|
||||
setShowScrollButton(true);
|
||||
}
|
||||
armedForNextUserMessageRef.current = false;
|
||||
pendingAnchorRef.current = null;
|
||||
positionedAnchorRef.current = null;
|
||||
settledAnchorRef.current = null;
|
||||
activeAnchorIndexRef.current = null;
|
||||
pendingAnchorRestoreRef.current = null;
|
||||
if (anchorRestoreFrameRef.current !== null) {
|
||||
cancelAnimationFrame(anchorRestoreFrameRef.current);
|
||||
anchorRestoreFrameRef.current = null;
|
||||
}
|
||||
}, [cancelShowButtonTimer]);
|
||||
|
||||
const isLiveFollowActive = React.useCallback(() => (
|
||||
liveFollowGenerationRef.current === userGenerationRef.current
|
||||
), []);
|
||||
|
||||
// ── snapshot persistence ────────────────────────────────────────────────
|
||||
const pendingSaveRef = React.useRef<{ sessionId: string; anchor: number } | null>(null);
|
||||
const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const flushSave = React.useCallback(() => {
|
||||
if (saveTimerRef.current !== null) {
|
||||
clearTimeout(saveTimerRef.current);
|
||||
saveTimerRef.current = null;
|
||||
}
|
||||
const pending = pendingSaveRef.current;
|
||||
if (!pending) return;
|
||||
const container = scrollRef.current;
|
||||
if (!container) {
|
||||
pendingSaveRef.current = null;
|
||||
return;
|
||||
}
|
||||
updateViewportAnchor(pending.sessionId, pending.anchor, {
|
||||
scrollTop: container.scrollTop,
|
||||
scrollHeight: container.scrollHeight,
|
||||
clientHeight: container.clientHeight,
|
||||
});
|
||||
pendingSaveRef.current = null;
|
||||
}, [updateViewportAnchor]);
|
||||
|
||||
const queueSave = React.useCallback(() => {
|
||||
const sessionId = currentSessionIdRef.current;
|
||||
if (!sessionId) return;
|
||||
const container = scrollRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const { scrollTop, scrollHeight, clientHeight } = container;
|
||||
const anchorRatio = scrollHeight > 0
|
||||
? (scrollTop + clientHeight / 2) / scrollHeight
|
||||
: 0;
|
||||
const anchor = Math.floor(anchorRatio * sessionMessageCountRef.current);
|
||||
|
||||
pendingSaveRef.current = { sessionId, anchor };
|
||||
if (saveTimerRef.current !== null) return;
|
||||
saveTimerRef.current = setTimeout(() => {
|
||||
saveTimerRef.current = null;
|
||||
flushSave();
|
||||
}, SAVE_DEBOUNCE_MS);
|
||||
}, [flushSave]);
|
||||
|
||||
const saveSnapshotNow = React.useCallback(() => {
|
||||
flushSave();
|
||||
}, [flushSave]);
|
||||
|
||||
// ── scroll commands ─────────────────────────────────────────────────────
|
||||
const goToBottomReassertTimersRef = React.useRef<Array<ReturnType<typeof setTimeout>>>([]);
|
||||
const clearGoToBottomReasserts = React.useCallback(() => {
|
||||
for (const timer of goToBottomReassertTimersRef.current) clearTimeout(timer);
|
||||
goToBottomReassertTimersRef.current = [];
|
||||
}, []);
|
||||
|
||||
const goToBottom = React.useCallback((mode: 'instant' | 'smooth' = 'instant') => {
|
||||
isAtEndRef.current = true;
|
||||
setIsPinned(true);
|
||||
setUserOwnsScroll(false);
|
||||
modeRef.current = 'following-end';
|
||||
// Returning to the end is an explicit opt back IN to live follow.
|
||||
liveFollowGenerationRef.current = userGenerationRef.current;
|
||||
clearAnchor();
|
||||
hideScrollButton();
|
||||
void listRef.current?.scrollToEnd({ animated: mode === 'smooth' });
|
||||
// While a stream is growing the content, a single jump lands on the
|
||||
// end as of that moment and the list's own follow may not have
|
||||
// re-armed yet — re-assert a few times until the edge holds, then the
|
||||
// library follows onward. A new user gesture invalidates the window.
|
||||
clearGoToBottomReasserts();
|
||||
const generation = userGenerationRef.current;
|
||||
for (const delay of [150, 400, 800]) {
|
||||
goToBottomReassertTimersRef.current.push(setTimeout(() => {
|
||||
if (userGenerationRef.current !== generation) return;
|
||||
if (modeRef.current !== 'following-end') return;
|
||||
const state = listRef.current?.getState();
|
||||
if (state && resolveTimelineIsAtEnd(state) === true) return;
|
||||
void listRef.current?.scrollToEnd({ animated: false });
|
||||
}, delay));
|
||||
}
|
||||
}, [clearAnchor, clearGoToBottomReasserts, hideScrollButton]);
|
||||
|
||||
// Sending arms the anchor. The message id is not known here (the optimistic
|
||||
// row is created by the store), so the next new user message id claims it.
|
||||
// Whether the send-time anchor positioning may animate. Sending from the
|
||||
// live edge parks the new message with a short smooth scroll; sending
|
||||
// from mid-history teleports — a long smooth scroll through the
|
||||
// virtualized timeline gets cancelled by rows mounting and measuring
|
||||
// along the way and dies partway there.
|
||||
const anchorPositionInstantRef = React.useRef(false);
|
||||
|
||||
const scrollToBottomOnSend = React.useCallback(() => {
|
||||
anchorPositionInstantRef.current = !isAtEndRef.current;
|
||||
isAtEndRef.current = true;
|
||||
setUserOwnsScroll(false);
|
||||
modeRef.current = 'anchoring-new-turn';
|
||||
liveFollowGenerationRef.current = userGenerationRef.current;
|
||||
armedForNextUserMessageRef.current = true;
|
||||
// The optimistic row is not committed yet; the next NEW user message id
|
||||
// relative to this baseline claims the anchor, independent of whether
|
||||
// the commit lands before or after this call.
|
||||
armBaselineUserMessageIdRef.current = lastArmedUserMessageIdRef.current;
|
||||
pendingAnchorRef.current = null;
|
||||
positionedAnchorRef.current = null;
|
||||
settledAnchorRef.current = null;
|
||||
activeAnchorIndexRef.current = null;
|
||||
hideScrollButton();
|
||||
}, [hideScrollButton]);
|
||||
|
||||
// Claim the anchor as soon as the sent row exists in the timeline. The
|
||||
// comparison is against the baseline captured when the send armed the
|
||||
// anchor, so the claim works whether the optimistic row committed before
|
||||
// or after the arming call.
|
||||
const lastArmedUserMessageIdRef = React.useRef<string | null>(lastUserMessageId);
|
||||
const armBaselineUserMessageIdRef = React.useRef<string | null>(lastUserMessageId);
|
||||
React.useEffect(() => {
|
||||
lastArmedUserMessageIdRef.current = lastUserMessageId;
|
||||
if (!armedForNextUserMessageRef.current) return;
|
||||
if (!lastUserMessageId || lastUserMessageId === armBaselineUserMessageIdRef.current) return;
|
||||
armedForNextUserMessageRef.current = false;
|
||||
pendingAnchorRef.current = lastUserMessageId;
|
||||
setAnchorMessageId(lastUserMessageId);
|
||||
}, [lastUserMessageId]);
|
||||
|
||||
const restoreSnapshot = React.useCallback(async (): Promise<boolean> => {
|
||||
const sessionKey = currentSessionKeyRef.current;
|
||||
if (!sessionKey) return false;
|
||||
|
||||
// Entering a session always returns to the live edge. Late async growth
|
||||
// is handled by the list staying at the end, not by a timed hold.
|
||||
isAtEndRef.current = true;
|
||||
setUserOwnsScroll(false);
|
||||
modeRef.current = 'following-end';
|
||||
liveFollowGenerationRef.current = userGenerationRef.current;
|
||||
clearAnchor();
|
||||
hideScrollButton();
|
||||
void listRef.current?.scrollToEnd({ animated: false });
|
||||
return false;
|
||||
}, [clearAnchor, hideScrollButton]);
|
||||
|
||||
// ── list callbacks ──────────────────────────────────────────────────────
|
||||
const registerList = React.useCallback((list: TimelineListHandle | null) => {
|
||||
listRef.current = list;
|
||||
const node = (list?.getScrollableNode() as HTMLDivElement | null) ?? null;
|
||||
scrollRef.current = node;
|
||||
setScrollNode(node);
|
||||
}, []);
|
||||
|
||||
const onIsAtEndChange = React.useCallback((isAtEnd: boolean) => {
|
||||
// While an automatic movement owns the viewport, leaving the end is our
|
||||
// own doing (the anchored turn parks mid-timeline, the glide trails its
|
||||
// target between corrections) — not a reason to offer the pill. Only a
|
||||
// real gesture (free-scrolling) shows it.
|
||||
if (!isAtEnd && isLiveFollowActive()) {
|
||||
hideScrollButton();
|
||||
return;
|
||||
}
|
||||
if (isAtEndRef.current === isAtEnd) return;
|
||||
isAtEndRef.current = isAtEnd;
|
||||
setIsPinned(isAtEnd);
|
||||
if (isAtEnd) {
|
||||
if (modeRef.current !== 'anchoring-new-turn') {
|
||||
modeRef.current = 'following-end';
|
||||
}
|
||||
liveFollowGenerationRef.current = userGenerationRef.current;
|
||||
setUserOwnsScroll(false);
|
||||
hideScrollButton();
|
||||
} else {
|
||||
modeRef.current = 'free-scrolling';
|
||||
liveFollowGenerationRef.current = null;
|
||||
scheduleShowScrollButton();
|
||||
}
|
||||
queueSave();
|
||||
}, [hideScrollButton, isLiveFollowActive, queueSave, scheduleShowScrollButton]);
|
||||
|
||||
// Park the anchored row near the top once the list has measured it.
|
||||
const onAnchorReady = React.useCallback((messageId: string, anchorIndex: number) => {
|
||||
// The anchored end space can be remeasured long after the send (turn
|
||||
// completion, images decoding). Only the send-time anchoring mode may
|
||||
// position the viewport.
|
||||
if (modeRef.current !== 'anchoring-new-turn') return;
|
||||
if (pendingAnchorRef.current === messageId) {
|
||||
pendingAnchorRef.current = null;
|
||||
}
|
||||
activeAnchorIndexRef.current = anchorIndex;
|
||||
if (positionedAnchorRef.current === messageId) return;
|
||||
positionedAnchorRef.current = messageId;
|
||||
settledAnchorRef.current = null;
|
||||
|
||||
const positionAnchor = (remainingAttempts: number) => {
|
||||
requestAnimationFrame(() => {
|
||||
if (positionedAnchorRef.current !== messageId) return;
|
||||
const list = listRef.current;
|
||||
if (!list) {
|
||||
if (remainingAttempts > 0) positionAnchor(remainingAttempts - 1);
|
||||
return;
|
||||
}
|
||||
const scrollNode = list.getScrollableNode();
|
||||
if (!scrollNode) {
|
||||
if (remainingAttempts > 0) positionAnchor(remainingAttempts - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
let finished = false;
|
||||
const finishPositioning = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(fallbackTimer);
|
||||
scrollNode.removeEventListener('scrollend', finishPositioning);
|
||||
if (positionedAnchorRef.current !== messageId) return;
|
||||
// Re-assert the resting offset without animation so the
|
||||
// smooth scroll's own momentum cannot drift past it.
|
||||
const scrollOffset = list.getState().scroll;
|
||||
void list.scrollToOffset({ offset: scrollOffset, animated: false });
|
||||
settledAnchorRef.current = messageId;
|
||||
};
|
||||
const fallbackTimer = setTimeout(finishPositioning, ANCHOR_SETTLE_FALLBACK_MS);
|
||||
scrollNode.addEventListener('scrollend', finishPositioning, { once: true });
|
||||
|
||||
void list.scrollToIndex({
|
||||
index: anchorIndex,
|
||||
animated: !anchorPositionInstantRef.current,
|
||||
viewPosition: 0,
|
||||
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
requestAnimationFrame(() => positionAnchor(ANCHOR_POSITION_ATTEMPTS));
|
||||
}, []);
|
||||
|
||||
// The anchored row can still change height after it settles (an image
|
||||
// decoding, a code block highlighting). Hold the resting offset, but only
|
||||
// against sub-pixel drift and only while the user has not taken over.
|
||||
const onAnchorSizeChanged = React.useCallback((messageId: string) => {
|
||||
if (settledAnchorRef.current !== messageId) return;
|
||||
if (!isLiveFollowActive()) return;
|
||||
const scrollOffset = listRef.current?.getState().scroll;
|
||||
if (scrollOffset === undefined) return;
|
||||
|
||||
if (pendingAnchorRestoreRef.current === null) {
|
||||
pendingAnchorRestoreRef.current = {
|
||||
messageId,
|
||||
offset: scrollOffset,
|
||||
userGeneration: userGenerationRef.current,
|
||||
};
|
||||
}
|
||||
if (anchorRestoreFrameRef.current !== null) return;
|
||||
|
||||
anchorRestoreFrameRef.current = requestAnimationFrame(() => {
|
||||
anchorRestoreFrameRef.current = null;
|
||||
const pending = pendingAnchorRestoreRef.current;
|
||||
pendingAnchorRestoreRef.current = null;
|
||||
if (
|
||||
!pending
|
||||
|| settledAnchorRef.current !== pending.messageId
|
||||
|| pending.userGeneration !== userGenerationRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const list = listRef.current;
|
||||
const currentOffset = list?.getState().scroll;
|
||||
if (
|
||||
typeof currentOffset === 'number'
|
||||
&& Math.abs(currentOffset - pending.offset) <= ANCHOR_RESTORE_TOLERANCE_PX
|
||||
) {
|
||||
void list?.scrollToOffset({ offset: pending.offset, animated: false });
|
||||
}
|
||||
});
|
||||
}, [isLiveFollowActive]);
|
||||
|
||||
// Whether the real rows (ignoring any reserved anchored end space) are tall
|
||||
// enough to scroll. Without this, entering a short session would scroll into
|
||||
// the reserved space and strand the content above the viewport.
|
||||
const realContentOverflowsViewport = React.useCallback((list: TimelineListHandle): boolean => {
|
||||
const state = list.getState();
|
||||
if (state.data.length === 0) return false;
|
||||
|
||||
const lastIndex = state.data.length - 1;
|
||||
const lastTop = state.positionAtIndex(lastIndex);
|
||||
const lastHeight = state.sizeAtIndex(lastIndex);
|
||||
if (
|
||||
typeof lastTop !== 'number'
|
||||
|| typeof lastHeight !== 'number'
|
||||
|| !Number.isFinite(lastTop)
|
||||
|| !Number.isFinite(lastHeight)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const realContentBottom = lastTop + Math.max(1, lastHeight);
|
||||
const visibleScrollLength = Math.max(
|
||||
0,
|
||||
state.scrollLength - composerOverlayHeightRef.current - CHAT_LIST_ANCHOR_OFFSET,
|
||||
);
|
||||
return realContentBottom > visibleScrollLength;
|
||||
}, []);
|
||||
|
||||
// One deterministic correction per data change, two frames out so the list
|
||||
// has measured the new rows. Nothing runs while the user owns the scroll.
|
||||
const dataChangeFramesRef = React.useRef<{ first: number | null; second: number | null }>({
|
||||
first: null,
|
||||
second: null,
|
||||
});
|
||||
// User preference: with auto-follow off, streaming growth never moves the
|
||||
// viewport — the anchored user message still parks at the top on send, but
|
||||
// no glide or end-follow correction runs afterwards.
|
||||
const streamingAutoFollowEnabled = useUIStore((state) => state.streamingAutoFollowEnabled);
|
||||
const streamingAutoFollowEnabledRef = React.useRef(streamingAutoFollowEnabled);
|
||||
streamingAutoFollowEnabledRef.current = streamingAutoFollowEnabled;
|
||||
|
||||
// While the list width is resizing, every pinning write fights the
|
||||
// per-frame row re-measure and the pinned viewport shakes. Corrections
|
||||
// stand down for the whole resize and the visible content is held by the
|
||||
// list's size compensation instead. Deliberately NO snap back to the end
|
||||
// afterwards: a slow drag settles repeatedly, and each snap reads as the
|
||||
// very jump this suspension removes — geometry changed, staying where the
|
||||
// reader is beats re-asserting the edge.
|
||||
const widthResizingRef = React.useRef(false);
|
||||
React.useEffect(() => {
|
||||
if (!scrollNode || typeof ResizeObserver === 'undefined') return;
|
||||
let lastWidth: number | null = null;
|
||||
let quietTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const observer = new ResizeObserver((observerEntries) => {
|
||||
const width = observerEntries[observerEntries.length - 1]?.contentRect.width;
|
||||
if (typeof width !== 'number') return;
|
||||
if (lastWidth === null) {
|
||||
lastWidth = width;
|
||||
return;
|
||||
}
|
||||
if (Math.abs(width - lastWidth) < 1) return;
|
||||
lastWidth = width;
|
||||
widthResizingRef.current = true;
|
||||
if (quietTimer !== null) clearTimeout(quietTimer);
|
||||
quietTimer = setTimeout(() => {
|
||||
quietTimer = null;
|
||||
widthResizingRef.current = false;
|
||||
}, 350);
|
||||
});
|
||||
observer.observe(scrollNode);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
if (quietTimer !== null) clearTimeout(quietTimer);
|
||||
};
|
||||
}, [scrollNode]);
|
||||
|
||||
const onTimelineDataChange = React.useCallback(() => {
|
||||
if (widthResizingRef.current) return;
|
||||
if (!streamingAutoFollowEnabledRef.current) return;
|
||||
if (!isLiveFollowActive()) return;
|
||||
|
||||
// Since @legendapp/list 3.3.x, maintainScrollAtEnd follows content
|
||||
// growth on its own — including a tail row growing in place — and
|
||||
// releases when the user scrolls away. Following the end therefore
|
||||
// needs no correction here; this handler only serves the
|
||||
// anchored-turn glide below.
|
||||
if (modeRef.current === 'following-end') return;
|
||||
|
||||
const frames = dataChangeFramesRef.current;
|
||||
if (frames.first !== null) cancelAnimationFrame(frames.first);
|
||||
if (frames.second !== null) cancelAnimationFrame(frames.second);
|
||||
|
||||
frames.first = requestAnimationFrame(() => {
|
||||
frames.first = null;
|
||||
frames.second = requestAnimationFrame(() => {
|
||||
frames.second = null;
|
||||
if (!isLiveFollowActive()) return;
|
||||
// An anchor that exists but has not come to rest yet owns the
|
||||
// viewport; correcting now would fight its animation.
|
||||
if (pendingAnchorRef.current !== null) return;
|
||||
if (
|
||||
positionedAnchorRef.current !== null
|
||||
&& settledAnchorRef.current !== positionedAnchorRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = listRef.current;
|
||||
if (!list) return;
|
||||
|
||||
if (modeRef.current === 'anchoring-new-turn') {
|
||||
const anchorIndex = activeAnchorIndexRef.current;
|
||||
if (anchorIndex === null) return;
|
||||
const metrics = getAnchoredTurnMetrics({
|
||||
state: list.getState(),
|
||||
anchorIndex,
|
||||
composerOverlayHeight: composerOverlayHeightRef.current,
|
||||
anchorOffset: CHAT_LIST_ANCHOR_OFFSET,
|
||||
});
|
||||
// The turn still fits: leave the viewport exactly where the
|
||||
// user is reading.
|
||||
if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) return;
|
||||
// Animated: successive corrections restart the smooth scroll
|
||||
// from the current position, so streaming reads as one
|
||||
// continuous glide instead of a per-line hop. A real user
|
||||
// gesture interrupts the native smooth scroll on its own.
|
||||
void list.scrollToOffset({
|
||||
offset: list.getState().scroll + metrics.scrollDeltaToRevealEnd,
|
||||
animated: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
}, [isLiveFollowActive]);
|
||||
|
||||
// The streaming tail grows inside one row without changing the entries
|
||||
// array, so data-change callbacks are silent for the entire stream. The
|
||||
// list's total content size is the authoritative growth signal; every
|
||||
// change re-runs the same guarded correction.
|
||||
const onTimelineDataChangeRef = React.useRef(onTimelineDataChange);
|
||||
onTimelineDataChangeRef.current = onTimelineDataChange;
|
||||
React.useEffect(() => {
|
||||
if (!scrollNode) return;
|
||||
const listen = listRef.current?.getState().listen;
|
||||
if (!listen) return;
|
||||
const unsubscribe = listen('totalSize', () => {
|
||||
onTimelineDataChangeRef.current();
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [scrollNode]);
|
||||
|
||||
// ── gesture opt-out ─────────────────────────────────────────────────────
|
||||
const onManualNavigationRef = React.useRef(onManualNavigation);
|
||||
onManualNavigationRef.current = onManualNavigation;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!scrollNode) return;
|
||||
|
||||
// A gesture is meaningful when the viewport can move up AT ALL:
|
||||
// either the real rows overflow the viewport, or there is scrolled
|
||||
// history above (an anchored turn parks mid-conversation with
|
||||
// reserved space below — the real rows may not overflow yet, but
|
||||
// wheel-up is still a genuine opt-out; swallowing it left live-follow
|
||||
// armed, which suppressed the pill and kept corrections armed under a
|
||||
// viewport the user had taken).
|
||||
const canScrollUp = () => {
|
||||
const list = listRef.current;
|
||||
if (!list) return false;
|
||||
if (list.getState().scroll > 1) return true;
|
||||
return realContentOverflowsViewport(list);
|
||||
};
|
||||
const gesture = () => {
|
||||
onManualNavigationRef.current();
|
||||
};
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
// Scrolling toward the end is not opting out of follow.
|
||||
if (event.deltaY < 0 && canScrollUp()) gesture();
|
||||
};
|
||||
// Touch mirrors wheel by finger direction, not by having already left
|
||||
// the end: while a stream keeps re-pinning the viewport, waiting for
|
||||
// an at-end transition means the drag never registers — the user
|
||||
// cannot scroll, the pill never appears, and live-follow stays armed
|
||||
// under a viewport they are fighting for.
|
||||
let touchLastY: number | null = null;
|
||||
const handleTouchStart = (event: TouchEvent) => {
|
||||
touchLastY = event.touches[0]?.clientY ?? null;
|
||||
};
|
||||
const handleTouchMove = (event: TouchEvent) => {
|
||||
const y = event.touches[0]?.clientY ?? null;
|
||||
const lastY = touchLastY;
|
||||
touchLastY = y;
|
||||
if (y === null) return;
|
||||
// A downward finger drags the content up — the touch wheel-up.
|
||||
const draggedUp = lastY !== null && y > lastY;
|
||||
if ((draggedUp || !isAtEndRef.current) && canScrollUp()) gesture();
|
||||
};
|
||||
const handleTouchEnd = () => {
|
||||
touchLastY = null;
|
||||
};
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
// The scrollbar track is the scroll node itself; a tap on a row
|
||||
// only breaks follow when the viewport already left the end.
|
||||
if ((event.target === scrollNode || !isAtEndRef.current) && canScrollUp()) gesture();
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.key === 'PageUp' || event.key === 'Home' || event.key === 'ArrowUp') && canScrollUp()) {
|
||||
gesture();
|
||||
}
|
||||
};
|
||||
const handleScroll = () => {
|
||||
queueSave();
|
||||
};
|
||||
|
||||
scrollNode.addEventListener('wheel', handleWheel, { passive: true });
|
||||
scrollNode.addEventListener('touchstart', handleTouchStart, { passive: true });
|
||||
scrollNode.addEventListener('touchmove', handleTouchMove, { passive: true });
|
||||
scrollNode.addEventListener('touchend', handleTouchEnd, { passive: true });
|
||||
scrollNode.addEventListener('touchcancel', handleTouchEnd, { passive: true });
|
||||
scrollNode.addEventListener('pointerdown', handlePointerDown, { passive: true });
|
||||
scrollNode.addEventListener('keydown', handleKeyDown);
|
||||
scrollNode.addEventListener('scroll', handleScroll, { passive: true });
|
||||
|
||||
return () => {
|
||||
scrollNode.removeEventListener('wheel', handleWheel);
|
||||
scrollNode.removeEventListener('touchstart', handleTouchStart);
|
||||
scrollNode.removeEventListener('touchmove', handleTouchMove);
|
||||
scrollNode.removeEventListener('touchend', handleTouchEnd);
|
||||
scrollNode.removeEventListener('touchcancel', handleTouchEnd);
|
||||
scrollNode.removeEventListener('pointerdown', handlePointerDown);
|
||||
scrollNode.removeEventListener('keydown', handleKeyDown);
|
||||
scrollNode.removeEventListener('scroll', handleScroll);
|
||||
};
|
||||
}, [queueSave, realContentOverflowsViewport, scrollNode]);
|
||||
|
||||
// ── session lifecycle ───────────────────────────────────────────────────
|
||||
const lastSessionKeyRef = React.useRef<string | null>(null);
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId || !currentSessionKey || currentSessionKey === lastSessionKeyRef.current) {
|
||||
return;
|
||||
}
|
||||
lastSessionKeyRef.current = currentSessionKey;
|
||||
MessageFreshnessDetector.getInstance().recordSessionStart(currentSessionId);
|
||||
// Persist the outgoing session's position before the new one takes over.
|
||||
flushSave();
|
||||
isAtEndRef.current = true;
|
||||
setUserOwnsScroll(false);
|
||||
modeRef.current = 'following-end';
|
||||
liveFollowGenerationRef.current = userGenerationRef.current;
|
||||
clearAnchor();
|
||||
hideScrollButton();
|
||||
}, [clearAnchor, currentSessionId, currentSessionKey, flushSave, hideScrollButton]);
|
||||
|
||||
// Suppress the overlay scrollbar thumb while automatic movement owns the
|
||||
// scroll position, so it does not jump on each correction.
|
||||
React.useEffect(() => {
|
||||
setIsFollowingProgrammatically(!showScrollButton && !userOwnsScroll);
|
||||
}, [showScrollButton, userOwnsScroll]);
|
||||
|
||||
React.useEffect(() => () => {
|
||||
cancelShowButtonTimer();
|
||||
if (saveTimerRef.current !== null) clearTimeout(saveTimerRef.current);
|
||||
if (anchorRestoreFrameRef.current !== null) cancelAnimationFrame(anchorRestoreFrameRef.current);
|
||||
const frames = dataChangeFramesRef.current;
|
||||
if (frames.first !== null) cancelAnimationFrame(frames.first);
|
||||
if (frames.second !== null) cancelAnimationFrame(frames.second);
|
||||
}, [cancelShowButtonTimer]);
|
||||
|
||||
// ── active-turn spy ─────────────────────────────────────────────────────
|
||||
// Reads turn positions straight from the DOM, so it is unaffected by which
|
||||
// list implementation owns the container. Rows mounting and unmounting
|
||||
// during virtualized scrolling are tracked through the mutation observer.
|
||||
React.useEffect(() => {
|
||||
if (!onActiveTurnChange) return;
|
||||
const container = scrollNode;
|
||||
if (!container) return;
|
||||
|
||||
let lastActiveTurnId: string | null = null;
|
||||
const spy = createScrollSpy({
|
||||
onActive: (turnId) => {
|
||||
if (turnId === lastActiveTurnId) return;
|
||||
lastActiveTurnId = turnId;
|
||||
onActiveTurnChange(turnId);
|
||||
},
|
||||
});
|
||||
spy.setContainer(container);
|
||||
|
||||
const elementByTurnId = new Map<string, HTMLElement>();
|
||||
const registerTurnNode = (node: HTMLElement) => {
|
||||
const turnId = node.dataset.turnId;
|
||||
if (!turnId) return false;
|
||||
elementByTurnId.set(turnId, node);
|
||||
spy.register(node, turnId);
|
||||
return true;
|
||||
};
|
||||
const unregisterTurnNode = (node: HTMLElement) => {
|
||||
const turnId = node.dataset.turnId;
|
||||
if (!turnId) return false;
|
||||
if (elementByTurnId.get(turnId) !== node) return false;
|
||||
elementByTurnId.delete(turnId);
|
||||
spy.unregister(turnId);
|
||||
return true;
|
||||
};
|
||||
const collectTurnNodes = (node: Node): HTMLElement[] => {
|
||||
if (!(node instanceof HTMLElement)) return [];
|
||||
const collected: HTMLElement[] = [];
|
||||
if (node.matches('[data-turn-id]')) collected.push(node);
|
||||
node.querySelectorAll<HTMLElement>('[data-turn-id]').forEach((el) => collected.push(el));
|
||||
return collected;
|
||||
};
|
||||
|
||||
container.querySelectorAll<HTMLElement>('[data-turn-id]').forEach(registerTurnNode);
|
||||
spy.markDirty();
|
||||
|
||||
const mutationObserver = new MutationObserver((records) => {
|
||||
let changed = false;
|
||||
records.forEach((record) => {
|
||||
record.removedNodes.forEach((node) => {
|
||||
collectTurnNodes(node).forEach((turnNode) => {
|
||||
if (unregisterTurnNode(turnNode)) changed = true;
|
||||
});
|
||||
});
|
||||
record.addedNodes.forEach((node) => {
|
||||
collectTurnNodes(node).forEach((turnNode) => {
|
||||
if (registerTurnNode(turnNode)) changed = true;
|
||||
});
|
||||
});
|
||||
});
|
||||
if (changed) spy.markDirty();
|
||||
});
|
||||
mutationObserver.observe(container, { subtree: true, childList: true });
|
||||
|
||||
const onScroll = () => spy.onScroll();
|
||||
container.addEventListener('scroll', onScroll, { passive: true });
|
||||
|
||||
return () => {
|
||||
container.removeEventListener('scroll', onScroll);
|
||||
mutationObserver.disconnect();
|
||||
spy.destroy();
|
||||
};
|
||||
}, [onActiveTurnChange, scrollNode]);
|
||||
|
||||
return {
|
||||
scrollRef,
|
||||
scrollNode,
|
||||
isPinned,
|
||||
registerList,
|
||||
anchorMessageId,
|
||||
onAnchorReady,
|
||||
onAnchorSizeChanged,
|
||||
onIsAtEndChange,
|
||||
onManualNavigation,
|
||||
onTimelineDataChange,
|
||||
showScrollButton,
|
||||
userOwnsScroll,
|
||||
isFollowingProgrammatically,
|
||||
goToBottom,
|
||||
scrollToBottomOnSend,
|
||||
saveSnapshotNow,
|
||||
restoreSnapshot,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user