import React, { useEffect, useRef, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
function App() {
const [inputNum, sqrtNum, message] = quickMath();
const canvasRef = sqrtNum ? showMath(inputNum, sqrtNum) : null;
return (
<div>
<h1>What number do you want to square root?</h1>
<form action="">
<input type="text" id="inputNum" name="inputNum"></input>
<br />
<input type="submit" value="Run the math"></input>
</form>
<h1>{message}</h1>
<br />
<canvas ref={canvasRef} />
</div>
);
}
function quickMath() {
const url = new URL(window.location.href);
const inputNum = url.searchParams.get("inputNum");
if (!inputNum) { return [null, null, null]; }
const sqrtNum = Math.sqrt(Number(inputNum));
const result = (!isNaN(sqrtNum))
? "The square root of " + inputNum + " is " + sqrtNum.toString()
: "There was an an error getting the square root, please try another number!";
return [inputNum, sqrtNum, result];
}
function showMath(inputNum, sqrtNum) {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
ctx.fillStyle = "#dedede";
ctx.fillRect(50, 50, 400, 400);
drawLine(ctx, 50, 50, 200, 50);
}, []);
return canvasRef;
}
function drawLine(ctx, startX, startY, endX, endY) {
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") {
client();
}
function server(req: Request): Promise<Response> {
return new Response(
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>square root</title>
<style>${CSS}</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="${import.meta.url}"></script>
</body>
</html>
`,
{
headers: { "Content-Type": "text/html" },
},
);
}
const CSS = `
body {
text-align: center;
font-family: cursive;