JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
import { html, render, useState, useEffect } from "https://unpkg.com/htm/preact/standalone.module.js";
function App() {
const [message, setMessage] = useState("A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution.");
const [hash, setHash] = useState(null);
useEffect(() => {
let cancelled = false;
(async () => {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));;
const hashString = hashArray
.map(byte => byte.toString(2).padStart(8, "0"))
.join("");
if (!cancelled) {
setHash(hashString);
}
})();
return () => {
cancelled = true;
}
}, [message]);
return html`
<div
style=${{
display: "flex",
flexDirection: "column",
alignItems: "center"
}}
>
<textarea
style=${{
alignSelf: "stretch",
border: "1px solid #ccc",
boxShadow: "inset 0 1px 3px rgba(0, 0, 0, 0.2)",
borderRadius: 4,
resize: "none",
padding: "8px 12px",
fontFamily: "sans-serif",
fontSize: 18
}}
rows=${4}
value=${message}
onInput=${(event) => {
setMessage(event.target.value);
}}
/>
<${SHAArrow} />
<div
style=${{
fontFamily: "monospace",
fontSize: 18,
maxWidth: "32ch",
wordBreak: "break-word",
margin: "0 auto",
}}
>
${hash}
</div>
</div>
`;
}
function SHAArrow() {
return html`
<svg width="100" height="auto" viewBox="0 0 144 181" version="1.1">
<g transform="matrix(1,0,0,1,-161.814,-7.10272)">
<g transform="matrix(1,-0,-0,1,161.814,7.10272)">
...