SLOPSHOPPER

wordle-mod

Play a Wordle-style game in a pane while Claude generates a response.

panecommandtoastnetworktimer
★ 1v0.1.0MITupdated 2026-10-09Sumo-99/claude_wordle_mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · wordle-mod
│ ┃ Wordle ✕ › fix the failing auth test and add an audit log call │ ┃ ╔═══════════════════════════════════════════ │ ┃ ║ 1UP 00000 HI-SCORE 00000 STA ⏺ Read(src/auth.ts) │ ┃ ║ ⎿ Read 6 lines │ ┃ ║ ▐ ⏺ Update(src/auth.ts) │ ┃ ║ ▐█● • • • • • • • • • • • ⎿ Added 2 lines, removed 1 line │ ┃ ║ ▐█ ⏺ Bash(bun test) │ ┃ ║ ▐ ⎿ 3 pass, 1 fail │ ┃ ║ │ ┃ ║ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ║ 1: SKIP │ ┃ ╚═══════════════════════════════════════════ ✻ Worked for 42s · done 4:20 PM │ ┃ ⏎ skip │ › /wordle │ ⎿ wordle-mod: Wordle pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Wordle
╔══════════════════════════════════════════════════════╗ ║ 1UP 00000 HI-SCORE 00000 STAGE 09 OCT ║ ║ ║ ║ ▐ ║ ║ ▐█● • • • • • • • • • • • • • ● ║ ║ ▐█ ║ ║ ▐ ║ ║ ║ ║ ║ ║ 1: SKIP ║ ╚══════════════════════════════════════════════════════╝ ⏎ skip
README

Claude Wordle mod

A Claude Code mod that lets you play Wordle in a pane while Claude is busy generating a response. It works in the terminal CLI and in the Code tab of the Claude Desktop app.

The Wordle mod: the arcade intro, the board and keyboard side by side, and the Pick a game screen

For the best experience, increase your terminal height.

Install

From the marketplace (Claude Code 2.1.275 or later):

/plugin install wordle-mod --marketplace Sumo-99/claude_wordle_mod

Load it

From a clone of this repo:

claude --plugin-dir .

Then type /wordle.

Commands

CommandWhat it does
/wordleOpens the Wordle pane (always available, even while Claude is working).
/wordle config auto-open onAlso open the pane automatically whenever Claude starts a turn.
/wordle config auto-open offTurn that off (the default).
/wordle config auto-openShow the current setting.
/wordle config reset-historySay how many saved games would be deleted. Add confirm to delete every saved game and cached word (stats and settings are kept; CLEAR STATS under ▾ MORE resets those).

The pane never closes on its own. Close it with its ✕ or Esc. An auto-opened pane doesn't take the keyboard from your prompt, and the platform only seats it in terminals at least 144 columns wide; /wordle typed by you has no width limit.

Playing

You get six guesses at the day's five-letter word. The pane is a compact arcade cabinet ("Claude night"), about 12 rows tall: a one-line header (the WORDLE badge and your score), then one framed panel with the board on the left and the controls on the right, and a hint line underneath.

After each guess every tile is filled by its result:

  • green: right letter, right place
  • amber: right letter, wrong place
  • dark with a dim letter: letter not in the word

Rows you haven't reached are pellets (•, with ● power pellets in the last row's corners); the row you are typing shows your letters and a ▌ cursor.

The keyboard mirrors what you've learned: a key's chip turns green or amber once that letter is found, and a letter that is known to be a miss is eaten: its key disappears, leaving a dim ·.

Controls

ControlWhat it does
TYPE: fieldType your guess (it has the keyboard when the pane opens). Backspace deletes the last letter, Enter submits.
On-screen keysClick a letter to add it. ⏎ submits, ⌫ deletes.
⏎ ENTER / ⌫ DELETEThe hint line names the two keys; click them like the chips. There are no digit hotkeys any more (a hotkey would draw a 1: in front of the icon) and letter keys have none either: type into the field instead.
◀ ▶Beside STAGE in the stats row: step back and forward through the last 14 days.
▶ TODAYUnder the frame on any other day: jump back to today's puzzle.
DATE…Under the frame, left of ▾ MORE: opens a big PICK A STAGE container below the compact layout (scroll down to it) with a list of the last 14 days and a field for any other date (YYYY-MM-DD, from 2021-06-19 on). Picking a day plays it and closes the container.
▾ MOREUnder the frame: opens a big STATS container below the compact layout: games played, the 1–6 guess distribution as bars, and CLEAR STATS (press twice to confirm). ▴ LESS closes it. Only one of the two containers is open at a time: opening one closes the other.
EscClose the pane.

In the header, 1UP is this puzzle's score (100 for every guess left when you solve it, 0 otherwise), HI is the best score in your stats, and STAGE is the puzzle's date. LIVES shows ◆ for each guess left and ◇ for each used; READY! shows until your first guess.

Solve the puzzle and the board gives way to a 3-second red celebration — it opens out from the centre with shockwaves, a red-and-gold burst, a turning sunburst and WORDDDD... / you solved it! — and it always plays to the end (there is no skip). Then the Pick a game screen opens. /wordle config reduce-motion on swaps it for a plain fade (and the opening splash for its 1-second still).

Pick a game

Open the pane with today's puzzle finished (won or lost) and, after the splash, it opens the Pick a game screen instead of the board. The same screen follows every finished game, today's or practice, and it opens by itself. A win plays the whole celebration first. A loss shows THE WORD WAS … for 3 seconds (with ⏎ CONTINUE, hotkey 1, to go sooner). The keyboard lands on RANDOM GAME, so 1 and 2 work right away.

The picker is the same compact frame (about 12 rows; the two cards stack when the pane is too narrow for them):

  • header: the badge, TODAY SOLVED 4/6 (or TODAY LOST · CRANE), then 1UP and HI
  • ⚄ RANDOM GAME (hotkey 1): a random date from 2021-06-19 to yesterday, never today and never one you finished today. Under it, how many are left. Played everything? It says You've played every game today! and starts the set over.
  • PICK A DATE (hotkey 2 plays the date shown): ◀ ▶ step through the same range, jumping over dates you finished today (the caption names what the last step skipped). It starts on yesterday, or the newest date you haven't played today.
  • STREAK, BEST, WIN%, and NEXT DAILY IN HH:MM:SS (it redraws every second, from a timer that only runs while the picker is showing)
  • footer: ↺ TODAY'S BOARD reopens today's board (a finished one is read-only, with CONTINUE back), DATE… opens a typed-date field (today, future dates, dates before 2021-06-19 and dates you finished today are rejected with a message), ESC TO EXIT.

A date counts as played today only when its game ends, won or lost; one you leave halfway stays available and resumes where you left off. A past date you finished on an earlier day starts over with a fresh board. Random and picked games are practice and never touch your stats. The played-today set lives in the store as { day, dates } and empties itself when the date changes. config:random (a number from 0 to under 1, set in the store) fixes RANDOM GAME's pick for repeatable testing; it is normally unset.

Stats

STREAK (current streak), BEST (longest streak) and WIN% sit in the controls panel, next to the stage. Only today's puzzle counts. ▾ MORE shows games played, wins and how many wins took 1–6 guesses, and CLEAR STATS resets the history to zero without touching your saved boards.

Practice: past puzzles

Any day other than today is a practice stage (PRACTICE STAGE beside the badge): it never changes your stats. Step to one with ◀ ▶ or type a date behind DATE…. Your board for each date is saved, so ▶ TODAY resumes where you left off.

Pane size

The pane opens in the compact layout, about 12 rows tall: the controls sit beside the board from 75 columns (78 wide when there's room), and wider panes get bigger tiles and keys (from 85 and 99 columns). The footer always stays on one row there; its right margin shrinks before it would wrap. In a pane narrower than 75 columns the controls stack under the board (about 20 rows). Docked, a dock too narrow for the compact layout is asked once for 78 columns; a wider dock is left as it is.

Inline, Claude Code gives the pane about a third of the terminal's height, so in a short terminal the compact layout gives way to keep the footer bar (DATE…, ▾ MORE) in view: first the blank rows around the board, then the one above the stats row, then the header, then the frame's border, down to 7 rows (a terminal of about 27 rows). Below that the board alone is taller than the pane, and the pane scrolls.

Each tile is one row tall, so a guess sits right on top of the next unless there's a blank row between them. The pane spends the rows it has to spare on those blank rows, one at a time as it grows: first between your latest guess and the row you're typing, then between earlier guesses, up to a gap between every two rows (15 rows side by side). It grows no taller than that. With no row to spare, the row you're typing still has its own lighter fill, so it never runs into the guess above it.

It opens compact whatever the height. Make the terminal taller after that and once the pane has the height for the stacked layout (its rows plus two: about 21 to 22 body rows), it stacks, board on top, with the biggest tiles and keys that fit. Once stacked it stays stacked until the height drops two rows below that, so it doesn't flicker on the edge. ▾ MORE and DATE… each open a big framed container underneath, which can take as much room as it needs (scroll down to it); the compact layout above stays as it is.

Offline

The day's word comes from the NYT's unofficial Wordle endpoint. If it can't be reached, the mod falls back to a deterministic offline word and shows a ⚠ OFFLINE marker in the header; press it to see why. The endpoint is undocumented and can change without notice, which is exactly what the fallback is for.

Network, data and privacy

What the mod does with your machine, in full:

  • Network: one request per puzzle date, to the NYT's unofficial Wordle endpoint, https://www.nytimes.com/svc/wordle/v2/<YYYY-MM-DD>.json, with a 3-second timeout. The only thing sent is the date being looked up. No account, no name, no prompt or code from your session is sent, and no other host is contacted.
  • Local reads: the two word lists in data/, read from the plugin folder so the offline word and the guess check work.
  • Local storage: the day's answer, your stats, which days you've played, and the pane's layout choices, kept in the engine's per-plugin store on your machine. Nothing in it leaves the machine.
  • Commands and tools: the mod runs no shell commands, starts no agents, and calls no tools or MCP servers. It draws its own pane, answers the /wordle command, optionally opens the pane when a session starts, and runs its own animation timers.
  • Credentials: the mod reads no credentials, tokens or keys from your machine.

License

MIT. See LICENSE.

Development

claude plugin validate .   # check the manifest and hooks module
claude plugin test .       # run hooks/__tests__/*.test.ts

Layout:

  • .claude-plugin/, hooks/, data/, types/: the plugin. hooks/register.js is the single hooks module and the only place that touches the engine's $; hooks/lib/ is pure logic it calls.
  • docs/spec/: the design and the reasons behind it.
  • plan/: the staged build plan this was built from, one contract per stage. VERIFY.md lists the manual checks.

The valid-guess and fallback-answer word lists in data/ come from public Wordle word lists (the original answers and allowed-guesses sets).

Source 12 files
hooks/register.js 723 lines
1import { atom, read, update } from 'claude-code'
2
3import { boardMetrics, COMPACT_WIDTH, FALLBACK_NOTE, isStackedLayout, renderBoard, SIDE_BY_SIDE_MIN } from './lib/board-view.js'
4import { boardKey, checkArchiveDate } from './lib/archive.js'
5import { hiScore, stepStage } from './lib/arcade.js'
6import { FRAME_MS as SPLASH_FRAME_MS, splashFrames } from './lib/splash.js'
7import {
8  ALL_PLAYED_MESSAGE,
9  checkPickerDate,
10  clearPlayed,
11  loadPlayed,
12  markPlayed,
13  PLAYED_KEY,
14  RANDOM_KEY,
15  randomDate,
16  shownDate,
17  stepPicker,
18} from './lib/picker.js'
19import { FRAME_MS, TOTAL_FRAMES } from './lib/fireworks.js'
20import {
21  AUTO_OPEN_KEY,
22  describeAutoOpen,
23  describeReduceMotion,
24  describeResetAsk,
25  describeResetDone,
26  historyKeys,
27  parseWordleArgs,
28  REDUCE_MOTION_KEY,
29  USAGE,
30} from './lib/lifecycle.js'
31import { createGame, submitGuess, WORD_LENGTH } from './lib/game-engine.js'
32import { DEFAULT_STATS, loadStats, recordCompletion, STATS_KEY } from './lib/stats.js'
33import { isValidGuess, resolveWord } from './lib/word-source.js'
34
35const PANE = 'wordle'
36
37const game = atom({ plugin: 'wordle-mod', key: 'game' }, null)
38const draft = atom({ plugin: 'wordle-mod', key: 'draft' }, '')
39const puzzle = atom({ plugin: 'wordle-mod', key: 'puzzle' }, null)
40const stats = atom({ plugin: 'wordle-mod', key: 'stats' }, DEFAULT_STATS)
41const isStatsOpen = atom({ plugin: 'wordle-mod', key: 'isStatsOpen' }, false)
42const isConfirmingClear = atom({ plugin: 'wordle-mod', key: 'isConfirmingClear' }, false)
43const isDateEntryOpen = atom({ plugin: 'wordle-mod', key: 'isDateEntryOpen' }, false)
44const celebrationFrame = atom({ plugin: 'wordle-mod', key: 'celebrationFrame' }, -1)
45const isMotionReduced = atom({ plugin: 'wordle-mod', key: 'isMotionReduced' }, false)
46const isStacked = atom({ plugin: 'wordle-mod', key: 'isStacked' }, false)
47const openRows = atom({ plugin: 'wordle-mod', key: 'openRows' }, null)
48// which screen the pane shows: the game board, or the Pick a game screen
49const mode = atom({ plugin: 'wordle-mod', key: 'mode' }, 'game')
50const pickerDate = atom({ plugin: 'wordle-mod', key: 'pickerDate' }, null)
51const pickerDir = atom({ plugin: 'wordle-mod', key: 'pickerDir' }, -1)
52const playedToday = atom({ plugin: 'wordle-mod', key: 'playedToday' }, { day: null, dates: [] })
53const todayGame = atom({ plugin: 'wordle-mod', key: 'todayGame' }, null)
54const tick = atom({ plugin: 'wordle-mod', key: 'tick' }, 0)
55// the opening splash while it plays: `{ id, frame, opts }` (see lib/splash.js), else null
56const splash = atom({ plugin: 'wordle-mod', key: 'splash' }, null)
57
58const CLEAR_CONFIRM_MS = 5000
59
60// A plugin has one hooks module and the engine's `$` can't cross an import, so
61// everything that touches `$` lives here; lib/ is pure and takes closures.
62const makeIo = $ => ({
63  store: { get: key => $.store.get(key), set: (key, value) => $.store.set(key, value) },
64  fetch: (url, init) => $.http.fetch(url, init),
65  sleep: ms => $.clock.sleep(ms),
66  readData: file => $.fs.read(`${$.plugin.root}/data/${file}`),
67})
68
69const today = async $ => {
70  const d = new Date(await $.clock.now())
71  const pad = n => String(n).padStart(2, '0')
72
73  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
74}
75
76let isLoading = false
77
78// Docked, the dock's share can be too narrow to sit side by side (49 columns at 120),
79// so the first draw asks it once for the compact layout's columns; a wider share is
80// left alone (a fixed request would narrow it). A request, not a grant: a width the
81// person drags wins. No `rows`: inline a request caps the room, so the pane couldn't
82// grow when the terminal does, and it can't buy rows the layout hasn't got to spare.
83let hasAskedWidth = false
84
85/**
86 * Opens the pane afresh: compact first, whatever the room, until the room grows.
87 * `splash` arms the opening splash ('full' from /wordle, 'short' from auto-open);
88 * the pane's first draw starts it.
89 */
90const openPane = async ($, options, { splash: version = null } = {}) => {
91  hasAskedWidth = false
92  await update($, openRows, () => null)
93  await update($, isStacked, () => false)
94  try {
95    if (version) await armSplash($, version === 'short')
96  } catch {
97    // no splash is better than no pane: open straight onto the game
98  }
99  await $.ui.open({ id: PANE, title: 'Wordle', closeOnEscape: true, ...options })
100}
101
102const isPaneOpen = async $ => {
103  try {
104    return (await $.ui.panes()).some(pane => pane.id === PANE)
105  } catch {
106    return false
107  }
108}
109
110// ---- the opening splash (lib/splash.js) ----
111
112// The running frame timer; STARTING while the first draw's start is queued. The module's
113// own, so after a reload the next draw finds none and carries on from the saved frame.
114const STARTING = { cancel: () => {} }
115let splashTimer = null
116let nextSplashId = 1
117let endedSplashId = 0
118
119const stopSplashTimer = () => {
120  splashTimer?.cancel()
121  splashTimer = null
122}
123
124/**
125 * Readies a splash for the pane about to open, frame 0. Reads, never writes: the
126 * HI-SCORE, whether today is finished (row 9's line), and the reduced-motion setting.
127 */
128const armSplash = async ($, isAutoOpen) => {
129  const io = makeIo($)
130  const now = await today($)
131  const saved = await io.store.get(boardKey(now))
132  const opts = {
133    date: now,
134    hiScore: hiScore(await loadStats(io)),
135    isTodayDone: Boolean(saved?.status && saved.status !== 'playing'),
136    reducedMotion: (await $.store.get(REDUCE_MOTION_KEY)) === true,
137    isAutoOpen,
138  }
139  stopSplashTimer()
140  const id = nextSplashId++
141  await update($, splash, () => ({ id, frame: 0, opts }))
142}
143
144/** Steps the armed splash every 100 ms from its saved frame; at the last frame it hands off. */
145const runSplash = async $ => {
146  if (splashTimer && splashTimer !== STARTING) return // another queued start got there first
147  const current = await read($, splash)
148  if (!current) {
149    splashTimer = null
150
151    return
152  }
153  if (splashTimer && splashTimer !== STARTING) return
154  const timer = $.clock.every(SPLASH_FRAME_MS, async () => {
155    const next = await update($, splash, s => (s?.id === current.id ? { ...s, frame: s.frame + 1 } : s))
156    if (next?.id !== current.id) return timer.cancel() // ended, or a newer open replaced it
157    if (next.frame >= splashFrames(next.opts)) await endSplash($)
158  })
159  splashTimer = timer
160  // a /wordle open holds the keyboard: put it on the key catcher, so any key skips.
161  // Auto-open never takes the keys from the person's next prompt.
162  if (!current.opts.isAutoOpen) {
163    try {
164      await $.ui.focus({ requestId: PANE, key: 'splash-key' })
165    } catch {
166      // a click or `1` still skips
167    }
168  }
169}
170
171/**
172 * Ends the splash: its last frame, a skip (any key, a click, `1`) or the pane
173 * closing. Then, unless the pane closed, the hand-off: today's game, or the
174 * picker when today is finished. Runs once per splash, however many skips race.
175 */
176const endSplash = async ($, { handOff = true } = {}) => {
177  const current = await read($, splash)
178  if (!current || current.id === endedSplashId) return
179  endedSplashId = current.id
180  stopSplashTimer()
181  await update($, splash, () => null)
182  if (!handOff) return
183  await update($, isDateEntryOpen, () => false)
184  await update($, isStatsOpen, () => false)
185  await startDate($, await today($))
186  const g = await read($, game)
187  if (g && g.status !== 'playing') return goPicker($)
188  await leavePicker($)
189  await focusGuess($)
190}
191
192/**
193 * Makes `date` the active puzzle: its word, and the saved board if that date was
194 * started before (so switching back resumes it). Runs from a timer or a handler,
195 * never from a draw. `fresh` (the picker opening a past date) starts a new board in
196 * place of a saved one that is finished; an unfinished one is resumed either way.
197 */
198const startDate = async ($, date, { fresh = false } = {}) => {
199  try {
200    const io = makeIo($)
201    const { solution, source } = await resolveWord(io, date)
202    const saved = await io.store.get(boardKey(date))
203    // If this date was started on an offline word and the live word has since come
204    // back different, finish the game already in progress on the word it began with
205    // (still marked offline) rather than throwing the player's guesses away.
206    const isReplay = fresh && saved?.status && saved.status !== 'playing'
207    const keepSaved = saved && !isReplay && (saved.answer === solution || saved.guesses.length > 0)
208    const resumed = keepSaved ? saved : createGame(solution)
209    if (isReplay) await io.store.set(boardKey(date), resumed)
210    const shownSource = resumed.answer === solution ? source : 'fallback'
211    const isToday = date === (await today($))
212    const savedStats = await loadStats(io)
213    await update($, game, () => resumed)
214    await update($, draft, () => '')
215    await update($, puzzle, () => ({ date, source: shownSource, isToday }))
216    await update($, stats, () => savedStats)
217  } catch {
218    $.ui.toast('Could not start a puzzle.')
219  } finally {
220    isLoading = false
221  }
222}
223
224/**
225 * Gives the keyboard back to the Guess field. A click on an on-screen key leaves
226 * the focus ring on that key, and then Enter would press the key again (the
227 * Backspace key, say, deleting a letter instead of submitting) and a physical
228 * Backspace would do nothing. With the ring back on the field, Enter submits and
229 * Backspace edits it, whichever way the last letter went in. A refusal (the field
230 * is gone because the game is over, or the pane doesn't hold the keys) is fine.
231 */
232const focusGuess = async $ => {
233  try {
234    await $.ui.focus({ requestId: PANE, key: 'guess' })
235  } catch {
236    // focus is a convenience; never let it get in the way of a press
237  }
238}
239
240// While true the Guess field is drawn empty. See resyncField.
241const isFieldBlanked = atom({ plugin: 'wordle-mod', key: 'isFieldBlanked' }, false)
242
243const RESYNC_GAP_MS = 60
244
245/**
246 * Makes the Guess field show the draft again. Found from the live diagnostic log:
247 * the field empties its own text on Enter, and it takes the `value` we draw it with
248 * only when that value CHANGES between two drawings. After a rejected guess the
249 * draft is unchanged, so the value was too, and the field stayed empty while the
250 * draft lived on unseen; the next keystroke then replaced it ("type from scratch").
251 * Drawing it empty and then with the draft is a change each time, so it takes both.
252 * Edits that arrive during the empty moment come from a blanked field and are
253 * dropped (see setDraft).
254 */
255const resyncField = async $ => {
256  await update($, isFieldBlanked, () => true)
257  // on a timer, not awaited: the handler that rejected the guess is not held up for it
258  $.clock.after(RESYNC_GAP_MS, () => update($, isFieldBlanked, () => false))
259}
260
261/**
262 * A guess that can't be played (too short, or not a word). As in the real Wordle
263 * the letters STAY and the guess costs nothing: the player just edits the word.
264 */
265const rejectGuess = async ($, message) => {
266  $.ui.toast(message)
267  await resyncField($)
268}
269
270const typeLetter = async ($, letter) => {
271  const g = await read($, game)
272  if (!g || g.status !== 'playing') return
273  await update($, draft, d => (d.length < WORD_LENGTH ? d + letter : d))
274}
275
276const backspace = async $ => {
277  await update($, draft, d => d.slice(0, -1))
278}
279
280/** The typing field's text, reduced to the draft: lowercase letters, at most five. */
281const setDraft = async ($, text) => {
282  const g = await read($, game)
283  if (!g || g.status !== 'playing') return
284  const letters = String(text).toLowerCase().replace(/[^a-z]/g, '').slice(0, WORD_LENGTH)
285  if (await read($, isFieldBlanked)) return // an edit of the field while it is being refilled
286  await update($, draft, () => letters)
287  // the draft is trimmed to letters, five at most; if that changed what was typed (a sixth
288  // letter, a digit), the field must be told, or it keeps showing the longer text
289  if (letters !== String(text).toLowerCase()) await resyncField($)
290}
291
292const REASONS = { length: 'Not enough letters', invalid: 'Not in word list' }
293
294const enter = async $ => {
295  const g = await read($, game)
296  if (!g || g.status !== 'playing') return
297  const word = await read($, draft)
298  if (word.length < WORD_LENGTH) return rejectGuess($, REASONS.length)
299
300  const isValid = await isValidGuess(makeIo($), word)
301  const out = submitGuess(g, word, () => isValid)
302  if (!out.ok) return rejectGuess($, REASONS[out.reason] ?? 'Cannot play that')
303  await update($, game, () => out.game)
304  await update($, draft, () => '')
305  const active = await read($, puzzle)
306  if (active) await $.store.set(boardKey(active.date), out.game)
307  // Only a finished game of today's puzzle counts; practice dates never do. The
308  // game was 'playing' before this guess, so this fires once per game, and a
309  // finished board that is merely resumed later never reaches here.
310  if (out.game.status !== 'playing' && active) {
311    const now = await today($)
312    if (active.date === now) {
313      const next = await recordCompletion(makeIo($), {
314        won: out.game.status === 'won',
315        guessCount: out.game.guesses.length,
316      })
317      await update($, stats, () => next)
318    } else {
319      // a practice game that ended: the picker leaves it out for the rest of the day
320      await markPlayed(makeIo($), now, active.date)
321    }
322  }
323  if (out.game.status === 'won') {
324    $.ui.toast(`Solved in ${out.game.guesses.length}!`)
325    await celebrate($)
326  }
327  if (out.game.status === 'lost') {
328    $.ui.toast(`The word was ${out.game.answer.toUpperCase()}`)
329    // the finished board holds the answer a moment, then the picker opens on its own
330    const date = active?.date
331    $.clock.after(LOSS_HOLD_MS, () => finishToPicker($, date))
332  }
333}
334
335/** ▶ TODAY and the date field: validate, then switch the active puzzle. */
336const pickDate = async ($, input) => {
337  if ((await read($, mode)) === 'picker') return playTyped($, input)
338  const check = checkArchiveDate(input, await today($))
339  if (!check.ok) return $.ui.toast(check.reason)
340  await update($, isDateEntryOpen, () => false)
341  await startDate($, check.date)
342}
343
344/** ◀ (dir -1) and ▶ (dir +1) beside the stage date: one day back or forward. */
345const stepToStage = async ($, dir) => {
346  const active = await read($, puzzle)
347  const now = await today($)
348  const date = stepStage(active?.date ?? now, now, dir)
349  if (date) await pickDate($, date)
350}
351
352/** DATE…: shows or hides the typed-date field, and gives it the keyboard when it opens. */
353const toggleDateEntry = async $ => {
354  const isOpen = await update($, isDateEntryOpen, v => !v)
355  if (isOpen) await update($, isStatsOpen, () => false) // one panel at a time
356  if (!isOpen) return focusGuess($)
357  try {
358    await $.ui.focus({ requestId: PANE, key: 'archive-date' })
359  } catch {
360    // the person can click into it instead
361  }
362}
363
364// ---- the Pick a game screen ----
365
366let tickTimer = null
367
368/** Reads today's saved board and the played-today set into the atoms the picker draws from. */
369const refreshPicker = async $ => {
370  const io = makeIo($)
371  const now = await today($)
372  const saved = await io.store.get(boardKey(now))
373  await update($, todayGame, () => (saved?.status && saved.status !== 'playing' ? saved : null))
374  const dates = await loadPlayed(io, now)
375  await update($, playedToday, () => ({ day: now, dates }))
376}
377
378/** Shows the picker; its clock ticks (the countdown) only while it is the screen. */
379const goPicker = async $ => {
380  await update($, isDateEntryOpen, () => false)
381  await update($, isStatsOpen, () => false)
382  await update($, pickerDate, () => null)
383  await update($, pickerDir, () => -1)
384  await update($, tick, () => 0)
385  await refreshPicker($)
386  await update($, mode, () => 'picker')
387  tickTimer?.cancel()
388  tickTimer = $.clock.every(1000, async () => {
389    if ((await read($, mode)) !== 'picker') return tickTimer?.cancel()
390    // a new day: today's board and the played-today set are another day's now
391    if ((await read($, playedToday)).day !== (await today($))) await refreshPicker($)
392    const now = await $.clock.now()
393    await update($, tick, () => now)
394  })
395  // the finished board's field is gone, so the keys would have nowhere to land: give
396  // them to RANDOM GAME, which puts the picker's 1 and 2 hotkeys in reach at once
397  try {
398    await $.ui.focus({ requestId: PANE, key: 'random' })
399  } catch {
400    // focus is a convenience; a click works too
401  }
402}
403
404// How long a lost board shows the answer before the picker opens on its own.
405const LOSS_HOLD_MS = 3000
406
407/**
408 * A game just ended (the celebration ran out, or a loss's hold is over): the picker opens
409 * on its own. Only if that same finished game is still on screen; one the person already
410 * left (CONTINUE, another date) is not pulled away from.
411 */
412const finishToPicker = async ($, date) => {
413  if ((await read($, mode)) !== 'game') return
414  const g = await read($, game)
415  if (!g || g.status === 'playing' || (await read($, puzzle))?.date !== date) return
416  await goPicker($)
417}
418
419const leavePicker = async $ => {
420  tickTimer?.cancel()
421  tickTimer = null
422  await update($, mode, () => 'game')
423}
424
425/** What the pane opens on: today's puzzle, or the picker once it is finished. */
426const openToday = async $ => {
427  await update($, isDateEntryOpen, () => false)
428  await startDate($, await today($))
429  await leavePicker($)
430}
431
432/** After a puzzle loads on its own (the pane opening): a finished daily goes to the picker. */
433const routeOpening = async $ => {
434  const g = await read($, game)
435  if (g && g.status !== 'playing') await goPicker($)
436}
437
438/** Opens a pool date from the picker: resumes an unfinished board, replaces a finished one. */
439const openPracticeDate = async ($, date) => {
440  await update($, isDateEntryOpen, () => false)
441  await startDate($, date, { fresh: true })
442  await leavePicker($)
443}
444
445/** Every date is played: say so and start the set over. */
446const allPlayed = async $ => {
447  $.ui.toast(ALL_PLAYED_MESSAGE)
448  await clearPlayed(makeIo($), await today($))
449  await refreshPicker($)
450}
451
452const playRandom = async $ => {
453  const now = await today($)
454  const fixed = await $.store.get(RANDOM_KEY)
455  const date = randomDate(now, await loadPlayed(makeIo($), now), typeof fixed === 'number' ? () => fixed : undefined)
456  if (!date) return allPlayed($)
457  await openPracticeDate($, date)
458}
459
460const stepPickerDate = async ($, dir) => {
461  const now = await today($)
462  const played = await loadPlayed(makeIo($), now)
463  const next = stepPicker(shownDate(await read($, pickerDate), now, played), now, played, dir)
464  if (!next) return
465  await update($, pickerDate, () => next)
466  await update($, pickerDir, () => dir)
467}
468
469const playShown = async $ => {
470  const now = await today($)
471  const played = await loadPlayed(makeIo($), now)
472  const date = shownDate(await read($, pickerDate), now, played)
473  if (played.includes(date)) return allPlayed($)
474  await openPracticeDate($, date)
475}
476
477/** The typed date on the picker: a rejection toasts and leaves the field open. */
478const playTyped = async ($, input) => {
479  const now = await today($)
480  const check = checkPickerDate(input, now, await loadPlayed(makeIo($), now))
481  if (!check.ok) return $.ui.toast(check.reason)
482  await openPracticeDate($, check.date)
483}
484
485/** What the picker draws: the played-today set counts only for today, whatever day the record is from. */
486const pickerView = async $ => {
487  const now = await today($)
488  const record = await read($, playedToday)
489  const played = record.day === now ? record.dates : []
490
491  return {
492    todayGame: await read($, todayGame),
493    played,
494    date: shownDate(await read($, pickerDate), now, played),
495    dir: await read($, pickerDir),
496    now: (await read($, tick)) || (await $.clock.now()),
497  }
498}
499
500let celebrationTimer = null
501
502/**
503 * Plays the win celebration: a timer steps the frame until the animation ends, then
504 * the picker opens. It always plays in full: there is no skip. Reads the
505 * reduced-motion setting once, as it starts.
506 */
507const celebrate = async $ => {
508  if ((await read($, celebrationFrame)) >= 0) return
509  const isReduced = (await $.store.get(REDUCE_MOTION_KEY)) === true
510  await update($, isMotionReduced, () => isReduced)
511  await update($, celebrationFrame, () => 0)
512  const date = (await read($, puzzle))?.date
513  celebrationTimer?.cancel()
514  const timer = $.clock.every(FRAME_MS, async () => {
515    const frame = await update($, celebrationFrame, n => (n < 0 ? n : n + 1))
516    if (frame < 0 || frame >= TOTAL_FRAMES) {
517      timer.cancel()
518      await update($, celebrationFrame, () => -1)
519      await finishToPicker($, date)
520    }
521  })
522  celebrationTimer = timer
523}
524
525/**
526 * Wipes the saved stats. Two presses within a few seconds: the first arms the
527 * button, the second clears. Saved boards are kept, so a finished puzzle stays
528 * finished; only streaks, win % and the distribution reset.
529 */
530const clearStats = async $ => {
531  if (!(await read($, isConfirmingClear))) {
532    await update($, isConfirmingClear, () => true)
533    $.clock.after(CLEAR_CONFIRM_MS, () => update($, isConfirmingClear, () => false))
534
535    return
536  }
537  await $.store.set(STATS_KEY, DEFAULT_STATS)
538  await update($, stats, () => DEFAULT_STATS)
539  await update($, isConfirmingClear, () => false)
540  $.ui.toast('Stats cleared.')
541}
542
543/** ▾ MORE / ▴ LESS beside the stats row: the details (played, distribution, Clear stats). */
544const toggleStats = async $ => {
545  const isOpen = await update($, isStatsOpen, v => !v)
546  if (isOpen) await update($, isDateEntryOpen, () => false) // one panel at a time
547}
548
549/** @type {import('claude-code').Register} */
550export const register = on => {
551  on('session.start', async ($, e, next) => {
552    await $.command.register({
553      name: 'wordle',
554      description: 'Open the Wordle pane',
555    })
556
557    return next(e)
558  })
559
560  on('command.run', { command: 'wordle' }, async ($, e) => {
561    const cmd = parseWordleArgs(e.args)
562    if (cmd.kind === 'usage') return { text: USAGE }
563    if (cmd.kind === 'show-auto-open') return { text: describeAutoOpen((await $.store.get(AUTO_OPEN_KEY)) === true) }
564    if (cmd.kind === 'set-auto-open') {
565      await $.store.set(AUTO_OPEN_KEY, cmd.value)
566
567      return { text: describeAutoOpen(cmd.value) }
568    }
569    if (cmd.kind === 'show-reduce-motion') return { text: describeReduceMotion((await $.store.get(REDUCE_MOTION_KEY)) === true) }
570    if (cmd.kind === 'set-reduce-motion') {
571      await $.store.set(REDUCE_MOTION_KEY, cmd.value)
572
573      return { text: describeReduceMotion(cmd.value) }
574    }
575    if (cmd.kind === 'reset-history-ask' || cmd.kind === 'reset-history') {
576      const doomed = historyKeys(await $.store.keys())
577      const games = doomed.filter(key => key.startsWith('board:')).length
578      if (cmd.kind === 'reset-history-ask') return { text: describeResetAsk(games) }
579
580      for (const key of doomed) await $.store.delete(key)
581      // the open game is history too: drop it so a pane that is showing it starts today afresh
582      await update($, game, () => null)
583      await update($, draft, () => '')
584      await update($, puzzle, () => null)
585      await $.store.delete(PLAYED_KEY)
586      await leavePicker($)
587
588      return { text: describeResetDone(games) }
589    }
590    // every /wordle plays the splash, even onto a pane that is already open
591    await openPane($, { focus: true }, { splash: 'full' })
592
593    return { text: 'Wordle pane opened.' }
594  })
595
596  // Auto-open: only if the person turned it on. No `focus` (the mod opened it,
597  // not the person, so it must not take the keyboard from the next prompt), and
598  // there is deliberately no turn.complete hook: the pane never auto-closes.
599  // The short splash plays only when this actually opens it: a pane already up
600  // (mid-game, say) is left as it is on every later turn.
601  on('turn.start', async ($, e, next) => {
602    try {
603      if ((await $.store.get(AUTO_OPEN_KEY)) === true) {
604        await openPane($, {}, { splash: (await isPaneOpen($)) ? null : 'short' })
605      }
606    } catch {
607      // a refused open must never get in the way of Claude's turn
608    }
609
610    return next(e)
611  })
612
613  // Closing the pane (Esc, its close mark) ends a splash that is playing, with no hand-off.
614  on('ui.close', async ($, e, next) => {
615    if (e.id === PANE) await endSplash($, { handOff: false })
616
617    return next(e)
618  }).catch(($, e, next) => next(e)) // a failure here must never keep the pane open
619
620  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
621    if (e.requestId !== PANE) return next(e)
622    const { Box, Text, Button, Input, Select } = $.ui.resolve(e)
623    // The Pane's size (this build hands it over under `e.props`): the body's width sizes
624    // the board, and its rows, once known, let it stack (board on top) when there's room.
625    const columns = e.props?.bodyColumns ?? e.viewport?.columns ?? 78
626    const bodyRows = e.props?.scroll?.bodyRows
627    const wasStacked = await read($, isStacked)
628    const rowsAtOpen = await read($, openRows)
629    const stacked = isStackedLayout(columns, bodyRows, wasStacked, rowsAtOpen)
630    const view = {
631      game: await read($, game),
632      draft: await read($, draft),
633      puzzle: await read($, puzzle),
634      today: await today($),
635      stats: await read($, stats),
636      isStatsOpen: await read($, isStatsOpen),
637      isConfirmingClear: await read($, isConfirmingClear),
638      isDateEntryOpen: await read($, isDateEntryOpen),
639      celebrationFrame: await read($, celebrationFrame),
640      isMotionReduced: await read($, isMotionReduced),
641      isFieldBlanked: await read($, isFieldBlanked),
642      mode: await read($, mode),
643      picker: await pickerView($),
644      splash: await read($, splash),
645      // the win screen fills the pane: the Pane's own width and row room (this build hands
646      // them over under `e.props`), the rows capped so the red stays about the board's height.
647      screen: {
648        columns: e.props?.bodyColumns ?? e.viewport?.columns ?? 40,
649        rows: Math.min(26, e.props?.scroll?.bodyRows ?? Math.max(12, (e.viewport?.rows ?? 30) - 6)),
650      },
651      layout: { columns, rows: bodyRows, isStacked: stacked },
652    }
653
654    // A draw can't write state, so the mode just drawn is recorded right after it; the
655    // next draw reads it back for the switch-back gap (and draws the same, so it settles)
656    // only stacking the height chose counts for the gap: one the width forced (a dock
657    // still too narrow on its first draw) mustn't hold the pane stacked once it's wider
658    const isStackedByHeight = stacked && boardMetrics(columns).isSideBySide
659    if (isStackedByHeight !== wasStacked) $.clock.after(0, () => update($, isStacked, () => isStackedByHeight))
660    // the rows it opened with: stacking waits until the room grows past them
661    if (rowsAtOpen == null && bodyRows != null) $.clock.after(0, () => update($, openRows, rows => rows ?? bodyRows))
662    if (e.props?.placement === 'dock' && columns < SIDE_BY_SIDE_MIN && !hasAskedWidth) {
663      hasAskedWidth = true
664      $.clock.after(0, () => $.ui.open({ id: PANE, title: 'Wordle', closeOnEscape: true, columns: COMPACT_WIDTH }))
665    }
666
667    // the splash starts on the first draw after an open (a pane that waits unplaced plays
668    // it when it appears); later draws, resizes included, leave the running one alone
669    if (view.splash && !splashTimer) {
670      splashTimer = STARTING
671      $.clock.after(0, () => runSplash($))
672    }
673
674    // while the splash plays its hand-off loads the puzzle (and must not be pulled to the picker under it)
675    if (!view.game && !isLoading && !view.splash) {
676      isLoading = true
677      $.clock.after(0, async () => {
678        await startDate($, await today($))
679        await routeOpening($)
680      })
681    }
682
683    return renderBoard({ h, Box, Text, Button, Input, Select }, view, {
684      letter: async ch => {
685        await typeLetter($, ch)
686        await focusGuess($)
687      },
688      enter: async () => {
689        await enter($)
690        await focusGuess($)
691      },
692      backspace: async () => {
693        await backspace($)
694        await focusGuess($)
695      },
696      input: text => setDraft($, text),
697      pickDate: async value => {
698        await pickDate($, value)
699        // a refused typed date leaves its field open, and the keyboard with it
700        if (!(await read($, isDateEntryOpen))) await focusGuess($)
701      },
702      stepStage: async dir => {
703        await stepToStage($, dir)
704        await focusGuess($)
705      },
706      toggleStats: () => toggleStats($),
707      toggleDateEntry: () => toggleDateEntry($),
708      clearStats: () => clearStats($),
709      fallbackInfo: () => $.ui.toast(FALLBACK_NOTE),
710      continue: () => goPicker($),
711      stepPicker: dir => stepPickerDate($, dir),
712      choosePickerDate: value => update($, pickerDate, () => value),
713      randomGame: () => playRandom($),
714      playPicked: () => playShown($),
715      openToday: async () => {
716        await openToday($)
717        await focusGuess($)
718      },
719      skipSplash: () => endSplash($),
720    })
721  })
722}
723
hooks/lib/board-view.js 781 lines
1import { recentDates } from './archive.js'
2import { gameScore, hiScore, keyLook, livesText, pad, PALETTE, stageLabel, stepStage, tileLook } from './arcade.js'
3import { celebrationRows, MIN_COLUMNS, MIN_ROWS } from './fireworks.js'
4import { MAX_GUESSES, WORD_LENGTH } from './game-engine.js'
5import { formatCount, longDate, nextDailyIn, recentUnplayed, remaining } from './picker.js'
6import { skipButton, splashLayout, splashRows } from './splash.js'
7import { winPercent } from './stats.js'
8
9export const FALLBACK_NOTE = "Couldn't reach the live word — showing an offline puzzle instead."
10
11const KEY_ROWS = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
12
13// A hotkey is one digit or one lowercase letter, so Enter and Backspace sit on
14// digits. The letter keys carry none: a `plain` Button with a hotkey draws as
15// `q: Q`, too wide for a 5-column key, and the Guess field takes typed letters.
16export const ENTER_KEY = '1'
17export const BACKSPACE_KEY = '2'
18
19const RANK = { gray: 1, yellow: 2, green: 3 }
20
21/**
22 * What the guesses have taught about each letter: the best result it has had.
23 * Green beats yellow beats gray, so a letter found in the right place stays
24 * green on the keyboard even if a later guess used it in the wrong spot.
25 */
26export const keyStates = game => {
27  const states = {}
28  for (const { word, score } of game.guesses) {
29    ;[...word].forEach((ch, i) => {
30      if (!states[ch] || RANK[score[i]] > RANK[states[ch]]) states[ch] = score[i]
31    })
32  }
33
34  return states
35}
36
37// The finished board's control: opens the picker (a lost board also opens it on its own after a moment).
38const CONTINUE_LABEL = '⏎ CONTINUE'
39
40/**
41 * The win screen: while it runs it REPLACES the board. Every cell of the pane is
42 * painted by `celebrationRows` (a red radial gradient with a turning sunburst,
43 * opening out from the centre, the burst and the words on top). It has no control:
44 * it always plays to the end, and then the picker opens. `screen` is
45 * `{ columns, rows }`, the room the pane has.
46 */
47const celebrationScreen = (h, Box, Text, frame, screen, reducedMotion) => {
48  const columns = Math.max(MIN_COLUMNS, screen.columns)
49  const rows = celebrationRows(frame, { columns, rows: Math.max(MIN_ROWS, screen.rows) }, reducedMotion)
50  const drawRow = (runs, y) =>
51    h(
52      Box,
53      { key: `fw${y}`, flexDirection: 'row' },
54      ...runs.map((run, i) => h(Text, { key: i, color: run.color, bold: run.bold, backgroundColor: run.backgroundColor }, run.text)),
55    )
56
57  return h(
58    Box,
59    { key: 'fireworks-wrap', flexDirection: 'column', alignItems: 'center' },
60    h(Box, { key: 'fireworks', flexDirection: 'column', width: columns }, ...rows.map(drawRow)),
61  )
62}
63
64/** The runs covering columns [from, to) of a row of runs. */
65const sliceRuns = (runs, from, to) => {
66  const out = []
67  let x = 0
68  for (const run of runs) {
69    const chars = [...run.text]
70    const text = chars.slice(Math.max(0, from - x), Math.max(0, to - x)).join('')
71    if (text) out.push({ ...run, text })
72    x += chars.length
73  }
74
75  return out
76}
77
78/**
79 * The opening splash: while it runs it REPLACES the pane, as the win screen does.
80 * `splashRows` paints the picture (centred; a bigger pane doesn't stretch it); the
81 * skip line's `1: label` is a real Button (a click or `1` skips). Typed keys skip
82 * too: they land in a key-catcher field drawn zero rows tall, so the picture keeps
83 * its rows and the letter never reaches the guess. `splash` is `{ frame, opts }`.
84 */
85const splashScreen = (ui, splash, layout, on) => {
86  const { h, Box, Text, Button, Input } = ui
87  const screen = { columns: layout.columns, rows: layout.rows }
88  const { columns } = splashLayout(screen)
89  const skip = skipButton(splash.frame, screen, splash.opts)
90  const drawRuns = (runs, prefix) =>
91    runs.map((run, i) => h(Text, { key: `${prefix}${i}`, color: run.color, bold: run.bold, backgroundColor: run.backgroundColor }, run.text))
92  const drawRow = (runs, y) => {
93    if (skip?.row !== y) return h(Box, { key: `sp${y}`, flexDirection: 'row' }, ...drawRuns(runs, 'r'))
94    const end = skip.column + skip.hotkey.length + 2 + skip.label.length
95
96    return h(
97      Box,
98      { key: `sp${y}`, flexDirection: 'row', backgroundColor: PALETTE.background },
99      ...drawRuns(sliceRuns(runs, 0, skip.column), 'a'),
100      h(Button, { key: 'skip-splash', label: skip.label, hotkey: skip.hotkey, plain: true, dimColor: true, onPress: () => on.skipSplash() }),
101      ...drawRuns(sliceRuns(runs, end, columns), 'b'),
102    )
103  }
104
105  return h(
106    Box,
107    { key: 'splash-wrap', flexDirection: 'column', alignItems: 'center', width: layout.columns },
108    h(Box, { key: 'splash', flexDirection: 'column', width: columns }, ...splashRows(splash.frame, screen, splash.opts).map(drawRow)),
109    h(
110      Box,
111      { key: 'splash-keys', height: 0, overflow: 'hidden' },
112      h(Input, { key: 'splash-key', value: '', autoFocus: true, submitLabel: 'skip', onInput: () => on.skipSplash(), onSubmit: () => on.skipSplash() }),
113    ),
114  )
115}
116
117// ---- the compact arcade board (docs/ui-ref/wordle-compact-options.png, panel 1) ----
118
119const FRAME_PADDING = 1 // blank rows above and below the board inside the frame
120const FRAME_BORDER = 2 // the round frame's two border columns (and its two border rows)
121const DIVIDER = 1 // the faint │ between board and controls
122const STATS_ROW = 45 // the widest right-hand row other than the keyboard (stats and stage)
123const BAR_WIDTH = 24
124
125/** The columns of the board and controls columns with `tile`- and `chip`-wide cells and `pad` either side. */
126const sizesFor = (tile, chip, pad) => {
127  const keyboard = KEY_ROWS[0].length * (chip + 1) - 1
128
129  return { tile, chip, pad, keyboard, board: WORD_LENGTH * tile + (WORD_LENGTH - 1) + pad * 2, controls: Math.max(keyboard, STATS_ROW) + pad * 2 }
130}
131const sideBySideWidth = s => FRAME_BORDER + s.board + DIVIDER + s.controls
132
133/** Side by side, widest first: 5-column tiles and chips (99 columns), 5-column tiles (85), all 3 (from 75). */
134const SIDE_BY_SIDE = [sizesFor(5, 5, 2), sizesFor(5, 3, 2), sizesFor(3, 3, 2)]
135/** From this many columns the controls sit beside the board; narrower, they stack under it. */
136export const SIDE_BY_SIDE_MIN = sideBySideWidth(SIDE_BY_SIDE.at(-1))
137/** The compact layout's width when there is room (the stage 09 reference): its controls take the extra columns. */
138export const COMPACT_WIDTH = 78
139
140/** Stacked: the controls take the widest chips and padding that fit `columns`, the board the widest tiles. */
141const stackedSizes = columns => {
142  const fits = s => FRAME_BORDER + s.controls <= columns
143  const pad = [2, 1, 0].find(p => fits(sizesFor(3, 3, p))) ?? 0
144  const chip = fits(sizesFor(3, 5, pad)) ? 5 : 3
145  const tile = FRAME_BORDER + sizesFor(5, chip, pad).board <= columns ? 5 : 3
146
147  return sizesFor(tile, chip, pad)
148}
149
150/**
151 * The board's sizes for a pane body `columns` wide. Side by side (unless
152 * `isStacked`): the widest layout that fits, drawn at its own width (centred;
153 * the rest is margin). Stacked, or too narrow to sit side by side: board on
154 * top, controls under it, at the full body width with the widest cells that fit.
155 */
156export const boardMetrics = (columns, isStacked = false) => {
157  const side = !isStacked && SIDE_BY_SIDE.find(s => sideBySideWidth(s) <= columns)
158  if (side === SIDE_BY_SIDE.at(-1)) return { ...side, isSideBySide: true, width: Math.min(columns, COMPACT_WIDTH) }
159  if (side) return { ...side, isSideBySide: true, width: sideBySideWidth(side) }
160
161  return { ...stackedSizes(columns), isSideBySide: false, width: columns }
162}
163
164// ---- height: the pane stacks when the body has the rows for it ----
165
166// The text the header and footer rows hold at their widest (a practice stage with
167// ▶ TODAY showing and DATE… open), so the stacked height doesn't change with the stage.
168const BADGE_TEXT = ' W O R D L E '
169const PRACTICE_TEXT = 'PRACTICE STAGE'
170const HEADER_CELLS = [['1UP', '00000'], ['HI', '00000'], ['STAGE', '27 SEP']]
171const HINT_PARTS = ['TYPE TO PLAY · ', '⏎ ENTER', ' · ', '⌫ DELETE', ' · ESC TO EXIT']
172const FOOTER_BUTTONS = ['▶ TODAY', '▴ DATE…', '▾ MORE']
173const HEADER_GAP = 2 // between the header's two halves, and between the badge and the practice line
174const HEADER_CELL_GAP = 3
175const FOOTER_GAP = 2 // between the hint and the footer's buttons
176const FOOTER_BUTTON_GAP = 3
177const FOOTER_RIGHT_PAD = 6
178
179const sum = parts => parts.reduce((n, part) => n + part, 0)
180const HEADER_WIDTH =
181  1 + BADGE_TEXT.length + 1 + HEADER_GAP + PRACTICE_TEXT.length + HEADER_GAP +
182  sum(HEADER_CELLS.map(([label, value]) => label.length + 1 + value.length)) + HEADER_CELL_GAP * (HEADER_CELLS.length - 1)
183const FOOTER_WIDTH =
184  sum(HINT_PARTS.map(part => part.length)) + FOOTER_GAP +
185  sum(FOOTER_BUTTONS.map(label => label.length)) + FOOTER_BUTTON_GAP * (FOOTER_BUTTONS.length - 1) + FOOTER_RIGHT_PAD
186/** A wrapping row of two halves: one row when it all fits, two when it doesn't. */
187const wrappedRows = (width, columns) => (width <= columns ? 1 : 2)
188const CONTROL_ROWS = 1 + 1 + KEY_ROWS.length + 1 + 1 // status, field, keyboard, gap, stats and stage
189
190/**
191 * How the compact layout gives way when the pane is short (inline it gets about a
192 * third of the terminal): first the board's two spare rows, then the blank row above
193 * the stats row, then the header, then the frame's border, so the board, the keyboard
194 * and the footer bar (DATE…, ▾ MORE) always show. Fullest first. `boardSpare` is the
195 * rows the fit keeps for the board beyond its six tile rows; they become gaps between
196 * tile rows (see `boardRoom` and `gapRows`).
197 */
198const COMPACT_FITS = [
199  { boardSpare: FRAME_PADDING * 2, hasGap: true, hasHeader: true, hasBorder: true },
200  { boardSpare: 0, hasGap: true, hasHeader: true, hasBorder: true },
201  { boardSpare: 0, hasGap: false, hasHeader: true, hasBorder: true },
202  { boardSpare: 0, hasGap: false, hasHeader: false, hasBorder: true },
203  { boardSpare: 0, hasGap: false, hasHeader: true, hasBorder: false },
204  { boardSpare: 0, hasGap: false, hasHeader: false, hasBorder: false },
205]
206/** The frame's inside rows at the least: the taller of the board (with its spare rows) and the controls. */
207const fitBodyRows = fit => Math.max(MAX_GUESSES + fit.boardSpare, CONTROL_ROWS - (fit.hasGap ? 0 : 1))
208/** The stacked layout's board as its height is measured (the fullest fit's): six tile rows and two spare. */
209const BOARD_ROWS = MAX_GUESSES + COMPACT_FITS[0].boardSpare
210/** The tallest the board grows: a blank row between every two tile rows. */
211const MAX_BOARD_ROWS = MAX_GUESSES * 2 - 1
212
213/** How many rows the stacked layout takes in a body `columns` wide: header, frame (board over controls), footer. */
214export const stackedRows = columns =>
215  wrappedRows(HEADER_WIDTH, columns) + FRAME_BORDER + BOARD_ROWS + CONTROL_ROWS + wrappedRows(FOOTER_WIDTH, columns)
216
217/**
218 * The room the board gets in a pane body `bodyRows` tall, the rest of the layout
219 * taking `aroundRows`: `body`, the rows the board's part of the frame takes (side by
220 * side, also the controls' and the divider's), and `spare`, the rows of it beyond the
221 * six tile rows (0–5), each one a gap between two tile rows. It grows a row at a time
222 * with the pane, from the fit's own rows up to a gap between every two tile rows,
223 * and no further: past that the pane keeps its compact height. Unknown rows: the fit's own.
224 */
225export const boardRoom = (least, bodyRows, aroundRows) => {
226  const body = bodyRows == null ? least : Math.max(least, Math.min(Math.max(MAX_BOARD_ROWS, least), bodyRows - aroundRows))
227
228  return { body, spare: Math.min(MAX_BOARD_ROWS, body) - MAX_GUESSES }
229}
230
231/**
232 * Which tile rows get a blank row under them, given `spare` rows to place. Only two
233 * filled rows next to each other can run together (a guess, or the row being typed;
234 * pellet rows have no fill), so the gaps go where those meet, the newest first: the
235 * last guess and the row being typed, then each guess and the one before it. Any
236 * left over go under the rows still to come, top down. The count is the pane's,
237 * never the game's: the board keeps its height as the guesses come in.
238 */
239export const gapRows = (game, spare) => {
240  const filled = game.guesses.length + (game.status === 'playing' ? 1 : 0)
241  const meeting = Array.from({ length: Math.max(0, filled - 1) }, (_, i) => filled - 2 - i)
242  const ahead = Array.from({ length: MAX_GUESSES - 1 }, (_, r) => r).filter(r => !meeting.includes(r))
243
244  return new Set([...meeting, ...ahead].slice(0, Math.max(0, spare)))
245}
246/** A fit's rows: header, frame border, frame body, footer. */
247export const fitRows = fit => (fit.hasHeader ? 1 : 0) + (fit.hasBorder ? FRAME_BORDER : 0) + fitBodyRows(fit) + 1
248/** The fullest compact layout that fits `bodyRows` (all of it while the rows are unknown). */
249export const compactFit = bodyRows => COMPACT_FITS.find(fit => bodyRows == null || fitRows(fit) <= bodyRows) ?? COMPACT_FITS.at(-1)
250
251/** The side-by-side layout's rows with room to spare: header, frame (the board beside the controls), footer. */
252export const SIDE_BY_SIDE_ROWS = fitRows(COMPACT_FITS[0])
253
254/** From this many body rows the pane stacks: the stacked layout's own height and two to spare. */
255export const stackAt = columns => stackedRows(columns) + 2
256/** Once stacked, the pane stays stacked until the body is this many rows short of the threshold. */
257export const STACK_GAP = 2
258
259/**
260 * Whether the pane draws stacked. Too narrow to sit side by side: always.
261 * Otherwise it opens compact, side by side, whatever its height (`openRows`,
262 * the rows it opened with, is still unknown on the first draw), and stacks only
263 * once the body has grown past those rows to `stackAt` or more (the width
264 * fitting the stacked layout). A pane that `wasStacked` keeps stacking until
265 * the body is `STACK_GAP` rows short of that, so it doesn't flicker on the edge.
266 */
267export const isStackedLayout = (columns, bodyRows, wasStacked = false, openRows = null) => {
268  if (!boardMetrics(columns).isSideBySide) return true
269  if (bodyRows == null || openRows == null) return false
270  if (FRAME_BORDER + stackedSizes(columns).controls > columns) return false
271
272  return bodyRows >= Math.max(stackAt(columns), openRows + 1) - (wasStacked ? STACK_GAP : 0)
273}
274
275/**
276 * The footer's right margin: the full margin when it fits, less when it doesn't,
277 * so side by side the footer stays one row (the compact layout's 12) whatever the
278 * buttons say. Stacked, the footer wraps instead and keeps the full margin.
279 */
280const footerPad = (width, hintWidth, labels, isSideBySide) => {
281  if (!isSideBySide) return FOOTER_RIGHT_PAD
282  const used = hintWidth + FOOTER_GAP + sum(labels.map(label => label.length)) + FOOTER_BUTTON_GAP * (labels.length - 1)
283
284  return Math.max(0, Math.min(FOOTER_RIGHT_PAD, width - used))
285}
286
287/** `glyph` centred in an odd `width`: ` X `, `  X  `. */
288const centred = (glyph, width) => `${' '.repeat((width - 1) / 2)}${glyph}${' '.repeat((width - 1) / 2)}`
289
290/** One tile: one row, the letter centred on a fill. A letterless tile is just the fill. */
291const tile = (h, Box, Text, key, width, fill, letter, color) =>
292  h(Box, { key, width }, h(Text, { color, backgroundColor: fill, bold: true }, centred(letter, width)))
293
294/** A spot with no tile yet: a pellet (`●`, a power pellet, in the last row's corners). */
295const pellet = (h, Box, Text, key, width, glyph) =>
296  h(Box, { key, width }, h(Text, { color: PALETTE.pellet }, centred(glyph, width)))
297
298/** Row `r` of the board: scored tiles, the row being typed (with its ▌ cursor), or pellets; `isGapped`: a blank row under it. */
299const tileRow = (h, Box, Text, game, draft, r, width, isGapped) => {
300  const played = game.guesses[r]
301  const isActive = r === game.guesses.length && game.status === 'playing'
302  const cells = Array.from({ length: WORD_LENGTH }, (_, i) => {
303    const key = `t${r}-${i}`
304    if (played) {
305      const look = tileLook(played.score[i])
306
307      return tile(h, Box, Text, key, width, look.fill, played.word[i].toUpperCase(), look.letter)
308    }
309    if (isActive && draft[i]) return tile(h, Box, Text, key, width, PALETTE.active, draft[i].toUpperCase(), PALETTE.text)
310    if (isActive && i === draft.length) return tile(h, Box, Text, key, width, PALETTE.active, '▌', PALETTE.accent)
311    if (isActive) return tile(h, Box, Text, key, width, PALETTE.active, ' ', PALETTE.text)
312    const isPower = r === MAX_GUESSES - 1 && (i === 0 || i === WORD_LENGTH - 1)
313
314    return pellet(h, Box, Text, key, width, isPower ? '●' : '•')
315  })
316
317  return h(Box, { key: `row${r}`, flexDirection: 'row', gap: 1, ...(isGapped && { marginBottom: 1 }) }, ...cells)
318}
319
320/** A key chip: a filled `width`×1 Box holding a plain Button (a Button's label can't be colored, only the chip). */
321const chip = (h, Box, Button, boxKey, width, fill, button) =>
322  h(Box, { key: boxKey, width, backgroundColor: fill, justifyContent: 'center' }, h(Button, { plain: true, ...button }))
323
324/** The on-screen keyboard: chips colored by best known state; a known miss is just a dim · (an eaten pellet). */
325const keyboard = (h, Box, Text, Button, game, metrics, on) => {
326  const states = keyStates(game)
327  const isOver = game.status !== 'playing'
328  const width = metrics.chip
329  const rows = KEY_ROWS.map((row, i) => {
330    const keys = [...row].map(ch => {
331      const look = keyLook(states[ch])
332      if (look.isEaten) {
333        return h(Box, { key: `kx-${ch}`, width, justifyContent: 'center' }, h(Text, { color: PALETTE.dim }, '·'))
334      }
335
336      return chip(h, Box, Button, `kc-${ch}`, width, look.fill, { key: `k-${ch}`, label: ch.toUpperCase(), dimColor: isOver, onPress: () => on.letter(ch) })
337    })
338    if (i === 2) {
339      keys.unshift(chip(h, Box, Button, 'kc-enter', width, PALETTE.accent, { key: 'enter', label: '⏎', dimColor: isOver, onPress: () => on.enter() }))
340      keys.push(chip(h, Box, Button, 'kc-back', width, PALETTE.keyIdle, { key: 'back', label: '⌫', dimColor: isOver, onPress: () => on.backspace() }))
341    }
342
343    return h(Box, { key: `krow${i}`, flexDirection: 'row', gap: 1, justifyContent: i === 1 ? 'center' : 'flex-start', width: metrics.keyboard }, ...keys)
344  })
345
346  return h(Box, { key: 'keyboard', flexDirection: 'column' }, ...rows)
347}
348
349/** READY! (before guess 1) · GUESS N OF 6 · LIVES ◆◆◆◇◇◇; once the game ends, how it ended. */
350const statusRow = (h, Box, Text, game) => {
351  const n = game.guesses.length
352  const progress =
353    game.status === 'won'
354      ? h(Text, { key: 'progress', color: PALETTE.correct, bold: true }, `SOLVED IN ${n}/${MAX_GUESSES}`)
355      : game.status === 'lost'
356        ? h(Text, { key: 'progress', color: PALETTE.present, bold: true }, `THE WORD WAS ${game.answer.toUpperCase()}`)
357        : h(Text, { key: 'progress', color: PALETTE.text, bold: true }, `GUESS ${n + 1} OF ${MAX_GUESSES}`)
358
359  return h(
360    Box,
361    { key: 'status', flexDirection: 'row', gap: 3 },
362    game.status === 'playing' && n === 0 && h(Text, { key: 'ready', color: PALETTE.ready, bold: true }, 'READY!'),
363    progress,
364    h(Box, { key: 'lives', flexDirection: 'row', gap: 1 }, h(Text, { color: PALETTE.lives, bold: true }, 'LIVES'), h(Text, { color: PALETTE.lives }, livesText(game))),
365  )
366}
367
368const statPair = (h, Box, Text, key, label, color, value) =>
369  h(Box, { key, flexDirection: 'row', gap: 1 }, h(Text, { color, bold: true }, label), h(Text, { color: PALETTE.text, bold: true }, value))
370
371/** STREAK 04  BEST 09  WIN% 82  STAGE ◀ 27 SEP ▶ */
372const statsStageRow = (h, Box, Text, Button, { stats, puzzle, today }, on) => {
373  const date = puzzle?.date ?? today
374  const prev = stepStage(date, today, -1)
375  const next = stepStage(date, today, 1)
376  const arrow = (key, glyph, target, dir) =>
377    target ? h(Button, { key, label: glyph, plain: true, onPress: () => on.stepStage(dir) }) : h(Text, { key, color: PALETTE.dim }, ' ')
378
379  return h(
380    Box,
381    { key: 'stats', flexDirection: 'row', flexWrap: 'wrap', columnGap: 2 },
382    statPair(h, Box, Text, 'streak', 'STREAK', PALETTE.streak, pad(stats.currentStreak, 2)),
383    statPair(h, Box, Text, 'best', 'BEST', PALETTE.best, pad(stats.maxStreak, 2)),
384    statPair(h, Box, Text, 'win', 'WIN%', PALETTE.winPercent, pad(winPercent(stats), 2)),
385    h(
386      Box,
387      { key: 'stage', flexDirection: 'row', gap: 1 },
388      h(Text, { color: PALETTE.stage, bold: true }, 'STAGE'),
389      arrow('stage-prev', '◀', prev, -1),
390      h(Text, { color: PALETTE.text, bold: true }, stageLabel(date)),
391      arrow('stage-next', '▶', next, 1),
392    ),
393  )
394}
395
396/** The right-hand column: status, typing field, keyboard, stats and stage, in the reference's 7 rows. */
397const controls = (h, ui, view, metrics, fit, on) => {
398  const { Box, Text, Button, Input } = ui
399  const { game, draft, isFieldBlanked } = view
400  const isOver = game.status !== 'playing'
401
402  return h(
403    Box,
404    { key: 'controls', flexDirection: 'column', justifyContent: 'center', flexGrow: 1, paddingX: metrics.pad },
405    statusRow(h, Box, Text, game),
406    // The typing surface: the field edits `draft` natively (Backspace deletes the last
407    // letter, Enter submits); the chips feed the same draft. It sits where the reference
408    // has a blank row, so the pane is no taller for it.
409    isOver
410      ? h(Box, { key: 'no-field', height: 1 }, h(Button, { key: 'continue', label: CONTINUE_LABEL, hotkey: ENTER_KEY, plain: true, onPress: () => on.continue() }))
411      : h(Input, {
412          key: 'guess',
413          label: 'TYPE',
414          placeholder: 'a five-letter word',
415          // drawn empty for a moment to make the field take the draft again (see resyncField)
416          value: isFieldBlanked ? '' : draft,
417          autoFocus: true,
418          submitLabel: 'guess',
419          onInput: text => on.input(text),
420          onSubmit: () => on.enter(),
421        }),
422    keyboard(h, Box, Text, Button, game, metrics, on),
423    fit.hasGap && h(Text, { key: 'gap' }, ' '),
424    statsStageRow(h, Box, Text, Button, view, on),
425  )
426}
427
428/** The board column: six tile rows, with `spare` blank rows placed between them (see gapRows), centred. */
429const board = (h, Box, Text, game, draft, metrics, spare) => {
430  const gaps = gapRows(game, spare)
431
432  return h(
433    Box,
434    { key: 'board', flexDirection: 'column', justifyContent: 'center', width: metrics.board, paddingX: metrics.pad },
435    ...Array.from({ length: MAX_GUESSES }, (_, r) => tileRow(h, Box, Text, game, draft, r, metrics.tile, gaps.has(r))),
436  )
437}
438
439/** The faint line between board and controls: one column of │, `rows` tall (the frame's body). */
440const divider = (h, Box, Text, rows) =>
441  h(
442    Box,
443    { key: 'divider', flexDirection: 'column', width: 1 },
444    ...Array.from({ length: rows }, (_, i) => h(Text, { key: `d${i}`, color: PALETTE.divider }, '│')),
445  )
446
447/** The WORDLE badge: bold spaced letters in the background color on a title-colored fill, ▐ ▌ in the accent color on each side. */
448const badge = (h, Box, Text) =>
449  h(
450    Box,
451    { key: 'badge', flexDirection: 'row' },
452    h(Text, { color: PALETTE.accent }, '▐'),
453    h(Text, { color: PALETTE.background, backgroundColor: PALETTE.title, bold: true }, BADGE_TEXT),
454    h(Text, { color: PALETTE.accent }, '▌'),
455  )
456
457const headerCell = (h, Box, Text, key, label, value) =>
458  h(Box, { key, flexDirection: 'row', gap: 1 }, h(Text, { color: PALETTE.title, bold: true }, label), h(Text, { color: PALETTE.text, bold: true }, value))
459
460/** The text after the badge: a practice stage, or a puzzle the new day has turned into practice. */
461const subtitle = (h, Text, puzzle, today) => {
462  if (!puzzle || puzzle.date === today) return null
463  // `isToday` is what the puzzle was when it loaded: if the day has since rolled
464  // over, this is no longer today's puzzle even though it started as one
465  if (puzzle.isToday) {
466    return h(Text, { key: 'subtitle', color: PALETTE.present, bold: true }, `A NEW DAY HAS STARTED · ${stageLabel(puzzle.date)} IS NOW PRACTICE`)
467  }
468
469  return h(Text, { key: 'subtitle', color: PALETTE.subtitle, bold: true }, PRACTICE_TEXT)
470}
471
472/**
473 * A big on-demand container under the compact layout (▾ MORE, DATE…): its own round
474 * frame, as wide as the one above. It may be as tall as it likes; the person scrolls to it.
475 */
476const drawer = (h, Box, Text, key, title, ...children) =>
477  h(
478    Box,
479    { key, flexDirection: 'column', gap: 1, borderStyle: 'round', borderColor: PALETTE.walls, backgroundColor: PALETTE.panel, paddingX: 2, paddingY: 1 },
480    h(Text, { color: PALETTE.title, bold: true }, title),
481    ...children,
482  )
483
484/** ▾ MORE: games played, the 1–6 distribution as bars, and Clear stats. */
485const statsDrawer = (h, Box, Text, Button, stats, isConfirmingClear, on) => {
486  const most = Math.max(1, ...stats.distribution)
487  const bars = stats.distribution.map((n, i) => {
488    const width = n === 0 ? 0 : Math.max(1, Math.round((n / most) * BAR_WIDTH))
489
490    return h(
491      Box,
492      { key: `dist${i}`, flexDirection: 'row', gap: 1 },
493      h(Text, { color: PALETTE.dim }, String(i + 1)),
494      h(Text, { color: PALETTE.correct }, width > 0 ? '█'.repeat(width) : ''),
495      h(Text, { color: n === 0 ? PALETTE.dim : PALETTE.text, bold: n > 0 }, String(n)),
496    )
497  })
498
499  return drawer(
500    h,
501    Box,
502    Text,
503    'stats-details',
504    'STATS',
505    h(
506      Box,
507      { flexDirection: 'row', justifyContent: 'space-between' },
508      h(Text, { color: PALETTE.text, bold: true }, `PLAYED ${stats.played} · WON ${stats.wins}`),
509      // dim until the pointer or focus is on it; the first press only arms it
510      h(Button, {
511        key: 'clear-stats',
512        label: isConfirmingClear ? 'PRESS AGAIN TO CLEAR' : 'CLEAR STATS',
513        plain: true,
514        dimColor: !isConfirmingClear,
515        onPress: () => on.clearStats(),
516      }),
517    ),
518    h(Box, { flexDirection: 'column' }, h(Text, { color: PALETTE.dim }, 'WINS BY GUESS'), ...bars),
519  )
520}
521
522/** DATE…: pick one of the last 14 days from a list, or type any past date, to play it as a practice stage. */
523const dateDrawer = (h, Box, Text, Input, Select, { puzzle, today }, on) => {
524  const dates = recentDates(today)
525  const options = dates.map(date => ({ value: date, label: date === today ? `${stageLabel(date)} · ${date} (today)` : `${stageLabel(date)} · ${date}` }))
526
527  return drawer(
528    h,
529    Box,
530    Text,
531    'date-drawer',
532    'PICK A STAGE',
533    h(Select, {
534      key: 'archive-pick',
535      label: 'Last 14 days', // the Select draws its own colon after it
536      options,
537      value: puzzle && dates.includes(puzzle.date) ? puzzle.date : today,
538      onSelect: value => on.pickDate(value),
539    }),
540    // no autoFocus: the guess field owns the keyboard, letters here would be lost guesses
541    h(Input, { key: 'archive-date', label: 'Or a date', placeholder: 'YYYY-MM-DD', submitLabel: 'play', onSubmit: text => on.pickDate(text) }),
542    h(Text, { color: PALETTE.dim }, 'ANY DAY FROM 2021-06-19 UP TO TODAY · PRACTICE STAGES DON’T COUNT TOWARD YOUR STATS'),
543  )
544}
545
546// ---- the Pick a game screen (docs/ui-ref/wordle-picker.png) ----
547
548const CARD_MIN = 28 // the narrowest a card can be: ◀ 08 OCT 2026 ▶ 2: play
549const CARD_MAX = 32
550const CARD_GAP = 4
551
552/** A pixel-rounded block: ▗▄▄▖ over `rows` on a `fill` over ▝▀▀▘. */
553const card = (h, Box, Text, key, width, fill, ...rows) =>
554  h(
555    Box,
556    { key, flexDirection: 'column', width },
557    h(Text, { color: fill }, `▗${'▄'.repeat(width - 2)}▖`),
558    ...rows.map((row, i) => h(Box, { key: `${key}-r${i}`, width, backgroundColor: fill, ...row.box }, ...row.children)),
559    h(Text, { color: fill }, `▝${'▀'.repeat(width - 2)}▘`),
560  )
561
562/** The header's "TODAY …" piece: how today's daily ended. */
563const todaySummary = (h, Text, game) => {
564  if (game?.status === 'won') {
565    return [h(Text, { key: 't0', color: PALETTE.title, bold: true }, 'TODAY'), h(Text, { key: 't1', color: PALETTE.correct, bold: true }, `SOLVED ${game.guesses.length}/${MAX_GUESSES}`)]
566  }
567  if (game?.status === 'lost') {
568    return [h(Text, { key: 't0', color: PALETTE.title, bold: true }, 'TODAY'), h(Text, { key: 't1', color: PALETTE.present, bold: true }, `LOST · ${game.answer.toUpperCase()}`)]
569  }
570
571  return [h(Text, { key: 't0', color: PALETTE.title, bold: true }, 'TODAY'), h(Text, { key: 't1', color: PALETTE.dim, bold: true }, 'NOT FINISHED')]
572}
573
574/**
575 * The Pick a game screen, about 12 rows in the game screen's frame: header, a
576 * round frame (title, two cards with a caption under each, streak and countdown), footer.
577 * `view.picker` is `{ todayGame, played, date, dir, now }`: today's saved board, the dates
578 * finished today, the stepper's date (already moved past played ones) and the way it last moved, and the clock.
579 */
580const pickerScreen = (ui, view, on) => {
581  const { h, Box, Text, Button, Input, Select } = ui
582  const { today, stats, isDateEntryOpen, layout } = view
583  const { todayGame, played, date, now } = view.picker
584  const width = Math.min(layout.columns, COMPACT_WIDTH)
585  const inner = width - FRAME_BORDER
586  const isSideBySide = inner >= CARD_MIN * 2 + CARD_GAP
587  const cardWidth = isSideBySide ? Math.min(CARD_MAX, Math.floor((inner - CARD_GAP) / 2)) : Math.min(inner, CARD_MAX)
588  // the dropdown: the newest dates not finished today (an older one is behind DATE…)
589  const dates = recentUnplayed(today, played)
590  const options = (dates.length > 0 ? dates : [date]).map(d => ({ value: d, label: longDate(d) }))
591
592  const random = card(h, Box, Text, 'card-random', cardWidth, PALETTE.accent,
593    { box: { justifyContent: 'center' }, children: [h(Text, { key: 'dice', color: PALETTE.background, backgroundColor: PALETTE.accent, bold: true }, '⚄ RANDOM GAME')] },
594    { box: { justifyContent: 'center' }, children: [h(Button, { key: 'random', label: 'play', hotkey: '1', plain: true, onPress: () => on.randomGame() })] },
595  )
596  const pick = card(h, Box, Text, 'card-pick', cardWidth, PALETTE.cardKey,
597    { box: { paddingX: 2 }, children: [h(Text, { key: 'pick-title', color: PALETTE.text, bold: true }, 'PICK A DATE')] },
598    {
599      box: { paddingX: 2, columnGap: 1 },
600      children: [
601        h(Select, { key: 'pick-date', options, value: date, onSelect: value => on.choosePickerDate(value) }),
602        h(Button, { key: 'pick-play', label: 'play', hotkey: '2', plain: true, onPress: () => on.playPicked() }),
603      ],
604    },
605  )
606  const left = remaining(today, played)
607  const caption = (key, align, text) =>
608    h(Box, { key, width: cardWidth, justifyContent: align }, h(Text, { color: PALETTE.dim }, text || ' '))
609  const randomCaption = caption('caption-random', 'center', `${formatCount(left)} left · never today's`)
610  const pickCaption = caption('caption-pick', 'center', played.length > 0 ? 'played today are left out' : 'older dates: DATE…')
611  const cards = isSideBySide
612    ? h(Box, { key: 'cards', flexDirection: 'column', alignItems: 'center' },
613        h(Box, { key: 'cards-row', flexDirection: 'row', columnGap: CARD_GAP }, random, pick),
614        h(Box, { key: 'captions-row', flexDirection: 'row', columnGap: CARD_GAP }, randomCaption, pickCaption))
615    : h(Box, { key: 'cards', flexDirection: 'column', alignItems: 'center' }, random, randomCaption, pick, pickCaption)
616
617  return h(
618    Box,
619    { key: 'pane', width: layout.columns, alignItems: 'center' },
620    h(
621      Box,
622      { key: 'layout', flexDirection: 'column', width, backgroundColor: PALETTE.background },
623      h(
624        Box,
625        { key: 'header', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', columnGap: HEADER_GAP },
626        h(Box, { key: 'header-left', flexDirection: 'row', columnGap: HEADER_GAP }, badge(h, Box, Text), h(Box, { key: 'today', flexDirection: 'row', gap: 1 }, ...todaySummary(h, Text, todayGame))),
627        h(
628          Box,
629          { key: 'header-right', flexDirection: 'row', columnGap: HEADER_CELL_GAP },
630          headerCell(h, Box, Text, 'score', '1UP', pad(gameScore(todayGame), 5)),
631          headerCell(h, Box, Text, 'hi-score', 'HI', pad(hiScore(stats), 5)),
632        ),
633      ),
634      h(
635        Box,
636        { key: 'frame', flexDirection: 'column', borderStyle: 'round', borderColor: PALETTE.walls, backgroundColor: PALETTE.panel },
637        h(Box, { key: 'title', justifyContent: 'center' }, h(Text, { color: PALETTE.dim, bold: true }, 'PICK YOUR NEXT GAME')),
638        h(Text, { key: 'gap' }, ' '),
639        cards,
640        h(
641          Box,
642          { key: 'stats', flexDirection: 'row', justifyContent: 'space-between', flexWrap: 'wrap', paddingX: 2 },
643          h(
644            Box,
645            { key: 'stats-left', flexDirection: 'row', columnGap: 2 },
646            statPair(h, Box, Text, 'streak', 'STREAK', PALETTE.streak, pad(stats.currentStreak, 2)),
647            statPair(h, Box, Text, 'best', 'BEST', PALETTE.best, pad(stats.maxStreak, 2)),
648            statPair(h, Box, Text, 'win', 'WIN%', PALETTE.winPercent, pad(winPercent(stats), 2)),
649          ),
650          h(Text, { key: 'countdown', color: PALETTE.present, bold: true }, `NEXT DAILY IN ${nextDailyIn(now)}`),
651        ),
652      ),
653      h(
654        Box,
655        { key: 'footer', flexDirection: 'row' },
656        h(Button, { key: 'todays-board', label: "↺ TODAY'S BOARD", plain: true, dimColor: true, onPress: () => on.openToday() }),
657        h(Text, { key: 'f0', color: PALETTE.dim }, ' · '),
658        h(Button, { key: 'date-entry', label: isDateEntryOpen ? '▴ DATE…' : 'DATE…', plain: true, dimColor: true, onPress: () => on.toggleDateEntry() }),
659        h(Text, { key: 'f1', color: PALETTE.dim }, ' · ESC TO EXIT'),
660      ),
661      isDateEntryOpen &&
662        drawer(
663          h,
664          Box,
665          Text,
666          'date-drawer',
667          'PICK A DATE',
668          h(Input, { key: 'archive-date', label: 'A date', placeholder: 'YYYY-MM-DD', submitLabel: 'play', onSubmit: text => on.pickDate(text) }),
669          h(Text, { color: PALETTE.dim }, 'ANY DAY FROM 2021-06-19 UP TO YESTERDAY, NOT ONE YOU FINISHED TODAY · PRACTICE GAMES DON’T COUNT TOWARD YOUR STATS'),
670        ),
671    ),
672  )
673}
674
675/**
676 * The pane's tree for one game state. Pure: the caller supplies the element
677 * factory `h`, the surface's elements, and the press callbacks, so this file
678 * never touches the engine's `$`.
679 *
680 * @param ui `{ h, Box, Text, Button, Input, Select }`
681 * @param view `{ game, draft, puzzle, today, stats, isStatsOpen, isConfirmingClear, isDateEntryOpen, isFieldBlanked, celebrationFrame, isMotionReduced, screen, layout }`; `celebrationFrame` >= 0 shows the win screen instead of the board; `splash` (`{ frame, opts }`, see splash.js) shows the opening splash instead; `screen` is `{ columns, rows }`, the win screen's size; `layout` is `{ columns, rows, isStacked }`: the pane body's width, which sizes the tiles and chips, its rows (when known), which the compact layout fits (see `compactFit`), and whether to stack (see `isStackedLayout`); `game` null means still loading; `mode` 'picker' (with `picker` `{ todayGame, played, date, dir, now }`) draws the Pick a game screen instead of the board
682 * @param on `{ letter(ch), enter(), backspace(), input(text), pickDate(date), stepStage(dir), toggleStats(), toggleDateEntry(), clearStats(), fallbackInfo(), continue(), choosePickerDate(date), randomGame(), playPicked(), openToday(), skipSplash() }`
683 */
684export const renderBoard = (ui, view, on) => {
685  const { h, Box, Text, Button, Input, Select } = ui
686  const { game, draft, puzzle, today, stats, isStatsOpen, isConfirmingClear, isDateEntryOpen, celebrationFrame, isMotionReduced, screen, layout } = view
687  if (celebrationFrame >= 0) return celebrationScreen(h, Box, Text, celebrationFrame, screen, isMotionReduced)
688  if (view.splash) return splashScreen(ui, view.splash, layout, on)
689  if (view.mode === 'picker' && view.picker) return pickerScreen(ui, view, on)
690  if (!game) {
691    return h(Box, { flexDirection: 'column', backgroundColor: PALETTE.background }, h(Text, { color: PALETTE.dim }, 'LOADING TODAY’S STAGE…'))
692  }
693
694  const metrics = boardMetrics(layout.columns, layout.isStacked)
695  const { isSideBySide, width } = metrics
696  // side by side it fits the pane's rows (the footer bar always in view); stacked only comes with room to spare
697  const fit = isSideBySide ? compactFit(layout.rows) : COMPACT_FITS[0]
698  // the board's room grows with the pane's rows, a gap at a time: side by side it is the frame's
699  // body (around it: header, border, footer); stacked it is the board's own rows (around it, the rest)
700  const room = isSideBySide
701    ? boardRoom(fitBodyRows(fit), layout.rows, (fit.hasHeader ? 1 : 0) + (fit.hasBorder ? FRAME_BORDER : 0) + 1)
702    : boardRoom(BOARD_ROWS, layout.rows, stackedRows(layout.columns) - BOARD_ROWS)
703  const isOver = game.status !== 'playing'
704  const date = puzzle?.date ?? today
705  const [typeToPlay, enterLabel, dot, deleteLabel, escToExit] = HINT_PARTS
706  const overHint = 'CONTINUE TO PICK A GAME · ESC TO EXIT'
707  const todayLabel = date !== today ? '▶ TODAY' : null
708  const dateLabel = isDateEntryOpen ? '▴ DATE…' : 'DATE…'
709  const statsLabel = isStatsOpen ? '▴ LESS' : '▾ MORE'
710  const hintWidth = isOver ? overHint.length : sum(HINT_PARTS.map(part => part.length))
711  const rightPad = footerPad(width, hintWidth, [todayLabel, dateLabel, statsLabel].filter(Boolean), isSideBySide)
712
713  // the layout is drawn at its own width, centred in the body: spare columns are margin
714  return h(
715    Box,
716    { key: 'pane', width: layout.columns, alignItems: 'center' },
717    h(
718      Box,
719      { key: 'layout', flexDirection: 'column', width, backgroundColor: PALETTE.background },
720      fit.hasHeader &&
721        h(
722          Box,
723          { key: 'header', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', columnGap: HEADER_GAP },
724          h(
725            Box,
726            { key: 'header-left', flexDirection: 'row', columnGap: HEADER_GAP },
727            badge(h, Box, Text),
728            subtitle(h, Text, puzzle, today),
729            puzzle?.source === 'fallback' && h(Button, { key: 'fallback-warning', label: '⚠ OFFLINE', plain: true, onPress: () => on.fallbackInfo() }),
730          ),
731          h(
732            Box,
733            { key: 'header-right', flexDirection: 'row', columnGap: HEADER_CELL_GAP },
734            headerCell(h, Box, Text, 'score', '1UP', pad(gameScore(game), 5)),
735            headerCell(h, Box, Text, 'hi-score', 'HI', pad(hiScore(stats), 5)),
736            headerCell(h, Box, Text, 'stage-date', 'STAGE', stageLabel(date)),
737          ),
738        ),
739      h(
740        Box,
741        {
742          key: 'frame',
743          flexDirection: isSideBySide ? 'row' : 'column',
744          alignItems: isSideBySide ? 'stretch' : 'center',
745          ...(fit.hasBorder && { borderStyle: 'round', borderColor: PALETTE.walls }),
746          backgroundColor: PALETTE.panel,
747        },
748        board(h, Box, Text, game, draft, metrics, room.spare),
749        isSideBySide && divider(h, Box, Text, room.body),
750        controls(h, ui, view, metrics, fit, on),
751      ),
752      h(
753        Box,
754        { key: 'footer', flexDirection: 'row', flexWrap: isSideBySide ? 'nowrap' : 'wrap', justifyContent: 'space-between', columnGap: FOOTER_GAP },
755        h(
756          Box,
757          { key: 'hint', flexDirection: 'row' },
758          isOver
759            ? h(Text, { color: PALETTE.dim }, overHint)
760            : [
761                h(Text, { key: 'h0', color: PALETTE.dim }, typeToPlay),
762                h(Button, { key: 'hotkey-enter', label: enterLabel, plain: true, dimColor: true, onPress: () => on.enter() }),
763                h(Text, { key: 'h1', color: PALETTE.dim }, dot),
764                h(Button, { key: 'hotkey-back', label: deleteLabel, plain: true, dimColor: true, onPress: () => on.backspace() }),
765                h(Text, { key: 'h2', color: PALETTE.dim }, escToExit),
766              ],
767        ),
768        h(
769          Box,
770          { key: 'footer-right', flexDirection: 'row', columnGap: FOOTER_BUTTON_GAP, paddingRight: rightPad },
771          todayLabel && h(Button, { key: 'play-today', label: todayLabel, plain: true, onPress: () => on.pickDate(today) }),
772          h(Button, { key: 'date-entry', label: dateLabel, plain: true, dimColor: true, onPress: () => on.toggleDateEntry() }),
773          h(Button, { key: 'stats-toggle', label: statsLabel, plain: true, dimColor: true, onPress: () => on.toggleStats() }),
774        ),
775      ),
776      isStatsOpen && statsDrawer(h, Box, Text, Button, stats, isConfirmingClear, on),
777      isDateEntryOpen && dateDrawer(h, Box, Text, Input, Select, view, on),
778    ),
779  )
780}
781
hooks/lib/archive.js 29 lines
1export const LAUNCH_DATE = '2021-06-19' // the first NYT-era Wordle: no puzzle exists before this
2const DAY_MS = 86400000
3const DATE_RE = /^\d{4}-\d{2}-\d{2}$/
4
5export const boardKey = date => `board:${date}`
6
7const toMs = date => Date.parse(`${date}T00:00:00Z`)
8const fromMs = ms => new Date(ms).toISOString().slice(0, 10)
9
10export const addDays = (date, n) => fromMs(toMs(date) + n * DAY_MS)
11
12/** `today` and the `count - 1` days before it, newest first. */
13export const recentDates = (today, count = 14) => Array.from({ length: count }, (_, i) => addDays(today, -i))
14
15/**
16 * Whether `input` names a puzzle the archive can play: a real YYYY-MM-DD,
17 * from launch through today. Returns { ok: true, date } or { ok: false, reason }.
18 */
19export const checkArchiveDate = (input, today) => {
20  const date = String(input ?? '').trim()
21  if (!DATE_RE.test(date) || Number.isNaN(toMs(date)) || fromMs(toMs(date)) !== date) {
22    return { ok: false, reason: 'Enter a date as YYYY-MM-DD' }
23  }
24  if (date > today) return { ok: false, reason: 'That puzzle is in the future' }
25  if (date < LAUNCH_DATE) return { ok: false, reason: `No puzzles before ${LAUNCH_DATE}` }
26
27  return { ok: true, date }
28}
29
hooks/lib/arcade.js 114 lines
1import { addDays } from './archive.js'
2import { MAX_GUESSES } from './game-engine.js'
3
4// Raw hex, not theme keys: the arcade look is one fixed palette ("Claude night"),
5// drawn the same whatever the person's theme. See docs/ui-ref/wordle-ui-final.png.
6export const PALETTE = {
7  background: '#171513',
8  panel: '#1f1c19',
9  walls: '#d97757',
10  title: '#e8875f',
11  subtitle: '#e58fc4',
12  text: '#f0e8dc',
13  dim: '#6e655b',
14  correct: '#5fb87a',
15  present: '#f0b44c',
16  miss: '#2e2a26',
17  active: '#4a4038', // the row being typed: lighter than a miss, so the two never read as one tile
18  accent: '#d97757',
19  pellet: '#e8a07c',
20  keyIdle: '#2e2a26',
21  cardKey: '#34302b', // the picker's PICK A DATE card
22  divider: '#3a3430',
23  ready: '#f0b44c',
24  lives: '#e8875f',
25  streak: '#e58fc4',
26  best: '#7cc4e8',
27  winPercent: '#f0b44c',
28  stage: '#e8875f',
29}
30
31// A 5×7 bitmap per title letter, '#' lit. Packed two pixel rows per text row
32// into ▀ ▄ █, so the title is 4 rows tall. (Stage 08's big title; the opening splash draws it now.)
33const FONT = {
34  W: ['#...#', '#...#', '#...#', '#.#.#', '#.#.#', '##.##', '#...#'],
35  O: ['#####', '#...#', '#...#', '#...#', '#...#', '#...#', '#####'],
36  R: ['####.', '#...#', '#...#', '####.', '#.#..', '#..#.', '#...#'],
37  D: ['####.', '#...#', '#...#', '#...#', '#...#', '#...#', '####.'],
38  L: ['#....', '#....', '#....', '#....', '#....', '#....', '#####'],
39  E: ['#####', '#....', '#....', '####.', '#....', '#....', '#####'],
40}
41
42const HALF = { '00': ' ', '10': '▀', '01': '▄', '11': '█' }
43
44/** `word` in the block font: 4 strings, one per text row, letters one column apart. */
45export const blockTitle = (word = 'WORDLE') => {
46  const glyphs = [...word].map(ch => FONT[ch])
47  const lit = (glyph, y, x) => (glyph[y]?.[x] === '#' ? '1' : '0')
48
49  return Array.from({ length: 4 }, (_, row) =>
50    glyphs
51      .map(glyph => Array.from({ length: 5 }, (_, x) => HALF[lit(glyph, row * 2, x) + lit(glyph, row * 2 + 1, x)]).join(''))
52      .join(' '),
53  )
54}
55
56/** The score a game earns: 100 for every guess left unused on a win, 0 otherwise. */
57export const gameScore = game => (game?.status === 'won' ? (MAX_GUESSES - game.guesses.length) * 100 : 0)
58
59/**
60 * The best score in the stats: the score of the fewest-guess win the
61 * distribution records. Stats only count today's puzzles, so practice never sets it.
62 */
63export const hiScore = stats => {
64  const fewest = (stats?.distribution ?? []).findIndex(n => n > 0)
65
66  return fewest < 0 ? 0 : (MAX_GUESSES - (fewest + 1)) * 100
67}
68
69export const pad = (n, width) => String(Math.max(0, n)).padStart(width, '0')
70
71const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
72
73/** '2026-09-27' → '27 SEP'. */
74export const stageLabel = date => `${date.slice(8, 10)} ${MONTHS[Number(date.slice(5, 7)) - 1]}`
75
76export const STAGE_DAYS = 14
77
78/**
79 * Where ◀ (dir -1) or ▶ (dir +1) goes from `date`, or null when there is
80 * nowhere to go: the steps cover today and the 13 days before it. A date
81 * typed from further back steps forward into that window.
82 */
83export const stepStage = (date, today, dir) => {
84  const oldest = addDays(today, -(STAGE_DAYS - 1))
85  if (dir < 0) return date > oldest ? addDays(date, -1) : null
86  if (date >= today) return null
87
88  return date < oldest ? oldest : addDays(date, 1)
89}
90
91/** ◆ for every guess left, ◇ for every guess used. */
92export const livesText = game => {
93  const used = game.guesses.length
94
95  return [...'◆'.repeat(MAX_GUESSES - used), ...'◇'.repeat(used)].join(' ')
96}
97
98const SCORE_FILL = { green: PALETTE.correct, yellow: PALETTE.present, gray: PALETTE.miss }
99
100/** A scored tile: its fill, and a letter in the background color (dim on a miss). */
101export const tileLook = score => ({
102  fill: SCORE_FILL[score],
103  letter: score === 'gray' ? PALETTE.dim : PALETTE.background,
104})
105
106const KEY_FILL = { green: PALETTE.correct, yellow: PALETTE.present }
107
108/**
109 * How the on-screen key for a letter in `state` (keyStates) is drawn: a chip
110 * with this fill, or, once the letter is a known miss, no key at all
111 * (`{ isEaten: true }`, an eaten pellet).
112 */
113export const keyLook = state => (state === 'gray' ? { isEaten: true } : { fill: KEY_FILL[state] ?? PALETTE.keyIdle })
114
hooks/lib/splash.js 267 lines
1import { blockTitle, pad, PALETTE, stageLabel } from './arcade.js'
2
3// The opening splash, "Chomp & grade" (docs/ui-ref/wordle-splash-AB.png): an eater
4// chomps a row of pellets and leaves the WORDLE title behind it as scored tiles, a
5// green wave grades it solved, a white flash, then it settles terracotta with READY!.
6
7export const FRAME_MS = 100
8
9/** The picture's size when there is room; a bigger pane centres it, never stretches it. */
10export const BASE_COLUMNS = 78
11export const BASE_ROWS = 11
12/** Below this many columns the block title gives way to a plain `W O R D L E`. */
13export const BLOCK_MIN_COLUMNS = 41
14/** The narrowest the picture is drawn; a narrower pane clips it. */
15export const MIN_COLUMNS = 20
16
17// Raw hex where the palette has no entry, as fireworks.js does.
18export const MISS_COLOR = '#5a524a'
19export const FLASH_COLOR = '#fff4e6'
20/** Each title letter's score as the eater reveals it: W correct, O present, R correct, D miss, L present, E correct. */
21export const LETTER_COLORS = [PALETTE.correct, PALETTE.present, PALETTE.correct, MISS_COLOR, PALETTE.present, PALETTE.correct]
22
23const WORD = 'WORDLE'
24const LETTER_STEP = 6 // a 5-column glyph and the column after it
25const TITLE_WIDTH = WORD.length * LETTER_STEP - 1 // 35
26const PELLET_ROW = 1 // title row 2: the pellets run through the middle of the letters
27const PELLET_STEP = 3
28const EATER_FROM = -2 // two columns left of the title …
29const EATER_TO = TITLE_WIDTH + 2 // … to two past it
30const BLINK_FRAMES = 3 // READY! blinks every 300 ms
31const HUD_PAD = 2
32const CHECKS = Array(WORD.length).fill('✓').join(' ')
33const SKIP_HOTKEY = '1'
34const SKIP_LABEL = 'PRESS ANY KEY TO SKIP'
35const SKIP_SHORT = 'SKIP'
36
37/**
38 * Each version's timeline, in frames. The full one (from /wordle): chomp 0–24,
39 * the scored title alone at 25, the grade 26–29, the flash 30–31 (3.0–3.15 s,
40 * 3.15 s falling inside frame 31), the settle 32–39. Auto-open plays a 2 s cut:
41 * chomp at double speed, no grade or flash. Reduced motion holds the settled picture 1 s.
42 */
43const TIMELINES = {
44  full: { frames: 40, chompTo: 25, gradeFrom: 26, flashFrom: 30, settleFrom: 32, blinks: true },
45  short: { frames: 20, chompTo: 14, gradeFrom: null, flashFrom: null, settleFrom: 14, blinks: true },
46  reduced: { frames: 10, chompTo: 0, gradeFrom: null, flashFrom: null, settleFrom: 0, blinks: false },
47}
48
49/** Which version plays: reduced motion wins, then auto-open's short one. */
50export const splashVariant = (opts = {}) => (opts.reducedMotion ? 'reduced' : opts.isAutoOpen ? 'short' : 'full')
51
52/** How many 100 ms frames the version `opts` asks for lasts: 40, 20 or 10. */
53export const splashFrames = (opts = {}) => TIMELINES[splashVariant(opts)].frames
54
55/** What the picture is doing at `frame`: 'chomp', 'scored', 'grade', 'flash' or 'settle'. */
56export const splashPhase = (frame, opts = {}) => {
57  const t = TIMELINES[splashVariant(opts)]
58  if (frame < t.chompTo) return 'chomp'
59  if (frame >= t.settleFrom) return 'settle'
60  if (t.flashFrom != null && frame >= t.flashFrom) return 'flash'
61  if (t.gradeFrom != null && frame >= t.gradeFrom) return 'grade'
62
63  return 'scored'
64}
65
66/** The eater's column during the chomp, in title columns (0 = the W's first column): a steady pace. */
67export const eaterColumn = (frame, opts = {}) => {
68  const { chompTo } = TIMELINES[splashVariant(opts)]
69
70  return EATER_FROM + Math.round(((EATER_TO - EATER_FROM) * frame) / Math.max(1, chompTo - 1))
71}
72
73/** The letter (0–5) a title column belongs to, the gap after it counting as its own; -1 before the W. */
74const letterAt = column => (column < 0 ? -1 : Math.min(WORD.length - 1, Math.floor(column / LETTER_STEP)))
75
76/** The eater's color: the letter it is in, present before the first. */
77export const eaterColor = (frame, opts = {}) => {
78  const i = letterAt(eaterColumn(frame, opts))
79
80  return i < 0 ? PALETTE.present : LETTER_COLORS[i]
81}
82
83/** Letter `i`'s color at `frame` once it is revealed. */
84const letterColor = (i, frame, phase, timeline) => {
85  if (phase === 'settle') return PALETTE.title
86  if (phase === 'flash') return FLASH_COLOR
87  // the wave: letter i turns correct in turn over the grade's four frames
88  if (phase === 'grade' && frame >= timeline.gradeFrom + Math.floor((4 * i) / WORD.length)) return PALETTE.correct
89
90  return LETTER_COLORS[i]
91}
92
93/**
94 * Which rows the picture has in `rows` of room, top to bottom. Short of the base
95 * 11 (8 with the plain title) it drops the HUD, then the skip line, then the blank
96 * rows, then the border; the title and READY! always stay.
97 */
98const rowPlan = (rows, titleRows) => {
99  const plan = ['top', 'hud', 'gap-top', ...Array.from({ length: titleRows }, (_, i) => `title${i}`), 'gap-mid', 'ready', 'skip', 'bottom']
100  const least = titleRows + 1
101  const want = Math.max(least, rows ?? plan.length)
102  for (const drop of ['hud', 'skip', 'gap-top', 'gap-mid', 'border']) {
103    if (plan.length <= want) break
104    if (drop === 'border') plan.splice(0, plan.length, ...plan.filter(kind => kind !== 'top' && kind !== 'bottom'))
105    else plan.splice(plan.indexOf(drop), 1)
106  }
107
108  return plan
109}
110
111/** The picture's width and rows for a pane body of `screen` `{ columns, rows }`. */
112export const splashLayout = screen => {
113  const columns = Math.min(BASE_COLUMNS, Math.max(MIN_COLUMNS, screen?.columns ?? BASE_COLUMNS))
114  const isBlock = columns >= BLOCK_MIN_COLUMNS
115
116  return { columns, isBlock, plan: rowPlan(screen?.rows, isBlock ? 4 : 1) }
117}
118
119/** The skip line's text: the prefix, and the label of the Button that skips (drawn `1: label`). */
120const skipText = (frame, inner, opts) => {
121  if (splashPhase(frame, opts) !== 'settle') return { prefix: '', label: SKIP_SHORT }
122  const prefix = opts.isTodayDone ? 'PICK YOUR NEXT GAME · ' : 'DAILY PUZZLE · '
123  const button = `${SKIP_HOTKEY}: ${SKIP_LABEL}`
124  if (prefix.length + button.length <= inner - 2) return { prefix, label: SKIP_LABEL }
125
126  return { prefix: '', label: button.length <= inner - 2 ? SKIP_LABEL : SKIP_SHORT }
127}
128
129/**
130 * Where the skip Button goes on `splashRows`' picture at `frame`: its row, its
131 * first column and its label (it draws as `1: label`). Null when the pane is too
132 * short for the skip line.
133 */
134export const skipButton = (frame, screen, opts = {}) => {
135  const layout = splashLayout(screen)
136  const row = layout.plan.indexOf('skip')
137  if (row < 0) return null
138  const inner = layout.columns - 2
139  const { prefix, label } = skipText(frame, inner, opts)
140  const width = prefix.length + SKIP_HOTKEY.length + 2 + label.length
141
142  return { row, column: 1 + Math.floor((inner - width) / 2) + prefix.length, label, hotkey: SKIP_HOTKEY }
143}
144
145/**
146 * One frame of the opening splash as rows of runs, `{ text, color?, backgroundColor, bold? }`,
147 * every row exactly the picture's width (78 columns when there is room; see
148 * `splashLayout`). Every cell carries the background color, so the dark picture
149 * holds whatever the person's theme.
150 *
151 * Pure: the same arguments always draw the same picture. A frame past the end
152 * draws the last one.
153 *
154 * @param frame 0 … splashFrames(opts) - 1
155 * @param screen `{ columns, rows? }`, the pane body's room
156 * @param opts `{ hiScore, date: 'YYYY-MM-DD', isTodayDone, reducedMotion, isAutoOpen }`
157 */
158export const splashRows = (frame, screen, opts = {}) => {
159  const timeline = TIMELINES[splashVariant(opts)]
160  frame = Math.min(timeline.frames - 1, Math.max(0, frame))
161  const phase = splashPhase(frame, opts)
162  const { columns: W, isBlock, plan } = splashLayout(screen)
163  const inner = W - 2
164  const blank = () => Array.from({ length: W }, () => ({ ch: ' ' }))
165  const grid = plan.map(blank)
166  const put = (y, x, ch, color, bold) => {
167    if (y < 0 || x < 1 || x > inner) return // inside the walls only
168    grid[y][x] = { ch, color, bold }
169  }
170  const write = (y, x, text, color, bold) => [...text].forEach((ch, i) => put(y, x + i, ch, color, bold))
171  const rowOf = kind => plan.indexOf(kind)
172
173  // --- the double-line walls
174  const top = rowOf('top')
175  if (top >= 0) {
176    const bottom = rowOf('bottom')
177    grid[top] = [...`╔${'═'.repeat(inner)}╗`].map(ch => ({ ch, color: PALETTE.walls }))
178    grid[bottom] = [...`╚${'═'.repeat(inner)}╝`].map(ch => ({ ch, color: PALETTE.walls }))
179    for (let y = top + 1; y < bottom; y++) {
180      grid[y][0] = { ch: '║', color: PALETTE.walls }
181      grid[y][W - 1] = { ch: '║', color: PALETTE.walls }
182    }
183  }
184
185  // --- the HUD: 1UP left, HI-SCORE centred and dim, STAGE right; the centre then the right give way
186  const hud = rowOf('hud')
187  if (hud >= 0) {
188    const score = ['1UP', '00000']
189    const stage = ['STAGE', stageLabel(opts.date ?? '2026-01-01')]
190    const hi = `HI-SCORE ${pad(opts.hiScore ?? 0, 5)}`
191    const left = 1 + HUD_PAD
192    const leftEnd = left + score.join(' ').length
193    const right = 1 + inner - HUD_PAD - stage.join(' ').length
194    const hiAt = 1 + Math.floor((inner - hi.length) / 2)
195    const hasStage = right > leftEnd
196    write(hud, left, score[0], PALETTE.title, true)
197    write(hud, left + score[0].length + 1, score[1], PALETTE.text, true)
198    if (hasStage) {
199      write(hud, right, stage[0], PALETTE.title, true)
200      write(hud, right + stage[0].length + 1, stage[1], PALETTE.text, true)
201    }
202    if (hiAt > leftEnd && hiAt + hi.length < (hasStage ? right : 1 + inner - HUD_PAD)) write(hud, hiAt, hi, PALETTE.dim, true)
203  }
204
205  // --- the title
206  const titleTop = rowOf('title0')
207  if (isBlock) {
208    const glyphRows = blockTitle(WORD)
209    const left = 1 + Math.floor((inner - TITLE_WIDTH) / 2)
210    const eater = phase === 'chomp' ? eaterColumn(frame, opts) : null
211    glyphRows.forEach((glyphRow, r) => {
212      ;[...glyphRow].forEach((ch, x) => {
213        const isRevealed = eater == null || x < eater
214        if (ch !== ' ' && isRevealed) put(titleTop + r, left + x, ch, letterColor(letterAt(x), frame, phase, timeline))
215      })
216    })
217    if (eater != null) {
218      // the pellets still ahead of it, ● at both ends, up to two columns short of the right wall
219      const last = inner - HUD_PAD - left
220      const ends = [0, last - (last % PELLET_STEP)]
221      for (let x = 0; x <= ends[1]; x += PELLET_STEP) {
222        if (x >= eater + 2) put(titleTop + PELLET_ROW, left + x, ends.includes(x) ? '●' : '•', PALETTE.pellet)
223      }
224      // the eater: ▐ down all four title rows, █ beside the middle two
225      const color = eaterColor(frame, opts)
226      for (let r = 0; r < 4; r++) put(titleTop + r, left + eater, '▐', color)
227      for (const r of [1, 2]) put(titleTop + r, left + eater + 1, '█', color)
228    }
229  } else {
230    // too narrow for the block font: the letters appear left to right as the eater (unseen) passes them
231    const spaced = [...WORD].join(' ')
232    const left = 1 + Math.floor((inner - spaced.length) / 2)
233    const eater = phase === 'chomp' ? eaterColumn(frame, opts) : null
234    ;[...WORD].forEach((ch, i) => {
235      if (eater == null || eater > i * LETTER_STEP + 2) put(titleTop, left + i * 2, ch, letterColor(i, frame, phase, timeline), true)
236    })
237  }
238
239  // --- row 8: the grade's ticks, then READY! (blinking, steady with reduced motion)
240  const ready = rowOf('ready')
241  const centre = (y, text, color, bold) => write(y, 1 + Math.floor((inner - text.length) / 2), text, color, bold)
242  if (phase === 'grade') centre(ready, CHECKS, PALETTE.correct)
243  if (phase === 'settle') {
244    const isLit = !timeline.blinks || Math.floor((frame - timeline.settleFrom) / BLINK_FRAMES) % 2 === 0
245    if (isLit) centre(ready, 'READY!', PALETTE.present, true)
246  }
247
248  // --- row 9: the skip line (the Button is drawn over its `1: label`; see skipButton)
249  const skip = skipButton(frame, screen, opts)
250  if (skip) {
251    const { prefix } = skipText(frame, inner, opts)
252    write(skip.row, skip.column - prefix.length, prefix, PALETTE.dim)
253    write(skip.row, skip.column, `${skip.hotkey}: ${skip.label}`, PALETTE.dim)
254  }
255
256  return grid.map(row => {
257    const runs = []
258    for (const cell of row) {
259      const last = runs[runs.length - 1]
260      if (last && last.color === cell.color && last.bold === cell.bold) last.text += cell.ch
261      else runs.push({ text: cell.ch, color: cell.color, backgroundColor: PALETTE.background, bold: cell.bold })
262    }
263
264    return runs
265  })
266}
267
hooks/lib/picker.js 170 lines
1import { addDays, checkArchiveDate, LAUNCH_DATE } from './archive.js'
2import { stageLabel } from './arcade.js'
3
4export const PLAYED_KEY = 'played-today'
5
6export const ALL_PLAYED_MESSAGE = "You've played every game today!"
7
8// A fixed pick for RANDOM GAME, read from the store when set (a number in [0, 1)): the pane's
9// way in for a deterministic test or a repeatable manual check. Unset, picks are Math.random.
10export const RANDOM_KEY = 'config:random'
11
12const DAY_MS = 86400000
13const dayIndex = date => Math.round((Date.parse(`${date}T00:00:00Z`) - Date.parse(`${LAUNCH_DATE}T00:00:00Z`)) / DAY_MS)
14
15/** Whether `date` is a pool date: launch day through yesterday. Today is never in it. */
16export const isInPool = (date, today) => date >= LAUNCH_DATE && date < today
17
18/** How many dates the pool holds. */
19export const poolSize = today => dayIndex(today)
20
21const playedSet = (played, today) => new Set(played.filter(date => isInPool(date, today)))
22
23/** How many pool dates are left to play: the pool minus the ones finished today. */
24export const remaining = (today, played) => poolSize(today) - playedSet(played, today).size
25
26// ---- the played-today set: { day, dates }, nothing else ----
27
28/**
29 * The dates finished on `today`. A record from another day is empty, and is
30 * overwritten with an empty one for today.
31 */
32export const loadPlayed = async (io, today) => {
33  const saved = await io.store.get(PLAYED_KEY)
34  if (saved?.day === today && Array.isArray(saved.dates)) return [...saved.dates]
35  if (saved) await io.store.set(PLAYED_KEY, { day: today, dates: [] })
36
37  return []
38}
39
40/** Adds `date` to today's finished set (once) and returns the set. */
41export const markPlayed = async (io, today, date) => {
42  const dates = await loadPlayed(io, today)
43  if (!dates.includes(date)) dates.push(date)
44  await io.store.set(PLAYED_KEY, { day: today, dates })
45
46  return dates
47}
48
49export const clearPlayed = async (io, today) => {
50  await io.store.set(PLAYED_KEY, { day: today, dates: [] })
51}
52
53// ---- RANDOM GAME ----
54
55/**
56 * A uniform pick from the pool minus `played`, or null when nothing is left.
57 * `rng` returns a number in [0, 1): inject one to make the pick deterministic.
58 */
59export const randomDate = (today, played, rng = Math.random) => {
60  const left = remaining(today, played)
61  if (left <= 0) return null
62  const skip = playedSet(played, today)
63  let pick = Math.min(left - 1, Math.floor(rng() * left))
64  for (let i = 0; i < poolSize(today); i++) {
65    const date = addDays(LAUNCH_DATE, i)
66    if (skip.has(date)) continue
67    if (pick === 0) return date
68    pick -= 1
69  }
70
71  return null
72}
73
74// ---- the date stepper ----
75
76/** The newest pool date not played today, or null when every date is played. */
77export const newestUnplayed = (today, played) => {
78  const skip = playedSet(played, today)
79  for (let date = addDays(today, -1); isInPool(date, today); date = addDays(date, -1)) {
80    if (!skip.has(date)) return date
81  }
82
83  return null
84}
85
86/** The dropdown's dates: the `count` newest pool dates not played today, newest first. */
87export const recentUnplayed = (today, played, count = 14) => {
88  const skip = playedSet(played, today)
89  const dates = []
90  for (let date = addDays(today, -1); isInPool(date, today) && dates.length < count; date = addDays(date, -1)) {
91    if (!skip.has(date)) dates.push(date)
92  }
93
94  return dates
95}
96
97/**
98 * The date the stepper shows: `date` while it is still playable, else the newest
99 * unplayed date (yesterday when everything is played, so the stepper always shows a date).
100 */
101export const shownDate = (date, today, played) =>
102  date && isInPool(date, today) && !played.includes(date) ? date : (newestUnplayed(today, played) ?? addDays(today, -1))
103
104/** One step from `date` (dir -1 earlier, +1 later) over played dates, or null at either end. */
105export const stepPicker = (date, today, played, dir) => {
106  const skip = playedSet(played, today)
107  let next = addDays(date, dir)
108  while (isInPool(next, today) && skip.has(next)) next = addDays(next, dir)
109
110  return isInPool(next, today) ? next : null
111}
112
113/**
114 * The played dates the last step jumped over: the run of played dates right behind
115 * `date` on the side the step came from (a ◀ step, dir -1, came from the later side).
116 */
117export const skippedBehind = (date, today, played, dir) => {
118  const skip = playedSet(played, today)
119  const run = []
120  for (let d = addDays(date, -dir); isInPool(d, today) && skip.has(d); d = addDays(d, -dir)) run.push(d)
121
122  return run.sort()
123}
124
125/** `skips 06, 07 OCT · played today`; nothing skipped is ''. Many dates are counted instead of listed. */
126export const skippedLabel = dates => {
127  if (dates.length === 0) return ''
128  if (dates.length > 4) return `skips ${dates.length} dates · played today`
129  const groups = []
130  for (const date of dates) {
131    const [day, month] = stageLabel(date).split(' ')
132    const last = groups.at(-1)
133    if (last?.month === month) last.days.push(day)
134    else groups.push({ month, days: [day] })
135  }
136
137  return `skips ${groups.map(g => `${g.days.join(', ')} ${g.month}`).join(', ')} · played today`
138}
139
140// ---- the typed date ----
141
142/** Whether a typed date can be played from the picker: { ok: true, date } or { ok: false, reason }. */
143export const checkPickerDate = (input, today, played) => {
144  const check = checkArchiveDate(input, today)
145  if (!check.ok) return check
146  if (check.date === today) return { ok: false, reason: "Today's puzzle is the daily: open it from ↺ TODAY'S BOARD" }
147  if (played.includes(check.date)) return { ok: false, reason: `You already played ${check.date} today` }
148
149  return check
150}
151
152// ---- display ----
153
154/** 1903 → '1,903'. */
155export const formatCount = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
156
157/** 'DD MON YYYY' for the stepper. */
158export const longDate = date => `${stageLabel(date)} ${date.slice(0, 4)}`
159
160const two = n => String(n).padStart(2, '0')
161
162/** HH:MM:SS from `nowMs` to the next local midnight, when the next daily opens. */
163export const nextDailyIn = nowMs => {
164  const now = new Date(nowMs)
165  const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime()
166  const seconds = Math.max(0, Math.ceil((midnight - nowMs) / 1000))
167
168  return `${two(Math.floor(seconds / 3600))}:${two(Math.floor((seconds % 3600) / 60))}:${two(seconds % 60)}`
169}
170
hooks/lib/fireworks.js 184 lines
1export const FRAME_MS = 100
2export const TOTAL_FRAMES = 30 // 30 frames x 100 ms = 3 seconds
3
4// The smallest screen the picture is laid out for; a bigger pane just gets more gradient.
5export const MIN_COLUMNS = 36
6export const MIN_ROWS = 11
7
8const LINE1 = 'WORDDDD...'
9const LINE2 = 'you solved it!'
10
11// Timeline, in frames (one frame = 100 ms).
12const IRIS_FRAMES = 4 // the red opens out from the centre
13const RING_STARTS = [0, 1, 2] // three shockwaves, a frame apart
14const RING_LIFE = 8 // ~0.8 s from the centre to the edge, fading as they go
15const PARTICLE_LIFE = 14
16const LINE1_FROM = 2 // letters pop one per frame (~80-100 ms stagger)
17const LINE1_DONE = LINE1_FROM + LINE1.length // the shake starts here
18const SHAKE = [2, -2, 1, -1, 1, 0]
19const LINE2_FROM = LINE1_DONE + 1
20const SLIDE = 3 // rows line 2 rises through
21const RAY_COUNT = 12
22const RAY_TURN_FRAMES = 200 // one full turn of the sunburst every 20 s
23const FADE_FRAMES = 5 // reduced motion: the whole picture fades in, then holds
24
25// Raw hex, not theme keys: the scheme is the point here.
26const CENTER = [0xff, 0x2d, 0x2d]
27const EDGE = [0x2a, 0x00, 0x00]
28const RAY = [0xff, 0x6a, 0x3d]
29const GLOW = [0xff, 0x8a, 0x8a]
30const WHITE = [0xff, 0xf4, 0xe6]
31const GOLD = [0xff, 0xd3, 0x4d]
32const SPARK_COLORS = ['#ffd34d', '#ff3b3b', '#ffb000', '#ff6b6b', '#fff1a8']
33const SPARK_GLYPHS = ['✹', '✦', '✦', '*', '*', '·']
34const SHADES = 12 // the gradient is quantized so neighbouring cells share a run
35
36const mix = (a, b, t) => a.map((v, i) => Math.round(v + (b[i] - v) * Math.min(1, Math.max(0, t))))
37const hex = c => `#${c.map(v => v.toString(16).padStart(2, '0')).join('')}`
38const easeOut = t => 1 - (1 - Math.min(1, Math.max(0, t))) ** 3
39// a fixed pseudo-random in [0, 1): the same particle always flies the same way
40const noise = i => {
41  const x = Math.sin(i * 127.1 + 311.7) * 43758.5453
42
43  return x - Math.floor(x)
44}
45
46/**
47 * One frame of the win screen as `rows` rows of exactly `columns` cells, each
48 * row a list of runs: { text, color?, backgroundColor?, bold? }. Every cell
49 * inside the red carries its own background, so the backdrop is exactly the
50 * pane; cells the opening iris has not reached yet have none.
51 *
52 * Pure: the same arguments always draw the same picture. Past the last frame
53 * (or before the first) every cell is blank.
54 *
55 * @param frame 0 … TOTAL_FRAMES - 1
56 * @param screen `{ columns, rows }`
57 * @param reducedMotion skip the iris, rays' turn, rings, particles and shake; just fade in
58 */
59export const celebrationRows = (frame, screen, reducedMotion = false) => {
60  const W = Math.max(MIN_COLUMNS, screen.columns)
61  const H = Math.max(MIN_ROWS, screen.rows)
62  const cx = (W - 1) / 2
63  const cy = (H - 1) / 2
64  // terminal cells are about twice as tall as wide: halve x so circles look round
65  const dist = (x, y) => Math.hypot((x - cx) / 2, y - cy)
66  const maxD = dist(0, 0)
67  const isOn = frame >= 0 && frame < TOTAL_FRAMES
68  const fade = reducedMotion ? Math.min(1, (frame + 1) / FADE_FRAMES) : 1
69
70  // --- the backdrop: radial gradient, slowly turning sunburst, opening from the centre
71  const iris = reducedMotion ? Infinity : maxD * 1.05 * Math.max(0.15, easeOut(frame / IRIS_FRAMES))
72  const turn = reducedMotion ? 0 : (frame / RAY_TURN_FRAMES) * Math.PI * 2
73  const bgAt = (x, y) => {
74    const d = dist(x, y)
75    if (!isOn || d > iris) return undefined
76    const t = Math.round((d / maxD) ** 0.8 * SHADES) / SHADES
77    let c = mix(CENTER, EDGE, t)
78    const angle = Math.atan2(y - cy, (x - cx) / 2) - turn
79    if (Math.cos(angle * RAY_COUNT) > 0.55) c = mix(c, RAY, 0.35 * (1 - t))
80
81    return hex(reducedMotion ? mix(EDGE, c, fade) : c)
82  }
83  const cells = Array.from({ length: H }, (_, y) =>
84    Array.from({ length: W }, (_, x) => ({ ch: ' ', backgroundColor: bgAt(x, y) })),
85  )
86  const put = (x, y, ch, color, bold, backgroundColor) => {
87    x = Math.round(x)
88    y = Math.round(y)
89    if (x < 0 || x >= W || y < 0 || y >= H || !cells[y][x].backgroundColor) return
90    cells[y][x] = { ch, color, bold, backgroundColor: backgroundColor ?? cells[y][x].backgroundColor }
91  }
92
93  if (isOn) {
94    const shake = reducedMotion ? 0 : (SHAKE[frame - LINE1_DONE] ?? 0)
95    const ox = cx + shake
96    const line1Y = Math.round(cy) - 1
97    const line2Y = line1Y + 2
98
99    if (!reducedMotion) {
100      // --- shockwave rings: scale 0 -> 3 (the third of the way out reaches the corners), fading
101      RING_STARTS.forEach((start, k) => {
102        const age = frame - start
103        if (age < 0 || age >= RING_LIFE) return
104        const r = (3 * maxD * (age + 1)) / (3 * RING_LIFE)
105        const color = hex(mix([0xff, 0xd0, 0xc0], [0xa0, 0x10, 0x10], age / RING_LIFE))
106        const glyph = age < 3 ? '•' : '·'
107        const steps = Math.ceil(r * 8) + 8
108        for (let i = 0; i < steps; i++) {
109          const a = (i / steps) * Math.PI * 2 + k * 0.3
110          put(ox + Math.cos(a) * r * 2, cy + Math.sin(a) * r, glyph, color, age < 3)
111        }
112      })
113
114      // --- the red and gold particle burst, with a little gravity
115      for (let i = 0; i < 40; i++) {
116        const age = frame - (i % 3 === 0 ? 1 : 0)
117        if (age < 0 || age >= PARTICLE_LIFE) continue
118        const a = (i / 40) * Math.PI * 2 + noise(i) * 0.4
119        const speed = 0.9 + noise(i + 100) * 1.4
120        const x = ox + Math.cos(a) * speed * age * 2
121        const y = cy + Math.sin(a) * speed * age + 0.04 * age * age
122        const glyph = SPARK_GLYPHS[Math.min(SPARK_GLYPHS.length - 1, Math.floor((age / PARTICLE_LIFE) * SPARK_GLYPHS.length))]
123        put(x, y, glyph, SPARK_COLORS[i % SPARK_COLORS.length], age < 6)
124      }
125    }
126
127    // --- line 1: letters pop in one at a time, overshoot in gold, then settle white.
128    // Every extra D bounces higher and longer than the one before it.
129    const left1 = Math.round(ox - (LINE1.length - 1) / 2)
130    ;[...LINE1].forEach((ch, i) => {
131      if (reducedMotion) {
132        if (frame >= 1) put(left1 + i, line1Y, ch, hex(mix(EDGE, WHITE, fade)), true)
133
134        return
135      }
136      const age = frame - (LINE1_FROM + i)
137      if (age < 0) return
138      const extraD = i >= 4 && i <= 6 ? i - 3 : 0 // the 2nd, 3rd, 4th D: 1, 2, 3
139      const bounce = age === 0 ? 0 : age <= extraD ? Math.min(2, Math.ceil(extraD / 2)) : 0
140      if (age === 0) put(left1 + i, line1Y, ch, hex(EDGE), true, hex(GOLD)) // the overshoot: a gold flash
141      else put(left1 + i, line1Y - bounce, ch, hex(age <= 1 + extraD ? GOLD : WHITE), true)
142    })
143
144    // --- line 2: slides up into place and fades in, then glows in a slow pulse
145    const age2 = reducedMotion ? frame - 2 : frame - LINE2_FROM
146    if (age2 >= 0) {
147      const rise = reducedMotion ? 0 : Math.max(0, SLIDE - age2)
148      const y = line2Y + rise
149      const left2 = Math.round(ox - (LINE2.length - 1) / 2)
150      const shown = reducedMotion ? fade : Math.min(1, (age2 + 1) / (SLIDE + 1))
151      const settled = reducedMotion || rise === 0
152      const pulse = settled && !reducedMotion ? (Math.sin((age2 - SLIDE) * 0.9) + 1) / 2 : 0.5
153      // the glow: a soft lighter halo one cell around the words, breathing with the pulse
154      if (settled) {
155        for (let gx = left2 - 2; gx < left2 + LINE2.length + 2; gx++) {
156          for (const gy of [y - 1, y, y + 1]) {
157            const bg = cells[gy]?.[gx]?.backgroundColor
158            if (!bg || cells[gy][gx].ch !== ' ') continue
159            const base = [1, 3, 5].map(o => parseInt(bg.slice(o, o + 2), 16))
160            const strength = (gy === y ? 0.45 : 0.2) * (0.4 + 0.6 * pulse)
161            cells[gy][gx] = { ch: ' ', backgroundColor: hex(mix(base, GLOW, strength)) }
162          }
163        }
164      }
165      const color = hex(mix(EDGE, mix(WHITE, [0xff, 0xc4, 0xc4], pulse), shown))
166      ;[...LINE2].forEach((ch, i) => {
167        if (ch !== ' ') put(left2 + i, y, ch, color, true)
168      })
169    }
170  }
171
172  return cells.map(row => {
173    const runs = []
174    for (const cell of row) {
175      const last = runs[runs.length - 1]
176      const same = last && last.color === cell.color && last.bold === cell.bold && last.backgroundColor === cell.backgroundColor
177      if (same) last.text += cell.ch
178      else runs.push({ text: cell.ch, color: cell.color, bold: cell.bold, backgroundColor: cell.backgroundColor })
179    }
180
181    return runs
182  })
183}
184
hooks/lib/lifecycle.js 62 lines
1export const AUTO_OPEN_KEY = 'config:autoOpen'
2export const REDUCE_MOTION_KEY = 'config:reduceMotion'
3
4export const USAGE =
5  'Usage: /wordle   |   /wordle config auto-open on|off   |   /wordle config reduce-motion on|off   |   /wordle config reset-history [confirm]'
6
7// setting name -> the kinds its show / set commands parse to
8const SETTINGS = {
9  'auto-open': { show: 'show-auto-open', set: 'set-auto-open' },
10  'reduce-motion': { show: 'show-reduce-motion', set: 'set-reduce-motion' },
11}
12
13// What reset-history deletes: every saved game and every cached word. Stats and
14// settings are different keys and are kept (Clear stats is its own control).
15export const HISTORY_KEY_PREFIXES = ['board:', 'word:']
16
17/** The store keys that make up the played-games history. */
18export const historyKeys = keys => keys.filter(key => HISTORY_KEY_PREFIXES.some(prefix => key.startsWith(prefix)))
19
20/**
21 * Parses what follows `/wordle`:
22 *   ''                          -> { kind: 'open' }
23 *   'config auto-open on|off'   -> { kind: 'set-auto-open', value }
24 *   'config auto-open'          -> { kind: 'show-auto-open' }
25 *   'config reduce-motion on|off' / 'config reduce-motion' -> the same, for the win animation
26 *   'config reset-history'          -> { kind: 'reset-history-ask' }  (asks first)
27 *   'config reset-history confirm'  -> { kind: 'reset-history' }
28 * anything else                 -> { kind: 'usage' }
29 */
30export const parseWordleArgs = args => {
31  const words = String(args ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean)
32  if (words.length === 0) return { kind: 'open' }
33  if (words[0] === 'config' && words[1] === 'reset-history') {
34    if (words.length === 2) return { kind: 'reset-history-ask' }
35    if (words.length === 3 && words[2] === 'confirm') return { kind: 'reset-history' }
36
37    return { kind: 'usage' }
38  }
39  const setting = words[0] === 'config' && Object.hasOwn(SETTINGS, words[1]) ? SETTINGS[words[1]] : null
40  if (!setting) return { kind: 'usage' }
41  if (words.length === 2) return { kind: setting.show }
42  if (words.length === 3 && (words[2] === 'on' || words[2] === 'off')) {
43    return { kind: setting.set, value: words[2] === 'on' }
44  }
45
46  return { kind: 'usage' }
47}
48
49export const describeAutoOpen = isOn => `Wordle auto-open is ${isOn ? 'on' : 'off'}.`
50
51export const describeReduceMotion = isOn =>
52  `Wordle reduced motion is ${isOn ? 'on: the win screen just fades in' : 'off: the win screen plays in full'}.`
53
54export const describeResetAsk = count =>
55  count === 0
56    ? 'No saved games to clear.'
57    : `This deletes ${count} saved game${count === 1 ? '' : 's'} (and the cached words). Your stats and settings are kept. ` +
58      'Run /wordle config reset-history confirm to go ahead.'
59
60export const describeResetDone = count =>
61  `Cleared ${count} saved game${count === 1 ? '' : 's'} and the cached words. Stats and settings were kept; today's puzzle starts fresh.`
62
hooks/lib/game-engine.js 60 lines
1export const WORD_LENGTH = 5
2export const MAX_GUESSES = 6
3
4/**
5 * Scores `guess` against `answer`: an array of 'green' | 'yellow' | 'gray'.
6 * Greens claim their letters first; each remaining guess letter is yellow only
7 * while an unclaimed copy of it is left in the answer, so repeats never score
8 * more often than the answer holds them.
9 */
10export const scoreGuess = (guess, answer) => {
11  const g = guess.toLowerCase()
12  const a = answer.toLowerCase()
13  const result = Array(WORD_LENGTH).fill('gray')
14  const pool = {}
15
16  for (let i = 0; i < WORD_LENGTH; i++) {
17    if (g[i] === a[i]) result[i] = 'green'
18    else pool[a[i]] = (pool[a[i]] ?? 0) + 1
19  }
20  for (let i = 0; i < WORD_LENGTH; i++) {
21    if (result[i] === 'green' || !pool[g[i]]) continue
22    result[i] = 'yellow'
23    pool[g[i]]--
24  }
25
26  return result
27}
28
29/** A fresh game. Games are plain data; `submitGuess` returns new ones. */
30export const createGame = answer => ({
31  answer: answer.toLowerCase(),
32  guesses: [],
33  status: 'playing',
34})
35
36/**
37 * Plays `guess` into `game` without mutating it.
38 *
39 * `isValid` is a sync predicate for allowed guesses (the caller resolves the
40 * word list; this module does no I/O). Resolves to `{ ok: true, game }`, or
41 * `{ ok: false, reason }` with reason 'finished' | 'length' | 'invalid'; a
42 * rejected guess costs nothing.
43 */
44export const submitGuess = (game, guess, isValid) => {
45  if (game.status !== 'playing') return { ok: false, reason: 'finished' }
46  const word = String(guess).trim().toLowerCase()
47  if (!/^[a-z]+$/.test(word) || word.length !== WORD_LENGTH) return { ok: false, reason: 'length' }
48  if (!isValid(word)) return { ok: false, reason: 'invalid' }
49
50  const scored = { word, score: scoreGuess(word, game.answer) }
51  const guesses = [...game.guesses, scored]
52  const status = scored.score.every(s => s === 'green')
53    ? 'won'
54    : guesses.length >= MAX_GUESSES
55      ? 'lost'
56      : 'playing'
57
58  return { ok: true, game: { ...game, guesses, status } }
59}
60
hooks/lib/stats.js 45 lines
1export const STATS_KEY = 'stats'
2
3export const DEFAULT_STATS = {
4  currentStreak: 0,
5  maxStreak: 0,
6  wins: 0,
7  played: 0,
8  distribution: [0, 0, 0, 0, 0, 0],
9}
10
11/** The stats after one finished game: a pure update, never mutating `stats`. */
12export const applyCompletion = (stats, { won, guessCount }) => {
13  const distribution = [...stats.distribution]
14  if (won) distribution[guessCount - 1] = (distribution[guessCount - 1] ?? 0) + 1
15  const currentStreak = won ? stats.currentStreak + 1 : 0
16
17  return {
18    currentStreak,
19    maxStreak: Math.max(stats.maxStreak, currentStreak),
20    wins: stats.wins + (won ? 1 : 0),
21    played: stats.played + 1,
22    distribution,
23  }
24}
25
26export const winPercent = stats => (stats.played === 0 ? 0 : Math.round((stats.wins / stats.played) * 100))
27
28/** Stored stats, filled out with defaults so a partial or missing record is safe. */
29export const loadStats = async io => {
30  const saved = await io.store.get(STATS_KEY)
31
32  return { ...DEFAULT_STATS, ...(saved ?? {}), distribution: saved?.distribution ?? [...DEFAULT_STATS.distribution] }
33}
34
35/**
36 * Records one finished game of TODAY's puzzle and returns the new stats. The
37 * caller must not call this for an archived date: practice never counts.
38 */
39export const recordCompletion = async (io, result) => {
40  const next = applyCompletion(await loadStats(io), result)
41  await io.store.set(STATS_KEY, next)
42
43  return next
44}
45
hooks/lib/word-source.js 103 lines
1const LIVE_URL = date => `https://www.nytimes.com/svc/wordle/v2/${date}.json`
2const TIMEOUT_MS = 3000
3const DAY_MS = 86400000
4const DATE_RE = /^\d{4}-\d{2}-\d{2}$/
5const WORD_RE = /^[a-z]{5}$/
6
7// Loaded once per module load; a hot reload simply re-reads the files.
8let fallbackList
9let guessSet
10
11/**
12 * `io` is what the library needs from the engine, built in register.js:
13 * `{ store: { get, set }, fetch, sleep, readData }`. The engine's `$` can't be
14 * passed across an import, so the caller wraps the calls it needs.
15 */
16const readLines = async (io, file) => {
17  const text = await io.readData(file)
18
19  return text
20    .split('\n')
21    .map(line => line.trim().toLowerCase())
22    .filter(Boolean)
23}
24
25const loadFallback = async io => {
26  fallbackList ??= readLines(io, 'fallback-answers.txt').catch(error => {
27    fallbackList = undefined
28    throw error
29  })
30
31  return fallbackList
32}
33
34const loadGuesses = async io => {
35  guessSet ??= readLines(io, 'valid-guesses.txt')
36    .then(words => new Set(words))
37    .catch(error => {
38      guessSet = undefined
39      throw error
40    })
41
42  return guessSet
43}
44
45/** Whole days between 1970-01-01 and `dateStr` (YYYY-MM-DD), in UTC. */
46export const daysSinceEpoch = dateStr => Math.floor(Date.parse(`${dateStr}T00:00:00Z`) / DAY_MS)
47
48const fetchLive = async (io, dateStr) => {
49  const response = await Promise.race([
50    io.fetch(LIVE_URL(dateStr)),
51    io.sleep(TIMEOUT_MS).then(() => {
52      throw new Error('timeout')
53    }),
54  ])
55  if (!response.ok) throw new Error(`status ${response.status}`)
56  const solution = JSON.parse(response.text)?.solution
57  if (typeof solution !== 'string' || !WORD_RE.test(solution.toLowerCase())) {
58    throw new Error('missing solution')
59  }
60
61  return solution.toLowerCase()
62}
63
64/**
65 * The answer for `dateStr` (YYYY-MM-DD): a cached live word, else live from NYT,
66 * else a deterministic offline word (retried live next time). Never throws for a
67 * network or schema problem.
68 *
69 * @returns {Promise<{ solution: string, source: 'live' | 'fallback' }>}
70 */
71export const resolveWord = async (io, dateStr) => {
72  if (!DATE_RE.test(dateStr) || Number.isNaN(Date.parse(dateStr))) {
73    throw new Error(`resolveWord: expected YYYY-MM-DD, got ${dateStr}`)
74  }
75  const key = `word:${dateStr}`
76  const cached = await io.store.get(key)
77  // A live word is final. A cached fallback is only a stand-in, so every look at
78  // that date tries the live source again and upgrades the record if it answers.
79  if (cached?.source === 'live') return cached
80
81  try {
82    const result = { solution: await fetchLive(io, dateStr), source: 'live' }
83    await io.store.set(key, result)
84
85    return result
86  } catch {
87    if (cached) return cached
88    const list = await loadFallback(io)
89    const index = ((daysSinceEpoch(dateStr) % list.length) + list.length) % list.length
90    const result = { solution: list[index], source: 'fallback' }
91    await io.store.set(key, result)
92
93    return result
94  }
95}
96
97/** Whether `word` is an allowed guess (answers are included in the list). */
98export const isValidGuess = async (io, word) => {
99  const guesses = await loadGuesses(io)
100
101  return guesses.has(String(word).trim().toLowerCase())
102}
103
types/index.d.ts 82 lines
1export type WordleScore = 'green' | 'yellow' | 'gray'
2
3export type WordleGame = {
4  answer: string
5  guesses: { word: string; score: WordleScore[] }[]
6  status: 'playing' | 'won' | 'lost'
7}
8
9/** The active puzzle: its date, where the word came from, and whether it is today's. */
10export type WordlePuzzle = {
11  date: string
12  source: 'live' | 'fallback'
13  /** Only today's puzzle counts toward stats; any other date is practice. */
14  isToday: boolean
15}
16
17export type WordleStats = {
18  currentStreak: number
19  maxStreak: number
20  wins: number
21  played: number
22  /** distribution[n - 1] = wins that took n guesses. */
23  distribution: number[]
24}
25
26/** What the opening splash draws from (see hooks/lib/splash.js), read once as the pane opens. */
27export type WordleSplashOptions = {
28  /** Today, 'YYYY-MM-DD': the HUD's STAGE. */
29  date: string
30  hiScore: number
31  /** Today's puzzle is finished: row 9 reads PICK YOUR NEXT GAME, and the hand-off opens the picker. */
32  isTodayDone: boolean
33  /** The 1 s settled picture instead of the animation. */
34  reducedMotion: boolean
35  /** Opened by auto-open: the 2 s cut. */
36  isAutoOpen: boolean
37}
38
39declare module 'claude-code' {
40  interface PluginState {
41    'wordle-mod': {
42      /** The game in play; null until the word has loaded. */
43      game: WordleGame | null
44      /** Letters typed toward the next guess (0-5, lowercase). */
45      draft: string
46      puzzle: WordlePuzzle | null
47      /** Mirror of the persisted `stats` record, for the stats row and HI-SCORE. */
48      stats: WordleStats
49      /** Whether the stats details (played, distribution, Clear stats) are open under the stats row. */
50      isStatsOpen: boolean
51      /** The Clear stats control has been pressed once and awaits a second press. */
52      isConfirmingClear: boolean
53      /** Whether the typed-date field (behind DATE…) is shown. */
54      isDateEntryOpen: boolean
55      /** True for a moment while the Guess field is drawn empty so it will take the draft again. */
56      isFieldBlanked: boolean
57      /** Frame of the win celebration; -1 when no animation is running. */
58      celebrationFrame: number
59      /** The running celebration plays its reduced-motion version (a plain fade). */
60      isMotionReduced: boolean
61      /** The height made the last draw stack (board over controls), not the width; read back for the switch-back gap. Session only. */
62      isStacked: boolean
63      /** The body rows the pane had when it opened (null until its first draw); it stacks only once the room grows past them. Session only. */
64      openRows: number | null
65      /** Which screen the pane shows: the game board, or the Pick a game screen. */
66      mode: 'game' | 'picker'
67      /** The date the picker's stepper was moved to (null: the newest date not played today). */
68      pickerDate: string | null
69      /** Which way the stepper last moved (-1 earlier, +1 later), for the "skips …" caption. */
70      pickerDir: -1 | 1
71      /** Mirror of the persisted `played-today` record: the dates whose game ended on `day`. */
72      playedToday: { day: string | null; dates: string[] }
73      /** Today's saved board once it is finished (the picker's header and 1UP); null otherwise. */
74      todayGame: WordleGame | null
75      /** The clock at the picker's last once-a-second tick; redraws the countdown. */
76      tick: number
77      /** The opening splash while it plays (`frame` counts 100 ms frames from the open); null otherwise. Session only. */
78      splash: { id: number; frame: number; opts: WordleSplashOptions } | null
79    }
80  }
81}
82