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
This commit is contained in:
parent
c1e13e5dc9
commit
f595828c99
14 changed files with 38344 additions and 142 deletions
|
|
@ -10,7 +10,12 @@ import { notifyUser } from "@/lib/notifications";
|
|||
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||
import type { DialogueFlagOp, FlowData, NpcDialogueEffect } from "@/lib/npc-dialogue/dialogue";
|
||||
import type {
|
||||
ChoiceGate,
|
||||
DialogueFlagOp,
|
||||
FlowData,
|
||||
NpcDialogueEffect,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
|
|
@ -122,7 +127,15 @@ 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, effect.flagText);
|
||||
await applyFlagEffect(
|
||||
payload,
|
||||
userId,
|
||||
key,
|
||||
op,
|
||||
amount,
|
||||
effect.flagText,
|
||||
effect.flagDelayMinutes,
|
||||
);
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `Conversation set flag "${key}" (${op}).`,
|
||||
|
|
@ -136,7 +149,9 @@ async function runEffect(
|
|||
}
|
||||
}
|
||||
|
||||
/** Create-or-update a player flag according to the effect's write mode. */
|
||||
/** Create-or-update a player flag according to the effect's write mode. A
|
||||
* positive `delayMinutes` stamps the flag with a future `activatesAt`, so it
|
||||
* reads as false until then (conditions fail, countdowns tick toward it). */
|
||||
async function applyFlagEffect(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
|
|
@ -144,7 +159,12 @@ async function applyFlagEffect(
|
|||
op: DialogueFlagOp,
|
||||
amount: number,
|
||||
effectText?: string,
|
||||
delayMinutes?: number,
|
||||
): Promise<void> {
|
||||
const activatesAt =
|
||||
delayMinutes && delayMinutes > 0
|
||||
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
|
||||
: null;
|
||||
const existing = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
|
|
@ -163,13 +183,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "boolean", boolValue },
|
||||
data: { flagType: "boolean", boolValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "boolean", boolValue },
|
||||
data: { user: userId, key, flagType: "boolean", boolValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -181,13 +201,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue: amount },
|
||||
data: { flagType: "number", numberValue: amount, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue: amount },
|
||||
data: { user: userId, key, flagType: "number", numberValue: amount, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -200,13 +220,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "text", textValue },
|
||||
data: { flagType: "text", textValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "text", textValue },
|
||||
data: { user: userId, key, flagType: "text", textValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -226,13 +246,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue },
|
||||
data: { flagType: "number", numberValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue },
|
||||
data: { user: userId, key, flagType: "number", numberValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -278,15 +298,16 @@ export async function evaluateNpcDialogueCondition(
|
|||
|
||||
/**
|
||||
* Evaluate every choice's visibility gate for a `choice` node in one round
|
||||
* trip. Ungated choices are always visible; gated ones appear only while the
|
||||
* reading user's flags satisfy their condition. The node is looked up
|
||||
* server-side from the stored flowchart, so clients never see gate config
|
||||
* for conversations an admin has not authored.
|
||||
* trip. Ungated choices always pass; gated ones report whether the reading
|
||||
* user's flags satisfy their condition and whether a failing choice should
|
||||
* still render locked (with its authored hint) instead of hiding. The node is
|
||||
* looked up server-side from the stored flowchart, so clients never see gate
|
||||
* config for conversations an admin has not authored.
|
||||
*/
|
||||
export async function evaluateNpcDialogueChoices(
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<boolean[]>> {
|
||||
): Promise<ActionResult<ChoiceGate[]>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
|
|
@ -304,15 +325,17 @@ export async function evaluateNpcDialogueChoices(
|
|||
return { success: true, data: [] };
|
||||
}
|
||||
|
||||
const visible: boolean[] = [];
|
||||
const gates: ChoiceGate[] = [];
|
||||
for (const choice of node.data.choices ?? []) {
|
||||
const showLocked = Boolean(choice.lockedHint?.trim());
|
||||
if (!choice.condition?.key?.trim()) {
|
||||
visible.push(true);
|
||||
gates.push({ pass: true, showLocked });
|
||||
continue;
|
||||
}
|
||||
visible.push(await evaluateCondition(payload, user.id as number, choice.condition));
|
||||
const pass = await evaluateCondition(payload, user.id as number, choice.condition);
|
||||
gates.push({ pass, showLocked });
|
||||
}
|
||||
return { success: true, data: visible };
|
||||
return { success: true, data: gates };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
|
|
@ -349,11 +372,15 @@ export async function resolveNpcDialogueTexts(
|
|||
|
||||
const keys = collectNodeTokens(node);
|
||||
const values: Record<string, string> = {};
|
||||
const countdowns: Record<string, string> = {};
|
||||
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" : "");
|
||||
}
|
||||
return { success: true, data: resolveNodeTexts(node, values) };
|
||||
return { success: true, data: resolveNodeTexts(node, values, countdowns) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
|
|
|
|||
|
|
@ -79,6 +79,24 @@ export const PlayerFlags: CollectionConfig = {
|
|||
"Inserted into conversation text wherever {{key}} appears. May contain dialogue markup like {green}NOMINAL{/}. A missing text flag reads as empty.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "activatesAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description:
|
||||
"Time-gated narrative: until this moment the flag reads as false / 0 / empty (conditions fail, {{countdown:key}} ticks). Leave empty for immediate.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "expiresAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description:
|
||||
"After this moment the flag reads as missing again (falls back to a global flag of the same key, else false / 0 / empty). Use for offers and windows that lapse.",
|
||||
},
|
||||
},
|
||||
],
|
||||
timestamps: true,
|
||||
indexes: [{ fields: ["user", "key"], unique: true }],
|
||||
|
|
|
|||
|
|
@ -337,9 +337,23 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
/>
|
||||
</div>
|
||||
)}
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
Lock message (optional)
|
||||
</Label>
|
||||
<Textarea
|
||||
value={choice.lockedHint ?? ""}
|
||||
onChange={(e) =>
|
||||
setChoice(index, { ...choice, lockedHint: e.target.value || undefined })
|
||||
}
|
||||
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
|
||||
rows={2}
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Player-specific flag takes priority; falls back to global (no user).
|
||||
Missing = false / 0. The choice button is hidden until this passes.
|
||||
Missing = false / 0. With a lock message the choice stays visible but
|
||||
disabled (tooltip explains why) while the condition fails; without one
|
||||
it is hidden entirely.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -468,6 +482,34 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
</p>
|
||||
</div>
|
||||
)}
|
||||
{(draft.effect.flagOp === "set_true" ||
|
||||
draft.effect.flagOp === "set_false" ||
|
||||
draft.effect.flagOp === "set_number" ||
|
||||
draft.effect.flagOp === "set_text") && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Delay activation (minutes, optional)
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={draft.effect.flagDelayMinutes ?? ""}
|
||||
onChange={(e) =>
|
||||
patchEffect({
|
||||
flagDelayMinutes:
|
||||
Number(e.target.value) > 0 ? Number(e.target.value) : undefined,
|
||||
})
|
||||
}
|
||||
placeholder="0 = immediate"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
For slow-burn narrative: the flag reads as false / 0 until this many
|
||||
minutes have passed, so conditions fail and {"{{countdown:key}}"} tokens
|
||||
tick down to it. Leave empty for an immediate write.
|
||||
</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; "Set text to" converts the flag to a text flag.
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, Fragment } from "react";
|
||||
import { MessageCircleIcon, XIcon } from "lucide-react";
|
||||
import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react";
|
||||
|
||||
import type { GameNpc } from "@/payload-types";
|
||||
import type { DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import type { ChoiceGate, 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 { flowHash, loadSeenMap, mergeSeenNodes, saveSeenMap, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import type { SeenMap } from "@/lib/npc-dialogue/seen";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
|
@ -84,7 +86,13 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
/** Per-node visibility gates for condition-gated choices, fetched from
|
||||
* the server when the conversation lands on a choice node. Cleared on
|
||||
* every `begin()` so flags gained mid-conversation are re-checked. */
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, boolean[]>>({});
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
|
||||
/** Per-browser read progress powering the NEW badges. Loaded after mount so
|
||||
* server and client markup agree (localStorage is invisible to SSR). */
|
||||
const [seenMap, setSeenMap] = useState<SeenMap>({});
|
||||
useEffect(() => {
|
||||
setSeenMap(loadSeenMap());
|
||||
}, []);
|
||||
const seq = useRef(0);
|
||||
const sessionRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
|
@ -132,8 +140,32 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
};
|
||||
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
|
||||
|
||||
// NEW badge inputs: current flowchart signature + the nodes this browser
|
||||
// has not read yet (a GM edit changes the hash and re-flags everything).
|
||||
const seenKey = dialogue ? String(dialogue.id) : "";
|
||||
const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]);
|
||||
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
|
||||
const unseenTargets = useMemo(
|
||||
() => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)),
|
||||
[seenMap, seenKey, flowSignature, allNodeIds],
|
||||
);
|
||||
|
||||
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||
|
||||
/** Records that this browser has read a node (persisted, idempotent). */
|
||||
const markSeen = (nodeId: string) => {
|
||||
setSeenMap((prev) => {
|
||||
const entry = prev[seenKey];
|
||||
if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev;
|
||||
const next: SeenMap = {
|
||||
...prev,
|
||||
[seenKey]: { hash: flowSignature, nodes: mergeSeenNodes(entry, flowSignature, nodeId) },
|
||||
};
|
||||
saveSeenMap(next);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
/** 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. */
|
||||
|
|
@ -149,6 +181,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
if (sessionRef.current !== token) return;
|
||||
setTyping(null);
|
||||
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]);
|
||||
markSeen(node.id);
|
||||
};
|
||||
|
||||
// Opening the conversation walks the start node and auto-advances through
|
||||
|
|
@ -255,14 +288,24 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
? lastNode.node
|
||||
: null;
|
||||
const visibleChoices = choiceNode
|
||||
? (choiceNode.data.choices ?? [])
|
||||
.map((hop, index) => ({ hop, index }))
|
||||
.filter(
|
||||
({ hop, index }) =>
|
||||
!(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) &&
|
||||
(!hop.condition?.key?.trim() || choiceGates[choiceNode.id]?.[index] === true),
|
||||
)
|
||||
? (choiceNode.data.choices ?? []).reduce<
|
||||
{ hop: DialogueNext; index: number; locked: boolean }[]
|
||||
>((acc, hop, index) => {
|
||||
if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc;
|
||||
if (!hop.condition?.key?.trim()) {
|
||||
acc.push({ hop, index, locked: false });
|
||||
return acc;
|
||||
}
|
||||
// Gated choices stay hidden until the server confirms them; a failing
|
||||
// gate with an authored hint renders the choice locked instead.
|
||||
const gate = choiceGates[choiceNode.id]?.[index];
|
||||
if (!gate) return acc;
|
||||
if (gate.pass) acc.push({ hop, index, locked: false });
|
||||
else if (gate.showLocked) acc.push({ hop, index, locked: true });
|
||||
return acc;
|
||||
}, [])
|
||||
: [];
|
||||
const anySelectableChoice = visibleChoices.some((choice) => !choice.locked);
|
||||
|
||||
/** Button text for a choice: the server-resolved label when the choice
|
||||
* node's strings contained flag tokens, the raw label otherwise. */
|
||||
|
|
@ -280,16 +323,35 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
return raw?.trim() ? raw : undefined;
|
||||
};
|
||||
|
||||
/** Tooltip for a locked choice (resolved like labels); generic fallback
|
||||
* when the author left the hint blank. */
|
||||
const choiceHint = (hop: DialogueNext, index: number): string => {
|
||||
const raw =
|
||||
(lastNode?.kind === "node" ? lastNode.resolved?.hints?.[index] : undefined) ??
|
||||
hop.lockedHint;
|
||||
return raw?.trim() ? raw : "Locked.";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={begin}
|
||||
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
|
||||
>
|
||||
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
|
||||
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
|
||||
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
|
||||
</Button>
|
||||
<span className="relative inline-flex">
|
||||
<Button
|
||||
onClick={begin}
|
||||
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
|
||||
>
|
||||
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
|
||||
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
|
||||
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
|
||||
</Button>
|
||||
{unseenTargets.size > 0 && (
|
||||
<span
|
||||
aria-label="New or updated dialogue"
|
||||
className="pointer-events-none absolute -right-1.5 -top-1.5 z-10 rounded-sm bg-cyan-400 px-1 py-px font-mono text-[9px] font-bold uppercase leading-none text-black"
|
||||
>
|
||||
New
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<Dialog open={open} onOpenChange={(next) => !next && close()}>
|
||||
<DialogContent
|
||||
|
|
@ -335,19 +397,35 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
lastNode.kind === "node" &&
|
||||
(lastNode.node.type === "choice" || lastNode.node.type === "end") && (
|
||||
<div className="flex flex-col gap-2 border-t border-white/15 bg-black/50 p-4">
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 ? (
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 && (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{visibleChoices.map(({ hop, index }) => {
|
||||
{visibleChoices.map(({ hop, index, locked }) => {
|
||||
const isNew = unseenTargets.has(hop.target);
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={locked}
|
||||
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"
|
||||
className={`w-full rounded-none border px-3 py-2 text-left text-sm transition-colors ${
|
||||
locked
|
||||
? "cursor-not-allowed border-white/10 bg-black/20 text-white/35"
|
||||
: "border-white/20 bg-black/40 text-white/80 hover:border-cyan-500/60 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<DialogueText text={choiceLabel(hop, index)} />
|
||||
<span className="flex items-center gap-2">
|
||||
{locked && (
|
||||
<LockIcon className="size-3 shrink-0 text-amber-400/70" />
|
||||
)}
|
||||
<DialogueText text={choiceLabel(hop, index)} />
|
||||
{isNew && !locked && (
|
||||
<span className="ml-auto shrink-0 rounded-sm bg-cyan-400 px-1 font-mono text-[9px] font-bold uppercase leading-tight text-black">
|
||||
New
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
const tip = choiceTooltip(hop, index);
|
||||
const tip = locked ? choiceHint(hop, index) : choiceTooltip(hop, index);
|
||||
if (!tip) return <Fragment key={index}>{button}</Fragment>;
|
||||
return (
|
||||
<Tooltip key={index}>
|
||||
|
|
@ -363,7 +441,8 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
);
|
||||
})}
|
||||
</TooltipProvider>
|
||||
) : (
|
||||
)}
|
||||
{(lastNode.node.type === "end" || !anySelectableChoice) && (
|
||||
<Button
|
||||
onClick={close}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
|
||||
|
|
|
|||
|
|
@ -1,16 +1,30 @@
|
|||
import type { ReactNode } from "react";
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { ExternalLinkIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
|
||||
/**
|
||||
* Renders a dialogue string for display: newlines are preserved and a tiny
|
||||
* inline markup subset is honoured (**bold**, *italic*, `code`, colored runs
|
||||
* and  inline images). Colors take a friendly name ({red}, {cyan},
|
||||
* ...) or a hex code ({#ff00ff}). Images render at text height like icons and
|
||||
* accept only http(s) or site-relative URLs (e.g. /api/media/file/coin.png).
|
||||
* Renders a dialogue string for display. Newlines are preserved and a tiny
|
||||
* inline markup subset is honoured, freely NESTABLE (markup accumulates):
|
||||
*
|
||||
* **bold**, *italic*, `code`
|
||||
* {green}colored{/} or {#ff00ff} — wraps bold/italic/images/links inside it
|
||||
*  inline images at text height (http(s) or site-relative URLs)
|
||||
* [label](url) links opening in an in-page popup frame (same-origin pages
|
||||
* stay put; no navigation, so conversation progress survives)
|
||||
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
|
||||
*
|
||||
* Shared by the admin flow editor previews and the frontend conversation
|
||||
* dialog, so it must stay client-safe (no Payload imports).
|
||||
*/
|
||||
export function DialogueText({ text, className }: { text: string; className?: string }) {
|
||||
return <span className={`whitespace-pre-wrap ${className ?? ""}`}>{renderInline(text)}</span>;
|
||||
return (
|
||||
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
||||
{parseSegment(text, 0, { i: 0 }, false).nodes}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Friendly color names mapped to Tailwind text classes (400 shades read well
|
||||
|
|
@ -34,83 +48,293 @@ const FRIENDLY_COLORS: Record<string, string> = {
|
|||
|
||||
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
||||
|
||||
const INLINE_PATTERN =
|
||||
/(!\[[^\]]*\]\([^()\s]*\)|\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\{(?:#[0-9a-fA-F]{3,6}|[a-zA-Z]+)\}[^{}]*\{\/\})/g;
|
||||
/** Guards against pathological nesting like `**{red}**{red}**...`. */
|
||||
const MAX_DEPTH = 8;
|
||||
|
||||
/** Matches one `` token produced by INLINE_PATTERN. */
|
||||
const IMG_TOKEN = /^!\[([^\]]*)\]\(([^()\s]*)\)$/;
|
||||
const IMG_RE = /^!\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const LINK_RE = /^\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const COLOR_OPEN_RE = /^\{([^{}|]{1,20})\}/;
|
||||
const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/;
|
||||
|
||||
/** Only http(s) and site-relative URLs render as images; anything else stays literal. */
|
||||
function safeImageSrc(url: string): string | null {
|
||||
/** Only http(s) and site-relative URLs render; anything else stays literal. */
|
||||
function safeUrl(url: string): string | null {
|
||||
if (/^https?:\/\//i.test(url)) return url;
|
||||
if (url.startsWith("/") && !url.startsWith("//")) return url;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Matches one colour token produced by INLINE_PATTERN. */
|
||||
const COLOR_TOKEN = /^\{(#?[a-zA-Z0-9#]+)\}([^{}]*)\{\/\}$/;
|
||||
|
||||
function renderInline(text: string): ReactNode {
|
||||
const parts = text.split(INLINE_PATTERN);
|
||||
return parts.map((part, index) => {
|
||||
const imgMatch = part.match(IMG_TOKEN);
|
||||
if (imgMatch) {
|
||||
const src = safeImageSrc(imgMatch[2]);
|
||||
if (!src) return <span key={index}>{part}</span>;
|
||||
return (
|
||||
<img
|
||||
key={index}
|
||||
src={src}
|
||||
alt={imgMatch[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (part.length > 4 && part.startsWith("**") && part.endsWith("**")) {
|
||||
return (
|
||||
<strong key={index} className="font-semibold">
|
||||
{part.slice(2, -2)}
|
||||
</strong>
|
||||
);
|
||||
}
|
||||
if (part.length > 2 && part.startsWith("*") && part.endsWith("*")) {
|
||||
return <em key={index}>{part.slice(1, -1)}</em>;
|
||||
}
|
||||
if (part.length > 2 && part.startsWith("`") && part.endsWith("`")) {
|
||||
return (
|
||||
<code
|
||||
key={index}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{part.slice(1, -1)}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
const colorMatch = part.match(COLOR_TOKEN);
|
||||
if (colorMatch) {
|
||||
const token = colorMatch[1];
|
||||
const inner = colorMatch[2];
|
||||
if (token.startsWith("#")) {
|
||||
// Only well-formed hex codes reach the style attribute; anything else
|
||||
// (e.g. {#12345}) renders as literal text.
|
||||
if (HEX_COLOR.test(token)) {
|
||||
return (
|
||||
<span key={index} style={{ color: token }}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
}
|
||||
const cls = FRIENDLY_COLORS[token.toLowerCase()];
|
||||
if (cls) {
|
||||
return (
|
||||
<span key={index} className={cls}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
});
|
||||
interface ParseResult {
|
||||
nodes: ReactNode[];
|
||||
/** True when the segment ended at a `{/}` (consumed by the caller's color). */
|
||||
closed: boolean;
|
||||
/** Characters consumed, including the closing `{/}` when closed. */
|
||||
consumed: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans `text` left to right, turning markup runs into elements and recursing
|
||||
* into their contents so styling accumulates (a bold run inside a color span
|
||||
* keeps both). When `insideColor` is set, scanning stops at the matching
|
||||
* `{/}` so nested colors close inner-first.
|
||||
*/
|
||||
function parseSegment(text: string, depth: number, keys: { i: number }, insideColor: boolean): ParseResult {
|
||||
const nodes: ReactNode[] = [];
|
||||
let plain = "";
|
||||
let i = 0;
|
||||
const key = () => `${depth}:${keys.i++}`;
|
||||
const flush = () => {
|
||||
if (plain) {
|
||||
nodes.push(plain);
|
||||
plain = "";
|
||||
}
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const rest = text.slice(i);
|
||||
|
||||
if (insideColor && rest.startsWith("{/}")) {
|
||||
flush();
|
||||
return { nodes, closed: true, consumed: i + 3 };
|
||||
}
|
||||
|
||||
if (depth < MAX_DEPTH) {
|
||||
// Inline code (literal content, no nesting).
|
||||
if (rest[0] === "`") {
|
||||
const end = rest.indexOf("`", 1);
|
||||
if (end > 1) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<code
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{rest.slice(1, end)}
|
||||
</code>,
|
||||
);
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Countdown leaf.
|
||||
const cd = COUNTDOWN_RE.exec(rest);
|
||||
if (cd) {
|
||||
flush();
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
i += cd[0].length;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Image (leaf).
|
||||
if (rest.startsWith("![")) {
|
||||
const img = IMG_RE.exec(rest);
|
||||
if (img) {
|
||||
const src = safeUrl(img[2]);
|
||||
if (src) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
i += img[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Link: label keeps its own markup; the popup frame preserves context.
|
||||
if (rest[0] === "[") {
|
||||
const link = LINK_RE.exec(rest);
|
||||
if (link) {
|
||||
const href = safeUrl(link[2]);
|
||||
if (href) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{parseSegment(link[1], depth + 1, keys, false).nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
i += link[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Color run: recurse so inner markup renders inside the colored span.
|
||||
if (rest[0] === "{") {
|
||||
const open = COLOR_OPEN_RE.exec(rest);
|
||||
if (open && open[1] !== "/") {
|
||||
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true);
|
||||
const style = colorStyle(open[1]);
|
||||
if (inner.closed && style) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
i += open[0].length + inner.consumed;
|
||||
continue;
|
||||
}
|
||||
// Unknown token or unclosed: fall through and render literally.
|
||||
}
|
||||
}
|
||||
|
||||
// Bold, then italic (bold checked first so `**` never reads as two stars).
|
||||
if (rest.startsWith("**")) {
|
||||
const end = rest.indexOf("**", 2);
|
||||
if (end > 2) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes}
|
||||
</strong>,
|
||||
);
|
||||
i += end + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (rest[0] === "*" && rest[1] !== "*") {
|
||||
const end = rest.indexOf("*", 1);
|
||||
if (end > 1 && rest[end + 1] !== "*") {
|
||||
flush();
|
||||
nodes.push(
|
||||
<em key={key()}>
|
||||
{parseSegment(rest.slice(1, end), depth + 1, keys, false).nodes}
|
||||
</em>,
|
||||
);
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plain += text[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
flush();
|
||||
return { nodes, closed: false, consumed: text.length };
|
||||
}
|
||||
|
||||
/** Resolves a color token to a className or inline style; null = not a color. */
|
||||
function colorStyle(token: string): { className?: string; style?: { color: string } } | null {
|
||||
if (token.startsWith("#")) {
|
||||
// Only well-formed hex codes reach the style attribute; anything else
|
||||
// (e.g. {#12345}) renders as literal text.
|
||||
return HEX_COLOR.test(token) ? { style: { color: token } } : null;
|
||||
}
|
||||
const cls = FRIENDLY_COLORS[token.toLowerCase()];
|
||||
return cls ? { className: cls } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A dialogue link. Clicking opens the destination in a popup frame instead of
|
||||
* navigating, so the conversation (and its progress) stays mounted behind it.
|
||||
*/
|
||||
function DialogueLink({ href, children }: { href: string; children: ReactNode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<a
|
||||
href={href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
className="font-medium text-cyan-400 underline decoration-cyan-500/40 underline-offset-2 transition-colors hover:text-cyan-300"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) setOpen(false);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex h-[85vh] w-[92vw] max-w-6xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:max-w-6xl"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
|
||||
<DialogTitle className="truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Attachment // {href.slice(0, 96)}
|
||||
</DialogTitle>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
Open in new tab
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
aria-label="Close attachment"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<iframe
|
||||
src={href}
|
||||
title="Dialogue link"
|
||||
className="min-h-0 flex-1 bg-zinc-900"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Formats a countdown duration: `2d 07h`, `7h 05m`, `12m 03s`, `9s`. */
|
||||
export function formatRemaining(ms: number): string {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(total / 86400);
|
||||
const hours = Math.floor((total % 86400) / 3600);
|
||||
const minutes = Math.floor((total % 3600) / 60);
|
||||
const seconds = total % 60;
|
||||
if (days > 0) return `${days}d ${hours}h`;
|
||||
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
||||
if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live countdown leaf. Value is an ISO activation time (ticks every second),
|
||||
* `done` (the flag already activated), or empty (flag missing: renders
|
||||
* nothing). Ticks client-side from the mount-time clock.
|
||||
*/
|
||||
function Countdown({ value }: { value: string }) {
|
||||
const target = value === "done" || value === "" ? null : Date.parse(value);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
if (target === null || Number.isNaN(target)) return;
|
||||
const timer = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [target]);
|
||||
|
||||
if (value === "done") return <span className="font-mono text-emerald-400">ready</span>;
|
||||
if (value === "") return null;
|
||||
if (target === null || Number.isNaN(target)) return null;
|
||||
|
||||
const remaining = target - now;
|
||||
if (remaining <= 0) return <span className="font-mono text-emerald-400">ready</span>;
|
||||
return (
|
||||
<span
|
||||
className="font-mono tabular-nums text-cyan-300"
|
||||
title={new Date(target).toISOString()}
|
||||
>
|
||||
{formatRemaining(remaining)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,20 @@ export interface DialogueNext {
|
|||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -87,6 +101,12 @@ export interface NpcDialogueEffect {
|
|||
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 = {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,46 @@ export interface FlagValues {
|
|||
bool: boolean;
|
||||
num: number;
|
||||
text: string;
|
||||
/** True when a non-expired flag document exists (even if not yet active). */
|
||||
exists: boolean;
|
||||
/**
|
||||
* When the flag is time-gated and not yet active, its ISO activation time
|
||||
* (so `{{countdown:key}}` tokens can tick toward it). Undefined otherwise.
|
||||
*/
|
||||
activatesAt?: string;
|
||||
}
|
||||
|
||||
/** True when the doc's activation window covers now (missing bounds = open). */
|
||||
function activeNow(
|
||||
doc: { activatesAt?: string | null; expiresAt?: string | null },
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (doc.activatesAt) {
|
||||
const t = Date.parse(doc.activatesAt);
|
||||
if (!Number.isNaN(t) && t > now) return false;
|
||||
}
|
||||
if (doc.expiresAt) {
|
||||
const t = Date.parse(doc.expiresAt);
|
||||
if (!Number.isNaN(t) && t <= now) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** True while the doc has an activation time strictly in the future. */
|
||||
function pendingActivation(
|
||||
doc: { activatesAt?: string | null },
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (!doc.activatesAt) return false;
|
||||
const t = Date.parse(doc.activatesAt);
|
||||
return !Number.isNaN(t) && t > now;
|
||||
}
|
||||
|
||||
/** The inactive read value, carrying the countdown target when pending. */
|
||||
function inactiveValues(doc: { activatesAt?: string | null }, now = Date.now()): FlagValues {
|
||||
return pendingActivation(doc, now)
|
||||
? { bool: false, num: 0, text: "", exists: true, activatesAt: doc.activatesAt ?? undefined }
|
||||
: { bool: false, num: 0, text: "", exists: false };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -19,6 +59,9 @@ export interface FlagValues {
|
|||
* 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).
|
||||
* Time windows apply: a not-yet-active flag reads as false (and reports its
|
||||
* `activatesAt` for countdowns); an expired flag reads as missing and falls
|
||||
* through to the global fallback.
|
||||
*/
|
||||
export async function readFlag(
|
||||
payload: Payload,
|
||||
|
|
@ -37,7 +80,10 @@ export async function readFlag(
|
|||
overrideAccess: true,
|
||||
});
|
||||
const playerDoc = playerRes.docs[0];
|
||||
if (playerDoc) return flagValues(playerDoc);
|
||||
if (playerDoc) {
|
||||
if (!activeNow(playerDoc)) return inactiveValues(playerDoc);
|
||||
return flagValues(playerDoc);
|
||||
}
|
||||
|
||||
// Global fallback (user is null).
|
||||
const globalRes = await payload.find({
|
||||
|
|
@ -51,7 +97,8 @@ export async function readFlag(
|
|||
overrideAccess: true,
|
||||
});
|
||||
const globalDoc = globalRes.docs[0];
|
||||
if (!globalDoc) return { bool: false, num: 0, text: "" };
|
||||
if (!globalDoc) return { bool: false, num: 0, text: "", exists: false };
|
||||
if (!activeNow(globalDoc)) return inactiveValues(globalDoc);
|
||||
return flagValues(globalDoc);
|
||||
}
|
||||
|
||||
|
|
@ -64,14 +111,14 @@ export function flagValues(doc: {
|
|||
}): FlagValues {
|
||||
if (doc.flagType === "number") {
|
||||
const num = doc.numberValue ?? 0;
|
||||
return { bool: num !== 0, num, text: String(num) };
|
||||
return { bool: num !== 0, num, text: String(num), exists: true };
|
||||
}
|
||||
if (doc.flagType === "text") {
|
||||
const text = doc.textValue ?? "";
|
||||
return { bool: text.trim().length > 0, num: 0, text };
|
||||
return { bool: text.trim().length > 0, num: 0, text, exists: true };
|
||||
}
|
||||
const bool = doc.boolValue === true;
|
||||
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false" };
|
||||
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false", exists: true };
|
||||
}
|
||||
|
||||
/** Evaluates one authored condition against the user's live flags. */
|
||||
|
|
|
|||
|
|
@ -17,6 +17,36 @@ import type { DialogueNode } from "./dialogue";
|
|||
* are documented as lowercase-with-underscores. */
|
||||
const FLAG_TOKEN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
||||
|
||||
/**
|
||||
* One `{{countdown:key}}` token: a live timer ticking toward the flag's
|
||||
* activation time. Server-side resolution rewrites it to the internal
|
||||
* `{cd|<iso|done|>}` leaf that DialogueText renders as a ticking span.
|
||||
*/
|
||||
const COUNTDOWN_TOKEN = /\{\{countdown:\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
||||
|
||||
/** Every distinct countdown key referenced by `text`, lowercased. */
|
||||
export function extractCountdownKeys(text: string | undefined): string[] {
|
||||
if (!text) return [];
|
||||
const keys = new Set<string>();
|
||||
for (const match of text.matchAll(COUNTDOWN_TOKEN)) {
|
||||
keys.add(match[1].toLowerCase());
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace every `{{countdown:key}}` token with its `{cd|value}` leaf.
|
||||
* Values: an ISO activation time (pending), "done" (flag active), or empty
|
||||
* (flag missing, renders nothing).
|
||||
*/
|
||||
export function replaceCountdowns(
|
||||
text: string | undefined,
|
||||
countdowns: Record<string, string>,
|
||||
): string {
|
||||
if (!text) return "";
|
||||
return text.replace(COUNTDOWN_TOKEN, (_match, key: string) => `{cd|${countdowns[key.toLowerCase()] ?? ""}}`);
|
||||
}
|
||||
|
||||
/** The display strings of a node that support interpolation. */
|
||||
export interface ResolvedNodeTexts {
|
||||
body?: string;
|
||||
|
|
@ -28,6 +58,8 @@ export interface ResolvedNodeTexts {
|
|||
labels?: string[];
|
||||
/** Choice tooltips, index-aligned with the node's choices. */
|
||||
tooltips?: string[];
|
||||
/** Locked-choice hints, index-aligned with the node's choices. */
|
||||
hints?: string[];
|
||||
}
|
||||
|
||||
/** Every distinct flag key referenced by `text`, lowercased. */
|
||||
|
|
@ -79,7 +111,9 @@ export function formatFlagValue(flag: FlagValueLike): string {
|
|||
}
|
||||
}
|
||||
|
||||
/** All flag keys the node's display strings reference (deduped, lowercased). */
|
||||
/** 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. */
|
||||
export function collectNodeTokens(node: DialogueNode): string[] {
|
||||
const keys = new Set<string>();
|
||||
const texts = [
|
||||
|
|
@ -87,10 +121,11 @@ export function collectNodeTokens(node: DialogueNode): string[] {
|
|||
node.data.leadIn,
|
||||
node.data.closing,
|
||||
node.data.effect?.message,
|
||||
...(node.data.choices?.flatMap((c) => [c.label, c.tooltip]) ?? []),
|
||||
...(node.data.choices?.flatMap((c) => [c.label, c.tooltip, c.lockedHint]) ?? []),
|
||||
];
|
||||
for (const text of texts) {
|
||||
for (const key of extractFlagTokens(text)) keys.add(key);
|
||||
for (const key of extractCountdownKeys(text)) keys.add(key);
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
|
@ -103,19 +138,25 @@ export function collectNodeTokens(node: DialogueNode): string[] {
|
|||
export function resolveNodeTexts(
|
||||
node: DialogueNode,
|
||||
values: Record<string, string>,
|
||||
countdowns: Record<string, string> = {},
|
||||
): ResolvedNodeTexts {
|
||||
const finish = (text: string | undefined): string =>
|
||||
replaceCountdowns(interpolateFlags(text, values), countdowns);
|
||||
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.body !== undefined) resolved.body = finish(node.data.body);
|
||||
if (node.data.leadIn !== undefined) resolved.leadIn = finish(node.data.leadIn);
|
||||
if (node.data.closing !== undefined) resolved.closing = finish(node.data.closing);
|
||||
if (node.data.effect?.message !== undefined) resolved.message = finish(node.data.effect.message);
|
||||
if (node.data.choices) {
|
||||
resolved.labels = node.data.choices.map((choice) => interpolateFlags(choice.label, values));
|
||||
resolved.labels = node.data.choices.map((choice) => finish(choice.label));
|
||||
if (node.data.choices.some((choice) => choice.tooltip !== undefined)) {
|
||||
resolved.tooltips = node.data.choices.map((choice) =>
|
||||
choice.tooltip === undefined ? "" : interpolateFlags(choice.tooltip, values),
|
||||
choice.tooltip === undefined ? "" : finish(choice.tooltip),
|
||||
);
|
||||
}
|
||||
if (node.data.choices.some((choice) => choice.lockedHint !== undefined)) {
|
||||
resolved.hints = node.data.choices.map((choice) =>
|
||||
choice.lockedHint === undefined ? "" : finish(choice.lockedHint),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
75
src/lib/npc-dialogue/seen.ts
Normal file
75
src/lib/npc-dialogue/seen.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
/**
|
||||
* Per-browser conversation progress tracking that powers the "NEW" badges.
|
||||
*
|
||||
* For each conversation (npc-dialogues id) we remember a hash of its
|
||||
* flowchart plus the node ids this browser has read. The Converse button
|
||||
* shows a badge when the flow changed (GM added paths -> new hash) or when
|
||||
* nodes remain unread; choice buttons badge their unseen targets. Stored in
|
||||
* localStorage like the tour/announcement dismissals: no server state, and a
|
||||
* fresh device rediscovers every path once. Pure module, client-safe.
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = "ptf:npc-dialogue-seen";
|
||||
|
||||
export interface SeenEntry {
|
||||
/** flowHash of the flowchart these node ids belong to. */
|
||||
hash: string;
|
||||
/** Node ids rendered at least once. */
|
||||
nodes: string[];
|
||||
}
|
||||
|
||||
export type SeenMap = Record<string, SeenEntry>;
|
||||
|
||||
/** Deterministic djb2 hash of the serialized flowchart (base36). */
|
||||
export function flowHash(flowData: unknown): string {
|
||||
const json = JSON.stringify(flowData ?? null);
|
||||
let h = 5381;
|
||||
for (let i = 0; i < json.length; i += 1) {
|
||||
h = ((h << 5) + h + json.charCodeAt(i)) | 0;
|
||||
}
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/** Reads the seen map; corrupt or absent storage reads empty. */
|
||||
export function loadSeenMap(): SeenMap {
|
||||
if (typeof window === "undefined") return {};
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return {};
|
||||
const parsed = JSON.parse(raw) as SeenMap;
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Persists the seen map; storage failures (private mode) are ignored. */
|
||||
export function saveSeenMap(map: SeenMap): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
|
||||
} catch {
|
||||
// Best effort only.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Node ids from `nodeIds` this browser has not read yet. A missing entry or a
|
||||
* hash mismatch (the GM edited the flowchart) counts everything as unseen.
|
||||
*/
|
||||
export function unseenNodeIds(
|
||||
entry: SeenEntry | undefined,
|
||||
hash: string,
|
||||
nodeIds: readonly string[],
|
||||
): string[] {
|
||||
if (!entry || entry.hash !== hash) return [...nodeIds];
|
||||
const seen = new Set(entry.nodes);
|
||||
return nodeIds.filter((id) => !seen.has(id));
|
||||
}
|
||||
|
||||
/** Returns the updated node list for one conversation (deduped, sorted-free). */
|
||||
export function mergeSeenNodes(entry: SeenEntry | undefined, hash: string, nodeId: string): string[] {
|
||||
const nodes = entry && entry.hash === hash ? [...entry.nodes] : [];
|
||||
if (!nodes.includes(nodeId)) nodes.push(nodeId);
|
||||
return nodes;
|
||||
}
|
||||
37438
src/migrations/20261006_205845_add_flag_time_windows.json
Normal file
37438
src/migrations/20261006_205845_add_flag_time_windows.json
Normal file
File diff suppressed because it is too large
Load diff
13
src/migrations/20261006_205845_add_flag_time_windows.ts
Normal file
13
src/migrations/20261006_205845_add_flag_time_windows.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "player_flags" ADD COLUMN "activates_at" timestamp(3) with time zone;
|
||||
ALTER TABLE "player_flags" ADD COLUMN "expires_at" timestamp(3) with time zone;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "player_flags" DROP COLUMN "activates_at";
|
||||
ALTER TABLE "player_flags" DROP COLUMN "expires_at";`)
|
||||
}
|
||||
|
|
@ -111,6 +111,7 @@ import * as migration_20261006_000000_add_npc_dialogue_and_activity_fields from
|
|||
import * as migration_20261006_155244_add_global_flag_support from './20261006_155244_add_global_flag_support';
|
||||
import * as migration_20261006_195605_add_text_flag_type from './20261006_195605_add_text_flag_type';
|
||||
import * as migration_20261006_203217_add_dialogue_entry_gate from './20261006_203217_add_dialogue_entry_gate';
|
||||
import * as migration_20261006_205845_add_flag_time_windows from './20261006_205845_add_flag_time_windows';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -676,6 +677,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261006_203217_add_dialogue_entry_gate.up,
|
||||
down: migration_20261006_203217_add_dialogue_entry_gate.down,
|
||||
name: '20261006_203217_add_dialogue_entry_gate'
|
||||
name: '20261006_203217_add_dialogue_entry_gate',
|
||||
},
|
||||
{
|
||||
up: migration_20261006_205845_add_flag_time_windows.up,
|
||||
down: migration_20261006_205845_add_flag_time_windows.down,
|
||||
name: '20261006_205845_add_flag_time_windows'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -2589,6 +2589,14 @@ export interface PlayerFlag {
|
|||
* Inserted into conversation text wherever {{key}} appears. May contain dialogue markup like {green}NOMINAL{/}. A missing text flag reads as empty.
|
||||
*/
|
||||
textValue?: string | null;
|
||||
/**
|
||||
* Time-gated narrative: until this moment the flag reads as false / 0 / empty (conditions fail, {{countdown:key}} ticks). Leave empty for immediate.
|
||||
*/
|
||||
activatesAt?: string | null;
|
||||
/**
|
||||
* After this moment the flag reads as missing again (falls back to a global flag of the same key, else false / 0 / empty). Use for offers and windows that lapse.
|
||||
*/
|
||||
expiresAt?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -7880,6 +7888,8 @@ export interface PlayerFlagsSelect<T extends boolean = true> {
|
|||
boolValue?: T;
|
||||
numberValue?: T;
|
||||
textValue?: T;
|
||||
activatesAt?: T;
|
||||
expiresAt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,14 +6,18 @@ import { renderToStaticMarkup } from "react-dom/server";
|
|||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import {
|
||||
collectNodeTokens,
|
||||
extractCountdownKeys,
|
||||
extractFlagTokens,
|
||||
formatFlagValue,
|
||||
hasFlagTokens,
|
||||
interpolateFlags,
|
||||
replaceCountdowns,
|
||||
resolveNodeTexts,
|
||||
} from "@/lib/npc-dialogue/interpolate";
|
||||
|
||||
|
|
@ -209,6 +213,42 @@ describe("text flags (player-flags collection)", () => {
|
|||
await payload.delete({ collection: "game-npcs", id: npc.id, overrideAccess: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reads time-gated flags: pending fails with a countdown target, expired reads missing", async () => {
|
||||
const future = new Date(Date.now() + 3_600_000).toISOString();
|
||||
const past = new Date(Date.now() - 3_600_000).toISOString();
|
||||
const pending = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_pending`, flagType: "boolean", boolValue: true, activatesAt: future },
|
||||
overrideAccess: true,
|
||||
});
|
||||
const expired = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_expired`, flagType: "number", numberValue: 9, expiresAt: past },
|
||||
overrideAccess: true,
|
||||
});
|
||||
try {
|
||||
const userId = 999_999; // no player docs for this id; exercises the global path
|
||||
const pendingRead = await readFlag(payload, userId, `${RUN}_pending`);
|
||||
expect(pendingRead.bool).toBe(false);
|
||||
expect(pendingRead.exists).toBe(true);
|
||||
expect(pendingRead.activatesAt).toBe(future);
|
||||
await expect(
|
||||
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_pending`, op: "is_true" }),
|
||||
).resolves.toBe(false);
|
||||
|
||||
const expiredRead = await readFlag(payload, userId, `${RUN}_expired`);
|
||||
expect(expiredRead.exists).toBe(false);
|
||||
expect(expiredRead.num).toBe(0);
|
||||
await expect(
|
||||
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_expired`, op: "gte", amount: 1 }),
|
||||
).resolves.toBe(false);
|
||||
} finally {
|
||||
for (const doc of [pending, expired]) {
|
||||
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inline images in dialogue markup", () => {
|
||||
|
|
@ -310,3 +350,125 @@ describe("choice tooltip interpolation", () => {
|
|||
expect(resolveNodeTexts(node, {}).tooltips).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("markup accumulation + links + countdowns", () => {
|
||||
const render = (text: string) =>
|
||||
renderToStaticMarkup(createElement(DialogueText, { text }));
|
||||
|
||||
it("accumulates bold inside color and color inside bold", () => {
|
||||
const stacked = render("{green}**cargo** secured{/}");
|
||||
expect(stacked).toContain("text-green-400");
|
||||
expect(stacked).toContain("<strong");
|
||||
const wrapped = render("**{red}danger{/} zone**");
|
||||
expect(wrapped).toContain("<strong");
|
||||
expect(wrapped).toContain("text-red-400");
|
||||
});
|
||||
|
||||
it("closes nested colors inner-first", () => {
|
||||
const html = render("{cyan}outer {red}inner{/} tail{/}");
|
||||
expect(html).toContain("text-cyan-400");
|
||||
expect(html).toContain("text-red-400");
|
||||
expect(html).toContain("tail");
|
||||
expect(html).not.toContain("{/}");
|
||||
});
|
||||
|
||||
it("renders hex colors wrapping nested markup", () => {
|
||||
const html = render("{#ff00ff}*wow*{/}");
|
||||
expect(html).toContain("color:#ff00ff");
|
||||
expect(html).toContain("<em");
|
||||
});
|
||||
|
||||
it("renders safe links as anchors and refuses javascript: urls", () => {
|
||||
const ok = render("[After Action Report](/intelligence/missions/12)");
|
||||
expect(ok).toContain('href="/intelligence/missions/12"');
|
||||
expect(ok).toContain("After Action Report");
|
||||
const bad = render("[trap](javascript:alert(1))");
|
||||
expect(bad).not.toContain("href=");
|
||||
expect(bad).toContain("[trap]");
|
||||
});
|
||||
|
||||
it("renders countdown leaves: ticking, ready, and empty", () => {
|
||||
const future = new Date(Date.now() + 3_600_000).toISOString();
|
||||
expect(render(`{cd|${future}}`)).toContain("text-cyan-300");
|
||||
expect(render("{cd|done}")).toContain("ready");
|
||||
const empty = render("x{cd|}y");
|
||||
expect(empty).toContain("xy");
|
||||
expect(empty).not.toContain("cd|");
|
||||
});
|
||||
|
||||
it("formats remaining time compactly", () => {
|
||||
expect(formatRemaining(9_000)).toBe("9s");
|
||||
expect(formatRemaining(63_000)).toBe("1m 03s");
|
||||
expect(formatRemaining(3_661_000)).toBe("1h 01m");
|
||||
expect(formatRemaining(93_600_000)).toBe("1d 2h");
|
||||
expect(formatRemaining(-5)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("countdown token resolution (pure)", () => {
|
||||
it("collects countdown keys so nodes get resolved", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "Analysis done in {{countdown:device_scan}}." },
|
||||
};
|
||||
expect(collectNodeTokens(node)).toContain("device_scan");
|
||||
expect(extractCountdownKeys("{{countdown:A}} {{countdown:a}} {{flag}}")).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("rewrites tokens to leaves with resolved values", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "{{countdown:device_scan}} / {{countdown:missing}}" },
|
||||
};
|
||||
const out = resolveNodeTexts(node, {}, { device_scan: "2030-01-01T00:00:00.000Z" });
|
||||
expect(out.body).toBe("{cd|2030-01-01T00:00:00.000Z} / {cd|}");
|
||||
});
|
||||
|
||||
it("replaceCountdowns lowercases keys and defaults missing to empty", () => {
|
||||
expect(replaceCountdowns("{{countdown:KEY}}", { key: "done" })).toBe("{cd|done}");
|
||||
expect(replaceCountdowns("{{countdown:key}}", {})).toBe("{cd|}");
|
||||
});
|
||||
|
||||
it("resolves locked hints index-aligned with the choices", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
choices: [
|
||||
{ label: "A", target: "t", lockedHint: "Needs {{rep}} rep" },
|
||||
{ label: "B", target: "u" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = resolveNodeTexts(node, { rep: "3" });
|
||||
expect(out.hints?.[0]).toBe("Needs 3 rep");
|
||||
expect(out.hints?.[1]).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("seen tracking (NEW badges)", () => {
|
||||
it("hashes flowcharts deterministically and differently on change", () => {
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).toBe(flowHash({ nodes: [{ id: "a" }] }));
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).not.toBe(flowHash({ nodes: [{ id: "b" }] }));
|
||||
});
|
||||
|
||||
it("treats a hash mismatch as everything unseen", () => {
|
||||
expect(unseenNodeIds({ hash: "old", nodes: ["a", "b"] }, "new", ["a", "b"])).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
]);
|
||||
expect(unseenNodeIds({ hash: "x", nodes: ["a"] }, "x", ["a", "b"])).toEqual(["b"]);
|
||||
expect(unseenNodeIds(undefined, "x", ["a"])).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("merges seen nodes without duplicates and resets on new hash", () => {
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "a")).toEqual(["a"]);
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "b")).toEqual(["a", "b"]);
|
||||
expect(mergeSeenNodes({ hash: "old", nodes: ["a"] }, "new", "b")).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue