Dev.to WebDev 🛠 Dev 👁 0 📖 9 min read

Embeddable math games in 7 languages: seeded Dart dots, measured iframes and a one-character noindex bug

We build Dyscalculia.io, a site with a free number-sense screening test and a paid daily practice program. The screening test is made of five small games: count a flash of dots, pick the bigger number, pick the group wit

We build Dyscalculia.io, a site with a free number-sense screening test and a paid daily practice program. The screening test is made of five small games: count a flash of dots, pick the bigger number, pick the group with more dots, place a number on a 0–100 line, and repeat a sequence of digits.

We wanted teachers and parents to be able to put one of these games on their own blog or class page. That sounds like a ten-minute job: wrap the component in an iframe and you're done. It took longer, and most of the work turned out to be stuff nobody sees: making the same five games safe to show on someone else's page, in seven languages, with no score, no tracking and no scroll bars.

This post covers the parts I'd do again and the parts I got wrong.

The constraint that shaped everything: practice, not a test

The screening test produces a result. An embedded copy on a random blog must not, because a game on a third-party page with no context and no follow-up is the wrong place to tell anyone anything about their maths. So the rule was: same game screens, and the score is thrown away.

The game components already reported a score through onDone(score). The practice wrapper keeps that API untouched and just ignores the value:

// components/embed/PracticeGame.tsx (trimmed)
const GAMES = {
  dots: DotEnumeration,
  symbolic: SymbolicCompare,
  compare: NonSymbolicCompare,
  numberline: NumberLine,
  digitspan: DigitSpan,
} as const;

export function PracticeGame({ game, s, t, moreHref }: Props) {
  const [done, setDone] = useState(false);
  const [round, setRound] = useState(0);
  const Game = GAMES[game];
  if (done) {
    return (
      <div aria-live="polite">
        <h2>{t.well}</h2>
        <p>{t.done}</p>
        <button onClick={() => { setRound(round + 1); setDone(false); }}>{t.again}</button>
        <a href={moreHref} target="_blank">{t.more}</a>
      </div>
    );
  }
  // The score is computed by the game and deliberately dropped here.
  return <Game key={round} s={s} onDone={() => setDone(true)} />;
}

key={round} is the whole "play again" feature: a new key remounts the game with fresh state.

The second guard is in the types. The test's string bundle includes result copy (strengths, focus areas). The games only read prompts, so I narrowed their prop type:

// components/test/games.tsx
export type GameStrings = Pick<TestStrings, "prompts">;

The frame page now passes { prompts: ui.prompts } and nothing else. Result text can't reach the iframe by accident because the compiler won't let you pass it.

Five games, one list

Every place that knows about embeds reads the same array: the builder page, the frame route, the sitemap code, the loader script's checks and the Playwright measurer.

// lib/embedGames.ts (trimmed)
export type EmbedGameId = "dots" | "symbolic" | "compare" | "numberline" | "digitspan";

export const EMBED_GAMES: readonly EmbedGame[] = [
  { id: "dots", key: "dotEnumeration", what: "Dot patterns flash on the screen..." },
  // ...
];

export const EMBED_SIZES = [
  { id: "compact", label: "Compact", w: 360 },
  { id: "standard", label: "Standard", w: 480 },
  { id: "wide", label: "Wide", w: 720 },
] as const;

The id is a URL segment, /embed/<lang>/<id>, and it is permanent. If I rename it, every embedded copy on someone else's site breaks, so the verifier fails the build if the list isn't exactly dots,symbolic,compare,numberline,digitspan.

The route is statically generated for every real (language, game) pair, and dynamicParams = false turns everything else into a 404:

// app/(embed)/embed/[locale]/[game]/page.tsx
export const dynamicParams = false;
export function generateStaticParams() {
  return embedTargets().map((t) => ({ locale: t.locale, game: t.game }));
}

The frames live under their own root layout, so analytics, the cookie banner, the attribution tracker and the theme script are simply not rendered there. The embed page sets no cookies and loads no analytics, and a build step greps the compiled HTML of every frame for googletagmanager, gtag( and google-analytics to keep it that way.

Game (id) What the player does Rounds Plain-iframe height (compact / standard / wide)
dots Taps how many dots flashed (1–9) 5 605 / 578 / 514 px
symbolic Taps the bigger of two numbers 5 471 / 445 / 389 px
compare Taps the group with more dots 5 471 / 445 / 414 px
numberline Slides a marker to a number on 0–100 3 543 / 488 / 488 px
digitspan Types back digits shown one at a time 3 565 / 565 / 538 px

Those heights were measured, not guessed. More on that below.

The dots have to be the same dots

The games started in our Flutter app, and the web version has to match it item for item: same counts, same order, same scoring, same feedback timing. The dot positions come from a seeded Random in Dart that places dots and rejects any that land too close to an existing one.

You can't just port that loop to JavaScript. Dart's seeded Random doesn't produce the same sequence as anything in JS, so a faithful re-implementation of the placement loop still gives you different dots. So I didn't port the RNG. I ran the Dart code once and committed what it printed:

// scripts/port-dot-layouts.dart (trimmed)
List<List<double>> layout(int count, int seed, double size, double dotSize,
    double margin, double gap, int maxAttempts) {
  final rng = Random(seed);
  final pos = <List<double>>[];
  var attempts = 0;
  while (pos.length < count && attempts < maxAttempts) {
    final x = rng.nextDouble() * (size - 2 * margin) + margin;
    final y = rng.nextDouble() * (size - 2 * margin) + margin;
    final close = pos.any((p) => sqrt(pow(p[0]-x,2)+pow(p[1]-y,2)) < dotSize + gap);
    if (!close) pos.add([double.parse(x.toStringAsFixed(2)), double.parse(y.toStringAsFixed(2))]);
    attempts++;
  }
  return pos;
}
// enumeration trials: counts [3, 6, 2, 8, 4], seed = i * 100 + count, 220 px box

The output is content/test/dotLayouts.json, which the React games import directly. If someone changes a seed or a box size in the app, they rerun the script. It's boring, it's deterministic, and the web and app versions are now guaranteed to draw the same pattern for trial three.

The other games keep their items in lib/testItems.ts (number-line targets [25, 67, 41] starting at 50, digits shown for 1400 ms each). The public methodology page that explains how the screening test is scored reads those same constants, so the documentation can't drift from the code.

The loader: one div, one script tag

What a teacher pastes:

<div data-dysc-game="dots" data-lang="de"></div>
<script async src="https://dyscalculia.io/embed.js"></script>

public/embed.js is about 90 lines of deliberately old-fashioned ES5 (catch (e) {} rather than catch {}), because it runs on whatever CMS and browser the host has. It finds every [data-dysc-game], builds an iframe and writes a visible credit line into the host page, under the frame:

// public/embed.js (trimmed)
frame.src = origin + "/embed/" + lang + "/" + game;
frame.title = TITLE[lang];
frame.loading = "lazy";
el.appendChild(frame);
var a = document.createElement("a");
a.href = origin + (lang === "en" ? "/" : "/" + lang);
a.target = "_blank";
a.textContent = "Dyscalculia.io";
p.appendChild(document.createTextNode(CREDIT[lang] + " "));
p.appendChild(a);
el.appendChild(p);

The credit goes outside the iframe on purpose: a link inside the frame belongs to our document, not to the host page.

Resizing is a tiny postMessage protocol. Inside the frame, a ResizeObserver sends the content height whenever a round changes the layout:

// components/embed/EmbedFrame.tsx (trimmed)
const send = () => {
  window.scrollTo(0, 0);
  window.parent.postMessage(
    { source: "dysc-embed", type: "resize", height: Math.ceil(el.getBoundingClientRect().height) },
    "*",
  );
};
const ro = new ResizeObserver(send);
ro.observe(el);

targetOrigin is "*" because the message only carries a number. The receiving side is where the checks matter:

window.addEventListener("message", function (e) {
  if (e.origin !== origin || !e.data || e.data.source !== "dysc-embed" || e.data.type !== "resize") return;
  var h = Number(e.data.height);
  if (!isFinite(h) || h < 120 || h > 2000) return;
  for (var i = 0; i < frames.length; i++) {
    if (frames[i].contentWindow === e.source) frames[i].style.height = Math.ceil(h) + "px";
  }
});

It checks the origin, the message shape, a sane height range, and matches e.source to the right iframe, so two games on one page don't resize each other. The frame also sets overflow: hidden on its own <html> and scrolls to the top on every resize, so a growing round never leaves the top cut off.

Measuring iframe heights instead of guessing

Some hosts strip scripts, so the builder also offers a plain <iframe> with a fixed height. A fixed height has to fit the tallest state of the game: the longest language, the round with the most wrapping, and the finish screen.

So scripts/measure-embed.mjs plays every game in real Chrome via Playwright. It starts a host page on a different origin (port 3152) that iframes the production build (port 3151) and records every dysc-embed message. For each game × language × size it plays every round, reaches the finish screen, presses "play again", and records the maximum height. It also loads each frame on its own at 360 and 390 px to check for horizontal overflow. With 5 games, 7 languages, 3 sizes and 2 viewport checks that's 175 jobs, run in a pool of 8.

Along the way it asserts what the frame must not show:

// scripts/measure-embed.mjs (trimmed, messages translated)
const afterHeading = endText.slice(endText.indexOf(t.well));
if (/\d/.test(afterHeading)) note(`${tag}: digit on finish screen (score?): ${afterHeading}`);

Any digit after "Well done" counts as a leaked score and fails the run. With --write, the script rewrites both lib/embedHeights.ts and the HEIGHTS table in embed.js (max + 4 px), and scripts/verify-embed.mjs fails make check if those two ever disagree.

When we added Turkish frames later, I reran the measurement for all seven languages. Nothing changed, because Turkish was never the tallest. I only know that because I measured.

What I got wrong

A wildcard that noindexed the wrong page. The frames should send X-Robots-Tag: noindex and frame-ancestors *. The /embed page that explains them should be indexable. On an earlier project I'd written the header rule as /embed/:path*, and * matches zero segments, so the info page got noindex too. This time it's :path+, and the verifier doesn't just regex the config. It loads the compiled routes-manifest.json and tests the rule's regex against /embed (must not match) and every /embed/<lang>/<game> (must match). Live, /embed/en/dots returns both headers and /embed returns neither.

Telling users to do something the code already did. The first builder label for the plain iframe said "you add the credit link yourself". But the generated snippet already had the credit <p> on its second line. Read literally, that label gets you two credit lines, or someone pastes only the first line and drops the credit. The fix was one sentence: "the credit line is part of the code: paste both lines and keep it."

Hardcoded "six languages". We launched with six frame languages and wrote "six" into the developer copy and the FAQ. When Turkish arrived, the code was the easy part and the prose was wrong. The verifier now builds the expected language list from the site's locale registry and fails if any site language ships without a frame. Still, no check catches a number written out as a word in a paragraph. I fixed those by grepping.

Assuming the RNG was portable. I covered this above. The fix I'd recommend to anyone sharing seeded content between Dart and JS: don't share the generator, share its output.

What I'd keep

  • One list (EMBED_GAMES) that everything reads, with permanent ids.
  • Narrow prop types (Pick<..., "prompts">) as a privacy boundary, not just tidiness.
  • Build-time assertions on the compiled output: HTML, headers manifest, sitemap. Config can look right and still compile to something else.
  • Measured numbers with the script that produced them sitting next to them.

If you want to poke at it, the embeddable number games builder generates both snippets with a live preview. If the dots game is the one you like, the site also has a standalone dot-flash subitizing trainer, and the full five-game free dyscalculia screening test runs without an account. It's a screening, not a diagnosis, and only a qualified professional can diagnose dyscalculia.

I drafted this post with help from an AI assistant. The code, numbers and mistakes are from our repository and were checked against it.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.