From 6db4ecc3a77b1a4766b80d645e8bbf6757e007b0 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 20:01:09 -0500 Subject: [PATCH] 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. --- .../frontend/personnel/NpcConversation.tsx | 109 +++++++++++++++--- src/lib/npc-dialogue/AGENTS.md | 28 ++++- 2 files changed, 114 insertions(+), 23 deletions(-) diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 81834d03..21a7b653 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -1,6 +1,6 @@ "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 type { GameNpc } from "@/payload-types"; @@ -189,6 +189,21 @@ export function NpcConversation({ const seq = useRef(0); const sessionRef = useRef(0); const scrollRef = useRef(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(null); + /** The log's content block, observed so a line growing as it types keeps the + * newest character in view. */ + const contentRef = useRef(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++}`; @@ -405,6 +420,7 @@ export function NpcConversation({ // sound stays silent for the whole conversation. primeTypeSound(); skipBeatRef.current = false; + followRef.current = true; setLog([]); setTyping(null); setPlayerTyping(false); @@ -505,6 +521,9 @@ export function NpcConversation({ // the NPC starts typing its reply. `displayText` is the label as shown on // the button (flag tokens already interpolated server-side). 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 text = displayText || hop.label || "…"; if (hop.once && lastNode && lastNode.kind === "node") { @@ -559,29 +578,78 @@ export function NpcConversation({ return node.type === "choice" || node.type === "end" ? node : null; })(); - // Keep the newest line in view. `streamingId` and the choice count are in the - // dependencies because the footer appearing (or a menu growing) changes how - // much room the log has, and the log would otherwise leave the newest line - // scrolled out of sight. + /** True while the log follows new content. A player who scrolls up to read + * something keeps their place; coming back to the bottom, or picking a choice, + * resumes the follow. */ + 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(() => { - const el = scrollRef.current; - if (el) el.scrollTop = el.scrollHeight; + if (followRef.current) scrollToEnd(); }, [log, typing, playerTyping, open, streamingId, visibleChoices.length]); - // The footer grows over several frames, so the log keeps shrinking after the - // effect above has run. Follow it while the player is at the bottom; if they - // scrolled up to re-read something, leave their position alone. + // Two things keep changing after the effect above has run: the footer opening + // shrinks the box, and a line being typed out grows the content. Both are + // 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(() => { - const el = scrollRef.current; - if (!el || typeof ResizeObserver === "undefined") return; + if (!scroller || typeof ResizeObserver === "undefined") return; + const content = contentRef.current; const observer = new ResizeObserver(() => { - if (el.scrollHeight - el.clientHeight - el.scrollTop < 40) { - el.scrollTop = el.scrollHeight; - } + if (followRef.current) scrollToEnd(); }); - observer.observe(el); + observer.observe(scroller); + if (content) observer.observe(content); 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 @@ -693,7 +761,7 @@ export function NpcConversation({ ) : ( <>
{ // A click anywhere in the log finishes the line that is // 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 viewport, so a long conversation still scrolls from the top and nothing becomes unreachable above the scroll origin. */} -
+
{log.map((entry) => (