"use client"; import { useCallback, useEffect, useMemo, useRef, useState, Fragment } from "react"; import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react"; import type { GameNpc } from "@/payload-types"; import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue"; import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import { DialogueText, visibleLength, visibleText } from "@/lib/npc-dialogue/DialogueText"; import { choiceIndexFromKey, choiceShortcutLabel, isSkipKey } from "@/lib/npc-dialogue/keys"; import { DEFAULT_PACING_PRESET, beatMs, buildRevealSchedule, scaleSchedule, shownAt, } from "@/lib/npc-dialogue/pacing"; import { playTypeTick, primeTypeSound } from "@/lib/npc-dialogue/typeSound"; import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments"; import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue"; import { DOSSIER } from "@/components/frontend/operations"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogTitle, } from "@/components/ui/dialog"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { evaluateNpcDialogueChoices, evaluateNpcDialogueCondition, markNpcDialogueNodeRead, resolveNpcDialogueTexts, triggerNpcDialogueEvent, } from "@/app/(frontend)/personnel/contacts/[id]/actions"; interface NpcConversationProps { readonly npc: GameNpc; readonly dialogue: { id: number; flowData?: FlowData } | null | undefined; /** Node ids this user has already read (server-side NEW badges). Seeds the * local seen set; reads during the session are sent to the server and * merged optimistically. */ readonly initialSeenNodeIds?: readonly string[]; /** Type lines out character by character. Resolved server-side from the * player's preference and the unit default; reduced-motion always wins. */ readonly typewriter?: boolean; /** Sound under the typing. Silent on lines that have a recorded clip. */ readonly typewriterSound?: boolean; /** Play recorded voice clips. The header button mutes for the session. */ readonly voice?: boolean; } interface ResolvedFlow { nodes: DialogueNode[]; startId: string | null; } type LogEntry = | { kind: "node"; id: string; node: DialogueNode; /** Server-resolved display strings (flag tokens interpolated), when the * node had tokens. Undefined = render the raw authored strings. */ resolved?: ResolvedNodeTexts; /** The line as shown, resolved text first. Stored so the reveal length and * the renderer can never disagree about what is being typed. */ text: string; /** Visible characters revealed so far while typing; undefined = whole * line is showing. */ reveal?: number; /** Playable voice clip for this line, when it has one. */ voiceUrl?: string; /** The browser refused autoplay; the line shows a play button instead. */ voiceBlocked?: boolean; } | { kind: "player"; id: string; text: string }; /** Resolves the authored flowchart into a shape the runtime can walk. */ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | null { if (!dialogue?.flowData || !Array.isArray(dialogue.flowData.nodes)) return null; const nodes = dialogue.flowData.nodes as DialogueNode[]; return { nodes, startId: findStartNode(nodes)?.id ?? null }; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Longest a line may take, pauses included. Past this the schedule is * compressed: a wall of text still has to arrive while the player is looking. */ const REVEAL_CAP_MS = 3000; /** True when the device asks for reduced motion; the animation is skipped * entirely rather than merely shortened. */ function prefersReducedMotion(): boolean { return ( typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches ); } /** Seconds in a clip, or 0 when the browser has not read the metadata yet. * Bounded so an unreadable file cannot stall the reveal. */ async function clipDuration(audio: HTMLAudioElement): Promise { if (Number.isFinite(audio.duration) && audio.duration > 0) return audio.duration; return await new Promise((resolve) => { const done = (value: number) => { audio.removeEventListener("loadedmetadata", onMeta); clearTimeout(timer); resolve(value); }; const onMeta = () => done(Number.isFinite(audio.duration) ? audio.duration : 0); const timer = setTimeout(() => done(0), 1200); audio.addEventListener("loadedmetadata", onMeta); }); } /** The line a node displays, resolved text first (flag tokens interpolated). * Single source of truth for both the reveal length and the rendered line. */ function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string { if (node.type === "event") { return ( (resolved?.body ?? node.data.body) || (resolved?.message ?? node.data.effect?.message) || "An event unfolds…" ); } if (node.type === "end") { return (resolved?.closing ?? node.data.closing) || "The conversation ends."; } if (node.type === "choice") { return (resolved?.leadIn ?? node.data.leadIn) || ""; } return (resolved?.body ?? node.data.body) || ""; } export function NpcConversation({ npc, dialogue, initialSeenNodeIds, typewriter = true, typewriterSound = true, voice = true, }: NpcConversationProps) { const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const [open, setOpen] = useState(false); const [log, setLog] = useState([]); /** Speaker label while the NPC types; "" for speaker-less narration. */ const [typing, setTyping] = useState(null); /** True while the player's chosen line is "typing" into the log. */ const [playerTyping, setPlayerTyping] = useState(false); /** Log entry currently typing itself out, if any. Gates the choice footer so * a player cannot answer a line they have not finished reading. */ const [streamingId, setStreamingId] = useState(null); /** Set by clicking the log: finish the line instead of waiting. */ const skipRevealRef = useRef(null); /** Set by clicking the log during the beat between lines: start the next one. */ const skipBeatRef = useRef(false); /** One element reused for every clip: a line's audio stops when the next * starts, and the browser keeps its autoplay permission for the session. */ const audioRef = useRef(null); /** This conversation's id: node lookups name it so the server can verify the * reader is in a conversation they are allowed to see. */ const dialogueId = dialogue?.id ?? null; /** Sound is on unless the player turned it off or muted this session. */ const [soundOn, setSoundOn] = useState(voice); const soundOnRef = useRef(soundOn); soundOnRef.current = soundOn; /** Which line's clip is playing, and how far through it is, for the progress * hairline under that line. */ const [playing, setPlaying] = useState<{ id: string; ratio: number } | null>(null); /** Fetched clips, keyed by their server URL, as object URLs so the next line * starts from memory instead of the network. Bounded, and revoked on eviction. */ const clipCacheRef = useRef>(new Map()); const clipPendingRef = useRef>(new Set()); /** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation. * Purely local: it resets on every `begin()`, so a choice hidden here * reappears the next time the conversation is opened. Persist across * conversations with a condition + player flag instead. */ const [takenChoices, setTakenChoices] = useState>(new Set()); /** Per-node visibility gates for condition-gated choices, fetched from * the server when the conversation lands on a choice node. Cleared on * every `begin()` so flags gained mid-conversation are re-checked. */ const [choiceGates, setChoiceGates] = useState>({}); /** Node ids this player has read, powering the NEW badges. Seeded from the * server (npc-dialogue-states); nodes read in this session are added here * optimistically and persisted via `markNpcDialogueNodeRead`. */ const [seenNodes, setSeenNodes] = useState>( () => new Set(initialSeenNodeIds ?? []), ); 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++}`; /** The URL to hand the audio element: the in-memory copy when it has been * fetched, the server URL otherwise. */ const playableUrl = (url: string) => clipCacheRef.current.get(url) ?? url; /** Fetch a clip before its line arrives. Failure is silent: the line then * loads its clip the old way, one request later. */ const preloadClip = (url: string | undefined) => { if (!url || !soundOnRef.current) return; if (clipCacheRef.current.has(url) || clipPendingRef.current.has(url)) return; clipPendingRef.current.add(url); void fetch(url) .then((res) => (res.ok ? res.blob() : null)) .then((blob) => { if (!blob) return; const objectUrl = URL.createObjectURL(blob); const cache = clipCacheRef.current; cache.set(url, objectUrl); // Eight clips is a few hundred kB and covers the usual branch depth. while (cache.size > 8) { const [oldest, value] = [...cache.entries()][0] ?? []; if (!oldest) break; URL.revokeObjectURL(value); cache.delete(oldest); } }) .catch(() => undefined) .finally(() => clipPendingRef.current.delete(url)); }; // Release the prefetched clips when the dialog goes away. Object URLs are not // collected on their own, so without this every opened conversation would // leave a few hundred kB behind. useEffect( () => () => { const cache = clipCacheRef.current; for (const value of cache.values()) URL.revokeObjectURL(value); cache.clear(); }, [], ); // Invalidate pending typing timers when the component unmounts. useEffect( () => () => { sessionRef.current += 1; }, [], ); // The choice node the log currently rests on (if any). const activeChoiceNodeId = useMemo(() => { const last = [...log].reverse().find((entry) => entry.kind === "node"); return last && last.kind === "node" && last.node.type === "choice" ? last.node.id : null; }, [log]); // Fetch the server-side visibility gates when landing on a choice node // that has gated choices. Gated choices stay hidden until confirmed, so a // forbidden option never flashes on screen. useEffect(() => { if (!open || !flow || !activeChoiceNodeId) return; if (choiceGates[activeChoiceNodeId]) return; const node = flow.nodes.find((n) => n.id === activeChoiceNodeId); const hasGated = (node?.data.choices ?? []).some( (c) => c.condition && !hasEmptyConditionKey(c.condition), ); if (!hasGated) return; let cancelled = false; if (dialogueId === null) return; void evaluateNpcDialogueChoices(dialogueId, Number(npc.id), activeChoiceNodeId).then((res) => { if (!cancelled && res.success && Array.isArray(res.data)) { const gate = res.data; setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate })); } }); return () => { cancelled = true; }; }, [open, flow, activeChoiceNodeId, choiceGates, npc.id]); // NEW badge input: nodes in this flow the player has never read. Server- // sourced, so badges follow the account across devices; GM edits no longer // re-flag content the player already saw. const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]); const unseenTargets = useMemo( () => new Set(allNodeIds.filter((id) => !seenNodes.has(id))), [seenNodes, allNodeIds], ); if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null; /** Marks a node read: clears its badge locally right away and persists the * marker server-side fire-and-forget (a failed write just re-badges on the * next load; the action itself is idempotent). */ const markSeen = (nodeId: string) => { if (!dialogue || seenNodes.has(nodeId)) return; setSeenNodes((prev) => new Set(prev).add(nodeId)); void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined); }; /** Resolves the node's display strings server-side (flag tokens), appends the * line to the log, then types it out unless the player has the animation off. * Nodes without tokens skip the round trip and use their authored text. */ const typeIn = async (node: DialogueNode, token: number) => { let resolved: ResolvedNodeTexts | undefined; if ( collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0 || node.data.voice ) { if (dialogueId === null) return; const res = await resolveNpcDialogueTexts(dialogueId, Number(npc.id), node.id); if (sessionRef.current !== token) return; if (res.success && res.data) resolved = res.data; } const text = displayText(node, resolved); const id = nextId(); const total = visibleLength(text); // Start the clip before the line lands so the first word is not late. A // rejected play() (autoplay policy) marks the entry so it can offer a // button instead of failing silently. const voiceUrl = resolved?.voice?.url; let voiceStarted = false; let clipSeconds = 0; if (voiceUrl && soundOnRef.current && audioRef.current) { const audio = audioRef.current; audio.src = playableUrl(voiceUrl); audio.currentTime = 0; try { await audio.play(); voiceStarted = true; setPlaying({ id, ratio: 0 }); clipSeconds = await clipDuration(audio); } catch { voiceStarted = false; setPlaying(null); } } // Nothing to animate for an empty line, and a reduced-motion device skips // the animation outright. Only the NPC's spoken lines type: choice lead-ins, // event lines, descriptive narration and end closings are the interface's // own voice, and they land whole so the footer never waits on prose the // player is not being spoken to by. const animate = typewriter && node.type === "dialogue" && total > 0 && !prefersReducedMotion(); // The schedule is already a duration in milliseconds (one base cost per // unit plus its pauses), so a preset's pause values mean what they say. A // clip takes over as the target and the schedule is scaled to fit it, which // keeps text and speech together. Only a very long line is compressed, by // the cap. const unscaled = buildRevealSchedule(text); const durationMs = voiceStarted && clipSeconds > 0.4 ? Math.min(60_000, clipSeconds * 1000) : Math.min(REVEAL_CAP_MS, unscaled.total); setLog((prev) => [ ...prev, { kind: "node", id, node, resolved, text, reveal: animate ? 0 : undefined, voiceUrl, voiceBlocked: Boolean(voiceUrl && !voiceStarted && soundOnRef.current), }, ]); markSeen(node.id); // Fetch the next line's clip now, while this one is still being read. const nextTarget = node.data.next?.target; const nextNode = nextTarget ? flow?.nodes.find((candidate) => candidate.id === nextTarget) : null; const nextFilename = nextNode?.data.voice?.filename; if (nextFilename) preloadClip(`/api/media/file/${nextFilename}`); if (!animate) return; const setReveal = (shown: number | undefined) => setLog((prev) => prev.map((entry) => entry.kind === "node" && entry.id === id ? { ...entry, reveal: shown } : entry, ), ); setStreamingId(id); skipRevealRef.current = null; // A schedule, not a fixed tick per character: the line arrives on its own // timing, with a pause after punctuation and line breaks. It is built in // relative units and scaled here, so a recorded line keeps the rhythm and // only stretches. Ticks are precomputed from the same schedule (seeded, so // a re-render cannot re-roll the rhythm) and fire as the reveal crosses them. const schedule = scaleSchedule(unscaled, durationMs); const unitCount = Math.min(total, schedule.arrivalMs.length); const ticking = typewriterSound && soundOnRef.current && !voiceStarted; let tickIndex = 0; let shown = 0; const startedAt = performance.now(); try { for (;;) { if (sessionRef.current !== token) return; if (skipRevealRef.current === id) break; const elapsed = performance.now() - startedAt; if (ticking) { while ( tickIndex < schedule.tickMs.length && schedule.tickMs[tickIndex] <= elapsed ) { playTypeTick(); tickIndex += 1; } } const next = Math.min(unitCount, shownAt(schedule.arrivalMs, elapsed)); if (next !== shown) { shown = next; setReveal(shown); } if (shown >= unitCount) break; await sleep(24); } } finally { // Land on the full line whether it finished, was skipped, or the dialog // closed mid-reveal (the session check above returns through here). setReveal(undefined); setStreamingId((current) => (current === id ? null : current)); } }; /** The beat between two lines: the speaker's typing dots, then the next line. * The gap is what gives the player a moment to finish reading; a click during * it starts the next line at once, the same way clicking a line finishes it. */ const beatThen = async (node: DialogueNode, token: number) => { skipBeatRef.current = false; setTyping(node.data.speaker?.trim() || npc.name); const wait = beatMs(); const startedAt = performance.now(); try { while (performance.now() - startedAt < wait) { if (sessionRef.current !== token || skipBeatRef.current) break; await sleep(40); } } finally { skipBeatRef.current = false; if (sessionRef.current === token) setTyping(null); } }; // Opening the conversation walks the start node and auto-advances through // linear dialogue/event nodes, so the player lands on the first interactive // node (a choice, an end, or a dead end) without clicking Continue. Each // line arrives after its own typing delay. const begin = () => { const token = ++sessionRef.current; audioRef.current?.pause(); // Opening the conversation is a user gesture, the only moment a browser // will let us create and resume the audio context. Without it the typing // sound stays silent for the whole conversation. primeTypeSound(); skipBeatRef.current = false; followRef.current = true; setLog([]); setTyping(null); setPlayerTyping(false); setStreamingId(null); setTakenChoices(new Set()); setChoiceGates({}); setOpen(true); if (!flow.startId) return; void (async () => { const start = flow.nodes.find((n) => n.id === flow.startId) ?? null; if (start) await cascadeFrom(start, token); })(); }; /** Types `start`, then auto-advances through linear dialogue/event/delay/ * condition nodes so the player always lands on the next interactive node * (a choice or an end). Delay nodes pause the conversation; condition nodes * branch on the player's flags, evaluated server-side. Neither is logged. */ const cascadeFrom = async (start: DialogueNode, token: number) => { let current: DialogueNode | null = start; const seen = new Set(); while (current && !seen.has(current.id) && sessionRef.current === token) { seen.add(current.id); if (current.type === "delay") { const seconds = Math.min(30, Math.max(0.5, current.data.delaySeconds ?? 2)); setTyping(""); await sleep(seconds * 1000); if (sessionRef.current !== token) return; setTyping(null); const target: string | undefined = current.data.next?.target; current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null; continue; } if (current.type === "condition") { if (dialogueId === null) return; const result = await evaluateNpcDialogueCondition( dialogueId, Number(npc.id), current.id, ); if (sessionRef.current !== token) return; const branch = result.success && result.data ? current.data.trueTarget : current.data.falseTarget; current = branch ? (flow.nodes.find((n) => n.id === branch) ?? null) : null; continue; } await typeIn(current, token); if (sessionRef.current !== token) return; if (current.type === "dialogue" || current.type === "event") { if (current.type === "event" && current.data.effect) { // Await the effect so flags it writes are visible to the lines // that follow (interpolated text and later condition nodes). if (dialogueId !== null) { await triggerNpcDialogueEvent(dialogueId, Number(npc.id), current.id).catch( () => undefined, ); } if (sessionRef.current !== token) return; } const target: string | undefined = current.data.next?.target; const nextNode = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null; // A beat before the next spoken line. The opening line of a cascade // never gets one, because no hop precedes it: the player just opened // the conversation, or just sent a line of their own. The typing dots // keep the gap from reading as a hang, and a click during it skips it. if ( nextNode && typewriter && nextNode.type === "dialogue" && (nextNode.data.body ?? "").trim().length > 0 && !prefersReducedMotion() ) { await beatThen(nextNode, token); if (sessionRef.current !== token) return; } current = nextNode; } else { current = null; } } }; /** Digits pick a choice, Enter or Space finishes the line that is typing (or * starts the next one during the beat). Attached to the dialog's content, so * it only acts when focus is inside the conversation, and it steps aside for * a focused control, where the browser's own activation is correct. */ const onConversationKeyDown = (event: React.KeyboardEvent) => { if (event.metaKey || event.ctrlKey || event.altKey) return; const target = event.target as HTMLElement | null; if (target?.closest("button, a, input, select, textarea, [role='button']")) return; const choiceIndex = choiceIndexFromKey(event.key, selectableChoices.length); if (choiceIndex !== null) { const choice = selectableChoices[choiceIndex]; if (choice) { event.preventDefault(); pick(choice.hop, choice.index, choiceLabel(choice.hop, choice.index)); } return; } if (!isSkipKey(event.key)) return; if (streamingId) { event.preventDefault(); skipRevealRef.current = streamingId; } else if (typing !== null) { event.preventDefault(); skipBeatRef.current = true; } }; const close = () => { sessionRef.current += 1; audioRef.current?.pause(); setTyping(null); setPlayerTyping(false); setStreamingId(null); setOpen(false); }; const lastNode = [...log].reverse().find((entry) => entry.kind === "node"); // The player's line types out (shorter than NPC pacing), lands, and then // 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") { const key = `${lastNode.node.id}:${choiceIndex}`; setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key))); } void (async () => { setPlayerTyping(true); await sleep(Math.min(1100, 300 + text.length * 16) * (0.85 + Math.random() * 0.3)); if (sessionRef.current !== token) return; setPlayerTyping(false); setLog((prev) => [...prev, { kind: "player", id: nextId(), text }]); const target = flow.nodes.find((n) => n.id === hop.target); if (target) await cascadeFrom(target, token); })(); }; // The choices offered by the node the log currently rests on. One-time // choices the player already took are hidden; if that empties the list the // footer falls back to the End conversation button so nobody gets stuck. const choiceNode = lastNode && lastNode.kind === "node" && lastNode.node.type === "choice" ? lastNode.node : null; const visibleChoices = choiceNode ? (choiceNode.data.choices ?? []).reduce< { hop: DialogueNext; index: number; locked: boolean }[] >((acc, hop, index) => { if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc; if (!hop.condition || hasEmptyConditionKey(hop.condition)) { acc.push({ hop, index, locked: false }); return acc; } // Gated choices stay hidden until the server confirms them; a failing // gate with an authored hint renders the choice locked instead. const gate = choiceGates[choiceNode.id]?.[index]; if (!gate) return acc; if (gate.pass) acc.push({ hop, index, locked: false }); else if (gate.showLocked) acc.push({ hop, index, locked: true }); return acc; }, []) : []; const anySelectableChoice = visibleChoices.some((choice) => !choice.locked); /** Only the choices a keypress may take. Numbering and the keyboard both run * off this list, so a locked option never consumes a digit. */ const selectableChoices = visibleChoices.filter((choice) => !choice.locked); /** The node whose options belong on screen. Null while anything is still * arriving, which is what opens and closes the footer: the row animates from * 0fr to 1fr, so the menu slides in instead of the text jumping. */ const footerNode = (() => { if (typing !== null || playerTyping || streamingId !== null) return null; if (!lastNode || lastNode.kind !== "node") return null; const node = lastNode.node; return node.type === "choice" || node.type === "end" ? node : null; })(); /** 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(() => { if (followRef.current) scrollToEnd(); }, [log, typing, playerTyping, open, streamingId, visibleChoices.length]); // 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(() => { if (!scroller || typeof ResizeObserver === "undefined") return; const content = contentRef.current; const observer = new ResizeObserver(() => { if (followRef.current) scrollToEnd(); }); 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 * node's strings contained flag tokens, the raw label otherwise. */ const choiceLabel = (hop: DialogueNext, index: number): string => ((lastNode?.kind === "node" ? lastNode.resolved?.labels?.[index] : undefined) ?? hop.label) || "…"; /** Rich hover tooltip for a choice (resolved like labels); undefined when * the author left it empty. */ const choiceTooltip = (hop: DialogueNext, index: number): string | undefined => { const raw = (lastNode?.kind === "node" ? lastNode.resolved?.tooltips?.[index] : undefined) ?? hop.tooltip; return raw?.trim() ? raw : undefined; }; /** Tooltip for a locked choice (resolved like labels); generic fallback * when the author left the hint blank. */ const choiceHint = (hop: DialogueNext, index: number): string => { const raw = (lastNode?.kind === "node" ? lastNode.resolved?.hints?.[index] : undefined) ?? hop.lockedHint; return raw?.trim() ? raw : "Locked."; }; return ( <> {unseenTargets.size > 0 && ( New )} !next && close()}>
Conversation // {npc.name}
{/* One element for every clip: starting a line stops the previous one and keeps the browser's autoplay permission for the session. */}
); } /** * A line that may still be typing. * * The visible copy truncates character by character, which is exactly what a * live region must not be fed: it would announce a stutter of fragments. So * while a reveal is running the visible text is hidden from assistive tech and * the whole sentence sits in an `sr-only` copy that never changes. A screen * reader therefore gets the line once, in full, at the moment it arrives. */ function RevealingText({ text, reveal }: { readonly text: string; readonly reveal?: number }) { if (reveal === undefined) return ; return ( <> {visibleText(text)} ); } function TimelineEntry({ entry, speakerDefault, onPlayVoice, playingRatio, }: { entry: LogEntry; speakerDefault: string; onPlayVoice?: (url: string) => void; /** How far through this line's clip playback is, or null when it is silent. */ playingRatio?: number | null; }) { if (entry.kind === "player") { return (
You

); } const { node, resolved, text, reveal } = entry; /** Replay for a line that has a clip and played normally. Autoplay-blocked * lines keep the louder "Play voice" button instead. */ const replayButton = entry.kind === "node" && entry.voiceUrl && !entry.voiceBlocked && onPlayVoice ? ( ) : null; /** A hairline under the line, filling as the clip plays, so a long read has * visible progress instead of only audio. */ const voiceProgress = playingRatio === null || playingRatio === undefined ? null : ( ); /** A clip the browser refused to autoplay gets a button rather than nothing. */ const voiceFallback = entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? ( ) : null; if (node.type === "event") { if (node.data.presentation === "narration") { // Descriptive narrative: the narrator's voice, not the NPC's. Centered // and muted with no accent bar so it reads as scene-setting rather than // as something the contact said. return (

{voiceProgress} {replayButton} {voiceFallback}
); } // Narration: no speaker, styled like a mission briefing line. return (

{voiceProgress} {replayButton} {voiceFallback}
); } if (node.type === "end") { return (

{voiceProgress} {replayButton} {voiceFallback}
); } if (node.type === "choice") { // The choice buttons live in the footer; only the lead-in joins the log. if (!text) return null; return (

); } const speaker = node.data.speaker?.trim() || speakerDefault; return (
{speaker} {replayButton}

{text ? ( ) : ( … )}

{voiceProgress} {voiceFallback}
); } /** Three bouncing dots while a line is "typing". `player` renders the * right-aligned cyan variant for the player's incoming response. */ function TypingIndicator({ speaker, player }: { speaker?: string; player?: boolean }) { return (
{player ? ( You ) : speaker ? ( {speaker} ) : null} {[0, 150, 300].map((delay) => ( ))}
); }