Finish the NPC dialogue flowchart work carried over from the base commit:
- Coloured NPC dialogue text via friendly names ({red}) or hex ({#ff00ff});
invalid names/hex render as literal text. Shared client-safe renderer
(DialogueText.tsx) used by both the admin canvas preview and the runtime.
- Player-flags feature: condition nodes branch on flags (evaluated
server-side), flag effects set/clear/adjust flags, PlayerFlags collection
+ migration, and event nodes can set flags.
- One-time ("once") choices: a choice flagged "Hide after picked" is hidden
for the rest of the current conversation only (per-session, resets on
begin()); GMs can persist across conversations with a condition flag.
- Admin editor: colour hint, once checkbox on choices, amber "once" badge.
Migration repair: the player_flags migration (20261005_185014) was sorting
before 20261006_000000, whose stale snapshot omitted player_flags, so any
future `migrate:create` re-emitted player_flags DDL. Restored 20261006_000000's
snapshot to the full current schema so it is the correct diff base.
Verified: `bun run payload migrate` clean, `migrate:create` reports no
schema changes, `tsc --noEmit` clean.
361 lines
12 KiB
TypeScript
361 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
|
|
import {
|
|
Background,
|
|
type Connection,
|
|
type Edge,
|
|
type Node,
|
|
ReactFlow,
|
|
useNodesState,
|
|
} from "@xyflow/react";
|
|
import "@xyflow/react/dist/style.css";
|
|
|
|
import { useField } from "@payloadcms/ui";
|
|
|
|
import type {
|
|
DialogueEdge,
|
|
DialogueNode,
|
|
DialogueNodeData,
|
|
FlowData,
|
|
NpcDialogueNodeType,
|
|
} from "@/lib/npc-dialogue/dialogue";
|
|
import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue";
|
|
import { NpcDialogueNode } from "./NpcDialogueNode";
|
|
import { NodeEditDialog } from "./NodeEditDialog";
|
|
|
|
const nodeTypes = {
|
|
dialogue: NpcDialogueNode,
|
|
choice: NpcDialogueNode,
|
|
event: NpcDialogueNode,
|
|
delay: NpcDialogueNode,
|
|
condition: NpcDialogueNode,
|
|
end: NpcDialogueNode,
|
|
};
|
|
|
|
const defaultFlow: FlowData = { nodes: [], edges: [] };
|
|
|
|
type ContextMenu = { x: number; y: number; nodeId: string } | null;
|
|
|
|
const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
|
|
dialogue: "Dialogue",
|
|
choice: "Choice",
|
|
event: "Event",
|
|
delay: "Delay",
|
|
condition: "Condition",
|
|
end: "End",
|
|
};
|
|
|
|
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
|
dialogue: { speaker: "NPC", body: "" },
|
|
choice: { choices: [] },
|
|
event: { effect: { type: "notify", message: "" } },
|
|
delay: { delaySeconds: 2 },
|
|
condition: { condition: { kind: "flag", key: "", op: "is_true" } },
|
|
end: {},
|
|
};
|
|
|
|
export function NpcDialogueEditor() {
|
|
const { value, setValue } = useField<FlowData>();
|
|
|
|
const initial: FlowData =
|
|
value && typeof value === "object" && Array.isArray((value as FlowData).nodes)
|
|
? (value as FlowData)
|
|
: defaultFlow;
|
|
|
|
const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes as Node[]);
|
|
const [editingNodeId, setEditingNodeId] = useState<string | null>(null);
|
|
const [contextMenu, setContextMenu] = useState<ContextMenu>(null);
|
|
|
|
const lastSerialized = useRef<string>("");
|
|
const menuRef = useRef<HTMLDivElement | null>(null);
|
|
|
|
// Edges are a derived projection of the node data, never edited directly.
|
|
const syncedEdges = useMemo<Edge[]>(
|
|
() => deriveEdges(nodes as DialogueNode[]),
|
|
[nodes],
|
|
);
|
|
|
|
const serialize = useCallback((nds: Node[]) => {
|
|
const payload: FlowData = {
|
|
nodes: nds as DialogueNode[],
|
|
edges: deriveEdges(nds as DialogueNode[]),
|
|
};
|
|
const serialized = JSON.stringify(payload);
|
|
if (serialized !== lastSerialized.current) {
|
|
lastSerialized.current = serialized;
|
|
setValue(payload);
|
|
}
|
|
}, [setValue]);
|
|
|
|
const addNode = useCallback(
|
|
(type: NpcDialogueNodeType) => {
|
|
const count = nodes.length;
|
|
const node: DialogueNode = {
|
|
id: crypto.randomUUID(),
|
|
type,
|
|
position: {
|
|
x: 120 + (count % 4) * 240,
|
|
y: 80 + Math.floor(count / 4) * 140,
|
|
},
|
|
data: { ...DEFAULT_DATA[type] },
|
|
};
|
|
const next = [...nodes, node];
|
|
setNodes(next);
|
|
serialize(next);
|
|
setEditingNodeId(node.id);
|
|
},
|
|
[nodes, setNodes, serialize],
|
|
);
|
|
|
|
const handleNodeSave = useCallback(
|
|
(nodeId: string, data: DialogueNodeData) => {
|
|
const next = nodes.map((n) => (n.id === nodeId ? { ...n, data } : n));
|
|
setNodes(next);
|
|
serialize(next);
|
|
setEditingNodeId(null);
|
|
},
|
|
[nodes, setNodes, serialize],
|
|
);
|
|
|
|
const deleteNode = useCallback(
|
|
(nodeId: string) => {
|
|
const next = (nodes as DialogueNode[])
|
|
.filter((n) => n.id !== nodeId)
|
|
.map((n) => ({
|
|
...n,
|
|
data: {
|
|
...n.data,
|
|
next: n.data.next && n.data.next.target !== nodeId ? n.data.next : undefined,
|
|
choices: (n.data.choices ?? []).filter((c) => c.target !== nodeId),
|
|
trueTarget: n.data.trueTarget !== nodeId ? n.data.trueTarget : undefined,
|
|
falseTarget: n.data.falseTarget !== nodeId ? n.data.falseTarget : undefined,
|
|
},
|
|
}));
|
|
setNodes(next);
|
|
serialize(next);
|
|
setContextMenu(null);
|
|
if (editingNodeId === nodeId) setEditingNodeId(null);
|
|
},
|
|
[nodes, setNodes, serialize, editingNodeId],
|
|
);
|
|
|
|
const onNodeContextMenu = useCallback(
|
|
(e: ReactMouseEvent, node: Node) => {
|
|
e.preventDefault();
|
|
setContextMenu({ x: e.clientX, y: e.clientY, nodeId: node.id });
|
|
},
|
|
[],
|
|
);
|
|
|
|
// Drag-to-connect writes into the node data (the graph's source of truth);
|
|
// edges stay a derived projection.
|
|
const applyConnection = useCallback(
|
|
(sourceId: string, targetId: string) => {
|
|
if (sourceId === targetId) return;
|
|
const all = nodes as DialogueNode[];
|
|
const source = all.find((n) => n.id === sourceId);
|
|
const target = all.find((n) => n.id === targetId);
|
|
if (!source || !target) return;
|
|
if (source.type === "end" || target.data.isStart) return;
|
|
const next = all.map((n) => {
|
|
if (n.id !== sourceId) return n;
|
|
if (n.type === "choice") {
|
|
return {
|
|
...n,
|
|
data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] },
|
|
};
|
|
}
|
|
if (n.type === "condition") {
|
|
// First connection wires the true branch, the second the false one.
|
|
if (n.data.trueTarget && n.data.falseTarget) return n;
|
|
return {
|
|
...n,
|
|
data: {
|
|
...n.data,
|
|
trueTarget: n.data.trueTarget ?? targetId,
|
|
falseTarget: n.data.trueTarget ? n.data.falseTarget : targetId,
|
|
},
|
|
};
|
|
}
|
|
return { ...n, data: { ...n.data, next: { target: targetId } } };
|
|
});
|
|
setNodes(next);
|
|
serialize(next);
|
|
// A fresh choice has no button text yet: pop the editor so it can be
|
|
// typed immediately (validateGraph flags empty labels).
|
|
if (source.type === "choice") setEditingNodeId(sourceId);
|
|
},
|
|
[nodes, setNodes, serialize],
|
|
);
|
|
|
|
const isValidConnection = useCallback(
|
|
(c: Connection | Edge) => {
|
|
if (!c.source || !c.target || c.source === c.target) return false;
|
|
const target = (nodes as DialogueNode[]).find((n) => n.id === c.target);
|
|
return !!target && !target.data.isStart;
|
|
},
|
|
[nodes],
|
|
);
|
|
|
|
const onPaneClick = useCallback(() => setContextMenu(null), []);
|
|
|
|
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
|
|
|
|
// Close the context menu on escape / pointer outside.
|
|
const closeMenu = useCallback(() => setContextMenu(null), []);
|
|
useEffect(() => {
|
|
if (!contextMenu) return;
|
|
const onKey = (e: KeyboardEvent) => {
|
|
if (e.key === "Escape") closeMenu();
|
|
};
|
|
// Ignore pointerdowns inside the menu itself: pointerdown fires before
|
|
// click, so closing here would unmount the menu before its buttons can
|
|
// ever receive the click.
|
|
const onPtr = (e: PointerEvent) => {
|
|
if (menuRef.current?.contains(e.target as globalThis.Node)) return;
|
|
closeMenu();
|
|
};
|
|
window.addEventListener("keydown", onKey);
|
|
document.addEventListener("pointerdown", onPtr);
|
|
return () => {
|
|
window.removeEventListener("keydown", onKey);
|
|
document.removeEventListener("pointerdown", onPtr);
|
|
};
|
|
}, [contextMenu, closeMenu]);
|
|
|
|
const buttonClass =
|
|
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
|
|
|
|
return (
|
|
<div className="flex flex-col gap-2 w-full">
|
|
<div className="flex flex-wrap items-center gap-1 px-2 py-1.5 bg-zinc-900 rounded-t-md border border-zinc-700">
|
|
<span className="text-[9px] uppercase tracking-wider text-zinc-500 font-semibold mr-1">
|
|
Nodes
|
|
</span>
|
|
<button
|
|
className={`${buttonClass} bg-blue-950 border-blue-700 text-blue-200 hover:bg-blue-900`}
|
|
onClick={() => addNode("dialogue")}
|
|
>
|
|
{NODE_LABELS.dialogue}
|
|
</button>
|
|
<button
|
|
className={`${buttonClass} bg-amber-950 border-amber-700 text-amber-200 hover:bg-amber-900`}
|
|
onClick={() => addNode("choice")}
|
|
>
|
|
{NODE_LABELS.choice}
|
|
</button>
|
|
<button
|
|
className={`${buttonClass} bg-emerald-950 border-emerald-700 text-emerald-200 hover:bg-emerald-900`}
|
|
onClick={() => addNode("event")}
|
|
>
|
|
{NODE_LABELS.event}
|
|
</button>
|
|
<button
|
|
className={`${buttonClass} bg-violet-950 border-violet-700 text-violet-200 hover:bg-violet-900`}
|
|
onClick={() => addNode("delay")}
|
|
>
|
|
{NODE_LABELS.delay}
|
|
</button>
|
|
<button
|
|
className={`${buttonClass} bg-sky-950 border-sky-700 text-sky-200 hover:bg-sky-900`}
|
|
onClick={() => addNode("condition")}
|
|
>
|
|
{NODE_LABELS.condition}
|
|
</button>
|
|
<button
|
|
className={`${buttonClass} bg-slate-950 border-slate-700 text-slate-200 hover:bg-slate-900`}
|
|
onClick={() => addNode("end")}
|
|
>
|
|
{NODE_LABELS.end}
|
|
</button>
|
|
|
|
<span className="ml-auto text-[10px] text-zinc-500">
|
|
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
|
|
</span>
|
|
</div>
|
|
|
|
{!validation.valid && (
|
|
<div className="px-2 py-1 bg-red-950/60 border-b border-red-900/50 text-xs text-red-300">
|
|
{validation.errors.slice(0, 3).join(" ")}
|
|
</div>
|
|
)}
|
|
|
|
<div className="npc-dialogue-flow h-96 border border-zinc-700 rounded-b-md overflow-hidden bg-zinc-950">
|
|
<ReactFlow
|
|
nodes={nodes}
|
|
edges={syncedEdges}
|
|
onNodesChange={onNodesChange}
|
|
onConnect={(c: Connection) => {
|
|
if (c.source && c.target) applyConnection(c.source, c.target);
|
|
}}
|
|
onConnectEnd={(event, connectionState) => {
|
|
// React Flow only resolves drops onto a handle. If the pointer
|
|
// was released over a node card instead, resolve that card
|
|
// ourselves so "drag onto the node" works as people expect.
|
|
if (!("fromNode" in connectionState)) return;
|
|
if (connectionState.toHandle) return; // dropped on a handle: onConnect leads
|
|
const sourceId = connectionState.fromNode?.id;
|
|
if (!sourceId) return;
|
|
const point = event as MouseEvent;
|
|
const element = document.elementFromPoint(point.clientX ?? 0, point.clientY ?? 0);
|
|
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
|
|
const targetId = nodeElement?.getAttribute("data-id");
|
|
if (!targetId || targetId === sourceId) return;
|
|
applyConnection(sourceId, targetId);
|
|
}}
|
|
isValidConnection={isValidConnection}
|
|
onNodeClick={(_e, node) => setEditingNodeId(node.id)}
|
|
onNodeContextMenu={onNodeContextMenu}
|
|
onPaneClick={onPaneClick}
|
|
nodeTypes={nodeTypes}
|
|
fitView
|
|
colorMode="dark"
|
|
defaultEdgeOptions={{ animated: true }}
|
|
proOptions={{ hideAttribution: true }}
|
|
>
|
|
<Background color="#27272a" gap={20} />
|
|
{nodes.length === 0 && (
|
|
<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.
|
|
</div>
|
|
)}
|
|
</ReactFlow>
|
|
</div>
|
|
|
|
<p className="text-[10px] text-zinc-500">
|
|
Click a node to edit. Right-click to delete. Drag from a node's right handle onto
|
|
another node to connect them (a choice node gains a new choice; dialogue and event nodes
|
|
re-point their continuation).
|
|
</p>
|
|
|
|
{contextMenu && (
|
|
<div
|
|
ref={menuRef}
|
|
className="fixed z-50 min-w-[7rem] overflow-hidden rounded-md border border-zinc-700 bg-zinc-900 p-1 shadow-lg"
|
|
style={{ left: contextMenu.x, top: contextMenu.y }}
|
|
>
|
|
<button
|
|
type="button"
|
|
onClick={() => deleteNode(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"
|
|
>
|
|
Delete node
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
<NodeEditDialog
|
|
node={(nodes as DialogueNode[]).find((n) => n.id === editingNodeId) ?? null}
|
|
allNodes={nodes as DialogueNode[]}
|
|
open={editingNodeId !== null}
|
|
onOpenChange={(open) => {
|
|
if (!open) setEditingNodeId(null);
|
|
}}
|
|
onSave={handleNodeSave}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default NpcDialogueEditor;
|