1
0
Fork 0

feat(npc-dialogue): play an unsaved draft in the editor

Authoring meant saving, leaving the admin, and finding the contact on the player
site to see whether a branch worked. A Play button in the canvas toolbar now
walks the draft exactly as it stands, without saving it.

The walker is not the runtime component: that resolves text and choices through
server actions keyed on a saved dialogue id, and teaching all four a draft mode
would be a much larger change. preview.ts answers what is local (choice order,
branch targets, effect descriptions) and the server answers the one thing it
cannot, flag values, through a new previewDialogueCondition action gated on
npc-dialogues:update. It calls the same evaluateCondition the player runtime
uses, so a preview cannot disagree with the outcome.

Effects are described, never applied. Choices the author's own flags would hide
are shown as hidden rather than silently dropped.

Verified on a temp document with an event effect and a condition node: the event
step showed 'Would set flag preview_probe_flag to true' with a dry-run note, the
condition answered false for a missing flag, the walk followed the false branch to
its END node, and player_flags gained no row (5 before, 5 after).

Bare admin buttons render with the UA's white background, so each one carries an
explicit background; 9 pure tests cover the walker's reading of the graph.
This commit is contained in:
Jason Fraley 2026-11-24 20:41:19 -05:00
parent 4dc82c0d5d
commit de765fe725
6 changed files with 790 additions and 1 deletions

View file

@ -0,0 +1,363 @@
"use client";
/**
* Walk an unsaved conversation draft in the editor.
*
* The player runtime reads the stored document, so a draft on the canvas cannot
* be played there: you have to save, leave the admin, and find the contact. This
* replays the graph as it stands right now, with real flag values from the
* server (`previewDialogueCondition`), and dry-runs effects instead of writing
* them.
*
* Deliberately not the runtime component: it resolves text and choices through
* server actions keyed on a saved dialogue id, and reusing it here would mean
* teaching four actions a draft mode. A small walker shows the same branch
* decisions, which is what an author is actually checking.
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import { 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 {
automaticTarget,
describeCondition,
isTerminal,
nodeForTarget,
previewStep,
} from "@/lib/npc-dialogue/preview";
import { previewDialogueCondition } from "./previewActions";
const NODE_LABEL: Record<string, string> = {
dialogue: "Dialogue",
choice: "Choice",
condition: "Condition",
event: "Event",
delay: "Delay",
end: "End",
};
interface DialoguePreviewDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
flow: FlowData;
contactName: string;
}
export function DialoguePreviewDialog({
open,
onOpenChange,
flow,
contactName,
}: DialoguePreviewDialogProps) {
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);
/** 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>>({});
const [gateErrors, setGateErrors] = useState<string | null>(null);
const [checking, setChecking] = useState(false);
/** Gate answers for conditional choices, keyed `<nodeId>:<index>`, so the
* preview disables a choice the runtime would hide. */
const [choiceGates, setChoiceGates] = useState<Record<string, boolean>>({});
const reset = useCallback(() => {
setCurrentId(findStartNode(flow.nodes as DialogueNode[])?.id ?? null);
setVisited([]);
setSteps(0);
setGates({});
setGateErrors(null);
}, [flow.nodes]);
// Reopening starts a fresh walk rather than resuming wherever it stopped.
useEffect(() => {
if (open) reset();
}, [open, reset]);
const node = currentId ? nodeForTarget(flow.nodes as DialogueNode[], currentId) : null;
const nodeChoices = node?.data.choices ?? [];
// A condition node has no body: ask the server, then continue on its branch.
useEffect(() => {
if (!open || !node || node.type !== "condition") return;
const condition = node.data.condition as DialogueCondition | undefined;
if (!condition) {
setGateErrors("This condition node has no condition set.");
return;
}
let cancelled = false;
setChecking(true);
void previewDialogueCondition(condition)
.then((result) => {
if (cancelled) return;
if (!result.success || typeof result.data !== "boolean") {
setGateErrors(result.error ?? "Could not evaluate this condition.");
return;
}
setGateErrors(null);
setGates((current) => ({ ...current, [node.id]: result.data as boolean }));
})
.finally(() => {
if (!cancelled) setChecking(false);
});
return () => {
cancelled = true;
};
}, [open, node]);
// Conditional choices: ask once per node which of them pass for this author.
useEffect(() => {
if (!open || !node || node.type !== "choice") return;
const gated = nodeChoices
.map((choice, index) => ({ choice, index }))
.filter((entry) => entry.choice.condition);
if (gated.length === 0) return;
let cancelled = false;
void Promise.all(
gated.map(async ({ choice, index }) => {
const result = await previewDialogueCondition(choice.condition as DialogueCondition);
return { index, passed: result.success ? Boolean(result.data) : true };
}),
).then((answers) => {
if (cancelled) return;
setChoiceGates((current) => {
const next = { ...current };
for (const answer of answers) {
next[`${node.id}:${answer.index}`] = answer.passed;
}
return next;
});
});
return () => {
cancelled = true;
};
// nodeChoices is derived from node, so node identity is enough.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, node]);
if (!open) return null;
const step = node ? previewStep(node) : null;
const gateAnswer = node && node.id in gates ? gates[node.id] : null;
const auto = node ? automaticTarget(node, gateAnswer) : { target: null, waitingOnGate: false };
const go = (target: string | null) => {
if (!target) return;
setVisited((current) => (current.includes(target) ? current : [...current, target]));
setSteps((current) => current + 1);
setCurrentId(target);
};
/** 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. */
const choiceAvailable = (index: number) => {
const choice = node?.data.choices?.[index];
if (!choice) return false;
if (choice.once === true && choice.target && visited.includes(choice.target)) return false;
if (!choice.condition) return true;
const answer = node ? choiceGates[`${node.id}:${index}`] : undefined;
// Not answered yet: keep it clickable rather than flashing disabled.
return answer === undefined ? true : answer;
};
return (
<div className="fixed inset-0 z-[60] flex items-start 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" />
<span className="font-mono text-[10px] uppercase tracking-widest text-white/70">
Draft preview
</span>
<span className="truncate text-xs text-white/40">{contactName || "unassigned contact"}</span>
<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"
>
<RotateCcwIcon className="size-2.5" /> Restart
</button>
<button
type="button"
onClick={() => onOpenChange(false)}
aria-label="Close preview"
className="cursor-pointer bg-transparent text-white/40 hover:text-white"
>
<XIcon className="size-4" />
</button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
{!start && (
<p className="text-sm text-amber-200">
This draft has no start node. Mark one as the start, or draw a node nothing points at.
</p>
)}
{start && !node && (
<p className="text-sm text-amber-200">
The start node points at a card that no longer exists.
</p>
)}
{step && node && (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2 font-mono text-[9px] uppercase tracking-widest text-white/40">
<span className="rounded-sm border border-white/15 px-1 py-0.5">
{NODE_LABEL[node.type] ?? node.type}
</span>
<span className="truncate">{node.id}</span>
{node.data.presentation === "narration" && <span>narration</span>}
</div>
{step.speaker && (
<span className="font-mono text-[9px] uppercase tracking-widest text-white/50">
{step.speaker}
</span>
)}
{step.text ? (
<p className="whitespace-pre-wrap text-sm leading-relaxed text-white/90">
<DialogueText text={step.text} />
</p>
) : (
node.type !== "condition" && (
<p className="text-sm italic text-white/35">Empty line.</p>
)
)}
{step.effectLines.length > 0 && (
<ul className="flex flex-col gap-1 rounded-sm border border-amber-900/50 bg-amber-950/30 px-2 py-1.5">
{step.effectLines.map((line) => (
<li key={line} className="font-mono text-[10px] leading-snug text-amber-200/90">
{line}
</li>
))}
<li className="font-mono text-[9px] uppercase tracking-wider text-amber-200/50">
Dry run, nothing written
</li>
</ul>
)}
{node.type === "condition" && (
<div className="rounded-sm border border-white/15 bg-black/30 px-2 py-1.5 font-mono text-[10px] leading-snug text-white/70">
<div>if {describeCondition(node.data.condition) ?? "(no condition)"}</div>
{checking && <div className="text-cyan-300">checking...</div>}
{gateErrors && <div className="text-red-300">{gateErrors}</div>}
{gateAnswer !== null && (
<div className="text-cyan-300">
{gateAnswer ? "true" : "false"} for you, so this draft continues{" "}
{gateAnswer ? "true" : "false"}
</div>
)}
</div>
)}
{node.type === "choice" && (
<div className="flex flex-col gap-1.5">
{step.choices.length === 0 && (
<p className="text-xs text-amber-200">This choice node has no choices yet.</p>
)}
{step.choices.map((choice) => {
const available = choiceAvailable(choice.index);
return (
<button
key={choice.index}
type="button"
disabled={!choice.target || !available}
onClick={() => go(choice.target)}
className={`w-full cursor-pointer rounded-sm border px-2.5 py-1.5 text-left text-sm transition-colors disabled:cursor-not-allowed ${
choice.target && available
? "border-white/20 bg-black/40 text-white/85 hover:border-cyan-500/60 hover:text-white"
: "border-white/10 bg-black/20 text-white/35"
}`}
>
<span className="flex items-center gap-2">
<span className="font-mono text-[9px] text-white/40">{choice.index + 1}</span>
<DialogueText text={choice.label} />
</span>
{choice.conditionNote && (
<span className="mt-0.5 block font-mono text-[9px] text-amber-200/70">
gate: {choice.conditionNote}
{node && choiceGates[`${node.id}:${choice.index}`] === false
? " (hidden for you)"
: ""}
</span>
)}
{!choice.target && (
<span className="mt-0.5 block font-mono text-[9px] text-red-300/80">
not wired
</span>
)}
{choice.once && (
<span className="mt-0.5 block font-mono text-[9px] text-white/35">
once per player
</span>
)}
</button>
);
})}
</div>
)}
{node.type === "condition" && gateAnswer !== null && auto.target && (
<button
type="button"
onClick={() => go(auto.target)}
className="w-fit cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
>
Continue down the {gateAnswer ? "true" : "false"} branch
</button>
)}
{node.type !== "choice" && node.type !== "condition" && !isTerminal(node) && (
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => go(auto.target)}
disabled={!auto.target}
className="cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
>
Continue
</button>
{!auto.target && (
<span className="font-mono text-[9px] uppercase tracking-wider text-amber-200/70">
this node goes nowhere
</span>
)}
</div>
)}
{isTerminal(node) && (
<div className="flex items-center gap-2">
<span className="font-mono text-[9px] uppercase tracking-widest text-white/40">
conversation ends
</span>
<button
type="button"
onClick={reset}
className="cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 hover:border-cyan-500/60 hover:text-white"
>
Play again
</button>
</div>
)}
</div>
)}
</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
{visited.length === 1 ? "" : "s"} visited. Text shows tokens as
authored; the player sees them resolved.
</div>
</div>
</div>
);
}

View file

@ -22,7 +22,7 @@ import {
type XYPosition,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { Magnet, Maximize2, Minimize2, Sparkles } from "lucide-react";
import { Magnet, Maximize2, Minimize2, Play, Sparkles } from "lucide-react";
import { useDocumentInfo, useField } from "@payloadcms/ui";
import type { NpcDialogue } from "@/payload-types";
@ -50,6 +50,7 @@ import {
import type { RouteRect } from "@/lib/flow-edge-routing";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } from "./GenerateDraftDialog";
import { DialoguePreviewDialog } from "./DialoguePreviewDialog";
import type { AttachTarget, DraftPlacementChoice } from "./GenerateDraftDialog";
import { RoutedFlowEdge } from "./RoutedFlowEdge";
@ -118,6 +119,9 @@ function FlowEditor() {
const [snap, setSnap] = useState(true);
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
const [generateOpen, setGenerateOpen] = useState(false);
// Walks the unsaved canvas as it stands, so an author can test a branch
// without saving and leaving the admin.
const [previewOpen, setPreviewOpen] = useState(false);
// Set after a draft lands, cleared when the author dismisses it. Purely a
// reminder: the document's own modified state is what actually guards saving.
const [draftNotice, setDraftNotice] = useState<string | null>(null);
@ -154,6 +158,15 @@ function FlowEditor() {
return null;
}, [docData]);
const npcLabel = useMemo(() => {
const raw = (docData as Record<string, unknown> | undefined)?.npc;
if (raw && typeof raw === "object" && "name" in raw) {
const name = (raw as { name?: unknown }).name;
if (typeof name === "string") return name;
}
return npcId === null ? "" : `contact ${npcId}`;
}, [docData, npcId]);
// This document's own id. New documents have none until the first save, which
// is also when a voice override could first be stored.
const dialogueId = useMemo(() => {
@ -764,6 +777,21 @@ function FlowEditor() {
{NODE_LABELS.end}
</button>
<button
type="button"
onClick={() => setPreviewOpen(true)}
disabled={nodes.length === 0}
title={
nodes.length === 0
? "Add a node before previewing"
: "Walk this draft without saving it"
}
className={`${buttonClass} inline-flex items-center gap-1 bg-emerald-950 border-emerald-700 text-emerald-200 hover:bg-emerald-900 disabled:opacity-40 disabled:cursor-not-allowed`}
>
<Play size={12} />
Play
</button>
<button
type="button"
onClick={() => setGenerateOpen(true)}
@ -1037,6 +1065,13 @@ function FlowEditor() {
dialogueId={dialogueId}
/>
<DialoguePreviewDialog
open={previewOpen}
onOpenChange={setPreviewOpen}
flow={{ nodes: nodes as DialogueNode[], edges: syncedEdges.map((e) => ({ id: e.id, source: e.source, target: e.target })) }}
contactName={npcLabel}
/>
<GenerateDraftDialog
open={generateOpen}
onOpenChange={setGenerateOpen}

View file

@ -0,0 +1,58 @@
"use server";
/**
* Evaluation for the editor's draft preview.
*
* The preview walks the author's unsaved graph on the client (it has the nodes),
* but flag values live in the database, so a condition can only be answered
* here. Gated like authoring: previewing is reading conversation content, and
* the caller is already editing this document.
*
* Nothing is written. Effects are described by the preview and never applied.
*/
import config from "@payload-config";
import { getPayload } from "payload";
import type { DialogueCondition } from "@/lib/npc-dialogue/dialogue";
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
import { hasPermission } from "@/utils/access-control/hasPermission";
export type PreviewConditionResult = { success: boolean; error?: string; data?: boolean };
async function authenticate() {
const payload = await getPayload({ config });
const { headers } = await import("next/headers");
const { user } = await payload.auth({ headers: await headers() });
return { payload, user };
}
/**
* Whether a condition passes for the editing user.
*
* `condition` comes from a client component, so it is checked for its kind
* before it reaches the evaluator; a malformed payload answers false rather than
* throwing inside the flag reader.
*/
export async function previewDialogueCondition(
condition: DialogueCondition,
): Promise<PreviewConditionResult> {
try {
const { payload, user } = await authenticate();
if (!user) return { success: false, error: "You must be logged in." };
const allowed = await hasPermission(payload, user, "npc-dialogues:update");
if (!allowed) {
return { success: false, error: "You are not allowed to preview conversations." };
}
if (!condition || (condition.kind !== "flag" && condition.kind !== "group")) {
return { success: false, error: "Unsupported condition." };
}
const passed = await evaluateCondition(payload, user.id as number, condition);
return { success: true, data: passed };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}

View file

@ -272,6 +272,40 @@ state, keyed by log entry id, so only the line actually playing shows it). The
element reports progress and clears on `ended`; muting and closing clear it
immediately.
### Play the draft (editor preview)
The player runtime reads the stored document, so an unsaved canvas cannot be
played on the contact page. `DialoguePreviewDialog` (client) walks the live
`nodes` from `useField` instead: a `Play` button in the toolbar opens it, and
`preview.ts` answers what can be answered locally (choices in runtime order,
branch targets, effect descriptions).
Conditions are the one thing that needs the server: flag values live in the
database. `previewActions.previewDialogueCondition` authenticates, requires
`npc-dialogues:update`, and calls the same `evaluateCondition` the runtime uses,
so the preview cannot disagree with the player's outcome. Gated choices are
evaluated per node and shown as "hidden for you", matching what the runtime would
hide.
**Effects are dry-run.** `previewEffectLines` describes the write ("Would set flag
X to true") and nothing calls the effect applier. Verified on a temp document with
a flag effect and a condition node: the event step showed the dry-run line, the
condition answered false for a missing flag, the walk followed the false branch,
and `player_flags` gained no row.
Two traps specific to this component, both costs of rendering inside the admin:
- Every bare `<button>` shows the UA's white background, because the admin bundle
has no theme tokens and no preflight for buttons. Give each one an explicit
background (`bg-transparent` or `bg-black/40`), not just a border.
- `contactName` comes from the relationship field, which is often a bare id at the
editor's depth. It falls back to `contact <id>`, which is honest; do not try to
fetch the name here.
`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.
### Unread markers
A contact card shows a `NEW` chip when the conversation that would be offered has

View file

@ -0,0 +1,169 @@
/**
* Read-only helpers for walking a draft conversation in the editor.
*
* The author's problem this solves: an unsaved canvas cannot be walked by the
* player runtime, which resolves everything from the stored document. The
* preview therefore replays the graph on the client and asks the server only
* what it cannot know locally: the player's flag values.
*
* Nothing here writes. Effects are described, never applied, so previewing a
* draft cannot grant a flag or send a notification.
*/
import type { DialogueCondition, DialogueNode, DialogueNext, NpcDialogueEffect } from "./dialogue";
/** What a choice node offers, as the preview should show it. */
export interface PreviewChoice {
/** Position among the node's choices, which is the runtime's index. */
index: number;
label: string;
/** Where it goes, or null when the author never wired it. */
target: string | null;
/** Gate text for the author when the choice is conditional. */
conditionNote: string | null;
/** Shown-but-unavailable because its `once` flag already fired this run. */
once: boolean;
}
function conditionValue(condition: DialogueCondition): string {
if (condition.kind === "group") {
const children = condition.children ?? [];
return children.map(conditionValue).join(` ${condition.op ?? "and"} `);
}
const amount = condition.amount ?? 0;
const flag = condition.key || "(no key)";
switch (condition.op) {
case "is_true":
return `${flag} is true`;
case "is_false":
return `${flag} is false`;
case "is_defined":
return `${flag} is defined`;
case "is_undefined":
return `${flag} is undefined`;
case "gte":
return `${flag} >= ${amount}`;
case "lte":
return `${flag} <= ${amount}`;
case "gt":
return `${flag} > ${amount}`;
case "lt":
return `${flag} < ${amount}`;
case "eq":
return `${flag} = ${amount}`;
}
}
/** Plain-language summary of a condition, for badges and the preview trace. */
export function describeCondition(condition: DialogueCondition | undefined): string | null {
if (!condition) return null;
return conditionValue(condition);
}
/** The choices on a choice node, in runtime order. */
export function previewChoices(node: DialogueNode): PreviewChoice[] {
return (node.data.choices ?? []).map((choice: DialogueNext, index) => ({
index,
label: choice.label?.trim() || "(unlabeled choice)",
target: choice.target ?? null,
conditionNote: describeCondition(choice.condition),
once: choice.once === true,
}));
}
/** One line per thing an effect would do, for a dry-run trace. */
export function previewEffectLines(effect: NpcDialogueEffect | undefined): string[] {
if (!effect) return [];
switch (effect.type) {
case "flag": {
const key = effect.flagKey || "(no key)";
switch (effect.flagOp) {
case "set_true":
return [`Would set flag ${key} to true`];
case "set_false":
return [`Would set flag ${key} to false`];
case "set_number":
return [`Would set flag ${key} to ${effect.flagAmount ?? 0}`];
case "add":
return [`Would add ${effect.flagAmount ?? 0} to flag ${key}`];
case "set_text":
return [`Would set flag ${key} to text: ${effect.flagText || "(empty)"}`];
default:
return [`Would write flag ${key}`];
}
}
case "notify":
return [`Would notify the player: ${effect.title || effect.message || "(empty)"}`];
case "emit":
return [`Would write an event: ${effect.message || "(empty)"}`];
case "reward":
return [`Would reward the player: ${effect.message || "(no detail)"}`];
default:
return [`Would run an effect (${String((effect as { type?: unknown }).type)})`];
}
}
/** The node a hop points at, if it still exists. A dangling target means the
* author deleted the card without unwiring it, which is worth showing. */
export function nodeForTarget(
nodes: readonly DialogueNode[],
target: string | undefined | null,
): DialogueNode | null {
if (!target) return null;
return nodes.find((node) => node.id === target) ?? null;
}
/** Everything the preview needs to draw one step. */
export interface PreviewStep {
node: DialogueNode;
/** Body text as authored. Tokens stay visible: the preview does not resolve
* them, so the author sees exactly which placeholders the line depends on. */
text: string;
speaker: string | null;
choices: PreviewChoice[];
effectLines: string[];
/** The single continuation for nodes that only go one way. */
nextTarget: string | null;
}
export function previewStep(node: DialogueNode): PreviewStep {
const body =
node.type === "choice" ? (node.data.leadIn ?? "") : (node.data.body ?? node.data.closing ?? "");
const effects = [
...previewEffectLines(node.data.effect),
...(node.data.attachments?.length
? [`${node.data.attachments.length} attachment(s) the player can open`]
: []),
...(node.data.voice?.filename ? [`Voice clip: ${node.data.voice.filename}`] : []),
];
const continuation =
node.type === "condition" ? null : (node.data.next?.target ?? null);
return {
node,
text: body,
speaker: node.data.speaker?.trim() || null,
choices: node.type === "choice" ? previewChoices(node) : [],
effectLines: effects,
nextTarget: continuation,
};
}
/** Where a node sends the walker on its own, without the player choosing. */
export function automaticTarget(
node: DialogueNode,
conditionPassed: boolean | null,
): { target: string | null; waitingOnGate: boolean } {
if (node.type === "condition") {
if (conditionPassed === null) return { target: null, waitingOnGate: true };
const target = conditionPassed ? node.data.trueTarget : node.data.falseTarget;
return { target: target ?? null, waitingOnGate: false };
}
if (node.type === "choice") return { target: null, waitingOnGate: false };
if (node.type === "end") return { target: null, waitingOnGate: false };
return { target: node.data.next?.target ?? null, waitingOnGate: false };
}
/** Node types the preview can continue through without the player picking. */
export function isTerminal(node: DialogueNode): boolean {
return node.type === "end";
}

View file

@ -0,0 +1,130 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import {
automaticTarget,
describeCondition,
isTerminal,
nodeForTarget,
previewChoices,
previewEffectLines,
previewStep,
} from "@/lib/npc-dialogue/preview";
/**
* The editor's draft preview walks an unsaved graph, so its reading of the
* author's nodes has to match the runtime's: same choice order, same branch for
* a condition, and effects described rather than applied.
*/
function node(partial: Partial<DialogueNode> & { id: string; type: DialogueNode["type"] }): DialogueNode {
return {
position: { x: 0, y: 0 },
data: {},
...partial,
} as DialogueNode;
}
describe("draft preview reading the graph", () => {
it("lists choices in runtime order with their gate text", () => {
const choice = node({
id: "c1",
type: "choice",
data: {
leadIn: "Pick one.",
choices: [
{ label: "First", target: "a" },
{ label: "", target: "b" },
{ label: "Third", target: "c", condition: { kind: "flag", key: "rank", op: "gt", amount: 2 } },
],
},
});
const choices = previewChoices(choice);
expect(choices.map((c) => c.index)).toEqual([0, 1, 2]);
expect(choices[1]?.label).toBe("(unlabeled choice)");
expect(choices[2]?.conditionNote).toBe("rank > 2");
});
it("describes condition groups in plain language", () => {
expect(
describeCondition({
kind: "group",
op: "and",
children: [
{ kind: "flag", key: "a", op: "is_true" },
{ kind: "flag", key: "b", op: "is_undefined" },
],
}),
).toBe("a is true and b is undefined");
expect(describeCondition(undefined)).toBeNull();
});
it("sends a condition node down the branch its answer picks", () => {
const condition = node({
id: "k1",
type: "condition",
data: { condition: { kind: "flag", key: "a", op: "is_true" }, trueTarget: "yes", falseTarget: "no" },
});
expect(automaticTarget(condition, null)).toEqual({ target: null, waitingOnGate: true });
expect(automaticTarget(condition, true)).toEqual({ target: "yes", waitingOnGate: false });
expect(automaticTarget(condition, false)).toEqual({ target: "no", waitingOnGate: false });
});
it("keeps the single continuation for linear nodes", () => {
const dialogue = node({ id: "d1", type: "dialogue", data: { body: "Hi", next: { target: "d2" } } });
expect(automaticTarget(dialogue, null).target).toBe("d2");
expect(automaticTarget(node({ id: "e1", type: "end", data: {} }), null).target).toBeNull();
});
it("only treats end nodes as terminal", () => {
expect(isTerminal(node({ id: "e1", type: "end", data: {} }))).toBe(true);
expect(isTerminal(node({ id: "d1", type: "dialogue", data: {} }))).toBe(false);
expect(isTerminal(node({ id: "y1", type: "delay", data: {} }))).toBe(false);
});
it("describes flag effects by their actual write, never as applied", () => {
expect(previewEffectLines({ type: "flag", flagKey: "trust", flagOp: "set_number", flagAmount: 3 })).toEqual([
"Would set flag trust to 3",
]);
expect(previewEffectLines({ type: "flag", flagKey: "trust", flagOp: "add", flagAmount: 2 })).toEqual([
"Would add 2 to flag trust",
]);
expect(previewEffectLines({ type: "notify", title: "Heads up" })).toEqual([
"Would notify the player: Heads up",
]);
expect(previewEffectLines(undefined)).toEqual([]);
});
it("reports a step's text, attachments and voice without resolving them", () => {
const step = previewStep(
node({
id: "d1",
type: "dialogue",
data: {
body: "You owe {{debt}} credits.",
speaker: "Quartermaster",
attachments: [{ mediaId: 1 }],
voice: { mediaId: 2, filename: "line.mp3" },
},
}),
);
expect(step.text).toBe("You owe {{debt}} credits.");
expect(step.speaker).toBe("Quartermaster");
expect(step.effectLines).toEqual([
"1 attachment(s) the player can open",
"Voice clip: line.mp3",
]);
});
it("uses the closing text for an end node and the lead-in for a choice", () => {
expect(previewStep(node({ id: "e1", type: "end", data: { closing: "Goodbye." } })).text).toBe("Goodbye.");
expect(previewStep(node({ id: "c1", type: "choice", data: { leadIn: "Well?" } })).text).toBe("Well?");
});
it("finds a target only when the card still exists", () => {
const nodes = [node({ id: "a", type: "dialogue", data: {} })];
expect(nodeForTarget(nodes, "a")?.id).toBe("a");
expect(nodeForTarget(nodes, "gone")).toBeNull();
expect(nodeForTarget(nodes, undefined)).toBeNull();
});
});