1
0
Fork 0

feat(npc-dialogue): interpolate flag values into conversation text

This commit is contained in:
Jason Fraley 2026-10-06 16:09:10 -04:00
parent 38eb8ff771
commit f20f57de66
5 changed files with 288 additions and 53 deletions

View file

@ -7,6 +7,8 @@ import type { User } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import type {
DialogueCondition,
DialogueFlagOp,
@ -124,7 +126,7 @@ async function runEffect(
if (!key) break;
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
const amount = effect.flagAmount ?? 0;
await applyFlagEffect(payload, userId, key, op, amount);
await applyFlagEffect(payload, userId, key, op, amount, effect.flagText);
await emitGameEvent(payload, {
type: EventTypes.NpcDialogue,
message: `Conversation set flag "${key}" (${op}).`,
@ -140,13 +142,15 @@ async function runEffect(
/**
* Effective value of a flag: player-specific entry takes priority; if absent,
* fall back to the global entry (user is null). Missing flags read false / 0.
* fall back to the global entry (user is null). Missing flags read false / 0 /
* empty. `text` is the string the flag contributes to interpolated dialogue
* (booleans render "true"/"false", numbers their digits, text flags verbatim).
*/
async function readFlag(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,
key: string,
): Promise<{ bool: boolean; num: number }> {
): Promise<{ bool: boolean; num: number; text: string }> {
// Player-specific flag (priority).
const playerRes = await payload.find({
collection: "player-flags",
@ -159,14 +163,7 @@ async function readFlag(
overrideAccess: true,
});
const playerDoc = playerRes.docs[0];
if (playerDoc) {
if (playerDoc.flagType === "number") {
const num = playerDoc.numberValue ?? 0;
return { bool: num !== 0, num };
}
const bool = playerDoc.boolValue === true;
return { bool, num: bool ? 1 : 0 };
}
if (playerDoc) return flagValues(playerDoc);
// Global fallback (user is null).
const globalRes = await payload.find({
@ -180,13 +177,27 @@ async function readFlag(
overrideAccess: true,
});
const globalDoc = globalRes.docs[0];
if (!globalDoc) return { bool: false, num: 0 };
if (globalDoc.flagType === "number") {
const num = globalDoc.numberValue ?? 0;
return { bool: num !== 0, num };
if (!globalDoc) return { bool: false, num: 0, text: "" };
return flagValues(globalDoc);
}
/** Reads a stored flag doc into its condition + interpolation values. */
function flagValues(doc: {
flagType: "boolean" | "number" | "text";
boolValue?: boolean | null;
numberValue?: number | null;
textValue?: string | null;
}): { bool: boolean; num: number; text: string } {
if (doc.flagType === "number") {
const num = doc.numberValue ?? 0;
return { bool: num !== 0, num, text: String(num) };
}
const bool = globalDoc.boolValue === true;
return { bool, num: bool ? 1 : 0 };
if (doc.flagType === "text") {
const text = doc.textValue ?? "";
return { bool: text.trim().length > 0, num: 0, text };
}
const bool = doc.boolValue === true;
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false" };
}
/** Create-or-update a player flag according to the effect's write mode. */
@ -196,6 +207,7 @@ async function applyFlagEffect(
key: string,
op: DialogueFlagOp,
amount: number,
effectText?: string,
): Promise<void> {
const existing = await payload.find({
collection: "player-flags",
@ -246,6 +258,25 @@ async function applyFlagEffect(
return;
}
if (op === "set_text") {
const textValue = effectText ?? "";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "text", textValue },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "text", textValue },
overrideAccess: true,
});
}
return;
}
// add: numeric flags accumulate; boolean flags convert (true = 1).
const current = doc
? doc.flagType === "number"
@ -355,6 +386,47 @@ export async function evaluateNpcDialogueChoices(
}
}
/**
* Resolve every interpolatable display string of one node against the reading
* user's live flags. Tokens (`{{key}}`) are replaced server-side at render
* time, so interpolated values may contain dialogue markup (colors) and stay
* fresh when flags change mid-conversation. Only the flag keys a node actually
* references are read; substituted values are never re-scanned for tokens.
*/
export async function resolveNpcDialogueTexts(
npcId: number,
nodeId: string,
): Promise<ActionResult<ResolvedNodeTexts>> {
try {
const { payload, user } = await authenticate();
const res = await payload.find({
collection: "npc-dialogues",
where: { npc: { equals: npcId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
const node = flowData?.nodes?.find((n) => n.id === nodeId);
if (!node) return { success: true, data: {} };
const keys = collectNodeTokens(node);
const values: Record<string, string> = {};
for (const key of keys) {
const flag = await readFlag(payload, user.id as number, key);
values[key] = flag.text;
}
return { success: true, data: resolveNodeTexts(node, values) };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}
async function evaluateCondition(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,

View file

@ -47,6 +47,7 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
set_true: "Set to true",
set_false: "Set to false",
set_number: "Set number to",
set_text: "Set text to",
add: "Add to number",
};
@ -191,7 +192,8 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<p className="text-[10px] text-white/40">
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}.
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}. Insert flag values
with {'{{flag_key}}'}; text flags may carry their own color markup.
</p>
</div>
)}
@ -356,6 +358,9 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
</p>
</div>
<div className="flex flex-col gap-1.5">
@ -430,9 +435,26 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
/>
</div>
)}
{draft.effect.flagOp === "set_text" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Text value
</Label>
<Input
value={draft.effect.flagText ?? ""}
onChange={(e) => patchEffect({ flagText: e.target.value || undefined })}
placeholder="{green}NOMINAL{/}"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
Conversations insert this value wherever {'{{key}}'} appears. Colors like
{` {green}...{/}`} render in dialogue lines.
</p>
</div>
)}
<p className="text-[10px] text-white/40">
Creates the flag when the player does not have it yet. "Add" keeps numeric
flags running totals.
flags running totals; "Set text to" converts the flag to a text flag.
</p>
</div>
)}
@ -568,6 +590,9 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
</p>
</div>
)}

View file

@ -5,6 +5,8 @@ import { MessageCircleIcon, XIcon } from "lucide-react";
import type { GameNpc } from "@/payload-types";
import type { DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
@ -17,6 +19,7 @@ import {
import {
evaluateNpcDialogueChoices,
evaluateNpcDialogueCondition,
resolveNpcDialogueTexts,
triggerNpcDialogueEvent,
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
@ -31,7 +34,14 @@ interface ResolvedFlow {
}
type LogEntry =
| { kind: "node"; id: string; node: DialogueNode; triggered: boolean }
| {
kind: "node";
id: string;
node: DialogueNode;
/** Server-resolved display strings (flag tokens interpolated), when the
* node had tokens. Undefined = render the raw authored strings. */
resolved?: ResolvedNodeTexts;
}
| { kind: "player"; id: string; text: string };
/** Resolves the authored flowchart into a shape the runtime can walk. */
@ -83,23 +93,6 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
[],
);
// Trigger every arrived event node's effect exactly once, in order (the
// opening cascade can land on several events at once).
useEffect(() => {
const pending = log.find(
(entry) =>
entry.kind === "node" &&
entry.node.type === "event" &&
!!entry.node.data.effect &&
!entry.triggered,
);
if (!pending || pending.kind !== "node") return;
void triggerNpcDialogueEvent(Number(npc.id), pending.node.id).catch(() => undefined);
setLog((prev) =>
prev.map((entry) => (entry.id === pending.id ? { ...entry, triggered: true } : entry)),
);
}, [log, npc.id]);
// Keep the newest line in view.
useEffect(() => {
const el = scrollRef.current;
@ -135,13 +128,21 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
/** Appends a node to the log after a length-based "typing" delay. */
/** Resolves the node's display strings server-side (flag tokens), then
* appends it to the log after a length-based "typing" delay. Nodes without
* tokens skip the round trip and render their raw authored text. */
const typeIn = async (node: DialogueNode, token: number) => {
let resolved: ResolvedNodeTexts | undefined;
if (collectNodeTokens(node).length > 0) {
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
if (sessionRef.current !== token) return;
if (res.success && res.data) resolved = res.data;
}
setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name);
await sleep(typingDelayMs(nodeText(node)));
if (sessionRef.current !== token) return;
setTyping(null);
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, triggered: false }]);
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]);
};
// Opening the conversation walks the start node and auto-advances through
@ -196,6 +197,12 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
await typeIn(current, token);
if (sessionRef.current !== token) return;
if (current.type === "dialogue" || current.type === "event") {
if (current.type === "event" && current.data.effect) {
// Await the effect so flags it writes are visible to the lines
// that follow (interpolated text and later condition nodes).
await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined);
if (sessionRef.current !== token) return;
}
const target: string | undefined = current.data.next?.target;
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
} else {
@ -214,10 +221,11 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
const lastNode = [...log].reverse().find((entry) => entry.kind === "node");
// The player's line types out (shorter than NPC pacing), lands, and then
// the NPC starts typing its reply.
const pick = (hop: DialogueNext, choiceIndex: number) => {
// the NPC starts typing its reply. `displayText` is the label as shown on
// the button (flag tokens already interpolated server-side).
const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => {
const token = sessionRef.current;
const text = hop.label || "…";
const text = displayText || hop.label || "…";
if (hop.once && lastNode && lastNode.kind === "node") {
const key = `${lastNode.node.id}:${choiceIndex}`;
setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
@ -250,6 +258,13 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
)
: [];
/** Button text for a choice: the server-resolved label when the choice
* node's strings contained flag tokens, the raw label otherwise. */
const choiceLabel = (hop: DialogueNext, index: number): string =>
((lastNode?.kind === "node" ? lastNode.resolved?.labels?.[index] : undefined) ??
hop.label) ||
"…";
return (
<>
<Button
@ -310,10 +325,10 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
<button
key={index}
type="button"
onClick={() => pick(hop, index)}
onClick={() => pick(hop, index, choiceLabel(hop, index))}
className="w-full rounded-none border border-white/20 bg-black/40 px-3 py-2 text-left text-sm text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
>
{hop.label || "…"}
<DialogueText text={choiceLabel(hop, index)} />
</button>
))
) : (
@ -346,17 +361,19 @@ function TimelineEntry({
<div className="flex flex-col items-end gap-1">
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
<p className="max-w-[85%] rounded-none border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-sm text-cyan-50">
{entry.text}
<DialogueText text={entry.text} />
</p>
</div>
);
}
const { node } = entry;
const { node, resolved } = entry;
if (node.type === "event") {
// Narration: no speaker, styled like a mission briefing line.
const text = node.data.body || node.data.effect?.message || "An event unfolds…";
const body = resolved?.body ?? node.data.body;
const message = resolved?.message ?? node.data.effect?.message;
const text = body || message || "An event unfolds…";
return (
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
@ -365,30 +382,33 @@ function TimelineEntry({
}
if (node.type === "end") {
const text = (resolved?.closing ?? node.data.closing) || "The conversation ends.";
return (
<p className="text-sm italic text-white/50">
<DialogueText text={node.data.closing || "The conversation ends."} />
<DialogueText text={text} />
</p>
);
}
if (node.type === "choice") {
// The choice buttons live in the footer; only the lead-in joins the log.
if (!node.data.leadIn) return null;
const leadIn = resolved?.leadIn ?? node.data.leadIn;
if (!leadIn) return null;
return (
<p className="text-sm italic text-white/60">
<DialogueText text={node.data.leadIn} />
<DialogueText text={leadIn} />
</p>
);
}
const speaker = node.data.speaker?.trim() || speakerDefault;
const body = resolved?.body ?? node.data.body;
return (
<div className="flex flex-col gap-1">
<span className={DOSSIER.readoutLabel}>{speaker}</span>
<p className="text-sm text-white/90">
{node.data.body ? (
<DialogueText text={node.data.body} />
{body ? (
<DialogueText text={body} />
) : (
<span className="italic text-white/30">…</span>
)}

View file

@ -53,7 +53,7 @@ export interface DialogueCondition {
}
/** How a flag effect writes the flag. */
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "add";
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "set_text" | "add";
/** Configured effect for an `event` node. */
export interface NpcDialogueEffect {
@ -68,6 +68,8 @@ export interface NpcDialogueEffect {
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;
}
export type DialogueNodeData = {

View file

@ -0,0 +1,116 @@
/**
* Dynamic text interpolation for NPC conversation strings.
*
* Authors embed flag values with double-brace tokens: `{{network_status}}`.
* Resolution happens server-side when a conversation line is about to render
* (see the `resolveNpcDialogueTexts` action), so an interpolated value may
* itself contain display markup like `{green}NOMINAL{/}` and still render
* colored through DialogueText. Values are substituted in a single pass and
* never re-scanned, so a flag value can never smuggle in another token.
*
* Pure module: client-safe (no Payload imports).
*/
import type { DialogueNode } from "./dialogue";
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
* are documented as lowercase-with-underscores. */
const FLAG_TOKEN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
/** The display strings of a node that support interpolation. */
export interface ResolvedNodeTexts {
body?: string;
leadIn?: string;
closing?: string;
/** Event node narration fallback (`effect.message`). */
message?: string;
/** Choice button labels, index-aligned with the node's choices. */
labels?: string[];
}
/** Every distinct flag key referenced by `text`, lowercased. */
export function extractFlagTokens(text: string | undefined): string[] {
if (!text) return [];
const keys = new Set<string>();
for (const match of text.matchAll(FLAG_TOKEN)) {
keys.add(match[1].toLowerCase());
}
return [...keys];
}
/** True when `text` contains at least one interpolation token. */
export function hasFlagTokens(text: string | undefined): boolean {
if (!text) return false;
FLAG_TOKEN.lastIndex = 0;
return FLAG_TOKEN.test(text);
}
/**
* Replace every `{{key}}` token with its value. Keys missing from `values`
* resolve to an empty string; substituted values are NOT re-scanned.
*/
export function interpolateFlags(
text: string | undefined,
values: Record<string, string>,
): string {
if (!text) return "";
return text.replace(FLAG_TOKEN, (_match, key: string) => values[key.toLowerCase()] ?? "");
}
/** Minimal shape needed to format a flag's value for interpolation. */
export interface FlagValueLike {
flagType: "boolean" | "number" | "text";
boolValue?: boolean | null;
numberValue?: number | null;
textValue?: string | null;
}
/** The string a flag contributes to interpolated text. */
export function formatFlagValue(flag: FlagValueLike): string {
switch (flag.flagType) {
case "number":
return String(flag.numberValue ?? 0);
case "text":
return flag.textValue ?? "";
default:
return flag.boolValue === true ? "true" : "false";
}
}
/** All flag keys the node's display strings reference (deduped, lowercased). */
export function collectNodeTokens(node: DialogueNode): string[] {
const keys = new Set<string>();
const texts = [
node.data.body,
node.data.leadIn,
node.data.closing,
node.data.effect?.message,
...(node.data.choices?.map((c) => c.label) ?? []),
];
for (const text of texts) {
for (const key of extractFlagTokens(text)) keys.add(key);
}
return [...keys];
}
/**
* Interpolates every display string of a node against resolved flag values.
* Only fields the node actually defines are returned, so the client can tell
* "resolved to empty" apart from "no such field".
*/
export function resolveNodeTexts(
node: DialogueNode,
values: Record<string, string>,
): ResolvedNodeTexts {
const resolved: ResolvedNodeTexts = {};
if (node.data.body !== undefined) resolved.body = interpolateFlags(node.data.body, values);
if (node.data.leadIn !== undefined) resolved.leadIn = interpolateFlags(node.data.leadIn, values);
if (node.data.closing !== undefined)
resolved.closing = interpolateFlags(node.data.closing, values);
if (node.data.effect?.message !== undefined)
resolved.message = interpolateFlags(node.data.effect.message, values);
if (node.data.choices) {
resolved.labels = node.data.choices.map((choice) => interpolateFlags(choice.label, values));
}
return resolved;
}