/** * 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). */ export interface DialogueCondition { /** 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" | "gte" | "lte" | "gt" | "lt" | "eq"; /** Right-hand side for the numeric comparisons. */ amount?: number; } /** All condition operators, in UI order. */ export const CONDITION_OPS: DialogueCondition["op"][] = [ "is_true", "is_false", "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"; /** 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/`). */ url: string; filename: string; mimeType: string; sizeBytes?: number; } 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; /** 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[]; /** 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; 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[]; } /** * 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. */ export function validateGraph(nodes: DialogueNode[]): 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 (!findStartNode(nodes)) { errors.push("Mark a node as the conversation start."); } for (const node of nodes) { 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 && !hop.condition.key.trim()) { 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 }; }