1
0
Fork 0
polaris-task-force/src/lib/npc-dialogue/dialogue.ts
Z8MB1E f595828c99 feat(npc-dialogue): stacked markup, link popups, new badges, locked choices, timed flags
- DialogueText rewritten as a recursive parser so markup accumulates
  ({green}**bold green**{/} and friends nest freely, colors close inner-first)
- [label](url) dialogue links open in an iframe popup dialog so
  conversation progress survives; only http(s)/relative urls render
- NEW badges: Converse button + choice buttons badge unread paths via a
  per-browser seen map (ptf:npc-dialogue-seen) keyed by flow hash, so GM
  edits re-flag the conversation
- choices gain lockedHint: failing conditions can show the choice disabled
  with a rich tooltip instead of hiding it (evaluateNpcDialogueChoices now
  returns ChoiceGate pass/showLocked pairs)
- player flags gain activatesAt/expiresAt time windows honored by readFlag,
  flag effects gain flagDelayMinutes for slow-burn writes, and
  {{countdown:key}} tokens tick live toward activation (done/missing states)
- migration 20261006_add_flag_time_windows; spec extended to 33 tests
2026-10-06 17:06:27 -04:00

270 lines
9.1 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).
*/
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;
/** 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;
}
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;
/** 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;
}
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.`);
}
}
}
return { valid: errors.length === 0, errors };
}