Files
Jyotisha/frontend/src/hooks/use-conversation-scroll-anchor.ts
T
jesse-ux cc1a89802e
Independent Staging Quality Gate / validate (push) Failing after 6m27s
Independent Staging Quality Gate / publish (push) Skipped
fix(web): 无用户行钉顶、闲置不上留白,并修会话列表 tsc 两错
2026-09-17 22:25:53 +08:00

293 lines
11 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 assistant carries the min-height spacer. Measuring it as the turn
// head feeds the spacer back into itself (BUG-931).
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;
}
/**
* 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. 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 anchored = anchor.key === resetKey ? anchor.anchored : true;
useEffect(() => {
anchoredRef.current = anchored;
}, [anchored]);
useEffect(() => {
shouldLand.current = true;
holdUnpin.current = false;
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.
useEffect(() => {
const element = container.current;
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") {
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]);
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;
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);
},
};
}