1
0
Fork 0

feat(npc-dialogue): hold a line until the player presses Continue

A conversation always advanced on its own once a line finished, so an author had
no way to let a line sit while the player reads it, or to pace a quiet moment.

Dialogue nodes now carry an optional requireContinue flag, off by default. The
line types and plays its clip as usual, then the footer offers a single Continue
button instead of moving on. Enter and Space resume it too.

waitsForContinue in dialogue.ts is the only place the rule lives: the flag must
be on and the node must have a successor, because a dead end would give the
player a button that does nothing. The runtime and the editor's draft preview
both call it, and the canvas card tags such a node continue.

The cascade parks on a promise rather than returning, so Continue resumes the
same walk and the next line still gets its beat between lines. close() and
begin() release a parked promise, so a conversation closed mid-gate cannot leave
a suspended walk behind; the existing token check makes the stale one return.

Also in this change, from the same request: the draft preview is centred
vertically instead of pinned to the top, and gains a Back button that pops a
trail of the cards walked through. The trail is separate from the visited set so
stepping back does not un-spend a once choice.

Verified with a three-line probe document: the gated first line was still alone
in the log after 3.7s with a Continue button showing, clicking it landed the
ungated second line and parked on the gated third, and Enter from there reached
the end node. In the editor, the panel measured 0px off centre and Back returned
to the previous card. 4 pure tests cover the rule; 212 tests pass across 19 files.
This commit is contained in:
Jason Fraley 2026-11-30 18:04:02 -05:00
parent 5032956da7
commit 90037711e2
7 changed files with 204 additions and 12 deletions

View file

@ -16,11 +16,11 @@
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import { PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
import { ArrowLeftIcon, PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import type { DialogueCondition, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { findStartNode, waitsForContinue } from "@/lib/npc-dialogue/dialogue";
import {
automaticTarget,
describeCondition,
@ -55,9 +55,10 @@ export function DialoguePreviewDialog({
const start = useMemo(() => findStartNode(flow.nodes as DialogueNode[]), [flow.nodes]);
const [currentId, setCurrentId] = useState<string | null>(start?.id ?? null);
const [visited, setVisited] = useState<string[]>([]);
/** Every hop taken, including revisits, so the footer counts what happened
* rather than how many distinct cards it saw. */
const [steps, setSteps] = useState(0);
/** The cards walked through, oldest first, which is what Back pops. Kept
* separately from `visited` because Back must return to where the player came
* from while `visited` keeps remembering that a `once` choice was spent. */
const [trail, setTrail] = useState<string[]>([]);
/** Gate answers for condition nodes, keyed by node id, so a step is not
* re-evaluated on every render. */
const [gates, setGates] = useState<Record<string, boolean>>({});
@ -70,7 +71,7 @@ export function DialoguePreviewDialog({
const reset = useCallback(() => {
setCurrentId(findStartNode(flow.nodes as DialogueNode[])?.id ?? null);
setVisited([]);
setSteps(0);
setTrail([]);
setGates({});
setGateErrors(null);
}, [flow.nodes]);
@ -149,11 +150,20 @@ export function DialoguePreviewDialog({
const go = (target: string | null) => {
if (!target) return;
setTrail((current) => (currentId ? [...current, currentId] : current));
setVisited((current) => (current.includes(target) ? current : [...current, target]));
setSteps((current) => current + 1);
setCurrentId(target);
};
/** Step back one card. Nothing is popped from `visited`, so a `once` choice
* taken on the way out stays taken: Back rewinds the walk, not the world. */
const back = () => {
const previous = trail[trail.length - 1];
if (previous === undefined) return;
setTrail((current) => current.slice(0, -1));
setCurrentId(previous);
};
/** A `once` choice is spent if its target was already visited this run, which
* is the closest the preview can get to the runtime's per-player bookkeeping.
* A gated choice is unavailable when the author's own flags fail its gate. */
@ -168,7 +178,7 @@ export function DialoguePreviewDialog({
};
return (
<div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/70 p-6">
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/70 p-6">
<div className="flex max-h-[80vh] w-full max-w-xl flex-col overflow-hidden rounded-md border border-white/20 bg-zinc-900 text-white shadow-2xl">
<div className="flex items-center gap-2 border-b border-white/10 px-4 py-2">
<PlayIcon className="size-3.5 text-cyan-300" />
@ -176,10 +186,19 @@ export function DialoguePreviewDialog({
Draft preview
</span>
<span className="truncate text-xs text-white/40">{contactName || "unassigned contact"}</span>
<button
type="button"
onClick={back}
disabled={trail.length === 0}
aria-label="Back one step"
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-white/15 disabled:hover:text-white/60"
>
<ArrowLeftIcon className="size-2.5" /> Back
</button>
<button
type="button"
onClick={reset}
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200"
className="inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200"
>
<RotateCcwIcon className="size-2.5" /> Restart
</button>
@ -214,6 +233,7 @@ export function DialoguePreviewDialog({
</span>
<span className="truncate">{node.id}</span>
{node.data.presentation === "narration" && <span>narration</span>}
{waitsForContinue(node) && <span className="text-cyan-300/80">continue gate</span>}
</div>
{step.speaker && (
@ -353,7 +373,7 @@ export function DialoguePreviewDialog({
</div>
<div className="border-t border-white/10 px-4 py-2 font-mono text-[9px] uppercase tracking-widest text-white/35">
{steps} step{steps === 1 ? "" : "s"} walked, {visited.length} card
{trail.length} step{trail.length === 1 ? "" : "s"} deep, {visited.length} card
{visited.length === 1 ? "" : "s"} visited. Text shows tokens as
authored; the player sees them resolved.
</div>

View file

@ -324,6 +324,28 @@ export function NodeEditDialog({
</div>
)}
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<label className="flex cursor-pointer items-center gap-2 text-xs text-white/70">
<Checkbox
checked={draft.requireContinue === true}
onCheckedChange={(checked) =>
// Unset rather than false: an absent key is the default and
// keeps stored flowData free of noise.
patch({ requireContinue: checked === true ? true : undefined })
}
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
/>
Wait for Continue before the next line
</label>
<p className="text-[10px] text-white/40">
The line types (and speaks, if it has a clip) and then holds until the player
presses Continue. Off by default so a conversation still reads as a flow. Has no
effect on a line with nowhere to go.
</p>
</div>
)}
{node.type === "choice" && (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">

View file

@ -67,6 +67,14 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
start
</span>
)}
{nodeType === "dialogue" && d.requireContinue === true && (
<span
title="Waits for the player to press Continue"
className={`${d.isStart ? "" : "ml-auto"} font-mono text-[8px] uppercase tracking-widest text-cyan-300/80`}
>
continue
</span>
)}
</div>
{/* Choice/condition cards must not clip their per-output handles, which

View file

@ -18,7 +18,11 @@ import {
} 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 {
findStartNode,
hasEmptyConditionKey,
waitsForContinue,
} from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
import { Button } from "@/components/ui/button";
import {
@ -486,6 +490,8 @@ export function NpcConversation({
setStreamingId(null);
setTakenChoices(new Set());
setChoiceGates({});
setAwaitingContinueId(null);
continueResolverRef.current = null;
setOpen(true);
if (!flow.startId) return;
void (async () => {
@ -544,6 +550,19 @@ export function NpcConversation({
}
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
@ -565,6 +584,20 @@ export function NpcConversation({
}
};
/** 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);
/** 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
@ -585,6 +618,11 @@ export function NpcConversation({
}
if (!isSkipKey(event.key)) return;
if (awaitingContinueId) {
event.preventDefault();
resumeContinue();
return;
}
if (streamingId) {
event.preventDefault();
skipRevealRef.current = streamingId;
@ -596,6 +634,9 @@ export function NpcConversation({
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);
@ -659,6 +700,11 @@ export function NpcConversation({
* 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. */
@ -931,10 +977,21 @@ export function NpcConversation({
<div
data-footer="choices"
className={`grid shrink-0 overflow-hidden transition-[grid-template-rows] duration-300 ease-out motion-reduce:transition-none ${
footerNode ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
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 && (

View file

@ -302,6 +302,10 @@ Two traps specific to this component, both costs of rendering inside the admin:
editor's depth. It falls back to `contact <id>`, which is honest; do not try to
fetch the name here.
The panel is centred vertically and keeps a `trail` of the cards walked through:
`Back` pops it. `visited` is deliberately separate, so stepping back rewinds the
walk without un-spending a `once` choice the player already took.
`once` choices are treated as spent once their target was visited in this run,
which is the closest the preview gets to the runtime's per-player bookkeeping.
The preview never writes read markers, so it cannot make a conversation look read.
@ -330,6 +334,26 @@ markers for the offered ones), plus one flag evaluation per NPC that has a gated
conversation. The page swallows loader errors and renders no chips rather than
failing the directory.
### The Continue gate
`data.requireContinue` (dialogue node, off by default) parks the conversation on
a line: it types and plays its clip, then the footer shows a single Continue
button instead of advancing. `waitsForContinue` in `dialogue.ts` is the only
place the rule lives (flag on **and** a successor exists; on a dead end the
button would be a dead control, so the flag is ignored), and both the runtime and
the editor preview call it.
The cascade does not return on a gate; it awaits a promise held in
`continueResolverRef`, so pressing Continue resumes the same walk and the next
line still gets its beat (`beatThen`). Enter or Space resumes too, unless focus is
on a control. `close()` and `begin()` resolve any parked promise so a closed
conversation cannot leave a suspended async walk behind, and the token check
after the await makes the stale one return.
Verified with a three-line probe document: the gated first line was still alone in
the log after 3.7s with a Continue button, clicking it landed the ungated second
line and parked on the gated third, and Enter from there reached the end node.
### The conversation frame
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that

View file

@ -233,6 +233,14 @@ export type DialogueNodeData = {
* NPC is not saying out loud. Ignored by every other node type.
*/
presentation?: "event" | "narration";
/**
* Hold the conversation on this line until the player presses Continue,
* instead of advancing when the line (and its clip) finish. Off by default:
* a conversation reads as a flow, and a gate on every line would make it a
* slideshow. Ignored on a node with nowhere to go, because there would be
* nothing to continue to.
*/
requireContinue?: boolean;
/** Branching options (choice nodes). */
choices?: DialogueNext[];
/** Optional lead-in text before the choices. */
@ -519,6 +527,17 @@ export function conditionSummary(condition: DialogueCondition): string {
return leaf(condition);
}
/**
* Whether the conversation must wait for the player here.
*
* A gate only means something when the node has a successor: on a dead end the
* Continue button would be a dead control, so the flag is ignored there rather
* than shown and refused.
*/
export function waitsForContinue(node: DialogueNode): boolean {
return node.data.requireContinue === true && Boolean(node.data.next?.target);
}
/** True when any leaf of the condition (including inside a group) lacks a key. */
export function hasEmptyConditionKey(condition: DialogueCondition): boolean {
if (condition.kind === "group") {

View file

@ -0,0 +1,42 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { waitsForContinue } from "@/lib/npc-dialogue/dialogue";
/**
* The Continue gate is off unless an author turns it on, and it only means
* something where a successor exists. Both facts are one function so the
* runtime and the editor's draft preview cannot disagree.
*/
function node(data: Record<string, unknown>, type: DialogueNode["type"] = "dialogue"): DialogueNode {
return { id: "n1", type, position: { x: 0, y: 0 }, data } as DialogueNode;
}
describe("continue gate", () => {
it("is off by default", () => {
expect(waitsForContinue(node({ body: "Hello." }))).toBe(false);
expect(waitsForContinue(node({ body: "Hello.", next: { target: "n2" } }))).toBe(false);
});
it("holds a line that has somewhere to go", () => {
expect(
waitsForContinue(node({ body: "Hello.", requireContinue: true, next: { target: "n2" } })),
).toBe(true);
});
it("ignores the flag on a dead end, where there is nothing to continue to", () => {
expect(waitsForContinue(node({ body: "Hello.", requireContinue: true }))).toBe(false);
expect(
waitsForContinue(node({ body: "Hello.", requireContinue: true, next: { target: "" } })),
).toBe(false);
});
it("applies to any node type that carries a continuation", () => {
expect(
waitsForContinue(
node({ body: "A scene.", requireContinue: true, next: { target: "n2" } }, "event"),
),
).toBe(true);
});
});