1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react */
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(() => {
// Create canvas
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
// Background color
ctx.fillStyle = "#dedede";
ctx.fillRect(50, 50, 400, 400);
// TODO: draw lines to demonstrate square root idea
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;