Fixed the dual bulb issue, added new font to typeface package

Signed-off-by: Alexander Lyall <alex@adcm.uk>
This commit is contained in:
2025-12-16 14:27:51 +00:00
parent 8d701a7704
commit 1519032f5b
5 changed files with 508 additions and 309 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -1,5 +1,13 @@
--- ---
import "../styles/binary.css"; import "../styles/binary.css";
// ✅ Vite-bundled JS URL (works in dev + build + preview)
import binaryScriptUrl from "../scripts/binary.js?url";
// If you already have a site-wide Layout that adds header/footer,
// wrap the page with it here.
// Example (uncomment and adjust if you have it):
// import Layout from "../layouts/Layout.astro";
--- ---
<!doctype html> <!doctype html>
@@ -11,26 +19,31 @@ import "../styles/binary.css";
</head> </head>
<body> <body>
<!-- Your site header/footer should already be handled by your layout. <!-- If using Layout, do:
If you *dont* have a layout, tell me and Ill wire it in properly. --> <Layout title="Binary | Computing:Box">
...everything inside <main>...
</Layout>
-->
<main class="wrap"> <main class="wrap">
<section class="topGrid"> <section class="topGrid">
<!-- LEFT: readout + buttons --> <!-- LEFT -->
<div> <div>
<div class="readout"> <div class="readout">
<div class="label">Denary</div> <div class="label">Denary</div>
<div id="denaryNumber" class="num denaryValue">0</div> <div id="denaryNumber" class="num denaryValue">0</div>
<div class="label">Binary</div> <div class="label">Binary</div>
<div id="binaryNumber" class="num binaryValue">0000 0000</div> <div id="binaryNumber" class="num binaryValue">0</div>
<!-- Custom buttons on one line -->
<div class="controlsStack"> <div class="controlsStack">
<div class="controlsRow"> <div class="controlsRow">
<button class="btn btnAccent" id="btnCustomBinary" type="button">Custom Binary</button> <button class="btn btnAccent" id="btnCustomBinary" type="button">Custom Binary</button>
<button class="btn btnAccent" id="btnCustomDenary" type="button">Custom Denary</button> <button class="btn btnAccent" id="btnCustomDenary" type="button">Custom Denary</button>
</div> </div>
<!-- Shift buttons on another line -->
<div class="controlsRow"> <div class="controlsRow">
<button class="btn" id="btnShiftLeft" type="button">Left Shift</button> <button class="btn" id="btnShiftLeft" type="button">Left Shift</button>
<button class="btn" id="btnShiftRight" type="button">Right Shift</button> <button class="btn" id="btnShiftRight" type="button">Right Shift</button>
@@ -40,13 +53,12 @@ import "../styles/binary.css";
<div class="divider"></div> <div class="divider"></div>
<!-- Bits render here -->
<section class="bitsWrap" aria-label="Bit switches"> <section class="bitsWrap" aria-label="Bit switches">
<div class="bitsGrid" id="bitsGrid"></div> <div class="bitsGrid" id="bitsGrid"></div>
</section> </section>
</div> </div>
<!-- RIGHT: mode + tools + bit width --> <!-- RIGHT -->
<aside class="panelCol"> <aside class="panelCol">
<div class="card"> <div class="card">
<div class="cardTitle">Mode</div> <div class="cardTitle">Mode</div>
@@ -67,16 +79,15 @@ import "../styles/binary.css";
</div> </div>
</div> </div>
<!-- Tools: arrows on one row, Reset+Random on one row -->
<div class="card"> <div class="card">
<div class="cardTitle">Tools</div> <div class="cardTitle">Tools</div>
<!-- Spinner row: HORIZONTAL buttons, arrows only -->
<div class="toolRow"> <div class="toolRow">
<button class="toolBtn toolSpin" id="btnDec" type="button" aria-label="Decrement">▼</button> <button class="toolBtn toolSpin" id="btnDec" type="button" aria-label="Decrement">▼</button>
<button class="toolBtn toolSpin" id="btnInc" type="button" aria-label="Increment">▲</button> <button class="toolBtn toolSpin" id="btnInc" type="button" aria-label="Increment">▲</button>
</div> </div>
<!-- Reset + Random on SAME LINE -->
<div class="toolRow2"> <div class="toolRow2">
<button class="toolBtn" id="btnClear" type="button">Reset</button> <button class="toolBtn" id="btnClear" type="button">Reset</button>
<button class="toolBtn" id="btnRandom" type="button">Random</button> <button class="toolBtn" id="btnRandom" type="button">Random</button>
@@ -115,7 +126,7 @@ import "../styles/binary.css";
</section> </section>
</main> </main>
<!-- IMPORTANT: This is the correct Astro/Vite way to reference a JS file in src/ --> <!-- ✅ correct bundled JS reference -->
<script type="module" src={new URL("../scripts/binary.js", import.meta.url)}></script> <script type="module" src={binaryScriptUrl}></script>
</body> </body>
</html> </html>

View File

@@ -1,353 +1,508 @@
// src/scripts/binary.js // src/scripts/binary.js
// Computing:Box — Binary page logic (Unsigned + Two's Complement)
// NOTE: This file is written to match the IDs/classes in your current binary.astro HTML.
document.addEventListener("DOMContentLoaded", () => { (() => {
/* -----------------------------
DOM
----------------------------- */
const bitsGrid = document.getElementById("bitsGrid"); const bitsGrid = document.getElementById("bitsGrid");
const denaryEl = document.getElementById("denaryNumber"); const denaryEl = document.getElementById("denaryNumber");
const binaryEl = document.getElementById("binaryNumber"); const binaryEl = document.getElementById("binaryNumber");
const bitsInput = document.getElementById("bitsInput");
const modeToggle = document.getElementById("modeToggle"); const modeToggle = document.getElementById("modeToggle");
const modeHint = document.getElementById("modeHint"); const modeHint = document.getElementById("modeHint");
const lblUnsigned = document.getElementById("lblUnsigned");
const bitsInput = document.getElementById("bitsInput"); const lblTwos = document.getElementById("lblTwos");
const btnBitsUp = document.getElementById("btnBitsUp");
const btnBitsDown = document.getElementById("btnBitsDown");
const btnCustomBinary = document.getElementById("btnCustomBinary"); const btnCustomBinary = document.getElementById("btnCustomBinary");
const btnCustomDenary = document.getElementById("btnCustomDenary"); const btnCustomDenary = document.getElementById("btnCustomDenary");
const btnShiftLeft = document.getElementById("btnShiftLeft"); const btnShiftLeft = document.getElementById("btnShiftLeft");
const btnShiftRight = document.getElementById("btnShiftRight"); const btnShiftRight = document.getElementById("btnShiftRight");
const btnDec = document.getElementById("btnDec");
const btnInc = document.getElementById("btnInc");
const btnClear = document.getElementById("btnClear"); const btnClear = document.getElementById("btnClear");
const btnRandom = document.getElementById("btnRandom"); const btnRandom = document.getElementById("btnRandom");
const btnInc = document.getElementById("btnInc");
const btnDec = document.getElementById("btnDec");
let bitCount = clampInt(Number(bitsInput.value || 8), 1, 64); const btnBitsUp = document.getElementById("btnBitsUp");
let isTwos = false; const btnBitsDown = document.getElementById("btnBitsDown");
// Bits stored MSB -> LSB (index 0 is MSB) /* -----------------------------
STATE
----------------------------- */
let bitCount = clampInt(Number(bitsInput?.value ?? 8), 1, 64);
// bits[i] is bit value 2^i (LSB at i=0)
let bits = new Array(bitCount).fill(false); let bits = new Array(bitCount).fill(false);
// Random timer // Random run timer (brief)
let randomTimer = null; let randomTimer = null;
/* -----------------------------
HELPERS
----------------------------- */
function clampInt(n, min, max) { function clampInt(n, min, max) {
n = Number(n);
if (!Number.isFinite(n)) return min; if (!Number.isFinite(n)) return min;
n = Math.floor(n); return Math.max(min, Math.min(max, Math.trunc(n)));
return Math.max(min, Math.min(max, n));
} }
function pow2(exp) { function isTwosMode() {
// exp can be up to 63; JS Number is fine for display and basic use here return !!modeToggle?.checked;
return 2 ** exp;
} }
function buildBits(count) { function pow2Big(n) {
bitsGrid.innerHTML = ""; return 1n << BigInt(n);
bits = new Array(count).fill(false); }
bitCount = count;
// Grid wrap at 8 bits per row; also center for small counts function unsignedMaxExclusive(nBits) {
if (count < 8) { return pow2Big(nBits); // 2^n
bitsGrid.classList.add("bitsFew"); }
bitsGrid.style.setProperty("--cols", String(count));
function unsignedMaxValue(nBits) {
return pow2Big(nBits) - 1n;
}
function twosMin(nBits) {
return -pow2Big(nBits - 1);
}
function twosMax(nBits) {
return pow2Big(nBits - 1) - 1n;
}
function bitsToUnsignedBigInt() {
let v = 0n;
for (let i = 0; i < bitCount; i++) {
if (bits[i]) v += pow2Big(i);
}
return v;
}
function unsignedBigIntToBits(vUnsigned) {
const v = ((vUnsigned % unsignedMaxExclusive(bitCount)) + unsignedMaxExclusive(bitCount)) % unsignedMaxExclusive(bitCount);
for (let i = 0; i < bitCount; i++) {
bits[i] = ((v >> BigInt(i)) & 1n) === 1n;
}
}
function bitsToSignedBigIntTwos() {
const u = bitsToUnsignedBigInt();
const signBit = bits[bitCount - 1] === true;
if (!signBit) return u;
// negative: u - 2^n
return u - pow2Big(bitCount);
}
function signedBigIntToBitsTwos(vSigned) {
// wrap into range [-2^(n-1), 2^(n-1)-1]
const min = twosMin(bitCount);
const max = twosMax(bitCount);
const span = pow2Big(bitCount); // 2^n
let v = vSigned;
// wrap using modular arithmetic on signed domain
// Convert to unsigned representative: v mod 2^n
v = ((v % span) + span) % span;
unsignedBigIntToBits(v);
// labels/denary will show signed later
// (No further action needed here)
}
function formatBinaryGrouped() {
// MSB..LSB with a space every 4 bits (matches your screenshot 0000 0000)
let s = "";
for (let i = bitCount - 1; i >= 0; i--) {
s += bits[i] ? "1" : "0";
const posFromRight = (bitCount - i);
if (i !== 0 && posFromRight % 4 === 0) s += " ";
}
return s;
}
function updateModeHint() {
if (!modeHint) return;
if (isTwosMode()) {
modeHint.textContent = "Tip: In twos complement, the left-most bit (MSB) represents a negative value.";
} else {
modeHint.textContent = "Tip: In unsigned binary, all bits represent positive values.";
}
}
/* -----------------------------
BUILD UI (BITS)
----------------------------- */
function buildBits(count) {
bitCount = clampInt(count, 1, 64);
if (bitsInput) bitsInput.value = String(bitCount);
// reset bits array size, preserve existing LSBs where possible
const oldBits = bits.slice();
bits = new Array(bitCount).fill(false);
for (let i = 0; i < Math.min(oldBits.length, bitCount); i++) bits[i] = oldBits[i];
bitsGrid.innerHTML = "";
// If less than 8 bits, centre nicely using your CSS helper
bitsGrid.classList.toggle("bitsFew", bitCount < 8);
if (bitCount < 8) {
bitsGrid.style.setProperty("--cols", String(bitCount));
} else { } else {
bitsGrid.classList.remove("bitsFew");
bitsGrid.style.removeProperty("--cols"); bitsGrid.style.removeProperty("--cols");
} }
for (let i = 0; i < count; i++) { // Render MSB..LSB left-to-right
const isMSB = i === 0; for (let i = bitCount - 1; i >= 0; i--) {
const valueUnsigned = pow2(count - 1 - i); // MSB is 2^(n-1) const bitEl = document.createElement("div");
bitEl.className = "bit";
const bit = document.createElement("div"); // IMPORTANT: We render the bulb as an emoji with NO circle/ring.
bit.className = "bit"; // We do not rely on the .bulb CSS ring/background at all.
bitEl.innerHTML = `
bit.innerHTML = ` <div class="bulb" id="bulb-${i}" aria-hidden="true">💡</div>
<div class="bulb" id="bulb-${i}" aria-hidden="true"></div> <div class="bitVal" id="bitLabel-${i}"></div>
<div class="bitVal" id="label-${i}">${valueUnsigned}</div>
<label class="switch" aria-label="Toggle bit ${i}"> <label class="switch" aria-label="Toggle bit ${i}">
<input type="checkbox" data-index="${i}"> <input type="checkbox" data-index="${i}">
<span class="slider"></span> <span class="slider"></span>
</label> </label>
`; `;
bitsGrid.appendChild(bit); bitsGrid.appendChild(bitEl);
} }
hookSwitches(); // Hook switches
updateModeLabels(); bitsGrid.querySelectorAll('input[type="checkbox"]').forEach((input) => {
updateReadout();
}
function hookSwitches() {
bitsGrid.querySelectorAll('input[type="checkbox"][data-index]').forEach((input) => {
input.addEventListener("change", () => { input.addEventListener("change", () => {
const i = Number(input.dataset.index); const i = Number(input.dataset.index);
bits[i] = input.checked; bits[i] = input.checked;
updateReadout(); updateUI();
}); });
}); });
}
function updateModeLabels() { // Force the bulb to be "just the emoji" (removes the circle even if CSS adds it)
isTwos = Boolean(modeToggle.checked);
modeHint.textContent = isTwos
? "Tip: In twos complement, the left-most bit (MSB) represents a negative value."
: "Tip: In unsigned binary, all bits represent positive values.";
// Update the labels so the MSB shows negative weight in two's complement
for (let i = 0; i < bitCount; i++) {
const label = document.getElementById(`label-${i}`);
if (!label) continue;
const unsignedWeight = pow2(bitCount - 1 - i);
if (isTwos && i === 0) {
// MSB weight is negative
label.textContent = `-${unsignedWeight}`;
} else {
label.textContent = `${unsignedWeight}`;
}
}
}
function formatBinaryString(raw) {
// group every 4 for readability (keeps your "0000 0000" look)
return raw.replace(/(.{4})/g, "$1 ").trim();
}
function computeUnsignedValue() {
let value = 0;
for (let i = 0; i < bitCount; i++) {
if (!bits[i]) continue;
value += pow2(bitCount - 1 - i);
}
return value;
}
function computeTwosValue() {
// If MSB is 0 -> same as unsigned
const msb = bits[0] ? 1 : 0;
let value = computeUnsignedValue();
if (msb === 1) {
// subtract 2^n to get signed negative value
value -= pow2(bitCount);
}
return value;
}
function updateReadout() {
// Binary string (MSB->LSB)
const rawBinary = bits.map((b) => (b ? "1" : "0")).join("");
binaryEl.textContent = formatBinaryString(rawBinary);
// Denary value based on mode
const denary = isTwos ? computeTwosValue() : computeUnsignedValue();
denaryEl.textContent = String(denary);
// Bulbs MUST update in BOTH modes (this was your reported bug)
for (let i = 0; i < bitCount; i++) { for (let i = 0; i < bitCount; i++) {
const bulb = document.getElementById(`bulb-${i}`); const bulb = document.getElementById(`bulb-${i}`);
if (!bulb) continue; if (!bulb) continue;
bulb.classList.toggle("on", bits[i]);
// Strip the ring/circle coming from CSS
bulb.style.width = "auto";
bulb.style.height = "auto";
bulb.style.border = "none";
bulb.style.background = "transparent";
bulb.style.borderRadius = "0";
bulb.style.boxShadow = "none";
bulb.style.opacity = "0.45";
bulb.style.fontSize = "26px";
bulb.style.lineHeight = "1";
bulb.style.display = "flex";
bulb.style.alignItems = "center";
bulb.style.justifyContent = "center";
bulb.style.filter = "grayscale(1)";
bulb.textContent = "💡";
}
updateUI();
}
/* -----------------------------
UI UPDATE (READOUT + LABELS + BULBS + SWITCHES)
----------------------------- */
function updateBitLabels() {
// Show weights under each bit.
// Unsigned: 2^i
// Two's: MSB is -2^(n-1), others are 2^i
for (let i = 0; i < bitCount; i++) {
const label = document.getElementById(`bitLabel-${i}`);
if (!label) continue;
if (isTwosMode() && i === bitCount - 1) {
label.textContent = `-${pow2Big(bitCount - 1).toString()}`;
} else {
label.textContent = pow2Big(i).toString();
}
} }
} }
function syncInputs() { function syncSwitchesToBits() {
bitsGrid.querySelectorAll('input[type="checkbox"][data-index]').forEach((input) => { bitsGrid.querySelectorAll('input[type="checkbox"]').forEach((input) => {
const i = Number(input.dataset.index); const i = Number(input.dataset.index);
input.checked = Boolean(bits[i]); input.checked = !!bits[i];
}); });
}
function updateBulbs() {
// Bulbs should ALWAYS reflect bits, regardless of mode.
for (let i = 0; i < bitCount; i++) {
const bulb = document.getElementById(`bulb-${i}`);
if (!bulb) continue;
const on = bits[i] === true;
// Make it look "lit" when on (no circle, just glow)
if (on) {
bulb.style.opacity = "1";
bulb.style.filter = "grayscale(0)";
bulb.style.textShadow = "0 0 14px rgba(255,216,107,.75), 0 0 26px rgba(255,216,107,.45)";
} else {
bulb.style.opacity = "0.45";
bulb.style.filter = "grayscale(1)";
bulb.style.textShadow = "none";
}
}
}
function updateReadout() {
if (!denaryEl || !binaryEl) return;
if (isTwosMode()) {
const signed = bitsToSignedBigIntTwos();
denaryEl.textContent = signed.toString();
} else {
const unsigned = bitsToUnsignedBigInt();
denaryEl.textContent = unsigned.toString();
}
binaryEl.textContent = formatBinaryGrouped();
}
function updateUI() {
updateModeHint();
updateBitLabels();
syncSwitchesToBits();
updateBulbs();
updateReadout(); updateReadout();
} }
function setAllBits(off = true) { /* -----------------------------
bits = bits.map(() => !off); SET FROM BINARY STRING
syncInputs(); ----------------------------- */
function setFromBinaryString(binStr) {
const clean = String(binStr ?? "").replace(/\s+/g, "");
if (!/^[01]+$/.test(clean)) return false;
// Use rightmost bitCount bits; left pad with 0
const padded = clean.slice(-bitCount).padStart(bitCount, "0");
for (let i = 0; i < bitCount; i++) {
// padded is MSB..LSB, bits[] is LSB..MSB
const charFromRight = padded[padded.length - 1 - i];
bits[i] = charFromRight === "1";
}
updateUI();
return true;
} }
/* -----------------------------
SET FROM DENARY INPUT
----------------------------- */
function setFromDenaryInput(vStr) {
const raw = String(vStr ?? "").trim();
if (!raw) return false;
// BigInt parse (supports negatives)
let v;
try {
// Allow normal integers only
if (!/^-?\d+$/.test(raw)) return false;
v = BigInt(raw);
} catch {
return false;
}
if (isTwosMode()) {
// Clamp to representable range
const min = twosMin(bitCount);
const max = twosMax(bitCount);
if (v < min || v > max) return false;
signedBigIntToBitsTwos(v);
} else {
// Unsigned only
if (v < 0n) return false;
if (v > unsignedMaxValue(bitCount)) return false;
unsignedBigIntToBits(v);
}
updateUI();
return true;
}
/* -----------------------------
SHIFTS
----------------------------- */
function shiftLeft() { function shiftLeft() {
// left shift: drop MSB, append 0 at LSB // logical left shift: bits move to higher index; LSB becomes 0
bits.shift(); for (let i = bitCount - 1; i >= 1; i--) {
bits.push(false); bits[i] = bits[i - 1];
syncInputs(); }
bits[0] = false;
updateUI();
} }
function shiftRight() { function shiftRight() {
// right shift: drop LSB, prepend 0 at MSB // logical right shift: bits move to lower index; MSB becomes 0
bits.pop(); for (let i = 0; i < bitCount - 1; i++) {
bits.unshift(false); bits[i] = bits[i + 1];
syncInputs();
}
function setFromBinary(input) {
const clean = String(input).replace(/\s+/g, "");
if (!/^[01]+$/.test(clean)) return false;
const padded = clean.slice(-bitCount).padStart(bitCount, "0");
bits = [...padded].map((ch) => ch === "1");
syncInputs();
return true;
}
function setFromDenary(input) {
let n = Number(input);
if (!Number.isInteger(n)) return false;
// For unsigned mode: allow 0..(2^n - 1)
// For two's mode: allow -(2^(n-1))..(2^(n-1)-1)
const maxUnsigned = pow2(bitCount) - 1;
const minTwos = -pow2(bitCount - 1);
const maxTwos = pow2(bitCount - 1) - 1;
if (!isTwos) {
if (n < 0 || n > maxUnsigned) return false;
// build bits from unsigned n
bits = new Array(bitCount).fill(false);
for (let i = 0; i < bitCount; i++) {
const weight = pow2(bitCount - 1 - i);
if (n >= weight) {
bits[i] = true;
n -= weight;
}
}
syncInputs();
return true;
} }
bits[bitCount - 1] = false;
updateUI();
}
// Two's complement: convert signed integer to n-bit representation /* -----------------------------
if (n < minTwos || n > maxTwos) return false; CLEAR / INC / DEC
----------------------------- */
let u = n; function clearAll() {
if (u < 0) u = pow2(bitCount) + u; // wrap into unsigned range bits.fill(false);
const bin = u.toString(2).padStart(bitCount, "0"); updateUI();
bits = [...bin].map((ch) => ch === "1");
syncInputs();
return true;
} }
function increment() { function increment() {
// increment the underlying value in current mode, wrap appropriately if (isTwosMode()) {
if (!isTwos) { const min = twosMin(bitCount);
const max = pow2(bitCount) - 1; const max = twosMax(bitCount);
let v = computeUnsignedValue(); let v = bitsToSignedBigIntTwos() + 1n;
v = (v + 1) % (max + 1); if (v > max) v = min; // wrap
setFromDenary(v); signedBigIntToBitsTwos(v);
return; } else {
const span = unsignedMaxExclusive(bitCount);
const v = (bitsToUnsignedBigInt() + 1n) % span;
unsignedBigIntToBits(v);
} }
updateUI();
const min = -pow2(bitCount - 1);
const max = pow2(bitCount - 1) - 1;
let v = computeTwosValue();
v = v + 1;
if (v > max) v = min; // wrap
setFromDenary(v);
} }
function decrement() { function decrement() {
if (!isTwos) { if (isTwosMode()) {
const max = pow2(bitCount) - 1; const min = twosMin(bitCount);
let v = computeUnsignedValue(); const max = twosMax(bitCount);
v = v - 1; let v = bitsToSignedBigIntTwos() - 1n;
if (v < 0) v = max; if (v < min) v = max; // wrap
setFromDenary(v); signedBigIntToBitsTwos(v);
return; } else {
const span = unsignedMaxExclusive(bitCount);
const v = (bitsToUnsignedBigInt() - 1n + span) % span;
unsignedBigIntToBits(v);
} }
updateUI();
const min = -pow2(bitCount - 1);
const max = pow2(bitCount - 1) - 1;
let v = computeTwosValue();
v = v - 1;
if (v < min) v = max;
setFromDenary(v);
} }
function startAutoRandom() { /* -----------------------------
stopAutoRandom(); RANDOM (FIXED: NO BigInt->Number Math.min)
----------------------------- */
function cryptoRandomBigInt(maxExclusive) {
// returns 0 <= x < maxExclusive
if (maxExclusive <= 0n) return 0n;
const durationMs = 1200; // runs briefly then stops const bitLen = maxExclusive.toString(2).length;
const tickMs = 90; const byteLen = Math.ceil(bitLen / 8);
// Rejection sampling
while (true) {
const bytes = new Uint8Array(byteLen);
crypto.getRandomValues(bytes);
let x = 0n;
for (const b of bytes) {
x = (x << 8n) | BigInt(b);
}
// mask down to bitLen to reduce rejections slightly
const extraBits = BigInt(byteLen * 8 - bitLen);
if (extraBits > 0n) x = x >> extraBits;
if (x < maxExclusive) return x;
}
}
function setRandomOnce() {
if (isTwosMode()) {
const span = unsignedMaxExclusive(bitCount); // 2^n
const u = cryptoRandomBigInt(span); // 0..2^n-1
unsignedBigIntToBits(u);
} else {
const span = unsignedMaxExclusive(bitCount);
const u = cryptoRandomBigInt(span);
unsignedBigIntToBits(u);
}
updateUI();
}
function runRandomBriefly() {
// stop any existing run
if (randomTimer) {
clearInterval(randomTimer);
randomTimer = null;
}
const start = Date.now(); const start = Date.now();
randomTimer = window.setInterval(() => { const durationMs = 900; // brief run then stop
// pick a random representable number depending on mode const tickMs = 80;
let target;
if (!isTwos) {
target = Math.floor(Math.random() * (pow2(bitCount)));
} else {
const min = -pow2(bitCount - 1);
const max = pow2(bitCount - 1) - 1;
target = min + Math.floor(Math.random() * (max - min + 1));
}
setFromDenary(target);
if (Date.now() - start >= durationMs) stopAutoRandom(); randomTimer = setInterval(() => {
setRandomOnce();
if (Date.now() - start >= durationMs) {
clearInterval(randomTimer);
randomTimer = null;
}
}, tickMs); }, tickMs);
} }
function stopAutoRandom() { /* -----------------------------
if (randomTimer !== null) { BIT WIDTH CONTROLS
window.clearInterval(randomTimer); ----------------------------- */
randomTimer = null; function setBitWidth(n) {
} const v = clampInt(n, 1, 64);
buildBits(v);
} }
// MODE toggle /* -----------------------------
modeToggle.addEventListener("change", () => { EVENTS
updateModeLabels(); ----------------------------- */
updateReadout(); modeToggle?.addEventListener("change", () => {
updateUI();
}); });
// Bit width btnCustomBinary?.addEventListener("click", () => {
btnBitsUp.addEventListener("click", () => { const v = prompt(`Enter binary (spaces allowed). Current width: ${bitCount} bits`);
const next = clampInt(bitCount + 1, 1, 64); if (v === null) return;
bitsInput.value = String(next); if (!setFromBinaryString(v)) alert("Invalid binary");
buildBits(next);
}); });
btnBitsDown.addEventListener("click", () => { btnCustomDenary?.addEventListener("click", () => {
const next = clampInt(bitCount - 1, 1, 64); const v = prompt(
bitsInput.value = String(next); isTwosMode()
buildBits(next); ? `Enter denary (${twosMin(bitCount).toString()} to ${twosMax(bitCount).toString()}):`
: `Enter denary (0 to ${unsignedMaxValue(bitCount).toString()}):`
);
if (v === null) return;
if (!setFromDenaryInput(v)) alert("Invalid denary for current mode/bit width");
}); });
bitsInput.addEventListener("change", () => { btnShiftLeft?.addEventListener("click", shiftLeft);
const next = clampInt(bitsInput.value, 1, 64); btnShiftRight?.addEventListener("click", shiftRight);
bitsInput.value = String(next);
buildBits(next); btnInc?.addEventListener("click", increment);
btnDec?.addEventListener("click", decrement);
btnClear?.addEventListener("click", clearAll);
btnRandom?.addEventListener("click", runRandomBriefly);
btnBitsUp?.addEventListener("click", () => setBitWidth(bitCount + 1));
btnBitsDown?.addEventListener("click", () => setBitWidth(bitCount - 1));
bitsInput?.addEventListener("change", () => {
setBitWidth(Number(bitsInput.value));
}); });
// Buttons /* -----------------------------
btnShiftLeft.addEventListener("click", shiftLeft); INIT
btnShiftRight.addEventListener("click", shiftRight); ----------------------------- */
updateModeHint();
btnCustomBinary.addEventListener("click", () => {
const val = prompt(`Enter a ${bitCount}-bit binary number:`);
if (val === null) return;
if (!setFromBinary(val)) alert("Invalid binary input (use only 0 and 1).");
});
btnCustomDenary.addEventListener("click", () => {
const modeRange = isTwos
? `(${ -pow2(bitCount - 1) } to ${ pow2(bitCount - 1) - 1 })`
: `(0 to ${ pow2(bitCount) - 1 })`;
const val = prompt(`Enter a denary number ${modeRange}:`);
if (val === null) return;
if (!setFromDenary(val)) alert("Invalid denary input for the current mode/bit width.");
});
btnClear.addEventListener("click", () => setAllBits(true));
btnRandom.addEventListener("click", startAutoRandom);
btnInc.addEventListener("click", increment);
btnDec.addEventListener("click", decrement);
// INIT
modeToggle.checked = false;
updateModeLabels();
buildBits(bitCount); buildBits(bitCount);
}); })();

View File

@@ -1,19 +1,34 @@
:root{ :root{
--bg: #1f2027; --bg: #1f2027;
--panel: #22242d;
--panel2: rgba(255,255,255,.04); --panel2: rgba(255,255,255,.04);
--text: #e8e8ee; --text: #e8e8ee;
--muted: #a9acb8; --muted: #a9acb8;
--accent: #33ff7a; --accent: #33ff7a;
--accent-dim: rgba(51,255,122,.15); --accent-dim: rgba(51,255,122,.15);
--line: rgba(255,255,255,.12); --line: rgba(255,255,255,.12);
--danger: #e24444;
--danger-dim: rgba(226,68,68,.22);
--success: #2fd66b;
--success-dim: rgba(47,214,107,.22);
} }
/* -------- Fonts -------- */
@font-face{ @font-face{
font-family: "DSEG7ClassicRegular"; font-family: "DSEG7ClassicRegular";
src: src:
url("/fonts/DSEG7Classic-Regular.ttf") format("truetype"), url("/fonts/DSEG7Classic-Regular.woff") format("woff"),
url("/fonts/DSEG7Classic-Regular.woff") format("woff"); url("/fonts/DSEG7Classic-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face{
font-family: "SevenSegment";
src:
url("/fonts/Seven-Segment.woff2") format("woff2"),
url("/fonts/Seven-Segment.woff") format("woff");
font-weight: 400; font-weight: 400;
font-style: normal; font-style: normal;
font-display: swap; font-display: swap;
@@ -21,7 +36,7 @@
body{ body{
margin:0; margin:0;
font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; font-family: "SevenSegment", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
background: var(--bg); background: var(--bg);
color: var(--text); color: var(--text);
} }
@@ -40,7 +55,6 @@ body{
} }
.readout{ .readout{
background: transparent;
text-align:center; text-align:center;
padding: 10px 10px 0; padding: 10px 10px 0;
} }
@@ -54,6 +68,7 @@ body{
margin-top: 10px; margin-top: 10px;
} }
/* Anything that is a number uses DSEG7 */
.num{ .num{
font-family: "DSEG7ClassicRegular", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-family: "DSEG7ClassicRegular", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-weight: 400; font-weight: 400;
@@ -62,17 +77,17 @@ body{
} }
.denaryValue{ .denaryValue{
font-size: 70px; /* smaller than before */ font-size: 70px;
line-height: 1.0; line-height: 1.0;
margin: 6px 0 10px; margin: 6px 0 10px;
} }
.binaryValue{ .binaryValue{
font-size: 52px; /* smaller than before */ font-size: 52px;
letter-spacing: .12em; letter-spacing: .12em;
line-height: 1.0; line-height: 1.0;
margin: 6px 0 14px; margin: 6px 0 14px;
white-space: pre; /* keep spaces */ white-space: pre;
} }
.controlsStack{ .controlsStack{
@@ -99,6 +114,7 @@ body{
font-weight: 700; font-weight: 700;
cursor: pointer; cursor: pointer;
min-width: 170px; min-width: 170px;
font-family: "SevenSegment", system-ui, sans-serif;
} }
.btn:active{ transform: translateY(1px); } .btn:active{ transform: translateY(1px); }
@@ -152,9 +168,10 @@ body{
color: var(--text); color: var(--text);
font-weight: 700; font-weight: 700;
font-size: 14px; font-size: 14px;
font-family: "SevenSegment", system-ui, sans-serif;
} }
/* Shared toggle switch (mode + bit switches) */ /* Switch */
.switch{ .switch{
position: relative; position: relative;
width: 56px; width: 56px;
@@ -195,14 +212,13 @@ body{
background: var(--accent); background: var(--accent);
} }
/* Tools card layout */ /* Tools layout */
.toolRow{ .toolRow{
display:grid; display:grid;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
gap: 10px; gap: 10px;
margin-bottom: 10px; margin-bottom: 10px;
} }
.toolRow2{ .toolRow2{
display:grid; display:grid;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
@@ -217,10 +233,26 @@ body{
color: #fff; color: #fff;
cursor: pointer; cursor: pointer;
font-weight: 800; font-weight: 800;
font-family: "SevenSegment", system-ui, sans-serif;
} }
/* Narrower arrow buttons (only the arrow pair) */
.toolSpin{ .toolSpin{
font-size: 22px; /* bigger spin feature */ font-size: 22px;
height: 48px;
max-width: 120px; /* narrower */
justify-self: start;
padding: 0;
}
/* Down = red, Up = green */
#btnDec{
background: var(--danger-dim);
border-color: rgba(226,68,68,.45);
}
#btnInc{
background: var(--success-dim);
border-color: rgba(47,214,107,.45);
} }
/* Bit width control */ /* Bit width control */
@@ -240,6 +272,7 @@ body{
cursor:pointer; cursor:pointer;
font-weight:900; font-weight:900;
font-size:18px; font-size:18px;
font-family: "SevenSegment", system-ui, sans-serif;
} }
.bitInputWrap{ .bitInputWrap{
@@ -258,6 +291,7 @@ body{
font-weight:800; font-weight:800;
letter-spacing:.18em; letter-spacing:.18em;
text-transform:uppercase; text-transform:uppercase;
font-family: "SevenSegment", system-ui, sans-serif;
} }
.bitInput{ .bitInput{
width:86px; width:86px;
@@ -275,18 +309,20 @@ body{
margin:0; margin:0;
} }
/* Bits area (wrap every 8 bits, centered) */ /* Bits: wrap every 8, centred */
.bitsWrap{ .bitsWrap{
margin-top: 22px; margin-top: 22px;
} }
.bitsGrid{ .bitsGrid{
display:grid; display:grid;
gap: 18px; gap: 18px;
justify-content:center; justify-content:center;
grid-template-columns: repeat(8, minmax(90px, 1fr)); /* wraps at 8 */ grid-template-columns: repeat(8, minmax(90px, 1fr));
padding-top: 18px; padding-top: 18px;
} }
.bitsGrid.bitsFew{
grid-template-columns: repeat(var(--cols, 4), minmax(90px, 1fr));
}
.bit{ .bit{
display:flex; display:flex;
@@ -297,36 +333,38 @@ body{
text-align:center; text-align:center;
} }
/* Bulb like 💡” but consistent + bigger */ /* Bulb (emoji only — no circle, no ::before so it won't duplicate) */
.bulb{ .bulb{
width: 34px; /* bigger */ width: auto;
height: 34px; /* bigger */ height: auto;
border-radius: 50%; border: none;
background: rgba(255,255,255,.08); background: transparent;
border: 1px solid rgba(255,255,255,.12); border-radius: 0;
box-shadow: none; box-shadow: none;
display:flex; display:flex;
align-items:center; align-items:center;
justify-content:center; justify-content:center;
font-size: 20px;
font-size: 26px;
line-height: 1; line-height: 1;
opacity: .55; opacity: .45;
}
.bulb::before{
content: "💡";
filter: grayscale(1); filter: grayscale(1);
} text-shadow: none;
.bulb.on{
opacity: 1;
background: rgba(255,216,107,.18);
border-color: rgba(255,216,107,.55);
box-shadow: 0 0 18px rgba(255,216,107,.45);
}
.bulb.on::before{
filter: grayscale(0);
} }
/* Bit value (MSB becomes negative in twos mode via JS label text) */ /* IMPORTANT: remove the pseudo-element that was causing the 2nd bulb */
.bulb::before{
content: none;
}
.bulb.on{
opacity: 1;
filter: grayscale(0);
text-shadow: 0 0 14px rgba(255,216,107,.75), 0 0 26px rgba(255,216,107,.45);
}
/* Bit value numbers use DSEG7 */
.bitVal{ .bitVal{
font-family:"DSEG7ClassicRegular", ui-monospace, monospace; font-family:"DSEG7ClassicRegular", ui-monospace, monospace;
font-size: 28px; font-size: 28px;
@@ -336,11 +374,6 @@ body{
min-height: 32px; min-height: 32px;
} }
/* Make sure small bit counts still look centered/nice */
.bitsGrid.bitsFew{
grid-template-columns: repeat(var(--cols, 4), minmax(90px, 1fr));
}
@media (max-width: 980px){ @media (max-width: 980px){
.topGrid{ grid-template-columns: 1fr; } .topGrid{ grid-template-columns: 1fr; }
.denaryValue{ font-size: 62px; } .denaryValue{ font-size: 62px; }