-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
53 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,61 @@ | ||
"use client"; | ||
|
||
import { VSpace } from "@/components/VSpace"; | ||
import type cytoscape from "cytoscape"; | ||
import { useRef, useState } from "react"; | ||
import CytoscapeComponent from "react-cytoscapejs"; | ||
import { parseGraph } from "./parse"; | ||
|
||
export default function Graph() { | ||
const elements = [ | ||
{ data: { id: "one", label: "Node 1" }, position: { x: 100, y: 100 } }, | ||
{ data: { id: "two", label: "Node 2" }, position: { x: 200, y: 200 } }, | ||
{ | ||
data: { source: "one", target: "two", label: "Edge from Node1 to Node2" }, | ||
}, | ||
]; | ||
const cyRef = useRef<cytoscape.Core>(); | ||
const [graphText, setGraphText] = useState(""); | ||
const [elements, setElements] = useState<cytoscape.ElementDefinition[]>([]); | ||
|
||
const handleTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { | ||
const value = e.target.value; | ||
const graph = parseGraph(value); | ||
if (graph !== null) { | ||
const width = cyRef.current?.width() ?? 0; | ||
const height = cyRef.current?.height() ?? 0; | ||
const newElements: typeof elements = []; | ||
for (let i = 1; i <= graph.n; i++) { | ||
newElements.push({ | ||
data: { id: `${i}`, label: `Node ${i}` }, | ||
renderedPosition: { | ||
x: (Math.random() + 0.5) * (width / 2), | ||
y: (Math.random() + 0.5) * (height / 2), | ||
}, | ||
}); | ||
} | ||
for (const e of graph.edges) { | ||
newElements.push({ data: { source: `${e.from}`, target: `${e.to}` } }); | ||
} | ||
setElements(newElements); | ||
} | ||
setGraphText(value); | ||
}; | ||
|
||
return ( | ||
<CytoscapeComponent | ||
elements={elements} | ||
style={{ width: "600px", height: "600px" }} | ||
/> | ||
<> | ||
<textarea value={graphText} onChange={handleTextAreaChange} /> | ||
<div /> | ||
<button | ||
type="button" | ||
onClick={() => { | ||
cyRef.current?.layout({ name: "random" }).run(); | ||
}} | ||
> | ||
layout | ||
</button> | ||
<CytoscapeComponent | ||
className="border" | ||
cy={(cy) => { | ||
cyRef.current = cy; | ||
}} | ||
elements={elements} | ||
style={{ width: "100%", height: "80vh" }} | ||
/> | ||
<VSpace size="L" /> | ||
</> | ||
); | ||
} |