Compare commits

...

12 Commits

Author SHA1 Message Date
1e452b0fcd deps(web): @testing-library/user-event 14.6.9
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:14:12 +01:00
1d6d3469eb web: tests close coverage gaps after rework
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:08:55 +01:00
5b31b19ea7 web: static probe no longer counts spoken labels
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:59:54 +01:00
f73d2fa513 Numeric dates; progress items without words
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:57:55 +01:00
8dbcc462c0 web: library, store, picks and jobs paint glyphs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:56:01 +01:00
7e0ae61164 web: dashboard, gaming and health paint glyphs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:55:42 +01:00
9f52d27893 web: backlog page paints glyphs and numbers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:55:30 +01:00
f74e70221f web: system and setup pages paint glyphs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:54:44 +01:00
30416da9b8 web: runner, palette and countdown paint glyphs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:54:44 +01:00
291a5ed26f Desktop toasts paint glyphs and numbers only
Guard test walks every toast call for literal words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:54:20 +01:00
138abc6ce9 web: pills, card and dialog titles spoken only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:45:30 +01:00
13df1dd14d web: command buttons paint glyphs only
Labels, descriptions and lock reasons are spoken only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:36:41 +01:00
100 changed files with 1752 additions and 620 deletions

View File

@ -41,7 +41,7 @@ INCIDENT_LOG: Final = (
Path(__file__).resolve().parents[1] / "leetcode_bonus_incidents.log"
)
_TITLE: Final = "Gaming budget: LeetCode bonus not applied"
_TITLE: Final = "🧩❌🎮"
# reason -> the local day it was last reported on.
_reported: dict[str, str] = {}
@ -69,7 +69,9 @@ def report_leetcode_incident(reason: str, *, fix: str) -> None:
body = f"{reason}. Budget is 1h lower until this is fixed. Try: {fix}"
logger.warning("LeetCode bonus not applied - %s. Try: %s", reason, fix)
notify_desktop_user(_TITLE, body)
# Textgate: the toast paints the bonus glyph, the lost hour and the fix
# command (content kuhy runs); the sentence stays in the log and journal.
notify_desktop_user(_TITLE, f"-1h {fix}")
_append_incident(f"{datetime.now().astimezone().isoformat()} {body}")

View File

@ -102,10 +102,7 @@ def _finalize_completion(
use_steam_protocol=True,
)
send_notification(
"Moving on!",
f"New achievement in {game_name}! Now playing: {state.current_game_name}",
)
send_notification("🏆", f"{game_name} → {state.current_game_name}")
_echo(f"\nAll done! Go play {state.current_game_name}!")

View File

@ -60,9 +60,5 @@ def guard_installed_games(allowed: set[int]) -> int:
)
if uninstall_game(app_id, name):
count += 1
send_notification(
"Game Removed!",
f"Uninstalled {name} (AppID={app_id}). "
f"Only your assigned game(s) are allowed.",
)
send_notification("🗑️", f"{name} · {app_id}")
return count

View File

@ -142,11 +142,7 @@ def _enforce_loop_iteration(
violations = enforce_allowed_game(allowed, kill_unauthorized=True)
for pid, app_id in violations:
_echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})")
send_notification(
"Game Blocked!",
f"Killed unauthorized game (AppID={app_id}). "
f"Focus on {allowed_names(state)}!",
)
send_notification("⛔🎮", f"{app_id} → 🎯 {allowed_names(state)}")
# B) Remove any newly-installed unauthorized games.
if config.uninstall_other_games:

View File

@ -100,7 +100,7 @@ def _enforce_auto_install(config: Config, state: State) -> None:
config.steam_id,
use_steam_protocol=True,
):
send_notification("Game Installing", f"{name} is being downloaded.")
send_notification("⬇️", name)
else:
_echo(" Could not auto-install. Install manually from Steam.")

View File

@ -241,7 +241,8 @@ class WaitReporter:
# Floor, so 99.99 never reads as done before the depot is.
progress.advance(self._label, step=int(snap.percent or 0))
else:
progress.advance(f"{_clock(snap.elapsed_seconds)} elapsed", step=0)
# The web UI paints the item (textgate): glyph + number, no word.
progress.advance(f"⏱️ {_clock(snap.elapsed_seconds)}", step=0)
if now - self._last_echo >= ECHO_SECONDS:
self._last_echo = now
_echo(f" Fast-installing {self._label}: {snap.describe()}")

View File

@ -24,7 +24,11 @@ from steam_backlog_enforcer._playtime_kill import (
request_steam_shutdown,
steam_and_launcher_pids,
)
from steam_backlog_enforcer._playtime_notify import _humanise, notify_desktop_user
from steam_backlog_enforcer._playtime_notify import (
_humanise,
notify_desktop_user,
short_duration,
)
from steam_backlog_enforcer._playtime_state import (
_SHUTDOWN_GRACE_SECONDS,
PlaytimeRules,
@ -53,12 +57,8 @@ def reconcile_for(rules: PlaytimeRules, *, should_block: bool) -> None:
reconcile(should_block=should_block)
_CUTOFF_BODY = {
False: "Daily budget used up. Steam and games are shutting down. "
"Unblocks at 06:00.",
True: "Daily leisure budget used up. Steam, games and leisure apps are "
"shutting down. Unblocks at 06:00.",
}
# Toasts are textgated: a glyph per budget and the unblock time, no sentence.
_UNBLOCK_AT = "06:00"
def _noun(rules: PlaytimeRules) -> str:
@ -66,6 +66,11 @@ def _noun(rules: PlaytimeRules) -> str:
return "Leisure" if rules.leisure else "Gaming"
def _glyph(rules: PlaytimeRules) -> str:
"""The toast glyph for the budget: 🛋️ leisure (Phase 2), 🎮 gaming."""
return "🛋️" if rules.leisure else "🎮"
def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
"""Fire the due warning, if any, and record that it fired.
@ -89,7 +94,7 @@ def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
state.seconds,
rules.budget_seconds,
)
notify_desktop_user(f"{noun} time running out", left)
notify_desktop_user(f"⏳{_glyph(rules)}", short_duration(threshold))
return replace(state, warned_seconds=[*state.warned_seconds, threshold])
@ -116,7 +121,7 @@ def _begin_cutoff(
logger.warning(
"Daily %s budget exhausted; shutting Steam down.", _noun(rules).lower()
)
notify_desktop_user(f"{_noun(rules)} time is up", _CUTOFF_BODY[rules.leisure])
notify_desktop_user(f"⛔{_glyph(rules)}", f"🔓 {_UNBLOCK_AT}")
request_steam_shutdown()
kill_gaming_processes(_kill_set(rules), force=False)
if rules.demo:

View File

@ -18,6 +18,23 @@ _SECONDS_PER_MINUTE = 60
_MINUTES_PER_HOUR = 60
def short_duration(seconds: int) -> str:
"""Render a threshold as a toast-sized number + unit (textgate: no words).
Args:
seconds: Seconds remaining.
Returns:
``"30s"``, ``"5m"``, ``"1h"`` or ``"1h 30m"``.
"""
if seconds < _SECONDS_PER_MINUTE:
return f"{seconds}s"
hours, minutes = divmod(seconds // _SECONDS_PER_MINUTE, _MINUTES_PER_HOUR)
if not hours:
return f"{minutes}m"
return f"{hours}h {minutes}m" if minutes else f"{hours}h"
def notify_desktop_user(title: str, body: str) -> None:
"""Send a desktop notification into the real user's session.

View File

@ -187,7 +187,4 @@ def detect_tampering(config: Config, state: State) -> None:
_echo("\n TAMPERING DETECTED:")
for name, app_id, diff in suspicious:
_echo(f" {name} (AppID={app_id}): +{diff} new achievements!")
send_notification(
"Tampering Detected!",
f"Achievements unlocked on {len(suspicious)} non-assigned games!",
)
send_notification("🕵️🏆", f"🎮 {len(suspicious)}")

View File

@ -225,10 +225,7 @@ def do_check(config: Config, state: State) -> None:
_echo(f"\n {verdict}")
if released:
release_game(state, game)
send_notification(
"Moving on!",
f"New achievement in {state.current_game_name}! Picking next game...",
)
send_notification("🏆", f"{state.current_game_name} → 🎲")
# Load snapshot and pick next.
snapshot_data = load_snapshot()

View File

@ -57,7 +57,7 @@ class TestReporting:
patch(f"{_PKG}.notify_desktop_user") as notify,
):
report_leetcode_incident("ledger unreadable", fix="systemctl status x")
assert notify.call_count == 1
notify.assert_called_once_with("🧩❌🎮", "-1h systemctl status x")
assert "ledger unreadable" in caplog.text
assert "systemctl status x" in log.read_text(encoding="utf-8")

View File

@ -213,7 +213,7 @@ class TestWaitReporter:
progress.phase.assert_called_once_with(
"Fast-installing G: shutting Steam down", None
)
progress.advance.assert_called_once_with("12s elapsed", step=0)
progress.advance.assert_called_once_with("⏱️ 12s", step=0)
def test_echo_is_throttled_to_30_seconds(self, tmp_path: Path) -> None:
reporter = self._reporter(tmp_path, _upto(" 46.90%"))

View File

@ -134,8 +134,7 @@ class TestLive:
_go_live(tmp_path)
state, spy = _tick({}, budget=3.0)
assert state.is_blocked()
assert notify.call_args.args[0] == "Leisure time is up"
assert "leisure" in notify.call_args.args[1]
assert notify.call_args.args == ("⛔🛋️", "🔓 06:00")
assert spy.calls[0][0].seconds >= spy.calls[0][1].budget_seconds
@ -149,32 +148,26 @@ _RULES = PlaytimeRules(
)
class TestWording:
def test_warnings_say_gaming_while_dormant(self) -> None:
class TestToastGlyphs:
"""Textgate: toasts paint glyphs and numbers, no words."""
def test_warnings_show_gaming_glyph_while_dormant(self) -> None:
with patch(f"{_CUTOFF}.notify_desktop_user") as notify:
_warn(PlaytimeState(day_key=_TODAY, seconds=10.0), _RULES)
notify.assert_called_once_with(
"Gaming time running out", "1 hour of today's gaming budget left."
)
notify.assert_called_once_with("⏳🎮", "1h")
def test_warnings_say_leisure_when_live(self) -> None:
def test_warnings_show_leisure_glyph_when_live(self) -> None:
with patch(f"{_CUTOFF}.notify_desktop_user") as notify:
_warn(
PlaytimeState(day_key=_TODAY, seconds=10.0),
replace(_RULES, leisure=True),
)
notify.assert_called_once_with(
"Leisure time running out", "1 hour of today's leisure budget left."
)
notify.assert_called_once_with("⏳🛋️", "1h")
@pytest.mark.usefixtures("notify")
def test_the_dormant_cutoff_text_is_unchanged(self, notify: MagicMock) -> None:
def test_the_dormant_cutoff_shows_unblock_time(self, notify: MagicMock) -> None:
_begin_cutoff(PlaytimeState(day_key=_TODAY), _RULES, now=_NOW)
notify.assert_called_once_with(
"Gaming time is up",
"Daily budget used up. Steam and games are shutting down. "
"Unblocks at 06:00.",
)
notify.assert_called_once_with("⛔🎮", "🔓 06:00")
def test_new_session_kills_through_the_budget_log() -> None:

View File

@ -195,7 +195,7 @@ class TestWarn:
) as mock_notify:
out = _warn(state, _rules())
assert out.warned_seconds == [3600, 1800, 600, 300]
assert "5 minutes" in mock_notify.call_args.args[1]
assert mock_notify.call_args.args == ("⏳🎮", "5m")
def test_a_fired_warning_is_logged(self, caplog: pytest.LogCaptureFixture) -> None:
state = PlaytimeState(seconds=8 * 3600 - 300, warned_seconds=[3600, 1800, 600])

View File

@ -2,7 +2,18 @@
from __future__ import annotations
from steam_backlog_enforcer._playtime_notify import _humanise
import pytest
from steam_backlog_enforcer._playtime_notify import _humanise, short_duration
@pytest.mark.parametrize(
("seconds", "shown"),
[(30, "30s"), (60, "1m"), (300, "5m"), (3600, "1h"), (5400, "1h 30m")],
)
def test_short_duration(seconds: int, shown: str) -> None:
"""Toasts paint a number + unit, never a word."""
assert short_duration(seconds) == shown
class TestHumanise:

View File

@ -0,0 +1,111 @@
"""Textgate guard: desktop toasts paint glyphs and numbers, never words.
Walks every ``send_notification`` / ``notify_desktop_user`` call in the
package and checks the literal parts of its arguments (string constants and
the constant pieces of f-strings). Interpolated values -- game names, app ids,
durations, shell commands -- are content and pass. A module-level constant
passed by name is resolved too, so ``_TITLE`` cannot hide a sentence.
"""
from __future__ import annotations
import ast
from pathlib import Path
import re
_PKG = Path(__file__).resolve().parents[1]
_TOAST_CALLS = {"send_notification", "notify_desktop_user"}
_WORD = re.compile(r"[A-Za-z]{2,}")
def _literal_parts(node: ast.expr, consts: dict[str, ast.expr]) -> list[str]:
"""The literal text an argument paints, following module constants.
Args:
node: One call argument.
consts: Module-level ``NAME = <expr>`` assignments.
Returns:
Every literal string fragment in the argument.
"""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return [node.value]
if isinstance(node, ast.JoinedStr):
return [
v.value
for v in node.values
if isinstance(v, ast.Constant) and isinstance(v.value, str)
]
if isinstance(node, ast.Name) and node.id in consts:
return _literal_parts(consts[node.id], consts)
if isinstance(node, ast.Subscript):
return _literal_parts(node.value, consts)
if isinstance(node, ast.Dict):
return [p for v in node.values for p in _literal_parts(v, consts)]
return []
def _module_consts(tree: ast.Module) -> dict[str, ast.expr]:
"""Map module-level simple assignments to their value expressions.
Args:
tree: A parsed module.
Returns:
``{name: value}`` for ``NAME = value`` and ``NAME: T = value``.
"""
out: dict[str, ast.expr] = {}
for stmt in tree.body:
if isinstance(stmt, ast.Assign):
for target in stmt.targets:
if isinstance(target, ast.Name):
out[target.id] = stmt.value
elif (
isinstance(stmt, ast.AnnAssign)
and isinstance(stmt.target, ast.Name)
and stmt.value is not None
):
out[stmt.target.id] = stmt.value
return out
def _toast_words() -> list[str]:
"""Every literal word passed to a toast, as ``file:line: text``.
Returns:
The offending fragments; empty when every toast is word-free.
"""
hits: list[str] = []
for path in sorted(_PKG.glob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"))
consts = _module_consts(tree)
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "")
if name not in _TOAST_CALLS:
continue
for arg in node.args:
hits.extend(
f"{path.name}:{node.lineno}: {part}"
for part in _literal_parts(arg, consts)
if _WORD.search(part)
)
return hits
def test_toasts_paint_no_words() -> None:
"""No toast title or body carries a literal 2+ letter word."""
assert _toast_words() == []
def test_the_guard_finds_toast_calls() -> None:
"""The walk is not vacuous: the package has toast call sites."""
calls = 0
for path in _PKG.glob("*.py"):
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
func = getattr(node, "func", None)
name = getattr(func, "id", None) or getattr(func, "attr", "")
calls += isinstance(node, ast.Call) and name in _TOAST_CALLS
assert calls >= 8

View File

@ -91,7 +91,7 @@ const install: Script = async (ctx) => {
const dir = await ctx.prompt('text', 'Steam library folder to install into:', { default: '/mnt/games/SteamLibrary' })
ctx.log(`steam://install/${world.currentAppId} → ${dir || '/mnt/games/SteamLibrary'}`)
for (let i = 1; i <= 20; i += 1) {
ctx.progress(i, 20, 'Downloading', `${name} — ${(i * 0.6).toFixed(1)} of 12.0 GB`, (20 - i) * 0.4)
ctx.progress(i, 20, 'Downloading', `${name} · ${(i * 0.6).toFixed(1)}/12.0 GB`, (20 - i) * 0.4)
await ctx.sleep(400)
}
return { summary: `${name} installed.` }

View File

@ -27,7 +27,7 @@
"@eslint/js": "10.0.1",
"@testing-library/dom": "10.4.2",
"@testing-library/jest-dom": "7.0.1",
"@testing-library/user-event": "14.6.8",
"@testing-library/user-event": "14.6.9",
"@types/node": "26.6.6",
"@vitest/coverage-v8": "5.1.0",
"eslint": "10.14.0",

View File

@ -190,8 +190,8 @@ importers:
specifier: 7.0.1
version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.1.0)
'@testing-library/user-event':
specifier: 14.6.8
version: 14.6.8(@testing-library/dom@10.4.2)
specifier: 14.6.9
version: 14.6.9(@testing-library/dom@10.4.2)
'@types/node':
specifier: 26.6.6
version: 26.6.6
@ -895,8 +895,8 @@ packages:
vitest:
optional: true
'@testing-library/user-event@14.6.8':
resolution: {integrity: sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==}
'@testing-library/user-event@14.6.9':
resolution: {integrity: sha512-/8boTjZHNXFi8JGUI2Ev05cq0Szh0OX35Bamkq6CK1ne+l1Xm8BKE3+nGgsnFgaYk0MX67Vh59cZDsNz5lJJEg==}
engines: {node: '>=12', npm: '>=6'}
peerDependencies:
'@testing-library/dom': '>=7.21.4'
@ -3103,7 +3103,7 @@ snapshots:
optionalDependencies:
vitest: 5.1.0(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(jsdom@31.0.0)(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
'@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)':
'@testing-library/user-event@14.6.9(@testing-library/dom@10.4.2)':
dependencies:
'@testing-library/dom': 10.4.2

View File

@ -1,6 +1,5 @@
// Textgate check over the built site: list every chrome word a page paints
// before its custom elements hydrate (layout, page heads, command-button
// labels). Spoken-only text (.sr-only, aria-hidden, the focus-only skip link)
// before its custom elements hydrate (layout, page heads). Spoken-only text (.sr-only, aria-hidden, the focus-only skip link)
// is ignored. Exit 1 when any page paints a word, so it works as a gate.
//
// Usage: node scripts/visible_words.mjs [distDir] (run `pnpm build` first)
@ -31,11 +30,8 @@ export function visibleWords(html) {
const t = n.textContent?.trim() ?? ''
if (WORD_RE.test(t)) out.push(t)
}
// command-button paints its label attribute once it hydrates.
for (const el of document.querySelectorAll('command-button[label]')) {
const t = el.getAttribute('label') ?? ''
if (WORD_RE.test(t)) out.push(`[button] ${t}`)
}
// command-button's `label` is spoken only (aria-label) once it hydrates;
// src/test/textgate.commands.guard.test.ts pins that.
return out
}

View File

@ -44,6 +44,36 @@ export const COMMAND_HOME = {
'restore-backup': '/system',
} as const satisfies Record<CommandName, SectionPath>
/** The glyph a command's button paints (textgate: its label is spoken only). */
export const COMMAND_ICON = {
status: '📊',
list: '📋',
stats: '📈',
installed: '💾',
'gaming-status': '⏱️',
check: '🔄',
scan: '🔎',
done: '🏆',
pick: '🎲',
'pick-manual': '📌',
'abandon-pick': '❌',
install: '⬇️',
uninstall: '🗑️',
hide: '🙈',
unhide: '👁️',
'buy-dlc': '💳',
unblock: '🔓',
'add-exception': '🎫',
'block-gaming': '⛔',
reset: '♻️',
setup: '🔧',
enforce: '🛡️',
'gaming-reset': '⏪',
'gaming-unblock': '🔌',
serve: '🌐',
'restore-backup': '🗄️',
} as const satisfies Record<CommandName, string>
/** Title-case label for buttons and the palette (`pick-manual` → `Pick manual`). */
export function commandLabel(name: CommandName): string {
const s = name.replace(/-/g, ' ')

View File

@ -26,7 +26,7 @@ describe('<command-button>', () => {
loaded([makeSpec('scan')])
const el = mount(`<command-button name="scan" preset='{"app_id":4}'></command-button>`)
await vi.waitFor(() => {
expect(el.querySelector('button')).toHaveTextContent('Run scan')
expect(el.querySelector('button')).toHaveAttribute('aria-label', 'Run scan')
})
const btn = must(el.querySelector('button'))
expect(btn).toHaveAttribute('aria-disabled', 'false')
@ -39,7 +39,7 @@ describe('<command-button>', () => {
loaded([])
const el = mount('<command-button></command-button>')
const btn = must(el.querySelector('button'))
expect(btn).toHaveTextContent('Open Status')
expect(btn).toHaveAttribute('aria-label', 'Open Status')
expect(btn).toHaveAttribute('aria-disabled', 'true')
btn.click()
await vi.waitFor(() => {
@ -52,10 +52,12 @@ describe('<command-button>', () => {
loaded([makeSpec('pick', { locked_reason: 'Locked by a manual pick' })])
const el = mount('<command-button name="pick" label="Pick it" tone="danger"></command-button>')
const btn = must(el.querySelector('button'))
expect(btn).toHaveTextContent('Pick it')
expect(btn).toHaveAttribute('aria-label', 'Pick it')
expect(btn.querySelector('.cmd-lock')).toBeNull()
await vi.waitFor(() => {
expect(el.querySelector('button')).toHaveAttribute('title', 'Locked by a manual pick')
expect(el.querySelector('button')).toHaveAttribute('aria-description', 'Locked by a manual pick')
})
expect(el.querySelector('.cmd-lock')).not.toBeNull()
expect(el.querySelector('button')).toHaveAttribute('aria-disabled', 'true')
expect(el.querySelector('button')).toHaveClass('btn-danger')
el.querySelector('button')?.click()
@ -69,7 +71,7 @@ describe('<command-button>', () => {
expect(el.querySelector('a')).not.toBeNull()
})
const link = must(el.querySelector('a'))
expect(link).toHaveTextContent('Open Status')
expect(link).toHaveAttribute('aria-label', 'Open Status')
expect(link).toHaveAttribute('href', '/')
expect(link).toHaveClass('btn-primary')
})
@ -78,7 +80,7 @@ describe('<command-button>', () => {
loaded([makeSpec('scan')])
const el = mount('<command-button name="scan"></command-button>')
await vi.waitFor(() => {
expect(el.querySelector('button')).toHaveTextContent('Run scan')
expect(el.querySelector('button')).toHaveAttribute('aria-label', 'Run scan')
})
el.querySelector('button')?.click()
expect(requests).toEqual([{ name: 'scan' }])
@ -109,9 +111,9 @@ describe('<command-card>', () => {
loaded([makeSpec('gaming-reset', { privileged: true, friction: { phrase_template: 'x', countdown_seconds: 300 } })])
const el = mount('<command-card name="gaming-reset"></command-card>')
await vi.waitFor(() => {
expect(el).toHaveTextContent('root')
expect(el.querySelector('[aria-label="root"]')).not.toBeNull()
})
expect(el).toHaveTextContent('countdown')
expect(el.querySelector('[aria-label="countdown"]')).not.toBeNull()
})
it('shows no countdown pill for a friction command without one', async () => {

View File

@ -9,8 +9,7 @@ import { q } from '../api/queries'
import { define, h, jsonAttr } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { pageHref, runner, type Preset } from '../lib/runner'
import { pill } from '../ui/build'
import { COMMAND_HOME, commandLabel, findCommand } from './catalog'
import { COMMAND_HOME, COMMAND_ICON, commandLabel, findCommand } from './catalog'
export interface ButtonProps {
name: CommandName
@ -34,23 +33,35 @@ function props(el: Element): ButtonProps {
export function commandButton({ name, preset, label, tone = 'ghost' }: ButtonProps): HTMLElement {
const spec = findCommand(q.commands.state.data, name)
const locked = spec?.locked_reason ?? null
const text = label ?? (spec?.kind === 'job' ? `Run ${name}` : `Open ${commandLabel(name)}`)
if (spec && spec.kind !== 'job') return h('a', { href: pageHref(COMMAND_HOME[name]), class: `btn btn-${tone}` }, text)
// Textgate: the glyph is painted, the label is spoken only.
const spoken = label ?? (spec?.kind === 'job' ? `Run ${name}` : `Open ${commandLabel(name)}`)
const glyph = h('span', { class: 'cmd-icon', 'aria-hidden': 'true' }, COMMAND_ICON[name])
if (spec && spec.kind !== 'job') {
return h('a', { href: pageHref(COMMAND_HOME[name]), class: `btn btn-${tone}`, 'aria-label': spoken }, glyph)
}
return h(
'button',
{
type: 'button',
class: `btn btn-${tone}`,
'aria-label': spoken,
'aria-disabled': String(locked !== null || !spec),
title: locked,
// The lock reason is spoken (no hover tooltip: textgate R7); 🔒 paints it.
'aria-description': locked,
onclick: () => {
if (spec && !locked) runner.run(name, preset)
},
},
text,
glyph,
locked === null ? null : h('span', { class: 'cmd-lock', 'aria-hidden': 'true' }, '🔒'),
)
}
/** A card flag (root, countdown): glyph painted, its word spoken. */
function flag(glyph: string, spoken: string): HTMLSpanElement {
return h('span', { class: 'pill pill-neutral', 'aria-label': spoken, role: 'img' }, glyph)
}
export class CommandButtonElement extends LiveElement {
protected override setup(): void {
this.watch(q.commands)
@ -77,11 +88,11 @@ export class CommandCardElement extends LiveElement {
h(
'h3',
{ class: 'cmd-name' },
commandLabel(p.name),
spec?.privileged ? pill('neutral', 'root') : null,
spec?.friction?.countdown_seconds ? pill('warning', 'countdown') : null,
h('span', { class: 'sr-only' }, commandLabel(p.name)),
spec?.privileged ? flag('🔑', 'root') : null,
spec?.friction?.countdown_seconds ? flag('⏳', 'countdown') : null,
),
h('p', { class: 'cmd-desc' }, locked ?? spec?.description ?? '…'),
h('p', { class: 'cmd-desc sr-only' }, locked ?? spec?.description ?? '…'),
commandButton(p),
),
)

View File

@ -28,7 +28,9 @@ function open(specs = SPECS) {
const box = () => must(document.querySelector<HTMLInputElement>('[role=combobox]'))
const options = () => [...document.querySelectorAll<HTMLElement>('[role=option]')]
const active = () => options().findIndex((o) => o.getAttribute('aria-selected') === 'true')
const opt = (title: string) => must(options().find((o) => o.querySelector('.palette-title')?.firstChild?.textContent === title))
/** The option whose spoken title (the glyph's sr-only label) is `title`. */
const opt = (title: string) => must(options().find((o) => o.querySelector('.palette-title .glyph .sr-only')?.textContent === title))
const hint = (o: HTMLElement) => must(o.querySelector('.palette-hint'))
const key = (k: string) => box().dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }))
const loaded = () => vi.waitFor(() => {
expect(options().length).toBeGreaterThan(0)
@ -51,12 +53,13 @@ describe('CommandPaletteElement', () => {
await loaded()
expect(el.isOpen).toBe(true)
expect(options()).toHaveLength(TOTAL)
expect(opt('Scan')).toHaveTextContent('run')
expect(opt('Unblock')).toHaveTextContent('run · confirm')
expect(opt('Status')).toHaveTextContent('open /')
expect(opt('Pick')).toHaveTextContent('locked')
expect(opt('Pick')).toHaveTextContent('Locked by a pick')
expect(hint(opt('Scan'))).toHaveTextContent('▶️run')
expect(hint(opt('Unblock'))).toHaveTextContent('▶️⌨️run · confirm')
expect(hint(opt('Status'))).toHaveTextContent('↗️open /')
expect(opt('Pick').querySelector('.pill')).toHaveTextContent('🔒locked')
expect(opt('Pick').querySelector('.palette-detail')).toHaveTextContent('Locked by a pick')
expect(opt('Pick')).not.toHaveTextContent('Pick next.')
expect(opt('Scan').querySelector('.palette-detail')).toHaveTextContent('Scan achievements.')
expect(document.body).toHaveTextContent('Go to Dashboard')
expect(document.activeElement).toBe(box())
})

View File

@ -8,15 +8,19 @@ import { define, h } from '../lib/dom'
import { uid } from '../lib/ids'
import { pageHref, runner } from '../lib/runner'
import { NAV } from '../shell/nav'
import { errorNotice, loading, pill } from '../ui/build'
import { empty, errorNotice, glyph, loading, pill } from '../ui/build'
import { Modal } from '../ui/dialog'
import { COMMAND_HOME, commandLabel } from './catalog'
import { COMMAND_HOME, COMMAND_ICON, commandLabel } from './catalog'
interface Entry {
key: string
title: string
detail: string
hint: string
/** Painted in place of the title (textgate). */
icon: string
/** Painted in place of the hint: ▶️ run, ↗️ open, 🧭 navigate. */
hintIcon: string
locked: string | null
act: () => void
}
@ -45,7 +49,7 @@ export class CommandPaletteElement extends HTMLElement {
'aria-expanded': 'true',
'aria-controls': `${this.listId}-list`,
'aria-label': 'Search commands',
placeholder: 'Type a command or section…',
placeholder: '🔍',
autofocus: true,
})
this.list = h('ul', { id: `${this.listId}-list`, role: 'listbox', class: 'palette-list', 'aria-label': 'Commands' })
@ -56,7 +60,12 @@ export class CommandPaletteElement extends HTMLElement {
this.input.addEventListener('keydown', (e) => {
this.onKey(e)
})
this.modal.render(this.input, this.status, this.list, h('p', { class: 'field-help' }, '↑↓ to move · Enter to run · Esc to close'))
this.modal.render(this.input, this.status, this.list, h(
'p',
{ class: 'field-help' },
h('span', { 'aria-hidden': 'true' }, '↑↓ · ⏎ · ⎋'),
h('span', { class: 'sr-only' }, '↑↓ to move · Enter to run · Esc to close'),
))
}
get isOpen(): boolean {
@ -108,6 +117,8 @@ export class CommandPaletteElement extends HTMLElement {
title: commandLabel(c.name),
detail: c.description,
hint: c.kind === 'job' ? (c.friction ? 'run · confirm' : 'run') : `open ${COMMAND_HOME[c.name]}`,
icon: COMMAND_ICON[c.name],
hintIcon: c.kind === 'job' ? (c.friction ? '▶️⌨️' : '▶️') : '↗️',
locked: c.locked_reason,
act: () => {
if (c.kind === 'job') runner.run(c.name)
@ -122,6 +133,8 @@ export class CommandPaletteElement extends HTMLElement {
title: `Go to ${n.label}`,
detail: n.blurb,
hint: 'navigate',
icon: n.icon,
hintIcon: '🧭',
locked: null,
act: () => {
this.close()
@ -143,9 +156,10 @@ export class CommandPaletteElement extends HTMLElement {
const li = h(
'li',
{ id: `${this.listId}-${i}`, role: 'option', 'aria-selected': String(i === this.active), class: i === this.active ? 'palette-item active' : 'palette-item' },
h('span', { class: 'palette-title' }, e.title, e.locked ? pill('warning', 'locked') : null),
h('span', { class: 'palette-detail' }, e.locked ?? e.detail),
h('span', { class: 'palette-hint' }, e.hint),
// Textgate: glyphs painted; title, detail and hint spoken only.
h('span', { class: 'palette-title' }, glyph(e.icon, e.title), e.locked ? pill('warning', 'locked', '🔒') : null),
h('span', { class: 'palette-detail sr-only' }, e.locked ?? e.detail),
h('span', { class: 'palette-hint' }, glyph(e.hintIcon, e.hint)),
)
li.addEventListener('mousemove', () => {
if (this.active !== i) this.setActive(i)
@ -154,7 +168,7 @@ export class CommandPaletteElement extends HTMLElement {
return li
}),
)
if (this.shown.length === 0) this.list.append(h('li', { class: 'empty' }, `No command matches “${this.input.value}”.`))
if (this.shown.length === 0) this.list.append(h('li', {}, empty(`No command matches “${this.input.value}”.`)))
this.syncActive()
}

View File

@ -26,7 +26,9 @@ function make(over: { specs?: ParamSpec[]; values?: ParamValues; disabled?: bool
}
function labelFor(text: RegExp | string): string {
const label = [...document.querySelectorAll('label')].find((l) => (typeof text === 'string' ? l.textContent === text : text.test(l.textContent)))
// The spoken label sits in an sr-only span; the painted part is a glyph.
const spoken = (l: HTMLLabelElement) => l.querySelector('.sr-only')?.textContent ?? ''
const label = [...document.querySelectorAll('label')].find((l) => (typeof text === 'string' ? spoken(l) === text : text.test(spoken(l))))
return label?.getAttribute('for') ?? ''
}
@ -37,7 +39,9 @@ describe('ParamsForm', () => {
expect(input(/Game/)).toHaveAttribute('inputmode', 'numeric')
expect(input(/Game/)).toHaveAttribute('autofocus')
expect(input(/Game/)).toBeRequired()
expect(document.body).toHaveTextContent('Game *')
expect(document.querySelector(`label[for="${input(/Game/).id}"]`)).toHaveTextContent('Game *')
expect(document.querySelector(`label[for="${input(/Game/).id}"] [aria-hidden]`)).toHaveTextContent('🎮')
expect(document.querySelector(`label[for="${input('Days').id}"]`)).not.toHaveTextContent('*')
expect(input('Days')).toHaveAttribute('type', 'number')
expect(input('Days')).toHaveAttribute('min', '1')
expect(input('Days')).toHaveAttribute('max', '9')
@ -129,6 +133,6 @@ describe('ParamsForm', () => {
const box: ParamSpec[] = [{ name: 'on', label: 'On', type: 'bool', required: false }]
const { input } = make({ specs: box, values: {} })
expect(input('On')).not.toBeChecked()
expect(document.querySelector('.field-help')?.textContent).toBe(' ')
expect(document.querySelector('.field-help')?.textContent).toBe('')
})
})

View File

@ -7,6 +7,34 @@ import { h } from '../lib/dom'
import { uid } from '../lib/ids'
import { paramError, type GameOption, type ParamValues } from './params'
/** Painted glyph per parameter (textgate); the catalog label is spoken only. */
const PARAM_ICON: Record<string, string> = {
app_id: '🎮',
backup_id: '🗄️',
days: '📅',
minutes: '⏱️',
reason: '💬',
replace: '🔁',
demo: '🧪',
}
function paramGlyph(spec: ParamSpec): HTMLSpanElement {
return h(
'span',
{},
h('span', { 'aria-hidden': 'true' }, PARAM_ICON[spec.name] ?? '✏️'),
h('span', { class: 'sr-only' }, spec.label),
)
}
/** Field help: optional painted mark, sentence spoken only. */
function spokenHelp(el: HTMLElement, mark: string | null, sentence: string): void {
el.replaceChildren(
mark ? h('span', { 'aria-hidden': 'true' }, mark) : '',
sentence ? h('span', { class: 'sr-only' }, sentence) : '',
)
}
interface Field {
wrap: HTMLDivElement
spec: ParamSpec
@ -64,7 +92,7 @@ export class ParamsForm {
input.addEventListener('change', () => {
emit(input.checked ? '1' : '0')
})
const wrap = h('div', { class: 'form-field' }, h('label', { class: 'check', for: id }, input, spec.label), help)
const wrap = h('div', { class: 'form-field' }, h('label', { class: 'check', for: id }, input, paramGlyph(spec)), help)
return { wrap, spec, input, help, datalist: null }
}
const numeric = spec.type !== 'string'
@ -89,7 +117,7 @@ export class ParamsForm {
const wrap = h(
'div',
{ class: 'form-field' },
h('label', { for: id, class: 'field-label' }, spec.label, spec.required ? h('span', { 'aria-hidden': 'true' }, ' *') : null),
h('label', { for: id, class: 'field-label' }, paramGlyph(spec), spec.required ? h('span', { 'aria-hidden': 'true' }, ' *') : null),
input,
datalist,
help,
@ -99,7 +127,7 @@ export class ParamsForm {
private refreshField({ spec, input, help, datalist }: Field): void {
if (spec.type === 'bool') {
help.textContent = spec.help ?? ' '
spokenHelp(help, null, spec.help ?? '')
return
}
const raw = this.values[spec.name] ?? ''
@ -109,11 +137,11 @@ export class ParamsForm {
input.setAttribute('aria-invalid', String(bad))
help.className = bad ? 'field-help text-danger' : 'field-help'
const game = spec.type === 'app_id' ? this.games.find((g) => g.app_id === Number(raw)) : undefined
help.textContent = bad
? err
: game
? game.name
: (spec.help ?? (spec.type === 'app_id' ? 'Type an app id or pick a game from the list.' : ' '))
// Textgate: an error paints ⚠️, a matched game paints its name (content);
// the error sentence and the field help are spoken only.
if (bad) spokenHelp(help, '⚠️', err)
else if (game) help.replaceChildren(game.name)
else spokenHelp(help, null, spec.help ?? (spec.type === 'app_id' ? 'Type an app id or pick a game from the list.' : ''))
if (datalist && datalist.childElementCount !== this.games.length) {
datalist.replaceChildren(...this.games.map((g) => h('option', { value: g.app_id }, g.name)))
}

View File

@ -38,7 +38,10 @@ describe('PendingCountdown', () => {
await tick(10_000)
expect(text()).toContain('0:21')
expect(el.querySelector('[role=progressbar]')).toHaveAttribute('aria-valuenow', '32')
expect(text()).toContain('Closing this dialog')
expect(el.querySelector('.notice-warning')).toHaveAttribute(
'aria-label',
'Closing this dialog, navigating away or closing the tab cancels the countdown.',
)
expect(button(el, 'Cancel countdown')).toHaveAttribute('autofocus')
})

View File

@ -21,6 +21,13 @@ import { PhraseField } from './phraseField'
*/
export const CLOCK_SLACK_MS = 1000
/** ⚠️ 🚪: leaving cancels the countdown; the sentence is spoken only. */
function stayNotice(): HTMLDivElement {
const el = notice('warning', null, h('span', { 'aria-hidden': 'true' }, '🚪✖️'))
el.setAttribute('aria-label', 'Closing this dialog, navigating away or closing the tab cancels the countdown.')
return el
}
export interface CountdownCallbacks {
onCommitted: (job: Job) => void
onCancel: () => void
@ -102,7 +109,7 @@ export class PendingCountdown {
this.el.className = 'stack'
this.el.replaceChildren(
errorNotice(this.beatError),
h('div', { class: 'actions' }, h('button', { type: 'button', class: 'btn btn-primary', autofocus: true, onclick: this.cb.onRearm }, 'Arm again')),
h('div', { class: 'actions' }, h('button', { type: 'button', class: 'btn btn-primary', autofocus: true, 'aria-label': 'Arm again', onclick: this.cb.onRearm }, '🔁')),
)
this.el.querySelector<HTMLElement>('[autofocus]')?.focus()
return
@ -113,11 +120,23 @@ export class PendingCountdown {
const left = Math.max(0, (ready - now) / 1000)
const isReady = left <= 0
this.parts.num.textContent = clock(left)
this.parts.caption.textContent = isReady ? 'Ready to commit' : 'until commit unlocks'
// Textgate: 🔓/🔒 painted beside the clock; 💓 + seconds since the last
// heartbeat (red 💔 when failing). Sentences are spoken only.
this.parts.caption.replaceChildren(
h('span', { 'aria-hidden': 'true' }, isReady ? '🔓' : '🔒'),
h('span', { class: 'sr-only' }, isReady ? 'Ready to commit' : 'until commit unlocks'),
)
this.parts.bar.replaceChildren(progressBar(Math.min(1, (now - armed) / (ready - armed)), 'Countdown', isReady ? 'success' : 'warning'))
const sinceBeat = Math.round((now - this.lastBeat) / 1000)
const failing = this.beatError !== null
this.parts.beat.replaceChildren(
`Keep this window open. Heartbeat every ${Math.round(this.pending.heartbeat_interval_seconds / 2)} s · last ${Math.round((now - this.lastBeat) / 1000)} s ago`,
this.beatError !== null ? h('span', { class: 'text-danger' }, ' · heartbeat failing, retrying') : '',
h('span', { 'aria-hidden': 'true', class: failing ? 'text-danger' : '' }, `${failing ? '💔' : '💓'} ${sinceBeat}s`),
h(
'span',
{ class: 'sr-only' },
`Keep this window open. Heartbeat every ${Math.round(this.pending.heartbeat_interval_seconds / 2)} s · last ${sinceBeat} s ago`,
failing ? ' · heartbeat failing, retrying' : '',
),
)
this.parts.live.textContent = isReady ? 'Countdown finished. Retype the phrase to commit.' : ''
if (isReady !== this.shownReady) this.renderBody(isReady)
@ -128,11 +147,15 @@ export class PendingCountdown {
this.shownReady = isReady
if (!isReady) {
this.parts.body.replaceChildren(
notice('warning', null, 'Closing this dialog, navigating away or closing the tab cancels the countdown.'),
stayNotice(),
h(
'div',
{ class: 'actions' },
h('button', { type: 'button', class: 'btn btn-ghost', autofocus: true, onclick: () => void this.doCancel() }, this.cancel.pending ? 'Cancelling…' : 'Cancel countdown'),
h(
'button',
{ type: 'button', class: 'btn btn-ghost', autofocus: true, 'aria-label': this.cancel.pending ? 'Cancelling…' : 'Cancel countdown', onclick: () => void this.doCancel() },
this.cancel.pending ? '⏳' : '✖️',
),
),
)
return
@ -153,7 +176,7 @@ export class PendingCountdown {
{ class: 'stack' },
this.phrase.el,
errorSlot,
h('div', { class: 'actions' }, submitBtn, h('button', { type: 'button', class: 'btn btn-ghost', onclick: () => void this.doCancel() }, 'Cancel')),
h('div', { class: 'actions' }, submitBtn, h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'Cancel', onclick: () => void this.doCancel() }, '✖️')),
)
form.addEventListener('submit', (e) => {
e.preventDefault()
@ -165,7 +188,8 @@ export class PendingCountdown {
}
const { submit, errors } = this.commitForm as { submit: HTMLButtonElement; errors: HTMLDivElement }
submit.disabled = !phraseMatches(this.pending.phrase, this.phrase.value) || this.commit.pending
submit.textContent = this.commit.pending ? 'Committing…' : 'Commit'
submit.textContent = this.commit.pending ? '⏳' : '✔️'
submit.setAttribute('aria-label', this.commit.pending ? 'Committing…' : 'Commit')
errors.replaceChildren(...(this.commit.error ? [errorNotice(this.commit.error)] : []))
}

View File

@ -57,7 +57,9 @@ describe('PhraseField', () => {
const { field, input } = make({ autofocus: true })
expect(field.el.querySelector('label')).toHaveTextContent('Type the phrase to confirm')
expect(field.el.querySelector('label')).toHaveAttribute('for', input.id)
expect(field.el.querySelector('.sr-only')).toHaveTextContent('Phrase: reset it')
expect(field.el.querySelector('label .sr-only')).toHaveTextContent('Type the phrase to confirm')
expect(field.el.querySelector('label [aria-hidden]')).toHaveTextContent('⌨️')
expect(field.el.querySelector('p.sr-only')).toHaveTextContent('Phrase: reset it')
expect(input).toHaveAttribute('autofocus')
expect(make({ label: 'Again' }).field.el.querySelector('label')).toHaveTextContent('Again')
expect(make().input).not.toHaveAttribute('autofocus')

View File

@ -48,7 +48,7 @@ export class PhraseField {
this.el = h(
'div',
{ class: 'phrase' },
h('label', { for: id, class: 'field-label' }, label),
h('label', { for: id, class: 'field-label' }, h('span', { 'aria-hidden': 'true' }, '⌨️'), h('span', { class: 'sr-only' }, label)),
this.target,
this.input,
h('p', { class: 'sr-only' }, `Phrase: ${phrase}`),
@ -71,10 +71,12 @@ export class PhraseField {
this.input.className = `input mono ${ok ? 'input-ok' : prefixOk ? '' : 'input-bad'}`.trim()
this.input.setAttribute('aria-invalid', String(!prefixOk))
this.status.className = `field-help ${ok ? 'text-success' : prefixOk ? '' : 'text-danger'}`.trim()
this.status.textContent = ok
? 'Matches.'
// Textgate: ✅ / count / ❌ painted; the sentence is spoken only.
const [mark, spoken] = ok
? ['✅', 'Matches.']
: prefixOk
? `${typed.length} of ${this.phrase.length} characters`
: 'Does not match — check case and spacing.'
? [`${typed.length}/${this.phrase.length}`, `${typed.length} of ${this.phrase.length} characters`]
: ['❌', 'Does not match — check case and spacing.']
this.status.replaceChildren(h('span', { 'aria-hidden': 'true' }, mark), h('span', { class: 'sr-only' }, spoken))
}
}

View File

@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { q } from '../api/queries'
import { makeSpec } from '../test/fixtures'
import { submit } from '../test/events'
import { must, submit } from '../test/events'
import { apiError, Reply } from '../test/harness'
import { field, found, openRunner, text } from '../test/runnerHelpers'
@ -18,7 +18,10 @@ describe('<runner-dialog> locked', () => {
})
openRunner([spec], 'pick')
const run = await found('Run pick')
expect(text()).toContain('Manual pick active')
// The reason is spoken only; 🔒 is painted in the notice.
const lock = must(document.querySelector('.notice-warning'))
expect(lock).toHaveAttribute('aria-label', 'Locked: Manual pick active')
expect(lock).toHaveTextContent('🔒')
expect(field('N')).toBeDisabled()
expect(document.querySelector('.phrase')).toBeNull()
expect(run).toBeDisabled()
@ -38,7 +41,10 @@ describe('<runner-dialog> start failures', () => {
it('offers the sudo fallback when the daemon is down', async () => {
openRunner([makeSpec('gaming-unblock')], 'gaming-unblock', { extra: { 'POST /api/jobs': apiError(502, 'daemon_unreachable') } })
submit(await found('Run gaming-unblock'))
await waitText('Run it from a terminal instead:')
await vi.waitFor(() => {
expect(document.querySelector('[data-code="daemon_unreachable"] p')).toHaveAttribute('aria-label', 'Run it from a terminal instead:')
})
expect(document.querySelector('[data-code="daemon_unreachable"] p')).toHaveTextContent('💻')
expect(text()).toContain('sudo ./run.sh gaming-unblock')
})

View File

@ -24,8 +24,14 @@ describe('<runner-dialog> catalog states', () => {
it('says so when the server does not offer the command', async () => {
openRunner([makeSpec('done')], 'scan')
await waitText('Not in the server catalog')
expect(text()).toContain('does not offer "scan"')
// Spoken only; the command's glyph is painted beside ⛔.
await vi.waitFor(() => {
expect(document.querySelector('.notice-danger')).toHaveAttribute(
'aria-label',
'Not in the server catalog: the server does not offer "scan".',
)
})
expect(document.querySelector('.notice-danger')).toHaveTextContent('🔎')
})
it('titles the dialog with the command label', async () => {
@ -136,7 +142,7 @@ describe('<runner-dialog> parameters', () => {
await found('Close (job keeps running)')
q.dataset.invalidate()
await vi.waitFor(() => { expect(q.dataset.state.loading).toBe(false) })
expect(text()).toContain('Open in Jobs')
expect(document.querySelector('a[aria-label="Open in Jobs"]')).toHaveAttribute('href', '/jobs/?id=j1')
})
})
@ -149,7 +155,10 @@ describe('<runner-dialog> friction', () => {
it('shows the exact phrase once its fields are known, and sends it', async () => {
const { mock } = openRunner([spec], 'uninstall', { extra: { 'POST /api/jobs': makeJob({ id: 'j1' }) } })
const run = await found('Run uninstall')
expect(text()).toMatch(/Fill in the fields above to see the exact phrase \(game_name\)/)
expect(document.querySelector('.notice-info')).toHaveAttribute(
'aria-label',
'Fill in the fields above to see the exact phrase (game_name).',
)
setValue(field(/Game/), '7')
await vi.waitFor(() => { expect(phraseInput()).toBeInTheDocument() })
expect(run).toBeDisabled()

View File

@ -9,7 +9,7 @@ import { define, h, hx } from '../lib/dom'
import { runner, jobHref, type RunRequest } from '../lib/runner'
import { errorNotice, loading, notice } from '../ui/build'
import { Modal } from '../ui/dialog'
import { commandLabel, findCommand } from './catalog'
import { COMMAND_ICON, commandLabel, findCommand } from './catalog'
import type { PendingCountdown } from './pendingCountdown'
import { Runner, type NextPhase } from './runnerForm'
@ -94,7 +94,12 @@ export class RunnerDialogElement extends HTMLElement {
return
}
if (error) this.modal.render(errorNotice(error))
else if (commands) this.modal.render(notice('danger', 'Not in the server catalog', `The server does not offer "${req.name}".`))
else if (commands) {
// ⛔ + the command's glyph; the sentence is spoken only.
const el = notice('danger', null, h('span', { 'aria-hidden': 'true' }, COMMAND_ICON[req.name]))
el.setAttribute('aria-label', `Not in the server catalog: the server does not offer "${req.name}".`)
this.modal.render(el)
}
else this.modal.render(loading('commands'))
}
@ -111,8 +116,8 @@ export class RunnerDialogElement extends HTMLElement {
h(
'div',
{ class: 'actions' },
h('button', { type: 'button', class: 'btn btn-ghost', onclick: () => { this.close() } }, 'Close (job keeps running)'),
h('a', { href: jobHref(next.id), class: 'btn btn-ghost' }, 'Open in Jobs'),
h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'Close (job keeps running)', onclick: () => { this.close() } }, '✖️'),
h('a', { href: jobHref(next.id), class: 'btn btn-ghost', 'aria-label': 'Open in Jobs' }, '⚙️'),
),
),
)

View File

@ -9,7 +9,7 @@ import { Action } from '../lib/action'
import { h } from '../lib/dom'
import type { Preset } from '../lib/runner'
import { commandLine, errorNotice, notice, pill } from '../ui/build'
import { fillPhrase, phraseMatches } from './catalog'
import { COMMAND_ICON, fillPhrase, phraseMatches } from './catalog'
import { enforcePreset } from './enforcePreset'
import { gameLookup } from './gameLookup'
import { initialValues, paramError, toParams, type ParamValues } from './params'
@ -23,6 +23,22 @@ const FALLBACK: Partial<Record<CommandName, string>> = {
}
/** ⏳ plus the minutes (a number, so painted); the word is spoken only. */
function countdownPill(seconds: number): HTMLSpanElement {
const minutes = Math.round(seconds / 60)
const el = pill('warning', `${minutes} min countdown`, '⏳')
el.append(h('span', { class: 'pill-num', 'aria-hidden': 'true' }, `${minutes}′`))
return el
}
/** 🔒 warning notice; the server's lock reason is spoken only. */
function lockedNotice(reason: string): HTMLDivElement {
const el = notice('warning', null)
el.querySelector('.notice-icon')?.replaceChildren('🔒')
el.setAttribute('aria-label', `Locked: ${reason}`)
return el
}
export type NextPhase = { k: 'pending'; countdown: PendingCountdown } | { k: 'job'; id: string } | { k: 'form'; runner: Runner }
export interface RunnerCallbacks {
@ -77,16 +93,18 @@ export class Runner {
this.el = h(
'form',
{ class: 'stack', novalidate: true },
h('p', { class: 'm0' }, spec.description),
// Textgate: the description and every tag are spoken only; each tag paints its own glyph.
h('p', { class: 'm0 sr-only' }, spec.description),
h(
'div',
{ class: 'tags' },
spec.privileged ? pill('neutral', 'Runs as root via the daemon') : null,
pill('neutral', spec.mutating ? 'Changes state' : 'Read-only'),
spec.cancellable ? pill('neutral', 'Cancellable') : null,
countdown ? pill('warning', `${Math.round(countdown / 60)} min countdown`) : null,
h('span', { class: 'runner-glyph', 'aria-hidden': 'true' }, COMMAND_ICON[spec.name]),
spec.privileged ? pill('neutral', 'Runs as root via the daemon', '🔑') : null,
spec.mutating ? pill('neutral', 'Changes state', '✏️') : pill('neutral', 'Read-only', '👁️'),
spec.cancellable ? pill('neutral', 'Cancellable', '⏹️') : null,
countdown ? countdownPill(countdown) : null,
),
spec.locked_reason !== null ? notice('warning', 'Locked', spec.locked_reason) : null,
spec.locked_reason !== null ? lockedNotice(spec.locked_reason) : null,
this.form.nodes,
this.phraseSlot,
this.errorSlot,
@ -94,7 +112,7 @@ export class Runner {
'div',
{ class: 'actions' },
this.submitBtn,
h('button', { type: 'button', class: 'btn btn-ghost', onclick: () => { cb.onClose() } }, 'Cancel'),
h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'Cancel', onclick: () => { cb.onClose() } }, '✖️'),
),
)
this.el.addEventListener('submit', (e) => {
@ -140,7 +158,10 @@ export class Runner {
if (key !== this.phraseKey) {
this.phraseKey = key
if (phrase && phrase.missing.length > 0) {
this.phraseSlot.replaceChildren(notice('info', null, `Fill in the fields above to see the exact phrase (${phrase.missing.join(', ')}).`))
// ℹ️ ⬆️: fill the fields above first; the sentence is spoken only.
const hint = notice('info', null, h('span', { 'aria-hidden': 'true' }, '⬆️'))
hint.setAttribute('aria-label', `Fill in the fields above to see the exact phrase (${phrase.missing.join(', ')}).`)
this.phraseSlot.replaceChildren(hint)
} else if (phrase && !locked) {
this.typed = ''
const field = new PhraseField({
@ -165,7 +186,7 @@ export class Runner {
errorNotice(
err,
failure?.code === 'daemon_unreachable' && fallback
? [h('p', { class: 'm0' }, 'Run it from a terminal instead:'), commandLine(fallback)]
? [h('p', { class: 'm0', 'aria-label': 'Run it from a terminal instead:' }, h('span', { 'aria-hidden': 'true' }, '💻')), commandLine(fallback)]
: null,
),
]
@ -174,7 +195,9 @@ export class Runner {
const countdown = this.spec.friction?.countdown_seconds
this.submitBtn.className = phrase ? 'btn btn-danger' : 'btn btn-primary'
this.submitBtn.disabled = !this.canSubmit() || this.start.pending
this.submitBtn.textContent = this.start.pending ? 'Starting…' : countdown ? 'Arm countdown' : `Run ${this.spec.name}`
// Glyph painted, label spoken: ⏳ starting, ⏲️ arm countdown, ▶️ run.
this.submitBtn.textContent = this.start.pending ? '⏳' : countdown ? '⏲️' : '▶️'
this.submitBtn.setAttribute('aria-label', this.start.pending ? 'Starting…' : countdown ? 'Arm countdown' : `Run ${this.spec.name}`)
}
private async submit(): Promise<void> {

View File

@ -7,11 +7,11 @@
import { api } from '../api/client'
import type { JobProgress as Progress, JobState } from '../api/jobContract'
import { q } from '../api/queries'
import { commandLabel, findCommand } from '../commands/catalog'
import { COMMAND_ICON, commandLabel, findCommand } from '../commands/catalog'
import { Action } from '../lib/action'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { errorNotice, notice } from '../ui/build'
import { errorNotice, glyph, notice } from '../ui/build'
import { clock, duration } from '../ui/format'
import { hub, type LiveJob } from './hub'
import { progressBar, stateBadge } from './progress'
@ -130,7 +130,8 @@ export class JobProgressElement extends LiveElement {
f.section.className = compact ? 'job job-compact' : 'job'
f.section.dataset.state = state
f.section.setAttribute('aria-label', `Job ${job ? commandLabel(job.command) : id}`)
f.title.textContent = title
// Textgate: the command's glyph painted, its name spoken.
f.title.replaceChildren(...(job ? [glyph(COMMAND_ICON[job.command], title)] : []))
f.badge.replaceChildren(stateBadge(state))
f.meta.replaceChildren(
job ? duration(job.started_at, job.ended_at, now) : '',
@ -141,11 +142,14 @@ export class JobProgressElement extends LiveElement {
{ class: live.connected ? 'dot dot-live' : 'dot dot-off', role: 'img', 'aria-label': live.connected ? 'Live' : 'Reconnecting' },
),
)
// The server's phase sentence is spoken only; the bar, step count and
// state glyph carry it on screen.
f.phase.replaceChildren(
h(
'span',
{ class: 'job-label' },
isDone(state) ? DONE_LABEL[state] : waiting ? '⏳' : (progress?.label ?? ''),
isDone(state) ? DONE_LABEL[state] : waiting ? '⏳' : progress ? '▶️' : '',
progress?.label && !finished ? h('span', { class: 'sr-only' }, progress.label) : null,
),
!finished && progress && progress.total !== null
? h('span', { class: 'job-step' }, `${progress.step}/${progress.total}`)
@ -171,7 +175,7 @@ export class JobProgressElement extends LiveElement {
this.updatePrompt(f, live, state)
f.result.replaceChildren(
...(live.result
? [notice(live.result.ok ? 'success' : 'danger', null, live.result.summary)]
? [notice(live.result.ok ? 'success' : 'danger', null, h('span', { class: 'sr-only' }, live.result.summary))]
: []),
)
f.actions.replaceChildren(

View File

@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import type { PromptEvent } from './hub'
import { promptForm } from './promptForm'
const choice = (options: { value: string; label: string }[]): PromptEvent => ({
seq: 1, ts: 't', type: 'prompt', prompt_id: 'q1', kind: 'choice', message: 'Which one?', options,
})
describe('choice prompt own-game escape', () => {
it('paints the escape as a glyph and speaks its label; game names stay plain text', () => {
const form = promptForm('j', choice([{ value: 'a', label: 'Alpha' }, { value: 'own', label: 'Pick my own game' }]))
document.body.append(form)
const own = form.querySelector('[data-value=own] .choice-label')
expect(own?.querySelector('[aria-hidden="true"]')?.textContent).toBe('🗂️')
expect(own?.querySelector('.sr-only')?.textContent).toBe('Pick my own game')
expect(form.querySelector('[data-value=a] .choice-label')?.textContent).toBe('Alpha')
})
})

View File

@ -10,9 +10,15 @@ import { PhraseField } from '../commands/phraseField'
import { Action } from '../lib/action'
import { h, hx } from '../lib/dom'
import type { GameBrowserElement } from '../library/pick'
import { errorNotice } from '../ui/build'
import { errorNotice, glyph } from '../ui/build'
import { hub, type PromptEvent } from './hub'
/** A glyph-only button: `icon` painted, `spoken` its accessible name. */
function sendButton(btn: HTMLButtonElement, spoken: string, icon: string): void {
btn.setAttribute('aria-label', spoken)
btn.textContent = icon
}
function answerAction(jobId: string, prompt: PromptEvent, onChange: () => void): Action<[string], void> {
return new Action(async (value: string) => {
await api.answer(jobId, { prompt_id: prompt.prompt_id, value })
@ -34,7 +40,8 @@ function answerForm(jobId: string, prompt: PromptEvent): HTMLFormElement {
const submit = (v: string = value) => {
void send.run(v)
}
const form = h('form', { class: 'prompt', 'aria-label': 'Job question' }, h('p', { class: 'prompt-msg' }, prompt.message))
// Textgate: the server's question is spoken; ❓ marks that the job waits on you.
const form = h('form', { class: 'prompt', 'aria-label': 'Job question' }, h('p', { class: 'prompt-msg' }, glyph('❓', prompt.message)))
form.addEventListener('submit', (e) => {
e.preventDefault()
if (ready()) submit()
@ -57,8 +64,9 @@ function answerForm(jobId: string, prompt: PromptEvent): HTMLFormElement {
'label',
{ class: 'choice' },
radio,
h('span', { class: 'choice-label' }, o.label),
o.detail ? h('span', { class: 'choice-detail' }, o.detail) : null,
// Option labels are game names (content); the "own game" escape is a glyph.
o.value === 'own' ? glyph('🗂️', o.label, 'choice-label') : h('span', { class: 'choice-label' }, o.label),
o.detail ? h('span', { class: 'choice-detail sr-only' }, o.detail) : null,
)
label.dataset.value = o.value
labels.push(label)
@ -95,14 +103,14 @@ function answerForm(jobId: string, prompt: PromptEvent): HTMLFormElement {
errorSlot.replaceChildren(...(send.error ? [errorNotice(send.error)] : []))
if (prompt.kind === 'confirm') {
actions.replaceChildren(
h('button', { type: 'button', class: 'btn btn-primary', autofocus: prompt.default !== 'no', disabled: send.pending, onclick: () => { submit('yes') } }, 'Yes'),
h('button', { type: 'button', class: 'btn btn-ghost', autofocus: prompt.default === 'no', disabled: send.pending, onclick: () => { submit('no') } }, 'No'),
h('button', { type: 'button', class: 'btn btn-primary', 'aria-label': 'Yes', autofocus: prompt.default !== 'no', disabled: send.pending, onclick: () => { submit('yes') } }, '✔️'),
h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'No', autofocus: prompt.default === 'no', disabled: send.pending, onclick: () => { submit('no') } }, '✖️'),
)
return
}
const btn = actions.querySelector('button') ?? actions.appendChild(h('button', { type: 'submit', class: 'btn btn-primary' }))
btn.disabled = !ready() || send.pending
btn.textContent = send.pending ? 'Sending…' : 'Answer'
sendButton(btn, send.pending ? 'Sending…' : 'Answer', send.pending ? '⏳' : '↵')
}
refresh()
return form
@ -127,12 +135,18 @@ function gamePrompt(jobId: string, prompt: PromptEvent): HTMLFormElement {
}
browser.pick = { appIds, selected, onSelect: pick }
const pickBtn = h('button', { type: 'submit', class: 'btn btn-primary' })
const backBtn = h('button', { type: 'button', class: 'btn btn-ghost', onclick: () => void send.run('') }, 'Back to the list')
const backBtn = h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'Back to the list', onclick: () => void send.run('') }, '↩️')
const errorSlot = h('div', { class: 'contents' })
const form = h(
'form',
{ class: 'prompt prompt-game', 'aria-label': 'Job question' },
h('p', { class: 'prompt-msg' }, prompt.message, ' ', h('span', { class: 'muted' }, `· ${appIds.size} games can be picked`)),
h(
'p',
{ class: 'prompt-msg' },
glyph('❓', prompt.message),
' ',
h('span', { class: 'muted' }, h('span', { 'aria-hidden': 'true' }, `· 🎮 ${appIds.size}`), h('span', { class: 'sr-only' }, `· ${appIds.size} games can be picked`)),
),
browser,
errorSlot,
h('div', { class: 'actions prompt-game-bar' }, pickBtn, backBtn),
@ -145,7 +159,13 @@ function gamePrompt(jobId: string, prompt: PromptEvent): HTMLFormElement {
function refresh(): void {
const name = q.library.state.data?.games.find((g) => g.app_id === selected)?.name ?? String(selected)
pickBtn.disabled = selected === null || send.pending
pickBtn.textContent = send.pending ? 'Sending…' : selected === null ? 'Select a game' : `Pick ${name}`
// 🎯 + the chosen game's name (content) painted; the verb is spoken.
if (send.pending) sendButton(pickBtn, 'Sending…', '⏳')
else if (selected === null) sendButton(pickBtn, 'Select a game', '🎯')
else {
pickBtn.setAttribute('aria-label', `Pick ${name}`)
pickBtn.replaceChildren(h('span', { 'aria-hidden': 'true' }, `🎯 ${name}`))
}
backBtn.disabled = send.pending
errorSlot.replaceChildren(...(send.error ? [errorNotice(send.error)] : []))
}

View File

@ -5,11 +5,11 @@
import { readHash } from './hashState'
import { NO_FILTERS, SORTS, type Filters, type SortKey } from './view'
/** Filter key, checkbox label, and its token in the hash's `f=` list. */
export const FILTERS: [keyof Filters, string, string][] = [
['hideCompleted', 'Hide completed', 'completed'],
['installedOnly', 'Installed only', 'installed'],
['pickableOnly', 'Pickable only', 'pickable'],
/** Filter key, spoken checkbox label, its token in the hash's `f=` list, painted glyph. */
export const FILTERS: [keyof Filters, string, string, string][] = [
['hideCompleted', 'Hide completed', 'completed', '🙈🏆'],
['installedOnly', 'Installed only', 'installed', '💾'],
['pickableOnly', 'Pickable only', 'pickable', '🎯'],
]
export interface BrowserState {

View File

@ -4,6 +4,7 @@
import type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom'
import { glyph } from '../ui/build'
import { FILTERS, type BrowserState } from './browserState'
import { SearchBox, type SearchBoxOptions } from './searchBox'
import { SORTS, type Filters, type SortKey } from './view'
@ -30,7 +31,7 @@ export class BrowserToolbar {
opts.onSort(this.sortSelect.value as SortKey)
},
},
SORTS.map((s) => h('option', { value: s.key }, s.label)),
SORTS.map((s) => h('option', { value: s.key, 'aria-label': s.label }, s.icon)),
)
this.checks = new Map(
FILTERS.map(([key]) => [
@ -47,12 +48,12 @@ export class BrowserToolbar {
'div',
{ class: 'lib-toolbar' },
this.searchBox.el,
h('label', { class: 'lib-sort' }, h('span', { class: 'field-label' }, 'Sort'), this.sortSelect),
h('label', { class: 'lib-sort' }, glyph('↕️', 'Sort', 'field-label'), this.sortSelect),
h(
'fieldset',
{ class: 'lib-filters' },
h('legend', { class: 'sr-only' }, 'Filters'),
FILTERS.map(([key, label]) => h('label', { class: 'check' }, this.checks.get(key), label)),
FILTERS.map(([key, label, , icon]) => h('label', { class: 'check' }, this.checks.get(key), glyph(icon, label))),
),
this.count,
)
@ -74,7 +75,12 @@ export class BrowserToolbar {
this.searchBox.setSuggestions(games)
}
setCount(text: string): void {
this.count.textContent = text
/** "🎮 3/5" (+ 🔍 while a search ranks by relevance); the sentence is spoken. */
setCount(shown: number, total: number, byRelevance: boolean): void {
const spoken = `${shown} of ${total} games${byRelevance ? ' · by relevance' : ''}`
this.count.replaceChildren(
h('span', { 'aria-hidden': 'true' }, `🎮 ${shown}/${total}${byRelevance ? ' 🔍' : ''}`),
h('span', { class: 'sr-only' }, spoken),
)
}
}

View File

@ -15,7 +15,7 @@ import type { LibraryGame } from '../api/contract'
import { q } from '../api/queries'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { errorNotice, loading } from '../ui/build'
import { empty, errorNotice, loading } from '../ui/build'
import { stateFromHash, stateToHash, type BrowserState } from './browserState'
import { BrowserToolbar } from './browserToolbar'
import { buildIndex, search, type Searchable } from './fuzzy'
@ -191,8 +191,8 @@ export class GameBrowser extends LiveElement implements GameBrowserElement {
}
this.grid.show(this.visible.map((g) => this.card(g)))
const query = this.state.query.trim()
this.toolbar.setCount(`${this.visible.length} of ${games.length} games${query ? ' · by relevance' : ''}`)
this.none.replaceChildren(...(this.visible.length === 0 ? [h('p', { class: 'muted' }, 'No game matches.')] : []))
this.toolbar.setCount(this.visible.length, games.length, query !== '')
this.none.replaceChildren(...(this.visible.length === 0 ? [empty('No game matches.')] : []))
}
/** A click: becomes the tab stop; in pick mode an eligible card is selected. */

View File

@ -1,6 +1,7 @@
import { fireEvent } from '@testing-library/dom'
import { describe, expect, it } from 'vitest'
import { makeLibGame } from '../test/fixtures'
import { visibleWords } from '../test/visibleWords'
import { gameCard, paintCard, placeCard, type CardPaint } from './gameCard'
const PLAIN: CardPaint = { reason: null, selected: false, pickMode: false }
@ -70,8 +71,17 @@ describe('gameCard', () => {
it('shows only the badge that applies', () => {
const card = make({ installed: true })
expect(card.querySelector('.game-badges')).toHaveTextContent(/^installed$/)
expect(make({ assigned: true }).querySelector('.game-badges')).toHaveTextContent(/^assigned$/)
expect(card.querySelectorAll('.game-badges .pill')).toHaveLength(1)
expect(card.querySelector('.game-badges .pill-neutral')).toHaveTextContent('💾installed')
const assigned = make({ assigned: true })
expect(assigned.querySelectorAll('.game-badges .pill')).toHaveLength(1)
expect(assigned.querySelector('.game-badges .pill-accent')).toHaveTextContent('🎯assigned')
})
it('paints glyphs and numbers only; reasons and meta words are spoken', () => {
const card = make({ assigned: true, installed: true }, { pickMode: true, selected: false, reason: 'Skipped until 2026-10-17' })
expect(visibleWords(card, [card.querySelector('.game-title')?.textContent ?? ''])).toEqual([])
expect(card.querySelector('.game-reason')).toHaveTextContent('⏭️ 2026-10-17')
})
it('has no badge row for a plain game', () => {

View File

@ -4,7 +4,8 @@
import { ENDPOINTS, type LibraryGame } from '../api/contract'
import { h } from '../lib/dom'
import { metaLine } from './view'
import { pill } from '../ui/build'
import { metaGlyphs, metaLine, reasonGlyph, spokenGlyphs } from './view'
export interface CardPaint {
/** Why it cannot be picked here, or null. Greys the card out. */
@ -36,13 +37,13 @@ export function gameCard(game: LibraryGame): HTMLButtonElement {
{ type: 'button', class: 'game-card', 'data-app-id': game.app_id, tabindex: -1 },
cover(game),
h('span', { class: 'game-title' }, game.name),
h('span', { class: 'game-meta' }, metaLine(game)),
spokenGlyphs(metaGlyphs(game), metaLine(game), 'game-meta'),
game.assigned || game.installed
? h(
'span',
{ class: 'game-badges' },
game.assigned ? h('span', { class: 'pill pill-accent' }, 'assigned') : null,
game.installed ? h('span', { class: 'pill pill-neutral' }, 'installed') : null,
game.assigned ? pill('accent', 'assigned', '🎯') : null,
game.installed ? pill('neutral', 'installed', '💾') : null,
)
: null,
)
@ -56,13 +57,15 @@ export function paintCard(card: HTMLButtonElement, { reason, selected, pickMode
else card.removeAttribute('aria-pressed')
if (pickMode && reason !== null) card.setAttribute('aria-disabled', 'true')
else card.removeAttribute('aria-disabled')
let line = card.querySelector('.game-reason')
const line = card.querySelector('.game-reason')
if (reason === null) {
line?.remove()
return
}
line ??= card.appendChild(h('span', { class: 'game-reason' }))
line.textContent = reason
// The reason is spoken; the card paints its glyph (and any date) greyed out.
const fresh = spokenGlyphs(reasonGlyph(reason), reason, 'game-reason')
if (line) line.replaceWith(fresh)
else card.append(fresh)
}
/** Place the card in the grid: its position and whether it is the tab stop. */

View File

@ -6,7 +6,7 @@
import type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom'
import { uid } from '../lib/ids'
import { metaLine } from './view'
import { reasonOrMeta } from './view'
export interface SearchBoxOptions {
/** Every edit of the text (typing, or Escape clearing it). */
@ -36,7 +36,7 @@ export class SearchBox {
'aria-expanded': 'false',
'aria-controls': this.listId,
'aria-autocomplete': 'list',
placeholder: 'Search your games (typos are fine)…',
placeholder: '🔍',
})
this.list = h('ul', { id: this.listId, role: 'listbox', class: 'lib-suggest', hidden: true, 'aria-label': 'Suggestions' })
this.el = h('div', { class: 'lib-search' }, this.input, this.list)
@ -138,7 +138,7 @@ export class SearchBox {
},
},
h('span', { class: 'lib-suggest-name' }, g.name),
h('span', { class: 'lib-suggest-meta' }, this.opts.reason(g) ?? metaLine(g)),
reasonOrMeta(this.opts.reason(g), g, 'lib-suggest-meta'),
),
)
: []),

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { makeLibGame } from '../test/fixtures'
import { completion, filterGames, isCompleted, metaLine, NO_FILTERS, sortGames } from './view'
import { completion, filterGames, isCompleted, metaGlyphs, metaLine, NO_FILTERS, reasonGlyph, reasonOrMeta, sortGames } from './view'
const g = makeLibGame
@ -68,3 +68,41 @@ describe('metaLine', () => {
expect(metaLine(g({ achievements_total: 0, hltb_hours: null, playtime_minutes: 0 }))).toBe('No achievements')
})
})
describe('metaGlyphs', () => {
it('paints trophy, clock and play with their values', () => {
expect(metaGlyphs(g({ achievements_total: 8, achievements_unlocked: 3, hltb_hours: 12, playtime_minutes: 192 })))
.toBe('🏆 37% · ⏱️ 12 h · ▶️ 3.2 h')
})
it('paints a dash for no achievements and drops unknown HLTB and zero playtime', () => {
expect(metaGlyphs(g({ achievements_total: 0, hltb_hours: null, playtime_minutes: 0 }))).toBe('🏆 —')
})
})
describe('reasonGlyph', () => {
it.each([
['Already 100% complete', '🏆✅'],
['No achievements', '🏆🚫'],
['Skipped by you', '⏭️'],
['Skipped until 2026-09-01', '⏭️ 2026-09-01'],
['Something else', '⛔'],
['Blocked until 2026-10-02', '⛔ 2026-10-02'],
])('%s paints %s', (reason, painted) => {
expect(reasonGlyph(reason)).toBe(painted)
})
})
describe('reasonOrMeta', () => {
it('paints the meta glyphs and speaks the meta line when pickable', () => {
const game = g({ achievements_total: 8, achievements_unlocked: 3, hltb_hours: 12, playtime_minutes: 192 })
const el = reasonOrMeta(null, game, 'sub')
expect(el.className).toBe('sub')
expect(el.querySelector('[aria-hidden="true"]')?.textContent).toBe(metaGlyphs(game))
expect(el.querySelector('.sr-only')?.textContent).toBe(metaLine(game))
})
it('paints the reason glyph and speaks the reason when not pickable', () => {
const el = reasonOrMeta('No achievements', g(), 'sub')
expect(el.querySelector('[aria-hidden="true"]')?.textContent).toBe('🏆🚫')
expect(el.querySelector('.sr-only')?.textContent).toBe('No achievements')
})
})

View File

@ -2,14 +2,16 @@
// the grid component only wires state to them.
import type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom'
export type SortKey = 'name' | 'recent' | 'completion' | 'hltb'
export const SORTS: { key: SortKey; label: string }[] = [
{ key: 'name', label: 'Name' },
{ key: 'recent', label: 'Recently played' },
{ key: 'completion', label: 'Completion' },
{ key: 'hltb', label: 'Shortest (HLTB)' },
/** `label` is spoken only; the sort select paints `icon`. */
export const SORTS: { key: SortKey; label: string; icon: string }[] = [
{ key: 'name', label: 'Name', icon: '🔤' },
{ key: 'recent', label: 'Recently played', icon: '🕐' },
{ key: 'completion', label: 'Completion', icon: '🏆' },
{ key: 'hltb', label: 'Shortest (HLTB)', icon: '⏱️' },
]
export interface Filters {
@ -58,7 +60,7 @@ export function filterGames(
)
}
/** "45% · 12 h HLTB · 3.2 h played", the card's one meta line. */
/** "45% · 12 h HLTB · 3.2 h played", the card's meta line (spoken only). */
export function metaLine(g: LibraryGame): string {
const pct = completion(g)
const parts = [pct === null ? 'No achievements' : `${Math.floor(pct)}%`]
@ -67,6 +69,34 @@ export function metaLine(g: LibraryGame): string {
return parts.join(' · ')
}
/** The painted meta line: "🏆 45% · ⏱️ 12 h · ▶️ 3.2 h" (🏆 — without achievements). */
export function metaGlyphs(g: LibraryGame): string {
const pct = completion(g)
const parts = [`🏆 ${pct === null ? '—' : `${Math.floor(pct)}%`}`]
if (g.hltb_hours !== null) parts.push(`⏱️ ${hours(g.hltb_hours)}`)
if (g.playtime_minutes > 0) parts.push(`▶️ ${hours(g.playtime_minutes / 60)}`)
return parts.join(' · ')
}
function hours(h: number): string {
return h >= 10 ? `${Math.round(h)} h` : `${h.toFixed(1)} h`
}
/** Glyph for a server ineligibility reason; a date in it stays painted. */
export function reasonGlyph(reason: string): string {
const date = /\d{4}-\d{2}-\d{2}/.exec(reason)?.[0]
if (reason.includes('100%')) return '🏆✅'
if (/no achievements/i.test(reason)) return '🏆🚫'
if (/skip/i.test(reason)) return date ? `⏭️ ${date}` : '⏭️'
return date ? `⛔ ${date}` : '⛔'
}
/** Glyphs painted, words spoken: `text` shown as `painted` with an sr-only twin. */
export function spokenGlyphs(painted: string, text: string, className: string): HTMLSpanElement {
return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, painted), h('span', { class: 'sr-only' }, text))
}
/** A suggestion's second line: the reason it cannot be picked, else the meta line. */
export function reasonOrMeta(reason: string | null, g: LibraryGame, className: string): HTMLSpanElement {
return reason === null ? spokenGlyphs(metaGlyphs(g), metaLine(g), className) : spokenGlyphs(reasonGlyph(reason), reason, className)
}

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

@ -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 '../../test/painted'
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

@ -2,6 +2,7 @@ import { screen, within } from '@testing-library/dom'
import { afterEach, describe, expect, it } from 'vitest'
import { makeGame } from '../../test/factories'
import { GAMES, hash, header, names, show, table } from '../../test/plannerHelpers'
import { ANY_GLYPH } from './glyphs'
import { hltbUrl } from './plannerTable'
afterEach(() => {
@ -89,7 +90,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 +105,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 () => {
@ -114,6 +116,16 @@ describe('<game-table> table', () => {
expect(screen.getByText('Fallback estimate', { exact: false })).toBeVisible()
})
it('paints the keep options as glyphs and speaks their values', async () => {
await show()
const options = [...screen.getByRole('combobox', { name: 'Filter Keep' }).querySelectorAll('option')]
expect(options.map((o) => [o.value, o.textContent, o.getAttribute('aria-label')])).toEqual([
['', ANY_GLYPH, 'All'],
['kept', '📌', 'kept'],
['excluded', '🚫', 'excluded'],
])
})
it('caps the table and notes the overflow', async () => {
await show(Array.from({ length: 301 }, (_, i) => makeGame({ app_id: i + 1, name: `Game ${i}` })))
expect(screen.getByText('300/301')).toBeVisible()

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,13 @@ 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.
// Only the keep and proton columns have a select filter; keep's options are
// always kept/excluded, so every one has a glyph.
const optionLabel = (c: Column, v: string) => (c.key === 'keep' ? KEEP_GLYPH[v] : tierGlyphs(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 +114,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 +161,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 +170,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 +194,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 '../../test/painted'
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 '../../test/painted'
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

@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest'
import { since } from './dashboard'
describe('since', () => {
it('paints a clock and the short span, speaking the full phrase', () => {
const el = since(new Date(Date.now() - 5 * 60_000).toISOString())
expect(el.querySelector('[aria-hidden="true"]')?.textContent).toBe('🕓 5 min')
expect(el.querySelector('.sr-only')?.textContent).toBe('5 min ago')
})
it('paints "<1 min" while speaking "just now"', () => {
const el = since(new Date().toISOString())
expect(el.querySelector('[aria-hidden="true"]')?.textContent).toBe('🕓 <1 min')
expect(el.querySelector('.sr-only')?.textContent).toBe('just now')
})
})

View File

@ -41,7 +41,8 @@ const show = (over: Record<string, Handler> = {}) => {
mount(PAGE)
return mock
}
const fact = (label: string) => screen.getByText(label, { selector: 'dt' }).nextElementSibling as HTMLElement
// A fact's term is a glyph whose label is spoken (sr-only).
const fact = (label: string) => screen.getByText(label, { selector: 'dt .sr-only' }).closest('dt')?.nextElementSibling as HTMLElement
const box = (name: string) => screen.getByRole('region', { name })
describe('Dashboard', () => {
@ -101,7 +102,8 @@ describe('Dashboard', () => {
vi.setSystemTime(Date.parse('2026-10-23T11:07:58Z'))
expect(fact('Total block')).toHaveTextContent('1h 8m left')
vi.advanceTimersByTime(1000)
const first = Number(/^(\d)s left$/.exec(fact('Total block').textContent)?.[1])
// Painted ⏳ + number; "left" is spoken (sr-only).
const first = Number(/^(\d)s left$/.exec(fact('Total block').querySelector('.sr-only')?.textContent ?? '')?.[1])
expect([3, 4]).toContain(first)
vi.advanceTimersByTime(1000)
expect(fact('Total block')).toHaveTextContent(`${first - 1}s left`)
@ -152,7 +154,7 @@ describe('Dashboard', () => {
it('keeps a failed daemon run on screen with its reason', async () => {
const failed = { ...bg3, phase: 'failed', percent: null, elapsed_seconds: 0, error: 'Refusing to mark it as installed' }
show({ 'GET /api/daemon': daemon([failed]) })
expect(await screen.findByText("Fast install of Baldur's Gate 3 failed: Refusing to mark it as installed")).toHaveClass('text-danger')
expect((await screen.findByText("Fast install of Baldur's Gate 3 failed: Refusing to mark it as installed")).closest('p')).toHaveClass('text-danger')
expect(screen.getByText("Steam's own download took over.")).toBeInTheDocument()
expect(screen.queryByRole('progressbar', { name: "Baldur's Gate 3 download" })).not.toBeInTheDocument()
})

View File

@ -1,17 +1,26 @@
// Dashboard sections (was screens/Dashboard.tsx): what the enforcer is doing
// right now, at a glance.
// right now, at a glance. Textgate: glyphs and numbers are painted, every
// sentence is spoken only (sr-only), game names stay visible as content.
import type { FastInstallRun, StatusPayload } from '../api/contract'
import { q } from '../api/queries'
import { commandLabel } from '../commands/catalog'
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
import '../commands/commandButton'
import { fmtDuration, fmtRemaining } from '../format'
import { progressBar, stateBadge, type BarTone } from '../jobs/progress'
import { define, h, hx } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { jobHref } from '../lib/runner'
import { card, empty, errorNotice, facts, link, loading } from '../ui/build'
import { card, empty, errorNotice, facts, glyph, link, loading } from '../ui/build'
import { ago } from '../ui/format'
import { said } from './spoken'
/** "5 min ago" painted as 🕓 5 min (the word "ago" spoken only). */
export function since(iso: string | null): HTMLSpanElement {
const spoken = ago(iso)
const short = spoken === 'just now' ? '<1 min' : spoken.replace(/ ago$/, '')
return said(spoken, '🕓 ', short)
}
/** Seconds left on the total block: from `until` when known, else the
* server's `days_remaining` (rounded to 0.1 d). */
@ -29,18 +38,29 @@ export class BlockCountdownElement extends LiveElement {
protected update(): void {
const block = q.status.state.data?.total_block
this.replaceChildren(...(block ? [h('span', { class: 'text-danger' }, `${fmtRemaining(blockSecondsLeft(block))} left`)] : []))
if (!block) {
this.replaceChildren()
return
}
const left = fmtRemaining(blockSecondsLeft(block))
this.replaceChildren(h('span', { class: 'text-danger' }, said(`${left} left`, '⏳ ', left)))
}
}
function statusFacts(s: StatusPayload): HTMLDListElement {
return facts([
['Installed', s.assigned_game_installed ? 'Yes' : h('span', { class: 'text-warning' }, 'No — install it from Library')],
['Games finished', s.finished_count],
['Store', s.store_blocked ? 'Blocked' : h('span', { class: 'text-warning' }, 'Unblocked')],
['Installed games', s.installed_count],
['Total block', s.total_block.active ? hx('block-countdown') : 'Off'],
['Manual picks', s.manual_picks.length ? s.manual_picks.map((p) => `${p.name} (${p.age_days} d)`).join(', ') : 'None'],
[
glyph('💾', 'Installed'),
s.assigned_game_installed ? glyph('✅', 'Yes') : h('span', { class: 'text-warning' }, glyph('⚠️', 'No — install it from Library')),
],
[glyph('🏆', 'Games finished'), s.finished_count],
[glyph('🛒', 'Store'), s.store_blocked ? glyph('🔒', 'Blocked') : h('span', { class: 'text-warning' }, glyph('🔓', 'Unblocked'))],
[glyph('🗂️', 'Installed games'), s.installed_count],
[glyph('⛔', 'Total block'), s.total_block.active ? hx('block-countdown') : glyph('➖', 'Off')],
[
glyph('📌', 'Manual picks'),
s.manual_picks.length ? s.manual_picks.map((p) => `${p.name} (${p.age_days} d)`).join(', ') : glyph('➖', 'None'),
],
])
}
@ -51,13 +71,16 @@ export class DashboardStatusElement extends LiveElement {
protected update(): void {
const { data, error } = q.status.state
const icon = '🎯'
if (error) {
this.replaceChildren(card('Assignment', errorNotice(error)))
this.replaceChildren(card('Assignment', errorNotice(error), { icon }))
} else if (!data) {
this.replaceChildren(card('Assignment', loading('status')))
this.replaceChildren(card('Assignment', loading('status'), { icon }))
} else {
const game = data.current_game_name ?? glyph('📭', 'Nothing assigned')
this.replaceChildren(
card('Assignment', [h('p', { class: 'hero-game' }, data.current_game_name ?? 'Nothing assigned'), statusFacts(data)], {
card('Assignment', [h('p', { class: 'hero-game' }, game), statusFacts(data)], {
icon,
// Its own element, so it follows the command catalog by itself.
aside: hx('command-button', { name: 'check', label: 'Check now' }),
}),
@ -71,6 +94,12 @@ function budgetTone(blocked: boolean, used: number): BarTone {
return used > 0.8 ? 'warning' : 'accent'
}
function billingLine(blocked: boolean, label: string): HTMLParagraphElement {
if (blocked) return h('p', { class: 'field-help' }, glyph('⛔', 'Blocked for today.'))
if (!label) return h('p', { class: 'field-help' }, said('Now: nothing billing', '⏸️'))
return h('p', { class: 'field-help' }, said(`Now: ${label}`, '▶️ ', label))
}
export class BudgetGlanceElement extends LiveElement {
protected override setup(): void {
this.watch(q.budget)
@ -78,12 +107,13 @@ export class BudgetGlanceElement extends LiveElement {
protected update(): void {
const { data, error } = q.budget.state
const icon = '⏱️'
if (error) {
this.replaceChildren(card('Gaming today', errorNotice(error)))
this.replaceChildren(card('Gaming today', errorNotice(error), { icon }))
return
}
if (!data) {
this.replaceChildren(card('Gaming today', loading('budget')))
this.replaceChildren(card('Gaming today', loading('budget'), { icon }))
return
}
const t = data.today
@ -93,37 +123,35 @@ export class BudgetGlanceElement extends LiveElement {
'p',
{ class: 'hero-num' },
`${fmtDuration(t.seconds_remaining)} `,
h('span', { class: 'muted' }, `left of ${fmtDuration(t.budget_seconds)}`),
h('span', { class: 'muted' }, said(`left of ${fmtDuration(t.budget_seconds)}`, `/ ${fmtDuration(t.budget_seconds)}`)),
),
progressBar(t.fraction_used, 'Budget used', budgetTone(t.blocked, t.fraction_used)),
h('p', { class: 'field-help' }, t.blocked ? 'Blocked for today.' : `Now: ${data.session.billing_label || 'nothing billing'}`),
billingLine(t.blocked, data.session.billing_label),
]
: h('p', { class: 'text-danger' }, data.error ?? 'Budget state unavailable.')
this.replaceChildren(card('Gaming today', body, { aside: link('/gaming/', 'Details') }))
: h('p', { class: 'text-danger' }, data.error ?? glyph('⚠️', 'Budget state unavailable.'))
this.replaceChildren(card('Gaming today', body, { icon, aside: link('/gaming/', glyph('➡️', 'Details')) }))
}
}
function fastInstallLine(r: FastInstallRun): string {
const where = r.percent === null ? r.phase : `${Math.floor(r.percent)}% (${r.phase})`
return `Fast-installing ${r.name} — ${where}`
}
function fastInstallRow(r: FastInstallRun): HTMLDivElement {
if (r.error) {
// The daemon has no job to report to: a failure stays here until Steam finishes.
// The error is the daemon's own message (content), the framing is spoken.
return h(
'div',
{},
h('p', { class: 'text-danger' }, `Fast install of ${r.name} failed: ${r.error}`),
h('p', { class: 'field-help' }, "Steam's own download took over."),
h('p', { class: 'text-danger' }, said(`Fast install of ${r.name} failed: ${r.error}`, '⛔ ', r.name, ': ', r.error)),
h('p', { class: 'field-help' }, glyph('↪️', "Steam's own download took over.")),
)
}
const pct = r.percent === null ? null : Math.floor(r.percent)
const where = pct === null ? r.phase : `${pct}% (${r.phase})`
return h(
'div',
{},
h('p', {}, fastInstallLine(r)),
progressBar(r.percent === null ? null : Math.floor(r.percent) / 100, `${r.name} download`),
h('p', { class: 'field-help' }, `${fmtDuration(r.elapsed_seconds)} elapsed`),
h('p', {}, said(`Fast-installing ${r.name} — ${where}`, '⚡ ', r.name, pct === null ? '' : ` ${pct}%`)),
progressBar(pct === null ? null : pct / 100, `${r.name} download`),
h('p', { class: 'field-help' }, said(`${fmtDuration(r.elapsed_seconds)} elapsed`, '⏳ ', fmtDuration(r.elapsed_seconds))),
)
}
@ -135,7 +163,7 @@ export class FastInstallsElement extends LiveElement {
protected update(): void {
const runs = q.daemon.state.data?.fast_installs ?? []
this.replaceChildren(...(runs.length ? [card('Fast install', runs.map(fastInstallRow))] : []))
this.replaceChildren(...(runs.length ? [card('Fast install', runs.map(fastInstallRow), { icon: '⚡' })] : []))
}
}
@ -162,16 +190,18 @@ export class RecentJobsElement extends LiveElement {
h(
'a',
{ href: jobHref(j.id), class: 'row-link' },
h('span', {}, commandLabel(j.command)),
h('span', { class: 'muted grow ellipsis' }, j.summary ?? j.progress?.label ?? ''),
h('span', { class: 'muted' }, ago(j.created_at)),
glyph(COMMAND_ICON[j.command], commandLabel(j.command)),
// The job's summary is a server sentence: spoken here, shown in the job view.
h('span', { class: 'sr-only' }, j.summary ?? j.progress?.label ?? ''),
h('span', { class: 'grow' }),
h('span', { class: 'muted' }, since(j.created_at)),
stateBadge(j.state),
),
),
),
),
],
{ aside: link('/jobs/', 'All jobs') },
{ icon: '⚙️', aside: link('/jobs/', glyph('➡️', 'All jobs')) },
),
)
}

View File

@ -1,7 +1,8 @@
import { screen } from '@testing-library/dom'
import { describe, expect, it } from 'vitest'
import { makeBudgetRules, makeBudgetSession, makeBudgetToday } from '../../test/factories'
import { historyCard, liveCard, rulesCard, todayCard, todayUnavailable } from './cards'
import { OTHER_KEY, UNATTRIBUTED_KEY } from '../../budgetSeries'
import { historyCard, liveCard, rulesCard, seriesLabel, todayCard, todayUnavailable } from './cards'
const show = (el: HTMLElement) => {
document.body.replaceChildren(el)
@ -74,7 +75,7 @@ describe('todayUnavailable', () => {
describe('liveCard', () => {
it('reports an engaged session with its game', () => {
show(liveCard(makeBudgetSession()))
expect(screen.getByText(/Billing — you are playing/)).toHaveClass('budget-verdict--engaged')
expect(screen.getByText(/Billing — you are playing/).closest('.budget-verdict')).toHaveClass('budget-verdict--engaged')
expect(screen.getByText(/Assigned game/)).toBeInTheDocument()
// Engaged, so the credited game is described in the present tense.
expect(screen.getByText(/Billing to/)).toBeInTheDocument()
@ -108,6 +109,58 @@ describe('liveCard', () => {
})
})
describe('liveCard reading age', () => {
const painted = () => document.querySelector('.hint:last-child [aria-hidden="true"]')?.textContent
const spoken = () => document.querySelector('.hint:last-child .sr-only')?.textContent
it('paints a clock and "<10s" for a fresh reading', () => {
show(liveCard(makeBudgetSession()))
expect(painted()).toBe('🕓 <10s')
expect(spoken()).toBe('as of just now')
})
it('paints the age without "ago" for an older reading', () => {
show(liveCard(makeBudgetSession({ observed_at: new Date(Date.now() - 125_000).toISOString() })))
expect(painted()).toMatch(/^🕓 2m/)
expect(spoken()).toMatch(/^as of 2m.* ago$/)
})
it('paints "?" when the reading time is unknown', () => {
show(liveCard(makeBudgetSession({ observed_at: '' })))
expect(painted()).toBe('🕓 ?')
expect(spoken()).toBe('as of unknown')
})
})
describe('seriesLabel', () => {
const paintedOf = (el: HTMLElement) => el.querySelector('[aria-hidden="true"]')?.textContent
const spokenOf = (el: HTMLElement) => el.querySelector('.sr-only')?.textContent
it('paints a plus for the grouped remainder and speaks its label', () => {
const el = seriesLabel(OTHER_KEY, 'Other games')
expect(paintedOf(el)).toBe('➕')
expect(spokenOf(el)).toBe('Other games')
})
it('paints a question mark for unattributed time', () => {
const el = seriesLabel(UNATTRIBUTED_KEY, 'Unattributed')
expect(paintedOf(el)).toBe('❔')
expect(spokenOf(el)).toBe('Unattributed')
})
it('paints a rocket and the bare name for a launcher, speaking the full label', () => {
const el = seriesLabel('launcher:steam', 'Steam (launcher)')
expect(paintedOf(el)).toBe('🚀 Steam')
expect(spokenOf(el)).toBe('Steam (launcher)')
})
it('paints a game name as plain text', () => {
const el = seriesLabel('app:1', 'Titan Quest')
expect(el.textContent).toBe('Titan Quest')
expect(el.querySelector('.sr-only')).toBeNull()
})
})
describe('historyCard', () => {
const legend = [
{ key: 'app:475150', label: 'Titan Quest' },

View File

@ -1,11 +1,15 @@
// The four budget panel sections (were BudgetTodayCard, BudgetLiveCard,
// BudgetHistoryChart and BudgetRulesCard.tsx) as pure DOM builders.
// Textgate: glyphs, numbers and game names are painted; every sentence and
// label is spoken only (`said`/`glyph`), and the meter/verdict colours stay.
import { seriesClass } from '../../budgetSeries'
import { OTHER_KEY, UNATTRIBUTED_KEY, seriesClass } from '../../budgetSeries'
import { fmtAgo, fmtDuration } from '../../format'
import { budgetHistorySvg } from '../../lib/charts/budgetHistory'
import { h } from '../../lib/dom'
import type { BudgetHistoryDay, BudgetLegendEntry, BudgetRules, BudgetSession, BudgetToday } from '../../types'
import { glyph } from '../../ui/build'
import { said } from '../spoken'
/** Which colour the meter takes: normal, into the warning band, or spent.
*
@ -19,7 +23,22 @@ function meterState(today: BudgetToday): string {
return today.warned_seconds.length > 0 ? 'warn' : 'ok'
}
function warningLine(today: BudgetToday, maskedCount: number): HTMLElement | string {
/** A series name: game names are content; the sentinels and the "(launcher)" tag are glyphs. */
export function seriesLabel(key: string, label: string): HTMLElement {
if (key === OTHER_KEY) return glyph('➕', label)
if (key === UNATTRIBUTED_KEY) return glyph('❔', label)
if (key.startsWith('launcher:')) return said(label, '🚀 ', label.replace(/\s*\(launcher\)$/, ''))
return h('span', {}, label)
}
/** "5m ago" painted as 🕓 5m. */
function asOf(iso: string): HTMLElement {
const ago = fmtAgo(iso)
const short = ago === 'unknown' ? '?' : ago === 'just now' ? '<10s' : ago.replace(/ ago$/, '')
return said(`as of ${ago}`, '🕓 ', short)
}
function warningLine(today: BudgetToday, maskedCount: number): HTMLElement {
if (today.blocked) {
// Read the live mount count rather than inferring it from `blocked`: the
// total-block branch releases every mount while leaving `blocked_at` set,
@ -28,12 +47,23 @@ function warningLine(today: BudgetToday, maskedCount: number): HTMLElement | str
return h(
'span',
{ class: 'budget-badge budget-badge--blocked' },
maskedCount > 0 ? 'Cutoff engaged — launchers are masked' : 'Cutoff engaged — launchers are not currently masked',
maskedCount > 0
? glyph('⛔🔒', 'Cutoff engaged — launchers are masked')
: glyph('⛔🔓', 'Cutoff engaged — launchers are not currently masked'),
)
}
return today.next_warning_seconds === null
? 'No further warnings today.'
: `Next warning at ${fmtDuration(today.next_warning_seconds)} remaining.`
const next = today.next_warning_seconds
return next === null
? glyph('🔕', 'No further warnings today.')
: said(`Next warning at ${fmtDuration(next)} remaining.`, '🔔 ', fmtDuration(next))
}
function usageLine(t: BudgetToday): HTMLElement {
const used = `${fmtDuration(t.seconds_used)} / ${fmtDuration(t.budget_seconds)} · ${Math.round(t.fraction_used * 100)}%`
const spoken =
`${fmtDuration(t.seconds_used)} of ${fmtDuration(t.budget_seconds)} used · ` +
`${Math.round(t.fraction_used * 100)}% · gaming day ${t.gaming_day} (starts ${t.day_starts_at})`
return said(spoken, used, ' · 📅 ', t.gaming_day, ' · 🌅 ', t.day_starts_at.replace(/\s*local$/, ''))
}
export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry[], maskedCount: number): HTMLElement {
@ -46,19 +76,14 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
return h(
'section',
{ class: 'budget-today' },
h('h2', {}, 'Today'),
h('p', { class: 'budget-hero' }, h('strong', {}, fmtDuration(today.seconds_remaining)), ' left'),
h('h2', {}, glyph('📅', 'Today')),
h('p', { class: 'budget-hero' }, h('strong', {}, fmtDuration(today.seconds_remaining)), h('span', { class: 'sr-only' }, ' left')),
h('div', { class: `budget-meter budget-meter--${meterState(today)}` }, fill),
h(
'p',
{ class: 'hint' },
`${fmtDuration(today.seconds_used)} of ${fmtDuration(today.budget_seconds)} used · ` +
`${Math.round(today.fraction_used * 100)}% · gaming day ${today.gaming_day} (starts ${today.day_starts_at})`,
),
h('p', { class: 'hint' }, usageLine(today)),
h('p', { class: 'hint' }, warningLine(today, maskedCount)),
today.games.length > 0
? [
h('h3', { class: 'budget-subhead' }, 'Today by game'),
h('h3', { class: 'budget-subhead' }, glyph('🎮', 'Today by game')),
h(
'ul',
{ class: 'budget-games' },
@ -67,7 +92,7 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
'li',
{},
h('span', { class: `swatch ${seriesClass(game.key, indexFor.get(game.key) ?? i)}`, 'aria-hidden': 'true' }),
h('span', { class: 'budget-game-name' }, game.label),
h('span', { class: 'budget-game-name' }, seriesLabel(game.key, game.label)),
h('span', { class: 'budget-game-time' }, fmtDuration(game.seconds)),
h('span', { class: 'budget-game-share' }, `${Math.round(game.fraction * 100)}%`),
),
@ -80,34 +105,37 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
/** Shown in place of `todayCard` when the state file cannot be read. */
export function todayUnavailable(error: string | null): HTMLElement {
return h('section', { class: 'budget-today' }, h('h2', {}, 'Today'), h('p', { class: 'error' }, error ?? 'Budget state unavailable.'))
return h(
'section',
{ class: 'budget-today' },
h('h2', {}, glyph('📅', 'Today')),
// The server's own error is shown as is; the fallback is a glyph.
h('p', { class: 'error' }, error ?? glyph('⚠️', 'Budget state unavailable.')),
)
}
const VERDICT_LABELS = new Map([
['engaged', 'Billing — you are playing'],
['not_applicable', 'Not billing — no game running'],
const VERDICT = new Map([
['engaged', ['▶️', 'Billing — you are playing']],
['not_applicable', ['⏸️', 'Not billing — no game running']],
])
export function liveCard(session: BudgetSession): HTMLElement {
const title = h('h2', {}, 'Right now')
const title = h('h2', {}, glyph('📡', 'Right now'))
if (!session.available) {
return h('section', { class: 'budget-live' }, title, h('p', { class: 'hint' }, 'No verdict has been logged yet.'))
return h('section', { class: 'budget-live' }, title, h('p', { class: 'hint' }, glyph('📭', 'No verdict has been logged yet.')))
}
const [icon, verdict] = VERDICT.get(session.state) ?? ['❔', session.state]
return h(
'section',
{ class: 'budget-live' },
title,
h(
'p',
{},
h('span', { class: `budget-verdict budget-verdict--${session.state}` }, VERDICT_LABELS.get(session.state) ?? session.state),
),
h('p', {}, h('span', { class: `budget-verdict budget-verdict--${session.state}` }, glyph(icon, verdict))),
session.qualifying_count > 0
? h(
'p',
{ class: 'hint' },
session.game_name ? ['Assigned game ', h('strong', {}, session.game_name), ' · '] : null,
`${session.qualifying_count} qualifying processes`,
session.game_name ? [said('Assigned game ', '🎯 '), h('strong', {}, session.game_name), ' · '] : null,
said(`${session.qualifying_count} qualifying processes`, '⚙️ ', session.qualifying_count),
)
: null,
// The assignment above is what the enforcer told you to play; this is
@ -118,24 +146,24 @@ export function liveCard(session: BudgetSession): HTMLElement {
? h(
'p',
{ class: 'hint' },
session.state === 'engaged' ? 'Billing to ' : 'Last billed to ',
session.state === 'engaged' ? said('Billing to ', '💸 ') : said('Last billed to ', '⏮️💸 '),
h('strong', {}, session.billing_label),
)
: null,
// The daemon logs on change or a 5-minute heartbeat, so this reading can
// legitimately be minutes old. Saying so beats implying "now".
h('p', { class: 'hint' }, `as of ${fmtAgo(session.observed_at)}`),
h('p', { class: 'hint' }, asOf(session.observed_at)),
)
}
export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number): HTMLElement {
const title = h('h2', {}, 'Last 14 days')
const title = h('h2', {}, glyph('📊', 'Last 14 days'))
if (days.length === 0) {
return h(
'div',
{ class: 'chart' },
title,
h('p', { class: 'hint' }, 'No budget history recorded yet — a bar appears for each gaming day from now on.'),
h('p', { class: 'hint' }, glyph('📭', 'No budget history recorded yet — a bar appears for each gaming day from now on.')),
)
}
// A <template> parses the markup as HTML, which puts <svg> in the SVG namespace.
@ -149,33 +177,36 @@ export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly
h(
'ul',
{ class: 'chart-legend' },
legend.map((entry, i) => h('li', {}, h('span', { class: `swatch ${seriesClass(entry.key, i)}`, 'aria-hidden': 'true' }), entry.label)),
legend.map((entry, i) =>
h('li', {}, h('span', { class: `swatch ${seriesClass(entry.key, i)}`, 'aria-hidden': 'true' }), seriesLabel(entry.key, entry.label)),
),
),
h(
'p',
{ class: 'hint' },
{ class: 'sr-only' },
"Billed gaming time per day, split by game. The dashed line is the daily budget; today's bar can still move.",
),
)
}
const onOff = (value: boolean): string => (value ? 'on' : 'off')
const onOff = (value: boolean, on: string, off: string) => (value ? glyph('✅', on) : glyph('➖', off))
export function rulesCard(rules: BudgetRules): HTMLElement {
const row = (term: string, value: string) => [h('dt', {}, term), h('dd', {}, value)]
const row = (icon: string, term: string, value: Node | string) => [h('dt', {}, glyph(icon, term)), h('dd', {}, value)]
const warn = rules.warn_at.map((s) => fmtDuration(s)).join(', ')
return h(
'section',
{ class: 'budget-rules' },
h('h2', {}, 'Rules in effect'),
h('h2', {}, glyph('📏', 'Rules in effect')),
h(
'dl',
{ class: 'budget-rules-list' },
row('Daily budget', fmtDuration(rules.budget_seconds)),
row('Enforcement', onOff(rules.enforcement)),
row('Counts launchers', rules.counts_launchers ? 'yes' : 'no'),
row('Warnings at', `${rules.warn_at.map((s) => fmtDuration(s)).join(', ')} remaining`),
rules.demo ? row('Mode', 'demo (short budget, separate state)') : null,
rules.masked_launchers.length > 0 ? row('Masked now', rules.masked_launchers.join(', ')) : null,
row('⏱️', 'Daily budget', fmtDuration(rules.budget_seconds)),
row('🛡️', 'Enforcement', onOff(rules.enforcement, 'on', 'off')),
row('🚀', 'Counts launchers', onOff(rules.counts_launchers, 'yes', 'no')),
row('🔔', 'Warnings at', said(`${warn} remaining`, warn)),
rules.demo ? row('🧪', 'Mode', glyph('🧪', 'demo (short budget, separate state)')) : null,
rules.masked_launchers.length > 0 ? row('🔒', 'Masked now', rules.masked_launchers.join(', ')) : null,
),
)
}

View File

@ -41,7 +41,7 @@ describe('<budget-panel>', () => {
it('shows a loading line before the first response', () => {
stubApi({ 'GET /api/budget': () => new Promise(() => undefined) })
mount('<budget-panel></budget-panel>')
expect(screen.getByText(/Reading budget state/)).toBeInTheDocument()
expect(screen.getByText(/Loading budget state/)).toBeInTheDocument()
})
it('reads the production budget and renders all four sections', async () => {
@ -66,7 +66,7 @@ describe('<budget-panel>', () => {
it('surfaces a transport failure', async () => {
stubApi({ 'GET /api/budget': () => Promise.reject(new Error('API returned 500 Server Error')) })
mount('<budget-panel></budget-panel>')
expect(await screen.findByText('Could not read budget state: API returned 500 Server Error')).toHaveClass('error')
expect((await screen.findByText('Could not read budget state: API returned 500 Server Error')).closest('p')).toHaveClass('error')
expect(screen.getByText('./run.sh serve')).toBeInTheDocument()
})
@ -145,6 +145,6 @@ describe('<budget-panel>', () => {
resolve(makeBudget())
await flush(10)
expect(el.querySelector('.budget')).toBeNull()
expect(el).toHaveTextContent('Reading budget state…')
expect(el).toHaveTextContent('Loading budget state')
})
})

View File

@ -7,6 +7,8 @@ import { explain } from '../../api/errors'
import { q } from '../../api/queries'
import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { commandLine, glyph, loading } from '../../ui/build'
import { said } from '../spoken'
import { historyCard, liveCard, rulesCard, todayCard, todayUnavailable } from './cards'
/** True on `/gaming/?demo=1` (and the legacy `?demo=true`). */
@ -19,8 +21,13 @@ export function isDemo(search: string = location.search): boolean {
export class BudgetModeLinkElement extends LiveElement {
protected update(): void {
const demo = isDemo()
// 🧪 switches to the demo budget, 🏭 back to production; the words are spoken.
this.replaceChildren(
h('a', { href: demo ? '/gaming/' : '/gaming/?demo=1', class: 'btn btn-ghost' }, demo ? 'Show production budget' : 'Show demo budget'),
h(
'a',
{ href: demo ? '/gaming/' : '/gaming/?demo=1', class: 'btn btn-ghost' },
demo ? glyph('🏭', 'Show production budget') : glyph('🧪', 'Show demo budget'),
),
)
}
}
@ -41,14 +48,17 @@ export class BudgetPanelElement extends LiveElement {
h(
'div',
{ class: 'status' },
h('p', { class: 'error' }, `Could not read budget state: ${explain(error).detail}`),
h('p', { class: 'hint' }, 'Is the backend running? Start it with ', h('code', {}, './run.sh serve'), '.'),
// The server's own detail is painted; the framing is spoken. The
// command is the recovery path, so it stays with a copy button.
h('p', { class: 'error' }, said(`Could not read budget state: ${explain(error).detail}`, '⛔ ', explain(error).detail)),
h('p', { class: 'hint' }, h('span', { class: 'sr-only' }, 'Is the backend running? Start it with')),
commandLine('./run.sh serve'),
),
)
return
}
if (!data) {
this.replaceChildren(h('div', { class: 'status' }, h('p', { class: 'hint' }, 'Reading budget state…')))
this.replaceChildren(h('div', { class: 'status' }, loading('budget state')))
return
}
this.replaceChildren(

View File

@ -37,10 +37,12 @@ describe('jobs list', () => {
expect(await screen.findByRole('table')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Jobs', level: 1 })).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Pick manual' })).toHaveAttribute('href', '/jobs/?id=a')
expect(screen.getByText('app_id=5 note=x')).toBeInTheDocument()
// Param values painted, keys and the server's summary spoken only.
expect(screen.getByText('5 x')).toHaveAttribute('aria-hidden', 'true')
expect(screen.getByText('app_id=5 note=x')).toHaveClass('sr-only')
expect(screen.getByText('1:05')).toBeInTheDocument()
expect(screen.getByText('Picked 5')).toBeInTheDocument()
expect(screen.getByText('Scanning')).toBeInTheDocument()
expect(screen.getByText('Picked 5')).toHaveClass('sr-only')
expect(screen.getByText('Scanning')).toHaveClass('sr-only')
expect(screen.getAllByLabelText('running')).toHaveLength(2)
})
@ -106,7 +108,9 @@ describe('job detail', () => {
stubApi({ 'GET /api/jobs/nope': apiError(404, 'not_found', 'No job nope.') })
mount('<jobs-page></jobs-page>')
expect(await screen.findByRole('heading', { name: 'Job not found', level: 1 })).toBeInTheDocument()
expect(screen.getByText('No job nope.')).toBeInTheDocument()
const notice = document.querySelector('[data-code="not_found"]')
expect(notice?.getAttribute('aria-label')).toMatch(/No job nope\.$/)
expect(notice).toHaveTextContent('nope')
expect(screen.getByRole('link', { name: 'See all jobs' })).toHaveAttribute('href', '/jobs/')
expect(document.querySelector('job-progress')).toBeNull()
expect(FakeEventSource.all).toHaveLength(0)
@ -127,8 +131,9 @@ describe('job detail', () => {
at('/jobs/?id=gone')
stubApi({ 'GET /api/jobs/gone': apiError(404, 'not_found') })
mount('<jobs-page></jobs-page>')
const title = await screen.findByText('Job not found', { selector: '.notice-title' })
expect(title.parentElement?.querySelectorAll('p')).toHaveLength(2)
await screen.findByRole('heading', { name: 'Job not found', level: 1 })
const notice = document.querySelector('[data-code="not_found"]')
expect(notice?.getAttribute('aria-label')).toMatch(/keeps the last 50\.$/)
})
it('treats a bare <job-detail> as an unknown job', async () => {

View File

@ -6,13 +6,13 @@ import { ApiFailure } from '../api/client'
import { explain } from '../api/errors'
import type { Job } from '../api/jobContract'
import { q } from '../api/queries'
import { commandLabel } from '../commands/catalog'
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
import '../jobs/jobProgress'
import { stateBadge } from '../jobs/progress'
import { define, h, hx } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { jobHref, pageHref } from '../lib/runner'
import { card, empty, errorNotice, link, loading, notice } from '../ui/build'
import { card, empty, errorNotice, glyph, link, loading, notice } from '../ui/build'
import { dateTime, duration } from '../ui/format'
/** The `id` query parameter, or null for the list (an empty `?id=` too). */
@ -27,18 +27,32 @@ function params(j: Job): string {
.join(' ')
}
/** The command's glyph painted, its name spoken. */
function commandGlyph(command: Job['command']): HTMLSpanElement {
return glyph(COMMAND_ICON[command], commandLabel(command), 'job-cmd')
}
/** One row, plus its duration cell so ticks can refresh just that. */
function row(j: Job): { tr: HTMLTableRowElement; took: HTMLTableCellElement } {
const args = params(j)
// Param values are content (ids, minutes); their keys are spoken only.
const values = Object.values(j.params).map(String).join(' ')
const took = h('td', { class: 'num mono' })
const summary = j.summary ?? j.progress?.label ?? ''
const tr = h(
'tr',
{},
h('td', {}, h('a', { href: jobHref(j.id) }, commandLabel(j.command)), args ? h('span', { class: 'muted mono' }, ` ${args}`) : null),
h(
'td',
{},
h('a', { href: jobHref(j.id) }, commandGlyph(j.command)),
args ? h('span', { class: 'muted mono' }, h('span', { 'aria-hidden': 'true' }, ` ${values}`), h('span', { class: 'sr-only' }, ` ${args}`)) : null,
// The server's summary sentence is spoken only; the state badge paints the outcome.
summary ? h('span', { class: 'sr-only' }, ` ${summary}`) : null,
),
h('td', {}, stateBadge(j.state)),
h('td', { class: 'muted' }, dateTime(j.created_at)),
took,
h('td', { class: 'ellipsis' }, j.summary ?? j.progress?.label ?? ''),
)
return { tr, took }
}
@ -72,18 +86,17 @@ export class JobListElement extends LiveElement {
h(
'tr',
{},
h('th', { scope: 'col' }, 'Command'),
h('th', { scope: 'col' }, 'State'),
h('th', { scope: 'col' }, 'Started'),
h('th', { scope: 'col', class: 'num' }, 'Took'),
h('th', { scope: 'col' }, 'Summary'),
h('th', { scope: 'col' }, glyph('⌨️', 'Command')),
h('th', { scope: 'col' }, glyph('🚦', 'State')),
h('th', { scope: 'col' }, glyph('🕐', 'Started')),
h('th', { scope: 'col', class: 'num' }, glyph('⏱️', 'Took')),
),
),
this.body,
),
)
const title = h('h1', {}, 'Jobs')
const sub = h('p', { class: 'sub' }, 'The last 50 jobs. They keep running if you close the page.')
const title = h('h1', { class: 'sr-only' }, 'Jobs')
const sub = h('p', { class: 'sr-only' }, 'The last 50 jobs. They keep running if you close the page.')
this.replaceChildren(pageHead(title, sub, null), card(null, [this.status, this.table]))
this.watch(q.jobs)
this.tick(1000)
@ -112,13 +125,16 @@ export class JobListElement extends LiveElement {
}
function notFound(id: string, error: ApiFailure): HTMLDivElement {
return notice(
// ❓ + the id painted; the explanation and the server's message are spoken.
const el = notice(
'warning',
'Job not found',
h('p', { class: 'm0' }, 'There is no job ', h('span', { class: 'mono' }, id), '. It may have been pruned: the history keeps the last 50.'),
error.message ? h('p', { class: 'm0 muted' }, error.message) : null,
h('p', { class: 'm0' }, h('a', { href: pageHref('/jobs') }, 'See all jobs')),
null,
h('p', { class: 'm0' }, h('span', { 'aria-hidden': 'true' }, '❓ '), h('span', { class: 'mono' }, id)),
h('p', { class: 'm0' }, link(pageHref('/jobs'), glyph('📋', 'See all jobs'), '')),
)
el.dataset.code = 'not_found'
el.setAttribute('aria-label', `Job not found. There is no job ${id}. It may have been pruned: the history keeps the last 50.${error.message ? ` ${error.message}` : ''}`)
return el
}
/** `/jobs/?id=…`: one job. `<job-progress>` is mounted once and owns itself. */
@ -139,7 +155,7 @@ export class JobDetailElement extends LiveElement {
this.sub = h('p', { class: 'sub' })
this.status = h('div', { class: 'contents' })
this.mounted = false
this.replaceChildren(pageHead(this.heading, this.sub, link(pageHref('/jobs'), 'All jobs', 'btn btn-ghost')), this.status)
this.replaceChildren(pageHead(this.heading, this.sub, link(pageHref('/jobs'), glyph('📋', 'All jobs'), 'btn btn-ghost')), this.status)
// Subscribed by hand, not via watch(): an unknown id stops polling.
let live = true
const off = q.job(this.jobId).subscribe(() => {
@ -156,8 +172,13 @@ export class JobDetailElement extends LiveElement {
const id = this.jobId
const { data, error, loading: waiting } = q.job(id).state
const missing = !data && error instanceof ApiFailure && error.code === 'not_found' ? error : null
this.heading.textContent = data ? commandLabel(data.command) : missing ? 'Job not found' : 'Job'
this.sub.replaceChildren('Job ', h('span', { class: 'mono' }, id), data ? ` · created ${dateTime(data.created_at)}` : '')
// Heading: the command's glyph (❓ when the id is unknown, ⚙️ while loading), name spoken.
this.heading.replaceChildren(data ? commandGlyph(data.command) : missing ? glyph('❓', 'Job not found') : glyph('⚙️', 'Job'))
this.sub.replaceChildren(
h('span', { class: 'sr-only' }, 'Job '),
h('span', { class: 'mono' }, id),
data ? h('span', {}, h('span', { 'aria-hidden': 'true' }, ' · 🕐 '), h('span', { class: 'sr-only' }, ' · created '), dateTime(data.created_at)) : '',
)
this.status.replaceChildren(
...(missing ? [notFound(id, missing)] : error ? [errorNotice(error)] : waiting ? [loading('job')] : []),
)

View File

@ -108,10 +108,10 @@ describe('Library page', () => {
view.remove()
at('/library/#view=installed')
window.dispatchEvent(new HashChangeEvent('hashchange'))
expect(view.querySelector('[aria-pressed="true"]')).toHaveTextContent('All games')
expect(view.querySelector('[aria-pressed="true"]')).toHaveAttribute('aria-label', 'All games')
page.append(view) // re-attached: same controls, view re-read from the hash
expect(view.querySelectorAll('.seg')).toHaveLength(1)
expect(view.querySelector('[aria-pressed="true"]')).toHaveTextContent('Installed')
expect(view.querySelector('[aria-pressed="true"]')).toHaveAttribute('aria-label', 'Installed')
})
it('says when nothing is installed', async () => {

View File

@ -8,14 +8,15 @@ import { define, h, hx } from '../lib/dom'
import { LiveElement } from '../lib/element'
import '../library/gameBrowser'
import { readHash, writeHash } from '../library/hashState'
import { card, empty, errorNotice, loading } from '../ui/build'
import { card, empty, errorNotice, glyph, loading, pill } from '../ui/build'
import { bytes } from '../ui/format'
type View = 'all' | 'installed'
const VIEWS: [View, string][] = [
['all', 'All games'],
['installed', 'Installed'],
/** View key, spoken label, painted glyph. */
const VIEWS: [View, string, string][] = [
['all', 'All games', '🗂️'],
['installed', 'Installed', '💾'],
]
const viewFromHash = (): View => (readHash().get('view') === 'installed' ? 'installed' : 'all')
@ -65,10 +66,10 @@ export class InstalledTableElement extends LiveElement {
h(
'tr',
{},
h('th', { scope: 'col' }, 'Game'),
h('th', { scope: 'col' }, 'App id'),
h('th', { scope: 'col', class: 'num' }, 'Size'),
h('th', { scope: 'col' }, 'Role'),
h('th', { scope: 'col' }, glyph('🎮', 'Game')),
h('th', { scope: 'col' }, glyph('#', 'App id')),
h('th', { scope: 'col', class: 'num' }, glyph('💽', 'Size')),
h('th', { scope: 'col' }, glyph('🏷️', 'Role')),
),
),
h(
@ -84,9 +85,9 @@ export class InstalledTableElement extends LiveElement {
h(
'td',
{},
g.assigned ? h('span', { class: 'pill pill-accent' }, 'assigned') : null,
g.protected ? h('span', { class: 'pill pill-neutral' }, 'protected') : null,
!g.assigned && !g.protected ? h('span', { class: 'muted' }, 'uninstall candidate') : null,
g.assigned ? pill('accent', 'assigned', '🎯') : null,
g.protected ? pill('neutral', 'protected', '🛡️') : null,
!g.assigned && !g.protected ? glyph('🗑️', 'uninstall candidate', 'muted') : null,
),
),
),
@ -95,7 +96,17 @@ export class InstalledTableElement extends LiveElement {
)
: null,
],
{ aside: data ? h('span', { class: 'muted' }, `${games.length} games · ${bytes(total)}`) : null },
{
icon: '💾',
aside: data
? h(
'span',
{ class: 'muted' },
h('span', { 'aria-hidden': 'true' }, `🎮 ${games.length} · 💽 ${bytes(total)}`),
h('span', { class: 'sr-only' }, `${games.length} games · ${bytes(total)}`),
)
: null,
},
),
)
}
@ -120,18 +131,19 @@ export class LibraryViewElement extends HTMLElement {
const seg = h(
'div',
{ class: 'seg', role: 'group', 'aria-label': 'Library view' },
VIEWS.map(([key, label]) => {
VIEWS.map(([key, label, icon]) => {
const btn = h(
'button',
{
type: 'button',
class: 'btn btn-ghost btn-small',
'aria-label': label,
onclick: () => {
writeHash({ view: key === 'all' ? null : key })
this.show(key)
},
},
label,
h('span', { 'aria-hidden': 'true' }, icon),
)
this.buttons.set(key, btn)
return btn

View File

@ -8,7 +8,7 @@ import { applyFilters } from '../estimate'
import { timelineChart } from '../lib/charts/timeline'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { card, errorNotice, link, loading } from '../ui/build'
import { card, errorNotice, glyph, link, loading } from '../ui/build'
import { defaultFilters } from './backlog/plannerFilters'
import { summaryCards } from './backlog/summary'
@ -19,9 +19,10 @@ export class BacklogOverviewElement extends LiveElement {
protected update(): void {
const { data, error } = q.dataset.state
const aside = link('/backlog/', 'Open the planner')
const aside = link('/backlog/', glyph('➡️', 'Open the planner'))
const icon = '📚'
if (!data) {
this.replaceChildren(card('Backlog outlook', error ? errorNotice(error) : loading('backlog'), { aside }))
this.replaceChildren(card('Backlog outlook', error ? errorNotice(error) : loading('backlog'), { aside, icon }))
return
}
const filters = defaultFilters(data.defaults)
@ -43,7 +44,7 @@ export class BacklogOverviewElement extends LiveElement {
}),
timelineChart(result, filters, data.state),
),
{ aside },
{ aside, icon },
),
)
}

View File

@ -7,6 +7,11 @@ import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { card, empty, errorNotice, loading } from '../ui/build'
/** Glyphs and numbers painted, the sentence spoken. */
function glyphText(painted: string, spoken: string): HTMLSpanElement {
return h('span', { class: 'muted' }, h('span', { 'aria-hidden': 'true' }, painted), h('span', { class: 'sr-only' }, spoken))
}
/** Page subtitle: the assigned game, once known. */
export class PicksSubElement extends LiveElement {
protected override setup(): void {
@ -41,7 +46,13 @@ export class ManualPicksElement extends LiveElement {
h(
'li',
{ class: 'row' },
h('span', { class: 'grow' }, h('strong', {}, p.name), ' ', h('span', { class: 'muted' }, `· picked ${p.age_days} d ago · ${p.app_id}`)),
h(
'span',
{ class: 'grow' },
h('strong', {}, p.name),
' ',
glyphText(`· 🕐 ${p.age_days} d · ${p.app_id}`, `· picked ${p.age_days} d ago · ${p.app_id}`),
),
abandon(p.app_id),
),
),
@ -50,7 +61,7 @@ export class ManualPicksElement extends LiveElement {
h(
'li',
{ class: 'row' },
h('span', { class: 'grow' }, h('strong', {}, p.name), ' ', h('span', { class: 'muted' }, `· kept · no lock · ${p.app_id}`)),
h('span', { class: 'grow' }, h('strong', {}, p.name), ' ', glyphText(`· 📌 🔓 · ${p.app_id}`, `· kept · no lock · ${p.app_id}`)),
abandon(p.app_id),
),
),
@ -58,7 +69,7 @@ export class ManualPicksElement extends LiveElement {
none
? h('div', { class: 'actions' }, commandButton({ name: 'abandon-pick', label: 'Abandon a pick by app id…' }))
: null,
]),
], { icon: '📌' }),
)
}
}

View File

@ -29,19 +29,23 @@ describe('setup-form', () => {
expect(keyBox()).toHaveValue('')
expect(keyBox()).toHaveFocus()
await waitFor(() => {
expect(keyBox()).toHaveAttribute('placeholder', expect.stringContaining('A key is stored'))
expect(keyBox()).toHaveAttribute('data-stored', 'true')
})
expect(keyBox().placeholder).toMatch(/^🔒 •{32}$/)
expect(idBox()).toHaveValue(ID)
expect(screen.queryByText('Not configured yet')).toBeNull()
expect(screen.getByRole('link', { name: 'steamcommunity.com/dev/apikey' })).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'steamcommunity.com/dev/apikey' })).toHaveAttribute('href', 'https://steamcommunity.com/dev/apikey')
expect(screen.getByRole('link', { name: 'steamid.io' })).toHaveAttribute('href', 'https://steamid.io')
})
it('warns on a first run, with a hint for the empty form', async () => {
stubApi({ 'GET /api/setup': status({ configured: false, has_api_key: false, steam_id: null }) })
show()
expect(await screen.findByText('Not configured yet')).toBeInTheDocument()
expect(keyBox()).toHaveAttribute('placeholder', '32 hex characters')
expect(keyBox()).toHaveAttribute('data-stored', 'false')
expect(keyBox().placeholder).toHaveLength(32)
expect(idBox()).toHaveValue('')
expect(idBox().placeholder).toMatch(/^7656·{13}$/)
})
it('shows loading', async () => {
@ -68,6 +72,8 @@ describe('setup-form', () => {
expect(screen.getByText('A SteamID64 is 17 digits and starts with 7656.')).toBeInTheDocument()
expect(keyBox()).toHaveAttribute('aria-invalid', 'true')
expect(keyBox()).toHaveClass('input-bad')
expect(keyBox().nextElementSibling).toHaveTextContent('⚠️ 6/32')
expect(idBox().nextElementSibling).toHaveTextContent('⚠️ 3/17')
expect(bodiesOf(mock, 'POST /api/setup')).toEqual([])
await userEvent.clear(keyBox())
await userEvent.type(keyBox(), KEY)

View File

@ -10,7 +10,11 @@ import { Action } from '../lib/action'
import { append, define, h, type Child } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { invalidateAll } from '../lib/query'
import { card, errorNotice, loading, notice } from '../ui/build'
import { card, errorNotice, glyph, loading, notice } from '../ui/build'
/** A notice's title and sentence, spoken only (textgate); its tone icon is painted. */
const spoken = (title: string, text: string): HTMLSpanElement =>
h('span', { class: 'sr-only' }, h('strong', {}, title), ` ${text}`)
const KEY_RE = /^[0-9A-Fa-f]{32}$/
const ID_RE = /^7656\d{13}$/
@ -23,27 +27,44 @@ export function idError(id: string): string | null {
return ID_RE.test(id.trim()) ? null : 'A SteamID64 is 17 digits and starts with 7656.'
}
const KEY_HELP = (): Child[] => [
'Get one at ',
h('a', { href: 'https://steamcommunity.com/dev/apikey', target: '_blank', rel: 'noreferrer' }, 'steamcommunity.com/dev/apikey'),
'. It is never shown again.',
// Textgate: help is a 🔗 to where the value comes from; its sentence is spoken only.
const helpLink = (href: string, spoken: string, sentence: string): Child[] => [
h('a', { href, target: '_blank', rel: 'noreferrer', class: 'setup-link', 'aria-label': spoken }, '🔗'),
h('span', { class: 'sr-only' }, sentence),
]
const ID_HELP = (): Child[] => ['Your profile URL or steamid.io shows it.']
const KEY_HELP = (): Child[] =>
helpLink('https://steamcommunity.com/dev/apikey', 'steamcommunity.com/dev/apikey', 'Get one at steamcommunity.com/dev/apikey. It is never shown again.')
const ID_HELP = (): Child[] => helpLink('https://steamid.io', 'steamid.io', 'Your profile URL or steamid.io shows it.')
/** Placeholders paint the expected shape: one dot per character, the fixed 7656 prefix. */
const KEY_SHAPE = '·'.repeat(32)
const KEY_STORED = `🔒 ${'•'.repeat(32)}`
const ID_SHAPE = `7656${'·'.repeat(13)}`
interface Field {
input: HTMLInputElement
help: HTMLParagraphElement
hint: () => Child[]
baseClass: string
/** Characters a valid value has; a bad value paints `⚠️ typed/want`. */
want: number
}
function field(id: string, label: string, input: HTMLInputElement, hint: () => Child[]): { el: HTMLDivElement; f: Field } {
function field(id: string, label: string, icon: string, input: HTMLInputElement, hint: () => Child[], want: number): { el: HTMLDivElement; f: Field } {
const help = h('p', { id: `${id}-help`, class: 'field-help' }, hint())
input.id = id
input.setAttribute('aria-describedby', `${id}-help`)
return {
el: h('div', { class: 'form-field' }, h('label', { for: id, class: 'field-label' }, label), input, help),
f: { input, help, hint, baseClass: input.className },
el: h(
'div',
{ class: 'form-field' },
// The glyph is painted beside a spoken-only <label>, so the label's text stays exactly `label`.
h('span', { class: 'field-label', 'aria-hidden': 'true' }, icon),
h('label', { for: id, class: 'sr-only' }, label),
input,
help,
),
f: { input, help, hint, baseClass: input.className, want },
}
}
@ -71,10 +92,19 @@ export class SetupFormElement extends LiveElement {
const key = field(
'setup-key',
'Steam Web API key',
'🔑',
h('input', { class: 'input mono', type: 'password', autocomplete: 'off', spellcheck: 'false', autofocus: true }),
KEY_HELP,
32,
)
const id = field(
'setup-id',
'SteamID64',
'🆔',
h('input', { class: 'input mono input-num', inputmode: 'numeric', placeholder: ID_SHAPE }),
ID_HELP,
17,
)
const id = field('setup-id', 'SteamID64', h('input', { class: 'input mono input-num', inputmode: 'numeric' }), ID_HELP)
this.keyField = key.f
this.idField = id.f
key.f.input.addEventListener('input', () => {
@ -116,10 +146,12 @@ export class SetupFormElement extends LiveElement {
...(error ? [errorNotice(error)] : []),
...(!data && !error ? [loading('setup')] : []),
...(data && !data.configured
? [notice('warning', 'Not configured yet', 'Every other screen needs these two values first.')]
? [notice('warning', null, spoken('Not configured yet', 'Every other screen needs these two values first.'))]
: []),
)
this.keyField.input.placeholder = data?.has_api_key ? 'A key is stored — type a new one to replace it' : '32 hex characters'
// 🔒 + filled dots: a key is stored (typing replaces it); hollow dots: none yet.
this.keyField.input.placeholder = data?.has_api_key ? KEY_STORED : KEY_SHAPE
this.keyField.input.dataset.stored = String(data?.has_api_key ?? false)
if (!this.idEdited) this.idField.input.value = data?.steam_id ?? ''
this.render()
}
@ -130,24 +162,35 @@ export class SetupFormElement extends LiveElement {
this.mark(this.idField, idError(this.idField.input.value))
this.saved.replaceChildren(
...(this.success
? [notice('success', 'Saved', 'Steam accepted the key. ', h('a', { href: '/' }, 'Go to the dashboard'), '.')]
? [
notice(
'success',
null,
spoken('Saved', 'Steam accepted the key.'),
h('a', { href: '/', class: 'btn btn-ghost btn-small', 'aria-label': 'Go to the dashboard' }, '🏠'),
),
]
: []),
)
this.failure.replaceChildren(...(this.save.error ? [errorNotice(this.save.error)] : []))
this.submit.disabled = this.save.pending
this.submit.textContent = this.save.pending ? 'Checking with Steam…' : 'Save and verify'
// ⏳ while Steam checks, ✔️ to save; the words are spoken only.
this.submit.replaceChildren(this.save.pending ? glyph('⏳', 'Checking with Steam…') : glyph('✔️', 'Save and verify'))
}
private mark(f: Field, problem: string | null): void {
const bad = this.touched && problem !== null
f.input.className = bad ? `${f.baseClass} input-bad` : f.baseClass
f.input.setAttribute('aria-invalid', String(bad))
const shown = f.help.dataset.bad === String(bad) && (!bad || f.help.textContent === problem)
if (shown) return
// A bad value paints ⚠️ and how many characters it has of the `want` it needs.
const count = `⚠️ ${f.input.value.trim().length}/${f.want}`
const state = bad ? `${problem}|${count}` : 'ok'
if (f.help.dataset.state === state) return
f.help.dataset.state = state
f.help.dataset.bad = String(bad)
f.help.className = bad ? 'field-help text-danger' : 'field-help'
f.help.replaceChildren()
append(f.help, bad ? problem : f.hint())
append(f.help, bad ? [h('span', { 'aria-hidden': 'true', class: 'mono' }, count), h('span', { class: 'sr-only' }, problem)] : f.hint())
}
private async store(): Promise<void> {

View File

@ -0,0 +1,8 @@
// Textgate helper: paint glyphs, numbers and names; speak the sentence.
import { h, type Child } from '../lib/dom'
/** `painted` is shown (glyphs, numbers, names); `spoken` is the sentence a screen reader hears. */
export function said(spoken: string, ...painted: Child[]): HTMLSpanElement {
return h('span', {}, h('span', { 'aria-hidden': 'true' }, ...painted), h('span', { class: 'sr-only' }, spoken))
}

View File

@ -3,23 +3,28 @@ import { describe, expect, it } from 'vitest'
import { q } from '../api/queries'
import { makeStatus } from '../test/fixtures'
import { mount, stubApi } from '../test/harness'
import { visibleWords } from '../test/visibleWords'
import './store'
describe('store notice', () => {
it('says the store is blocked', async () => {
stubApi({ 'GET /api/status': makeStatus({ store_blocked: true }) })
mount('<store-notice></store-notice>')
expect(await screen.findByText('Store blocked')).toBeInTheDocument()
expect(screen.getByText(/capped at 30 minutes/)).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveClass('notice-info')
const el = mount('<store-notice></store-notice>')
const notice = await screen.findByRole('status')
expect(notice).toHaveClass('notice-info')
expect(notice).toHaveAttribute('data-blocked', 'true')
expect(screen.getByText(/Store blocked\. .*capped at 30 minutes/)).toHaveClass('sr-only')
expect(visibleWords(el)).toEqual([])
})
it('warns when it is open', async () => {
stubApi({ 'GET /api/status': makeStatus({ store_blocked: false }) })
mount('<store-notice></store-notice>')
expect(await screen.findByText('Store unblocked')).toBeInTheDocument()
expect(screen.getByText(/re-blocks automatically/)).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveClass('notice-warning')
const el = mount('<store-notice></store-notice>')
const notice = await screen.findByRole('status')
expect(notice).toHaveClass('notice-warning')
expect(notice).toHaveAttribute('data-blocked', 'false')
expect(screen.getByText(/Store unblocked\. .*re-blocks automatically/)).toHaveClass('sr-only')
expect(visibleWords(el)).toEqual([])
})
it('shows no notice until the status is known', () => {

View File

@ -2,7 +2,7 @@
// right now. Nothing shows until the status is known.
import { q } from '../api/queries'
import { define } from '../lib/dom'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { notice } from '../ui/build'
@ -17,11 +17,13 @@ export class StoreNoticeElement extends LiveElement {
this.replaceChildren()
return
}
this.replaceChildren(
data.store_blocked
? notice('info', 'Store blocked', 'Unblocking takes a typed phrase and is capped at 30 minutes.')
: notice('warning', 'Store unblocked', 'The store is open right now; it re-blocks automatically.'),
)
// Textgate: 🛒 + lock state painted (tone is the 2nd channel), the sentence spoken.
const [tone, icon, spoken] = data.store_blocked
? (['info', '🛒🔒', 'Store blocked. Unblocking takes a typed phrase and is capped at 30 minutes.'] as const)
: (['warning', '🛒🔓', 'Store unblocked. The store is open right now; it re-blocks automatically.'] as const)
const el = notice(tone, null, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken))
el.dataset.blocked = String(data.store_blocked)
this.replaceChildren(el)
}
}

View File

@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it } from 'vitest'
import { q } from '../../api/queries'
import { makeJob, makeSpec } from '../../test/fixtures'
import { apiError, bodiesOf, flush, installEventSource, mount, stubApi, type Handler } from '../../test/harness'
import { dateTime } from '../../ui/format'
import { restorePhrase } from './backupsCard'
const BACKUP = { id: '20261010-100000', created_at: '2026-10-10T10:00:00Z', reason: 'before reset', size_bytes: 2048 }
@ -25,7 +26,7 @@ const openDialog = async () => {
await userEvent.click(await screen.findByRole('button', { name: 'Restore…' }))
return screen.findByRole('dialog', { name: `Restore backup ${BACKUP.id}` })
}
const phraseBox = () => screen.getByLabelText('Type the phrase to confirm')
const phraseBox = () => screen.getByLabelText(/Type the phrase to confirm/)
describe('restorePhrase', () => {
it('mirrors the server friction phrase', () => {
@ -40,10 +41,22 @@ describe('backups-card', () => {
show()
expect(await screen.findByText(BACKUP.id)).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'State backups' })).toBeInTheDocument()
expect(screen.getByText(/before reset · 2.0 KB/)).toBeInTheDocument()
expect(document.querySelector('[data-reason="before reset"]')).toHaveTextContent(/♻️.*before reset · 2.0 KB/)
expect(await screen.findByRole('button', { name: 'Reset all state…' })).toBeInTheDocument()
})
it('paints a generic archive glyph for an unknown reason, in the list and the dialog', async () => {
show({ 'GET /api/backups': [{ ...BACKUP, reason: 'manual' }] })
expect(await screen.findByText(BACKUP.id)).toBeInTheDocument()
const row = document.querySelector('[data-reason="manual"]')
expect(row?.querySelector('[aria-hidden="true"]')?.textContent).toBe('🗄️')
expect(row?.querySelector('.sr-only')?.textContent).toBe('manual')
await userEvent.click(screen.getByRole('button', { name: 'Restore…' }))
const dialog = await screen.findByRole('dialog', { name: `Restore backup ${BACKUP.id}` })
const painted = [...(dialog.querySelector('p.row')?.querySelectorAll(':scope > [aria-hidden="true"]') ?? [])].map((e) => e.textContent)
expect(painted).toEqual([`🗄️ ${BACKUP.id} · ${dateTime(BACKUP.created_at)}`, '🗄️'])
})
it('says when there are none', async () => {
show({ 'GET /api/backups': [] })
expect(await screen.findByText('No backups yet.')).toBeInTheDocument()

View File

@ -15,7 +15,7 @@ import '../../jobs/jobProgress'
import { Action } from '../../lib/action'
import { define, h, hx } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { card, empty, errorNotice, loading } from '../../ui/build'
import { card, empty, errorNotice, glyph, loading } from '../../ui/build'
import { Modal } from '../../ui/dialog'
import { bytes, dateTime } from '../../ui/format'
@ -23,6 +23,10 @@ import { bytes, dateTime } from '../../ui/format'
// know it. Mirrors FRICTION["restore-backup"] in _friction.py.
export const restorePhrase = (id: string): string => `restore backup ${id}`
/** Why a backup was taken, as a glyph (reason words spoken only). */
const REASON_ICON: Record<string, string> = { 'before reset': '♻️', nightly: '🌙' }
const reasonGlyph = (reason: string): HTMLSpanElement => glyph(REASON_ICON[reason] ?? '🗄️', reason)
/** One restore: phrase form, then the job it started. */
export class RestoreDialog {
readonly modal: Modal
@ -57,14 +61,21 @@ export class RestoreDialog {
if (this.matches() && !this.restore.pending) void this.run(onClose)
},
},
h('p', { class: 'm0' }, `Replaces the current state with the backup from ${dateTime(backup.created_at)} (${backup.reason}).`),
// Painted: the backup's id, date and reason glyph; the sentence is spoken only.
h(
'p',
{ class: 'm0 row' },
h('span', { class: 'sr-only' }, `Replaces the current state with the backup from ${dateTime(backup.created_at)} (${backup.reason}).`),
h('span', { 'aria-hidden': 'true', class: 'mono' }, `🗄️ ${backup.id} · ${dateTime(backup.created_at)}`),
h('span', { 'aria-hidden': 'true' }, REASON_ICON[backup.reason] ?? '🗄️'),
),
this.field.el,
this.failure,
h(
'div',
{ class: 'actions' },
this.submit,
h('button', { type: 'button', class: 'btn btn-ghost', onclick: onClose }, 'Cancel'),
h('button', { type: 'button', class: 'btn btn-ghost', onclick: onClose }, glyph('✖️', 'Cancel')),
),
)
this.modal.render(form)
@ -77,7 +88,7 @@ export class RestoreDialog {
private sync(): void {
this.submit.disabled = !this.matches() || this.restore.pending
this.submit.textContent = this.restore.pending ? 'Restoring…' : 'Restore'
this.submit.replaceChildren(this.restore.pending ? glyph('⏳', 'Restoring…') : glyph('⏮️', 'Restore'))
this.failure.replaceChildren(...(this.restore.error ? [errorNotice(this.restore.error)] : []))
}
@ -90,7 +101,7 @@ export class RestoreDialog {
'div',
{ class: 'stack' },
hx('job-progress', { 'job-id': out.value.id }),
h('div', { class: 'actions' }, h('button', { type: 'button', class: 'btn btn-ghost', onclick: onClose }, 'Close')),
h('div', { class: 'actions' }, h('button', { type: 'button', class: 'btn btn-ghost', onclick: onClose }, glyph('✖️', 'Close'))),
),
)
this.modal.focusFirst()
@ -102,8 +113,8 @@ export class BackupsCardElement extends LiveElement {
private readonly list = h('ul', { class: 'rows' })
private readonly root = card(
'State backups',
[h('p', { class: 'field-help m0' }, 'Reset takes a timestamped backup first, so it can be undone here.'), this.status, this.list],
{ aside: hx('command-button', { name: 'reset', label: 'Reset all state…' }) },
[h('p', { class: 'sr-only' }, 'Reset takes a timestamped backup first, so it can be undone here.'), this.status, this.list],
{ aside: hx('command-button', { name: 'reset', label: 'Reset all state…' }), icon: '🗄️' },
)
private dialog: RestoreDialog | null = null
private shownKey = ''
@ -134,7 +145,13 @@ export class BackupsCardElement extends LiveElement {
'li',
{ class: 'row' },
h('span', { class: 'mono' }, b.id),
h('span', { class: 'muted grow' }, `${dateTime(b.created_at)} · ${b.reason} · ${bytes(b.size_bytes)}`),
h(
'span',
{ class: 'muted grow', 'data-reason': b.reason },
`${dateTime(b.created_at)} · `,
reasonGlyph(b.reason),
` · ${bytes(b.size_bytes)}`,
),
h(
'button',
{
@ -144,7 +161,7 @@ export class BackupsCardElement extends LiveElement {
this.open(b)
},
},
'Restore…',
glyph('⏮️', 'Restore…'),
),
),
),

View File

@ -44,11 +44,18 @@ describe('daemon-card', () => {
expect(await screen.findByText('4242')).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'Enforcer daemon' })).toBeInTheDocument()
expect(screen.getByText('running')).toBeInTheDocument()
expect(screen.getByText(/ago/)).toBeInTheDocument()
expect(screen.getByLabelText(/ago/)).toBeInTheDocument()
expect(screen.getByText('running').closest('[data-state]')).toHaveAttribute('data-state', 'running')
expect(journal()).toHaveTextContent(/line one\s+line two/)
expect(screen.queryByText('Daemon unreachable')).toBeNull()
})
it('paints a just-started daemon as 0 min and speaks "just now"', async () => {
show(daemon({ started_at: new Date().toISOString() }))
const up = await screen.findByLabelText('just now')
expect(up.querySelector('[aria-hidden="true"]')?.textContent).toBe('0 min')
})
it('restarts through the runner when allowed', async () => {
show(daemon())
await userEvent.click(await screen.findByRole('button', { name: 'Restart daemon…' }))
@ -77,8 +84,8 @@ describe('daemon-card', () => {
expect(button).toHaveAttribute('aria-disabled', 'true')
await userEvent.click(button)
expect(run).not.toHaveBeenCalled()
expect(screen.getByText('No journal lines.')).toBeInTheDocument()
expect(screen.getAllByText('—')).toHaveLength(2)
expect(journal()).toHaveTextContent(/^—$/)
expect(screen.getAllByText('—')).toHaveLength(3)
})
it('offers the demo run', async () => {

View File

@ -8,19 +8,36 @@ import { q } from '../../api/queries'
import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { runner } from '../../lib/runner'
import { card, commandLine, errorNotice, facts, loading, notice } from '../../ui/build'
import type { DaemonState } from '../../api/contract'
import { card, commandLine, errorNotice, facts, glyph, loading, notice } from '../../ui/build'
import { ago, clock } from '../../ui/format'
/** "3 h ago" painted as "3 h" (a number + unit), the full phrase spoken. */
function since(iso: string): HTMLSpanElement {
const full = ago(iso)
const painted = full === 'just now' ? '0 min' : full.replace(/ ago$/, '')
return h('span', { 'aria-label': full }, h('span', { 'aria-hidden': 'true' }, painted))
}
/** Milliseconds left on the restart rate limit; 0 when free. */
export function restartWaitMs(availableAt: string | null, now: number = Date.now()): number {
return availableAt ? Math.max(0, Date.parse(availableAt) - now) : 0
}
/** Daemon state: glyph painted, the state word spoken. */
const STATE_ICON: Record<DaemonState, string> = { running: '🟢', restarting: '🔄', unreachable: '🔴' }
function unreachableNotice(): HTMLDivElement {
// Textgate: ⛔ + the command to run are painted; the explanation is spoken only.
return notice(
'danger',
'Daemon unreachable',
'Privileged actions (store unblock, gaming reset/block/unblock, restart) are unavailable. Check it from a terminal:',
null,
h(
'span',
{ class: 'sr-only' },
h('strong', {}, 'Daemon unreachable'),
' Privileged actions (store unblock, gaming reset/block/unblock, restart) are unavailable. Check it from a terminal:',
),
commandLine('systemctl status steam-backlog-enforcer'),
)
}
@ -49,16 +66,16 @@ export class DaemonCardElement extends LiveElement {
runner.run('enforce', { demo: 1 })
},
},
'Demo run (enforce --demo)…',
glyph('🧪', 'Demo run (enforce --demo)…'),
)
private readonly parts = [
this.alert,
this.factsSlot,
h('div', { class: 'actions' }, this.restart, this.demo),
h('h3', { class: 'h3' }, 'Journal'),
h('h3', { class: 'h3' }, glyph('📜', 'Journal')),
this.journal,
]
private readonly root = card('Enforcer daemon', [this.status, this.body])
private readonly root = card('Enforcer daemon', [this.status, this.body], { icon: '🛡️' })
private shown = false
private canRestart = false
private unreachable = false
@ -87,20 +104,27 @@ export class DaemonCardElement extends LiveElement {
}
this.factsSlot.replaceChildren(
facts([
['State', data.state],
['PID', data.pid ?? '—'],
['Up since', data.started_at ? ago(data.started_at) : '—'],
[glyph('📡', 'State'), h('span', { 'data-state': data.state }, glyph(STATE_ICON[data.state], data.state))],
[glyph('#️⃣', 'PID'), data.pid ?? '—'],
[glyph('⏱️', 'Up since'), data.started_at ? since(data.started_at) : '—'],
]),
)
this.canRestart = waitMs === 0 && data.state === 'running'
this.restart.setAttribute('aria-disabled', String(!this.canRestart))
this.restart.textContent = waitMs > 0 ? `Restart available in ${clock(waitMs / 1000)}` : 'Restart daemon…'
// Rate limited: ⏳ + the clock counting down; free: 🔄. Words spoken only.
const wait = clock(waitMs / 1000)
this.restart.replaceChildren(
waitMs > 0
? h('span', { 'aria-label': `Restart available in ${wait}` }, h('span', { 'aria-hidden': 'true' }, `⏳ ${wait}`))
: glyph('🔄', 'Restart daemon…'),
)
this.fillJournal(data.journal_tail)
}
/** New text only when it changed; follow the tail unless scrolled up. */
private fillJournal(lines: string[]): void {
const text = lines.length ? lines.join('\n') : 'No journal lines.'
// The journal lines are the daemon's own log (content); empty paints a dash.
const text = lines.length ? lines.join('\n') : '—'
const j = this.journal
if (j.textContent === text) return
const following = j.scrollHeight - j.scrollTop - j.clientHeight < 8

View File

@ -6,7 +6,7 @@ import { q } from '../../api/queries'
import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { ServerRestart } from '../../shell/serverRestart'
import { card, errorNotice, facts, loading, notice } from '../../ui/build'
import { card, errorNotice, facts, glyph, loading, notice } from '../../ui/build'
import { ago, dateTime } from '../../ui/format'
export class ServerCardElement extends LiveElement {
@ -19,7 +19,7 @@ export class ServerCardElement extends LiveElement {
void this.restart.action.run()
},
})
private readonly root = card('Web server', [this.info, this.failure, h('div', { class: 'actions' }, this.button)])
private readonly root = card('Web server', [this.info, this.failure, h('div', { class: 'actions' }, this.button)], { icon: '🌐' })
private readonly restart = new ServerRestart(() => {
this.update()
})
@ -37,13 +37,13 @@ export class ServerCardElement extends LiveElement {
this.info.replaceChildren(
...(error ? [errorNotice(error)] : []),
...(!data && !error ? [loading('server health')] : []),
...(data?.stale ? [notice('warning', 'Stale', 'The code on disk is newer than this process.')] : []),
...(data?.stale ? [notice('warning', null, h('span', { class: 'sr-only' }, h('strong', {}, 'Stale'), ' The code on disk is newer than this process.'))] : []),
...(data
? [
facts([
['Version', h('span', { class: 'mono' }, data.version)],
['Started', `${dateTime(data.started_at)} (${ago(data.started_at)})`],
['Code', data.stale ? 'stale' : 'current'],
[glyph('🏷️', 'Version'), h('span', { class: 'mono' }, data.version)],
[glyph('🕒', 'Started'), h('span', { 'aria-label': `${dateTime(data.started_at)} (${ago(data.started_at)})` }, dateTime(data.started_at))],
[glyph('💾', 'Code'), data.stale ? glyph('⚠️', 'stale') : glyph('✅', 'current')],
]),
]
: []),
@ -51,7 +51,8 @@ export class ServerCardElement extends LiveElement {
const { action, restarting } = this.restart
this.failure.replaceChildren(...(action.error ? [errorNotice(action.error)] : []))
this.button.disabled = restarting || action.pending
this.button.textContent = restarting ? 'Restarting… the page reloads when it is back' : 'Restart server'
this.button.dataset.restarting = String(restarting)
this.button.replaceChildren(restarting ? glyph('⏳', 'Restarting… the page reloads when it is back') : glyph('🔄', 'Restart server'))
}
}

View File

@ -5,7 +5,7 @@ import { q } from '../../api/queries'
import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element'
import { pageHref } from '../../lib/runner'
import { card, facts, link } from '../../ui/build'
import { card, facts, glyph, link } from '../../ui/build'
export class SetupCardElement extends LiveElement {
protected override setup(): void {
@ -18,11 +18,11 @@ export class SetupCardElement extends LiveElement {
card(
'Setup',
facts([
['Configured', data ? (data.configured ? 'Yes' : 'No') : '…'],
['Steam API key', data ? (data.has_api_key ? 'Stored (never shown)' : 'Missing') : '…'],
['Steam ID', h('span', { class: 'mono' }, data?.steam_id ?? '—')],
[glyph('⚙️', 'Configured'), data ? (data.configured ? glyph('✅', 'Yes') : glyph('❌', 'No')) : '…'],
[glyph('🔑', 'Steam API key'), data ? (data.has_api_key ? glyph('🔒', 'Stored (never shown)') : glyph('❌', 'Missing')) : '…'],
[glyph('🆔', 'Steam ID'), h('span', { class: 'mono' }, data?.steam_id ?? '—')],
]),
{ aside: link(pageHref('/setup'), 'Open setup') },
{ aside: link(pageHref('/setup'), glyph('✏️', 'Open setup')), icon: '🔧' },
),
)
}

View File

@ -0,0 +1,66 @@
// Guard test (textgate-rework R6): the System and Setup pages paint glyphs,
// numbers, ids, dates and the daemon's own journal, never chrome words.
import { screen, waitFor } from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it } from 'vitest'
import { makeSpec } from '../../test/fixtures'
import { installEventSource, mount, stubApi } from '../../test/harness'
import { visibleWords } from '../../test/visibleWords'
import '../setup'
import './backupsCard'
import './daemonCard'
import './serverCard'
import './setupCard'
/** Content inside a painted string: sizes and backup ids (dates are numeric). */
const CONTENT = [/\d[\d.,]* (B|KB|MB|GB)\b/g, /\d{8}-\d{6}/g]
const chrome = (root: Element, allowed: string[] = []): string[] =>
visibleWords(root, allowed).filter((w) => /[A-Za-z]{2,}/.test(CONTENT.reduce((s, re) => s.replace(re, ''), w)))
beforeEach(installEventSource)
describe('textgate guard: system', () => {
it('server, setup, daemon and backup cards paint no words, stale and unreachable included', async () => {
stubApi({
'GET /api/server': { stale: true, started_at: '2026-10-10T10:00:00Z', version: '9.9.9' },
'GET /api/setup': { configured: false, has_api_key: false, steam_id: null },
'GET /api/daemon': { state: 'unreachable', started_at: null, pid: null, journal_tail: [], restart_available_at: null },
'GET /api/backups': [{ id: '20261010-100000', created_at: '2026-10-10T10:00:00Z', reason: 'nightly', size_bytes: 2048 }],
'GET /api/commands': [makeSpec('reset')],
'GET /api/jobs': [],
})
const el = mount('<server-card></server-card><setup-card></setup-card><daemon-card></daemon-card><backups-card></backups-card>')
await screen.findByText('20261010-100000')
await screen.findByText('Daemon unreachable')
await screen.findByText('Stale')
// The recovery command is content kuhy runs.
expect(chrome(el, ['systemctl status steam-backlog-enforcer'])).toEqual([])
})
it('the restore dialog paints no words', async () => {
stubApi({
'GET /api/backups': [{ id: '20261010-100000', created_at: '2026-10-10T10:00:00Z', reason: 'before reset', size_bytes: 2048 }],
'GET /api/commands': [makeSpec('reset')],
'GET /api/jobs': [],
})
const el = mount('<backups-card></backups-card>')
await userEvent.click(await screen.findByRole('button', { name: 'Restore…' }))
const dialog = await screen.findByRole('dialog')
// The phrase is the friction text kuhy types (settled decision 2).
expect(chrome(el, ['restore backup 20261010-100000'])).toEqual([])
expect(dialog).toBeInTheDocument()
})
it('the setup form paints no words, invalid values included', async () => {
stubApi({ 'GET /api/setup': { configured: false, has_api_key: false, steam_id: null } })
const el = mount('<setup-form></setup-form>')
await screen.findByText('Not configured yet')
await userEvent.type(screen.getByLabelText('Steam Web API key'), 'nothex')
await userEvent.click(screen.getByRole('button', { name: 'Save and verify' }))
await waitFor(() => {
expect(screen.getByLabelText('Steam Web API key')).toHaveAttribute('aria-invalid', 'true')
})
expect(chrome(el)).toEqual([])
})
})

View File

@ -6,7 +6,7 @@ import './health'
const server = (over = {}) => ({ stale: false, started_at: '2026-10-10T10:00:00Z', version: '1.2.3', ...over })
const daemon = (state: string) => ({ state, started_at: null, pid: null, journal_tail: [], restart_available_at: null })
const pill = (el: Element, text: string) => [...el.querySelectorAll('.pill')].find((p) => p.textContent === text)
const pill = (el: Element, text: string) => [...el.querySelectorAll('.pill')].find((p) => p.getAttribute('data-state') === text)
const never = () => new Promise(() => undefined)
describe('<health-badges>', () => {
@ -16,13 +16,17 @@ describe('<health-badges>', () => {
expect(pill(el, 'Server ok')).toHaveClass('pill-success')
expect(pill(el, 'Daemon …')).toHaveClass('pill-neutral')
expect(pill(el, 'Server ok')).not.toHaveAttribute('title')
expect(pill(el, 'Server ok')?.querySelector('[aria-hidden]')).toHaveTextContent('🌐✅')
expect(pill(el, 'Daemon …')?.querySelector('[aria-hidden]')).toHaveTextContent('🛡️…')
})
it('shows a healthy server with its version, and a running daemon', async () => {
stubApi({ 'GET /api/server': server(), 'GET /api/daemon': daemon('running') })
const el = mount('<health-badges></health-badges>')
await vi.waitFor(() => { expect(pill(el, 'Daemon running')).toHaveClass('pill-success') })
expect(pill(el, 'Server ok')).toHaveAttribute('title', 'v1.2.3')
// The version is spoken, never a tooltip (textgate).
expect(pill(el, 'Server ok')).not.toHaveAttribute('title')
expect(pill(el, 'Server ok')?.querySelector('.sr-only')).toHaveTextContent('Server ok v1.2.3')
})
it('flags a stale server and a restarting daemon', async () => {

View File

@ -4,10 +4,21 @@
import { q } from '../api/queries'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { errorNotice } from '../ui/build'
import { errorNotice, glyph } from '../ui/build'
import { ServerRestart } from './serverRestart'
const DAEMON_TONE = { running: 'success', restarting: 'warning', unreachable: 'danger' } as const
const STATE_GLYPH: Record<string, string> = { success: '✅', warning: '⚠️', danger: '⛔', neutral: '…' }
/** A health pill: glyphs painted, `text` (+ `extra`) spoken. `data-state` holds the words for tests. */
function badge(tone: string, icons: string, text: string, extra = ''): HTMLSpanElement {
return h(
'span',
{ class: `pill pill-${tone}`, 'data-state': text },
h('span', { 'aria-hidden': 'true' }, icons),
h('span', { class: 'sr-only' }, text + extra),
)
}
export class HealthBadgesElement extends LiveElement {
protected override setup(): void {
@ -20,12 +31,15 @@ export class HealthBadgesElement extends LiveElement {
const d = q.daemon.state.data?.state
const serverTone = server.error ? 'danger' : server.data?.stale ? 'warning' : 'success'
const serverText = server.error ? 'Server down' : server.data?.stale ? 'Server stale' : 'Server ok'
// Textgate: 🌐 server / 🛡️ daemon + a state glyph, on the tone colour; the
// words (and the version, formerly a tooltip) are spoken only.
const version = server.data ? ` v${server.data.version}` : ''
this.replaceChildren(
h(
'div',
{ class: 'health', 'aria-label': 'Health' },
h('span', { class: `pill pill-${serverTone}`, title: server.data ? `v${server.data.version}` : null }, serverText),
h('span', { class: `pill pill-${d ? DAEMON_TONE[d] : 'neutral'}` }, `Daemon ${d ?? '…'}`),
badge(serverTone, `🌐${STATE_GLYPH[serverTone]}`, serverText, version),
badge(d ? DAEMON_TONE[d] : 'neutral', `🛡️${STATE_GLYPH[d ? DAEMON_TONE[d] : 'neutral']}`, `Daemon ${d ?? '…'}`),
),
)
}
@ -53,7 +67,7 @@ export class StaleBannerElement extends LiveElement {
h(
'div',
{ class: 'banner banner-warning', role: 'status' },
h('span', {}, h('strong', {}, 'The web server is running stale code.'), ' Restart it to pick up the new version.'),
glyph('⚠️🌐', 'The web server is running stale code. Restart it to pick up the new version.'),
h(
'button',
{
@ -61,8 +75,9 @@ export class StaleBannerElement extends LiveElement {
class: 'btn btn-primary btn-small',
disabled: this.restart.restarting || action.pending,
onclick: () => void action.run(),
'aria-label': this.restart.restarting ? 'Restarting…' : 'Restart server',
},
this.restart.restarting ? 'Restarting…' : 'Restart server',
h('span', { 'aria-hidden': 'true' }, this.restart.restarting ? '⏳' : '🔄'),
),
action.error ? errorNotice(action.error) : null,
),

View File

@ -3,12 +3,13 @@
import type { Job } from '../api/jobContract'
import { isActive, q } from '../api/queries'
import { commandLabel } from '../commands/catalog'
import { COMMAND_ICON, commandLabel } from '../commands/catalog'
import { hub } from '../jobs/hub'
import { progressBar } from '../jobs/progress'
import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element'
import { jobHref } from '../lib/runner'
import { glyph } from '../ui/build'
export function jobChip(job: Job): HTMLAnchorElement {
const live = hub.get(job.id)
@ -24,7 +25,13 @@ export function jobChip(job: Job): HTMLAnchorElement {
class: waiting ? 'jobchip jobchip-wait' : 'jobchip',
'aria-label': `${label}: ${waiting ? 'needs your input' : (p?.label ?? 'running')}`,
},
h('span', { class: 'jobchip-label' }, label, h('span', { class: 'jobchip-sub' }, waiting ? 'needs input' : p?.total ? `${p.step}/${p.total}` : '…')),
// Textgate: the command's glyph is painted; its name and "needs input" are spoken (aria-label above).
h(
'span',
{ class: 'jobchip-label' },
glyph(COMMAND_ICON[job.command], label),
h('span', { class: 'jobchip-sub' }, waiting ? glyph('✋', 'needs input') : p?.total ? `${p.step}/${p.total}` : '…'),
),
progressBar(fraction, label, waiting ? 'warning' : 'accent', true),
)
}

View File

@ -145,3 +145,5 @@
.countdown-clock { display: flex; align-items: baseline; gap: var(--space-3); }
.countdown-num { font-size: var(--text-display); letter-spacing: var(--tracking-display); font-weight: 650; font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.row-link > .muted:not(.grow) { white-space: nowrap; }
.cmd-icon { font-size: var(--text-subtitle); line-height: 1; }
.cmd-lock { margin-left: var(--space-1); font-size: var(--text-label); }

9
web/src/test/painted.ts Normal file
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

@ -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
}

View File

@ -0,0 +1,40 @@
// Guard test (textgate-rework R6): command buttons and cards paint a glyph,
// never their label, description or lock reason; those are spoken only.
import { describe, expect, it, vi } from 'vitest'
import { mount, stubApi } from './harness'
import { makeSpec } from './fixtures'
import { visibleWords } from './visibleWords'
import '../commands/commandButton'
describe('textgate guard: commands', () => {
it('a labelled command button paints no words', async () => {
stubApi({ 'GET /api/commands': [makeSpec('done')] })
const el = mount('<command-button name="done" label="I got an achievement"></command-button>')
await vi.waitFor(() => {
expect(el.querySelector('button')).toHaveAttribute('aria-disabled', 'false')
})
expect(visibleWords(el)).toEqual([])
})
it('a view command link paints no words', async () => {
stubApi({ 'GET /api/commands': [makeSpec('status', { kind: 'view' })] })
const el = mount('<command-button name="status"></command-button>')
await vi.waitFor(() => {
expect(el.querySelector('a')).not.toBeNull()
})
expect(visibleWords(el)).toEqual([])
})
it('a locked, privileged countdown card paints no words', async () => {
const friction = { phrase_template: 'x', countdown_seconds: 300 }
stubApi({
'GET /api/commands': [makeSpec('gaming-reset', { privileged: true, friction, locked_reason: 'Locked by a pick' })],
})
const el = mount('<command-card name="gaming-reset" label="Reset today…"></command-card>')
await vi.waitFor(() => {
expect(el.querySelector('article')).toHaveClass('locked')
})
expect(visibleWords(el)).toEqual([])
})
})

View File

@ -0,0 +1,59 @@
// Guard test (textgate-rework R6): the dashboard and gaming panels paint
// glyphs, numbers and game names only; every label and sentence is spoken.
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { makeBudget } from './factories'
import { makeJob, makeSpec, makeStatus } from './fixtures'
import { installEventSource, mount, stubApi } from './harness'
import { visibleWords } from './visibleWords'
import '../sections/dashboard'
import '../sections/gaming/panel'
import '../shell/health'
import '../shell/jobIndicator'
const daemon = {
state: 'running',
started_at: null,
pid: 1,
journal_tail: [],
restart_available_at: null,
fast_installs: [{ app_id: 1, name: 'Celeste', phase: 'downloading depot 3/8', percent: 40, elapsed_seconds: 60 }],
}
beforeEach(installEventSource)
describe('textgate guard: dashboard + gaming', () => {
it('paints no chrome words once everything has loaded', async () => {
const budget = makeBudget()
stubApi({
'GET /api/status': makeStatus({ total_block: { active: true, days_remaining: 1, until: null } }),
'GET /api/daemon': daemon,
'GET /api/server': { stale: true, started_at: null, version: '1.2.3' },
'GET /api/budget': budget,
'GET /api/jobs': [makeJob({ id: 'a', command: 'scan', state: 'running', summary: 'Scanned 12' })],
'GET /api/commands': [makeSpec('check'), makeSpec('scan')],
})
const el = mount(
'<main><health-badges></health-badges><stale-banner></stale-banner><job-indicator></job-indicator>' +
'<dashboard-status></dashboard-status><budget-glance></budget-glance><fast-installs></fast-installs>' +
'<recent-jobs></recent-jobs><budget-panel></budget-panel></main>',
)
await vi.waitFor(() => {
expect(el.querySelector('.budget-rules')).not.toBeNull()
expect(el.querySelector('.hero-game')).not.toBeNull()
expect(el.querySelector('.banner')).not.toBeNull()
}, { timeout: 3000 })
const content = [
...budget.legend.map((e) => e.label),
...(budget.today?.games.map((g) => g.label) ?? []),
budget.session.game_name,
budget.session.billing_label,
budget.rules.masked_launchers.join(', '),
makeStatus().current_game_name ?? '',
'Celeste',
// Chart bar tooltips are "<day> · <game>: <duration>": all content.
...[...el.querySelectorAll('svg title')].map((t) => t.textContent.trim()),
]
expect(visibleWords(el, content)).toEqual([])
})
})

View File

@ -5,32 +5,13 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { installEventSource } from './harness'
import { mountJob } from './jobHelpers'
import { visibleWords } from './visibleWords'
import { ApiFailure } from '../api/client'
import { timelineChart } from '../lib/charts/timeline'
import { errorNotice, loading } from '../ui/build'
import type { EstimateResult } from '../estimate'
import type { Filters } from '../types'
const WORD_RE = /[A-Za-z]{2,}/
function spokenOnly(el: Element | null): boolean {
for (let cur = el; cur; cur = cur.parentElement) {
if (cur.classList.contains('sr-only') || cur.getAttribute('aria-hidden') === 'true' || (cur instanceof HTMLElement && cur.hidden)) return true
}
return false
}
/** Visible text nodes holding a word of 2+ letters, minus `allowed` content. */
function visibleWords(root: Element, allowed: readonly string[] = []): string[] {
const out: string[] = []
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const t = n.textContent?.trim() ?? ''
if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t)) continue
out.push(t)
}
return out
}
beforeEach(installEventSource)

View File

@ -0,0 +1,26 @@
// Textgate guard helper (textgate-rework R6): the words an element paints.
// Spoken-only text (.sr-only, [hidden]) and content the caller passes in
// `allowed` (game names, server messages) do not count. aria-hidden text
// still paints, so it counts.
const WORD_RE = /[A-Za-z]{2,}/
function spokenOnly(el: Element | null): boolean {
for (let cur = el; cur; cur = cur.parentElement) {
if (cur.classList.contains('sr-only')) return true
if (cur instanceof HTMLElement && cur.hidden) return true
}
return false
}
/** Visible text nodes holding a word of 2+ letters, minus `allowed` content. */
export function visibleWords(root: Element, allowed: readonly string[] = []): string[] {
const out: string[] = []
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const t = n.textContent?.trim() ?? ''
if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t)) continue
out.push(t)
}
return out
}

View File

@ -81,6 +81,16 @@ describe('small builders', () => {
expect(el.querySelector('.pill-icon')).not.toBeNull()
})
it('pill paints a bullet for an unknown tone and speaks its text', () => {
const el = pill('mystery', 'odd one')
expect(el.querySelector('.pill-icon')?.textContent).toBe('•')
expect(el.querySelector('.sr-only')?.textContent).toBe('odd one')
})
it('pill paints the icon it is given over the tone glyph', () => {
expect(pill('danger', 'x', '🔥').querySelector('.pill-icon')?.textContent).toBe('🔥')
})
it('link is an anchor', () => {
const a = link('/library/', 'Open')
expect(a.getAttribute('href')).toBe('/library/')

View File

@ -75,11 +75,18 @@ export function empty(label: string): HTMLParagraphElement {
export interface CardOptions {
aside?: Child
className?: string
icon?: string
}
export function card(title: string | null, body: Child, { aside, className = '' }: CardOptions = {}): HTMLElement {
const head =
title || aside ? h('div', { class: 'box-head' }, title ? h('h2', {}, title) : null, aside ?? null) : null
/** A painted glyph whose meaning is spoken only (textgate: no visible words). */
export function glyph(icon: string, spoken: string, className = 'glyph'): HTMLSpanElement {
return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken))
}
/** A card; its title is spoken only, `icon` (if any) is painted in its place. */
export function card(title: string | null, body: Child, { aside, className = '', icon }: CardOptions = {}): HTMLElement {
const heading = title ? h('h2', {}, icon ? glyph(icon, title) : h('span', { class: 'sr-only' }, title)) : null
const head = title || aside ? h('div', { class: 'box-head' }, heading, aside ?? null) : null
return h('section', { class: `box ${className}`.trim(), 'aria-label': title ?? '' }, head, body)
}
@ -103,9 +110,14 @@ const TONE_PILL_ICON: Record<string, string> = {
running: '▶️',
}
export function pill(tone: string, text: string): HTMLSpanElement {
const icon = TONE_PILL_ICON[tone] ?? ''
return h('span', { class: `pill pill-${tone}` }, icon && h('span', { class: 'pill-icon', 'aria-hidden': 'true' }, icon), text)
/** A tone badge: `icon` (else the tone's glyph) painted, `text` spoken only. */
export function pill(tone: string, text: string, icon = TONE_PILL_ICON[tone] ?? '•'): HTMLSpanElement {
return h(
'span',
{ class: `pill pill-${tone}` },
h('span', { class: 'pill-icon', 'aria-hidden': 'true' }, icon),
h('span', { class: 'sr-only' }, text),
)
}
export function link(href: string, text: Child, className = 'btn btn-ghost btn-small'): HTMLAnchorElement {

View File

@ -18,7 +18,8 @@ export class Modal {
private opener: Element | null = null
constructor({ title, wide = false, onClose }: ModalOptions) {
this.heading = h('h2', {}, title)
// Textgate: the title is spoken only; the dialog's content says what it is.
this.heading = h('h2', { class: 'sr-only' }, title)
const close = h(
'button',
{ type: 'button', class: 'btn btn-ghost btn-icon dialog-close', 'aria-label': 'Close', onclick: onClose },

View File

@ -31,7 +31,7 @@ describe('ui format', () => {
it('dateTime formats or dashes', () => {
expect(dateTime(null)).toBe('—')
expect(dateTime('2026-10-10T12:00:00Z')).toMatch(/\d/)
expect(dateTime('2026-10-10T12:00:00Z')).toMatch(/^\d\d-\d\d \d\d:\d\d$/)
})
it('duration spans start to end, or to now while running', () => {

View File

@ -31,11 +31,12 @@ export function ago(iso: string | null, now: number = Date.now()): string {
return `${Math.round(s / 86_400)} d ago`
}
/** Local `MM-DD HH:MM`: numbers only (textgate: no month names). */
export function dateTime(iso: string | null): string {
if (!iso) return '—'
return new Date(iso).toLocaleString(undefined, {
month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
})
const d = new Date(iso)
const p = (n: number) => String(n).padStart(2, '0')
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
}
export function duration(startIso: string | null, endIso: string | null, now: number = Date.now()): string {