feat(npc-dialogue): flow editor UX pass for authoring dialogue flows
- Delete selected nodes with Del/Backspace (guarded against open dialogs, menus, and focused form fields) - Double-click the canvas to drop a dialogue node at the cursor; right-click empty canvas for a New node menu with all six types; toolbar buttons now place nodes at the viewport center instead of blind grid coordinates - Choices support optional flag conditions evaluated server-side per player (player flag first, global fallback); gated choices stay hidden until the server confirms them, so forbidden options never flash on screen - Litegraph-style per-output handles: one source handle per choice row plus dedicated true/false handles on condition nodes, wired through derived edges and handle-aware connections - Brighten passive edge lines and edge labels on the dark canvas - New dialogue nodes default to an empty speaker, rendering the NPC's name
This commit is contained in:
parent
0cadd1e062
commit
089246def8
7 changed files with 479 additions and 62 deletions
|
|
@ -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<ActionResult<boolean[]>> {
|
||||||
|
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(
|
async function evaluateCondition(
|
||||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||||
userId: number,
|
userId: number,
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,27 @@
|
||||||
border-color: #22d3ee;
|
border-color: #22d3ee;
|
||||||
box-shadow: 0 0 6px rgba(34, 211, 238, 0.9);
|
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 +
|
/* NPC dialogue editor: "expand" mode floats the whole editor (toolbar +
|
||||||
|
|
|
||||||
|
|
@ -132,6 +132,17 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
||||||
const removeChoice = (index: number) =>
|
const removeChoice = (index: number) =>
|
||||||
patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) });
|
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<DialogueCondition> | null) =>
|
||||||
|
patch({
|
||||||
|
choices: (draft.choices ?? []).map((c, i) => {
|
||||||
|
if (i !== index) return c;
|
||||||
|
if (partial === null) return { ...c, condition: undefined };
|
||||||
|
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
|
||||||
|
return { ...c, condition: { ...base, ...partial } };
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
const targetOptions = allNodes.filter((n) => n.id !== node.id);
|
const targetOptions = allNodes.filter((n) => n.id !== node.id);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -252,6 +263,68 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
||||||
/>
|
/>
|
||||||
Hide after picked (one-time choice)
|
Hide after picked (one-time choice)
|
||||||
</label>
|
</label>
|
||||||
|
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||||
|
<Checkbox
|
||||||
|
checked={choice.condition !== undefined}
|
||||||
|
onCheckedChange={(checked) =>
|
||||||
|
setChoiceCondition(index, checked === true ? {} : null)
|
||||||
|
}
|
||||||
|
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
|
||||||
|
/>
|
||||||
|
Only show when a flag condition passes
|
||||||
|
</label>
|
||||||
|
{choice.condition && (
|
||||||
|
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
|
||||||
|
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||||
|
Flag key
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
value={choice.condition.key}
|
||||||
|
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
|
||||||
|
placeholder="met_informant"
|
||||||
|
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||||
|
/>
|
||||||
|
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||||
|
When the flag
|
||||||
|
</Label>
|
||||||
|
<select
|
||||||
|
value={choice.condition.op}
|
||||||
|
onChange={(e) =>
|
||||||
|
setChoiceCondition(index, {
|
||||||
|
op: e.target.value as DialogueCondition["op"],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||||
|
>
|
||||||
|
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
|
||||||
|
(op) => (
|
||||||
|
<option key={op} value={op}>
|
||||||
|
{CONDITION_OP_LABELS[op]}
|
||||||
|
</option>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</select>
|
||||||
|
{NUMERIC_OPS.includes(choice.condition.op) && (
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||||
|
Amount
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={choice.condition.amount ?? 0}
|
||||||
|
onChange={(e) =>
|
||||||
|
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
|
||||||
|
}
|
||||||
|
className="bg-zinc-800 border-white/20 text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<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.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,23 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
|
import {
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type MouseEvent as ReactMouseEvent,
|
||||||
|
} from "react";
|
||||||
import {
|
import {
|
||||||
Background,
|
Background,
|
||||||
type Connection,
|
type Connection,
|
||||||
type Edge,
|
type Edge,
|
||||||
type Node,
|
type Node,
|
||||||
ReactFlow,
|
ReactFlow,
|
||||||
|
ReactFlowProvider,
|
||||||
useNodesState,
|
useNodesState,
|
||||||
|
useReactFlow,
|
||||||
|
type XYPosition,
|
||||||
} from "@xyflow/react";
|
} from "@xyflow/react";
|
||||||
import "@xyflow/react/dist/style.css";
|
import "@xyflow/react/dist/style.css";
|
||||||
import { Maximize2, Minimize2 } from "lucide-react";
|
import { Maximize2, Minimize2 } from "lucide-react";
|
||||||
|
|
@ -37,6 +47,8 @@ const nodeTypes = {
|
||||||
const defaultFlow: FlowData = { nodes: [], edges: [] };
|
const defaultFlow: FlowData = { nodes: [], edges: [] };
|
||||||
|
|
||||||
type ContextMenu = { x: number; y: number; nodeId: string } | null;
|
type ContextMenu = { x: number; y: number; nodeId: string } | null;
|
||||||
|
/** Right-click menu on empty canvas: adds a node at the clicked flow spot. */
|
||||||
|
type PaneMenu = { x: number; y: number; fx: number; fy: number } | null;
|
||||||
|
|
||||||
const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
|
const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
|
||||||
dialogue: "Dialogue",
|
dialogue: "Dialogue",
|
||||||
|
|
@ -48,7 +60,8 @@ const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
||||||
dialogue: { speaker: "NPC", body: "" },
|
// No speaker by default: an empty speaker renders as the NPC's own name.
|
||||||
|
dialogue: { body: "" },
|
||||||
choice: { choices: [] },
|
choice: { choices: [] },
|
||||||
event: { effect: { type: "notify", message: "" } },
|
event: { effect: { type: "notify", message: "" } },
|
||||||
delay: { delaySeconds: 2 },
|
delay: { delaySeconds: 2 },
|
||||||
|
|
@ -56,8 +69,9 @@ const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
||||||
end: {},
|
end: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function NpcDialogueEditor() {
|
function FlowEditor() {
|
||||||
const { value, setValue } = useField<FlowData>();
|
const { value, setValue } = useField<FlowData>();
|
||||||
|
const rf = useReactFlow();
|
||||||
|
|
||||||
const initial: FlowData =
|
const initial: FlowData =
|
||||||
value && typeof value === "object" && Array.isArray((value as FlowData).nodes)
|
value && typeof value === "object" && Array.isArray((value as FlowData).nodes)
|
||||||
|
|
@ -67,10 +81,13 @@ export function NpcDialogueEditor() {
|
||||||
const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes as Node[]);
|
const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes as Node[]);
|
||||||
const [editingNodeId, setEditingNodeId] = useState<string | null>(null);
|
const [editingNodeId, setEditingNodeId] = useState<string | null>(null);
|
||||||
const [contextMenu, setContextMenu] = useState<ContextMenu>(null);
|
const [contextMenu, setContextMenu] = useState<ContextMenu>(null);
|
||||||
|
const [paneMenu, setPaneMenu] = useState<PaneMenu>(null);
|
||||||
const [expanded, setExpanded] = useState(false);
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
|
||||||
const lastSerialized = useRef<string>("");
|
const lastSerialized = useRef<string>("");
|
||||||
const menuRef = useRef<HTMLDivElement | null>(null);
|
const menuRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const paneMenuRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const canvasRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
// Edges are a derived projection of the node data, never edited directly.
|
// Edges are a derived projection of the node data, never edited directly.
|
||||||
const syncedEdges = useMemo<Edge[]>(
|
const syncedEdges = useMemo<Edge[]>(
|
||||||
|
|
@ -90,24 +107,40 @@ export function NpcDialogueEditor() {
|
||||||
}
|
}
|
||||||
}, [setValue]);
|
}, [setValue]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a node. Without an explicit position it lands in the middle of the
|
||||||
|
* current viewport (with a small cascade offset), so toolbar-added nodes
|
||||||
|
* are never dropped off-screen.
|
||||||
|
*/
|
||||||
const addNode = useCallback(
|
const addNode = useCallback(
|
||||||
(type: NpcDialogueNodeType) => {
|
(type: NpcDialogueNodeType, at?: XYPosition) => {
|
||||||
const count = nodes.length;
|
const count = nodes.length;
|
||||||
|
let position: XYPosition;
|
||||||
|
if (at) {
|
||||||
|
position = at;
|
||||||
|
} else {
|
||||||
|
const vp = rf.getViewport();
|
||||||
|
const rect = canvasRef.current?.getBoundingClientRect();
|
||||||
|
const cx = (rect?.width ?? 800) / 2;
|
||||||
|
const cy = (rect?.height ?? 500) / 2;
|
||||||
|
position = {
|
||||||
|
x: (cx - vp.x) / vp.zoom - 160 + (count % 3) * 28,
|
||||||
|
y: (cy - vp.y) / vp.zoom - 60 + (count % 3) * 22,
|
||||||
|
};
|
||||||
|
}
|
||||||
const node: DialogueNode = {
|
const node: DialogueNode = {
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
type,
|
type,
|
||||||
position: {
|
position,
|
||||||
x: 120 + (count % 4) * 240,
|
|
||||||
y: 80 + Math.floor(count / 4) * 140,
|
|
||||||
},
|
|
||||||
data: { ...DEFAULT_DATA[type] },
|
data: { ...DEFAULT_DATA[type] },
|
||||||
};
|
};
|
||||||
const next = [...nodes, node];
|
const next = [...nodes, node];
|
||||||
setNodes(next);
|
setNodes(next);
|
||||||
serialize(next);
|
serialize(next);
|
||||||
setEditingNodeId(node.id);
|
setEditingNodeId(node.id);
|
||||||
|
setPaneMenu(null);
|
||||||
},
|
},
|
||||||
[nodes, setNodes, serialize],
|
[nodes, setNodes, serialize, rf],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleNodeSave = useCallback(
|
const handleNodeSave = useCallback(
|
||||||
|
|
@ -120,24 +153,26 @@ export function NpcDialogueEditor() {
|
||||||
[nodes, setNodes, serialize],
|
[nodes, setNodes, serialize],
|
||||||
);
|
);
|
||||||
|
|
||||||
const deleteNode = useCallback(
|
/** Deletes one or more nodes and scrubs every hop that pointed at them. */
|
||||||
(nodeId: string) => {
|
const deleteNodes = useCallback(
|
||||||
|
(ids: string[]) => {
|
||||||
|
const gone = new Set(ids);
|
||||||
const next = (nodes as DialogueNode[])
|
const next = (nodes as DialogueNode[])
|
||||||
.filter((n) => n.id !== nodeId)
|
.filter((n) => !gone.has(n.id))
|
||||||
.map((n) => ({
|
.map((n) => ({
|
||||||
...n,
|
...n,
|
||||||
data: {
|
data: {
|
||||||
...n.data,
|
...n.data,
|
||||||
next: n.data.next && n.data.next.target !== nodeId ? n.data.next : undefined,
|
next: n.data.next && !gone.has(n.data.next.target) ? n.data.next : undefined,
|
||||||
choices: (n.data.choices ?? []).filter((c) => c.target !== nodeId),
|
choices: (n.data.choices ?? []).filter((c) => !gone.has(c.target)),
|
||||||
trueTarget: n.data.trueTarget !== nodeId ? n.data.trueTarget : undefined,
|
trueTarget: n.data.trueTarget && !gone.has(n.data.trueTarget) ? n.data.trueTarget : undefined,
|
||||||
falseTarget: n.data.falseTarget !== nodeId ? n.data.falseTarget : undefined,
|
falseTarget: n.data.falseTarget && !gone.has(n.data.falseTarget) ? n.data.falseTarget : undefined,
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
setNodes(next);
|
setNodes(next);
|
||||||
serialize(next);
|
serialize(next);
|
||||||
setContextMenu(null);
|
setContextMenu(null);
|
||||||
if (editingNodeId === nodeId) setEditingNodeId(null);
|
if (editingNodeId && gone.has(editingNodeId)) setEditingNodeId(null);
|
||||||
},
|
},
|
||||||
[nodes, setNodes, serialize, editingNodeId],
|
[nodes, setNodes, serialize, editingNodeId],
|
||||||
);
|
);
|
||||||
|
|
@ -150,26 +185,71 @@ export function NpcDialogueEditor() {
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Drag-to-connect writes into the node data (the graph's source of truth);
|
// Right-click on empty canvas: offer a "new node" menu at the cursor.
|
||||||
// edges stay a derived projection.
|
const onPaneContextMenu = useCallback(
|
||||||
|
(e: MouseEvent | ReactMouseEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const p = rf.screenToFlowPosition({ x: e.clientX, y: e.clientY });
|
||||||
|
setContextMenu(null);
|
||||||
|
setPaneMenu({ x: e.clientX, y: e.clientY, fx: p.x, fy: p.y });
|
||||||
|
},
|
||||||
|
[rf],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Double-click on empty canvas: drop a Dialogue node right there.
|
||||||
|
const onCanvasDoubleClick = useCallback(
|
||||||
|
(e: ReactMouseEvent<HTMLDivElement>) => {
|
||||||
|
const target = e.target as HTMLElement;
|
||||||
|
if (!target.closest?.(".react-flow__pane")) return;
|
||||||
|
const pos = rf.screenToFlowPosition({ x: e.clientX, y: e.clientY });
|
||||||
|
addNode("dialogue", pos);
|
||||||
|
},
|
||||||
|
[rf, addNode],
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drag-to-connect writes into the node data (the graph's source of truth);
|
||||||
|
* edges stay a derived projection. `sourceHandle` identifies which output
|
||||||
|
* was dragged (`c0`..`cN` per choice row, `true`/`false` per condition
|
||||||
|
* branch); without one, sensible fallbacks apply (choice gains a new
|
||||||
|
* option, condition fills its first free branch).
|
||||||
|
*/
|
||||||
const applyConnection = useCallback(
|
const applyConnection = useCallback(
|
||||||
(sourceId: string, targetId: string) => {
|
(sourceId: string, targetId: string, sourceHandle?: string | null) => {
|
||||||
if (sourceId === targetId) return;
|
if (sourceId === targetId) return;
|
||||||
const all = nodes as DialogueNode[];
|
const all = nodes as DialogueNode[];
|
||||||
const source = all.find((n) => n.id === sourceId);
|
const source = all.find((n) => n.id === sourceId);
|
||||||
const target = all.find((n) => n.id === targetId);
|
const target = all.find((n) => n.id === targetId);
|
||||||
if (!source || !target) return;
|
if (!source || !target) return;
|
||||||
if (source.type === "end" || target.data.isStart) return;
|
if (source.type === "end" || target.data.isStart) return;
|
||||||
|
let needsChoiceLabel = false;
|
||||||
const next = all.map((n) => {
|
const next = all.map((n) => {
|
||||||
if (n.id !== sourceId) return n;
|
if (n.id !== sourceId) return n;
|
||||||
if (n.type === "choice") {
|
if (n.type === "choice") {
|
||||||
|
const m = sourceHandle?.match(/^c(\d+)$/);
|
||||||
|
if (m) {
|
||||||
|
const idx = Number(m[1]);
|
||||||
|
const choices = [...(n.data.choices ?? [])];
|
||||||
|
if (!choices[idx]) return n;
|
||||||
|
choices[idx] = { ...choices[idx], target: targetId };
|
||||||
|
if (!choices[idx].label?.trim()) needsChoiceLabel = true;
|
||||||
|
return { ...n, data: { ...n.data, choices } };
|
||||||
|
}
|
||||||
|
// Generic handle (zero choices): dragging creates the first choice.
|
||||||
|
needsChoiceLabel = true;
|
||||||
return {
|
return {
|
||||||
...n,
|
...n,
|
||||||
data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] },
|
data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (n.type === "condition") {
|
if (n.type === "condition") {
|
||||||
// First connection wires the true branch, the second the false one.
|
if (sourceHandle === "true") {
|
||||||
|
return { ...n, data: { ...n.data, trueTarget: targetId } };
|
||||||
|
}
|
||||||
|
if (sourceHandle === "false") {
|
||||||
|
return { ...n, data: { ...n.data, falseTarget: targetId } };
|
||||||
|
}
|
||||||
|
// No handle info (dropped on the card): first free branch wins.
|
||||||
if (n.data.trueTarget && n.data.falseTarget) return n;
|
if (n.data.trueTarget && n.data.falseTarget) return n;
|
||||||
return {
|
return {
|
||||||
...n,
|
...n,
|
||||||
|
|
@ -184,9 +264,9 @@ export function NpcDialogueEditor() {
|
||||||
});
|
});
|
||||||
setNodes(next);
|
setNodes(next);
|
||||||
serialize(next);
|
serialize(next);
|
||||||
// A fresh choice has no button text yet: pop the editor so it can be
|
// A fresh or still-unlabeled choice pops the editor so its button text
|
||||||
// typed immediately (validateGraph flags empty labels).
|
// can be typed immediately (validateGraph flags empty labels).
|
||||||
if (source.type === "choice") setEditingNodeId(sourceId);
|
if (source.type === "choice" && needsChoiceLabel) setEditingNodeId(sourceId);
|
||||||
},
|
},
|
||||||
[nodes, setNodes, serialize],
|
[nodes, setNodes, serialize],
|
||||||
);
|
);
|
||||||
|
|
@ -200,23 +280,30 @@ export function NpcDialogueEditor() {
|
||||||
[nodes],
|
[nodes],
|
||||||
);
|
);
|
||||||
|
|
||||||
const onPaneClick = useCallback(() => setContextMenu(null), []);
|
const onPaneClick = useCallback(() => {
|
||||||
|
setContextMenu(null);
|
||||||
|
setPaneMenu(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
|
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
|
||||||
|
|
||||||
// Close the context menu on escape / pointer outside.
|
// Close both context menus on escape / pointer outside.
|
||||||
const closeMenu = useCallback(() => setContextMenu(null), []);
|
const closeMenus = useCallback(() => {
|
||||||
|
setContextMenu(null);
|
||||||
|
setPaneMenu(null);
|
||||||
|
}, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!contextMenu) return;
|
if (!contextMenu && !paneMenu) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") closeMenu();
|
if (e.key === "Escape") closeMenus();
|
||||||
};
|
};
|
||||||
// Ignore pointerdowns inside the menu itself: pointerdown fires before
|
// Ignore pointerdowns inside a menu itself: pointerdown fires before
|
||||||
// click, so closing here would unmount the menu before its buttons can
|
// click, so closing here would unmount the menu before its buttons can
|
||||||
// ever receive the click.
|
// ever receive the click.
|
||||||
const onPtr = (e: PointerEvent) => {
|
const onPtr = (e: PointerEvent) => {
|
||||||
if (menuRef.current?.contains(e.target as globalThis.Node)) return;
|
const t = e.target as globalThis.Node;
|
||||||
closeMenu();
|
if (menuRef.current?.contains(t) || paneMenuRef.current?.contains(t)) return;
|
||||||
|
closeMenus();
|
||||||
};
|
};
|
||||||
window.addEventListener("keydown", onKey);
|
window.addEventListener("keydown", onKey);
|
||||||
document.addEventListener("pointerdown", onPtr);
|
document.addEventListener("pointerdown", onPtr);
|
||||||
|
|
@ -224,18 +311,43 @@ export function NpcDialogueEditor() {
|
||||||
window.removeEventListener("keydown", onKey);
|
window.removeEventListener("keydown", onKey);
|
||||||
document.removeEventListener("pointerdown", onPtr);
|
document.removeEventListener("pointerdown", onPtr);
|
||||||
};
|
};
|
||||||
}, [contextMenu, closeMenu]);
|
}, [contextMenu, paneMenu, closeMenus]);
|
||||||
|
|
||||||
// Escape collapses the expanded editor, but only when nothing is layered
|
// Escape collapses the expanded editor, but only when nothing is layered
|
||||||
// on top of it (the node dialog or the context menu claim the key first).
|
// on top of it (the node dialog or a context menu claim the key first).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!expanded) return;
|
if (!expanded) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape" && !contextMenu && editingNodeId === null) setExpanded(false);
|
if (e.key === "Escape" && !contextMenu && !paneMenu && editingNodeId === null) setExpanded(false);
|
||||||
};
|
};
|
||||||
window.addEventListener("keydown", onKey);
|
window.addEventListener("keydown", onKey);
|
||||||
return () => window.removeEventListener("keydown", onKey);
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
}, [expanded, contextMenu, editingNodeId]);
|
}, [expanded, contextMenu, paneMenu, editingNodeId]);
|
||||||
|
|
||||||
|
// Delete/Backspace removes the selected nodes, unless a dialog or menu is
|
||||||
|
// open or the user is typing in a form field.
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key !== "Delete" && e.key !== "Backspace") return;
|
||||||
|
if (editingNodeId !== null || contextMenu || paneMenu) return;
|
||||||
|
const el = document.activeElement as HTMLElement | null;
|
||||||
|
if (
|
||||||
|
el &&
|
||||||
|
(el.tagName === "INPUT" ||
|
||||||
|
el.tagName === "TEXTAREA" ||
|
||||||
|
el.tagName === "SELECT" ||
|
||||||
|
el.isContentEditable)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const selected = nodes.filter((n) => n.selected).map((n) => n.id);
|
||||||
|
if (selected.length === 0) return;
|
||||||
|
e.preventDefault();
|
||||||
|
deleteNodes(selected);
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [nodes, editingNodeId, contextMenu, paneMenu, deleteNodes]);
|
||||||
|
|
||||||
const buttonClass =
|
const buttonClass =
|
||||||
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
|
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
|
||||||
|
|
@ -309,16 +421,18 @@ export function NpcDialogueEditor() {
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
|
ref={canvasRef}
|
||||||
className={`npc-dialogue-flow border border-zinc-700 overflow-hidden bg-zinc-950 ${
|
className={`npc-dialogue-flow border border-zinc-700 overflow-hidden bg-zinc-950 ${
|
||||||
expanded ? "flex-1 min-h-0 rounded-md" : "h-[60vh] min-h-[28rem] rounded-b-md"
|
expanded ? "flex-1 min-h-0 rounded-md" : "h-[60vh] min-h-[28rem] rounded-b-md"
|
||||||
}`}
|
}`}
|
||||||
|
onDoubleClick={onCanvasDoubleClick}
|
||||||
>
|
>
|
||||||
<ReactFlow
|
<ReactFlow
|
||||||
nodes={nodes}
|
nodes={nodes}
|
||||||
edges={syncedEdges}
|
edges={syncedEdges}
|
||||||
onNodesChange={onNodesChange}
|
onNodesChange={onNodesChange}
|
||||||
onConnect={(c: Connection) => {
|
onConnect={(c: Connection) => {
|
||||||
if (c.source && c.target) applyConnection(c.source, c.target);
|
if (c.source && c.target) applyConnection(c.source, c.target, c.sourceHandle);
|
||||||
}}
|
}}
|
||||||
onConnectEnd={(event, connectionState) => {
|
onConnectEnd={(event, connectionState) => {
|
||||||
// React Flow only resolves drops onto a handle. If the pointer
|
// React Flow only resolves drops onto a handle. If the pointer
|
||||||
|
|
@ -333,14 +447,18 @@ export function NpcDialogueEditor() {
|
||||||
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
|
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
|
||||||
const targetId = nodeElement?.getAttribute("data-id");
|
const targetId = nodeElement?.getAttribute("data-id");
|
||||||
if (!targetId || targetId === sourceId) return;
|
if (!targetId || targetId === sourceId) return;
|
||||||
applyConnection(sourceId, targetId);
|
// Keep the originating handle when we know it, so per-choice and
|
||||||
|
// per-branch wiring survives a drop onto the target card.
|
||||||
|
applyConnection(sourceId, targetId, connectionState.fromHandle?.id);
|
||||||
}}
|
}}
|
||||||
isValidConnection={isValidConnection}
|
isValidConnection={isValidConnection}
|
||||||
onNodeClick={(_e, node) => setEditingNodeId(node.id)}
|
onNodeClick={(_e, node) => setEditingNodeId(node.id)}
|
||||||
onNodeContextMenu={onNodeContextMenu}
|
onNodeContextMenu={onNodeContextMenu}
|
||||||
onPaneClick={onPaneClick}
|
onPaneClick={onPaneClick}
|
||||||
|
onPaneContextMenu={onPaneContextMenu}
|
||||||
nodeTypes={nodeTypes}
|
nodeTypes={nodeTypes}
|
||||||
fitView
|
fitView
|
||||||
|
zoomOnDoubleClick={false}
|
||||||
colorMode="dark"
|
colorMode="dark"
|
||||||
defaultEdgeOptions={{ animated: true }}
|
defaultEdgeOptions={{ animated: true }}
|
||||||
proOptions={{ hideAttribution: true }}
|
proOptions={{ hideAttribution: true }}
|
||||||
|
|
@ -348,16 +466,16 @@ export function NpcDialogueEditor() {
|
||||||
<Background color="#27272a" gap={20} />
|
<Background color="#27272a" gap={20} />
|
||||||
{nodes.length === 0 && (
|
{nodes.length === 0 && (
|
||||||
<div className="absolute inset-0 pointer-events-none flex items-center justify-center text-zinc-600 text-sm">
|
<div className="absolute inset-0 pointer-events-none flex items-center justify-center text-zinc-600 text-sm">
|
||||||
Add a node to start building the conversation.
|
Double-click anywhere to add a node.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ReactFlow>
|
</ReactFlow>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="text-[10px] text-zinc-500">
|
<p className="text-[10px] text-zinc-500">
|
||||||
Click a node to edit. Right-click to delete. Drag from a node's right handle onto
|
Click a node to edit. Select and press Del (or right-click) to delete. Double-click the
|
||||||
another node to connect them (a choice node gains a new choice; dialogue and event nodes
|
canvas for a new dialogue node; right-click it for any type. Drag a row's dot to wire
|
||||||
re-point their continuation). Use Expand to fill the screen (Esc to shrink).
|
that exact choice or branch. Use Expand to fill the screen (Esc to shrink).
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{contextMenu && (
|
{contextMenu && (
|
||||||
|
|
@ -368,7 +486,7 @@ export function NpcDialogueEditor() {
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => deleteNode(contextMenu.nodeId)}
|
onClick={() => deleteNodes([contextMenu.nodeId])}
|
||||||
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm text-red-400 outline-none select-none hover:bg-red-950/40"
|
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm text-red-400 outline-none select-none hover:bg-red-950/40"
|
||||||
>
|
>
|
||||||
Delete node
|
Delete node
|
||||||
|
|
@ -376,6 +494,40 @@ export function NpcDialogueEditor() {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{paneMenu && (
|
||||||
|
<div
|
||||||
|
ref={paneMenuRef}
|
||||||
|
className="fixed z-50 min-w-[8rem] overflow-hidden rounded-md border border-zinc-700 bg-zinc-900 p-1 shadow-lg"
|
||||||
|
style={{ left: paneMenu.x, top: paneMenu.y }}
|
||||||
|
>
|
||||||
|
<p className="px-2 pb-1 pt-0.5 font-mono text-[9px] uppercase tracking-widest text-zinc-500">
|
||||||
|
New node
|
||||||
|
</p>
|
||||||
|
{(Object.keys(NODE_LABELS) as NpcDialogueNodeType[]).map((type) => (
|
||||||
|
<button
|
||||||
|
key={type}
|
||||||
|
type="button"
|
||||||
|
onClick={() => addNode(type, { x: paneMenu.fx, y: paneMenu.fy })}
|
||||||
|
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-sm text-zinc-200 outline-none select-none hover:bg-zinc-700/60"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`size-2 rounded-sm ${
|
||||||
|
{
|
||||||
|
dialogue: "bg-blue-500",
|
||||||
|
choice: "bg-amber-500",
|
||||||
|
event: "bg-emerald-500",
|
||||||
|
delay: "bg-violet-500",
|
||||||
|
condition: "bg-sky-500",
|
||||||
|
end: "bg-slate-500",
|
||||||
|
}[type]
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{NODE_LABELS[type]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<NodeEditDialog
|
<NodeEditDialog
|
||||||
node={(nodes as DialogueNode[]).find((n) => n.id === editingNodeId) ?? null}
|
node={(nodes as DialogueNode[]).find((n) => n.id === editingNodeId) ?? null}
|
||||||
allNodes={nodes as DialogueNode[]}
|
allNodes={nodes as DialogueNode[]}
|
||||||
|
|
@ -389,4 +541,12 @@ export function NpcDialogueEditor() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function NpcDialogueEditor() {
|
||||||
|
return (
|
||||||
|
<ReactFlowProvider>
|
||||||
|
<FlowEditor />
|
||||||
|
</ReactFlowProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default NpcDialogueEditor;
|
export default NpcDialogueEditor;
|
||||||
|
|
|
||||||
|
|
@ -22,10 +22,14 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
const d = data as DialogueNodeData;
|
const d = data as DialogueNodeData;
|
||||||
const nodeType = type as NpcDialogueNodeType;
|
const nodeType = type as NpcDialogueNodeType;
|
||||||
const meta = DIALOGUE_NODES[nodeType];
|
const meta = DIALOGUE_NODES[nodeType];
|
||||||
// Only end nodes are truly terminal. A choice node keeps its source handle
|
// Only end nodes are truly terminal. A choice node keeps its generic source
|
||||||
// even with zero choices, otherwise there would be no way to drag the
|
// handle while it has zero choices, otherwise there would be no way to drag
|
||||||
// first choice out of it.
|
// 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 terminal = nodeType === "end";
|
||||||
|
const genericSource = !terminal && nodeType !== "condition" && !(nodeType === "choice" && choiceCount > 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|
@ -43,7 +47,15 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="max-h-32 min-h-20 overflow-y-auto px-3 py-2">
|
{/* Choice/condition cards must not clip their per-output handles, which
|
||||||
|
sit outside the card edge; other types keep scrollable content. */}
|
||||||
|
<div
|
||||||
|
className={`min-h-20 px-3 py-2 ${
|
||||||
|
nodeType === "choice" || nodeType === "condition"
|
||||||
|
? "overflow-visible"
|
||||||
|
: "max-h-32 overflow-y-auto"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
{nodeType === "dialogue" && (
|
{nodeType === "dialogue" && (
|
||||||
<div>
|
<div>
|
||||||
{d.speaker && (
|
{d.speaker && (
|
||||||
|
|
@ -68,7 +80,7 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
)}
|
)}
|
||||||
<ul className="flex flex-col gap-1">
|
<ul className="flex flex-col gap-1">
|
||||||
{(d.choices ?? []).map((choice, index) => (
|
{(d.choices ?? []).map((choice, index) => (
|
||||||
<li key={index} className="flex items-center gap-1.5 text-xs text-white/70">
|
<li key={index} className="relative flex items-center gap-1.5 text-xs text-white/70">
|
||||||
<span className="size-3 shrink-0 rounded border border-amber-500/50" />
|
<span className="size-3 shrink-0 rounded border border-amber-500/50" />
|
||||||
<span className="truncate">{choice.label || "Unlabeled choice"}</span>
|
<span className="truncate">{choice.label || "Unlabeled choice"}</span>
|
||||||
{choice.once && (
|
{choice.once && (
|
||||||
|
|
@ -76,6 +88,23 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
once
|
once
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{choice.condition && (
|
||||||
|
<span
|
||||||
|
className="shrink-0 rounded-sm border border-sky-500/40 bg-sky-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-sky-300"
|
||||||
|
title={`Only shown when flag "${choice.condition.key}" ${choice.condition.op.replace(/_/g, " ")}`}
|
||||||
|
>
|
||||||
|
gated
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{/* Per-choice source handle: drag this row's dot to wire
|
||||||
|
exactly this choice (litegraph-style per-output). */}
|
||||||
|
<Handle
|
||||||
|
id={`c${index}`}
|
||||||
|
type="source"
|
||||||
|
position={position}
|
||||||
|
className="!size-2 !bg-amber-400/80"
|
||||||
|
style={{ right: -16 }}
|
||||||
|
/>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
{(d.choices?.length ?? 0) === 0 && (
|
{(d.choices?.length ?? 0) === 0 && (
|
||||||
|
|
@ -127,18 +156,43 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{nodeType === "condition" && (
|
{nodeType === "condition" && (
|
||||||
<div className="text-sm text-white/70">
|
<div className="flex flex-col gap-1.5 text-sm text-white/70">
|
||||||
{d.condition?.key ? (
|
<div>
|
||||||
<span>
|
{d.condition?.key ? (
|
||||||
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
|
<span>
|
||||||
<span className="text-white/50">{d.condition.op}</span>
|
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
|
||||||
{typeof d.condition.amount === "number" && (
|
<span className="text-white/50">{d.condition.op}</span>
|
||||||
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
|
{typeof d.condition.amount === "number" && (
|
||||||
)}
|
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
|
||||||
</span>
|
)}
|
||||||
) : (
|
</span>
|
||||||
<span className="italic text-white/30">Set a flag key to branch on.</span>
|
) : (
|
||||||
)}
|
<span className="italic text-white/30">Set a flag key to branch on.</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{/* Dedicated true/false source handles, one per branch. */}
|
||||||
|
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-emerald-300/80">
|
||||||
|
<span className="size-2 shrink-0 rounded-full border border-emerald-400/60" />
|
||||||
|
true
|
||||||
|
</div>
|
||||||
|
<Handle
|
||||||
|
id="true"
|
||||||
|
type="source"
|
||||||
|
position={position}
|
||||||
|
className="!size-2 !bg-emerald-400/80"
|
||||||
|
style={{ top: "auto", bottom: 26 }}
|
||||||
|
/>
|
||||||
|
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-rose-300/80">
|
||||||
|
<span className="size-2 shrink-0 rounded-full border border-rose-400/60" />
|
||||||
|
false
|
||||||
|
</div>
|
||||||
|
<Handle
|
||||||
|
id="false"
|
||||||
|
type="source"
|
||||||
|
position={position}
|
||||||
|
className="!size-2 !bg-rose-400/80"
|
||||||
|
style={{ bottom: 4 }}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -155,7 +209,7 @@ export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!terminal && (
|
{genericSource && (
|
||||||
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
|
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
|
||||||
)}
|
)}
|
||||||
{!d.isStart && (
|
{!d.isStart && (
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import {
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import {
|
import {
|
||||||
|
evaluateNpcDialogueChoices,
|
||||||
evaluateNpcDialogueCondition,
|
evaluateNpcDialogueCondition,
|
||||||
triggerNpcDialogueEvent,
|
triggerNpcDialogueEvent,
|
||||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
} 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
|
* reappears the next time the conversation is opened. Persist across
|
||||||
* conversations with a condition + player flag instead. */
|
* conversations with a condition + player flag instead. */
|
||||||
const [takenChoices, setTakenChoices] = useState<Set<string>>(new Set());
|
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, boolean[]>>({});
|
||||||
const seq = useRef(0);
|
const seq = useRef(0);
|
||||||
const sessionRef = useRef(0);
|
const sessionRef = useRef(0);
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
@ -101,6 +106,33 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||||
if (el) el.scrollTop = el.scrollHeight;
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
}, [log, typing, playerTyping, open]);
|
}, [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;
|
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||||
|
|
||||||
/** Appends a node to the log after a length-based "typing" delay. */
|
/** Appends a node to the log after a length-based "typing" delay. */
|
||||||
|
|
@ -122,6 +154,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||||
setTyping(null);
|
setTyping(null);
|
||||||
setPlayerTyping(false);
|
setPlayerTyping(false);
|
||||||
setTakenChoices(new Set());
|
setTakenChoices(new Set());
|
||||||
|
setChoiceGates({});
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
if (!flow.startId) return;
|
if (!flow.startId) return;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
|
@ -210,7 +243,11 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||||
const visibleChoices = choiceNode
|
const visibleChoices = choiceNode
|
||||||
? (choiceNode.data.choices ?? [])
|
? (choiceNode.data.choices ?? [])
|
||||||
.map((hop, index) => ({ hop, index }))
|
.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 (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,12 @@ export interface DialogueNext {
|
||||||
* `dlg-once:` player flag).
|
* `dlg-once:` player flag).
|
||||||
*/
|
*/
|
||||||
once?: boolean;
|
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;
|
source: string;
|
||||||
target: string;
|
target: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
|
/** Source handle the edge leaves from (`c0`..`cN` per choice, `true`/`false`). */
|
||||||
|
sourceHandle?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FlowData {
|
export interface FlowData {
|
||||||
|
|
@ -150,6 +158,20 @@ export function findStartNode(nodes: DialogueNode[]): DialogueNode | null {
|
||||||
return (roots.length ? roots[0] : nodes[0]) ?? 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. */
|
/** Builds the edge projection that mirrors the node graph. */
|
||||||
export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
|
export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
|
||||||
const edges: DialogueEdge[] = [];
|
const edges: DialogueEdge[] = [];
|
||||||
|
|
@ -161,6 +183,7 @@ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
|
||||||
source: node.id,
|
source: node.id,
|
||||||
target: hop.target,
|
target: hop.target,
|
||||||
label: hop.label,
|
label: hop.label,
|
||||||
|
sourceHandle: handleIdForHop(node, index),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -198,6 +221,9 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
|
||||||
if (node.type === "choice" && !hop.label?.trim()) {
|
if (node.type === "choice" && !hop.label?.trim()) {
|
||||||
errors.push(`A choice on "${node.id}" needs button text.`);
|
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.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue