web: backlog page paints glyphs and numbers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-11 11:55:30 +01:00
parent f74e70221f
commit 9f52d27893
17 changed files with 342 additions and 175 deletions

View File

@ -22,7 +22,7 @@ describe('<runner-dialog> locked', () => {
const lock = must(document.querySelector('.notice-warning'))
expect(lock).toHaveAttribute('aria-label', 'Locked: Manual pick active')
expect(lock).toHaveTextContent('🔒')
expect(field(/N$/)).toBeDisabled()
expect(field('N')).toBeDisabled()
expect(document.querySelector('.phrase')).toBeNull()
expect(run).toBeDisabled()
submit(run)

View File

@ -121,7 +121,7 @@ describe('FilterPanel', () => {
it('shows each slider value, the hours cap as off or N h', () => {
const { el, panel } = setup()
expect(getByText(el, '4 h/day')).toBeInTheDocument()
expect(getByText(el, 'off')).toBeInTheDocument()
expect(getByText(el, '∞')).toBeInTheDocument()
panel.sync(makeFilters({ maxHoursPerGame: 50 }))
expect(getByText(el, '50 h')).toBeInTheDocument()
})

View File

@ -1,27 +1,32 @@
// The planner's estimate filters (was FilterPanel.tsx). Built once; `sync()`
// writes values, active segments and conditional rows in place, so a slider
// being dragged or a date being typed never loses focus.
// Textgate: every label is a glyph (glyphs.ts) with its words spoken only;
// slider values (numbers + units) stay painted.
import { h } from '../../lib/dom'
import { SELECTABLE_TIERS } from '../../protondb'
import type { EstimateBasis, Filters, PlaytimeMode, ProtonMode, WebDefaults } from '../../types'
import { glyph } from '../../ui/build'
import { ANY_GLYPH, BASIS_GLYPH, TIER_GLYPH } from './glyphs'
type Update = (patch: Partial<Filters>) => void
interface Seg<T> { id: T; label: string; icon: string }
const BASES: readonly { id: EstimateBasis; label: string }[] = [
{ id: 'rush', label: 'Rush' },
{ id: 'leisure', label: 'Leisure' },
{ id: 'worst', label: 'Worst' },
{ id: 'pace', label: 'Pace' },
const BASES: readonly Seg<EstimateBasis>[] = [
{ id: 'rush', label: 'Rush', icon: BASIS_GLYPH.rush },
{ id: 'leisure', label: 'Leisure', icon: BASIS_GLYPH.leisure },
{ id: 'worst', label: 'Worst', icon: BASIS_GLYPH.worst },
{ id: 'pace', label: 'Pace', icon: BASIS_GLYPH.pace },
]
const PROTON: readonly { id: ProtonMode; label: string }[] = [
{ id: 'playable', label: 'Playable (CLI rule)' },
{ id: 'minTier', label: 'Min tier' },
const PROTON: readonly Seg<ProtonMode>[] = [
{ id: 'playable', label: 'Playable (CLI rule)', icon: '⌨️' },
{ id: 'minTier', label: 'Min tier', icon: '🥇≥' },
]
const PLAYTIME: readonly { id: PlaytimeMode; label: string }[] = [
{ id: 'all', label: 'All' },
{ id: 'started', label: 'Started' },
{ id: 'untouched', label: 'Untouched' },
const PLAYTIME: readonly Seg<PlaytimeMode>[] = [
{ id: 'all', label: 'All', icon: ANY_GLYPH },
{ id: 'started', label: 'Started', icon: '▶️' },
{ id: 'untouched', label: 'Untouched', icon: '∅' },
]
type NumberKey = 'dailyHours' | 'minCountComp' | 'minComp100' | 'minConfidenceSum' | 'maxHoursPerGame' | 'fallbackHours'
@ -33,12 +38,14 @@ interface Slider {
show: (f: Filters) => string
}
const hint = (text: string) => h('p', { class: 'hint sr-only' }, text)
export class FilterPanel {
readonly el: HTMLElement
private readonly syncs: ((f: Filters) => void)[] = []
constructor(defaults: WebDefaults, update: Update, onReset: () => void) {
const slider = (key: NumberKey, label: string, min: number, max: number, step: number, show: Slider['show']) => {
const slider = (key: NumberKey, icon: string, label: string, min: number, max: number, step: number, show: Slider['show']) => {
const val = h('span', { class: 'val' })
const input = h('input', { type: 'range', min, max, step, 'aria-label': label })
input.addEventListener('input', () => {
@ -50,18 +57,22 @@ export class FilterPanel {
input.value = String(f[key])
val.textContent = show(f)
})
return { label: h('label', {}, `${label} `, val), input }
return { label: h('label', {}, glyph(icon, label), ' ', val), input }
}
const segmented = <T extends string>(items: readonly { id: T; label: string }[], current: (f: Filters) => T, set: (id: T) => void) => {
const segmented = <T extends string>(items: readonly Seg<T>[], current: (f: Filters) => T, set: (id: T) => void) => {
const buttons = items.map((it) =>
h('button', { type: 'button', class: 'seg', onclick: () => { set(it.id) } }, it.label),
h('button', { type: 'button', class: 'seg', 'aria-label': it.label, onclick: () => { set(it.id) } }, it.icon),
)
this.syncs.push((f) => {
buttons.forEach((b, i) => b.classList.toggle('active', items[i]?.id === current(f)))
buttons.forEach((b, i) => {
const on = items[i]?.id === current(f)
b.classList.toggle('active', on)
b.setAttribute('aria-pressed', String(on))
})
})
return h('div', { class: 'segmented' }, buttons)
}
const check = (label: string, read: (f: Filters) => boolean, set: (on: boolean) => void) => {
const check = (icon: string, label: string, read: (f: Filters) => boolean, set: (on: boolean) => void) => {
const input = h('input', { type: 'checkbox' })
input.addEventListener('change', () => {
set(input.checked)
@ -69,7 +80,7 @@ export class FilterPanel {
this.syncs.push((f) => {
input.checked = read(f)
})
return h('label', { class: 'check' }, input, label)
return h('label', { class: 'check' }, input, glyph(icon, label))
}
const shownWhen = <E extends HTMLElement>(el: E, when: (f: Filters) => boolean): E => {
this.syncs.push((f) => {
@ -77,17 +88,22 @@ export class FilterPanel {
})
return el
}
const heading = (icon: string, label: string) => h('label', {}, glyph(icon, label))
const daily = slider('dailyHours', 'Daily play time', 0.5, 16, 0.5, (f) => `${f.dailyHours} h/day`)
const minComp = slider('minCountComp', 'Min HLTB completions', 0, 100, 1, (f) => String(f.minCountComp))
const min100 = slider('minComp100', 'Min polled completionist times', 0, 50, 1, (f) => String(f.minComp100))
const minConf = slider('minConfidenceSum', 'Min confidence sum', 0, 150, 1, (f) => String(f.minConfidenceSum))
const maxH = slider('maxHoursPerGame', 'Max time per game', 0, 200, 5, (f) =>
f.maxHoursPerGame > 0 ? `${f.maxHoursPerGame} h` : 'off',
const daily = slider('dailyHours', '⏰', 'Daily play time', 0.5, 16, 0.5, (f) => `${f.dailyHours} h/day`)
const minComp = slider('minCountComp', '#', 'Min HLTB completions', 0, 100, 1, (f) => String(f.minCountComp))
const min100 = slider('minComp100', '💯', 'Min polled completionist times', 0, 50, 1, (f) => String(f.minComp100))
const minConf = slider('minConfidenceSum', 'Σ', 'Min confidence sum', 0, 150, 1, (f) => String(f.minConfidenceSum))
const maxH = slider('maxHoursPerGame', '⏳', 'Max time per game', 0, 200, 5, (f) =>
f.maxHoursPerGame > 0 ? `${f.maxHoursPerGame} h` : '∞',
)
const fallback = slider('fallbackHours', 'Fallback estimate', 1, 100, 1, (f) => `${f.fallbackHours} h`)
const fallback = slider('fallbackHours', '❓', 'Fallback estimate', 1, 100, 1, (f) => `${f.fallbackHours} h`)
const tier = h('select', { 'aria-label': 'Minimum ProtonDB tier' }, SELECTABLE_TIERS.map((t) => h('option', { value: t }, t)))
const tier = h(
'select',
{ 'aria-label': 'Minimum ProtonDB tier' },
SELECTABLE_TIERS.map((t) => h('option', { value: t, 'aria-label': t }, TIER_GLYPH[t])),
)
tier.addEventListener('change', () => {
update({ protonMinTier: tier.value })
})
@ -103,7 +119,7 @@ export class FilterPanel {
date.value = f.targetDate
})
const clear = shownWhen(
h('button', { type: 'button', class: 'ghost', onclick: () => { update({ targetDate: '' }) } }, 'Clear'),
h('button', { type: 'button', class: 'ghost', 'aria-label': 'Clear', onclick: () => { update({ targetDate: '' }) } }, '✕'),
(f) => f.targetDate !== '',
)
@ -113,66 +129,47 @@ export class FilterPanel {
h(
'div',
{ class: 'panel-head' },
h('h2', {}, 'Filters'),
h('button', { type: 'button', class: 'ghost', onclick: () => { onReset() } }, 'Reset to CLI defaults'),
),
h(
'section',
{ class: 'field' },
h('label', {}, 'Estimate basis'),
segmented(BASES, (f) => f.basis, (basis) => { update({ basis }) }),
h('h2', {}, glyph('🎚️', 'Filters')),
h('button', { type: 'button', class: 'ghost', 'aria-label': 'Reset to CLI defaults', onclick: () => { onReset() } }, '↺ ⌨️'),
),
h('section', { class: 'field' }, heading('📐', 'Estimate basis'), segmented(BASES, (f) => f.basis, (basis) => { update({ basis }) })),
h('section', { class: 'field' }, daily.label, daily.input),
h(
'section',
{ class: 'field' },
minComp.label,
minComp.input,
h('p', { class: 'hint' }, `Higher = more reliable HLTB times (CLI default ${defaults.min_count_comp}).`),
),
h(
'details',
{ class: 'field' },
h('summary', {}, 'Advanced confidence'),
min100.label,
min100.input,
minConf.label,
minConf.input,
hint(`Higher = more reliable HLTB times (CLI default ${defaults.min_count_comp}).`),
),
h('details', { class: 'field' }, h('summary', {}, glyph('🔬', 'Advanced confidence')), min100.label, min100.input, minConf.label, minConf.input),
h(
'section',
{ class: 'field' },
h('label', {}, 'ProtonDB compatibility'),
heading('🐧', 'ProtonDB compatibility'),
segmented(PROTON, (f) => f.protonMode, (protonMode) => { update({ protonMode }) }),
shownWhen(
h(
'div',
{ class: 'subfield' },
tier,
check('Keep games with no ProtonDB data', (f) => f.protonTreatMissingAsPass, (on) => {
check('❓', 'Keep games with no ProtonDB data', (f) => f.protonTreatMissingAsPass, (on) => {
update({ protonTreatMissingAsPass: on })
}),
),
(f) => f.protonMode === 'minTier',
),
),
h('section', { class: 'field' }, maxH.label, maxH.input, hint('Hide games longer than this (0 = no cap).')),
h(
'section',
{ class: 'field' },
maxH.label,
maxH.input,
h('p', { class: 'hint' }, 'Hide games longer than this (0 = no cap).'),
),
h(
'section',
{ class: 'field' },
h('label', {}, 'Playtime'),
heading('⏱', 'Playtime'),
segmented(PLAYTIME, (f) => f.playtimeMode, (playtimeMode) => { update({ playtimeMode }) }),
),
h(
'section',
{ class: 'field' },
check('Include games with no HLTB data', (f) => f.includeNoData, (on) => {
check('❓', 'Include games with no HLTB data', (f) => f.includeNoData, (on) => {
update({ includeNoData: on })
}),
shownWhen(h('div', { class: 'subfield' }, fallback.label, fallback.input), (f) => f.includeNoData),
@ -180,9 +177,9 @@ export class FilterPanel {
h(
'section',
{ class: 'field' },
h('label', {}, 'Target finish date'),
heading('🏁', 'Target finish date'),
h('div', { class: 'subfield row' }, date, clear),
h('p', { class: 'hint' }, 'Pick a date to see the hours/day required.'),
hint('Pick a date to see the hours/day required.'),
),
)
}

View File

@ -11,7 +11,8 @@ describe('<game-table> loading', () => {
it('shows loading until the dataset arrives', () => {
stubApi({ 'GET /api/dataset': () => new Promise(() => undefined) })
mount('<game-table></game-table>')
expect(screen.getByText(/Loading your backlog/i)).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('Loading backlog')
expect(document.querySelector('game-table .spinner')).not.toBeNull()
})
it('renders the planner once data loads', async () => {
@ -24,7 +25,7 @@ describe('<game-table> loading', () => {
stubApi({ 'GET /api/dataset': apiError(500, 'boom') })
mount('<game-table></game-table>')
await flush()
expect(screen.getByText('Could not load data: API returned 500 Error')).toBeInTheDocument()
expect(screen.getByRole('alert')).toHaveAttribute('data-code')
expect(screen.getByText('./run.sh serve')).toBeInTheDocument()
})

View File

@ -6,10 +6,9 @@
import { q } from '../../api/queries'
import { h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { commandLine, errorNotice, loading } from '../../ui/build'
import { Planner } from './planner'
const message = (e: unknown) => (e instanceof Error ? e.message : String(e))
export class GameTableElement extends LiveElement {
private planner: Planner | null = null
@ -24,15 +23,10 @@ export class GameTableElement extends LiveElement {
const { data, error } = q.dataset.state
if (!data) {
this.planner = null
// Textgate: ⛔ + the server's own message + the recovery command; the
// explanation is spoken only (errorNotice).
this.replaceChildren(
error
? h(
'div',
{ class: 'status' },
h('p', { class: 'error' }, `Could not load data: ${message(error)}`),
h('p', { class: 'hint' }, 'Is the backend running? Start it with ', h('code', {}, './run.sh serve'), '.'),
)
: h('div', { class: 'status' }, h('p', { class: 'hint' }, 'Loading your backlog…')),
h('div', { class: 'status' }, error ? errorNotice(error, commandLine('./run.sh serve')) : loading('backlog')),
)
return
}

View File

@ -0,0 +1,57 @@
// Backlog pictograms (textgate: these are painted, the words are spoken only).
// One glyph per idea across the stats card, the planner filters, the summary
// cards and the table headers, so a glyph learned in one place reads the same
// everywhere.
import type { EstimateBasis } from '../../types'
import { glyph } from '../../ui/build'
export const BASIS_GLYPH: Record<EstimateBasis, string> = {
rush: '🐇',
leisure: '🐢',
worst: '🐌',
pace: '👤',
}
/** Player style vs HLTB; the `--<style>` class adds the colour channel. */
export const STYLE_GLYPH: Record<string, string> = {
faster_than_rush: '⚡',
rush_to_leisure: '🐇↔🐢',
slower_than_leisure: '🐌',
unknown: '❔',
}
export const STYLE_SPOKEN: Record<string, string> = {
faster_than_rush: 'Faster than HLTB rush',
rush_to_leisure: 'Between rush and leisure',
slower_than_leisure: 'Slower than HLTB leisure',
unknown: 'Not enough finished games yet',
}
/** A player style: its glyph painted (the class adds colour), its sentence spoken. */
export const styleGlyph = (style: string) =>
glyph(STYLE_GLYPH[style] ?? '❔', STYLE_SPOKEN[style] ?? style, `player-insight-style player-insight-style--${style}`)
/** ProtonDB tiers, best to worst: medals, then a crash and an hourglass. */
export const TIER_GLYPH: Record<string, string> = {
native: '⭐',
platinum: '💎',
gold: '🥇',
silver: '🥈',
bronze: '🥉',
borked: '💥',
pending: '⏳',
}
const tierGlyph = (tier: string) => TIER_GLYPH[tier] ?? '❔'
/** A tierLabel() string (`gold`, `gold / silver`, `—`) as glyphs. */
export function tierGlyphs(label: string): string {
if (!label || label === '—') return '—'
return label.split(' / ').map(tierGlyph).join('/')
}
export const KEEP_GLYPH: Record<string, string> = { kept: '📌', excluded: '🚫' }
/** "Any value" in a filter select or segmented control. */
export const ANY_GLYPH = '✱'

View File

@ -0,0 +1,9 @@
// Test helper: the text an element paints, i.e. its textContent without the
// spoken-only (.sr-only) words, whitespace collapsed.
export function painted(el: Element | null | undefined): string {
if (!el) return ''
const copy = el.cloneNode(true) as Element
for (const s of copy.querySelectorAll('.sr-only')) s.remove()
return copy.textContent.replace(/\s+/g, ' ').trim()
}

View File

@ -3,6 +3,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import { q } from '../../api/queries'
import { makeDataset, makeGame, makeState } from '../../test/factories'
import { big, GAMES, hash, header, names, panel, show, table } from '../../test/plannerHelpers'
import { painted } from './painted.testutil'
afterEach(() => {
history.replaceState(null, '', '/')
@ -13,21 +14,21 @@ describe('<game-table> planner', () => {
await show(GAMES, {
state: makeState({ current_game_name: 'Hollow Knight', games_done_since_start: 3, enforcement_started_at: '2026-03-04T00:00:00+00:00' }),
})
expect(document.querySelector('.app-head .sub')?.textContent).toBe(
'Currently playing Hollow Knight · 3 games finished since 2026-03-04 · 3 candidates',
)
const sub = document.querySelector('.app-head .sub')
expect(painted(sub)).toBe('▶️ Hollow Knight · 🏆 3 · 📅 2026-03-04 · 🎮 3')
expect(sub).toHaveTextContent(/Currently playing/)
})
it('dashes a missing start date', async () => {
await show()
expect(document.querySelector('.app-head .sub')?.textContent).toBe('0 games finished since — · 3 candidates')
expect(painted(document.querySelector('.app-head .sub'))).toBe('🏆 0 · 📅 — · 🎮 3')
})
it('recomputes scope when basis changes and a game is excluded', async () => {
const { user } = await show(GAMES.slice(0, 2), { state: makeState({ pace_games_per_day: 0.9 }) })
expect(big()).toBe('2')
await user.click(panel().getByRole('button', { name: 'Rush' }))
expect(document.querySelector('.card.active .card-title')?.textContent).toBe('Rush')
expect(document.querySelector('.card.active')).toHaveAttribute('data-basis', 'rush')
expect(hash().get('basis')).toBe('rush')
const box = within(table()).getAllByRole('checkbox')[0]
@ -68,7 +69,7 @@ describe('<game-table> planner', () => {
q.dataset.set(makeDataset([...GAMES, makeGame({ app_id: 4, name: 'Delta', protondb_tier: 'native', protondb_trending_tier: '' })]))
expect(screen.getByRole('searchbox', { name: 'Filter Game' })).toHaveValue('a')
expect(names()).toContain('Delta')
expect(document.querySelector('.app-head .sub')?.textContent).toMatch(/4 candidates/)
expect(painted(document.querySelector('.app-head .sub'))).toMatch(/🎮 4$/)
const proton = screen.getByRole('combobox', { name: 'Filter ProtonDB' })
expect([...(proton as HTMLSelectElement).options].map((o) => o.value)).toEqual(['', 'gold', 'gold / platinum', 'native', 'platinum'])
})

View File

@ -13,6 +13,7 @@ import { timelineChart } from '../../lib/charts/timeline'
import { h } from '../../lib/dom'
import { buildIndex, type Searchable } from '../../library/fuzzy'
import type { Filters, WebDataset } from '../../types'
import { glyph } from '../../ui/build'
import { FilterPanel } from './filterPanel'
import { defaultFilters, readFilters, writeFilters } from './plannerFilters'
import { PlannerTable } from './plannerTable'
@ -59,7 +60,8 @@ export class Planner {
this.panel = new FilterPanel(data.defaults, (patch) => { this.patch(patch) }, () => { this.reset() })
const content = h('div', { class: 'content' }, this.summary, this.chart, this.view.el)
this.nodes = [
h('header', { class: 'app-head' }, h('div', {}, h('h1', {}, 'Backlog Completion Planner'), this.sub)),
// Textgate: the heading is spoken only; the page's rail icon names it.
h('header', { class: 'app-head' }, h('div', {}, h('h1', { class: 'sr-only' }, 'Backlog Completion Planner'), this.sub)),
h('div', { class: 'layout' }, this.panel.el, content),
]
this.restore()
@ -110,8 +112,13 @@ export class Planner {
private syncSub(): void {
const s = this.data.state
this.sub.replaceChildren(
...(s.current_game_name ? ['Currently playing ', h('strong', {}, s.current_game_name), ' · '] : []),
`${s.games_done_since_start} games finished since ${s.enforcement_started_at.slice(0, 10) || '—'} · ${this.data.games.length} candidates`,
...(s.current_game_name ? [glyph('▶️', 'Currently playing '), ' ', h('strong', {}, s.current_game_name), ' · '] : []),
glyph('🏆', 'games finished'),
` ${s.games_done_since_start} · `,
glyph('📅', 'since'),
` ${s.enforcement_started_at.slice(0, 10) || '—'} · `,
glyph('🎮', 'candidates'),
` ${this.data.games.length}`,
)
}

View File

@ -89,7 +89,7 @@ describe('<game-table> table', () => {
expect(names()).toEqual(['Beta'])
await user.click(within(table()).getAllByRole('checkbox')[0])
await user.selectOptions(proton, '')
await user.selectOptions(screen.getByRole('combobox', { name: 'Filter Keep' }), 'Excluded')
await user.selectOptions(screen.getByRole('combobox', { name: 'Filter Keep' }), 'excluded')
expect(names()).toEqual(['Beta'])
expect(hash().get('f.keep')).toBe('excluded')
})
@ -104,7 +104,8 @@ describe('<game-table> table', () => {
it('formats each cell like the CLI list', async () => {
await show(GAMES.slice(0, 1))
const cells = [...table().querySelectorAll('tbody td')].map((td) => td.textContent)
expect(cells.slice(0, 8)).toEqual(['Alpha', '10', '1.0 h', '5.0', '30.0', '40.0', '20', 'gold'])
expect(cells.slice(0, 8)).toEqual(['Alpha', '10', '1.0 h', '5.0', '30.0', '40.0', '20', '🥇'])
expect(table().querySelector('td.proton')).toHaveAttribute('aria-label', 'gold')
})
it('shows a no-data badge for games without HLTB times when they are included', async () => {

View File

@ -8,6 +8,8 @@ import { fmtHoursPrecise, fmtPlaytime } from '../../format'
import { h } from '../../lib/dom'
import { tierLabel } from '../../protondb'
import type { WebGame } from '../../types'
import { glyph } from '../../ui/build'
import { ANY_GLYPH, KEEP_GLYPH, tierGlyphs } from './glyphs'
import { COLUMNS, optionsFor, type Column, type ColumnKey, type TableState } from './tableState'
export const DISPLAY_CAP = 300
@ -34,7 +36,15 @@ export function hltbUrl(game: WebGame): string {
return `https://howlongtobeat.com/?q=${encodeURIComponent(game.name)}`
}
const optionLabel = (c: Column, v: string) => (c.key === 'keep' ? (v === 'kept' ? 'Kept' : 'Excluded') : v)
// Textgate: select options paint glyphs; the value (kept/excluded, a
// tierLabel string) is what the hash stores and what the option speaks.
const optionLabel = (c: Column, v: string) => {
if (c.key === 'keep') return KEEP_GLYPH[v] ?? v
if (c.key === 'proton') return tierGlyphs(v)
return v
}
const option = (c: Column, v: string) =>
h('option', { value: v, 'aria-label': v || 'All' }, v ? optionLabel(c, v) : ANY_GLYPH)
// Textgate: column headers are pictograms; the column name is the button's
// aria-label (spoken only), the sort arrow stays visible.
@ -106,7 +116,7 @@ export class PlannerTable {
return h('td', { class: 'range-filter' }, h('div', {}, bound('min'), bound('max')))
}
if (c.filter === 'select') {
const select = h('select', { 'aria-label': `Filter ${c.label}` }, h('option', { value: '' }, 'All'))
const select = h('select', { 'aria-label': `Filter ${c.label}` }, option(c, ''))
this.selects.push([c, select])
return h('td', {}, field(c.key, select))
}
@ -153,7 +163,7 @@ export class PlannerTable {
keep.addEventListener('change', () => { this.opts.onToggle(id) })
const link = h('a', { target: '_blank', rel: 'noreferrer' })
const name = h('td', { class: 'name' }, link)
row = { tr: h('tr', {}, name, cells, h('td', { class: 'num' }, keep)), name, link, badge: h('span', { class: 'badge' }, 'no data'), cells, keep }
row = { tr: h('tr', {}, name, cells, h('td', { class: 'num' }, keep)), name, link, badge: glyph('❓', 'no data', 'badge'), cells, keep }
this.rows.set(id, row)
}
const g = r.game
@ -162,16 +172,19 @@ export class PlannerTable {
row.link.textContent = g.name
if (r.noData) row.name.append(row.badge)
else row.badge.remove()
const tier = tierLabel(g.protondb_tier, g.protondb_trending_tier)
const texts = [
g.completion_pct.toFixed(0),
fmtPlaytime(g.playtime_minutes),
// fmtPlaytime says "untouched" for 0; the table paints the number.
g.playtime_minutes > 0 ? fmtPlaytime(g.playtime_minutes) : '0 h',
fmtHoursPrecise(r.rush),
fmtHoursPrecise(r.leisure),
fmtHoursPrecise(r.worst),
String(g.count_comp),
tierLabel(g.protondb_tier, g.protondb_trending_tier),
tierGlyphs(tier),
]
texts.forEach((text, i) => { row.cells[i].textContent = text })
row.cells[6].setAttribute('aria-label', tier)
row.keep.checked = !r.excluded
row.keep.setAttribute('aria-label', r.excluded ? 'Re-include' : 'Exclude')
return row.tr
@ -183,7 +196,7 @@ export class PlannerTable {
const want = ['', ...optionsFor(c, all, current)]
const have = [...select.options].map((o) => o.value)
if (want.join('\n') !== have.join('\n')) {
select.replaceChildren(...want.map((v) => h('option', { value: v }, v ? optionLabel(c, v) : 'All')))
select.replaceChildren(...want.map((v) => option(c, v)))
}
select.value = current
}

View File

@ -11,7 +11,8 @@ async function show(reply: unknown) {
mount('<backlog-stats></backlog-stats>')
await flush()
}
const fact = (label: string) => screen.getByText(label, { selector: 'dt' }).nextElementSibling
// A fact's label is spoken only (sr-only inside the dt's glyph).
const fact = (label: string) => screen.getByText(label, { selector: 'dt .sr-only' }).closest('dt')?.nextElementSibling
describe('<backlog-stats>', () => {
it('shows the estimates for the default filters', async () => {
@ -35,7 +36,8 @@ describe('<backlog-stats>', () => {
it('dashes a ratio the server could not compute', async () => {
await show(stats(makePaceVsHltb({ player_style: 'unknown', ratio_vs_rush: -1, ratio_vs_leisure: -1 })))
expect(screen.getByText('Not enough finished games yet')).toBeInTheDocument()
expect(screen.getByText('Not enough finished games yet')).toHaveClass('sr-only')
expect(fact('Your pace')?.querySelector('.player-insight-style--unknown')).not.toBeNull()
expect(fact('vs rush')).toHaveTextContent('—')
expect(fact('vs leisure')).toHaveTextContent('—')
})

View File

@ -1,22 +1,17 @@
// <backlog-stats>: the CLI's `stats` estimate for the default filters (was
// screens/Backlog.tsx StatsCard).
// screens/Backlog.tsx StatsCard). Textgate: labels are glyphs, words spoken only.
import { q } from '../../api/queries'
import { fmtHours } from '../../format'
import { h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { card, errorNotice, facts, loading } from '../../ui/build'
const STYLE: Record<string, string> = {
faster_than_rush: 'Faster than HLTB rush',
rush_to_leisure: 'Between rush and leisure',
slower_than_leisure: 'Slower than HLTB leisure',
unknown: 'Not enough finished games yet',
}
import { card, errorNotice, facts, glyph, loading } from '../../ui/build'
import { BASIS_GLYPH, styleGlyph } from './glyphs'
const ICON = '📊'
const ratio = (r: number) => (r < 0 ? '—' : `${r.toFixed(2)}×`)
const stat = (num: string | number, label: string) =>
h('div', { class: 'stat' }, h('span', { class: 'stat-num' }, num), h('span', { class: 'stat-label' }, label))
const stat = (num: string | number, icon: string, label: string) =>
h('div', { class: 'stat' }, h('span', { class: 'stat-num' }, num), glyph(icon, label, 'stat-label'))
export class BacklogStatsElement extends LiveElement {
protected override setup(): void {
@ -26,34 +21,38 @@ export class BacklogStatsElement extends LiveElement {
protected update(): void {
const { data, error } = q.stats.state
if (error) {
this.replaceChildren(card('Estimates', errorNotice(error)))
this.replaceChildren(card('Estimates', errorNotice(error), { icon: ICON }))
return
}
if (!data) {
this.replaceChildren(card('Estimates', loading('stats')))
this.replaceChildren(card('Estimates', loading('stats'), { icon: ICON }))
return
}
const s = data.default_summary
const p = data.pace_vs_hltb
this.replaceChildren(
card('Estimates (default filters)', [
h(
'div',
{ class: 'stat-row' },
stat(s.qualifying, 'qualifying games'),
stat(fmtHours(s.rush_total), 'rush'),
stat(fmtHours(s.leisure_total), 'leisure'),
stat(fmtHours(s.worst_total), 'worst case'),
),
p
? facts([
['Your pace', STYLE[p.player_style] ?? p.player_style],
['vs rush', ratio(p.ratio_vs_rush)],
['vs leisure', ratio(p.ratio_vs_leisure)],
['Calibrated on', `${p.calibration_count} finished games`],
])
: null,
]),
card(
'Estimates (default filters)',
[
h(
'div',
{ class: 'stat-row' },
stat(s.qualifying, '🎮', 'qualifying games'),
stat(fmtHours(s.rush_total), BASIS_GLYPH.rush, 'rush'),
stat(fmtHours(s.leisure_total), BASIS_GLYPH.leisure, 'leisure'),
stat(fmtHours(s.worst_total), BASIS_GLYPH.worst, 'worst case'),
),
p
? facts([
[glyph(BASIS_GLYPH.pace, 'Your pace'), styleGlyph(p.player_style)],
[glyph(BASIS_GLYPH.rush, 'vs rush'), ratio(p.ratio_vs_rush)],
[glyph(BASIS_GLYPH.leisure, 'vs leisure'), ratio(p.ratio_vs_leisure)],
[glyph('🏆', 'Calibrated on'), [String(p.calibration_count), h('span', { class: 'sr-only' }, ' finished games')]],
])
: null,
],
{ icon: ICON },
),
)
}
}

View File

@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'
import { applyFilters } from '../../estimate'
import { makeDataset, makeFilters, makeGame, makePaceVsHltb, makeState } from '../../test/factories'
import type { Filters, PaceVsHLTB } from '../../types'
import { painted } from './painted.testutil'
import { summaryCards } from './summary'
const NOW = new Date('2026-01-01T00:00:00Z')
@ -35,12 +36,14 @@ describe('summaryCards', () => {
it('drops the match badge when the count differs from the CLI', () => {
const el = cards({}, 0, null, 7)
expect(el.querySelector('.parity')?.textContent).toBe('CLI default qualifies 7')
expect(painted(el.querySelector('.parity'))).toBe('⌨️ 7')
expect(el.querySelector('.parity')).toHaveAttribute('data-match', 'false')
})
it('marks the active basis card and lists presets for hour bases only', () => {
const el = cards({ basis: 'rush' })
expect(el.querySelector('.card.active .card-title')?.textContent).toBe('Rush')
expect(el.querySelector('.card.active')).toHaveAttribute('data-basis', 'rush')
expect(painted(el.querySelector('.card.active .card-title'))).toBe('🐇')
expect(el.querySelectorAll('.cards .card')).toHaveLength(4)
expect(el.querySelectorAll('.cards .presets')).toHaveLength(3)
expect(el.querySelector('.card .card-total')?.textContent).toBe('10 h')
@ -53,22 +56,23 @@ describe('summaryCards', () => {
it('shows the pace card ETA when a pace is known', () => {
const el = cards({}, 0.5)
const pace = [...el.querySelectorAll('.card')].at(-1)
expect(pace?.querySelector('.card-total')?.textContent).toBe('0.5 games/day')
expect(painted(pace?.querySelector('.card-total'))).toBe('0.5 🎮/d')
expect(pace?.querySelector('.card-eta')?.textContent).toMatch(/^2 days · /)
})
it('renders the target-date banner with required hours/day', () => {
const banner = cards({ targetDate: '2026-01-11', basis: 'leisure' }).querySelector('.target-banner')
expect(banner?.textContent).toBe('To finish 1 games by 2026-01-11 (10 days) on the leisure model, you need 2.0 h/day.')
expect(painted(banner)).toBe('🎮 1 🏁 2026-01-11 (10 d) 🐢 → 2.0 h/day')
expect(banner).toHaveTextContent(/on the leisure model, you need/)
})
it('renders the target banner in games/day for the pace basis', () => {
const banner = cards({ targetDate: '2099-01-01', basis: 'pace' }, 0.9).querySelector('.target-banner')
expect(banner?.textContent).toMatch(/games\/day/i)
expect(painted(banner)).toMatch(/👤 → [\d.]+ 🎮\/d$/)
})
it('counts a past target as one day', () => {
expect(cards({ targetDate: '2020-01-01' }).querySelector('.target-banner')?.textContent).toMatch(/\(1 days\)/)
expect(painted(cards({ targetDate: '2020-01-01' }).querySelector('.target-banner'))).toMatch(/\(1 d\)/)
})
it('defaults the clock to now', () => {
@ -94,9 +98,12 @@ describe('player insight', () => {
expect(getByText(el, /Calibration games/i)).toBeInTheDocument()
expect(getByText(el, /vs Rush speed/i)).toBeInTheDocument()
expect(getByText(el, 'Play style')).toBeInTheDocument()
expect(getByText(el, /Between rush and leisure/i)).toHaveClass('player-insight-style--rush_to_leisure')
const style = el.querySelector('.player-insight-style--rush_to_leisure')
expect(style).toHaveTextContent(/Between rush and leisure/)
expect(painted(style)).toBe('🐇↔🐢')
expect(getByText(el, '1.05×')).toHaveClass('player-insight-slow')
expect(getByText(el, '0.050')).toHaveAttribute('title', '0 = rush speed · 1 = leisure speed')
expect(getByText(el, '0.050')).not.toHaveAttribute('title')
expect(getByText(el, /0 = rush speed, 1 = leisure speed/)).toHaveClass('sr-only')
})
it('shows the estimated total at the player’s pace', () => {

View File

@ -1,10 +1,13 @@
// The planner's headline: games in scope, the target-date banner, one card per
// estimate basis and the player's pace vs HLTB (was SummaryCards.tsx).
// Textgate: labels are glyphs (glyphs.ts), the old wording is spoken only.
import { basisTotal, etaDays, paceDays, playerEstimatedTotal, type EstimateResult } from '../../estimate'
import { fmtEta, fmtHours } from '../../format'
import { h } from '../../lib/dom'
import type { EstimateBasis, Filters, PaceVsHLTB, WebStateInfo } from '../../types'
import { empty, glyph } from '../../ui/build'
import { BASIS_GLYPH, styleGlyph } from './glyphs'
export interface SummaryProps {
result: EstimateResult
@ -22,12 +25,9 @@ const CARDS: readonly { basis: EstimateBasis; title: string; blurb: string }[] =
{ basis: 'pace', title: 'At your pace', blurb: 'Based on games finished' },
]
const STYLE_LABELS: Record<string, string> = {
faster_than_rush: 'Faster than rush',
rush_to_leisure: 'Between rush and leisure',
slower_than_leisure: 'Slower than leisure',
unknown: 'Unknown',
}
const spoken = (text: string) => h('span', { class: 'sr-only' }, text)
/** Games per day: the 🎮 stands in for the word "games". */
const perDay = (n: number | string) => [`${n} 🎮/d`, spoken(' games per day')]
function targetBanner({ result, filters }: SummaryProps, now: Date): HTMLDivElement | null {
if (!filters.targetDate) return null
@ -35,20 +35,21 @@ function targetBanner({ result, filters }: SummaryProps, now: Date): HTMLDivElem
const days = Math.max(1, Math.ceil((target.getTime() - now.getTime()) / 86400000))
// Pace is the only basis without an hours total: it needs games per day.
const total = basisTotal(result, filters.basis)
const need =
total === null ? `${(result.remainingGames / days).toFixed(2)} games/day` : `${(total / days).toFixed(1)} h/day`
const need = total === null ? perDay((result.remainingGames / days).toFixed(2)) : `${(total / days).toFixed(1)} h/day`
return h(
'div',
{ class: 'target-banner' },
'To finish ',
glyph('🎮', 'To finish'),
' ',
h('strong', {}, result.remainingGames),
' games by ',
spoken(' games'),
' 🏁 ',
spoken('by '),
h('strong', {}, filters.targetDate),
` (${days} days) on the `,
h('strong', {}, filters.basis),
' model, you need ',
` (${days} d) `,
glyph(BASIS_GLYPH[filters.basis], `on the ${filters.basis} model, you need`),
' → ',
h('strong', {}, need),
'.',
)
}
@ -59,25 +60,19 @@ const presetRows = (presets: readonly number[], eta: (perDay: number) => number
presets.map((p) => h('div', { class: 'preset' }, h('span', {}, `${p} h/day`), h('span', {}, fmtEta(eta(p))))),
)
const pair = (label: string, value: string, attrs: Record<string, string> = {}) => [
h('span', {}, label),
h('span', attrs, value),
const pair = (icon: string, label: string, value: Node | string, attrs: Record<string, string> = {}) => [
glyph(icon, label),
typeof value === 'string' ? h('span', attrs, value) : value,
]
function playerInsight({ result, paceVsHltb: pace, presets }: SummaryProps): HTMLDivElement {
const title = h('div', { class: 'player-insight-title' }, 'Your Play Style vs HLTB')
const title = h('div', { class: 'player-insight-title' }, glyph(BASIS_GLYPH.pace, 'Your Play Style vs HLTB'))
if (!pace || pace.calibration_count === 0) {
return h(
'div',
{ class: 'player-insight player-insight--empty' },
title,
h(
'p',
{ class: 'player-insight-empty' },
'No calibration data yet. Finish games (100% achievements) and re-run ',
h('code', {}, 'stats'),
' to see your pace estimate.',
),
empty('No calibration data yet. Finish games (100% achievements) and re-run stats to see your pace estimate.'),
)
}
const estimated = playerEstimatedTotal(result.rushTotal, result.leisureTotal, pace)
@ -88,19 +83,18 @@ function playerInsight({ result, paceVsHltb: pace, presets }: SummaryProps): HTM
h(
'div',
{ class: 'player-insight-grid' },
pair('Calibration games', String(pace.calibration_count)),
pair('🏆', 'Calibration games', String(pace.calibration_count)),
pace.ratio_vs_rush !== -1
? pair('vs Rush speed', `${pace.ratio_vs_rush.toFixed(2)}×`, {
? pair(BASIS_GLYPH.rush, 'vs Rush speed', `${pace.ratio_vs_rush.toFixed(2)}×`, {
class: pace.ratio_vs_rush <= 1 ? 'player-insight-fast' : 'player-insight-slow',
})
: null,
pace.ratio_vs_leisure !== -1 ? pair('vs Leisure speed', `${pace.ratio_vs_leisure.toFixed(2)}×`) : null,
pace.ratio_vs_leisure !== -1 ? pair(BASIS_GLYPH.leisure, 'vs Leisure speed', `${pace.ratio_vs_leisure.toFixed(2)}×`) : null,
// `t` is the formula's own symbol: 0 = rush speed, 1 = leisure speed.
pace.interpolation_t !== -1
? pair('Interpolation t', pace.interpolation_t.toFixed(3), { title: '0 = rush speed · 1 = leisure speed' })
? pair('t', 'Interpolation t, 0 = rush speed, 1 = leisure speed', pace.interpolation_t.toFixed(3))
: null,
pair('Play style', STYLE_LABELS[pace.player_style] ?? pace.player_style, {
class: `player-insight-style player-insight-style--${pace.player_style}`,
}),
pair('🎭', 'Play style', styleGlyph(pace.player_style)),
),
estimated !== null
? h(
@ -109,7 +103,8 @@ function playerInsight({ result, paceVsHltb: pace, presets }: SummaryProps): HTM
h(
'div',
{ class: 'player-insight-estimate-total' },
'Estimated total at your pace: ',
glyph('Σ', 'Estimated total at your pace: '),
' ',
h('strong', { class: 'player-insight-estimate-hours' }, fmtHours(estimated)),
),
presetRows(presets, (p) => (estimated > 0 ? Math.floor(estimated / p) : null)),
@ -126,17 +121,18 @@ function basisCard(props: SummaryProps, c: (typeof CARDS)[number]): HTMLDivEleme
const eta = isPace ? paceDays(result.remainingGames, pace) : etaDays(total, filters.dailyHours)
return h(
'div',
{ class: filters.basis === c.basis ? 'card active' : 'card' },
h('div', { class: 'card-title' }, c.title),
h('div', { class: 'card-blurb' }, c.blurb),
h('div', { class: 'card-total' }, isPace ? `${pace} games/day` : fmtHours(total)),
h('div', { class: 'card-eta' }, isPace && !pace ? 'No start date set' : fmtEta(eta)),
{ class: filters.basis === c.basis ? 'card active' : 'card', 'data-basis': c.basis },
h('div', { class: 'card-title' }, glyph(BASIS_GLYPH[c.basis], c.title)),
spoken(c.blurb),
h('div', { class: 'card-total' }, isPace ? perDay(pace) : fmtHours(total)),
h('div', { class: 'card-eta' }, isPace && !pace ? glyph('∅', 'No start date set') : fmtEta(eta)),
isPace ? null : presetRows(presets, (p) => etaDays(total, p)),
)
}
export function summaryCards(props: SummaryProps, now: Date = new Date()): HTMLDivElement {
const { result, defaultQualifying } = props
const match = result.remainingGames === defaultQualifying
return h(
'div',
{ class: 'summary' },
@ -147,14 +143,15 @@ export function summaryCards(props: SummaryProps, now: Date = new Date()): HTMLD
'div',
{},
h('span', { class: 'big' }, result.remainingGames.toLocaleString()),
h('span', { class: 'big-label' }, 'games in scope'),
glyph('🎮', 'games in scope', 'big-label'),
),
h(
'div',
{ class: 'parity' },
'CLI default qualifies ',
{ class: 'parity', 'data-match': String(match) },
glyph('⌨️', 'CLI default qualifies '),
' ',
h('strong', {}, defaultQualifying),
result.remainingGames === defaultQualifying ? h('span', { class: 'ok' }, ' ✓ match') : null,
match ? h('span', { class: 'ok' }, ' ✓', spoken(' match')) : null,
),
),
targetBanner(props, now),

View File

@ -0,0 +1,81 @@
// Guard test (textgate-rework R6): the backlog page paints glyphs, numbers and
// game names only; every label, hint and sentence is spoken only.
import { screen } from '@testing-library/dom'
import { afterEach, describe, expect, it } from 'vitest'
import { makeGame, makePaceVsHltb, makeState } from '../../test/factories'
import { flush, mount, stubApi } from '../../test/harness'
import { GAMES, panel, show } from '../../test/plannerHelpers'
import { visibleWords } from '../../test/visibleWords'
import { ANY_GLYPH, KEEP_GLYPH, styleGlyph, tierGlyphs } from './glyphs'
import { painted } from './painted.testutil'
afterEach(() => {
history.replaceState(null, '', '/')
})
// <option> text paints only inside the open select; it is still checked here.
const NAMES = ['Alpha', 'Beta', 'Gamma', 'Hollow Knight', 'No Data']
// A unit right after a number is content (4 h/day, 140 days, 3 h).
const UNIT = /\d[\d,.]*\s*(h\/day|days?|[hmsd])\b/g
const words = (allowed: string[] = []) =>
visibleWords(document.body, allowed).filter((w) => /[A-Za-z]{2,}/.test(w.replace(UNIT, '')))
describe('textgate guard: backlog', () => {
it('the planner paints no words, with every panel open', async () => {
history.replaceState(null, '', '/backlog/#nodata=1&proton=minTier&target=2099-01-01')
await show([...GAMES, makeGame({ app_id: 9, name: 'No Data', rush_hours: -1, leisure_hours: -1, worst_hours: -1 })], {
state: makeState({ current_game_name: 'Hollow Knight' }),
pace_vs_hltb: makePaceVsHltb(),
})
expect(words(NAMES)).toEqual([])
})
it('the stats card paints no words', async () => {
const summary = { qualifying: 4, rush_total: 1, leisure_total: 2, worst_total: 3 }
stubApi({ 'GET /api/stats': { default_summary: summary, pace_vs_hltb: makePaceVsHltb() } })
mount('<backlog-stats></backlog-stats>')
await flush()
expect(screen.getByRole('heading', { name: 'Estimates (default filters)' })).toBeInTheDocument()
expect(words()).toEqual([])
})
it('the load error paints only the server message and the recovery command', async () => {
stubApi({ 'GET /api/dataset': () => Promise.reject(new Error('net')) })
mount('<game-table></game-table>')
await flush()
expect(visibleWords(document.body, ['net', './run.sh serve'])).toEqual([])
})
})
describe('backlog glyphs', () => {
it('paints ProtonDB tiers as medals, unknown tiers as ❔', () => {
expect(tierGlyphs('gold / silver')).toBe('🥇/🥈')
expect(tierGlyphs('—')).toBe('—')
expect(tierGlyphs('')).toBe('—')
expect(tierGlyphs('weird')).toBe('❔')
expect(KEEP_GLYPH.excluded).toBe('🚫')
})
it('speaks an unknown play style by its key', () => {
const el = styleGlyph('odd')
expect(painted(el)).toBe('❔')
expect(el).toHaveTextContent('odd')
expect(el).toHaveClass('player-insight-style--odd')
})
it('offers glyph options in the table filters, values unchanged', async () => {
await show()
const keep = screen.getByRole('combobox', { name: 'Filter Keep' })
expect([...keep.querySelectorAll('option')].map((o) => [o.value, o.textContent])).toContainEqual(['', ANY_GLYPH])
expect([...keep.querySelectorAll('option')].map((o) => [o.value, o.textContent])).toContainEqual(['kept', '📌'])
const tier = screen.getByRole('combobox', { name: 'Filter ProtonDB' })
expect([...tier.querySelectorAll('option')].map((o) => o.textContent)).toContain('🥇/💎')
})
it('marks the pressed basis segment for assistive tech', async () => {
await show()
expect(panel().getByRole('button', { name: 'Leisure' })).toHaveAttribute('aria-pressed', 'true')
expect(panel().getByRole('button', { name: 'Rush' })).toHaveAttribute('aria-pressed', 'false')
})
})

View File

@ -27,9 +27,10 @@ export async function found(text: string): Promise<HTMLButtonElement> {
return vi.waitFor(() => button(document.body, text))
}
/** The input whose label starts with `label`. */
/** The input whose spoken label (its .sr-only text, else its text) starts with `label`. */
export function field(label: string | RegExp): HTMLInputElement {
const l = [...document.querySelectorAll('label')].find((x) => (typeof label === 'string' ? x.textContent.startsWith(label) : label.test(x.textContent)))
const spoken = (x: Element) => x.querySelector('.sr-only')?.textContent ?? x.textContent
const l = [...document.querySelectorAll('label')].find((x) => (typeof label === 'string' ? spoken(x).startsWith(label) : label.test(spoken(x))))
return document.getElementById(l?.getAttribute('for') ?? '') as HTMLInputElement
}