"use client"; import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, } from "react"; import { Background, type Connection, type Edge, MarkerType, type Node, type NodeChange, ReactFlow, ReactFlowProvider, useNodesState, useReactFlow, type XYPosition, } from "@xyflow/react"; import "@xyflow/react/dist/style.css"; import { Magnet, Maximize2, Minimize2, Play, Sparkles } from "lucide-react"; import { useDocumentInfo, useField } from "@payloadcms/ui"; import type { NpcDialogue } from "@/payload-types"; import type { DialogueEdge, DialogueNext, DialogueNode, DialogueNodeData, FlowData, NpcDialogueNodeType, } from "@/lib/npc-dialogue/dialogue"; import { connectHop, deriveEdges, hopFromHandle, removeHopFromNode, validateGraph, } from "@/lib/npc-dialogue/dialogue"; import type { DialogueBrief } from "@/lib/npc-dialogue/generationPrompt"; import { describeAttachTarget, insertGeneratedFragment, } from "@/lib/npc-dialogue/fragmentInsert"; import type { RouteRect } from "@/lib/flow-edge-routing"; import { NpcDialogueNode } from "./NpcDialogueNode"; import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } from "./GenerateDraftDialog"; import { DialoguePreviewDialog } from "./DialoguePreviewDialog"; import type { AttachTarget, DraftPlacementChoice } from "./GenerateDraftDialog"; import { RoutedFlowEdge } from "./RoutedFlowEdge"; const nodeTypes = { dialogue: NpcDialogueNode, choice: NpcDialogueNode, event: NpcDialogueNode, delay: NpcDialogueNode, condition: NpcDialogueNode, end: NpcDialogueNode, }; const edgeTypes = { routed: RoutedFlowEdge }; /** Arrowhead tinted to match the animated cyan edge stroke. */ const EDGE_MARKER = { type: MarkerType.ArrowClosed, width: 14, height: 14, color: "#67e8f9" }; /** Drag snapping grid (px); matches the Background dot gap. */ const SNAP_GRID = 20; const SNAP_STORAGE_KEY = "ptf:npc-dialogue:snap-to-grid"; const defaultFlow: FlowData = { nodes: [], edges: [] }; 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 = { dialogue: "Dialogue", choice: "Choice", event: "Event", delay: "Delay", condition: "Condition", end: "End", }; const DEFAULT_DATA: Record = { // No speaker by default: an empty speaker renders as the NPC's own name. dialogue: { body: "" }, choice: { choices: [] }, event: { effect: { type: "notify", message: "" } }, delay: { delaySeconds: 2 }, condition: { condition: { kind: "flag", key: "", op: "is_true" } }, end: {}, }; function FlowEditor() { const { value, setValue } = useField(); // Sibling field on the same document: provenance for the draft that was // accepted. Written when a draft lands, persisted by the document's Save. const { setValue: setGeneration } = useField({ path: "generation", }); const rf = useReactFlow(); 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 [paneMenu, setPaneMenu] = useState(null); const [expanded, setExpanded] = useState(false); const [snap, setSnap] = useState(true); const [selectedEdgeId, setSelectedEdgeId] = useState(null); const [generateOpen, setGenerateOpen] = useState(false); // Walks the unsaved canvas as it stands, so an author can test a branch // without saving and leaving the admin. const [previewOpen, setPreviewOpen] = useState(false); // Set after a draft lands, cleared when the author dismisses it. Purely a // reminder: the document's own modified state is what actually guards saving. const [draftNotice, setDraftNotice] = useState(null); // Explains a refused drop. React Flow cannot say why a connection was // rejected, so the canvas looks dead instead ("I dragged it and nothing // happened"); this names the rule that blocked it. const [connectNotice, setConnectNotice] = useState(null); /** * The one node a generated branch can attach under: whatever is selected, when * exactly one thing is selected. Using the selection instead of a node picker * keeps the choice where the author already is, and it matches how a hand-drawn * wire lands when dropped on a card. */ const attachTarget = useMemo(() => { const selected = (nodes as Node[]).filter((node) => node.selected) as unknown as DialogueNode[]; if (selected.length !== 1) return null; const node = selected[0]; if (!node) return null; const described = describeAttachTarget(node); return { id: node.id, ...described }; }, [nodes]); // The contact this conversation belongs to. It is a relationship field on the // same document, so the edited doc is the only place it can come from. const { data: docData } = useDocumentInfo(); const npcId = useMemo(() => { const raw = (docData as Record | undefined)?.npc; if (typeof raw === "number") return raw; if (raw && typeof raw === "object" && "id" in raw) { const id = (raw as { id?: unknown }).id; return typeof id === "number" ? id : null; } return null; }, [docData]); const npcLabel = useMemo(() => { const raw = (docData as Record | undefined)?.npc; if (raw && typeof raw === "object" && "name" in raw) { const name = (raw as { name?: unknown }).name; if (typeof name === "string") return name; } return npcId === null ? "" : `contact ${npcId}`; }, [docData, npcId]); // This document's own id. New documents have none until the first save, which // is also when a voice override could first be stored. const dialogueId = useMemo(() => { const raw = (docData as Record | undefined)?.id; return typeof raw === "number" ? raw : null; }, [docData]); const lastSerialized = useRef(""); const menuRef = useRef(null); const paneMenuRef = useRef(null); const canvasRef = useRef(null); // Nodes created but never saved: closing their dialog without saving // discards them instead of leaving an empty card on the canvas. const draftIds = useRef>(new Set()); // Snap-to-grid is a per-browser preference (default on), like the tech // tree's; reading it after mount keeps SSR/CSR markup identical. useEffect(() => { try { const stored = window.localStorage.getItem(SNAP_STORAGE_KEY); if (stored === "off") setSnap(false); } catch { // Storage unavailable: keep the default. } }, []); const toggleSnap = useCallback(() => { setSnap((prev) => { const next = !prev; try { window.localStorage.setItem(SNAP_STORAGE_KEY, next ? "on" : "off"); } catch { // Preference just won't persist. } return next; }); }, []); // Edges are a derived projection of the node data, never edited directly. // Every edge renders through the routed edge type so lines bend around // unrelated cards instead of slicing through them. The card rectangles used // for obstacle avoidance are computed here from the live `nodes` state and // handed to each edge via `data`: React Flow mutates its store's nodeLookup // Map in place, so reading it inside the edge yields a stale snapshot that // only refreshes on remount (edges kept bending around where cards used to // be until save+refresh). Deriving from `nodes` re-routes edges as you drag. const syncedEdges = useMemo(() => { const obstacles: RouteRect[] = []; for (const n of nodes) { const width = n.measured?.width ?? 0; const height = n.measured?.height ?? 0; if (!width || !height) continue; obstacles.push({ id: n.id, x: n.position.x, y: n.position.y, width, height }); } return deriveEdges(nodes as DialogueNode[]) .map((edge) => ({ ...edge, type: "routed", animated: true, markerEnd: EDGE_MARKER, selected: edge.id === selectedEdgeId, data: { obstacles }, })); }, [nodes, selectedEdgeId]); const serialize = useCallback((nds: Node[]) => { // Volatile interaction flags (selection, in-progress drags) are not part // of the graph and must not leak into the persisted value. const clean = nds.map(({ selected, dragging, ...rest }) => rest) as DialogueNode[]; const payload: FlowData = { nodes: clean, edges: deriveEdges(clean), }; const serialized = JSON.stringify(payload); if (serialized !== lastSerialized.current) { lastSerialized.current = serialized; setValue(payload); } }, [setValue]); /** Says why a drop did nothing, for the cases the canvas cannot show. */ const refuseConnection = useCallback(() => { setConnectNotice( "Nothing was connected there. An end node has no way out, a condition has two branches, and the start node accepts nothing.", ); }, []); /** * Drops a generated draft into the canvas. It travels the same `serialize` * path as a dragged node, so it becomes unsaved field state and nothing more: * the only way to persist it stays the document's own Save. * * Two shapes, decided by the dialog: * * - **replace** writes the draft over the whole graph (the original behaviour, * and the only sensible one on an empty canvas); * - **attach / beside** splices it in as a branch. `insertGeneratedFragment` * remaps ids, strips any start flag, places it beside the node it continues * from, and wires it, so the author's existing conversation survives. */ const applyGeneratedDraft = useCallback( ( result: { flow: FlowData; model: string; promptVersion: string; promptSource: "builtin" | "global" | "dialogue"; promptRevision: number | null; connectionLabel: string | null; attempts: number; truncated: boolean; scope: "full" | "fragment"; }, brief: DialogueBrief, choice: DraftPlacementChoice, ) => { const incoming = result.flow.nodes as DialogueNode[]; const existing = nodes as DialogueNode[]; const existingIds = new Set(existing.map((node) => node.id)); const replace = choice.placement === "replace" || existing.length === 0; let nextNodes: Node[]; const notes: string[] = []; let framed: string[] = []; if (replace) { nextNodes = incoming as Node[]; framed = incoming.map((node) => node.id); if (existing.length > 0) notes.push("It replaced the conversation that was on the canvas."); } else { const inserted = insertGeneratedFragment(existing, incoming, { attachment: choice.placement === "attach" && attachTarget?.canAttach ? { sourceId: attachTarget.id, sourceHandle: null } : null, returnToCaller: choice.returnToCaller, }); nextNodes = inserted.nodes as Node[]; framed = inserted.nodes.filter((node) => !existingIds.has(node.id)).map((node) => node.id); if (inserted.wired && attachTarget) { notes.push(`Wired in from ${attachTarget.label}.`); } else if (choice.placement === "attach") { notes.push("Inserted beside the conversation without a wire."); } else { notes.push("Inserted beside the conversation, unwired."); } if (inserted.returnKind === "caller") { notes.push("One open branch points back at that menu."); } else if (inserted.returnKind === "successor") { notes.push("One open branch continues into the step it used to lead to."); } if (inserted.derivedLabel) { notes.push(`Its new choice button reads "${inserted.derivedLabel}", worth rewording.`); } notes.push(...inserted.errors); } setNodes(nextNodes); serialize(nextNodes); // The `brief` field is a Payload `json` column, whose generated type is a // loose scalar/object union, so the object shape needs a double cast. setGeneration({ model: result.model, promptVersion: result.promptVersion, promptSource: result.promptSource, promptRevision: result.promptRevision, connectionLabel: result.connectionLabel, attempts: result.attempts, generatedAt: new Date().toISOString(), brief, } as unknown as NpcDialogue["generation"]); // The voice is easy to forget about once the draft lands: naming it here is // how an author notices that a per-dialogue override, not the brief, shaped // the register they are looking at. const voiceNote = result.promptSource === "builtin" ? "" : result.promptSource === "dialogue" ? " Voice: this dialogue's own override." : " Voice: the global setting."; const modelNote = result.connectionLabel ? ` Connection: ${result.connectionLabel}.` : ""; const shapeNote = notes.length > 0 ? ` ${notes.join(" ")}` : ""; setDraftNotice( result.truncated ? `AI draft.${voiceNote}${modelNote}${shapeNote} The model hit its output limit, so the ending may be missing. Review every line before saving.` : `AI draft.${voiceNote}${modelNote}${shapeNote} Review every line, then save the document to publish it.`, ); // Frame what the draft produced, not the whole document: in a large // conversation, fitting everything shrinks the new branch to an illegible // speck and the author has to hunt for it. window.setTimeout(() => { void rf.fitView({ nodes: framed.length > 0 ? framed.map((id) => ({ id })) : undefined, padding: framed.length > 0 ? 0.35 : 0.2, duration: 400, }); }, 0); }, [nodes, attachTarget, refuseConnection, setNodes, serialize, setGeneration, rf], ); // Dragging fires a position change per mousemove; only the settled one // (dragging === false) is worth writing to the field value. The flag is // consumed by the effect below, which sees the updated nodes state. const pendingPositionSave = useRef(false); const handleNodesChange = useCallback( (changes: NodeChange[]) => { if (changes.some((c) => c.type === "position" && !c.dragging)) { pendingPositionSave.current = true; } onNodesChange(changes); }, [onNodesChange], ); // Clicking the pane or an edge clears node selection; edge selection lives // in its own state so it survives the node re-render. const clearNodeSelection = useCallback(() => { setNodes((nds) => nds.map((n) => (n.selected ? { ...n, selected: false } : n))); }, [setNodes]); useEffect(() => { if (!pendingPositionSave.current) return; pendingPositionSave.current = false; serialize(nodes); }, [nodes, serialize]); /** * 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( (type: NpcDialogueNodeType, at?: XYPosition) => { 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 = { id: crypto.randomUUID(), type, position, data: { ...DEFAULT_DATA[type] }, }; const next = [...nodes, node]; setNodes(next); serialize(next); draftIds.current.add(node.id); setEditingNodeId(node.id); setPaneMenu(null); }, [nodes, setNodes, serialize, rf], ); const handleNodeSave = useCallback( (nodeId: string, data: DialogueNodeData) => { const next = nodes.map((n) => (n.id === nodeId ? { ...n, data } : n)); setNodes(next); serialize(next); draftIds.current.delete(nodeId); setEditingNodeId(null); }, [nodes, setNodes, serialize], ); /** Deletes one or more nodes and scrubs every hop that pointed at them. */ const deleteNodes = useCallback( (ids: string[]) => { const gone = new Set(ids); const next = (nodes as DialogueNode[]) .filter((n) => !gone.has(n.id)) .map((n) => ({ ...n, data: { ...n.data, next: n.data.next && !gone.has(n.data.next.target) ? n.data.next : undefined, choices: (n.data.choices ?? []).filter((c) => !gone.has(c.target)), trueTarget: n.data.trueTarget && !gone.has(n.data.trueTarget) ? n.data.trueTarget : undefined, falseTarget: n.data.falseTarget && !gone.has(n.data.falseTarget) ? n.data.falseTarget : undefined, }, })); setNodes(next); serialize(next); setContextMenu(null); if (editingNodeId && gone.has(editingNodeId)) setEditingNodeId(null); }, [nodes, setNodes, serialize, editingNodeId], ); /** * Deletes one edge. Edges are derived, so this scrubs the hop it represents * from the source node data: a choice row, a condition branch, or the single * continuation. `sourceHandle` identifies which one (c0..cN / true / false / * undefined). */ const deleteEdge = useCallback( (edge: Edge) => { const source = (nodes as DialogueNode[]).find((n) => n.id === edge.source); if (!source) return; const next = (nodes as DialogueNode[]).map((n) => n.id === edge.source ? removeHopFromNode(n, edge.sourceHandle) : n, ); setNodes(next); serialize(next); }, [nodes, setNodes, serialize], ); const onNodeContextMenu = useCallback( (e: ReactMouseEvent, node: Node) => { e.preventDefault(); setContextMenu({ x: e.clientX, y: e.clientY, nodeId: node.id }); }, [], ); // Right-click on empty canvas: offer a "new node" menu at the cursor. 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) => { const target = e.target as HTMLElement; // Node double-clicks open the edit dialog (onNodeDoubleClick); they // must never also spawn a new node. if (target.closest?.(".react-flow__node")) return; 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 and reconnection both write into the node data (the graph's * source of truth); edges stay a derived projection. The graph rules live in * `connectHop` so they are unit-tested rather than only exercised by hand. */ /** * The one place a connection is written. Returns `changed: false` when the graph * did not move, so callers can explain a refusal instead of leaving the canvas * looking frozen. */ const commitConnection = useCallback( ( base: DialogueNode[], sourceId: string, targetId: string, sourceHandle?: string | null, carried?: DialogueNext | null, ): { nodes: DialogueNode[]; changed: boolean } => { const result = connectHop(base, { sourceId, targetId, sourceHandle, carried }); if (!result.changed) return { nodes: base, changed: false }; // A fresh choice with no button text pops the editor so it can be typed // immediately, instead of saving a conversation with a blank button. if (result.labelNodeId) setEditingNodeId(result.labelNodeId); return { nodes: result.nodes, changed: true }; }, [setEditingNodeId], ); const applyConnection = useCallback( (sourceId: string, targetId: string, sourceHandle?: string | null) => { const all = nodes as DialogueNode[]; const { nodes: next, changed } = commitConnection(all, sourceId, targetId, sourceHandle); if (!changed) { refuseConnection(); return; } setNodes(next); serialize(next); setConnectNotice(null); }, [nodes, commitConnection, refuseConnection, setNodes, serialize], ); /** * Reconnection. * * React Flow enables edge reconnection by default (`edgesReconnectable: true`, * both ends draggable), and with no `onReconnect` handler it draws the line and * then throws the drop away: the edge snaps back and nothing changes, which * reads as a broken canvas. Handling it also lets the hop travel: a choice keeps * its button text, tooltip and gate instead of becoming a blank row. */ const onReconnect = useCallback( (oldEdge: Edge, connection: Connection) => { if (!connection.source || !connection.target) return; const all = nodes as DialogueNode[]; const oldSource = all.find((n) => n.id === oldEdge.source); if (!oldSource) return; const carried = hopFromHandle(oldSource, oldEdge.sourceHandle); const handle = connection.sourceHandle ?? oldEdge.sourceHandle; if (connection.source === oldEdge.source) { const { nodes: next, changed } = commitConnection( all, connection.source, connection.target, handle, carried, ); if (!changed) { refuseConnection(); return; } setNodes(next); serialize(next); setConnectNotice(null); return; } // The tail moved, so the hop has to leave the old node as well; otherwise // the graph would keep two hops where the author now sees one line. const detached = all.map((n) => n.id === oldEdge.source ? removeHopFromNode(n, oldEdge.sourceHandle) : n, ); const { nodes: next, changed } = commitConnection( detached, connection.source, connection.target, handle, carried, ); if (!changed) { // Detaching before knowing the new tail worked would delete the hop the // author can still see. Keep the original graph and explain. refuseConnection(); return; } setNodes(next); serialize(next); setConnectNotice(null); }, [nodes, commitConnection, 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); setPaneMenu(null); setSelectedEdgeId(null); }, []); /** * Selects an edge so it can be removed with the Delete key. Edges are a * derived projection, so this only toggles selection: a second click on the * same edge clears it, and either way node selection is cleared first. */ const onEdgeClick = useCallback( (e: ReactMouseEvent, edge: Edge) => { e.stopPropagation(); setSelectedEdgeId((prev) => (prev === edge.id ? null : edge.id)); clearNodeSelection(); }, [clearNodeSelection], ); const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]); // Close both context menus on escape / pointer outside. const closeMenus = useCallback(() => { setContextMenu(null); setPaneMenu(null); }, []); useEffect(() => { if (!contextMenu && !paneMenu) return; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") closeMenus(); }; // Ignore pointerdowns inside a 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) => { const t = e.target as globalThis.Node; if (menuRef.current?.contains(t) || paneMenuRef.current?.contains(t)) return; closeMenus(); }; window.addEventListener("keydown", onKey); document.addEventListener("pointerdown", onPtr); return () => { window.removeEventListener("keydown", onKey); document.removeEventListener("pointerdown", onPtr); }; }, [contextMenu, paneMenu, closeMenus]); // Escape collapses the expanded editor, but only when nothing is layered // on top of it (the node dialog or a context menu claim the key first). useEffect(() => { if (!expanded) return; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape" && !contextMenu && !paneMenu && editingNodeId === null) setExpanded(false); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [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; } // An edge selection takes precedence over node selection. if (selectedEdgeId) { const edge = syncedEdges.find((candidate) => candidate.id === selectedEdgeId); if (edge) { e.preventDefault(); setSelectedEdgeId(null); deleteEdge(edge); } 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, selectedEdgeId, syncedEdges, deleteEdge, deleteNodes]); 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(" ")}
)} {draftNotice && (
{draftNotice}
)}
{ if (c.source && c.target) applyConnection(c.source, c.target, c.sourceHandle); }} 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) { // Released over empty canvas: nothing to explain, and saying // something on every stray drag would be noise. setConnectNotice(null); return; } if (targetId === sourceId) { setConnectNotice("A node cannot point at itself."); return; } const dropped = (nodes as DialogueNode[]).find((n) => n.id === targetId); if (dropped?.data.isStart) { setConnectNotice( "That node starts the conversation, so nothing can point at it. Connect to the step after it instead.", ); return; } // 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); }} onReconnect={onReconnect} onReconnectEnd={(event, edge) => { // A reconnect dropped on a handle is resolved by React Flow and // arrives at `onReconnect` above. Dropped on a node card, React Flow // calls this with no connection at all, and the edge snaps back: the // line looks draggable but nothing happens. Finish the obvious intent // here and point the edge at that card, keeping the hop's text. // // Which END was dragged is not reported reliably enough to act on // (a drag from the tail anchor arrived as "target"), so a card drop // always retargets: moving the tail over a card would otherwise be // ambiguous with moving the arrow. const element = document.elementFromPoint( (event as MouseEvent).clientX ?? 0, (event as MouseEvent).clientY ?? 0, ) as HTMLElement | null; if (!element) return; if (element.closest(".react-flow__handle")) return; const nodeElement = element.closest(".react-flow__node") as HTMLElement | null; const cardId = nodeElement?.getAttribute("data-id"); if (!cardId || cardId === edge.source || cardId === edge.target) return; const all = nodes as DialogueNode[]; const source = all.find((n) => n.id === edge.source); const card = all.find((n) => n.id === cardId); if (!source || !card) return; if (card.data.isStart) { setConnectNotice( "That node starts the conversation, so nothing can point at it. Connect to the step after it instead.", ); return; } const { nodes: next, changed } = commitConnection( all, edge.source, cardId, edge.sourceHandle, hopFromHandle(source, edge.sourceHandle), ); if (!changed) { refuseConnection(); return; } setNodes(next); serialize(next); setConnectNotice(null); }} isValidConnection={isValidConnection} // Single click selects (React Flow default); double-click edits. onNodeDoubleClick={(_e, node) => setEditingNodeId(node.id)} onNodeContextMenu={onNodeContextMenu} onEdgeClick={onEdgeClick} onPaneClick={onPaneClick} onPaneContextMenu={onPaneContextMenu} nodeTypes={nodeTypes} edgeTypes={edgeTypes} snapToGrid={snap} snapGrid={[SNAP_GRID, SNAP_GRID]} fitView zoomOnDoubleClick={false} colorMode="dark" proOptions={{ hideAttribution: true }} > {nodes.length === 0 && (
Double-click anywhere to add a node.
)}
{connectNotice && (
{connectNotice}
)}

Click a node to select it, double-click to edit. Click an edge to select it, then press Del (or right-click a node) to delete. Double-click the canvas for a new dialogue node; right-click it for any type. Drag a row's dot to wire that exact choice or branch, and drag either end of an existing line to move it. Use Expand to fill the screen (Esc to shrink).

{contextMenu && (
)} {paneMenu && (

New node

{(Object.keys(NODE_LABELS) as NpcDialogueNodeType[]).map((type) => ( ))}
)} n.id === editingNodeId) ?? null} allNodes={nodes as DialogueNode[]} open={editingNodeId !== null} onOpenChange={(open) => { if (open || !editingNodeId) return; const id = editingNodeId; setEditingNodeId(null); // A brand-new node abandoned in its own dialog is a cancelled // draft: remove it instead of persisting an empty card. if (draftIds.current.delete(id)) deleteNodes([id]); }} onSave={handleNodeSave} npcId={npcId} dialogueId={dialogueId} /> ({ id: e.id, source: e.source, target: e.target })) }} contactName={npcLabel} />
); } export function NpcDialogueEditor() { return ( ); } export default NpcDialogueEditor;