/** * Splicing a generated branch into a conversation that already exists. * * Pure (no Payload, no React) so every rule here is unit-tested. The editor calls * this and writes the result through its normal `serialize` path, which means the * inserted branch is unsaved field state like any hand-drawn node: nothing is * persisted until the document's own Save. * * Three things have to be right or the canvas breaks in a confusing way: * * 1. **Ids must be remapped.** The model writes `n1`, `n2`, ... and a document * already has nodes; a collision would silently repoint existing hops. Every * id is replaced and every hop that pointed at it is rewritten. * 2. **The branch must not claim the start.** A generated `isStart` would give the * conversation two starts, and the runtime picks whichever it finds first. * 3. **It has to land somewhere visible.** Generated positions start near 0,0, so * an offset is applied to put the branch beside the node it continues from, * and pushed clear if that space is already occupied. */ import type { DialogueNode, DialogueNext } from "./dialogue"; import { connectHop, hopFromHandle, isTerminalNode } from "./dialogue"; /** Where a branch continues from: one output of one existing node. */ export interface FragmentAttachment { sourceId: string; /** `c0`..`cN` for a choice row, `true`/`false` for a condition branch. */ sourceHandle?: string | null; } export interface InsertFragmentOptions { /** Wire the branch in from this node's output. Omitted means insert unwired. */ attachment?: FragmentAttachment | null; /** * Point the branch's last open node back at the node it attached from, so a * side conversation returns where it came from. */ returnToCaller?: boolean; /** Injectable for deterministic tests. Must return unique ids. */ newId?: () => string; } export interface InsertFragmentResult { nodes: DialogueNode[]; /** The inserted node a player enters the branch through. */ entryId: string; /** False when the attachment was refused (the branch is still inserted). */ wired: boolean; /** The inserted node now pointing back at the caller, when one was found. */ returnedFrom: string | null; /** * Where that hop goes: back to the caller (a menu of choices re-presented), or * on to the step the caller already led to, which the branch has replaced. */ returnKind: "caller" | "successor" | null; /** Author-facing notes: a refused attachment, or a return that never applied. */ errors: string[]; /** * Set when attaching under a choice node created a button row whose text was * derived from the branch's first line. Worth flagging in the UI: the author * should read that button, because it is the one string the model did not write. */ derivedLabel: string | null; } /** Horizontal gap left between the attachment node and the inserted branch. */ export const FRAGMENT_COLUMN_GAP = 420; /** Vertical gap used when the ideal spot is occupied. */ export const FRAGMENT_STACK_GAP = 120; /** How many times the branch is nudged down before accepting an overlap. */ const MAX_PLACEMENT_TRIES = 12; interface Box { minX: number; minY: number; maxX: number; maxY: number; } /** * A rough box for a node. Real card widths come from React Flow's measurements, * which do not exist for freshly generated nodes, so a constant is used: it only * has to be good enough to avoid dropping a branch on top of a card. */ const NODE_WIDTH = 320; const NODE_HEIGHT = 160; function boxOf(nodes: DialogueNode[]): Box | null { if (nodes.length === 0) return null; const xs = nodes.map((n) => n.position.x); const ys = nodes.map((n) => n.position.y); return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs) + NODE_WIDTH, maxY: Math.max(...ys) + NODE_HEIGHT, }; } function overlaps(a: Box, b: Box): boolean { return a.minX < b.maxX && a.maxX > b.minX && a.minY < b.maxY && a.maxY > b.minY; } /** * Whether a candidate box lands on any individual card. * * Deliberately per-node rather than against the union of everything: a graph is * mostly empty space inside its own bounding box, so testing against the union * makes every position "occupied" in a large conversation and the branch gets * marched hundreds of pixels down the canvas, far from where it belongs. */ function collidesWithAny(candidate: Box, existing: DialogueNode[]): boolean { return existing.some((node) => { const box = boxOf([node]); return box ? overlaps(candidate, box) : false; }); } /** Rewrites every hop on one node through the id map, dropping dead targets. */ function remapNode(node: DialogueNode, ids: Map): DialogueNode { const mapHop = (hop: DialogueNext | undefined): DialogueNext | undefined => { if (!hop) return hop; const target = ids.get(hop.target); // A hop to an id the draft never wrote is already rejected by the validator; // dropping it here keeps a partly bad draft from poisoning the document. return target ? { ...hop, target } : undefined; }; const { isStart: _dropped, ...data } = node.data; return { ...node, id: ids.get(node.id) ?? node.id, position: { ...node.position }, data: { ...data, next: mapHop(data.next), choices: data.choices ?.map((choice) => { const mapped = mapHop(choice); return mapped ? { ...choice, ...mapped } : null; }) .filter((choice): choice is DialogueNext => choice !== null), trueTarget: data.trueTarget ? ids.get(data.trueTarget) : undefined, falseTarget: data.falseTarget ? ids.get(data.falseTarget) : undefined, } as DialogueNode["data"], }; } /** * Where a returned branch continues. * * Only a choice caller has somewhere sensible to *return to*: its other buttons * are still there, so coming back re-presents the menu. Rejoining any other caller * would loop, because attaching replaced its one outgoing hop with this branch. * For those the branch continues to the successor that hop used to point at, which * is what keeps the rest of the conversation reachable. * * A condition caller gets nothing: re-entering it re-evaluates the same flags and * takes the same branch again, forever. */ export function returnTargetOf( source: DialogueNode, sourceHandle?: string | null, ): { target: string; kind: "caller" | "successor" } | null { // A hop into the start node is refused everywhere else (`connectHop`, the // canvas drop handler), so a start menu is the one caller that cannot take a // return. Its open end stays free instead of breaking that rule silently. if (source.type === "choice") { return source.data.isStart ? null : { target: source.id, kind: "caller" }; } if (source.type === "condition") return null; const successor = hopFromHandle(source, sourceHandle)?.target; return successor ? { target: successor, kind: "successor" } : null; } /** * The inserted node a return hop should leave from: the last open node in reading * order. Skipped: * * - `end`, because a closing line that continues is a contradiction; * - `choice` and `condition`, because their exits live in `choices`/`*Target` and * writing `next` on them is a hop no walker reads. */ function findReturnNode(nodes: DialogueNode[]): DialogueNode | null { const open = nodes.filter( (node) => isTerminalNode(node) && (node.type === "dialogue" || node.type === "event" || node.type === "delay"), ); if (open.length === 0) return null; return open.reduce((best, node) => node.position.x > best.position.x || (node.position.x === best.position.x && node.position.y > best.position.y) ? node : best, ); } /** * Inserts a generated branch and optionally wires it in. * * Never throws and never mutates its inputs: a failed attachment still returns the * inserted branch plus an error the editor can show, because throwing away a * draft the model spent a minute producing is the worst outcome for the author. */ export function insertGeneratedFragment( existing: DialogueNode[], fragment: DialogueNode[], options: InsertFragmentOptions = {}, ): InsertFragmentResult { const newId = options.newId ?? (() => globalThis.crypto.randomUUID()); const errors: string[] = []; const ids = new Map(); for (const node of fragment) { if (!ids.has(node.id)) ids.set(node.id, newId()); } const remapped = fragment.map((node) => remapNode(node, ids)); const entryId = remapped[0]?.id ?? ""; // Place the branch beside the node it continues from, else beside everything. const attachmentNode = options.attachment ? existing.find((node) => node.id === options.attachment?.sourceId) : undefined; const existingBox = boxOf(existing); const fragmentBox = boxOf(remapped); const anchorX = attachmentNode ? attachmentNode.position.x + FRAGMENT_COLUMN_GAP : (existingBox?.maxX ?? 0) + FRAGMENT_COLUMN_GAP; const anchorY = attachmentNode ? attachmentNode.position.y : (existingBox?.minY ?? 0); const dx = fragmentBox ? anchorX - fragmentBox.minX : 0; const dy = fragmentBox ? anchorY - fragmentBox.minY : 0; const placed = remapped.map((node) => ({ ...node, position: { x: node.position.x + dx, y: node.position.y + dy }, })); // Nudge down until the branch is not sitting on top of an existing card. let offsetY = 0; for (let attempt = 0; attempt < MAX_PLACEMENT_TRIES; attempt += 1) { const box = boxOf(placed); if (!box) break; const shifted = { ...box, minY: box.minY + offsetY, maxY: box.maxY + offsetY }; if (!collidesWithAny(shifted, existing)) break; offsetY += FRAGMENT_STACK_GAP; } let nodes: DialogueNode[] = [ ...existing, ...placed.map((node) => ({ ...node, position: { x: node.position.x, y: node.position.y + offsetY }, })), ]; // Captured before wiring: attaching to a node overwrites its one following hop, // so this is the only chance to know where the conversation went next. const returnTarget = options.returnToCaller && attachmentNode ? returnTargetOf(attachmentNode, options.attachment?.sourceHandle ?? null) : null; let wired = false; let derivedLabel: string | null = null; if (options.attachment && entryId) { const result = connectHop(nodes, { sourceId: options.attachment.sourceId, targetId: entryId, sourceHandle: options.attachment.sourceHandle ?? null, }); if (result.changed) { nodes = result.nodes; wired = true; // Attaching under a choice node creates a button row, and a blank one fails // validation. The branch's first line is the only text available, so it // becomes the button and the author edits it. if (result.labelNodeId) { const entry = nodes.find((node) => node.id === entryId); const label = firstWords(entry?.data.body ?? entry?.data.leadIn ?? ""); if (label) { nodes = nodes.map((node) => { if (node.id !== result.labelNodeId) return node; const choices = [...(node.data.choices ?? [])]; const blank = choices.findIndex( (choice) => choice.target === entryId && !choice.label?.trim(), ); if (blank < 0) return node; choices[blank] = { ...choices[blank], label }; return { ...node, data: { ...node.data, choices } }; }); derivedLabel = label; } } } else { errors.push( "The branch was inserted unwired: that node cannot take another connection (an end node has no way out, and the start node cannot be pointed at).", ); } } let returnedFrom: string | null = null; let returnKind: "caller" | "successor" | null = null; if (options.returnToCaller && options.attachment) { if (!returnTarget) { errors.push( attachmentNode?.type === "condition" ? "This attaches under a condition, which cannot be re-entered without taking the same branch again, so the branch's open end stays free." : "The step it attaches to had nothing after it, so there is nowhere to return to and the branch's open end stays free.", ); } else { const insertedIds = new Set(placed.map((node) => node.id)); const returnNode = findReturnNode(nodes.filter((node) => insertedIds.has(node.id))); if (returnNode) { nodes = nodes.map((node) => node.id === returnNode.id ? { ...node, data: { ...node.data, next: { ...(node.data.next ?? {}), target: returnTarget.target }, }, } : node, ); returnedFrom = returnNode.id; returnKind = returnTarget.kind; } else { errors.push( "No branch was left open to continue from, so the rest of the conversation is not reachable from it.", ); } } } return { nodes, entryId, wired, returnedFrom, returnKind, errors, derivedLabel }; } /** First few words of a line, for a choice button derived from dialogue. */ function firstWords(text: string, count = 7): string { const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean); if (words.length === 0) return ""; const head = words.slice(0, count).join(" "); return words.length > count ? `${head}...` : head; } /** What attaching a branch under one node would do, for the dialog's copy. */ export function describeAttachTarget(node: DialogueNode): { label: string; output: string; canAttach: boolean; /** Where a returned branch would continue, or null when it cannot return. */ returnsTo: "caller" | "successor" | null; } { const spoken = (node.data.body ?? node.data.leadIn ?? node.data.closing ?? "") .replace(/\s+/g, " ") .trim(); const head = spoken.length > 48 ? `${spoken.slice(0, 48)}...` : spoken; const label = head ? `${node.type}: "${head}"` : `${node.type} node`; if (node.type === "end") { return { label, output: "nothing, this node ends the conversation", canAttach: false, returnsTo: null, }; } if (node.type === "choice") { return { label, output: "a new choice button", canAttach: true, returnsTo: returnTargetOf(node, null)?.kind ?? null, }; } if (node.type === "condition") { // A branch cannot rejoin a condition: re-entering re-evaluates the same flags // and takes the same branch again. const freeTrue = !node.data.trueTarget; const freeFalse = !node.data.falseTarget; if (!freeTrue && !freeFalse) { return { label, output: "nothing, both branches are taken", canAttach: false, returnsTo: null }; } return { label, output: freeTrue ? "the true branch" : "the false branch", canAttach: true, returnsTo: null, }; } return { label, output: "its next step", canAttach: true, returnsTo: returnTargetOf(node, null)?.kind ?? null, }; }