1. GLOBAL CONFIGURATION
-----------------------
- CARDS_PER_ROUND: 9
- BASE_LANGUAGE: English
- TARGET_LANGUAGE: Ukrainian
- GAME: Custom
- LANGUAGE_CODE: Two letter standard code for TARGET_LANGUAGE (All Caps).
Dataset Fields: id | text (English) | translation (TARGET_LANGUAGE Translation) | audio (set
explicitly to null)
Elminate any duplicates in the dataset.
Act as an expert Frontend Engineer.
Build a single, standalone HTML file (index.html) for a language learning game.
IMPORTANT: Do not add any notes at the top or bottom of the HTML file.
2. TECHNICAL STACK & SETUP
--------------------------
- React, ReactDOM, Babel, TailwindCSS (via CDN).
- Embed all CSS/JS within the single file.
- You MUST include <meta charset="UTF-8"> at the very top of the <head>.
- In the <head>, load exactly these four dependencies, in this order, each as a plain
<script src="...">, using these exact URLs:
React: https://unpkg.com/react@18.3.1/umd/react.production.min.js (with the crossorigin attribute)
ReactDOM: https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js (with the crossorigin
attribute)
Babel: https://unpkg.com/@babel/standalone@7.23.0/babel.min.js
Tailwind: https://cdn.tailwindcss.com/3.4.17
- Analytics: Include the standard Google Analytics 4 (gtag.js) script in the <head>. Initialize
`window.dataLayer` and config using the `GA_MEASUREMENT_ID`.
3. ARCHITECTURE & STATE MANAGEMENT (CRITICAL)
---------------------------------------------
- Storage Key: Use const
`STORAGE_KEY = 'openlang_' + CONFIG.TARGET_LANGUAGE + '_' + CONFIG.GAME + '_progress'`.
- SAFE STORAGE (CRITICAL): Browsers can block site data (blocked cookies, privacy extensions, in-app
browsers/WebViews). Then merely reading `window.localStorage` throws a SecurityError (or it is
null), which crashes the game. The game MUST stay fully playable when storage is unavailable;
progress is simply not persisted.
- In the <head>, in a small plain <script> placed IMMEDIATELY BEFORE the first other <script> tag,
define a global object `window.safeStorage` with four methods: getItem(key), setItem(key,
value), removeItem(key), and keys(). It behaves like localStorage, with these guarantees:
* Every touch of `window.localStorage` (including merely reading the property) is wrapped in
try/catch. If storage is missing or throws, the method quietly carries on.
* It also keeps an in-memory copy of everything written. setItem always updates the copy, then
tries localStorage. getItem tries localStorage first and falls back to the copy (null if
neither has the key). removeItem deletes from both.
* keys() returns the keys in localStorage, or the in-memory copy's keys when storage is
unavailable.
* Keys and values are always converted to strings.
* It never throws, so the game plays normally (without saving progress) when storage is
blocked.
- You MUST NOT reference `localStorage` or `window.localStorage` anywhere else in the file. Every
read, write, and removal of saved data (progress, totals, mute state) MUST use
`safeStorage.getItem`, `safeStorage.setItem`, or `safeStorage.removeItem`. To list saved keys,
use `safeStorage.keys()`.
- Wrap `JSON.parse` of saved progress in try/catch; on failure, treat it as no saved data.
- The "Mirror Ref" Pattern for Stale Closures: Because global touch listeners trap state, you MUST
use `useRef` hooks (`scoreRef`, `streakRef`, `learnedIdsRef`, `deckRef`, `selectedRef`,
`roundDataRef`) as the absolute source of truth for math and logic. You MUST also maintain
separate `useState` hooks (`score`, `streak`, `learnedIds`, `selectedCard`, `roundData`) purely
for rendering the UI.
- ROUND DATA (CRITICAL, phones break without it): every time `roundData` is set, also set
`roundDataRef.current` to the same value (inside a `setRoundData(prev => ...)` updater too). The
match handler, `handleCardTap` and every other handler MUST look cards up in
`roundDataRef.current`, NEVER in the `roundData` state. The touch listeners are attached once on
mount, so the `roundData` they would see is the empty first render, and every phone tap and drop
would silently do nothing.
- The Golden Rule: Inside your event handlers, ALWAYS read from the Ref, do the math, update the
Ref, and then pass that new Ref value into the state setter (e.g.,
`scoreRef.current += 10; setScore(scoreRef.current);`). NEVER read the current value from the
`useState` variable inside a handler.
- Initialization: On mount, read saved progress with `safeStorage.getItem(STORAGE_KEY)`. If data
exists, hydrate BOTH the Refs and the State variables. Write total words to storage:
`safeStorage.setItem('openlang_' + CONFIG.TARGET_LANGUAGE + '_' + CONFIG.GAME + '_total', RAW_DATA.length);`
- Deck Logic: Initialize `deckRef` using a Fisher-Yates shuffle of RAW_DATA items that are NOT in
`learnedIdsRef.current`.
- Round Transition: Watch `[roundData.left.length, isWon]`. If `roundData.left.length === 0` and
`deckRef.current.length > 0`, call `startRound()`.
4. LAYOUT & VISUALS
-------------------
- Master Container: Wrap the entire application in a single div.
- Desktop: width: 400px; margin: 0 auto; position: relative;
- Mobile: width: 100%; height: 100dvh;
- Behavior: All children (Header, Game Area, Footer) must inherit this exact width.
- Structure: A flex-column container (h-100dvh) within the master boundary.
Header: Fixed height, flex-shrink: 0.
Game Area: Flex-1, overflow: hidden, overscroll-behavior: none. (CRITICAL: Do NOT use
overflow-y: auto. You MUST enforce the touch-none Tailwind class directly on the JSX elements
to prevent entire columns from native dragging/scrolling). This container MUST have the class
flex so its children (the two columns) automatically stretch to fill the full available height.
Columns: Two columns (50% width).
- CSS Logic: Apply flex flex-col justify-start to each column. Calculate a fixed card height using
calc((100dvh - 6.9rem) / (CARDS_PER_ROUND + 1)), defined once as the constant `CARD_MAX_HEIGHT`
(see FIT TEXT TO CARD) and passed as every card's inline `height`. This ensures cards never change
size or move positions when others are removed.
- COMPACT CARDS (optional config): CONFIG may contain `COMPACT_CARDS: true` (a boolean; treat a
missing field as false). When true, `fitAllCards` gives all cards of a round ONE shared height:
just tall enough for the round's longest text (no empty space above and below the text beyond
the p-2 padding), at least 44px and never more than CARD_MAX_HEIGHT. That height is set when the
round starts and does not shrink while cards are removed, so cards still never change size when
others are removed. When false, every card keeps the full CARD_MAX_HEIGHT.
Card Content (Strict):
Each card must be a single <div> element with key, data-id, data-side, className, style,
draggable, and onClick all on the same element. Do not wrap cards in an outer container div.
Left (English) Card: Display the English text using the calculated fixed height .95rem.
Right (TARGET_LANGUAGE) Card: Display the translation. CRITICAL SIZING & LOCALIZATION: Use the
exact same font size (1rem) by default.
CRITICAL FONT SIZING FIX: You MUST use a dynamic inline style for the TARGET_LANGUAGE card's font
size. Use exactly this logic: fontSize: ['Arabic', 'Hebrew', 'Farsi', 'Urdu', 'Hindi', 'Thai',
'Chinese', 'Japanese', 'Sindhi'].includes(CONFIG.TARGET_LANGUAGE) ? '1.25rem' : '.95rem'. (Do not
use Tailwind text classes for the right card's size). You MUST also include dir={['Arabic',
'Hebrew', 'Farsi', 'Urdu'].includes(CONFIG.TARGET_LANGUAGE) ? 'rtl' : 'ltr'} on the target card
element.
Card Styling: Use p-2 (0.5rem) padding and leading-tight. Centrally align text vertically and
horizontally. The white background must tightly 'hug' the text within the calculated height. MUST
INCLUDE CSS: user-select: none; -webkit-user-select: none; to prevent native text-drag interference.
FONT SUPPORT: Apply a robust modern system font fallback stack tailored to the TARGET_LANGUAGE to
ensure non-Latin scripts render beautifully and readably without external font files.
FIT TEXT TO CARD (CRITICAL): Some datasets have long cards (quotes, slogans, explanations of 150-250
characters). Text MUST NEVER spill outside its card: spilled text covers neighbouring cards and the
header, steals taps, and is unreadable. Cards keep their fixed height (or, with
CONFIG.COMPACT_CARDS, the round's shared compact height); text that still does not fit is made
smaller instead.
- Every card's inline style MUST include `overflow: 'hidden'` and `overflowWrap: 'anywhere'`, and
every card element MUST carry the attribute `data-base-font` set to its starting font size (the
left card's '.95rem', the right card's dynamic TARGET_LANGUAGE size).
- Define, with the global constants, `CARD_MAX_HEIGHT` as the CSS string calc((100dvh - 6.9rem) /
(CARDS_PER_ROUND + 1)), with CONFIG.CARDS_PER_ROUND + 1 filled in as a number.
- Define these pure helpers OUTSIDE the component:
* `fitCardText(card)` shrinks one card's text until it fits. First reset the card's font size
to its `data-base-font` value (so text grows back when a card shows a shorter phrase). Then
read the card's actual font size in pixels from its computed style (`data-base-font` is in
rem, so do not parse it as a pixel value). Then, while the content is taller OR wider than
the card (allow 1px of slack for sub-pixel rounding), reduce the font size by 0.5px. The
font must never be smaller than 9px: if the next step would go below 9px, use exactly 9px
and stop there, even if the text still overflows.
* `capFontSpread(cards, keepCaps)` evens out font sizes (see EVEN FONT SIZES). For each side
separately, the cap is the smallest fitted font size (in px) among that side's cards. If
keepCaps is true and caps were saved earlier, each side's cap is the SMALLER of the saved
cap and the new one, so caps never grow. Save the caps in a module-level variable, then set
every card on that side to its side's cap.
* `fitAllCards(restyled)` fits every card on screen (elements with `data-side`); it does
nothing when there are none. It remembers, in module-level variables, which cards (side +
id) it fitted last time: a new round starts only when at least one card on screen was not on
screen at the last fit (cards disappearing after a match does NOT start a new round, and
neither does a restyle). It also remembers how many cards the round started with. Call
capFontSpread with keepCaps = true unless this is a new round, or this is a restyle/resize
while all of the round's cards are still on screen. If COMPACT_CARDS is off, run fitCardText
on each card. If COMPACT_CARDS is on, choose ONE shared height for the round: measure
CARD_MAX_HEIGHT in pixels (apply it to a card and read its height), measure each card at its
base font with height:auto, take the tallest, keep it between 44px and CARD_MAX_HEIGHT, and
when refitting the same round never let it drop below the height chosen last time. Round up
to whole pixels, apply that height to every card, then run fitCardText on each. In both
modes finish with capFontSpread.
- Call `fitAllCards()` in a `useLayoutEffect` that runs whenever `roundData` changes (so new cards
are fitted before they are painted).
- EVEN FONT SIZES: `capFontSpread` keeps the text size even within a round. After fitting, every
card on a side gets the same font size: the smallest fitted font on that side (left and right
are capped separately), so one short text does not stand out in large type next to long texts
that had to shrink. The caps are kept while matched cards are removed (so the remaining cards do
not grow), and are recomputed for a new round, or when the page is restyled or resized
(`fitAllCards(true)`) while the whole round is still on screen. Once a card has been matched, a
restyle or resize keeps the caps (they can only get smaller), because the Tailwind CDN rewrites
its <style> on every match and caps measured without the matched cards would let the remaining
cards grow.
- Refit whenever the page's styling or size changes after that, because the Tailwind CDN script
and web fonts restyle the page AFTER React's first render (a fit done before that leaves cards
overflowing). In a mount-only `useEffect`, schedule `fitAllCards(true)` for the next animation
frame (cancelling any refit already scheduled, so it runs at most once per frame) whenever:
anything in <head> changes (watch it with a MutationObserver, including child elements and
text), the window resizes, the device rotates, the page finishes loading, or web fonts finish
loading. On unmount, disconnect the observer, cancel the pending frame, and remove the
listeners.
- Every card's inline style passes `height: CARD_MAX_HEIGHT` (the same constant on every render).
Do NOT compute card heights or fitted sizes in React state or in JSX: `fitAllCards` writes
`el.style.height` and `el.style.fontSize` directly, and the JSX keeps passing the same starting
values, so React never overwrites the fitted values (the props do not change between renders).
Visual Hover State (PRO):
Define a CSS class .target-hover.
Style: border: 2px solid #3b82f6 !important; background-color: #eff6ff !important; transform:
scale(1.05); transition: transform 0.1s ease;.
This class will be applied to a TARGET_LANGUAGE card when an BASE_LANGUAGE card is "pointing" at
it.
Visual Selected State (Tap-to-Match):
Define a CSS class .card-selected.
Style: border: 3px solid #1d4ed8 !important; background-color: #dbeafe !important; box-shadow: 0
0 0 2px #93c5fd; transform: scale(1.03); transition: transform 0.1s ease;.
This class is applied (via React className, driven by `selectedCard` state) to the ONE card the
user has tapped/clicked and is waiting to match. It MUST look clearly different from
.target-hover so the user immediately sees their tap registered.
Right (TARGET_LANGUAGE) cards MUST use `cursor-pointer`. Left cards keep their existing grab
cursor.
Mobile View: UI must fit on a single screen without horizontal scrolling.
Desktop: Set CSS width to 400px (including header and footer).
Footer: Fixed height. Contains Copyright (defined below).
5. INTERACTION & EVENTS (STRICT CONSTRAINTS)
--------------------------------------------
- TYPE CASTING (CRITICAL): IDs pulled from the DOM (`data-id`) or drag events are ALWAYS Strings.
Because the IDs in `RAW_DATA` are Integers, you MUST wrap extracted IDs in `parseInt(id)` before
doing ANY game logic, strict equality (`===`) checks, or array filtering.
- The game supports TWO ways to match, and both MUST work on every device: drag-and-drop (Systems A
and B) and tap-to-match (System C). A first-time player must succeed with whichever one they try,
with no instructions.
- System A (Desktop): Use standard React `onDragStart`, `onDrop`, `onDragOver`, `onDragLeave`.
Conditionally set `draggable={!isTouchDevice}`. `onDragStart` MUST clear any tap selection
(`clearSelection()`).
- System B (Mobile): Use global `touchstart`, `touchmove`, `touchend` window listeners attached
exactly ONCE in a `useEffect`. Because they are attached once, they MUST NOT call `handleCardTap`
or the match handler directly, since those would be the copies from the first render. Keep a ref
named `handlersRef`, assign it an object holding the current `handleCardTap` and match handler in
the component body on EVERY render, and inside the listeners call the functions through
`handlersRef.current`. Use a visual absolute clone for dragging. Identify the drop target using
`document.elementFromPoint()` at the Clone's center coordinates. Apply `.target-hover` directly
via DOM classList manipulation.
- TAP vs DRAG (CRITICAL): On `touchstart` over ANY card, LEFT OR RIGHT (find it with
`e.target.closest('[data-side]')`, NOT only `[data-side="left"]`), record the start coordinates
and the card's id/side in a ref, but DO NOT create the clone yet. In `touchmove`, create the
clone ONLY once the finger has moved 10px or more (Euclidean distance) from the start point AND
the touched card is a LEFT card; from then on it is a drag (call `clearSelection()` at that
moment) and behaves exactly as before. Only LEFT cards can be dragged.
- In `touchend` (attached with `{ passive: false }`): if no clone was ever created (movement
stayed under 10px), it is a TAP: call `e.preventDefault()` (this cancels the browser's synthetic
click for this tap), set `window._lastTouchTap = { id: parseInt(id), side, time: Date.now() }`,
and call `handleCardTap(id, side)` for the touched card (left OR right). Otherwise it is a drop:
run the existing drop logic, then remove the clone and any `.target-hover`.
- FAST TAPS (CRITICAL, Android): a player often taps a left card and then its partner within a
fraction of a second. Every tap on a card, left or right, MUST be handled by `touchend` itself;
never rely on the synthetic click for touch taps, and never ignore clicks on OTHER cards after a
touch tap (that silently drops the second tap of a fast match).
- Always reset the touch-tracking ref and remove the clone on `touchend` and `touchcancel`.
- System C (Tap-to-Match, all devices): A single function `handleCardTap(id, side)` handles every
tap/click on a card.
- Selection state (Mirror Ref pattern): keep `selectedRef` (source of truth, `{ id, side }` or
null) and `selectedCard` state (for rendering .card-selected). Update both together via
`selectCard(id, side)` and `clearSelection()`. Inside handlers ALWAYS read
`selectedRef.current`, never the state.
- ID TYPES (CRITICAL): `handleCardTap` MUST begin with `id = parseInt(id);`, and `selectCard` MUST
store `parseInt(id)`. When rendering, compute `isSelected` as
`selectedCard && selectedCard.id === parseInt(item.id) && selectedCard.side === '<column side>'`.
Never compare against `String(...)`: clicks pass numeric ids while touch handlers read string
`data-id` values, and a type mismatch silently hides the highlight.
- NO REACT STATE INSIDE `handleCardTap` (CRITICAL): it is called from the global touch listeners
attached once on mount, so any `useState` value it reads is frozen at its initial value. Keep
`successIdsRef` and `showInfoRef` mirrored from `successIds` and `showInfo` (update each ref in
a `useEffect` on that state), and read only those refs in the step-1 guard below.
- Rules, in order:
1. Ignore the tap if the Info modal is open (`showInfoRef.current`), or if the tapped card (its
side + id) is in `successIdsRef.current` (it is already matched and about to be removed;
without this a player could re-match the green cards and score twice).
2. Nothing selected -> select the tapped card (left OR right; either column may be tapped
first).
3. Tapped the currently selected card again -> deselect it (`clearSelection()`).
4. Tapped a different card in the SAME column -> move the selection to the tapped card.
5. Tapped a card in the OTHER column -> attempt a match: baseId = the LEFT card's id, targetId =
the RIGHT card's id (regardless of which was tapped first). Call `clearSelection()`, then run
exactly the same MATCH VALIDATION / SUCCESS / FAIL logic used by drag-and-drop (Section 6).
Do NOT duplicate the scoring logic; both systems call the same match function.
- Wiring: every card has `onClick={() => onCardClick(item.id, 'left'|'right')}`. As a backup for
browsers that still fire a synthetic click after a touch tap, `onCardClick` MUST first check
`const t = window._lastTouchTap; if (t && t.id === parseInt(id) && t.side === side && Date.now() - t.time < 700) return;`
(ignore ONLY a click on the SAME card that was just tapped; handling both would select and
immediately deselect it). Otherwise it calls `handleCardTap`.
- Clear the selection whenever a new round starts (`startRound`) and after every match attempt
(success or fail).
6. GAME LOGIC
-------------
- MATCH VALIDATION: A match is correct if `parseInt(baseId) === parseInt(targetId)`, OR if the RIGHT
card's translation text is exactly the same as the translation of the LEFT card's item (two items
can share an answer, e.g. 3 x 8 and 4 x 6 both show "24"; either "24" card is correct). Because
the two cards can then have different ids, everything below that touches a card names it by side:
the LEFT card is baseId, the RIGHT card is targetId.
- SUCCESS (match is correct):
1. Call `speakCard()`.
2. Increment `scoreRef.current` by (10 + `streakRef.current`).
3. Increment `streakRef.current` by 1.
4. Push the parsed ID to `learnedIdsRef.current` (if not already there).
5. Filter the ID out of `deckRef.current`.
6. Sync UI & Storage: Call `setScore`, `setStreak`, and `setLearnedIds` using the newly updated
Ref values. Save the Refs with `safeStorage.setItem(STORAGE_KEY, ...)`.
7. Trigger the Green Flash on the LEFT card with baseId and the RIGHT card with targetId (track
flashing cards per side in `successIds`, e.g. as 'left' + id and 'right' + id). The green flash
lasts 0.2 seconds: a green background/border applied at once (no fade-in or fade-out), shown
for the 200ms until the cards are removed (step 8).
8. Inside a 200ms `setTimeout` (NOT longer: fast players move on immediately, and cards lingering
on screen scramble their next move), remove the LEFT card with baseId and the RIGHT card with
targetId from `roundData`.
- FAIL (match is not correct):
1. Add parsed targetId to `failIds` state for Red Flash.
2. Reset `streakRef.current` to 0. Decrease `scoreRef.current` by 5 (minimum 0).
3. Sync UI & Storage: Call `setScore` and `setStreak` with the updated Refs. Save with
`safeStorage.setItem(STORAGE_KEY, ...)`.
4. Remove from `failIds` after 2000ms.
7. AUDIO SYSTEM (MOBILE ROBUSTNESS - iOS FIXES)
-----------------------------------------------
CRITICAL: iOS Safari TTS is highly unstable. You MUST implement the audio system exactly as
described below.
Initialization & Unlock (The Native Pattern):
- You MUST use a `useEffect` on component mount to attach native listeners:
`window.addEventListener('touchstart', unlockAudio, { once: true });` and `mousedown`.
- Inside `unlockAudio`: Call `window.speechSynthesis.resume()`. Create
`const unlockUtterance = new SpeechSynthesisUtterance(' ');`. Set volume to 1. Call
`window.speechSynthesis.speak(unlockUtterance);`. DO NOT place this unlock logic inside the game's
drag-and-drop touch events.
Implementation inside `speakCard(item)`:
- STALE CLOSURE FIX: At the very top, add: `if (isMutedNow()) return;` (see MUTE in the HEADER
section; it reads the saved mute state from storage).
- Target Locale: If `navigator.language.toLowerCase().includes('en')`, use
`CONFIG.LANGUAGE_CODE.toLowerCase()`. Otherwise, use 'en'.
- Text Source: If English browser, use TARGET_LANGUAGE. Otherwise, use English.
Execution Constraints:
- Priority 1: If `item.audio` exists, `new Audio(item.audio).play(); return;`
- Priority 2 (Synthesis Fallback):
1. CRITICAL iOS QUEUE FIX: `window.speechSynthesis.cancel();`
2. `window.speechSynthesis.resume();`
3. Create: `const utterance = new SpeechSynthesisUtterance(TextSource);`
4. CRITICAL iOS GARBAGE COLLECTION FIX: `window._activeUtterance = utterance;`
5. `utterance.lang = TargetLocale;`
6. `const voices = window.speechSynthesis.getVoices();`
7. `const voiceMatch = voices.find(v => v.lang.toLowerCase().startsWith(TargetLocale));`
8. CRITICAL iOS LANG FIX: If `voiceMatch` exists, set `utterance.voice = voiceMatch;` AND
`utterance.lang = voiceMatch.lang;` (This safely adopts the exact device tag, preventing silent
drops).
9. Call `window.speechSynthesis.speak(utterance);` SYNCHRONOUSLY.
8. HEADER
---------
- Header Elements
LOGO: An <a href="/"> anchor tag wrapping the Chinese character U+6587, written as the HTML entity
文. Style: font-size 1.9em, color deep red, no text-decoration. The entire element must be a
clickable link to "/".
TARGET_LANGUAGE (.8rem, blue, underlined, linked to "/Ukrainian", preserve upper/lower case)
GAME: Advanced-1 (.8rem, dark grey)
MUTE: Mute Button: The exact text "MUTE" (1rem). Toggles isMuted state, mutes all sound, text
toggles to "UNMUTE".
- MUTED BY DEFAULT (optional config): CONFIG may contain `MUTED: true` (a boolean; treat a
missing field as false). Define, with the global constants:
`const MUTE_KEY = CONFIG.MUTED ? 'openlang_' + CONFIG.TARGET_LANGUAGE + '_' + CONFIG.GAME + '_mute_state' : 'openlang_global_mute_state';`
and
`function isMutedNow() { const saved = safeStorage.getItem(MUTE_KEY); return saved === null ? !!CONFIG.MUTED : saved === 'true'; }`.
- A game with MUTED: true starts muted (the button shows "UNMUTE") and keeps its own mute
setting under its own key, so it never changes the mute state of other games. All other games
share the exact key 'openlang_global_mute_state' so the setting persists universally across
them.
- CRITICAL: initialize isMuted on mount with `setIsMuted(isMutedNow())`; every time the button
is toggled save the boolean to MUTE_KEY (via `safeStorage.setItem`); and the mute check at the
top of speakCard MUST be `if (isMutedNow()) return;` (read storage, not React state, to avoid
stale closures).
INFO: Info icon: question mark ("?" 1.8rem): Opens Info modal.
- Info Modal:
- Explain rules in detail (how to match: drag a card onto its partner, OR tap a card and then
tap its partner in the other column; point scoring for correct and penalty for wrong answer,
streak bonus = length of the streak, MUTE button to kill sound, game is won when all cards are
guessed).
- Closing: Add a global `window.addEventListener('keydown')` to close modal when "Escape" is
pressed or on any tap or mouse click.
SCORE: "Score X" (.8rem)
LEARNED: Learned Y% (.8rem)
- Implementation: Use 'display: grid; grid-template-columns: 6% 24% 20% 50%; width: 100%;
box-sizing: border-box; height: 2.5rem;', tight veritcal spacing.
- Column 1:
- LOGO
- Column 2:
- First Row: LANGUAGE
- Second Row: GAME
- Column 3:
- First Row: SCORE
- Second Row: LEARNED
- Column 4:
- Layout: This grid cell MUST be a flex container: 'display: flex; width: 100%; height: 100%;
align-items: stretch; justify-content: flex-end; gap: 2px;'.
- Button/Link Constraints: MUTE, INFO:
- Every element in this column MUST have 'flex: 1 1 0%;' (force equal growth/shrink) and
'display: flex;'.
- Use 'align-items: center; justify-content: center;' on the buttons so text remains
centered as they grow.
- Set 'width: 100%' and 'height: 100%' for each button/link to fill the header's vertical
and horizontal space.
- Appearance: Add a border (e.g., 'border: 1px solid #e5e7eb') and background to make them
look like large, distinct touch targets.
- General Styling:
- Metadata Font: 10px to 12px.
- Button Font: 9px to 11px, 'font-weight: bold', 'white-space: nowrap'.
- Use 'text-center' on all text elements.
9. STRICT CODE ORGANIZATION (NON-NEGOTIABLE)
----------------------------------------------
WORD LIST AT THE TOP OF THE PAGE (CRITICAL): People read the page source to see the whole game, so
the dataset MUST be easy to find and read.
- Put `const RAW_DATA = [ ... ];` in its own small plain <script> (NOT type="text/babel") in the
<head>, directly after the <title> (and after any link-preview <meta> tags).
- Put this comment on the line just before that <script>:
<!-- openlang-data: the complete word list for this game, one pair per line: "text" is the left card, "translation" the right card -->
- Put this comment on the line just after its </script>: <!-- /openlang-data -->
- One item per line, keys in the order id, text, translation. Right-align the id and pad the text
value with spaces so the "translation" keys line up in one column. Leave out "audio" when it is
null (the game treats a missing audio field the same as null).
- CRITICAL: RAW_DATA must be a strictly valid JSON array of objects. Use double quotes (") for
all keys and string values to prevent syntax errors with apostrophes (e.g., "don't").
- The main script below MUST NOT declare RAW_DATA again; it reads this global RAW_DATA. In its
place it has the comment /* RAW_DATA (the word list) is defined near the top of this page. */
To ensure consistency and prevent Scope/Reference errors, you MUST structure the main <script> tag
in this EXACT order and place it at the very end of the <body> tag (after the <div id="root">):
1. Global Constants & Config (CONFIG, AUDIO_ENABLED, MUTE_KEY, isMutedNow; RAW_DATA comes from the
word-list script at the top of the page).
2. Pure Helper Functions (shuffle, getDerangement, fitCardText, capFontSpread, fitAllCards) -
defined OUTSIDE the component.
3. The Main Component (`const App = () => { ... }`):
a. State Definitions (CRITICAL: You MUST destructure hooks at the top of the component: const {
useState, useEffect, useLayoutEffect, useRef } = React;).
b. Refs (`useRef`).
c. Initial Effect (`useEffect` for mounting/loading storage).
d. Core Logic Functions (`startRound`, `saveProgress`, `speakCard`).
e. Interaction Handlers (`handleMatch`, `handleFail`, `selectCard`, `clearSelection`,
`handleCardTap` - defined INSIDE component).
f. Event Wrappers (`onTouchStart`, `onDragStart`, `onCardClick` - defined INSIDE component).
g. The JSX Return.
- Card height: style={{ height: CARD_MAX_HEIGHT, ... }} (the constant string defined with the
helpers); fitAllCards then adjusts it only when CONFIG.COMPACT_CARDS is true.
4. ReactDOM.createRoot / render.
10. LOGIC TRACE & STATE PROGRESSION EXAMPLE (STRICT REFERENCE)
--------------------------------------------------------------
CRITICAL OVERFIT WARNING: The specific words ([health], [boy], etc.), the language (Italian), and
the browser language ('en-US') used in the trace below are purely HYPOTHETICAL EXAMPLES to
demonstrate the mathematical logic and order of operations. DO NOT hardcode these specific words or
language codes into your React code. Your code must dynamically use the generated dataset,
`TARGET_LANGUAGE`, `LANGUAGE_CODE`, and the user's actual `navigator.language`.
[HYPOTHETICAL INITIAL SETUP (For tracing purposes only)]
- Assume for this example: TARGET_LANGUAGE is "Italian" and LANGUAGE_CODE is "IT".
- Round loads dynamically with 3 pairs from the dataset.
- Global State: Score: 0 | Streak: 0 | Learned Words: 0
- Hypothetical User Environment: Assume `navigator.language` evaluates to 'en-US' (English) and Mute
state is 'false'. CONFIG.MUTED and CONFIG.COMPACT_CARDS are absent.
- Hypothetical Left Column: [health], [boy], [future]
- Hypothetical Right Column: [futuro], [salute], [ragazzo]
- Constraint Check: Valid Derangement confirmed.
[TURN 1: Correct Guess (Standard)]
- Action: User drags "health" (Left) and drops it on "salute" (Right).
- State Check: Match is CORRECT.
- Execution:
1. Audio Check: Mute is false. Browser is English ('en'). Speak TARGET text: "salute" using a
voice matching `LANGUAGE_CODE`.
2. Visual: Apply CSS Green Flash to both cards.
3. Math: Score = 0 + (10 base + 0 streak) = 10.
4. Math: Streak increases 0 -> 1.
5. State & Memory: Add "health" to `learnedIds`. Remove "health" from `deckRef.current`
immediately.
6. Storage: Save updated `{ score, streak, learnedIds }` with safeStorage.setItem.
7. Board: Remove both cards from display after 200ms timeout.
[TURN 1.5: ALTERNATE TTS SCENARIO (Non-English Browser)]
- Scenario: If the user's `navigator.language` matched the `LANGUAGE_CODE` (e.g., 'it-IT') instead
of English.
- Execution: Audio Check sees browser is NOT English. Speaks BASE text: "health" using an English
('en') voice. All other logic identical to Turn 1.
[TURN 2: Wrong Guess]
- Action: User drags "boy" (Left) and drops it on "futuro" (Right).
- State Check: Match is INCORRECT.
- Execution:
1. Visual: Apply CSS Red Flash to target card ("futuro") for 2 seconds.
2. Math: Score = 10 - 5 (penalty) = 5.
3. Math: Streak resets 1 -> 0.
4. Storage: Save updated `{ score, streak, learnedIds }` with safeStorage.setItem.
5. Board: Cards remain on the screen.
[TURN 2.5: Tap Selection Changes (No Scoring)]
- Action A: User taps "ragazzo" (Right). Nothing was selected -> "ragazzo" gets .card-selected.
- Action B: User taps "futuro" (Right). Same column -> selection moves to "futuro".
- Action C: User taps "futuro" (Right) again. Same card -> selection cleared; no card is
highlighted.
- Execution: No match attempt, no audio, Score stays 5, Streak stays 0, nothing saved.
- Mobile note: Each tap moved the finger less than 10px, so no drag clone was created; each tap was
handled in `touchend`, which called `preventDefault()` so no synthetic click followed (any click
that still arrives for the same card within 700ms is ignored via `_lastTouchTap`).
[TURN 3: Correct Guess (by Tap)]
- Action: User taps "boy" (Left), then taps "ragazzo" (Right).
- Tap Logic: "boy" gets .card-selected. Then other column -> baseId = boy, targetId = ragazzo.
Selection cleared, then the shared match logic runs.
- State Check: Match is CORRECT.
- Execution: Audio plays, Green Flash, Score = 5 + (10 + 0 streak) = 15, Streak becomes 1, added to
`learnedIds`, removed from `deckRef`, saved via safeStorage. Both cards removed after 200ms.
[TURN 4: Round Completion (by Tap, Right Column First)]
- Action: User taps "futuro" (Right), then taps "future" (Left).
- Tap Logic: Other column -> baseId = future (the LEFT card), targetId = futuro (the RIGHT card),
even though the right card was tapped first. Selection cleared, then the shared match logic runs.
- State Check: Match is CORRECT.
- Execution: Audio plays, Green Flash, Score = 15 + (10 + 1 streak) = 26, Streak becomes 2, added to
`learnedIds`, removed from `deckRef`, saved via safeStorage.
- Round Check: 0 cards left in `roundData`. `deckRef` still has unlearned items.
- Execution: `startRound()` triggered automatically via `useEffect` to load next batch.
11. ACCEPTANCE CHECKS (THE FINISHED PAGE MUST PASS ALL OF THESE)
-----------------------------------------------------------------
- Fast taps: on an Android phone, tapping a left card and then its partner on the right as fast as
possible (under half a second apart) always attempts the match.
- Phone matching: on a touch phone, tapping a left card and then its partner on the right, or
dragging the left card onto it, scores points and removes both cards, in the first round and in
every later round.
- Long text: with a dataset of 150-250 character cards, no text ever extends past its card's edges,
on first load or later, on a 360px-wide phone and on desktop.
- Short after long: when a new round puts a short phrase where a long one was, its font returns to
the normal size instead of staying small.
- Unbreakable words: a single very long word wraps or shrinks inside its card and never sticks out
sideways.
- Even sizes: all cards on one side of a round show the same font size, and the remaining cards
never grow while matched cards are removed.
- Compact cards (COMPACT_CARDS true): all cards in a round share one height that hugs the longest
text (at least 44px, at most CARD_MAX_HEIGHT), and no card changes height while others are
removed.
- Slow load: with a throttled connection (the Tailwind CDN and fonts arriving late), cards are still
fitted correctly once the page finishes loading.
- Resize and rotate: after resizing the window or rotating the phone, all cards are refitted and
nothing overflows.
- Blocked storage: with site data blocked (or `window.localStorage` throwing on access), the game
loads and plays normally with no console errors; progress is just not kept after reload.
- Normal storage: with storage available, score, streak, learned words, and mute state survive a
page reload.
12. COPYRIGHT (Footer)
---------------------
Place the copyright text verbatim in the Footer (very small print, centered):
- Link "Functional AI Inc" to: https://functional.by
- Link "MIT License" to: https://opensource.org/licenses/MIT
"Copyright (c) 2026 by Functional AI Inc. Licensed under the MIT License."
Use exactly this JSX for the text (no margin or padding classes on the links, so no gap appears
before the full stops; both links open in a new tab and are underlined):
<span>Copyright (c) 2026 by <a href="https://functional.by" target="_blank" rel="noreferrer" className="underline">Functional AI Inc</a>. Licensed under the <a href="https://opensource.org/licenses/MIT" target="_blank" rel="noreferrer" className="underline">MIT License</a>.</span>