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:
co-authored by
Claude Opus 5.5
parent
e45d97019f
commit
da2613ffd9
+2
-1
@@ -258,7 +258,8 @@ Both chat surfaces pin a new turn at its head instead of following the last stre
|
||||
- **Head:** the user row of this turn. When this turn has no user row (rectification choice tap, opening, auto-continue) the head is the new assistant row.
|
||||
- **Pin:** on send (and on those rectification new-turn entries) the scroller places that row at the top with a `space-4` gap and then holds still while the reply grows downward.
|
||||
- **Spacer:** the last turn's entry — the `.message-list` child that holds the assistant row, its `.message-actions`, follow-up chips and (rectification) delivery card — gets `min-height: calc(var(--conversation-viewport) - var(--latest-turn-head-height))` plus `align-content: start`, both variables written onto the scroller by `useConversationScrollAnchor`. The spacer trails the whole turn: the actions row sits right under the text at its own `margin: -4px 0 8px`, and the empty space comes after it (BUG-1042; the assistant row itself never carries the spacer — that pushed the actions half a screen down). `align-content: start` keeps the rectification wrap's grid rows from stretching into the space. Not sticky, and `.conversation`'s `padding-bottom` is unchanged. The spacer lasts until the next send; switching sessions clears it.
|
||||
- **History:** opening another session still lands on the newest content once.
|
||||
- **Release:** the pin holds until the reader scrolls — a wheel, a touch drag, a scroll key outside a text field, or a press on the scroller's own scrollbar, followed by a scroll within 1s. Scrolling back to within 96px of the bottom then resumes following; scrolling up leaves the viewport where they put it. Where the pin happens to rest never releases it: the rectification surface rests 94px from the bottom (its spacer plus the jump-chip clearance), inside the threshold, and treating that as "back at the bottom" dragged long rectification replies to their last line (BUG-1044). Taps on buttons inside a message do not count.
|
||||
- **History:** opening another session still lands on the newest content once. That includes the first session on page load (refresh, `?c=` deep link, boot landing): the scroller only mounts after the loading screen, and the hook attaches its scroll listener and resize observer whenever the scroller element appears, not only when `active` or the session key changes (BUG-1043). Without that, a directly opened session showed “跳到最新” under a short reply and never followed.
|
||||
- **Jump to latest:** if the growing turn (or the reader scrolling) leaves more than 96px below the fold, the shared chip appears; pressing it sticks to the bottom for the rest of the turn.
|
||||
|
||||
### Jump to latest
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React, { useRef } from "react";
|
||||
|
||||
import { isScrollKeyGesture, useConversationScrollAnchor } from "../src/hooks/use-conversation-scroll-anchor.ts";
|
||||
import { createClientLifecycleHarness } from "./react-client-lifecycle-test-support.ts";
|
||||
|
||||
Object.assign(globalThis, { React });
|
||||
|
||||
/**
|
||||
* Real React lifecycle (createRoot + act, effects and refs are React's own)
|
||||
* around `useConversationScrollAnchor`. Only the scroller's geometry, its
|
||||
* listeners and ResizeObserver are faked: the host node React mounts is
|
||||
* decorated with scrollTop / scrollHeight / clientHeight, an event registry and
|
||||
* an async `scrollTo` that fires `scroll` afterwards, as a browser's smooth
|
||||
* scroll does. Numbers follow the CDP measurements in BUG-1042 / 1044
|
||||
* (consultation rests ~198px above the bottom after a pin, rectification 94px).
|
||||
*/
|
||||
|
||||
type Listener = (event: Record<string, unknown>) => void;
|
||||
|
||||
type FakeRow = {
|
||||
offsetTop: number;
|
||||
offsetHeight: number;
|
||||
getBoundingClientRect: () => { top: number };
|
||||
};
|
||||
|
||||
type FakeScroller = {
|
||||
scrollTop: number;
|
||||
scrollHeight: number;
|
||||
clientHeight: number;
|
||||
tail: FakeRow;
|
||||
children: unknown[];
|
||||
listeners: Map<string, Set<Listener>>;
|
||||
scrollListenerAdds: number;
|
||||
dispatch: (type: string, event?: Record<string, unknown>) => void;
|
||||
scrollTo: (options: { top: number }) => void;
|
||||
};
|
||||
|
||||
type Anchor = ReturnType<typeof useConversationScrollAnchor>;
|
||||
|
||||
let observeCalls = 0;
|
||||
const observers = new Set<FakeResizeObserver>();
|
||||
|
||||
class FakeResizeObserver {
|
||||
readonly targets = new Set<unknown>();
|
||||
constructor(readonly callback: () => void) {
|
||||
observers.add(this);
|
||||
}
|
||||
observe(target: unknown) {
|
||||
observeCalls += 1;
|
||||
this.targets.add(target);
|
||||
}
|
||||
disconnect() {
|
||||
this.targets.clear();
|
||||
}
|
||||
unobserve() {}
|
||||
}
|
||||
|
||||
/** Content grew: every observer that still watches something fires. */
|
||||
function resizeAll() {
|
||||
for (const observer of Array.from(observers)) {
|
||||
if (observer.targets.size) observer.callback();
|
||||
}
|
||||
}
|
||||
|
||||
function row(offsetTop: number, offsetHeight: number, scroller: () => FakeScroller | null): FakeRow {
|
||||
return {
|
||||
offsetTop,
|
||||
offsetHeight,
|
||||
getBoundingClientRect() {
|
||||
return { top: this.offsetTop - (scroller()?.scrollTop ?? 0) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const decorated = new WeakMap<object, FakeScroller>();
|
||||
|
||||
// The inline ref callback below runs again on every render; decorate each host node once.
|
||||
function decorate(node: Record<string, unknown>, geometry: { scrollHeight: number; clientHeight: number; tail: FakeRow }): FakeScroller {
|
||||
const existing = decorated.get(node);
|
||||
if (existing) return existing;
|
||||
const styles = new Map<string, string>();
|
||||
const listeners = new Map<string, Set<Listener>>();
|
||||
let top = 0;
|
||||
const scroller = node as unknown as FakeScroller;
|
||||
Object.defineProperty(node, "style", {
|
||||
configurable: true,
|
||||
value: {
|
||||
setProperty: (name: string, value: string) => styles.set(name, value),
|
||||
getPropertyValue: (name: string) => styles.get(name) ?? "",
|
||||
removeProperty: (name: string) => styles.delete(name),
|
||||
},
|
||||
});
|
||||
Object.defineProperty(node, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => top,
|
||||
set: (value: number) => {
|
||||
top = Math.max(0, Math.min(value, scroller.scrollHeight - scroller.clientHeight));
|
||||
},
|
||||
});
|
||||
Object.assign(node, {
|
||||
scrollHeight: geometry.scrollHeight,
|
||||
clientHeight: geometry.clientHeight,
|
||||
tail: geometry.tail,
|
||||
children: [{ child: 1 }, { child: 2 }],
|
||||
listeners,
|
||||
scrollListenerAdds: 0,
|
||||
addEventListener(type: string, listener: Listener) {
|
||||
if (type === "scroll") scroller.scrollListenerAdds += 1;
|
||||
if (!listeners.has(type)) listeners.set(type, new Set());
|
||||
listeners.get(type)!.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: Listener) {
|
||||
listeners.get(type)?.delete(listener);
|
||||
},
|
||||
dispatch(type: string, event: Record<string, unknown> = {}) {
|
||||
for (const listener of Array.from(listeners.get(type) ?? [])) listener({ target: node, ...event });
|
||||
},
|
||||
// Smooth scroll: the position moves later, then `scroll` fires.
|
||||
scrollTo({ top: next }: { top: number }) {
|
||||
setTimeout(() => {
|
||||
scroller.scrollTop = next;
|
||||
scroller.dispatch("scroll");
|
||||
}, 0);
|
||||
},
|
||||
getBoundingClientRect: () => ({ top: 0 }),
|
||||
querySelector: () => scroller.tail,
|
||||
querySelectorAll: () => [],
|
||||
});
|
||||
decorated.set(node, scroller);
|
||||
return scroller;
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const harness = createClientLifecycleHarness();
|
||||
const window = globalThis.window as unknown as Record<string, unknown>;
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
const originalResizeObserver = Object.getOwnPropertyDescriptor(globalThis, "ResizeObserver");
|
||||
Object.defineProperty(globalThis, "ResizeObserver", { value: FakeResizeObserver, configurable: true, writable: true });
|
||||
observers.clear();
|
||||
observeCalls = 0;
|
||||
return {
|
||||
harness,
|
||||
async close() {
|
||||
await harness.close();
|
||||
if (originalResizeObserver) Object.defineProperty(globalThis, "ResizeObserver", originalResizeObserver);
|
||||
else Reflect.deleteProperty(globalThis, "ResizeObserver");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type SurfaceProps = {
|
||||
readonly loading: boolean;
|
||||
readonly active?: boolean;
|
||||
readonly resetKey: string;
|
||||
readonly geometry: () => { scrollHeight: number; clientHeight: number; tail: FakeRow };
|
||||
readonly onScroller: (scroller: FakeScroller | null) => void;
|
||||
readonly onAnchor: (anchor: Anchor) => void;
|
||||
readonly generation?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Mirrors the home page: while bootstrapping it renders only the loading
|
||||
* screen, then reveals `.conversation` with the same `active` and `resetKey`.
|
||||
* The hook is called above the gate on every render, as `page.tsx` does.
|
||||
*/
|
||||
function Surface({ loading, active = true, resetKey, geometry, onScroller, onAnchor, generation = 0 }: SurfaceProps) {
|
||||
const conversation = useRef<HTMLDivElement | null>(null);
|
||||
const anchor = useConversationScrollAnchor(conversation, active, resetKey);
|
||||
onAnchor(anchor);
|
||||
if (loading) return <main className="app-loading" aria-busy="true" />;
|
||||
return (
|
||||
<div
|
||||
key={generation}
|
||||
className="conversation"
|
||||
ref={(node) => {
|
||||
const scroller = node ? decorate(node as unknown as Record<string, unknown>, geometry()) : null;
|
||||
conversation.current = scroller as unknown as HTMLDivElement | null;
|
||||
onScroller(scroller);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const VIEWPORT = 600;
|
||||
const PIN_SPACE = 16;
|
||||
|
||||
test("an existing conversation revealed after the loading screen attaches the anchor (BUG-1043)", async () => {
|
||||
const { harness, close } = setup();
|
||||
try {
|
||||
let scroller: FakeScroller | null = null;
|
||||
let anchor!: Anchor;
|
||||
const history = row(1700, 276, () => scroller);
|
||||
const props = {
|
||||
resetKey: "session-1",
|
||||
geometry: () => ({ scrollHeight: 2000, clientHeight: VIEWPORT, tail: history }),
|
||||
onScroller: (value: FakeScroller | null) => { scroller = value; },
|
||||
onAnchor: (value: Anchor) => { anchor = value; },
|
||||
};
|
||||
|
||||
// Given: the page boots behind the loading screen, then reveals the same session.
|
||||
await harness.render(<Surface {...props} loading />);
|
||||
await harness.idle();
|
||||
assert.equal(scroller, null);
|
||||
await harness.render(<Surface {...props} loading={false} />);
|
||||
await harness.idle();
|
||||
|
||||
// Then: the scroll listener and the resize observer are attached to the revealed scroller,
|
||||
// and opening the session landed on its newest content once.
|
||||
const element = scroller as unknown as FakeScroller;
|
||||
assert.equal(element.scrollListenerAdds, 1);
|
||||
assert.ok(observeCalls > 0, "ResizeObserver never observed the scroller's children");
|
||||
assert.equal(element.scrollTop, 2000 - VIEWPORT);
|
||||
|
||||
// Re-rendering (every streamed token re-renders the page) does not attach twice.
|
||||
await harness.render(<Surface {...props} loading={false} />);
|
||||
await harness.render(<Surface {...props} loading={false} />);
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollListenerAdds, 1);
|
||||
assert.equal(element.listeners.get("scroll")?.size, 1);
|
||||
|
||||
// When: a short question is sent. The user row lands at 2000, the reply is 80px, and the
|
||||
// spacer makes room for the pin; consultation rests ~198px above the bottom.
|
||||
const user = row(2000, 48, () => scroller);
|
||||
element.tail = row(2064, 80, () => scroller);
|
||||
element.scrollHeight = 2000 - PIN_SPACE + VIEWPORT + 198;
|
||||
await harness.update(() => anchor.pinLatestTurn(user as unknown as HTMLElement));
|
||||
await harness.idle();
|
||||
await harness.idle();
|
||||
|
||||
// Then: the head is pinned and, once the smooth scroll lands, a short reply shows no jump chip.
|
||||
assert.equal(element.scrollTop, 2000 - PIN_SPACE);
|
||||
assert.equal(anchor.latestBelowFold, false);
|
||||
assert.equal(anchor.anchored, false);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a long reply after reveal shows the jump chip and following works once pressed (BUG-1043)", async () => {
|
||||
const { harness, close } = setup();
|
||||
try {
|
||||
let scroller: FakeScroller | null = null;
|
||||
let anchor!: Anchor;
|
||||
const history = row(1700, 276, () => scroller);
|
||||
const props = {
|
||||
resetKey: "session-1",
|
||||
geometry: () => ({ scrollHeight: 2000, clientHeight: VIEWPORT, tail: history }),
|
||||
onScroller: (value: FakeScroller | null) => { scroller = value; },
|
||||
onAnchor: (value: Anchor) => { anchor = value; },
|
||||
};
|
||||
await harness.render(<Surface {...props} loading />);
|
||||
await harness.render(<Surface {...props} loading={false} />);
|
||||
await harness.idle();
|
||||
const element = scroller as unknown as FakeScroller;
|
||||
|
||||
const user = row(2000, 48, () => scroller);
|
||||
element.tail = row(2064, 1400, () => scroller);
|
||||
element.scrollHeight = 2064 + 1400 + 198;
|
||||
await harness.update(() => anchor.pinLatestTurn(user as unknown as HTMLElement));
|
||||
await harness.idle();
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, 2000 - PIN_SPACE);
|
||||
assert.equal(anchor.latestBelowFold, true);
|
||||
|
||||
// When: the reader presses 跳到最新.
|
||||
await harness.update(() => anchor.anchorToLatest());
|
||||
await harness.idle();
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, element.scrollHeight - VIEWPORT);
|
||||
assert.equal(anchor.latestBelowFold, false);
|
||||
assert.equal(anchor.anchored, true);
|
||||
|
||||
// Then: further growth keeps the viewport on the bottom.
|
||||
element.tail.offsetHeight += 400;
|
||||
element.scrollHeight += 400;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, element.scrollHeight - VIEWPORT);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a scroller that remounts under the same key re-attaches to the new element (BUG-1043)", async () => {
|
||||
const { harness, close } = setup();
|
||||
try {
|
||||
const seen: FakeScroller[] = [];
|
||||
let anchor!: Anchor;
|
||||
const props = {
|
||||
loading: false,
|
||||
resetKey: "session-1",
|
||||
geometry: () => ({ scrollHeight: 1200, clientHeight: VIEWPORT, tail: row(900, 276, () => null) }),
|
||||
onScroller: (value: FakeScroller | null) => { if (value && !seen.includes(value)) seen.push(value); },
|
||||
onAnchor: (value: Anchor) => { anchor = value; },
|
||||
};
|
||||
await harness.render(<Surface {...props} generation={0} />);
|
||||
await harness.idle();
|
||||
await harness.render(<Surface {...props} generation={1} />);
|
||||
await harness.idle();
|
||||
assert.equal(seen.length, 2);
|
||||
const [first, second] = seen;
|
||||
assert.equal(first.listeners.get("scroll")?.size ?? 0, 0, "the detached scroller kept its listener");
|
||||
assert.equal(second.listeners.get("scroll")?.size, 1);
|
||||
assert.ok(anchor);
|
||||
|
||||
// Unmounting the page releases the listener.
|
||||
await harness.render(<Surface {...props} loading generation={1} />);
|
||||
await harness.idle();
|
||||
assert.equal(second.listeners.get("scroll")?.size ?? 0, 0);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function pinnedRectificationTurn() {
|
||||
const env = setup();
|
||||
let scroller: FakeScroller | null = null;
|
||||
let anchor!: Anchor;
|
||||
const history = row(1700, 276, () => scroller);
|
||||
const props = {
|
||||
loading: false,
|
||||
resetKey: "case-1",
|
||||
geometry: () => ({ scrollHeight: 2000, clientHeight: VIEWPORT, tail: history }),
|
||||
onScroller: (value: FakeScroller | null) => { scroller = value; },
|
||||
onAnchor: (value: Anchor) => { anchor = value; },
|
||||
};
|
||||
// The rectification surface mounts after reveal, so its scroller exists from the first render.
|
||||
await env.harness.render(<Surface {...props} />);
|
||||
await env.harness.idle();
|
||||
const element = scroller as unknown as FakeScroller;
|
||||
assert.equal(element.scrollTop, 2000 - VIEWPORT);
|
||||
|
||||
// A choice tap: no user row, the new assistant is the head and the tail. The full-viewport
|
||||
// spacer plus the rectification list's bottom padding leave the pin resting 94px above the
|
||||
// bottom, i.e. inside the 96px threshold (CDP measurement, BUG-1044).
|
||||
const head = row(2000, 80, () => scroller);
|
||||
element.tail = head;
|
||||
element.scrollHeight = 2000 - PIN_SPACE + VIEWPORT + 94;
|
||||
await env.harness.update(() => anchor.pinLatestTurn(head as unknown as HTMLElement));
|
||||
await env.harness.idle();
|
||||
await env.harness.idle();
|
||||
return { ...env, element, head, anchor: () => anchor };
|
||||
}
|
||||
|
||||
test("a rectification pin resting within the threshold is not pulled to the bottom (BUG-1044)", async () => {
|
||||
const { harness, close, element, head, anchor } = await pinnedRectificationTurn();
|
||||
try {
|
||||
const pinned = 2000 - PIN_SPACE;
|
||||
assert.equal(element.scrollTop, pinned);
|
||||
assert.equal(element.scrollHeight - element.scrollTop - element.clientHeight, 94);
|
||||
assert.equal(anchor().anchored, false);
|
||||
|
||||
// A scroll event nobody made (layout, scroll anchoring) at the same resting position.
|
||||
await harness.update(() => element.dispatch("scroll"));
|
||||
await harness.idle();
|
||||
assert.equal(anchor().anchored, false);
|
||||
|
||||
// When: the reply streams past the viewport.
|
||||
head.offsetHeight = 1400;
|
||||
element.scrollHeight = 2000 + 1400 + 94;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
|
||||
// Then: the head stays at the top and the jump chip appears instead.
|
||||
assert.equal(element.scrollTop, pinned);
|
||||
assert.equal(anchor().anchored, false);
|
||||
assert.equal(anchor().latestBelowFold, true);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("after a pin only a reader's own scroll to the bottom resumes following (BUG-1044)", async () => {
|
||||
const { harness, close, element, head, anchor } = await pinnedRectificationTurn();
|
||||
try {
|
||||
head.offsetHeight = 1400;
|
||||
element.scrollHeight = 2000 + 1400 + 94;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, 2000 - PIN_SPACE);
|
||||
|
||||
// When: the reader wheels down to the bottom.
|
||||
await harness.update(() => {
|
||||
element.dispatch("wheel", { deltaY: 900 });
|
||||
element.scrollTop = element.scrollHeight;
|
||||
element.dispatch("scroll");
|
||||
});
|
||||
await harness.idle();
|
||||
assert.equal(anchor().anchored, true);
|
||||
assert.equal(anchor().latestBelowFold, false);
|
||||
|
||||
// Then: further growth is followed.
|
||||
head.offsetHeight += 400;
|
||||
element.scrollHeight += 400;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, element.scrollHeight - VIEWPORT);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("after a pin a touch drag upward releases the pin without following (BUG-930 kept)", async () => {
|
||||
const { harness, close, element, head, anchor } = await pinnedRectificationTurn();
|
||||
try {
|
||||
await harness.update(() => {
|
||||
element.dispatch("touchmove");
|
||||
element.scrollTop -= 300;
|
||||
element.dispatch("scroll");
|
||||
});
|
||||
await harness.idle();
|
||||
assert.equal(anchor().anchored, false);
|
||||
const readingAt = element.scrollTop;
|
||||
|
||||
head.offsetHeight = 1400;
|
||||
element.scrollHeight = 2000 + 1400 + 94;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, readingAt);
|
||||
assert.equal(anchor().latestBelowFold, true);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("clicking inside the transcript is not a scroll gesture (BUG-1044)", async () => {
|
||||
const { harness, close, element, head, anchor } = await pinnedRectificationTurn();
|
||||
try {
|
||||
// A tap on a button in a message (copy, thinking toggle) bubbles pointerdown to the scroller.
|
||||
await harness.update(() => {
|
||||
element.dispatch("pointerdown", { target: head });
|
||||
element.dispatch("scroll");
|
||||
});
|
||||
await harness.idle();
|
||||
head.offsetHeight = 1400;
|
||||
element.scrollHeight = 2000 + 1400 + 94;
|
||||
await harness.update(() => resizeAll());
|
||||
await harness.idle();
|
||||
assert.equal(element.scrollTop, 2000 - PIN_SPACE);
|
||||
assert.equal(anchor().anchored, false);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("switching the hook off and on (starter home, rectification surface) detaches and re-attaches", async () => {
|
||||
const { harness, close } = setup();
|
||||
try {
|
||||
let scroller: FakeScroller | null = null;
|
||||
const props = {
|
||||
loading: false,
|
||||
resetKey: "session-1",
|
||||
geometry: () => ({ scrollHeight: 1200, clientHeight: VIEWPORT, tail: row(900, 276, () => null) }),
|
||||
onScroller: (value: FakeScroller | null) => { scroller = value; },
|
||||
onAnchor: () => undefined,
|
||||
};
|
||||
await harness.render(<Surface {...props} active={false} />);
|
||||
await harness.idle();
|
||||
const element = scroller as unknown as FakeScroller;
|
||||
assert.equal(element.listeners.get("scroll")?.size ?? 0, 0);
|
||||
await harness.render(<Surface {...props} active />);
|
||||
await harness.idle();
|
||||
assert.equal(element.listeners.get("scroll")?.size, 1);
|
||||
await harness.render(<Surface {...props} active={false} />);
|
||||
await harness.idle();
|
||||
assert.equal(element.listeners.get("scroll")?.size ?? 0, 0);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("scroll keys count as a reader gesture only outside text fields and buttons", () => {
|
||||
const target = (match: string | null) => ({ closest: (selector: string) => (match && selector.includes(match) ? {} : null) });
|
||||
const key = (value: string, over: Partial<KeyboardEvent> = {}) => ({
|
||||
key: value, target: target(null), altKey: false, ctrlKey: false, metaKey: false, ...over,
|
||||
}) as unknown as KeyboardEvent;
|
||||
assert.equal(isScrollKeyGesture(key("PageDown")), true);
|
||||
assert.equal(isScrollKeyGesture(key("End")), true);
|
||||
assert.equal(isScrollKeyGesture(key(" ")), true);
|
||||
assert.equal(isScrollKeyGesture(key("a")), false);
|
||||
assert.equal(isScrollKeyGesture(key("Enter")), false);
|
||||
assert.equal(isScrollKeyGesture(key("ArrowDown", { target: target("textarea") as unknown as EventTarget })), false);
|
||||
assert.equal(isScrollKeyGesture(key(" ", { target: target("button") as unknown as EventTarget })), false);
|
||||
assert.equal(isScrollKeyGesture(key("PageDown", { target: target("button") as unknown as EventTarget })), true);
|
||||
assert.equal(isScrollKeyGesture(key("ArrowDown", { metaKey: true })), false);
|
||||
});
|
||||
Reference in New Issue
Block a user