Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

textarea への入力からグラフを表示する #3

Merged
merged 5 commits into from
Oct 8, 2024
Merged
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
11 changes: 11 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,14 @@ jobs:
uses: biomejs/setup-biome@v2
- name: Run Biome
run: biome ci .
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node
uses: actions/setup-node@v4
- name: Install Deps
run: npm clean-install
- name: Test
run: npm run test
9 changes: 9 additions & 0 deletions app/graph/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { Metadata } from "next";

export const metadata: Metadata = {
title: "Graph",
};

export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
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" />
</>
);
}
77 changes: 77 additions & 0 deletions app/graph/parse.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { describe, expect, test } from "vitest";
import { parseGraph } from "./parse";

describe("valid", () => {
test("single node", () => {
expect(parseGraph("1")).toStrictEqual({ n: 1, edges: [] });

expect(
parseGraph(`1
1 1`),
).toStrictEqual({ n: 1, edges: [{ from: 1, to: 1 }] });

expect(
parseGraph(`1
1 1
1 1`),
).toStrictEqual({
n: 1,
edges: [
{ from: 1, to: 1 },
{ from: 1, to: 1 },
],
});
});

test("two nodes", () => {
expect(parseGraph("2")).toStrictEqual({ n: 2, edges: [] });

expect(
parseGraph(`2
1 2`),
).toStrictEqual({ n: 2, edges: [{ from: 1, to: 2 }] });

expect(
parseGraph(`2
1 2
2 1`),
).toStrictEqual({
n: 2,
edges: [
{ from: 1, to: 2 },
{ from: 2, to: 1 },
],
});
});
});

describe("invalid", () => {
test.each([
["0"],
["-1"],
["0.5"],
["ABC"],
[
`4
1 `,
],
[
`4
1 0.5`,
],
[
`4
-1 2`,
],
[
`4
2 7`,
],
[
`4
1 AAA`,
],
])('"%s"', (input) => {
expect(parseGraph(input)).toBe(null);
});
});
34 changes: 34 additions & 0 deletions app/graph/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { z } from "zod";

type Graph = {
n: number;
edges: { from: number; to: number }[];
};

const PositiveInt = z.coerce.number().int().positive();

export function parseGraph(input: string): Graph | null {
const lines = input.trimEnd().split("\n");

const n = PositiveInt.safeParse(lines[0].trim());
if (n.error) {
return null;
}

const NodeIndex = PositiveInt.max(n.data);
const Edge = z.object({
from: NodeIndex,
to: NodeIndex,
});
const edges: Graph["edges"] = [];
for (let i = 1; i < lines.length; i++) {
const [from, to] = lines[i].trim().split(" ");
const e = Edge.safeParse({ from, to });
if (e.error) {
return null;
}
edges.push(e.data);
}

return { n: n.data, edges };
}
Loading