Skip to content

Commit

Permalink
グラフを表示する
Browse files Browse the repository at this point in the history
  • Loading branch information
ia7ck committed Oct 7, 2024
1 parent 307ea38 commit 2e5068b
Showing 1 changed file with 53 additions and 11 deletions.
64 changes: 53 additions & 11 deletions app/graph/page.tsx
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" />
</>
);
}

0 comments on commit 2e5068b

Please sign in to comment.