Files
Jyotisha/frontend/src/hooks/use-conversation-scroll-anchor.ts
T
Jesse_ChenandClaude Opus 5.5 da2613ffd9 fix(chat): attach scroll anchor when the scroller appears; only reader scroll releases a pin (BUG-1043, BUG-1044)
- The anchor listener and follow observer now attach whenever the scroller
  element itself appears (checked after every commit, no-op unless element,
  active or resetKey changed). The home page mounts `.conversation` after its
  loading screen with unchanged active/resetKey, so a directly opened session
  never got a listener, never landed on its newest content, showed the jump
  chip under short replies and did not follow after pressing it.
- After a pin, geometry no longer releases the hold: only a wheel, touch drag,
  scroll key or scrollbar press followed by a scroll within 1s does. The
  rectification pin rests 94px from the bottom, inside the 96px threshold,
  which dragged long replies to their last line.
- Real React lifecycle tests (loading screen -> reveal, 94px rest), DESIGN,
  BUG history, PROGRESS, CHANGELOG, device checklist and CDP screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017eEAG8HD3mm8gsKXgk8uU8
2026-09-26 10:42:12 +08:00

369 lines
15 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import type { RefObject } from "react";
export const conversationAnchorThreshold = 96;
export const conversationPinSpaceToken = "--space-4";
const pinSpaceFallbackPx = 16;
type AnchorState = {
readonly key: string;
readonly anchored: boolean;
};
type ConversationScrollAnchor = {
readonly anchored: boolean;
readonly latestBelowFold: boolean;
readonly anchorToLatest: () => void;
readonly pinLatestTurn: (target?: HTMLElement) => void;
};
export function conversationDistanceFromBottom(container: HTMLElement) {
return container.scrollHeight - container.scrollTop - container.clientHeight;
}
export function nextAnchorState(anchored: boolean, distanceFromBottom: number, scrolledUp: boolean) {
if (distanceFromBottom <= conversationAnchorThreshold) return true;
return scrolledUp ? false : anchored;
}
export function readPinSpacePx(element: HTMLElement): number {
if (typeof getComputedStyle !== "function") return pinSpaceFallbackPx;
const raw = getComputedStyle(element).getPropertyValue(conversationPinSpaceToken).trim();
const parsed = Number.parseFloat(raw);
return Number.isFinite(parsed) ? parsed : pinSpaceFallbackPx;
}
const DOCUMENT_POSITION_FOLLOWING = 4;
export function isNodeAfter(earlier: Node, later: Node): boolean {
if (typeof earlier.compareDocumentPosition !== "function") return false;
return (earlier.compareDocumentPosition(later) & DOCUMENT_POSITION_FOLLOWING) !== 0;
}
/**
* Turn head is the latest user row, unless an assistant sits after it with
* another assistant in between (choice / opening / auto-continue: this turn
* has no user row) or there is no user row at all.
*/
export function resolveTurnHead(container: ParentNode, target?: HTMLElement | null): HTMLElement | null {
if (target) return target;
const users = Array.from(container.querySelectorAll(".message-user")) as HTMLElement[];
const assistants = Array.from(container.querySelectorAll(".message-assistant")) as HTMLElement[];
const lastUser = users.at(-1) ?? null;
const lastAssistant = assistants.at(-1) ?? null;
if (!lastUser) return lastAssistant;
if (!lastAssistant) return lastUser;
if (!isNodeAfter(lastUser, lastAssistant)) return lastUser;
const between = assistants.some((row) => isNodeAfter(lastUser, row) && isNodeAfter(row, lastAssistant));
return between ? lastAssistant : lastUser;
}
export function offsetWithinScroller(scroller: HTMLElement, node: HTMLElement): number {
return node.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
}
export function pinTurnScrollTop(scroller: HTMLElement, row: HTMLElement, spacePx: number): number {
return Math.max(0, offsetWithinScroller(scroller, row) - spacePx);
}
export function applyFollowBottom(
element: { scrollTop: number; scrollHeight: number },
anchored: boolean,
): void {
if (!anchored) return;
element.scrollTop = element.scrollHeight;
}
export function lastTurnTail(container: HTMLElement): HTMLElement | null {
return (container.querySelector(".message-list > :last-child .message-assistant")
?? container.querySelector(".message-assistant:last-of-type")
?? container.querySelector(".message-user:last-of-type")) as HTMLElement | null;
}
export function turnHeadHeightForSpacer(head: HTMLElement | null, tail: HTMLElement | null): number {
if (!head) return 0;
// The last turn's entry, which starts at this assistant row, carries the
// min-height spacer (BUG-1042). Subtracting the row's own height would leave
// that entry one row short of the viewport; before BUG-1042 the row itself
// carried the spacer and measuring it fed the spacer back into itself
// (BUG-931). Either way the head-is-tail case subtracts nothing.
if (tail && head === tail) return 0;
return head.offsetHeight;
}
export function applyTurnSpacer(container: HTMLElement, head: HTMLElement | null): void {
container.style.setProperty("--conversation-viewport", `${container.clientHeight}px`);
container.style.setProperty(
"--latest-turn-head-height",
`${turnHeadHeightForSpacer(head, lastTurnTail(container))}px`,
);
}
export function clearTurnSpacer(container: HTMLElement): void {
container.style.removeProperty("--conversation-viewport");
container.style.removeProperty("--latest-turn-head-height");
}
export function turnTailOverflow(container: HTMLElement): number {
const last = lastTurnTail(container);
if (!last) return conversationDistanceFromBottom(container);
return last.offsetTop + last.offsetHeight - (container.scrollTop + container.clientHeight);
}
export function latestContentBelowFold(overflow: number): boolean {
return overflow > conversationAnchorThreshold;
}
/** How long after a wheel / touch drag / scroll key / scrollbar press a scroll still counts as the reader's own. */
export const conversationGestureWindowMs = 1_000;
const scrollKeys = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "]);
export function isScrollKeyGesture(event: Pick<KeyboardEvent, "key" | "target" | "altKey" | "ctrlKey" | "metaKey">): boolean {
if (!scrollKeys.has(event.key) || event.altKey || event.ctrlKey || event.metaKey) return false;
const target = event.target as { closest?: (selector: string) => unknown } | null;
if (typeof target?.closest !== "function") return true;
if (target.closest("input, textarea, select, [contenteditable]:not([contenteditable='false'])")) return false;
// Space on a button or link activates it instead of scrolling.
return !(event.key === " " && target.closest("button, a[href], summary, [role='button']"));
}
type Attachment = {
readonly element: HTMLElement;
readonly resetKey: string;
readonly detach: () => void;
};
/**
* Owns both halves of "follow the conversation": whether the reader is
* anchored to the bottom (a scroll listener), and landing the viewport on the
* newest content while they are (a resize observer over the scroller's
* children, one frame per change). Both chat surfaces use this one hook.
*
* A new turn pins its head (the user row, or the new assistant when this turn
* has no user row) at the top and does not follow streamed growth. Only the
* reader's own scrolling releases that pin (BUG-1044). Switching conversations
* still lands on the newest content once.
*/
export function useConversationScrollAnchor(
container: RefObject<HTMLElement | null>,
active: boolean,
resetKey: string,
): ConversationScrollAnchor {
const [anchor, setAnchor] = useState<AnchorState>({ key: resetKey, anchored: false });
const [latestBelowFold, setLatestBelowFold] = useState(false);
const lastScrollTop = useRef(0);
const anchoredRef = useRef(false);
const shouldLand = useRef(true);
const holdUnpin = useRef(false);
const pinnedHeadRef = useRef<HTMLElement | null>(null);
const lastGestureAt = useRef(Number.NEGATIVE_INFINITY);
const attachment = useRef<Attachment | null>(null);
const anchored = anchor.key === resetKey ? anchor.anchored : true;
useEffect(() => {
anchoredRef.current = anchored;
}, [anchored]);
useEffect(() => {
shouldLand.current = true;
holdUnpin.current = false;
pinnedHeadRef.current = null;
}, [resetKey]);
// Follow: while anchored, any change in the scroller's content height lands the
// viewport on the bottom, at most once per frame. Switching conversations
// (resetKey) lands there immediately. Unanchored turns only refresh the spacer.
//
// The anchor listener and this observer attach to the scroller element itself,
// whenever it appears. The home page mounts `.conversation` only after its
// loading screen, while `active` and `resetKey` stay the same, so an effect
// keyed on those alone ran once against a null ref and never again (BUG-1043).
// This effect therefore checks after every commit and is a no-op unless the
// element, `active` or `resetKey` changed.
useEffect(() => {
const element = container.current;
const current = attachment.current;
if (current && active && current.element === element && current.resetKey === resetKey) return;
current?.detach();
attachment.current = null;
if (!active || !element) return;
// Anchored or not: a scroll listener, plus the reader-gesture marks that alone may release a pin.
const watchAnchor = () => {
lastScrollTop.current = element.scrollTop;
let frame = 0;
const measure = () => {
frame = 0;
const overflow = turnTailOverflow(element);
const distance = conversationDistanceFromBottom(element);
const scrolledUp = element.scrollTop < lastScrollTop.current;
lastScrollTop.current = element.scrollTop;
setLatestBelowFold(latestContentBelowFold(overflow));
if (holdUnpin.current) {
// A pinned turn rests wherever the pin and the spacer put it, which on
// the rectification surface is 94px from the bottom, inside the
// threshold. Geometry alone therefore never releases the pin; only a
// scroll the reader made does, up or down (BUG-1044).
const readerScrolled = performance.now() - lastGestureAt.current <= conversationGestureWindowMs;
if (!readerScrolled) return;
holdUnpin.current = false;
}
setAnchor((state) => {
const currentAnchored = state.key === resetKey ? state.anchored : true;
const next = nextAnchorState(currentAnchored, distance, scrolledUp);
return next === currentAnchored && state.key === resetKey ? state : { key: resetKey, anchored: next };
});
};
const onScroll = () => {
if (frame) return;
frame = window.requestAnimationFrame(measure);
};
const markGesture = () => {
lastGestureAt.current = performance.now();
};
// Pointer presses count only on the scroller itself (its scrollbar), not on
// a button or text inside a message.
const onPointerDown = (event: Event) => {
if (event.target === element) markGesture();
};
const onKeyDown = (event: KeyboardEvent) => {
if (isScrollKeyGesture(event)) markGesture();
};
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", markGesture, { passive: true });
element.addEventListener("touchmove", markGesture, { passive: true });
element.addEventListener("pointerdown", onPointerDown, { passive: true });
window.addEventListener("keydown", onKeyDown);
frame = window.requestAnimationFrame(measure);
return () => {
if (frame) window.cancelAnimationFrame(frame);
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", markGesture);
element.removeEventListener("touchmove", markGesture);
element.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("keydown", onKeyDown);
};
};
const followContent = () => {
let frame = 0;
const follow = () => {
frame = 0;
if (shouldLand.current) {
element.scrollTop = element.scrollHeight;
shouldLand.current = false;
holdUnpin.current = false;
pinnedHeadRef.current = null;
clearTurnSpacer(element);
const atBottom = conversationDistanceFromBottom(element) <= conversationAnchorThreshold;
anchoredRef.current = atBottom;
setAnchor({ key: resetKey, anchored: atBottom });
setLatestBelowFold(false);
return;
}
if (anchoredRef.current) {
element.scrollTop = element.scrollHeight;
} else if (pinnedHeadRef.current) {
applyTurnSpacer(element, pinnedHeadRef.current);
}
setLatestBelowFold(latestContentBelowFold(turnTailOverflow(element)));
};
const requestFollow = () => {
if (frame) return;
frame = window.requestAnimationFrame(follow);
};
requestFollow();
if (typeof ResizeObserver === "undefined") {
return () => {
if (frame) window.cancelAnimationFrame(frame);
};
}
const sizes = new ResizeObserver(requestFollow);
const observeChildren = () => {
sizes.disconnect();
for (const child of Array.from(element.children)) sizes.observe(child);
};
observeChildren();
const children = typeof MutationObserver === "undefined"
? null
: new MutationObserver(() => {
observeChildren();
requestFollow();
});
children?.observe(element, { childList: true });
return () => {
sizes.disconnect();
children?.disconnect();
if (frame) window.cancelAnimationFrame(frame);
};
};
const stopWatching = watchAnchor();
const stopFollowing = followContent();
attachment.current = {
element,
resetKey,
detach: () => {
stopWatching();
stopFollowing();
},
};
});
useEffect(() => () => {
attachment.current?.detach();
attachment.current = null;
}, []);
return {
anchored,
latestBelowFold,
anchorToLatest: () => {
const element = container.current;
holdUnpin.current = false;
shouldLand.current = false;
pinnedHeadRef.current = null;
if (element) {
clearTurnSpacer(element);
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
element.scrollTo({ top: element.scrollHeight, behavior: reduceMotion ? "auto" : "smooth" });
setLatestBelowFold(false);
}
setAnchor({ key: resetKey, anchored: true });
},
pinLatestTurn: (target?: HTMLElement) => {
const element = container.current;
const run = () => {
shouldLand.current = false;
holdUnpin.current = true;
// The gesture that sent this turn (tap, Enter) must not release its own pin.
lastGestureAt.current = Number.NEGATIVE_INFINITY;
anchoredRef.current = false;
if (!element) {
setAnchor({ key: resetKey, anchored: false });
setLatestBelowFold(false);
return;
}
const head = resolveTurnHead(element, target);
pinnedHeadRef.current = head;
applyTurnSpacer(element, head);
const space = readPinSpacePx(element);
const top = head ? pinTurnScrollTop(element, head, space) : 0;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
element.scrollTo({ top, behavior: reduceMotion ? "auto" : "smooth" });
lastScrollTop.current = element.scrollTop;
setAnchor({ key: resetKey, anchored: false });
setLatestBelowFold(latestContentBelowFold(turnTailOverflow(element)));
};
if (typeof window === "undefined") {
run();
return;
}
window.requestAnimationFrame(run);
},
};
}