1
0
Fork 0
polaris-task-force/src/components/frontend/personnel/NpcConversation.tsx
Z8MB1E b1168dcc38 fix(personnel): mobile layout for conversations
- Converse button no longer floats over the hero text on phones: it sits
  in the card's content flow below the status chips and only anchors to
  the hero's right edge from md up
- conversation dialog keeps a side margin on small screens instead of
  rendering edge-to-edge
- dialog titles truncate with min-w-0 so long NPC names and attachment
  urls cannot push the close buttons out
2026-10-06 17:21:26 -04:00

556 lines
23 KiB
TypeScript

"use client";
import { useEffect, useMemo, useRef, useState, Fragment } from "react";
import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react";
import type { GameNpc } from "@/payload-types";
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 {
Dialog,
DialogContent,
DialogTitle,
} from "@/components/ui/dialog";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
evaluateNpcDialogueChoices,
evaluateNpcDialogueCondition,
resolveNpcDialogueTexts,
triggerNpcDialogueEvent,
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
interface NpcConversationProps {
readonly npc: GameNpc;
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
}
interface ResolvedFlow {
nodes: DialogueNode[];
startId: string | null;
}
type LogEntry =
| {
kind: "node";
id: string;
node: DialogueNode;
/** Server-resolved display strings (flag tokens interpolated), when the
* node had tokens. Undefined = render the raw authored strings. */
resolved?: ResolvedNodeTexts;
}
| { kind: "player"; id: string; text: string };
/** Resolves the authored flowchart into a shape the runtime can walk. */
function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | null {
if (!dialogue?.flowData || !Array.isArray(dialogue.flowData.nodes)) return null;
const nodes = dialogue.flowData.nodes as DialogueNode[];
return { nodes, startId: findStartNode(nodes)?.id ?? null };
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
/** Text length drives how long the NPC "types"; jitter keeps it human. */
function typingDelayMs(text: string): number {
return Math.min(2600, 450 + text.length * 24) * (0.85 + Math.random() * 0.3);
}
function nodeText(node: DialogueNode): string {
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
}
export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
const [open, setOpen] = useState(false);
const [log, setLog] = useState<LogEntry[]>([]);
/** Speaker label while the NPC types; "" for speaker-less narration. */
const [typing, setTyping] = useState<string | null>(null);
/** True while the player's chosen line is "typing" into the log. */
const [playerTyping, setPlayerTyping] = useState(false);
/** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation.
* Purely local: it resets on every `begin()`, so a choice hidden here
* reappears the next time the conversation is opened. Persist across
* conversations with a condition + player flag instead. */
const [takenChoices, setTakenChoices] = useState<Set<string>>(new Set());
/** 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, 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);
const nextId = () => `entry-${seq.current++}`;
// Invalidate pending typing timers when the component unmounts.
useEffect(
() => () => {
sessionRef.current += 1;
},
[],
);
// Keep the newest line in view.
useEffect(() => {
const el = scrollRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [log, typing, playerTyping, open]);
// The choice node the log currently rests on (if any).
const activeChoiceNodeId = useMemo(() => {
const last = [...log].reverse().find((entry) => entry.kind === "node");
return last && last.kind === "node" && last.node.type === "choice" ? last.node.id : null;
}, [log]);
// Fetch the server-side visibility gates when landing on a choice node
// that has gated choices. Gated choices stay hidden until confirmed, so a
// forbidden option never flashes on screen.
useEffect(() => {
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());
if (!hasGated) return;
let cancelled = false;
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
if (!cancelled && res.success && Array.isArray(res.data)) {
const gate = res.data;
setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate }));
}
});
return () => {
cancelled = true;
};
}, [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. */
const typeIn = async (node: DialogueNode, token: number) => {
let resolved: ResolvedNodeTexts | undefined;
if (collectNodeTokens(node).length > 0) {
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
if (sessionRef.current !== token) return;
if (res.success && res.data) resolved = res.data;
}
setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name);
await sleep(typingDelayMs(nodeText(node)));
if (sessionRef.current !== token) return;
setTyping(null);
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]);
markSeen(node.id);
};
// Opening the conversation walks the start node and auto-advances through
// linear dialogue/event nodes, so the player lands on the first interactive
// node (a choice, an end, or a dead end) without clicking Continue. Each
// line arrives after its own typing delay.
const begin = () => {
const token = ++sessionRef.current;
setLog([]);
setTyping(null);
setPlayerTyping(false);
setTakenChoices(new Set());
setChoiceGates({});
setOpen(true);
if (!flow.startId) return;
void (async () => {
const start = flow.nodes.find((n) => n.id === flow.startId) ?? null;
if (start) await cascadeFrom(start, token);
})();
};
/** Types `start`, then auto-advances through linear dialogue/event/delay/
* condition nodes so the player always lands on the next interactive node
* (a choice or an end). Delay nodes pause the conversation; condition nodes
* branch on the player's flags, evaluated server-side. Neither is logged. */
const cascadeFrom = async (start: DialogueNode, token: number) => {
let current: DialogueNode | null = start;
const seen = new Set<string>();
while (current && !seen.has(current.id) && sessionRef.current === token) {
seen.add(current.id);
if (current.type === "delay") {
const seconds = Math.min(30, Math.max(0.5, current.data.delaySeconds ?? 2));
setTyping("");
await sleep(seconds * 1000);
if (sessionRef.current !== token) return;
setTyping(null);
const target: string | undefined = current.data.next?.target;
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
continue;
}
if (current.type === "condition") {
const result = await evaluateNpcDialogueCondition(Number(npc.id), current.id);
if (sessionRef.current !== token) return;
const branch =
result.success && result.data ? current.data.trueTarget : current.data.falseTarget;
current = branch ? (flow.nodes.find((n) => n.id === branch) ?? null) : null;
continue;
}
await typeIn(current, token);
if (sessionRef.current !== token) return;
if (current.type === "dialogue" || current.type === "event") {
if (current.type === "event" && current.data.effect) {
// Await the effect so flags it writes are visible to the lines
// that follow (interpolated text and later condition nodes).
await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined);
if (sessionRef.current !== token) return;
}
const target: string | undefined = current.data.next?.target;
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
} else {
current = null;
}
}
};
const close = () => {
sessionRef.current += 1;
setTyping(null);
setPlayerTyping(false);
setOpen(false);
};
const lastNode = [...log].reverse().find((entry) => entry.kind === "node");
// The player's line types out (shorter than NPC pacing), lands, and then
// the NPC starts typing its reply. `displayText` is the label as shown on
// the button (flag tokens already interpolated server-side).
const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => {
const token = sessionRef.current;
const text = displayText || hop.label || "…";
if (hop.once && lastNode && lastNode.kind === "node") {
const key = `${lastNode.node.id}:${choiceIndex}`;
setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
}
void (async () => {
setPlayerTyping(true);
await sleep(Math.min(1100, 300 + text.length * 16) * (0.85 + Math.random() * 0.3));
if (sessionRef.current !== token) return;
setPlayerTyping(false);
setLog((prev) => [...prev, { kind: "player", id: nextId(), text }]);
const target = flow.nodes.find((n) => n.id === hop.target);
if (target) await cascadeFrom(target, token);
})();
};
// The choices offered by the node the log currently rests on. One-time
// choices the player already took are hidden; if that empties the list the
// footer falls back to the End conversation button so nobody gets stuck.
const choiceNode =
lastNode && lastNode.kind === "node" && lastNode.node.type === "choice"
? lastNode.node
: null;
const visibleChoices = choiceNode
? (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. */
const choiceLabel = (hop: DialogueNext, index: number): string =>
((lastNode?.kind === "node" ? lastNode.resolved?.labels?.[index] : undefined) ??
hop.label) ||
"…";
/** Rich hover tooltip for a choice (resolved like labels); undefined when
* the author left it empty. */
const choiceTooltip = (hop: DialogueNext, index: number): string | undefined => {
const raw =
(lastNode?.kind === "node" ? lastNode.resolved?.tooltips?.[index] : undefined) ??
hop.tooltip;
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 (
<>
<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
showCloseButton={false}
className="flex w-[calc(100%-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:w-full sm:rounded-none"
>
<div className={`relative flex items-center justify-between ${DOSSIER.strip}`}>
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Conversation // {npc.name}
</DialogTitle>
<button
type="button"
onClick={close}
aria-label="Close conversation"
className="shrink-0 text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
<span
aria-hidden
className="pointer-events-none absolute inset-0 opacity-[0.04]"
style={DOSSIER.gridTexture}
/>
</div>
{flow.startId === null ? (
<div className="p-5 text-sm text-white/50">
This conversation has no start node. Ask staff to configure it.
</div>
) : (
<>
<div ref={scrollRef} className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5">
{log.map((entry) => (
<TimelineEntry key={entry.id} entry={entry} speakerDefault={npc.name} />
))}
{typing !== null && <TypingIndicator speaker={typing} />}
{playerTyping && <TypingIndicator player />}
</div>
{!typing &&
!playerTyping &&
lastNode &&
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 && (
<TooltipProvider delayDuration={150}>
{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 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"
}`}
>
<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 = locked ? choiceHint(hop, index) : choiceTooltip(hop, index);
if (!tip) return <Fragment key={index}>{button}</Fragment>;
return (
<Tooltip key={index}>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={8}
className="max-w-xs rounded-none border border-white/20 bg-zinc-900 p-3 text-left text-sm font-normal leading-relaxed text-white/85"
>
<DialogueText text={tip} />
</TooltipContent>
</Tooltip>
);
})}
</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"
>
End conversation
</Button>
)}
</div>
)}
</>
)}
</DialogContent>
</Dialog>
</>
);
}
function TimelineEntry({
entry,
speakerDefault,
}: {
entry: LogEntry;
speakerDefault: string;
}) {
if (entry.kind === "player") {
return (
<div className="flex flex-col items-end gap-1">
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
<p className="max-w-[85%] rounded-none border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-sm text-cyan-50">
<DialogueText text={entry.text} />
</p>
</div>
);
}
const { node, resolved } = entry;
if (node.type === "event") {
// Narration: no speaker, styled like a mission briefing line.
const body = resolved?.body ?? node.data.body;
const message = resolved?.message ?? node.data.effect?.message;
const text = body || message || "An event unfolds…";
return (
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
</p>
);
}
if (node.type === "end") {
const text = (resolved?.closing ?? node.data.closing) || "The conversation ends.";
return (
<p className="text-sm italic text-white/50">
<DialogueText text={text} />
</p>
);
}
if (node.type === "choice") {
// The choice buttons live in the footer; only the lead-in joins the log.
const leadIn = resolved?.leadIn ?? node.data.leadIn;
if (!leadIn) return null;
return (
<p className="text-sm italic text-white/60">
<DialogueText text={leadIn} />
</p>
);
}
const speaker = node.data.speaker?.trim() || speakerDefault;
const body = resolved?.body ?? node.data.body;
return (
<div className="flex flex-col gap-1">
<span className={DOSSIER.readoutLabel}>{speaker}</span>
<p className="text-sm text-white/90">
{body ? (
<DialogueText text={body} />
) : (
<span className="italic text-white/30">…</span>
)}
</p>
</div>
);
}
/** Three bouncing dots while a line is "typing". `player` renders the
* right-aligned cyan variant for the player's incoming response. */
function TypingIndicator({ speaker, player }: { speaker?: string; player?: boolean }) {
return (
<div className={`flex flex-col gap-1 ${player ? "items-end" : ""}`}>
{player ? (
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
) : speaker ? (
<span className={DOSSIER.readoutLabel}>{speaker}</span>
) : null}
<span
className={`flex items-center gap-1 py-1 ${player ? "justify-end" : ""}`}
role="status"
aria-label={player ? "You are typing" : "typing"}
>
{[0, 150, 300].map((delay) => (
<span
key={delay}
className={`size-1.5 animate-bounce rounded-full ${player ? "bg-cyan-300/80" : "bg-cyan-400/70"}`}
style={{ animationDelay: `${delay}ms` }}
/>
))}
</span>
</div>
);
}