Compare commits

...

5 Commits

Author SHA1 Message Date
ec8d762197 Point icon words contract at its new doc
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 10:09:47 +01:00
f1539195a2 Move icon words API docs to own file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 10:09:39 +01:00
b46725d151 Add kuhy's icon word picks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 10:08:27 +01:00
ff7ba540d3 Add icon registry, words picker and render
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 10:08:26 +01:00
79478225be Add icon word ledger and API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
2026-11-16 10:08:26 +01:00
56 changed files with 2719 additions and 94 deletions

14
DOCS-icon-words.md Normal file
View File

@ -0,0 +1,14 @@
# Icon words API
Part of the web control API ([DOCS-web-control-api.md](DOCS-web-control-api.md)).
## `/api/icon-words`
`GET /api/icon-words` → `IconLedger`; `POST` or `PUT /api/icon-words/{icon_id}` with `{word?, glyph?}` → `IconLedger` (200). Writes need Host, Origin and `X-SBE-Token` like every non-GET. TS mirror: `web/src/api/iconWordsContract.ts`.
- **Ledger** `web/src/ui/icon_words.json` (a repo file the user commits; `SBE_ICON_WORDS` overrides the path): `{"version":1,"icons":{"<id>":{"word":"<text>"|null,"glyph":"<emoji>"|null}}}`. Absent id = unanswered; no `word` key = only a glyph chosen; `word: null` = skipped (no label); `glyph: null` = default. The server reads it per request and never builds from it (`_web_build` ignores it); writes go to a sibling temp file, then rename.
- **Registry** `web/src/icons/registry.json`: id → default glyph, spoken name, description, 3 suggested words, 3 alternative glyphs (`registry.ts` types it).
- **`word`**: any text; casing kept, whitespace runs collapsed; 1–40 characters, no control characters, else `invalid_params`. `null` skips. **`glyph`**: the default or one of the icon's 3 alternatives (the default is stored as `null`), else `invalid_params`. Unknown id → `not_found`; empty body or unknown key → `invalid_params`.
- Every served `.html` page carries the ledger as `<script type="application/json" id="sbe-icon-words">` (`<` escaped), so a pick shows on the next page load.
- **Corrupt ledger** (bad JSON or schema): copied to `<ledger>.corrupt` (an older copy is never overwritten) and left in place; every read and write answers `op_failed` (500) naming the copy until someone fixes it. Pages then carry that error body and draw no words.
- UI: a word is drawn right of its icon in sentence case (`web/src/icons/textCase.ts` holds the acronym list); the `/words` picker (palette → Icon words) sets words and glyphs; `localStorage["sbe-icon-words-hidden"] = "1"` hides all words.

View File

@ -243,3 +243,5 @@ hard-codes it.
to anything pytest did not spawn and Steam/kill argv in real `Popen`, to anything pytest did not spawn and Steam/kill argv in real `Popen`,
and fails any test that hits it (a stale demo test once killed the and fails any test that hits it (a stale demo test once killed the
live game). live game).
Icon words (`/api/icon-words`): see [DOCS-icon-words.md](DOCS-icon-words.md).

View File

@ -0,0 +1,139 @@
"""The icon-word ledger file: the words (and glyph swaps) the user picked.
``{"version": 1, "icons": {"<icon id>": {"word": "<text>" | null,
"glyph": "<emoji>" | null}}}``. An absent id is unanswered; an entry without
a ``word`` key has a glyph choice but no word decision yet; ``word: null``
is a skip (no label); ``glyph: null`` keeps the registry's default.
It lives in the repo (``web/src/ui/icon_words.json``, committed by the user)
and is read by the web server at runtime, never by the build: a pick shows
on the next page load. ``SBE_ICON_WORDS`` points a scratch server at a copy.
Writes go to a sibling temp file and are renamed over the ledger, so a crash
mid-write leaves the previous file whole. A file that does not parse or does
not match the schema is copied aside as ``.corrupt`` (never over an older
copy) and every read fails loudly until someone fixes it: dropping it and
starting empty would silently lose the user's picks.
"""
from __future__ import annotations
import contextlib
import json
import os
from pathlib import Path
import tempfile
import time
from typing import Any, Final
LEDGER_ENV: Final = "SBE_ICON_WORDS"
LEDGER_NAME: Final = "icon_words.json"
DEFAULT_LEDGER: Final = (
Path(__file__).resolve().parent.parent / "web" / "src" / "ui" / LEDGER_NAME
)
VERSION: Final = 1
# A repo file: world-readable like its neighbours (mkstemp would make it 0600).
FILE_MODE: Final = 0o644
_ENTRY_KEYS: Final = frozenset({"word", "glyph"})
type Ledger = dict[str, Any]
class LedgerCorruptError(Exception):
"""The ledger does not parse; *kept* holds the copy set aside."""
def __init__(self, path: Path, kept: Path, why: str) -> None:
"""Name the broken file, its kept copy and what is wrong with it."""
super().__init__(
f"The icon-word ledger {path} is unreadable ({why}); a copy was kept "
f"as {kept}. Fix or restore it (git checkout) to use icon words."
)
self.path = path
self.kept = kept
def ledger_path() -> Path:
"""The ledger this process reads: ``$SBE_ICON_WORDS`` or the repo file."""
override = os.environ.get(LEDGER_ENV)
return Path(override) if override else DEFAULT_LEDGER
def is_ledger_file(path: Path) -> bool:
"""True for a ledger, its temp files and its corrupt copies (runtime data)."""
name = path.name.lstrip(".")
return name == LEDGER_NAME or name.startswith(f"{LEDGER_NAME}.")
def empty_ledger() -> Ledger:
"""A ledger with nothing answered."""
return {"version": VERSION, "icons": {}}
def _schema_problem(data: object) -> str | None:
"""Why *data* is not a ledger, or None when it is one."""
if not isinstance(data, dict) or set(data) != {"version", "icons"}:
return "not a {version, icons} object"
if data["version"] != VERSION:
return f"version {data['version']!r} is not {VERSION}"
if not isinstance(data["icons"], dict):
return "icons is not an object"
for icon, entry in data["icons"].items():
if not isinstance(entry, dict) or not set(entry) <= _ENTRY_KEYS:
return f"entry {icon!r} is not a {{word, glyph}} object"
for key, value in entry.items():
if value is not None and not isinstance(value, str):
return f"{icon}.{key} is neither text nor null"
return None
def _keep_aside(path: Path, raw: bytes) -> Path:
"""Copy *raw* next to *path* as ``.corrupt``; never overwrite an older copy."""
kept = path.with_name(f"{path.name}.corrupt")
if kept.exists():
if kept.read_bytes() == raw:
return kept
kept = path.with_name(f"{path.name}.corrupt.{time.time_ns()}")
kept.write_bytes(raw)
return kept
def load_ledger(path: Path) -> Ledger:
"""Read the ledger at *path*; a missing file is an empty ledger.
Raises:
LedgerCorruptError: the file does not parse or match the schema
(it is kept aside first, and left in place).
"""
try:
raw = path.read_bytes()
except FileNotFoundError:
return empty_ledger()
try:
data = json.loads(raw)
except ValueError as exc:
raise LedgerCorruptError(path, _keep_aside(path, raw), str(exc)) from None
why = _schema_problem(data)
if why is not None:
raise LedgerCorruptError(path, _keep_aside(path, raw), why)
return data
def save_ledger(path: Path, ledger: Ledger) -> None:
"""Write *ledger* atomically: sibling temp file, fsync, rename over *path*.
Sorted keys and a trailing newline keep the user's commits diffable.
"""
text = json.dumps(ledger, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as out:
out.write(text)
out.flush()
os.fsync(out.fileno())
Path(tmp).chmod(FILE_MODE)
Path(tmp).replace(path)
except BaseException:
with contextlib.suppress(FileNotFoundError):
Path(tmp).unlink()
raise

View File

@ -13,6 +13,7 @@ from pathlib import Path
import shutil import shutil
import subprocess import subprocess
from steam_backlog_enforcer._icon_ledger import is_ledger_file
from steam_backlog_enforcer.game_install import _echo from steam_backlog_enforcer.game_install import _echo
WEB_DIR = (Path(__file__).resolve().parent.parent / "web").resolve() WEB_DIR = (Path(__file__).resolve().parent.parent / "web").resolve()
@ -61,7 +62,13 @@ def frontend_is_stale() -> bool:
sources = list(_SOURCE_FILES) sources = list(_SOURCE_FILES)
for source_dir in _SOURCE_DIRS: for source_dir in _SOURCE_DIRS:
if source_dir.is_dir(): if source_dir.is_dir():
sources.extend(path for path in source_dir.rglob("*") if path.is_file()) sources.extend(
path
for path in source_dir.rglob("*")
# The icon-word ledger lives in src/ but the server reads it per
# page; counting it would rebuild on every pick.
if path.is_file() and not is_ledger_file(path)
)
return any(_mtime(path) > built for path in sources) return any(_mtime(path) > built for path in sources)

View File

@ -0,0 +1,168 @@
"""``/api/icon-words``: the words the user puts next to the UI's icons.
The UI is text-free except for these: every icon has a registry entry
(``web/src/icons/registry.json``: default glyph, 3 suggested words, 3
alternative glyphs) and the user picks a word and optionally a glyph for each
on the ``/words`` page. Picks land in the ledger (:mod:`._icon_ledger`) and
every served page carries the ledger as a JSON ``<script>``, so a pick shows
on the next page load without a rebuild.
Manual words are always accepted, whatever they say: casing is kept,
whitespace runs collapse to one space, and only empty, over-40-character or
control-character text is refused. A glyph must be the icon's default or one
of its three registered alternatives.
"""
from __future__ import annotations
from http import HTTPStatus
import json
import logging
from pathlib import Path
import re
import threading
from typing import TYPE_CHECKING, Any, Final
from steam_backlog_enforcer import _icon_ledger
from steam_backlog_enforcer._web_errors import ApiError, not_found
from steam_backlog_enforcer._web_io import Reply, ok
if TYPE_CHECKING:
from steam_backlog_enforcer._web_io import Request
logger = logging.getLogger(__name__)
REGISTRY_FILE: Final = (
Path(__file__).resolve().parent.parent / "web" / "src" / "icons" / "registry.json"
)
# The <script id> the UI reads at boot (ICON_WORDS_SCRIPT in iconWordsContract.ts).
SCRIPT_ID: Final = "sbe-icon-words"
MAX_WORD: Final = 40
# The same classes as web/src/icons/wordRules.ts, spelled out so Python's
# wider ``\s`` (it counts \x1c-\x1f as space) cannot make the two disagree.
_SPACE: Final = re.compile(r"[\t\n\v\f\r \u00a0\u2000-\u200a\u2028\u2029\u202f\u3000]+")
_CONTROL: Final = re.compile(r"[\x00-\x1f\x7f-\x9f]")
_HEAD_TAG: Final = re.compile(rb"<head[^>]*>", re.IGNORECASE)
_BODY_KEYS: Final = frozenset({"word", "glyph"})
# One writer at a time: the server is threaded and a save is read-modify-write.
_WRITE_LOCK = threading.Lock()
def _failed(message: str) -> ApiError:
"""A loud 500: the ledger or registry cannot be used as it is."""
return ApiError(message, code="op_failed", status=HTTPStatus.INTERNAL_SERVER_ERROR)
def _load() -> _icon_ledger.Ledger:
"""The current ledger; a corrupt one is logged and refused."""
try:
return _icon_ledger.load_ledger(_icon_ledger.ledger_path())
except _icon_ledger.LedgerCorruptError as exc:
failure = exc
# Logged outside the handler: the message is the whole story, no traceback.
logger.error("%s", failure)
raise _failed(str(failure))
def load_registry() -> dict[str, dict[str, Any]]:
"""Every registered icon by id (its default glyph and alternatives)."""
try:
return json.loads(REGISTRY_FILE.read_text("utf-8"))["icons"]
except (OSError, ValueError, KeyError, TypeError) as exc:
msg = f"The icon registry {REGISTRY_FILE} is unreadable: {exc}."
raise _failed(msg) from None
def normalize_word(raw: object) -> str:
"""The word to store for *raw*: collapsed whitespace, casing kept.
Raises:
ApiError: ``invalid_params`` for non-text, empty, over-long or
control-character input.
"""
if not isinstance(raw, str):
msg = "word must be text, or null to skip."
raise ApiError(msg, code="invalid_params")
word = _SPACE.sub(" ", raw).strip()
if not word:
msg = "word is empty; send null to skip this icon instead."
raise ApiError(msg, code="invalid_params")
if len(word) > MAX_WORD:
msg = f"word is {len(word)} characters; at most {MAX_WORD} fit next to an icon."
raise ApiError(msg, code="invalid_params")
if _CONTROL.search(word):
msg = "word holds a control character."
raise ApiError(msg, code="invalid_params")
return word
def _glyph(raw: object, entry: dict[str, Any]) -> str | None:
"""The glyph to store: null for the default, else a registered alternative.
Raises:
ApiError: ``invalid_params`` for anything else.
"""
if raw is None or raw == entry["glyph"]:
return None
if isinstance(raw, str) and raw in entry["alts"]:
return raw
allowed = " ".join(entry["alts"])
msg = f"glyph must be the default {entry['glyph']} or one of {allowed}."
raise ApiError(msg, code="invalid_params")
def _update(body: dict[str, Any], entry: dict[str, Any]) -> dict[str, Any]:
"""The validated changes in *body* (``word`` and/or ``glyph``)."""
unknown = set(body) - _BODY_KEYS
if unknown or not body:
msg = (
"Send word (text, or null to skip) and/or glyph (an alternative, or null)."
)
raise ApiError(msg, code="invalid_params")
out: dict[str, Any] = {}
if "word" in body:
out["word"] = None if body["word"] is None else normalize_word(body["word"])
if "glyph" in body:
out["glyph"] = _glyph(body["glyph"], entry)
return out
def icon_words_view(_request: Request) -> Reply:
"""``GET /api/icon-words`` — the whole ledger."""
return ok(_load())
def set_icon_word_view(request: Request) -> Reply:
"""``POST|PUT /api/icon-words/{icon}`` — save a word, skip or glyph."""
(icon,) = request.args
entry = load_registry().get(icon)
if entry is None:
msg = f"No icon {icon!r} is registered."
raise not_found(msg)
changes = _update(request.body, entry)
with _WRITE_LOCK:
ledger = _load()
saved = ledger["icons"].setdefault(icon, {})
saved.update(changes)
saved.setdefault("glyph", None)
_icon_ledger.save_ledger(_icon_ledger.ledger_path(), ledger)
return ok(ledger)
def inject_icon_words(html: bytes) -> bytes:
"""Insert the ledger as ``<script type="application/json">`` after ``<head>``.
A corrupt ledger never breaks the page: the script then carries the
error body, which the UI reports. ``<`` is escaped, so no word can close
the script element early.
"""
try:
payload: object = _load()
except ApiError as exc:
payload = exc.body()
text = json.dumps(payload, ensure_ascii=False).replace("<", "\\u003c")
tag = f'<script type="application/json" id="{SCRIPT_ID}">{text}</script>'.encode()
match = _HEAD_TAG.search(html)
if match is None:
return tag + html
return html[: match.end()] + tag + html[match.end() :]

View File

@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer import ( from steam_backlog_enforcer import (
_web_art, _web_art,
_web_daemon, _web_daemon,
_web_icon_words,
_web_jobs, _web_jobs,
_web_library, _web_library,
_web_process, _web_process,
@ -29,6 +30,8 @@ if TYPE_CHECKING:
type Route = Callable[[Request], Reply] type Route = Callable[[Request], Reply]
_ID = r"([0-9A-Za-z_-]{1,64})" _ID = r"([0-9A-Za-z_-]{1,64})"
# Icon ids are dotted (``job.state.waiting_input``); the registry re-checks them.
_ICON = r"([a-z][a-z0-9_.-]{0,63})"
# Matched before the table by the server: it streams instead of replying. # Matched before the table by the server: it streams instead of replying.
EVENTS_PATH: Final = re.compile(rf"^/api/jobs/{_ID}/events$") EVENTS_PATH: Final = re.compile(rf"^/api/jobs/{_ID}/events$")
@ -43,8 +46,9 @@ class _Entry:
def _r(method: str, path: str, route: Route) -> _Entry: def _r(method: str, path: str, route: Route) -> _Entry:
"""Build an entry; ``{id}`` in *path* captures one id segment.""" """Build an entry; ``{id}`` / ``{icon}`` in *path* capture one segment."""
return _Entry(method, re.compile("^" + path.replace("{id}", _ID) + "$"), route) pattern = path.replace("{id}", _ID).replace("{icon}", _ICON)
return _Entry(method, re.compile("^" + pattern + "$"), route)
ROUTES: Final[tuple[_Entry, ...]] = ( ROUTES: Final[tuple[_Entry, ...]] = (
@ -71,6 +75,9 @@ ROUTES: Final[tuple[_Entry, ...]] = (
_r("POST", "/api/pending/{id}/heartbeat", _web_daemon.heartbeat_view), _r("POST", "/api/pending/{id}/heartbeat", _web_daemon.heartbeat_view),
_r("POST", "/api/pending/{id}/commit", _web_daemon.commit_view), _r("POST", "/api/pending/{id}/commit", _web_daemon.commit_view),
_r("DELETE", "/api/pending/{id}", _web_daemon.cancel_pending_view), _r("DELETE", "/api/pending/{id}", _web_daemon.cancel_pending_view),
_r("GET", "/api/icon-words", _web_icon_words.icon_words_view),
_r("POST", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view),
_r("PUT", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view),
) )

View File

@ -5,7 +5,7 @@ DNS-rebinding guard, :mod:`._web_auth`), fails closed on stale code
(:mod:`._serve_stale`), checks ``Origin`` and the per-launch token on (:mod:`._serve_stale`), checks ``Origin`` and the per-launch token on
anything that is not a GET (and on the SSE stream), then hands off to a anything that is not a GET (and on the SSE stream), then hands off to a
route from :mod:`._web_routes`, the SSE streamer (:mod:`._web_sse`) or the route from :mod:`._web_routes`, the SSE streamer (:mod:`._web_sse`) or the
static bundle (``web/dist``, with the token injected into every ``.html`` page). static bundle (``web/dist``; ``.html`` pages get the token and icon words).
Binds to loopback only; never serves secrets and never sends CORS headers. Binds to loopback only; never serves secrets and never sends CORS headers.
In development the Vite dev server proxies ``/api`` here; in production the In development the Vite dev server proxies ``/api`` here; in production the
@ -21,7 +21,7 @@ import mimetypes
from pathlib import Path from pathlib import Path
from urllib.parse import parse_qs, urlsplit from urllib.parse import parse_qs, urlsplit
from steam_backlog_enforcer import _web_auth, _web_process from steam_backlog_enforcer import _web_auth, _web_icon_words, _web_process
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
from steam_backlog_enforcer._serve_stale import outdated_source from steam_backlog_enforcer._serve_stale import outdated_source
from steam_backlog_enforcer._web_errors import ApiError, not_found from steam_backlog_enforcer._web_errors import ApiError, not_found
@ -88,6 +88,10 @@ class _Handler(BaseHTTPRequestHandler):
"""Handle a DELETE.""" """Handle a DELETE."""
self._handle("DELETE") self._handle("DELETE")
def do_PUT(self) -> None:
"""Handle a PUT (``/api/icon-words/{icon}`` takes PUT or POST)."""
self._handle("PUT")
def _handle(self, method: str) -> None: def _handle(self, method: str) -> None:
"""Run the checks, then dispatch; every refusal is a JSON error.""" """Run the checks, then dispatch; every refusal is a JSON error."""
split = urlsplit(self.path) split = urlsplit(self.path)
@ -184,9 +188,9 @@ class _Handler(BaseHTTPRequestHandler):
body = candidate.read_bytes() body = candidate.read_bytes()
headers: dict[str, str] = {} headers: dict[str, str] = {}
if candidate.suffix == ".html": if candidate.suffix == ".html":
# Carries this launch's token: never cache it.
body = _web_auth.inject_token(body, self.server.token) body = _web_auth.inject_token(body, self.server.token)
headers["Cache-Control"] = "no-store" body = _web_icon_words.inject_icon_words(body)
headers["Cache-Control"] = "no-store" # carries token + icon words
send_bytes(self, status, body, ctype, headers) send_bytes(self, status, body, ctype, headers)

View File

@ -0,0 +1,23 @@
"""A two-icon registry the icon-word tests use instead of the real one."""
from __future__ import annotations
REGISTRY: dict[str, object] = {
"version": 1,
"icons": {
"nav.dashboard": {
"glyph": "🏠",
"spoken": "Dashboard",
"desc": "d",
"words": ["home", "dashboard", "overview"],
"alts": ["🏡", "🧭", "📟"],
},
"cmd.done": {
"glyph": "🏆",
"spoken": "Done",
"desc": "d",
"words": ["done", "finished", "next"],
"alts": ["🥇", "🎉", "🏁"],
},
},
}

View File

@ -1,9 +1,9 @@
"""Autouse isolation of the control plane and the HLTB endpoint memo. """Autouse isolation of the control plane and the HLTB endpoint memo.
Redirects the web cover-art caches, the daemon control socket, restart Redirects the web cover-art caches, the daemon control socket, restart
markers, backups and web job store (all under ``/var/lib``, ``/run`` or the markers, backups, web job store (all under ``/var/lib``, ``/run`` or the
real ``~/.local/state``) into ``tmp_path``, and forgets the remembered HLTB real ``~/.local/state``) and the repo's icon-word ledger into
search URL around every test. ``tmp_path``, and forgets the remembered HLTB search URL around every test.
Split out of ``conftest.py`` to keep every file inside the 250-line cap; Split out of ``conftest.py`` to keep every file inside the 250-line cap;
``conftest`` imports the fixtures by name, which is what registers them. ``conftest`` imports the fixtures by name, which is what registers them.
@ -18,6 +18,7 @@ import pytest
from steam_backlog_enforcer._hltb_failures import reset_failures from steam_backlog_enforcer._hltb_failures import reset_failures
from steam_backlog_enforcer._hltb_search_api import forget_hltb_search_url from steam_backlog_enforcer._hltb_search_api import forget_hltb_search_url
from steam_backlog_enforcer._icon_ledger import LEDGER_ENV
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
@ -38,6 +39,8 @@ def _isolate_control_plane(
""" """
state = tmp_path / "ctl_state" state = tmp_path / "ctl_state"
monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "xdg_runtime")) monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "xdg_runtime"))
# The icon-word ledger is a committed repo file: never write the real one.
monkeypatch.setenv(LEDGER_ENV, str(tmp_path / "icon_words.json"))
with ( with (
patch("steam_backlog_enforcer._ctl_gap.RESTART_EXIT_FILE", state / "exit.json"), patch("steam_backlog_enforcer._ctl_gap.RESTART_EXIT_FILE", state / "exit.json"),
patch( patch(

View File

@ -0,0 +1,180 @@
"""Tests for _icon_ledger: the icon-word ledger file (load, atomic save, corrupt)."""
from __future__ import annotations
import json
import os
from pathlib import Path
import stat
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger as mod
_GOOD = {
"version": 1,
"icons": {
"nav.dashboard": {"word": "Home", "glyph": None},
"cmd.done": {"word": None, "glyph": "🥇"},
"cmd.scan": {"glyph": "📡"},
},
}
@pytest.fixture(name="home")
def fixture_home(tmp_path: Path) -> Path:
"""An empty directory of its own (conftest fixtures also use tmp_path)."""
path = tmp_path / "ledger_home"
path.mkdir()
return path
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
class TestPath:
"""Where the ledger lives."""
def test_default_is_the_repo_file(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Without the env override the ledger is web/src/ui/icon_words.json."""
monkeypatch.delenv(mod.LEDGER_ENV, raising=False)
repo = Path(mod.__file__).resolve().parent.parent
assert repo / "web" / "src" / "ui" / "icon_words.json" == mod.DEFAULT_LEDGER
assert mod.ledger_path() == mod.DEFAULT_LEDGER
def test_env_override_wins(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""SBE_ICON_WORDS points the server at another file (scratch copies)."""
monkeypatch.setenv(mod.LEDGER_ENV, str(tmp_path / "copy.json"))
assert mod.ledger_path() == tmp_path / "copy.json"
def test_tests_never_see_the_repo_file(self) -> None:
"""The autouse isolation redirects the ledger into tmp_path."""
assert mod.ledger_path() != mod.DEFAULT_LEDGER
@pytest.mark.parametrize(
("name", "expected"),
[
("icon_words.json", True),
("icon_words.json.corrupt", True),
(".icon_words.json.x1y2.tmp", True),
("icon_words.ts", False),
("registry.json", False),
],
)
def test_is_ledger_file(self, name: str, *, expected: bool) -> None:
"""The ledger, its temp files and corrupt copies are runtime data."""
assert mod.is_ledger_file(Path("/x") / name) is expected
class TestLoad:
"""load_ledger: missing, valid and corrupt files."""
def test_missing_file_is_an_empty_ledger(self, home: Path) -> None:
"""No file yet means nothing answered."""
assert mod.load_ledger(home / "none.json") == {"version": 1, "icons": {}}
def test_valid_file_round_trips(self, home: Path) -> None:
"""A valid file loads as written, a missing word key included."""
path = home / "l.json"
_write(path, json.dumps(_GOOD))
assert mod.load_ledger(path) == _GOOD
@pytest.mark.parametrize(
"text",
[
"{not json",
"[]",
'{"version": 2, "icons": {}}',
'{"version": 1, "icons": []}',
'{"version": 1, "icons": {"a.b": "word"}}',
'{"version": 1, "icons": {"a.b": {"word": 5}}}',
'{"version": 1, "icons": {"a.b": {"glyph": ["x"]}}}',
'{"version": 1, "icons": {"a.b": {"word": "x", "extra": 1}}}',
],
)
def test_corrupt_file_is_kept_aside_and_fails_loudly(
self, home: Path, text: str
) -> None:
"""Bad JSON or schema: copied to .corrupt, original untouched, raises."""
path = home / "l.json"
_write(path, text)
with pytest.raises(mod.LedgerCorruptError) as err:
mod.load_ledger(path)
kept = home / "l.json.corrupt"
assert err.value.kept == kept
assert kept.read_text("utf-8") == text
assert path.read_text("utf-8") == text
assert str(kept) in str(err.value)
def test_same_corrupt_bytes_are_kept_once(self, home: Path) -> None:
"""Re-reading the same broken file does not pile up copies."""
path = home / "l.json"
_write(path, "{bad")
for _ in range(2):
with pytest.raises(mod.LedgerCorruptError):
mod.load_ledger(path)
assert sorted(p.name for p in home.iterdir()) == [
"l.json",
"l.json.corrupt",
]
def test_older_corrupt_copy_is_never_overwritten(self, home: Path) -> None:
"""A different broken file gets its own copy; the first one survives."""
path = home / "l.json"
_write(home / "l.json.corrupt", "{first")
_write(path, "{second")
with pytest.raises(mod.LedgerCorruptError) as err:
mod.load_ledger(path)
assert (home / "l.json.corrupt").read_text("utf-8") == "{first"
assert err.value.kept.name.startswith("l.json.corrupt.")
assert err.value.kept.read_text("utf-8") == "{second"
class TestSave:
"""save_ledger: atomic, stable, readable."""
def test_writes_sorted_indented_json_with_newline(self, home: Path) -> None:
"""Stable output so the user's commits diff cleanly; emoji kept raw."""
path = home / "l.json"
mod.save_ledger(path, _GOOD)
text = path.read_text("utf-8")
assert text.endswith("}\n")
assert "🥇" in text
assert json.loads(text) == _GOOD
assert text.index('"cmd.done"') < text.index('"nav.dashboard"')
assert stat.S_IMODE(path.stat().st_mode) == mod.FILE_MODE
def test_replace_failure_leaves_the_old_file_and_no_temp(self, home: Path) -> None:
"""A failed rename keeps the previous ledger intact and cleans up."""
path = home / "l.json"
_write(path, json.dumps({"version": 1, "icons": {}}))
with (
patch.object(mod.os, "replace", side_effect=OSError("disk")),
pytest.raises(OSError, match="disk"),
):
mod.save_ledger(path, _GOOD)
assert json.loads(path.read_text("utf-8")) == {"version": 1, "icons": {}}
assert [p.name for p in home.iterdir()] == ["l.json"]
def test_goes_through_a_temp_file_in_the_same_dir(self, home: Path) -> None:
"""The new content lands by rename from a sibling temp file."""
path = home / mod.LEDGER_NAME
seen: list[tuple[str, str]] = []
real = os.replace
def spy(src: str, dst: str) -> None:
seen.append((src, dst))
real(src, dst)
with patch.object(mod.os, "replace", side_effect=spy):
mod.save_ledger(path, _GOOD)
assert len(seen) == 1
src, dst = seen[0]
assert Path(dst) == path
assert Path(src).parent == home
assert mod.is_ledger_file(Path(src))

View File

@ -108,6 +108,22 @@ class TestFrontendIsStale:
_touch(web / "dist" / "index.html", 2000.0) _touch(web / "dist" / "index.html", 2000.0)
assert _web_build.frontend_is_stale() is False assert _web_build.frontend_is_stale() is False
def test_icon_word_ledger_is_runtime_data_not_a_build_input(
self, web: Path
) -> None:
# The server reads the ledger per page; a pick must not make the
# next `serve` rebuild (a unit without pnpm on PATH would crash-loop).
"""The ledger, its temp files and corrupt copies never mark dist stale."""
_touch(web / "src" / "app.tsx", 1000.0)
_touch(web / "dist" / "index.html", 2000.0)
for name in (
"icon_words.json",
".icon_words.json.ab.tmp",
"icon_words.json.corrupt",
):
_touch(web / "src" / "ui" / name, 3000.0)
assert _web_build.frontend_is_stale() is False
def test_directories_in_src_are_skipped(self, web: Path) -> None: def test_directories_in_src_are_skipped(self, web: Path) -> None:
# A directory's own mtime bumps whenever a file inside it is added or # A directory's own mtime bumps whenever a file inside it is added or
# removed, so counting it would report staleness after a build. # removed, so counting it would report staleness after a build.

View File

@ -0,0 +1,212 @@
"""Tests for _web_icon_words: the icon-word endpoints and the page injection."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger, _web_icon_words, _web_routes
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer.tests._icon_registry import REGISTRY
from steam_backlog_enforcer.tests._web_request import make_request, payload_of
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@pytest.fixture(autouse=True, name="registry")
def fixture_registry(tmp_path: Path) -> Iterator[Path]:
"""A two-icon registry instead of the real one."""
path = tmp_path / "registry.json"
path.write_text(json.dumps(REGISTRY), encoding="utf-8")
with patch.object(_web_icon_words, "REGISTRY_FILE", path):
yield path
def _set(icon: str, **body: object) -> dict[str, object]:
reply = _web_icon_words.set_icon_word_view(
make_request(icon, body=body, method="POST")
)
return payload_of(reply)
def _stored() -> dict[str, dict[str, object]]:
return json.loads(_icon_ledger.ledger_path().read_text("utf-8"))["icons"]
def _refused(icon: str, code: str, **body: object) -> ApiError:
with pytest.raises(ApiError) as err:
_set(icon, **body)
assert err.value.code == code
return err.value
class TestWords:
"""POST /api/icon-words/<id> with a word."""
def test_suggestion_is_saved_and_the_ledger_returned(self) -> None:
"""A picked word is stored and the whole ledger comes back."""
out = _set("nav.dashboard", word="home")
assert out == {
"version": 1,
"icons": {"nav.dashboard": {"word": "home", "glyph": None}},
}
assert _stored() == {"nav.dashboard": {"word": "home", "glyph": None}}
def test_manual_multi_word_keeps_casing_and_collapses_spaces(self) -> None:
"""Any words are accepted; whitespace runs become one space."""
_set("cmd.done", word=" I got\tan HLTB\n win ")
assert _stored()["cmd.done"] == {"word": "I got an HLTB win", "glyph": None}
def test_forty_characters_is_the_limit(self) -> None:
"""40 characters pass; 41 are refused."""
_set("cmd.done", word="x" * 40)
_refused("cmd.done", "invalid_params", word="x" * 41)
assert _stored()["cmd.done"]["word"] == "x" * 40
@pytest.mark.parametrize(
"word", ["", " ", "bad\x00word", "esc\x1b", "del\x7f", 5, ["a"]]
)
def test_bad_words_are_refused(self, word: object) -> None:
"""Empty, control characters and non-strings are invalid_params (400)."""
err = _refused("cmd.done", "invalid_params", word=word)
assert err.status == 400
assert not _icon_ledger.ledger_path().exists()
def test_skip_stores_null(self) -> None:
"""word: null means skipped (no label), and counts as answered."""
_set("cmd.done", word=None)
assert _stored()["cmd.done"] == {"word": None, "glyph": None}
class TestGlyphs:
"""POST /api/icon-words/<id> with a glyph."""
def test_alternative_is_saved_without_answering_the_word(self) -> None:
"""A glyph alone leaves the word unanswered (no word key)."""
_set("cmd.done", glyph="🎉")
assert _stored()["cmd.done"] == {"glyph": "🎉"}
def test_word_survives_a_later_glyph_choice(self) -> None:
"""Word and glyph are independent."""
_set("cmd.done", word="won")
_set("cmd.done", glyph="🏁")
assert _stored()["cmd.done"] == {"word": "won", "glyph": "🏁"}
@pytest.mark.parametrize("glyph", ["🏆", None])
def test_default_or_null_resets_to_default(self, glyph: object) -> None:
"""Choosing the default glyph is stored as null (keep default)."""
_set("cmd.done", glyph="🎉")
_set("cmd.done", glyph=glyph)
assert _stored()["cmd.done"] == {"glyph": None}
@pytest.mark.parametrize("glyph", ["🍕", "🏡", "", 3])
def test_unregistered_glyph_is_refused(self, glyph: object) -> None:
"""Only the default or this icon's own 3 alternatives are accepted."""
_refused("cmd.done", "invalid_params", glyph=glyph)
class TestRequestShape:
"""Unknown ids, empty and unknown bodies."""
def test_unknown_id_is_not_found(self) -> None:
"""An id the registry lacks is a 404."""
assert _refused("cmd.nope", "not_found", word="x").status == 404
def test_empty_body_is_refused(self) -> None:
"""Neither word nor glyph: nothing to save."""
_refused("cmd.done", "invalid_params")
def test_unknown_key_is_refused(self) -> None:
"""A typo'd key is never silently ignored."""
_refused("cmd.done", "invalid_params", word="x", colour="red")
def test_missing_registry_fails_loudly(self, registry: Path) -> None:
"""Without the registry no glyph or id can be checked: op_failed."""
registry.unlink()
assert _refused("cmd.done", "op_failed", word="x").status == 500
class TestCorruptLedger:
"""A corrupt ledger is kept aside, reads and writes fail loudly."""
def test_get_and_post_fail_and_the_file_is_untouched(self) -> None:
"""Nothing is overwritten while the ledger does not parse."""
path = _icon_ledger.ledger_path()
path.write_text("{broken", encoding="utf-8")
with pytest.raises(ApiError) as err:
_web_icon_words.icon_words_view(make_request())
assert (err.value.code, err.value.status) == ("op_failed", 500)
assert ".corrupt" in err.value.message
_refused("cmd.done", "op_failed", word="x")
assert path.read_text("utf-8") == "{broken"
assert path.with_name(path.name + ".corrupt").read_text("utf-8") == "{broken"
class TestGetAndInject:
"""GET /api/icon-words and the ledger carried by every served page."""
def test_get_returns_the_ledger(self) -> None:
"""GET serves the stored ledger, ids the registry lacks included."""
ledger = {"version": 1, "icons": {"old.id": {"word": "kept", "glyph": None}}}
_icon_ledger.save_ledger(_icon_ledger.ledger_path(), ledger)
assert payload_of(_web_icon_words.icon_words_view(make_request())) == ledger
def test_page_carries_the_ledger_with_script_breakouts_escaped(self) -> None:
"""Words are free text: '<' is escaped so a word cannot close the script."""
_set("cmd.done", word="</script><b>x")
html = _web_icon_words.inject_icon_words(
b"<html><head><title>t</title></head></html>"
)
text = html.decode("utf-8")
start = text.index(
f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
)
assert start < text.index("<title>")
body = text[start:].split(">", 1)[1].split("</script>", 1)[0]
assert "<" not in body
assert json.loads(body)["icons"]["cmd.done"]["word"] == "</script><b>x"
def test_page_carries_the_error_when_corrupt(self) -> None:
"""A corrupt ledger never breaks the page: it carries the error instead."""
_icon_ledger.ledger_path().write_text("{broken", encoding="utf-8")
html = _web_icon_words.inject_icon_words(b"<head></head>").decode("utf-8")
body = html.split('">', 1)[1].split("</script>", 1)[0]
assert json.loads(body)["error"] == "op_failed"
def test_page_without_head_gets_the_script_first(self) -> None:
"""A fragment without <head> still carries the ledger."""
html = _web_icon_words.inject_icon_words(b"<p>x</p>").decode("utf-8")
assert html.startswith(
f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
)
assert html.endswith("<p>x</p>")
class TestRoutes:
"""The route table knows both endpoints; ids may contain dots."""
def test_get_route(self) -> None:
"""GET /api/icon-words is the ledger view."""
assert _web_routes.resolve("GET", "/api/icon-words") == (
_web_icon_words.icon_words_view,
(),
)
@pytest.mark.parametrize("method", ["POST", "PUT"])
def test_set_route_captures_a_dotted_id(self, method: str) -> None:
"""POST and PUT /api/icon-words/job.state.waiting_input capture the id."""
found = _web_routes.resolve(method, "/api/icon-words/job.state.waiting_input")
assert found == (
_web_icon_words.set_icon_word_view,
("job.state.waiting_input",),
)
@pytest.mark.parametrize("path", ["/api/icon-words/a b", "/api/icon-words/../x"])
def test_malformed_ids_do_not_route(self, path: str) -> None:
"""Spaces or path tricks never reach the view."""
assert _web_routes.resolve("POST", path) is None

View File

@ -0,0 +1,161 @@
"""The icon-word endpoints over real HTTP: auth rules and the served page."""
from __future__ import annotations
from http.client import HTTPConnection
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger, _web_icon_words, _web_server
from steam_backlog_enforcer.tests._icon_registry import REGISTRY
from steam_backlog_enforcer.tests._web_process_state import (
clean_process_state,
running_server,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@pytest.fixture(autouse=True)
def _clean_process_state() -> Iterator[None]:
"""Never "stale": other edits to the tree must not leak in."""
yield from clean_process_state()
@pytest.fixture(name="server")
def fixture_server(tmp_path: Path) -> Iterator[_web_server.WebServer]:
"""A live server on an ephemeral port with a one-page bundle."""
dist = (tmp_path / "dist").resolve()
dist.mkdir()
(dist / "index.html").write_text("<html><head></head>X</html>", "utf-8")
registry = tmp_path / "registry.json"
registry.write_text(json.dumps(REGISTRY), "utf-8")
with (
patch.object(_web_server, "WEB_DIST", dist),
patch.object(_web_icon_words, "REGISTRY_FILE", registry),
running_server() as server,
):
yield server
def _call(
server: _web_server.WebServer,
method: str,
path: str,
body: object = None,
headers: dict[str, str] | None = None,
) -> tuple[int, dict[str, object] | str]:
host = f"127.0.0.1:{server.port}"
sent = {"Host": host, **(headers or {})}
data = None
if body is not None:
data = json.dumps(body).encode()
sent["Content-Type"] = "application/json"
conn = HTTPConnection("127.0.0.1", server.port, timeout=5)
try:
conn.request(method, path, body=data, headers=sent)
resp = conn.getresponse()
raw = resp.read().decode("utf-8")
ctype = resp.headers.get("Content-Type", "")
return resp.status, json.loads(raw) if "json" in ctype else raw
finally:
conn.close()
def _authed(server: _web_server.WebServer) -> dict[str, str]:
return {"Origin": f"http://127.0.0.1:{server.port}", "X-SBE-Token": server.token}
class TestAuth:
"""Writes follow the server's Host, Origin and token rules."""
@pytest.mark.parametrize(
("headers", "code"),
[
({}, "bad_origin"),
({"Origin": "http://evil.example"}, "bad_origin"),
({"Origin": "ORIGIN"}, "bad_token"),
],
)
def test_post_without_origin_or_token_is_refused(
self, server: _web_server.WebServer, headers: dict[str, str], code: str
) -> None:
"""No Origin, a foreign one, or no token: 403 and nothing written."""
sent = {
k: v.replace("ORIGIN", f"http://127.0.0.1:{server.port}")
for k, v in headers.items()
}
status, body = _call(
server, "POST", "/api/icon-words/cmd.done", {"word": "x"}, sent
)
assert status == 403
assert isinstance(body, dict)
assert body["error"] == code
assert not _icon_ledger.ledger_path().exists()
def test_foreign_host_is_refused_even_for_get(
self, server: _web_server.WebServer
) -> None:
"""The DNS-rebinding guard covers the ledger too."""
status, _ = _call(
server, "GET", "/api/icon-words", headers={"Host": "evil.example"}
)
assert status == 403
@pytest.mark.parametrize("method", ["POST", "PUT"])
def test_authed_write_saves_and_get_reads_it(
self, server: _web_server.WebServer, method: str
) -> None:
"""With Origin and token a write lands; a token-less GET reads it."""
status, body = _call(
server,
method,
"/api/icon-words/cmd.done",
{"word": "My win"},
_authed(server),
)
assert status == 200
assert isinstance(body, dict)
assert body["icons"] == {"cmd.done": {"word": "My win", "glyph": None}}
status, body = _call(server, "GET", "/api/icon-words")
assert (status, body) == (
200,
{"version": 1, "icons": {"cmd.done": {"word": "My win", "glyph": None}}},
)
def test_bad_word_is_a_400(self, server: _web_server.WebServer) -> None:
"""Validation errors are invalid_params over HTTP too."""
status, body = _call(
server,
"POST",
"/api/icon-words/cmd.done",
{"word": "x" * 41},
_authed(server),
)
assert status == 400
assert isinstance(body, dict)
assert body["error"] == "invalid_params"
class TestServedPage:
"""Every served page carries the current ledger: no rebuild needed."""
def test_a_pick_shows_on_the_next_page_load(
self, server: _web_server.WebServer
) -> None:
"""Save a word, reload the page: the injected ledger has it."""
_call(
server, "POST", "/api/icon-words/cmd.done", {"word": "Yay"}, _authed(server)
)
status, html = _call(server, "GET", "/")
assert status == 200
assert isinstance(html, str)
marker = f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
payload = html.split(marker, 1)[1].split("</script>", 1)[0]
assert json.loads(payload)["icons"]["cmd.done"]["word"] == "Yay"
assert f'content="{server.token}"' in html

View File

@ -234,3 +234,6 @@ export const TOKEN_META = 'sbe-token'
export const TOKEN_HEADER = 'X-SBE-Token' export const TOKEN_HEADER = 'X-SBE-Token'
export type { BudgetSnapshot, WebDataset } export type { BudgetSnapshot, WebDataset }
// Icon words (DOCS-icon-words.md): types in iconWordsContract.ts.
export * from './iconWordsContract'

View File

@ -0,0 +1,32 @@
// Icon words: the TS mirror of DOCS-icon-words.md.
// Split out of contract.ts like jobContract.ts; contract.ts re-exports it.
/** One icon's picks. No `word` key: not answered; `word: null`: skipped; `glyph: null`: default. */
export interface IconChoice {
word?: string | null
glyph?: string | null
}
/** `web/src/ui/icon_words.json`; an absent id is unanswered. */
export interface IconLedger {
version: 1
icons: Record<string, IconChoice>
}
/**
* `POST|PUT /api/icon-words/{id}` body: `word` (text, or null to skip) and/or
* `glyph` (one of the icon's 3 alternatives, or null / the default to reset).
* Answers the whole `IconLedger`.
*/
export type IconChoiceUpdate = { word: string | null } | { glyph: string | null } | { word: string | null; glyph: string | null }
/** Every served page carries the ledger in `<script type="application/json" id=…>`. */
export const ICON_WORDS_SCRIPT = 'sbe-icon-words'
/** A manual word: 1–40 characters after whitespace collapses, no control characters. */
export const ICON_WORD_MAX = 40
export const ICON_WORDS_ENDPOINTS = {
ledger: '/api/icon-words',
icon: (id: string) => `/api/icon-words/${id}`,
} as const

View File

@ -4,6 +4,8 @@
// the build. // the build.
import type { CommandName, CommandSpec, InstalledGame } from '../api/contract' import type { CommandName, CommandSpec, InstalledGame } from '../api/contract'
import type { IconId } from '../icons/registry'
import { iconFor } from '../icons/render'
export type SectionPath = export type SectionPath =
| '/' | '/'
@ -44,35 +46,25 @@ 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). */ /** A command's registered icon id (`cmd.<name>`); the compiler proves every command has one. */
export const COMMAND_ICON = { export function commandIcon(name: CommandName): IconId {
status: '📊', return `cmd.${name}` as const satisfies IconId
list: '📋', }
stats: '📈',
installed: '💾', /**
'gaming-status': '⏱️', * The glyph a command paints, for sites not yet on `glyph(commandIcon(…))`
check: '🔄', * (they get the chosen alternative glyph, not the word). Live getters, so a
scan: '🔎', * ledger change shows without re-importing.
done: '🏆', */
pick: '🎲', export const COMMAND_ICON: Readonly<Record<CommandName, string>> = Object.defineProperties(
'pick-manual': '📌', {},
'abandon-pick': '❌', Object.fromEntries(
install: '⬇️', (Object.keys(COMMAND_HOME) as CommandName[]).map((name) => [
uninstall: '🗑️', name,
hide: '🙈', { enumerable: true, get: () => iconFor(commandIcon(name)).glyph },
unhide: '👁️', ]),
'buy-dlc': '💳', ),
unblock: '🔓', ) as Record<CommandName, string>
'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 {

View File

@ -6,10 +6,11 @@
import type { CommandName } from '../api/contract' import type { CommandName } from '../api/contract'
import { q } from '../api/queries' import { q } from '../api/queries'
import { iconMark, iconWord } from '../icons/render'
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 { COMMAND_HOME, commandIcon, commandLabel, findCommand } from './catalog'
export interface ButtonProps { export interface ButtonProps {
name: CommandName name: CommandName
@ -35,7 +36,7 @@ export function commandButton({ name, preset, label, tone = 'ghost' }: ButtonPro
const locked = spec?.locked_reason ?? null const locked = spec?.locked_reason ?? null
// Textgate: the glyph is painted, the label is spoken only. // Textgate: the glyph is painted, the label is spoken only.
const spoken = label ?? (spec?.kind === 'job' ? `Run ${name}` : `Open ${commandLabel(name)}`) const spoken = label ?? (spec?.kind === 'job' ? `Run ${name}` : `Open ${commandLabel(name)}`)
const glyph = h('span', { class: 'cmd-icon', 'aria-hidden': 'true' }, COMMAND_ICON[name]) const glyph = [iconMark(commandIcon(name), 'cmd-icon'), iconWord(commandIcon(name))]
if (spec && spec.kind !== 'job') { if (spec && spec.kind !== 'job') {
return h('a', { href: pageHref(COMMAND_HOME[name]), class: `btn btn-${tone}`, 'aria-label': spoken }, glyph) return h('a', { href: pageHref(COMMAND_HOME[name]), class: `btn btn-${tone}`, 'aria-label': spoken }, glyph)
} }

View File

@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NAV } from '../shell/nav' import { NAV, PALETTE_PAGES } from '../shell/nav'
import { runner, type RunRequest } from '../lib/runner' import { runner, type RunRequest } from '../lib/runner'
import { must, setValue } from '../test/events' import { must, setValue } from '../test/events'
import { makeSpec } from '../test/fixtures' import { makeSpec } from '../test/fixtures'
@ -12,7 +12,8 @@ const SPECS = [
makeSpec('status', { kind: 'view', description: 'Show status.' }), makeSpec('status', { kind: 'view', description: 'Show status.' }),
makeSpec('pick', { description: 'Pick next.', locked_reason: 'Locked by a pick' }), makeSpec('pick', { description: 'Pick next.', locked_reason: 'Locked by a pick' }),
] ]
const TOTAL = SPECS.length + NAV.length const PAGES = NAV.length + PALETTE_PAGES.length
const TOTAL = SPECS.length + PAGES
const assign = vi.fn() const assign = vi.fn()
const runs: RunRequest[] = [] const runs: RunRequest[] = []
@ -111,7 +112,7 @@ describe('CommandPaletteElement', () => {
expect(document.body).toHaveTextContent('catalog broken') expect(document.body).toHaveTextContent('catalog broken')
}) })
expect(document.body).not.toHaveTextContent('Loading commands') expect(document.body).not.toHaveTextContent('Loading commands')
expect(options()).toHaveLength(NAV.length) expect(options()).toHaveLength(PAGES)
}) })
it('filters by text and says when nothing matches', async () => { it('filters by text and says when nothing matches', async () => {

View File

@ -7,17 +7,17 @@ import { q } from '../api/queries'
import { define, h } from '../lib/dom' 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, PALETTE_PAGES } from '../shell/nav'
import { empty, errorNotice, glyph, loading, pill } from '../ui/build' import { empty, errorNotice, glyph, 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, commandIcon, 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). */ /** A registered icon id (painted with the user's word) or a raw glyph. */
icon: string icon: string
/** Painted in place of the hint: ▶️ run, ↗️ open, 🧭 navigate. */ /** Painted in place of the hint: ▶️ run, ↗️ open, 🧭 navigate. */
hintIcon: string hintIcon: string
@ -117,7 +117,7 @@ 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], icon: commandIcon(c.name),
hintIcon: c.kind === 'job' ? (c.friction ? '▶️⌨️' : '▶️') : '↗️', hintIcon: c.kind === 'job' ? (c.friction ? '▶️⌨️' : '▶️') : '↗️',
locked: c.locked_reason, locked: c.locked_reason,
act: () => { act: () => {
@ -128,7 +128,7 @@ export class CommandPaletteElement extends HTMLElement {
} }
}, },
})), })),
...NAV.map((n) => ({ ...[...NAV, ...PALETTE_PAGES].map((n) => ({
key: `nav:${n.to}`, key: `nav:${n.to}`,
title: `Go to ${n.label}`, title: `Go to ${n.label}`,
detail: n.blurb, detail: n.blurb,

View File

@ -5,11 +5,12 @@
import { api } from '../api/client' import { api } from '../api/client'
import { q } from '../api/queries' import { q } from '../api/queries'
import { iconMark, iconWord } from '../icons/render'
import { define, h, hx } from '../lib/dom' 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 { commandIcon, 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'
@ -96,7 +97,7 @@ export class RunnerDialogElement extends HTMLElement {
if (error) this.modal.render(errorNotice(error)) if (error) this.modal.render(errorNotice(error))
else if (commands) { else if (commands) {
// ⛔ + the command's glyph; the sentence is spoken only. // ⛔ + the command's glyph; the sentence is spoken only.
const el = notice('danger', null, h('span', { 'aria-hidden': 'true' }, COMMAND_ICON[req.name])) const el = notice('danger', null, h('span', { class: 'has-word' }, iconMark(commandIcon(req.name), ''), iconWord(commandIcon(req.name))))
el.setAttribute('aria-label', `Not in the server catalog: the server does not offer "${req.name}".`) el.setAttribute('aria-label', `Not in the server catalog: the server does not offer "${req.name}".`)
this.modal.render(el) this.modal.render(el)
} }

View File

@ -5,11 +5,12 @@
import { ApiFailure, startJob } from '../api/client' import { ApiFailure, startJob } from '../api/client'
import type { CommandName, CommandSpec } from '../api/contract' import type { CommandName, CommandSpec } from '../api/contract'
import { q } from '../api/queries' import { q } from '../api/queries'
import { iconMark, iconWord } from '../icons/render'
import { Action } from '../lib/action' 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 { commandIcon, 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'
@ -98,7 +99,7 @@ export class Runner {
h( h(
'div', 'div',
{ class: 'tags' }, { class: 'tags' },
h('span', { class: 'runner-glyph', 'aria-hidden': 'true' }, COMMAND_ICON[spec.name]), h('span', { class: 'runner-mark' }, iconMark(commandIcon(spec.name), 'runner-glyph'), iconWord(commandIcon(spec.name))),
spec.privileged ? pill('neutral', 'Runs as root via the daemon', '🔑') : null, spec.privileged ? pill('neutral', 'Runs as root via the daemon', '🔑') : null,
spec.mutating ? pill('neutral', 'Changes state', '✏️') : pill('neutral', 'Read-only', '👁️'), spec.mutating ? pill('neutral', 'Changes state', '✏️') : pill('neutral', 'Read-only', '👁️'),
spec.cancellable ? pill('neutral', 'Cancellable', '⏹️') : null, spec.cancellable ? pill('neutral', 'Cancellable', '⏹️') : null,

View File

@ -0,0 +1,61 @@
import { describe, expect, it, vi } from 'vitest'
import { injectLedgerScript, useIcons } from '../test/iconLedger'
import { choiceOf, isAnswered, ledger, ledgerError, setWordsHidden, wordsHidden, WORDS_HIDDEN_KEY } from './ledger'
describe('ledger', () => {
it('is empty when the page carries none (dev server, tests)', () => {
expect(ledger()).toEqual({ version: 1, icons: {} })
expect(isAnswered('cmd.done')).toBe(false)
expect(ledgerError()).toBeNull()
})
it('reads the payload the server injected into the page, once', () => {
injectLedgerScript({ version: 1, icons: { 'cmd.done': { word: 'Won', glyph: '🎉' } } })
expect(choiceOf('cmd.done')).toEqual({ word: 'Won', glyph: '🎉' })
document.getElementById('sbe-icon-words')?.remove()
expect(choiceOf('cmd.done').word).toBe('Won')
})
it('counts an id as answered only once its word is decided (text or skip)', () => {
useIcons({ 'cmd.done': { word: null, glyph: null }, 'cmd.scan': { glyph: '📡' }, 'cmd.pick': { word: 'roll' } })
expect(isAnswered('cmd.done')).toBe(true)
expect(isAnswered('cmd.pick')).toBe(true)
expect(isAnswered('cmd.scan')).toBe(false)
expect(isAnswered('cmd.check')).toBe(false)
expect(choiceOf('cmd.check')).toEqual({})
})
it('fails loudly on a corrupt ledger the server reported', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => undefined)
injectLedgerScript({ error: 'op_failed', message: 'kept aside as x.corrupt' })
expect(ledger().icons).toEqual({})
expect(ledgerError()).toBe('kept aside as x.corrupt')
expect(err).toHaveBeenCalledWith(expect.stringContaining('x.corrupt'))
})
it('names the failure even when the error body has no message', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
injectLedgerScript({ error: 'op_failed' })
expect(ledgerError()).toBe('The icon-word ledger is unreadable.')
})
it('fails loudly on a payload that does not parse', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => undefined)
injectLedgerScript('{nope')
expect(ledger().icons).toEqual({})
expect(ledgerError()).toMatch(/does not parse/)
expect(err).toHaveBeenCalled()
})
})
describe('words-hidden setting', () => {
it('defaults to words shown and persists in localStorage', () => {
expect(wordsHidden()).toBe(false)
setWordsHidden(true)
expect(wordsHidden()).toBe(true)
expect(localStorage.getItem(WORDS_HIDDEN_KEY)).toBe('1')
setWordsHidden(false)
expect(wordsHidden()).toBe(false)
expect(localStorage.getItem(WORDS_HIDDEN_KEY)).toBeNull()
})
})

72
web/src/icons/ledger.ts Normal file
View File

@ -0,0 +1,72 @@
// The icon-word ledger as this page knows it. The Python server injects it
// into every page (`<script type="application/json" id="sbe-icon-words">`),
// so it is read synchronously on first use and every renderer sees the same
// picks; the /words picker replaces it after each save. A corrupt ledger
// arrives as the server's error body: no words are drawn and the error is
// logged (and shown on /words), never swallowed.
import { ICON_WORDS_SCRIPT, type IconChoice, type IconLedger } from '../api/iconWordsContract'
/** localStorage key of the one "hide all words" setting; absent = words shown. */
export const WORDS_HIDDEN_KEY = 'sbe-icon-words-hidden'
const EMPTY: IconLedger = { version: 1, icons: {} }
let cached: IconLedger | null = null
let failure: string | null = null
function readPage(): IconLedger {
const raw = document.getElementById(ICON_WORDS_SCRIPT)?.textContent
if (raw === undefined) return EMPTY
let parsed: Partial<IconLedger> & { message?: string }
try {
parsed = JSON.parse(raw) as typeof parsed
} catch (e) {
parsed = { message: `The icon-word ledger in this page does not parse: ${String(e)}` }
}
if (parsed.icons) return parsed as IconLedger
failure = parsed.message ?? 'The icon-word ledger is unreadable.'
console.error(`[sbe] icon words off: ${failure}`)
return EMPTY
}
export function ledger(): IconLedger {
cached ??= readPage()
return cached
}
/** Use `next` from now on (the picker, after the server answered a save). */
export function setLedger(next: IconLedger): void {
cached = next
failure = null
}
/** Forget the cached ledger so the next read re-reads the page (tests). */
export function resetLedger(): void {
cached = null
failure = null
}
/** The server's message when the page carried a corrupt ledger, else null. */
export function ledgerError(): string | null {
ledger()
return failure
}
export function choiceOf(id: string): IconChoice {
return ledger().icons[id] ?? {}
}
/** Answered = the word is decided (text or a skip); a glyph alone is not enough. */
export function isAnswered(id: string): boolean {
return 'word' in choiceOf(id)
}
export function wordsHidden(): boolean {
return localStorage.getItem(WORDS_HIDDEN_KEY) === '1'
}
export function setWordsHidden(hidden: boolean): void {
if (hidden) localStorage.setItem(WORDS_HIDDEN_KEY, '1')
else localStorage.removeItem(WORDS_HIDDEN_KEY)
}

View File

@ -0,0 +1,109 @@
import { describe, expect, it, vi } from 'vitest'
import { must } from '../test/events'
import { apiError, bodiesOf, stubApi } from '../test/harness'
import { A, B, C, N, at, count, field, input, press, q, start, url } from '../test/pickerHelpers'
import { wordsHidden } from './ledger'
import { ICONS } from './registry'
describe('<icon-words-picker>: moving, summary, errors', () => {
it('←/→ move; a revisit shows the saved choice', async () => {
start({ [A.id]: { word: A.words[2] ?? '', glyph: null }, [B.id]: { word: 'Mine all mine' }, [C.id]: { word: null } })
await at(4)
press('ArrowLeft')
await at(3)
expect(q('[data-skip]')).toHaveAttribute('aria-pressed', 'true')
press('ArrowLeft')
await at(2)
expect(field().value).toBe('Mine all mine')
press('ArrowLeft')
await at(1)
expect(q('[data-word-slot="2"]')).toHaveAttribute('aria-pressed', 'true')
expect(field().value).toBe('')
press('ArrowLeft')
await at(1)
press('ArrowRight')
await at(2)
})
it('a failed glyph save keeps the field empty and reports the error', async () => {
start()
await at(3)
stubApi({ [url(C.id)]: apiError(500, 'op_failed', 'disk full') })
press('7')
await vi.waitFor(() => { expect(q('.picker-status .notice-danger')).toHaveTextContent('disk full') })
expect(field().value).toBe('')
expect(field()).toHaveAttribute('aria-invalid', 'false')
})
it('refuses a bad own word before sending and flags the field', async () => {
const { mock } = start()
await at(3)
field().value = 'x'.repeat(41)
must(field().form).requestSubmit()
expect(field()).toHaveAttribute('aria-invalid', 'true')
expect(bodiesOf(mock, url(C.id))).toEqual([])
})
it('shows a server refusal and stays on the icon', async () => {
start()
await at(3)
stubApi({ 'GET /api/icon-words': { version: 1, icons: {} }, [url(C.id)]: apiError(400, 'invalid_params', 'no') })
field().value = 'fine'
must(field().form).requestSubmit()
await vi.waitFor(() => { expect(field()).toHaveAttribute('aria-invalid', 'true') })
expect(q('.picker-status .notice-danger')).toHaveTextContent('no')
expect(count()).toBe(`3 / ${N}`)
})
it('ends on a summary that jumps back to the first unanswered icon', async () => {
const all = Object.fromEntries(ICONS.slice(0, -1).map((e) => [e.id, { word: null }]))
start(all)
await at(N)
press('s')
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`${String(N)} / ${String(N)}`) })
expect(document.querySelector('[data-jump]')).toBeNull()
for (const k of ['1', '7', '6', 's']) press(k)
await Promise.resolve()
expect(document.querySelector('.picker-count')).toBeNull()
press('ArrowLeft')
await at(N)
})
it('opens on the summary when every icon is answered', async () => {
start(Object.fromEntries(ICONS.map((e) => [e.id, { word: 'x' }])))
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`${String(N)} / ${String(N)}`) })
expect(q('[data-go="1"]')).toBeDisabled()
})
it('offers the jump when icons are left unanswered', async () => {
start()
await at(3)
press('ArrowRight')
for (let i = 4; i <= N; i++) {
await at(i)
press('ArrowRight')
}
await vi.waitFor(() => { expect(q('.picker-summary')).toHaveTextContent(`2 / ${String(N)}`) })
q('[data-jump]').click()
await at(3)
})
it('the show-words switch flips the one setting', async () => {
start()
await at(3)
const box = () => input('input[name=show-words]')
expect(box().checked).toBe(true)
box().click()
expect(wordsHidden()).toBe(true)
expect(box().checked).toBe(false)
box().click()
expect(wordsHidden()).toBe(false)
})
it('shows the error when the ledger cannot be read', async () => {
stubApi({ 'GET /api/icon-words': apiError(500, 'op_failed', 'kept aside as x.corrupt') })
document.body.innerHTML = '<icon-words-picker></icon-words-picker>'
await vi.waitFor(() => { expect(q('.picker-status .notice-danger')).toHaveTextContent('x.corrupt') })
expect(document.querySelector('.picker-count')).toBeNull()
})
})

View File

@ -0,0 +1,130 @@
import { describe, expect, it, vi } from 'vitest'
import { must } from '../test/events'
import { bodiesOf } from '../test/harness'
import { C, D, N, at, count, field, input, press, q, start, url } from '../test/pickerHelpers'
describe('<icon-words-picker>: keys and saves', () => {
it('starts at the first unanswered icon with its glyph, context, description and progress', async () => {
start()
await at(3)
expect(q('.picker-id')).toHaveTextContent(C.id)
expect(q('.picker-big')).toHaveTextContent(C.glyph)
expect(q('.picker-context').textContent).toContain(C.glyph)
expect(q('.picker-desc')).toHaveTextContent(C.desc)
expect(q('[role=progressbar]')).toHaveAttribute('aria-valuenow', String(Math.round((2 / N) * 100)))
const words = [...document.querySelectorAll('[data-word-slot]')].map((b) => b.textContent)
expect(words).toEqual(C.words.map((w, i) => `${String(i + 1)}${w}`))
})
it('1/2/3 save a suggestion and advance', async () => {
const { mock } = start()
await at(3)
press('2')
await at(4)
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: C.words[1] }])
expect(q('[role=progressbar]')).toHaveAttribute('aria-valuenow', String(Math.round((3 / N) * 100)))
})
it('O focuses the own-word field; Enter saves a multi-word entry and advances', async () => {
const { mock } = start()
await at(3)
expect(press('o')).toBe(false)
expect(document.activeElement).toBe(field())
field().value = ' My OWN words '
press('s', {}, field())
must(field().form).requestSubmit()
await at(4)
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: 'My OWN words' }])
})
it('S skips (word null) and advances', async () => {
const { mock } = start()
await at(3)
press('S')
await at(4)
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: null }])
})
it('7/8/9 swap the glyph and stay; 6 keeps the default', async () => {
const { mock } = start()
await at(3)
press('8')
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[1] ?? '') })
expect(count()).toBe(`3 / ${N}`)
expect(q('[data-glyph-slot="1"]')).toHaveAttribute('aria-pressed', 'true')
press('6')
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.glyph) })
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[1] }, { glyph: null }])
expect(q('[data-glyph-slot="default"]')).toHaveAttribute('aria-pressed', 'true')
})
it('ignores keys while typing and keys with modifiers (Alt+digit is the nav)', async () => {
const { mock } = start()
await at(3)
press('1', { altKey: true })
press('2', { ctrlKey: true })
press('3', { metaKey: true })
press('s', {}, field())
await Promise.resolve()
expect(bodiesOf(mock, url(C.id))).toEqual([])
expect(count()).toBe(`3 / ${N}`)
})
it('3, 9, upper-case O and the keep-default button reach their slots', async () => {
const { mock } = start()
await at(3)
press('9')
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[2] ?? '') })
q('[data-glyph-slot="default"]').click()
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.glyph) })
press('O')
expect(document.activeElement).toBe(field())
field().blur()
press('3')
await at(4)
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[2] }, { glyph: null }, { word: C.words[2] }])
})
it('ignores unknown keys, keys before the ledger loads and keys under an open dialog', async () => {
const { mock } = start()
press('1')
await at(3)
press('x')
document.body.append(Object.assign(document.createElement('dialog'), { open: true }))
press('S')
await Promise.resolve()
expect(bodiesOf(mock, url(C.id))).toEqual([])
expect(count()).toBe(`3 / ${N}`)
})
it('keys still work while the show-words checkbox has focus; Esc leaves the field', async () => {
const { mock } = start()
await at(3)
const box = input('input[name=show-words]')
box.focus()
press('S', {}, box)
await at(4)
expect(bodiesOf(mock, url(C.id))).toEqual([{ word: null }])
press('o')
expect(document.activeElement).toBe(field())
press('Escape', {}, field())
expect(document.activeElement).not.toBe(field())
})
it('clicks work like keys', async () => {
const { mock } = start()
await at(3)
q('[data-glyph-slot="0"]').click()
await vi.waitFor(() => { expect(q('.picker-big')).toHaveTextContent(C.alts[0] ?? '') })
q('[data-word-slot="0"]').click()
await at(4)
q('[data-skip]').click()
await at(5)
q('[data-go="-1"]').click()
await at(4)
q('[data-go="1"]').click()
await at(5)
expect(bodiesOf(mock, url(C.id))).toEqual([{ glyph: C.alts[0] }, { word: C.words[0] }])
expect(bodiesOf(mock, url(D.id))).toEqual([{ word: null }])
})
})

172
web/src/icons/picker.ts Normal file
View File

@ -0,0 +1,172 @@
// `<icon-words-picker>` on /words, after cleanup-plate's icon-word picker:
// one icon at a time, big and as it looks in place, with what it is and does,
// three suggested words, a field for your own words, a skip, and three
// alternative glyphs. Every choice is saved at once (POST /api/icon-words/…);
// a word or a skip advances, a glyph swap stays so you see it. It opens on the
// first unanswered icon; going back shows what you saved.
// Keys: 1 2 3 pick, O own word (Enter saves, Esc leaves the field), S skip,
// 6 default glyph, 7 8 9 alternatives, ←/→ move. Keys never fire while you
// type, with Alt/Ctrl/Meta held (Alt+digit is the section nav) or under a
// dialog (the command palette).
import { request } from '../api/client'
import { ICON_WORDS_ENDPOINTS, type IconChoiceUpdate, type IconLedger } from '../api/iconWordsContract'
import { define } from '../lib/dom'
import { loading } from '../ui/build'
import { isAnswered, setLedger, setWordsHidden, wordsHidden } from './ledger'
import { pickerStatus, pickerView, type PickerHandlers } from './pickerView'
import { ICONS } from './registry'
import { decorateChrome } from './render'
import { normalizeWord, wordProblem } from './wordRules'
function firstUnanswered(): number {
const i = ICONS.findIndex((e) => !isAnswered(e.id))
return i === -1 ? ICONS.length : i
}
/** A text field has the keys while focused; a checkbox does not. */
function typing(target: EventTarget | null): boolean {
return target instanceof HTMLInputElement && target.type !== 'checkbox'
}
export class IconWordsPickerElement extends HTMLElement {
private index = 0
private loaded = false
private error: unknown = null
private invalid = false
private draft: string | null = null
private readonly onKey = (e: KeyboardEvent): void => {
this.key(e)
}
private readonly handlers: PickerHandlers = {
word: (slot) => { this.pick(slot) },
own: (text) => { this.own(text) },
skip: () => { void this.commit({ word: null }, true) },
glyph: (slot) => { this.glyph(slot) },
go: (to) => { this.go(to) },
jump: () => { this.go(firstUnanswered()) },
showWords: (on) => {
setWordsHidden(!on)
decorateChrome()
this.render()
},
}
private readonly keys = new Map<string, () => void>([
['1', () => { this.pick(0) }],
['2', () => { this.pick(1) }],
['3', () => { this.pick(2) }],
['6', () => { this.glyph(null) }],
['7', () => { this.glyph(0) }],
['8', () => { this.glyph(1) }],
['9', () => { this.glyph(2) }],
['o', () => { this.focusOwn() }],
['O', () => { this.focusOwn() }],
['s', this.handlers.skip],
['S', this.handlers.skip],
['ArrowLeft', () => { this.go(this.index - 1) }],
['ArrowRight', () => { this.go(this.index + 1) }],
])
connectedCallback(): void {
document.addEventListener('keydown', this.onKey)
this.replaceChildren(loading('icon words'))
request<IconLedger>('GET', ICON_WORDS_ENDPOINTS.ledger).then(
(ledger) => {
setLedger(ledger)
this.loaded = true
this.go(firstUnanswered())
},
(e: unknown) => {
this.replaceChildren(pickerStatus(e))
},
)
}
disconnectedCallback(): void {
document.removeEventListener('keydown', this.onKey)
}
/** The shown icon; undefined on the summary page after the last one. */
private get entry() {
return ICONS.at(this.index)
}
private go(to: number): void {
this.index = Math.min(Math.max(0, to), ICONS.length)
this.error = null
this.invalid = false
this.draft = null
this.render()
}
private focusOwn(): void {
this.querySelector<HTMLInputElement>('input[name=own]')?.focus()
}
private pick(slot: number): void {
const word = this.entry?.words[slot]
if (word !== undefined) void this.commit({ word }, true)
}
private glyph(slot: number | null): void {
const entry = this.entry
if (!entry) return
void this.commit({ glyph: slot === null ? null : entry.alts[slot] }, false)
}
private own(text: string): void {
if (wordProblem(text)) {
this.draft = text
this.invalid = true
this.render()
return
}
void this.commit({ word: normalizeWord(text) }, true)
}
private async commit(update: IconChoiceUpdate, advance: boolean): Promise<void> {
const entry = this.entry
if (!entry) return
try {
setLedger(await request<IconLedger>('POST', ICON_WORDS_ENDPOINTS.icon(entry.id), update))
decorateChrome()
this.go(advance ? this.index + 1 : this.index)
} catch (e) {
const word = (update as { word?: unknown }).word
this.error = e
this.invalid = (e as { code?: string }).code === 'invalid_params'
this.draft = typeof word === 'string' ? word : null
this.render()
}
}
private key(e: KeyboardEvent): void {
const act = this.keys.get(e.key)
if (!act || !this.loaded || e.altKey || e.ctrlKey || e.metaKey || typing(e.target)) return
if (document.querySelector('dialog[open]')) return
e.preventDefault()
act()
}
private render(): void {
this.replaceChildren(
...pickerView(
{
index: this.index,
total: ICONS.length,
answered: ICONS.filter((e) => isAnswered(e.id)).length,
entry: this.entry ?? null,
error: this.error,
invalid: this.invalid,
draft: this.draft,
wordsShown: !wordsHidden(),
},
this.handlers,
),
)
}
}
define('icon-words-picker', IconWordsPickerElement)

128
web/src/icons/pickerView.ts Normal file
View File

@ -0,0 +1,128 @@
// The widgets of the icon-word picker (picker.ts holds the state and keys).
// A developer page the user asked to carry text: the description, the
// suggestions and the key hints are meant to be read.
import { progressBar } from '../jobs/progress'
import { h, type Child } from '../lib/dom'
import { errorNotice } from '../ui/build'
import { choiceOf } from './ledger'
import { contextPreview } from './preview'
import type { IconEntry } from './registry'
import { iconFor } from './render'
import { sentenceCase } from './textCase'
export interface PickerHandlers {
word: (slot: number) => void
own: (text: string) => void
skip: () => void
/** null keeps the default glyph. */
glyph: (slot: number | null) => void
go: (to: number) => void
jump: () => void
showWords: (on: boolean) => void
}
export interface PickerState {
index: number
total: number
answered: number
entry: IconEntry | null
error: unknown
invalid: boolean
/** The own-word text to keep in the field (a refused entry). */
draft: string | null
wordsShown: boolean
}
const keyed = (key: string, ...label: Child[]) => [h('kbd', {}, key), ...label]
function choiceButton(attrs: Record<string, string>, pressed: boolean, onclick: () => void, ...label: Child[]) {
return h('button', { type: 'button', class: 'btn btn-ghost picker-choice', 'aria-pressed': String(pressed), onclick, ...attrs }, ...label)
}
function ownForm(s: PickerState, entry: IconEntry, on: PickerHandlers, saved: string | null | undefined): HTMLFormElement {
const own = typeof saved === 'string' && !entry.words.includes(saved) ? saved : ''
const input = h('input', { class: 'input', name: 'own', autocomplete: 'off', 'aria-invalid': String(s.invalid), value: s.draft ?? own })
const form = h(
'form',
{ class: 'picker-own' },
h('label', { class: 'picker-own-label' }, h('span', {}, ...keyed('O', ' Own word')), input),
h('button', { type: 'submit', class: 'btn btn-primary' }, '✓ ', h('kbd', {}, '⏎')),
)
form.addEventListener('submit', (e) => {
e.preventDefault()
on.own(input.value)
})
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') input.blur()
})
return form
}
function choices(s: PickerState, entry: IconEntry, on: PickerHandlers): HTMLElement {
const saved = choiceOf(entry.id)
const glyph = saved.glyph && entry.alts.includes(saved.glyph) ? saved.glyph : null
return h(
'div',
{ class: 'picker-choices stack' },
h('p', { class: 'picker-desc m0' }, entry.desc),
h(
'div',
{ class: 'picker-words' },
entry.words.map((w, i) => choiceButton({ 'data-word-slot': String(i) }, saved.word === w, () => { on.word(i) }, ...keyed(String(i + 1), w))),
),
ownForm(s, entry, on, saved.word),
choiceButton({ 'data-skip': '' }, saved.word === null, on.skip, ...keyed('S', ' Skip (no word)')),
h(
'div',
{ class: 'picker-glyphs', role: 'group', 'aria-label': 'Glyph' },
choiceButton({ 'data-glyph-slot': 'default' }, glyph === null, () => { on.glyph(null) }, ...keyed('6', ` ${entry.glyph} keep default`)),
entry.alts.map((a, i) => choiceButton({ 'data-glyph-slot': String(i) }, glyph === a, () => { on.glyph(i) }, ...keyed(String(i + 7), ` ${a}`))),
),
)
}
function header(s: PickerState, entry: IconEntry): HTMLElement {
const word = choiceOf(entry.id).word
const saved = typeof word === 'string' ? sentenceCase(word) : word === null ? '— skipped' : ''
return h(
'div',
{ class: 'picker-head' },
h('span', { class: 'picker-count' }, `${String(s.index + 1)} / ${String(s.total)}`),
h('code', { class: 'picker-id' }, entry.id),
h('span', { class: 'picker-saved' }, saved),
)
}
function footer(s: PickerState, on: PickerHandlers): HTMLElement {
return h(
'div',
{ class: 'picker-nav' },
h('button', { type: 'button', class: 'btn btn-ghost', 'data-go': '-1', disabled: s.index === 0, onclick: () => { on.go(s.index - 1) } }, '← back'),
h('label', { class: 'picker-toggle' }, h('input', { type: 'checkbox', name: 'show-words', checked: s.wordsShown, onchange: (e: Event) => { on.showWords((e.target as HTMLInputElement).checked) } }), ' Show words next to icons'),
h('button', { type: 'button', class: 'btn btn-ghost', 'data-go': '1', disabled: s.entry === null, onclick: () => { on.go(s.index + 1) } }, 'forward →'),
)
}
function done(s: PickerState, on: PickerHandlers): HTMLElement {
return h(
'div',
{ class: 'picker-done stack' },
h('p', { class: 'picker-summary m0' }, `${String(s.answered)} / ${String(s.total)}`),
s.answered < s.total ? h('button', { type: 'button', class: 'btn btn-primary', 'data-jump': '', onclick: on.jump }, 'Next unanswered') : h('p', { class: 'm0' }, '✅'),
)
}
/** The error slot (also all there is when the ledger could not be read). */
export function pickerStatus(error: unknown): HTMLElement {
return h('div', { class: 'picker-status' }, error ? errorNotice(error) : null)
}
/** Everything the loaded picker shows for `s`. */
export function pickerView(s: PickerState, on: PickerHandlers): HTMLElement[] {
const status = pickerStatus(s.error)
const bar = progressBar(s.answered / s.total, 'Answered')
if (!s.entry) return [bar, status, done(s, on), footer(s, on)]
const stage = h('div', { class: 'picker-stage' }, h('div', { class: 'picker-big', 'aria-hidden': 'true' }, iconFor(s.entry.id).glyph), contextPreview(s.entry.id))
return [header(s, s.entry), bar, status, h('div', { class: 'picker-body' }, stage, choices(s, s.entry, on)), footer(s, on)]
}

View File

@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { useIcons } from '../test/iconLedger'
import { contextPreview } from './preview'
import type { IconId } from './registry'
describe('contextPreview: the icon as it looks where it is used', () => {
it.each<[IconId, string, string]>([
['nav.gaming', '.nav-link', '🕹️'],
['palette.open', '.palette-btn', '⌨️'],
['cmd.install', '.btn', '📥'],
['job.state.failed', '.pill', '💔'],
['notice.info', '.notice', '💡'],
])('%s renders inside %s with the chosen glyph and word', (id, shell, alt) => {
useIcons({ [id]: { word: 'shown here', glyph: alt } })
const el = contextPreview(id)
expect(el).toHaveAttribute('inert')
const host = el.querySelector(shell)
expect(host).not.toBeNull()
expect(host?.textContent).toContain(alt)
expect(host?.querySelector('.icon-word')?.textContent).toBe('Shown here')
})
it('shows the default glyph and no word before any choice', () => {
const el = contextPreview('cmd.install')
expect(el.textContent).toContain('⬇️')
expect(el.querySelector('.icon-word')).toBeNull()
})
})

40
web/src/icons/preview.ts Normal file
View File

@ -0,0 +1,40 @@
// The icon as it looks where the UI paints it, for the /words picker: inert
// replicas built from the same pieces as the real call sites (no handlers),
// showing the current glyph and word.
import type { JobState } from '../api/jobContract'
import { stateBadge } from '../jobs/progress'
import { h } from '../lib/dom'
import { NAV } from '../shell/nav'
import { notice, type Tone } from '../ui/build'
import type { IconId } from './registry'
import { iconMark, iconWord } from './render'
function inContext(id: IconId): HTMLElement {
const [group = '', ...rest] = id.split('.')
const tail = rest.join('.')
const word = iconWord(id)
const paired = word ? ' has-word' : ''
switch (group) {
case 'nav':
return h(
'span',
{ class: `nav-link active${paired}` },
iconMark(id, 'nav-icon'),
word,
NAV.filter((n) => n.icon === id).map((n) => h('kbd', {}, n.key)),
)
case 'palette':
return h('span', { class: 'btn btn-ghost palette-btn' }, iconMark(id, ''), word, h('kbd', {}, '⌃K'))
case 'job':
return stateBadge(tail.replace(/^state\./, '') as JobState)
case 'notice':
return notice(tail as Tone, null)
default:
return h('span', { class: 'btn btn-ghost' }, iconMark(id, 'cmd-icon'), word)
}
}
export function contextPreview(id: IconId): HTMLDivElement {
return h('div', { class: 'picker-context', inert: true }, inContext(id))
}

View File

@ -0,0 +1,50 @@
{
"version": 1,
"icons": {
"nav.dashboard": { "glyph": "🏠", "spoken": "Dashboard", "desc": "Sidebar link to the dashboard (Alt+1). It opens the start page with the assigned game, today's gaming budget and the quick actions.", "words": ["home", "dashboard", "overview"], "alts": ["🏡", "🧭", "📟"] },
"nav.backlog": { "glyph": "📚", "spoken": "Backlog", "desc": "Sidebar link to the backlog page (Alt+2). It opens the planner, the completion-time stats and the full game list.", "words": ["backlog", "planner", "queue"], "alts": ["📖", "🗃️", "📜"] },
"nav.picks": { "glyph": "🎯", "spoken": "Picks", "desc": "Sidebar link to the picks page (Alt+3). It opens check, done, pick and scan, plus your manual picks.", "words": ["picks", "assignment", "target"], "alts": ["🏹", "📍", "🔭"] },
"nav.gaming": { "glyph": "🎮", "spoken": "Gaming", "desc": "Sidebar link to the gaming page (Alt+4). It opens the daily gaming budget with its reset, block and unblock actions.", "words": ["gaming", "budget", "playtime"], "alts": ["🕹️", "👾", "⌛"] },
"nav.library": { "glyph": "🗂️", "spoken": "Library", "desc": "Sidebar link to the library page (Alt+5). It opens every game you own, with install, uninstall and hide.", "words": ["library", "games", "collection"], "alts": ["📦", "🖼️", "💿"] },
"nav.store": { "glyph": "🛒", "spoken": "Store", "desc": "Sidebar link to the store page (Alt+6). It opens the timed store unblock, buying DLC and game exceptions.", "words": ["store", "shop", "purchases"], "alts": ["🏪", "🛍️", "💰"] },
"nav.jobs": { "glyph": "⚙️", "spoken": "Jobs", "desc": "Sidebar link to the jobs page (Alt+7). It lists the running and past jobs with their logs.", "words": ["jobs", "tasks", "activity"], "alts": ["🛠️", "🧰", "🏗️"] },
"nav.system": { "glyph": "🖥️", "spoken": "System", "desc": "Sidebar link to the system page (Alt+8). It opens the root daemon, the web server, state backups, reset and setup.", "words": ["system", "daemon", "admin"], "alts": ["💻", "🔩", "📡"] },
"palette.open": { "glyph": "🔍", "spoken": "Commands", "desc": "Top-bar button (Ctrl+K) that opens the command palette. There you search for any command or section and run or open it.", "words": ["commands", "search", "palette"], "alts": ["⌨️", "✨", "🗒️"] },
"cmd.status": { "glyph": "📊", "spoken": "Status", "desc": "Opens the current status: the assigned game, its achievement progress and the enforcer's state.", "words": ["status", "state", "summary"], "alts": ["🩺", "🧾", "🚥"] },
"cmd.list": { "glyph": "📋", "spoken": "List", "desc": "Opens the game list from the last scan snapshot, with achievements and completion times.", "words": ["list", "games", "snapshot"], "alts": ["📃", "📑", "🧻"] },
"cmd.stats": { "glyph": "📈", "spoken": "Stats", "desc": "Opens the backlog estimates: how long the remaining games take to finish at your pace.", "words": ["stats", "estimates", "forecast"], "alts": ["📉", "🧮", "🔮"] },
"cmd.installed": { "glyph": "💾", "spoken": "Installed", "desc": "Opens the list of games installed on this PC, with the assigned and protected ones marked.", "words": ["installed", "disk", "local"], "alts": ["💽", "📀", "🧊"] },
"cmd.gaming-status": { "glyph": "⏱️", "spoken": "Gaming status", "desc": "Opens today's gaming time: minutes used, budget left and whether gaming is blocked.", "words": ["today", "playtime", "clock"], "alts": ["⏲️", "🕐", "📆"] },
"cmd.check": { "glyph": "🔄", "spoken": "Check", "desc": "Runs check: looks for a new achievement on the assigned game. One new achievement releases the game.", "words": ["check", "verify", "refresh"], "alts": ["🔁", "🧐", "☑️"] },
"cmd.scan": { "glyph": "🔎", "spoken": "Scan", "desc": "Runs scan: reads the achievements of every owned game and assigns a game when none is set.", "words": ["scan", "survey", "assign"], "alts": ["🛰️", "🗺️", "🧪"] },
"cmd.done": { "glyph": "🏆", "spoken": "Done", "desc": "Runs done: confirms a new achievement on the assigned game and moves on to pick the next one.", "words": ["done", "finished", "next"], "alts": ["🥇", "🎉", "🏁"] },
"cmd.pick": { "glyph": "🎲", "spoken": "Pick", "desc": "Runs pick: offers other candidate games to play next. It keeps the current game unless told to replace it.", "words": ["pick", "choose", "random"], "alts": ["🃏", "🎰", "🔀"] },
"cmd.pick-manual": { "glyph": "📌", "spoken": "Pick manual", "desc": "Runs a manual pick: you choose a game by hand and the enforcer locks onto it for some days.", "words": ["manual", "lock", "own"], "alts": ["✋", "🧷", "🖐️"] },
"cmd.abandon-pick": { "glyph": "❌", "spoken": "Abandon pick", "desc": "Runs abandon pick: undoes a manual pick, so the enforcer assigns a game again.", "words": ["abandon", "undo", "drop"], "alts": ["✖️", "↩️", "🚮"] },
"cmd.install": { "glyph": "⬇️", "spoken": "Install", "desc": "Runs install: downloads an allowed game, trying the fast installer first.", "words": ["install", "download", "get"], "alts": ["📥", "🔽", "⏬"] },
"cmd.uninstall": { "glyph": "🗑️", "spoken": "Uninstall", "desc": "Runs uninstall: removes every installed game that is neither assigned nor protected.", "words": ["uninstall", "remove", "clean"], "alts": ["🧹", "⏏️", "🪣"] },
"cmd.hide": { "glyph": "🙈", "spoken": "Hide", "desc": "Runs hide: hides every game except the assigned one in the Steam library.", "words": ["hide", "conceal", "mask"], "alts": ["🫣", "🕶️", "🌫️"] },
"cmd.unhide": { "glyph": "👁️", "spoken": "Unhide", "desc": "Runs unhide: shows every game in the Steam library again.", "words": ["unhide", "show", "reveal"], "alts": ["👀", "🔦", "🪟"] },
"cmd.buy-dlc": { "glyph": "💳", "spoken": "Buy DLC", "desc": "Runs buy DLC: unblocks the Steam store for 15 minutes so you can buy a game or DLC.", "words": ["DLC", "buy", "purchase"], "alts": ["💵", "🪙", "🏷️"] },
"cmd.unblock": { "glyph": "🔓", "spoken": "Unblock", "desc": "Runs unblock: opens the Steam store for a number of minutes, at most 30.", "words": ["unblock", "open", "unlock"], "alts": ["🚪", "🗝️", "🔆"] },
"cmd.add-exception": { "glyph": "🎫", "spoken": "Add exception", "desc": "Runs add exception: allows one game right away, after a typed phrase and a logged reason.", "words": ["exception", "allow", "whitelist"], "alts": ["🎟️", "🆗", "📝"] },
"cmd.block-gaming": { "glyph": "⛔", "spoken": "Block gaming", "desc": "Runs block gaming: blocks all gaming for a number of days. There is no undo in the app.", "words": ["block", "ban", "lockdown"], "alts": ["🧱", "📵", "🚷"] },
"cmd.reset": { "glyph": "♻️", "spoken": "Reset", "desc": "Runs reset: wipes all enforcer state after saving a timestamped backup.", "words": ["reset", "wipe", "restart"], "alts": ["🧨", "🔃", "🆕"] },
"cmd.setup": { "glyph": "🔧", "spoken": "Setup", "desc": "Opens setup: the Steam API key and the SteamID the enforcer needs.", "words": ["setup", "configure", "key"], "alts": ["🪛", "🎛️", "🧩"] },
"cmd.enforce": { "glyph": "🛡️", "spoken": "Enforce", "desc": "Runs the enforcer: block, uninstall, kill and hide. The demo runs a 60-second gaming budget only.", "words": ["enforce", "guard", "shield"], "alts": ["👮", "🚔", "🔰"] },
"cmd.gaming-reset": { "glyph": "⏪", "spoken": "Gaming reset", "desc": "Runs gaming reset: resets today's gaming counter as root, after a typed phrase and a five-minute countdown.", "words": ["rewind", "reset", "refill"], "alts": ["⏮️", "🔙", "🔂"] },
"cmd.gaming-unblock": { "glyph": "🔌", "spoken": "Gaming unblock", "desc": "Runs gaming unblock: force-releases the playtime bind mounts. It is the root recovery hatch.", "words": ["release", "unplug", "recover"], "alts": ["🪫", "🆘", "🧯"] },
"cmd.serve": { "glyph": "🌐", "spoken": "Serve", "desc": "Restarts this web UI server. It comes back on the current code by itself.", "words": ["server", "web", "restart"], "alts": ["🕸️", "📶", "🔗"] },
"cmd.restore-backup": { "glyph": "🗄️", "spoken": "Restore backup", "desc": "Restores a saved state backup after you type its phrase.", "words": ["restore", "backup", "rollback"], "alts": ["💼", "🧳", "📼"] },
"job.state.queued": { "glyph": "⏸️", "spoken": "Queued", "desc": "Job state badge: the job waits to start.", "words": ["queued", "waiting", "pending"], "alts": ["🕒", "⏳", "💤"] },
"job.state.running": { "glyph": "▶️", "spoken": "Running", "desc": "Job state badge: the job is running now.", "words": ["running", "active", "busy"], "alts": ["🏃", "⚡", "🔵"] },
"job.state.waiting_input": { "glyph": "⚠️", "spoken": "Waiting for input", "desc": "Job state badge: the job is paused on a question and needs your answer.", "words": ["input", "question", "answer"], "alts": ["❓", "💬", "🙋"] },
"job.state.succeeded": { "glyph": "✅", "spoken": "Succeeded", "desc": "Job state badge: the job finished without errors.", "words": ["succeeded", "done", "ok"], "alts": ["✔️", "🟢", "👍"] },
"job.state.failed": { "glyph": "⛔", "spoken": "Failed", "desc": "Job state badge: the job stopped on an error. Its log says why.", "words": ["failed", "error", "broken"], "alts": ["💔", "🔴", "💥"] },
"job.state.cancelled": { "glyph": "🚫", "spoken": "Cancelled", "desc": "Job state badge: the job was stopped before it finished.", "words": ["cancelled", "stopped", "aborted"], "alts": ["⏹️", "🛑", "✂️"] },
"notice.info": { "glyph": "ℹ️", "spoken": "Information", "desc": "Mark on an information notice: a neutral fact or a hint.", "words": ["info", "note", "hint"], "alts": ["💡", "🔷", "📢"] },
"notice.success": { "glyph": "✅", "spoken": "Success", "desc": "Mark on a success notice: the action worked.", "words": ["success", "ok", "done"], "alts": ["✔️", "🎉", "👍"] },
"notice.warning": { "glyph": "⚠️", "spoken": "Warning", "desc": "Mark on a warning notice: something needs your attention, but nothing failed.", "words": ["warning", "caution", "careful"], "alts": ["🟡", "🔶", "❗"] },
"notice.danger": { "glyph": "⛔", "spoken": "Error", "desc": "Mark on an error notice: something failed or was refused. The server's message follows it.", "words": ["error", "danger", "problem"], "alts": ["🛑", "‼️", "🔴"] }
}
}

View File

@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest'
import type { JobState } from '../api/jobContract'
import { COMMAND_HOME, commandIcon } from '../commands/catalog'
import { NAV } from '../shell/nav'
import type { Tone } from '../ui/build'
import { ICONS, iconEntry, isIconId } from './registry'
const JOB_STATES: JobState[] = ['queued', 'running', 'waiting_input', 'succeeded', 'failed', 'cancelled']
const TONES: Tone[] = ['info', 'success', 'warning', 'danger']
describe('icon registry', () => {
it('registers exactly this pass: 8 nav, the palette, 26 commands, 6 job states, 4 tones', () => {
const ids = ICONS.map((e) => e.id)
expect(new Set(ids).size).toBe(ids.length)
expect(ids).toHaveLength(8 + 1 + 26 + 6 + 4)
for (const n of NAV) expect(isIconId(n.icon)).toBe(true)
expect(isIconId('palette.open')).toBe(true)
for (const name of Object.keys(COMMAND_HOME) as (keyof typeof COMMAND_HOME)[]) {
expect(isIconId(commandIcon(name))).toBe(true)
}
for (const s of JOB_STATES) expect(isIconId(`job.state.${s}`)).toBe(true)
for (const t of TONES) expect(isIconId(`notice.${t}`)).toBe(true)
})
it.each(ICONS.map((e) => [e.id, e] as const))('%s: glyph, name, description, 3 words, 3 alternatives', (_id, e) => {
expect(e.glyph).not.toBe('')
expect(e.spoken).not.toBe('')
expect(e.desc.length).toBeGreaterThan(20)
expect(e.desc.split(/[.!?](\s|$)/).filter((s) => s.trim()).length).toBeLessThanOrEqual(2)
expect(e.words).toHaveLength(3)
expect(new Set(e.words.map((w) => w.toLowerCase())).size).toBe(3)
for (const w of e.words) expect(w).toMatch(/^\S+$/)
expect(e.alts).toHaveLength(3)
expect(new Set([e.glyph, ...e.alts]).size).toBe(4)
})
it('keeps every default glyph the UI painted before the registry', () => {
expect(iconEntry('nav.dashboard').glyph).toBe('🏠')
expect(iconEntry('palette.open').glyph).toBe('🔍')
expect(iconEntry('cmd.done').glyph).toBe('🏆')
expect(iconEntry('cmd.restore-backup').glyph).toBe('🗄️')
expect(iconEntry('job.state.waiting_input').glyph).toBe('⚠️')
expect(iconEntry('notice.danger').glyph).toBe('⛔')
})
it('tells registered ids from raw glyphs', () => {
expect(isIconId('cmd.done')).toBe(true)
expect(isIconId('🏆')).toBe(false)
expect(isIconId('toString')).toBe(false)
})
})

38
web/src/icons/registry.ts Normal file
View File

@ -0,0 +1,38 @@
// The icon registry: every icon the UI paints by id, its default glyph, its
// spoken name, what it is and does, 3 one-word suggestions and 3 alternative
// glyphs. The data is registry.json so the Python server can check a glyph
// choice against the same list; this module types it (IconId is the union of
// its keys, so an unregistered id fails the build) and looks it up.
// Order in the file is the picker's order.
import data from './registry.json'
export type IconId = keyof typeof data.icons
export interface IconEntry {
id: IconId
glyph: string
/** The accessible name (aria-label / .sr-only) when a caller gives none. */
spoken: string
/** What the icon is and what it does, shown on the /words picker. */
desc: string
/** Three distinct one-word suggestions (keys 1/2/3 on the picker). */
words: readonly string[]
/** Three glyphs that may replace the default (keys 7/8/9). */
alts: readonly string[]
}
const RAW: Record<string, Omit<IconEntry, 'id'>> = data.icons
export const ICONS: readonly IconEntry[] = Object.entries(RAW).map(([id, e]) => ({ id: id as IconId, ...e }))
const BY_ID = Object.fromEntries(ICONS.map((e) => [e.id, e])) as Record<IconId, IconEntry>
/** True for a registered id, false for a raw glyph (the old `glyph(icon, spoken)` path). */
export function isIconId(s: string): s is IconId {
return Object.hasOwn(BY_ID, s)
}
export function iconEntry(id: IconId): IconEntry {
return BY_ID[id]
}

View File

@ -0,0 +1,135 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { useIcons } from '../test/iconLedger'
import { glyph } from '../ui/build'
import { setWordsHidden } from './ledger'
import { decorateChrome, decorateIcons, iconFor, iconMark, iconWord } from './render'
// vitest runs from web/ (vitest.config.ts); jsdom loads no CSS, so read the rule.
const css = readFileSync(join(process.cwd(), 'src/styles/icons.css'), 'utf8')
describe('decorateChrome', () => {
it('decorates the sidebar and top bar only', () => {
useIcons({ 'nav.jobs': { word: 'jobs' }, 'palette.open': { word: 'find' } })
document.body.innerHTML =
'<aside class="sidebar"><a class="nav-link"><span data-icon="nav.jobs">⚙️</span></a></aside>' +
'<header class="topbar"><button class="btn"><span data-icon="palette.open">🔍</span></button></header>' +
'<main><span data-icon="nav.jobs">⚙️</span></main>'
decorateChrome()
expect([...document.querySelectorAll('.icon-word')].map((w) => w.textContent)).toEqual(['Jobs', 'Find'])
})
})
describe('iconFor', () => {
it('is the default glyph and no word without a ledger entry', () => {
expect(iconFor('cmd.done')).toEqual({ id: 'cmd.done', glyph: '🏆', word: '', spoken: 'Done' })
})
it('draws the stored word in sentence case and swaps in the chosen glyph', () => {
useIcons({ 'cmd.done': { word: 'got an HLTB win', glyph: '🎉' } })
expect(iconFor('cmd.done')).toMatchObject({ glyph: '🎉', word: 'Got an HLTB win' })
})
it('has no word when skipped or hidden, but keeps the chosen glyph', () => {
useIcons({ 'cmd.done': { word: null, glyph: '🏁' }, 'cmd.scan': { word: 'scan' } })
expect(iconFor('cmd.done')).toMatchObject({ glyph: '🏁', word: '' })
setWordsHidden(true)
expect(iconFor('cmd.scan').word).toBe('')
})
it('ignores a stored glyph that is not one of the registered ones', () => {
useIcons({ 'cmd.done': { glyph: '🍕' } })
expect(iconFor('cmd.done').glyph).toBe('🏆')
})
})
describe('glyph(id)', () => {
it('paints the word to the right of the icon and keeps the spoken name', () => {
useIcons({ 'nav.jobs': { word: 'my jobs' } })
const el = glyph('nav.jobs')
const [icon, word, spoken] = [...el.children]
expect(icon).toHaveAttribute('aria-hidden', 'true')
expect(icon.textContent).toBe('⚙️')
expect(word).toHaveClass('icon-word')
expect(word).toHaveAttribute('aria-hidden', 'true')
expect(word.textContent).toBe('My jobs')
expect(spoken).toHaveClass('sr-only')
expect(spoken.textContent).toBe('Jobs')
expect(el).toHaveClass('glyph', 'has-word')
})
it('takes an explicit spoken name and class', () => {
const el = glyph('cmd.scan', 'Run scan', 'job-cmd')
expect(el.className).toBe('job-cmd')
expect(el.querySelector('.sr-only')?.textContent).toBe('Run scan')
expect(el.querySelector('.icon-word')).toBeNull()
})
it('still paints a raw glyph with the old signature', () => {
const el = glyph('🧭', 'navigate')
expect(el.querySelector('[aria-hidden]')?.textContent).toBe('🧭')
expect(el.querySelector('.sr-only')?.textContent).toBe('navigate')
expect(el.querySelector('.icon-word')).toBeNull()
})
})
describe('icon pieces', () => {
it('iconMark is the glyph alone, tagged with its id', () => {
useIcons({ 'nav.store': { glyph: '🏪' } })
const el = iconMark('nav.store', 'nav-icon')
expect(el.className).toBe('nav-icon')
expect(el).toHaveAttribute('data-icon', 'nav.store')
expect(el).toHaveAttribute('aria-hidden', 'true')
expect(el.textContent).toBe('🏪')
})
it('iconWord is null without a word, a tagged span with one', () => {
expect(iconWord('nav.store')).toBeNull()
useIcons({ 'nav.store': { word: 'shop' } })
const w = iconWord('nav.store')
expect(w).toHaveAttribute('data-icon-word', 'nav.store')
expect(w?.textContent).toBe('Shop')
})
it('the CSS lays the word out on the right, vertically centred, never under', () => {
const rule = /\.has-word\s*\{([^}]*)\}/.exec(css)?.[1] ?? ''
expect(rule).toMatch(/display:\s*inline-flex/)
expect(rule).toMatch(/align-items:\s*center/)
expect(rule).not.toMatch(/column|wrap/)
})
})
describe('decorateIcons (static Astro markup: sidebar, palette button)', () => {
const markup = () => {
document.body.innerHTML =
'<a class="nav-link"><span class="nav-icon" aria-hidden="true" data-icon="nav.picks">🎯</span><kbd>3</kbd></a>' +
'<span data-icon="no.such">❓</span>'
return document.body
}
it('swaps the glyph and puts the word right after the icon, once', () => {
useIcons({ 'nav.picks': { word: 'target', glyph: '🏹' } })
const root = markup()
decorateIcons(root)
decorateIcons(root)
const icon = root.querySelector('[data-icon="nav.picks"]')
expect(icon?.textContent).toBe('🏹')
expect(icon?.nextElementSibling).toHaveClass('icon-word')
expect(icon?.nextElementSibling?.textContent).toBe('Target')
expect(root.querySelectorAll('.icon-word')).toHaveLength(1)
expect(icon?.parentElement).toHaveClass('has-word')
expect(root.querySelector('[data-icon="no.such"]')?.textContent).toBe('❓')
})
it('removes the words again when they are hidden', () => {
useIcons({ 'nav.picks': { word: 'target' } })
const root = markup()
decorateIcons(root)
setWordsHidden(true)
decorateIcons(root)
expect(root.querySelector('.icon-word')).toBeNull()
expect(root.querySelector('.nav-link')).not.toHaveClass('has-word')
expect(root.querySelector('[data-icon="nav.picks"]')?.textContent).toBe('🎯')
})
})

60
web/src/icons/render.ts Normal file
View File

@ -0,0 +1,60 @@
// Drawing a registered icon: the glyph (the user's alternative if he chose
// one) and, when he picked a word, that word to the RIGHT of the icon,
// vertically centred (styles/icons.css `.has-word`), in sentence case. The
// word is aria-hidden: the icon's spoken name stays its one accessible name.
// `glyph(id)` in ui/build.ts is the usual entry; these are its parts.
import { h } from '../lib/dom'
import { choiceOf, wordsHidden } from './ledger'
import { iconEntry, isIconId, type IconId } from './registry'
import { sentenceCase } from './textCase'
export interface ResolvedIcon {
id: IconId
glyph: string
/** As drawn (sentence case); '' when skipped, unanswered or hidden. */
word: string
spoken: string
}
export function iconFor(id: IconId): ResolvedIcon {
const entry = iconEntry(id)
const choice = choiceOf(id)
const glyph = choice.glyph && entry.alts.includes(choice.glyph) ? choice.glyph : entry.glyph
const word = typeof choice.word === 'string' && !wordsHidden() ? sentenceCase(choice.word) : ''
return { id, glyph, word, spoken: entry.spoken }
}
/** The painted glyph alone, tagged with its id (decorateIcons can refresh it). */
export function iconMark(id: IconId, className: string): HTMLSpanElement {
return h('span', { class: className, 'aria-hidden': 'true', 'data-icon': id }, iconFor(id).glyph)
}
/** The word span that goes right after the icon, or null when it has none. */
export function iconWord(id: IconId): HTMLSpanElement | null {
const { word } = iconFor(id)
return word ? h('span', { class: 'icon-word', 'aria-hidden': 'true', 'data-icon-word': id }, word) : null
}
/**
* Refresh static markup (the Astro sidebar and palette button) from the
* ledger: each `[data-icon]` gets its current glyph and, right after it, its
* word. Idempotent, so it can rerun after a pick or a hide toggle.
*/
export function decorateIcons(root: ParentNode): void {
for (const el of root.querySelectorAll<HTMLElement>('[data-icon]')) {
const id = String(el.dataset.icon)
if (!isIconId(id)) continue
const next = el.nextElementSibling
if (next?.classList.contains('icon-word')) next.remove()
el.textContent = iconFor(id).glyph
const word = iconWord(id)
if (word) el.after(word)
el.parentElement?.classList.toggle('has-word', word !== null)
}
}
/** The static chrome every page shares (sidebar, top bar); run at boot and after a pick. */
export function decorateChrome(doc: Document = document): void {
for (const el of doc.querySelectorAll('.sidebar, .topbar')) decorateIcons(el)
}

View File

@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest'
import { KEEP, sentenceCase } from './textCase'
describe('sentenceCase', () => {
it.each([
['home', 'Home'],
['gaming Reset', 'Gaming reset'],
['My Own Words', 'My own words'],
['buy dlc', 'Buy DLC'],
['hltb times', 'HLTB times'],
['app Id', 'App ID'],
['open steam', 'Open Steam'],
['get (dlc)!', 'Get (DLC)!'],
['"quoted" word', '"Quoted" word'],
['', ''],
['42 games', '42 games'],
])('%j -> %j', (stored, drawn) => {
expect(sentenceCase(stored)).toBe(drawn)
})
it('changes only first letters: the rest of a word stays verbatim', () => {
expect(sentenceCase('iPhone sYnc')).toBe('IPhone sYnc')
})
it('keeps the acronyms the brief names', () => {
for (const word of ['DLC', 'HLTB', 'CDP', 'ID']) expect(KEEP).toContain(word)
expect(sentenceCase('via cdp')).toBe('Via CDP')
})
})

29
web/src/icons/textCase.ts Normal file
View File

@ -0,0 +1,29 @@
// The one casing rule for every icon word, after cleanup-plate's TextCase:
// sentence case. The first letter of the text is upper-case, every later word
// starts lower-case, except the acronyms / proper nouns in KEEP, which always
// get their listed spelling. Only first letters change: typos, punctuation and
// the rest of a word stay verbatim. Applied at render time; the user's ledger
// is never rewritten. Add a new acronym or name HERE, nowhere else.
export const KEEP: readonly string[] = ['API', 'CDP', 'DLC', 'HLTB', 'ID', 'OK', 'Steam', 'UI']
const EDGE = /^[,.;:!?()"']*/
const TAIL = /[,.;:!?()"']*$/
function caseWord(word: string, first: boolean): string {
const lead = word.slice(0, word.length - word.replace(EDGE, '').length)
const core = word.slice(lead.length).replace(TAIL, '')
if (core === '') return word
const keep = KEEP.find((k) => k.toLowerCase() === core.toLowerCase())
if (keep) return lead + keep + word.slice(lead.length + core.length)
const letter = word.charAt(lead.length)
const cased = first ? letter.toUpperCase() : letter.toLowerCase()
return lead + cased + word.slice(lead.length + 1)
}
export function sentenceCase(text: string): string {
return text
.split(' ')
.map((w, i) => caseWord(w, i === 0))
.join(' ')
}

View File

@ -0,0 +1,57 @@
// The registered call sites look their icon up by id: a ledger word shows
// right of the icon, a chosen alternative replaces the default glyph.
import { describe, expect, it } from 'vitest'
import { COMMAND_ICON, commandIcon } from '../commands/catalog'
import { commandButton } from '../commands/commandButton'
import { stateBadge } from '../jobs/progress'
import { NAV } from '../shell/nav'
import { useIcons } from '../test/iconLedger'
import { notice } from '../ui/build'
import { isIconId } from './registry'
describe('registered call sites', () => {
it('a command button paints the word right of its icon, label still spoken', () => {
useIcons({ 'cmd.done': { word: 'trophy', glyph: '🥇' } })
const btn = commandButton({ name: 'done', label: 'I got an achievement' })
const icon = btn.querySelector('.cmd-icon')
expect(icon?.textContent).toBe('🥇')
expect(icon?.nextElementSibling).toHaveClass('icon-word')
expect(icon?.nextElementSibling?.textContent).toBe('Trophy')
expect(btn).toHaveAttribute('aria-label', 'I got an achievement')
})
it('a command button without a word is unchanged', () => {
const btn = commandButton({ name: 'scan' })
expect(btn.querySelector('.cmd-icon')?.textContent).toBe('🔎')
expect(btn.querySelector('.icon-word')).toBeNull()
})
it('a notice paints its tone word right of the tone icon', () => {
useIcons({ 'notice.warning': { word: 'careful' } })
const el = notice('warning', null)
const icon = el.querySelector('.notice-icon')
expect(icon?.nextElementSibling?.textContent).toBe('Careful')
expect(icon?.parentElement).toHaveClass('has-word')
})
it('a job state badge paints its word and keeps its aria-label', () => {
useIcons({ 'job.state.running': { word: 'busy', glyph: '⚡' } })
const el = stateBadge('running')
expect(el.querySelector('.pill-icon')?.textContent).toBe('⚡')
expect(el.querySelector('.icon-word')?.textContent).toBe('Busy')
expect(el).toHaveAttribute('aria-label', 'running')
})
it('nav entries and commands are looked up by id', () => {
for (const n of NAV) expect(isIconId(n.icon)).toBe(true)
expect(commandIcon('gaming-status')).toBe('cmd.gaming-status')
})
it('COMMAND_ICON (sites not yet on ids) is the live glyph, alternative applied', () => {
expect(COMMAND_ICON.done).toBe('🏆')
useIcons({ 'cmd.done': { glyph: '🏁' } })
expect(COMMAND_ICON.done).toBe('🏁')
expect(Object.keys(COMMAND_ICON)).toHaveLength(26)
})
})

View File

@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { normalizeWord, wordProblem } from './wordRules'
describe('manual words (mirror of the server rules)', () => {
it('collapses whitespace and keeps casing', () => {
expect(normalizeWord(' My OWN\tword\n ')).toBe('My OWN word')
})
it.each(['My own words', 'x', 'HLTB 100%', 'I got an achievement!', '🏆'.repeat(40), 'a'.repeat(40)])(
'accepts %j',
(text) => {
expect(wordProblem(text)).toBe('')
},
)
it.each([
['', 'empty'],
[' ', 'empty'],
['a'.repeat(41), 'too_long'],
['bad\u0000word', 'control'],
['esc\u001b', 'control'],
['del\u007f', 'control'],
])('refuses %j as %s', (text, why) => {
expect(wordProblem(text)).toBe(why)
})
})

View File

@ -0,0 +1,25 @@
// Manual icon words, the client's copy of the server's rule
// (_web_icon_words.normalize_word): any words, casing kept, whitespace runs
// collapsed, 1–40 characters, no control characters. The server re-checks;
// this only lets the picker flag a bad entry before sending it.
import { ICON_WORD_MAX } from '../api/iconWordsContract'
// Spelled out (not \s) so it matches the Python side character for character.
const SPACE = /[\t\n\v\f\r \u00a0\u2000-\u200a\u2028\u2029\u202f\u3000]+/g
// eslint-disable-next-line no-control-regex -- control characters are the point
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
export type WordProblem = '' | 'empty' | 'too_long' | 'control'
export function normalizeWord(text: string): string {
return text.replace(SPACE, ' ').trim()
}
/** '' when `text` is a storable word, else why not. Length counts code points, like Python. */
export function wordProblem(text: string): WordProblem {
const word = normalizeWord(text)
if (word === '') return 'empty'
if (Array.from(word).length > ICON_WORD_MAX) return 'too_long'
return CONTROL.test(word) ? 'control' : ''
}

View File

@ -1,16 +1,18 @@
// Job state pill and progress bar (was jobs/ProgressBar.tsx). // Job state pill and progress bar (was jobs/ProgressBar.tsx).
import type { JobState } from '../api/jobContract' import type { JobState } from '../api/jobContract'
import type { IconId } from '../icons/registry'
import { iconMark, iconWord } from '../icons/render'
import { h } from '../lib/dom' import { h } from '../lib/dom'
const STATE_ICON: Record<JobState, string> = { const STATE_ICON = {
queued: '⏸️', queued: 'job.state.queued',
running: '▶️', running: 'job.state.running',
waiting_input: '⚠️', waiting_input: 'job.state.waiting_input',
succeeded: '✅', succeeded: 'job.state.succeeded',
failed: '⛔', failed: 'job.state.failed',
cancelled: '🚫', cancelled: 'job.state.cancelled',
} } as const satisfies Record<JobState, IconId>
const STATE_TONE: Record<JobState, string> = { const STATE_TONE: Record<JobState, string> = {
queued: 'neutral', queued: 'neutral',
@ -22,7 +24,8 @@ const STATE_TONE: Record<JobState, string> = {
} }
export function stateBadge(state: JobState): HTMLSpanElement { export function stateBadge(state: JobState): HTMLSpanElement {
return h('span', { class: `pill pill-${STATE_TONE[state]}`, 'aria-label': state }, h('span', { class: 'pill-icon', 'aria-hidden': 'true' }, STATE_ICON[state])) const id = STATE_ICON[state]
return h('span', { class: `pill pill-${STATE_TONE[state]}`, 'aria-label': state }, iconMark(id, 'pill-icon'), iconWord(id))
} }
export type BarTone = 'accent' | 'success' | 'danger' | 'warning' export type BarTone = 'accent' | 'success' | 'danger' | 'warning'

View File

@ -9,7 +9,9 @@ import '../styles/app.css'
import '../styles/controls.css' import '../styles/controls.css'
import '../styles/screens.css' import '../styles/screens.css'
import '../styles/library.css' import '../styles/library.css'
import '../styles/icons.css'
import DevToken from '../components/DevToken.astro' import DevToken from '../components/DevToken.astro'
import { iconEntry } from '../icons/registry'
import { BUILD_STAMP } from '../lib/buildStamp' import { BUILD_STAMP } from '../lib/buildStamp'
import { NAV } from '../shell/nav' import { NAV } from '../shell/nav'
@ -52,7 +54,7 @@ const href = (to: string) => (to === '/' ? '/' : `${to}/`)
aria-label={n.label} aria-label={n.label}
aria-keyshortcuts={`Alt+${n.key}`} aria-keyshortcuts={`Alt+${n.key}`}
> >
<span class="nav-icon" aria-hidden="true">{n.icon}</span> <span class="nav-icon" aria-hidden="true" data-icon={n.icon}>{iconEntry(n.icon).glyph}</span>
<kbd aria-hidden="true">{n.key}</kbd> <kbd aria-hidden="true">{n.key}</kbd>
</a> </a>
</li> </li>
@ -64,7 +66,7 @@ const href = (to: string) => (to === '/' ? '/' : `${to}/`)
<div class="main-col"> <div class="main-col">
<header class="topbar"> <header class="topbar">
<button type="button" class="btn btn-ghost palette-btn" data-open-palette aria-keyshortcuts="Control+K" aria-label="Commands"> <button type="button" class="btn btn-ghost palette-btn" data-open-palette aria-keyshortcuts="Control+K" aria-label="Commands">
<span aria-hidden="true">🔍</span> <kbd aria-hidden="true">⌃K</kbd> <span aria-hidden="true" data-icon="palette.open">{iconEntry('palette.open').glyph}</span> <kbd aria-hidden="true">⌃K</kbd>
</button> </button>
<job-indicator></job-indicator> <job-indicator></job-indicator>
<span class="grow"></span> <span class="grow"></span>

View File

@ -0,0 +1,16 @@
---
// The icon-word picker: the one page that carries text on purpose (the user
// asked for it; descriptions and suggestions are for reading). Reached from
// the command palette. All of it is rendered by <icon-words-picker>.
import PageHead from '../../components/PageHead.astro'
import Shell from '../../layouts/Shell.astro'
---
<Shell title="Icon words">
<PageHead title="Icon words" sub="Pick the word drawn next to each icon, or skip it." />
<icon-words-picker></icon-words-picker>
</Shell>
<script>
import '../../icons/picker'
</script>

View File

@ -4,7 +4,7 @@
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 { commandIcon, 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'
@ -190,7 +190,7 @@ 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)), glyph(commandIcon(j.command), commandLabel(j.command)),
// The job's summary is a server sentence: spoken here, shown in the job view. // The job's summary is a server sentence: spoken here, shown in the job view.
h('span', { class: 'sr-only' }, j.summary ?? j.progress?.label ?? ''), h('span', { class: 'sr-only' }, j.summary ?? j.progress?.label ?? ''),
h('span', { class: 'grow' }), h('span', { class: 'grow' }),

View File

@ -6,7 +6,7 @@ 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 { commandIcon, 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'
@ -29,7 +29,7 @@ function params(j: Job): string {
/** The command's glyph painted, its name spoken. */ /** The command's glyph painted, its name spoken. */
function commandGlyph(command: Job['command']): HTMLSpanElement { function commandGlyph(command: Job['command']): HTMLSpanElement {
return glyph(COMMAND_ICON[command], commandLabel(command), 'job-cmd') return glyph(commandIcon(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. */

View File

@ -4,6 +4,7 @@
import { q, refreshAfterJob } from '../api/queries' import { q, refreshAfterJob } from '../api/queries'
import { go } from '../commands/palette' import { go } from '../commands/palette'
import { decorateChrome } from '../icons/render'
import { hub } from '../jobs/hub' import { hub } from '../jobs/hub'
import { runner } from '../lib/runner' import { runner } from '../lib/runner'
import { NAV } from './nav' import { NAV } from './nav'
@ -67,6 +68,8 @@ export function boot(): void {
runner.openPalette() runner.openPalette()
}) })
watchSetup(window.location.pathname) watchSetup(window.location.pathname)
// The sidebar and palette button are static HTML: give them the user's words.
decorateChrome()
const build = document.querySelector<HTMLMetaElement>(`meta[name="${BUILD_META}"]`)?.content const build = document.querySelector<HTMLMetaElement>(`meta[name="${BUILD_META}"]`)?.content
if (build) setInterval(() => void checkBuild(build), BUILD_POLL_MS) if (build) setInterval(() => void checkBuild(build), BUILD_POLL_MS)
} }

View File

@ -3,7 +3,7 @@
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 { commandIcon, 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'
@ -29,7 +29,7 @@ export function jobChip(job: Job): HTMLAnchorElement {
h( h(
'span', 'span',
{ class: 'jobchip-label' }, { class: 'jobchip-label' },
glyph(COMMAND_ICON[job.command], label), glyph(commandIcon(job.command), label),
h('span', { class: 'jobchip-sub' }, waiting ? glyph('✋', 'needs input') : p?.total ? `${p.step}/${p.total}` : '…'), 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

@ -1,22 +1,36 @@
import type { SectionPath } from '../commands/catalog' import type { SectionPath } from '../commands/catalog'
import type { IconId } from '../icons/registry'
export interface NavItem { export interface NavItem {
to: SectionPath | '/jobs' to: SectionPath | '/jobs'
/** Spoken only (aria-label); the sidebar paints `icon`. */ /** Spoken (aria-label); the sidebar paints `icon` and the user's word for it. */
label: string label: string
blurb: string blurb: string
icon: string icon: IconId
/** Alt+<key> accelerator, shown in the sidebar as the bare digit. */ /** Alt+<key> accelerator, shown in the sidebar as the bare digit. */
key: string key: string
} }
export const NAV: NavItem[] = [ export const NAV: NavItem[] = [
{ to: '/', label: 'Dashboard', blurb: 'Status, budget and quick actions', icon: '🏠', key: '1' }, { to: '/', label: 'Dashboard', blurb: 'Status, budget and quick actions', icon: 'nav.dashboard', key: '1' },
{ to: '/backlog', label: 'Backlog', blurb: 'Planner, stats and the full game list', icon: '📚', key: '2' }, { to: '/backlog', label: 'Backlog', blurb: 'Planner, stats and the full game list', icon: 'nav.backlog', key: '2' },
{ to: '/picks', label: 'Picks', blurb: 'Check, done, pick, scan, manual picks', icon: '🎯', key: '3' }, { to: '/picks', label: 'Picks', blurb: 'Check, done, pick, scan, manual picks', icon: 'nav.picks', key: '3' },
{ to: '/gaming', label: 'Gaming', blurb: 'Daily budget, reset, block, unblock', icon: '🎮', key: '4' }, { to: '/gaming', label: 'Gaming', blurb: 'Daily budget, reset, block, unblock', icon: 'nav.gaming', key: '4' },
{ to: '/library', label: 'Library', blurb: 'All your games, installed, install, uninstall, hide', icon: '🗂️', key: '5' }, { to: '/library', label: 'Library', blurb: 'All your games, installed, install, uninstall, hide', icon: 'nav.library', key: '5' },
{ to: '/store', label: 'Store', blurb: 'Unblock, buy DLC, exceptions', icon: '🛒', key: '6' }, { to: '/store', label: 'Store', blurb: 'Unblock, buy DLC, exceptions', icon: 'nav.store', key: '6' },
{ to: '/jobs', label: 'Jobs', blurb: 'Running and past jobs', icon: '⚙️', key: '7' }, { to: '/jobs', label: 'Jobs', blurb: 'Running and past jobs', icon: 'nav.jobs', key: '7' },
{ to: '/system', label: 'System', blurb: 'Daemon, server, backups, reset, setup', icon: '🖥️', key: '8' }, { to: '/system', label: 'System', blurb: 'Daemon, server, backups, reset, setup', icon: 'nav.system', key: '8' },
]
/** Pages reached from the palette only: no sidebar slot, no Alt key. */
export interface PalettePage {
to: string
label: string
blurb: string
/** A raw glyph: these pages are not in the icon registry yet. */
icon: string
}
export const PALETTE_PAGES: PalettePage[] = [
{ to: '/words', label: 'Icon words', blurb: 'Pick the word shown next to each icon', icon: '🏷️' },
] ]

View File

@ -45,8 +45,8 @@ kbd {
/* ── Shell ── */ /* ── Shell ── */
.shell { .shell {
display: grid; display: grid;
/* Icon rail: nav paints glyph + digit only (textgate). */ /* Icon rail: glyph + digit; it widens to fit the user's icon words (icons.css). */
grid-template-columns: 6rem minmax(0, 1fr); grid-template-columns: minmax(6rem, max-content) minmax(0, 1fr);
min-height: 100dvh; min-height: 100dvh;
} }
.sidebar { .sidebar {

41
web/src/styles/icons.css Normal file
View File

@ -0,0 +1,41 @@
/* Icon words (icons/render.ts) and the /words picker. Tokens only. */
/* The word sits RIGHT of its icon, vertically centred on it, never under. */
.has-word { display: inline-flex; flex-direction: row; align-items: center; gap: var(--space-1); }
.icon-word { white-space: nowrap; line-height: 1.2; font-size: var(--text-body); }
.pill .icon-word { font-size: var(--text-caption); }
.pill.has-word, .pill:has(.icon-word) { gap: var(--space-1); }
/* Sidebar: icon + word on the left, the Alt digit pushed right. */
.nav-link.has-word { display: flex; justify-content: flex-start; gap: var(--space-2); }
.nav-link.has-word kbd { margin-left: auto; }
.notice-mark { align-self: flex-start; }
.runner-mark { display: inline-flex; align-items: center; gap: var(--space-1); }
/* ── /words picker ── */
icon-words-picker { display: flex; flex-direction: column; gap: var(--space-4); }
.picker-head { display: flex; align-items: baseline; gap: var(--space-3); font-size: var(--text-title); }
.picker-id { font-size: var(--text-body); color: var(--text-muted); }
.picker-saved { color: var(--accent); }
.picker-body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 2fr); gap: var(--space-5); align-items: start; }
.picker-stage { display: flex; flex-direction: column; align-items: center; gap: var(--space-4); padding: var(--space-5); background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--radius-md); }
.picker-big { font-size: 9rem; line-height: 1; }
.picker-context { display: flex; justify-content: center; min-width: 12rem; max-width: 100%; overflow-x: auto; padding: var(--space-3); background: var(--bg); border-radius: var(--radius-sm); }
.picker-context .nav-link { min-width: 10rem; }
.picker-desc { font-size: var(--text-subtitle); max-width: var(--measure); }
.picker-words, .picker-glyphs { display: flex; flex-wrap: wrap; gap: var(--space-2); }
.picker-choice { font-size: var(--text-subtitle); justify-content: flex-start; }
.picker-choice kbd { margin-right: var(--space-2); }
.picker-choice[aria-pressed='true'] { border-color: var(--accent); box-shadow: inset 0 0 0 2px var(--accent); }
.picker-own { display: flex; align-items: flex-end; gap: var(--space-2); }
.picker-own-label { display: flex; flex-direction: column; gap: var(--space-1); flex: 1 1 auto; }
.picker-own .input { font-size: var(--text-subtitle); }
.picker-own .input[aria-invalid='true'] { border-color: var(--danger); box-shadow: inset 0 0 0 2px var(--danger); }
.picker-nav { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); }
.picker-toggle { display: flex; align-items: center; gap: var(--space-2); }
.picker-done { align-items: center; padding: var(--space-6); }
.picker-summary { font-size: var(--text-display); }
@media (max-width: 800px) {
.picker-body { grid-template-columns: minmax(0, 1fr); }
}

View File

@ -0,0 +1,21 @@
// Test helpers for the icon-word ledger: set it directly, or plant the
// `<script id="sbe-icon-words">` the Python server injects into every page.
import { ICON_WORDS_SCRIPT, type IconChoice } from '../api/iconWordsContract'
import { resetLedger, setLedger } from '../icons/ledger'
/** Use `icons` as the loaded ledger (what a page load would have read). */
export function useIcons(icons: Record<string, IconChoice>): void {
setLedger({ version: 1, icons })
}
/** Plant the server's injected payload, then forget the cached ledger. */
export function injectLedgerScript(payload: unknown): void {
document.getElementById(ICON_WORDS_SCRIPT)?.remove()
const script = document.createElement('script')
script.type = 'application/json'
script.id = ICON_WORDS_SCRIPT
script.textContent = typeof payload === 'string' ? payload : JSON.stringify(payload)
document.head.append(script)
resetLedger()
}

View File

@ -0,0 +1,36 @@
// Shared by the icon-word picker tests: mount it against a fake server that
// stores what it is sent, plus key and query helpers.
import { expect, vi } from 'vitest'
import type { IconChoice } from '../api/iconWordsContract'
import { ICONS } from '../icons/registry'
import { must } from './events'
import { stubApi } from './harness'
import '../icons/picker'
export const N = ICONS.length
export const [A, B, C, D] = ICONS as [(typeof ICONS)[number], (typeof ICONS)[number], (typeof ICONS)[number], (typeof ICONS)[number]]
export const url = (id: string) => `POST /api/icon-words/${id}`
/** Mount the picker against a fake server that stores what it is sent. */
export function start(icons: Record<string, IconChoice> = { [A.id]: { word: 'x', glyph: null }, [B.id]: { word: null, glyph: null } }) {
const stored: Record<string, IconChoice> = structuredClone(icons)
const routes: Record<string, unknown> = { 'GET /api/icon-words': () => ({ version: 1, icons: stored }) }
for (const e of ICONS) {
routes[url(e.id)] = ({ body }: { body: IconChoice }) => {
stored[e.id] = { ...stored[e.id], ...body }
return { version: 1, icons: stored }
}
}
const mock = stubApi(routes as never)
document.body.innerHTML = '<icon-words-picker></icon-words-picker>'
return { mock, stored }
}
export const q = (sel: string): HTMLElement => must(document.querySelector<HTMLElement>(sel))
export const input = (sel: string): HTMLInputElement => must(document.querySelector<HTMLInputElement>(sel))
export const count = () => q('.picker-count').textContent
export const field = () => input('input[name=own]')
export const press = (key: string, init: KeyboardEventInit = {}, target: Element = document.body) =>
target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init }))
export const at = (n: number) => vi.waitFor(() => { expect(count()).toBe(`${n} / ${N}`) })

View File

@ -1,6 +1,8 @@
import { configure } from '@testing-library/dom' import { configure } from '@testing-library/dom'
import * as matchers from '@testing-library/jest-dom/matchers' import * as matchers from '@testing-library/jest-dom/matchers'
import { afterEach, expect, vi } from 'vitest' import { afterEach, expect, vi } from 'vitest'
import { ICON_WORDS_SCRIPT } from '../api/iconWordsContract'
import { resetLedger } from '../icons/ledger'
import { resetAll } from '../lib/query' import { resetAll } from '../lib/query'
// Registered by hand: jest-dom 7 still augments vitest's old Assertion<T> // Registered by hand: jest-dom 7 still augments vitest's old Assertion<T>
@ -26,8 +28,12 @@ Element.prototype.scrollIntoView = () => undefined
window.scrollTo = () => undefined window.scrollTo = () => undefined
// Queries are module-level singletons: no test may see another's cache. // Queries are module-level singletons: no test may see another's cache.
// The icon-word ledger and its hide setting are page-wide state too.
afterEach(() => { afterEach(() => {
document.body.replaceChildren() document.body.replaceChildren()
document.getElementById(ICON_WORDS_SCRIPT)?.remove()
resetLedger()
localStorage.clear()
resetAll() resetAll()
vi.useRealTimers() vi.useRealTimers()
vi.unstubAllGlobals() vi.unstubAllGlobals()

View File

@ -0,0 +1,53 @@
// Guard test (textgate-rework R6): the user's own icon words are the one
// visible text allowed outside the /words picker, and only exactly as the
// ledger draws them. Anything else in an `.icon-word` still counts.
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 { useIcons } from './iconLedger'
import { visibleWords } from './visibleWords'
import { notice } from '../ui/build'
import '../sections/dashboard'
import '../shell/jobIndicator'
beforeEach(installEventSource)
describe('textgate guard: icon words', () => {
it('the dashboard paints the ledger words and nothing else', async () => {
useIcons({
'cmd.scan': { word: 'scan it' },
'cmd.check': { word: 'look' },
'job.state.running': { word: 'busy' },
})
stubApi({
'GET /api/status': makeStatus(),
'GET /api/budget': makeBudget(),
'GET /api/jobs': [makeJob({ id: 'a', command: 'scan', state: 'running', summary: 'Scanned 12' })],
'GET /api/commands': [makeSpec('check'), makeSpec('scan')],
})
const el = mount('<main><job-indicator></job-indicator><recent-jobs></recent-jobs></main>')
await vi.waitFor(() => {
expect(el.querySelectorAll('.icon-word').length).toBeGreaterThan(1)
}, { timeout: 3000 })
const painted = [...el.querySelectorAll('.icon-word')].map((w) => w.textContent)
expect(painted).toEqual(expect.arrayContaining(['Scan it', 'Busy']))
expect(visibleWords(el, ['Scanned 12'])).toEqual([])
})
it('a word the ledger does not hold still counts', () => {
useIcons({ 'notice.info': { word: 'note' } })
const el = notice('info', null)
expect(visibleWords(el)).toEqual([])
const word = el.querySelector('.icon-word')
if (word) word.textContent = 'Smuggled'
expect(visibleWords(el)).toEqual(['Smuggled'])
})
it('hidden words leave nothing to allow', () => {
const el = notice('info', null)
expect(el.querySelector('.icon-word')).toBeNull()
expect(visibleWords(el)).toEqual([])
})
})

View File

@ -1,7 +1,12 @@
// Textgate guard helper (textgate-rework R6): the words an element paints. // Textgate guard helper (textgate-rework R6): the words an element paints.
// Spoken-only text (.sr-only, [hidden]) and content the caller passes in // Spoken-only text (.sr-only, [hidden]) and content the caller passes in
// `allowed` (game names, server messages) do not count. aria-hidden text // `allowed` (game names, server messages) do not count. aria-hidden text
// still paints, so it counts. // still paints, so it counts. The user's own icon words are the one chrome
// text allowed: an `.icon-word` passes only when it reads exactly what the
// ledger draws for its icon id.
import { iconFor } from '../icons/render'
import { isIconId } from '../icons/registry'
const WORD_RE = /[A-Za-z]{2,}/ const WORD_RE = /[A-Za-z]{2,}/
@ -13,13 +18,19 @@ function spokenOnly(el: Element | null): boolean {
return false return false
} }
/** True for the text of an icon word that is the ledger's word for that icon. */
function ledgerWord(el: Element | null, text: string): boolean {
const id = el?.closest('.icon-word')?.getAttribute('data-icon-word') ?? ''
return isIconId(id) && iconFor(id).word === text
}
/** Visible text nodes holding a word of 2+ letters, minus `allowed` content. */ /** Visible text nodes holding a word of 2+ letters, minus `allowed` content. */
export function visibleWords(root: Element, allowed: readonly string[] = []): string[] { export function visibleWords(root: Element, allowed: readonly string[] = []): string[] {
const out: string[] = [] const out: string[] = []
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
for (let n = walker.nextNode(); n; n = walker.nextNode()) { for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const t = n.textContent?.trim() ?? '' const t = n.textContent?.trim() ?? ''
if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t)) continue if (!WORD_RE.test(t) || spokenOnly(n.parentElement) || allowed.includes(t) || ledgerWord(n.parentElement, t)) continue
out.push(t) out.push(t)
} }
return out return out

View File

@ -3,22 +3,24 @@
// for content a custom element renders from live data. // for content a custom element renders from live data.
import { explain } from '../api/errors' import { explain } from '../api/errors'
import { isIconId, type IconId } from '../icons/registry'
import { iconFor, iconMark, iconWord } from '../icons/render'
import { h, type Child } from '../lib/dom' import { h, type Child } from '../lib/dom'
export type Tone = 'info' | 'success' | 'warning' | 'danger' export type Tone = 'info' | 'success' | 'warning' | 'danger'
const TONE_ICON: Record<Tone, string> = { const TONE_ICON = {
info: 'ℹ️', info: 'notice.info',
success: '✅', success: 'notice.success',
warning: '⚠️', warning: 'notice.warning',
danger: '⛔', danger: 'notice.danger',
} } as const satisfies Record<Tone, IconId>
export function notice(tone: Tone, title: string | null, ...children: Child[]): HTMLDivElement { export function notice(tone: Tone, title: string | null, ...children: Child[]): HTMLDivElement {
const el = h( const el = h(
'div', 'div',
{ class: `notice notice-${tone}`, role: tone === 'danger' ? 'alert' : 'status' }, { class: `notice notice-${tone}`, role: tone === 'danger' ? 'alert' : 'status' },
h('span', { class: 'notice-icon', 'aria-hidden': 'true' }, TONE_ICON[tone]), noticeMark(TONE_ICON[tone]),
title ? h('strong', { class: 'notice-title' }, title) : null, title ? h('strong', { class: 'notice-title' }, title) : null,
) )
if (children.length) { if (children.length) {
@ -27,6 +29,13 @@ export function notice(tone: Tone, title: string | null, ...children: Child[]):
return el return el
} }
/** The tone icon; with a word, icon and word share one row (the notice is a column). */
function noticeMark(id: IconId): HTMLElement {
const icon = iconMark(id, 'notice-icon')
const word = iconWord(id)
return word ? h('span', { class: 'notice-mark has-word' }, icon, word) : icon
}
export function errorNotice(error: unknown, ...children: Child[]): HTMLDivElement { export function errorNotice(error: unknown, ...children: Child[]): HTMLDivElement {
// Textgate: the explanation (title + hint) is spoken only; the ⛔ icon, // Textgate: the explanation (title + hint) is spoken only; the ⛔ icon,
// danger tone and the server's own message stay visible. // danger tone and the server's own message stay visible.
@ -78,10 +87,28 @@ export interface CardOptions {
icon?: string icon?: string
} }
/** A painted glyph whose meaning is spoken only (textgate: no visible words). */ /**
export function glyph(icon: string, spoken: string, className = 'glyph'): HTMLSpanElement { * A painted glyph whose meaning is spoken (.sr-only). With a registered id the
* glyph comes from the registry (the user's alternative applied) and his word,
* if any, is drawn right of it; `spoken` then defaults to the registry name.
* A raw glyph (`glyph('🧭', 'navigate')`) paints just that, as before.
*/
export function glyph(id: IconId, spoken?: string, className?: string): HTMLSpanElement
export function glyph(icon: string, spoken: string, className?: string): HTMLSpanElement
export function glyph(icon: string, spoken?: string, className = 'glyph'): HTMLSpanElement {
if (!isIconId(icon)) {
return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken)) return h('span', { class: className }, h('span', { 'aria-hidden': 'true' }, icon), h('span', { class: 'sr-only' }, spoken))
} }
const { glyph: painted, spoken: name } = iconFor(icon)
const word = iconWord(icon)
return h(
'span',
{ class: word ? `${className} has-word` : className },
h('span', { 'aria-hidden': 'true', 'data-icon': icon }, painted),
word,
h('span', { class: 'sr-only' }, spoken ?? name),
)
}
/** A card; its title is spoken only, `icon` (if any) is painted in its place. */ /** 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 { export function card(title: string | null, body: Child, { aside, className = '', icon }: CardOptions = {}): HTMLElement {

185
web/src/ui/icon_words.json Normal file
View File

@ -0,0 +1,185 @@
{
"icons": {
"cmd.abandon-pick": {
"glyph": null,
"word": "abandon"
},
"cmd.add-exception": {
"glyph": null,
"word": "whitelist"
},
"cmd.block-gaming": {
"glyph": null,
"word": "block"
},
"cmd.buy-dlc": {
"glyph": null,
"word": "DLC"
},
"cmd.check": {
"glyph": null,
"word": "check"
},
"cmd.done": {
"glyph": null,
"word": "done"
},
"cmd.enforce": {
"glyph": null,
"word": "enforce"
},
"cmd.gaming-reset": {
"glyph": null,
"word": "reset"
},
"cmd.gaming-status": {
"glyph": null,
"word": "today"
},
"cmd.gaming-unblock": {
"glyph": null,
"word": "release"
},
"cmd.hide": {
"glyph": null,
"word": "hide"
},
"cmd.install": {
"glyph": null,
"word": "install"
},
"cmd.installed": {
"glyph": null,
"word": "installed"
},
"cmd.list": {
"glyph": null,
"word": "list"
},
"cmd.pick": {
"glyph": null,
"word": "pick"
},
"cmd.pick-manual": {
"glyph": null,
"word": "manual"
},
"cmd.reset": {
"glyph": null,
"word": "reset"
},
"cmd.restore-backup": {
"glyph": null,
"word": "restore"
},
"cmd.scan": {
"glyph": null,
"word": "scan"
},
"cmd.serve": {
"glyph": null,
"word": "restart"
},
"cmd.setup": {
"glyph": null,
"word": "setup"
},
"cmd.stats": {
"glyph": null,
"word": "stats"
},
"cmd.status": {
"glyph": null,
"word": "state"
},
"cmd.unblock": {
"glyph": null,
"word": "unblock"
},
"cmd.unhide": {
"glyph": null,
"word": "unhide"
},
"cmd.uninstall": {
"glyph": null,
"word": "remove"
},
"job.state.cancelled": {
"glyph": null,
"word": "stopped"
},
"job.state.failed": {
"glyph": null,
"word": "failed"
},
"job.state.queued": {
"glyph": null,
"word": "queued"
},
"job.state.running": {
"glyph": null,
"word": "running"
},
"job.state.succeeded": {
"glyph": null,
"word": "done"
},
"job.state.waiting_input": {
"glyph": null,
"word": "question"
},
"nav.backlog": {
"glyph": null,
"word": "backlog"
},
"nav.dashboard": {
"glyph": null,
"word": "home"
},
"nav.gaming": {
"glyph": null,
"word": "budget"
},
"nav.jobs": {
"glyph": null,
"word": "jobs"
},
"nav.library": {
"glyph": null,
"word": "library"
},
"nav.picks": {
"glyph": null,
"word": "picks"
},
"nav.store": {
"glyph": null,
"word": "store"
},
"nav.system": {
"glyph": null,
"word": "admin"
},
"notice.danger": {
"glyph": null,
"word": "error"
},
"notice.info": {
"glyph": null,
"word": "info"
},
"notice.success": {
"glyph": null,
"word": "success"
},
"notice.warning": {
"glyph": null,
"word": "warning"
},
"palette.open": {
"glyph": null,
"word": "search"
}
},
"version": 1
}