Compare commits

..

No commits in common. "1e452b0fcd1c56eaa5c5f7307532f0aea852c81c" and "582ce6b2b6175fc724ec8a45f8826de0db925c98" have entirely different histories.

100 changed files with 620 additions and 1752 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,23 +18,6 @@ _SECONDS_PER_MINUTE = 60
_MINUTES_PER_HOUR = 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: def notify_desktop_user(title: str, body: str) -> None:
"""Send a desktop notification into the real user's session. """Send a desktop notification into the real user's session.

View File

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

View File

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

View File

@ -57,7 +57,7 @@ class TestReporting:
patch(f"{_PKG}.notify_desktop_user") as notify, patch(f"{_PKG}.notify_desktop_user") as notify,
): ):
report_leetcode_incident("ledger unreadable", fix="systemctl status x") report_leetcode_incident("ledger unreadable", fix="systemctl status x")
notify.assert_called_once_with("🧩❌🎮", "-1h systemctl status x") assert notify.call_count == 1
assert "ledger unreadable" in caplog.text assert "ledger unreadable" in caplog.text
assert "systemctl status x" in log.read_text(encoding="utf-8") 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( progress.phase.assert_called_once_with(
"Fast-installing G: shutting Steam down", None "Fast-installing G: shutting Steam down", None
) )
progress.advance.assert_called_once_with("⏱️ 12s", step=0) progress.advance.assert_called_once_with("12s elapsed", step=0)
def test_echo_is_throttled_to_30_seconds(self, tmp_path: Path) -> None: def test_echo_is_throttled_to_30_seconds(self, tmp_path: Path) -> None:
reporter = self._reporter(tmp_path, _upto(" 46.90%")) reporter = self._reporter(tmp_path, _upto(" 46.90%"))

View File

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

View File

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

View File

@ -2,18 +2,7 @@
from __future__ import annotations from __future__ import annotations
import pytest from steam_backlog_enforcer._playtime_notify import _humanise
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: class TestHumanise:

View File

@ -1,111 +0,0 @@
"""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' }) 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'}`) ctx.log(`steam://install/${world.currentAppId} → ${dir || '/mnt/games/SteamLibrary'}`)
for (let i = 1; i <= 20; i += 1) { for (let i = 1; i <= 20; i += 1) {
ctx.progress(i, 20, 'Downloading', `${name} · ${(i * 0.6).toFixed(1)}/12.0 GB`, (20 - i) * 0.4) ctx.progress(i, 20, 'Downloading', `${name} — ${(i * 0.6).toFixed(1)} of 12.0 GB`, (20 - i) * 0.4)
await ctx.sleep(400) await ctx.sleep(400)
} }
return { summary: `${name} installed.` } return { summary: `${name} installed.` }

View File

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

View File

@ -190,8 +190,8 @@ importers:
specifier: 7.0.1 specifier: 7.0.1
version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.1.0) version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.1.0)
'@testing-library/user-event': '@testing-library/user-event':
specifier: 14.6.9 specifier: 14.6.8
version: 14.6.9(@testing-library/dom@10.4.2) version: 14.6.8(@testing-library/dom@10.4.2)
'@types/node': '@types/node':
specifier: 26.6.6 specifier: 26.6.6
version: 26.6.6 version: 26.6.6
@ -895,8 +895,8 @@ packages:
vitest: vitest:
optional: true optional: true
'@testing-library/user-event@14.6.9': '@testing-library/user-event@14.6.8':
resolution: {integrity: sha512-/8boTjZHNXFi8JGUI2Ev05cq0Szh0OX35Bamkq6CK1ne+l1Xm8BKE3+nGgsnFgaYk0MX67Vh59cZDsNz5lJJEg==} resolution: {integrity: sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==}
engines: {node: '>=12', npm: '>=6'} engines: {node: '>=12', npm: '>=6'}
peerDependencies: peerDependencies:
'@testing-library/dom': '>=7.21.4' '@testing-library/dom': '>=7.21.4'
@ -3103,7 +3103,7 @@ snapshots:
optionalDependencies: 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)) 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.9(@testing-library/dom@10.4.2)': '@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)':
dependencies: dependencies:
'@testing-library/dom': 10.4.2 '@testing-library/dom': 10.4.2

View File

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

View File

@ -44,36 +44,6 @@ export const COMMAND_HOME = {
'restore-backup': '/system', 'restore-backup': '/system',
} as const satisfies Record<CommandName, SectionPath> } 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`). */ /** Title-case label for buttons and the palette (`pick-manual` → `Pick manual`). */
export function commandLabel(name: CommandName): string { export function commandLabel(name: CommandName): string {
const s = name.replace(/-/g, ' ') const s = name.replace(/-/g, ' ')

View File

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

View File

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

View File

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

View File

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

View File

@ -26,9 +26,7 @@ function make(over: { specs?: ParamSpec[]; values?: ParamValues; disabled?: bool
} }
function labelFor(text: RegExp | string): string { function labelFor(text: RegExp | string): string {
// The spoken label sits in an sr-only span; the painted part is a glyph. const label = [...document.querySelectorAll('label')].find((l) => (typeof text === 'string' ? l.textContent === text : text.test(l.textContent)))
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') ?? '' return label?.getAttribute('for') ?? ''
} }
@ -39,9 +37,7 @@ describe('ParamsForm', () => {
expect(input(/Game/)).toHaveAttribute('inputmode', 'numeric') expect(input(/Game/)).toHaveAttribute('inputmode', 'numeric')
expect(input(/Game/)).toHaveAttribute('autofocus') expect(input(/Game/)).toHaveAttribute('autofocus')
expect(input(/Game/)).toBeRequired() expect(input(/Game/)).toBeRequired()
expect(document.querySelector(`label[for="${input(/Game/).id}"]`)).toHaveTextContent('Game *') expect(document.body).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('type', 'number')
expect(input('Days')).toHaveAttribute('min', '1') expect(input('Days')).toHaveAttribute('min', '1')
expect(input('Days')).toHaveAttribute('max', '9') expect(input('Days')).toHaveAttribute('max', '9')

View File

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

View File

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

View File

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

View File

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

View File

@ -48,7 +48,7 @@ export class PhraseField {
this.el = h( this.el = h(
'div', 'div',
{ class: 'phrase' }, { class: 'phrase' },
h('label', { for: id, class: 'field-label' }, h('span', { 'aria-hidden': 'true' }, '⌨️'), h('span', { class: 'sr-only' }, label)), h('label', { for: id, class: 'field-label' }, label),
this.target, this.target,
this.input, this.input,
h('p', { class: 'sr-only' }, `Phrase: ${phrase}`), h('p', { class: 'sr-only' }, `Phrase: ${phrase}`),
@ -71,12 +71,10 @@ export class PhraseField {
this.input.className = `input mono ${ok ? 'input-ok' : prefixOk ? '' : 'input-bad'}`.trim() this.input.className = `input mono ${ok ? 'input-ok' : prefixOk ? '' : 'input-bad'}`.trim()
this.input.setAttribute('aria-invalid', String(!prefixOk)) this.input.setAttribute('aria-invalid', String(!prefixOk))
this.status.className = `field-help ${ok ? 'text-success' : prefixOk ? '' : 'text-danger'}`.trim() this.status.className = `field-help ${ok ? 'text-success' : prefixOk ? '' : 'text-danger'}`.trim()
// Textgate: ✅ / count / ❌ painted; the sentence is spoken only. this.status.textContent = ok
const [mark, spoken] = ok ? 'Matches.'
? ['✅', 'Matches.']
: prefixOk : prefixOk
? [`${typed.length}/${this.phrase.length}`, `${typed.length} of ${this.phrase.length} characters`] ? `${typed.length} of ${this.phrase.length} characters`
: ['❌', 'Does not match — check case and spacing.'] : '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 { describe, expect, it, vi } from 'vitest'
import { q } from '../api/queries' import { q } from '../api/queries'
import { makeSpec } from '../test/fixtures' import { makeSpec } from '../test/fixtures'
import { must, submit } from '../test/events' import { submit } from '../test/events'
import { apiError, Reply } from '../test/harness' import { apiError, Reply } from '../test/harness'
import { field, found, openRunner, text } from '../test/runnerHelpers' import { field, found, openRunner, text } from '../test/runnerHelpers'
@ -18,10 +18,7 @@ describe('<runner-dialog> locked', () => {
}) })
openRunner([spec], 'pick') openRunner([spec], 'pick')
const run = await found('Run pick') const run = await found('Run pick')
// The reason is spoken only; 🔒 is painted in the notice. expect(text()).toContain('Manual pick active')
const lock = must(document.querySelector('.notice-warning'))
expect(lock).toHaveAttribute('aria-label', 'Locked: Manual pick active')
expect(lock).toHaveTextContent('🔒')
expect(field('N')).toBeDisabled() expect(field('N')).toBeDisabled()
expect(document.querySelector('.phrase')).toBeNull() expect(document.querySelector('.phrase')).toBeNull()
expect(run).toBeDisabled() expect(run).toBeDisabled()
@ -41,10 +38,7 @@ describe('<runner-dialog> start failures', () => {
it('offers the sudo fallback when the daemon is down', async () => { 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') } }) openRunner([makeSpec('gaming-unblock')], 'gaming-unblock', { extra: { 'POST /api/jobs': apiError(502, 'daemon_unreachable') } })
submit(await found('Run gaming-unblock')) submit(await found('Run gaming-unblock'))
await vi.waitFor(() => { await waitText('Run it from a terminal instead:')
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') expect(text()).toContain('sudo ./run.sh gaming-unblock')
}) })

View File

@ -24,14 +24,8 @@ describe('<runner-dialog> catalog states', () => {
it('says so when the server does not offer the command', async () => { it('says so when the server does not offer the command', async () => {
openRunner([makeSpec('done')], 'scan') openRunner([makeSpec('done')], 'scan')
// Spoken only; the command's glyph is painted beside ⛔. await waitText('Not in the server catalog')
await vi.waitFor(() => { expect(text()).toContain('does not offer "scan"')
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 () => { it('titles the dialog with the command label', async () => {
@ -142,7 +136,7 @@ describe('<runner-dialog> parameters', () => {
await found('Close (job keeps running)') await found('Close (job keeps running)')
q.dataset.invalidate() q.dataset.invalidate()
await vi.waitFor(() => { expect(q.dataset.state.loading).toBe(false) }) await vi.waitFor(() => { expect(q.dataset.state.loading).toBe(false) })
expect(document.querySelector('a[aria-label="Open in Jobs"]')).toHaveAttribute('href', '/jobs/?id=j1') expect(text()).toContain('Open in Jobs')
}) })
}) })
@ -155,10 +149,7 @@ describe('<runner-dialog> friction', () => {
it('shows the exact phrase once its fields are known, and sends it', async () => { 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 { mock } = openRunner([spec], 'uninstall', { extra: { 'POST /api/jobs': makeJob({ id: 'j1' }) } })
const run = await found('Run uninstall') const run = await found('Run uninstall')
expect(document.querySelector('.notice-info')).toHaveAttribute( expect(text()).toMatch(/Fill in the fields above to see the exact phrase \(game_name\)/)
'aria-label',
'Fill in the fields above to see the exact phrase (game_name).',
)
setValue(field(/Game/), '7') setValue(field(/Game/), '7')
await vi.waitFor(() => { expect(phraseInput()).toBeInTheDocument() }) await vi.waitFor(() => { expect(phraseInput()).toBeInTheDocument() })
expect(run).toBeDisabled() 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 { runner, jobHref, type RunRequest } from '../lib/runner'
import { errorNotice, loading, notice } from '../ui/build' import { errorNotice, loading, notice } from '../ui/build'
import { Modal } from '../ui/dialog' import { Modal } from '../ui/dialog'
import { COMMAND_ICON, commandLabel, findCommand } from './catalog' import { commandLabel, findCommand } from './catalog'
import type { PendingCountdown } from './pendingCountdown' import type { PendingCountdown } from './pendingCountdown'
import { Runner, type NextPhase } from './runnerForm' import { Runner, type NextPhase } from './runnerForm'
@ -94,12 +94,7 @@ export class RunnerDialogElement extends HTMLElement {
return return
} }
if (error) this.modal.render(errorNotice(error)) if (error) this.modal.render(errorNotice(error))
else if (commands) { else if (commands) this.modal.render(notice('danger', 'Not in the server catalog', `The server does not offer "${req.name}".`))
// ⛔ + 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')) else this.modal.render(loading('commands'))
} }
@ -116,8 +111,8 @@ export class RunnerDialogElement extends HTMLElement {
h( h(
'div', 'div',
{ class: 'actions' }, { class: 'actions' },
h('button', { type: 'button', class: 'btn btn-ghost', 'aria-label': 'Close (job keeps running)', onclick: () => { this.close() } }, '✖️'), 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', 'aria-label': 'Open in Jobs' }, '⚙️'), h('a', { href: jobHref(next.id), class: 'btn btn-ghost' }, 'Open in Jobs'),
), ),
), ),
) )

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,6 @@
import type { LibraryGame } from '../api/contract' import type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom' import { h } from '../lib/dom'
import { glyph } from '../ui/build'
import { FILTERS, type BrowserState } from './browserState' import { FILTERS, type BrowserState } from './browserState'
import { SearchBox, type SearchBoxOptions } from './searchBox' import { SearchBox, type SearchBoxOptions } from './searchBox'
import { SORTS, type Filters, type SortKey } from './view' import { SORTS, type Filters, type SortKey } from './view'
@ -31,7 +30,7 @@ export class BrowserToolbar {
opts.onSort(this.sortSelect.value as SortKey) opts.onSort(this.sortSelect.value as SortKey)
}, },
}, },
SORTS.map((s) => h('option', { value: s.key, 'aria-label': s.label }, s.icon)), SORTS.map((s) => h('option', { value: s.key }, s.label)),
) )
this.checks = new Map( this.checks = new Map(
FILTERS.map(([key]) => [ FILTERS.map(([key]) => [
@ -48,12 +47,12 @@ export class BrowserToolbar {
'div', 'div',
{ class: 'lib-toolbar' }, { class: 'lib-toolbar' },
this.searchBox.el, this.searchBox.el,
h('label', { class: 'lib-sort' }, glyph('↕️', 'Sort', 'field-label'), this.sortSelect), h('label', { class: 'lib-sort' }, h('span', { class: 'field-label' }, 'Sort'), this.sortSelect),
h( h(
'fieldset', 'fieldset',
{ class: 'lib-filters' }, { class: 'lib-filters' },
h('legend', { class: 'sr-only' }, 'Filters'), h('legend', { class: 'sr-only' }, 'Filters'),
FILTERS.map(([key, label, , icon]) => h('label', { class: 'check' }, this.checks.get(key), glyph(icon, label))), FILTERS.map(([key, label]) => h('label', { class: 'check' }, this.checks.get(key), label)),
), ),
this.count, this.count,
) )
@ -75,12 +74,7 @@ export class BrowserToolbar {
this.searchBox.setSuggestions(games) this.searchBox.setSuggestions(games)
} }
/** "🎮 3/5" (+ 🔍 while a search ranks by relevance); the sentence is spoken. */ setCount(text: string): void {
setCount(shown: number, total: number, byRelevance: boolean): void { this.count.textContent = text
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 { q } from '../api/queries'
import { define, h } from '../lib/dom' import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { empty, errorNotice, loading } from '../ui/build' import { errorNotice, loading } from '../ui/build'
import { stateFromHash, stateToHash, type BrowserState } from './browserState' import { stateFromHash, stateToHash, type BrowserState } from './browserState'
import { BrowserToolbar } from './browserToolbar' import { BrowserToolbar } from './browserToolbar'
import { buildIndex, search, type Searchable } from './fuzzy' 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))) this.grid.show(this.visible.map((g) => this.card(g)))
const query = this.state.query.trim() const query = this.state.query.trim()
this.toolbar.setCount(this.visible.length, games.length, query !== '') this.toolbar.setCount(`${this.visible.length} of ${games.length} games${query ? ' · by relevance' : ''}`)
this.none.replaceChildren(...(this.visible.length === 0 ? [empty('No game matches.')] : [])) this.none.replaceChildren(...(this.visible.length === 0 ? [h('p', { class: 'muted' }, 'No game matches.')] : []))
} }
/** A click: becomes the tab stop; in pick mode an eligible card is selected. */ /** A click: becomes the tab stop; in pick mode an eligible card is selected. */

View File

@ -1,7 +1,6 @@
import { fireEvent } from '@testing-library/dom' import { fireEvent } from '@testing-library/dom'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { makeLibGame } from '../test/fixtures' import { makeLibGame } from '../test/fixtures'
import { visibleWords } from '../test/visibleWords'
import { gameCard, paintCard, placeCard, type CardPaint } from './gameCard' import { gameCard, paintCard, placeCard, type CardPaint } from './gameCard'
const PLAIN: CardPaint = { reason: null, selected: false, pickMode: false } const PLAIN: CardPaint = { reason: null, selected: false, pickMode: false }
@ -71,17 +70,8 @@ describe('gameCard', () => {
it('shows only the badge that applies', () => { it('shows only the badge that applies', () => {
const card = make({ installed: true }) const card = make({ installed: true })
expect(card.querySelectorAll('.game-badges .pill')).toHaveLength(1) expect(card.querySelector('.game-badges')).toHaveTextContent(/^installed$/)
expect(card.querySelector('.game-badges .pill-neutral')).toHaveTextContent('💾installed') expect(make({ assigned: true }).querySelector('.game-badges')).toHaveTextContent(/^assigned$/)
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', () => { it('has no badge row for a plain game', () => {

View File

@ -4,8 +4,7 @@
import { ENDPOINTS, type LibraryGame } from '../api/contract' import { ENDPOINTS, type LibraryGame } from '../api/contract'
import { h } from '../lib/dom' import { h } from '../lib/dom'
import { pill } from '../ui/build' import { metaLine } from './view'
import { metaGlyphs, metaLine, reasonGlyph, spokenGlyphs } from './view'
export interface CardPaint { export interface CardPaint {
/** Why it cannot be picked here, or null. Greys the card out. */ /** Why it cannot be picked here, or null. Greys the card out. */
@ -37,13 +36,13 @@ export function gameCard(game: LibraryGame): HTMLButtonElement {
{ type: 'button', class: 'game-card', 'data-app-id': game.app_id, tabindex: -1 }, { type: 'button', class: 'game-card', 'data-app-id': game.app_id, tabindex: -1 },
cover(game), cover(game),
h('span', { class: 'game-title' }, game.name), h('span', { class: 'game-title' }, game.name),
spokenGlyphs(metaGlyphs(game), metaLine(game), 'game-meta'), h('span', { class: 'game-meta' }, metaLine(game)),
game.assigned || game.installed game.assigned || game.installed
? h( ? h(
'span', 'span',
{ class: 'game-badges' }, { class: 'game-badges' },
game.assigned ? pill('accent', 'assigned', '🎯') : null, game.assigned ? h('span', { class: 'pill pill-accent' }, 'assigned') : null,
game.installed ? pill('neutral', 'installed', '💾') : null, game.installed ? h('span', { class: 'pill pill-neutral' }, 'installed') : null,
) )
: null, : null,
) )
@ -57,15 +56,13 @@ export function paintCard(card: HTMLButtonElement, { reason, selected, pickMode
else card.removeAttribute('aria-pressed') else card.removeAttribute('aria-pressed')
if (pickMode && reason !== null) card.setAttribute('aria-disabled', 'true') if (pickMode && reason !== null) card.setAttribute('aria-disabled', 'true')
else card.removeAttribute('aria-disabled') else card.removeAttribute('aria-disabled')
const line = card.querySelector('.game-reason') let line = card.querySelector('.game-reason')
if (reason === null) { if (reason === null) {
line?.remove() line?.remove()
return return
} }
// The reason is spoken; the card paints its glyph (and any date) greyed out. line ??= card.appendChild(h('span', { class: 'game-reason' }))
const fresh = spokenGlyphs(reasonGlyph(reason), reason, 'game-reason') line.textContent = 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. */ /** 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 type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom' import { h } from '../lib/dom'
import { uid } from '../lib/ids' import { uid } from '../lib/ids'
import { reasonOrMeta } from './view' import { metaLine } from './view'
export interface SearchBoxOptions { export interface SearchBoxOptions {
/** Every edit of the text (typing, or Escape clearing it). */ /** Every edit of the text (typing, or Escape clearing it). */
@ -36,7 +36,7 @@ export class SearchBox {
'aria-expanded': 'false', 'aria-expanded': 'false',
'aria-controls': this.listId, 'aria-controls': this.listId,
'aria-autocomplete': 'list', 'aria-autocomplete': 'list',
placeholder: '🔍', placeholder: 'Search your games (typos are fine)…',
}) })
this.list = h('ul', { id: this.listId, role: 'listbox', class: 'lib-suggest', hidden: true, 'aria-label': 'Suggestions' }) 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) 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-name' }, g.name),
reasonOrMeta(this.opts.reason(g), g, 'lib-suggest-meta'), h('span', { class: 'lib-suggest-meta' }, this.opts.reason(g) ?? metaLine(g)),
), ),
) )
: []), : []),

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { makeLibGame } from '../test/fixtures' import { makeLibGame } from '../test/fixtures'
import { completion, filterGames, isCompleted, metaGlyphs, metaLine, NO_FILTERS, reasonGlyph, reasonOrMeta, sortGames } from './view' import { completion, filterGames, isCompleted, metaLine, NO_FILTERS, sortGames } from './view'
const g = makeLibGame const g = makeLibGame
@ -68,41 +68,3 @@ describe('metaLine', () => {
expect(metaLine(g({ achievements_total: 0, hltb_hours: null, playtime_minutes: 0 }))).toBe('No achievements') 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,16 +2,14 @@
// the grid component only wires state to them. // the grid component only wires state to them.
import type { LibraryGame } from '../api/contract' import type { LibraryGame } from '../api/contract'
import { h } from '../lib/dom'
export type SortKey = 'name' | 'recent' | 'completion' | 'hltb' export type SortKey = 'name' | 'recent' | 'completion' | 'hltb'
/** `label` is spoken only; the sort select paints `icon`. */ export const SORTS: { key: SortKey; label: string }[] = [
export const SORTS: { key: SortKey; label: string; icon: string }[] = [ { key: 'name', label: 'Name' },
{ key: 'name', label: 'Name', icon: '🔤' }, { key: 'recent', label: 'Recently played' },
{ key: 'recent', label: 'Recently played', icon: '🕐' }, { key: 'completion', label: 'Completion' },
{ key: 'completion', label: 'Completion', icon: '🏆' }, { key: 'hltb', label: 'Shortest (HLTB)' },
{ key: 'hltb', label: 'Shortest (HLTB)', icon: '⏱️' },
] ]
export interface Filters { export interface Filters {
@ -60,7 +58,7 @@ export function filterGames(
) )
} }
/** "45% · 12 h HLTB · 3.2 h played", the card's meta line (spoken only). */ /** "45% · 12 h HLTB · 3.2 h played", the card's one meta line. */
export function metaLine(g: LibraryGame): string { export function metaLine(g: LibraryGame): string {
const pct = completion(g) const pct = completion(g)
const parts = [pct === null ? 'No achievements' : `${Math.floor(pct)}%`] const parts = [pct === null ? 'No achievements' : `${Math.floor(pct)}%`]
@ -69,34 +67,6 @@ export function metaLine(g: LibraryGame): string {
return parts.join(' · ') 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 { function hours(h: number): string {
return h >= 10 ? `${Math.round(h)} h` : `${h.toFixed(1)} h` 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', () => { it('shows each slider value, the hours cap as off or N h', () => {
const { el, panel } = setup() const { el, panel } = setup()
expect(getByText(el, '4 h/day')).toBeInTheDocument() expect(getByText(el, '4 h/day')).toBeInTheDocument()
expect(getByText(el, '∞')).toBeInTheDocument() expect(getByText(el, 'off')).toBeInTheDocument()
panel.sync(makeFilters({ maxHoursPerGame: 50 })) panel.sync(makeFilters({ maxHoursPerGame: 50 }))
expect(getByText(el, '50 h')).toBeInTheDocument() expect(getByText(el, '50 h')).toBeInTheDocument()
}) })

View File

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

View File

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

View File

@ -6,9 +6,10 @@
import { q } from '../../api/queries' import { q } from '../../api/queries'
import { h } from '../../lib/dom' import { h } from '../../lib/dom'
import { LiveElement } from '../../lib/element' import { LiveElement } from '../../lib/element'
import { commandLine, errorNotice, loading } from '../../ui/build'
import { Planner } from './planner' import { Planner } from './planner'
const message = (e: unknown) => (e instanceof Error ? e.message : String(e))
export class GameTableElement extends LiveElement { export class GameTableElement extends LiveElement {
private planner: Planner | null = null private planner: Planner | null = null
@ -23,10 +24,15 @@ export class GameTableElement extends LiveElement {
const { data, error } = q.dataset.state const { data, error } = q.dataset.state
if (!data) { if (!data) {
this.planner = null this.planner = null
// Textgate: ⛔ + the server's own message + the recovery command; the
// explanation is spoken only (errorNotice).
this.replaceChildren( this.replaceChildren(
h('div', { class: 'status' }, error ? errorNotice(error, commandLine('./run.sh serve')) : loading('backlog')), 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…')),
) )
return return
} }

View File

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

View File

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

View File

@ -2,7 +2,6 @@ import { screen, within } from '@testing-library/dom'
import { afterEach, describe, expect, it } from 'vitest' import { afterEach, describe, expect, it } from 'vitest'
import { makeGame } from '../../test/factories' import { makeGame } from '../../test/factories'
import { GAMES, hash, header, names, show, table } from '../../test/plannerHelpers' import { GAMES, hash, header, names, show, table } from '../../test/plannerHelpers'
import { ANY_GLYPH } from './glyphs'
import { hltbUrl } from './plannerTable' import { hltbUrl } from './plannerTable'
afterEach(() => { afterEach(() => {
@ -90,7 +89,7 @@ describe('<game-table> table', () => {
expect(names()).toEqual(['Beta']) expect(names()).toEqual(['Beta'])
await user.click(within(table()).getAllByRole('checkbox')[0]) await user.click(within(table()).getAllByRole('checkbox')[0])
await user.selectOptions(proton, '') 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(names()).toEqual(['Beta'])
expect(hash().get('f.keep')).toBe('excluded') expect(hash().get('f.keep')).toBe('excluded')
}) })
@ -105,8 +104,7 @@ describe('<game-table> table', () => {
it('formats each cell like the CLI list', async () => { it('formats each cell like the CLI list', async () => {
await show(GAMES.slice(0, 1)) await show(GAMES.slice(0, 1))
const cells = [...table().querySelectorAll('tbody td')].map((td) => td.textContent) 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', '🥇']) expect(cells.slice(0, 8)).toEqual(['Alpha', '10', '1.0 h', '5.0', '30.0', '40.0', '20', 'gold'])
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 () => { it('shows a no-data badge for games without HLTB times when they are included', async () => {
@ -116,16 +114,6 @@ describe('<game-table> table', () => {
expect(screen.getByText('Fallback estimate', { exact: false })).toBeVisible() 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 () => { it('caps the table and notes the overflow', async () => {
await show(Array.from({ length: 301 }, (_, i) => makeGame({ app_id: i + 1, name: `Game ${i}` }))) await show(Array.from({ length: 301 }, (_, i) => makeGame({ app_id: i + 1, name: `Game ${i}` })))
expect(screen.getByText('300/301')).toBeVisible() expect(screen.getByText('300/301')).toBeVisible()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,81 +0,0 @@
// 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

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

View File

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

View File

@ -1,8 +1,7 @@
import { screen } from '@testing-library/dom' import { screen } from '@testing-library/dom'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { makeBudgetRules, makeBudgetSession, makeBudgetToday } from '../../test/factories' import { makeBudgetRules, makeBudgetSession, makeBudgetToday } from '../../test/factories'
import { OTHER_KEY, UNATTRIBUTED_KEY } from '../../budgetSeries' import { historyCard, liveCard, rulesCard, todayCard, todayUnavailable } from './cards'
import { historyCard, liveCard, rulesCard, seriesLabel, todayCard, todayUnavailable } from './cards'
const show = (el: HTMLElement) => { const show = (el: HTMLElement) => {
document.body.replaceChildren(el) document.body.replaceChildren(el)
@ -75,7 +74,7 @@ describe('todayUnavailable', () => {
describe('liveCard', () => { describe('liveCard', () => {
it('reports an engaged session with its game', () => { it('reports an engaged session with its game', () => {
show(liveCard(makeBudgetSession())) show(liveCard(makeBudgetSession()))
expect(screen.getByText(/Billing — you are playing/).closest('.budget-verdict')).toHaveClass('budget-verdict--engaged') expect(screen.getByText(/Billing — you are playing/)).toHaveClass('budget-verdict--engaged')
expect(screen.getByText(/Assigned game/)).toBeInTheDocument() expect(screen.getByText(/Assigned game/)).toBeInTheDocument()
// Engaged, so the credited game is described in the present tense. // Engaged, so the credited game is described in the present tense.
expect(screen.getByText(/Billing to/)).toBeInTheDocument() expect(screen.getByText(/Billing to/)).toBeInTheDocument()
@ -109,58 +108,6 @@ 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', () => { describe('historyCard', () => {
const legend = [ const legend = [
{ key: 'app:475150', label: 'Titan Quest' }, { key: 'app:475150', label: 'Titan Quest' },

View File

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

View File

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

View File

@ -37,12 +37,10 @@ describe('jobs list', () => {
expect(await screen.findByRole('table')).toBeInTheDocument() expect(await screen.findByRole('table')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Jobs', level: 1 })).toBeInTheDocument() expect(screen.getByRole('heading', { name: 'Jobs', level: 1 })).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Pick manual' })).toHaveAttribute('href', '/jobs/?id=a') expect(screen.getByRole('link', { name: 'Pick manual' })).toHaveAttribute('href', '/jobs/?id=a')
// Param values painted, keys and the server's summary spoken only. expect(screen.getByText('app_id=5 note=x')).toBeInTheDocument()
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('1:05')).toBeInTheDocument()
expect(screen.getByText('Picked 5')).toHaveClass('sr-only') expect(screen.getByText('Picked 5')).toBeInTheDocument()
expect(screen.getByText('Scanning')).toHaveClass('sr-only') expect(screen.getByText('Scanning')).toBeInTheDocument()
expect(screen.getAllByLabelText('running')).toHaveLength(2) expect(screen.getAllByLabelText('running')).toHaveLength(2)
}) })
@ -108,9 +106,7 @@ describe('job detail', () => {
stubApi({ 'GET /api/jobs/nope': apiError(404, 'not_found', 'No job nope.') }) stubApi({ 'GET /api/jobs/nope': apiError(404, 'not_found', 'No job nope.') })
mount('<jobs-page></jobs-page>') mount('<jobs-page></jobs-page>')
expect(await screen.findByRole('heading', { name: 'Job not found', level: 1 })).toBeInTheDocument() expect(await screen.findByRole('heading', { name: 'Job not found', level: 1 })).toBeInTheDocument()
const notice = document.querySelector('[data-code="not_found"]') expect(screen.getByText('No job nope.')).toBeInTheDocument()
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(screen.getByRole('link', { name: 'See all jobs' })).toHaveAttribute('href', '/jobs/')
expect(document.querySelector('job-progress')).toBeNull() expect(document.querySelector('job-progress')).toBeNull()
expect(FakeEventSource.all).toHaveLength(0) expect(FakeEventSource.all).toHaveLength(0)
@ -131,9 +127,8 @@ describe('job detail', () => {
at('/jobs/?id=gone') at('/jobs/?id=gone')
stubApi({ 'GET /api/jobs/gone': apiError(404, 'not_found') }) stubApi({ 'GET /api/jobs/gone': apiError(404, 'not_found') })
mount('<jobs-page></jobs-page>') mount('<jobs-page></jobs-page>')
await screen.findByRole('heading', { name: 'Job not found', level: 1 }) const title = await screen.findByText('Job not found', { selector: '.notice-title' })
const notice = document.querySelector('[data-code="not_found"]') expect(title.parentElement?.querySelectorAll('p')).toHaveLength(2)
expect(notice?.getAttribute('aria-label')).toMatch(/keeps the last 50\.$/)
}) })
it('treats a bare <job-detail> as an unknown job', async () => { 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 { explain } from '../api/errors'
import type { Job } from '../api/jobContract' import type { Job } from '../api/jobContract'
import { q } from '../api/queries' import { q } from '../api/queries'
import { COMMAND_ICON, commandLabel } from '../commands/catalog' import { commandLabel } from '../commands/catalog'
import '../jobs/jobProgress' import '../jobs/jobProgress'
import { stateBadge } from '../jobs/progress' import { stateBadge } from '../jobs/progress'
import { define, h, hx } from '../lib/dom' import { define, h, hx } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { jobHref, pageHref } from '../lib/runner' import { jobHref, pageHref } from '../lib/runner'
import { card, empty, errorNotice, glyph, link, loading, notice } from '../ui/build' import { card, empty, errorNotice, link, loading, notice } from '../ui/build'
import { dateTime, duration } from '../ui/format' import { dateTime, duration } from '../ui/format'
/** The `id` query parameter, or null for the list (an empty `?id=` too). */ /** The `id` query parameter, or null for the list (an empty `?id=` too). */
@ -27,32 +27,18 @@ function params(j: Job): string {
.join(' ') .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. */ /** One row, plus its duration cell so ticks can refresh just that. */
function row(j: Job): { tr: HTMLTableRowElement; took: HTMLTableCellElement } { function row(j: Job): { tr: HTMLTableRowElement; took: HTMLTableCellElement } {
const args = params(j) 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 took = h('td', { class: 'num mono' })
const summary = j.summary ?? j.progress?.label ?? ''
const tr = h( const tr = h(
'tr', 'tr',
{}, {},
h( h('td', {}, h('a', { href: jobHref(j.id) }, commandLabel(j.command)), args ? h('span', { class: 'muted mono' }, ` ${args}`) : null),
'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', {}, stateBadge(j.state)),
h('td', { class: 'muted' }, dateTime(j.created_at)), h('td', { class: 'muted' }, dateTime(j.created_at)),
took, took,
h('td', { class: 'ellipsis' }, j.summary ?? j.progress?.label ?? ''),
) )
return { tr, took } return { tr, took }
} }
@ -86,17 +72,18 @@ export class JobListElement extends LiveElement {
h( h(
'tr', 'tr',
{}, {},
h('th', { scope: 'col' }, glyph('⌨️', 'Command')), h('th', { scope: 'col' }, 'Command'),
h('th', { scope: 'col' }, glyph('🚦', 'State')), h('th', { scope: 'col' }, 'State'),
h('th', { scope: 'col' }, glyph('🕐', 'Started')), h('th', { scope: 'col' }, 'Started'),
h('th', { scope: 'col', class: 'num' }, glyph('⏱️', 'Took')), h('th', { scope: 'col', class: 'num' }, 'Took'),
h('th', { scope: 'col' }, 'Summary'),
), ),
), ),
this.body, this.body,
), ),
) )
const title = h('h1', { class: 'sr-only' }, 'Jobs') const title = h('h1', {}, 'Jobs')
const sub = h('p', { class: 'sr-only' }, 'The last 50 jobs. They keep running if you close the page.') const sub = h('p', { class: 'sub' }, '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.replaceChildren(pageHead(title, sub, null), card(null, [this.status, this.table]))
this.watch(q.jobs) this.watch(q.jobs)
this.tick(1000) this.tick(1000)
@ -125,16 +112,13 @@ export class JobListElement extends LiveElement {
} }
function notFound(id: string, error: ApiFailure): HTMLDivElement { function notFound(id: string, error: ApiFailure): HTMLDivElement {
// ❓ + the id painted; the explanation and the server's message are spoken. return notice(
const el = notice(
'warning', 'warning',
null, 'Job not found',
h('p', { class: 'm0' }, h('span', { 'aria-hidden': 'true' }, '❓ '), h('span', { class: 'mono' }, id)), h('p', { class: 'm0' }, 'There is no job ', h('span', { class: 'mono' }, id), '. It may have been pruned: the history keeps the last 50.'),
h('p', { class: 'm0' }, link(pageHref('/jobs'), glyph('📋', 'See all jobs'), '')), error.message ? h('p', { class: 'm0 muted' }, error.message) : null,
h('p', { class: 'm0' }, h('a', { href: pageHref('/jobs') }, '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. */ /** `/jobs/?id=…`: one job. `<job-progress>` is mounted once and owns itself. */
@ -155,7 +139,7 @@ export class JobDetailElement extends LiveElement {
this.sub = h('p', { class: 'sub' }) this.sub = h('p', { class: 'sub' })
this.status = h('div', { class: 'contents' }) this.status = h('div', { class: 'contents' })
this.mounted = false this.mounted = false
this.replaceChildren(pageHead(this.heading, this.sub, link(pageHref('/jobs'), glyph('📋', 'All jobs'), 'btn btn-ghost')), this.status) this.replaceChildren(pageHead(this.heading, this.sub, link(pageHref('/jobs'), 'All jobs', 'btn btn-ghost')), this.status)
// Subscribed by hand, not via watch(): an unknown id stops polling. // Subscribed by hand, not via watch(): an unknown id stops polling.
let live = true let live = true
const off = q.job(this.jobId).subscribe(() => { const off = q.job(this.jobId).subscribe(() => {
@ -172,13 +156,8 @@ export class JobDetailElement extends LiveElement {
const id = this.jobId const id = this.jobId
const { data, error, loading: waiting } = q.job(id).state const { data, error, loading: waiting } = q.job(id).state
const missing = !data && error instanceof ApiFailure && error.code === 'not_found' ? error : null const missing = !data && error instanceof ApiFailure && error.code === 'not_found' ? error : null
// Heading: the command's glyph (❓ when the id is unknown, ⚙️ while loading), name spoken. this.heading.textContent = data ? commandLabel(data.command) : missing ? 'Job not found' : 'Job'
this.heading.replaceChildren(data ? commandGlyph(data.command) : missing ? glyph('❓', 'Job not found') : glyph('⚙️', 'Job')) this.sub.replaceChildren('Job ', h('span', { class: 'mono' }, id), data ? ` · created ${dateTime(data.created_at)}` : '')
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( this.status.replaceChildren(
...(missing ? [notFound(id, missing)] : error ? [errorNotice(error)] : waiting ? [loading('job')] : []), ...(missing ? [notFound(id, missing)] : error ? [errorNotice(error)] : waiting ? [loading('job')] : []),
) )

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@
// right now. Nothing shows until the status is known. // right now. Nothing shows until the status is known.
import { q } from '../api/queries' import { q } from '../api/queries'
import { define, h } from '../lib/dom' import { define } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { notice } from '../ui/build' import { notice } from '../ui/build'
@ -17,13 +17,11 @@ export class StoreNoticeElement extends LiveElement {
this.replaceChildren() this.replaceChildren()
return return
} }
// Textgate: 🛒 + lock state painted (tone is the 2nd channel), the sentence spoken. this.replaceChildren(
const [tone, icon, spoken] = data.store_blocked data.store_blocked
? (['info', '🛒🔒', 'Store blocked. Unblocking takes a typed phrase and is capped at 30 minutes.'] as const) ? notice('info', 'Store blocked', 'Unblocking takes a typed phrase and is capped at 30 minutes.')
: (['warning', '🛒🔓', 'Store unblocked. The store is open right now; it re-blocks automatically.'] as const) : notice('warning', 'Store unblocked', 'The store is open right now; it re-blocks automatically.'),
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,7 +4,6 @@ import { beforeEach, describe, expect, it } from 'vitest'
import { q } from '../../api/queries' import { q } from '../../api/queries'
import { makeJob, makeSpec } from '../../test/fixtures' import { makeJob, makeSpec } from '../../test/fixtures'
import { apiError, bodiesOf, flush, installEventSource, mount, stubApi, type Handler } from '../../test/harness' import { apiError, bodiesOf, flush, installEventSource, mount, stubApi, type Handler } from '../../test/harness'
import { dateTime } from '../../ui/format'
import { restorePhrase } from './backupsCard' import { restorePhrase } from './backupsCard'
const BACKUP = { id: '20261010-100000', created_at: '2026-10-10T10:00:00Z', reason: 'before reset', size_bytes: 2048 } const BACKUP = { id: '20261010-100000', created_at: '2026-10-10T10:00:00Z', reason: 'before reset', size_bytes: 2048 }
@ -26,7 +25,7 @@ const openDialog = async () => {
await userEvent.click(await screen.findByRole('button', { name: 'Restore…' })) await userEvent.click(await screen.findByRole('button', { name: 'Restore…' }))
return screen.findByRole('dialog', { name: `Restore backup ${BACKUP.id}` }) 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', () => { describe('restorePhrase', () => {
it('mirrors the server friction phrase', () => { it('mirrors the server friction phrase', () => {
@ -41,22 +40,10 @@ describe('backups-card', () => {
show() show()
expect(await screen.findByText(BACKUP.id)).toBeInTheDocument() expect(await screen.findByText(BACKUP.id)).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'State backups' })).toBeInTheDocument() expect(screen.getByRole('region', { name: 'State backups' })).toBeInTheDocument()
expect(document.querySelector('[data-reason="before reset"]')).toHaveTextContent(/♻️.*before reset · 2.0 KB/) expect(screen.getByText(/before reset · 2.0 KB/)).toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'Reset all state…' })).toBeInTheDocument() 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 () => { it('says when there are none', async () => {
show({ 'GET /api/backups': [] }) show({ 'GET /api/backups': [] })
expect(await screen.findByText('No backups yet.')).toBeInTheDocument() expect(await screen.findByText('No backups yet.')).toBeInTheDocument()

View File

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

View File

@ -44,18 +44,11 @@ describe('daemon-card', () => {
expect(await screen.findByText('4242')).toBeInTheDocument() expect(await screen.findByText('4242')).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'Enforcer daemon' })).toBeInTheDocument() expect(screen.getByRole('region', { name: 'Enforcer daemon' })).toBeInTheDocument()
expect(screen.getByText('running')).toBeInTheDocument() expect(screen.getByText('running')).toBeInTheDocument()
expect(screen.getByLabelText(/ago/)).toBeInTheDocument() expect(screen.getByText(/ago/)).toBeInTheDocument()
expect(screen.getByText('running').closest('[data-state]')).toHaveAttribute('data-state', 'running')
expect(journal()).toHaveTextContent(/line one\s+line two/) expect(journal()).toHaveTextContent(/line one\s+line two/)
expect(screen.queryByText('Daemon unreachable')).toBeNull() 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 () => { it('restarts through the runner when allowed', async () => {
show(daemon()) show(daemon())
await userEvent.click(await screen.findByRole('button', { name: 'Restart daemon…' })) await userEvent.click(await screen.findByRole('button', { name: 'Restart daemon…' }))
@ -84,8 +77,8 @@ describe('daemon-card', () => {
expect(button).toHaveAttribute('aria-disabled', 'true') expect(button).toHaveAttribute('aria-disabled', 'true')
await userEvent.click(button) await userEvent.click(button)
expect(run).not.toHaveBeenCalled() expect(run).not.toHaveBeenCalled()
expect(journal()).toHaveTextContent(/^—$/) expect(screen.getByText('No journal lines.')).toBeInTheDocument()
expect(screen.getAllByText('—')).toHaveLength(3) expect(screen.getAllByText('—')).toHaveLength(2)
}) })
it('offers the demo run', async () => { it('offers the demo run', async () => {

View File

@ -8,36 +8,19 @@ import { q } from '../../api/queries'
import { define, h } from '../../lib/dom' import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element' import { LiveElement } from '../../lib/element'
import { runner } from '../../lib/runner' import { runner } from '../../lib/runner'
import type { DaemonState } from '../../api/contract' import { card, commandLine, errorNotice, facts, loading, notice } from '../../ui/build'
import { card, commandLine, errorNotice, facts, glyph, loading, notice } from '../../ui/build'
import { ago, clock } from '../../ui/format' 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. */ /** Milliseconds left on the restart rate limit; 0 when free. */
export function restartWaitMs(availableAt: string | null, now: number = Date.now()): number { export function restartWaitMs(availableAt: string | null, now: number = Date.now()): number {
return availableAt ? Math.max(0, Date.parse(availableAt) - now) : 0 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 { function unreachableNotice(): HTMLDivElement {
// Textgate: ⛔ + the command to run are painted; the explanation is spoken only.
return notice( return notice(
'danger', 'danger',
null, 'Daemon unreachable',
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:', 'Privileged actions (store unblock, gaming reset/block/unblock, restart) are unavailable. Check it from a terminal:',
),
commandLine('systemctl status steam-backlog-enforcer'), commandLine('systemctl status steam-backlog-enforcer'),
) )
} }
@ -66,16 +49,16 @@ export class DaemonCardElement extends LiveElement {
runner.run('enforce', { demo: 1 }) runner.run('enforce', { demo: 1 })
}, },
}, },
glyph('🧪', 'Demo run (enforce --demo)…'), 'Demo run (enforce --demo)…',
) )
private readonly parts = [ private readonly parts = [
this.alert, this.alert,
this.factsSlot, this.factsSlot,
h('div', { class: 'actions' }, this.restart, this.demo), h('div', { class: 'actions' }, this.restart, this.demo),
h('h3', { class: 'h3' }, glyph('📜', 'Journal')), h('h3', { class: 'h3' }, 'Journal'),
this.journal, this.journal,
] ]
private readonly root = card('Enforcer daemon', [this.status, this.body], { icon: '🛡️' }) private readonly root = card('Enforcer daemon', [this.status, this.body])
private shown = false private shown = false
private canRestart = false private canRestart = false
private unreachable = false private unreachable = false
@ -104,27 +87,20 @@ export class DaemonCardElement extends LiveElement {
} }
this.factsSlot.replaceChildren( this.factsSlot.replaceChildren(
facts([ facts([
[glyph('📡', 'State'), h('span', { 'data-state': data.state }, glyph(STATE_ICON[data.state], data.state))], ['State', data.state],
[glyph('#️⃣', 'PID'), data.pid ?? '—'], ['PID', data.pid ?? '—'],
[glyph('⏱️', 'Up since'), data.started_at ? since(data.started_at) : '—'], ['Up since', data.started_at ? ago(data.started_at) : '—'],
]), ]),
) )
this.canRestart = waitMs === 0 && data.state === 'running' this.canRestart = waitMs === 0 && data.state === 'running'
this.restart.setAttribute('aria-disabled', String(!this.canRestart)) this.restart.setAttribute('aria-disabled', String(!this.canRestart))
// Rate limited: ⏳ + the clock counting down; free: 🔄. Words spoken only. this.restart.textContent = waitMs > 0 ? `Restart available in ${clock(waitMs / 1000)}` : 'Restart daemon…'
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) this.fillJournal(data.journal_tail)
} }
/** New text only when it changed; follow the tail unless scrolled up. */ /** New text only when it changed; follow the tail unless scrolled up. */
private fillJournal(lines: string[]): void { private fillJournal(lines: string[]): void {
// The journal lines are the daemon's own log (content); empty paints a dash. const text = lines.length ? lines.join('\n') : 'No journal lines.'
const text = lines.length ? lines.join('\n') : '—'
const j = this.journal const j = this.journal
if (j.textContent === text) return if (j.textContent === text) return
const following = j.scrollHeight - j.scrollTop - j.clientHeight < 8 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 { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element' import { LiveElement } from '../../lib/element'
import { ServerRestart } from '../../shell/serverRestart' import { ServerRestart } from '../../shell/serverRestart'
import { card, errorNotice, facts, glyph, loading, notice } from '../../ui/build' import { card, errorNotice, facts, loading, notice } from '../../ui/build'
import { ago, dateTime } from '../../ui/format' import { ago, dateTime } from '../../ui/format'
export class ServerCardElement extends LiveElement { export class ServerCardElement extends LiveElement {
@ -19,7 +19,7 @@ export class ServerCardElement extends LiveElement {
void this.restart.action.run() void this.restart.action.run()
}, },
}) })
private readonly root = card('Web server', [this.info, this.failure, h('div', { class: 'actions' }, this.button)], { icon: '🌐' }) private readonly root = card('Web server', [this.info, this.failure, h('div', { class: 'actions' }, this.button)])
private readonly restart = new ServerRestart(() => { private readonly restart = new ServerRestart(() => {
this.update() this.update()
}) })
@ -37,13 +37,13 @@ export class ServerCardElement extends LiveElement {
this.info.replaceChildren( this.info.replaceChildren(
...(error ? [errorNotice(error)] : []), ...(error ? [errorNotice(error)] : []),
...(!data && !error ? [loading('server health')] : []), ...(!data && !error ? [loading('server health')] : []),
...(data?.stale ? [notice('warning', null, h('span', { class: 'sr-only' }, h('strong', {}, 'Stale'), ' The code on disk is newer than this process.'))] : []), ...(data?.stale ? [notice('warning', 'Stale', 'The code on disk is newer than this process.')] : []),
...(data ...(data
? [ ? [
facts([ facts([
[glyph('🏷️', 'Version'), h('span', { class: 'mono' }, data.version)], ['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))], ['Started', `${dateTime(data.started_at)} (${ago(data.started_at)})`],
[glyph('💾', 'Code'), data.stale ? glyph('⚠️', 'stale') : glyph('✅', 'current')], ['Code', data.stale ? 'stale' : 'current'],
]), ]),
] ]
: []), : []),
@ -51,8 +51,7 @@ export class ServerCardElement extends LiveElement {
const { action, restarting } = this.restart const { action, restarting } = this.restart
this.failure.replaceChildren(...(action.error ? [errorNotice(action.error)] : [])) this.failure.replaceChildren(...(action.error ? [errorNotice(action.error)] : []))
this.button.disabled = restarting || action.pending this.button.disabled = restarting || action.pending
this.button.dataset.restarting = String(restarting) this.button.textContent = restarting ? 'Restarting… the page reloads when it is back' : 'Restart server'
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 { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element' import { LiveElement } from '../../lib/element'
import { pageHref } from '../../lib/runner' import { pageHref } from '../../lib/runner'
import { card, facts, glyph, link } from '../../ui/build' import { card, facts, link } from '../../ui/build'
export class SetupCardElement extends LiveElement { export class SetupCardElement extends LiveElement {
protected override setup(): void { protected override setup(): void {
@ -18,11 +18,11 @@ export class SetupCardElement extends LiveElement {
card( card(
'Setup', 'Setup',
facts([ facts([
[glyph('⚙️', 'Configured'), data ? (data.configured ? glyph('✅', 'Yes') : glyph('❌', 'No')) : '…'], ['Configured', data ? (data.configured ? 'Yes' : 'No') : '…'],
[glyph('🔑', 'Steam API key'), data ? (data.has_api_key ? glyph('🔒', 'Stored (never shown)') : glyph('❌', 'Missing')) : '…'], ['Steam API key', data ? (data.has_api_key ? 'Stored (never shown)' : 'Missing') : '…'],
[glyph('🆔', 'Steam ID'), h('span', { class: 'mono' }, data?.steam_id ?? '—')], ['Steam ID', h('span', { class: 'mono' }, data?.steam_id ?? '—')],
]), ]),
{ aside: link(pageHref('/setup'), glyph('✏️', 'Open setup')), icon: '🔧' }, { aside: link(pageHref('/setup'), 'Open setup') },
), ),
) )
} }

View File

@ -1,66 +0,0 @@
// 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 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 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.getAttribute('data-state') === text) const pill = (el: Element, text: string) => [...el.querySelectorAll('.pill')].find((p) => p.textContent === text)
const never = () => new Promise(() => undefined) const never = () => new Promise(() => undefined)
describe('<health-badges>', () => { describe('<health-badges>', () => {
@ -16,17 +16,13 @@ describe('<health-badges>', () => {
expect(pill(el, 'Server ok')).toHaveClass('pill-success') expect(pill(el, 'Server ok')).toHaveClass('pill-success')
expect(pill(el, 'Daemon …')).toHaveClass('pill-neutral') expect(pill(el, 'Daemon …')).toHaveClass('pill-neutral')
expect(pill(el, 'Server ok')).not.toHaveAttribute('title') 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 () => { it('shows a healthy server with its version, and a running daemon', async () => {
stubApi({ 'GET /api/server': server(), 'GET /api/daemon': daemon('running') }) stubApi({ 'GET /api/server': server(), 'GET /api/daemon': daemon('running') })
const el = mount('<health-badges></health-badges>') const el = mount('<health-badges></health-badges>')
await vi.waitFor(() => { expect(pill(el, 'Daemon running')).toHaveClass('pill-success') }) await vi.waitFor(() => { expect(pill(el, 'Daemon running')).toHaveClass('pill-success') })
// The version is spoken, never a tooltip (textgate). expect(pill(el, 'Server ok')).toHaveAttribute('title', 'v1.2.3')
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 () => { it('flags a stale server and a restarting daemon', async () => {

View File

@ -4,21 +4,10 @@
import { q } from '../api/queries' import { q } from '../api/queries'
import { define, h } from '../lib/dom' import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { errorNotice, glyph } from '../ui/build' import { errorNotice } from '../ui/build'
import { ServerRestart } from './serverRestart' import { ServerRestart } from './serverRestart'
const DAEMON_TONE = { running: 'success', restarting: 'warning', unreachable: 'danger' } as const 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 { export class HealthBadgesElement extends LiveElement {
protected override setup(): void { protected override setup(): void {
@ -31,15 +20,12 @@ export class HealthBadgesElement extends LiveElement {
const d = q.daemon.state.data?.state const d = q.daemon.state.data?.state
const serverTone = server.error ? 'danger' : server.data?.stale ? 'warning' : 'success' const serverTone = server.error ? 'danger' : server.data?.stale ? 'warning' : 'success'
const serverText = server.error ? 'Server down' : server.data?.stale ? 'Server stale' : 'Server ok' 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( this.replaceChildren(
h( h(
'div', 'div',
{ class: 'health', 'aria-label': 'Health' }, { class: 'health', 'aria-label': 'Health' },
badge(serverTone, `🌐${STATE_GLYPH[serverTone]}`, serverText, version), h('span', { class: `pill pill-${serverTone}`, title: server.data ? `v${server.data.version}` : null }, serverText),
badge(d ? DAEMON_TONE[d] : 'neutral', `🛡️${STATE_GLYPH[d ? DAEMON_TONE[d] : 'neutral']}`, `Daemon ${d ?? '…'}`), h('span', { class: `pill pill-${d ? DAEMON_TONE[d] : 'neutral'}` }, `Daemon ${d ?? '…'}`),
), ),
) )
} }
@ -67,7 +53,7 @@ export class StaleBannerElement extends LiveElement {
h( h(
'div', 'div',
{ class: 'banner banner-warning', role: 'status' }, { class: 'banner banner-warning', role: 'status' },
glyph('⚠️🌐', 'The web server is running stale code. Restart it to pick up the new version.'), h('span', {}, h('strong', {}, 'The web server is running stale code.'), ' Restart it to pick up the new version.'),
h( h(
'button', 'button',
{ {
@ -75,9 +61,8 @@ export class StaleBannerElement extends LiveElement {
class: 'btn btn-primary btn-small', class: 'btn btn-primary btn-small',
disabled: this.restart.restarting || action.pending, disabled: this.restart.restarting || action.pending,
onclick: () => void action.run(), onclick: () => void action.run(),
'aria-label': this.restart.restarting ? 'Restarting…' : 'Restart server',
}, },
h('span', { 'aria-hidden': 'true' }, this.restart.restarting ? '⏳' : '🔄'), this.restart.restarting ? 'Restarting…' : 'Restart server',
), ),
action.error ? errorNotice(action.error) : null, action.error ? errorNotice(action.error) : null,
), ),

View File

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

View File

@ -145,5 +145,3 @@
.countdown-clock { display: flex; align-items: baseline; gap: var(--space-3); } .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; } .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; } .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); }

View File

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

View File

@ -1,40 +0,0 @@
// 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

@ -1,59 +0,0 @@
// 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,13 +5,32 @@
import { beforeEach, describe, expect, it } from 'vitest' import { beforeEach, describe, expect, it } from 'vitest'
import { installEventSource } from './harness' import { installEventSource } from './harness'
import { mountJob } from './jobHelpers' import { mountJob } from './jobHelpers'
import { visibleWords } from './visibleWords'
import { ApiFailure } from '../api/client' import { ApiFailure } from '../api/client'
import { timelineChart } from '../lib/charts/timeline' import { timelineChart } from '../lib/charts/timeline'
import { errorNotice, loading } from '../ui/build' import { errorNotice, loading } from '../ui/build'
import type { EstimateResult } from '../estimate' import type { EstimateResult } from '../estimate'
import type { Filters } from '../types' 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) beforeEach(installEventSource)

View File

@ -1,26 +0,0 @@
// 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,16 +81,6 @@ describe('small builders', () => {
expect(el.querySelector('.pill-icon')).not.toBeNull() 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', () => { it('link is an anchor', () => {
const a = link('/library/', 'Open') const a = link('/library/', 'Open')
expect(a.getAttribute('href')).toBe('/library/') expect(a.getAttribute('href')).toBe('/library/')

View File

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

View File

@ -18,8 +18,7 @@ export class Modal {
private opener: Element | null = null private opener: Element | null = null
constructor({ title, wide = false, onClose }: ModalOptions) { constructor({ title, wide = false, onClose }: ModalOptions) {
// Textgate: the title is spoken only; the dialog's content says what it is. this.heading = h('h2', {}, title)
this.heading = h('h2', { class: 'sr-only' }, title)
const close = h( const close = h(
'button', 'button',
{ type: 'button', class: 'btn btn-ghost btn-icon dialog-close', 'aria-label': 'Close', onclick: onClose }, { 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', () => { it('dateTime formats or dashes', () => {
expect(dateTime(null)).toBe('—') expect(dateTime(null)).toBe('—')
expect(dateTime('2026-10-10T12:00:00Z')).toMatch(/^\d\d-\d\d \d\d:\d\d$/) expect(dateTime('2026-10-10T12:00:00Z')).toMatch(/\d/)
}) })
it('duration spans start to end, or to now while running', () => { it('duration spans start to end, or to now while running', () => {

View File

@ -31,12 +31,11 @@ export function ago(iso: string | null, now: number = Date.now()): string {
return `${Math.round(s / 86_400)} d ago` 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 { export function dateTime(iso: string | null): string {
if (!iso) return '—' if (!iso) return '—'
const d = new Date(iso) return new Date(iso).toLocaleString(undefined, {
const p = (n: number) => String(n).padStart(2, '0') month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
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 { export function duration(startIso: string | null, endIso: string | null, now: number = Date.now()): string {