<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[The daily mini game.]]></title><description><![CDATA[The daily mini game.]]></description><link>https://minigamedaily.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b059ae47b492aefb2b6bb58/bf96df10-500c-40a0-8759-32dc89deb1ef.png</url><title>The daily mini game.</title><link>https://minigamedaily.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 21:58:27 GMT</lastBuildDate><atom:link href="https://minigamedaily.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[4 Zero-Build Browser UX Fixes: Split Credit Wallets, Lazy Audio Mutexes, Grid Overlays & Top-Layer Dialogs]]></title><description><![CDATA[Four vanilla JS & CSS browser UX fixes: split credit wallets, lazy audio mutexes, non-clipping CSS Grid overlays, and top-layer dialogs.]]></description><link>https://minigamedaily.hashnode.dev/4-zero-build-browser-ux-fixes-split-credit-wallets-lazy-audio-mutexes-grid-overlays-top-layer-dialogs</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/4-zero-build-browser-ux-fixes-split-credit-wallets-lazy-audio-mutexes-grid-overlays-top-layer-dialogs</guid><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Fri, 04 Dec 2026 08:20:58 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://calendrieraventenligne.com/_a/share.1e3a1a6dc8.png" alt="Calendrier Avent en Ligne — interactive French online Advent calendar" /></p>
<p>When you ship a zero-framework browser utility that runs without accounts or forced email capture, the bugs that actually hurt conversion are rarely dramatic crashes. They are small, quiet friction points: a modal overlay clipping its bottom button on a 375px phone screen, a multi-second loading spinner before telling a guest they have zero paid credits, or two <code>&lt;audio&gt;</code> players accidentally singing over each other.</p>
<p>While upgrading <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a>—a free French-first interactive online Advent calendar supporting personal gift boxes and collaborative <a href="https://calendrieraventenligne.com/entre-amis">Entre amis</a> countdowns—we audited every mobile and desktop interaction and fixed four concrete browser patterns in plain HTML, CSS, and vanilla JS.</p>
<p>Here are the exact bugs we hit and the zero-dependency patterns we shipped to solve them (with reusable helpers published in our MIT repo <a href="https://github.com/sunrain113/advent-ics-midnight-js"><code>advent-ics-midnight-js</code></a>).</p>
<hr />
<h2>1. Never Make a Zero-Balance Guest Wait 4 Seconds for a <code>401</code></h2>
<p>One subtle architectural trap in browser tools with both <strong>free earned credits</strong> (stored locally in <code>localStorage</code> for cosmetic themes) and <strong>optional purchased credits</strong> (stored server-side for heavier AI features like a 24-door idea generator or a custom French Christmas song) is hiding the distinction behind a single balance badge.</p>
<p>We originally rendered one combined <code>❄️ 2</code> pill in the header. A visitor with <code>2</code> free welcome credits would click an AI tool costing <code>5</code> purchased credits, watch a progress bar animate for 3–5 seconds, and only then get an error from the server.</p>
<p>Two small changes eliminated that dead end completely:</p>
<ol>
<li><strong>Always split the two wallets in the UI</strong> (<code>Flocons gratuits</code> vs. <code>Flocons achetés</code>) so visitors immediately understand which balance unlocks cosmetic door wraps (<code>2–4 ❄️</code>) versus server-side AI features (<code>5 ❄️</code> / <code>15 ❄️</code>).</li>
<li><strong>Pre-check <code>meLoaded &amp;&amp; paidCredits &lt; cost</code> synchronously before firing <code>fetch()</code></strong>, while keeping a clean one-click free fallback right inside the upsell panel:</li>
</ol>
<pre><code class="language-js">function canStartPaidAction({ meLoaded, paidCredits, cost }) {
  if (!meLoaded) {
    // Session state not hydrated yet; defer to server validation.
    return { allowed: true, reason: "pending_hydration" };
  }
  if (Number(paidCredits) &lt; Number(cost)) {
    return {
      allowed: false,
      reason: "not_enough_credits",
      missing: Math.max(0, Number(cost) - Number(paidCredits)),
    };
  }
  return { allowed: true, reason: "ok" };
}
</code></pre>
<p>We applied the same friction-removal principle to optional paid door wraps on <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a>: if a creator experiments with a <code>4 ❄️</code> luxury wrap on Door 1 while holding <code>2 ❄️</code> and clicks <em>Create</em>, the modal shows both the top-up packs <strong>and</strong> a one-click <em>"Create for free without paid wraps"</em> button that resets paid wraps to standard paper (<code>0 ❄️</code>) and submits the form automatically. Zero trapped drafts.</p>
<hr />
<h2>2. Lazy-Loading Real <code>&lt;audio&gt;</code> Previews With a 6-Line Playback Mutex</h2>
<p>Adding a real sung MP3 sample dramatically improves trust compared to describing an AI song in text, especially when the demo appears in three different surfaces (the inline door editor, the standalone song dialog, and the post-creation spotlight card).</p>
<p>However, embedding three <code>&lt;audio&gt;</code> tags carelessly causes two immediate regressions:</p>
<ul>
<li>Browsers eagerly download megabytes of MP3 metadata on initial page load, hurting mobile LCP.</li>
<li>Visitors who play the sample inside the page and then open a modal sample hear two tracks overlapping.</li>
</ul>
<p>Pairing <code>loading="lazy"</code> with <code>preload="none"</code> and <code>controls</code> keeps initial transfer at <strong>0 bytes</strong> until the visitor explicitly presses Play, and a single delegated capturing <code>play</code> listener coordinates every <code>&lt;audio&gt;</code> element inside the tool root:</p>
<pre><code class="language-html">&lt;figure class="adv-demo-audio"&gt;
  &lt;figcaption&gt;Real French sample&lt;/figcaption&gt;
  &lt;audio controls loading="lazy" preload="none" src="/_a/demo-chanson-noel.4a2cf092ce.mp3"&gt;&lt;/audio&gt;
&lt;/figure&gt;
</code></pre>
<pre><code class="language-js">// Capture phase is required because HTMLMediaElement "play" does not bubble.
root.addEventListener("play", (event) =&gt; {
  if (!event.target || event.target.tagName !== "AUDIO") return;
  root.querySelectorAll("audio").forEach((audioEl) =&gt; {
    if (audioEl !== event.target) {
      try { audioEl.pause(); } catch (_) {}
    }
  });
}, true);
</code></pre>
<p>Notice the third argument <code>true</code> (<code>useCapture</code>): <code>HTMLMediaElement</code>'s <code>play</code> event does <strong>not</strong> bubble, so a normal bubbling listener on <code>root</code> will silently never fire!</p>
<hr />
<h2>3. Fixing Mobile Overlay Clipping Without Fixed Heights or <code>order</code> Hacks</h2>
<p>On narrow mobile viewports (<code>375×812</code>), an <code>overflow: hidden</code> stage container with a fixed <code>224px</code> canvas and a <code>position: absolute; inset: 0; justify-content: center;</code> end-screen overlay is a classic clipping bug: as soon as the end-screen displays a score, reward pill, primary CTA, and two share buttons (~310px tall), <code>justify-content: center</code> pushes the top heading and bottom button right past the clipped edges.</p>
<p>Replacing <code>position: absolute</code> with a <strong>shared CSS Grid cell</strong> (<code>grid-area: 1 / 1</code>) plus <code>min-block-size</code> and <code>justify-content: safe center</code> solves both idle compactness and dynamic end-screen height in 10 lines of CSS:</p>
<pre><code class="language-css">.stage-board {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  min-block-size: 224px;
  overflow: hidden;
}

.stage-canvas,
.stage-overlay {
  grid-area: 1 / 1;
}

.stage-overlay {
  position: relative;
  width: 100%;
  min-block-size: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: safe center;
  z-index: 4;
}
</code></pre>
<p>When the idle overlay is shorter than <code>224px</code>, the board stays compact so the primary Start button remains above the fold. When the end-screen expands to <code>368px</code>, the shared grid track grows naturally with zero top/bottom clipping—and <code>safe center</code> prevents scroll-inaccessible top overflow on extra-narrow viewports.</p>
<p>Similarly, when making mobile forms easier to reach on <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a>, we resisted using CSS <code>order: -1</code> to visually flip the form above the calendar grid—because CSS <code>order</code> decouples visual order from DOM/keyboard Tab focus order. Instead, we kept natural DOM order, added a compact mobile quick-jump CTA bar above the grid, and folded the empty collaborative preview to 2 rows (8 doors) on narrow screens.</p>
<hr />
<h2>4. Opaque Top-Layer <code>&lt;dialog&gt;</code> Polish &amp; Honest Copy</h2>
<p>Native HTML <code>&lt;dialog&gt;</code> with <code>closedby="any"</code> and discrete <code>@starting-style</code> transitions removes the need for heavy modal libraries, but two small details showed up during live mobile QA:</p>
<ol>
<li><strong>Explicitly style non-transparent surfaces on <code>dialog:not(.fullscreen-stage)</code></strong>: leaving background inheritance ambiguous caused subtle visual bleed on dark backdrops, whereas explicit <code>background: #FFFFFF; max-height: 90dvh; overflow-y: auto; overscroll-behavior: contain;</code> with a crisp <code>0.16s</code> transition feels native on both iOS Safari and Android Chrome.</li>
<li><strong>Keep every UI promise 100% accurate</strong>: we caught a micro-copy line claiming doors were <em>"editable after creation"</em> when our zero-account <code>#owner=</code> architecture actually lets creators edit freely <em>before</em> creation and moderate/preview/delete <em>after</em> creation. Tightening that wording across the studio, our <a href="https://calendrieraventenligne.com/idees-cases">24 French Advent calendar ideas guide</a>, our <a href="https://calendrieraventenligne.com/entreprise">team &amp; HR guide</a>, and our <a href="https://calendrieraventenligne.com/comparatif">objective 8-tool 2026 comparison</a> keeps user expectations aligned with real behavior.</li>
</ol>
<hr />
<h2>Try It Live or Reuse the Snippets</h2>
<p>If you want to inspect these patterns in action—especially the mobile layout, split credit wallet, lazy <code>&lt;audio&gt;</code> sample, and zero-account workflow—you can test <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a> directly in Chrome, Safari, or Firefox (no signup required), or grab the standalone date-unlock, RFC 5545 <code>.ics</code>, and wallet/audio helpers from <a href="https://github.com/sunrain113/advent-ics-midnight-js"><code>sunrain113/advent-ics-midnight-js</code></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Fixing Mobile CSS Grid Overlay Clipping, Lazy Audio Previews & Dual-Balance Pre-Checks in Vanilla JS]]></title><description><![CDATA[Shipping interactive holiday web tools comes with an unforgiving constraint: most visitors open shared links on narrow 375px mobile screens, tap audio…]]></description><link>https://minigamedaily.hashnode.dev/fixing-mobile-css-grid-overlay-clipping-lazy-audio-previews-dual-balance-pre-checks-in-vanilla-js</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/fixing-mobile-css-grid-overlay-clipping-lazy-audio-previews-dual-balance-pre-checks-in-vanilla-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[webdev]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Fri, 04 Dec 2026 08:17:04 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://digitaleradventskalender.com/_a/share.ec377a2633.png" alt="Digitaler Adventskalender – 24 digitale Türchen kostenlos online erstellen" /></p>
<p>Shipping interactive holiday web tools comes with an unforgiving constraint: most visitors open shared links on narrow <code>375px</code> mobile screens, tap audio samples inline, and bail immediately if clicking a button triggers a 4-second spinner that ends in a <code>401</code>.</p>
<p>While auditing and updating <strong><a href="https://digitaleradventskalender.com/">Digitaler Adventskalender</a></strong> — a free, zero-login German advent calendar builder that pairs a 7/12/24/25-door creator (including the collaborative <strong><a href="https://digitaleradventskalender.com/mit-freunden">Mit Freunden</a></strong> group board) with <strong><a href="https://digitaleradventskalender.com/spiele">4 browser mini-games</a></strong> — three front-end bugs stood out during real mobile testing:</p>
<ol>
<li><strong>Post-game overlay clipping on mobile</strong> inside a fixed-height game stage</li>
<li><strong>Simultaneous <code>&lt;audio loading="lazy"&gt;</code> playback</strong> when offering real German AI Christmas song previews alongside a custom player</li>
<li><strong>Wasted <code>401</code> round-trips</strong> when free earned mini-game credits (<code>Gratis-Flocken</code>) cannot cover paid AI endpoints (<code>Gekaufte Flocken</code>)</li>
</ol>
<p>Here are the exact CSS and vanilla JS fixes we deployed — plus two new MIT-licensed helpers pushed to <a href="https://github.com/sunrain113/vanilla-js-calendar-story-snippets"><code>vanilla-js-calendar-story-snippets</code></a>.</p>
<hr />
<h2>1. Replacing Fixed-Height Overlay Clipping with Single-Cell CSS Grid Stacking</h2>
<p>Originally, our mini-game stage used <code>position: relative; height: 320px; overflow: hidden;</code> on <code>.ds-board</code> with <code>.ds-overlay</code> using <code>position: absolute; inset: 0;</code>.</p>
<p>During the game intro (a short title + Play button), <code>320px</code> looked tidy. Once a visitor finished all 6 pairs in Memory, however, the post-game overlay rendered the score summary, reward badge, conversion pitch, WhatsApp challenge link, and replay button (<code>~473px</code> tall on a <code>375×812</code> viewport). Because <code>.ds-overlay</code> was <code>position: absolute</code> inside an <code>overflow: hidden</code> fixed-height box, both the top score and bottom CTA buttons were silently sliced off.</p>
<p>Refactoring <code>.ds-board</code> into a single-cell CSS Grid track (<code>grid-template-areas: "stage"</code>) without <code>overflow: hidden</code> lets the overlay expand the stage naturally when content grows, while keeping layers stacked directly on top of one another:</p>
<pre><code class="language-css">.ds-board {
  position: relative;
  display: grid;
  grid-template-areas: "stage";
  border-radius: 14px;
  border: 2px solid var(--border);
  background: var(--bg);
}

.ds-canvas,
.ds-dom-area,
.ds-overlay {
  grid-area: stage;
}

.ds-canvas[hidden],
.ds-dom-area[hidden],
.ds-overlay[hidden] {
  display: none;
}

.ds-overlay {
  position: relative;
  width: 100%;
  min-block-size: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 16px;
}
</code></pre>
<p>Key detail: <code>[hidden]</code> elements inside CSS Grid or <code>display: flex</code> containers must be explicitly forced to <code>display: none</code> so author display rules never override the HTML <code>hidden</code> attribute. On a live <code>375×812</code> mobile test finishing a full Memory round on <a href="https://digitaleradventskalender.com/spiele">digitaleradventskalender.com/spiele</a>, <code>.ds-board</code> expanded cleanly from <code>320px</code> to <code>472.77px</code> with <code>0</code> clipping and <code>0</code> horizontal overflow (<code>CLS = 0</code>).</p>
<hr />
<h2>2. Lazy Audio Previews and Capture-Phase Single-Active Playback Guard</h2>
<p>We added real MP3 sample previews of our personalized German AI Christmas song across the studio panel, post-creation viewer, and <strong><a href="https://digitaleradventskalender.com/preise">Preise &amp; Pakete</a></strong> page so visitors can actually hear vocal quality before spending paid credits.</p>
<p>Two small browser quirks matter when embedding multiple <code>&lt;audio&gt;</code> players on a tool page:</p>
<ol>
<li><strong><code>&lt;audio loading="lazy" preload="none"&gt;</code> must keep <code>controls</code></strong>: Lazy-loaded <code>&lt;audio&gt;</code> elements without <code>controls</code> are hidden by browsers and won't load audio. Always keep <code>controls</code> visible and pair it with <code>preload="none"</code> so the 3.8 MB MP3 isn't fetched until the visitor actually taps Play.</li>
<li><strong><code>play</code> events on <code>&lt;audio&gt;</code> do not bubble</strong>: If you have a sample demo player, a generated track preview, and an attached calendar song player on the same page, bubbling listeners on <code>document.addEventListener("play", ...)</code> won't fire! Pass <code>true</code> (<code>capture: true</code>) so starting any player immediately pauses sibling players:</li>
</ol>
<pre><code class="language-js">function isAudioElement(node) {
  return Boolean(node &amp;&amp; typeof node.tagName === "string" &amp;&amp; node.tagName.toUpperCase() === "AUDIO");
}

export function attachSingleActiveAudioGuard(root = typeof document !== "undefined" ? document : null) {
  if (!root || typeof root.addEventListener !== "function") {
    return () =&gt; {};
  }

  const onPlay = (event) =&gt; {
    const target = event?.target;
    if (!isAudioElement(target) || typeof root.querySelectorAll !== "function") return;
    for (const player of root.querySelectorAll("audio")) {
      if (player !== target &amp;&amp; !player.paused &amp;&amp; typeof player.pause === "function") {
        player.pause();
      }
    }
  };

  root.addEventListener("play", onPlay, true);
  return () =&gt; root.removeEventListener("play", onPlay, true);
}
</code></pre>
<hr />
<h2>3. Dual-Balance Clarity and Synchronous Pre-Checks (Zero 401 Spinners)</h2>
<p>Free browser-earned credits (from daily door opens or <a href="https://digitaleradventskalender.com/spiele">mini-game rounds</a>) are great for cosmetic skins (<code>2 / 3 / 4 ❄️</code> door wraps or the <code>15 ❄️</code> Gold-Edition), while paid server-side AI tools (<code>5 ❄️</code> for 24 custom German door ideas, <code>15 ❄️</code> for a custom MP3 song) require purchased credits (<code>Gekaufte Flocken</code>).</p>
<p>Showing a single combined flake number in the header confused users with <code>3 ❄️</code> free balance when AI actions returned <code>401</code>. Calling the backend anyway also forced a 3–5 second spinner before failing!</p>
<p>Splitting the UI display into explicit free vs. paid counters and running a synchronous pre-check before starting any progress indicator eliminates wasted requests completely:</p>
<pre><code class="language-js">export function checkDualCreditPrecheck({
  freeBalance = 0,
  paidBalance = 0,
  requiredCost = 0,
  mode = "paid_only"
} = {}) {
  const free = Math.max(0, Math.floor(Number(freeBalance) || 0));
  const paid = Math.max(0, Math.floor(Number(paidBalance) || 0));
  const cost = Math.max(0, Math.floor(Number(requiredCost) || 0));
  const paidOnly = mode === "paid_only";
  const spendable = paidOnly ? paid : free + paid;
  const shortfall = Math.max(0, cost - spendable);

  return {
    ok: shortfall === 0,
    shortfall,
    paidOnly,
    requiredCost: cost,
    freeBalance: free,
    paidBalance: paid,
    spendableBalance: spendable,
    action: shortfall === 0 ? "proceed" : "prompt_purchase_or_fallback"
  };
}
</code></pre>
<p>When <code>action === "prompt_purchase_or_fallback"</code>, we keep the progress bar hidden (<code>hidden = true</code>), reveal a clear message explaining exact free vs. paid balances, and offer both the guest checkout CTA and a 1-click free template fallback (<code>24 digitale Türchen</code> ready from our <a href="https://digitaleradventskalender.com/ideen-tuerchen">content ideas guide</a>).</p>
<hr />
<h2>Try It Live or Inspect the MIT Snippets</h2>
<ul>
<li>Build a 7/12/24/25-door calendar with zero sign-up: <strong><a href="https://digitaleradventskalender.com/">Digitaler Adventskalender</a></strong></li>
<li>Test the CSS Grid post-game overlay on mobile: <strong><a href="https://digitaleradventskalender.com/spiele">Weihnachts-Minispiele</a></strong></li>
<li>Listen to the lazy-loaded German AI Christmas song demo: <strong><a href="https://digitaleradventskalender.com/preise">Preise &amp; Hörprobe</a></strong></li>
<li>Grab the standalone utilities and unit tests (<code>node test.mjs</code>): <a href="https://github.com/sunrain113/vanilla-js-calendar-story-snippets"><code>sunrain113/vanilla-js-calendar-story-snippets</code></a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Zero-Upload Browser Apps: Floating-Time .ics Reminders, Deterministic Grid Shuffles & 9:16 Story PNGs in Vanilla JS]]></title><description><![CDATA[Most holiday or countdown web apps follow the same heavy blueprint: require an account up front, upload user photos to object storage, run cron jobs for…]]></description><link>https://minigamedaily.hashnode.dev/zero-upload-browser-apps-floating-time-ics-reminders-deterministic-grid-shuffles-9-16-story-pngs-in-vanilla-js</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/zero-upload-browser-apps-floating-time-ics-reminders-deterministic-grid-shuffles-9-16-story-pngs-in-vanilla-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[webdev]]></category><category><![CDATA[privacy]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Thu, 03 Dec 2026 07:51:28 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://digitaleradventskalender.com/_a/share.ec377a2633.png" alt="Digitaler Adventskalender – 24 digitale Türchen kostenlos online erstellen" /></p>
<p>Most holiday or countdown web apps follow the same heavy blueprint: require an account up front, upload user photos to object storage, run cron jobs for daily reminder emails, and generate share cards on a headless browser server.</p>
<p>While building <strong><a href="https://digitaleradventskalender.com/">Digitaler Adventskalender</a></strong> — a free, German-language browser tool where users create 7-, 12-, 24-, or 25-door digital advent calendars (or run a shared <strong><a href="https://digitaleradventskalender.com/mit-freunden">Mit Freunden</a></strong> group board without sign-ups) — we intentionally removed logins, email collection, and image uploads completely.</p>
<p>That constraint forced us to solve five surprisingly interesting client-side JavaScript problems cleanly in the browser:</p>
<ol>
<li><strong>Timezone-safe daily unlocks</strong> using the <code>Temporal</code> API with a clean <code>Date</code> fallback</li>
<li><strong>Serverless daily reminders</strong> via client-generated RFC 5545 floating-time <code>.ics</code> files</li>
<li><strong>Consistent randomized door grids</strong> across all recipients using FNV-1a + xorshift32</li>
<li><strong>One-tap 9:16 Instagram/WhatsApp Story cards (<code>1080x1920</code>)</strong> rendered on <code>&lt;canvas&gt;</code></li>
<li><strong>Account-less moderation &amp; privacy-first embeds</strong> (<code>youtube-nocookie.com</code> click-to-load + <code>#owner=</code> fragment keys)</li>
</ol>
<p>I also extracted all five standalone utilities (MIT-licensed, zero dependencies) into a small companion repo: <a href="https://github.com/sunrain113/vanilla-js-calendar-story-snippets"><code>vanilla-js-calendar-story-snippets</code></a>.</p>
<hr />
<h2>1. Timezone-Safe Midnight Unlocks Without Server Clock Drift</h2>
<p>In a gift calendar, "Door 4 unlocks on December 4" should unlock at <strong>midnight in the recipient's local timezone</strong>, not UTC midnight in Frankfurt or Virginia. Comparing ISO timestamps triggers classic DST and UTC-offset off-by-one bugs.</p>
<p>Keeping calendar dates strictly as plain <code>{ y, m, d }</code> integer triples eliminates timezone conversion surprises. When <code>Temporal.PlainDate</code> is available in modern browsers, we use it first and fall back cleanly to local <code>new Date(y, m - 1, d + days)</code>:</p>
<pre><code class="language-js">export function parseYmd(str) {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(str || "").trim());
  if (!m) return { y: 2026, m: 12, d: 1 };
  const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]);
  if (mo &lt; 1 || mo &gt; 12 || d &lt; 1 || d &gt; 31) return { y: 2026, m: 12, d: 1 };
  return { y, m: mo, d };
}

export function todayYmd() {
  if (typeof Temporal !== "undefined" &amp;&amp; Temporal.Now?.plainDateISO) {
    const p = Temporal.Now.plainDateISO();
    return { y: p.year, m: p.month, d: p.day };
  }
  const now = new Date();
  return { y: now.getFullYear(), m: now.getMonth() + 1, d: now.getDate() };
}

export function addDaysYmd(ymd, days) {
  if (typeof Temporal !== "undefined" &amp;&amp; Temporal.PlainDate) {
    const p = Temporal.PlainDate.from({ year: ymd.y, month: ymd.m, day: ymd.d }).add({ days });
    return { y: p.year, m: p.month, d: p.day };
  }
  const dt = new Date(ymd.y, ymd.m - 1, ymd.d + days);
  return { y: dt.getFullYear(), m: dt.getMonth() + 1, d: dt.getDate() };
}

export function cmpYmd(a, b) {
  return (a.y * 10000 + a.m * 100 + a.d) - (b.y * 10000 + b.m * 100 + b.d);
}
</code></pre>
<p>Because <code>addDaysYmd</code> uses local calendar arithmetic rather than <code>86_400_000 ms</code> millisecond addition, crossing daylight saving boundaries never duplicates or skips a day, and <code>fmtDeLong</code> formats labels using <code>Date.UTC(y, m - 1, d)</code> with <code>timeZone: "UTC"</code> so displayed door labels never shift backward in negative UTC offsets.</p>
<hr />
<h2>2. Multi-Day <code>.ics</code> Reminders Instead of Collecting Emails</h2>
<p>Email reminders are one of the top reasons simple consumer tools add an auth wall. An <strong>RFC 5545 <code>.ics</code> Blob</strong> solves the same retention problem locally across Apple Calendar, Google Calendar, and Outlook without storing a single email address.</p>
<p>The important RFC 5545 detail here is <strong>floating time</strong>: omitting the trailing <code>Z</code> on <code>DTSTART:YYYYMMDDT090000</code> tells calendar clients to fire the alert at 09:00 AM in whichever timezone the recipient happens to be in on that day:</p>
<pre><code class="language-js">function pad2(n) {
  return n &lt; 10 ? "0" + n : String(n);
}

function icsEscape(str) {
  return String(str || "")
    .replace(/\\/g, "\\\\")
    .replace(/;/g, "\\;")
    .replace(/,/g, "\\,")
    .replace(/\r?\n/g, "\\n");
}

export function buildFloatingIcs({ title, startStr, count, shareUrl }) {
  const base = parseYmd(startStr);
  const nowStamp = new Date().toISOString().replace(/[-:]/g, "").slice(0, 15) + "Z";
  const lines = [
    "BEGIN:VCALENDAR",
    "VERSION:2.0",
    "PRODID:-//Digitaler Adventskalender//DE",
    "CALSCALE:GREGORIAN"
  ];

  for (let i = 0; i &lt; count; i++) {
    const d = addDaysYmd(base, i);
    const ymd = `${d.y}${pad2(d.m)}${pad2(d.d)}`;
    lines.push(
      "BEGIN:VEVENT",
      `UID:tuerchen-${i + 1}-${ymd}@digitaleradventskalender.com`,
      `DTSTAMP:${nowStamp}`,
      `DTSTART:${ymd}T090000`,
      "DURATION:PT15M",
      `SUMMARY:${icsEscape(`Türchen ${i + 1} — ${title}`)}`,
      `DESCRIPTION:${icsEscape(`Öffne dein heutiges Türchen unter: ${shareUrl}`)}`,
      "BEGIN:VALARM",
      "ACTION:DISPLAY",
      `DESCRIPTION:${icsEscape("Neues Adventskalender-Türchen bereit!")}`,
      "TRIGGER:PT0M",
      "END:VALARM",
      "END:VEVENT"
    );
  }

  lines.push("END:VCALENDAR");
  return new Blob([lines.join("\r\n")], { type: "text/calendar;charset=utf-8" });
}
</code></pre>
<p>Wait on two details: CRLF (<code>\r\n</code>) line endings are required by strict <code>.ics</code> parsers (especially older Outlook desktop builds), and semicolons/commas inside <code>SUMMARY</code> and <code>DESCRIPTION</code> must be escaped with <code>icsEscape</code> so URLs or calendar titles don't corrupt event properties.</p>
<hr />
<h2>3. Deterministic Door Shuffling With FNV-1a + xorshift32</h2>
<p>Classic paper advent calendars hide doors in a jumbled layout instead of neat rows from <code>1</code> to <code>24</code>. If you use <code>Math.random()</code> on every page load, the grid jumps around on every refresh; if you store the permutation server-side, it bloats the calendar payload.</p>
<p>Instead, we hash the calendar's immutable public ID into an unsigned 32-bit seed using <strong>FNV-1a</strong>, then run <strong>xorshift32</strong> inside a Fisher-Yates shuffle:</p>
<pre><code class="language-js">export function doorOrder(count, shuffle, seedStr) {
  const arr = [];
  for (let i = 1; i &lt;= count; i++) arr.push(i);
  if (!shuffle) return arr;

  let h = 2166136261;
  const s = String(seedStr || "advent");
  for (let j = 0; j &lt; s.length; j++) {
    h ^= s.charCodeAt(j);
    h = Math.imul(h, 16777619);
  }

  for (let k = arr.length - 1; k &gt; 0; k--) {
    h ^= h &lt;&lt; 13;
    h ^= h &gt;&gt;&gt; 17;
    h ^= h &lt;&lt; 5;
    const idx = (h &gt;&gt;&gt; 0) % (k + 1);
    const tmp = arr[k];
    arr[k] = arr[idx];
    arr[idx] = tmp;
  }

  return arr;
}
</code></pre>
<p>Notice <code>Math.imul</code> and <code>h &gt;&gt;&gt; 0</code>: JavaScript's bitwise operators return signed 32-bit integers, so keeping multiplication in <code>Math.imul</code> avoids floating-point precision loss while <code>&gt;&gt;&gt; 0</code> guarantees a non-negative modulo index. Every friend opening the same shared calendar on mobile Safari, Android Chrome, or desktop Firefox sees the exact same randomized door layout—zero extra storage required. That is especially useful on shared office and group boards like the one documented on our guide for <a href="https://digitaleradventskalender.com/fuer-teams">teams and clubs</a>.</p>
<hr />
<h2>4. Generating <code>1080x1920</code> 9:16 Story PNGs Client-Side</h2>
<p>In collaborative group mode, links dropped in WhatsApp group chats work great, while Instagram and TikTok invite stories prefer a vertical <strong>9:16 graphic</strong> paired with a readable short code visitors can enter on <a href="https://digitaleradventskalender.com/code"><code>/code</code></a>.</p>
<p>Rendering a <code>1080x1920</code> canvas right inside the browser keeps the workflow zero-upload and zero-latency:</p>
<pre><code class="language-js">function wrapCanvasText(ctx, text, x, y, maxW, lineH, maxLines) {
  const words = String(text || "").split(/\s+/);
  let line = "";
  let drawn = 0;

  for (let i = 0; i &lt; words.length; i++) {
    const test = line ? `${line} ${words[i]}` : words[i];
    if (ctx.measureText(test).width &gt; maxW &amp;&amp; line) {
      ctx.fillText(line, x, y);
      y += lineH;
      drawn++;
      line = words[i];
      if (maxLines &amp;&amp; drawn &gt;= maxLines - 1) break;
    } else {
      line = test;
    }
  }

  if (line) {
    ctx.fillText(line, x, y);
    y += lineH;
  }
  return y;
}
</code></pre>
<p>Wrapping text via <code>ctx.measureText(test).width</code> lets user-chosen German titles (<code>maxlength="80"</code>) flow across up to 3 centered lines without clipping on narrow 9:16 Story safe zones, and exporting <code>canvas.toDataURL("image/png")</code> gives both an instant <code>&lt;img&gt;</code> preview and a one-click PNG download.</p>
<hr />
<h2>5. Privacy-First Media Parsing &amp; Accountless Moderation (<code>#owner=</code>)</h2>
<p>To ensure opening an advent calendar never leaks visitor IPs to third-party trackers before consent, the link parser enforces strict <code>https:</code> validation and converts standard YouTube watch/short/Shorts URLs to <code>youtube-nocookie.com/embed/...</code> — and <strong>never mounts the <code>&lt;iframe&gt;</code> until the recipient explicitly clicks "Vorschau laden"</strong>:</p>
<pre><code class="language-js">export function safeHttpsUrl(raw) {
  let s = String(raw || "").trim();
  if (!s) return "";
  if (!/^https?:\/\//i.test(s)) s = "https://" + s;
  try {
    const u = new URL(s);
    return u.protocol === "https:" ? u.toString() : "";
  } catch {
    return "";
  }
}

export function parseMedia(urlStr) {
  const clean = safeHttpsUrl(urlStr);
  if (!clean) return null;
  try {
    const u = new URL(clean);
    const h = u.hostname.replace(/^www\./, "");
    if (h === "youtu.be" || h === "youtube.com" || h === "m.youtube.com") {
      let vid = "";
      if (h === "youtu.be") vid = u.pathname.slice(1).split("/")[0];
      else if (u.searchParams.get("v")) vid = u.searchParams.get("v");
      else if (u.pathname.startsWith("/shorts/")) vid = u.pathname.slice(8).split("/")[0];
      if (/^[A-Za-z0-9_-]{11}$/.test(vid)) {
        return {
          url: clean,
          label: "YouTube-Video",
          embedUrl: `https://www.youtube-nocookie.com/embed/${vid}`,
          kind: "youtube"
        };
      }
    }
    if (h === "open.spotify.com") {
      const m = /^\/(?:intl-[a-z-]+\/)?(track|album|playlist|episode)\/([A-Za-z0-9]+)/.exec(u.pathname);
      if (m) {
        return {
          url: clean,
          label: "Spotify-Titel",
          embedUrl: `https://open.spotify.com/embed/${m[1]}/${m[2]}`,
          kind: "spotify"
        };
      }
    }
    return { url: clean, label: h, embedUrl: "", kind: "link" };
  } catch {
    return null;
  }
}
</code></pre>
<p>For moderation without accounts (essential when friends submit doors on shared boards), creators receive a revocable key carried in the URL fragment (<code>#owner=</code>) and stripped via <code>history.replaceState(...)</code> as soon as the key is claimed into local storage — keeping private moderator tokens out of HTTP referer headers and server access logs.</p>
<hr />
<h2>Wrapping Up</h2>
<p>Removing logins and uploads forced cleaner client-side architecture everywhere: <code>.ics</code> replaced email cron jobs, <code>#owner=</code> replaced session tables, <code>Temporal</code> + integer triples solved local midnight unlocks, and Canvas PNG export replaced server-side image rendering.</p>
<p>You can test the live tool on <strong><a href="https://digitaleradventskalender.com/">Digitaler Adventskalender</a></strong> (including the <strong><a href="https://digitaleradventskalender.com/spiele">browser mini-games</a></strong> or our transparent breakdown of <strong><a href="https://digitaleradventskalender.com/alternativen">free advent calendar alternatives</a></strong>), or browse the extracted standalone utilities in <a href="https://github.com/sunrain113/vanilla-js-calendar-story-snippets"><code>sunrain113/vanilla-js-calendar-story-snippets</code></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Click-Free Sub-Bass Sweeps (20–250 Hz), Cabinet Rattle Tests & Exponential Pitch Sliders in Vanilla JS]]></title><description><![CDATA[If you build a browser-based tone generator or subwoofer check with naive oscillator.frequency.value = hz assignments and abrupt .start() / .stop() calls…]]></description><link>https://minigamedaily.hashnode.dev/click-free-sub-bass-sweeps-20-250-hz-cabinet-rattle-tests-exponential-pitch-sliders-in-vanilla-js</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/click-free-sub-bass-sweeps-20-250-hz-cabinet-rattle-tests-exponential-pitch-sliders-in-vanilla-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Audio]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[audio]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:44:19 GMT</pubDate><content:encoded><![CDATA[<p>If you build a browser-based tone generator or subwoofer check with naive <code>oscillator.frequency.value = hz</code> assignments and abrupt <code>.start()</code> / <code>.stop()</code> calls, users hear it immediately—and not in a good way. Dropping straight into a <code>30 Hz</code> sine wave at full gain makes speaker cones pop violently on startup, dragging a linear slider crams five octaves into the leftmost 15% of the track, and sweeping linearly from <code>20 Hz</code> to <code>20,000 Hz</code> blows past the entire bass region in half a second.</p>
<p>While building <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong>—a free, zero-login suite of 11 browser-native Web Audio API diagnostics running strictly in client-side RAM—two tools forced us to get sub-bass envelopes and octave-accurate scheduling right: a safe 20–250 Hz subwoofer and rattle tester, and a 20 Hz–20 kHz precision tone generator.</p>
<p>Here are the exact vanilla JavaScript patterns we use to keep sweeps smooth, click-free, and safe for real speakers and headphones.</p>
<hr />
<h2>1. Click-Free Gain Envelopes &amp; Rhythmic Sub-Bass Pulses (20–250 Hz)</h2>
<p>A <code>25 Hz</code> sine wave has a <code>40 ms</code> cycle period and demands significant speaker cone excursion even when it sounds relatively quiet to human ears. If you connect an <code>OscillatorNode</code> straight to a <code>GainNode</code> set to <code>0.5</code>—or call <code>osc.stop()</code> mid-cycle—the instantaneous step discontinuity creates a sharp transient spike rich in high-frequency clicks ("speaker pop").</p>
<p>In our <strong><a href="https://soundtesthq.com/bass-test">online bass test</a></strong>, every frequency pad, downward <strong>Bass Drop Sweep (120 Hz → 20 Hz)</strong>, upward <strong>Rattle Sweep (20 Hz → 200 Hz)</strong>, and <strong>Rhythmic Bass Pulse</strong> wraps gain changes in explicit <code>AudioParam</code> ramps anchored to <code>actx.currentTime</code>:</p>
<pre><code class="language-js">function startClickFreeTone(actx, masterGain, startHz, targetGain, waveform = 'sine') {
  const now = actx.currentTime;
  const osc = actx.createOscillator();
  const env = actx.createGain();

  osc.type = waveform;
  osc.frequency.setValueAtTime(startHz, now);

  // Anchor at 0 before ramping up (25 ms attack eliminates DC-step pops)
  env.gain.setValueAtTime(0.0001, now);
  env.gain.linearRampToValueAtTime(targetGain, now + 0.025);

  osc.connect(env);
  env.connect(masterGain);
  osc.start(now);

  return {
    osc,
    env,
    stop() {
      const t = actx.currentTime;
      env.gain.cancelScheduledValues(t);
      env.gain.setValueAtTime(env.gain.value, t);
      env.gain.linearRampToValueAtTime(0.0001, t + 0.03);
      osc.stop(t + 0.035);
    },
  };
}
</code></pre>
<h3>Three Practical Lessons From Testing Subwoofers and Earbuds</h3>
<ol>
<li><strong>Always call <code>setValueAtTime(currentValue, t)</code> before ramping:</strong> Skipping the anchor point before <code>linearRampToValueAtTime</code> or <code>exponentialRampToValueAtTime</code> is the #1 Web Audio automation bug. Without an explicit anchor at <code>t</code>, the browser interpolates from the <em>previous</em> scheduled event (often seconds in the past), causing sudden volume jumps or broken sweeps.</li>
<li><strong>Envelope rhythmic bass pulses for transient testing:</strong> Steady sine tones expose roll-off and cabinet buzz, but tight kick-drum punch shows up better with gated pulses (<code>50 Hz</code> or <code>80 Hz</code> bursts with <code>15 ms</code> fade-in, <code>140 ms</code> sustain, and <code>35 ms</code> decay). Using <code>setTargetAtTime</code> or short linear ramps prevents clicking at the start and end of every beat while letting listeners hear whether a subwoofer starts and stops cleanly or smears notes into a room boom.</li>
<li><strong>Track the exact Hz where buzz or roll-off hits:</strong> During a slow <code>120 Hz → 20 Hz</code> drop or <code>20 Hz → 200 Hz</code> rattle sweep, reading <code>osc.frequency.value</code> alone can diverge from scheduled automation depending on browser engine timing. Computing the current sweep frequency analytically from elapsed time (<code>f0 * Math.pow(f1 / f0, progress)</code>) keeps the UI readout and the <strong>Mark Current Hz</strong> diagnostic button locked to the exact acoustic tone in real time.</li>
</ol>
<hr />
<h2>2. Logarithmic Pitch Sliders &amp; <code>exponentialRampToValueAtTime</code> (20 Hz–20 kHz)</h2>
<p>Human hearing perceives pitch logarithmically by octaves, not linearly by Hertz:</p>
<ul>
<li><code>20 Hz → 40 Hz → 80 Hz → 160 Hz → 320 Hz</code> spans four full octaves inside just <code>300 Hz</code>.</li>
<li>Meanwhile, <code>10,000 Hz → 20,000 Hz</code> spans <code>10,000 Hz</code> yet equals only <strong>one single octave</strong>.</li>
</ul>
<p>If you map a <code>0–1000</code> <code>&lt;input type="range"&gt;</code> slider linearly from <code>20</code> to <code>20000</code>, <code>1,000 Hz</code> sits cramped near <code>5%</code> of the slider width and sweeping linearly spends under a second in bass/midrange before dragging endlessly through treble.</p>
<p>In our <strong><a href="https://soundtesthq.com/frequency-test">online frequency test</a></strong> (a full 20 Hz–20,000 Hz Hertz tone generator with ±1/±10/±100 Hz fine nudging, note/wavelength readouts, and 4 waveforms), both the slider UI and Web Audio sweep scheduling operate in log-frequency space:</p>
<pre><code class="language-js">// Map normalized slider position [0..1] &lt;-&gt; logarithmic frequency [20..20000 Hz]
const MIN_HZ = 20;
const MAX_HZ = 20000;

function sliderToHz(norm) {
  const clamped = Math.min(1, Math.max(0, norm));
  return Math.round(MIN_HZ * Math.pow(MAX_HZ / MIN_HZ, clamped));
}

function hzToSlider(hz) {
  const clamped = Math.min(MAX_HZ, Math.max(MIN_HZ, hz));
  return Math.log(clamped / MIN_HZ) / Math.log(MAX_HZ / MIN_HZ);
}

function scheduleOctaveSweep(actx, osc, startHz, endHz, durationSec) {
  const now = actx.currentTime;
  osc.frequency.cancelScheduledValues(now);
  // exponentialRampToValueAtTime requires strictly positive (&gt; 0) endpoints
  osc.frequency.setValueAtTime(Math.max(1, startHz), now);
  osc.frequency.exponentialRampToValueAtTime(Math.max(1, endHz), now + durationSec);
  return now;
}
</code></pre>
<h3>Waveform Gain Compensation &amp; Treble Safety</h3>
<p>Switching from a pure <code>sine</code> wave to <code>square</code> or <code>sawtooth</code> mid-playback introduces dense odd/even harmonics that sound dramatically louder—and can confuse upper-treble roll-off checks because listeners still hear lower harmonics even after the fundamental crosses <code>16 kHz</code>. Scaling per-waveform gain (<code>1.0</code> for <code>sine</code>, <code>0.78</code> for <code>triangle</code>, <code>0.42</code> for <code>square</code>/<code>sawtooth</code>) inside <code>setTargetAtTime(scaledGain, now, 0.015)</code> keeps perceived loudness comfortable while keeping pure-sine mode clean for tweeter and codec roll-off checks.</p>
<hr />
<h2>3. Connecting Low-End Checks Across the Full Audio Chain</h2>
<p>In practice, low-frequency symptoms rarely live in isolation. Pair these browser checks when debugging real hardware:</p>
<ul>
<li><strong>LFE Subwoofer Routing in Home Theater:</strong> Once you verify low-end extension down to <code>25–35 Hz</code>, test whether Windows, macOS, or HDMI eARC routes the dedicated <code>.1</code> channel cleanly using our <strong><a href="https://soundtesthq.com/surround-sound-test">surround sound test</a></strong> (discrete <code>ChannelMergerNode</code> routing when 6–8 channels exist, automatic 3D HRTF preview on stereo headphones).</li>
<li><strong>File Clipping vs. Speaker Distortion:</strong> Hear buzz on a favorite track? Inspect the local MP3, WAV, or FLAC file in browser memory with our <strong><a href="https://soundtesthq.com/audio-quality-test">audio quality test</a></strong> to separate pre-existing digital clipping in the file from physical driver rattle.</li>
<li><strong>Wireless Gaming Delay:</strong> Testing Bluetooth earbuds or a 2.4 GHz gaming headset? Benchmark end-to-end wireless lag in milliseconds via our two-stage <strong><a href="https://soundtesthq.com/audio-latency-test">audio latency test</a></strong>.</li>
</ul>
<hr />
<h2>Honest Scope &amp; Code Snippets</h2>
<p>Browser Web Audio tools are built for fast everyday diagnostics—checking sub-bass extension, pinpointing cabinet rattle frequencies, testing tweeter roll-off, and verifying speaker wiring—rather than replacing calibrated acoustic measurement rigs like REW or certified Class 1/2 hardware meters.</p>
<p>Everything runs 100% locally in browser RAM with zero downloads, zero accounts, and zero server uploads. We also maintain the standalone vanilla JS patterns on GitHub (<a href="https://github.com/sunrain113/webaudio-diagnostics-snippets">https://github.com/sunrain113/webaudio-diagnostics-snippets</a>), and you can try all 11 diagnostics free at <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Keeping an 829-Entity Minecraft Trivia Game Under a 100KB Edge Budget (Collision-Safe Matching, Moderation & VM Smoke Tests)]]></title><description><![CDATA[Most browser word and trivia games start simple until real players hit edge cases you never anticipated on localhost. When we shipped Minellion Games — an…]]></description><link>https://minigamedaily.hashnode.dev/keeping-an-829-entity-minecraft-trivia-game-under-a-100kb-edge-budget-collision-safe-matching-moderation-vm-smoke-tests</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/keeping-an-829-entity-minecraft-trivia-game-under-a-100kb-edge-budget-collision-safe-matching-moderation-vm-smoke-tests</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[GameDev]]></category><category><![CDATA[webdev]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Thu, 03 Dec 2026 05:39:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b059ae47b492aefb2b6bb58/7b2ba324-b90e-4f44-a944-aabb2bcbccdd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most browser word and trivia games start simple until real players hit edge cases you never anticipated on localhost.</p>
<p>When we shipped <strong><a href="https://minelliongames.com/">Minellion Games</a></strong> — an independent, free, zero-login browser Minecraft 1.21+ reverse-trivia game where rarer valid answers dig deeper from <code>Y+64</code> Surface down to <code>Y-64</code> Bedrock — we made one architectural constraint non-negotiable: <strong>zero runtime JS frameworks, zero iframes, and a single edge-served client bundle strictly under <code>100 KB</code></strong>.</p>
<p>Scaling the catalog from <strong>538 → 829 Minecraft entities</strong>, hardening <strong><a href="https://minelliongames.com/leaderboard">Global Leaderboards</a></strong> for public moderation, and testing inside a strict byte ceiling forced four concrete JavaScript lessons that generalize to any lightweight browser game.</p>
<hr />
<h2>1. Living Inside a Hard <code>100 KB</code> Edge Script Limit (Zero Bundler, Zero Frameworks)</h2>
<p>When your entire theme runtime script is validated server-side against a <strong>100 KB ceiling</strong> (our current production <code>script.js</code> weighs in at <strong>99,610 characters / 99,664 bytes</strong>), every kilobyte matters.</p>
<p>Instead of pulling in external UI libraries or validation dependencies, we kept all three game hubs — Daily Dig, <strong><a href="https://minelliongames.com/unlimited">Unlimited Practice</a></strong>, and <strong><a href="https://minelliongames.com/creeper-party">Creeper Party</a></strong> (including its 5 zero-LLM local AI bot personas) — inside a single vanilla IIFE with tiny DOM helpers:</p>
<pre><code class="language-js">function ce(t, c, x) {
  var e = document.createElement(t);
  if (c) e.className = c;
  if (x != null) e.textContent = x;
  return e;
}
function on(e, t, f) {
  if (e) e.addEventListener(t, f);
}
</code></pre>
<p>Separating the static entity/prompt JSON catalog (<code>829</code> entities across Mobs, Blocks, Items, Biomes, Enchantments, and Structures, also documented in the <strong><a href="https://minelliongames.com/rarity-guide">Minecraft 1.21+ Rarity Guide</a></strong>) from <code>script.js</code> means catalog expansions add <strong>zero bytes</strong> to the JavaScript bundle.</p>
<hr />
<h2>2. Scaling to 829 Entities Broke Single-Hit Alias Resolution</h2>
<p>Once our catalog crossed 800+ Minecraft 1.21+ entities, shorthand aliases and plural stems started colliding across different prompt categories.</p>
<p>Consider what happens when a player types <strong><code>fossil</code></strong> or <strong><code>vex</code></strong>:</p>
<ul>
<li>If the prompt asks for a <strong>Minecraft Structure</strong>, <strong><code>Nether Fossil</code></strong> is a valid answer — even though <strong><code>Bone Block</code></strong> is also tagged under blocks/fossils.</li>
<li>If a resolver maps normalized strings or aliases to a single entity and <strong>immediately returns <code>{ mismatch: cand }</code></strong> on the first candidate that fails <code>matchesPrompt(cand, prompt)</code>, whichever entity happened to be indexed first blocks the valid match in another category!</li>
</ul>
<p>Our fix in <code>resolveAnswer</code> holds any prompt mismatch as <code>mismatchCand</code> instead of aborting early, inspecting every exact normalized bucket, alias bucket, and key hit across all query variants (<code>singular</code>, <code>stripped articles</code>, <code>es</code>/<code>s</code>/<code>ies</code> stems) — and even running bounded Levenshtein typo checks against valid entities before reporting a category mismatch:</p>
<pre><code class="language-js">function resolveAnswer(raw, data, prompt) {
  var vars = queryVariants(raw);
  if (!vars.length) return null;
  var mismatchCand = null;

  for (var vi = 0; vi &lt; vars.length; vi++) {
    var qv = vars[vi];
    var cands = [].concat(
      data.byNorm[qv] || [],
      data.aliases[qv] || [],
      data.byKey[qv] ? [data.byKey[qv]] : []
    );
    for (var ci = 0; ci &lt; cands.length; ci++) {
      var cand = cands[ci];
      if (matchesPrompt(cand, prompt)) return cand;
      if (!mismatchCand) mismatchCand = cand;
    }
  }

  // Pass 2: bounded Levenshtein recovery strictly over prompt-valid candidates
  var valid = data.entities.filter(function (e) {
    return matchesPrompt(e, prompt);
  });
  for (var vi2 = 0; vi2 &lt; vars.length; vi2++) {
    var q2 = vars[vi2];
    var maxDist = q2.length &gt;= 9 ? 2 : 1;
    var best = null, bestD = 99;
    for (var j = 0; j &lt; valid.length; j++) {
      var d = lev(q2, valid[j]._n);
      if (d &lt;= maxDist &amp;&amp; d &lt; bestD) {
        bestD = d;
        best = valid[j];
      }
    }
    if (best) return best;
  }

  if (mismatchCand) return { mismatch: mismatchCand };
  return null;
}
</code></pre>
<p>Notice why holding <code>mismatchCand</code> matters UX-wise too: if someone types <strong><code>Vex</code></strong> during an <strong>Armor Trim</strong> round, they don't get a vague <em>"Unknown entity"</em> rejection — they get clean feedback that <code>Vex</code> exists in the catalog (mob), whereas <code>Vex Armor Trim</code> (<code>vex trim</code>) belongs in the Trim round.</p>
<p>We extracted and open-sourced this exact <strong>multi-candidate bucket resolver</strong> pattern in <strong><code>v1.1.0</code></strong> of <a href="https://github.com/sunrain113/minecraft-trivia-bot-engine"><code>sunrain113/minecraft-trivia-bot-engine</code></a> (MIT License) alongside an interactive browser playground hosted on <strong><a href="https://sunrain113.github.io/minecraft-trivia-bot-engine/">GitHub Pages</a></strong>.</p>
<hr />
<h2>3. Zero-False-Positive Moderation for Public Leaderboards (Watching Out for the Scunthorpe Trap)</h2>
<p>Opening <strong><a href="https://minelliongames.com/leaderboard">Global Leaderboards</a></strong> and shareable <strong><a href="https://minelliongames.com/creeper-party">Creeper Party</a></strong> friend duel titles to zero-login visitors creates an immediate moderation requirement: you need to block URLs, Discord invite spam, zero-width character spoofs, and profanity <em>without</em> false-flagging normal Minecraft player handles.</p>
<p>A naive substring blocklist falls straight into classic traps:</p>
<ul>
<li>Blocking <code>hell</code>, <code>ass</code>, <code>tit</code>, or <code>cock</code> as substrings falsely rejects legitimate gaming terms and Minecraft entities like <strong><code>Compass</code></strong>, <strong><code>Grass</code></strong>, <strong><code>Nether</code></strong>, <strong><code>Wither</code></strong>, or <strong><code>Warden</code></strong>, and city/surname classics like <strong><code>Scunthorpe</code></strong>.</li>
</ul>
<p>Our two-tier client guard combines:</p>
<ol>
<li><strong>Invisible control / zero-width character normalization</strong> before length checks (<code>[\u0000-\u001F\u007F\u200B-\u200F\uFEFF]</code>).</li>
<li><strong>Domain / link / handle rejection</strong> (<code>https://</code>, <code>discord.gg</code>, <code>t.me/</code>, <code>play.example.gg</code>).</li>
<li><strong>Word-boundary token matching</strong> for short ambiguous strings (<code>\b...\b</code>) paired with <strong>per-token stripped substring matching</strong> only for unambiguous slurs — plus an accessible inline <code>Report</code> action directly next to each public leaderboard entry so visitors can flag anything inappropriate with duplicate-report <code>409</code> idempotency.</li>
</ol>
<p>Testing the open-source <code>src/nickValidator.js</code> module with Node's native <code>node:test</code> runner actually caught a real edge case immediately (<code>ScunthorpeFan</code> tripped a substring token), letting us move it into the word-bounded token regex while verifying safe Minecraft handles (<code>Warden</code>, <code>Wither</code>, <code>Fossil</code>, <code>Compass</code>, <code>GrassBlock</code>, <code>RedstoneBot</code>) pass cleanly.</p>
<hr />
<h2>4. Catching Variable Shadowing Under Tight Minification Budgets With <code>node:vm</code></h2>
<p>When you hand-trim helper names down to 2-character identifiers like <code>on(el, ev, fn)</code> and <code>sa(el, k, v)</code> to stay inside <strong>99.6 KB</strong>, JavaScript <code>var</code> hoisting is a silent trap.</p>
<p>While compressing our theme bundle to keep headroom under 100 KB, hoisting a local <code>var on</code> inside a function inside the same IIFE shadowed the top-level <code>function on(e, t, f)</code> listener helper — breaking click handlers silently if <code>on(...)</code> was invoked anywhere inside that lexical scope. Because <code>script.js</code> runs directly in browsers without a TypeScript compiler step, static syntax checks (<code>node --check</code>) still exit <code>0</code> on valid shadowing!</p>
<p>Our pre-publish smoke suite now loads <code>script.js</code> inside <strong><code>node:vm</code></strong> with lightweight DOM stubs, executes initialization paths, dispatches simulated mode/filter clicks, and asserts resolver behavior (<code>fossil</code>, <code>vex</code>, <code>vex trim</code>) and zero-throw execution <em>before</em> deploying any site version. That 40-line <code>node:vm</code> smoke harness caught real runtime regressions twice faster than clicking around manually.</p>
<hr />
<h2>Try the Game or Inspect the MIT Engine</h2>
<ul>
<li><strong>Play Minellion Games (829 entities, free, zero login):</strong> <a href="https://minelliongames.com/">https://minelliongames.com/</a></li>
<li><strong>Interactive Zero-LLM Bot &amp; Resolver Sandbox (GitHub Pages):</strong> <a href="https://sunrain113.github.io/minecraft-trivia-bot-engine/">https://sunrain113.github.io/minecraft-trivia-bot-engine/</a></li>
<li><strong>Unlimited Practice Mode (Zen &amp; Blitz):</strong> <a href="https://minelliongames.com/unlimited">https://minelliongames.com/unlimited</a></li>
<li><strong>Creeper Party (5 Local AI Bots + Friend Duels):</strong> <a href="https://minelliongames.com/creeper-party">https://minelliongames.com/creeper-party</a></li>
<li><strong>Open-Source Vanilla ESM Engine (<code>v1.1.0</code>, MIT):</strong> <a href="https://github.com/sunrain113/minecraft-trivia-bot-engine">https://github.com/sunrain113/minecraft-trivia-bot-engine</a></li>
</ul>
<p><em>(Disclosure: Independent fan-made Minecraft trivia web project; not affiliated with Mojang AB, Microsoft Corporation, or minellion.io.)</em></p>
]]></content:encoded></item><item><title><![CDATA[Building a Zero-Account, Zero-Upload Digital Advent Calendar in Vanilla JS: Capability Links, Local-Midnight Unlocks, and .ics Reminders]]></title><description><![CDATA[Every December, someone asks: "Where can I make an online Advent calendar quickly without forcing 20 friends to register, verify emails, or upload private…]]></description><link>https://minigamedaily.hashnode.dev/building-a-zero-account-zero-upload-digital-advent-calendar-in-vanilla-js-capability-links-local-midnight-unlocks-and-ics-reminders</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/building-a-zero-account-zero-upload-digital-advent-calendar-in-vanilla-js-capability-links-local-midnight-unlocks-and-ics-reminders</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[open source]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Thu, 03 Dec 2026 04:44:12 GMT</pubDate><content:encoded><![CDATA[<p>Every December, someone asks: <em>"Where can I make an online Advent calendar quickly without forcing 20 friends to register, verify emails, or upload private photos to a random server?"</em></p>
<p>While building <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a>, a free French-first interactive Advent calendar web app, three small browser engineering problems turned out to matter much more than fancy animations:</p>
<ol>
<li>Letting creators <strong>save, edit, and delete</strong> their calendar later <em>without</em> accounts or email addresses.</li>
<li>Avoiding off-by-one timezone bugs so Door #5 opens at <strong>00:00 in the recipient's local timezone</strong>, while immediately unlocking past doors if a gift starts on December 10.</li>
<li>Generating RFC 5545 <code>.ics</code> daily reminders purely client-side so recipients actually remember to open Day 6 in Safari or Chrome.</li>
</ol>
<p>We extracted the date-unlock and <code>.ics</code> generation core into a tiny zero-dependency MIT repo: <a href="https://github.com/sunrain113/advent-ics-midnight-js"><code>advent-ics-midnight-js</code></a>. Here is how the pieces fit together.</p>
<h2>1. Capability URLs (<code>#owner=</code>) Instead of Email Recovery</h2>
<p>Most "no-signup" tools fall into two traps: either they store everything inside a multi-kilobyte query string (making links fragile in SMS or WhatsApp), or they still capture your email address just to mail you an edit token.</p>
<p>A cleaner middle ground is pairing a short public share URL with a <strong>browser-only <code>#owner=</code> fragment capability</strong> (plus a short human-copyable recovery key):</p>
<ul>
<li>Fragments after <code>#</code> are never sent in HTTP <code>GET</code> requests or standard server logs.</li>
<li>Opening the <code>#owner=</code> URL transfers ownership capabilities onto a new phone or laptop without ever collecting an email address or setting up OAuth.</li>
<li>Because personal media stays off our servers—users share text notes, custom gift vouchers, and external HTTPS links to Spotify, YouTube, or GIFs—moderation is just a one-click removal action if a guest leaves an off-topic door in collaborative mode.</li>
</ul>
<p>We documented the cross-device recovery workflow in <a href="https://calendrieraventenligne.com/comment-creer">the French mobile &amp; desktop creation guide</a>, which works directly in Safari on iPhone/iPad, Chrome on Android, and desktop Firefox/Chrome.</p>
<h2>2. Fixing the UTC Date-Parsing Trap for Local-Midnight Door Unlocks</h2>
<p>A classic bug when building countdowns in JavaScript is calling <code>new Date("2026-12-01")</code>. By spec, ISO date-only strings parse as <strong>UTC midnight</strong>, not local midnight—meaning a recipient in New York sees December 1 unlocked on November 30 at 19:00, while someone testing <code>YYYY-MM-DD</code> comparisons in UTC+8 can hit off-by-one skips around DST boundaries.</p>
<p>Instead, parse calendar dates strictly into local year/month/day components:</p>
<pre><code class="language-js">function parseIsoDate(iso) {
  if (typeof iso !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(iso)) {
    throw new RangeError(`Expected YYYY-MM-DD date string, got "${iso}"`);
  }
  const [y, m, d] = iso.split('-').map(Number);
  const dt = new Date(y, m - 1, d, 0, 0, 0, 0);
  if (dt.getFullYear() !== y || dt.getMonth() !== m - 1 || dt.getDate() !== d) {
    throw new RangeError(`Invalid calendar date: "${iso}"`);
  }
  return dt;
}

function computeDoorUnlockState({ startDate = '2026-12-01', count = 24, now = new Date() } = {}) {
  const start = parseIsoDate(startDate);
  const todayLocal = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
  const doors = [];

  for (let i = 0; i &lt; count; i++) {
    const unlockDate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i, 0, 0, 0, 0);
    const isUnlocked = todayLocal.getTime() &gt;= unlockDate.getTime();
    const isToday = todayLocal.getTime() === unlockDate.getTime();
    doors.push({
      dayNumber: i + 1,
      unlockDate,
      isUnlocked,
      isToday,
      isPastCatchup: isUnlocked &amp;&amp; !isToday,
    });
  }
  return doors;
}
</code></pre>
<p>Two practical benefits fall out of keeping every unlock check strictly at local <code>00:00:00.000</code>:</p>
<ul>
<li><strong>Mid-December start:</strong> If an HR lead or friend launches a 24-door calendar on December 8 (<a href="https://calendrieraventenligne.com/entreprise">very common for workplace team countdowns</a>), Days 1–7 automatically evaluate <code>isPastCatchup: true</code> and open immediately without showing frustrating locks on already-elapsed dates.</li>
<li><strong>Year-round countdowns:</strong> Changing <code>startDate</code> and choosing <code>7</code>, <code>12</code>, <code>24</code>, or <code>25</code> doors lets the exact same UI handle birthdays or pre-vacation trips across month/year boundaries cleanly.</li>
</ul>
<h2>3. Generating Valid RFC 5545 <code>.ics</code> Reminders With Zero Libraries</h2>
<p>Open rates on digital Advent calendars drop sharply around Day 4 unless recipients get a gentle morning nudge. Push notification permissions in mobile browsers have high friction—especially on iOS—so a 1-click <code>.ics</code> download that drops daily events straight into Apple Calendar, Google Calendar, or Outlook is far more reliable.</p>
<p>Generating <code>.ics</code> text by hand only requires remembering three RFC 5545 rules:</p>
<ol>
<li>Line breaks must be <code>\r\n</code> (<code>CRLF</code>), never bare <code>\n</code>.</li>
<li>Commas, semicolons, backslashes, and newlines inside <code>SUMMARY</code> or <code>DESCRIPTION</code> must be escaped (<code>\,</code>, <code>\;</code>, <code>\\</code>, <code>\n</code>).</li>
<li>Lines longer than 75 octets should be folded with <code>\r\n </code> (CRLF + single space).</li>
</ol>
<pre><code class="language-js">function escapeIcsText(text) {
  return String(text ?? '')
    .replace(/\\/g, '\\\\')
    .replace(/\r?\n/g, '\\n')
    .replace(/,/g, '\\,')
    .replace(/;/g, '\\;');
}

function buildDailyAdventIcs({ title, url, startDate = '2026-12-01', count = 24, alarmHour = 9 } = {}) {
  const start = parseIsoDate(startDate);
  const pad = (n) =&gt; String(n).padStart(2, '0');
  const hh = pad(Math.max(0, Math.min(23, Number(alarmHour) || 9)));
  const lines = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//AdventICS//FR',
    'CALSCALE:GREGORIAN',
  ];

  for (let i = 0; i &lt; count; i++) {
    const dt = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
    const ymd = `${dt.getFullYear()}${pad(dt.getMonth() + 1)}${pad(dt.getDate())}`;
    lines.push(
      'BEGIN:VEVENT',
      `UID:advent-day-${i + 1}-${ymd}@local`,
      `DTSTART;VALUE=DATE:${ymd}`,
      `SUMMARY:${escapeIcsText(`${title} — Jour ${i + 1}`)}`,
      `DESCRIPTION:${escapeIcsText(`Ouvrir la case ${i + 1} : ${url}`)}`,
      ...(url ? [`URL:${url}`] : []),
      'BEGIN:VALARM',
      `TRIGGER;VALUE=DURATION:PT${hh}H`,
      'ACTION:DISPLAY',
      `DESCRIPTION:${escapeIcsText(`${title} (Jour ${i + 1})`)}`,
      'END:VALARM',
      'END:VEVENT'
    );
  }

  lines.push('END:VCALENDAR');
  return lines.join('\r\n') + '\r\n';
}
</code></pre>
<h2>Comparing Approaches Across Digital Advent Platforms</h2>
<p>When researching existing tools (we also published a transparent 8-platform breakdown on our <a href="https://calendrieraventenligne.com/comparatif">2026 online Advent calendar comparison</a>), we noticed a clear split: design suites like Canva, Adobe Express, and Genially excel for custom static layouts or interactive classroom games but require accounts, whereas specialized Advent makers differ sharply on email requirements, server photo storage, and free participant limits.</p>
<p>By skipping server-side photo hosting and keeping both modes (<code>Gift</code> and collaborative <code>Friends</code>) lightweight in vanilla JS, Calendrier Avent en Ligne stays <code>$0</code> free, watermark-free, and open to unlimited readers across mobile and desktop browsers.</p>
<p>Explore the extracted MIT helpers in <a href="https://github.com/sunrain113/advent-ics-midnight-js"><code>sunrain113/advent-ics-midnight-js</code></a>, or try the live French creator directly at <a href="https://calendrieraventenligne.com/">Calendrier Avent en Ligne</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Building a 60-Line Two-Pass Fuzzy Typo Normalizer in Vanilla JS for 25-Second Browser Trivia]]></title><description><![CDATA[If you give trivia players two minutes to type an answer, most of them will fix their own spelling before pressing Enter. Give them 25 seconds on a phone…]]></description><link>https://minigamedaily.hashnode.dev/building-a-60-line-two-pass-fuzzy-typo-normalizer-in-vanilla-js-for-25-second-browser-trivia</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/building-a-60-line-two-pass-fuzzy-typo-normalizer-in-vanilla-js-for-25-second-browser-trivia</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Tue, 01 Dec 2026 15:00:31 GMT</pubDate><content:encoded><![CDATA[<p>If you give trivia players two minutes to type an answer, most of them will fix their own spelling before pressing Enter. Give them <strong>25 seconds</strong> on a phone keyboard, and accurate players routinely lose rounds to missed accent marks, extra leading articles, plural endings, or a single fat-fingered letter.</p>
<p>We ran straight into that UX failure mode while tuning our <a href="https://minigamedaily.com/krillion-unlimited"><strong>Krillion Unlimited practice mode</strong></a> on <a href="https://minigamedaily.com/"><strong>MiniGameDaily</strong></a>. Instead of rewarding obvious answers, rarity-scoring trivia rewards obscure valid picks—precisely the longer, less frequently typed words that mobile autocorrect mangles worst when a countdown clock is ticking down the final five seconds.</p>
<p>Pulling in a full fuzzy-search library would bloat a zero-framework bundle and invite awkward false positives on short three-letter or four-letter answers. So we kept the matcher under 60 lines of dependency-free ES modules and extracted it into a standalone helper repository, <a href="https://github.com/sunrain113/rarity-trivia-scorer-js"><code>sunrain113/rarity-trivia-scorer-js</code></a>.</p>
<p><em>(Disclosure: MiniGameDaily is an independent browser-game hub and practice trainer; we are not affiliated with <code>krillion.io</code>.)</em></p>
<hr />
<h2>Why Strict <code>===</code> Fails Under a 25-Second Mobile Timer</h2>
<p>In fast browser puzzle rounds, four harmless player variations show up constantly in valid answers:</p>
<ol>
<li><strong>Diacritics and typography</strong>: typing <code>cafe</code>, <code>naive</code>, or <code>curacao</code> instead of <code>café</code>, <code>naïve</code>, or <code>curaçao</code>, or mixing smart apostrophes (<code>’</code>) with ASCII quotes (<code>'</code>).</li>
<li><strong>Leading English articles</strong>: submitting <code>The Amazon</code> or <code>an octopus</code> when the canonical bank stores <code>Amazon</code> or <code>octopus</code>.</li>
<li><strong>Plural drift</strong>: typing <code>berries</code> vs. <code>berry</code>, or <code>volcanoes</code> / <code>dolphins</code> vs. singular nouns, while true <code>-ss</code> / <code>-us</code> / <code>-is</code> endings like <code>mars</code>, <code>cactus</code>, <code>iris</code>, or <code>glass</code> must stay untouched.</li>
<li><strong>One-character typos on longer words</strong>: typing <code>chamelion</code>, <code>rhinocros</code>, or <code>kilimanjaro</code> with one swapped or dropped letter under time pressure.</li>
</ol>
<p>Meanwhile, blind fuzzy matching has an equally painful failure mode: allowing edit distance <code>1</code> everywhere turns <code>bat</code> into <code>cat</code>, <code>mars</code> into <code>cars</code>, or <code>ant</code> into <code>art</code>. Under a competitive rarity curve, letting accidental guesses sneak through destroys trust in the leaderboard.</p>
<p>That is why we split matching into two explicit passes: <strong>deterministic canonical normalization first, length-guarded Levenshtein lookup second</strong>.</p>
<hr />
<h2>Pass 1: Deterministic Normalization (<code>normalizeAnswer</code>)</h2>
<p>Here is the exact normalization helper from our open-source <a href="https://github.com/sunrain113/rarity-trivia-scorer-js"><code>sunrain113/rarity-trivia-scorer-js</code></a> module:</p>
<pre><code class="language-js">export function normalizeAnswer(input) {
  if (typeof input !== 'string') return '';

  let clean = input
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .replace(/['’`]/g, '')
    .replace(/[^a-z0-9\s]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
    .replace(/^(?:the|an|a)\s+/i, '');

  if (clean.length &gt; 4 &amp;&amp; clean.endsWith('ies')) {
    clean = clean.slice(0, -3) + 'y';
  } else if (
    clean.length &gt; 3 &amp;&amp;
    clean.endsWith('s') &amp;&amp;
    !clean.endsWith('ss') &amp;&amp;
    !clean.endsWith('us') &amp;&amp;
    !clean.endsWith('is')
  ) {
    clean = clean.slice(0, -1);
  }

  return clean;
}
</code></pre>
<p>Three design details matter in practice:</p>
<ul>
<li><strong>Unicode NFD decomposition before punctuation stripping</strong>: Calling <code>.normalize('NFD')</code> separates base characters from combining marks (<code>\u0300-\u036f</code>), converting <code>São Paulo</code> into <code>sao paulo</code> without maintaining lookup tables.</li>
<li><strong>Apostrophe removal before symbol cleanup</strong>: Stripping <code>['’\</code>]<code> first avoids splitting contractions or possessives into artificial tokens (</code>McDonald's<code>stays</code>mcdonalds<code>, not </code>mcdonald s`).</li>
<li><strong>Conservative suffix guards</strong>: Stripping <code>-s</code> unconditionally breaks nouns like <code>mars</code>, <code>iris</code>, <code>glass</code>, <code>bus</code>, or <code>cactus</code>. Checking <code>clean.length &gt; 3</code> and guarding <code>-ss</code>, <code>-us</code>, and <code>-is</code> prevents mangling singular nouns while folding standard plurals (<code>dolphins</code> -&gt; <code>dolphin</code>, <code>berries</code> -&gt; <code>berry</code>) cleanly.</li>
</ul>
<p>Because both user input and canonical bank entries run through <code>normalizeAnswer</code>, exact semantic equivalents collide deterministically in Pass 1 with zero false positives.</p>
<hr />
<h2>Pass 2: Guarded O(n) Levenshtein Fuzzy Lookup (<code>matchAnswer</code>)</h2>
<p>Only when Pass 1 misses do we fall back to bounded edit distance:</p>
<pre><code class="language-js">export function levenshtein(a, b) {
  if (a === b) return 0;
  if (!a.length) return b.length;
  if (!b.length) return a.length;

  const prev = Array.from({ length: b.length + 1 }, (_, j) =&gt; j);
  for (let i = 1; i &lt;= a.length; i++) {
    let diag = prev[0];
    prev[0] = i;
    for (let j = 1; j &lt;= b.length; j++) {
      const saved = prev[j];
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + cost);
      diag = saved;
    }
  }
  return prev[b.length];
}
</code></pre>
<p>Notice it keeps only a single rolling <code>prev</code> row in memory instead of allocating an <code>m x n</code> matrix—a neat zero-GC pattern for mobile browsers.</p>
<p>The safety net sits around <code>levenshtein</code> inside <code>matchAnswer</code>:</p>
<pre><code class="language-js">export function matchAnswer(input, entries, options = {}) {
  const { maxEditDistance = 1, minFuzzyLength = 5 } = options;
  const normalizedInput = normalizeAnswer(input);

  if (!normalizedInput || !Array.isArray(entries)) {
    return { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
  }

  const normalizedEntries = entries.map((entry) =&gt; ({
    entry,
    normalized: normalizeAnswer(extractEntryText(entry)),
  }));

  const exactHit = normalizedEntries.find((item) =&gt; item.normalized === normalizedInput);
  if (exactHit) {
    return { matched: true, matchType: 'exact', distance: 0, normalizedInput, entry: exactHit.entry };
  }

  if (maxEditDistance &lt;= 0 || normalizedInput.length &lt; minFuzzyLength) {
    return { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
  }

  let bestHit = null;
  let bestDistance = Infinity;
  for (const item of normalizedEntries) {
    if (!item.normalized || item.normalized.length &lt; minFuzzyLength) continue;
    if (Math.abs(item.normalized.length - normalizedInput.length) &gt; maxEditDistance) continue;
    const dist = levenshtein(normalizedInput, item.normalized);
    if (dist &lt;= maxEditDistance &amp;&amp; dist &lt; bestDistance) {
      bestDistance = dist;
      bestHit = item;
    }
  }

  return bestHit
    ? { matched: true, matchType: 'fuzzy', distance: bestDistance, normalizedInput, entry: bestHit.entry }
    : { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
}
</code></pre>
<p>Two rules keep fuzzy tolerance fair in <a href="https://minigamedaily.com/krillion-unlimited"><strong>Krillion endless mode</strong></a>:</p>
<ol>
<li><strong>Minimum fuzzy length (<code>minFuzzyLength = 5</code>)</strong>: Short 3–4 letter words (<code>mars</code>, <code>lion</code>, <code>gold</code>, <code>oak</code>) never fuzzy-match, blocking <code>cars -&gt; mars</code> or <code>boat -&gt; goat</code>. Only answers with at least five normalized characters qualify (<code>chamelion -&gt; chameleon</code>, <code>platyps -&gt; platypus</code>).</li>
<li><strong>Symmetric length guard (<code>maxEditDistance = 1</code>)</strong>: Both the player string and candidate entry must satisfy <code>&gt;= 5</code> characters and differ by at most <code>1</code> character in length before running DP, skipping pointless comparisons in a single integer check.</li>
</ol>
<hr />
<h2>Calibrating Ocean-Depth Rarity Buckets (<code>RARITY_BANDS</code>)</h2>
<p>Matching an answer is half the equation; scoring how common or obscure it is determines whether a round feels strategic. Scoring raw <code>1 / share</code> directly makes tiny sample fluctuations swing wildly between rounds.</p>
<p>Instead, we map normalized crowd shares into six calibrated ocean-depth tiers via <code>scoreRarityShare</code>:</p>
<table>
<thead>
<tr>
<th align="left">Crowd Share</th>
<th align="left">Score</th>
<th align="left">Ocean Depth</th>
<th align="left">Tier Label</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>&gt;= 14%</code></td>
<td align="left"><code>10 pts</code></td>
<td align="left"><code>100 m</code></td>
<td align="left"><code>Plankton</code></td>
</tr>
<tr>
<td align="left"><code>&gt;= 8%</code></td>
<td align="left"><code>15 pts</code></td>
<td align="left"><code>150 m</code></td>
<td align="left"><code>Too Clever</code></td>
</tr>
<tr>
<td align="left"><code>&gt;= 4%</code></td>
<td align="left"><code>30 pts</code></td>
<td align="left"><code>300 m</code></td>
<td align="left"><code>Schooler</code></td>
</tr>
<tr>
<td align="left"><code>&gt;= 2%</code></td>
<td align="left"><code>60 pts</code></td>
<td align="left"><code>600 m</code></td>
<td align="left"><code>Rare</code></td>
</tr>
<tr>
<td align="left"><code>&gt;= 0.8%</code></td>
<td align="left"><code>80 pts</code></td>
<td align="left"><code>800 m</code></td>
<td align="left"><code>Deep Cut</code></td>
</tr>
<tr>
<td align="left"><code>&lt; 0.8%</code></td>
<td align="left"><code>100 pts</code></td>
<td align="left"><code>1,000 m</code></td>
<td align="left"><code>One in a Krillion</code></td>
</tr>
</tbody></table>
<p>Why add the <code>15 pts</code> (<code>Too Clever</code>) band right above <code>10 pts</code> (<code>Plankton</code>)? Crowd data in rarity trivia consistently exhibits a second-choice spike: when dozens of players consciously skip the #1 reflex answer, they crowd onto the exact same "clever" #2 fallback (<code>8%–13.9%</code> share). Explicitly buckling that tier into <code>Too Clever</code> pushes players one step deeper rather than letting second-best reflexes score like genuinely rare picks.</p>
<hr />
<h2>Checking Prompt Constraints Across the Bank (<code>summarizeDiveBank</code>)</h2>
<p>Our helper module also exports <code>summarizeDiveBank(prompts)</code>, which flags parenthetical or negative disqualifiers (<code>no</code>, <code>not</code>, <code>without</code>, <code>only</code>, <code>starting with</code>, <code>over</code>/<code>under</code>, parentheses) alongside per-tier counts. Across a benchmark slice of <strong>112 prompts and 1,977 tiered answers</strong>, <strong>35 prompts (31.3%)</strong> included explicit exclusion clauses in the prompt wording. When players miss a valid rare word, pairing fast typo normalization with post-round constraint highlighting shows right away whether the issue was spelling or a disqualified clue.</p>
<hr />
<h2>Try the Live Practice Game or Grab the Code</h2>
<p>You can inspect the full 60-line module, unit tests (<code>node --test</code>), and MIT license on GitHub at <a href="https://github.com/sunrain113/rarity-trivia-scorer-js"><code>sunrain113/rarity-trivia-scorer-js</code></a>, or jump straight into a live 25-second round with our <a href="https://minigamedaily.com/krillion-unlimited"><strong>Krillion unlimited guide</strong></a> and browse all daily puzzles over on <a href="https://minigamedaily.com/"><strong>MiniGameDaily</strong></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Zero-LLM Game AI: Building 5 Human-Like Multiplayer Trivia Bots in Vanilla JS (Plus Fixing Real Mobile Safari Crashes)]]></title><description><![CDATA[When we launched Minellion Games — a free, zero-login browser Minecraft 1.21+ reverse-trivia game where rarer answers dig deeper toward Y-64 Bedrock…]]></description><link>https://minigamedaily.hashnode.dev/zero-llm-game-ai-5-trivia-bots-vanilla-js-safari-fixes</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/zero-llm-game-ai-5-trivia-bots-vanilla-js-safari-fixes</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[GameDev]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Mon, 30 Nov 2026 11:12:05 GMT</pubDate><content:encoded><![CDATA[<p>When we launched <strong><a href="https://minelliongames.com/">Minellion Games</a></strong> — a free, zero-login browser Minecraft 1.21+ reverse-trivia game where rarer answers dig deeper toward Y-64 Bedrock — players immediately jumped into our Daily Dig and Unlimited modes.</p>
<p>Within 48 hours of launching, our first <strong>1,622+ real answer submissions</strong> taught us two hard product lessons:</p>
<ol>
<li><strong>Players want a multiplayer party feel even when playing solo at 1 AM</strong> — nobody wants to sit in an empty WebSocket matchmaking lobby waiting for 3 strangers to join a browser trivia game.</li>
<li><strong>Real mobile visitors will instantly expose browser compatibility bugs that desktop Chrome hides</strong> — two subtle JS features broke entire game sessions on older iOS Safari and older Chrome builds.</li>
</ol>
<p>Here is how we solved both without adding React, WebSockets, or LLM APIs, and how we open-sourced the core engine in <a href="https://github.com/sunrain113/minecraft-trivia-bot-engine"><code>sunrain113/minecraft-trivia-bot-engine</code></a>.</p>
<hr />
<h2>1. Why We Built Zero-LLM Local AI Bots for Creeper Party</h2>
<p>Our hot-potato party mode, <strong><a href="https://minelliongames.com/creeper-party">Creeper Party</a></strong>, works like a ticking bomb: a Minecraft prompt appears, you have 10–15 seconds to name a valid unused entity, and passing the bomb shrinks the fuse.</p>
<p>Originally it was pass-and-play only. We wanted players to open <code>/creeper-party</code> alone and immediately jump into a 4-player ring — plus still support local Pass &amp; Play and zero-login Shareable Friend Duel links (<code>?duel=...</code>).</p>
<p>Calling an LLM API for each bot turn sounded clever on paper, but failed every real constraint of a fast browser game:</p>
<ul>
<li><strong>1.5–4s network latency</strong> ruins a 9-second fuse countdown.</li>
<li><strong>Entity hallucinations</strong> break strict tag rules (like 1.19–1.21 blocks or max-stack-1 unstackable items).</li>
<li><strong>Rate limits &amp; API keys</strong> don't belong in a 100% free, account-free browser game.</li>
</ul>
<p>Instead, we designed <strong>5 distinct Minecraft-archetype bot personas</strong> that run locally in under 1 millisecond against our structured <code>/_d/trivia/*</code> JSON catalog:</p>
<table>
<thead>
<tr>
<th align="left">Bot Persona</th>
<th align="left">Archetype</th>
<th align="left">Specialty Categories</th>
<th align="left">Weak Spots</th>
<th align="center">Typing Pace</th>
<th align="center">Rarity Bias</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong><code>RedstoneBot</code></strong></td>
<td align="left">Methodical Engineer</td>
<td align="left">Blocks, Items</td>
<td align="left">Biomes</td>
<td align="center">58 WPM</td>
<td align="center">Medium-High (<code>0.62</code>)</td>
</tr>
<tr>
<td align="left"><strong><code>WardenAI</code></strong></td>
<td align="left">Deep Dark Lore Hunter</td>
<td align="left">Mobs, Structures</td>
<td align="left">Enchantments</td>
<td align="center">50 WPM</td>
<td align="center">Very Deep (<code>0.82</code>)</td>
</tr>
<tr>
<td align="left"><strong><code>BlazeCore</code></strong></td>
<td align="left">Speedrunner</td>
<td align="left">Items, Mobs</td>
<td align="left">Blocks</td>
<td align="center">72 WPM</td>
<td align="center">Pragmatic (<code>0.44</code>)</td>
</tr>
<tr>
<td align="left"><strong><code>EndermanAI</code></strong></td>
<td align="left">Cryptic Wildcard</td>
<td align="left">Biomes, Enchantments</td>
<td align="left">Structures</td>
<td align="center">54 WPM</td>
<td align="center">Deep (<code>0.76</code>)</td>
</tr>
<tr>
<td align="left"><strong><code>GolemBot</code></strong></td>
<td align="left">Steady Tank</td>
<td align="left">Blocks, Structures</td>
<td align="left">Enchantments</td>
<td align="center">46 WPM</td>
<td align="center">Safe (<code>0.38</code>)</td>
</tr>
</tbody></table>
<h3>Making Rule-Based Bots Feel Unmistakably Human</h3>
<p>The difference between a robotic <code>setTimeout(() =&gt; submit(randomItem), 2000)</code> and an AI ring that actually creates tension comes down to five small behavioral details:</p>
<ol>
<li><strong>Category affinity</strong>: <code>WardenAI</code> dominates Mob and Structure rounds (<code>+6%</code> accuracy, deeper rarity picks) but visibly struggles on Enchantment rounds (<code>-9%</code>).</li>
<li><strong>Fuse-panic adrenaline</strong>: As the fuse drops below 14 seconds, bots type up to <strong>32% faster</strong> while slightly increasing fumble probability based on each persona's <code>panicResistance</code>.</li>
<li><strong>Low-heart clutch XP hunting</strong>: When a bot drops to its final heart (<code>hearts === 1</code>), it shifts toward higher-rarity answers (<code>+0.15</code> rarity bias) and gains a tiny adrenaline focus boost.</li>
<li><strong>35% second-wind panic recovery</strong>: When a bot initially blanks out, there is a 35% chance it recovers late in the fuse with a safe familiar fallback answer and fires a clutch quip (<code>"Repeater saved it!"</code>, <code>"Clutch water bucket!"</code>).</li>
<li><strong>2-stage live typing previews</strong>: Instead of answers popping out of nowhere, the ring shows progressive typing previews (<code>typing: Soul ...</code> → <code>typing: Soul Campf...</code> → <code>Soul Campfire</code>) synced to each persona's WPM.</li>
</ol>
<p>Running a 500-turn Monte Carlo benchmark (<code>node scripts/benchmark.mjs</code> in our <a href="https://github.com/sunrain113/minecraft-trivia-bot-engine">open-source engine repo</a>) shows clear, playable personality separation:</p>
<pre><code class="language-text">Persona       | Archetype              | Pass % | Clutch % | Avg Time | Avg Rarity
--------------|------------------------|--------|----------|----------|-----------
RedstoneBot   | Methodical Engineer    |  88.0% |     5.5% |   3862ms |      81.5
WardenAI      | Deep Dark Lore Hunter  |  90.4% |     5.1% |   5331ms |      89.3
BlazeCore     | Speedrunner            |  84.8% |     9.0% |   2866ms |      70.1
EndermanAI    | Cryptic Wildcard       |  88.0% |     4.8% |   4591ms |      86.6
GolemBot      | Steady Tank            |  87.2% |     8.3% |   3981ms |      65.5
</code></pre>
<p><code>BlazeCore</code> fires answers in <del>2.86s with the highest clutch rate (<code>9.0%</code>), while <code>WardenAI</code> thinks longer (</del>5.33s) to pull rare <code>89.3</code> rarity answers straight out of the Deep Dark.</p>
<hr />
<h2>2. Two Real-Visitor JS Crashes We Caught From Live Telemetry</h2>
<p>On day 2, our lightweight client-side error reporter surfaced two real-world crashes that never triggered on our local dev machines:</p>
<h3>Crash A: <code>Object.hasOwn(...)</code> on older Chrome / school Chromebooks</h3>
<p>A subset of players on locked-down Chrome builds hit <code>TypeError: Object.hasOwn is not a function</code> during answer resolution.</p>
<p><strong>Fix:</strong> Replace every <code>Object.hasOwn(obj, key)</code> with a tiny ES5-safe helper:</p>
<pre><code class="language-js">function hasOwn(obj, key) {
  return obj != null &amp;&amp; Object.prototype.hasOwnProperty.call(obj, key);
}
</code></pre>
<h3>Crash B: <code>:popover-open</code> inside <code>element.matches()</code> on older iOS Safari</h3>
<p>Checking whether a native popover was open via <code>el.matches(':popover-open')</code> threw a fatal <code>SyntaxError: ':popover-open' is not a valid selector</code> on older iOS Safari versions that don't yet support the Popover API pseudo-class.</p>
<p><strong>Fix:</strong> Guard selector checks and fall back to an explicit class/attribute toggle:</p>
<pre><code class="language-js">function isPopoverVisible(el) {
  if (!el) return false;
  try {
    if (el.matches &amp;&amp; el.matches(":popover-open")) return true;
  } catch (_) {}
  return el.classList.contains("is-open");
}
</code></pre>
<p>After shipping both fixes alongside our <strong><a href="https://minelliongames.com/leaderboard">Live Global Leaderboards</a></strong> (tracking Daily Dig, Weekly Depth, Unlimited Streaks, and Creeper Party AI Ring survival), real-visitor JS crash reports dropped straight to <strong>0</strong>.</p>
<hr />
<h2>3. Turning Live Miss Telemetry Into Better Trivia UX</h2>
<p>Because we log anonymized prompt hit-rates on our edge backend, we also caught three catalog blind spots right away:</p>
<ul>
<li><strong><code>blk-modern</code> (1.19–1.21 blocks)</strong> showed a <strong>0% hit rate</strong> on day 2 because everyday staples like <code>Sculk</code>, <code>Mud</code>, <code>Cherry Planks</code>, <code>Decorated Pot</code>, and <code>Eyeblossom</code> weren't tagged yet → expanded from <strong>22 to 50</strong> valid blocks.</li>
<li><strong><code>itm-unstackable</code> (max stack size 1)</strong> sat at <strong>28.3% (<code>13/46</code>)</strong> because players naturally typed <code>Diamond Helmet</code>, <code>Boat</code>, <code>Bed</code>, <code>Minecart</code>, <code>Milk Bucket</code>, <code>Potion</code>, and <code>Enchanted Book</code> → expanded from <strong>53 to 92</strong> valid items.</li>
<li><strong><code>itm-trim</code></strong> missed half of valid answers because players type <code>sentry</code> or <code>vex trim</code> instead of <code>Sentry Armor Trim</code> → added collision-safe aliases across all 18 Smithing Templates while deliberately excluding bare <code>vex</code> (so it never collides with the hostile <code>Vex</code> mob) and bare <code>ward</code> (keeping <code>Music Disc Ward</code> safe).</li>
</ul>
<p>Because our trivia data lives on static edge JSON endpoints (<code>/_d/trivia/*</code>), we hot-patched all <strong>538 entities</strong> and <strong>115 aliases</strong> with zero downtime and without even redeploying HTML templates <em>(and after another wave of day-3 telemetry, expanded the live catalog further to <strong>621 entities</strong> and <strong>231 collision-safe aliases</strong> across <strong>107 prompts</strong>)</em>.</p>
<hr />
<h2>Try It or Reuse the Code</h2>
<ul>
<li><strong>Play Minellion Games (free, zero login):</strong> <a href="https://minelliongames.com/">https://minelliongames.com/</a></li>
<li><strong>Battle the 5 AI Bots in Creeper Party:</strong> <a href="https://minelliongames.com/creeper-party">https://minelliongames.com/creeper-party</a></li>
<li><strong>Global Leaderboards &amp; Pickaxe Ranks:</strong> <a href="https://minelliongames.com/leaderboard">https://minelliongames.com/leaderboard</a></li>
<li><strong>Full 1.21+ Rarity Guide:</strong> <a href="https://minelliongames.com/rarity-guide">https://minelliongames.com/rarity-guide</a></li>
<li><strong>Open-Source Bot &amp; Resolver Engine (MIT, zero dependencies):</strong> <a href="https://github.com/sunrain113/minecraft-trivia-bot-engine">https://github.com/sunrain113/minecraft-trivia-bot-engine</a></li>
</ul>
<p><em>(Independent fan-made browser project — not affiliated with Mojang, Microsoft, or minellion.io.)</em></p>
<p>If you're building lightweight browser games without heavy frameworks or backend matchmaking, I'd love to hear how you handle solo bot opponents or Safari edge cases in the comments!</p>
]]></content:encoded></item><item><title><![CDATA[Inspecting MP3, WAV & FLAC Locally in Browser RAM: Clipping Detection, FFT & Bluetooth Latency in Vanilla JS]]></title><description><![CDATA[Most online audio file analyzers ask you to upload your MP3, WAV, or FLAC recording to a remote server, wait for an FFmpeg worker, and trust that your…]]></description><link>https://minigamedaily.hashnode.dev/inspecting-mp3-wav-flac-locally-in-browser-ram-clipping-detection-fft-bluetooth-latency</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/inspecting-mp3-wav-flac-locally-in-browser-ram-clipping-detection-fft-bluetooth-latency</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[audio]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Mon, 30 Nov 2026 09:45:10 GMT</pubDate><content:encoded><![CDATA[<p>Most online audio file analyzers ask you to upload your MP3, WAV, or FLAC recording to a remote server, wait for an FFmpeg worker, and trust that your private voice memo or master export gets deleted later. Yet modern browsers already ship a fast, native multi-codec audio decoder and real-time FFT engine right inside the <strong>Web Audio API</strong>.</p>
<p>While building <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong>—a free, zero-login suite of 11 browser-native audio diagnostics running 100% client-side with zero external frameworks—two tools pushed browser audio math furthest: a zero-upload local file inspector and a two-stage Bluetooth gaming latency estimator that works without any microphone or loopback cable.</p>
<p>Here are the exact vanilla JavaScript patterns behind both.</p>
<hr />
<h2>1. Zero-Upload Audio File Inspection with <code>decodeAudioData()</code></h2>
<p>When a user drops an MP3, WAV, FLAC, AAC, M4A, OGG, or WebM file into our <strong><a href="https://soundtesthq.com/audio-quality-test">online audio quality test</a></strong>, nothing leaves browser memory. We read the local <code>File</code> via <code>file.arrayBuffer()</code> and pass it straight to <code>actx.decodeAudioData()</code>:</p>
<pre><code class="language-js">async function inspectLocalAudioFile(file, actx) {
  const buf = await file.arrayBuffer();
  const audioBuffer = await actx.decodeAudioData(buf);
  const channels = audioBuffer.numberOfChannels;
  const length = audioBuffer.length;

  let peak = 0;
  let sumSq = 0;
  let sumDc = 0;
  let clippedSamples = 0;
  let consecutiveClip = 0;
  let clipEvents = 0;

  const left = audioBuffer.getChannelData(0);
  const right = channels &gt; 1 ? audioBuffer.getChannelData(1) : left;

  for (let i = 0; i &lt; length; i++) {
    const l = left[i];
    const r = right[i];
    const absMax = Math.max(Math.abs(l), Math.abs(r));

    if (absMax &gt; peak) peak = absMax;
    sumSq += (l * l + r * r) * 0.5;
    sumDc += (l + r) * 0.5;

    // 3+ consecutive full-scale samples strongly indicates digital clipping
    if (absMax &gt;= 0.999) {
      clippedSamples++;
      consecutiveClip++;
      if (consecutiveClip === 3) clipEvents++;
    } else {
      consecutiveClip = 0;
    }
  }

  const rms = Math.sqrt(sumSq / length);
  const peakDbfs = peak &gt; 0 ? 20 * Math.log10(peak) : -Infinity;
  const rmsDbfs = rms &gt; 0 ? 20 * Math.log10(rms) : -Infinity;
  const crestDb = peakDbfs - rmsDbfs;
  const dcOffset = sumDc / length;

  return {
    sampleRate: audioBuffer.sampleRate,
    durationSec: audioBuffer.duration,
    channels,
    peakDbfs,
    rmsDbfs,
    crestDb,
    dcOffset,
    clippedSamples,
    clipEvents,
  };
}
</code></pre>
<h3>Three Real-World Details That Make File Checks Actually Useful</h3>
<ol>
<li><strong>Detecting clipped <em>runs</em>, not just isolated <code>0 dBFS</code> peaks:</strong> A single sample touching <code>0.999</code> can happen on a clean limiter peak. Counting contiguous runs of <code>&gt;= 3</code> samples at <code>&gt;= 0.999</code> surfaces audible flat-topped digital clipping and lets you highlight exact clipped regions in red on the overview waveform canvas.</li>
<li><strong>Checking lossless vs. lossy shelf cutoffs (<code>FLAC</code> vs. <code>MP3</code>):</strong> Pairing <code>AudioBufferSourceNode</code> playback with an <code>AnalyserNode</code> (<code>fftSize = 4096</code>, <code>smoothingTimeConstant = 0.65</code>) gives roughly <code>11.7 Hz</code> per FFT bin at <code>48 kHz</code>. Even a quick glance at the live 20 Hz–20 kHz spectrum immediately reveals whether a supposed "FLAC" file is actually a transcoded 128 kbps MP3 with a hard brickwall shelf around <code>16 kHz</code>.</li>
<li><strong>Channel solo + balance diagnostics:</strong> Computing per-channel RMS (<code>rmsL</code> vs <code>rmsR</code>) exposes lopsided podcast recordings or mono-in-one-ear exports immediately—and pairs cleanly with our <strong><a href="https://soundtesthq.com/headphone-test">online headphone test</a></strong> whenever a user needs to verify whether an imbalance lives in the audio file or their physical earcups.</li>
</ol>
<hr />
<h2>2. Estimating Bluetooth Audio Latency Without a Loopback Cable</h2>
<p>Measuring end-to-end audio hardware latency in a browser usually hits a wall: browsers cannot read Bluetooth codec buffer sizes (<code>SBC</code> vs. <code>AAC</code> vs. <code>aptX LL</code>) directly, and asking everyday users to wire a physical audio loopback cable into a mic jack is a non-starter.</p>
<p>In our <strong><a href="https://soundtesthq.com/audio-latency-test">online audio latency test</a></strong>, we use a <strong>two-stage differential reaction protocol</strong> that cancels out the user's own reaction time:</p>
<ol>
<li><strong>Stage 1 — Visual Baseline (5 randomized trials):</strong> After a random 1.2s–2.8s delay, a high-contrast visual card flashes on screen (<code>requestAnimationFrame</code> timestamped via <code>performance.now()</code>). The user taps/clicks as fast as they can. We drop outliers and record their median visual reaction time (<code>V_med</code>, typically ~220–270 ms).</li>
<li><strong>Stage 2 — Audio Pulse Stage (5 randomized trials):</strong> Using the same randomized wait window, we schedule a crisp 1 kHz Web Audio pulse and record their median tap delay (<code>A_med</code>).</li>
<li><strong>Differential Latency Estimate:</strong> In human psychophysics, simple auditory reaction time is actually ~30–40 ms <em>faster</em> than visual reaction time (<code>Δ_phys ≈ 35 ms</code>). So if a user reacts <code>145 ms</code> slower to audio than to the visual flash, their Bluetooth stack is actually adding roughly <code>145 + 35 = 180 ms</code> of latency:</li>
</ol>
<pre><code class="language-js">function median(arr) {
  const s = arr.slice().sort((a, b) =&gt; a - b);
  const mid = Math.floor(s.length / 2);
  return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
}

// Positive result = estimated wireless/OS audio output delay in ms
function estimateAudioLatencyMs(visualTrialsMs, audioTrialsMs) {
  const PHYSIOLOGICAL_AV_OFFSET_MS = 35; // auditory RT is ~35 ms faster than visual RT
  const vMed = median(visualTrialsMs);
  const aMed = median(audioTrialsMs);
  return Math.max(0, Math.round((aMed - vMed) + PHYSIOLOGICAL_AV_OFFSET_MS));
}
</code></pre>
<h3>Touch Latency Trap We Caught on Mobile Safari</h3>
<p>On mobile browsers, binding tap responses to <code>click</code> adds up to <code>100–300 ms</code> of synthetic tap delay and double-tap-to-zoom jitter, which completely swamps a 40 ms wired vs. 180 ms Bluetooth comparison. Switching the reaction pad to <strong><code>pointerdown</code></strong> with <code>touch-action: manipulation</code> and <code>user-select: none</code> eliminated touch jitter across iOS and Android immediately.</p>
<p><em>(For readers comparing interactive gaming lag against TV/OBS dialogue drift, we also wrote a short reference guide explaining <strong><a href="https://soundtesthq.com/guides/audio-latency-vs-audio-delay-benchmarks">audio latency vs. audio delay benchmarks</a></strong> across wired 3.5 mm, 2.4 GHz dongles, aptX Low Latency, and standard Bluetooth AAC/SBC.)</em></p>
<hr />
<h2>Honest Scope &amp; Try It Locally</h2>
<p>Browser diagnostics are built for fast everyday checks—spotting digital clipping, verifying lossless spectrum cutoffs, checking Bluetooth headset lag, and isolating left/right earcup issues—not replacing certified acoustic lab hardware like REW or APx analyzers.</p>
<p>Every tool runs strictly in local browser memory with zero downloads, zero accounts, and zero server uploads (verifiable in 10 seconds in DevTools → Network). You can try all 11 diagnostics on <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong>.</p>
]]></content:encoded></item><item><title><![CDATA[How We Dropped Real-User Mobile CLS from 0.326 to 0.058 and Fixed an Async Start-Button Race Condition in Zero-Framework Browser Games]]></title><description><![CDATA[How we cut real-user mobile CLS from 0.326 to 0.058 and fixed an async Promise.all start-button crash in zero-framework browser games.]]></description><link>https://minigamedaily.hashnode.dev/fixing-mobile-cls-and-async-start-race-conditions-in-zero-framework-browser-games</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/fixing-mobile-cls-and-async-start-race-conditions-in-zero-framework-browser-games</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[GameDev]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Mon, 30 Nov 2026 09:19:43 GMT</pubDate><content:encoded><![CDATA[<p>Shipping browser games without React, Vue, or a client bundler makes initial loads fast—until real mobile users arrive on flaky 4G connections and start tapping buttons 180 milliseconds after First Paint.</p>
<p>This week, while monitoring real-user telemetry (RUM) and automatic browser error reports on <strong><a href="https://minigamedaily.com/">MiniGameDaily</a></strong>—an independent hub of zero-login daily browser puzzles and our 25-second <strong><a href="https://minigamedaily.com/krillion-unlimited">Krillion Unlimited practice mode</a></strong>—two subtle production bugs showed up in the wild:</p>
<ol>
<li><strong>7-day real-user CLS sat at <code>0.326</code> (<code>poor</code>)</strong> even though desktop Lighthouse reports looked spotless.</li>
<li><strong>An Android Chrome visitor triggered an uncaught runtime crash</strong> (<code>Uncaught TypeError: Cannot read properties of undefined (reading 'q')</code>) the moment they tapped the primary Start button on a slow connection.</li>
</ol>
<p>Both bugs came from the same architectural tension: <strong>server-rendering an interactive game shell immediately while hydrating JSON prompt decks asynchronously from the edge.</strong></p>
<p>Here is exactly how both bugs happened, the minimal vanilla-JS/CSS fixes we shipped, and what changed in real-user metrics within 24 hours.</p>
<p><em>(Disclosure: MiniGameDaily is an independent browser-game hub and practice trainer; we are not affiliated with <code>krillion.io</code>.)</em></p>
<hr />
<h2>Bug 1: Why Zero-Framework SSR Shells Still Trigger <code>0.326</code> Mobile CLS</h2>
<p>When you ditch client frameworks and server-render clean HTML, it is easy to assume layout shift is solved. It isn't.</p>
<p>In a browser puzzle widget, the game container is rendered in SSR HTML so visitors see the title, mode toggles, and start card immediately. Then, 200–600 ms later, the inline widget script fetches its edge JSON prompt deck and populates:</p>
<ul>
<li>A dynamic prompt box (switching from a 1-line placeholder to a 2–3 line trivia prompt)</li>
<li>A score/leaderboard drawer that suddenly toggles <code>hidden = false</code></li>
<li>An embedded SVG canvas or timer bar whose intrinsic height wasn't locked before JS measured <code>clientWidth</code></li>
</ul>
<p>On fast desktop Wi-Fi, those DOM updates finish before the browser settles its first paint window. On mobile phones—where users begin scrolling or reading before the JSON response returns—every vertical push below the fold adds directly to Cumulative Layout Shift.</p>
<h3>The 3-Part Fix That Brought 24h RUM CLS Down to <code>0.058</code></h3>
<p>We didn't rewrite the widgets. We applied three strict geometric constraints across our game containers:</p>
<ol>
<li><strong>Reserve explicit vertical height on every dynamic slot before hydration.</strong>
Prompt banners, HUD rows, and status lines got explicit <code>min-height</code> values tuned to their worst-case 2-line mobile wrap so swapping placeholder text for a real prompt never pushes the game stage down a single pixel.</li>
<li><strong>Lock stage geometry with CSS <code>aspect-ratio</code> instead of JS sizing.</strong>
For interactive vector canvases and timed input stages, setting <code>aspect-ratio</code> directly on the outer shell ensures the browser allocates the exact pixel box at initial HTML parse—long before external geometry or prompt packs arrive.</li>
<li><strong>Keep secondary panels (<code>leaderboard</code>, <code>round summary</code>, <code>confirm bar</code>) strictly out of initial flow or below a reserved anchor.</strong>
Never inject a variable-height banner <em>above</em> an element the user is already looking at.</li>
</ol>
<p>After shipping those widget layout locks, <strong>24-hour real-user CLS dropped from <code>0.326</code> (7-day baseline) down to <code>0.058</code> (<code>good</code>)</strong>, alongside <strong><code>INP 56 ms</code></strong> and <strong><code>LCP 2,122 ms</code></strong>—without sacrificing instant SSR interactivity.</p>
<hr />
<h2>Bug 2: The 180-Millisecond Start-Button Race Condition</h2>
<p>Two days later, our visitor error collector surfaced a single Android Chrome stack trace:</p>
<pre><code class="language-text">TypeError: Cannot read properties of undefined (reading 'q')
    at loadRound (.../game-widget.js:496:48)
    at startNewRun (.../game-widget.js:563:18)
    at HTMLButtonElement.&lt;anonymous&gt; (.../game-widget.js:609:7)
</code></pre>
<p>We checked the live JSON prompt pack first—all 63 prompts were valid with zero missing <code>.q</code> fields. So why was <code>state.currentPrompt</code> <code>undefined</code>?</p>
<p>Look at the classic SSR + async hydration sequence:</p>
<pre><code class="language-js">// 1. Click listener attaches synchronously on script evaluation
elStartBtn.addEventListener("click", function () {
  startNewRun(state.mode);
});

// 2. Prompt deck &amp; static assets load asynchronously
Promise.all([
  fetch(DATA_BASE + "countries").then(r =&gt; r.json()),
  fetch(DATA_BASE + "prompts").then(r =&gt; r.json()),
  fetchWorldAtlas()
]).then(function (res) {
  state.prompts = res[1].prompts || [];
  renderStage(res[2], res[0]);
  elLoading.hidden = true;
  prepareIdleState();
});
</code></pre>
<p>On desktop broadband, <code>Promise.all</code> finishes in ~250 ms—faster than a human moves their mouse to the Start button. On mobile cellular networks, the SSR Start button renders immediately at the top of the card while the external TopoJSON/prompt bundle is still in flight for 1.5–3 seconds.</p>
<p>An eager mobile player taps <strong>Start</strong>, <code>startNewRun()</code> shuffles <code>state.prompts</code> (still <code>[]</code>), <code>nextPromptFromDeck()</code> returns <code>undefined</code>, and <code>elPrompt.textContent = state.currentPrompt.q</code> throws—halting the entire game loop.</p>
<h3>Don't Just Disable the Button—Queue the Intent</h3>
<p>The naive fix is adding <code>disabled</code> to the SSR Start button until <code>Promise.all</code> resolves. That prevents the crash, <strong>but it feels sluggish on mobile</strong>: a player taps once, nothing happens, and they have to tap a second time a second later.</p>
<p>Instead, we implemented an <strong>intent-queuing state machine</strong> (<code>ready</code>, <code>loadFailed</code>, <code>pendingStart</code>) with defensive guards all the way down to <code>loadRound()</code>:</p>
<pre><code class="language-js">var state = {
  ready: false,
  loadFailed: false,
  pendingStart: false,
  started: false,
  mode: "survival",
  prompts: [],
  deck: [],
  deckIdx: 0
};

function nextPromptFromDeck() {
  if (!state.prompts || !state.prompts.length) return null;
  if (state.deckIdx &gt;= state.deck.length) {
    state.deck = shuffle(state.prompts);
    state.deckIdx = 0;
  }
  return state.deck[state.deckIdx++] || null;
}

function startNewRun(mode) {
  if (mode) state.mode = mode;

  // Guard: data still hydrating or failed
  if (!state.ready || !state.prompts.length) {
    syncModeButtons();
    if (state.loadFailed) {
      elPrompt.textContent = "Could not load game data. Please refresh to retry.";
      return;
    }
    state.pendingStart = true;
    if (elStartBtn) elStartBtn.textContent = "Loading…";
    elPrompt.textContent = "Loading deck — your run will start automatically…";
    return;
  }

  state.pendingStart = false;
  if (elStartBtn) elStartBtn.textContent = "Start endless run";
  state.started = true;
  state.deck = shuffle(state.prompts);
  state.deckIdx = 0;
  loadRound();
}
</code></pre>
<p>Then, inside the <code>Promise.all</code> resolution handler:</p>
<pre><code class="language-js">]).then(function (res) {
  var loadedPrompts = (res[1] &amp;&amp; Array.isArray(res[1].prompts))
    ? res[1].prompts.filter(function (p) { return p &amp;&amp; typeof p.q === "string" &amp;&amp; p.q.trim(); })
    : [];
  if (!loadedPrompts.length) throw new Error("empty prompts");

  state.prompts = loadedPrompts;
  renderStage(res[2], res[0]);
  state.ready = true;
  state.loadFailed = false;
  elLoading.hidden = true;

  // Honor an early mobile tap seamlessly instead of making the user tap twice
  if (state.pendingStart) {
    state.pendingStart = false;
    startNewRun(state.mode);
  } else {
    prepareIdleState();
  }
}).catch(function () {
  state.ready = false;
  state.loadFailed = true;
  state.pendingStart = false;
  if (elStartBtn) elStartBtn.textContent = "Start endless run";
  elPrompt.textContent = "Could not load game data. Please refresh to retry.";
});
</code></pre>
<p>And one final belt-and-suspenders guard in <code>loadRound()</code>:</p>
<pre><code class="language-js">function loadRound(restoredPrompt, restoredSecs) {
  var nextPrompt = restoredPrompt || nextPromptFromDeck();
  if (!nextPrompt || !nextPrompt.q) {
    prepareIdleState();
    return;
  }
  state.currentPrompt = nextPrompt;
  elPrompt.textContent = state.currentPrompt.q;
  // ...
}
</code></pre>
<h3>Why This Pattern Works Better for Daily Web Games</h3>
<ol>
<li><strong>Zero lost first taps:</strong> If a player taps Start (or even switches between Survival and Relaxed mode mid-load), <code>state.mode</code> updates live and the run auto-starts the millisecond hydration finishes.</li>
<li><strong>Graceful offline degradation:</strong> If a CDN times out or returns a malformed payload, tapping Start never throws—it surfaces an actionable retry prompt.</li>
<li><strong>Zero SSR HTML churn:</strong> Because the entire fix lives in 40 lines of client JS, the SSR markup and layout stay untouched with zero CLS penalty.</li>
</ol>
<hr />
<h2>Bonus: Open-Sourcing the Rarity-Scoring Core</h2>
<p>While hardening our game widgets for mobile play on <strong><a href="https://minigamedaily.com/krillion-unlimited">Krillion endless mode</a></strong> (now over 120 curated prompts and 2,000+ verified tiered answers), we also extracted the core 6-tier rarity-scoring bucket engine and 2-pass typo normalizer into a standalone, zero-dependency MIT package:</p>
<ul>
<li><strong>GitHub (<code>v1.0.0</code>)</strong>: <a href="https://github.com/sunrain113/rarity-trivia-scorer-js">sunrain113/rarity-trivia-scorer-js</a> — calibrated percentile depth tiers, NFD diacritic/article stripping, and length-guarded Levenshtein fallback (<code>node --test</code>, 6/6 passing).</li>
<li><strong>Playable trainer &amp; mechanics breakdown</strong>: try <strong><a href="https://minigamedaily.com/krillion-unlimited">Krillion unlimited guide</a></strong> or browse the rest of our lightweight browser puzzles on <strong><a href="https://minigamedaily.com/">MiniGameDaily</a></strong>.</li>
</ul>
<h3>Quick Checklist for Anyone Building SSR + Vanilla JS Web Games</h3>
<ul>
<li><input disabled type="checkbox" /> Lock container heights (<code>min-height</code> / <code>aspect-ratio</code>) in CSS before any <code>fetch()</code> resolves.</li>
<li><input disabled type="checkbox" /> Treat every SSR button as clickable at <code>t = 0 ms</code>—assume users <em>will</em> tap before your JSON or TopoJSON finishes loading.</li>
<li><input disabled type="checkbox" /> Queue early user intent (<code>pendingStart</code>) instead of silently ignoring clicks or leaving unguarded array accesses in <code>loadRound()</code>.</li>
<li><input disabled type="checkbox" /> Filter hydrated JSON entries defensively (<code>p &amp;&amp; typeof p.q === "string"</code>) so a single malformed record can never take down a session.</li>
<li><input disabled type="checkbox" /> Collect real-user RUM vitals and <code>window.onerror</code> stacks—desktop Lighthouse almost never catches a 4G mobile tap race.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Building 5.1/7.1 Surround Routing, A/V Lip-Sync Metronomes & Blind Audio Tests in Vanilla JS]]></title><description><![CDATA[Three vanilla JS Web Audio patterns: discrete 5.1/7.1 routing with HRTF fallback, sample-accurate A/V lip-sync, and blind L/R headphone state locks.]]></description><link>https://minigamedaily.hashnode.dev/building-5-1-7-1-surround-routing-a-v-lip-sync-metronomes-blind-audio-tests-in-vanilla-js</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/building-5-1-7-1-surround-routing-a-v-lip-sync-metronomes-blind-audio-tests-in-vanilla-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webaudio]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Sat, 28 Nov 2026 00:46:26 GMT</pubDate><content:encoded><![CDATA[<p>Most browser audio demos stop at playing a single sine wave or visualizing an MP3. Once you try building a full diagnostic toolkit—covering 5.1/7.1 surround channel mapping, millisecond-accurate A/V lip-sync checks, blind left/right headphone orientation quizzes, and 20 Hz–20 kHz logarithmic tone sweeps—the Web Audio API starts throwing subtle hardware, timing, and UI state challenges at you.</p>
<p>While building and refining <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong> (11 zero-upload, browser-native audio diagnostics written in vanilla HTML/CSS/JS with zero runtime frameworks), three engineering patterns made the biggest difference between a toy demo and something genuinely reliable across desktop monitors, HDMI receivers, and phones.</p>
<hr />
<h2>1. Discrete 5.1/7.1 Hardware Routing with Automatic 3D HRTF Fallback</h2>
<p>Testing a 5.1 or 7.1 speaker system in a browser has an immediate catch: most desktop laptops and mobile devices expose only <code>2</code> hardware output channels (<code>actx.destination.maxChannelCount === 2</code>), whereas a Windows or macOS machine configured for multichannel PCM over HDMI or USB exposes <code>6</code> or <code>8</code>.</p>
<p>If you blindly construct a 6- or 8-channel <code>ChannelMergerNode</code> on a stereo device, the browser silently downmixes surround channels together—making Side Left (<code>SL</code>) and Rear Left (<code>RL</code>) sound identical to Front Left (<code>FL</code>).</p>
<p>Our fix in the <strong><a href="https://soundtesthq.com/surround-sound-test">5.1 &amp; 7.1 surround sound test</a></strong> checks <code>actx.destination.maxChannelCount</code> dynamically and switches between two distinct audio graphs:</p>
<ul>
<li><strong>Discrete hardware path (<code>maxCh &gt;= needed</code>):</strong> Locks <code>channelCountMode = 'explicit'</code> and <code>channelInterpretation = 'discrete'</code>, then connects the band-passed pink noise (or 55 Hz LFE sine) directly into the exact SMPTE channel index on a <code>ChannelMergerNode</code> (<code>FL=0</code>, <code>FR=1</code>, <code>C=2</code>, <code>LFE=3</code>, with <code>SL/SR</code> mapping to <code>4/5</code> in 5.1 and <code>6/7</code> in 7.1).</li>
<li><strong>Stereo / headphone fallback (<code>maxCh &lt; needed</code>):</strong> Uses a <code>PannerNode</code> with <code>panningModel = 'HRTF'</code> and places each virtual speaker around the listener by azimuth angle (<code>±30°</code> fronts, <code>±110°</code> 5.1 surrounds, <code>±90°</code> / <code>±145°</code> 7.1 sides/rears), while showing a transparent status banner explaining how to unlock discrete PCM in Windows Sound Configure or macOS Audio MIDI Setup.</li>
</ul>
<pre><code class="language-js">var needed = state.layout === '7.1' ? 8 : 6;
var maxCh = actx.destination.maxChannelCount || 2;
var discrete = maxCh &gt;= needed;

actx.destination.channelCount = discrete ? needed : Math.min(2, maxCh);
actx.destination.channelCountMode = 'explicit';
actx.destination.channelInterpretation = discrete ? 'discrete' : 'speakers';

if (discrete) {
  var merger = actx.createChannelMerger(needed);
  var chIdx = state.layout === '7.1' ? cfg.ch71 : cfg.ch51;
  env.connect(merger, 0, chIdx);
  merger.connect(masterGain);
} else if (!cfg.lfe &amp;&amp; actx.createPanner) {
  var panner = actx.createPanner();
  panner.panningModel = 'HRTF';
  var rad = (az * Math.PI) / 180;
  panner.positionX.value = Math.sin(rad) * 2;
  panner.positionY.value = 0;
  panner.positionZ.value = -Math.cos(rad) * 2;
  env.connect(panner);
  panner.connect(masterGain);
}
</code></pre>
<hr />
<h2>2. Sample-Accurate A/V Lip-Sync Scheduling (<code>-100 ms</code> to <code>+400 ms</code>)</h2>
<p>Anyone who has debugged Bluetooth earbuds, HDMI ARC soundbars, or OBS capture cards knows that a 180 ms A/V offset ruins dialogue. You might think you can test lip-sync with a <code>setInterval</code> flash and beep—but JavaScript main-thread timers routinely jitter by 15–40 ms, which is larger than the entire ITU lip-sync tolerance window (<code>-20 ms</code> to <code>+45 ms</code>).</p>
<p>In our <strong><a href="https://soundtesthq.com/audio-delay-test">online audio delay test</a></strong>, both the 60fps canvas animation and the click oscillator derive from the exact same hardware clock: <code>actx.currentTime</code>.</p>
<ol>
<li>Pick a fixed origin timestamp (<code>originAudioTime = actx.currentTime + 0.2</code>) and beat period (<code>0.8s</code>).</li>
<li>Inside <code>requestAnimationFrame</code>, derive visual triangle-wave phase purely from <code>(actx.currentTime - originAudioTime) / (PERIOD * 2)</code> so the moving bar always crosses the center line at <code>originAudioTime + (0.5 + n) * PERIOD</code>.</li>
<li>Run a lightweight 25 ms lookahead scheduler that books short 1,100 Hz sine clicks ahead of time at:</li>
</ol>
<pre><code class="language-js">var visualHitTime = avState.originAudioTime + (0.5 + avState.nextBeatIdx) * PERIOD;
var audioTime = visualHitTime - (avState.offsetMs / 1000);
if (audioTime &gt; actx.currentTime + 0.01) {
  scheduleClickAt(audioTime);
}
</code></pre>
<p>When the user drags the offset slider right (<code>+200 ms</code>), the Web Audio scheduler fires the click 200 ms <em>earlier</em> so that after passing through a 200 ms Bluetooth buffer, the click arrives at the user's ears at the exact millisecond the visual bar hits center.</p>
<p>One practical visual detail we learned during mobile QA: always sync <code>&lt;canvas&gt;</code> backing buffers to <code>clientWidth * Math.min(devicePixelRatio, 2)</code> via <code>ResizeObserver</code> and <code>ctx.setTransform(dpr, 0, 0, dpr, 0, 0)</code>. Otherwise, high-DPR phones stretch canvas coordinate labels and blur thin reference ticks.</p>
<hr />
<h2>3. Two Subtle UX Traps: Blind-Test Spoilers &amp; Logarithmic Tone Scaling</h2>
<p>Two real-world QA bugs taught us that audio tooling UX is just as much about UI state discipline as DSP math:</p>
<ol>
<li><strong>VU meters and pan sliders spoil blind L/R checks:</strong> In our <strong><a href="https://soundtesthq.com/headphone-test">online headphone test</a></strong>, the Blind L/R Ear Check plays a 900 ms tone in a hidden earcup and asks which ear you heard. Initially, the audio engine updated the shared pan state (<code>-100</code> or <code>+100</code>), which quietly moved the stereo pan slider, lit up the matching earcup card, and animated either the blue <code>L</code> or teal <code>R</code> oscilloscope trace! Fixing it meant introducing an explicit <code>blindActive</code> lock that keeps the pan slider centered and disabled (<code>Hidden (Blind Check)</code>), zeroes both VU bars, draws a single neutral slate waveform so the user confirms playback is alive without color-coding left vs. right, and keeps that lock intact even after the 900 ms beep ends until the user clicks a guess.</li>
<li><strong>Linear sliders feel broken from 20 Hz to 20,000 Hz:</strong> Human pitch perception is logarithmic—half the audible octave range sits below 630 Hz. In our <strong><a href="https://soundtesthq.com/frequency-test">20 Hz–20 kHz frequency test</a></strong>, mapping the slider exponentially (<code>20 * Math.pow(1000, v / 1000)</code>) gives equal physical thumb travel per octave, while automatically trimming gain on <code>square</code> and <code>sawtooth</code> waves (<code>0.32</code> vs <code>0.8</code> for pure <code>sine</code>) prevents harsh harmonic loudness jumps when users toggle waveforms mid-test.</li>
</ol>
<hr />
<p>Everything runs 100% locally in browser memory with zero downloads, zero accounts, and zero server uploads. If you're working with Web Audio routing or want to check your own speakers, headphones, surround layout, or Bluetooth lip-sync right in the browser, you can try all 11 diagnostics on <strong><a href="https://soundtesthq.com/">SoundTestHQ</a></strong>. </p>
]]></content:encoded></item><item><title><![CDATA[Why Browser Trivia Games Fail to Load on Phones & School Chromebooks (And How Minellion Games Fixes It)]]></title><description><![CDATA[If you have ever opened a daily browser trivia game on an iPhone, Android phone, or school Chromebook only to hit a blank gray rectangle or a frozen input…]]></description><link>https://minigamedaily.hashnode.dev/why-browser-trivia-games-fail-to-load-minellion-games</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/why-browser-trivia-games-fail-to-load-minellion-games</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[GameDev]]></category><category><![CDATA[minecraft]]></category><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Fri, 27 Nov 2026 23:21:59 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://minelliongames.com/_a/share.ad8a78cb27.png" alt="Minellion Games — Free Browser Minecraft Reverse-Trivia" /></p>
<p>If you have ever opened a daily browser trivia game on an iPhone, Android phone, or school Chromebook only to hit a blank gray rectangle or a frozen input box, the root cause is rarely your device—it is usually how the game was embedded and bundled.</p>
<p>When I built <strong><a href="https://minelliongames.com/">Minellion Games</a></strong>—an independent, fan-made Minecraft reverse-trivia digging game inspired by Minellion and Krillion—my primary engineering goal was making sure every mode loads reliably across <strong>Windows, Mac, iPhone (Safari), Android (Chrome), iPads/tablets, and restricted school Chromebooks</strong> with <strong>zero downloads, zero subscriptions, and zero account signup</strong>.</p>
<p><em>(Transparency note: Minellion Games is an independent fan project at <code>minelliongames.com</code>. It is not an official Minecraft product and is not affiliated with Mojang AB, Microsoft, or Hydro's original <code>minellion.io</code>.)</em></p>
<hr />
<h2>Why Many Browser Trivia Games Stop Loading (Especially on Mobile &amp; Campus Wi-Fi)</h2>
<p>Across dozens of browser puzzle and trivia sites, loading failures almost always trace back to four architectural pitfalls:</p>
<ol>
<li><strong>Cross-origin <code>&lt;iframe&gt;</code> embeds:</strong> Game portals often wrap a third-party game domain inside an iframe. School and office firewalls routinely block the embedded domain while letting the wrapper page load, leaving players with an empty gray frame.</li>
<li><strong>Oversized asset bundles &amp; WebGL canvases:</strong> Pulling megabytes of textures or WebGL shaders before the first prompt appears causes timeouts on spotty mobile data or low-RAM Chromebooks.</li>
<li><strong>Aggressive ad/script blocker collisions:</strong> When game data fetches share paths with analytics or ad trackers, privacy extensions can accidentally block the trivia dataset itself.</li>
<li><strong>Mobile virtual keyboard traps:</strong> On <code>375px–390px</code> phone screens, fixed-height iframes often clip the answer field behind the iOS Safari or Android keyboard as soon as the 25-second round clock starts ticking.</li>
</ol>
<hr />
<h2>How Minellion Games Engineers Reliable Cross-Device Play</h2>
<p>Instead of wrapping external embeds, everything on <code>minelliongames.com</code> runs natively in first-party HTML, CSS, and lightweight vanilla JavaScript against a compact Minecraft Java &amp; Bedrock 1.21+ JSON lexicon:</p>
<ul>
<li><strong>100% first-party DOM (zero external iframes):</strong> There is no third-party frame for a firewall to block. For quiet classrooms and office networks, our <a href="https://minelliongames.com/unblocked">Minellion Unblocked</a> page exposes an instant Web Audio <code>SFX: Off</code> toggle right in the console HUD.</li>
<li><strong>No app install or registration wall:</strong> Minellion Games is strictly browser-based—there is no official mobile app on the App Store or Google Play (players should avoid third-party APK wrappers claiming to be an official app). Progress, daily streaks, and sound preferences persist locally in <code>localStorage</code>, with only an optional anonymous miner nickname for the UTC Daily Leaderboard.</li>
<li><strong>Mobile-first typing ergonomics:</strong> Under a 25-second timer, typing long blocks like <code>Waxed Weathered Cut Copper Stairs</code> on a phone keyboard is tough. Built-in autocomplete hints, 1–2 character typo tolerance, and shorthand resolution (<code>wither skelly</code>, <code>gap</code>, <code>egap</code>, <code>e-pearl</code>, <code>totem</code>, <code>cmd block</code>) let players dig down from Surface Grass (<code>Y+64</code>) to Bedrock (<code>Y-64</code>, 128 blocks deep) without losing valid answers to thumb slips.</li>
<li><strong>Live retry before timeout:</strong> If a player submits an unrecognized or wrong-category guess, the console reports it immediately so they can fix and resubmit while the 25-second clock is still running (skipping or timing out scores <code>0</code> blocks; each entity can only be used once per 7-prompt shaft).</li>
</ul>
<hr />
<h2>Step-by-Step Troubleshooting: Fixing a Browser Trivia Game That Won't Load</h2>
<p>If a browser trivia game like Minellion Games stalls, fails to open, or freezes on your phone or computer, work through this quick checklist before assuming the server is down:</p>
<h3>On iPhone (Safari) &amp; Android (Chrome)</h3>
<ol>
<li><strong>Toggle Wi-Fi vs. mobile data:</strong> Captive portals and filtered public Wi-Fi often stall JSON requests.</li>
<li><strong>Use an updated browser:</strong> Open the URL directly in current <strong>Safari</strong> (iOS) or <strong>Chrome</strong> (Android) rather than inside an in-app social media webview.</li>
<li><strong>Refresh and free memory:</strong> Close heavy background tabs and reload the page.</li>
<li><strong>Clear site cache:</strong> Clear cached website data for the domain if an old script bundle is stuck in cache.</li>
</ol>
<h3>On Windows, Mac &amp; School Chromebooks</h3>
<ol>
<li><strong>Hard-refresh the tab:</strong> Press <code>Ctrl+F5</code> (Windows/Chromebook) or <code>Cmd+Shift+R</code> (Mac).</li>
<li><strong>Verify JavaScript &amp; local storage:</strong> Confirm JavaScript is enabled and site storage isn't blocked in strict private mode if streaks aren't saving.</li>
<li><strong>Pause script/ad blockers temporarily:</strong> Test once with aggressive content blockers paused to see if local trivia JSON files are being intercepted.</li>
<li><strong>Use a zero-iframe entry point on filtered networks:</strong> Bookmark a native first-party page such as <a href="https://minelliongames.com/unblocked">Minellion Unblocked</a> rather than iframe-based portals.</li>
</ol>
<hr />
<h2>Choosing a Daily Browser Trivia Game by Device &amp; Play Style</h2>
<p>Looking for free, browser-playable daily trivia or Minecraft guessing alternatives that work cleanly across desktop and mobile without downloads? Here is a quick comparison by format and accessibility:</p>
<table>
<thead>
<tr>
<th>Browser Game</th>
<th>Core Format</th>
<th>Modes Available</th>
<th>Registration / Cost</th>
<th>Best Suited For</th>
</tr>
</thead>
<tbody><tr>
<td><strong><a href="https://minelliongames.com/">Minellion Games</a></strong></td>
<td>Minecraft 1.21+ reverse-trivia digging (7 timed prompts, Y+64 to Y-64 Bedrock)</td>
<td>Daily Dig (00:00 UTC), <a href="https://minelliongames.com/unlimited">Unlimited</a> (6 packs + Zen/Blitz), local <a href="https://minelliongames.com/creeper-party">Creeper Party</a>, <a href="https://minelliongames.com/rarity-guide">Rarity Guide</a></td>
<td>No signup, 100% free forever, zero iframes</td>
<td>Mobile, tablet &amp; Chromebook players wanting instant zero-login daily + category practice</td>
</tr>
<tr>
<td><strong>Minellion (Original by Hydro)</strong></td>
<td>Original Minecraft reverse-trivia digging game</td>
<td>Daily Dig, Unlimited, Past Digs, online Creeper Party rooms</td>
<td>Free (optional Google sign-in &amp; optional ad-removal)</td>
<td>Players wanting online public rooms, Minecraft skins, and cross-device synced streaks</td>
</tr>
<tr>
<td><strong>Krillion</strong></td>
<td>General-knowledge reverse-trivia (rarer valid picks dive deeper underwater)</td>
<td>Daily challenge</td>
<td>Free, no signup</td>
<td>General trivia fans who enjoy reverse-consensus strategy</td>
</tr>
<tr>
<td><strong>MCdle</strong></td>
<td>Wordle-style Minecraft clue guessing (mobs, items, blocks)</td>
<td>Daily puzzles</td>
<td>Free, no signup</td>
<td>Players who prefer step-by-step deduction over timed recall</td>
</tr>
<tr>
<td><strong>Wordle</strong></td>
<td>Five-letter daily word guessing in 6 attempts</td>
<td>Daily puzzle</td>
<td>Free (optional account)</td>
<td>Classic short daily word puzzles</td>
</tr>
<tr>
<td><strong>Worldle</strong></td>
<td>Daily country silhouette &amp; distance/direction geography guessing</td>
<td>Daily puzzle</td>
<td>Free, no signup</td>
<td>Geography and world-map fans</td>
</tr>
</tbody></table>
<hr />
<h2>Try It Live &amp; Practice Weak Categories</h2>
<p>If you want to benchmark your Minecraft 1.21+ recall—whether in today's shared 7-prompt Daily Dig, untimed Zen drills in <a href="https://minelliongames.com/unlimited">Minellion Unlimited</a>, or a 2–12 player Pass &amp; Play match in <a href="https://minelliongames.com/creeper-party">Creeper Party</a>—everything is live in your browser at <strong><a href="https://minelliongames.com/">minelliongames.com</a></strong>. You can also browse 400+ calibrated mobs, blocks, armor trims, music discs, and biomes inside the <a href="https://minelliongames.com/rarity-guide">Minellion Rarity Guide</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Fixing Silent Web Audio on iOS Safari & Mobile Mic Errors: Lessons from Building 11 Browser Audio Tools]]></title><description><![CDATA[webdev, javascript, audio, tutorial]]></description><link>https://minigamedaily.hashnode.dev/fixing-silent-web-audio-on-ios-safari-mobile-mic-errors-lessons-from-building-11-browser-audio-tools</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/fixing-silent-web-audio-on-ios-safari-mobile-mic-errors-lessons-from-building-11-browser-audio-tools</guid><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Thu, 26 Nov 2026 15:36:22 GMT</pubDate><content:encoded><![CDATA[<p>When you build browser-based audio diagnostics, desktop Chrome tricks you into thinking the Web Audio API is effortless. Open an <code>AudioContext</code>, wire up an oscillator or <code>AnalyserNode</code>, request <code>getUserMedia()</code>, and everything works on the first try.</p>
<p>Then you open the same page on an iPhone with the side Ring/Silent switch flipped down—or test a Bluetooth headset mic on Android—and half your tools go silent or throw unexpected <code>TypeError</code> and <code>OverconstrainedError</code> exceptions.</p>
<p>While building <a href="https://soundtesthq.com"><strong>SoundTestHQ</strong></a>, a zero-upload browser audio diagnostic suite with 11 vanilla JavaScript utilities running strictly in browser RAM, those mobile Web Audio quirks showed up immediately in real-world testing. Here are three production fixes that solved them without adding frameworks or external libraries.</p>
<hr />
<h2>1. Bypassing the iPhone Physical Mute Switch (<code>navigator.audioSession</code>)</h2>
<p>By default, Web Audio API output in iOS Safari runs on the <code>ambient</code> audio session channel. That means if a visitor has their iPhone side mute switch enabled (as a huge portion of mobile users do all day), tapping <strong>Play Tone</strong> or <strong>Left Speaker (L)</strong> produces complete silence through phone speakers—making users assume the web app itself is broken.</p>
<p>Modern iOS Safari (iOS 17+) exposes <code>navigator.audioSession</code>. Setting <code>navigator.audioSession.type = 'playback'</code> before creating or resuming the <code>AudioContext</code> switches output to the media playback channel, matching how web video and music players behave when users intentionally tap play:</p>
<pre><code class="language-js">function ensureAudio() {
  if (!AudioCtx) {
    showError('Web Audio API is unavailable in this browser.');
    return false;
  }
  if (navigator.audioSession &amp;&amp; navigator.audioSession.type !== 'playback') {
    try { navigator.audioSession.type = 'playback'; } catch (e) {}
  }
  if (!actx || actx.state === 'closed') {
    actx = new AudioCtx();
    // ... build stereo ChannelMergerNode graph
  }
  safeResume(actx);
  return true;
}
</code></pre>
<p>We paired that with explicit stereo routing via <code>actx.createChannelMerger(2)</code> in our <a href="https://soundtesthq.com/speaker-test"><strong>online speaker test</strong></a> so left, right, and wiring polarity checks stay isolated down to the individual channel (<code>rSign = state.phase === 'out' ? -1 : 1</code>) while still resuming safely inside <code>touchstart</code> handlers if Safari suspends the context after backgrounding.</p>
<hr />
<h2>2. Preventing Mobile <code>getUserMedia</code> Constraint Rejections &amp; Frozen Analysers</h2>
<p>For accurate level measurement, you want raw microphone input—without browser automatic gain control (AGC), echo cancellation, or noise suppression flattening room dynamics. Passing <code>{ echoCancellation: false, noiseSuppression: false, autoGainControl: false }</code> works cleanly on most desktop setups, yet certain mobile browsers or in-app webviews reject one of those constraints or hang when users rapidly toggle devices.</p>
<p>Two defensive patterns fixed almost every mobile mic error:</p>
<ol>
<li><strong>Constraint fallback (</strong><code>requestMicStream</code><strong>):</strong> Keep <code>NotAllowedError</code> and <code>NotFoundError</code> surfaced clearly with actionable troubleshooting text, while automatically retrying <code>{ audio: true }</code> on constraint/driver errors and flagging <code>"Standard Mic"</code> in the UI:</li>
</ol>
<pre><code class="language-js">function requestMicStream(devId) {
  var rawCfg = {
    echoCancellation: false,
    noiseSuppression: false,
    autoGainControl: false
  };
  if (devId) rawCfg.deviceId = { ideal: devId };
  return Promise.resolve().then(function () {
    return navigator.mediaDevices.getUserMedia({ audio: rawCfg });
  }).then(function (s) {
    return { stream: s, fallback: false };
  }).catch(function (err) {
    var name = err &amp;&amp; err.name ? err.name : '';
    if (name === 'NotAllowedError' || name === 'PermissionDeniedError' ||
        name === 'NotFoundError' || name === 'DevicesNotFoundError') {
      throw err;
    }
    return Promise.resolve().then(function () {
      return navigator.mediaDevices.getUserMedia({ audio: true });
    }).then(function (s) {
      return { stream: s, fallback: true };
    });
  });
}
</code></pre>
<ol start="2">
<li><strong>Keeping</strong> <code>AnalyserNode</code> <strong>alive with a silent sink +</strong> <code>runToken</code><strong>:</strong> On mobile WebKit, an <code>AnalyserNode</code> disconnected from <code>actx.destination</code> often returns flat zero buffers. Routing <code>sourceNode -&gt; analyser -&gt; zeroGain (gain = 0) -&gt; actx.destination</code> keeps the audio graph pulling frames with zero speaker feedback. Meanwhile, incrementing a <code>runToken</code> on every <code>startMeter()</code> and <code>stopMeter()</code> call prevents late-resolving <code>getUserMedia</code> promises from leaking an orphaned mic track if a user stops or switches microphones mid-permission prompt.</li>
</ol>
<hr />
<h2>3. IEC 61672 <code>dB(A)</code> / <code>dB(C)</code> Weighting &amp; Pink Noise in Vanilla JS</h2>
<p>Computing meaningful frequency-weighted decibel readings or band-filtered speaker noise requires zero external DSP dependencies:</p>
<ul>
<li><strong>Per-bin A/C weighting (</strong><code>buildWeights</code><strong>):</strong> Pre-compute squared IEC 61672 transfer magnitude curves (<code>weightA</code> and <code>weightC</code>) once per sample rate (<code>12194</code>, <code>20.6</code>, <code>107.7</code>, <code>737.9</code> Hz poles), integrate FFT bin power per animation frame, and smooth with exponential time constants (<code>125 ms</code> Fast / <code>1 s</code> Slow).</li>
<li><strong>Paul Kellet's 7-tap pink noise buffer (</strong><code>getPinkBuffer</code><strong>):</strong> Generate a 3-second seamless pink noise buffer at <code>actx.sampleRate</code> in ~15 lines of JavaScript, then feed it through high-pass/low-pass <code>BiquadFilterNode</code> pairs for woofer (<code>40–200 Hz</code>), midrange (<code>300 Hz–3 kHz</code>), and tweeter (<code>4–16 kHz</code>) bands.</li>
</ul>
<p>One honest engineering boundary worth keeping front and center: consumer smartphone and laptop microphones vary by roughly <code>±5–10 dB</code> across models and built-in hardware limiters. Giving users a local <code>±20 dB</code> calibration offset slider makes browser measurements practical for everyday troubleshooting while remaining transparent that web diagnostics complement—rather than replace—calibrated Class 1/2 SPL meters or acoustic measurement rigs.</p>
<p>If you're building with the Web Audio API or want to test your own setup directly in the browser (no sign-up, zero server uploads), you can run all 11 diagnostics on <a href="https://soundtesthq.com"><strong>SoundTestHQ</strong></a> or jump straight to the <a href="https://soundtesthq.com/speaker-test"><strong>online speaker test</strong></a> to try the L/R channel and phase checks yourself.</p>
]]></content:encoded></item><item><title><![CDATA[Slimming a 203 KB Daily Trivia Archive Down to 94 KB with Lazy Edge JSON Hydration]]></title><description><![CDATA[:webdev, performance, javascript, cloudflare-workers, seo]]></description><link>https://minigamedaily.hashnode.dev/slimming-a-203-kb-daily-trivia-archive-down-to-94-kb-with-lazy-edge-json-hydration</link><guid isPermaLink="true">https://minigamedaily.hashnode.dev/slimming-a-203-kb-daily-trivia-archive-down-to-94-kb-with-lazy-edge-json-hydration</guid><dc:creator><![CDATA[Jack Song]]></dc:creator><pubDate>Wed, 25 Nov 2026 12:22:18 GMT</pubDate><content:encoded><![CDATA[<p>Static daily puzzle sites look deceptively tiny on Day 1. You publish one daily board of seven prompts, add a few helpful hints, and the HTML document is a crisp 15 KB.</p>
<p>Two weeks later, things change. Add a searchable archive of daily boards, multi-tier answer explanations, and interactive filters—and suddenly a single archive page swells past <strong>12,000 words and 203 KB of raw HTML</strong> before Gzip. Worse, every time you append a new daily board, crawlers have to re-parse tens of thousands of historical DOM nodes just to index today's update.</p>
<p>That exact growth problem hit our Krillion Answers daily archive on <a href="https://minigamedaily.com/"><strong>MiniGameDaily</strong></a>—an independent hub for daily browser trivia, practice drills, and original zero-login puzzle games. By splitting initial <strong>server-side rendering (SSR)</strong> from <strong>lazy edge JSON hydration</strong>, we cut the archive's HTML payload from <strong>~203 KB (12,176 words) down to ~94 KB (5,389 words)</strong>—a <strong>54% reduction in SSR weight</strong>—without dropping search coverage, deep-link anchors, or automated daily expansion across our games.</p>
<p><em>(Disclosure: MiniGameDaily is an independent player hub and original browser-game studio; we are not affiliated with</em> <a href="http://krillion.io"><code>krillion.io</code></a> <em>or</em> <a href="http://farflung.game"><code>farflung.game</code></a><em>.)</em></p>
<hr />
<h2><strong>Why Daily Puzzle Archives Outgrow Pure SSR</strong></h2>
<p>Each archived daily dive on our site holds <code>7</code> prompts, <code>1</code> featured <code>100-point</code> rare pick, grouped tier lists (<em>Deep Cut</em>, <em>Rare</em>, <em>Schooler</em>, <em>Common / Plankton</em>), a spoiler-free hint, and strategy commentary. Across <code>12</code> archived dives (<code>#120–#131</code>), that comes out to <code>84</code> prompts and <strong>1,654 indexed answer rows</strong>.</p>
<p>Dumping every single day directly into static HTML created three headaches:</p>
<ol>
<li><strong>DOM weight &amp; mobile scroll bloat:</strong> Phones downloading <code>/krillion-answers</code> first had to parse hundreds of hidden <code>&lt;details&gt;</code> elements they might never open.</li>
<li><strong>Slow incremental deploys:</strong> Adding one new daily board meant shipping a huge page rewrite instead of a small daily JSON drop.</li>
<li><strong>All-or-nothing search tradeoffs:</strong> Naive pagination hides older answers from an on-page Answer Checker unless you either bloat the HTML <em>or</em> force users through extra full-page loads.</li>
</ol>
<p>Instead of spinning up a heavy SPA or migrating to a backend SQL database, we kept static HTML lean and shifted older boards into <strong>Cloudflare Worker edge static JSON endpoints</strong> under <code>/_d/</code>.</p>
<hr />
<h2><strong>Pattern 1: Keep Latest 5 Days in SSR HTML, Hydrate Older Days on Demand</strong></h2>
<p>The key decision was deciding <em>what Googlebot and human visitors actually need immediately at</em> <code>0 ms</code>:</p>
<ul>
<li><strong>First 5 dives (</strong><code>#131–#127</code><strong>) stay server-rendered in HTML:</strong> Readers landing from search for today's or this week's daily prompts get immediate zero-JS content, table rows, and contextual links right in the HTML response (~94 KB, 5,389 words).</li>
<li><strong>Earlier dives (</strong><code>#126–#120+</code><strong>) live as atomic edge JSON payloads:</strong> Each older board is stored separately at <code>/_d/krillion-answers-archive/dive-&lt;id&gt;</code> and exposed as compact chip buttons at the bottom of the archive.</li>
</ul>
<p>Under the hood, a tiny memoized promise cache ensures we never fetch the same historical day twice, whether triggered by a button click, search preloading, or a URL hash:</p>
<pre><code class="language-javascript">var loadedDiveData = {};

var diveFetchPromises = {};

function fetchDiveData(diveId) {

var id = String(diveId || "");

if (loadedDiveData[id]) return Promise.resolve(loadedDiveData[id]);

if (diveFetchPromises[id]) return diveFetchPromises[id];

  diveFetchPromises[id] = fetch(archiveBase + "/dive-" + encodeURIComponent(id))

.then(function (r) {

if (!r.ok) throw new Error("Failed to load Dive #" + id);

return r.json();

})

.then(function (raw) {

var d = Array.isArray(raw &amp;&amp; raw.prompts) ? raw : raw.value;

      loadedDiveData[id] = d;

indexDiveObject(d);

return d;

})

.catch(function (err) {

delete diveFetchPromises[id];

throw err;

});

return diveFetchPromises[id];

}
</code></pre>
<h3><strong>Preserving Deep Links (</strong><code>#dive123-q4</code><strong>) &amp; Full 1,654-Answer Search</strong></h3>
<p>Two UX details usually break when teams lazy-load older content: <strong>hash links</strong> and <strong>client search</strong>.</p>
<ol>
<li><strong>Hash-aware hydration (</strong><code>revealTargetFromHash</code><strong>):</strong> If a user shares a direct link like <code>/krillion-answers#dive123-q4</code>, a 15-line regex extracts <code>diveId = "123"</code>, calls <code>ensureDiveLoaded("123")</code> to fetch that single JSON file, builds the card DOM via <code>buildDiveCard()</code>, switches tabs, opens that prompt's <code>&lt;details&gt;</code> block, and smooth-scrolls straight into view.</li>
<li><strong>Idle background indexing (</strong><code>preloadOlderArchive</code><strong>):</strong> When someone focuses or submits the <strong>Answer Checker</strong> bar at the top of the page, <code>preloadOlderArchive()</code> fetches any remaining unindexed <code>/_d/...</code> chunks in parallel via <code>Promise.all</code>—keeping all <code>12</code> dives, <code>84</code> prompts, and <code>1,654</code> entries searchable instantly without penalizing initial page load.</li>
</ol>
<hr />
<h2><strong>Pattern 2: Powering Daily Auto-Updates Across Three Games From</strong> <code>/_d/</code></h2>
<p>Once <code>/_d/</code> static JSON hydration worked cleanly for the archive, using the exact same pattern across our playable browser games removed HTML deployments from our daily content pipeline altogether:</p>
<ul>
<li><strong>CrowdGuess</strong> <em>(Original free daily consensus game — 00:00 UTC reset)</em>: Fetches <code>/_d/crowdguess/prompts</code> at runtime so a daily cron job can append <code>+5</code> new prompts (<code>155+</code> total across Geography, Movies, Music, Sports, and Food) without touching page HTML or templates.</li>
<li><strong>Farflung Unlimited</strong> <em>(Original endless 197-country world-map game)</em>: Reads <code>/_d/farflung/countries</code> + <code>/_d/farflung/prompts</code> (<code>48+</code> curated prompts, updated daily) alongside cached TopoJSON (<code>world-atlas@2.0.2</code>), keeping the interactive SVG map and microstate pins independent from prompt updates.</li>
<li><a href="https://minigamedaily.com/krillion-unlimited"><strong>Krillion Unlimited practice mode</strong></a> <em>(Independent rarity drill)</em>: Hydrates <code>12</code> dives / <code>84+</code> open trivia prompts cleanly from <code>/_d/krillion-drill-v2/</code> so players can train 25-second rarity reflexes anytime with no daily cap.</li>
</ul>
<h3><strong>Automated Edge Rotation Without Client Layout Shift</strong></h3>
<p>We also applied a companion server-side pattern to our homepage's <code>Dive deeper</code> 3-card showcase: instead of rotating cards in JavaScript (which causes layout/link churn crawlers miss), a small daily script swaps an edge data config so server-rendered HTML deterministically rotates weekly across <code>9</code> inner guide and game pages with zero runtime flicker.</p>
<hr />
<h2><strong>Practical Takeaways for Static Edge-First Game Sites</strong></h2>
<ol>
<li><strong>Keep 3–5 days in SSR HTML, archive older boards to atomic</strong> <code>/_d/&lt;id&gt;</code> <strong>JSON files.</strong> You retain instant first paint and full crawlability for fresh content while capping HTML size as months go by.</li>
<li><strong>Use URL-hash interception (</strong><code>#dive123-q4</code><strong>) before rendering older fragments.</strong> Lazy chunks shouldn't break bookmarkable links or fragment scrolls.</li>
<li><strong>Separate game mechanics from daily prompt packs.</strong> Decoupling <code>prompts.json</code> from <code>tool.html</code> and <code>tool.js</code> lets automated daily updates ship small verified diffs without risking template regressions.</li>
</ol>
<p>If you're into lean edge architectures or daily browser puzzles, you can try the <a href="https://minigamedaily.com/krillion-unlimited"><strong>Krillion endless mode</strong></a> on <a href="https://minigamedaily.com/"><strong>MiniGameDaily</strong></a>—or test our lazy archive on Krillion Answers and play quick zero-login rounds of CrowdGuess or Farflung Unlimited.</p>
]]></content:encoded></item></channel></rss>