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.
363 lines
15 KiB
TypeScript
363 lines
15 KiB
TypeScript
"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>
|
|
);
|
|
}
|