54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import dagre from '@dagrejs/dagre';
|
|
import { DialogueNode } from '../types/dialogue';
|
|
|
|
export type PositionMap = Record<string, { x: number; y: number }>;
|
|
|
|
const NODE_WIDTH = 260;
|
|
const NODE_HEIGHT = 130;
|
|
|
|
export function computeLayout(nodes: DialogueNode[]): PositionMap {
|
|
const g = new dagre.graphlib.Graph();
|
|
g.setDefaultEdgeLabel(() => ({}));
|
|
g.setGraph({ rankdir: 'TB', ranksep: 60, nodesep: 50 });
|
|
|
|
nodes.forEach(n => {
|
|
const h = n.type === 'Choice'
|
|
? NODE_HEIGHT + Math.max(0, n.choices.length - 1) * 28
|
|
: NODE_HEIGHT;
|
|
g.setNode(n.id, { width: NODE_WIDTH, height: h });
|
|
});
|
|
|
|
nodes.forEach(n => {
|
|
switch (n.type) {
|
|
case 'Line':
|
|
case 'SetFlag':
|
|
case 'CutsceneStart':
|
|
if (n.next) g.setEdge(n.id, n.next);
|
|
break;
|
|
case 'Choice':
|
|
n.choices.forEach(c => { if (c.next) g.setEdge(n.id, c.next); });
|
|
break;
|
|
case 'Condition':
|
|
if (n.trueNext) g.setEdge(n.id, n.trueNext);
|
|
if (n.falseNext) g.setEdge(n.id, n.falseNext);
|
|
break;
|
|
}
|
|
});
|
|
|
|
dagre.layout(g);
|
|
|
|
const positions: PositionMap = {};
|
|
nodes.forEach(n => {
|
|
const pos = g.node(n.id);
|
|
if (pos) {
|
|
const h = n.type === 'Choice'
|
|
? NODE_HEIGHT + Math.max(0, n.choices.length - 1) * 28
|
|
: NODE_HEIGHT;
|
|
positions[n.id] = { x: pos.x - NODE_WIDTH / 2, y: pos.y - h / 2 };
|
|
} else {
|
|
positions[n.id] = { x: 0, y: 0 };
|
|
}
|
|
});
|
|
return positions;
|
|
}
|