1
0
Fork 0

feat(npc-dialogue): bigger flow handles + delete edges via Delete

- Enlarge flow-editor wire handles from size-2 (8px) to size-3 (12px) so
  they are easier to click and grab.
- Select an edge by clicking it, then remove it with the Delete key.
  Selection is tracked in state and the highlight renders through BaseEdge
  stroke props so the chosen line stands out.
- Edges are a derived projection, so deletion scrubs the hop from the
  source node data via a new pure removeHopFromNode() helper in dialogue.ts
  (choice row, condition branch, or single continuation).
- Add tests/int/npc-dialogue-remove-hop.int.spec.ts (4 tests).
This commit is contained in:
Jason Fraley 2026-10-07 14:25:14 -04:00
parent 538b7d4c4c
commit a96eddf32c
5 changed files with 147 additions and 19 deletions

View file

@ -33,7 +33,7 @@ import type {
FlowData,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";
import { RoutedFlowEdge } from "./RoutedFlowEdge";
@ -96,6 +96,7 @@ function FlowEditor() {
const [paneMenu, setPaneMenu] = useState<PaneMenu>(null);
const [expanded, setExpanded] = useState(false);
const [snap, setSnap] = useState(true);
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
const lastSerialized = useRef<string>("");
const menuRef = useRef<HTMLDivElement | null>(null);
@ -133,13 +134,15 @@ function FlowEditor() {
// unrelated cards instead of slicing through them.
const syncedEdges = useMemo<Edge[]>(
() =>
deriveEdges(nodes as DialogueNode[]).map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
})),
[nodes],
deriveEdges(nodes as DialogueNode[])
.map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
selected: edge.id === selectedEdgeId,
})),
[nodes, selectedEdgeId],
);
const serialize = useCallback((nds: Node[]) => {
@ -172,6 +175,12 @@ function FlowEditor() {
[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;
@ -250,6 +259,25 @@ function FlowEditor() {
[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();
@ -359,8 +387,23 @@ function FlowEditor() {
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.
@ -416,6 +459,16 @@ function FlowEditor() {
) {
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();
@ -423,7 +476,7 @@ function FlowEditor() {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [nodes, editingNodeId, contextMenu, paneMenu, deleteNodes]);
}, [nodes, editingNodeId, contextMenu, paneMenu, selectedEdgeId, syncedEdges, deleteEdge, deleteNodes]);
const buttonClass =
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
@ -545,6 +598,7 @@ function FlowEditor() {
// 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}
@ -566,10 +620,10 @@ function FlowEditor() {
</div>
<p className="text-[10px] text-zinc-500">
Click a node to select it, double-click to edit. Select and press Del (or right-click) 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. Use Expand to fill the screen (Esc to
shrink).
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. Use Expand to fill
the screen (Esc to shrink).
</p>
{contextMenu && (

View file

@ -106,7 +106,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id={`c${index}`}
type="source"
position={position}
className="!size-2 !bg-amber-400/80"
className="!size-3 !bg-amber-400/80"
style={{ right: -16 }}
/>
</li>
@ -183,7 +183,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id="true"
type="source"
position={position}
className="!size-2 !bg-emerald-400/80"
className="!size-3 !bg-emerald-400/80"
style={{ top: "auto", bottom: 26 }}
/>
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-rose-300/80">
@ -194,7 +194,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id="false"
type="source"
position={position}
className="!size-2 !bg-rose-400/80"
className="!size-3 !bg-rose-400/80"
style={{ bottom: 4 }}
/>
</div>
@ -214,10 +214,10 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
</div>
{genericSource && (
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
<Handle type="source" position={position} className="!size-3 !bg-white/60" />
)}
{!d.isStart && (
<Handle type="target" position={inputPosition} className="!size-2 !bg-white/60" />
<Handle type="target" position={inputPosition} className="!size-3 !bg-white/60" />
)}
</div>
);

View file

@ -36,6 +36,7 @@ export function RoutedFlowEdge({
targetPosition,
markerEnd,
label,
selected,
}: EdgeProps) {
const nodeLookup = useStore((s) => s.nodeLookup);
@ -71,7 +72,12 @@ export function RoutedFlowEdge({
return (
<>
<BaseEdge id={id} path={path} markerEnd={markerEnd} />
<BaseEdge
id={id}
path={path}
markerEnd={markerEnd}
{...(selected ? { stroke: "#67e8f9", strokeWidth: 5, strokeDasharray: "8 5" } : {})}
/>
{labelText ? (
<EdgeLabelRenderer>
<div

View file

@ -239,6 +239,29 @@ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
return edges;
}
/**
* Removes the hop an edge represents from a node's data. Edges are a derived
* projection, so deleting one scrubs the source hop: a choice row (`c0`..`cN`),
* a condition branch (`true`/`false`), or the single continuation. Returns a
* new node and never mutates the input.
*/
export function removeHopFromNode(node: DialogueNode, sourceHandle?: string | null): DialogueNode {
if (node.type === "choice") {
const m = sourceHandle?.match(/^c(\d+)$/);
if (!m) return node;
const idx = Number(m[1]);
const choices = [...(node.data.choices ?? [])];
choices.splice(idx, 1);
return { ...node, data: { ...node.data, choices } };
}
if (node.type === "condition") {
if (sourceHandle === "true") return { ...node, data: { ...node.data, trueTarget: undefined } };
if (sourceHandle === "false") return { ...node, data: { ...node.data, falseTarget: undefined } };
return node;
}
return { ...node, data: { ...node.data, next: undefined } };
}
export interface GraphValidation {
valid: boolean;
errors: string[];

View file

@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { removeHopFromNode } from "@/lib/npc-dialogue/dialogue";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
const node = (type: DialogueNode["type"], data: DialogueNode["data"]): DialogueNode => ({
id: `${type}-1`,
type,
position: { x: 0, y: 0 },
data,
});
describe("removeHopFromNode (edge deletion scrubs the derived hop)", () => {
it("removes a single choice row by its handle", () => {
const n = node("choice", { choices: [{ label: "a", target: "x" }, { label: "b", target: "y" }] });
const next = removeHopFromNode(n, "c0");
expect(next.data.choices).toEqual([{ label: "b", target: "y" }]);
// the other row is untouched
expect(n.data.choices).toEqual([
{ label: "a", target: "x" },
{ label: "b", target: "y" },
]);
});
it("removes a condition branch by name", () => {
const yes = node("condition", { condition: { kind: "flag", key: "k", op: "is_true" }, trueTarget: "t", falseTarget: "f" });
expect(removeHopFromNode(yes, "true").data.trueTarget).toBeUndefined();
expect(removeHopFromNode(yes, "true").data.falseTarget).toBe("f");
const no = node("condition", { condition: { kind: "flag", key: "k", op: "is_true" }, trueTarget: "t", falseTarget: "f" });
const falseRemoved = removeHopFromNode(no, "false");
expect(falseRemoved.data.falseTarget).toBeUndefined();
expect(falseRemoved.data.trueTarget).toBe("t");
});
it("clears the single continuation on a plain node", () => {
const n = node("dialogue", { body: "hi", next: { label: "next", target: "t" } });
expect(removeHopFromNode(n).data.next).toBeUndefined();
});
it("leaves a choice node unchanged when the handle is not a numbered row", () => {
const n = node("choice", { choices: [{ label: "a", target: "x" }] });
expect(removeHopFromNode(n, undefined)).toEqual(n);
});
});