1
0
Fork 0

Compare commits

..

No commits in common. "3d93ecafb3e0a080a40bf4ae6b978e929691fab0" and "78dc4945f76550c7b79baec7669fed5595d6d05e" have entirely different histories.

15 changed files with 276 additions and 1266 deletions

View file

@ -1,21 +1,5 @@
# Changelog
# v0.5.2
The dialogue flow editor gets a full authoring pass, and connection lines on both the dialogue canvas and the tech tree learn to route around cards instead of through them.
### Features
- **Dialogue flow editing, upgraded.** The flow canvas is taller and can expand to fill your whole screen while you work. Click selects, double-click edits, right-click the canvas adds any node type at the spot you clicked, and each choice row or condition branch has its own drag-out dot so wiring lands exactly where you mean it. A brand-new node you cancel out of is discarded instead of lingering as an empty card, dragging can snap to the grid with a toggle that remembers your choice, and selected cards now show a clear highlight ring.
- **Lines that route themselves.** Connection lines on the dialogue canvas (and the same engine behind the tech tree) now bend around cards they are not connected to, return loops run along clean corridors above or below the graph instead of slicing across it, arrowheads show which way a line flows, and condition labels sit in readable chips on their own line. Lines that would cross cards fan out into separate lanes so parallel connections stay traceable.
### Fixes
- **Node positions stick.** Moving a card in a dialogue flow and saving the conversation now actually keeps the layout; previously the nodes could jump back to their old spots after a reload.
---
# v0.4.1
NPCs get portraits and bios, your limited arsenal now syncs with in-game, and the maps pick up an Arma-style grid.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.5.2",
"version": "0.5.1",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -309,52 +309,6 @@ export async function evaluateNpcDialogueCondition(
}
}
/**
* Evaluate every choice's visibility gate for a `choice` node in one round
* trip. Ungated choices are always visible; gated ones appear only while the
* reading user's flags satisfy their condition. The node is looked up
* server-side from the stored flowchart, so clients never see gate config
* for conversations an admin has not authored.
*/
export async function evaluateNpcDialogueChoices(
npcId: number,
nodeId: string,
): Promise<ActionResult<boolean[]>> {
try {
const { payload, user } = await authenticate();
const res = await payload.find({
collection: "npc-dialogues",
where: { npc: { equals: npcId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
const node = flowData?.nodes?.find((n) => n.id === nodeId);
if (!node || node.type !== "choice") {
// Not a choice node: nothing to gate.
return { success: true, data: [] };
}
const visible: boolean[] = [];
for (const choice of node.data.choices ?? []) {
if (!choice.condition?.key?.trim()) {
visible.push(true);
continue;
}
visible.push(await evaluateCondition(payload, user.id as number, choice.condition));
}
return { success: true, data: visible };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}
async function evaluateCondition(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,

View file

@ -59,47 +59,6 @@
border-color: #22d3ee;
box-shadow: 0 0 6px rgba(34, 211, 238, 0.9);
}
/* Resting edges: the default thin grey line nearly vanishes on the dark
canvas, so brighten passive edges and their labels. Animated (wired)
edges get a cyan tint so connections read at a glance. */
.react-flow__edge-path {
stroke: #a1a1aa;
stroke-opacity: 0.9;
stroke-width: 1.5;
}
.react-flow__edge.animated .react-flow__edge-path {
stroke: #67e8f9;
stroke-opacity: 0.85;
}
.react-flow__edge-text {
fill: #d4d4d8;
font-size: 10px;
}
.react-flow__edge-textbg {
fill: #18181b;
fill-opacity: 0.9;
}
}
/* NPC dialogue editor: "expand" mode floats the whole editor (toolbar +
canvas) over the document form, filling the viewport to the right of the
admin sidebar. Offsets ride the admin shell's own CSS vars so the overlay
tracks the sidebar width and header height; z-index stays below the
status toasts (--z-status: 40) and Radix dialogs (z-50). */
.npc-dialogue-editor--expanded {
position: fixed;
top: var(--app-header-height);
left: var(--nav-width);
right: 0;
bottom: 0;
z-index: calc(var(--z-modal) - 1);
/* Small breakpoint: --nav-width becomes 100vw (off-canvas nav), which would
push the overlay off screen. */
@media (max-width: 1024px) {
left: 0;
}
}
/* Tech Tree: dark thin scrollbars for the panel and its dropdowns. */

View file

@ -132,17 +132,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
const removeChoice = (index: number) =>
patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) });
/** Toggle/update a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
patch({
choices: (draft.choices ?? []).map((c, i) => {
if (i !== index) return c;
if (partial === null) return { ...c, condition: undefined };
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
return { ...c, condition: { ...base, ...partial } };
}),
});
const targetOptions = allNodes.filter((n) => n.id !== node.id);
return (
@ -263,68 +252,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
/>
Hide after picked (one-time choice)
</label>
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={choice.condition !== undefined}
onCheckedChange={(checked) =>
setChoiceCondition(index, checked === true ? {} : null)
}
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
/>
Only show when a flag condition passes
</label>
{choice.condition && (
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Flag key
</Label>
<Input
value={choice.condition.key}
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
When the flag
</Label>
<select
value={choice.condition.op}
onChange={(e) =>
setChoiceCondition(index, {
op: e.target.value as DialogueCondition["op"],
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
(op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
),
)}
</select>
{NUMERIC_OPS.includes(choice.condition.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Amount
</Label>
<Input
type="number"
value={choice.condition.amount ?? 0}
onChange={(e) =>
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<p className="text-[10px] text-white/40">
Player-specific flag takes priority; falls back to global (no user).
Missing = false / 0. The choice button is hidden until this passes.
</p>
</div>
)}
<Button
type="button"
variant="outline"

View file

@ -1,28 +1,15 @@
"use client";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MouseEvent as ReactMouseEvent,
} from "react";
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 } from "lucide-react";
import { useField } from "@payloadcms/ui";
@ -36,7 +23,6 @@ import type {
import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";
import { RoutedFlowEdge } from "./RoutedFlowEdge";
const nodeTypes = {
dialogue: NpcDialogueNode,
@ -47,20 +33,9 @@ const nodeTypes = {
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",
@ -72,8 +47,7 @@ const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
};
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
// No speaker by default: an empty speaker renders as the NPC's own name.
dialogue: { body: "" },
dialogue: { speaker: "NPC", body: "" },
choice: { choices: [] },
event: { effect: { type: "notify", message: "" } },
delay: { delaySeconds: 2 },
@ -81,9 +55,8 @@ const DEFAULT_DATA: Record<string, DialogueNodeData> = {
end: {},
};
function FlowEditor() {
export function NpcDialogueEditor() {
const { value, setValue } = useField<FlowData>();
const rf = useReactFlow();
const initial: FlowData =
value && typeof value === "object" && Array.isArray((value as FlowData).nodes)
@ -93,62 +66,20 @@ function FlowEditor() {
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 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.
const syncedEdges = useMemo<Edge[]>(
() =>
deriveEdges(nodes as DialogueNode[]).map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
})),
() => deriveEdges(nodes as DialogueNode[]),
[nodes],
);
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),
nodes: nds as DialogueNode[],
edges: deriveEdges(nds as DialogueNode[]),
};
const serialized = JSON.stringify(payload);
if (serialized !== lastSerialized.current) {
@ -157,62 +88,24 @@ function FlowEditor() {
}
}, [setValue]);
// 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],
);
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) => {
(type: NpcDialogueNodeType) => {
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,
position: {
x: 120 + (count % 4) * 240,
y: 80 + Math.floor(count / 4) * 140,
},
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],
[nodes, setNodes, serialize],
);
const handleNodeSave = useCallback(
@ -220,32 +113,29 @@ function FlowEditor() {
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 deleteNode = useCallback(
(nodeId: string) => {
const next = (nodes as DialogueNode[])
.filter((n) => !gone.has(n.id))
.filter((n) => n.id !== nodeId)
.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,
next: n.data.next && n.data.next.target !== nodeId ? n.data.next : undefined,
choices: (n.data.choices ?? []).filter((c) => c.target !== nodeId),
trueTarget: n.data.trueTarget !== nodeId ? n.data.trueTarget : undefined,
falseTarget: n.data.falseTarget !== nodeId ? n.data.falseTarget : undefined,
},
}));
setNodes(next);
serialize(next);
setContextMenu(null);
if (editingNodeId && gone.has(editingNodeId)) setEditingNodeId(null);
if (editingNodeId === nodeId) setEditingNodeId(null);
},
[nodes, setNodes, serialize, editingNodeId],
);
@ -258,74 +148,26 @@ function FlowEditor() {
[],
);
// 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 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 writes into the node data (the graph's source of truth);
// edges stay a derived projection.
const applyConnection = useCallback(
(sourceId: string, targetId: string, sourceHandle?: string | null) => {
(sourceId: string, targetId: string) => {
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.
// First connection wires the true branch, the second the false one.
if (n.data.trueTarget && n.data.falseTarget) return n;
return {
...n,
@ -340,9 +182,9 @@ function FlowEditor() {
});
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);
// A fresh choice has no button text yet: pop the editor so it can be
// typed immediately (validateGraph flags empty labels).
if (source.type === "choice") setEditingNodeId(sourceId);
},
[nodes, setNodes, serialize],
);
@ -356,30 +198,23 @@ function FlowEditor() {
[nodes],
);
const onPaneClick = useCallback(() => {
setContextMenu(null);
setPaneMenu(null);
}, []);
const onPaneClick = useCallback(() => setContextMenu(null), []);
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
// Close both context menus on escape / pointer outside.
const closeMenus = useCallback(() => {
setContextMenu(null);
setPaneMenu(null);
}, []);
// Close the context menu on escape / pointer outside.
const closeMenu = useCallback(() => setContextMenu(null), []);
useEffect(() => {
if (!contextMenu && !paneMenu) return;
if (!contextMenu) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") closeMenus();
if (e.key === "Escape") closeMenu();
};
// Ignore pointerdowns inside a menu itself: pointerdown fires before
// Ignore pointerdowns inside the 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();
if (menuRef.current?.contains(e.target as globalThis.Node)) return;
closeMenu();
};
window.addEventListener("keydown", onKey);
document.addEventListener("pointerdown", onPtr);
@ -387,53 +222,13 @@ function FlowEditor() {
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;
}
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, deleteNodes]);
}, [contextMenu, closeMenu]);
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-col gap-2 w-full">
<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
@ -478,30 +273,6 @@ function FlowEditor() {
<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 && (
@ -510,19 +281,13 @@ function FlowEditor() {
</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}
>
<div className="npc-dialogue-flow h-96 border border-zinc-700 rounded-b-md overflow-hidden bg-zinc-950">
<ReactFlow
nodes={nodes}
edges={syncedEdges}
onNodesChange={handleNodesChange}
onNodesChange={onNodesChange}
onConnect={(c: Connection) => {
if (c.source && c.target) applyConnection(c.source, c.target, c.sourceHandle);
if (c.source && c.target) applyConnection(c.source, c.target);
}}
onConnectEnd={(event, connectionState) => {
// React Flow only resolves drops onto a handle. If the pointer
@ -537,39 +302,31 @@ function FlowEditor() {
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
const targetId = nodeElement?.getAttribute("data-id");
if (!targetId || targetId === sourceId) 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);
applyConnection(sourceId, targetId);
}}
isValidConnection={isValidConnection}
// Single click selects (React Flow default); double-click edits.
onNodeDoubleClick={(_e, node) => setEditingNodeId(node.id)}
onNodeClick={(_e, node) => setEditingNodeId(node.id)}
onNodeContextMenu={onNodeContextMenu}
onPaneClick={onPaneClick}
onPaneContextMenu={onPaneContextMenu}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
snapToGrid={snap}
snapGrid={[SNAP_GRID, SNAP_GRID]}
fitView
zoomOnDoubleClick={false}
colorMode="dark"
defaultEdgeOptions={{ animated: true }}
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.
Add a node to start building the conversation.
</div>
)}
</ReactFlow>
</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 edit. Right-click to delete. Drag from a node&apos;s right handle onto
another node to connect them (a choice node gains a new choice; dialogue and event nodes
re-point their continuation).
</p>
{contextMenu && (
@ -580,7 +337,7 @@ function FlowEditor() {
>
<button
type="button"
onClick={() => deleteNodes([contextMenu.nodeId])}
onClick={() => deleteNode(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
@ -588,51 +345,12 @@ function FlowEditor() {
</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]);
if (!open) setEditingNodeId(null);
}}
onSave={handleNodeSave}
/>
@ -640,12 +358,4 @@ function FlowEditor() {
);
}
export function NpcDialogueEditor() {
return (
<ReactFlowProvider>
<FlowEditor />
</ReactFlowProvider>
);
}
export default NpcDialogueEditor;

View file

@ -18,26 +18,18 @@ const position: Position = Position.Right;
const inputPosition: Position = Position.Left;
/** Single reusable canvas node for every dialogue node type. */
export function NpcDialogueNode({ data, type, selected }: NodeProps) {
export function NpcDialogueNode({ data, type }: NodeProps) {
const d = data as DialogueNodeData;
const nodeType = type as NpcDialogueNodeType;
const meta = DIALOGUE_NODES[nodeType];
// Only end nodes are truly terminal. A choice node keeps its generic source
// handle while it has zero choices, otherwise there would be no way to drag
// the first choice out of it; once choices exist each row gets its own
// handle (litegraph-style per-output wiring). Condition nodes always use
// dedicated true/false handles instead of the generic one.
const choiceCount = nodeType === "choice" ? (d.choices?.length ?? 0) : 1;
// Only end nodes are truly terminal. A choice node keeps its source handle
// even with zero choices, otherwise there would be no way to drag the
// first choice out of it.
const terminal = nodeType === "end";
const genericSource = !terminal && nodeType !== "condition" && !(nodeType === "choice" && choiceCount > 0);
return (
<div
className={`w-[20rem] max-w-[20rem] rounded border bg-zinc-900 shadow-lg ${meta.border} ${
// Gentle glow so the selection reads without shouting over the
// per-type border colors.
selected ? "ring-2 ring-cyan-400/50" : ""
}`}
className={`w-[20rem] max-w-[20rem] rounded border bg-zinc-900 shadow-lg ${meta.border}`}
>
<div className="flex items-center gap-2 border-b border-white/10 px-3 py-1.5">
<NodeIcon type={nodeType} />
@ -51,15 +43,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
)}
</div>
{/* Choice/condition cards must not clip their per-output handles, which
sit outside the card edge; other types keep scrollable content. */}
<div
className={`min-h-20 px-3 py-2 ${
nodeType === "choice" || nodeType === "condition"
? "overflow-visible"
: "max-h-32 overflow-y-auto"
}`}
>
<div className="max-h-32 min-h-20 overflow-y-auto px-3 py-2">
{nodeType === "dialogue" && (
<div>
{d.speaker && (
@ -84,7 +68,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
)}
<ul className="flex flex-col gap-1">
{(d.choices ?? []).map((choice, index) => (
<li key={index} className="relative flex items-center gap-1.5 text-xs text-white/70">
<li key={index} className="flex items-center gap-1.5 text-xs text-white/70">
<span className="size-3 shrink-0 rounded border border-amber-500/50" />
<span className="truncate">{choice.label || "Unlabeled choice"}</span>
{choice.once && (
@ -92,23 +76,6 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
once
</span>
)}
{choice.condition && (
<span
className="shrink-0 rounded-sm border border-sky-500/40 bg-sky-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-sky-300"
title={`Only shown when flag "${choice.condition.key}" ${choice.condition.op.replace(/_/g, " ")}`}
>
gated
</span>
)}
{/* Per-choice source handle: drag this row's dot to wire
exactly this choice (litegraph-style per-output). */}
<Handle
id={`c${index}`}
type="source"
position={position}
className="!size-2 !bg-amber-400/80"
style={{ right: -16 }}
/>
</li>
))}
{(d.choices?.length ?? 0) === 0 && (
@ -160,43 +127,18 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
)}
{nodeType === "condition" && (
<div className="flex flex-col gap-1.5 text-sm text-white/70">
<div>
{d.condition?.key ? (
<span>
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
<span className="text-white/50">{d.condition.op}</span>
{typeof d.condition.amount === "number" && (
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
)}
</span>
) : (
<span className="italic text-white/30">Set a flag key to branch on.</span>
)}
</div>
{/* Dedicated true/false source handles, one per branch. */}
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-emerald-300/80">
<span className="size-2 shrink-0 rounded-full border border-emerald-400/60" />
true
</div>
<Handle
id="true"
type="source"
position={position}
className="!size-2 !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">
<span className="size-2 shrink-0 rounded-full border border-rose-400/60" />
false
</div>
<Handle
id="false"
type="source"
position={position}
className="!size-2 !bg-rose-400/80"
style={{ bottom: 4 }}
/>
<div className="text-sm text-white/70">
{d.condition?.key ? (
<span>
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
<span className="text-white/50">{d.condition.op}</span>
{typeof d.condition.amount === "number" && (
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
)}
</span>
) : (
<span className="italic text-white/30">Set a flag key to branch on.</span>
)}
</div>
)}
@ -213,7 +155,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
)}
</div>
{genericSource && (
{!terminal && (
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
)}
{!d.isStart && (

View file

@ -1,90 +0,0 @@
"use client";
/**
* Flow edge that routes around node cards instead of cutting through them.
*
* The dialogue graph loops back a lot (a choice returning to an earlier
* line), and plain Bezier connectors sliced straight through unrelated
* cards, which made return paths impossible to trace. All shape logic lives
* in the shared `routeEdge` (`@/lib/flow-edge-routing`, also used by the
* tech tree); this component gathers the card rectangles from the React Flow
* store and renders the result with rounded corners, an arrowhead, and the
* condition label as a chip at the path midpoint so text stays readable
* over other geometry.
*/
import { useMemo } from "react";
import { BaseEdge, EdgeLabelRenderer, useStore, type EdgeProps } from "@xyflow/react";
import {
buildRoutePath,
polylineMidpoint,
routeEdge,
type RoutePoint,
type RouteRect,
type StubDirection,
} from "@/lib/flow-edge-routing";
export function RoutedFlowEdge({
id,
source,
target,
sourceX,
sourceY,
targetX,
targetY,
sourcePosition,
targetPosition,
markerEnd,
label,
}: EdgeProps) {
const nodeLookup = useStore((s) => s.nodeLookup);
const nodes = useMemo(() => {
const rects: RouteRect[] = [];
nodeLookup.forEach((node) => {
const width = node.measured?.width ?? 0;
const height = node.measured?.height ?? 0;
if (!width || !height) return;
const { x, y } = node.internals.positionAbsolute;
rects.push({ id: node.id, x, y, width, height });
});
return rects;
}, [nodeLookup]);
const start: RoutePoint = { x: sourceX, y: sourceY };
const end: RoutePoint = { x: targetX, y: targetY };
const { points: routed } = routeEdge({
id,
start,
end,
sourceDirection: sourcePosition as StubDirection | null,
targetDirection: targetPosition as StubDirection | null,
nodes,
sourceId: source,
targetId: target,
});
const path = buildRoutePath(routed);
const mid = polylineMidpoint(routed.length >= 2 ? routed : [start, end]);
const labelText = typeof label === "string" || typeof label === "number" ? String(label) : null;
return (
<>
<BaseEdge id={id} path={path} markerEnd={markerEnd} />
{labelText ? (
<EdgeLabelRenderer>
<div
className="nodrag nopan pointer-events-none rounded-sm border border-white/15 bg-zinc-950/90 px-1.5 py-0.5 font-mono text-[10px] leading-none text-zinc-300"
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${mid.x}px, ${mid.y}px)`,
}}
>
{labelText}
</div>
</EdgeLabelRenderer>
) : null}
</>
);
}

View file

@ -4,7 +4,12 @@ import { BaseEdge, EdgeLabelRenderer, useReactFlow, type EdgeProps } from "@xyfl
import React from "react";
import { buildRoutePath, type RouteWaypoint } from "./edgeRoutes";
import { routeEdge, type RoutePoint, type RouteRect } from "./edgeRouting";
import {
routeAroundObstacles,
segmentCrossesRect,
type RoutePoint,
type RouteRect,
} from "./edgeRouting";
export type RoutedEdgeData = {
/** User-placed waypoints for this edge (empty = automatic routing). */
@ -50,25 +55,36 @@ export function RoutedEdge({
const { screenToFlowPosition } = useReactFlow();
const dragIndexRef = React.useRef<number | null>(null);
// Shared shape builder (same logic as the dialogue canvas): forward edges
// take a stubbed Z-step at the source's lane (stepPosition), back edges try
// bus corridors around the cards, and every candidate is detoured around
// unrelated technologies with the cleanest result winning. User waypoints,
// when present, are routed verbatim.
const obstacles = (route?.obstacles ?? []).filter(
(r) => r.id !== route?.sourceId && r.id !== route?.targetId,
);
// Preferred shape: the user's waypoints if routed, else the automatic
// "out, across, in" path. If that path would cut through a node, fall back to
// the direct line so the router can bend around the obstacles (a midpoint
// sitting inside a box leaves the router nothing to work with).
const start: RoutePoint = { x: sourceX, y: sourceY };
const end: RoutePoint = { x: targetX, y: targetY };
const { points: routed, base } = routeEdge({
id: route?.routeId,
const stepX = sourceX + (targetX - sourceX) * (route?.stepPosition ?? 0.5);
const orthogonal: RoutePoint[] = [
start,
{ x: stepX, y: sourceY },
{ x: stepX, y: targetY },
end,
sourceDirection: "right",
targetDirection: "left",
nodes: route?.obstacles ?? [],
sourceId: route?.sourceId,
targetId: route?.targetId,
waypoints: waypoints.length > 0 ? waypoints : undefined,
stepPosition: route?.stepPosition,
});
];
const hasCrossing = (pts: RoutePoint[]) =>
pts.some(
(p, i) => i < pts.length - 1 && obstacles.some((r) => segmentCrossesRect(p, pts[i + 1], r)),
);
const base: RoutePoint[] =
waypoints.length > 0
? [start, ...waypoints, end]
: hasCrossing(orthogonal)
? [start, end]
: orthogonal;
const routed = routeAroundObstacles(base, obstacles);
const path = routed.length >= 2 ? buildRoutePath(routed) : "";
const commit = (next: RouteWaypoint[]) => route?.onRouteChange(route.routeId, next);

View file

@ -8,14 +8,9 @@
* Storage is per-browser (localStorage): routing is a personal viewing aid
* rather than shared tree data. Promoting it to a persisted field on the
* target technology is a small change once the schema settles.
*
* The path builder itself is shared (`@/lib/flow-edge-routing`); this module
* keeps only the per-browser persistence.
*/
import { type RouteWaypoint } from "@/lib/flow-edge-routing";
export { buildRoutePath, ROUTE_CORNER_RADIUS, type RouteWaypoint } from "@/lib/flow-edge-routing";
export type RouteWaypoint = { x: number; y: number };
export type EdgeRouteMap = Record<string, RouteWaypoint[]>;
const STORAGE_KEY = "ptf:tech-tree:edge-routes";
@ -45,3 +40,46 @@ export function saveEdgeRoutes(routes: EdgeRouteMap): void {
// Storage can be unavailable (private mode); routing just won't persist.
}
}
/** Corner rounding radius (px) at each waypoint. */
export const ROUTE_CORNER_RADIUS = 14;
function distance(a: RouteWaypoint, b: RouteWaypoint): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
/**
* SVG path through the given points. Each interior corner is cut with a
* quadratic curve so bends read as smooth corners instead of hard angles; the
* radius shrinks automatically on short segments so curves never overshoot.
*/
export function buildRoutePath(points: RouteWaypoint[], radius = ROUTE_CORNER_RADIUS): string {
if (points.length < 2) return "";
const start = points[0];
let d = `M ${start.x},${start.y}`;
for (let i = 1; i < points.length - 1; i += 1) {
const prev = points[i - 1];
const cur = points[i];
const next = points[i + 1];
const inLen = distance(prev, cur);
const outLen = distance(cur, next);
if (inLen === 0 || outLen === 0) {
d += ` L ${cur.x},${cur.y}`;
continue;
}
const r = Math.min(radius, inLen / 2, outLen / 2);
const a = {
x: cur.x - ((cur.x - prev.x) / inLen) * r,
y: cur.y - ((cur.y - prev.y) / inLen) * r,
};
const b = {
x: cur.x + ((next.x - cur.x) / outLen) * r,
y: cur.y + ((next.y - cur.y) / outLen) * r,
};
d += ` L ${a.x},${a.y} Q ${cur.x},${cur.y} ${b.x},${b.y}`;
}
const end = points[points.length - 1];
return `${d} L ${end.x},${end.y}`;
}

View file

@ -1,8 +1,133 @@
/**
* Obstacle-avoiding routing for Tech Tree edges.
*
* The generic router now lives in `@/lib/flow-edge-routing` (shared with the
* NPC dialogue flow editor); this module re-exports it so tech-tree imports
* stay stable.
* A prerequisite edge should not cut through technologies it is not connected
* to. Given the polyline an edge would take (source -> optional waypoints ->
* target) and the rectangles of every OTHER node, this inserts detour points
* so each segment swings around the boxes it would otherwise cross.
*
* The detour is greedy: for the first box a segment hits, it tries that box's
* four (inflated) corners and picks the one with the shortest total bend,
* recursing on the two halves. Bounded depth keeps it cheap and terminating.
*/
export * from "@/lib/flow-edge-routing";
export type RouteRect = { id: number; x: number; y: number; width: number; height: number };
export type RoutePoint = { x: number; y: number };
/** Clearance kept around a node when routing around it. */
export const ROUTE_CLEARANCE = 22;
const MAX_DEPTH = 3;
const EPS = 1;
/** Does segment a->b cross the interior of rect r? (exported for tests) */
export function segmentCrossesRect(a: RoutePoint, b: RoutePoint, r: RouteRect): boolean {
const x1 = r.x + EPS;
const y1 = r.y + EPS;
const x2 = r.x + r.width - EPS;
const y2 = r.y + r.height - EPS;
if (x2 <= x1 || y2 <= y1) return false;
// Liang-Barsky clip of the segment against the (slightly inset) box.
let t0 = 0;
let t1 = 1;
const dx = b.x - a.x;
const dy = b.y - a.y;
const p = [-dx, dx, -dy, dy];
const q = [a.x - x1, x2 - a.x, a.y - y1, y2 - a.y];
for (let i = 0; i < 4; i += 1) {
if (p[i] === 0) {
if (q[i] < 0) return false;
} else {
const t = q[i] / p[i];
if (p[i] < 0) {
if (t > t1) return false;
if (t > t0) t0 = t;
} else {
if (t < t0) return false;
if (t < t1) t1 = t;
}
}
}
return true;
}
const crosses = segmentCrossesRect;
function corners(r: RouteRect, margin: number): RoutePoint[] {
const x1 = r.x - margin;
const y1 = r.y - margin;
const x2 = r.x + r.width + margin;
const y2 = r.y + r.height + margin;
return [
{ x: x1, y: y1 },
{ x: x2, y: y1 },
{ x: x2, y: y2 },
{ x: x1, y: y2 },
];
}
function inside(p: RoutePoint, r: RouteRect, margin: number): boolean {
return (
p.x > r.x - margin && p.x < r.x + r.width + margin && p.y > r.y - margin && p.y < r.y + r.height + margin
);
}
function dist(a: RoutePoint, b: RoutePoint): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
/** Detour points from a to b (excluding a, ending with b). */
function detour(
a: RoutePoint,
b: RoutePoint,
obstacles: RouteRect[],
margin: number,
depth: number,
): RoutePoint[] {
if (depth >= MAX_DEPTH) return [b];
const hit = obstacles.find((r) => crosses(a, b, r));
if (!hit) return [b];
let best: RoutePoint | null = null;
let bestLen = Number.POSITIVE_INFINITY;
for (const c of corners(hit, margin)) {
// Skip a corner inside another box, or one not reachable from `a` without
// still cutting through the box. The second half is left to the recursion,
// which chains a second corner for wide boxes.
if (obstacles.some((r) => r.id !== hit.id && inside(c, r, 0))) continue;
if (crosses(a, c, hit)) continue;
// A corner at the current point or the destination makes no progress.
if (dist(a, c) < 1 || dist(c, b) < 1) continue;
const len = dist(a, c) + dist(c, b);
if (len < bestLen) {
bestLen = len;
best = c;
}
}
if (!best) return [b];
return [
...detour(a, best, obstacles, margin, depth + 1),
...detour(best, b, obstacles, margin, depth + 1),
];
}
/**
* Route a polyline around the given obstacle boxes. Returns a new point list;
* returns the input unchanged when there is nothing to avoid.
*/
export function routeAroundObstacles(
points: RoutePoint[],
obstacles: RouteRect[],
margin = ROUTE_CLEARANCE,
): RoutePoint[] {
if (points.length < 2 || obstacles.length === 0) return points;
const out: RoutePoint[] = [points[0]];
for (let i = 0; i < points.length - 1; i += 1) {
for (const p of detour(points[i], points[i + 1], obstacles, margin, 0)) {
const last = out[out.length - 1];
if (Math.abs(p.x - last.x) > 0.5 || Math.abs(p.y - last.y) > 0.5) out.push(p);
}
}
return out;
}

View file

@ -15,7 +15,6 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import {
evaluateNpcDialogueChoices,
evaluateNpcDialogueCondition,
triggerNpcDialogueEvent,
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
@ -65,10 +64,6 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
* reappears the next time the conversation is opened. Persist across
* conversations with a condition + player flag instead. */
const [takenChoices, setTakenChoices] = useState<Set<string>>(new Set());
/** Per-node visibility gates for condition-gated choices, fetched from
* the server when the conversation lands on a choice node. Cleared on
* every `begin()` so flags gained mid-conversation are re-checked. */
const [choiceGates, setChoiceGates] = useState<Record<string, boolean[]>>({});
const seq = useRef(0);
const sessionRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null);
@ -106,33 +101,6 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
if (el) el.scrollTop = el.scrollHeight;
}, [log, typing, playerTyping, open]);
// The choice node the log currently rests on (if any).
const activeChoiceNodeId = useMemo(() => {
const last = [...log].reverse().find((entry) => entry.kind === "node");
return last && last.kind === "node" && last.node.type === "choice" ? last.node.id : null;
}, [log]);
// Fetch the server-side visibility gates when landing on a choice node
// that has gated choices. Gated choices stay hidden until confirmed, so a
// forbidden option never flashes on screen.
useEffect(() => {
if (!open || !flow || !activeChoiceNodeId) return;
if (choiceGates[activeChoiceNodeId]) return;
const node = flow.nodes.find((n) => n.id === activeChoiceNodeId);
const hasGated = (node?.data.choices ?? []).some((c) => c.condition?.key?.trim());
if (!hasGated) return;
let cancelled = false;
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
if (!cancelled && res.success && Array.isArray(res.data)) {
const gate = res.data;
setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate }));
}
});
return () => {
cancelled = true;
};
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
/** Appends a node to the log after a length-based "typing" delay. */
@ -154,7 +122,6 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
setTyping(null);
setPlayerTyping(false);
setTakenChoices(new Set());
setChoiceGates({});
setOpen(true);
if (!flow.startId) return;
void (async () => {
@ -243,11 +210,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
const visibleChoices = choiceNode
? (choiceNode.data.choices ?? [])
.map((hop, index) => ({ hop, index }))
.filter(
({ hop, index }) =>
!(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) &&
(!hop.condition?.key?.trim() || choiceGates[choiceNode.id]?.[index] === true),
)
.filter(({ hop, index }) => !(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)))
: [];
return (

View file

@ -1,381 +0,0 @@
/**
* Obstacle-avoiding edge routing shared by the admin flow canvases
* (tech tree, NPC dialogue flow editor).
*
* An edge should not cut through nodes it is not connected to. Given the
* polyline an edge would take (source -> optional waypoints -> target) and
* the rectangles of every other node, this inserts detour points so each
* segment swings around the boxes it would otherwise cross.
*
* The detour is greedy: for the first box a segment hits, it tries that box's
* four (inflated) corners and picks the one with the shortest total bend,
* recursing on the two halves. Bounded depth keeps it cheap and terminating.
*
* Pure module: no React/Payload imports, safe on client and server.
*/
export type RoutePoint = { x: number; y: number };
/** A node rectangle to route around. Ids may be numeric or string. */
export type RouteRect = {
id: number | string;
x: number;
y: number;
width: number;
height: number;
};
/** Clearance kept around a node when routing around it. */
export const ROUTE_CLEARANCE = 22;
const MAX_DEPTH = 4;
const EPS = 1;
/** Does segment a->b cross the interior of rect r? (exported for tests) */
export function segmentCrossesRect(a: RoutePoint, b: RoutePoint, r: RouteRect): boolean {
const x1 = r.x + EPS;
const y1 = r.y + EPS;
const x2 = r.x + r.width - EPS;
const y2 = r.y + r.height - EPS;
if (x2 <= x1 || y2 <= y1) return false;
// Liang-Barsky clip of the segment against the (slightly inset) box.
let t0 = 0;
let t1 = 1;
const dx = b.x - a.x;
const dy = b.y - a.y;
const p = [-dx, dx, -dy, dy];
const q = [a.x - x1, x2 - a.x, a.y - y1, y2 - a.y];
for (let i = 0; i < 4; i += 1) {
if (p[i] === 0) {
if (q[i] < 0) return false;
} else {
const t = q[i] / p[i];
if (p[i] < 0) {
if (t > t1) return false;
if (t > t0) t0 = t;
} else {
if (t < t0) return false;
if (t < t1) t1 = t;
}
}
}
return true;
}
const crosses = segmentCrossesRect;
function corners(r: RouteRect, margin: number): RoutePoint[] {
const x1 = r.x - margin;
const y1 = r.y - margin;
const x2 = r.x + r.width + margin;
const y2 = r.y + r.height + margin;
return [
{ x: x1, y: y1 },
{ x: x2, y: y1 },
{ x: x2, y: y2 },
{ x: x1, y: y2 },
];
}
function inside(p: RoutePoint, r: RouteRect, margin: number): boolean {
return (
p.x > r.x - margin &&
p.x < r.x + r.width + margin &&
p.y > r.y - margin &&
p.y < r.y + r.height + margin
);
}
function dist(a: RoutePoint, b: RoutePoint): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
/** Detour points from a to b (excluding a, ending with b). */
function detour(
a: RoutePoint,
b: RoutePoint,
obstacles: RouteRect[],
margin: number,
depth: number,
): RoutePoint[] {
if (depth >= MAX_DEPTH) return [b];
const hit = obstacles.find((r) => crosses(a, b, r));
if (!hit) return [b];
let best: RoutePoint | null = null;
let bestLen = Number.POSITIVE_INFINITY;
for (const c of corners(hit, margin)) {
// Skip a corner inside another box, or one not reachable from `a` without
// still cutting through the box. The second half is left to the recursion,
// which chains a second corner for wide boxes.
if (obstacles.some((r) => r.id !== hit.id && inside(c, r, 0))) continue;
if (crosses(a, c, hit)) continue;
// A corner at the current point or the destination makes no progress.
if (dist(a, c) < 1 || dist(c, b) < 1) continue;
const len = dist(a, c) + dist(c, b);
if (len < bestLen) {
bestLen = len;
best = c;
}
}
if (!best) return [b];
return [
...detour(a, best, obstacles, margin, depth + 1),
...detour(best, b, obstacles, margin, depth + 1),
];
}
/** Does any segment of the polyline cut one of the obstacles? */
function hasCrossing(points: RoutePoint[], obstacles: RouteRect[]): boolean {
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => crosses(points[i], points[i + 1], r))) return true;
}
return false;
}
/** One greedy pass: detour every base segment around the boxes it hits. */
function routePass(points: RoutePoint[], obstacles: RouteRect[], margin: number): RoutePoint[] {
const out: RoutePoint[] = [points[0]];
for (let i = 0; i < points.length - 1; i += 1) {
for (const p of detour(points[i], points[i + 1], obstacles, margin, 0)) {
const last = out[out.length - 1];
if (Math.abs(p.x - last.x) > 0.5 || Math.abs(p.y - last.y) > 0.5) out.push(p);
}
}
return out;
}
/**
* Route a polyline around the given obstacle boxes. Returns a new point list;
* returns the input unchanged when there is nothing to avoid. A single greedy
* pass can leave a residual crossing when a chosen corner's continuation
* hits yet another box, so the result is re-routed until clean (bounded).
*/
export function routeAroundObstacles(
points: RoutePoint[],
obstacles: RouteRect[],
margin = ROUTE_CLEARANCE,
): RoutePoint[] {
if (points.length < 2 || obstacles.length === 0) return points;
let routed = points;
for (let pass = 0; pass < 3; pass += 1) {
routed = routePass(routed, obstacles, margin);
if (!hasCrossing(routed, obstacles)) break;
}
return routed;
}
// ---------------------------------------------------------------------------
// Path building
// ---------------------------------------------------------------------------
export type RouteWaypoint = RoutePoint;
/** Corner rounding radius (px) at each waypoint. */
export const ROUTE_CORNER_RADIUS = 14;
/**
* SVG path through the given points. Each interior corner is cut with a
* quadratic curve so bends read as smooth corners instead of hard angles; the
* radius shrinks automatically on short segments so curves never overshoot.
*/
export function buildRoutePath(points: RouteWaypoint[], radius = ROUTE_CORNER_RADIUS): string {
if (points.length < 2) return "";
const start = points[0];
let d = `M ${start.x},${start.y}`;
for (let i = 1; i < points.length - 1; i += 1) {
const prev = points[i - 1];
const cur = points[i];
const next = points[i + 1];
const inLen = dist(prev, cur);
const outLen = dist(cur, next);
if (inLen === 0 || outLen === 0) {
d += ` L ${cur.x},${cur.y}`;
continue;
}
const r = Math.min(radius, inLen / 2, outLen / 2);
const a = {
x: cur.x - ((cur.x - prev.x) / inLen) * r,
y: cur.y - ((cur.y - prev.y) / inLen) * r,
};
const b = {
x: cur.x + ((next.x - cur.x) / outLen) * r,
y: cur.y + ((next.y - cur.y) / outLen) * r,
};
d += ` L ${a.x},${a.y} Q ${cur.x},${cur.y} ${b.x},${b.y}`;
}
const end = points[points.length - 1];
return `${d} L ${end.x},${end.y}`;
}
/** Point at half the total polyline length, for placing edge labels. */
export function polylineMidpoint(points: RoutePoint[]): RoutePoint {
if (points.length === 0) return { x: 0, y: 0 };
if (points.length === 1) return points[0];
let total = 0;
for (let i = 0; i < points.length - 1; i += 1) total += dist(points[i], points[i + 1]);
let target = total / 2;
for (let i = 0; i < points.length - 1; i += 1) {
const seg = dist(points[i], points[i + 1]);
if (target <= seg) {
const t = seg === 0 ? 0 : target / seg;
return {
x: points[i].x + (points[i + 1].x - points[i].x) * t,
y: points[i].y + (points[i + 1].y - points[i].y) * t,
};
}
target -= seg;
}
return points[points.length - 1];
}
// ---------------------------------------------------------------------------
// Edge shape builder
// ---------------------------------------------------------------------------
/** How far a line leaves its handle before it may bend (px). */
export const EDGE_STUB = 24;
/** Which side of its card a handle sits on. */
export type StubDirection = "left" | "right" | "top" | "bottom";
function stubFor(point: RoutePoint, direction: StubDirection | null | undefined, length: number): RoutePoint {
switch (direction) {
case "left":
return { x: point.x - length, y: point.y };
case "right":
return { x: point.x + length, y: point.y };
case "top":
return { x: point.x, y: point.y - length };
case "bottom":
return { x: point.x, y: point.y + length };
default:
return point;
}
}
/**
* Detour lanes come in three depths so edges that enter the same handle (or
* loop around the same card) don't collapse onto one identical lane and read
* as a single thick bundle. The depth is derived from the edge id, so it is
* stable across renders and differs between edges with overwhelming
* probability.
*/
const LANE_STEPS = [0, 16, 32];
export function laneFor(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) | 0;
return LANE_STEPS[Math.abs(h) % LANE_STEPS.length];
}
export type EdgeRouteInput = {
/** Edge identity, used to spread detour lanes. */
id?: string;
start: RoutePoint;
end: RoutePoint;
sourceDirection?: StubDirection | null;
targetDirection?: StubDirection | null;
/** Rectangles of every node card on the canvas. */
nodes: RouteRect[];
sourceId?: number | string;
targetId?: number | string;
/** Manual waypoints: routed verbatim (cleaned), skipping auto candidates. */
waypoints?: RoutePoint[];
/** Where the forward Z-step's vertical run sits (0..1). */
stepPosition?: number;
stubLength?: number;
};
export type EdgeRouteResult = {
/** Final polyline to render (detoured, clean when possible). */
points: RoutePoint[];
/** The winning unrouted base shape (for "add a bend" handles). */
base: RoutePoint[];
};
/**
* Build the full route for one edge between two cards.
*
* Forward edges prefer a tidy Z-step (perpendicular stubs at each handle);
* back edges try structured "bus routes" that run along a corridor above or
* below every card before swinging into the entry handle. Candidates are
* scored by residual crossings after detouring, and the cleanest wins.
* Back edges treat ALL cards as obstacles (including their own ends, which
* the line must loop around); forward edges exclude their own endpoints.
*/
export function routeEdge(input: EdgeRouteInput): EdgeRouteResult {
const {
id = "",
start,
end,
sourceDirection,
targetDirection,
nodes,
sourceId,
targetId,
waypoints,
stepPosition = 0.5,
stubLength = EDGE_STUB,
} = input;
const endpointFree = nodes.filter((r) => r.id !== sourceId && r.id !== targetId);
const isBackEdge = end.x < start.x;
const obstacles = isBackEdge ? nodes : endpointFree;
const lane = laneFor(id);
const margin = ROUTE_CLEARANCE + lane;
const sStub = stubFor(start, sourceDirection, stubLength);
const tStub = stubFor(end, targetDirection, stubLength);
const crossingCount = (points: RoutePoint[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => crosses(points[i], points[i + 1], r))) n += 1;
}
return n;
};
if (waypoints && waypoints.length > 0) {
const base = [start, ...waypoints, end];
return { points: routeAroundObstacles(base, obstacles, margin), base };
}
const candidates: RoutePoint[][] = [];
if (isBackEdge && obstacles.length > 0) {
const topY = Math.min(...obstacles.map((r) => r.y)) - ROUTE_CLEARANCE - lane;
const botY = Math.max(...obstacles.map((r) => r.y + r.height)) + ROUTE_CLEARANCE + lane;
const bus = (y: number): RoutePoint[] => [
start,
sStub,
{ x: sStub.x, y },
{ x: tStub.x, y },
tStub,
end,
];
candidates.push(bus(topY), bus(botY), [start, sStub, tStub, end]);
} else if (isBackEdge) {
candidates.push([start, sStub, tStub, end]);
} else {
const stepX = sStub.x + (tStub.x - sStub.x) * stepPosition;
candidates.push(
[start, sStub, { x: stepX, y: sStub.y }, { x: stepX, y: tStub.y }, tStub, end],
[start, sStub, tStub, end],
);
}
let best: RoutePoint[] | null = null;
let bestBase = candidates[0];
let bestScore = Number.POSITIVE_INFINITY;
for (const candidate of candidates) {
const cleaned = routeAroundObstacles(candidate, obstacles, margin);
const score = crossingCount(cleaned);
if (score < bestScore) {
best = cleaned;
bestBase = candidate;
bestScore = score;
}
if (score === 0) break;
}
return { points: best ?? [start, end], base: bestBase };
}

View file

@ -27,12 +27,6 @@ export interface DialogueNext {
* `dlg-once:` player flag).
*/
once?: boolean;
/**
* Choice hops only: when set, the choice button is only offered to players
* whose live flags satisfy this condition (evaluated server-side, same
* flag semantics as condition nodes). Missing key = ungated.
*/
condition?: DialogueCondition;
}
/**
@ -109,8 +103,6 @@ export interface DialogueEdge {
source: string;
target: string;
label?: string;
/** Source handle the edge leaves from (`c0`..`cN` per choice, `true`/`false`). */
sourceHandle?: string;
}
export interface FlowData {
@ -158,20 +150,6 @@ export function findStartNode(nodes: DialogueNode[]): DialogueNode | null {
return (roots.length ? roots[0] : nodes[0]) ?? null;
}
/** Handle id an outgoing hop leaves its node through (per-choice / per-branch). */
export function handleIdForHop(node: DialogueNode, index: number): string | undefined {
if (node.type === "choice") return `c${index}`;
if (node.type === "condition") {
// outgoingHops skips unset branches, so map by what actually exists:
// only-true -> "true", only-false -> "false", both -> first is true.
const hasTrue = !!node.data.trueTarget;
const hasFalse = !!node.data.falseTarget;
if (hasTrue && hasFalse) return index === 0 ? "true" : "false";
return hasTrue ? "true" : "false";
}
return undefined;
}
/** Builds the edge projection that mirrors the node graph. */
export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
const edges: DialogueEdge[] = [];
@ -183,7 +161,6 @@ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
source: node.id,
target: hop.target,
label: hop.label,
sourceHandle: handleIdForHop(node, index),
});
});
}
@ -221,9 +198,6 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
if (node.type === "choice" && !hop.label?.trim()) {
errors.push(`A choice on "${node.id}" needs button text.`);
}
if (node.type === "choice" && hop.condition && !hop.condition.key.trim()) {
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
}
}
}

View file

@ -1,111 +0,0 @@
import { describe, expect, it } from "vitest";
import {
laneFor,
routeEdge,
segmentCrossesRect,
type RoutePoint,
type RouteRect,
} from "@/lib/flow-edge-routing";
const crossings = (points: RoutePoint[], rects: RouteRect[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (rects.some((r) => segmentCrossesRect(points[i], points[i + 1], r))) n += 1;
}
return n;
};
const A: RouteRect = { id: "a", x: 0, y: 0, width: 200, height: 100 };
const B: RouteRect = { id: "b", x: 600, y: 0, width: 200, height: 100 };
const BLOCKER: RouteRect = { id: "x", x: 340, y: -20, width: 80, height: 140 };
describe("shared edge router (routeEdge)", () => {
it("draws a stubbed Z-step for a clear forward edge", () => {
const { points } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B],
sourceId: "a",
targetId: "b",
});
// start, sStub, two step corners (coincident on a straight run), tStub,
// end — no detours needed.
expect(points).toHaveLength(6);
expect(points[0]).toEqual({ x: 200, y: 50 });
expect(points[1]).toEqual({ x: 224, y: 50 }); // 24px stub off the handle
expect(points[2]).toEqual({ x: 400, y: 50 });
expect(points[3]).toEqual({ x: 400, y: 50 });
expect(points[points.length - 1]).toEqual({ x: 600, y: 50 });
expect(points[points.length - 2]).toEqual({ x: 576, y: 50 });
});
it("routes a blocked forward edge with zero card crossings", () => {
const { points } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "a",
targetId: "b",
});
expect(crossings(points, [BLOCKER])).toBe(0);
});
it("sends a back edge around the cards via a bus corridor", () => {
const { points } = routeEdge({
id: "back",
start: { x: 800, y: 50 },
end: { x: 0, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "b",
targetId: "a",
});
expect(crossings(points, [A, B, BLOCKER])).toBe(0);
// It must actually leave the card band (above or below everything).
const ys = points.map((p) => p.y);
expect(Math.min(...ys) < -20 || Math.max(...ys) > 120).toBe(true);
});
it("spreads detour lanes per edge id", () => {
const route = (id: string) =>
JSON.stringify(
routeEdge({
id,
start: { x: 800, y: 50 },
end: { x: 0, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B, BLOCKER],
sourceId: "b",
targetId: "a",
}).points,
);
// laneFor buckets ids into distinct depths; these two land on different ones.
expect(laneFor("e1")).not.toBe(laneFor("e2"));
expect(route("e1")).not.toBe(route("e2"));
});
it("routes manual waypoints verbatim as the base shape", () => {
const wp: RoutePoint[] = [{ x: 400, y: 300 }];
const { base } = routeEdge({
id: "e",
start: { x: 200, y: 50 },
end: { x: 600, y: 50 },
sourceDirection: "right",
targetDirection: "left",
nodes: [A, B],
sourceId: "a",
targetId: "b",
waypoints: wp,
});
expect(base).toEqual([{ x: 200, y: 50 }, ...wp, { x: 600, y: 50 }]);
});
});