JSFiddle - React, Tailwind, and code Playground
author(s):
Tao Xin
HTML
<script src="https://cdn.jsdelivr.net/gh/vanjs-org/van/public/van-0.12.4.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 = () => {
const displayNum = van.state(0)
let lhs = null, op = null, rhs = 0
const calc = (lhs, op, rhs) => {
const rhsNumber = parseFloat(rhs)
if (!op || lhs === null) return rhsNumber
if (op === "+") return lhs + rhsNumber
if (op === "-") return lhs - rhsNumber
if (op === "x") return lhs * rhsNumber
if (op === "÷") return lhs / rhsNumber
}
const onclick = e => {
const str = e.target.innerText
if (str >= "0" && str <= "9") {
if (rhs) {
if (typeof rhs === "string") rhs += str; else rhs = rhs * 10 + parseInt(str)
} else
rhs = parseInt(str)
} else if (str === "AC") {
lhs = op = null, rhs = 0
} else if (str === "+/-") {
if (rhs) rhs = -rhs
} else if (str === "%") {
if (rhs) rhs *= 0.01
} else if (str === "+" || str === "-" || str === "x" || str === "÷") {
if (rhs !== null) lhs = calc(lhs, op, rhs), rhs = null
op = str
} else if (str === "=") {
if (op && rhs !== null) lhs = calc(lhs, op, rhs), op = null, rhs = null
} else if (str === ".") {
rhs = rhs ? rhs + "." : "0."
}
displayNum.val = rhs ?? lhs
}
const Button = str => div({class: "button"}, button(str))
return div({id: "root"},
div({id: "display"}, div(displayNum)),
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())