1
0
Fork 0

feat(npc-dialogue): condition groups and ternary text tokens

Conditions become a discriminated union: the existing flag leaf plus a
single-level group combining leaves with AND / OR / NOR. The evaluator
recurses one level, and every flat-assuming site (choice gating, graph
validation, editor, canvas previews) is group-aware; DB entry gates stay
flat by design. The node editor gains a shared condition builder with a
combinator dropdown and repeatable rows for both branch nodes and gated
choices.

Display strings also gain ternaries: {{ key ? yes : no }}, {{ !key ? .. }},
and numeric compares like {{ rep >= 5 ? .. }}. A brace-depth scanner
rewrites ternaries over bounded passes so branches may nest flag tokens
and even nested ternaries, then plain interpolation runs its single
never-rescanned pass. Ternary keys join collectNodeTokens so the server
reads exactly the flags a node needs.
This commit is contained in:
Jason Fraley 2026-10-14 16:21:16 -04:00
parent a1aaed913d
commit c299acbe4f
10 changed files with 646 additions and 133 deletions

View file

@ -19,6 +19,7 @@ import type {
FlowData,
NpcDialogueEffect,
} from "@/lib/npc-dialogue/dialogue";
import { hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
interface ActionResult<T = undefined> {
success: boolean;
@ -230,7 +231,7 @@ export async function evaluateNpcDialogueChoices(
const gates: ChoiceGate[] = [];
for (const choice of node.data.choices ?? []) {
const showLocked = Boolean(choice.lockedHint?.trim());
if (!choice.condition?.key?.trim()) {
if (!choice.condition || hasEmptyConditionKey(choice.condition)) {
gates.push({ pass: true, showLocked });
continue;
}
@ -275,14 +276,17 @@ export async function resolveNpcDialogueTexts(
const keys = collectNodeTokens(node);
const values: Record<string, string> = {};
const countdowns: Record<string, string> = {};
const truths: Record<string, { bool: boolean; num: number }> = {};
for (const key of keys) {
const flag = await readFlag(payload, user.id as number, key);
values[key] = flag.text;
// Countdown leaf: pending flags tick toward activation, active ones read
// "done", missing ones render nothing.
countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : "");
// Truth inputs for ternary conditions (`{{ key ? .. : .. }}`).
truths[key] = { bool: flag.bool, num: flag.num };
}
const resolved = resolveNodeTexts(node, values, countdowns);
const resolved = resolveNodeTexts(node, values, countdowns, truths);
// Attachments ride the same round trip: ids become renderable file
// references here, so the client never guesses media URLs and deleted
// files simply drop off instead of rendering dead chips.

View file

@ -19,6 +19,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import type {
DialogueAttachment,
DialogueCondition,
DialogueConditionGroup,
DialogueFlagCondition,
DialogueFlagOp,
DialogueNext,
DialogueNode,
@ -26,7 +28,7 @@ import type {
NpcDialogueEffect,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
@ -54,7 +56,7 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
add: "Add to number",
};
const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
is_true: "is true",
is_false: "is false",
gte: "is at least",
@ -64,8 +66,18 @@ const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
eq: "equals",
};
/** Group combinators, in UI order. Groups are single-level over leaves. */
const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
and: "All conditions match (AND)",
or: "Any condition matches (OR)",
nor: "No condition matches (NOR)",
};
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** A blank leaf used when switching into single mode or adding a group row. */
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };
/** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls
* inside the box from here; the user can still drag-resize it taller. */
@ -100,7 +112,7 @@ function nodeLabel(node: DialogueNode): string {
break;
case "condition": {
const c = d.condition;
preview = c ? `flag "${c.key || "?"}" ${CONDITION_OP_LABELS[c.op]}` : "Condition";
preview = c ? conditionSummary(c) : "Condition";
break;
}
default:
@ -173,10 +185,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
patch({ effect: { type: "notify", ...draft.effect, ...partial } });
const patchCondition = (partial: Partial<DialogueCondition>) =>
patch({
condition: { kind: "flag", key: "", op: "is_true", ...draft.condition, ...partial },
});
const setChoice = (index: number, next: DialogueNext) =>
patch({ choices: (draft.choices ?? []).map((choice, i) => (i === index ? next : choice)) });
@ -194,15 +203,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
if (ordered) patch({ choices: ordered });
};
/** Toggle/update a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
/** Toggle/replace a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, next: DialogueCondition | null) =>
patch({
choices: (draft.choices ?? []).map((c, i) => {
if (i !== index) return c;
if (partial === null) return { ...c, condition: undefined };
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
return { ...c, condition: { ...base, ...partial } };
}),
choices: (draft.choices ?? []).map((c, i) =>
i === index ? { ...c, condition: next ?? undefined } : c,
),
});
const targetOptions = allNodes.filter((n) => n.id !== node.id);
@ -258,7 +264,9 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
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}`}. Insert flag values
with {'{{flag_key}}'}; text flags may carry their own color markup. Inline
with {'{{flag_key}}'}; text flags may carry their own color markup. Pick a branch
with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and
{'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline
images use {'![alt](url)'} (e.g. {`![coin](/api/media/file/coin.png)`}) and
render at text height.
</p>
@ -374,7 +382,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Checkbox
checked={choice.condition !== undefined}
onCheckedChange={(checked) =>
setChoiceCondition(index, checked === true ? {} : null)
setChoiceCondition(index, checked === true ? EMPTY_LEAF : null)
}
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
/>
@ -382,50 +390,10 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</label>
{choice.condition && (
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Flag key
</Label>
<Input
value={choice.condition.key}
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
<ConditionFields
value={choice.condition}
onChange={(next) => setChoiceCondition(index, next)}
/>
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
When the flag
</Label>
<select
value={choice.condition.op}
onChange={(e) =>
setChoiceCondition(index, {
op: e.target.value as DialogueCondition["op"],
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
(op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
),
)}
</select>
{NUMERIC_OPS.includes(choice.condition.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Amount
</Label>
<Input
type="number"
value={choice.condition.amount ?? 0}
onChange={(e) =>
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Lock message (optional)
</Label>
@ -705,51 +673,14 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "condition" && (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Flag key
</Label>
<Input
value={draft.condition?.key ?? ""}
onChange={(e) => patchCondition({ key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing = false / 0.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
When the flag
</Label>
<select
value={draft.condition?.op ?? "is_true"}
onChange={(e) => patchCondition({ op: e.target.value as DialogueCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
</div>
{NUMERIC_OPS.includes(draft.condition?.op ?? "is_true") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Amount
</Label>
<Input
type="number"
value={draft.condition?.amount ?? 0}
onChange={(e) => patchCondition({ amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<ConditionFields
value={draft.condition ?? EMPTY_LEAF}
onChange={(condition) => patch({ condition })}
/>
<p className="-mt-2 text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing =
false / 0.
</p>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
@ -973,3 +904,121 @@ function AttachmentEditor({
</div>
);
}
/**
* Single-level condition builder: a combinator dropdown (one flag, or an
* AND / OR / NOR group) plus one editable row per leaf. Groups never nest,
* which keeps authored JSON shallow and the runtime evaluator single-pass.
*/
function ConditionFields({
value,
onChange,
}: {
value: DialogueCondition;
onChange: (next: DialogueCondition) => void;
}) {
const mode = value.kind === "group" ? `group:${value.op}` : "leaf";
const setMode = (next: string) => {
if (next === mode) return;
if (next === "leaf") {
onChange(value.kind === "group" ? (value.children[0] ?? EMPTY_LEAF) : value);
return;
}
const op = next.slice("group:".length) as DialogueConditionGroup["op"];
if (value.kind === "group") onChange({ ...value, op });
else onChange({ kind: "group", op, children: [value] });
};
const patchLeaf = (index: number, partial: Partial<DialogueFlagCondition>) => {
if (value.kind === "flag" && index === 0) onChange({ ...value, ...partial });
else if (value.kind === "group")
onChange({
...value,
children: value.children.map((c, i) => (i === index ? { ...c, ...partial } : c)),
});
};
const leaves = value.kind === "group" ? value.children : [value];
return (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Condition</Label>
<select
value={mode}
onChange={(e) => setMode(e.target.value)}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="leaf">Single flag condition</option>
{(Object.keys(GROUP_OP_LABELS) as DialogueConditionGroup["op"][]).map((op) => (
<option key={op} value={`group:${op}`}>
{GROUP_OP_LABELS[op]}
</option>
))}
</select>
{leaves.map((leaf, index) => (
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-1.5">
<div className="flex items-center justify-between">
<Label className="text-[9px] uppercase tracking-wider text-white/40">
{value.kind === "group" ? `Condition ${index + 1}` : "Flag key"}
</Label>
{value.kind === "group" && leaves.length > 1 && (
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove condition"
onClick={() =>
onChange({ ...value, children: value.children.filter((_, i) => i !== index) })
}
className="h-5 border-red-900/50 px-1.5 text-[10px] text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
)}
</div>
<Input
value={leaf.key}
onChange={(e) => patchLeaf(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<Label className="text-[9px] uppercase tracking-wider text-white/40">When the flag</Label>
<select
value={leaf.op}
onChange={(e) => patchLeaf(index, { op: e.target.value as DialogueFlagCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueFlagCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
{NUMERIC_OPS.includes(leaf.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Amount</Label>
<Input
type="number"
value={leaf.amount ?? 0}
onChange={(e) => patchLeaf(index, { amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
</div>
))}
{value.kind === "group" && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onChange({ ...value, children: [...value.children, EMPTY_LEAF] })}
className="h-6 self-end border-white/20 text-xs text-white"
>
Add condition
</Button>
)}
</div>
);
}

View file

@ -11,6 +11,7 @@ import {
} from "lucide-react";
import type { DialogueNodeData, NpcDialogueNodeType } from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { DIALOGUE_NODES } from "./types";
@ -95,7 +96,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
{choice.condition && (
<span
className="shrink-0 rounded-sm border border-sky-500/40 bg-sky-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-sky-300"
title={`Only shown when flag "${choice.condition.key}" ${choice.condition.op.replace(/_/g, " ")}`}
title={`Only shown when ${conditionSummary(choice.condition)}`}
>
gated
</span>
@ -162,13 +163,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
{nodeType === "condition" && (
<div className="flex flex-col gap-1.5 text-sm text-white/70">
<div>
{d.condition?.key ? (
{d.condition && !hasEmptyConditionKey(d.condition) ? (
<span>
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
<span className="text-white/50">{d.condition.op}</span>
{typeof d.condition.amount === "number" && (
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
)}
Flag <span className="font-mono text-sky-300">{conditionSummary(d.condition)}</span>
</span>
) : (
<span className="italic text-white/30">Set a flag key to branch on.</span>

View file

@ -9,7 +9,7 @@ import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
import { Button } from "@/components/ui/button";
import {
@ -130,7 +130,9 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
if (!open || !flow || !activeChoiceNodeId) return;
if (choiceGates[activeChoiceNodeId]) return;
const node = flow.nodes.find((n) => n.id === activeChoiceNodeId);
const hasGated = (node?.data.choices ?? []).some((c) => c.condition?.key?.trim());
const hasGated = (node?.data.choices ?? []).some(
(c) => c.condition && !hasEmptyConditionKey(c.condition),
);
if (!hasGated) return;
let cancelled = false;
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
@ -290,7 +292,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
{ hop: DialogueNext; index: number; locked: boolean }[]
>((acc, hop, index) => {
if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc;
if (!hop.condition?.key?.trim()) {
if (!hop.condition || hasEmptyConditionKey(hop.condition)) {
acc.push({ hop, index, locked: false });
return acc;
}

View file

@ -61,7 +61,7 @@ export interface ChoiceGate {
* true/false; numeric flags compare against `amount` (a missing flag counts
* as false / zero).
*/
export interface DialogueCondition {
export interface DialogueFlagCondition {
/** Currently only generic player flags; more kinds can join later. */
kind: "flag";
/** `player-flags` key checked for the reading user. */
@ -72,8 +72,22 @@ export interface DialogueCondition {
amount?: number;
}
/** All condition operators, in UI order. */
export const CONDITION_OPS: DialogueCondition["op"][] = [
/**
* 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",
"gte",
@ -299,6 +313,28 @@ export interface GraphValidation {
errors: string[];
}
/** 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 && !["is_true", "is_false"].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);
}
/** 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
@ -316,6 +352,9 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
}
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;
@ -325,7 +364,7 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
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()) {
if (node.type === "choice" && hop.condition && hasEmptyConditionKey(hop.condition)) {
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
}
if (

View file

@ -144,12 +144,29 @@ export function flagValues(doc: {
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false", exists: true };
}
/** Evaluates one authored condition against the user's live flags. */
/**
* Evaluates one authored condition against the user's live flags. Leaves
* compare a single flag; groups combine leaves with and / or / nor (groups
* are single-level by construction, so recursion stops at the children).
*/
export async function evaluateCondition(
payload: Payload,
userId: number,
condition: DialogueCondition,
): Promise<boolean> {
if (condition.kind === "group") {
const results = await Promise.all(
(condition.children ?? []).map((child) => evaluateCondition(payload, userId, child)),
);
switch (condition.op) {
case "and":
return results.every(Boolean);
case "or":
return results.some(Boolean);
default:
return results.every((pass) => !pass);
}
}
const flag = await readFlag(payload, userId, condition.key);
const amount = condition.amount ?? 0;
switch (condition.op) {

View file

@ -47,6 +47,173 @@ export function replaceCountdowns(
return text.replace(COUNTDOWN_TOKEN, (_match, key: string) => `{cd|${countdowns[key.toLowerCase()] ?? ""}}`);
}
/**
* Ternary token: `{{ cond ? 'yes' : 'no' }}`, where `cond` is an optional
* `!` plus a flag key plus an optional numeric comparison (`>= 5`, `< 2`,
* `= 0`, `> 1`, `<= 10`). Branches are free text and may themselves contain
* `{{flag}}` tokens, color markup, or nested ternaries; those resolve on
* later passes (bounded) before `interpolateFlags` runs its single pass.
*/
const TERNARY_CONDITION = /^(!?)\s*([a-zA-Z0-9_]+)\s*(?:(>=|<=|>|<|=)\s*(-?\d+(?:\.\d+)?))?$/;
/** How many rewrite passes `resolveTernaries` makes over one string. Nested
* ternaries deeper than this stay literal, which beats any unbounded loop. */
const MAX_TERNARY_PASSES = 4;
/** The truth inputs a ternary condition reads for one flag key. */
export interface TernaryTruth {
bool: boolean;
num: number;
}
/** Evaluates one parsed ternary condition against live flag truths. Missing
* flags read falsy (false / 0), matching condition-node semantics. */
function ternaryConditionPasses(condition: string, truths: Record<string, TernaryTruth>): boolean {
const match = TERNARY_CONDITION.exec(condition.trim());
if (!match) return false;
const [, negate, key, cmp, amount] = match;
const flag = truths[key.toLowerCase()];
let pass: boolean;
if (cmp) {
pass = compareNumeric(flag?.num ?? 0, cmp, Number(amount));
} else {
pass = flag?.bool === true;
}
return negate === "!" ? !pass : pass;
}
function compareNumeric(left: number, op: string, right: number): boolean {
switch (op) {
case ">=":
return left >= right;
case "<=":
return left <= right;
case ">":
return left > right;
case "<":
return left < right;
default:
return left === right;
}
}
interface FoundTernary {
/** Index of the opening `{{`. */
start: number;
/** Index just past the closing `}}`. */
end: number;
condition: string;
whenTrue: string;
whenFalse: string;
}
/**
* Finds the next ternary token at or after `from` with a brace-depth scan:
* nested `{{ }}` raise the depth so their `?`/`:` never split the outer
* token, and the token ends at the `}}` that returns depth to zero. The
* boundaries are the first top-level `?` and the first top-level `:` after
* it, so authors separate parts with spaces around `?` and `:` (a literal
* colon in branch text is not supported). Tokens without both boundaries
* (plain flags, countdowns) are skipped, not treated as ternaries.
*/
function findTernary(text: string, from: number): FoundTernary | null {
let cursor = from;
while (cursor < text.length) {
const open = text.indexOf("{{", cursor);
if (open === -1) return null;
let depth = 1;
let i = open + 2;
let questionAt = -1;
let colonAt = -1;
let end = -1;
while (i < text.length) {
const ch = text[i];
if (ch === "{" && text[i + 1] === "{") {
depth += 1;
i += 2;
continue;
}
if (ch === "}" && text[i + 1] === "}") {
depth -= 1;
if (depth === 0) {
end = i + 2;
break;
}
i += 2;
continue;
}
if (depth === 1) {
if (ch === "?" && questionAt === -1) questionAt = i;
else if (ch === ":" && questionAt !== -1 && colonAt === -1) colonAt = i;
}
i += 1;
}
if (end === -1) return null;
if (questionAt !== -1 && colonAt !== -1) {
return {
start: open,
end,
condition: text.slice(open + 2, questionAt),
whenTrue: text.slice(questionAt + 1, colonAt).trim(),
whenFalse: text.slice(colonAt + 1, end - 2).trim(),
};
}
cursor = open + 2;
}
return null;
}
/** Every flag key referenced by ternary conditions in `text`, lowercased. */
export function extractTernaryKeys(text: string | undefined): string[] {
if (!text) return [];
const keys = new Set<string>();
for (const token of iterTernaries(text)) {
const match = TERNARY_CONDITION.exec(token.condition.trim());
if (match) keys.add(match[2].toLowerCase());
}
return [...keys];
}
/** Iterates every well-formed ternary token in `text` (top level per scan). */
function* iterTernaries(text: string): Generator<FoundTernary> {
let cursor = 0;
for (;;) {
const found = findTernary(text, cursor);
if (!found) return;
yield found;
cursor = found.end;
}
}
/**
* Rewrites ternary tokens to their taken branch over a bounded number of
* passes, so branches containing nested tokens resolve on later passes. The
* chosen branch is inserted verbatim; `interpolateFlags` then substitutes
* plain `{{flag}}` tokens in a final single pass that never re-scans values.
*/
export function resolveTernaries(
text: string | undefined,
truths: Record<string, TernaryTruth>,
): string {
if (!text || !text.includes("?")) return text ?? "";
let current = text;
for (let pass = 0; pass < MAX_TERNARY_PASSES; pass++) {
let out = "";
let cursor = 0;
let replaced = false;
for (const token of iterTernaries(current)) {
out += current.slice(cursor, token.start);
out += ternaryConditionPasses(token.condition, truths) ? token.whenTrue : token.whenFalse;
cursor = token.end;
replaced = true;
}
out += current.slice(cursor);
current = out;
if (!replaced) break;
}
return current;
}
/** The display strings of a node that support interpolation. */
export interface ResolvedNodeTexts {
body?: string;
@ -118,8 +285,8 @@ export function formatFlagValue(flag: FlagValueLike): string {
}
/** All flag keys the node's display strings reference (deduped, lowercased).
* Countdown (`{{countdown:key}}`) keys join this set too: they need the same
* server-side flag read to resolve their activation time. */
* Countdown (`{{countdown:key}}`) and ternary condition (`{{ key ? .. : .. }}`)
* keys join this set too: they need the same server-side flag read. */
export function collectNodeTokens(node: DialogueNode): string[] {
const keys = new Set<string>();
const texts = [
@ -132,22 +299,27 @@ export function collectNodeTokens(node: DialogueNode): string[] {
for (const text of texts) {
for (const key of extractFlagTokens(text)) keys.add(key);
for (const key of extractCountdownKeys(text)) keys.add(key);
for (const key of extractTernaryKeys(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".
* Ternaries resolve first (bounded passes, so nested tokens inside branches
* survive into the plain-token pass), then `{{key}}` substitution runs once,
* then countdown leaves are rewritten. 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>,
countdowns: Record<string, string> = {},
truths: Record<string, TernaryTruth> = {},
): ResolvedNodeTexts {
const finish = (text: string | undefined): string =>
replaceCountdowns(interpolateFlags(text, values), countdowns);
replaceCountdowns(interpolateFlags(resolveTernaries(text, truths), values), countdowns);
const resolved: ResolvedNodeTexts = {};
if (node.data.body !== undefined) resolved.body = finish(node.data.body);
if (node.data.leadIn !== undefined) resolved.leadIn = finish(node.data.leadIn);

View file

@ -9,12 +9,16 @@
* so this stays testable and client-safe.
*/
import type { DialogueCondition } from "./dialogue";
import type { DialogueFlagCondition } from "./dialogue";
/** The stored entry gate shape on an npc-dialogues document. */
/**
* The stored entry gate shape on an npc-dialogues document. Entry gates stay
* flat leaves by design (the DB column shape predates condition groups and
* gating a whole conversation with one flag is the intended use).
*/
export interface DialogueEntryGate {
key?: string | null;
op?: DialogueCondition["op"] | null;
op?: DialogueFlagCondition["op"] | null;
amount?: number | null;
}
@ -26,7 +30,9 @@ export interface GateCandidate {
}
/** Turns a stored gate into a runtime condition; null when ungated. */
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
export function gateCondition(
gate: DialogueEntryGate | null | undefined,
): DialogueFlagCondition | null {
const key = gate?.key?.trim();
if (!key || !gate) return null;
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
@ -39,7 +45,7 @@ export function gateCondition(gate: DialogueEntryGate | null | undefined): Dialo
*/
export async function selectDialogueForUser<T extends GateCandidate>(
docs: readonly T[],
evaluate: (condition: DialogueCondition) => Promise<boolean>,
evaluate: (condition: DialogueFlagCondition) => Promise<boolean>,
): Promise<T | null> {
const ordered = [...docs].sort(
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,

View file

@ -0,0 +1,160 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DialogueCondition, DialogueFlagCondition } from "@/lib/npc-dialogue/dialogue";
import { applyFlagEffect, evaluateCondition } from "@/lib/npc-dialogue/flags";
import { conditionSummary, hasEmptyConditionKey, validateGraph } from "@/lib/npc-dialogue/dialogue";
let payload: Payload;
const RUN = `grp_${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const userIds: number[] = [];
async function createUser(username: string): Promise<number> {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `GRP ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
userIds.push(user.id);
return user.id;
}
describe("condition groups (and / or / nor over leaf conditions)", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
const flags = await payload.find({
collection: "player-flags",
where: { key: { like: `${RUN}_%` } },
limit: 200,
overrideAccess: true,
});
for (const doc of flags.docs) {
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
});
it(
"combines leaves with and / or / nor against live flags",
async () => {
const user = await createUser(`${RUN}_combo`);
await applyFlagEffect(payload, user, `${RUN}_a`, "set_true", 0);
await applyFlagEffect(payload, user, `${RUN}_rep`, "set_number", 7);
const leafA: DialogueFlagCondition = { kind: "flag", key: `${RUN}_a`, op: "is_true" };
const leafMissing: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_nope`,
op: "is_true",
};
const leafRep: DialogueFlagCondition = { kind: "flag", key: `${RUN}_rep`, op: "gte", amount: 5 };
const leafRepFail: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_rep`,
op: "gte",
amount: 99,
};
const evalGroup = (op: "and" | "or" | "nor", children: DialogueFlagCondition[]) =>
evaluateCondition(payload, user, { kind: "group", op, children });
expect(await evalGroup("and", [leafA, leafRep])).toBe(true);
expect(await evalGroup("and", [leafA, leafMissing])).toBe(false);
expect(await evalGroup("or", [leafMissing, leafRep])).toBe(true);
expect(await evalGroup("or", [leafMissing, leafRepFail])).toBe(false);
expect(await evalGroup("nor", [leafMissing, leafRepFail])).toBe(true);
expect(await evalGroup("nor", [leafA, leafRepFail])).toBe(false);
},
TIMEOUT,
);
it(
"treats empty groups as vacuous (and/nor pass, or fails) and leaves still work",
async () => {
const user = await createUser(`${RUN}_empty`);
expect(await evaluateCondition(payload, user, { kind: "group", op: "and", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "nor", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "or", children: [] })).toBe(
false,
);
// A plain leaf keeps its old semantics.
expect(
await evaluateCondition(payload, user, { kind: "flag", key: `${RUN}_x`, op: "is_false" }),
).toBe(true);
},
TIMEOUT,
);
it("summarises and validates groups for the editor", () => {
const group: DialogueCondition = {
kind: "group",
op: "or",
children: [
{ kind: "flag", key: "met_informant", op: "is_true" },
{ kind: "flag", key: "rep", op: "gte", amount: 5 },
],
};
expect(conditionSummary(group)).toBe('"met_informant" is true or "rep" gte 5');
expect(hasEmptyConditionKey(group)).toBe(false);
expect(
hasEmptyConditionKey({
kind: "group",
op: "and",
children: [{ kind: "flag", key: " ", op: "is_true" }],
}),
).toBe(true);
expect(hasEmptyConditionKey({ kind: "group", op: "and", children: [] })).toBe(true);
const nodes = [
{
id: "start",
type: "dialogue" as const,
position: { x: 0, y: 0 },
data: { isStart: true, body: "hi", next: { target: "c1" } },
},
{
id: "c1",
type: "choice" as const,
position: { x: 0, y: 0 },
data: {
choices: [
{
label: "Ask",
target: "",
condition: {
kind: "group" as const,
op: "and" as const,
children: [{ kind: "flag" as const, key: " ", op: "is_true" as const }],
},
},
],
},
},
];
const validation = validateGraph(nodes);
expect(validation.valid).toBe(false);
expect(validation.errors.join(" ")).toContain("needs a flag key");
});
});

View file

@ -13,11 +13,13 @@ import {
collectNodeTokens,
extractCountdownKeys,
extractFlagTokens,
extractTernaryKeys,
formatFlagValue,
hasFlagTokens,
interpolateFlags,
replaceCountdowns,
resolveNodeTexts,
resolveTernaries,
} from "@/lib/npc-dialogue/interpolate";
let payload: Payload;
@ -454,3 +456,68 @@ describe("countdown token resolution (pure)", () => {
expect(out.hints?.[1]).toBe("");
});
});
describe("ternary tokens ({{ cond ? yes : no }})", () => {
const truths = {
trust: { bool: true, num: 1 },
met: { bool: false, num: 0 },
rep: { bool: true, num: 7 },
};
it("picks branches by boolean truth, negation and numeric comparison", () => {
expect(resolveTernaries("He is {{ trust ? friend : hostile }}.", truths)).toBe(
"He is friend.",
);
expect(resolveTernaries("He is {{ met ? friend : hostile }}.", truths)).toBe(
"He is hostile.",
);
expect(resolveTernaries("{{ !met ? who_are_you : welcome_back }}", truths)).toBe(
"who_are_you",
);
expect(resolveTernaries("{{ rep >= 5 ? elite : rookie }}", truths)).toBe("elite");
expect(resolveTernaries("{{ rep > 10 ? elite : rookie }}", truths)).toBe("rookie");
expect(resolveTernaries("{{ rep = 7 ? exact : off }}", truths)).toBe("exact");
});
it("treats missing flags as falsy and keeps malformed tokens literal", () => {
expect(resolveTernaries("{{ ghost ? a : b }}", truths)).toBe("b");
expect(resolveTernaries("{{ !ghost ? a : b }}", truths)).toBe("a");
// Not ternaries: plain flag, countdown, and a token without a colon.
const plain = "Status {{network_status}} at {{countdown:exfil}} maybe {{ broken";
expect(resolveTernaries(plain, truths)).toBe(plain);
});
it("leaves nested tokens for the later passes and resolves nested ternaries", () => {
// Branch tokens survive resolveTernaries; interpolateFlags fills them next.
const once = resolveTernaries("{{ trust ? {{ rep }} pts : none }}", truths);
expect(once).toBe("{{ rep }} pts");
expect(interpolateFlags(once, { rep: "7" })).toBe("7 pts");
// A ternary inside a branch resolves on the second bounded pass.
expect(
resolveTernaries("{{ trust ? {{ met ? seen : new }} : dark }}", truths),
).toBe("new");
});
it("extracts condition keys (negated and numeric) for the flag read", () => {
// The third token has no `?`, so it is not a ternary and contributes nothing.
expect(extractTernaryKeys("{{ trust ? a : b }} {{ !met ? c : d }} {{ rep >= 2 : e : f }}")).toEqual([
"trust",
"met",
]);
expect(extractTernaryKeys("{{ rep >= 2 ? e : f }}")).toEqual(["rep"]);
expect(extractTernaryKeys("no tokens {{plain}} {{countdown:x}}")).toEqual([]);
});
it("resolves through resolveNodeTexts with values, countdowns and truths", () => {
const node: DialogueNode = {
id: "t1",
type: "dialogue",
position: { x: 0, y: 0 },
data: { body: "{{ trust ? Status {{ rep }} : silent }} {{countdown:exfil}}" },
};
const resolved = resolveNodeTexts(node, { rep: "7" }, { exfil: "done" }, truths);
expect(resolved.body).toBe("Status 7 {cd|done}");
// collectNodeTokens must see ternary keys so the server reads those flags.
expect(collectNodeTokens(node)).toEqual(expect.arrayContaining(["trust", "rep", "exfil"]));
});
});