1
0
Fork 0
polaris-task-force/src/components/frontend/personnel/NpcConversation.tsx
Z8MB1E c05ef12110 feat(polls): raise a unit poll from an NPC dialogue event node
A fifth effect type, `poll`, alongside notify/emit/reward/flag. The node holds
only the authoring config; the poll itself is a document created on first
trigger, so the conversation cannot rewrite a live poll.

- Node editor: question, context, options (keys derived from the labels, so two
  options that read the same still get distinct keys), duration, multi-select,
  anonymity, role eligibility, weight tiers and the result flag. Role pickers
  are native checkboxes: the admin bundle never loads the frontend stylesheet,
  so portaled selects render unstyled and only respond to the keyboard.
- The effect is idempotent by construction: a player who reaches the node twice
  gets the same poll back, and the action returns its id.
- The conversation keeps a link to the poll it raised, so the player does not
  have to hunt for it in the notification inbox.
- Drafts can never emit a poll: the generation schema only allows none/flag/
  notify, and the validator rejects anything else.
2026-12-01 14:17:40 -05:00

1305 lines
54 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState, Fragment } from "react";
import Link from "next/link";
import {
LockIcon,
MessageCircleIcon,
Volume2Icon,
VolumeXIcon,
VoteIcon,
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,
lineDurationMs,
buildRevealSchedule,
scaleSchedule,
shownAt,
} from "@/lib/npc-dialogue/pacing";
import type { PacingPreset } from "@/lib/npc-dialogue/pacing";
import { playTypeTick, primeTypeSound } from "@/lib/npc-dialogue/typeSound";
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import {
findStartNode,
hasEmptyConditionKey,
waitsForContinue,
} 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;
/** Typing speed and punctuation pauses, chosen in the admin panel. Resolved
* server-side so the dialog needs no round trip for it. */
readonly pacing?: PacingPreset;
}
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<void>((resolve) => setTimeout(resolve, ms));
/* Line duration lives in pacing.ts (`lineDurationMs`): the 3s ceiling that used
* to sit here compressed every line past about 120 characters, down to 8ms per
* character on a long one, which is why the typing felt faster the deeper a
* conversation went. */
/** 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<number> {
if (Number.isFinite(audio.duration) && audio.duration > 0) return audio.duration;
return await new Promise<number>((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,
pacing = DEFAULT_PACING_PRESET,
}: NpcConversationProps) {
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
const [open, setOpen] = useState(false);
const [log, setLog] = useState<LogEntry[]>([]);
/** Speaker label while the NPC types; "" for speaker-less narration. */
const [typing, setTyping] = useState<string | null>(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<string | null>(null);
/** Set by clicking the log: finish the line instead of waiting. */
const skipRevealRef = useRef<string | null>(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<HTMLAudioElement | null>(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<Map<string, string>>(new Map());
const clipPendingRef = useRef<Set<string>>(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<Set<string>>(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<Record<string, ChoiceGate[]>>({});
/** 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<Set<string>>(
() => new Set(initialSeenNodeIds ?? []),
);
const seq = useRef(0);
const sessionRef = useRef(0);
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++}`;
/** 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, pacing);
const voicedMs =
voiceStarted && clipSeconds > 0.4 ? Math.min(60_000, clipSeconds * 1000) : null;
const durationMs = lineDurationMs(unscaled, voicedMs);
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(pacing);
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({});
setAwaitingContinueId(null);
continueResolverRef.current = null;
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<string>();
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) {
const result = await triggerNpcDialogueEvent(
dialogueId,
Number(npc.id),
current.id,
).catch(() => null);
// A poll effect hands back the poll it opened (or joined).
if (result?.success && result.data?.pollId) {
setRaisedPollId(result.data.pollId);
}
}
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;
// Authors can hold a line until the player is ready. The cascade parks
// here rather than returning, so pressing Continue resumes the same
// walk and the next line still gets its beat.
if (waitsForContinue(current) && nextNode) {
setAwaitingContinueId(current.id);
await new Promise<void>((resolve) => {
continueResolverRef.current = resolve;
});
if (sessionRef.current !== token) return;
setAwaitingContinueId(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;
}
}
};
/** The line the conversation is parked on, waiting for Continue. The cascade
* awaits a promise this ref resolves, so the walk resumes exactly where it
* stopped (including the beat before the next spoken line). */
const [awaitingContinueId, setAwaitingContinueId] = useState<string | null>(null);
const continueResolverRef = useRef<(() => void) | null>(null);
/** Poll raised by an event node in this conversation. The notification is the
* durable path; this link keeps the player from having to leave the dialog
* and find it in their inbox. */
const [raisedPollId, setRaisedPollId] = useState<number | null>(null);
/** Let the parked cascade continue. Idempotent: a second press finds no
* resolver and does nothing. */
const resumeContinue = () => {
const resolve = continueResolverRef.current;
continueResolverRef.current = null;
resolve?.();
};
/** 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<HTMLDivElement>) => {
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 (awaitingContinueId) {
event.preventDefault();
resumeContinue();
return;
}
if (streamingId) {
event.preventDefault();
skipRevealRef.current = streamingId;
} else if (typing !== null) {
event.preventDefault();
skipBeatRef.current = true;
}
};
const close = () => {
sessionRef.current += 1;
// Release a parked cascade so it wakes, sees the stale token and returns.
resumeContinue();
setAwaitingContinueId(null);
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 line holding the conversation open, waiting for Continue. */
const awaitingNode = awaitingContinueId
? (flow.nodes.find((node) => node.id === awaitingContinueId) ?? null)
: null;
/** 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 (
<>
<span className="relative inline-flex">
<Button
onClick={begin}
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
>
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
</Button>
{unseenTargets.size > 0 && (
<span
aria-label="New or updated dialogue"
className="pointer-events-none absolute -right-1.5 -top-1.5 z-10 rounded-sm bg-cyan-400 px-1 py-px font-mono text-[9px] font-bold uppercase leading-none text-black"
>
New
</span>
)}
</span>
<Dialog open={open} onOpenChange={(next) => !next && close()}>
<DialogContent
showCloseButton={false}
onKeyDown={onConversationKeyDown}
className={`flex w-[calc(100%-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:w-full sm:rounded-none ${
// A frame of fixed height. The dialog used to size itself to its
// content, so the choice footer appearing made it taller, and being
// vertically centred made the whole box jump up and down. With a
// fixed height the window never moves: the log gives up space and
// scrolls instead, and a long choice list scrolls inside its own
// band rather than shrinking the conversation to nothing.
flow.startId === null ? "" : "h-[min(80dvh,36rem)]"
}`}
>
<div className={`relative flex items-center justify-between ${DOSSIER.strip}`}>
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Conversation // {npc.name}
</DialogTitle>
<div className="flex shrink-0 items-center gap-3">
<button
type="button"
onClick={() => {
const next = !soundOn;
setSoundOn(next);
if (!next) {
// Muting mid-line silences the clip immediately; the reveal
// keeps its current pace.
audioRef.current?.pause();
setPlaying(null);
}
}}
aria-pressed={!soundOn}
aria-label={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
title={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
className="text-white/40 transition-colors hover:text-white/90"
>
{soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />}
</button>
<button
type="button"
onClick={close}
aria-label="Close conversation"
className="text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
</div>
<span
aria-hidden
className="pointer-events-none absolute inset-0 opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
</div>
{/* One element for every clip: starting a line stops the previous one
and keeps the browser's autoplay permission for the session. */}
<audio
ref={audioRef}
preload="none"
className="hidden"
onTimeUpdate={(event) => {
const audio = event.currentTarget;
if (!audio.duration || !Number.isFinite(audio.duration)) return;
const ratio = audio.currentTime / audio.duration;
setPlaying((current) => (current ? { ...current, ratio } : current));
}}
onEnded={() => setPlaying(null)}
/>
{flow.startId === null ? (
<div className="p-5 text-sm text-white/50">
This conversation has no start node. Ask staff to configure it.
</div>
) : (
<>
<div
ref={attachScroller}
onClick={() => {
// A click anywhere in the log finishes the line that is
// typing, or starts the next one when the beat is showing,
// rather than leaving the player to wait either out.
if (streamingId) skipRevealRef.current = streamingId;
else skipBeatRef.current = true;
}}
data-log="conversation"
role="log"
aria-live="polite"
aria-relevant="additions"
aria-busy={streamingId !== null || typing !== null || playerTyping}
aria-label={`Conversation with ${npc.name}`}
className="min-h-0 flex-1 overflow-y-auto p-5"
>
{/* Bottom-anchored like a messenger: a short conversation sits
just above its choices instead of floating in a tall empty
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. */}
<div
ref={contentRef}
className="flex min-h-full flex-col justify-end gap-3"
>
{log.map((entry) => (
<TimelineEntry
key={entry.id}
entry={entry}
speakerDefault={npc.name}
playingRatio={playing?.id === entry.id ? playing.ratio : null}
onPlayVoice={(url) => {
// Explicit click: always allowed, and clears the notice.
const audio = audioRef.current;
if (!audio) return;
audio.src = playableUrl(url);
audio.currentTime = 0;
setPlaying({ id: entry.id, ratio: 0 });
void audio
.play()
.then(() =>
setLog((prev) =>
prev.map((e) =>
e.kind === "node" && e.id === entry.id
? { ...e, voiceBlocked: false }
: e,
),
),
)
.catch(() => undefined);
}}
/>
))}
{typing !== null && <TypingIndicator speaker={typing} />}
{playerTyping && <TypingIndicator player />}
</div>
</div>
{/* A conversation that raised a poll leaves a way back to it. The
notification is the durable path; this keeps the player in
the dialog without having to hunt for it. */}
{raisedPollId !== null && (
<div className="shrink-0 border-t border-cyan-500/30 bg-cyan-500/5 px-4 py-2">
<Link
href={`/polls/${raisedPollId}`}
className="flex items-center gap-2 text-xs text-cyan-300 underline-offset-4 hover:underline"
>
<VoteIcon className="size-3.5 shrink-0" />
The unit is being polled on this. Open the poll.
</Link>
</div>
)}
{/* The footer opens by growing its grid row, so the menu slides in
and the log above it gives up height over the same 260ms
instead of the text jumping up in one frame. Always mounted so
the transition has something to animate; `motion-reduce`
collapses the timing to nothing. */}
<div
data-footer="choices"
className={`grid shrink-0 overflow-hidden transition-[grid-template-rows] duration-300 ease-out motion-reduce:transition-none ${
footerNode || awaitingNode ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
}`}
>
<div className="min-h-0">
{awaitingNode && (
<div className="border-t border-white/15 bg-black/50 p-4">
<Button
onClick={resumeContinue}
aria-keyshortcuts="Enter"
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
>
Continue
</Button>
</div>
)}
{footerNode && (
<div className="flex max-h-[260px] flex-col gap-2 overflow-y-auto border-t border-white/15 bg-black/50 p-4">
{footerNode.type === "choice" && visibleChoices.length > 0 && (
<TooltipProvider delayDuration={150}>
{visibleChoices.map(({ hop, index, locked }) => {
const isNew = unseenTargets.has(hop.target);
// The number matches the key that picks it; locked
// choices are unnumbered because no key reaches them.
const shortcut = locked
? null
: choiceShortcutLabel(
selectableChoices.findIndex((choice) => choice.index === index),
);
const button = (
<button
type="button"
disabled={locked}
onClick={() => pick(hop, index, choiceLabel(hop, index))}
aria-keyshortcuts={shortcut ?? undefined}
style={{ animationDelay: `${Math.min(index, 6) * 40}ms` }}
className={`w-full rounded-none border px-3 py-2 text-left text-sm transition-colors animate-in fade-in-0 slide-in-from-bottom-1 fill-mode-both duration-200 motion-reduce:animate-none ${
locked
? "cursor-not-allowed border-white/10 bg-black/20 text-white/35"
: "border-white/20 bg-black/40 text-white/80 hover:border-cyan-500/60 hover:text-white"
}`}
>
<span className="flex items-center gap-2">
{locked && (
<LockIcon className="size-3 shrink-0 text-amber-400/70" />
)}
{shortcut && (
<span
aria-hidden
className="shrink-0 rounded-sm border border-white/15 bg-black/40 px-1 font-mono text-[10px] leading-tight text-white/40"
>
{shortcut}
</span>
)}
<DialogueText text={choiceLabel(hop, index)} />
{isNew && !locked && (
<span className="ml-auto shrink-0 rounded-sm bg-cyan-400 px-1 font-mono text-[9px] font-bold uppercase leading-tight text-black">
New
</span>
)}
</span>
</button>
);
const tip = locked ? choiceHint(hop, index) : choiceTooltip(hop, index);
if (!tip) return <Fragment key={index}>{button}</Fragment>;
return (
<Tooltip key={index}>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={8}
className="max-w-xs rounded-none border border-white/20 bg-zinc-900 p-3 text-left text-sm font-normal leading-relaxed text-white/85"
>
<DialogueText text={tip} />
</TooltipContent>
</Tooltip>
);
})}
</TooltipProvider>
)}
{(footerNode.type === "end" || !anySelectableChoice) && (
<Button
onClick={close}
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
>
End conversation
</Button>
)}
</div>
)}
</div>
</div>
</>
)}
</DialogContent>
</Dialog>
</>
);
}
/**
* 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 <DialogueText text={text} />;
return (
<>
<span aria-hidden>
<DialogueText text={text} reveal={reveal} />
</span>
<span className="sr-only">{visibleText(text)}</span>
</>
);
}
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 (
<div className="flex flex-col items-end gap-1">
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
<p className="max-w-[85%] rounded-none border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-sm text-cyan-50">
<DialogueText text={entry.text} />
</p>
</div>
);
}
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 ? (
<button
type="button"
onClick={() => onPlayVoice(entry.voiceUrl as string)}
aria-label="Replay this line"
title="Replay this line"
className="inline-flex items-center gap-1 rounded-sm border border-white/10 bg-black/30 px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/40 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
>
<Volume2Icon className="size-2.5" />
Replay
</button>
) : 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 : (
<span aria-hidden className="mt-0.5 block h-px w-full bg-white/10">
<span
className="block h-full bg-cyan-400/70 transition-[width] duration-150 ease-linear"
style={{ width: `${Math.max(0, Math.min(1, playingRatio)) * 100}%` }}
/>
</span>
);
/** A clip the browser refused to autoplay gets a button rather than nothing. */
const voiceFallback =
entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? (
<button
type="button"
onClick={() => onPlayVoice(entry.voiceUrl as string)}
className="mt-1 inline-flex items-center gap-1.5 self-start rounded-sm border border-white/20 bg-black/40 px-2 py-1 font-mono text-[10px] uppercase tracking-wider text-white/70 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
>
<Volume2Icon className="size-3" />
Play voice
</button>
) : 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 (
<div className="flex flex-col items-center gap-2 py-1 text-center">
<p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55">
<RevealingText text={text} reveal={reveal} />
</p>
{voiceProgress}
{replayButton}
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}
// Narration: no speaker, styled like a mission briefing line.
return (
<div className="flex flex-col gap-1">
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<RevealingText text={text} reveal={reveal} />
</p>
{voiceProgress}
{replayButton}
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}
if (node.type === "end") {
return (
<div className="flex flex-col gap-1">
<p className="text-sm italic text-white/50">
<RevealingText text={text} reveal={reveal} />
</p>
{voiceProgress}
{replayButton}
{voiceFallback}
</div>
);
}
if (node.type === "choice") {
// The choice buttons live in the footer; only the lead-in joins the log.
if (!text) return null;
return (
<p className="text-sm italic text-white/60">
<RevealingText text={text} reveal={reveal} />
</p>
);
}
const speaker = node.data.speaker?.trim() || speakerDefault;
return (
<div className="flex flex-col gap-1">
<span className="flex items-center gap-2">
<span className={DOSSIER.readoutLabel}>{speaker}</span>
{replayButton}
</span>
<p className="text-sm text-white/90">
{text ? (
<RevealingText text={text} reveal={reveal} />
) : (
<span className="italic text-white/30">…</span>
)}
</p>
{voiceProgress}
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}
/** 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 (
<div className={`flex flex-col gap-1 ${player ? "items-end" : ""}`}>
{player ? (
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
) : speaker ? (
<span className={DOSSIER.readoutLabel}>{speaker}</span>
) : null}
<span
className={`flex items-center gap-1 py-1 ${player ? "justify-end" : ""}`}
role="status"
aria-label={player ? "You are typing" : "typing"}
>
{[0, 150, 300].map((delay) => (
<span
key={delay}
className={`size-1.5 animate-bounce rounded-full ${player ? "bg-cyan-300/80" : "bg-cyan-400/70"}`}
style={{ animationDelay: `${delay}ms` }}
/>
))}
</span>
</div>
);
}