From ad63217e446133b2a7d258eb2a9823b38fc30e94 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 13:58:32 -0500 Subject: [PATCH] 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. --- .../admin/npc-dialogue/NpcDialogueEditor.tsx | 214 +++++++++++++----- .../admin/npc-dialogue/NpcDialogueNode.tsx | 33 ++- src/lib/npc-dialogue/AGENTS.md | 32 +++ src/lib/npc-dialogue/dialogue.ts | 118 ++++++++++ tests/int/npc-dialogue-connect.int.spec.ts | 168 ++++++++++++++ 5 files changed, 502 insertions(+), 63 deletions(-) create mode 100644 tests/int/npc-dialogue-connect.int.spec.ts diff --git a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx index d0ee7811..319155ad 100644 --- a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx +++ b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx @@ -29,12 +29,19 @@ import type { NpcDialogue } from "@/payload-types"; import type { DialogueEdge, + DialogueNext, DialogueNode, DialogueNodeData, FlowData, NpcDialogueNodeType, } from "@/lib/npc-dialogue/dialogue"; -import { deriveEdges, removeHopFromNode, validateGraph } 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"; @@ -109,6 +116,10 @@ function FlowEditor() { // 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 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. @@ -408,67 +419,79 @@ function FlowEditor() { ); /** - * 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). + * 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) => { - 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; - let needsChoiceLabel = false; - const next = all.map((n) => { - if (n.id !== sourceId) return n; - 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 { - ...n, - data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] }, - }; - } - if (n.type === "condition") { - 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; - 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 } } }; - }); + const next = commitConnection(all, sourceId, targetId, sourceHandle); + if (next === all) return; setNodes(next); serialize(next); - // A fresh or still-unlabeled choice pops the editor so its button text - // can be typed immediately (validateGraph flags empty labels). - if (source.type === "choice" && needsChoiceLabel) setEditingNodeId(sourceId); + setConnectNotice(null); }, - [nodes, setNodes, serialize], + [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( @@ -715,11 +738,72 @@ function FlowEditor() { 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; + 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)} @@ -745,11 +829,25 @@ function FlowEditor() { + {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. Use Expand to fill - the screen (Esc to shrink). + 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 && ( diff --git a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx index 92a51333..0ff6baab 100644 --- a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx +++ b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx @@ -18,6 +18,23 @@ import { DIALOGUE_NODES } from "./types"; const position: Position = Position.Right; const inputPosition: Position = Position.Left; +/** + * A 6-12px dot (it shrinks with zoom) is a small target, and missing it by a few + * pixels drags the node card instead of starting a connection, which reads as "the + * dot does not work". + * + * This child element widens the press target without making the dot bigger. A + * child works where a `::before` does not: hit-testing over a pseudo-element box + * was not reliable here, and React Flow reads `event.currentTarget` (the handle), + * so a bubbled press from this span starts the connection normally. + * + * The extra area is generous horizontally, where the only neighbour is empty + * canvas, and only slightly taller than the dot, because choice rows stack a few + * pixels apart when the graph is zoomed out: an over-tall target would start the + * drag for the row above or below the one the author aimed at. + */ +const HIT_AREA = "pointer-events-auto absolute inset-x-[-8px] inset-y-[-3px] block rounded-full"; + /** Single reusable canvas node for every dialogue node type. */ export function NpcDialogueNode({ data, type, selected }: NodeProps) { const d = data as DialogueNodeData; @@ -109,7 +126,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) { position={position} className="!size-3 !bg-amber-400/80" style={{ right: -16 }} - /> + > + + ))} {(d.choices?.length ?? 0) === 0 && ( @@ -180,7 +199,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) { id="true" type="source" position={position} - className="!size-3 !bg-emerald-400/80" + className={`!size-3 !bg-emerald-400/80 ${HIT_AREA}`} style={{ top: "auto", bottom: 26 }} />
@@ -191,7 +210,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) { id="false" type="source" position={position} - className="!size-3 !bg-rose-400/80" + className={`!size-3 !bg-rose-400/80 ${HIT_AREA}`} style={{ bottom: 4 }} />
@@ -211,10 +230,14 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) { {genericSource && ( - + + + )} {!d.isStart && ( - + + + )} ); diff --git a/src/lib/npc-dialogue/AGENTS.md b/src/lib/npc-dialogue/AGENTS.md index b7390431..7164144a 100644 --- a/src/lib/npc-dialogue/AGENTS.md +++ b/src/lib/npc-dialogue/AGENTS.md @@ -127,3 +127,35 @@ both rules. `tests/int/npc-dialogue-*.int.spec.ts`: interpolate, attachments, condition groups, flag targets, remove-hop, reorder, and generation. The generation spec injects the model call, so it runs without the model host. + +### Canvas wiring: nodes are the source of truth + +Edges in the canvas are a **derived projection** of node data (`deriveEdges`), so +every wiring edit has to write the hop, never the edge. Both drag-a-new-line and +drag-the-end-of-an-existing-line go through `connectHop` in `dialogue.ts`, which is +pure and unit-tested in `tests/int/npc-dialogue-connect.int.spec.ts`; the editor +only persists the result. + +Rules that came out of real bugs: + +- **A refused connection must explain itself.** React Flow cannot say why a drop + was rejected, so a refusal looks like a dead canvas. The editor shows an amber + notice for the two cases an author actually hits: dropping on the start node + ("nothing can point at it") and a self-link. +- **Reconnection needs `onReconnect`.** React Flow enables edge reconnection by + default, draws the line, and then discards the drop with no handler: the edge + snaps back and nothing changes. Handle drops arrive at `onReconnect`; a drop + over a node card arrives at `onReconnectEnd` with no connection, so that handler + retargets. Which END was dragged is not reported reliably (`handleType` said + "target" for a drag started on the tail anchor), so a card drop always + retargets rather than guessing. +- **Carry the hop.** A reconnect passes the original hop as `carried`, so a choice + keeps its button text, tooltip, `once` flag and gate. Rebuilding it from a + target id silently blanks the button. +- **Dropping on a condition card fills its first *free* branch.** Filling both at + once wired true and false to the same node, which made the condition pointless. +- **Handle hit areas are horizontal-first.** Dots shrink with zoom; a real child + element widens the target (a `::before` did not hit-test reliably here) but stays + short vertically, because choice rows stack a few pixels apart when zoomed out + and an over-tall target starts the drag for the neighbouring row. + diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts index 80f772fd..908b6658 100644 --- a/src/lib/npc-dialogue/dialogue.ts +++ b/src/lib/npc-dialogue/dialogue.ts @@ -319,6 +319,124 @@ export interface GraphValidation { errors: string[]; } +/** + * The hop an edge leaves a node through, keyed by the handle the edge started + * from. Edges leaving single-continuation nodes carry no handle id, so an absent + * handle maps to the node's only hop rather than to nothing. + * + * Used when an edge is reconnected: the hop has to travel with the line, or a + * choice would come back as a blank button. + */ +export function hopFromHandle( + node: DialogueNode, + sourceHandle?: string | null, +): DialogueNext | null { + const hops = outgoingHops(node); + if (hops.length === 0) return null; + const index = hops.findIndex( + (_hop, i) => handleIdForHop(node, i) === (sourceHandle ?? undefined), + ); + if (index >= 0) return hops[index] ?? null; + return sourceHandle ? null : (hops[0] ?? null); +} + +export interface ConnectionResult { + /** The new node list, or the input list unchanged when the link is refused. */ + nodes: DialogueNode[]; + /** False when nothing was written (a refused or no-op connection). */ + changed: boolean; + /** + * Set when the connection created or left an unlabelled choice, so the editor + * can open that node immediately (validateGraph flags empty labels). + */ + labelNodeId: string | null; +} + +/** + * Writes one connection into the node data, which is the graph's source of truth. + * + * `sourceHandle` names the output that was dragged: `c0`..`cN` for a choice row, + * `true`/`false` for a condition branch. Without one, the fallbacks are what a + * drop onto the node card should mean: a choice gains an option, a condition + * takes its first free branch. + * + * `carried` is a hop lifted from an existing edge (a reconnect). Its label, + * tooltip, `once` flag and gate are preserved, so moving a wired choice keeps what + * the author wrote. + * + * Refusals are silent by design here: the canvas explains them. Pure, so the + * editor wrapper only has to persist the result. + */ +export function connectHop( + nodes: DialogueNode[], + input: { + sourceId: string; + targetId: string; + sourceHandle?: string | null; + carried?: DialogueNext | null; + }, +): ConnectionResult { + const { sourceId, targetId, sourceHandle, carried } = input; + const unchanged: ConnectionResult = { nodes, changed: false, labelNodeId: null }; + + if (sourceId === targetId) return unchanged; + const source = nodes.find((n) => n.id === sourceId); + const target = nodes.find((n) => n.id === targetId); + if (!source || !target) return unchanged; + // End nodes have no way out, and the start node has no way in. + if (source.type === "end" || target.data.isStart) return unchanged; + + let labelNodeId: string | null = null; + + const next = nodes.map((node) => { + if (node.id !== sourceId) return node; + if (node.type === "choice") { + const match = sourceHandle?.match(/^c(\d+)$/); + if (match) { + const index = Number(match[1]); + const choices = [...(node.data.choices ?? [])]; + if (!choices[index]) return node; + choices[index] = { ...choices[index], ...(carried ?? {}), target: targetId }; + if (!choices[index].label?.trim()) labelNodeId = sourceId; + return { ...node, data: { ...node.data, choices } }; + } + // Generic handle (no choices yet): the drag creates the first one. + if (!carried?.label?.trim()) labelNodeId = sourceId; + return { + ...node, + data: { + ...node.data, + choices: [ + ...(node.data.choices ?? []), + { ...(carried ?? {}), label: carried?.label ?? "", target: targetId }, + ], + }, + }; + } + if (node.type === "condition") { + if (sourceHandle === "true") { + return { ...node, data: { ...node.data, trueTarget: targetId } }; + } + if (sourceHandle === "false") { + return { ...node, data: { ...node.data, falseTarget: targetId } }; + } + // Dropped on the card: the first free branch takes it. Filling both at + // once (the pre-`connectHop` behaviour) wired an if/else to the same node, + // which made the condition meaningless. + if (!node.data.trueTarget) { + return { ...node, data: { ...node.data, trueTarget: targetId } }; + } + if (!node.data.falseTarget) { + return { ...node, data: { ...node.data, falseTarget: targetId } }; + } + return node; + } + return { ...node, data: { ...node.data, next: { ...(carried ?? {}), target: targetId } } }; + }); + + return { nodes: next, changed: true, labelNodeId }; +} + /** One-line human summary of a condition for editor previews. */ export function conditionSummary(condition: DialogueCondition): string { const leaf = (c: DialogueFlagCondition): string => diff --git a/tests/int/npc-dialogue-connect.int.spec.ts b/tests/int/npc-dialogue-connect.int.spec.ts new file mode 100644 index 00000000..40188ca0 --- /dev/null +++ b/tests/int/npc-dialogue-connect.int.spec.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from "vitest"; + +import type { DialogueNode } from "@/lib/npc-dialogue/dialogue"; +import { connectHop, hopFromHandle } from "@/lib/npc-dialogue/dialogue"; + +/** + * Connection writing is the canvas's core edit: a wrong hop either loses what the + * author typed (a choice button, its gate) or silently rewires the conversation. + * These are the rules the drag handlers rely on, tested without a browser. + */ +const node = ( + id: string, + type: DialogueNode["type"], + data: DialogueNode["data"] = {}, +): DialogueNode => ({ id, type, position: { x: 0, y: 0 }, data }); + +const choice = node("choice", "choice", { + choices: [ + { label: "Ask about the radio", target: "radio", tooltip: "**Radio** status", once: true }, + { label: "Leave", target: "end" }, + ], +}); +const dialogue = node("d", "dialogue", { body: "Line", next: { target: "choice" } }); +const other = node("other", "dialogue", { body: "Elsewhere" }); +const end = node("end", "end", { closing: "Done" }); +const start = node("start", "dialogue", { body: "Opening", isStart: true }); + +const base = [start, dialogue, choice, other, end]; +const find = (nodes: DialogueNode[], id: string) => nodes.find((n) => n.id === id)!; + +describe("connectHop", () => { + it("routes one choice row without touching its siblings", () => { + const result = connectHop(base, { sourceId: "choice", targetId: "other", sourceHandle: "c1" }); + + expect(result.changed).toBe(true); + const choices = find(result.nodes, "choice").data.choices ?? []; + expect(choices[0].target).toBe("radio"); + expect(choices[1].target).toBe("other"); + // A labelled row needs no editor popup. + expect(result.labelNodeId).toBeNull(); + }); + + it("keeps a choice's label, tooltip and once flag when a reconnect carries the hop", () => { + const carried = hopFromHandle(choice, "c0"); + expect(carried?.label).toBe("Ask about the radio"); + + const result = connectHop(base, { + sourceId: "choice", + targetId: "other", + sourceHandle: "c0", + carried, + }); + + const row = (find(result.nodes, "choice").data.choices ?? [])[0]; + expect(row.target).toBe("other"); + expect(row.label).toBe("Ask about the radio"); + expect(row.tooltip).toBe("**Radio** status"); + expect(row.once).toBe(true); + }); + + it("creates the first choice from a generic handle and asks for its label", () => { + const empty = node("fresh", "choice", { choices: [] }); + const result = connectHop([start, empty, other], { + sourceId: "fresh", + targetId: "other", + sourceHandle: null, + }); + + const choices = find(result.nodes, "fresh").data.choices ?? []; + expect(choices).toHaveLength(1); + expect(choices[0].target).toBe("other"); + expect(result.labelNodeId).toBe("fresh"); + }); + + it("does not ask for a label when a carried choice already has one", () => { + const empty = node("fresh", "choice", { choices: [] }); + const carried = { label: "Ask about the radio", target: "choice", tooltip: "T" }; + const result = connectHop([start, empty, other], { + sourceId: "fresh", + targetId: "other", + sourceHandle: null, + carried, + }); + + expect(result.labelNodeId).toBeNull(); + expect((find(result.nodes, "fresh").data.choices ?? [])[0].label).toBe("Ask about the radio"); + }); + + it("routes a single continuation", () => { + const result = connectHop(base, { sourceId: "d", targetId: "other" }); + expect(find(result.nodes, "d").data.next?.target).toBe("other"); + }); + + it("fills a condition's named branch, and the first free branch when the card is hit", () => { + const cond = node("cond", "condition", { + condition: { kind: "flag", key: "ready", op: "is_true" }, + }); + + const trueBranch = connectHop([start, cond, other], { + sourceId: "cond", + targetId: "other", + sourceHandle: "true", + }); + expect(find(trueBranch.nodes, "cond").data.trueTarget).toBe("other"); + expect(find(trueBranch.nodes, "cond").data.falseTarget).toBeUndefined(); + + const byCard = connectHop([start, cond, other, dialogue], { + sourceId: "cond", + targetId: "other", + }); + expect(find(byCard.nodes, "cond").data.trueTarget).toBe("other"); + expect(find(byCard.nodes, "cond").data.falseTarget).toBeUndefined(); + + const second = connectHop(byCard.nodes, { sourceId: "cond", targetId: "d" }); + expect(find(second.nodes, "cond").data.falseTarget).toBe("d"); + + // Both branches taken: a third drop changes nothing. + const full = connectHop(second.nodes, { sourceId: "cond", targetId: "choice" }); + expect(full.changed).toBe(false); + }); + + it("refuses to point at the conversation start", () => { + const result = connectHop(base, { sourceId: "d", targetId: "start" }); + expect(result.changed).toBe(false); + expect(result.nodes).toBe(base); + }); + + it("refuses a self-link and an unknown node", () => { + expect(connectHop(base, { sourceId: "d", targetId: "d" }).changed).toBe(false); + expect(connectHop(base, { sourceId: "d", targetId: "ghost" }).changed).toBe(false); + }); + + it("refuses to draw a way out of an end node", () => { + expect(connectHop(base, { sourceId: "end", targetId: "other" }).changed).toBe(false); + }); + + it("never mutates the input nodes", () => { + const snapshot = JSON.stringify(base); + connectHop(base, { sourceId: "choice", targetId: "other", sourceHandle: "c0" }); + connectHop(base, { sourceId: "d", targetId: "other" }); + expect(JSON.stringify(base)).toBe(snapshot); + }); +}); + +describe("hopFromHandle", () => { + it("maps a choice handle to its row", () => { + expect(hopFromHandle(choice, "c1")?.label).toBe("Leave"); + }); + + it("maps an absent handle to a single continuation", () => { + expect(hopFromHandle(dialogue, undefined)?.target).toBe("choice"); + }); + + it("maps condition handles to their branches", () => { + const cond = node("cond", "condition", { + condition: { kind: "flag", key: "ready", op: "is_true" }, + trueTarget: "other", + falseTarget: "end", + }); + expect(hopFromHandle(cond, "true")?.target).toBe("other"); + expect(hopFromHandle(cond, "false")?.target).toBe("end"); + }); + + it("returns null for a handle that does not exist, and for a node with no hops", () => { + expect(hopFromHandle(choice, "c9")).toBeNull(); + expect(hopFromHandle(end, undefined)).toBeNull(); + }); +});