JSFiddle - React, Tailwind, and code Playground
author(s):
Tao Xin
HTML
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/vanjs-org/van/public/van-1.6.1.nomodule.min.js"></script>
CSS
html { height: 100%; }
body {
background-color: black;
margin: 0;
padding: 0;
font-size: 10px;
font-family: sans-serif;
height: 100%;
}
@media (min-width: 400px) and (min-height: 400px) {
html { font-size: 20px; }
}
@media (min-width: 500px) and (min-height: 500px) {
html { font-size: 30px; }
}
@media (min-width: 600px) and (min-height: 600px) {
html { font-size: 40px; }
}
@media (min-width: 800px) and (min-height: 800px) {
html { font-size: 50px; }
}
#root {
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 100%;
}
#display {
background-color: #858694;
color: white;
text-align: right;
font-weight: 200;
flex: 0 0 auto;
width: 100%;
}
#display > div {
font-size: 2.5rem;
padding: 0.2rem 0.7rem 0.1rem 0.5rem;
}
#panel {
background-color: #858694;
display: flex;
flex-direction: row;
flex-wrap: wrap;
flex: 1 0 auto;
}
#panel > div {
width: 100%;
margin-bottom: 1px;
flex: 1 0 auto;
display: -ms-flexbox;
display: flex;
}
.button {
display: inline-flex;
width: 25%;
flex: 1 0 auto;
}
.button.wide { width: 50%; }
.button button {
background-color: #e0e0e0;
border: 0;
font-size: 1.5rem;
margin: 0 1px 0 0;
flex: 1 0 auto;
padding: 0;
}
.button:last-child button {
margin-right: 0;
background-color: #f5923e;
color: white;
}
JavaScript
const {button, div} = van.tags
const Calculator = () => {
let lhs = van.state(null), op = null, rhs = van.state(0)
const calc = (lhs, op, rhs) =>
!op || lhs === null ? rhs :
op === "+" ? lhs + rhs :
op === "-" ? lhs - rhs :
op === "x" ? lhs * rhs : lhs / rhs
const onclick = e => {
const str = e.target.innerText
if (str >= "0" && str <= "9")
typeof rhs.val === "string" ? rhs.val += str : rhs.val = rhs.val * 10 + Number(str)
else if (str === "AC") lhs.val = op = null, rhs.val = 0
else if (str === "+/-" && rhs.val) rhs.val = -rhs.val
else if (str === "%" && rhs.val) rhs.val *= 0.01
else if (str === "+" || str === "-" || str === "x" || str === "÷") {
if (rhs.val !== null) lhs.val = calc(lhs.val, op, Number(rhs.val)), rhs.val = null
op = str
} else if (str === "=" && op && rhs.val !== null)
lhs.val = calc(lhs.val, op, Number(rhs.val)), op = null, rhs.val = null
else if (str === ".")
rhs.val = rhs.val ? rhs.val + "." : "0."
}
const Button = str => div({class: "button"}, button(str))
return div({id: "root"},
div({id: "display"}, div(() => rhs.val ?? lhs.val)),
div({id: "panel", onclick},
div(Button("AC"), Button("+/-"), Button("%"), Button("÷")),
div(Button("7"), Button("8"), Button("9"), Button("x")),
div(Button("4"), Button("5"), Button("6"), Button("-")),
div(Button("1"), Button("2"), Button("3"), Button("+")),
div(div({class: "button wide"}, button("0")), Button("."), Button("=")),
),
)
}
van.add(document.body, Calculator())