"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 = { 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(start?.id ?? null); const [visited, setVisited] = useState([]); /** 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>({}); const [gateErrors, setGateErrors] = useState(null); const [checking, setChecking] = useState(false); /** Gate answers for conditional choices, keyed `:`, so the * preview disables a choice the runtime would hide. */ const [choiceGates, setChoiceGates] = useState>({}); 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 (
Draft preview {contactName || "unassigned contact"}
{!start && (

This draft has no start node. Mark one as the start, or draw a node nothing points at.

)} {start && !node && (

The start node points at a card that no longer exists.

)} {step && node && (
{NODE_LABEL[node.type] ?? node.type} {node.id} {node.data.presentation === "narration" && narration}
{step.speaker && ( {step.speaker} )} {step.text ? (

) : ( node.type !== "condition" && (

Empty line.

) )} {step.effectLines.length > 0 && (
    {step.effectLines.map((line) => (
  • {line}
  • ))}
  • Dry run, nothing written
)} {node.type === "condition" && (
if {describeCondition(node.data.condition) ?? "(no condition)"}
{checking &&
checking...
} {gateErrors &&
{gateErrors}
} {gateAnswer !== null && (
{gateAnswer ? "true" : "false"} for you, so this draft continues{" "} {gateAnswer ? "true" : "false"}
)}
)} {node.type === "choice" && (
{step.choices.length === 0 && (

This choice node has no choices yet.

)} {step.choices.map((choice) => { const available = choiceAvailable(choice.index); return ( ); })}
)} {node.type === "condition" && gateAnswer !== null && auto.target && ( )} {node.type !== "choice" && node.type !== "condition" && !isTerminal(node) && (
{!auto.target && ( this node goes nowhere )}
)} {isTerminal(node) && (
conversation ends
)}
)}
{steps} step{steps === 1 ? "" : "s"} walked, {visited.length} card {visited.length === 1 ? "" : "s"} visited. Text shows tokens as authored; the player sees them resolved.
); }