From b2f8e879abe88ef4267db880a8c523592fbcf51d Mon Sep 17 00:00:00 2001 From: Aidan Dona Date: Tue, 13 Oct 2026 16:44:07 -0500 Subject: [PATCH] Add puzzle hints and per-word descriptions with sources Hint is revealed on demand below the board while playing. After the game ends, each word's description and source link are listed below the puzzle, and hovering a solved word highlights its entry. Co-Authored-By: Claude Opus 5.5 --- build.md | 6 ++++-- lib.js | 23 ++++++++++++++++++++--- public/admin.js | 17 +++++++++++++---- public/play.js | 45 +++++++++++++++++++++++++++++++++++++++++---- public/style.css | 43 ++++++++++++++++++++++++++++++++++++++++--- server.js | 12 +++++++----- test.js | 16 ++++++++++++++++ 7 files changed, 141 insertions(+), 21 deletions(-) diff --git a/build.md b/build.md index 26b32e5..1dc34ee 100644 --- a/build.md +++ b/build.md @@ -19,6 +19,8 @@ - **"One away..."** message when a guess has 3 of 4 from one group. - Repeat guesses are not counted as mistakes. - **Share results:** copy an emoji grid (🟨🟩🟦🟪 per guess) to clipboard. +- **Hint:** optional per-puzzle hint; a "Show hint" button below the board reveals it while playing. +- **About the words:** after the game ends, each word's description and source link are listed below the puzzle. Hovering a word in a solved row highlights its description. ## Pages - `/` — Puzzle of the day: the game whose assigned date is today; if none, the most recent past-dated game. @@ -27,11 +29,11 @@ - `/admin` — login, then create / edit / delete games. ## Editor (admin page) -- Fields: title, date (optional, unique), 4 groups × (name, color, 4 words). +- Fields: title, date (optional, unique), hint (optional), 4 groups × (name, color, 4 words, each with optional description and source URL). - Validation: exactly 16 words, no duplicates (case-insensitive), every field filled, each color used once. ## Data model -- `games(id, title, date UNIQUE NULL, groups_json, created_at, updated_at)` +- `games(id, title, date UNIQUE NULL, hint, groups_json, created_at, updated_at)`; each group in `groups_json` has `details: [{ description, source }]` parallel to `words`. - Answers are never sent to the browser before solved: the client posts guesses to `/api/games/:id/guess` and the server returns correct / one-away / wrong. ## Out of scope (for now) diff --git a/lib.js b/lib.js index 9bd5e31..8069c4a 100644 --- a/lib.js +++ b/lib.js @@ -9,7 +9,11 @@ function isRealDate(s) { return !isNaN(d) && d.toISOString().slice(0, 10) === s; } -// Returns { errors: [...] } or { game: { title, date, groups } } with cleaned values. +function isHttpUrl(s) { + try { return ['http:', 'https:'].includes(new URL(s).protocol); } catch { return false; } +} + +// Returns { errors: [...] } or { game: { title, date, hint, groups } } with cleaned values. function validateGame(input) { const errors = []; const title = String(input?.title ?? '').trim(); @@ -19,6 +23,9 @@ function validateGame(input) { let date = input?.date ? String(input.date).trim() : null; if (date && !isRealDate(date)) errors.push('Date must be a real date (YYYY-MM-DD).'); + const hint = String(input?.hint ?? '').trim(); + if (hint.length > 200) errors.push('Hint must be 200 characters or fewer.'); + const rawGroups = Array.isArray(input?.groups) ? input.groups : []; if (rawGroups.length !== 4) errors.push('A game needs exactly 4 groups.'); @@ -40,10 +47,20 @@ function validateGame(input) { if (w && seen.has(w)) errors.push(`"${w}" appears more than once.`); seen.add(w); } - return { name, color, words }; + // Optional per-word description and source link, shown after the puzzle ends. + const rawDetails = Array.isArray(g?.details) ? g.details : []; + const details = words.map((w, j) => { + const description = String(rawDetails[j]?.description ?? '').trim(); + const source = String(rawDetails[j]?.source ?? '').trim(); + if (description.length > 500) errors.push(`Description for "${w}" must be 500 characters or fewer.`); + if (source.length > 500) errors.push(`Source for "${w}" must be 500 characters or fewer.`); + else if (source && !isHttpUrl(source)) errors.push(`Source for "${w}" must be a full http(s) link.`); + return { description, source }; + }); + return { name, color, words, details }; }); - return errors.length ? { errors: [...new Set(errors)] } : { game: { title, date, groups } }; + return errors.length ? { errors: [...new Set(errors)] } : { game: { title, date, hint, groups } }; } // Returns { result: 'correct', group } | { result: 'one-away' } | { result: 'wrong' } | { error } diff --git a/public/admin.js b/public/admin.js index df776ca..bcb8a2a 100644 --- a/public/admin.js +++ b/public/admin.js @@ -49,11 +49,12 @@ function showLogin(error) { } function showEditor(game) { - const g = game || { title: '', date: '', groups: COLORS.map((color) => ({ name: '', color, words: ['', '', '', ''] })) }; + const g = game || { title: '', date: '', hint: '', groups: COLORS.map((color) => ({ name: '', color, words: ['', '', '', ''] })) }; const field = (id, label, input, help) => el('div', { class: 'field' }, el('label', { for: id }, label), input, help ? el('p', { class: 'help' }, help) : null); const title = el('input', { id: 'title', value: g.title, maxlength: 100, required: true }); const date = el('input', { id: 'date', type: 'date', value: g.date || '' }); + const hint = el('input', { id: 'hint', value: g.hint || '', maxlength: 200 }); const errBox = el('div'); const groupEls = g.groups.map((grp, i) => { @@ -61,14 +62,21 @@ function showEditor(game) { const name = el('input', { id: `g${n}-name`, value: grp.name, maxlength: 80, required: true }); const color = el('select', { id: `g${n}-color` }, COLORS.map((c) => el('option', { value: c, selected: c === grp.color }, c[0].toUpperCase() + c.slice(1)))); const words = grp.words.map((w, j) => el('input', { value: w, maxlength: 30, required: true, 'aria-label': `Group ${n} word ${j + 1}` })); + const descs = grp.words.map((_, j) => el('input', { value: grp.details?.[j]?.description || '', maxlength: 500, placeholder: 'Description (optional)', 'aria-label': `Group ${n} word ${j + 1} description` })); + const sources = grp.words.map((_, j) => el('input', { type: 'url', value: grp.details?.[j]?.source || '', maxlength: 500, placeholder: 'https://source (optional)', 'aria-label': `Group ${n} word ${j + 1} source link` })); const box = el('fieldset', { class: 'group-edit' }, el('legend', { class: 'sr' }, `Group ${n}`), el('div', { class: 'head' }, field(`g${n}-name`, el('span', {}, el('span', { class: `swatch ${grp.color}` }), `Group ${n} name`), name), field(`g${n}-color`, 'Color', color)), - el('label', {}, 'Words'), el('div', { class: 'words' }, words)); + el('label', {}, 'Words'), + el('p', { class: 'help', style: 'margin-bottom:8px' }, 'Descriptions and sources show below the puzzle once it ends.'), + el('div', { class: 'words' }, words.map((w, j) => el('div', { class: 'word-row' }, w, descs[j], sources[j])))); color.addEventListener('change', () => { box.querySelector('.swatch').className = `swatch ${color.value}`; }); - return { box, read: () => ({ name: name.value, color: color.value, words: words.map((w) => w.value) }) }; + return { box, read: () => ({ + name: name.value, color: color.value, words: words.map((w) => w.value), + details: words.map((_, j) => ({ description: descs[j].value, source: sources[j].value })), + }) }; }); $app.replaceChildren( @@ -78,7 +86,7 @@ function showEditor(game) { el('form', { novalidate: true, onsubmit: async (e) => { e.preventDefault(); const btn = e.submitter; btn.disabled = true; - const body = { title: title.value, date: date.value || null, groups: groupEls.map((x) => x.read()) }; + const body = { title: title.value, date: date.value || null, hint: hint.value, groups: groupEls.map((x) => x.read()) }; const { ok, data } = await api(game ? `/api/admin/games/${game.id}` : '/api/admin/games', { method: game ? 'PUT' : 'POST', body }); btn.disabled = false; if (ok) { toast('Saved'); return showList(); } @@ -89,6 +97,7 @@ function showEditor(game) { errBox, field('title', 'Title', title), field('date', 'Date', date, 'Optional. The puzzle becomes the daily puzzle on this date.'), + field('hint', 'Hint', hint, 'Optional. Players can reveal it below the puzzle while playing.'), groupEls.map((x) => x.box), el('div', { class: 'actions', style: 'justify-content:flex-start' }, el('button', { class: 'btn primary', type: 'submit' }, icon('check'), 'Save puzzle'))), ); diff --git a/public/play.js b/public/play.js index cf67214..4019e35 100644 --- a/public/play.js +++ b/public/play.js @@ -6,7 +6,9 @@ const $game = document.getElementById('game'); const idMatch = location.pathname.match(/^\/play\/(\d+)/); if (!idMatch) document.getElementById('nav-today').setAttribute('aria-current', 'page'); -const state = { game: null, words: [], selected: new Set(), solved: [], mistakes: 0, guesses: [], tried: new Set(), done: false, won: false }; +const state = { game: null, words: [], selected: new Set(), solved: [], mistakes: 0, guesses: [], tried: new Set(), done: false, won: false, showHint: false }; + +const icon = (name) => el('i', { class: `ph-bold ph-${name}`, 'aria-hidden': 'true' }); async function load() { const { ok, data } = await api(idMatch ? `/api/games/${idMatch[1]}` : '/api/daily'); @@ -26,7 +28,8 @@ async function load() { function render() { const board = el('div', { class: 'board' }, - state.solved.map((g) => el('div', { class: `solved ${g.color}` }, el('strong', {}, g.name), el('span', {}, g.words.join(', ')))), + state.solved.map((g) => el('div', { class: `solved ${g.color}` }, el('strong', {}, g.name), + el('span', {}, g.words.flatMap((w, i) => [i ? ', ' : '', el('span', { class: 'word', 'data-word': w }, w)])))), state.words.length ? el('div', { class: 'row4' }, state.words.map((w) => el('button', { class: 'tile', 'aria-pressed': String(state.selected.has(w)), disabled: state.done, onclick: () => toggle(w) }, w))) : null, ); @@ -34,15 +37,22 @@ function render() { if (state.done) { kids.push(resultPanel()); + const details = detailsPanel(); + if (details) kids.push(details); } else { kids.push( el('div', { class: 'mistakes', 'aria-label': `${MAX_MISTAKES - state.mistakes} mistakes remaining` }, 'Mistakes remaining:', [...Array(MAX_MISTAKES)].map((_, i) => el('i', { class: i < state.mistakes ? 'used' : '' }))), el('div', { class: 'actions' }, - el('button', { class: 'btn', onclick: shuffleWords }, el('i', { class: 'ph-bold ph-shuffle', 'aria-hidden': 'true' }), 'Shuffle'), + el('button', { class: 'btn', onclick: shuffleWords }, icon('shuffle'), 'Shuffle'), el('button', { class: 'btn', disabled: !state.selected.size, onclick: () => { state.selected.clear(); render(); } }, 'Deselect all'), el('button', { class: 'btn primary', disabled: state.selected.size !== 4, onclick: submit }, 'Submit')), ); + if (state.game.hint) { + kids.push(state.showHint + ? el('p', { class: 'hint' }, icon('lightbulb'), el('span', {}, el('strong', {}, 'Hint: '), state.game.hint)) + : el('div', { class: 'hint-toggle' }, el('button', { class: 'btn', onclick: () => { state.showHint = true; render(); } }, icon('lightbulb'), 'Show hint'))); + } } // Re-rendering replaces the buttons, so put keyboard focus back on the same one. const focused = $game.contains(document.activeElement) ? document.activeElement.textContent : null; @@ -122,10 +132,37 @@ function resultPanel() { el('p', { class: 'sub' }, state.won ? `Finished with ${state.mistakes} mistake${state.mistakes === 1 ? '' : 's'}.` : 'Here are the groups.'), el('pre', { 'aria-label': 'Your guesses' }, grid), el('div', { class: 'actions' }, - el('button', { class: 'btn primary', onclick: () => share(text) }, el('i', { class: 'ph-bold ph-copy', 'aria-hidden': 'true' }), 'Share results'), + el('button', { class: 'btn primary', onclick: () => share(text) }, icon('copy'), 'Share results'), el('a', { class: 'btn', href: '/puzzles' }, 'More puzzles'))); } +function detailsPanel() { + const hasAny = state.solved.some((g) => g.details?.some((d) => d.description || d.source)); + if (!hasAny) return null; + const host = (url) => { try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return 'Source'; } }; + return el('section', { class: 'details', 'aria-labelledby': 'details-h' }, + el('h2', { id: 'details-h' }, 'About the words'), + state.solved.map((g) => el('div', { class: 'detail-group' }, + el('h3', {}, el('span', { class: `swatch ${g.color}` }), g.name), + el('dl', {}, g.words.map((w, i) => { + const d = g.details?.[i] || {}; + return el('div', { class: 'detail', 'data-word': w }, + el('dt', {}, w), + el('dd', {}, d.description || null, + d.source ? el('a', { class: 'source', href: d.source, target: '_blank', rel: 'noopener noreferrer' }, icon('arrow-square-out'), host(d.source)) : null)); + }))))); +} + +// After the game ends, hovering a word in a solved row highlights its description. +function highlight(e, on) { + const word = state.done && e.target.closest?.('.solved .word'); + if (!word) return; + word.classList.toggle('hl', on); + $game.querySelector(`.detail[data-word="${CSS.escape(word.dataset.word)}"]`)?.classList.toggle('hl', on); +} +$game.addEventListener('mouseover', (e) => highlight(e, true)); +$game.addEventListener('mouseout', (e) => highlight(e, false)); + async function share(text) { try { await navigator.clipboard.writeText(text); diff --git a/public/style.css b/public/style.css index f2d8129..ee49bb5 100644 --- a/public/style.css +++ b/public/style.css @@ -164,6 +164,41 @@ h1 { font-size: clamp(1.6rem, 4vw, 2.1rem); letter-spacing: -0.03em; line-height .result h2 { margin: 0 0 4px; letter-spacing: -0.02em; } .result pre { font-family: inherit; font-size: 1.4rem; line-height: 1.25; margin: 12px 0 20px; } +/* Hint (while playing) */ +.hint-toggle { display: flex; justify-content: center; margin-top: 16px; } +.hint { + display: flex; + gap: 10px; + align-items: flex-start; + margin: 16px 0 0; + padding: 12px 16px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + animation: pop 0.3s var(--ease); +} +.hint i { margin-top: 4px; } + +/* Word descriptions (after the game ends) */ +.solved .word { border-radius: 4px; padding: 0 2px; transition: background 0.15s; } +.solved .word.hl { background: rgb(0 0 0 / 0.14); } +.details { margin-top: 32px; animation: pop 0.4s var(--ease); } +.details h2 { margin: 0 0 12px; letter-spacing: -0.02em; } +.detail-group { margin-bottom: 20px; } +.detail-group h3 { font-size: 1rem; margin: 0 0 8px; text-transform: uppercase; letter-spacing: 0.02em; } +.detail-group dl { display: grid; gap: 6px; margin: 0; } +.detail { + padding: 10px 14px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + transition: border-color 0.15s, background 0.15s; +} +.detail.hl { border-color: var(--ink); background: var(--tile); } +.detail dt { font-weight: 700; text-transform: uppercase; } +.detail dd { margin: 0; color: var(--muted); display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; } +.detail .source { display: inline-flex; gap: 4px; align-items: center; color: var(--ink); font-weight: 600; font-size: 0.9rem; } + /* Lists and forms */ .list { display: grid; gap: 10px; padding: 0; margin: 0; list-style: none; } .list a, .list .item { @@ -198,15 +233,17 @@ input, select { input:focus, select:focus { border-color: var(--ink); outline: none; } .group-edit { min-width: 0; padding: 16px; border-radius: var(--radius); margin-bottom: 14px; border: 1px solid var(--line); background: var(--surface); } .group-edit .head { display: grid; grid-template-columns: 1fr 140px; gap: 10px; margin-bottom: 10px; } -.group-edit .words { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; } -.group-edit .swatch { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 6px; vertical-align: middle; } +.group-edit .words { display: grid; gap: 8px; } +.group-edit .word-row { display: grid; grid-template-columns: 150px 1fr 1fr; gap: 8px; } +.swatch { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 6px; vertical-align: middle; } .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } .errors { color: var(--error); margin: 0 0 16px; padding-left: 20px; } .row-actions { display: flex; gap: 8px; } .icon-btn { padding: 8px 12px; } @media (max-width: 767px) { - .group-edit .head, .group-edit .words { grid-template-columns: 1fr 1fr; } + .group-edit .head { grid-template-columns: 1fr 1fr; } + .group-edit .word-row { grid-template-columns: 1fr; padding-bottom: 8px; border-bottom: 1px solid var(--line); } .topbar nav { gap: 14px; } } diff --git a/server.js b/server.js index 2775090..7dea051 100644 --- a/server.js +++ b/server.js @@ -23,10 +23,12 @@ db.exec(`CREATE TABLE IF NOT EXISTS games ( created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) )`); +// Added after launch; existing databases get the column on first start. +if (!db.prepare('PRAGMA table_info(games)').all().some((c) => c.name === 'hint')) db.exec('ALTER TABLE games ADD COLUMN hint TEXT'); // Server's local date decides "today"; set TZ on the VPS to the timezone you want. const today = () => new Date().toLocaleDateString('en-CA'); -const toGame = (row) => row && { id: row.id, title: row.title, date: row.date, groups: JSON.parse(row.groups_json) }; +const toGame = (row) => row && { id: row.id, title: row.title, date: row.date, hint: row.hint || '', groups: JSON.parse(row.groups_json) }; // A game is public once its date has arrived (undated games are always public). const getPublic = (id) => @@ -58,7 +60,7 @@ app.get('/puzzles', page('puzzles.html')); app.get('/admin', page('admin.html')); // ---- Player API (never sends group membership until solved or revealed) ---- -const publicView = (g) => ({ id: g.id, title: g.title, date: g.date, words: shuffle(g.groups.flatMap((x) => x.words)) }); +const publicView = (g) => ({ id: g.id, title: g.title, date: g.date, hint: g.hint, words: shuffle(g.groups.flatMap((x) => x.words)) }); app.get('/api/games', (req, res) => { const rows = db @@ -116,10 +118,10 @@ function save(req, res, id) { const { errors, game } = validateGame(req.body); if (errors) return res.status(400).json({ errors }); try { - const args = [game.title, game.date, JSON.stringify(game.groups)]; + const args = [game.title, game.date, game.hint || null, JSON.stringify(game.groups)]; const r = id - ? db.prepare("UPDATE games SET title = ?, date = ?, groups_json = ?, updated_at = datetime('now') WHERE id = ?").run(...args, id) - : db.prepare('INSERT INTO games (title, date, groups_json) VALUES (?, ?, ?)').run(...args); + ? db.prepare("UPDATE games SET title = ?, date = ?, hint = ?, groups_json = ?, updated_at = datetime('now') WHERE id = ?").run(...args, id) + : db.prepare('INSERT INTO games (title, date, hint, groups_json) VALUES (?, ?, ?, ?)').run(...args); if (id && r.changes === 0) return res.status(404).json({ errors: ['Puzzle not found.'] }); res.json({ id: id || Number(r.lastInsertRowid) }); } catch (e) { diff --git a/test.js b/test.js index 27013ae..fb641bf 100644 --- a/test.js +++ b/test.js @@ -45,3 +45,19 @@ test('checkGuess: correct, one away, wrong, invalid', () => { assert.ok(checkGuess(groups, ['bass', 'bass', 'pike', 'carp']).error); assert.ok(checkGuess(groups, 'nope').error); }); + +test('hint and per-word details are validated', () => { + const g = good(); + g.hint = ' Think water '; + g.groups[0].details = [{ description: 'A fish', source: 'https://example.com/bass' }]; + const { game } = validateGame(g); + assert.equal(game.hint, 'Think water'); + assert.deepEqual(game.groups[0].details[0], { description: 'A fish', source: 'https://example.com/bass' }); + assert.deepEqual(game.groups[0].details[1], { description: '', source: '' }); + + g.groups[0].details = [{ source: 'javascript:alert(1)' }]; + g.hint = 'x'.repeat(201); + const { errors } = validateGame(g); + assert.ok(errors.some((e) => e.includes('http(s) link'))); + assert.ok(errors.some((e) => e.includes('Hint'))); +});