initial commit
This commit is contained in:
42
src/App.css
Normal file
42
src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
18
src/App.tsx
Normal file
18
src/App.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { GraphRenderer } from "./Graph";
|
||||
|
||||
export default function App() {
|
||||
const containerRef = useRef(null);
|
||||
const firstLevelGraph = new GraphRenderer(containerRef);
|
||||
|
||||
useEffect(() => {
|
||||
firstLevelGraph.render();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex-1 p-4">
|
||||
<div ref={containerRef} className="w-full h-full bg-white rounded shadow" style={{minHeight: '600px', overflow: 'auto'}}></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
99
src/Graph.tsx
Normal file
99
src/Graph.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import React, { useState } from "react";
|
||||
import Viz from 'viz.js';
|
||||
import { Module, render } from 'viz.js/full.render.js';
|
||||
import { graphToDot } from "./Graphviz";
|
||||
import * as d3 from 'd3';
|
||||
import { NodeContextMenu } from "./NodeContextMenu";
|
||||
|
||||
const viz = new Viz({ Module, render });
|
||||
|
||||
export class GraphRenderer {
|
||||
graph: Graph;
|
||||
setGraph: React.Dispatch<React.SetStateAction<Graph>>;
|
||||
containerRef: React.RefObject<null>;
|
||||
contextMenu: NodeContextMenu;
|
||||
|
||||
constructor(containerRef: React.RefObject<null>) {
|
||||
[this.graph, this.setGraph] = useState(defaultGraph());
|
||||
this.containerRef = containerRef;
|
||||
this.contextMenu = new NodeContextMenu(containerRef);
|
||||
}
|
||||
|
||||
public async render() {
|
||||
const dot = graphToDot(this.graph);
|
||||
|
||||
try {
|
||||
const svgElement = await viz.renderSVGElement(dot, { engine: 'dot' });
|
||||
const container = this.containerRef.current;
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
container.appendChild(svgElement);
|
||||
this.attachInteractions(svgElement);
|
||||
} catch (e) {
|
||||
console.error('Viz render error', e);
|
||||
}
|
||||
}
|
||||
|
||||
attachInteractions(svgElement: SVGSVGElement) {
|
||||
const svg = d3.select(svgElement);
|
||||
const self = this;
|
||||
svg.selectAll('g.node')
|
||||
.style('cursor', 'pointer')
|
||||
.on('click', function (event) {
|
||||
event.stopPropagation();
|
||||
const id = d3.select(this).attr('id');
|
||||
self.createChildNode(id);
|
||||
self.render();
|
||||
})
|
||||
.on('contextmenu', function (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const id = d3.select(this).attr('id');
|
||||
const { clientX: x, clientY: y } = event;
|
||||
self.contextMenu.setContextMenu({ x, y, nodeId: id });
|
||||
});
|
||||
}
|
||||
|
||||
createChildNode(parentId: string) {
|
||||
const id = crypto.randomUUID();
|
||||
this.setGraph(prev => ({ ...prev, nodes: [...prev.nodes, { id, label: 'New node' }], edges: [...prev.edges, { from: parentId, to: id }] }));
|
||||
}
|
||||
}
|
||||
|
||||
function defaultGraph(): Graph {
|
||||
return {
|
||||
nodes: [
|
||||
{ id: 'A', label: 'A' },
|
||||
{ id: 'B', label: 'B' },
|
||||
{ id: 'C', label: 'C' }
|
||||
],
|
||||
edges: [
|
||||
{ from: 'A', to: 'B' },
|
||||
{ from: 'B', to: 'C' }
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
export class Graph {
|
||||
nodes: Node[] = [];
|
||||
edges: Edge[] = [];
|
||||
}
|
||||
|
||||
export class Edge {
|
||||
from: string;
|
||||
to: string;
|
||||
|
||||
constructor(from: string, to: string) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
}
|
||||
}
|
||||
|
||||
export class Node {
|
||||
public id: string;
|
||||
public label?: string;
|
||||
|
||||
constructor(id: string) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
24
src/Graphviz.tsx
Normal file
24
src/Graphviz.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
export function graphToDot(g) {
|
||||
// Directed graph, use neato layout so we can use pos attributes
|
||||
const lines = [];
|
||||
lines.push('digraph G {');
|
||||
lines.push(' graph [splines=true, overlap=false, rankdir=LR];');
|
||||
lines.push(' node [shape=rectangle, style=filled, fillcolor="white", fontsize=12];');
|
||||
|
||||
// nodes
|
||||
for (const n of g.nodes) {
|
||||
const attrs = [];
|
||||
attrs.push(`label=\"${n.label}\"`);
|
||||
attrs.push(`id=\"${n.id}\"`)
|
||||
lines.push(` \"${n.id}\" [${attrs.join(', ')}];`);
|
||||
}
|
||||
|
||||
// edges
|
||||
for (const e of g.edges) {
|
||||
lines.push(` \"${e.from}\" -> \"${e.to}\";`);
|
||||
}
|
||||
|
||||
// close
|
||||
lines.push('}');
|
||||
return lines.join('\n');
|
||||
}
|
||||
70
src/NodeContextMenu.tsx
Normal file
70
src/NodeContextMenu.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
export class NodeContextMenu {
|
||||
contextMenu: ContextMenuInput | null;
|
||||
setContextMenu: React.Dispatch<React.SetStateAction<ContextMenuInput | null>>;
|
||||
|
||||
constructor(containerRef: React.RefObject<null>) {
|
||||
[this.contextMenu, this.setContextMenu] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if(!this.contextMenu){
|
||||
return;
|
||||
}
|
||||
const container = containerRef.current;
|
||||
if (container) {
|
||||
const menu = renderToStaticMarkup(this.render());
|
||||
renderTo
|
||||
(container as HTMLElement).append
|
||||
}
|
||||
}, [this.contextMenu]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = () => this.setContextMenu(null);
|
||||
document.addEventListener('click', close);
|
||||
return () => document.removeEventListener('click', close);
|
||||
}, []);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.contextMenu)
|
||||
return (
|
||||
<div
|
||||
className="absolute bg-white border rounded shadow-lg z-50 p-2 text-sm"
|
||||
style={{ left: this.contextMenu.x, top: this.contextMenu.y }}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div className="font-bold mb-1">Node: {this.contextMenu.nodeId}</div>
|
||||
<button
|
||||
className="block w-full text-left hover:bg-gray-100 px-2 py-1"
|
||||
onClick={() => {
|
||||
this.setContextMenu(null);
|
||||
}}
|
||||
>
|
||||
Edit subgraph
|
||||
</button>
|
||||
<button
|
||||
className="block w-full text-left hover:bg-gray-100 px-2 py-1"
|
||||
onClick={() => {
|
||||
this.setContextMenu(null);
|
||||
}}
|
||||
>
|
||||
Delete node
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class ContextMenuInput {
|
||||
x: number;
|
||||
y: number;
|
||||
nodeId: string;
|
||||
|
||||
constructor(x: number, y: number, nodeId: string) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.nodeId = nodeId;
|
||||
}
|
||||
}
|
||||
1
src/assets/react.svg
Normal file
1
src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
68
src/index.css
Normal file
68
src/index.css
Normal file
@@ -0,0 +1,68 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
10
src/main.tsx
Normal file
10
src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
499
src/stash
Normal file
499
src/stash
Normal file
@@ -0,0 +1,499 @@
|
||||
/*
|
||||
Graphviz + React interactive graph editor
|
||||
|
||||
Features implemented (best-effort):
|
||||
- Uses Viz.js (Graphviz compiled to WASM) to render DOT -> SVG (engine: neato)
|
||||
- Create nodes, delete nodes, rename nodes
|
||||
- Create & delete edges (connect nodes)
|
||||
- Drag nodes (hold Ctrl while dragging) to set fixed position in the graph
|
||||
- Drag a node and drop it onto an edge to insert it into that edge (edge A->B becomes A->dragged and dragged->B)
|
||||
- Double-click a node to open an in-app modal where you can create a subgraph assigned to that node
|
||||
- "Flatten" button combines the main graph and all subgraphs into one merged graph
|
||||
|
||||
Limitations / notes:
|
||||
- This is a single-file React component (App.jsx). It assumes you have a React + Tailwind project set up.
|
||||
- You need to install dependencies: viz.js and d3.
|
||||
npm install react react-dom d3 viz.js
|
||||
|
||||
How to use:
|
||||
- Run your React app (e.g. with Vite or CRA). Place this file as src/App.jsx and start.
|
||||
- The UI has controls on the left. Click "Add node" to add a node. Select source and target and click "Connect" to add edge.
|
||||
- Hold Ctrl and drag a node to move it. Drop onto an edge to split the edge as described.
|
||||
- Double-click a node to open its subgraph editor in a modal.
|
||||
- Click Flatten to view the merged graph.
|
||||
|
||||
This is a non-trivial interactive example — adapt and harden for production.
|
||||
*/
|
||||
|
||||
import React, {useEffect, useRef, useState} from 'react';
|
||||
import Viz from 'viz.js';
|
||||
import { Module, render } from 'viz.js/full.render.js';
|
||||
import * as d3 from 'd3';
|
||||
|
||||
const viz = new Viz({ Module, render });
|
||||
|
||||
function makeId(prefix = 'n') {
|
||||
return prefix + Math.random().toString(36).slice(2, 9);
|
||||
}
|
||||
|
||||
function defaultGraph() {
|
||||
return {
|
||||
nodes: [
|
||||
{ id: 'A', label: 'A' },
|
||||
{ id: 'B', label: 'B' },
|
||||
{ id: 'C', label: 'C' }
|
||||
],
|
||||
edges: [
|
||||
{ from: 'A', to: 'B' },
|
||||
{ from: 'B', to: 'C' }
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [graph, setGraph] = useState(defaultGraph());
|
||||
// map nodeId -> {nodes,edges}
|
||||
const [subgraphs, setSubgraphs] = useState({});
|
||||
const [selectedSource, setSelectedSource] = useState(null);
|
||||
const [selectedTarget, setSelectedTarget] = useState(null);
|
||||
const [selectedNode, setSelectedNode] = useState(null);
|
||||
const [selectedEdge, setSelectedEdge] = useState(null);
|
||||
const [flatDot, setFlatDot] = useState(null);
|
||||
|
||||
const svgRef = useRef(null);
|
||||
const containerRef = useRef(null);
|
||||
|
||||
// modal for subgraph
|
||||
const [modalNode, setModalNode] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
renderGraph();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [graph, subgraphs]);
|
||||
|
||||
async function renderGraph(overrideDot=null) {
|
||||
const dot = overrideDot || graphToDot(graph);
|
||||
try {
|
||||
const svgElement = await viz.renderSVGElement(dot, {engine: 'neato'});
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
container.appendChild(svgElement);
|
||||
svgRef.current = svgElement;
|
||||
attachInteractions(svgElement);
|
||||
} catch (e) {
|
||||
console.error('Viz render error', e);
|
||||
// try to recover
|
||||
viz.reset();
|
||||
}
|
||||
}
|
||||
|
||||
function graphToDot(g, options={includePositions:false}) {
|
||||
// Directed graph, use neato layout so we can use pos attributes
|
||||
const lines = [];
|
||||
lines.push('digraph G {');
|
||||
lines.push(' graph [splines=true, overlap=false, sep="+8", rankdir=LR, layout=neato];');
|
||||
lines.push(' node [shape=circle, style=filled, fillcolor="lightgoldenrod", fontsize=12];');
|
||||
|
||||
// nodes
|
||||
for (const n of g.nodes) {
|
||||
const attrs = [];
|
||||
attrs.push(`label=\"${escapeLabel(n.label)}\"`);
|
||||
if (n.pos) {
|
||||
// pin node if pos is set
|
||||
attrs.push(`pos=\"${n.pos}\"`);
|
||||
attrs.push(`pin=true`);
|
||||
}
|
||||
lines.push(` \"${n.id}\" [${attrs.join(', ')}];`);
|
||||
}
|
||||
|
||||
// edges
|
||||
for (const e of g.edges) {
|
||||
lines.push(` \"${e.from}\" -> \"${e.to}\";`);
|
||||
}
|
||||
|
||||
// close
|
||||
lines.push('}');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function escapeLabel(s) {
|
||||
return String(s).replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
// Attach interactivity (d3)
|
||||
function attachInteractions(svgElement) {
|
||||
const svg = d3.select(svgElement);
|
||||
|
||||
// mark edges and nodes with helpful data attributes
|
||||
svg.selectAll('g.edge').each(function() {
|
||||
const g = d3.select(this);
|
||||
const title = g.select('title').text(); // Graphviz gives "A->B"
|
||||
if (title) {
|
||||
// parse
|
||||
const match = title.match(/([^\s]+)\s*->\s*([^\s]+)/);
|
||||
if (match) {
|
||||
g.attr('data-from', match[1]);
|
||||
g.attr('data-to', match[2]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
svg.selectAll('g.node').each(function() {
|
||||
const g = d3.select(this);
|
||||
const title = g.select('title').text(); // node id
|
||||
if (title) {
|
||||
g.attr('data-id', title);
|
||||
}
|
||||
});
|
||||
|
||||
// node click handlers
|
||||
svg.selectAll('g.node')
|
||||
.style('cursor', 'pointer')
|
||||
.on('click', function(event) {
|
||||
event.stopPropagation();
|
||||
const id = d3.select(this).attr('data-id');
|
||||
setSelectedNode(id);
|
||||
})
|
||||
.on('dblclick', function(event) {
|
||||
event.stopPropagation();
|
||||
const id = d3.select(this).attr('data-id');
|
||||
openSubgraphModal(id);
|
||||
});
|
||||
|
||||
// Add dragging: user must hold Ctrl while dragging a node
|
||||
// We'll implement a manual pointer drag (not d3.drag) to get full control
|
||||
svg.selectAll('g.node').each(function() {
|
||||
const nodeG = d3.select(this);
|
||||
const id = nodeG.attr('data-id');
|
||||
const shape = nodeG.select('ellipse, polygon, path');
|
||||
nodeG.on('pointerdown', function(event) {
|
||||
if (!event.ctrlKey) return; // require Ctrl key
|
||||
event.preventDefault();
|
||||
const pointerId = event.pointerId;
|
||||
const startPos = getEventPoint(event, svgElement);
|
||||
// capture pointer on this node
|
||||
nodeG.node().setPointerCapture(pointerId);
|
||||
|
||||
const onPointerMove = (ev) => {
|
||||
ev.preventDefault();
|
||||
const p = getEventPoint(ev, svgElement);
|
||||
// move the node by updating its pos temporarily and re-render with pin
|
||||
// convert to graph coords - Graphviz uses points; fortunately, render gives coords matching svg units
|
||||
const fixedPos = `${p.x},${p.y}!`;
|
||||
setGraph(prev => {
|
||||
// update node's pos
|
||||
const nodes = prev.nodes.map(n => n.id === id ? {...n, pos: `${p.x},${p.y}`} : n);
|
||||
return {...prev, nodes};
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerUp = (ev) => {
|
||||
try { nodeG.node().releasePointerCapture(pointerId); } catch(e){}
|
||||
document.removeEventListener('pointermove', onPointerMove);
|
||||
document.removeEventListener('pointerup', onPointerUp);
|
||||
|
||||
const p = getEventPoint(ev, svgElement);
|
||||
|
||||
// check if dropped on an edge
|
||||
const hitEdge = findEdgeUnderPoint(svgElement, p);
|
||||
if (hitEdge) {
|
||||
const from = hitEdge.getAttribute('data-from');
|
||||
const to = hitEdge.getAttribute('data-to');
|
||||
// perform split: remove from->to, add from->id and id->to
|
||||
setGraph(prev => {
|
||||
// ensure node id exists in prev
|
||||
const hasNode = prev.nodes.some(n => n.id === id);
|
||||
const nodes = hasNode ? prev.nodes : [...prev.nodes, {id, label: id, pos: `${p.x},${p.y}`}];
|
||||
const edges = prev.edges.filter(e => !(e.from === from && e.to === to));
|
||||
edges.push({from, to: id});
|
||||
edges.push({from: id, to: to});
|
||||
return {...prev, nodes, edges};
|
||||
});
|
||||
} else {
|
||||
// just set final pos on node (already set during move)
|
||||
// to be safe, re-render
|
||||
renderGraph();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('pointermove', onPointerMove);
|
||||
document.addEventListener('pointerup', onPointerUp);
|
||||
});
|
||||
});
|
||||
|
||||
// edge click select
|
||||
svg.selectAll('g.edge').style('cursor', 'pointer').on('click', function(event) {
|
||||
event.stopPropagation();
|
||||
const g = d3.select(this);
|
||||
const from = g.attr('data-from');
|
||||
const to = g.attr('data-to');
|
||||
setSelectedEdge({from, to});
|
||||
});
|
||||
|
||||
// click empty area resets selection
|
||||
svg.on('click', () => {
|
||||
setSelectedNode(null);
|
||||
setSelectedEdge(null);
|
||||
});
|
||||
}
|
||||
|
||||
function getEventPoint(event, svgElement) {
|
||||
const pt = svgElement.createSVGPoint();
|
||||
pt.x = event.clientX;
|
||||
pt.y = event.clientY;
|
||||
const ctm = svgElement.getScreenCTM().inverse();
|
||||
const loc = pt.matrixTransform(ctm);
|
||||
return {x: loc.x, y: loc.y};
|
||||
}
|
||||
|
||||
function findEdgeUnderPoint(svgElement, point) {
|
||||
// iterate edges, compute distance to their path
|
||||
const edges = svgElement.querySelectorAll('g.edge');
|
||||
for (const g of edges) {
|
||||
const path = g.querySelector('path');
|
||||
if (!path) continue;
|
||||
const total = path.getTotalLength();
|
||||
// sample along path to find min distance
|
||||
const samples = Math.max(10, Math.floor(total / 10));
|
||||
let minDist = Infinity;
|
||||
for (let i=0;i<=samples;i++){
|
||||
const pt = path.getPointAtLength((i/samples) * total);
|
||||
const dx = pt.x - point.x;
|
||||
const dy = pt.y - point.y;
|
||||
const d = Math.sqrt(dx*dx + dy*dy);
|
||||
if (d < minDist) minDist = d;
|
||||
}
|
||||
if (minDist < 12) return g; // threshold
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// UI actions
|
||||
function addNode() {
|
||||
const id = makeId('n');
|
||||
setGraph(prev => ({...prev, nodes: [...prev.nodes, {id, label: id}]}));
|
||||
}
|
||||
|
||||
function connectSelected() {
|
||||
if (!selectedSource || !selectedTarget) return;
|
||||
setGraph(prev => ({...prev, edges: [...prev.edges, {from: selectedSource, to: selectedTarget}]}));
|
||||
setSelectedSource(null);
|
||||
setSelectedTarget(null);
|
||||
}
|
||||
|
||||
function deleteSelectedNode() {
|
||||
if (!selectedNode) return;
|
||||
const id = selectedNode;
|
||||
setGraph(prev => ({nodes: prev.nodes.filter(n=>n.id!==id), edges: prev.edges.filter(e=>e.from!==id && e.to!==id)}));
|
||||
// also remove subgraph
|
||||
setSubgraphs(prev => {
|
||||
const copy = {...prev}; delete copy[id]; return copy;
|
||||
});
|
||||
setSelectedNode(null);
|
||||
}
|
||||
|
||||
function renameSelectedNode(newLabel) {
|
||||
if (!selectedNode) return;
|
||||
setGraph(prev => ({...prev, nodes: prev.nodes.map(n=>n.id===selectedNode?{...n,label:newLabel}:n)}));
|
||||
}
|
||||
|
||||
function deleteSelectedEdge() {
|
||||
if (!selectedEdge) return;
|
||||
setGraph(prev => ({...prev, edges: prev.edges.filter(e=>!(e.from===selectedEdge.from && e.to===selectedEdge.to))}));
|
||||
setSelectedEdge(null);
|
||||
}
|
||||
|
||||
function openSubgraphModal(nodeId) {
|
||||
setModalNode(nodeId);
|
||||
// ensure subgraph exists
|
||||
setSubgraphs(prev => ({...prev, [nodeId]: prev[nodeId] || defaultGraph()}));
|
||||
}
|
||||
|
||||
function saveSubgraph(nodeId, sub) {
|
||||
setSubgraphs(prev=> ({...prev, [nodeId]: sub}));
|
||||
setModalNode(null);
|
||||
}
|
||||
|
||||
function flattenAll() {
|
||||
// produce a merged DOT: main graph + each subgraph where subgraph node ids are prefixed by parent id
|
||||
const lines = [];
|
||||
lines.push('digraph FLATTEN {');
|
||||
lines.push(' graph [splines=true, overlap=false, layout=neato];');
|
||||
lines.push(' node [shape=circle, style=filled, fillcolor="lightblue"];');
|
||||
|
||||
// main nodes
|
||||
for (const n of graph.nodes) {
|
||||
const attrs = [`label=\"${escapeLabel(n.label)}\"`];
|
||||
if (n.pos) attrs.push(`pos=\"${n.pos}\"`);
|
||||
lines.push(` \"${n.id}\" [${attrs.join(',')}];`);
|
||||
}
|
||||
for (const e of graph.edges) lines.push(` \"${e.from}\" -> \"${e.to}\";`);
|
||||
|
||||
// subgraphs
|
||||
for (const [parent, sub] of Object.entries(subgraphs)) {
|
||||
for (const n of sub.nodes) {
|
||||
const id = `${parent}::${n.id}`;
|
||||
const attrs = [`label=\"${escapeLabel(n.label)}\"`];
|
||||
if (n.pos) attrs.push(`pos=\"${n.pos}\"`);
|
||||
lines.push(` \"${id}\" [${attrs.join(',')}];`);
|
||||
}
|
||||
for (const e of sub.edges) {
|
||||
const from = `${parent}::${e.from}`;
|
||||
const to = `${parent}::${e.to}`;
|
||||
lines.push(` \"${from}\" -> \"${to}\";`);
|
||||
}
|
||||
// connect parent node to subgraph root nodes (optional: connect parent -> root nodes)
|
||||
// We'll connect parent to every node without incoming edges in the subgraph to make structure visible.
|
||||
const incoming = new Set(sub.edges.map(e=>e.to));
|
||||
for (const n of sub.nodes) {
|
||||
if (!incoming.has(n.id)) {
|
||||
lines.push(` \"${parent}\" -> \"${parent}::${n.id}\" [style=dashed];`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('}');
|
||||
const dot = lines.join('\n');
|
||||
setFlatDot(dot);
|
||||
// render the flattened one in the main panel
|
||||
renderGraph(dot);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-screen flex bg-gray-100">
|
||||
<div className="w-80 p-4 bg-white border-r">
|
||||
<h2 className="text-lg font-bold mb-3">Graph Editor</h2>
|
||||
<button className="mb-2 w-full btn" onClick={addNode}>Add node</button>
|
||||
<div className="mt-3">
|
||||
<div className="mb-2">Connect nodes:</div>
|
||||
<select value={selectedSource||''} onChange={e=>setSelectedSource(e.target.value)} className="w-full mb-1">
|
||||
<option value="">-- source --</option>
|
||||
{graph.nodes.map(n => <option key={n.id} value={n.id}>{n.id} ({n.label})</option>)}
|
||||
</select>
|
||||
<select value={selectedTarget||''} onChange={e=>setSelectedTarget(e.target.value)} className="w-full mb-1">
|
||||
<option value="">-- target --</option>
|
||||
{graph.nodes.map(n => <option key={n.id} value={n.id}>{n.id} ({n.label})</option>)}
|
||||
</select>
|
||||
<button className="mb-2 w-full btn" onClick={connectSelected}>Connect</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<div className="mb-2">Selected Node: {selectedNode || '-'}</div>
|
||||
<div className="flex gap-2">
|
||||
<input placeholder="rename..." id="rename-input" className="flex-1 p-1 border" />
|
||||
<button className="btn" onClick={()=>{
|
||||
const v = document.getElementById('rename-input').value.trim(); if(v) renameSelectedNode(v);
|
||||
}}>Rename</button>
|
||||
</div>
|
||||
<button className="mt-2 btn w-full" onClick={deleteSelectedNode}>Delete Node</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<div>Selected Edge: {selectedEdge ? `${selectedEdge.from} -> ${selectedEdge.to}` : '-'}</div>
|
||||
<button className="mt-2 btn w-full" onClick={deleteSelectedEdge}>Delete Edge</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<button className="w-full btn" onClick={()=>{ renderGraph(); setFlatDot(null); }}>Re-render</button>
|
||||
<button className="w-full btn mt-2" onClick={flattenAll}>Flatten (merge subgraphs)</button>
|
||||
<div className="text-sm text-gray-600 mt-2">Tip: Hold Ctrl and drag a node to move it. Drop onto an edge to insert the node into that edge. Double-click a node to edit its subgraph.</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex-1 p-4">
|
||||
<div ref={containerRef} className="w-full h-full bg-white rounded shadow" style={{minHeight: '600px', overflow: 'auto'}}></div>
|
||||
</div>
|
||||
|
||||
{modalNode && (
|
||||
<SubgraphModal nodeId={modalNode} subgraph={subgraphs[modalNode]} onClose={()=>setModalNode(null)} onSave={(sub)=>saveSubgraph(modalNode, sub)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubgraphModal({nodeId, subgraph, onClose, onSave}){
|
||||
const [local, setLocal] = useState(() => subgraph ? JSON.parse(JSON.stringify(subgraph)) : defaultGraph());
|
||||
|
||||
useEffect(()=>{ setLocal(subgraph ? JSON.parse(JSON.stringify(subgraph)) : defaultGraph()); }, [subgraph]);
|
||||
|
||||
function addNode(){ const id=makeId('s'); setLocal(prev=>({...prev, nodes: [...prev.nodes, {id,label:id}]})); }
|
||||
function connect(a,b){ setLocal(prev=>({...prev, edges: [...prev.edges, {from:a,to:b}]})); }
|
||||
function save(){ onSave(local); }
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white p-4 w-3/4 h-3/4 overflow-auto rounded shadow-lg">
|
||||
<h3 className="text-lg font-bold mb-2">Subgraph for node {nodeId}</h3>
|
||||
<div className="flex gap-4">
|
||||
<div className="w-1/3 border p-2">
|
||||
<button className="btn mb-2 w-full" onClick={addNode}>Add node to subgraph</button>
|
||||
<div className="text-sm">Nodes</div>
|
||||
<ul className="list-disc pl-5">
|
||||
{local.nodes.map(n=> <li key={n.id}>{n.id} ({n.label})</li>)}
|
||||
</ul>
|
||||
<div className="mt-2">Connect:</div>
|
||||
<ConnectSubUI nodes={local.nodes} onConnect={(a,b)=>connect(a,b)} />
|
||||
<div className="mt-2">Edges</div>
|
||||
<ul className="list-disc pl-5">
|
||||
{local.edges.map((e,i)=> <li key={i}>{e.from} → {e.to}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
<div className="flex-1 border p-2">
|
||||
<div className="text-sm mb-2">Preview</div>
|
||||
<SubgraphPreview graph={local} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button className="btn" onClick={save}>Save subgraph</button>
|
||||
<button className="btn" onClick={onClose}>Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectSubUI({nodes, onConnect}){
|
||||
const [a,setA] = useState('');
|
||||
const [b,setB] = useState('');
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<select value={a} onChange={e=>setA(e.target.value)} className="flex-1">
|
||||
<option value="">--</option>
|
||||
{nodes.map(n=> <option key={n.id} value={n.id}>{n.id}</option>)}
|
||||
</select>
|
||||
<select value={b} onChange={e=>setB(e.target.value)} className="flex-1">
|
||||
<option value="">--</option>
|
||||
{nodes.map(n=> <option key={n.id} value={n.id}>{n.id}</option>)}
|
||||
</select>
|
||||
<button className="btn" onClick={()=>{ if(a && b) onConnect(a,b); }}>Connect</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubgraphPreview({graph}){
|
||||
const ref = useRef(null);
|
||||
useEffect(()=>{
|
||||
let cancelled = false;
|
||||
(async ()=>{
|
||||
const dot = graphToDotLocal(graph);
|
||||
try{
|
||||
const svgEl = await viz.renderSVGElement(dot, {engine:'neato'});
|
||||
const c = ref.current; if(!c) return;
|
||||
c.innerHTML=''; c.appendChild(svgEl);
|
||||
}catch(e){ console.error(e); viz.reset(); }
|
||||
})();
|
||||
return ()=>{ cancelled=true; };
|
||||
}, [graph]);
|
||||
return <div ref={ref} style={{width:'100%', height:300}} className="bg-white"></div>;
|
||||
}
|
||||
|
||||
function graphToDotLocal(g){
|
||||
const lines=['digraph G {',' graph [layout=neato];',' node [shape=circle];'];
|
||||
for(const n of g.nodes){ lines.push(` \"${n.id}\" [label=\"${escapeLabel(n.label)}\"];`); }
|
||||
for(const e of g.edges){ lines.push(` \"${e.from}\" -> \"${e.to}\";`); }
|
||||
lines.push('}'); return lines.join('\n');
|
||||
}
|
||||
|
||||
function escapeLabel(s){ return String(s).replace(/\"/g,'\\\"'); }
|
||||
Reference in New Issue
Block a user