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.
599 lines
22 KiB
TypeScript
599 lines
22 KiB
TypeScript
/**
|
|
* Canonical model + pure helpers for NPC conversation flowcharts.
|
|
*
|
|
* The graph is authoritative in node data: every node lists where the
|
|
* conversation can go next (`next` for a single continuation, `choices` for
|
|
* branching). Edges are a derived projection of that data, so the admin
|
|
* canvas and the runtime walker always agree.
|
|
*/
|
|
|
|
export type NpcDialogueNodeType =
|
|
| "dialogue"
|
|
| "choice"
|
|
| "event"
|
|
| "end"
|
|
| "delay"
|
|
| "condition";
|
|
|
|
/** A directed hop to another node. `label` is the choice button text. */
|
|
export interface DialogueNext {
|
|
/** Button text shown to the player (required on choice hops). */
|
|
label?: string;
|
|
/** Target node id. */
|
|
target: string;
|
|
/**
|
|
* Choice hops only: once the player picks this choice it is hidden from
|
|
* them in every later conversation turn (tracked per player as a reserved
|
|
* `dlg-once:` player flag).
|
|
*/
|
|
once?: boolean;
|
|
/**
|
|
* Choice hops only: optional rich tooltip shown when the player hovers or
|
|
* focuses the choice button. Supports the same inline markup as dialogue
|
|
* lines (colors, bold, images) plus `{{flag}}` interpolation.
|
|
*/
|
|
tooltip?: string;
|
|
/**
|
|
* Choice hops only: when set, the choice button is only offered to players
|
|
* whose live flags satisfy this condition (evaluated server-side, same
|
|
* flag semantics as condition nodes). Missing key = ungated.
|
|
*/
|
|
condition?: DialogueCondition;
|
|
/**
|
|
* Choice hops only: when the condition fails, show the choice disabled
|
|
* with this rich tooltip explaining why (supports markup + {{flags}})
|
|
* instead of hiding it. Empty/missing keeps the hide-when-failed behavior.
|
|
*/
|
|
lockedHint?: string;
|
|
}
|
|
|
|
/** Server-resolved visibility state for one gated choice. */
|
|
export interface ChoiceGate {
|
|
/** True while the player's flags satisfy the choice condition. */
|
|
pass: boolean;
|
|
/** True when a failing choice should still render, locked, with its hint. */
|
|
showLocked: boolean;
|
|
}
|
|
|
|
/**
|
|
* Branch condition evaluated server-side against live web-app state when the
|
|
* conversation arrives at a `condition` node. Boolean flags compare against
|
|
* true/false; numeric flags compare against `amount` (a missing flag counts
|
|
* as false / zero). The defined checks test whether the reading player has a
|
|
* recorded value at all, which no truthiness test can express: a missing flag
|
|
* and a flag explicitly set to false both read as false.
|
|
*/
|
|
export interface DialogueFlagCondition {
|
|
/** Currently only generic player flags; more kinds can join later. */
|
|
kind: "flag";
|
|
/** `player-flags` key checked for the reading user. */
|
|
key: string;
|
|
/** Comparison applied to the flag's effective value. */
|
|
op:
|
|
| "is_true"
|
|
| "is_false"
|
|
| "is_defined"
|
|
| "is_undefined"
|
|
| "gte"
|
|
| "lte"
|
|
| "gt"
|
|
| "lt"
|
|
| "eq";
|
|
/**
|
|
* Right-hand side for the numeric comparisons. Ignored by the state checks
|
|
* (`is_true` / `is_false` / `is_defined` / `is_undefined`).
|
|
*/
|
|
amount?: number;
|
|
}
|
|
|
|
/**
|
|
* Single-level group over leaf conditions (children are always leaves, so
|
|
* authored JSON stays shallow and the editor builder stays simple).
|
|
* `and` passes when every child passes, `or` when any does, `nor` when none
|
|
* does. An empty group passes for `and`/`nor` and fails for `or`.
|
|
*/
|
|
export interface DialogueConditionGroup {
|
|
kind: "group";
|
|
op: "and" | "or" | "nor";
|
|
children: DialogueFlagCondition[];
|
|
}
|
|
|
|
export type DialogueCondition = DialogueFlagCondition | DialogueConditionGroup;
|
|
|
|
/** All leaf condition operators, in UI order. */
|
|
export const CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
|
"is_true",
|
|
"is_false",
|
|
"is_defined",
|
|
"is_undefined",
|
|
"gte",
|
|
"lte",
|
|
"gt",
|
|
"lt",
|
|
"eq",
|
|
];
|
|
|
|
/**
|
|
* Ops that compare the flag against `amount`. Everything else tests the flag's
|
|
* state (truthiness or existence), so the amount is meaningless for them and
|
|
* the UI hides it. Shared so the editor, the entry-gate field and the canvas
|
|
* summary never disagree about which ops take a number.
|
|
*/
|
|
export const NUMERIC_CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
|
"gte",
|
|
"lte",
|
|
"gt",
|
|
"lt",
|
|
"eq",
|
|
];
|
|
|
|
/** How a flag effect writes the flag. */
|
|
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "set_text" | "add";
|
|
|
|
/** Configured effect for an `event` node. */
|
|
export interface NpcDialogueEffect {
|
|
type: "notify" | "emit" | "reward" | "flag";
|
|
/** In-app notification title (notify). */
|
|
title?: string;
|
|
/** Notification / event-log body (notify, emit). */
|
|
message?: string;
|
|
/**
|
|
* Visibility of the game-event-log entry this effect writes (emit, reward,
|
|
* flag). Dialogue events default to restricted (narrative spoilers), gated
|
|
* to dialogue/flag staff; set "public" for announcements that should appear
|
|
* in every member's event feed. Omitted means "use the default policy".
|
|
*/
|
|
eventVisibility?: "public" | "restricted";
|
|
/**
|
|
* Queue the emitted game-event entry for the bot's Discord NPC dispatch
|
|
* channel (emit, reward, flag). Reserve for milestone beats; the poll
|
|
* service posts the message once and stamps the log entry.
|
|
*/
|
|
discord?: boolean;
|
|
/** Flag key to write (flag). */
|
|
flagKey?: string;
|
|
/** Write mode (flag). */
|
|
flagOp?: DialogueFlagOp;
|
|
/** Value for set_number / addend for add (flag). */
|
|
flagAmount?: number;
|
|
/** Value for set_text (flag). May contain display markup, e.g. {green}OK{/}. */
|
|
flagText?: string;
|
|
/**
|
|
* Flag effects only: delay the write's effect this many minutes by stamping
|
|
* the flag with `activatesAt = now + N`. Conditions read it as false until
|
|
* then, and `{{countdown:key}}` tokens tick down to it.
|
|
*/
|
|
flagDelayMinutes?: number;
|
|
/**
|
|
* Flag effects only: which player the flag belongs to. `self` (the default)
|
|
* targets the active conversation participant; `global` targets the shared
|
|
* `user: null` flag of the same key; `user` targets a specific player via
|
|
* `flagTargetUserId`. A flag's identity is (owner, key), so the same key can
|
|
* hold independent values for different owners.
|
|
*/
|
|
flagTarget?: "self" | "global" | "user";
|
|
/** `flagTarget === "user"`: the player the flag belongs to. */
|
|
flagTargetUserId?: number | null;
|
|
}
|
|
|
|
/**
|
|
* A file attached to a conversation node (transcripts, orders, images). The
|
|
* bytes live in the `media` collection; flowData only stores the pointer, so
|
|
* the runtime resolves ids to URLs server-side before the client renders
|
|
* chips (JSON relationships are never auto-populated).
|
|
*/
|
|
export interface DialogueAttachment {
|
|
/** `media` document id holding the file. */
|
|
mediaId: number | string;
|
|
/** Chip label; falls back to the stored filename. */
|
|
label?: string;
|
|
}
|
|
|
|
/** An attachment resolved for rendering (server-side). */
|
|
export interface ResolvedAttachment {
|
|
label: string;
|
|
/** Site-relative file URL (`/api/media/file/<filename>`). */
|
|
url: string;
|
|
filename: string;
|
|
mimeType: string;
|
|
sizeBytes?: number;
|
|
}
|
|
|
|
/**
|
|
* Voice clip recorded for one line. Only the media pointer is stored in
|
|
* flowData; the runtime resolves it to a URL per read, the same way
|
|
* attachments work, so a deleted file simply stops playing.
|
|
*/
|
|
export interface DialogueVoiceClip {
|
|
/** `media` document holding the audio. */
|
|
mediaId: number;
|
|
/**
|
|
* Stored filename, for the editor's inline preview. Playback still resolves
|
|
* through `mediaId`, so a stale name cannot break the line.
|
|
*/
|
|
filename?: string;
|
|
}
|
|
|
|
/** A voice clip resolved for playback. */
|
|
export interface ResolvedVoiceClip {
|
|
url: string;
|
|
filename: string;
|
|
mimeType: string;
|
|
}
|
|
|
|
export type DialogueNodeData = {
|
|
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
|
|
speaker?: string;
|
|
/** The spoken line (dialogue) or narrative description (event nodes). */
|
|
body?: string;
|
|
/**
|
|
* How an `event` node's body is presented to the player. `event` (default) is
|
|
* the spoken-style amber line with the NPC's name above it; `narration` is a
|
|
* centered, muted description with no speaker, for scene-setting beats the
|
|
* 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. */
|
|
leadIn?: string;
|
|
/** Triggered when the conversation arrives at this node. */
|
|
effect?: NpcDialogueEffect;
|
|
/** Closing text shown when the conversation ends. */
|
|
closing?: string;
|
|
/** Files attached to this node's message (dialogue/event/end nodes). */
|
|
attachments?: DialogueAttachment[];
|
|
/**
|
|
* Recorded voice for this line (dialogue/event/end nodes). Plays when the
|
|
* line lands and paces the reveal to the clip, so the text finishes with the
|
|
* read. Omitted = a silent line.
|
|
*/
|
|
voice?: DialogueVoiceClip;
|
|
/** Marks this node as the conversation start. */
|
|
isStart?: boolean;
|
|
/** Single continuation (dialogue / event / end nodes). */
|
|
next?: DialogueNext;
|
|
/** Pause in seconds before the conversation continues (delay nodes). */
|
|
delaySeconds?: number;
|
|
/** Branch condition evaluated when the conversation arrives (condition nodes). */
|
|
condition?: DialogueCondition;
|
|
/** Continuation when the condition passes (condition nodes). */
|
|
trueTarget?: string;
|
|
/** Continuation when the condition fails (condition nodes). */
|
|
falseTarget?: string;
|
|
} & Record<string, unknown>;
|
|
|
|
export interface DialogueNode {
|
|
id: string;
|
|
type: NpcDialogueNodeType;
|
|
position: { x: number; y: number };
|
|
data: DialogueNodeData;
|
|
}
|
|
|
|
export interface DialogueEdge {
|
|
id: string;
|
|
source: string;
|
|
target: string;
|
|
label?: string;
|
|
/** Source handle the edge leaves from (`c0`..`cN` per choice, `true`/`false`). */
|
|
sourceHandle?: string;
|
|
}
|
|
|
|
export interface FlowData {
|
|
nodes: DialogueNode[];
|
|
edges: DialogueEdge[];
|
|
}
|
|
|
|
/** All effect types the runtime can actually trigger. */
|
|
export const EFFECT_TYPES: NpcDialogueEffect["type"][] = [
|
|
"notify",
|
|
"emit",
|
|
"reward",
|
|
"flag",
|
|
];
|
|
|
|
/**
|
|
* Every outgoing hop of a node, in canvas order: choice buttons, the single
|
|
* continuation, or the condition's true/false branches. The edge projection,
|
|
* validation, and the runtime walker all share this so they never disagree.
|
|
*/
|
|
export function outgoingHops(node: DialogueNode): DialogueNext[] {
|
|
if (node.type === "choice") return node.data.choices ?? [];
|
|
if (node.type === "condition") {
|
|
const hops: DialogueNext[] = [];
|
|
if (node.data.trueTarget) hops.push({ label: "true", target: node.data.trueTarget });
|
|
if (node.data.falseTarget) hops.push({ label: "false", target: node.data.falseTarget });
|
|
return hops;
|
|
}
|
|
return node.data.next ? [node.data.next] : [];
|
|
}
|
|
|
|
/** True when a node has no outgoing hops (conversation ends here). */
|
|
export function isTerminalNode(node: DialogueNode): boolean {
|
|
return outgoingHops(node).length === 0;
|
|
}
|
|
|
|
/** Resolves the node the conversation should start at. */
|
|
export function findStartNode(nodes: DialogueNode[]): DialogueNode | null {
|
|
if (nodes.length === 0) return null;
|
|
const marked = nodes.find((node) => node.data.isStart === true);
|
|
if (marked) return marked;
|
|
// Fall back to the first node with no incoming edges.
|
|
const targets = new Set(nodes.flatMap((n) => outgoingHops(n).map((h) => h.target)));
|
|
const roots = nodes.filter((n) => !targets.has(n.id));
|
|
return (roots.length ? roots[0] : nodes[0]) ?? null;
|
|
}
|
|
|
|
/** Handle id an outgoing hop leaves its node through (per-choice / per-branch). */
|
|
export function handleIdForHop(node: DialogueNode, index: number): string | undefined {
|
|
if (node.type === "choice") return `c${index}`;
|
|
if (node.type === "condition") {
|
|
// outgoingHops skips unset branches, so map by what actually exists:
|
|
// only-true -> "true", only-false -> "false", both -> first is true.
|
|
const hasTrue = !!node.data.trueTarget;
|
|
const hasFalse = !!node.data.falseTarget;
|
|
if (hasTrue && hasFalse) return index === 0 ? "true" : "false";
|
|
return hasTrue ? "true" : "false";
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/** Builds the edge projection that mirrors the node graph. */
|
|
export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
|
|
const edges: DialogueEdge[] = [];
|
|
for (const node of nodes) {
|
|
outgoingHops(node).forEach((hop, index) => {
|
|
if (!hop || !hop.target) return;
|
|
edges.push({
|
|
id: `${node.id}->${index}`,
|
|
source: node.id,
|
|
target: hop.target,
|
|
label: hop.label,
|
|
sourceHandle: handleIdForHop(node, index),
|
|
});
|
|
});
|
|
}
|
|
return edges;
|
|
}
|
|
|
|
/**
|
|
* Removes the hop an edge represents from a node's data. Edges are a derived
|
|
* projection, so deleting one scrubs the source hop: a choice row (`c0`..`cN`),
|
|
* a condition branch (`true`/`false`), or the single continuation. Returns a
|
|
* new node and never mutates the input.
|
|
*/
|
|
export function removeHopFromNode(node: DialogueNode, sourceHandle?: string | null): DialogueNode {
|
|
if (node.type === "choice") {
|
|
const m = sourceHandle?.match(/^c(\d+)$/);
|
|
if (!m) return node;
|
|
const idx = Number(m[1]);
|
|
const choices = [...(node.data.choices ?? [])];
|
|
choices.splice(idx, 1);
|
|
return { ...node, data: { ...node.data, choices } };
|
|
}
|
|
if (node.type === "condition") {
|
|
if (sourceHandle === "true") return { ...node, data: { ...node.data, trueTarget: undefined } };
|
|
if (sourceHandle === "false") return { ...node, data: { ...node.data, falseTarget: undefined } };
|
|
return node;
|
|
}
|
|
return { ...node, data: { ...node.data, next: undefined } };
|
|
}
|
|
|
|
export interface GraphValidation {
|
|
valid: boolean;
|
|
errors: string[];
|
|
}
|
|
|
|
/**
|
|
* The hop an edge leaves a node through, keyed by the handle the edge started
|
|
* from. Edges leaving single-continuation nodes carry no handle id, so an absent
|
|
* handle maps to the node's only hop rather than to nothing.
|
|
*
|
|
* Used when an edge is reconnected: the hop has to travel with the line, or a
|
|
* choice would come back as a blank button.
|
|
*/
|
|
export function hopFromHandle(
|
|
node: DialogueNode,
|
|
sourceHandle?: string | null,
|
|
): DialogueNext | null {
|
|
const hops = outgoingHops(node);
|
|
if (hops.length === 0) return null;
|
|
const index = hops.findIndex(
|
|
(_hop, i) => handleIdForHop(node, i) === (sourceHandle ?? undefined),
|
|
);
|
|
if (index >= 0) return hops[index] ?? null;
|
|
return sourceHandle ? null : (hops[0] ?? null);
|
|
}
|
|
|
|
export interface ConnectionResult {
|
|
/** The new node list, or the input list unchanged when the link is refused. */
|
|
nodes: DialogueNode[];
|
|
/** False when nothing was written (a refused or no-op connection). */
|
|
changed: boolean;
|
|
/**
|
|
* Set when the connection created or left an unlabelled choice, so the editor
|
|
* can open that node immediately (validateGraph flags empty labels).
|
|
*/
|
|
labelNodeId: string | null;
|
|
}
|
|
|
|
/**
|
|
* Writes one connection into the node data, which is the graph's source of truth.
|
|
*
|
|
* `sourceHandle` names the output that was dragged: `c0`..`cN` for a choice row,
|
|
* `true`/`false` for a condition branch. Without one, the fallbacks are what a
|
|
* drop onto the node card should mean: a choice gains an option, a condition
|
|
* takes its first free branch.
|
|
*
|
|
* `carried` is a hop lifted from an existing edge (a reconnect). Its label,
|
|
* tooltip, `once` flag and gate are preserved, so moving a wired choice keeps what
|
|
* the author wrote.
|
|
*
|
|
* Refusals report `changed: false` and hand back the input list untouched, so a
|
|
* caller can explain them instead of writing a graph that did not change. Pure,
|
|
* so the editor wrapper only has to persist the result.
|
|
*/
|
|
export function connectHop(
|
|
nodes: DialogueNode[],
|
|
input: {
|
|
sourceId: string;
|
|
targetId: string;
|
|
sourceHandle?: string | null;
|
|
carried?: DialogueNext | null;
|
|
},
|
|
): ConnectionResult {
|
|
const { sourceId, targetId, sourceHandle, carried } = input;
|
|
const unchanged: ConnectionResult = { nodes, changed: false, labelNodeId: null };
|
|
|
|
if (sourceId === targetId) return unchanged;
|
|
const source = nodes.find((n) => n.id === sourceId);
|
|
const target = nodes.find((n) => n.id === targetId);
|
|
if (!source || !target) return unchanged;
|
|
// End nodes have no way out, and the start node has no way in.
|
|
if (source.type === "end" || target.data.isStart) return unchanged;
|
|
|
|
let labelNodeId: string | null = null;
|
|
|
|
const next = nodes.map((node) => {
|
|
if (node.id !== sourceId) return node;
|
|
if (node.type === "choice") {
|
|
const match = sourceHandle?.match(/^c(\d+)$/);
|
|
if (match) {
|
|
const index = Number(match[1]);
|
|
const choices = [...(node.data.choices ?? [])];
|
|
if (!choices[index]) return node;
|
|
choices[index] = { ...choices[index], ...(carried ?? {}), target: targetId };
|
|
if (!choices[index].label?.trim()) labelNodeId = sourceId;
|
|
return { ...node, data: { ...node.data, choices } };
|
|
}
|
|
// Generic handle (no choices yet): the drag creates the first one.
|
|
if (!carried?.label?.trim()) labelNodeId = sourceId;
|
|
return {
|
|
...node,
|
|
data: {
|
|
...node.data,
|
|
choices: [
|
|
...(node.data.choices ?? []),
|
|
{ ...(carried ?? {}), label: carried?.label ?? "", target: targetId },
|
|
],
|
|
},
|
|
};
|
|
}
|
|
if (node.type === "condition") {
|
|
if (sourceHandle === "true") {
|
|
return { ...node, data: { ...node.data, trueTarget: targetId } };
|
|
}
|
|
if (sourceHandle === "false") {
|
|
return { ...node, data: { ...node.data, falseTarget: targetId } };
|
|
}
|
|
// Dropped on the card: the first free branch takes it. Filling both at
|
|
// once (the pre-`connectHop` behaviour) wired an if/else to the same node,
|
|
// which made the condition meaningless.
|
|
if (!node.data.trueTarget) {
|
|
return { ...node, data: { ...node.data, trueTarget: targetId } };
|
|
}
|
|
if (!node.data.falseTarget) {
|
|
return { ...node, data: { ...node.data, falseTarget: targetId } };
|
|
}
|
|
return node;
|
|
}
|
|
return { ...node, data: { ...node.data, next: { ...(carried ?? {}), target: targetId } } };
|
|
});
|
|
|
|
// A refused write still maps to a new array, so identity is not the signal.
|
|
const changed = next.some((node, index) => node !== nodes[index]);
|
|
return { nodes: changed ? next : nodes, changed, labelNodeId };
|
|
}
|
|
|
|
/** One-line human summary of a condition for editor previews. */
|
|
export function conditionSummary(condition: DialogueCondition): string {
|
|
const leaf = (c: DialogueFlagCondition): string =>
|
|
`"${c.key || "?"}" ${c.op.replace(/_/g, " ")}${
|
|
c.amount !== undefined && NUMERIC_CONDITION_OPS.includes(c.op) ? ` ${c.amount}` : ""
|
|
}`;
|
|
if (condition.kind === "group") {
|
|
const joiner = condition.op === "and" ? " and " : condition.op === "or" ? " or " : " and ";
|
|
const body = condition.children.map(leaf).join(joiner);
|
|
return condition.op === "nor" ? `none of: ${body}` : body;
|
|
}
|
|
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") {
|
|
return condition.children.length === 0 || condition.children.some((child) => !child.key.trim());
|
|
}
|
|
return !condition.key.trim();
|
|
}
|
|
|
|
/**
|
|
* Validates a flowchart: a start node exists, every hop target resolves, and
|
|
* choice hops carry a label. Does not hard-fail on cycles (branching can be
|
|
* intentionally re-entrant) but reports them.
|
|
*
|
|
* `requireStart: false` is for validating a branch on its own, before it has been
|
|
* spliced into a conversation that already has a start node.
|
|
*/
|
|
export function validateGraph(
|
|
nodes: DialogueNode[],
|
|
options: { requireStart?: boolean } = {},
|
|
): GraphValidation {
|
|
const errors: string[] = [];
|
|
const ids = new Set(nodes.map((n) => n.id));
|
|
|
|
if (nodes.length === 0) {
|
|
return { valid: false, errors: ["Add at least one node to start building the conversation."] };
|
|
}
|
|
if (options.requireStart !== false && !findStartNode(nodes)) {
|
|
errors.push("Mark a node as the conversation start.");
|
|
}
|
|
|
|
for (const node of nodes) {
|
|
if (node.type === "condition" && node.data.condition && hasEmptyConditionKey(node.data.condition)) {
|
|
errors.push(`The branch condition on "${node.id}" needs a flag key.`);
|
|
}
|
|
const hops = outgoingHops(node);
|
|
for (const hop of hops) {
|
|
if (!hop) continue;
|
|
if (hop.target && !ids.has(hop.target)) {
|
|
errors.push(`"${node.id}" points to missing node "${hop.target}".`);
|
|
}
|
|
if (node.type === "choice" && !hop.label?.trim()) {
|
|
errors.push(`A choice on "${node.id}" needs button text.`);
|
|
}
|
|
if (node.type === "choice" && hop.condition && hasEmptyConditionKey(hop.condition)) {
|
|
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
|
|
}
|
|
if (
|
|
node.type === "event" &&
|
|
node.data.effect?.type === "flag" &&
|
|
node.data.effect.flagTarget === "user" &&
|
|
!node.data.effect.flagTargetUserId
|
|
) {
|
|
errors.push(`An event flag on "${node.id}" set to "Specific user" needs a target player.`);
|
|
}
|
|
}
|
|
}
|
|
|
|
return { valid: errors.length === 0, errors };
|
|
}
|