|
1 | 1 | "use client";
|
2 | 2 |
|
| 3 | +import { VSpace } from "@/components/VSpace"; |
| 4 | +import type cytoscape from "cytoscape"; |
| 5 | +import { useRef, useState } from "react"; |
3 | 6 | import CytoscapeComponent from "react-cytoscapejs";
|
| 7 | +import { parseGraph } from "./parse"; |
4 | 8 |
|
5 | 9 | export default function Graph() {
|
6 |
| - const elements = [ |
7 |
| - { data: { id: "one", label: "Node 1" }, position: { x: 100, y: 100 } }, |
8 |
| - { data: { id: "two", label: "Node 2" }, position: { x: 200, y: 200 } }, |
9 |
| - { |
10 |
| - data: { source: "one", target: "two", label: "Edge from Node1 to Node2" }, |
11 |
| - }, |
12 |
| - ]; |
| 10 | + const cyRef = useRef<cytoscape.Core>(); |
| 11 | + const [graphText, setGraphText] = useState(""); |
| 12 | + const [elements, setElements] = useState<cytoscape.ElementDefinition[]>([]); |
| 13 | + |
| 14 | + const handleTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { |
| 15 | + const value = e.target.value; |
| 16 | + const graph = parseGraph(value); |
| 17 | + if (graph !== null) { |
| 18 | + const width = cyRef.current?.width() ?? 0; |
| 19 | + const height = cyRef.current?.height() ?? 0; |
| 20 | + const newElements: typeof elements = []; |
| 21 | + for (let i = 1; i <= graph.n; i++) { |
| 22 | + newElements.push({ |
| 23 | + data: { id: `${i}`, label: `Node ${i}` }, |
| 24 | + renderedPosition: { |
| 25 | + x: (Math.random() + 0.5) * (width / 2), |
| 26 | + y: (Math.random() + 0.5) * (height / 2), |
| 27 | + }, |
| 28 | + }); |
| 29 | + } |
| 30 | + for (const e of graph.edges) { |
| 31 | + newElements.push({ data: { source: `${e.from}`, target: `${e.to}` } }); |
| 32 | + } |
| 33 | + setElements(newElements); |
| 34 | + } |
| 35 | + setGraphText(value); |
| 36 | + }; |
| 37 | + |
13 | 38 | return (
|
14 |
| - <CytoscapeComponent |
15 |
| - elements={elements} |
16 |
| - style={{ width: "600px", height: "600px" }} |
17 |
| - /> |
| 39 | + <> |
| 40 | + <textarea value={graphText} onChange={handleTextAreaChange} /> |
| 41 | + <div /> |
| 42 | + <button |
| 43 | + type="button" |
| 44 | + onClick={() => { |
| 45 | + cyRef.current?.layout({ name: "random" }).run(); |
| 46 | + }} |
| 47 | + > |
| 48 | + layout |
| 49 | + </button> |
| 50 | + <CytoscapeComponent |
| 51 | + className="border" |
| 52 | + cy={(cy) => { |
| 53 | + cyRef.current = cy; |
| 54 | + }} |
| 55 | + elements={elements} |
| 56 | + style={{ width: "100%", height: "80vh" }} |
| 57 | + /> |
| 58 | + <VSpace size="L" /> |
| 59 | + </> |
18 | 60 | );
|
19 | 61 | }
|
0 commit comments