- {d.condition?.key ? (
+ {d.condition && !hasEmptyConditionKey(d.condition) ? (
- Flag {d.condition.key}{" "}
- {d.condition.op}
- {typeof d.condition.amount === "number" && (
- {d.condition.amount}
- )}
+ Flag {conditionSummary(d.condition)}
) : (
Set a flag key to branch on.
diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx
index 2a975ab7..3db55742 100644
--- a/src/components/frontend/personnel/NpcConversation.tsx
+++ b/src/components/frontend/personnel/NpcConversation.tsx
@@ -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;
}
diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts
index feed0007..29038975 100644
--- a/src/lib/npc-dialogue/dialogue.ts
+++ b/src/lib/npc-dialogue/dialogue.ts
@@ -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 (
diff --git a/src/lib/npc-dialogue/flags.ts b/src/lib/npc-dialogue/flags.ts
index f956acc6..be81fbb4 100644
--- a/src/lib/npc-dialogue/flags.ts
+++ b/src/lib/npc-dialogue/flags.ts
@@ -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 {
+ 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) {
diff --git a/src/lib/npc-dialogue/interpolate.ts b/src/lib/npc-dialogue/interpolate.ts
index e336cf54..0005cc4a 100644
--- a/src/lib/npc-dialogue/interpolate.ts
+++ b/src/lib/npc-dialogue/interpolate.ts
@@ -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): 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();
+ 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 {
+ 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 {
+ 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();
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,
countdowns: Record = {},
+ truths: Record = {},
): 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);
diff --git a/src/lib/npc-dialogue/selection.ts b/src/lib/npc-dialogue/selection.ts
index e555aedb..54cc0397 100644
--- a/src/lib/npc-dialogue/selection.ts
+++ b/src/lib/npc-dialogue/selection.ts
@@ -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(
docs: readonly T[],
- evaluate: (condition: DialogueCondition) => Promise,
+ evaluate: (condition: DialogueFlagCondition) => Promise,
): Promise {
const ordered = [...docs].sort(
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,
diff --git a/tests/int/npc-dialogue-condition-groups.int.spec.ts b/tests/int/npc-dialogue-condition-groups.int.spec.ts
new file mode 100644
index 00000000..d17f788c
--- /dev/null
+++ b/tests/int/npc-dialogue-condition-groups.int.spec.ts
@@ -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 {
+ 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");
+ });
+});
diff --git a/tests/int/npc-dialogue-interpolate.int.spec.ts b/tests/int/npc-dialogue-interpolate.int.spec.ts
index c6290a11..ac279a21 100644
--- a/tests/int/npc-dialogue-interpolate.int.spec.ts
+++ b/tests/int/npc-dialogue-interpolate.int.spec.ts
@@ -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"]));
+ });
+});