diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts index 72f1b14c..e1aac7b7 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -309,6 +309,52 @@ 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. + */ +export async function evaluateNpcDialogueChoices( + npcId: number, + nodeId: string, +): Promise> { + try { + const { payload, user } = await authenticate(); + + const res = await payload.find({ + collection: "npc-dialogues", + where: { npc: { equals: npcId } }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; + const node = flowData?.nodes?.find((n) => n.id === nodeId); + if (!node || node.type !== "choice") { + // Not a choice node: nothing to gate. + return { success: true, data: [] }; + } + + const visible: boolean[] = []; + for (const choice of node.data.choices ?? []) { + if (!choice.condition?.key?.trim()) { + visible.push(true); + continue; + } + visible.push(await evaluateCondition(payload, user.id as number, choice.condition)); + } + return { success: true, data: visible }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} + async function evaluateCondition( payload: Awaited>, userId: number, diff --git a/src/app/(payload)/custom.scss b/src/app/(payload)/custom.scss index baf9d4bd..9d80ff6e 100644 --- a/src/app/(payload)/custom.scss +++ b/src/app/(payload)/custom.scss @@ -59,6 +59,27 @@ border-color: #22d3ee; box-shadow: 0 0 6px rgba(34, 211, 238, 0.9); } + + /* Resting edges: the default thin grey line nearly vanishes on the dark + canvas, so brighten passive edges and their labels. Animated (wired) + edges get a cyan tint so connections read at a glance. */ + .react-flow__edge-path { + stroke: #a1a1aa; + stroke-opacity: 0.9; + stroke-width: 1.5; + } + .react-flow__edge.animated .react-flow__edge-path { + stroke: #67e8f9; + stroke-opacity: 0.85; + } + .react-flow__edge-text { + fill: #d4d4d8; + font-size: 10px; + } + .react-flow__edge-textbg { + fill: #18181b; + fill-opacity: 0.9; + } } /* NPC dialogue editor: "expand" mode floats the whole editor (toolbar + diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx index b79c1c1e..a5b980f7 100644 --- a/src/components/admin/npc-dialogue/NodeEditDialog.tsx +++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx @@ -132,6 +132,17 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N const removeChoice = (index: number) => patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) }); + /** Toggle/update a choice's visibility gate; null removes the gate. */ + const setChoiceCondition = (index: number, partial: Partial | null) => + patch({ + choices: (draft.choices ?? []).map((c, i) => { + if (i !== index) return c; + if (partial === null) return { ...c, condition: undefined }; + const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" }; + return { ...c, condition: { ...base, ...partial } }; + }), + }); + const targetOptions = allNodes.filter((n) => n.id !== node.id); return ( @@ -252,6 +263,68 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N /> Hide after picked (one-time choice) + + {choice.condition && ( +
+ + setChoiceCondition(index, { key: e.target.value })} + placeholder="met_informant" + className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" + /> + + + {NUMERIC_OPS.includes(choice.condition.op) && ( +
+ + + setChoiceCondition(index, { amount: Number(e.target.value) || 0 }) + } + className="bg-zinc-800 border-white/20 text-white" + /> +
+ )} +

+ Player-specific flag takes priority; falls back to global (no user). + Missing = false / 0. The choice button is hidden until this passes. +

+
+ )} + ))} + + )} + n.id === editingNodeId) ?? null} allNodes={nodes as DialogueNode[]} @@ -389,4 +541,12 @@ export function NpcDialogueEditor() { ); } +export function NpcDialogueEditor() { + return ( + + + + ); +} + export default NpcDialogueEditor; diff --git a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx index 661bc433..67f1ca5b 100644 --- a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx +++ b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx @@ -22,10 +22,14 @@ export function NpcDialogueNode({ data, type }: NodeProps) { const d = data as DialogueNodeData; const nodeType = type as NpcDialogueNodeType; const meta = DIALOGUE_NODES[nodeType]; - // Only end nodes are truly terminal. A choice node keeps its source handle - // even with zero choices, otherwise there would be no way to drag the - // first choice out of it. + // Only end nodes are truly terminal. A choice node keeps its generic source + // handle while it has zero choices, otherwise there would be no way to drag + // the first choice out of it; once choices exist each row gets its own + // handle (litegraph-style per-output wiring). Condition nodes always use + // dedicated true/false handles instead of the generic one. + const choiceCount = nodeType === "choice" ? (d.choices?.length ?? 0) : 1; const terminal = nodeType === "end"; + const genericSource = !terminal && nodeType !== "condition" && !(nodeType === "choice" && choiceCount > 0); return (
-
+ {/* Choice/condition cards must not clip their per-output handles, which + sit outside the card edge; other types keep scrollable content. */} +
{nodeType === "dialogue" && (
{d.speaker && ( @@ -68,7 +80,7 @@ export function NpcDialogueNode({ data, type }: NodeProps) { )}
    {(d.choices ?? []).map((choice, index) => ( -
  • +
  • {choice.label || "Unlabeled choice"} {choice.once && ( @@ -76,6 +88,23 @@ export function NpcDialogueNode({ data, type }: NodeProps) { once )} + {choice.condition && ( + + gated + + )} + {/* Per-choice source handle: drag this row's dot to wire + exactly this choice (litegraph-style per-output). */} +
  • ))} {(d.choices?.length ?? 0) === 0 && ( @@ -127,18 +156,43 @@ export function NpcDialogueNode({ data, type }: NodeProps) { )} {nodeType === "condition" && ( -
    - {d.condition?.key ? ( - - Flag {d.condition.key}{" "} - {d.condition.op} - {typeof d.condition.amount === "number" && ( - {d.condition.amount} - )} - - ) : ( - Set a flag key to branch on. - )} +
    +
    + {d.condition?.key ? ( + + Flag {d.condition.key}{" "} + {d.condition.op} + {typeof d.condition.amount === "number" && ( + {d.condition.amount} + )} + + ) : ( + Set a flag key to branch on. + )} +
    + {/* Dedicated true/false source handles, one per branch. */} +
    + + true +
    + +
    + + false +
    +
    )} @@ -155,7 +209,7 @@ export function NpcDialogueNode({ data, type }: NodeProps) { )}
    - {!terminal && ( + {genericSource && ( )} {!d.isStart && ( diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 9c0ad37f..c292da12 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -15,6 +15,7 @@ import { DialogTitle, } from "@/components/ui/dialog"; import { + evaluateNpcDialogueChoices, evaluateNpcDialogueCondition, triggerNpcDialogueEvent, } from "@/app/(frontend)/personnel/contacts/[id]/actions"; @@ -64,6 +65,10 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) { * reappears the next time the conversation is opened. Persist across * conversations with a condition + player flag instead. */ const [takenChoices, setTakenChoices] = useState>(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>({}); const seq = useRef(0); const sessionRef = useRef(0); const scrollRef = useRef(null); @@ -101,6 +106,33 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) { 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]); + if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null; /** Appends a node to the log after a length-based "typing" delay. */ @@ -122,6 +154,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) { setTyping(null); setPlayerTyping(false); setTakenChoices(new Set()); + setChoiceGates({}); setOpen(true); if (!flow.startId) return; void (async () => { @@ -210,7 +243,11 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) { const visibleChoices = choiceNode ? (choiceNode.data.choices ?? []) .map((hop, index) => ({ hop, index })) - .filter(({ hop, index }) => !(hop.once && takenChoices.has(`${choiceNode.id}:${index}`))) + .filter( + ({ hop, index }) => + !(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) && + (!hop.condition?.key?.trim() || choiceGates[choiceNode.id]?.[index] === true), + ) : []; return ( diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts index 6b5b3dcb..f08df5e4 100644 --- a/src/lib/npc-dialogue/dialogue.ts +++ b/src/lib/npc-dialogue/dialogue.ts @@ -27,6 +27,12 @@ export interface DialogueNext { * `dlg-once:` player flag). */ once?: boolean; + /** + * Choice hops only: when set, the choice button is only offered to players + * whose live flags satisfy this condition (evaluated server-side, same + * flag semantics as condition nodes). Missing key = ungated. + */ + condition?: DialogueCondition; } /** @@ -103,6 +109,8 @@ export interface DialogueEdge { source: string; target: string; label?: string; + /** Source handle the edge leaves from (`c0`..`cN` per choice, `true`/`false`). */ + sourceHandle?: string; } export interface FlowData { @@ -150,6 +158,20 @@ export function findStartNode(nodes: DialogueNode[]): DialogueNode | null { return (roots.length ? roots[0] : nodes[0]) ?? null; } +/** Handle id an outgoing hop leaves its node through (per-choice / per-branch). */ +export function handleIdForHop(node: DialogueNode, index: number): string | undefined { + if (node.type === "choice") return `c${index}`; + if (node.type === "condition") { + // outgoingHops skips unset branches, so map by what actually exists: + // only-true -> "true", only-false -> "false", both -> first is true. + const hasTrue = !!node.data.trueTarget; + const hasFalse = !!node.data.falseTarget; + if (hasTrue && hasFalse) return index === 0 ? "true" : "false"; + return hasTrue ? "true" : "false"; + } + return undefined; +} + /** Builds the edge projection that mirrors the node graph. */ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] { const edges: DialogueEdge[] = []; @@ -161,6 +183,7 @@ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] { source: node.id, target: hop.target, label: hop.label, + sourceHandle: handleIdForHop(node, index), }); }); } @@ -198,6 +221,9 @@ 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()) { + errors.push(`A gated choice on "${node.id}" needs a flag key.`); + } } }