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
This commit is contained in:
Jesse_Chen
2026-09-26 10:42:12 +08:00
co-authored by Claude Opus 5.5
parent e45d97019f
commit da2613ffd9
12 changed files with 792 additions and 108 deletions
@@ -116,6 +116,26 @@ 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
@@ -123,8 +143,9 @@ export function latestContentBelowFold(overflow: number): boolean {
* 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. Switching
* conversations still lands on the newest content once.
* 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>,
@@ -138,6 +159,8 @@ export function useConversationScrollAnchor(
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(() => {
@@ -150,102 +173,150 @@ export function useConversationScrollAnchor(
pinnedHeadRef.current = null;
}, [resetKey]);
useEffect(() => {
const element = container.current;
if (!active || !element) return;
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) {
if (scrolledUp) {
holdUnpin.current = false;
} else if (distance <= conversationAnchorThreshold) {
holdUnpin.current = false;
} else {
return;
}
}
setAnchor((current) => {
const currentAnchored = current.key === resetKey ? current.anchored : true;
const next = nextAnchorState(currentAnchored, distance, scrolledUp);
return next === currentAnchored && current.key === resetKey ? current : { key: resetKey, anchored: next };
});
};
const onScroll = () => {
if (frame) return;
frame = window.requestAnimationFrame(measure);
};
element.addEventListener("scroll", onScroll, { passive: true });
frame = window.requestAnimationFrame(measure);
return () => {
if (frame) window.cancelAnimationFrame(frame);
element.removeEventListener("scroll", onScroll);
};
}, [active, container, 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;
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") {
// 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 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 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);
};
};
}, [active, container, resetKey]);
const stopWatching = watchAnchor();
const stopFollowing = followContent();
attachment.current = {
element,
resetKey,
detach: () => {
stopWatching();
stopFollowing();
},
};
});
useEffect(() => () => {
attachment.current?.detach();
attachment.current = null;
}, []);
return {
anchored,
@@ -268,6 +339,8 @@ export function useConversationScrollAnchor(
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 });