1
0
Fork 0

fix(npc-dialogue): follow the end of the log, unless the player scrolled up

The log jumped to the bottom whenever the choice menu appeared, even for someone
who had scrolled up to re-read an earlier line. Following is now a state: it
starts on, a wheel or touch gesture upward turns it off, reaching the bottom or
picking a choice turns it back on. A 150ms guard after our own scroll write stops
a pin from being read as the player leaving.

Two layout changes had to be observed, since neither changes the log array: the
footer opening shrinks the box, and a line growing as it types lengthens the
content. One ResizeObserver watches both and re-pins only while following, which
also fixes the newest characters drifting below the fold mid-line.

The scroller now reaches the effects through a callback ref plus state. Radix
mounts the dialog's DOM a commit after open flips, so an effect keyed on open ran
with a null ref: no observer and no scroll listeners were ever attached, which is
why the previous commit's follow behaviour did nothing.

Measured: untouched, the log ends at the new bottom (228px, distance 0) when the
menu opens; scrolled up first, it holds the player's 76px position while the menu
opens beneath.
This commit is contained in:
Jason Fraley 2026-11-24 20:01:09 -05:00
parent ccbbeaaa99
commit 6db4ecc3a7
2 changed files with 114 additions and 23 deletions

View file

@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, useMemo, useRef, useState, Fragment } from "react"; import { useCallback, useEffect, useMemo, useRef, useState, Fragment } from "react";
import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react"; import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react";
import type { GameNpc } from "@/payload-types"; import type { GameNpc } from "@/payload-types";
@ -189,6 +189,21 @@ export function NpcConversation({
const seq = useRef(0); const seq = useRef(0);
const sessionRef = useRef(0); const sessionRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
/** The scroller as state, not just a ref: the dialog's DOM is mounted by Radix
* a commit after `open` flips, so an effect keyed on `open` would run before
* the element exists and never attach its observers. */
const [scroller, setScroller] = useState<HTMLDivElement | null>(null);
/** The log's content block, observed so a line growing as it types keeps the
* newest character in view. */
const contentRef = useRef<HTMLDivElement>(null);
/** Stable ref callback. An inline arrow here would be a new function every
* render, so React would detach and reattach it each time and the state write
* would loop. */
const attachScroller = useCallback((node: HTMLDivElement | null) => {
scrollRef.current = node;
setScroller((current) => (current === node ? current : node));
}, []);
const nextId = () => `entry-${seq.current++}`; const nextId = () => `entry-${seq.current++}`;
@ -405,6 +420,7 @@ export function NpcConversation({
// sound stays silent for the whole conversation. // sound stays silent for the whole conversation.
primeTypeSound(); primeTypeSound();
skipBeatRef.current = false; skipBeatRef.current = false;
followRef.current = true;
setLog([]); setLog([]);
setTyping(null); setTyping(null);
setPlayerTyping(false); setPlayerTyping(false);
@ -505,6 +521,9 @@ export function NpcConversation({
// the NPC starts typing its reply. `displayText` is the label as shown on // the NPC starts typing its reply. `displayText` is the label as shown on
// the button (flag tokens already interpolated server-side). // the button (flag tokens already interpolated server-side).
const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => { const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => {
// Choosing is the player saying they are done reading up the log, so the
// log resumes following their own line and the reply that comes back.
followRef.current = true;
const token = sessionRef.current; const token = sessionRef.current;
const text = displayText || hop.label || "…"; const text = displayText || hop.label || "…";
if (hop.once && lastNode && lastNode.kind === "node") { if (hop.once && lastNode && lastNode.kind === "node") {
@ -559,29 +578,78 @@ export function NpcConversation({
return node.type === "choice" || node.type === "end" ? node : null; return node.type === "choice" || node.type === "end" ? node : null;
})(); })();
// Keep the newest line in view. `streamingId` and the choice count are in the /** True while the log follows new content. A player who scrolls up to read
// dependencies because the footer appearing (or a menu growing) changes how * something keeps their place; coming back to the bottom, or picking a choice,
// much room the log has, and the log would otherwise leave the newest line * resumes the follow. */
// scrolled out of sight. const followRef = useRef(true);
/** When we last wrote `scrollTop` ourselves, so our own writes are never read
* as the player scrolling away. */
const lastAutoScrollRef = useRef(0);
const scrollToEnd = () => {
if (!scroller) return;
scroller.scrollTop = scroller.scrollHeight;
lastAutoScrollRef.current =
typeof performance === "undefined" ? 0 : performance.now();
};
// Follow new lines, the typing dots and the footer opening, but only while the
// player is following: someone reading further up keeps their place instead of
// being dragged to the bottom when a menu appears.
useEffect(() => { useEffect(() => {
const el = scrollRef.current; if (followRef.current) scrollToEnd();
if (el) el.scrollTop = el.scrollHeight;
}, [log, typing, playerTyping, open, streamingId, visibleChoices.length]); }, [log, typing, playerTyping, open, streamingId, visibleChoices.length]);
// The footer grows over several frames, so the log keeps shrinking after the // Two things keep changing after the effect above has run: the footer opening
// effect above has run. Follow it while the player is at the bottom; if they // shrinks the box, and a line being typed out grows the content. Both are
// scrolled up to re-read something, leave their position alone. // watched, so the newest character stays in view while the player is
// following. Depends on `open` because the dialog's DOM does not exist until
// it is first opened, and the refs would be null on mount.
useEffect(() => { useEffect(() => {
const el = scrollRef.current; if (!scroller || typeof ResizeObserver === "undefined") return;
if (!el || typeof ResizeObserver === "undefined") return; const content = contentRef.current;
const observer = new ResizeObserver(() => { const observer = new ResizeObserver(() => {
if (el.scrollHeight - el.clientHeight - el.scrollTop < 40) { if (followRef.current) scrollToEnd();
el.scrollTop = el.scrollHeight;
}
}); });
observer.observe(el); observer.observe(scroller);
if (content) observer.observe(content);
return () => observer.disconnect(); return () => observer.disconnect();
}, []); }, [scroller]);
// Stop following when the player scrolls up, resume at the bottom. The wheel
// and touch listeners catch the gesture itself (before the scroll lands), the
// scroll listener resumes and also catches a dragged scrollbar.
useEffect(() => {
const el = scroller;
if (!el) return;
const distanceFromEnd = () => el.scrollHeight - el.clientHeight - el.scrollTop;
const onWheel = (event: WheelEvent) => {
if (event.deltaY < 0 && distanceFromEnd() > 8) followRef.current = false;
};
const onTouchMove = () => {
if (distanceFromEnd() > 8) followRef.current = false;
};
const onScroll = () => {
if (distanceFromEnd() <= 8) {
followRef.current = true;
return;
}
const now = typeof performance === "undefined" ? 0 : performance.now();
// A box change (the footer opening) or our own pin can make the distance
// grow for a frame. Only a scroll well after our last write counts as the
// player leaving the bottom.
if (now - lastAutoScrollRef.current < 150) return;
followRef.current = false;
};
el.addEventListener("wheel", onWheel, { passive: true });
el.addEventListener("touchmove", onTouchMove, { passive: true });
el.addEventListener("scroll", onScroll, { passive: true });
return () => {
el.removeEventListener("wheel", onWheel);
el.removeEventListener("touchmove", onTouchMove);
el.removeEventListener("scroll", onScroll);
};
}, [scroller]);
/** Button text for a choice: the server-resolved label when the choice /** Button text for a choice: the server-resolved label when the choice
@ -693,7 +761,7 @@ export function NpcConversation({
) : ( ) : (
<> <>
<div <div
ref={scrollRef} ref={attachScroller}
onClick={() => { onClick={() => {
// A click anywhere in the log finishes the line that is // A click anywhere in the log finishes the line that is
// typing, or starts the next one when the beat is showing, // typing, or starts the next one when the beat is showing,
@ -709,7 +777,10 @@ export function NpcConversation({
box. `min-h-full` keeps the block able to grow past the box. `min-h-full` keeps the block able to grow past the
viewport, so a long conversation still scrolls from the top viewport, so a long conversation still scrolls from the top
and nothing becomes unreachable above the scroll origin. */} and nothing becomes unreachable above the scroll origin. */}
<div className="flex min-h-full flex-col justify-end gap-3"> <div
ref={contentRef}
className="flex min-h-full flex-col justify-end gap-3"
>
{log.map((entry) => ( {log.map((entry) => (
<TimelineEntry <TimelineEntry
key={entry.id} key={entry.id}

View file

@ -243,10 +243,30 @@ it, `justify-end` puts overflow above the scroll origin where it cannot be reach
The auto-scroll effect depends on `streamingId` and `visibleChoices.length` as well The auto-scroll effect depends on `streamingId` and `visibleChoices.length` as well
as the log: the footer appearing (or a menu gaining items) changes how much room the as the log: the footer appearing (or a menu gaining items) changes how much room the
log has, and without those the newest line can end up scrolled out of sight. A log has, and without those the newest line can end up scrolled out of sight.
`ResizeObserver` on the log keeps pinning it to the bottom while the footer animates,
but only when the player is already near the bottom, so nobody reading further up **Following is a state, not a rule about position.** `followRef` starts true and the
gets yanked. log pins to the end on new lines, the typing dots, the footer opening and any content
growth. The player scrolling up turns it off, so nothing drags them to the bottom
while they are reading; coming back to the bottom, or picking a choice, turns it back
on. Detection uses `wheel` (upward delta), `touchmove`, and `scroll` (resuming at the
bottom, and catching a dragged scrollbar), with a 150ms guard after our own write so a
pin cannot be mistaken for the player leaving. Measured: untouched, the log ends at
the new `maxTop` (228px, distance 0) when the footer opens; scrolled up first, it stays
exactly where the player left it (76px) while the footer opens beneath.
Two things had to be watched, because both change the layout without changing the log
array: the footer opening (the box shrinks) and a line growing as it types (the content
grows). One `ResizeObserver` watches the scroller and the content block, and re-pins
only while following. Without the content observer the newest characters drift below
the fold mid-line, which is what the reveal looked like before.
The scroller reaches the effects through a **callback ref plus state**, not a plain
`useCallback`-less ref: Radix mounts the dialog's DOM a commit after `open` flips, so
an effect keyed on `open` ran while `scrollRef.current` was still null, attached
nothing, and every follow behaviour silently did nothing. The callback ref is also
`useCallback`-wrapped, because an inline arrow is a new function each render and React
would detach and reattach it, looping on the state write.
**The footer slides in.** It is wrapped in a grid whose **The footer slides in.** It is wrapped in a grid whose
`grid-template-rows` goes `0fr` to `1fr` over 300ms, with the item `min-h-0` and the `grid-template-rows` goes `0fr` to `1fr` over 300ms, with the item `min-h-0` and the