Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@tanstack/react-query-devtools": "5.59.11",
"@xyflow/react": "12.3.2",
"elkjs": "0.9.3",
"libavoid-js": "0.4.5",
"monaco-editor": "0.52.0",
"react": "18.3.1",
"react-aria-components": "^1.4.0",
Expand Down
34 changes: 34 additions & 0 deletions src/Visualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ function Rendering({
setUseInteractiveLayout,
mergeEdges,
setMergeEdges,
avoidEdgeRouting,
setAvoidEdgeRouting,
showText,
setShowText,
textSyntax,
Expand All @@ -232,6 +234,8 @@ function Rendering({
setUseInteractiveLayout: (value: boolean) => void;
mergeEdges: boolean;
setMergeEdges: (value: boolean) => void;
avoidEdgeRouting: boolean;
setAvoidEdgeRouting: (value: boolean) => void;
showText: boolean;
setShowText: (value: boolean) => void;
textSyntax: TextSyntax;
Expand Down Expand Up @@ -338,6 +342,10 @@ function Rendering({
[setUseInteractiveLayout, useInteractiveLayout]
);
const handleToggleMergeEdges = useCallback(() => setMergeEdges(!mergeEdges), [setMergeEdges, mergeEdges]);
const handleToggleAvoidEdgeRouting = useCallback(
() => setAvoidEdgeRouting(!avoidEdgeRouting),
[setAvoidEdgeRouting, avoidEdgeRouting]
);
const handleCopyText = useCallback(
() => textClipboard.copy(blocksToPlainText(formatEGraphBlocks(subgraph, textSyntax))),
[subgraph, textSyntax, textClipboard]
Expand Down Expand Up @@ -463,6 +471,13 @@ function Rendering({
<MenuItemLabel>Merge edges</MenuItemLabel>
<MenuItemDescription>{mergeEdges ? "Seperate ports for incoming edges" : "Merge all incoming edges"}</MenuItemDescription>
</MenuItem>
<MenuItem onAction={handleToggleAvoidEdgeRouting} className="cursor-pointer">
<AccessibleIcon>{avoidEdgeRouting ? <ArrowUturnRightIcon /> : <ArrowLongRightIcon />}</AccessibleIcon>
<MenuItemLabel>Edge routing: {avoidEdgeRouting ? "libavoid" : "ELK"}</MenuItemLabel>
<MenuItemDescription>
{avoidEdgeRouting ? "Switch to ELK layered edge routing" : "Route edges with libavoid to reduce crossings"}
</MenuItemDescription>
</MenuItem>
<MenuSeparator />
<MenuItem onAction={handleCopyText} className="cursor-pointer">
<AccessibleIcon>
Expand Down Expand Up @@ -529,6 +544,8 @@ function LayoutFlow({
setTextSyntax,
inlineLevel,
setInlineLevel,
avoidEdgeRouting,
setAvoidEdgeRouting,
}: {
egraph: string;
outerElem: HTMLDivElement;
Expand All @@ -542,6 +559,8 @@ function LayoutFlow({
setTextSyntax: (value: TextSyntax) => void;
inlineLevel: InlineLevel;
setInlineLevel: (value: InlineLevel) => void;
avoidEdgeRouting: boolean;
setAvoidEdgeRouting: (value: boolean) => void;
}) {
const [useInteractiveLayout, setUseInteractiveLayout] = useState(false);
const [mergeEdges, setMergeEdges] = useState(false);
Expand Down Expand Up @@ -665,6 +684,7 @@ function LayoutFlow({
selectedNodes,
previousLayout,
mergeEdges,
avoidEdgeRouting,
inlineLevel,
effectiveInlineSyntax,
],
Expand All @@ -679,6 +699,7 @@ function LayoutFlow({
selectedNodes,
previousLayout,
mergeEdges,
avoidEdgeRouting,
inlineLevel,
effectiveInlineSyntax,
signal
Expand Down Expand Up @@ -837,6 +858,8 @@ function LayoutFlow({
setUseInteractiveLayout={setUseInteractiveLayout}
mergeEdges={mergeEdges}
setMergeEdges={setMergeEdges}
avoidEdgeRouting={avoidEdgeRouting}
setAvoidEdgeRouting={setAvoidEdgeRouting}
showText={showText}
setShowText={setShowText}
textSyntax={textSyntax}
Expand Down Expand Up @@ -931,6 +954,7 @@ export type MountOptions = {
showText?: boolean;
textSyntax?: TextSyntax;
inlineLevel?: InlineLevel;
avoidEdgeRouting?: boolean;
};

export function Visualizer({
Expand All @@ -940,13 +964,15 @@ export function Visualizer({
showText: initialShowText = false,
textSyntax: initialTextSyntax = "call",
inlineLevel: initialInlineLevel = 0,
avoidEdgeRouting: initialAvoidEdgeRouting = true,
}: {
egraphs: string[];
height?: string | null;
resize?: boolean;
showText?: boolean;
textSyntax?: TextSyntax;
inlineLevel?: InlineLevel;
avoidEdgeRouting?: boolean;
}) {
const [rootElem, setRootElem] = useState<HTMLDivElement | null>(null);

Expand All @@ -956,6 +982,7 @@ export function Visualizer({
const [showText, setShowText] = useState(initialShowText);
const [textSyntax, setTextSyntax] = useState<TextSyntax>(initialTextSyntax);
const [inlineLevel, setInlineLevel] = useState<InlineLevel>(initialInlineLevel);
const [avoidEdgeRouting, setAvoidEdgeRouting] = useState(initialAvoidEdgeRouting);
const aspectRatio = rootElem ? rootElem.clientWidth / rootElem.clientHeight : null;

useEffect(() => {
Expand All @@ -970,6 +997,10 @@ export function Visualizer({
setInlineLevel(initialInlineLevel);
}, [initialInlineLevel]);

useEffect(() => {
setAvoidEdgeRouting(initialAvoidEdgeRouting);
}, [initialAvoidEdgeRouting]);

// If we are at null, then use the last item in the list
// if the last selection was for a list of egraphs that no longer exists, then use the last item in the list
const [selected, setSelected] = useState<null | { egraphs: string[]; index: number }>(null);
Expand Down Expand Up @@ -1003,6 +1034,8 @@ export function Visualizer({
setTextSyntax={setTextSyntax}
inlineLevel={inlineLevel}
setInlineLevel={setInlineLevel}
avoidEdgeRouting={avoidEdgeRouting}
setAvoidEdgeRouting={setAvoidEdgeRouting}
/>
)}
</div>
Expand Down Expand Up @@ -1060,6 +1093,7 @@ export function mount(
showText={merged.showText}
textSyntax={merged.textSyntax}
inlineLevel={merged.inlineLevel}
avoidEdgeRouting={merged.avoidEdgeRouting}
/>
</QueryClientProvider>
);
Expand Down
104 changes: 93 additions & 11 deletions src/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Node, Edge } from "@xyflow/react";
// Make worker inline because if its external cannot be loaded from esm.sh due to CORS
import ELKWorker from "elkjs/lib/elk-worker?worker&inline";
import { InlineLevel, InlineResult, inlineLeaves } from "./inline";
import { routeOuterEdgesWithCancel } from "./routing";
import { TextSyntax } from "./text";

// Elk has a *huge* amount of options to configure. To see everything you can
Expand Down Expand Up @@ -276,6 +277,7 @@ export async function layoutGraph(
selectedNodes: SelectedNodes,
previousLayout: PreviousLayout | null,
mergeEdges: boolean,
avoidEdgeRouting: boolean,
inlineLevel: InlineLevel,
inlineSyntax: TextSyntax,
signal: AbortSignal
Expand Down Expand Up @@ -313,7 +315,7 @@ export async function layoutGraph(
const { elkNode, colors } = toELKNode(subgraph, getNodeSize, getExtraSize, selectedNodes, aspectRatio, previousLayout, mergeEdges);
const elkJSON = JSON.stringify(elkNode, null, 2);
const layout = (await layoutWithCancel(elkNode, signal)) as MyELKNodeLayedOut;
const edges = toFlowEdges(layout);
const edges = await toFlowEdges(layout, mergeEdges, avoidEdgeRouting, signal);
const nodes = toFlowNodes(layout);
const nodeToEdges = new Map(
[...Object.entries(Object.groupBy(edges, (edge) => edge.source)), ...Object.entries(Object.groupBy(edges, (edge) => edge.target))].map(
Expand Down Expand Up @@ -576,9 +578,52 @@ function toFlowNodes(layout: MyELKNodeLayedOut): (FlowClass | FlowNode)[] {
]);
}

function toFlowEdges(layout: MyELKNodeLayedOut): FlowEdge[] {
function joinInnerAndOuterPoints(
innerPoints: { x: number; y: number }[],
outerPoints: { x: number; y: number }[],
sourceNodeBounds?: { x: number; y: number; width: number; height: number }
): { x: number; y: number }[] {
const innerEnd = innerPoints[innerPoints.length - 1];
const outerStart = outerPoints[0];
if (Math.hypot(innerEnd.x - outerStart.x, innerEnd.y - outerStart.y) < 0.5) {
return [...innerPoints, ...outerPoints.slice(1)];
}
// If inner edge is a straight vertical drop and libavoid nudged the border exit slightly
// horizontally within the source e-node's width, align the vertical drop so there is no jog.
if (
sourceNodeBounds &&
innerPoints.length === 2 &&
Math.abs(innerPoints[0].x - innerEnd.x) < 0.5 &&
Math.abs(innerEnd.y - outerStart.y) < 1 &&
outerStart.x >= sourceNodeBounds.x + 3 &&
outerStart.x <= sourceNodeBounds.x + sourceNodeBounds.width - 3
) {
return [{ x: outerStart.x, y: innerPoints[0].y }, ...outerPoints];
}
return [...innerPoints, ...outerPoints];
}

async function toFlowEdges(
layout: MyELKNodeLayedOut,
mergeEdges: boolean,
avoidEdgeRouting: boolean,
signal: AbortSignal
): Promise<FlowEdge[]> {
const outerEdges = Object.fromEntries(layout.edges!.map(({ edgeID, sections }) => [edgeID, sections![0]]));
return layout.children.flatMap(({ x: parentX, y: parentY, edges }) =>
const classes = layout.children.map(({ id, x, y, width, height }) => ({ id, x, y, width, height }));
const nodeBounds = new Map<string, { x: number; y: number; width: number; height: number }>();
for (const cls of layout.children) {
for (const child of cls.children) {
nodeBounds.set(child.id, {
x: cls.x + child.x,
y: cls.y + child.y,
width: child.width,
height: child.height,
});
}
}

const edgeItems = layout.children.flatMap(({ id: sourceClassID, x: parentX, y: parentY, edges }) =>
edges!.map(({ edgeID, sections, sourceNode, targetNode }) => {
const [section] = sections!;
const outerEdge = outerEdges[edgeID];
Expand All @@ -588,15 +633,52 @@ function toFlowEdges(layout: MyELKNodeLayedOut): FlowEdge[] {
y: y + parentY,
}));
return {
type: "edge",
id: edgeID,
source: sourceNode,
target: targetNode!,
data: {
// Combien inner and outer edge show it just shows up once in the rendering and can be selected as a single unit.
points: [...innerPoints, ...(outerEdge.bendPoints || []), outerEdge.endPoint],
},
edgeID,
sourceNode,
sourceClassID,
targetNode: targetNode!,
innerPoints,
outerEdge,
};
})
);

let routedOuter: Map<string, { x: number; y: number }[]> | null = null;
if (avoidEdgeRouting) {
try {
routedOuter = await routeOuterEdgesWithCancel(
classes,
edgeItems.map((item) => ({
edgeID: item.edgeID,
sourceClassID: item.sourceClassID,
targetClassID: item.targetNode,
sourcePoint: item.innerPoints[item.innerPoints.length - 1],
elkTargetPoint: item.outerEdge.endPoint,
})),
mergeEdges,
signal
);
} catch (err) {
if (signal.aborted) {
throw err;
}
// Fall back to ELK edge routes if WASM routing fails in an unusual host environment.
console.warn("libavoid edge routing failed, falling back to ELK routes:", err);
}
}

return edgeItems.map(({ edgeID, sourceNode, targetNode, innerPoints, outerEdge }) => {
const outerPoints = routedOuter?.get(edgeID);
const points =
outerPoints && outerPoints.length >= 2
? joinInnerAndOuterPoints(innerPoints, outerPoints, nodeBounds.get(sourceNode))
: [...innerPoints, ...(outerEdge.bendPoints || []), outerEdge.endPoint];
return {
type: "edge",
id: edgeID,
source: sourceNode,
target: targetNode,
data: { points },
};
});
}
98 changes: 98 additions & 0 deletions src/routing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Make worker inline so it works from esm.sh / AnyWidget without external asset fetches or CORS issues.
import RoutingWorker from "./routing.worker?worker&inline";
import type {
ClassBox,
OuterEdgeInput,
RoutePoint,
RouteWorkerRequest,
RouteWorkerResponse,
} from "./routing.worker";

export type { ClassBox, OuterEdgeInput, RoutePoint };

// Reuse a single warm worker when not aborted so WASM only compiles once per session;
// terminate and recreate on abort so long routing jobs cancel immediately.
let sharedWorker: Worker | null = null;
let workerBusy = false;

function acquireWorker(): Worker {
if (sharedWorker && !workerBusy) {
return sharedWorker;
}
return new RoutingWorker();
}

export function routeOuterEdgesWithCancel(
classes: ClassBox[],
edges: OuterEdgeInput[],
mergeEdges: boolean,
signal: AbortSignal
): Promise<Map<string, RoutePoint[]>> {
if (edges.length === 0 || classes.length === 0) {
return Promise.resolve(new Map());
}

return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}

const worker = acquireWorker();
const isShared = worker === sharedWorker || sharedWorker === null;
if (sharedWorker === null) {
sharedWorker = worker;
}
if (isShared) {
workerBusy = true;
}

let settled = false;
const cleanup = (terminate: boolean) => {
worker.onmessage = null;
worker.onerror = null;
signal.removeEventListener("abort", onAbort);
if (terminate) {
worker.terminate();
if (worker === sharedWorker) {
sharedWorker = null;
workerBusy = false;
}
} else if (isShared) {
workerBusy = false;
} else {
worker.terminate();
}
};

const onAbort = () => {
if (settled) return;
settled = true;
cleanup(true);
reject(signal.reason);
};

signal.addEventListener("abort", onAbort, { once: true });

worker.onmessage = (event: MessageEvent<RouteWorkerResponse>) => {
if (settled) return;
settled = true;
cleanup(false);
if (event.data.ok) {
resolve(new Map(event.data.routes));
} else {
reject(new Error(event.data.error));
}
};

worker.onerror = (err) => {
if (settled) return;
settled = true;
cleanup(true);
reject(err instanceof ErrorEvent ? err.error ?? new Error(err.message) : err);
};

const req: RouteWorkerRequest = { classes, edges, mergeEdges };
worker.postMessage(req);
});
}
Loading
Loading