"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 = { dialogue: "Dialogue", choice: "Choice", event: "Event", delay: "Delay", condition: "Condition", end: "End", }; const DEFAULT_DATA: Record = { 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(); 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(null); const [contextMenu, setContextMenu] = useState(null); const lastSerialized = useRef(""); const menuRef = useRef(null); // Edges are a derived projection of the node data, never edited directly. const syncedEdges = useMemo( () => 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 (
Nodes {nodes.length} node{nodes.length !== 1 ? "s" : ""}
{!validation.valid && (
{validation.errors.slice(0, 3).join(" ")}
)}
{ 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 }} > {nodes.length === 0 && (
Add a node to start building the conversation.
)}

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).

{contextMenu && (
)} n.id === editingNodeId) ?? null} allNodes={nodes as DialogueNode[]} open={editingNodeId !== null} onOpenChange={(open) => { if (!open) setEditingNodeId(null); }} onSave={handleNodeSave} />
); } export default NpcDialogueEditor;