1
0
Fork 0
polaris-task-force/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
Z8MB1E ad63217e44 fix(npc-dialogue): make canvas wiring actually work
Three defects in the flow editor, all of which made it look like drag
and drop was simply broken:

- Reconnection was a silent no-op. React Flow enables it by default, so
  the drag drew a line and then threw the drop away with no handler: the
  edge snapped back. Reconnects now write the hop, and a drop over a node
  card (which arrives with no resolved connection) retargets, carrying
  the existing choice text, tooltip, once flag and gate instead of
  blanking the button.
- A refused drop said nothing. Dropping on the start node looked like the
  canvas had frozen; it now explains why nothing can point there.
- Handle dots were unmissable at 100% zoom and unusable zoomed out. A
  child element widens the press target, generously horizontally where
  the only neighbour is empty canvas and barely vertically because choice
  rows stack a few pixels apart when zoomed out.

Dropping a condition branch on the card filled true and false with the
same node, which made the condition pointless; it now takes the first
free branch.

Connection writing moved into `connectHop` in the lib so the rules are
unit-tested rather than exercised only by hand.
2026-11-24 13:58:32 -05:00

940 lines
35 KiB
TypeScript

"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, 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 type { RouteRect } from "@/lib/flow-edge-routing";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } 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<NpcDialogueNodeType, string> = {
dialogue: "Dialogue",
choice: "Choice",
event: "Event",
delay: "Delay",
condition: "Condition",
end: "End",
};
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
// 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<FlowData>();
// 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<NpcDialogue["generation"]>({
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<string | null>(null);
const [contextMenu, setContextMenu] = useState<ContextMenu>(null);
const [paneMenu, setPaneMenu] = useState<PaneMenu>(null);
const [expanded, setExpanded] = useState(false);
const [snap, setSnap] = useState(true);
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
const [generateOpen, setGenerateOpen] = 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<string | null>(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<string | null>(null);
// 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<string, unknown> | 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]);
// 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<string, unknown> | undefined)?.id;
return typeof raw === "number" ? raw : null;
}, [docData]);
const lastSerialized = useRef<string>("");
const menuRef = useRef<HTMLDivElement | null>(null);
const paneMenuRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLDivElement | null>(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<Set<string>>(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<Edge[]>(() => {
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]);
/**
* 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.
*/
const applyGeneratedDraft = useCallback(
(result: {
flow: FlowData;
model: string;
promptVersion: string;
promptSource: "builtin" | "global" | "dialogue";
promptRevision: number | null;
connectionLabel: string | null;
attempts: number;
truncated: boolean;
}, brief: DialogueBrief) => {
const incoming = result.flow.nodes as Node[];
setNodes(incoming);
serialize(incoming);
// 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}.` : "";
setDraftNotice(
result.truncated
? `AI draft.${voiceNote}${modelNote} The model hit its output limit, so the ending may be missing. Review every line before saving.`
: `AI draft.${voiceNote}${modelNote} Review every line, then save the document to publish it.`,
);
// Fit the new graph once React Flow has measured the nodes it was handed.
window.setTimeout(() => {
void rf.fitView({ padding: 0.2 });
}, 0);
},
[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<Node>[]) => {
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<HTMLDivElement>) => {
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.
*/
const commitConnection = useCallback(
(
base: DialogueNode[],
sourceId: string,
targetId: string,
sourceHandle?: string | null,
carried?: DialogueNext | null,
): DialogueNode[] => {
const result = connectHop(base, { sourceId, targetId, sourceHandle, carried });
if (!result.changed) return base;
// 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 result.nodes;
},
[setEditingNodeId],
);
const applyConnection = useCallback(
(sourceId: string, targetId: string, sourceHandle?: string | null) => {
const all = nodes as DialogueNode[];
const next = commitConnection(all, sourceId, targetId, sourceHandle);
if (next === all) return;
setNodes(next);
serialize(next);
setConnectNotice(null);
},
[nodes, commitConnection, 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 next = commitConnection(all, connection.source, connection.target, handle, carried);
if (next === all) 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 next = commitConnection(detached, connection.source, connection.target, handle, carried);
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 (
<div
className={`flex flex-col gap-2 w-full${
expanded ? " npc-dialogue-editor--expanded bg-zinc-950 p-3" : ""
}`}
>
<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>
<button
type="button"
onClick={() => setGenerateOpen(true)}
disabled={npcId === null}
title={
npcId === null
? "Pick a contact on this conversation before generating"
: "Draft a conversation from a brief"
}
className={`${buttonClass} inline-flex items-center gap-1 bg-fuchsia-950 border-fuchsia-700 text-fuchsia-200 hover:bg-fuchsia-900 disabled:opacity-40 disabled:cursor-not-allowed`}
>
<Sparkles size={12} />
Generate
</button>
<span className="ml-auto text-[10px] text-zinc-500">
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
</span>
<button
type="button"
title={snap ? "Nodes snap to the grid while dragging" : "Grid snapping is off"}
aria-pressed={snap}
onClick={toggleSnap}
className={`${buttonClass} inline-flex items-center gap-1 ${
snap
? "bg-cyan-950 border-cyan-700 text-cyan-200 hover:bg-cyan-900"
: "bg-zinc-800 border-zinc-600 text-zinc-400 hover:bg-zinc-700"
}`}
>
<Magnet size={12} />
Snap {snap ? "On" : "Off"}
</button>
<button
type="button"
title={expanded ? "Shrink editor (Esc)" : "Expand editor to fill the screen"}
aria-pressed={expanded}
onClick={() => setExpanded((v) => !v)}
className={`${buttonClass} inline-flex items-center gap-1 bg-zinc-800 border-zinc-600 text-zinc-300 hover:bg-zinc-700`}
>
{expanded ? <Minimize2 size={12} /> : <Maximize2 size={12} />}
{expanded ? "Shrink" : "Expand"}
</button>
</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>
)}
{draftNotice && (
<div className="flex items-start gap-2 px-2 py-1 bg-fuchsia-950/60 border border-fuchsia-900/50 text-xs text-fuchsia-200">
<Sparkles size={12} className="mt-0.5 shrink-0" />
<span className="flex-1">{draftNotice}</span>
<button
type="button"
onClick={() => setDraftNotice(null)}
className="shrink-0 text-fuchsia-300 hover:text-fuchsia-100 cursor-pointer"
aria-label="Dismiss draft notice"
>
Dismiss
</button>
</div>
)}
<div
ref={canvasRef}
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"
}`}
onDoubleClick={onCanvasDoubleClick}
>
<ReactFlow
nodes={nodes}
edges={syncedEdges}
onNodesChange={handleNodesChange}
onConnect={(c: Connection) => {
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 next = commitConnection(
all,
edge.source,
cardId,
edge.sourceHandle,
hopFromHandle(source, edge.sourceHandle),
);
if (next === all) 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 }}
>
<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">
Double-click anywhere to add a node.
</div>
)}
</ReactFlow>
</div>
{connectNotice && (
<div className="flex items-start gap-2 rounded-md border border-amber-900/60 bg-amber-950/50 px-2 py-1 text-xs text-amber-200">
<span className="flex-1">{connectNotice}</span>
<button
type="button"
onClick={() => setConnectNotice(null)}
className="shrink-0 cursor-pointer text-amber-300 hover:text-amber-100"
aria-label="Dismiss connection notice"
>
Dismiss
</button>
</div>
)}
<p className="text-[10px] text-zinc-500">
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&apos;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).
</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={() => 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"
>
Delete node
</button>
</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
node={(nodes as DialogueNode[]).find((n) => 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}
/>
<GenerateDraftDialog
open={generateOpen}
onOpenChange={setGenerateOpen}
npcId={npcId}
dialogueId={dialogueId}
nodeCount={nodes.length}
onGenerated={applyGeneratedDraft}
/>
</div>
);
}
export function NpcDialogueEditor() {
return (
<ReactFlowProvider>
<FlowEditor />
</ReactFlowProvider>
);
}
export default NpcDialogueEditor;