mirror of
https://github.com/rommapp/romm.git
synced 2026-12-06 07:54:18 +01:00
Merge remote-tracking branch 'origin/master' into fix/v2-pair-route
# Conflicts: # frontend/src/v2/layouts/AuthLayout.vue # frontend/src/v2/views/DevicePairShell.vue # frontend/src/v2/views/PairShell.vue
This commit is contained in:
86 files changed
+2326
-494
No files matched your search
@@ -99,6 +99,7 @@ npm run generate # writes src/__generated__/ via openapi-typescript-codegen
|
||||
cd backend
|
||||
uv run python3 main.py # run (migrations auto-apply on startup)
|
||||
uv run pytest <path/file> # tests - affected files only, NEVER the whole suite
|
||||
uv run pytest -n auto <dir> # same, in parallel; use for directories, not single files
|
||||
```
|
||||
|
||||
- Tests: pytest + pytest-asyncio, isolated per `pytest-xdist` worker (per-worker DBs); `fakeredis`; `pytest-recording` VCR cassettes mock external APIs; Hypothesis for property tests. Mirror the `backend/<area>/` layout under `backend/tests/`. First-time test DB setup: `docker exec -i romm-db-dev mariadb -uroot -p<pw> < backend/romm_test/setup.sql`.
|
||||
|
||||
@@ -194,7 +194,7 @@ With `uiVersion = "v2"`:
|
||||
|
||||
Run from `backend/`:
|
||||
|
||||
1. `uv run pytest <path/file>`: zero failures on the tests affected by the diff. Never run the whole suite locally (20+ minutes); see [AGENTS.md](../../../AGENTS.md) for how to pick targets. CI runs it in full.
|
||||
1. `uv run pytest <path/file>`: zero failures on the tests affected by the diff. Add `-n auto` when the targets span a directory or more. Never run the whole suite locally (20+ minutes serially); see [AGENTS.md](../../../AGENTS.md) for how to pick targets. CI runs it in full.
|
||||
2. `trunk fmt && trunk check`: ruff/black/isort/bandit clean (CI enforces Trunk).
|
||||
3. `uv run mypy --config-file ../.trunk/configs/mypy.ini .`: zero errors across the backend (CI enforces it).
|
||||
4. **If you added a migration:** `uv run alembic upgrade head` then `uv run alembic downgrade -1` to prove both directions; it must work on MariaDB **and** PostgreSQL (CI runs both).
|
||||
|
||||
@@ -53,19 +53,24 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha
|
||||
|
||||
## Never run the full backend test suite locally
|
||||
|
||||
A bare `uv run pytest` (or `pytest -vv`) over `backend/` takes 20+ minutes and burns a
|
||||
huge number of tokens on output. Don't do it, even to "double check" at the end.
|
||||
A bare `uv run pytest` (or `pytest -vv`) over `backend/` runs serially, takes 20+ minutes, and
|
||||
burns a huge number of tokens on output. Don't do it, even to "double check" at the end.
|
||||
|
||||
Instead, select the tests affected by the change and run only those:
|
||||
Instead, select the tests affected by the change and run only those. Add `-n auto` when the
|
||||
selection spans a directory or more: the suite is set up for `pytest-xdist` (one database per
|
||||
worker).
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
uv run pytest tests/path/to/test_file.py # one file
|
||||
uv run pytest tests/path/to/test_file.py::test_name # one test
|
||||
uv run pytest tests/handler/ tests/endpoints/ # affected areas
|
||||
uv run pytest -n auto tests/handler/ tests/endpoints/ # affected areas, in parallel
|
||||
uv run pytest -k "scan or queue" # by name pattern
|
||||
```
|
||||
|
||||
It gains nothing on a single file or test, and `--pdb` and `-s` don't work under it, so drop it
|
||||
when debugging.
|
||||
|
||||
Pick the targets from the diff: the test file mirroring each changed module
|
||||
(`backend/<area>/x.py` → `backend/tests/<area>/test_x.py`), plus the tests of the
|
||||
callers of anything whose signature or behavior you changed (`grep` for the symbol).
|
||||
|
||||
+4
-3
@@ -236,7 +236,8 @@ _Migrations will be run automatically when running the tests._
|
||||
cd backend
|
||||
# path or test file can be passed as argument to test only a subset
|
||||
uv run pytest [path/file]
|
||||
# or run the following command to run all tests
|
||||
# the -vv switch increases the verbosity of the output, providing more detailed information during test execution.
|
||||
uv run pytest -vv
|
||||
# or run the following command to run all tests, one worker per CPU core
|
||||
uv run pytest -n auto
|
||||
```
|
||||
|
||||
_Each `-n` worker gets its own database (`romm_test_gw0`, `romm_test_gw1`, ...), created and migrated on demand; `setup.sql` grants the test user the rights to create them. On a machine with many cores, cap the workers with `--maxprocesses 4` (CI's count) to keep the load on the database down. A serial run of the whole suite takes 20+ minutes. Drop `-n auto` when debugging with `--pdb` or `-s`, which don't work under parallel workers._
|
||||
@@ -6,6 +6,7 @@
|
||||
uv sync --all-extras --dev # install
|
||||
uv run main.py # run (migrations auto-apply)
|
||||
uv run pytest <path/file> # test - affected files only, NEVER the whole suite
|
||||
uv run pytest -n auto <dir> # same, in parallel; use for directories, not single files
|
||||
uv run mypy --config-file ../.trunk/configs/mypy.ini . # type-check the whole backend
|
||||
uv run alembic revision --autogenerate -m "msg" # new migration (then HAND-REVIEW)
|
||||
uv run alembic upgrade head # apply migrations
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
class RomFileOwnerChangedError(Exception):
|
||||
def __init__(self, rom_file_id: int) -> None:
|
||||
self.message = (
|
||||
f"Rom file {rom_file_id} moved to another rom while it was being locked"
|
||||
)
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.message
|
||||
@@ -11,7 +11,6 @@ from models.audit_event import AuditCategory, AuditEvent, actions_in
|
||||
from models.device import Device
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
from utils.database import LIKE_ESCAPE_CHAR, escape_like
|
||||
|
||||
from .base_handler import DBBaseHandler, affected_rows
|
||||
|
||||
@@ -94,11 +93,10 @@ class DBAuditEventsHandler(DBBaseHandler):
|
||||
if filters.max_id is not None:
|
||||
clauses.append(AuditEvent.id <= filters.max_id)
|
||||
if filters.search:
|
||||
like = f"%{escape_like(filters.search.lower())}%"
|
||||
clauses.append(
|
||||
or_(
|
||||
*(
|
||||
func.lower(column).like(like, escape=LIKE_ESCAPE_CHAR)
|
||||
column.icontains(filters.search, autoescape=True)
|
||||
for column in (
|
||||
AuditEvent.actor_name,
|
||||
AuditEvent.target_name,
|
||||
|
||||
@@ -40,11 +40,12 @@ from sqlalchemy.orm import (
|
||||
selectinload,
|
||||
undefer,
|
||||
)
|
||||
from sqlalchemy.sql.elements import ClauseList, ColumnElement, UnaryExpression
|
||||
from sqlalchemy.sql.elements import ColumnElement, UnaryExpression
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
|
||||
from config.config_manager import config_manager as cm
|
||||
from decorators.database import INJECTED_SESSION, begin_session
|
||||
from exceptions.database_exceptions import RomFileOwnerChangedError
|
||||
from handler.database.rom_filters import (
|
||||
ROM_FILTER_SPECS,
|
||||
FilterKind,
|
||||
@@ -83,15 +84,18 @@ from models.rom import (
|
||||
)
|
||||
from utils import get_version
|
||||
from utils.database import (
|
||||
LIKE_ESCAPE_CHAR,
|
||||
ROMS_SEARCH_FULLTEXT_COLUMNS,
|
||||
SORTABLE_NULLABLE_ROM_COLUMNS,
|
||||
epoch_ms_in_ranges,
|
||||
escape_like,
|
||||
is_non_blank,
|
||||
release_day_ranges,
|
||||
rom_unset_flag_column,
|
||||
)
|
||||
from utils.fulltext import (
|
||||
FULLTEXT_TOKEN_REGEX,
|
||||
fulltext_settings,
|
||||
split_fulltext_words,
|
||||
)
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
from utils.sql_dialect import (
|
||||
Analyze,
|
||||
@@ -103,7 +107,7 @@ from utils.sql_dialect import (
|
||||
nulls_last,
|
||||
)
|
||||
|
||||
from .base_handler import DBBaseHandler, affected_rows
|
||||
from .base_handler import DBBaseHandler, affected_rows, sync_engine
|
||||
|
||||
type RomSelect = Select[tuple[Rom]]
|
||||
|
||||
@@ -162,12 +166,6 @@ RUFFLE_SUPPORTED_PLATFORMS = [
|
||||
UPS.BROWSER,
|
||||
]
|
||||
|
||||
# Used to remove native full-text SQL operators
|
||||
FULLTEXT_BOOLEAN_OPERATORS_REGEX = re.compile(r'[+\-~<>()"@*]')
|
||||
|
||||
# 3 is the default minimum size in InnoDB
|
||||
FULLTEXT_MIN_TOKEN_SIZE = 3
|
||||
|
||||
# A term reaches the hash columns only when it is hex of exactly a digest
|
||||
# length, so an ordinary name search builds no hash SQL at all. Hashes are
|
||||
# stored lowercase, which keeps the lookup an indexed equality.
|
||||
@@ -237,6 +235,12 @@ ROM_SEARCH_COLUMNS: tuple[QueryableAttribute[Any], ...] = tuple(
|
||||
)
|
||||
|
||||
|
||||
def _name_like(word: str) -> ColumnElement[bool]:
|
||||
return or_(
|
||||
*(column.icontains(word, autoescape=True) for column in ROM_SEARCH_COLUMNS)
|
||||
)
|
||||
|
||||
|
||||
def _fulltext_match(boolean_query: str) -> ColumnElement[Any]:
|
||||
"""A MariaDB/MySQL FULLTEXT match of the ROM's name, filename and aliases."""
|
||||
return fulltext_match(
|
||||
@@ -245,6 +249,15 @@ def _fulltext_match(boolean_query: str) -> ColumnElement[Any]:
|
||||
)
|
||||
|
||||
|
||||
def _search_relevance(phrases: Sequence[str]) -> ColumnElement[Any]:
|
||||
"""How well the ROM's name, filename or aliases hold the phrases, words in order."""
|
||||
holds_a_phrase = or_(*(_name_like(phrase) for phrase in phrases))
|
||||
return DialectCase(
|
||||
postgresql=case((holds_a_phrase, 1), else_=0),
|
||||
mysql=_fulltext_match(" ".join(f'"{phrase}"' for phrase in phrases)),
|
||||
)
|
||||
|
||||
|
||||
# Filter dropdowns read the narrow `roms_facets` mirror instead of `roms`,
|
||||
# whose rows carry the raw metadata blobs. Column order matches the unpacking
|
||||
# in `_collect_filter_values`.
|
||||
@@ -685,6 +698,39 @@ def _drop_filter_values_bump(session: Session) -> None:
|
||||
session.info.pop(FILTER_VALUES_BUMP_KEY, None)
|
||||
|
||||
|
||||
# Per-user cache invalidations queued by `_queue_user_cache_bumps`, keyed by
|
||||
# user id; they run once the transaction commits.
|
||||
USER_CACHE_BUMPS_KEY = "user_cache_bumps"
|
||||
|
||||
|
||||
@event.listens_for(Session, "after_commit")
|
||||
def _bump_user_caches_after_commit(session: Session) -> None:
|
||||
bumps: dict[int, set[str]] = session.info.pop(USER_CACHE_BUMPS_KEY, {})
|
||||
# No keys-set bookkeeping: entries under an old version become
|
||||
# unreachable and are reaped by the TTL or the next global bump.
|
||||
for uid, uid_flags in bumps.items():
|
||||
# The write is already durable, so a cache failure only logs; the
|
||||
# stale entry falls to the TTL.
|
||||
try:
|
||||
if "sort" in uid_flags:
|
||||
sync_cache.incr(_user_sort_version_key(uid))
|
||||
if "sib" in uid_flags:
|
||||
sync_cache.incr(_user_sibling_version_key(uid))
|
||||
if "feed" in uid_flags:
|
||||
# Imported here because the recommendation package reads
|
||||
# this module.
|
||||
from handler.recommendation import invalidate_cached_feed
|
||||
|
||||
invalidate_cached_feed(uid)
|
||||
except Exception:
|
||||
log.exception("Failed to bump user %s cache versions", uid)
|
||||
|
||||
|
||||
@event.listens_for(Session, "after_rollback")
|
||||
def _drop_user_cache_bumps(session: Session) -> None:
|
||||
session.info.pop(USER_CACHE_BUMPS_KEY, None)
|
||||
|
||||
|
||||
def _queue_user_cache_bumps(
|
||||
session: Session,
|
||||
user_id: int,
|
||||
@@ -696,47 +742,12 @@ def _queue_user_cache_bumps(
|
||||
"""Queues per-user cache invalidations for after this transaction
|
||||
commits, so a rollback bumps nothing and a concurrent reader cannot
|
||||
cache pre-commit rows under the new version."""
|
||||
bumps: dict[int, set[str]] = session.info.setdefault("user_cache_bumps", {})
|
||||
flags = bumps.setdefault(user_id, set())
|
||||
flags.update(
|
||||
bumps: dict[int, set[str]] = session.info.setdefault(USER_CACHE_BUMPS_KEY, {})
|
||||
bumps.setdefault(user_id, set()).update(
|
||||
flag
|
||||
for flag, queued in (("sort", sort_keys), ("sib", siblings), ("feed", feed))
|
||||
if queued
|
||||
)
|
||||
if "user_cache_bumps_armed" in session.info:
|
||||
return
|
||||
session.info["user_cache_bumps_armed"] = True
|
||||
|
||||
def _consume(ending_session: Session) -> dict[int, set[str]]:
|
||||
# Popping the state re-arms the next transaction on a reused session.
|
||||
ending_session.info.pop("user_cache_bumps_armed", None)
|
||||
bumps: dict[int, set[str]] = ending_session.info.pop("user_cache_bumps", {})
|
||||
return bumps
|
||||
|
||||
@event.listens_for(session, "after_commit", once=True)
|
||||
def _flush(_session: Session) -> None:
|
||||
# No keys-set bookkeeping: entries under an old version become
|
||||
# unreachable and are reaped by the TTL or the next global bump.
|
||||
for uid, uid_flags in _consume(_session).items():
|
||||
# The write is already durable, so a cache failure only logs;
|
||||
# the stale entry falls to the TTL.
|
||||
try:
|
||||
if "sort" in uid_flags:
|
||||
sync_cache.incr(_user_sort_version_key(uid))
|
||||
if "sib" in uid_flags:
|
||||
sync_cache.incr(_user_sibling_version_key(uid))
|
||||
if "feed" in uid_flags:
|
||||
# Imported here because the recommendation package reads
|
||||
# this module.
|
||||
from handler.recommendation import invalidate_cached_feed
|
||||
|
||||
invalidate_cached_feed(uid)
|
||||
except Exception:
|
||||
log.exception("Failed to bump user %s cache versions", uid)
|
||||
|
||||
@event.listens_for(session, "after_rollback", once=True)
|
||||
def _discard(_session: Session) -> None:
|
||||
_consume(_session)
|
||||
|
||||
|
||||
class DBRomsHandler(DBBaseHandler):
|
||||
@@ -1119,47 +1130,40 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
)
|
||||
|
||||
def _build_fulltext_boolean_query(self, term: str) -> str | None:
|
||||
words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split()
|
||||
if not words or any(len(word) < FULLTEXT_MIN_TOKEN_SIZE for word in words):
|
||||
return None
|
||||
return " ".join(f"+{word}*" for word in words)
|
||||
|
||||
def _build_fulltext_relevance(self, search_term: str) -> str | None:
|
||||
parts: list[str] = []
|
||||
def _build_search_phrases(self, search_term: str) -> list[str]:
|
||||
"""The multi-word terms of a search, which relevance ranks by."""
|
||||
phrases: list[str] = []
|
||||
for term in search_term.split("|"):
|
||||
words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split()
|
||||
words = FULLTEXT_TOKEN_REGEX.findall(term)
|
||||
if len(words) > 1:
|
||||
parts.append('"' + " ".join(words) + '"')
|
||||
return " ".join(parts) if parts else None
|
||||
phrases.append(" ".join(words))
|
||||
return phrases
|
||||
|
||||
def _build_name_conditions(self, terms: Sequence[str]) -> list[Any]:
|
||||
"""One condition per term, matching it against the ROM's name, filename and aliases."""
|
||||
# PostgreSQL's pg_trgm indexes serve the ILIKE; MariaDB and MySQL use
|
||||
# their FULLTEXT index unless a word is too short for it.
|
||||
like_conditions = [
|
||||
and_(
|
||||
*(
|
||||
or_(*(column.ilike(f"%{word}%") for column in ROM_SEARCH_COLUMNS))
|
||||
for word in term.split()
|
||||
settings = fulltext_settings(sync_engine)
|
||||
conditions: list[Any] = []
|
||||
for term in terms:
|
||||
words = term.split()
|
||||
likes = {word: _name_like(word) for word in words}
|
||||
like = and_(*likes.values())
|
||||
# Unreadable settings leave LIKE alone to decide.
|
||||
indexed, unindexed = (
|
||||
split_fulltext_words(words, settings) if settings else ([], words)
|
||||
)
|
||||
if not indexed:
|
||||
conditions.append(like)
|
||||
continue
|
||||
# PostgreSQL's pg_trgm indexes serve the ILIKE. On MariaDB and MySQL
|
||||
# FULLTEXT drives the query and LIKE checks the words it can't hold.
|
||||
match = _fulltext_match(" ".join(f"+{word}*" for word in indexed))
|
||||
conditions.append(
|
||||
DialectCase(
|
||||
postgresql=like,
|
||||
mysql=and_(match, *(likes[word] for word in unindexed)),
|
||||
)
|
||||
)
|
||||
for term in terms
|
||||
]
|
||||
boolean_queries = [
|
||||
query
|
||||
for term in terms
|
||||
if (query := self._build_fulltext_boolean_query(term)) is not None
|
||||
]
|
||||
if len(boolean_queries) < len(terms):
|
||||
return like_conditions
|
||||
|
||||
return [
|
||||
DialectCase(postgresql=like, mysql=_fulltext_match(boolean_query))
|
||||
for boolean_query, like in zip(
|
||||
boolean_queries, like_conditions, strict=True
|
||||
)
|
||||
]
|
||||
return conditions
|
||||
|
||||
def _build_hash_selects(self, terms: Iterable[str]) -> list[Select[tuple[int]]]:
|
||||
"""Id-yielding selects for terms shaped like a hash digest.
|
||||
@@ -1835,23 +1839,20 @@ class DBRomsHandler(DBBaseHandler):
|
||||
# mixed-direction pair forces a filesort.
|
||||
tiebreaker = Rom.id.desc() if descending else Rom.id.asc()
|
||||
|
||||
relevance = self._build_fulltext_relevance(search_term) if search_term else None
|
||||
if relevance:
|
||||
relevance_clause = _fulltext_match(relevance).desc()
|
||||
# Only the FULLTEXT engines rank: relevance breaks an explicit sort's
|
||||
# ties, or leads (with name breaking its ties) when no sort is picked.
|
||||
order_clause = DialectCase(
|
||||
postgresql=order_clause,
|
||||
mysql=(
|
||||
ClauseList(order_clause, relevance_clause)
|
||||
if order_by
|
||||
else ClauseList(relevance_clause, order_clause)
|
||||
),
|
||||
)
|
||||
sort_clauses: list[Any] = [order_clause]
|
||||
phrases = self._build_search_phrases(search_term) if search_term else []
|
||||
if phrases:
|
||||
# Relevance breaks an explicit sort's ties, or leads (with name
|
||||
# breaking its ties) when no sort is picked.
|
||||
relevance_clause = _search_relevance(phrases).desc()
|
||||
if order_by:
|
||||
sort_clauses.append(relevance_clause)
|
||||
else:
|
||||
sort_clauses.insert(0, relevance_clause)
|
||||
|
||||
return [
|
||||
clause
|
||||
for clause in (nulls_last_clause, order_clause, tiebreaker)
|
||||
for clause in (nulls_last_clause, *sort_clauses, tiebreaker)
|
||||
if clause is not None
|
||||
]
|
||||
|
||||
@@ -2446,18 +2447,46 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
return rom_user
|
||||
|
||||
def _lock_rom_row(self, rom_id: int, session: Session) -> None:
|
||||
"""Serialise writers of one rom's files so each size total counts the others'."""
|
||||
# Taken before the file write, whose foreign key check would otherwise
|
||||
# share-lock the row first and deadlock two writers on MariaDB.
|
||||
session.execute(
|
||||
select(Rom.id).where(Rom.id == rom_id).with_for_update(key_share=True)
|
||||
def _lock_rom_file_and_roms(
|
||||
self, rom_file_id: int, other_rom_ids: Iterable[int], session: Session
|
||||
) -> set[int] | None:
|
||||
"""Lock a file's owning rom and `other_rom_ids`, then the file row.
|
||||
|
||||
Returns:
|
||||
Every rom id locked, or None if the file does not exist.
|
||||
|
||||
Raises:
|
||||
RomFileOwnerChangedError: a concurrent move changed the owner first.
|
||||
"""
|
||||
# All rom locks go in one sorted batch before the file lock, the order
|
||||
# folder conversion writes in, so no two writers can wait on each other.
|
||||
owner = session.scalar(select(RomFile.rom_id).where(RomFile.id == rom_file_id))
|
||||
if owner is None:
|
||||
return None
|
||||
locked = {owner, *other_rom_ids}
|
||||
self._lock_rom_rows(locked, session)
|
||||
confirmed = session.scalar(
|
||||
select(RomFile.rom_id).where(RomFile.id == rom_file_id).with_for_update()
|
||||
)
|
||||
if confirmed is None:
|
||||
return None
|
||||
if confirmed not in locked:
|
||||
raise RomFileOwnerChangedError(rom_file_id)
|
||||
return locked
|
||||
|
||||
def _lock_rom_rows(self, rom_ids: Iterable[int], session: Session) -> None:
|
||||
"""Serialise writers of these roms' files so each size total counts the others'."""
|
||||
# Taken before the file write, whose foreign key check would otherwise
|
||||
# share-lock the row first; in id order so two moves cannot deadlock.
|
||||
for rom_id in sorted(set(rom_ids)):
|
||||
session.execute(
|
||||
select(Rom.id).where(Rom.id == rom_id).with_for_update(key_share=True)
|
||||
)
|
||||
|
||||
def _recompute_fs_size_bytes(self, rom_id: int, session: Session) -> None:
|
||||
"""Re-derive the size the gallery sorts on from the rom's file rows."""
|
||||
# Summed inside the UPDATE, which MariaDB reads with locks rather than
|
||||
# from the transaction snapshot; the caller holds `_lock_rom_row`.
|
||||
# from the transaction snapshot; the caller holds `_lock_rom_rows`.
|
||||
total = (
|
||||
select(func.coalesce(func.sum(RomFile.file_size_bytes), 0))
|
||||
.where(RomFile.rom_id == rom_id)
|
||||
@@ -2477,10 +2506,18 @@ class DBRomsHandler(DBBaseHandler):
|
||||
rom_file: RomFile,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> RomFile:
|
||||
self._lock_rom_row(rom_file.rom_id, session)
|
||||
rom_ids = (
|
||||
self._lock_rom_file_and_roms(rom_file.id, [rom_file.rom_id], session)
|
||||
if rom_file.id is not None
|
||||
else None
|
||||
)
|
||||
if rom_ids is None:
|
||||
rom_ids = {rom_file.rom_id}
|
||||
self._lock_rom_rows(rom_ids, session)
|
||||
merged = session.merge(rom_file)
|
||||
session.flush()
|
||||
self._recompute_fs_size_bytes(merged.rom_id, session)
|
||||
for rom_id in sorted(rom_ids):
|
||||
self._recompute_fs_size_bytes(rom_id, session)
|
||||
return merged
|
||||
|
||||
def _apply_scanned_rom_file(
|
||||
@@ -2716,13 +2753,10 @@ class DBRomsHandler(DBBaseHandler):
|
||||
data: dict[str, Any],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> RomFile | None:
|
||||
resized_rom_id = (
|
||||
session.scalar(select(RomFile.rom_id).where(RomFile.id == id))
|
||||
if "file_size_bytes" in data
|
||||
else None
|
||||
)
|
||||
if resized_rom_id is not None:
|
||||
self._lock_rom_row(resized_rom_id, session)
|
||||
rom_ids: set[int] = set()
|
||||
if data.keys() & {"file_size_bytes", "rom_id"}:
|
||||
new_owner = [data["rom_id"]] if "rom_id" in data else []
|
||||
rom_ids = self._lock_rom_file_and_roms(id, new_owner, session) or set()
|
||||
|
||||
session.execute(
|
||||
update(RomFile)
|
||||
@@ -2731,8 +2765,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
if resized_rom_id is not None:
|
||||
self._recompute_fs_size_bytes(resized_rom_id, session)
|
||||
for rom_id in sorted(rom_ids):
|
||||
self._recompute_fs_size_bytes(rom_id, session)
|
||||
return session.scalars(select(RomFile).filter_by(id=id)).one_or_none()
|
||||
|
||||
@begin_session
|
||||
@@ -2858,12 +2892,11 @@ class DBRomsHandler(DBBaseHandler):
|
||||
if rom_id is not None:
|
||||
clauses.append(Rom.id == rom_id)
|
||||
if search:
|
||||
like = f"%{escape_like(search.lower())}%"
|
||||
clauses.append(
|
||||
or_(
|
||||
func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
TrackMeta.title.icontains(search, autoescape=True),
|
||||
TrackMeta.artist.icontains(search, autoescape=True),
|
||||
TrackMeta.album.icontains(search, autoescape=True),
|
||||
)
|
||||
)
|
||||
if artist and exclude_field != "artist":
|
||||
@@ -3055,11 +3088,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
where.append(func.length(func.trim(col)) > 0)
|
||||
if search:
|
||||
target = cast(col, String) if field == "years" else col
|
||||
where.append(
|
||||
func.lower(target).like(
|
||||
f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR
|
||||
)
|
||||
)
|
||||
where.append(target.icontains(search, autoescape=True))
|
||||
count_col = func.count().label("count")
|
||||
base = (
|
||||
select(col.label("value"), count_col)
|
||||
@@ -3237,11 +3266,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
max_duration=max_duration,
|
||||
)
|
||||
if search:
|
||||
where.append(
|
||||
func.lower(Platform.name).like(
|
||||
f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR
|
||||
)
|
||||
)
|
||||
where.append(Platform.name.icontains(search, autoescape=True))
|
||||
count_col = func.count().label("count")
|
||||
base = self._music_facet_joins(
|
||||
select(
|
||||
@@ -3304,13 +3329,12 @@ class DBRomsHandler(DBBaseHandler):
|
||||
max_duration=max_duration,
|
||||
)
|
||||
if search:
|
||||
like = f"%{escape_like(search.lower())}%"
|
||||
where.append(
|
||||
or_(
|
||||
func.lower(Rom.name).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR),
|
||||
Rom.name.icontains(search, autoescape=True),
|
||||
TrackMeta.title.icontains(search, autoescape=True),
|
||||
TrackMeta.artist.icontains(search, autoescape=True),
|
||||
TrackMeta.album.icontains(search, autoescape=True),
|
||||
)
|
||||
)
|
||||
count_col = func.count().label("count")
|
||||
@@ -3350,16 +3374,16 @@ class DBRomsHandler(DBBaseHandler):
|
||||
id: int,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> None:
|
||||
rom_id = session.scalar(select(RomFile.rom_id).where(RomFile.id == id))
|
||||
if rom_id is None:
|
||||
rom_ids = self._lock_rom_file_and_roms(id, [], session)
|
||||
if rom_ids is None:
|
||||
return
|
||||
self._lock_rom_row(rom_id, session)
|
||||
session.execute(
|
||||
delete(RomFile)
|
||||
.where(RomFile.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
self._recompute_fs_size_bytes(rom_id, session)
|
||||
for rom_id in sorted(rom_ids):
|
||||
self._recompute_fs_size_bytes(rom_id, session)
|
||||
|
||||
# Note management methods
|
||||
def _rom_notes_query(
|
||||
@@ -3381,7 +3405,10 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
if search:
|
||||
query = query.filter(
|
||||
or_(RomNote.title.contains(search), RomNote.content.contains(search))
|
||||
or_(
|
||||
RomNote.title.contains(search, autoescape=True),
|
||||
RomNote.content.contains(search, autoescape=True),
|
||||
)
|
||||
)
|
||||
|
||||
if tags:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from enum import Enum
|
||||
from typing import Any, Final
|
||||
from typing import Any, Final, cast
|
||||
from uuid import uuid4
|
||||
|
||||
from redis import Redis
|
||||
@@ -74,11 +75,46 @@ def __get_sync_cache() -> Redis:
|
||||
return client
|
||||
|
||||
|
||||
def __get_async_cache() -> AsyncRedis:
|
||||
if IS_PYTEST_RUN:
|
||||
_LOOP_CLIENT_ATTR: Final = "_romm_fake_async_redis"
|
||||
|
||||
|
||||
class _PerLoopFakeAsyncRedis:
|
||||
"""A fake async client per event loop, or per thread outside one, over one fake server."""
|
||||
|
||||
# The TestClient's loop and a test's asyncio.run loop use the cache at once,
|
||||
# and an asyncio.Lock in a pool they share binds to just one of them.
|
||||
def __init__(self, server: Any) -> None:
|
||||
self._server = server
|
||||
self._by_thread = threading.local()
|
||||
|
||||
def _new_client(self) -> Any:
|
||||
from fakeredis import FakeAsyncRedis
|
||||
|
||||
return FakeAsyncRedis(server=_fake_server)
|
||||
return FakeAsyncRedis(server=self._server)
|
||||
|
||||
def _client(self) -> Any:
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
client = getattr(self._by_thread, "client", None)
|
||||
if client is None:
|
||||
client = self._by_thread.client = self._new_client()
|
||||
return client
|
||||
# Held on the loop, not in a map keyed by it: the client's asyncio
|
||||
# objects reference the loop, so such a map would never let one go.
|
||||
client = getattr(loop, _LOOP_CLIENT_ATTR, None)
|
||||
if client is None:
|
||||
client = self._new_client()
|
||||
setattr(loop, _LOOP_CLIENT_ATTR, client)
|
||||
return client
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._client(), name)
|
||||
|
||||
|
||||
def __get_async_cache() -> AsyncRedis:
|
||||
if IS_PYTEST_RUN:
|
||||
return cast(AsyncRedis, _PerLoopFakeAsyncRedis(_fake_server))
|
||||
|
||||
# A separate client that auto-decodes responses is needed
|
||||
client = AsyncRedis.from_url(REDIS_URL, decode_responses=True)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Author identity on the note responses, which no note row stores itself."""
|
||||
"""Note responses: author identity, deletion and search."""
|
||||
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -58,3 +58,25 @@ def test_delete_note_removes_it_once(client: TestClient, access_token: str, rom:
|
||||
# Nothing left to match, so the handler reports no rows deleted.
|
||||
again = client.delete(url, headers=_auth(access_token))
|
||||
assert again.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_note_search_matches_wildcards_literally(
|
||||
client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
for title in ("100% run", "1000 coins"):
|
||||
client.post(
|
||||
f"/api/roms/{rom.id}/notes",
|
||||
headers=_auth(access_token),
|
||||
json={"title": title, "content": "", "is_public": False},
|
||||
)
|
||||
|
||||
def search(term: str) -> list[str]:
|
||||
listed = client.get(
|
||||
f"/api/roms/{rom.id}/notes",
|
||||
headers=_auth(access_token),
|
||||
params={"search": term},
|
||||
)
|
||||
return sorted(n["title"] for n in listed.json())
|
||||
|
||||
assert search("100%") == ["100% run"]
|
||||
assert search("1_0") == []
|
||||
@@ -2,6 +2,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_audit_event_handler, db_user_handler
|
||||
@@ -189,6 +190,26 @@ class TestFilters:
|
||||
assert _ids(target) == [zelda.id]
|
||||
assert _ids(address) == [from_lan.id]
|
||||
|
||||
def test_search_matches_wildcards_literally(
|
||||
self, client: TestClient, access_token: str
|
||||
):
|
||||
full_run = _add(None, target_name="100% run")
|
||||
_add(None, target_name="1000 coins")
|
||||
|
||||
percent = client.get(
|
||||
"/api/audit-events",
|
||||
params={"search": "100%"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
underscore = client.get(
|
||||
"/api/audit-events",
|
||||
params={"search": "1_0"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(percent) == [full_run.id]
|
||||
assert _ids(underscore) == []
|
||||
|
||||
def test_pages_stay_pinned_to_max_id(self, client, access_token, admin_user):
|
||||
newest = _add(admin_user, minutes_ago=1)
|
||||
# Recorded after `newest` but happened before it, like a synced play.
|
||||
|
||||
@@ -296,6 +296,31 @@ def test_facet_years_typeahead(client: TestClient, access_token: str, music_libr
|
||||
assert {i["value"] for i in body["items"]} == {1991, 1992}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "key", "wildcard", "literal", "expected"),
|
||||
[
|
||||
("/api/music/artists", "value", "k_shiro", "oshi", {"Koshiro"}),
|
||||
("/api/music/years", "value", "19_1", "991", {1991}),
|
||||
("/api/music/platforms", "name", "g_nesis", "enes", {"genesis"}),
|
||||
("/api/music/games", "name", "s_nic", "oni", {"Sonic"}),
|
||||
],
|
||||
)
|
||||
def test_facet_search_matches_wildcards_literally(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
music_library: dict[str, Platform | Rom],
|
||||
path: str,
|
||||
key: str,
|
||||
wildcard: str,
|
||||
literal: str,
|
||||
expected: set[str | int],
|
||||
):
|
||||
wild = client.get(path, params={"search": wildcard}, headers=_auth(access_token))
|
||||
assert wild.json()["total"] == 0
|
||||
found = client.get(path, params={"search": literal}, headers=_auth(access_token))
|
||||
assert {i[key] for i in found.json()["items"]} == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", ["/api/roms", "/api/music/tracks", "/api/music/artists"]
|
||||
)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.engine import Dialect
|
||||
from tests.sql_dialects import MARIADB_DIALECT, POSTGRESQL_DIALECT, compile_sql
|
||||
|
||||
from handler.database import db_rom_handler, roms_handler
|
||||
from models.rom import Rom
|
||||
from utils.fulltext import DEFAULT_FULLTEXT_SETTINGS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dialect", "like_count", "has_match"),
|
||||
[(MARIADB_DIALECT, 3, True), (POSTGRESQL_DIALECT, 9, False)],
|
||||
)
|
||||
def test_search_keeps_the_fulltext_index_for_indexable_words(
|
||||
dialect: Dialect, like_count: int, has_match: bool
|
||||
):
|
||||
with patch.object(
|
||||
roms_handler, "fulltext_settings", return_value=DEFAULT_FULLTEXT_SETTINGS
|
||||
):
|
||||
query = db_rom_handler._filter_by_search_term(select(Rom.id), "final fantasy 7")
|
||||
|
||||
sql = compile_sql(query, dialect, literal_binds=True)
|
||||
|
||||
assert ("AGAINST ('+final* +fantasy*' IN BOOLEAN MODE)" in sql) is has_match
|
||||
# MariaDB checks only "7" by LIKE; PostgreSQL checks every word.
|
||||
assert sql.count("LIKE") == like_count
|
||||
|
||||
|
||||
def test_search_uses_like_alone_while_the_settings_are_unreadable():
|
||||
with patch.object(roms_handler, "fulltext_settings", return_value=None):
|
||||
query = db_rom_handler._filter_by_search_term(select(Rom.id), "final fantasy")
|
||||
|
||||
sql = compile_sql(query, MARIADB_DIALECT, literal_binds=True)
|
||||
|
||||
assert "+final*" not in sql
|
||||
assert sql.count("LIKE") == 6
|
||||
@@ -19,6 +19,7 @@ from tests.factories import make_rom, make_save, make_state
|
||||
from tests.sql_dialects import MARIADB_DIALECT, POSTGRESQL_DIALECT, compile_sql
|
||||
|
||||
from decorators.database import INJECTED_SESSION
|
||||
from exceptions.database_exceptions import RomFileOwnerChangedError
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.database.base_handler import sync_engine, sync_session
|
||||
from handler.database.roms_handler import _filter_values_cache_version
|
||||
@@ -673,6 +674,35 @@ class TestRomFileSizeTotal:
|
||||
|
||||
assert self._size(rom) == 1000
|
||||
|
||||
def test_moving_a_file_updates_both_roms(self, rom: Rom, second_rom: Rom):
|
||||
_add_rom_file(rom, "game.bin", 1000, RomFileCategory.GAME)
|
||||
manual = _add_rom_file(rom, "manual.pdf", 200, RomFileCategory.MANUAL)
|
||||
|
||||
db_rom_handler.update_rom_file(manual.id, {"rom_id": second_rom.id})
|
||||
|
||||
assert self._size(rom) == 1000
|
||||
assert self._size(second_rom) == 200
|
||||
|
||||
def test_merging_a_file_under_another_rom_updates_both(
|
||||
self, rom: Rom, second_rom: Rom
|
||||
):
|
||||
_add_rom_file(rom, "game.bin", 1000, RomFileCategory.GAME)
|
||||
manual = _add_rom_file(rom, "manual.pdf", 200, RomFileCategory.MANUAL)
|
||||
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
id=manual.id,
|
||||
rom_id=second_rom.id,
|
||||
file_name=manual.file_name,
|
||||
file_path=second_rom.fs_path,
|
||||
file_size_bytes=manual.file_size_bytes,
|
||||
category=manual.category,
|
||||
)
|
||||
)
|
||||
|
||||
assert self._size(rom) == 1000
|
||||
assert self._size(second_rom) == 200
|
||||
|
||||
|
||||
class TestRomFileSizeSidecarInvalidation:
|
||||
"""The size-sorted rom-id and char indexes are cached under the filter
|
||||
@@ -787,6 +817,53 @@ class TestRomFileSizeLocking:
|
||||
|
||||
self._assert_locked_before(statements, "UPDATE rom_files")
|
||||
|
||||
def test_move_locks_its_roms_before_the_file(
|
||||
self, rom: Rom, second_rom: Rom, statements: list[str]
|
||||
):
|
||||
# Folder conversion writes the rom row before its file rows, so file
|
||||
# writes lock in the same order.
|
||||
game = _add_rom_file(rom)
|
||||
statements.clear()
|
||||
|
||||
db_rom_handler.update_rom_file(game.id, {"rom_id": second_rom.id})
|
||||
|
||||
file_lock = next(
|
||||
i
|
||||
for i, s in enumerate(statements)
|
||||
if s.startswith("SELECT rom_files.rom_id") and s.endswith("FOR UPDATE")
|
||||
)
|
||||
rom_locks = [
|
||||
i
|
||||
for i, s in enumerate(statements)
|
||||
if s.startswith("SELECT roms.id") and re.search(r"FOR (NO KEY )?UPDATE$", s)
|
||||
]
|
||||
assert len(rom_locks) == 2
|
||||
assert max(rom_locks) < file_lock
|
||||
|
||||
def test_an_owner_changed_meanwhile_fails_the_write(self):
|
||||
session = MagicMock()
|
||||
# The file moved from rom 1 to rom 2 before this transaction locked rom 1.
|
||||
session.scalar.side_effect = [1, 2]
|
||||
|
||||
with pytest.raises(RomFileOwnerChangedError):
|
||||
db_rom_handler._lock_rom_file_and_roms(10, [3], session)
|
||||
|
||||
def test_a_move_into_a_locked_rom_needs_no_more_locks(self):
|
||||
session = MagicMock()
|
||||
session.scalar.side_effect = [1, 3]
|
||||
|
||||
locked = db_rom_handler._lock_rom_file_and_roms(10, [3], session)
|
||||
|
||||
assert locked == {1, 3}
|
||||
assert session.execute.call_count == 2
|
||||
|
||||
def test_a_vanished_file_locks_nothing_more(self):
|
||||
session = MagicMock()
|
||||
session.scalar.side_effect = [None]
|
||||
|
||||
assert db_rom_handler._lock_rom_file_and_roms(10, [3], session) is None
|
||||
session.execute.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dialect", "clause"),
|
||||
[(MARIADB_DIALECT, "FOR UPDATE"), (POSTGRESQL_DIALECT, "FOR NO KEY UPDATE")],
|
||||
@@ -795,7 +872,20 @@ class TestRomFileSizeLocking:
|
||||
# NO KEY UPDATE leaves other tables' foreign key checks on the row free.
|
||||
session = MagicMock()
|
||||
|
||||
db_rom_handler._lock_rom_row(7, session)
|
||||
db_rom_handler._lock_rom_rows([7], session)
|
||||
|
||||
(statement,) = session.execute.call_args.args
|
||||
assert compile_sql(statement, dialect).endswith(clause)
|
||||
|
||||
def test_move_locks_both_roms_in_id_order(self, rom: Rom, second_rom: Rom):
|
||||
# Two opposite moves take the locks in the same order, so they cannot
|
||||
# deadlock.
|
||||
session = MagicMock()
|
||||
|
||||
db_rom_handler._lock_rom_rows([second_rom.id, rom.id, second_rom.id], session)
|
||||
|
||||
locked = [
|
||||
call.args[0].compile().params["id_1"]
|
||||
for call in session.execute.call_args_list
|
||||
]
|
||||
assert locked == sorted({rom.id, second_rom.id})
|
||||
@@ -148,19 +148,21 @@ class TestMetadataSortQueryShape:
|
||||
(
|
||||
POSTGRESQL_DIALECT,
|
||||
"asc",
|
||||
"roms.generated_player_count ASC NULLS LAST, roms.id ASC",
|
||||
"roms.generated_player_count ASC NULLS LAST, "
|
||||
"CASE WHEN ((roms.name ILIKE",
|
||||
),
|
||||
(
|
||||
POSTGRESQL_DIALECT,
|
||||
"desc",
|
||||
"roms.generated_player_count DESC NULLS LAST, roms.id DESC",
|
||||
"roms.generated_player_count DESC NULLS LAST, "
|
||||
"CASE WHEN ((roms.name ILIKE",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_search_relevance_follows_the_null_placement_terms(
|
||||
self, dialect: sa.Dialect, order_dir: str, expected: str
|
||||
):
|
||||
"""Relevance only ranks on the FULLTEXT engines, after the explicit sort."""
|
||||
"""Relevance ranks after the explicit sort, on every engine."""
|
||||
query, _ = db_rom_handler.get_roms_query(
|
||||
order_by="player_count", order_dir=order_dir, search_term="final fantasy"
|
||||
)
|
||||
|
||||
@@ -7,7 +7,6 @@ from sqlalchemy import inspect as sa_inspect
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from tests.factories import make_rom, make_save, make_screenshot, make_state
|
||||
|
||||
from config import ROMM_DB_DRIVER
|
||||
from handler.auth import auth_handler
|
||||
from handler.database import (
|
||||
db_platform_handler,
|
||||
@@ -232,20 +231,19 @@ def test_filter_by_search_term_multi_word_and_ranking(platform: Platform):
|
||||
# Only titles containing BOTH words appear (AND semantics).
|
||||
assert set(result_ids) == {ff.id, ff7.id, fantasy_final.id}
|
||||
|
||||
# Relevance ordering uses MATCH ... AGAINST, which only runs on
|
||||
# MySQL/MariaDB; PostgreSQL falls back to name ordering, so the
|
||||
# phrase-ranking assertions only hold on those drivers.
|
||||
if ROMM_DB_DRIVER in ("mariadb", "mysql"):
|
||||
# Exact-order phrase matches rank above the reversed-order match.
|
||||
assert result_ids.index(ff.id) < result_ids.index(fantasy_final.id)
|
||||
assert result_ids.index(ff7.id) < result_ids.index(fantasy_final.id)
|
||||
# Exact-order phrase matches rank above the reversed-order match.
|
||||
assert result_ids.index(ff.id) < result_ids.index(fantasy_final.id)
|
||||
assert result_ids.index(ff7.id) < result_ids.index(fantasy_final.id)
|
||||
|
||||
# The relevance ORDER BY must also survive the group_by_meta_id subquery
|
||||
# wrapping used by the gallery (each ROM here is its own group).
|
||||
grouped = db_rom_handler.get_roms_scalar(
|
||||
search_term="final fantasy", group_by_meta_id=True
|
||||
)
|
||||
assert {r.id for r in grouped} == {ff.id, ff7.id, fantasy_final.id}
|
||||
grouped_ids = [r.id for r in grouped]
|
||||
assert set(grouped_ids) == {ff.id, ff7.id, fantasy_final.id}
|
||||
assert grouped_ids.index(ff.id) < grouped_ids.index(fantasy_final.id)
|
||||
assert grouped_ids.index(ff7.id) < grouped_ids.index(fantasy_final.id)
|
||||
|
||||
# An explicit sort takes priority over relevance: ordering by name asc puts
|
||||
# "Fantasy Final" first (relevance is only the tiebreaker here).
|
||||
@@ -256,6 +254,41 @@ def test_filter_by_search_term_multi_word_and_ranking(platform: Platform):
|
||||
assert explicit_ids.index(fantasy_final.id) < explicit_ids.index(ff.id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("search_term", "expected"),
|
||||
[
|
||||
# "7" is too short for the FULLTEXT index.
|
||||
("final fantasy 7", {"Final Fantasy 7"}),
|
||||
# "the" is an InnoDB stopword, "of" both short and a stopword.
|
||||
("the legend zelda", {"The Legend of Zelda"}),
|
||||
("legend of zelda", {"The Legend of Zelda"}),
|
||||
# No word the index holds, so LIKE alone decides.
|
||||
("x-2", {"Final Fantasy X-2"}),
|
||||
# The index holds "dr." as "dr", too short to require.
|
||||
("dr. mario", {"Dr. Mario"}),
|
||||
# `_` is literal, not a LIKE wildcard.
|
||||
("x_2", set()),
|
||||
],
|
||||
)
|
||||
def test_filter_by_search_term_words_fulltext_cannot_index(
|
||||
platform: Platform, search_term: str, expected: set[str]
|
||||
):
|
||||
for name in (
|
||||
"Final Fantasy 7",
|
||||
"Final Fantasy X-2",
|
||||
"Final Fantasy",
|
||||
"Dr. Mario",
|
||||
"The Legend of Zelda",
|
||||
"Zelda II The Adventure of Link",
|
||||
):
|
||||
# Spaced like a real dump, so the filename splits into the same words.
|
||||
make_rom(platform, name, fs_stem=f"{name} (USA)")
|
||||
|
||||
results = db_rom_handler.get_roms_scalar(search_term=search_term)
|
||||
|
||||
assert {r.name for r in results} == expected
|
||||
|
||||
|
||||
def test_sibling_roms_empty_fs_name_no_tags_not_matched(platform: Platform):
|
||||
"""ROMs with empty fs_name_no_tags should NOT be matched as siblings.
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -6,6 +9,7 @@ from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobEr
|
||||
from rq.job import Job, JobStatus
|
||||
|
||||
from handler.redis_handler import (
|
||||
async_cache,
|
||||
cancel_job,
|
||||
get_job_func_name,
|
||||
get_job_kwargs,
|
||||
@@ -147,3 +151,34 @@ class TestHasLiveWorker:
|
||||
assert has_live_worker(low_prio_queue) is expected
|
||||
|
||||
mock_all.assert_called_once_with(queue=low_prio_queue)
|
||||
|
||||
|
||||
class TestAsyncCacheUnderTests:
|
||||
def test_concurrent_threads_and_loops_never_share_a_pool(self):
|
||||
"""The TestClient's loop and a test's asyncio.run overlap across threads."""
|
||||
|
||||
async def running_loop_pool() -> Any:
|
||||
return async_cache.connection_pool
|
||||
|
||||
pools: dict[str, Any] = {}
|
||||
|
||||
def other_thread() -> None:
|
||||
pools["other thread, no loop"] = async_cache.connection_pool
|
||||
pools["other thread, in a loop"] = asyncio.run(running_loop_pool())
|
||||
|
||||
thread = threading.Thread(target=other_thread)
|
||||
thread.start()
|
||||
thread.join()
|
||||
pools["this thread, no loop"] = async_cache.connection_pool
|
||||
pools["this thread, in a loop"] = asyncio.run(running_loop_pool())
|
||||
|
||||
assert len({id(pool) for pool in pools.values()}) == len(pools)
|
||||
|
||||
def test_every_client_reads_the_one_keyspace(self):
|
||||
async def read() -> Any:
|
||||
return await async_cache.get("per-loop")
|
||||
|
||||
asyncio.run(async_cache.set("per-loop", "1"))
|
||||
value = asyncio.run(read())
|
||||
|
||||
assert value in ("1", b"1")
|
||||
@@ -0,0 +1,146 @@
|
||||
from collections.abc import Iterator
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from handler.database.base_handler import sync_engine
|
||||
from utils import fulltext
|
||||
from utils.database import is_postgresql
|
||||
from utils.fulltext import (
|
||||
DEFAULT_FULLTEXT_SETTINGS,
|
||||
FulltextSettings,
|
||||
fulltext_settings,
|
||||
read_fulltext_settings,
|
||||
split_fulltext_words,
|
||||
)
|
||||
|
||||
IS_FULLTEXT_ENGINE = not is_postgresql(sync_engine)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_settings() -> Iterator[None]:
|
||||
fulltext._server_fulltext_settings.cache_clear()
|
||||
yield
|
||||
fulltext._server_fulltext_settings.cache_clear()
|
||||
|
||||
|
||||
def _conn_reporting(
|
||||
min_token_size: int = 3,
|
||||
*,
|
||||
stopwords_enabled: bool = True,
|
||||
user_table: str | None = None,
|
||||
server_table: str | None = None,
|
||||
) -> MagicMock:
|
||||
conn = MagicMock()
|
||||
conn.execute.return_value.one.return_value = (
|
||||
min_token_size,
|
||||
84,
|
||||
int(stopwords_enabled),
|
||||
user_table,
|
||||
server_table,
|
||||
)
|
||||
conn.scalars.return_value = ["Foo", "bar", None]
|
||||
return conn
|
||||
|
||||
|
||||
def _engine_connecting(conn: MagicMock) -> MagicMock:
|
||||
engine = MagicMock()
|
||||
engine.engine.name = "mariadb"
|
||||
engine.connect.return_value.__enter__.return_value = conn
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.mark.skipif(not IS_FULLTEXT_ENGINE, reason="InnoDB full-text only")
|
||||
def test_reads_the_servers_settings():
|
||||
with sync_engine.connect() as conn:
|
||||
min_token_size = conn.execute(
|
||||
text("SELECT @@innodb_ft_min_token_size")
|
||||
).scalar_one()
|
||||
settings = read_fulltext_settings(conn)
|
||||
|
||||
assert settings.min_token_size == min_token_size
|
||||
assert "the" in settings.stopwords
|
||||
|
||||
|
||||
@pytest.mark.skipif(IS_FULLTEXT_ENGINE, reason="PostgreSQL has no FULLTEXT index")
|
||||
def test_postgresql_uses_the_defaults():
|
||||
assert fulltext_settings(sync_engine) == DEFAULT_FULLTEXT_SETTINGS
|
||||
|
||||
|
||||
def test_skips_fulltext_and_retries_when_the_server_is_unreachable():
|
||||
engine = _engine_connecting(MagicMock())
|
||||
engine.connect.side_effect = OperationalError("SELECT", {}, Exception("2013"))
|
||||
|
||||
assert fulltext_settings(engine) is None
|
||||
assert fulltext_settings(engine) is None
|
||||
|
||||
assert engine.connect.call_count == 2
|
||||
|
||||
|
||||
def test_keeps_the_token_sizes_when_the_stopwords_are_unreadable():
|
||||
conn = _conn_reporting(4)
|
||||
conn.scalars.side_effect = OperationalError("SELECT", {}, Exception("1227"))
|
||||
|
||||
assert read_fulltext_settings(conn) == DEFAULT_FULLTEXT_SETTINGS._replace(
|
||||
min_token_size=4
|
||||
)
|
||||
|
||||
|
||||
def test_reads_a_custom_stopword_table():
|
||||
conn = _conn_reporting(2, server_table="romm/stopwords")
|
||||
|
||||
settings = read_fulltext_settings(conn)
|
||||
|
||||
query = conn.scalars.call_args.args[0]
|
||||
assert "FROM romm.stopwords" in str(query)
|
||||
assert settings == FulltextSettings(2, 84, frozenset({"foo", "bar"}))
|
||||
|
||||
|
||||
def test_prefers_the_user_stopword_table():
|
||||
conn = _conn_reporting(user_table="romm/mine", server_table="romm/stopwords")
|
||||
|
||||
read_fulltext_settings(conn)
|
||||
|
||||
assert "FROM romm.mine" in str(conn.scalars.call_args.args[0])
|
||||
|
||||
|
||||
def test_unreadable_custom_stopwords_skip_fulltext_and_retry():
|
||||
conn = _conn_reporting(server_table="romm/stopwords")
|
||||
conn.scalars.side_effect = OperationalError("SELECT", {}, Exception("1142"))
|
||||
|
||||
engine = _engine_connecting(conn)
|
||||
|
||||
assert fulltext_settings(engine) is None
|
||||
assert fulltext_settings(engine) is None
|
||||
assert conn.scalars.call_count == 2
|
||||
|
||||
|
||||
def test_disabled_stopwords_leave_none():
|
||||
conn = _conn_reporting(stopwords_enabled=False)
|
||||
|
||||
assert read_fulltext_settings(conn) == FulltextSettings(3, 84, frozenset())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("term", "expected"),
|
||||
[
|
||||
("final fantasy 7", (["final", "fantasy"], ["7"])),
|
||||
("the legend", (["legend"], ["the"])),
|
||||
# InnoDB reads "dr." as the 2-letter token "dr".
|
||||
("dr. mario", (["mario"], ["dr."])),
|
||||
("pokemon: red", (["pokemon", "red"], [])),
|
||||
("spider-man x-2", (["spider", "man"], ["x-2"])),
|
||||
("mario's", (["mario's"], [])),
|
||||
("a" * 85, ([], ["a" * 85])),
|
||||
],
|
||||
)
|
||||
def test_split_fulltext_words(term: str, expected: tuple[list[str], list[str]]):
|
||||
assert split_fulltext_words(term.split(), DEFAULT_FULLTEXT_SETTINGS) == expected
|
||||
|
||||
|
||||
def test_split_fulltext_words_follows_the_token_size():
|
||||
settings = DEFAULT_FULLTEXT_SETTINGS._replace(min_token_size=2)
|
||||
|
||||
assert split_fulltext_words(["ff", "of"], settings) == (["ff"], ["of"])
|
||||
@@ -22,6 +22,7 @@ import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
@@ -830,19 +831,23 @@ def main() -> int:
|
||||
|
||||
from handler.auth import auth_handler
|
||||
from handler.database.base_handler import sync_engine
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# Pin every connection to UTC so the random historical timestamps we
|
||||
# generate never land in a local DST gap that TIMESTAMP columns reject.
|
||||
postgresql = is_postgresql(sync_engine)
|
||||
|
||||
@event.listens_for(sync_engine, "connect")
|
||||
def _session_utc(dbapi_conn: DBAPIConnection, _record: ConnectionPoolEntry) -> None:
|
||||
cur = dbapi_conn.cursor()
|
||||
try:
|
||||
try:
|
||||
cur.execute("SET time_zone = '+00:00'") # MySQL/MariaDB
|
||||
except Exception:
|
||||
cur.execute("SET TIME ZONE 'UTC'") # PostgreSQL
|
||||
cur.execute(
|
||||
"SET TIME ZONE 'UTC'" if postgresql else "SET time_zone = '+00:00'"
|
||||
)
|
||||
finally:
|
||||
cur.close()
|
||||
# PostgreSQL's SET is transactional: the pool's rollback on return would undo it.
|
||||
dbapi_conn.commit()
|
||||
|
||||
pw_hash = auth_handler.get_password_hash(args.password)
|
||||
|
||||
@@ -1028,6 +1033,8 @@ def main() -> int:
|
||||
bulk_insert(conn, Device, device_rows)
|
||||
bulk_insert(conn, ClientToken, token_rows)
|
||||
bulk_insert(conn, Firmware, firmware_rows)
|
||||
if postgresql:
|
||||
_advance_sequences(conn, (Platform, User, ClientToken, Firmware))
|
||||
counts["platforms"] = len(platform_rows)
|
||||
counts["users"] = len(user_rows)
|
||||
counts["devices"] = len(device_rows)
|
||||
@@ -1447,6 +1454,10 @@ def main() -> int:
|
||||
bulk_insert(conn, Screenshot, shot_rows)
|
||||
bulk_insert(conn, RomNote, note_rows)
|
||||
bulk_insert(conn, DeviceSaveSync, dss_rows)
|
||||
if postgresql:
|
||||
_advance_sequences(
|
||||
conn, (Rom, RomFile, RomUser, Save, State, Screenshot, RomNote)
|
||||
)
|
||||
|
||||
counts["roms"] += len(rom_rows)
|
||||
counts["rom_files"] += len(file_rows)
|
||||
@@ -1576,6 +1587,10 @@ def main() -> int:
|
||||
bulk_insert(conn, SmartCollection, smart_rows)
|
||||
bulk_insert(conn, SyncSession, sync_rows)
|
||||
bulk_insert(conn, PlaySession, play_rows)
|
||||
if postgresql:
|
||||
_advance_sequences(
|
||||
conn, (Collection, SmartCollection, SyncSession, PlaySession)
|
||||
)
|
||||
counts["collections"] = len(coll_rows)
|
||||
counts["collections_roms"] = len(coll_rom_rows)
|
||||
counts["smart_collections"] = len(smart_rows)
|
||||
@@ -1597,6 +1612,26 @@ def main() -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _advance_sequences(conn: Connection, models: Iterable[type[BaseModel]]) -> None:
|
||||
"""Move each PostgreSQL id sequence past the explicit ids inserted here."""
|
||||
# Unlike AUTO_INCREMENT, a sequence ignores explicit ids. The sequence's own
|
||||
# last value keeps this from moving it back past ids the app already drew.
|
||||
from sqlalchemy import text
|
||||
|
||||
for model in models:
|
||||
t = model.__tablename__
|
||||
# nosec B608 - table names come from the script's own models, not user input
|
||||
conn.execute(
|
||||
text(
|
||||
"SELECT setval(s.seq, GREATEST(" # nosec B608
|
||||
f"(SELECT COALESCE(MAX(id), 0) FROM {t}),"
|
||||
" COALESCE(pg_sequence_last_value(s.seq), 0)) + 1, false)"
|
||||
f" FROM (SELECT CAST(pg_get_serial_sequence('{t}', 'id') AS regclass)"
|
||||
" AS seq) AS s"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _wipe(conn: Connection) -> None:
|
||||
"""Delete all rows from the tables this script populates (FK-safe order)."""
|
||||
from sqlalchemy import text
|
||||
|
||||
@@ -317,18 +317,6 @@ def epoch_ms_in_ranges(
|
||||
)
|
||||
|
||||
|
||||
LIKE_ESCAPE_CHAR = "\\"
|
||||
|
||||
|
||||
def escape_like(term: str) -> str:
|
||||
"""Escape LIKE wildcards so a search term matches literally (pass escape=LIKE_ESCAPE_CHAR to like())."""
|
||||
return (
|
||||
term.replace(LIKE_ESCAPE_CHAR, LIKE_ESCAPE_CHAR * 2)
|
||||
.replace("%", f"{LIKE_ESCAPE_CHAR}%")
|
||||
.replace("_", f"{LIKE_ESCAPE_CHAR}_")
|
||||
)
|
||||
|
||||
|
||||
def safe_str_to_bool(value: Any, default: bool = False) -> bool:
|
||||
"""Safely convert a value to bool, returning default if conversion fails."""
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""InnoDB's full-text settings, and how its parser splits search words."""
|
||||
|
||||
import functools
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from typing import NamedTuple
|
||||
|
||||
from sqlalchemy import Connection, Engine, String
|
||||
from sqlalchemy import column as sql_column
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import table as sql_table
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from logger.logger import log
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# The tokens InnoDB's parser reads out of a word: "dr." holds only "dr".
|
||||
FULLTEXT_TOKEN_REGEX = re.compile(r"\w+(?:'\w+)*")
|
||||
|
||||
|
||||
class FulltextSettings(NamedTuple):
|
||||
min_token_size: int
|
||||
max_token_size: int
|
||||
stopwords: frozenset[str]
|
||||
|
||||
|
||||
# InnoDB's defaults, for what the server won't report. The index skips
|
||||
# stopwords, so a required `+the*` would match nothing.
|
||||
DEFAULT_FULLTEXT_SETTINGS = FulltextSettings(
|
||||
min_token_size=3,
|
||||
max_token_size=84,
|
||||
stopwords=frozenset(
|
||||
"a about an are as at be by com de en for from how i in is it la of on or"
|
||||
" that the this to und was what when where who will with www".split()
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def read_fulltext_settings(conn: Connection) -> FulltextSettings:
|
||||
"""The server's InnoDB full-text settings; raises if they can't be read."""
|
||||
min_size, max_size, stopwords_enabled, user_table, server_table = conn.execute(
|
||||
text(
|
||||
"SELECT @@innodb_ft_min_token_size, @@innodb_ft_max_token_size,"
|
||||
" @@innodb_ft_enable_stopword, @@innodb_ft_user_stopword_table,"
|
||||
" @@innodb_ft_server_stopword_table"
|
||||
)
|
||||
).one()
|
||||
stopwords: frozenset[str] = frozenset()
|
||||
if stopwords_enabled:
|
||||
custom_table = user_table or server_table
|
||||
schema, _, name = (
|
||||
custom_table or "information_schema/INNODB_FT_DEFAULT_STOPWORD"
|
||||
).rpartition("/")
|
||||
query = select(sql_column("value", String)).select_from(
|
||||
sql_table(name, schema=schema or None)
|
||||
)
|
||||
try:
|
||||
stopwords = frozenset(word.lower() for word in conn.scalars(query) if word)
|
||||
except SQLAlchemyError as exc:
|
||||
if custom_table:
|
||||
raise
|
||||
# MySQL needs PROCESS for INNODB_FT_DEFAULT_STOPWORD, which holds these.
|
||||
log.warning(f"Using InnoDB's default full-text stopwords: {exc}")
|
||||
stopwords = DEFAULT_FULLTEXT_SETTINGS.stopwords
|
||||
return FulltextSettings(int(min_size), int(max_size), stopwords)
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _server_fulltext_settings(engine: Engine) -> FulltextSettings:
|
||||
with engine.connect() as conn:
|
||||
return read_fulltext_settings(conn)
|
||||
|
||||
|
||||
def fulltext_settings(engine: Engine) -> FulltextSettings | None:
|
||||
"""The server's InnoDB full-text settings, or None while they can't be read."""
|
||||
if is_postgresql(engine):
|
||||
return DEFAULT_FULLTEXT_SETTINGS
|
||||
try:
|
||||
return _server_fulltext_settings(engine)
|
||||
except SQLAlchemyError as exc:
|
||||
# Left uncached, so a transient failure is retried on the next search.
|
||||
log.warning(f"Can't read the full-text settings: {exc}")
|
||||
return None
|
||||
|
||||
|
||||
def split_fulltext_words(
|
||||
words: Iterable[str], settings: FulltextSettings
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Words as (tokens a FULLTEXT index holds, words it can't hold)."""
|
||||
indexed: list[str] = []
|
||||
unindexed: list[str] = []
|
||||
for word in words:
|
||||
tokens = FULLTEXT_TOKEN_REGEX.findall(word)
|
||||
if tokens and all(
|
||||
settings.min_token_size <= len(token) <= settings.max_token_size
|
||||
and token.lower() not in settings.stopwords
|
||||
for token in tokens
|
||||
):
|
||||
indexed.extend(tokens)
|
||||
else:
|
||||
unindexed.append(word)
|
||||
return indexed, unindexed
|
||||
@@ -439,6 +439,10 @@ Query SQL that differs between engines lives in `utils/sql_dialect.py`
|
||||
(`DialectCase` and the helpers built on it), which picks each engine's spelling
|
||||
when the statement compiles. Handlers don't branch on `ROMM_DB_DRIVER`.
|
||||
|
||||
`utils/fulltext.py` reads InnoDB's full-text token sizes and stopwords from the
|
||||
server and splits search words the way its parser does, so a search can require
|
||||
the words a FULLTEXT index holds and check the rest with `LIKE`.
|
||||
|
||||
### Engine & Session Setup
|
||||
|
||||
**Location:** `handler/database/base_handler.py`
|
||||
|
||||
@@ -117,7 +117,7 @@ watch(
|
||||
|
||||
<template>
|
||||
<v-app id="application" :class="{ 'mouse-hidden': consoleMode && mouseIdle }">
|
||||
<v-main id="main" class="no-transition">
|
||||
<v-main id="main" class="no-transition" :tag="isV2 ? 'div' : 'main'">
|
||||
<router-view v-if="!isV2" v-slot="{ Component }">
|
||||
<component :is="Component" />
|
||||
<!-- Fade out the app loading logo -->
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Всички игри са заредени",
|
||||
"back-to-top": "Към началото",
|
||||
"column-actions": "Действия",
|
||||
"column-cover": "Корица",
|
||||
"filters": "Филтри",
|
||||
"firmware-files-count": "{count} файла",
|
||||
"firmware-selected-count": "{count} избрани",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Všechny hry byly načteny",
|
||||
"back-to-top": "Zpět nahoru",
|
||||
"column-actions": "Akce",
|
||||
"column-cover": "Obal",
|
||||
"filters": "Filtry",
|
||||
"firmware-files-count": "{count} souborů",
|
||||
"firmware-selected-count": "{count} vybráno",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Alle Spiele wurden geladen",
|
||||
"back-to-top": "Nach oben",
|
||||
"column-actions": "Aktionen",
|
||||
"column-cover": "Cover",
|
||||
"filters": "Filter",
|
||||
"firmware-files-count": "{count} Dateien",
|
||||
"firmware-selected-count": "{count} ausgewählt",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "All games have been loaded",
|
||||
"back-to-top": "Back to top",
|
||||
"column-actions": "Actions",
|
||||
"column-cover": "Cover",
|
||||
"filters": "Filters",
|
||||
"firmware-files-count": "{count} files",
|
||||
"firmware-selected-count": "{count} selected",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "All games have been loaded",
|
||||
"back-to-top": "Back to top",
|
||||
"column-actions": "Actions",
|
||||
"column-cover": "Cover",
|
||||
"filters": "Filters",
|
||||
"firmware-files-count": "{count} files",
|
||||
"firmware-selected-count": "{count} selected",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Todos los juegos han sido cargados",
|
||||
"back-to-top": "Volver arriba",
|
||||
"column-actions": "Acciones",
|
||||
"column-cover": "Portada",
|
||||
"filters": "Filtros",
|
||||
"firmware-files-count": "{count} archivos",
|
||||
"firmware-selected-count": "{count} seleccionados",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Tous les jeux ont été chargés",
|
||||
"back-to-top": "Retour en haut",
|
||||
"column-actions": "Actions",
|
||||
"column-cover": "Jaquette",
|
||||
"filters": "Filtres",
|
||||
"firmware-files-count": "{count} fichiers",
|
||||
"firmware-selected-count": "{count} sélectionné(s)",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Minden játék betöltődött",
|
||||
"back-to-top": "Vissza a tetejére",
|
||||
"column-actions": "Műveletek",
|
||||
"column-cover": "Borító",
|
||||
"filters": "Szűrők",
|
||||
"firmware-files-count": "{count} fájl",
|
||||
"firmware-selected-count": "{count} kiválasztva",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Tutti i giochi sono stati caricati",
|
||||
"back-to-top": "Torna su",
|
||||
"column-actions": "Azioni",
|
||||
"column-cover": "Copertina",
|
||||
"filters": "Filtri",
|
||||
"firmware-files-count": "{count} file",
|
||||
"firmware-selected-count": "{count} selezionati",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "すべてのゲームが読み込まれました",
|
||||
"back-to-top": "トップへ戻る",
|
||||
"column-actions": "操作",
|
||||
"column-cover": "カバー",
|
||||
"filters": "フィルタ",
|
||||
"firmware-files-count": "{count}件のファイル",
|
||||
"firmware-selected-count": "{count}件選択中",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "모든 게임이 불러와졌습니다",
|
||||
"back-to-top": "맨 위로",
|
||||
"column-actions": "작업",
|
||||
"column-cover": "커버",
|
||||
"filters": "필터",
|
||||
"firmware-files-count": "{count}개 파일",
|
||||
"firmware-selected-count": "{count}개 선택됨",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Wszystkie gry zostały załadowane",
|
||||
"back-to-top": "Powrót na górę",
|
||||
"column-actions": "Akcje",
|
||||
"column-cover": "Okładka",
|
||||
"filters": "Filtry",
|
||||
"firmware-files-count": "{count} plików",
|
||||
"firmware-selected-count": "{count} wybrano",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Todos os jogos foram carregados",
|
||||
"back-to-top": "Voltar ao topo",
|
||||
"column-actions": "Ações",
|
||||
"column-cover": "Capa",
|
||||
"filters": "Filtros",
|
||||
"firmware-files-count": "{count} arquivos",
|
||||
"firmware-selected-count": "{count} selecionado(s)",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Toate jocurile au fost încărcate",
|
||||
"back-to-top": "Înapoi sus",
|
||||
"column-actions": "Acțiuni",
|
||||
"column-cover": "Copertă",
|
||||
"filters": "Filtre",
|
||||
"firmware-files-count": "{count} fișiere",
|
||||
"firmware-selected-count": "{count} selectate",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Все игры загружены",
|
||||
"back-to-top": "Наверх",
|
||||
"column-actions": "Действия",
|
||||
"column-cover": "Обложка",
|
||||
"filters": "Фильтры",
|
||||
"firmware-files-count": "{count} файлов",
|
||||
"firmware-selected-count": "{count} выбрано",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "Tüm oyunlar yüklendi",
|
||||
"back-to-top": "Başa dön",
|
||||
"column-actions": "İşlemler",
|
||||
"column-cover": "Kapak",
|
||||
"filters": "Filtreler",
|
||||
"firmware-files-count": "{count} dosya",
|
||||
"firmware-selected-count": "{count} seçildi",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "所有游戏已加载",
|
||||
"back-to-top": "返回顶部",
|
||||
"column-actions": "操作",
|
||||
"column-cover": "封面",
|
||||
"filters": "筛选器",
|
||||
"firmware-files-count": "{count} 个文件",
|
||||
"firmware-selected-count": "已选择 {count} 个",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"all-loaded": "所有遊戲已載入",
|
||||
"back-to-top": "回到頂端",
|
||||
"column-actions": "操作",
|
||||
"column-cover": "封面",
|
||||
"filters": "篩選器",
|
||||
"firmware-files-count": "{count} 個檔案",
|
||||
"firmware-selected-count": "已選擇 {count} 個",
|
||||
|
||||
@@ -28,15 +28,14 @@ const { destinations, activeId } = useNavDestinations();
|
||||
|
||||
<template>
|
||||
<div v-if="smAndDown" class="r-v2-bottom-nav-anchor">
|
||||
<div class="r-v2-bottom-nav">
|
||||
<nav class="r-v2-bottom-nav" :aria-label="t('common.primary-navigation')">
|
||||
<RSliderBtnGroup
|
||||
:model-value="activeId"
|
||||
:items="destinations"
|
||||
variant="tab"
|
||||
class="r-v2-bottom-nav__group"
|
||||
:aria-label="t('common.primary-navigation')"
|
||||
/>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ import GameListRow from "@/v2/components/Gallery/GameListRow.vue";
|
||||
import GameListSkeletonRow from "@/v2/components/Gallery/GameListSkeletonRow.vue";
|
||||
import SelectionBar from "@/v2/components/Gallery/SelectionBar.vue";
|
||||
import {
|
||||
getListColumns,
|
||||
getListMinWidth,
|
||||
getSortOptions,
|
||||
isListSortKey,
|
||||
@@ -387,10 +388,19 @@ watch(
|
||||
// and only the matching one actually moves focus, so they don't fight.
|
||||
// Virtualised rows past the overscan window simply aren't in the DOM, so
|
||||
// nav clamps at the boundary; scrolling past mounts more rows.
|
||||
useGridNav(sectionEl, { rowSelector: ".r-v2-shell__row" });
|
||||
function revealEdge(edge: "first" | "last") {
|
||||
scrollToItem(edge === "first" ? 0 : virtualItems.value.length - 1, false);
|
||||
}
|
||||
useGridNav(sectionEl, {
|
||||
rowSelector: ".r-v2-shell__row",
|
||||
roving: true,
|
||||
revealEdge,
|
||||
});
|
||||
useGridNav(sectionEl, {
|
||||
rowSelector: ".game-list-row",
|
||||
getCells: (row) => [row],
|
||||
roving: true,
|
||||
revealEdge,
|
||||
});
|
||||
|
||||
const loadingInitial = computed(
|
||||
@@ -687,6 +697,10 @@ let jumpDeadline = 0;
|
||||
function anchorLetter(letter: string, smooth: boolean) {
|
||||
const idx = letterToIndex.value.get(letter);
|
||||
if (idx == null) return;
|
||||
scrollToItem(idx, smooth);
|
||||
}
|
||||
|
||||
function scrollToItem(idx: number, smooth: boolean) {
|
||||
// The section runs under the top bar, so rows land below it in either dock.
|
||||
const section = sectionEl.value;
|
||||
const navHeight = section
|
||||
@@ -911,6 +925,53 @@ const asEmpty = (i: GalleryItem) => i as EmptyItem;
|
||||
const asListRow = (i: GalleryItem) => i as ListRowItem;
|
||||
const itemKind = (i: GalleryItem) => i.kind;
|
||||
|
||||
// The desktop list header is the grid's first row; the compact one is a
|
||||
// toolbar above the grid.
|
||||
const listHeaderInGrid = computed(
|
||||
() => layout.value === "list" && !smAndDown.value,
|
||||
);
|
||||
|
||||
// The rows form one ARIA grid, which leaves out the page header and toolbar.
|
||||
const gridAttrs = computed(() => {
|
||||
const items = virtualItems.value;
|
||||
if (items.length === 0 && !listHeaderInGrid.value) return undefined;
|
||||
const loaded = items.some((i) => i.kind === "row" || i.kind === "list-row");
|
||||
return {
|
||||
role: "grid",
|
||||
"aria-label": t("common.games"),
|
||||
"aria-multiselectable": true,
|
||||
"aria-busy": !loaded && !items.some((i) => i.kind === "empty"),
|
||||
"aria-rowcount": items.length + (listHeaderInGrid.value ? 1 : 0),
|
||||
"aria-colcount": listHeaderInGrid.value
|
||||
? getListColumns(props.showPlatformColumn).length
|
||||
: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
function rowIndex(index: number): number {
|
||||
return index + 1 + (listHeaderInGrid.value ? 1 : 0);
|
||||
}
|
||||
|
||||
// A list row is its own `role="row"`; skeletons stay out of the grid.
|
||||
function itemAttrs(item: GalleryItem, index: number) {
|
||||
switch (item.kind) {
|
||||
case "letter-header":
|
||||
case "row":
|
||||
case "empty":
|
||||
return { role: "row", "aria-rowindex": rowIndex(index) };
|
||||
case "skeleton-row":
|
||||
case "skeleton-list-row":
|
||||
return { "aria-hidden": true };
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function isRomSelected(position: number): boolean {
|
||||
const rom = getRomAt(position);
|
||||
return !!rom && gallerySelection.isSelected(rom.id);
|
||||
}
|
||||
|
||||
// Stable identity for the virtualiser. Each GalleryItem carries a content-
|
||||
// derived `key` (`row-${start}`, `lh-${letter}`, `lr-${p}`, …); feeding it to
|
||||
// RVirtualScroller as `get-item-key` lets Vue MATCH rows across a re-pack and
|
||||
@@ -960,6 +1021,7 @@ defineExpose({
|
||||
layout === 'list' && !smAndDown ? listMinWidth : undefined
|
||||
"
|
||||
class="r-v2-shell__scroller"
|
||||
:body-attrs="gridAttrs"
|
||||
:tabindex="-1"
|
||||
@wheel.passive="endLetterJump"
|
||||
@pointerdown.passive="endLetterJump"
|
||||
@@ -1023,7 +1085,7 @@ defineExpose({
|
||||
Shares `LIST_GRID_TEMPLATE` with every GameListRow underneath
|
||||
so columns align. Header click cycles asc/desc into the
|
||||
store's orderBy/orderDir. -->
|
||||
<template v-if="layout === 'list'">
|
||||
<template v-if="layout === 'list' && !listHeaderInGrid">
|
||||
<div
|
||||
v-if="toolbarPosition === 'floating'"
|
||||
ref="listHeaderSentinel"
|
||||
@@ -1040,15 +1102,36 @@ defineExpose({
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<template v-if="listHeaderInGrid" #head>
|
||||
<div
|
||||
v-if="toolbarPosition === 'floating'"
|
||||
ref="listHeaderSentinel"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<GameListHeader
|
||||
class="r-v2-shell__list-header"
|
||||
:class="{ 'r-pinned-list-header': listHeaderPinned }"
|
||||
:sort-key="listSortKey"
|
||||
:sort-dir="orderDir"
|
||||
:show-platform-column="showPlatformColumn"
|
||||
aria-rowindex="1"
|
||||
@sort="onListSort"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- GRID / TABLE (Section 3): letter-headers + rows of cards in
|
||||
grid/grouped mode, or a single RTable in list mode. Skeleton
|
||||
rows render while the first window is in flight. The empty
|
||||
/ not-found state replaces everything below the toolbar
|
||||
with a single message. -->
|
||||
<template #default="{ item }">
|
||||
<div class="r-v2-shell__item">
|
||||
<template #default="{ item, index }">
|
||||
<div
|
||||
class="r-v2-shell__item"
|
||||
v-bind="itemAttrs(item as GalleryItem, index)"
|
||||
>
|
||||
<RLetterHeading
|
||||
v-if="itemKind(item as GalleryItem) === 'letter-header'"
|
||||
role="rowheader"
|
||||
:label="asLetterHeader(item as GalleryItem).letter"
|
||||
/>
|
||||
|
||||
@@ -1056,9 +1139,12 @@ defineExpose({
|
||||
v-else-if="itemKind(item as GalleryItem) === 'row'"
|
||||
class="r-v2-shell__row"
|
||||
>
|
||||
<template
|
||||
<div
|
||||
v-for="(p, slotIdx) in rowPositions(asRow(item as GalleryItem))"
|
||||
:key="p"
|
||||
role="gridcell"
|
||||
class="r-v2-shell__cell"
|
||||
:aria-selected="getRomAt(p) ? isRomSelected(p) : undefined"
|
||||
>
|
||||
<GameCard
|
||||
v-if="getRomAt(p)"
|
||||
@@ -1072,11 +1158,12 @@ defineExpose({
|
||||
@ratio="onCardRatio"
|
||||
/>
|
||||
<GameCardSkeleton v-else />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GameListRow
|
||||
v-else-if="itemKind(item as GalleryItem) === 'list-row'"
|
||||
:aria-rowindex="rowIndex(index)"
|
||||
:position="asListRow(item as GalleryItem).position"
|
||||
:webp="supportsWebp"
|
||||
:show-platform-column="showPlatformColumn"
|
||||
@@ -1100,6 +1187,7 @@ defineExpose({
|
||||
|
||||
<div
|
||||
v-else-if="itemKind(item as GalleryItem) === 'empty'"
|
||||
role="gridcell"
|
||||
class="r-v2-shell__empty"
|
||||
>
|
||||
<REmptyState
|
||||
@@ -1308,7 +1396,11 @@ html[data-bp~="md-and-up"] .r-v2-shell__list-header {
|
||||
/* Never shrink: float rounding can push a "just fits" row a hair over, and
|
||||
shrinking a fixed-height card would crop its cover. Take ragged overflow
|
||||
instead (also keeps skeletons, default shrink:1, at their packed width). */
|
||||
.r-v2-shell__row > * {
|
||||
/* A cell has no box of its own, so the card inside is the flex item. */
|
||||
.r-v2-shell__cell {
|
||||
display: contents;
|
||||
}
|
||||
.r-v2-shell__cell > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ref } from "vue";
|
||||
import GameListHeader from "./GameListHeader.vue";
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
const smAndDown = ref(false);
|
||||
vi.mock("@/v2/composables/useBreakpoint", () => ({
|
||||
useBreakpoint: () => ({ smAndDown }),
|
||||
}));
|
||||
|
||||
function mountHeader() {
|
||||
return mount(GameListHeader, {
|
||||
props: { sortKey: "name", sortDir: "asc" },
|
||||
global: { stubs: { RIcon: true, ListSortMenu: true } },
|
||||
});
|
||||
}
|
||||
|
||||
describe("GameListHeader", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
smAndDown.value = false;
|
||||
});
|
||||
|
||||
it("is a row of column headers, one per column", () => {
|
||||
const row = mountHeader().get("[role=row]");
|
||||
const headers = row.findAll(":scope > [role=columnheader]");
|
||||
|
||||
expect(headers).toHaveLength(row.element.children.length);
|
||||
expect(headers.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("puts aria-sort on the sortable column headers only", () => {
|
||||
const headers = mountHeader().findAll("[role=columnheader]");
|
||||
const sorts = headers.map((h) => h.attributes("aria-sort"));
|
||||
|
||||
expect(sorts.filter((s) => s === "ascending")).toHaveLength(1);
|
||||
expect(sorts).toContain("none");
|
||||
expect(sorts).toContain(undefined);
|
||||
expect(mountHeader().findAll("button[aria-sort]")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("names every column header", () => {
|
||||
for (const header of mountHeader().findAll("[role=columnheader]")) {
|
||||
const name = header.text() || header.find("[aria-label]").exists();
|
||||
expect(name, header.html()).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("is a plain toolbar on phones, outside any grid", () => {
|
||||
smAndDown.value = true;
|
||||
const wrapper = mountHeader();
|
||||
|
||||
expect(wrapper.find("[role=row]").exists()).toBe(false);
|
||||
expect(wrapper.find("[role=columnheader]").exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,12 @@ function onSelectAllClick(e: MouseEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
function ariaSort(col: ListColumn) {
|
||||
if (!col.sortable) return undefined;
|
||||
if (props.sortKey !== col.key) return "none";
|
||||
return props.sortDir === "asc" ? "ascending" : "descending";
|
||||
}
|
||||
|
||||
function handleClick(col: ListColumn) {
|
||||
if (!isSortableColumn(col)) return;
|
||||
// Toggle direction when re-clicking the active column; otherwise start the
|
||||
@@ -85,11 +91,7 @@ function handleClick(col: ListColumn) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="smAndDown"
|
||||
class="game-list-header game-list-header--compact"
|
||||
role="row"
|
||||
>
|
||||
<div v-if="smAndDown" class="game-list-header game-list-header--compact">
|
||||
<RCheckbox
|
||||
class="game-list-header__check"
|
||||
:model-value="selectionState === 'all'"
|
||||
@@ -116,7 +118,14 @@ function handleClick(col: ListColumn) {
|
||||
</div>
|
||||
|
||||
<div v-else class="game-list-header" :style="gridStyle" role="row">
|
||||
<template v-for="col in columns" :key="String(col.key)">
|
||||
<div
|
||||
v-for="col in columns"
|
||||
:key="String(col.key)"
|
||||
role="columnheader"
|
||||
class="game-list-header__col"
|
||||
:class="{ 'game-list-header__col--center': col.key === 'select' }"
|
||||
:aria-sort="ariaSort(col)"
|
||||
>
|
||||
<!-- Tri-state select-all checkbox (off → some → all), judged
|
||||
against the whole filtered result. -->
|
||||
<RCheckbox
|
||||
@@ -137,24 +146,26 @@ function handleClick(col: ListColumn) {
|
||||
@click="onSelectAllClick"
|
||||
/>
|
||||
|
||||
<span
|
||||
v-else-if="!col.sortable"
|
||||
class="game-list-header__cell"
|
||||
:class="{ 'game-list-header__cell--end': col.align === 'end' }"
|
||||
>
|
||||
<span v-if="col.label" class="game-list-header__label">
|
||||
{{ col.label }}
|
||||
</span>
|
||||
<span v-else class="game-list-header__hidden">
|
||||
{{ col.hiddenLabel }}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="game-list-header__cell"
|
||||
class="game-list-header__cell game-list-header__cell--sortable"
|
||||
:class="{
|
||||
'game-list-header__cell--sortable': col.sortable,
|
||||
'game-list-header__cell--end': col.align === 'end',
|
||||
'game-list-header__cell--active': col.sortable && sortKey === col.key,
|
||||
'game-list-header__cell--active': sortKey === col.key,
|
||||
}"
|
||||
:aria-sort="
|
||||
col.sortable && sortKey === col.key
|
||||
? sortDir === 'asc'
|
||||
? 'ascending'
|
||||
: 'descending'
|
||||
: 'none'
|
||||
"
|
||||
:tabindex="col.sortable ? 0 : -1"
|
||||
:disabled="!col.sortable"
|
||||
@click="handleClick(col)"
|
||||
>
|
||||
<span class="game-list-header__label">{{ col.label }}</span>
|
||||
@@ -167,7 +178,7 @@ function handleClick(col: ListColumn) {
|
||||
class="game-list-header__icon"
|
||||
/>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -194,7 +205,17 @@ function handleClick(col: ListColumn) {
|
||||
width: var(--r-list-select-w);
|
||||
}
|
||||
|
||||
.game-list-header__col {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.game-list-header__col--center {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.game-list-header__cell {
|
||||
flex: 1;
|
||||
appearance: none;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
@@ -254,6 +275,15 @@ function handleClick(col: ListColumn) {
|
||||
/* Select-all checkbox in the leading column: RCheckbox bare/circle, matching the
|
||||
GameCard and GameListRow ticks, and centred over every row's tick. */
|
||||
.game-list-header__check {
|
||||
justify-self: center;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.game-list-header__hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -124,9 +124,22 @@ const rom = computed<SimpleRom | null>(() => {
|
||||
: null;
|
||||
});
|
||||
|
||||
const romName = computed(() =>
|
||||
rom.value ? (rom.value.name ?? rom.value.fs_name_no_ext) : "",
|
||||
);
|
||||
const isSelected = computed(() =>
|
||||
!isStatic.value && rom.value ? selection.isSelected(rom.value.id) : false,
|
||||
);
|
||||
// Space on the name link selects the row, Shift+Space the range from the
|
||||
// last one toggled.
|
||||
function onRowKeydown(e: KeyboardEvent) {
|
||||
const item = rom.value;
|
||||
if (e.key !== " " || !item || isStatic.value) return;
|
||||
if (props.position === undefined) return;
|
||||
e.preventDefault();
|
||||
if (e.shiftKey) selectionInput.handleActivate(item, props.position, e);
|
||||
else selection.toggle(item, props.position);
|
||||
}
|
||||
|
||||
function onCheckboxClick(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
@@ -302,7 +315,7 @@ function onRowClick(e: MouseEvent) {
|
||||
// Default click: prevent the anchor's native navigation, run the
|
||||
// morph, then push the route.
|
||||
e.preventDefault();
|
||||
navigateTo(item, e.currentTarget as HTMLElement | null);
|
||||
navigateTo(item, rowEl.value);
|
||||
}
|
||||
|
||||
// Mirror of GameCard's onHighlight: swap the AppLayout backdrop to the
|
||||
@@ -328,8 +341,10 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a
|
||||
<div
|
||||
ref="rowEl"
|
||||
v-bind="$attrs"
|
||||
role="row"
|
||||
class="game-list-row"
|
||||
:class="[
|
||||
{
|
||||
@@ -341,27 +356,20 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
entranceClass,
|
||||
]"
|
||||
:style="[smAndDown ? undefined : gridStyle, entranceStyle]"
|
||||
:href="rom ? `/rom/${rom.id}` : undefined"
|
||||
:aria-label="
|
||||
rom
|
||||
? t('common.open-item', { name: rom.name ?? rom.fs_name_no_ext })
|
||||
: undefined
|
||||
"
|
||||
:aria-selected="rom && !isStatic ? isSelected : undefined"
|
||||
:data-rom-position="position"
|
||||
:data-rom-id="rom?.id"
|
||||
:data-focus-key="rom ? `rom-${rom.id}` : undefined"
|
||||
@click="onRowClick"
|
||||
@mouseenter="onRowHighlight"
|
||||
@focus="onRowHighlight"
|
||||
@pointerenter="onRowHighlight"
|
||||
@focusin="onRowHighlight"
|
||||
@pointerdown="onRowPointerDown"
|
||||
@contextmenu="selectionInput.handleContextMenu"
|
||||
@animationend.self="endEntrance"
|
||||
>
|
||||
<template v-if="rom">
|
||||
<!-- COMPACT (phones / tablets): two lines plus the chevron; the
|
||||
columns move into the detail panel below. -->
|
||||
<template v-if="smAndDown">
|
||||
<div class="game-list-row__compact r-list-compact">
|
||||
<div class="game-list-row__compact r-list-compact" role="gridcell">
|
||||
<div class="game-list-row__select">
|
||||
<RCheckbox
|
||||
v-if="!isStatic"
|
||||
@@ -372,7 +380,7 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
color="primary"
|
||||
bare
|
||||
hide-details
|
||||
tabindex="-1"
|
||||
decorative
|
||||
@click="onCheckboxClick"
|
||||
/>
|
||||
</div>
|
||||
@@ -390,9 +398,15 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
</div>
|
||||
|
||||
<div class="r-list-compact__stack">
|
||||
<div class="game-list-row__name">
|
||||
{{ rom.name ?? rom.fs_name_no_ext }}
|
||||
</div>
|
||||
<a
|
||||
:href="`/rom/${rom.id}`"
|
||||
class="game-list-row__name"
|
||||
@click="onRowClick"
|
||||
@keydown="onRowKeydown"
|
||||
@contextmenu="selectionInput.handleContextMenu"
|
||||
>
|
||||
{{ romName }}
|
||||
</a>
|
||||
<div class="r-list-compact__facts">
|
||||
<template v-if="platformName">
|
||||
<PlatformIcon
|
||||
@@ -457,6 +471,7 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
|
||||
<div
|
||||
v-if="expanded"
|
||||
role="gridcell"
|
||||
class="game-list-row__detail"
|
||||
:style="{ height: `${detailHeight}px` }"
|
||||
@click.stop
|
||||
@@ -500,7 +515,7 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
picked. RCheckbox provides the box / fill / draw animations
|
||||
(same animation language as the GameCard checkbox in grid
|
||||
mode). -->
|
||||
<div class="game-list-row__cell game-list-row__select">
|
||||
<div role="gridcell" class="game-list-row__cell game-list-row__select">
|
||||
<RCheckbox
|
||||
v-if="!isStatic"
|
||||
class="game-list-row__check"
|
||||
@@ -510,12 +525,12 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
color="primary"
|
||||
bare
|
||||
hide-details
|
||||
tabindex="-1"
|
||||
decorative
|
||||
@click="onCheckboxClick"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="game-list-row__cell game-list-row__cover">
|
||||
<div role="gridcell" class="game-list-row__cell game-list-row__cover">
|
||||
<GameCard
|
||||
:rom="rom"
|
||||
size="xs"
|
||||
@@ -527,12 +542,18 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="game-list-row__cell game-list-row__title">
|
||||
<div role="gridcell" class="game-list-row__cell game-list-row__title">
|
||||
<div class="game-list-row__meta">
|
||||
<div class="game-list-row__name-row">
|
||||
<div class="game-list-row__name">
|
||||
{{ rom.name ?? rom.fs_name_no_ext }}
|
||||
</div>
|
||||
<a
|
||||
:href="`/rom/${rom.id}`"
|
||||
class="game-list-row__name"
|
||||
@click="onRowClick"
|
||||
@keydown="onRowKeydown"
|
||||
@contextmenu="selectionInput.handleContextMenu"
|
||||
>
|
||||
{{ romName }}
|
||||
</a>
|
||||
<div class="game-list-row__badges" @click.stop>
|
||||
<GameActionBtn
|
||||
v-if="hasStatus"
|
||||
@@ -556,6 +577,7 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
|
||||
<div
|
||||
v-if="showPlatformColumn"
|
||||
role="gridcell"
|
||||
class="game-list-row__cell game-list-row__platform"
|
||||
>
|
||||
<PlatformIcon
|
||||
@@ -569,34 +591,45 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('fs_size_bytes')"
|
||||
>
|
||||
{{ formatBytes(rom.fs_size_bytes) }}
|
||||
</div>
|
||||
<div class="game-list-row__cell" :class="cellModifiers('created_at')">
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('created_at')"
|
||||
>
|
||||
{{ formatDate(rom.created_at) }}
|
||||
</div>
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('first_release_date')"
|
||||
>
|
||||
{{ releaseDate(rom) }}
|
||||
</div>
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('average_rating')"
|
||||
>
|
||||
{{ ratingValue(rom) }}
|
||||
</div>
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('hltb_main_story')"
|
||||
>
|
||||
{{ lengthValue(rom) }}
|
||||
</div>
|
||||
|
||||
<div class="game-list-row__cell game-list-row__cell--pills">
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell game-list-row__cell--pills"
|
||||
>
|
||||
<div class="game-list-row__pills">
|
||||
<RChip
|
||||
v-for="l in (rom.languages ?? []).slice(0, PILLS_VISIBLE)"
|
||||
@@ -621,7 +654,10 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
location="top"
|
||||
/>
|
||||
</div>
|
||||
<div class="game-list-row__cell game-list-row__cell--pills">
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell game-list-row__cell--pills"
|
||||
>
|
||||
<div class="game-list-row__pills">
|
||||
<RChip
|
||||
v-for="r in (rom.regions ?? []).slice(0, PILLS_VISIBLE)"
|
||||
@@ -647,7 +683,11 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="game-list-row__cell" :class="cellModifiers('actions')">
|
||||
<div
|
||||
role="gridcell"
|
||||
class="game-list-row__cell"
|
||||
:class="cellModifiers('actions')"
|
||||
>
|
||||
<div class="game-list-row__actions" @click.stop>
|
||||
<GameActionBtn
|
||||
:rom="rom"
|
||||
@@ -754,12 +794,13 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
</template>
|
||||
</template>
|
||||
</template>
|
||||
</a>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.game-list-row {
|
||||
/* An inline <a> would shrink-wrap its content and swallow the bleed. */
|
||||
/* Contains the name link's stretched hit area. */
|
||||
position: relative;
|
||||
display: block;
|
||||
/* The long press selects the row; iOS would offer its link callout too. */
|
||||
-webkit-touch-callout: none;
|
||||
@@ -906,11 +947,13 @@ function onRowPointerDown(e: PointerEvent) {
|
||||
}
|
||||
|
||||
/* The scroller clips an outline past the row's screen edge, so key and pad
|
||||
focus paint inside the row. */
|
||||
html:not([data-input]) .game-list-row:focus-visible,
|
||||
html[data-input="key"] .game-list-row:focus-visible,
|
||||
html[data-input="pad"] .game-list-row:focus-visible {
|
||||
focus on the name link paint around the whole row. */
|
||||
.game-list-row__name:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
html:not([data-input]) .game-list-row:has(.game-list-row__name:focus-visible),
|
||||
html[data-input="key"] .game-list-row:has(.game-list-row__name:focus-visible),
|
||||
html[data-input="pad"] .game-list-row:has(.game-list-row__name:focus-visible) {
|
||||
box-shadow: inset 0 0 0 var(--r-focus-ring-width) var(--r-color-focus);
|
||||
}
|
||||
|
||||
@@ -1002,7 +1045,26 @@ html[data-input="pad"] .game-list-row:focus-visible {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* The name link covers the row, so a click anywhere opens the game, and the
|
||||
row's own controls sit above it. */
|
||||
.game-list-row__name::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
.game-list-row__check,
|
||||
.game-list-row__badges,
|
||||
.game-list-row__providers,
|
||||
.game-list-row__actions,
|
||||
.game-list-row__detail {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.game-list-row__name {
|
||||
display: block;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
font-size: var(--r-font-size-md);
|
||||
font-weight: var(--r-font-weight-medium);
|
||||
color: var(--r-color-fg);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ref } from "vue";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
import storeGallerySelection from "@/v2/stores/gallerySelection";
|
||||
import GameListRow from "./GameListRow.vue";
|
||||
import { rom } from "./listRowFixture";
|
||||
|
||||
@@ -101,3 +103,53 @@ describe("list row on phones and tablets", () => {
|
||||
expect(fields).toContain("en");
|
||||
});
|
||||
});
|
||||
|
||||
describe("list row selection", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
smAndDown.value = false;
|
||||
});
|
||||
|
||||
// Seeded after mounting: the first gallery row to mount resets the store.
|
||||
async function mountGalleryRow(attrs: Record<string, unknown> = {}) {
|
||||
const wrapper = mountRow({ rom: undefined, position: 0, ...attrs });
|
||||
storeGalleryRoms().byPosition.set(0, rom());
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
it("selects on Space from its name link", async () => {
|
||||
const wrapper = await mountGalleryRow();
|
||||
|
||||
await wrapper.get("a.game-list-row__name").trigger("keydown", { key: " " });
|
||||
|
||||
expect(storeGallerySelection().ids).toEqual([rom().id]);
|
||||
expect(wrapper.get("[role=row]").attributes("aria-selected")).toBe("true");
|
||||
});
|
||||
|
||||
it("is a row with one cell on phones", async () => {
|
||||
smAndDown.value = true;
|
||||
const row = (await mountGalleryRow()).get("[role=row]");
|
||||
|
||||
expect(
|
||||
Array.from(row.element.children).map((c) => c.getAttribute("role")),
|
||||
).toEqual(["gridcell"]);
|
||||
});
|
||||
it("is a grid row of cells, with the name as its link", async () => {
|
||||
const wrapper = await mountGalleryRow({ "aria-rowindex": 4 });
|
||||
const row = wrapper.get("[role=row]");
|
||||
|
||||
expect(row.attributes("aria-rowindex")).toBe("4");
|
||||
expect(row.attributes("aria-selected")).toBe("false");
|
||||
expect(
|
||||
row.element.children.length,
|
||||
"every column is a cell",
|
||||
).toBeGreaterThan(1);
|
||||
for (const child of Array.from(row.element.children)) {
|
||||
expect(child.getAttribute("role")).toBe("gridcell");
|
||||
}
|
||||
expect(row.get("a.game-list-row__name").attributes("href")).toBe(
|
||||
`/rom/${rom().id}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,11 @@ const { smAndDown } = useBreakpoint();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="smAndDown" class="r-glr-skel r-glr-skel--compact r-list-compact">
|
||||
<div
|
||||
v-if="smAndDown"
|
||||
class="r-glr-skel r-glr-skel--compact r-list-compact"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<!-- Stands in for the compact row's tick column, or the cover would start
|
||||
further left here than in the row this replaces. -->
|
||||
<div class="r-glr-skel__select" />
|
||||
@@ -68,7 +72,12 @@ const { smAndDown } = useBreakpoint();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="r-glr-skel r-glr-skel--columns" :style="gridStyle">
|
||||
<div
|
||||
v-else
|
||||
class="r-glr-skel r-glr-skel--columns"
|
||||
:style="gridStyle"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<template v-for="col in columns" :key="String(col.key)">
|
||||
<div v-if="col.key === 'select'" class="r-glr-skel__cell" />
|
||||
<div
|
||||
|
||||
@@ -350,7 +350,7 @@ function clear() {
|
||||
ref="barEl"
|
||||
class="selection-bar"
|
||||
:class="{ 'selection-bar--visible': selection.enabled }"
|
||||
:aria-hidden="!selection.enabled"
|
||||
:inert="!selection.enabled"
|
||||
>
|
||||
<!-- One stroke around bar, hill and fillets, since three boxes cannot
|
||||
share a border without seams where their edges meet. -->
|
||||
|
||||
@@ -40,6 +40,8 @@ export interface ListColumn {
|
||||
/** Column header label. Empty string renders no text (used for the
|
||||
* leading select column + trailing actions column). */
|
||||
label: string;
|
||||
/** Header text for assistive tech when `label` is empty. */
|
||||
hiddenLabel?: string;
|
||||
/** Whether the column header is clickable to toggle sort. */
|
||||
sortable: boolean;
|
||||
/** Column alignment, read by the header label, the value cells and the
|
||||
@@ -64,7 +66,13 @@ export function getListColumns(showPlatform: boolean): readonly ListColumn[] {
|
||||
{ key: "select", label: "", sortable: false, align: "start" },
|
||||
// Cover gets its own fixed-width column so the title/meta column starts
|
||||
// at the same x on every row, regardless of the cover's natural width.
|
||||
{ key: "cover", label: "", sortable: false, align: "start" },
|
||||
{
|
||||
key: "cover",
|
||||
label: "",
|
||||
hiddenLabel: t("gallery.column-cover"),
|
||||
sortable: false,
|
||||
align: "start",
|
||||
},
|
||||
{
|
||||
key: "name",
|
||||
label: t("settings.title-header"),
|
||||
@@ -136,7 +144,13 @@ export function getListColumns(showPlatform: boolean): readonly ListColumn[] {
|
||||
align: "start",
|
||||
skeletonWidth: 80,
|
||||
},
|
||||
{ key: "actions", label: "", sortable: false, align: "end" },
|
||||
{
|
||||
key: "actions",
|
||||
label: "",
|
||||
hiddenLabel: t("gallery.column-actions"),
|
||||
sortable: false,
|
||||
align: "end",
|
||||
},
|
||||
);
|
||||
return cols;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ const sampleRom = {
|
||||
const meta: Meta<typeof GameCard> = {
|
||||
title: "Media/GameCard",
|
||||
component: GameCard,
|
||||
// Rendered as in the gallery: a link card with the multi-select checkbox,
|
||||
// so the a11y check covers both.
|
||||
args: { selectable: true, position: 0 },
|
||||
argTypes: {
|
||||
hero: { control: "boolean" },
|
||||
focused: { control: "boolean" },
|
||||
@@ -68,7 +71,7 @@ export const Grid: Story = {
|
||||
},
|
||||
template: `
|
||||
<div style="display:grid;grid-template-columns:repeat(3,180px);gap:1.5rem">
|
||||
<GameCard v-for="rom in roms" :key="rom.id" :rom="rom" />
|
||||
<GameCard v-for="(rom, i) in roms" :key="rom.id" :rom="rom" selectable :position="i" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
|
||||
@@ -87,6 +87,33 @@ describe("GameCard selection", () => {
|
||||
expect(selection.ids).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it("is a plain link with a decorative checkbox", async () => {
|
||||
const wrapper = await mountCard(1, makeRouter());
|
||||
const card = wrapper.find(".r-gc");
|
||||
|
||||
expect(card.attributes("role")).toBeUndefined();
|
||||
expect(card.attributes("aria-pressed")).toBeUndefined();
|
||||
expect(wrapper.find(".r-gc__check input").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("selects on Space, even before anything is selected", async () => {
|
||||
const wrapper = await mountCard(1, makeRouter());
|
||||
|
||||
await wrapper.find(".r-gc").trigger("keydown", { key: " " });
|
||||
|
||||
expect(storeGallerySelection().ids).toEqual([1]);
|
||||
});
|
||||
|
||||
it("leaves Space on its own buttons to them", async () => {
|
||||
const wrapper = await mountCard(1, makeRouter());
|
||||
const card = wrapper.find(".r-gc");
|
||||
const button = card.find("button");
|
||||
|
||||
await button.trigger("keydown", { key: " " });
|
||||
|
||||
expect(storeGallerySelection().ids).toEqual([]);
|
||||
});
|
||||
|
||||
it("consumes a modifier click on the checkbox", async () => {
|
||||
const router = makeRouter();
|
||||
const wrapper = await mountCard(1, router);
|
||||
@@ -98,3 +125,15 @@ describe("GameCard selection", () => {
|
||||
expect(storeGallerySelection().ids).toEqual([1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GameCard static", () => {
|
||||
it("is a plain button unless the consumer passes selected", () => {
|
||||
const plain = mount(GameCard, { props: { rom: rom(1), static: true } });
|
||||
expect(plain.find(".r-gc").attributes("aria-pressed")).toBeUndefined();
|
||||
|
||||
const toggle = mount(GameCard, {
|
||||
props: { rom: rom(1), static: true, selected: false },
|
||||
});
|
||||
expect(toggle.find(".r-gc").attributes("aria-pressed")).toBe("false");
|
||||
});
|
||||
});
|
||||
@@ -114,7 +114,8 @@ interface Props {
|
||||
* (cover-variant picker, multi-select gallery). When `selectable`
|
||||
* is true this prop is ignored: the card subscribes directly to
|
||||
* `gallerySelection` so a single source of truth (the store)
|
||||
* drives every selected card across the gallery. */
|
||||
* drives every selected card across the gallery. Left unset, a static
|
||||
* card gets no `aria-pressed`. */
|
||||
selected?: boolean;
|
||||
/** Opt the card into the gallery's multi-select store. When true:
|
||||
* the card reads its selected state from `gallerySelection`,
|
||||
@@ -142,7 +143,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
showTitle: true,
|
||||
coverSrc: undefined,
|
||||
coverPip: false,
|
||||
selected: false,
|
||||
selected: undefined,
|
||||
selectable: false,
|
||||
position: undefined,
|
||||
});
|
||||
@@ -290,13 +291,9 @@ const showCheckbox = computed(
|
||||
const checkboxAlwaysOn = computed(
|
||||
() => props.selectable && !props.decorative && selectionStore.enabled,
|
||||
);
|
||||
|
||||
function onCheckboxClick(e: MouseEvent) {
|
||||
// The checkbox itself is a deliberate selection gesture. We bind
|
||||
// RCheckbox in "controlled" mode (only `:model-value`: no v-model),
|
||||
// so the native input change is purely visual; `preventDefault`
|
||||
// here cancels the label → input click default so the input never
|
||||
// toggles itself, and our store mutation drives the next render.
|
||||
// The box is decorative and the store drives its state. Stop the click
|
||||
// here so the enclosing link doesn't navigate.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (props.position == null) return;
|
||||
@@ -339,13 +336,21 @@ function onCardPointerDown(e: PointerEvent) {
|
||||
selectionInput.handlePointerDown(props.rom, props.position, e);
|
||||
}
|
||||
|
||||
function onStaticKeydown(e: KeyboardEvent) {
|
||||
// Enter / Space activate the card when it's rendered as a plain
|
||||
// <article role="button"> instead of a router-link.
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
function onCardKeydown(e: KeyboardEvent) {
|
||||
if (props.decorative || (e.key !== "Enter" && e.key !== " ")) return;
|
||||
// A static card is an <article role="button">, so Enter / Space activate it.
|
||||
if (props.static) {
|
||||
e.preventDefault();
|
||||
emit("click", e as unknown as MouseEvent);
|
||||
return;
|
||||
}
|
||||
// Space on the card selects it, Shift+Space the range from the last one
|
||||
// toggled. Keys from the card's own buttons are theirs.
|
||||
if (e.key !== " " || e.target !== e.currentTarget) return;
|
||||
if (!props.selectable || props.position == null) return;
|
||||
e.preventDefault();
|
||||
if (e.shiftKey) selectionInput.handleActivate(props.rom, props.position, e);
|
||||
else selectionStore.toggle(props.rom, props.position);
|
||||
}
|
||||
|
||||
// Reverse-morph (paint the view-transition-name when GameDetails is
|
||||
@@ -375,21 +380,13 @@ function onStaticKeydown(e: KeyboardEvent) {
|
||||
]"
|
||||
:style="{ '--r-cover-ratio': coverAspectRatio }"
|
||||
:aria-label="decorative ? undefined : title"
|
||||
:aria-pressed="
|
||||
decorative
|
||||
? undefined
|
||||
: static
|
||||
? selected
|
||||
: selectable
|
||||
? isSelected
|
||||
: undefined
|
||||
"
|
||||
:aria-pressed="static && !decorative ? selected : undefined"
|
||||
:data-rom-id="rom.id"
|
||||
:data-rom-position="selectable ? position : undefined"
|
||||
:data-focus-key="!decorative && !static ? `rom-${rom.id}` : undefined"
|
||||
@click.capture="onCardClickCapture"
|
||||
@click="onCardClick"
|
||||
@keydown="static && !decorative ? onStaticKeydown($event) : undefined"
|
||||
@keydown="onCardKeydown"
|
||||
@mouseenter="onCoverEnter"
|
||||
@mouseleave="onCoverLeave"
|
||||
@focus="onCoverFocus"
|
||||
@@ -426,7 +423,7 @@ function onStaticKeydown(e: KeyboardEvent) {
|
||||
color="primary"
|
||||
bare
|
||||
hide-details
|
||||
tabindex="-1"
|
||||
decorative
|
||||
@click="onCheckboxClick"
|
||||
/>
|
||||
|
||||
|
||||
@@ -38,13 +38,16 @@ import GameListRow from "@/v2/components/Gallery/GameListRow.vue";
|
||||
import GameListSkeletonRow from "@/v2/components/Gallery/GameListSkeletonRow.vue";
|
||||
import SelectionBar from "@/v2/components/Gallery/SelectionBar.vue";
|
||||
import {
|
||||
getListColumns,
|
||||
isListSortKey,
|
||||
LIST_ROW_HEIGHT_PX,
|
||||
type ListSortKey,
|
||||
} from "@/v2/components/Gallery/listColumns";
|
||||
import CachedPlatformIcon from "@/v2/components/shared/CachedPlatformIcon.vue";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import { useConfirm } from "@/v2/composables/useConfirm";
|
||||
import { useGallerySelectionInput } from "@/v2/composables/useGallerySelectionInput";
|
||||
import { useGridNav } from "@/v2/composables/useGridNav";
|
||||
import { useListExpansion } from "@/v2/composables/useListExpansion";
|
||||
import { useLoadingPhase } from "@/v2/composables/useLoadingPhase";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
@@ -184,6 +187,32 @@ function rowPosition(item: unknown): number {
|
||||
return isListRow(v) ? v.position : -1;
|
||||
}
|
||||
|
||||
// The rows form an ARIA grid. On desktop the column header is its first row;
|
||||
// the compact header is a toolbar, so there the grid starts at the rows.
|
||||
const { smAndDown } = useBreakpoint();
|
||||
const listEl = ref<HTMLElement | null>(null);
|
||||
const gridAttrs = computed(() => {
|
||||
const headerRows = smAndDown.value ? 0 : 1;
|
||||
return {
|
||||
role: "grid",
|
||||
"aria-label": t("common.games"),
|
||||
"aria-multiselectable": true,
|
||||
"aria-busy": !virtualItems.value.some(isListRow),
|
||||
"aria-rowcount": virtualItems.value.length + headerRows,
|
||||
"aria-colcount": smAndDown.value ? undefined : getListColumns(true).length,
|
||||
};
|
||||
});
|
||||
const scrollerRef = ref<InstanceType<typeof RVirtualScroller> | null>(null);
|
||||
useGridNav(listEl, {
|
||||
rowSelector: ".game-list-row",
|
||||
getCells: (row) => [row],
|
||||
roving: true,
|
||||
revealEdge: (edge) =>
|
||||
scrollerRef.value?.scrollToIndex(
|
||||
edge === "first" ? 0 : virtualItems.value.length - 1,
|
||||
),
|
||||
});
|
||||
|
||||
function onListSort({ key, dir }: { key: ListSortKey; dir: "asc" | "desc" }) {
|
||||
galleryRoms.setOrderBy(key);
|
||||
galleryRoms.setOrderDir(dir);
|
||||
@@ -387,23 +416,32 @@ onBeforeUnmount(() => {
|
||||
icon="mdi-folder-question-outline"
|
||||
:title="t('settings.missing-games-none')"
|
||||
/>
|
||||
<div v-else-if="phase !== 'idle'" class="r-v2-missing__list">
|
||||
<div
|
||||
v-else-if="phase !== 'idle'"
|
||||
ref="listEl"
|
||||
class="r-v2-missing__list"
|
||||
v-bind="smAndDown ? undefined : gridAttrs"
|
||||
>
|
||||
<GameListHeader
|
||||
:sort-key="listSortKey"
|
||||
:sort-dir="orderDir"
|
||||
:aria-rowindex="smAndDown ? undefined : 1"
|
||||
@sort="onListSort"
|
||||
/>
|
||||
<RVirtualScroller
|
||||
ref="scrollerRef"
|
||||
:items="virtualItems"
|
||||
:get-item-height="vItemHeight"
|
||||
:offset-shift="offsetShift"
|
||||
:overscan="25"
|
||||
:body-attrs="smAndDown ? gridAttrs : undefined"
|
||||
class="r-v2-missing__scroller"
|
||||
@update:viewport-range="onViewportRange"
|
||||
>
|
||||
<template #default="{ item }">
|
||||
<template #default="{ item, index }">
|
||||
<GameListRow
|
||||
v-if="isListRow(item as VItem)"
|
||||
:aria-rowindex="index + (smAndDown ? 1 : 2)"
|
||||
:position="rowPosition(item)"
|
||||
:webp="supportsWebp"
|
||||
expandable
|
||||
|
||||
@@ -13,14 +13,7 @@
|
||||
// Tone defaults to "warning"; pass "danger" for irreversible-and-serious.
|
||||
import { RBtn, RDialog, RTextField } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
ref,
|
||||
} from "vue";
|
||||
import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { Events } from "@/types/emitter";
|
||||
|
||||
@@ -34,7 +27,6 @@ const emitter = inject<Emitter<Events>>("emitter");
|
||||
const open = ref(false);
|
||||
const payload = ref<Payload | null>(null);
|
||||
const typed = ref("");
|
||||
const cancelButtonRef = ref<InstanceType<typeof RBtn> | null>(null);
|
||||
|
||||
const tone = computed(() => payload.value?.tone ?? "warning");
|
||||
const confirmColor = computed(() =>
|
||||
@@ -66,9 +58,6 @@ function onShow(p: Payload) {
|
||||
payload.value = p;
|
||||
typed.value = "";
|
||||
open.value = true;
|
||||
nextTick(() => {
|
||||
cancelButtonRef.value?.$el?.focus?.();
|
||||
});
|
||||
}
|
||||
|
||||
// Closing without picking (header X, route change) counts as a cancel.
|
||||
@@ -122,9 +111,11 @@ onBeforeUnmount(() => emitter?.off("showConfirm", onShow));
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="payload" #footer-start>
|
||||
<RBtn ref="cancelButtonRef" variant="outlined" @click="onCancel">
|
||||
<!-- eslint-disable vuejs-accessibility/no-autofocus -- RDialog reads [autofocus] to place initial focus, and Cancel is the safe default -->
|
||||
<RBtn autofocus variant="outlined" @click="onCancel">
|
||||
{{ payload.cancelText ?? t("common.cancel") }}
|
||||
</RBtn>
|
||||
<!-- eslint-enable vuejs-accessibility/no-autofocus -->
|
||||
</template>
|
||||
<template v-if="payload" #footer>
|
||||
<RBtn
|
||||
|
||||
@@ -4,7 +4,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
import { AXIS_THRESHOLD, PAD_BUTTON, useGamepad } from "./index";
|
||||
import {
|
||||
popEscapable,
|
||||
pushEscapable,
|
||||
} from "@/v2/lib/overlays/RDialog/escapeStack";
|
||||
import {
|
||||
AXIS_THRESHOLD,
|
||||
EXIT_CHORD_HOLD_MS,
|
||||
PAD_BUTTON,
|
||||
useGamepad,
|
||||
} from "./index";
|
||||
|
||||
vi.mock("vue-router", () => ({
|
||||
useRoute: () => ({ path: "/platforms" }),
|
||||
@@ -31,11 +40,11 @@ function padWithStick(x: number, y: number): Gamepad {
|
||||
};
|
||||
}
|
||||
|
||||
function padHolding(button: number): Gamepad {
|
||||
function padHolding(...held: number[]): Gamepad {
|
||||
const buttons = Array.from({ length: 17 }, (_, i) => ({
|
||||
pressed: i === button,
|
||||
touched: i === button,
|
||||
value: i === button ? 1 : 0,
|
||||
pressed: held.includes(i),
|
||||
touched: held.includes(i),
|
||||
value: held.includes(i) ? 1 : 0,
|
||||
}));
|
||||
return { ...padWithStick(0, 0), buttons };
|
||||
}
|
||||
@@ -59,9 +68,9 @@ describe("useGamepad", () => {
|
||||
|
||||
// Seeing a pad at install flips the modality, so hand the session back to
|
||||
// the mouse: these tests are about the user who launched with a click.
|
||||
function installOnMouse(pad: Gamepad) {
|
||||
function installOnMouse(pad: Gamepad | (() => Gamepad[])) {
|
||||
Object.defineProperty(navigator, "getGamepads", {
|
||||
value: () => [pad],
|
||||
value: typeof pad === "function" ? pad : () => [pad],
|
||||
configurable: true,
|
||||
});
|
||||
wrapper = mount(
|
||||
@@ -144,4 +153,127 @@ describe("useGamepad", () => {
|
||||
expect(keys).toEqual([]);
|
||||
expect(modality.value).toBe("mouse");
|
||||
});
|
||||
|
||||
describe("exit chord", () => {
|
||||
const CHORD = [PAD_BUTTON.back, PAD_BUTTON.start];
|
||||
let pads: Gamepad[] = [];
|
||||
let chords = 0;
|
||||
const onChord = () => chords++;
|
||||
let now: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
// Polls once at `ms` past the clock's start.
|
||||
function stepAt(ms: number) {
|
||||
now.mockReturnValue(1000 + ms);
|
||||
step();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pads = [];
|
||||
chords = 0;
|
||||
now = vi.spyOn(performance, "now").mockReturnValue(1000);
|
||||
window.addEventListener("gamepad:exitchord", onChord);
|
||||
installOnMouse(() => pads);
|
||||
storePlaying().setPlaying(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.removeEventListener("gamepad:exitchord", onChord);
|
||||
});
|
||||
|
||||
it("fires once Select+Start has been held for the full hold", () => {
|
||||
pads = [padHolding(...CHORD)];
|
||||
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS - 1);
|
||||
expect(chords).toBe(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS);
|
||||
expect(chords).toBe(1);
|
||||
});
|
||||
|
||||
it("waits for a release before a held chord can fire again", () => {
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 3);
|
||||
expect(chords).toBe(1);
|
||||
|
||||
pads = [padHolding()];
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 3 + 100);
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 4);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 5);
|
||||
expect(chords).toBe(2);
|
||||
});
|
||||
|
||||
it("starts the hold over when either button is let go", () => {
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(0);
|
||||
pads = [padHolding(PAD_BUTTON.back)];
|
||||
stepAt(1000);
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(1100);
|
||||
stepAt(1100 + EXIT_CHORD_HOLD_MS - 1);
|
||||
|
||||
expect(chords).toBe(0);
|
||||
});
|
||||
|
||||
it("ignores a disconnected pad's stale buttons", () => {
|
||||
// Firefox keeps disconnected entries in getGamepads() (#3851).
|
||||
pads = [{ ...padHolding(...CHORD), connected: false }];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 2);
|
||||
|
||||
expect(chords).toBe(0);
|
||||
});
|
||||
|
||||
it("ignores pads without the standard mapping", () => {
|
||||
pads = [{ ...padHolding(...CHORD), mapping: "" }];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 2);
|
||||
|
||||
expect(chords).toBe(0);
|
||||
});
|
||||
|
||||
it("stays quiet outside a game, where Select and Start drive the app", () => {
|
||||
storePlaying().setPlaying(false);
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 2);
|
||||
|
||||
expect(chords).toBe(0);
|
||||
});
|
||||
|
||||
it("holds off while an overlay sits over the game", () => {
|
||||
const dialog = { close: () => {}, persistent: true };
|
||||
pushEscapable(dialog);
|
||||
try {
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 2);
|
||||
} finally {
|
||||
popEscapable(dialog);
|
||||
}
|
||||
|
||||
expect(chords).toBe(0);
|
||||
});
|
||||
|
||||
it("stays fired after its dialog closes while the chord is still held", () => {
|
||||
const dialog = { close: () => {}, persistent: false };
|
||||
pads = [padHolding(...CHORD)];
|
||||
stepAt(0);
|
||||
stepAt(EXIT_CHORD_HOLD_MS);
|
||||
expect(chords).toBe(1);
|
||||
|
||||
pushEscapable(dialog);
|
||||
try {
|
||||
stepAt(EXIT_CHORD_HOLD_MS + 100);
|
||||
} finally {
|
||||
popEscapable(dialog);
|
||||
}
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 3);
|
||||
stepAt(EXIT_CHORD_HOLD_MS * 5);
|
||||
|
||||
expect(chords).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,7 +26,9 @@
|
||||
// Two contexts suppress this translation:
|
||||
// * Game running (storePlaying.playing): the emulator reads the pad
|
||||
// itself, so all translation is off. Otherwise B (shared by Circle /
|
||||
// Nintendo-A in the standard mapping) would quit the game.
|
||||
// Nintendo-A in the standard mapping) would quit the game. Holding
|
||||
// Select+Start instead fires `gamepad:exitchord`; a player opts into
|
||||
// a pad exit by listening for it.
|
||||
// * Controller-test screen (ACTIONS_DISABLED_PATHS): built-in actions
|
||||
// are muted so every button can be pressed and inspected in place.
|
||||
import { onBeforeUnmount } from "vue";
|
||||
@@ -51,6 +53,8 @@ const ACTIONS_DISABLED_PATHS = new Set<string>(["/controller-debug"]);
|
||||
const INITIAL_DELAY_MS = 350;
|
||||
const REPEAT_MS = 120;
|
||||
export const AXIS_THRESHOLD = 0.5;
|
||||
// Outlasts anything a game itself binds to Select+Start.
|
||||
export const EXIT_CHORD_HOLD_MS = 1500;
|
||||
|
||||
// Short symbolic name → W3C standard-mapping button index, so a view can
|
||||
// read raw pad state without memorising indices. Exhaustive over the standard
|
||||
@@ -92,6 +96,7 @@ export interface GamepadButtonEventDetail {
|
||||
declare global {
|
||||
interface WindowEventMap {
|
||||
"gamepad:buttondown": CustomEvent<GamepadButtonEventDetail>;
|
||||
"gamepad:exitchord": Event;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +128,15 @@ export function isUsablePad(pad: Gamepad | null): pad is Gamepad {
|
||||
return pad !== null && pad.connected;
|
||||
}
|
||||
|
||||
// Other mappings don't guarantee the Back/Start indices.
|
||||
function holdsExitChord(pad: Gamepad): boolean {
|
||||
return (
|
||||
pad.mapping === "standard" &&
|
||||
!!pad.buttons[PAD_BUTTON.back]?.pressed &&
|
||||
!!pad.buttons[PAD_BUTTON.start]?.pressed
|
||||
);
|
||||
}
|
||||
|
||||
function dispatchKey(binding: Binding) {
|
||||
const target =
|
||||
(document.activeElement as HTMLElement | null) ?? document.body;
|
||||
@@ -242,6 +256,10 @@ export function useGamepad() {
|
||||
const { setModality } = useInputModality();
|
||||
let rafId = 0;
|
||||
let everSawPad = false;
|
||||
let chordHeldSince: number | null = null;
|
||||
// Cleared only on release, so a chord still held after its dialog is
|
||||
// cancelled doesn't reopen it.
|
||||
let chordFired = false;
|
||||
|
||||
const onAnyInput = () => setModality("pad");
|
||||
const onConnect = () => setModality("pad");
|
||||
@@ -285,10 +303,12 @@ export function useGamepad() {
|
||||
// On the controller-test screen the built-in actions are muted so
|
||||
// every button can be pressed and inspected without side effects.
|
||||
const actionsDisabled = ACTIONS_DISABLED_PATHS.has(route.path);
|
||||
let chordHeld = false;
|
||||
|
||||
for (const pad of pads) {
|
||||
// Skip disconnected phantom gamepads.
|
||||
if (!isUsablePad(pad)) continue;
|
||||
chordHeld ||= holdsExitChord(pad);
|
||||
const key = `${pad.index}:${pad.id}`;
|
||||
const st = (states[key] ||= {
|
||||
buttons: {},
|
||||
@@ -353,6 +373,20 @@ export function useGamepad() {
|
||||
}
|
||||
}
|
||||
|
||||
// B is muted during play, so a long Select+Start hold is the pad's exit.
|
||||
if (!chordHeld) {
|
||||
chordHeldSince = null;
|
||||
chordFired = false;
|
||||
} else if (!gameOwnsInput) {
|
||||
chordHeldSince = null;
|
||||
} else if (!chordFired) {
|
||||
chordHeldSince ??= t;
|
||||
if (t - chordHeldSince >= EXIT_CHORD_HOLD_MS) {
|
||||
chordFired = true;
|
||||
window.dispatchEvent(new Event("gamepad:exitchord"));
|
||||
}
|
||||
}
|
||||
|
||||
rafId = requestAnimationFrame(loop);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import { useGridNav } from "./index";
|
||||
|
||||
vi.mock("vue-router", () => ({ useRoute: () => ({ fullPath: "/gallery" }) }));
|
||||
|
||||
// Two rows of two cells; each cell holds a link, a button, and a control
|
||||
// its component already took out of the tab order.
|
||||
const Grid = defineComponent({
|
||||
setup() {
|
||||
const root = ref<HTMLElement | null>(null);
|
||||
useGridNav(root, { rowSelector: ".row", roving: true });
|
||||
const cell = (id: number) =>
|
||||
h("div", { class: "cell", role: "gridcell" }, [
|
||||
h("a", { href: `/rom/${id}`, "data-focus-key": `rom-${id}` }, "Game"),
|
||||
h("button", { class: "fav" }, "Favorite"),
|
||||
h("button", { class: "skip", tabindex: "-1" }, "Skip"),
|
||||
]);
|
||||
return () =>
|
||||
h("div", { ref: root, role: "grid" }, [
|
||||
h("div", { class: "row", role: "row" }, [cell(1), cell(2)]),
|
||||
h("div", { class: "row", role: "row" }, [cell(3), cell(4)]),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
function tabbable(wrapper: ReturnType<typeof mount>): string[] {
|
||||
return wrapper
|
||||
.findAll("a, button")
|
||||
.filter((el) => el.attributes("tabindex") !== "-1")
|
||||
.map((el) => el.attributes("href") ?? el.classes()[0]);
|
||||
}
|
||||
|
||||
function focusLink(id: number) {
|
||||
(document.querySelector(`a[href='/rom/${id}']`) as HTMLElement).focus();
|
||||
}
|
||||
|
||||
function press(key: string, init: KeyboardEventInit = {}) {
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key, ...init }));
|
||||
}
|
||||
|
||||
function focusedHref(): string | null | undefined {
|
||||
return document.activeElement?.getAttribute("href");
|
||||
}
|
||||
|
||||
async function frame() {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
describe("useGridNav roving", () => {
|
||||
let wrapper: ReturnType<typeof mount>;
|
||||
|
||||
beforeEach(async () => {
|
||||
setActivePinia(createPinia());
|
||||
wrapper = mount(Grid, { attachTo: document.body });
|
||||
await frame();
|
||||
});
|
||||
|
||||
afterEach(() => wrapper.unmount());
|
||||
|
||||
it("leaves only the first cell's controls in the tab order", () => {
|
||||
expect(tabbable(wrapper)).toEqual(["/rom/1", "fav"]);
|
||||
});
|
||||
|
||||
it("moves the tab stop with the arrow keys", async () => {
|
||||
(wrapper.get("a[href='/rom/1']").element as HTMLElement).focus();
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown" }));
|
||||
await nextTick();
|
||||
|
||||
expect(document.activeElement?.getAttribute("href")).toBe("/rom/3");
|
||||
expect(tabbable(wrapper)).toEqual(["/rom/3", "fav"]);
|
||||
});
|
||||
|
||||
it("follows focus that arrives another way, such as a click", async () => {
|
||||
const fav = wrapper.findAll("button.fav")[3].element as HTMLElement;
|
||||
fav.focus();
|
||||
// happy-dom's focus() fires no focusin.
|
||||
fav.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
|
||||
await nextTick();
|
||||
|
||||
expect(tabbable(wrapper)).toEqual(["/rom/4", "fav"]);
|
||||
});
|
||||
|
||||
it("moves to the row's ends on Home and End", async () => {
|
||||
focusLink(1);
|
||||
press("End");
|
||||
expect(focusedHref()).toBe("/rom/2");
|
||||
press("Home");
|
||||
expect(focusedHref()).toBe("/rom/1");
|
||||
});
|
||||
|
||||
it("moves to the grid's ends on Ctrl+Home and Ctrl+End", async () => {
|
||||
focusLink(1);
|
||||
press("End", { ctrlKey: true });
|
||||
await frame();
|
||||
await frame();
|
||||
expect(focusedHref()).toBe("/rom/4");
|
||||
press("Home", { ctrlKey: true });
|
||||
await frame();
|
||||
await frame();
|
||||
expect(focusedHref()).toBe("/rom/1");
|
||||
});
|
||||
|
||||
it("keeps the column on PageDown and PageUp", async () => {
|
||||
focusLink(2);
|
||||
press("PageDown");
|
||||
expect(focusedHref()).toBe("/rom/4");
|
||||
press("PageUp");
|
||||
expect(focusedHref()).toBe("/rom/2");
|
||||
});
|
||||
|
||||
it("never puts a control its component excluded back in the order", async () => {
|
||||
(wrapper.get("a[href='/rom/2']").element as HTMLElement).focus();
|
||||
await nextTick();
|
||||
|
||||
expect(
|
||||
wrapper.findAll("button.skip").map((el) => el.attributes("tabindex")),
|
||||
).toEqual(["-1", "-1", "-1", "-1"]);
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,9 @@
|
||||
// focusable selector, otherwise the first focusable descendant.
|
||||
// * ArrowLeft / ArrowRight → prev / next cell in the current row.
|
||||
// * ArrowUp / ArrowDown → same column in the prev / next row (clamped).
|
||||
// * Home / End → first / last cell in the row; with Ctrl (or a row of
|
||||
// one cell), the first cell of the grid / the last.
|
||||
// * PageUp / PageDown → same column, one viewport of rows up / down.
|
||||
// * On autofocus we remember a "preferred column" and restore it when
|
||||
// moving up/down through rows of different lengths, a common media-UI
|
||||
// pattern so row switching doesn't permanently lose horizontal place.
|
||||
@@ -51,8 +54,52 @@ export interface UseGridNavOptions {
|
||||
* element itself is the single focusable cell, or a custom selector
|
||||
* to skip non-focusable spacers / dividers. */
|
||||
getCells?: (row: HTMLElement) => HTMLElement[];
|
||||
/** Keep a single tab stop in the grid, as the ARIA grid pattern asks:
|
||||
* the controls of the active cell stay tabbable and every other cell's
|
||||
* get `tabindex="-1"`, including cells that mount later. */
|
||||
roving?: boolean;
|
||||
/** Renders the grid's first or last row when it virtualises its rows, so
|
||||
* Ctrl+Home / Ctrl+End can reach rows that aren't mounted. */
|
||||
revealEdge?: (edge: "first" | "last") => void;
|
||||
}
|
||||
|
||||
const GRID_KEYS = new Set([
|
||||
"ArrowLeft",
|
||||
"ArrowRight",
|
||||
"ArrowUp",
|
||||
"ArrowDown",
|
||||
"Home",
|
||||
"End",
|
||||
"PageUp",
|
||||
"PageDown",
|
||||
]);
|
||||
|
||||
function nextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
|
||||
}
|
||||
|
||||
// Height of the box the grid scrolls in, which is one page of rows.
|
||||
function pageHeight(el: HTMLElement): number {
|
||||
for (let node = el.parentElement; node; node = node.parentElement) {
|
||||
const overflow = getComputedStyle(node).overflowY;
|
||||
if (overflow === "auto" || overflow === "scroll") return node.clientHeight;
|
||||
}
|
||||
return window.innerHeight;
|
||||
}
|
||||
|
||||
// Controls the roving mode may take out of the tab order. Unlike
|
||||
// FOCUSABLE_SELECTOR, this still matches them once they are at -1.
|
||||
const ROVING_CANDIDATES = [
|
||||
"a[href]",
|
||||
"button:not([disabled])",
|
||||
"input:not([disabled])",
|
||||
"select:not([disabled])",
|
||||
"textarea:not([disabled])",
|
||||
"[tabindex]",
|
||||
].join(",");
|
||||
// The tabindex a control had before the roving mode touched it.
|
||||
const ROVING_ORIGINAL = "data-grid-roving";
|
||||
|
||||
export function useGridNav(
|
||||
rootRef: Ref<HTMLElement | null>,
|
||||
options: UseGridNavOptions = {},
|
||||
@@ -68,6 +115,10 @@ export function useGridNav(
|
||||
const route = useRoute();
|
||||
const focusStore = storeFocusRestoration();
|
||||
let preferredCol = 0;
|
||||
let activeKey: string | null = null;
|
||||
// The cell this composable last focused, to tell when focus arrived another
|
||||
// way (a click) and the remembered column no longer applies.
|
||||
let navCell: HTMLElement | null = null;
|
||||
|
||||
// Walk up from `node` looking for a `[data-focus-key]` carrier. Tiles
|
||||
// mark their root with this so focus can survive navigation.
|
||||
@@ -81,6 +132,15 @@ export function useGridNav(
|
||||
return null;
|
||||
}
|
||||
|
||||
// A cell's own `[data-focus-key]`, or that of the tile inside it.
|
||||
function cellKey(cell: HTMLElement): string | null {
|
||||
return (
|
||||
cell.getAttribute("data-focus-key") ??
|
||||
cell.querySelector("[data-focus-key]")?.getAttribute("data-focus-key") ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function rows(): HTMLElement[] {
|
||||
if (options.getRows) return options.getRows();
|
||||
if (!rootRef.value) return [];
|
||||
@@ -92,11 +152,52 @@ export function useGridNav(
|
||||
}
|
||||
|
||||
function focusableIn(el: HTMLElement): HTMLElement {
|
||||
if (el.matches(FOCUSABLE_SELECTOR)) return el;
|
||||
const inner = el.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
|
||||
const selector = options.roving ? ROVING_CANDIDATES : FOCUSABLE_SELECTOR;
|
||||
if (el.matches(selector)) return el;
|
||||
const inner = el.querySelector<HTMLElement>(selector);
|
||||
return inner ?? el;
|
||||
}
|
||||
|
||||
// The controls of a cell that are tabbable on their own, so the roving
|
||||
// mode leaves alone the ones a component already took out of the order.
|
||||
function rovingControls(cell: HTMLElement): HTMLElement[] {
|
||||
const found = Array.from(
|
||||
cell.querySelectorAll<HTMLElement>(ROVING_CANDIDATES),
|
||||
);
|
||||
if (cell.matches(ROVING_CANDIDATES)) found.unshift(cell);
|
||||
return found.filter((el) => {
|
||||
if (!el.hasAttribute(ROVING_ORIGINAL)) {
|
||||
el.setAttribute(ROVING_ORIGINAL, el.getAttribute("tabindex") ?? "");
|
||||
}
|
||||
return el.getAttribute(ROVING_ORIGINAL) !== "-1";
|
||||
});
|
||||
}
|
||||
|
||||
function syncRoving() {
|
||||
if (!options.roving) return;
|
||||
const allCells = rows().flatMap((row) => cells(row));
|
||||
const active =
|
||||
allCells.find((cell) => activeKey && cellKey(cell) === activeKey) ??
|
||||
allCells.find((cell) => rovingControls(cell).length > 0);
|
||||
for (const cell of allCells) {
|
||||
for (const el of rovingControls(cell)) {
|
||||
const original = el.getAttribute(ROVING_ORIGINAL) ?? "";
|
||||
if (cell !== active) el.setAttribute("tabindex", "-1");
|
||||
else if (original) el.setAttribute("tabindex", original);
|
||||
else el.removeAttribute("tabindex");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let syncFrame = 0;
|
||||
function scheduleSyncRoving() {
|
||||
if (!options.roving || syncFrame) return;
|
||||
syncFrame = requestAnimationFrame(() => {
|
||||
syncFrame = 0;
|
||||
syncRoving();
|
||||
});
|
||||
}
|
||||
|
||||
function current(): { rowIdx: number; colIdx: number } | null {
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
if (!active) return null;
|
||||
@@ -127,20 +228,26 @@ export function useGridNav(
|
||||
const clamped = Math.min(Math.max(colIdx, 0), cs.length - 1);
|
||||
const cell = cs[clamped];
|
||||
const target = focusableIn(cell);
|
||||
navCell = cell;
|
||||
|
||||
// Roving tabindex: only the current cell is a tab stop, every other
|
||||
// cell sets tabindex="-1". Lets the user land on the last focused
|
||||
// card via Tab from outside the grid, and keeps Shift+Tab escape
|
||||
// behaviour clean. Borrowed from the v1 console useRovingDom.
|
||||
const previous = rootRef.value?.querySelectorAll<HTMLElement>(
|
||||
"[data-grid-nav-cell]",
|
||||
);
|
||||
previous?.forEach((other) => {
|
||||
other.setAttribute("tabindex", "-1");
|
||||
other.removeAttribute("data-grid-nav-cell");
|
||||
});
|
||||
target.setAttribute("data-grid-nav-cell", "");
|
||||
target.setAttribute("tabindex", "0");
|
||||
if (options.roving) {
|
||||
activeKey = cellKey(cell);
|
||||
syncRoving();
|
||||
} else {
|
||||
const previous = rootRef.value?.querySelectorAll<HTMLElement>(
|
||||
"[data-grid-nav-cell]",
|
||||
);
|
||||
previous?.forEach((other) => {
|
||||
other.setAttribute("tabindex", "-1");
|
||||
other.removeAttribute("data-grid-nav-cell");
|
||||
});
|
||||
target.setAttribute("data-grid-nav-cell", "");
|
||||
target.setAttribute("tabindex", "0");
|
||||
}
|
||||
|
||||
target.focus({ preventScroll: true });
|
||||
|
||||
@@ -184,7 +291,7 @@ export function useGridNav(
|
||||
for (let r = 0; r < rs.length; r++) {
|
||||
const cs = cells(rs[r]);
|
||||
for (let c = 0; c < cs.length; c++) {
|
||||
if (focusKeyOf(cs[c]) === savedKey) {
|
||||
if (cellKey(cs[c]) === savedKey) {
|
||||
preferredCol = c;
|
||||
focusAt(r, c, { verticalJump: true });
|
||||
return true;
|
||||
@@ -194,15 +301,67 @@ export function useGridNav(
|
||||
return false;
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (
|
||||
e.key !== "ArrowLeft" &&
|
||||
e.key !== "ArrowRight" &&
|
||||
e.key !== "ArrowUp" &&
|
||||
e.key !== "ArrowDown"
|
||||
) {
|
||||
return;
|
||||
function hasControl(cell: HTMLElement): boolean {
|
||||
const selector = options.roving ? ROVING_CANDIDATES : FOCUSABLE_SELECTOR;
|
||||
return focusableIn(cell) !== cell || cell.matches(selector);
|
||||
}
|
||||
|
||||
// Focuses the first or last cell that holds a control, skipping skeletons.
|
||||
function focusEdge(edge: "first" | "last") {
|
||||
const rs = rows();
|
||||
const order = edge === "first" ? rs.keys() : [...rs.keys()].reverse();
|
||||
for (const r of order) {
|
||||
const cs = cells(rs[r]);
|
||||
const cols = edge === "first" ? cs.keys() : [...cs.keys()].reverse();
|
||||
for (const c of cols) {
|
||||
if (!hasControl(cs[c])) continue;
|
||||
preferredCol = c;
|
||||
focusAt(r, c, { verticalJump: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the outermost cell on `edge` holds a loaded control yet.
|
||||
function edgeLoaded(edge: "first" | "last"): boolean {
|
||||
const rs = rows();
|
||||
const row = edge === "first" ? rs[0] : rs[rs.length - 1];
|
||||
if (!row) return false;
|
||||
const cs = cells(row);
|
||||
const cell = edge === "first" ? cs[0] : cs[cs.length - 1];
|
||||
return !!cell && hasControl(cell);
|
||||
}
|
||||
|
||||
async function jumpToEdge(edge: "first" | "last") {
|
||||
if (options.revealEdge) {
|
||||
options.revealEdge(edge);
|
||||
// Two frames for the scroll to mount the edge rows, then up to about
|
||||
// two seconds for their data to load.
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
for (let i = 0; i < 120 && !edgeLoaded(edge); i++) await nextFrame();
|
||||
}
|
||||
focusEdge(edge);
|
||||
}
|
||||
|
||||
// The row about one viewport above or below `from`, clamped to the rows
|
||||
// that are mounted.
|
||||
function pageRow(rs: HTMLElement[], from: number, dir: 1 | -1): number {
|
||||
const top = rs[from].getBoundingClientRect().top;
|
||||
const target = top + dir * pageHeight(rs[from]);
|
||||
let best = from;
|
||||
for (let r = from + dir; r >= 0 && r < rs.length; r += dir) {
|
||||
const rowTop = rs[r].getBoundingClientRect().top;
|
||||
if (dir === 1 ? rowTop > target : rowTop < target) break;
|
||||
best = r;
|
||||
}
|
||||
return best === from
|
||||
? Math.min(Math.max(from + dir, 0), rs.length - 1)
|
||||
: best;
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (!GRID_KEYS.has(e.key)) return;
|
||||
if (!rootRef.value) return;
|
||||
// Only steer when focus is already inside the grid; don't hijack
|
||||
// arrow keys meant for input fields, menus, or other widgets.
|
||||
@@ -215,6 +374,7 @@ export function useGridNav(
|
||||
let { rowIdx, colIdx } = cur;
|
||||
const rs = rows();
|
||||
const rowCells = cells(rs[rowIdx]);
|
||||
if (rowCells[colIdx] !== navCell) preferredCol = colIdx;
|
||||
let verticalJump = false;
|
||||
|
||||
if (e.key === "ArrowLeft") {
|
||||
@@ -235,6 +395,20 @@ export function useGridNav(
|
||||
rowIdx += 1;
|
||||
colIdx = preferredCol;
|
||||
verticalJump = true;
|
||||
} else if (e.key === "Home" || e.key === "End") {
|
||||
// A row of one cell has nowhere to go inside it, so it moves through
|
||||
// the grid instead.
|
||||
if (e.ctrlKey || e.metaKey || rowCells.length === 1) {
|
||||
e.preventDefault();
|
||||
void jumpToEdge(e.key === "Home" ? "first" : "last");
|
||||
return;
|
||||
}
|
||||
colIdx = e.key === "Home" ? 0 : rowCells.length - 1;
|
||||
preferredCol = colIdx;
|
||||
} else if (e.key === "PageUp" || e.key === "PageDown") {
|
||||
rowIdx = pageRow(rs, rowIdx, e.key === "PageDown" ? 1 : -1);
|
||||
colIdx = preferredCol;
|
||||
verticalJump = true;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
@@ -264,16 +438,30 @@ export function useGridNav(
|
||||
if (!rootRef.value?.contains(target)) return;
|
||||
const key = focusKeyOf(target);
|
||||
if (key) focusStore.save(route.fullPath, key);
|
||||
if (options.roving) {
|
||||
const cell = rows()
|
||||
.flatMap((row) => cells(row))
|
||||
.find((c) => c.contains(target));
|
||||
const cellFocusKey = cell ? cellKey(cell) : null;
|
||||
if (cellFocusKey && cellFocusKey !== activeKey) {
|
||||
activeKey = cellFocusKey;
|
||||
syncRoving();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener("keydown", onKey);
|
||||
window.addEventListener("focusin", onFocusIn);
|
||||
if (rootRef.value) {
|
||||
observer = new MutationObserver(() => maybeAutofocus());
|
||||
observer = new MutationObserver(() => {
|
||||
scheduleSyncRoving();
|
||||
maybeAutofocus();
|
||||
});
|
||||
observer.observe(rootRef.value, { childList: true, subtree: true });
|
||||
}
|
||||
requestAnimationFrame(maybeAutofocus);
|
||||
scheduleSyncRoving();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -281,6 +469,7 @@ export function useGridNav(
|
||||
window.removeEventListener("focusin", onFocusIn);
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
cancelAnimationFrame(syncFrame);
|
||||
});
|
||||
|
||||
// Reactively autofocus when modality becomes "pad". Useful when the
|
||||
|
||||
@@ -4,6 +4,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, h, ref } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { useGridNav } from "@/v2/composables/useGridNav";
|
||||
import {
|
||||
type EscapableEntry,
|
||||
popEscapable,
|
||||
pushEscapable,
|
||||
} from "@/v2/lib/overlays/RDialog/escapeStack";
|
||||
import { useSpatialNav } from "./index";
|
||||
|
||||
vi.mock("vue-router", () => ({
|
||||
@@ -86,7 +91,38 @@ describe("useSpatialNav", () => {
|
||||
wrapper = mount(Page, { attachTo: document.body });
|
||||
});
|
||||
|
||||
// A dialog below the page with Cancel and Confirm side by side.
|
||||
let dialog: EscapableEntry | null = null;
|
||||
let dialogPanel: HTMLElement | null = null;
|
||||
function openDialog(withPanel = true): void {
|
||||
const panel = document.createElement("div");
|
||||
for (const [id, x] of [
|
||||
["cancel", 0],
|
||||
["confirm", 100],
|
||||
] as const) {
|
||||
const button = document.createElement("button");
|
||||
button.id = id;
|
||||
button.dataset.x = String(x);
|
||||
button.dataset.y = "600";
|
||||
panel.append(button);
|
||||
}
|
||||
document.body.append(panel);
|
||||
dialogPanel = panel;
|
||||
dialog = {
|
||||
close: () => {},
|
||||
persistent: true,
|
||||
panel: withPanel ? () => panel : undefined,
|
||||
};
|
||||
pushEscapable(dialog);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (dialog) {
|
||||
popEscapable(dialog);
|
||||
dialog = null;
|
||||
}
|
||||
dialogPanel?.remove();
|
||||
dialogPanel = null;
|
||||
wrapper?.unmount();
|
||||
wrapper = null;
|
||||
restores.splice(0).forEach((restore) => restore());
|
||||
@@ -157,4 +193,40 @@ describe("useSpatialNav", () => {
|
||||
|
||||
expect(document.activeElement).toBe(el("play"));
|
||||
});
|
||||
|
||||
it("moves between an open dialog's buttons", () => {
|
||||
openDialog();
|
||||
el("cancel").focus();
|
||||
|
||||
expect(press("ArrowRight").defaultPrevented).toBe(true);
|
||||
expect(document.activeElement).toBe(el("confirm"));
|
||||
});
|
||||
|
||||
it("keeps focus inside the open dialog", () => {
|
||||
openDialog();
|
||||
el("cancel").focus();
|
||||
|
||||
press("ArrowUp");
|
||||
|
||||
expect(document.activeElement).toBe(el("cancel"));
|
||||
});
|
||||
|
||||
it("moves inside a dialog opened over a running game", () => {
|
||||
storePlaying().setPlaying(true);
|
||||
openDialog();
|
||||
el("cancel").focus();
|
||||
|
||||
press("ArrowRight");
|
||||
|
||||
expect(document.activeElement).toBe(el("confirm"));
|
||||
});
|
||||
|
||||
it("leaves an overlay without a panel to its owner", () => {
|
||||
openDialog(false);
|
||||
el("tab").focus();
|
||||
|
||||
press("ArrowUp");
|
||||
|
||||
expect(document.activeElement).toBe(el("tab"));
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,10 @@
|
||||
// The grids listen on `document`, which an event reaches before `window`.
|
||||
import { onBeforeUnmount } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { hasOpenEscapable } from "@/v2/lib/overlays/RDialog/escapeStack";
|
||||
import {
|
||||
hasOpenEscapable,
|
||||
topEscapablePanel,
|
||||
} from "@/v2/lib/overlays/RDialog/escapeStack";
|
||||
import {
|
||||
ARROW_DIRECTIONS,
|
||||
FOCUSABLE_SELECTOR,
|
||||
@@ -77,10 +80,14 @@ function isInView(el: HTMLElement): boolean {
|
||||
return !hit || el.contains(hit) || hit.contains(el);
|
||||
}
|
||||
|
||||
/** Moves focus from `from` to the nearest control in `dir`, if any. */
|
||||
export function moveFocus(from: HTMLElement, dir: SpatialDirection): boolean {
|
||||
/** Moves focus from `from` to the nearest control in `dir` under `scope`. */
|
||||
export function moveFocus(
|
||||
from: HTMLElement,
|
||||
dir: SpatialDirection,
|
||||
scope: ParentNode = document,
|
||||
): boolean {
|
||||
const candidates = Array.from(
|
||||
document.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
|
||||
scope.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
|
||||
)
|
||||
.filter((el) => el !== from && !el.contains(from) && isNavigable(el))
|
||||
.map((el) => ({ item: el, box: el.getBoundingClientRect() }));
|
||||
@@ -117,13 +124,20 @@ export function useSpatialNav() {
|
||||
const dir = ARROW_DIRECTIONS[e.key];
|
||||
if (!dir || e.defaultPrevented) return;
|
||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
// A running game reads the arrows itself, and an open overlay keeps
|
||||
// focus inside its own panel.
|
||||
if (playingStore.playing || hasOpenEscapable()) return;
|
||||
const active = document.activeElement;
|
||||
if (!(active instanceof HTMLElement) || active === document.body) return;
|
||||
if (ownsArrowKeys(active)) return;
|
||||
if (moveFocus(active, dir)) e.preventDefault();
|
||||
// An open overlay, a dialog over a game included, keeps focus inside
|
||||
// its own panel; otherwise a running game reads the arrows itself.
|
||||
let scope: ParentNode = document;
|
||||
if (hasOpenEscapable()) {
|
||||
const panel = topEscapablePanel();
|
||||
if (!panel?.contains(active)) return;
|
||||
scope = panel;
|
||||
} else if (playingStore.playing) {
|
||||
return;
|
||||
}
|
||||
if (moveFocus(active, dir, scope)) e.preventDefault();
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", onKey);
|
||||
|
||||
@@ -2,7 +2,11 @@ import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { effectScope, nextTick, ref } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { installStageActiveClass, useStageActive } from "./index";
|
||||
import {
|
||||
installStageActiveClass,
|
||||
usePlayingWhile,
|
||||
useStageActive,
|
||||
} from "./index";
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
@@ -50,6 +54,31 @@ describe("useStageActive", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("usePlayingWhile", () => {
|
||||
it("mirrors the active source into the playing flag", async () => {
|
||||
const active = ref(true);
|
||||
const scope = effectScope();
|
||||
scope.run(() => usePlayingWhile(active));
|
||||
const store = storePlaying();
|
||||
expect(store.playing).toBe(true);
|
||||
|
||||
active.value = false;
|
||||
await nextTick();
|
||||
expect(store.playing).toBe(false);
|
||||
scope.stop();
|
||||
});
|
||||
|
||||
it("clears the flag when its owning scope is disposed", () => {
|
||||
const scope = effectScope();
|
||||
scope.run(() => usePlayingWhile(() => true));
|
||||
const store = storePlaying();
|
||||
expect(store.playing).toBe(true);
|
||||
|
||||
scope.stop();
|
||||
expect(store.playing).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("installStageActiveClass", () => {
|
||||
function htmlHasClass(): boolean {
|
||||
return document.documentElement.classList.contains("r-v2-stage-active");
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import { onScopeDispose, toValue, watch, type MaybeRefOrGetter } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
|
||||
// Mirrors a source into one of the playing store's flags, cleared on dispose.
|
||||
function mirrorFlag(
|
||||
source: MaybeRefOrGetter<boolean>,
|
||||
set: (on: boolean) => void,
|
||||
): void {
|
||||
watch(() => toValue(source), set, { immediate: true });
|
||||
onScopeDispose(() => set(false));
|
||||
}
|
||||
|
||||
/** Mirrors a player's running state into the global stage flag that
|
||||
* unmounts the app chrome and zeroes the nav-height tokens. */
|
||||
export function useStageActive(running: MaybeRefOrGetter<boolean>): void {
|
||||
const playingStore = storePlaying();
|
||||
// Deliberately not the `playing` flag: that one also spans pre-stage
|
||||
// phases (Stream sets it while loading behind its config screen).
|
||||
watch(
|
||||
() => toValue(running),
|
||||
(active) => playingStore.setStageActive(active),
|
||||
{ immediate: true },
|
||||
);
|
||||
onScopeDispose(() => playingStore.setStageActive(false));
|
||||
mirrorFlag(running, (on) => playingStore.setStageActive(on));
|
||||
}
|
||||
|
||||
/** Mirrors a session, launch or pending claim included, into the global
|
||||
* playing flag, which hands the controller from useGamepad to the session. */
|
||||
export function usePlayingWhile(active: MaybeRefOrGetter<boolean>): void {
|
||||
const playingStore = storePlaying();
|
||||
mirrorFlag(active, (on) => playingStore.setPlaying(on));
|
||||
}
|
||||
|
||||
/** Mirrors the flag onto <html> (next to the theme classes) so
|
||||
|
||||
@@ -397,6 +397,34 @@ export const Bare: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const Decorative: Story = {
|
||||
render: () => ({
|
||||
components: { RCheckbox },
|
||||
setup: () => ({ checked: ref(true) }),
|
||||
template: `
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
:aria-checked="checked"
|
||||
aria-label="Chrono Trigger"
|
||||
style="display:inline-flex;align-items:center;gap:8px;padding:8px 12px"
|
||||
@click="checked = !checked"
|
||||
>
|
||||
<RCheckbox :model-value="checked" decorative bare hide-details shape="circle" />
|
||||
Chrono Trigger
|
||||
</button>
|
||||
`,
|
||||
}),
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Use `decorative` when an enclosing control owns the state, such as a selectable card: the box mirrors it with no input of its own.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// ── Motion ──────────────────────────────────────────────────────────
|
||||
|
||||
export const Toggle: Story = {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { parse as parseSfc } from "@vue/compiler-sfc";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import postcss from "postcss";
|
||||
import type { Rule } from "postcss";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import source from "./RCheckbox.vue?raw";
|
||||
import { RCheckbox } from "./index";
|
||||
|
||||
// happy-dom has no layout, so the stylesheet is checked directly.
|
||||
function declarationsFor(selector: string): Record<string, string> {
|
||||
@@ -27,3 +29,16 @@ describe("RCheckbox native input", () => {
|
||||
expect(declarationsFor(".r-checkbox").position).toBe("relative");
|
||||
});
|
||||
});
|
||||
|
||||
describe("RCheckbox decorative", () => {
|
||||
it("draws the box without an input or label", () => {
|
||||
const wrapper = mount(RCheckbox, {
|
||||
props: { modelValue: true, decorative: true },
|
||||
});
|
||||
|
||||
expect(wrapper.find("input").exists()).toBe(false);
|
||||
expect(wrapper.find("label").exists()).toBe(false);
|
||||
expect(wrapper.find(".r-checkbox").attributes("aria-hidden")).toBe("true");
|
||||
expect(wrapper.classes()).toContain("r-checkbox--checked");
|
||||
});
|
||||
});
|
||||
@@ -64,6 +64,9 @@ interface Props {
|
||||
/** Error tone: red box + red label. */
|
||||
error?: boolean;
|
||||
errorMessages?: string | string[];
|
||||
/** Draw the box only, with no input, for a mirror of state that an
|
||||
* enclosing control already exposes. Hidden from assistive tech. */
|
||||
decorative?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
@@ -83,6 +86,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
bare: false,
|
||||
error: false,
|
||||
errorMessages: () => [],
|
||||
decorative: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -204,11 +208,15 @@ const hasLabel = computed(
|
||||
'--r-cb-fill': fillColor,
|
||||
}"
|
||||
>
|
||||
<!-- eslint-disable-next-line vuejs-accessibility/label-has-for -- the native checkbox input is nested inside this label, a valid control association -->
|
||||
<label class="r-checkbox">
|
||||
<component
|
||||
:is="decorative ? 'span' : 'label'"
|
||||
class="r-checkbox"
|
||||
:aria-hidden="decorative || undefined"
|
||||
>
|
||||
<!-- Native input: visually hidden but kept in the layout for
|
||||
form submission, keyboard, and screen reader support. -->
|
||||
<input
|
||||
v-if="!decorative"
|
||||
ref="inputRef"
|
||||
type="checkbox"
|
||||
class="r-checkbox__input"
|
||||
@@ -267,7 +275,7 @@ const hasLabel = computed(
|
||||
<slot name="subtitle">{{ subtitle }}</slot>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</component>
|
||||
|
||||
<div v-if="showDetailsRow" class="r-checkbox__details">
|
||||
<span v-for="(m, i) in messages" :key="i" class="r-checkbox__message">
|
||||
|
||||
@@ -74,6 +74,11 @@ export function onEscapableOpen(listener: () => void): () => void {
|
||||
return () => openListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** The topmost overlay's panel; null when none is open or it has no panel. */
|
||||
export function topEscapablePanel(): HTMLElement | null {
|
||||
return stack[stack.length - 1]?.panel?.() ?? null;
|
||||
}
|
||||
|
||||
/** True when `el` is covered by the topmost overlay rather than living
|
||||
* inside it. A panel-less entry has no opinion and covers nothing. */
|
||||
export function isUnderOpenEscapable(el: Node | null): boolean {
|
||||
|
||||
@@ -121,7 +121,9 @@ const dashOffset = computed(() => 100 - progressValue.value);
|
||||
"
|
||||
:aria-valuemin="decorative ? undefined : 0"
|
||||
:aria-valuemax="decorative ? undefined : 100"
|
||||
:aria-valuenow="!decorative && !indeterminate ? progressValue : undefined"
|
||||
:aria-valuenow="
|
||||
!decorative && !indeterminate ? Math.floor(progressValue) : undefined
|
||||
"
|
||||
:aria-busy="!decorative && indeterminate ? true : undefined"
|
||||
>
|
||||
<svg class="r-pc__svg" :viewBox="`0 0 ${diameter} ${diameter}`">
|
||||
|
||||
@@ -100,7 +100,7 @@ const fillStyle = computed(() =>
|
||||
);
|
||||
|
||||
const ariaValueNow = computed(() =>
|
||||
props.indeterminate ? undefined : clampedValue.value,
|
||||
props.indeterminate ? undefined : Math.floor(clampedValue.value),
|
||||
);
|
||||
|
||||
const wrapperStyle = computed(() => {
|
||||
|
||||
@@ -86,3 +86,30 @@ describe("RVirtualScroller offsetShift", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("RVirtualScroller body", () => {
|
||||
it("wraps the head and the rows, but not the prepend, in bodyAttrs", async () => {
|
||||
const wrapper = mount(RVirtualScroller, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
items,
|
||||
getItemHeight: () => ROW_H,
|
||||
height: VIEWPORT_H,
|
||||
bodyAttrs: { role: "grid", "aria-rowcount": 6 },
|
||||
},
|
||||
slots: {
|
||||
prepend: `<div class="toolbar" />`,
|
||||
head: `<div class="header-row" />`,
|
||||
default: `<div class="row" />`,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
const body = wrapper.get("[role=grid]");
|
||||
expect(body.attributes("aria-rowcount")).toBe("6");
|
||||
expect(body.find(".header-row").exists()).toBe(true);
|
||||
expect(body.findAll(".row")).toHaveLength(items.length);
|
||||
expect(body.find(".toolbar").exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -73,6 +73,10 @@ interface Props {
|
||||
* instead of squashing / clipping). The virtualised inner gets this as
|
||||
* `min-width` and the container gets `overflow-x: auto`. Number = px. */
|
||||
minContentWidth?: number | string;
|
||||
/** Attributes for the element wrapping `#head` and the items, e.g. a
|
||||
* `role="grid"` that must own a header row and the rows but not the
|
||||
* `#prepend` band. */
|
||||
bodyAttrs?: Record<string, string | number | boolean | undefined>;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
@@ -81,6 +85,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
offsetShift: undefined,
|
||||
getItemKey: undefined,
|
||||
minContentWidth: undefined,
|
||||
bodyAttrs: undefined,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -96,6 +101,8 @@ defineSlots<{
|
||||
prepend(): unknown;
|
||||
/** Flow content between `#prepend` and the inner, position: sticky. */
|
||||
sticky(): unknown;
|
||||
/** Flow content right above the items, inside the `bodyAttrs` element. */
|
||||
head(): unknown;
|
||||
}>();
|
||||
|
||||
const containerEl = ref<HTMLElement | null>(null);
|
||||
@@ -246,11 +253,13 @@ onMounted(() => {
|
||||
// bubbles up via the container's own size or the inner's offsetTop.
|
||||
if (innerEl.value) {
|
||||
innerObserver = new ResizeObserver(syncInnerOffset);
|
||||
// Observe siblings above the inner: that's what shifts `innerOffsetTop`.
|
||||
let prev = innerEl.value.previousElementSibling;
|
||||
while (prev) {
|
||||
innerObserver.observe(prev);
|
||||
prev = prev.previousElementSibling;
|
||||
// Observe siblings above the inner and the body: they shift `innerOffsetTop`.
|
||||
for (const start of [innerEl.value, innerEl.value.parentElement]) {
|
||||
let prev = start?.previousElementSibling;
|
||||
while (prev) {
|
||||
innerObserver.observe(prev);
|
||||
prev = prev.previousElementSibling;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -350,14 +359,17 @@ const innerStyle = computed(() => {
|
||||
<div v-if="$slots.sticky" class="r-virtual-scroller__sticky">
|
||||
<slot name="sticky" />
|
||||
</div>
|
||||
<div ref="innerEl" class="r-virtual-scroller__inner" :style="innerStyle">
|
||||
<div
|
||||
v-for="entry in renderedItems"
|
||||
:key="entry.key"
|
||||
class="r-virtual-scroller__item"
|
||||
:style="{ transform: `translateY(${entry.top}px)` }"
|
||||
>
|
||||
<slot :item="entry.item" :index="entry.index" />
|
||||
<div class="r-virtual-scroller__body" v-bind="bodyAttrs">
|
||||
<slot name="head" />
|
||||
<div ref="innerEl" class="r-virtual-scroller__inner" :style="innerStyle">
|
||||
<div
|
||||
v-for="entry in renderedItems"
|
||||
:key="entry.key"
|
||||
class="r-virtual-scroller__item"
|
||||
:style="{ transform: `translateY(${entry.top}px)` }"
|
||||
>
|
||||
<slot :item="entry.item" :index="entry.index" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -64,6 +64,7 @@ import DevicePair from "@/v2/views/DevicePair.vue";
|
||||
max-width: 460px;
|
||||
}
|
||||
|
||||
/* Absolute so it stays out of the grid and the stage keeps its centring. */
|
||||
.r-v2-devpair-shell__footer {
|
||||
position: absolute;
|
||||
left: var(--r-space-4);
|
||||
|
||||
@@ -179,7 +179,7 @@ function onDelete(fileId: number, romId: number) {
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="jukebox__main">
|
||||
<div class="jukebox__main">
|
||||
<SoundtrackPanel
|
||||
:key="selected"
|
||||
:tracks="panelTracks"
|
||||
@@ -194,7 +194,7 @@ function onDelete(fileId: number, romId: number) {
|
||||
@reached="pager.loadMoreIfNear"
|
||||
@delete-track="onDelete"
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -178,7 +178,7 @@ const launchRows = computed<{ title: string; tiles: LaunchTile[] }[]>(() => [
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="jukebox__home">
|
||||
<div class="jukebox__home">
|
||||
<CardRow
|
||||
v-for="row in launchRows"
|
||||
:key="row.title"
|
||||
@@ -200,7 +200,7 @@ const launchRows = computed<{ title: string; tiles: LaunchTile[] }[]>(() => [
|
||||
<template #count>{{ tile.count }}</template>
|
||||
</Tile>
|
||||
</CardRow>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -59,6 +59,7 @@ import Pair from "@/v2/views/Pair.vue";
|
||||
max-width: 440px;
|
||||
}
|
||||
|
||||
/* Absolute so it stays out of the grid and the stage keeps its centring. */
|
||||
.r-v2-pair-shell__footer {
|
||||
position: absolute;
|
||||
left: var(--r-space-4);
|
||||
|
||||
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
|
||||
heartbeatTick: null as (() => Promise<void>) | null,
|
||||
routeLeave: null as (() => Promise<boolean> | boolean) | null,
|
||||
socketHandlers: {} as Record<string, (payload: unknown) => unknown>,
|
||||
setPlaying: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
@@ -49,6 +50,10 @@ vi.mock("@/services/api/streaming", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/playing", () => ({
|
||||
default: () => ({ setPlaying: mocks.setPlaying }),
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/streaming", () => ({
|
||||
useStreamingStore: () => ({ heartbeatSession: mocks.heartbeatSession }),
|
||||
}));
|
||||
@@ -83,6 +88,35 @@ let mounted: VueWrapper | null = null;
|
||||
|
||||
const CLAIMED_AT = "2026-09-17T10:00:00";
|
||||
const KEY = "http://webstation-dev:8000";
|
||||
const CLAIM = {
|
||||
data: {
|
||||
container: KEY,
|
||||
host: "http://webstation-dev:8080",
|
||||
label: "PS2",
|
||||
platform: "ps2",
|
||||
claimed_at: CLAIMED_AT,
|
||||
},
|
||||
};
|
||||
|
||||
// A pending call the test answers by hand.
|
||||
function deferred() {
|
||||
let answer = (_: unknown) => {};
|
||||
const promise = new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
});
|
||||
return { promise, answer };
|
||||
}
|
||||
|
||||
// Unstamped, a release reaches whichever session took the container.
|
||||
function expectReleasedOwnClaim(): void {
|
||||
expect(mocks.releaseSession).toHaveBeenCalledWith(
|
||||
"ps2",
|
||||
undefined,
|
||||
KEY,
|
||||
undefined,
|
||||
CLAIMED_AT,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -103,15 +137,7 @@ async function mountDesktop(): Promise<VueWrapper> {
|
||||
}
|
||||
|
||||
async function openDesktop(): Promise<VueWrapper> {
|
||||
mocks.claimDesktop.mockResolvedValue({
|
||||
data: {
|
||||
container: KEY,
|
||||
host: "http://webstation-dev:8080",
|
||||
label: "PS2",
|
||||
platform: "ps2",
|
||||
claimed_at: CLAIMED_AT,
|
||||
},
|
||||
});
|
||||
mocks.claimDesktop.mockResolvedValue(CLAIM);
|
||||
return mountDesktop();
|
||||
}
|
||||
|
||||
@@ -229,12 +255,8 @@ describe("Desktop heartbeats", () => {
|
||||
it("keeps the exit a release made while a beat was in flight", async () => {
|
||||
const wrapper = await openDesktop();
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
let answer = (_: unknown) => {};
|
||||
mocks.heartbeatSession.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}),
|
||||
);
|
||||
const { promise, answer } = deferred();
|
||||
mocks.heartbeatSession.mockReturnValue(promise);
|
||||
|
||||
const beat = mocks.heartbeatTick?.();
|
||||
expect(await mocks.routeLeave?.()).toBe(true);
|
||||
@@ -256,20 +278,13 @@ describe("Desktop heartbeats", () => {
|
||||
});
|
||||
|
||||
describe("Desktop releases", () => {
|
||||
// Unstamped, a release reaches whichever session took the container.
|
||||
it("names the claim it releases on exit", async () => {
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
await openDesktop();
|
||||
|
||||
expect(await mocks.routeLeave?.()).toBe(true);
|
||||
|
||||
expect(mocks.releaseSession).toHaveBeenCalledWith(
|
||||
"ps2",
|
||||
undefined,
|
||||
KEY,
|
||||
undefined,
|
||||
CLAIMED_AT,
|
||||
);
|
||||
expectReleasedOwnClaim();
|
||||
});
|
||||
|
||||
it("names the claim it releases when the tab closes", async () => {
|
||||
@@ -345,3 +360,99 @@ describe("Desktop container naming", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Desktop controller ownership", () => {
|
||||
// The emulator inside the container reads the pad, so RomM's gamepad
|
||||
// navigation must stay muted or B pops history out of the session.
|
||||
it("mutes pad navigation while the desktop is claimed", async () => {
|
||||
await openDesktop();
|
||||
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
it("hands the pad back once a notice ends the claim", async () => {
|
||||
await openDesktop();
|
||||
|
||||
endSession({ platform: "ps2", container: KEY });
|
||||
await flushPromises();
|
||||
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("hands the pad back when the claim is refused", async () => {
|
||||
await refuseDesktop({ rom_name: null, claimed_at: null, draining: true });
|
||||
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("hands the pad back when the view unmounts", async () => {
|
||||
const wrapper = await openDesktop();
|
||||
|
||||
wrapper.unmount();
|
||||
mounted = null;
|
||||
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("mutes pad navigation while the claim is still in flight", async () => {
|
||||
mocks.claimDesktop.mockReturnValue(new Promise(() => {}));
|
||||
const wrapper = await mountDesktop();
|
||||
|
||||
expect(vmOf(wrapper).state).toBe("loading");
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
it("hands the pad back once the desktop is exited", async () => {
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
await openDesktop();
|
||||
|
||||
expect(await mocks.routeLeave?.()).toBe(true);
|
||||
await flushPromises();
|
||||
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("ends the desktop from the pad's exit chord", async () => {
|
||||
// B is muted with the rest of the pad, so the chord is the pad's way out.
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
const wrapper = await openDesktop();
|
||||
|
||||
window.dispatchEvent(new Event("gamepad:exitchord"));
|
||||
await flushPromises();
|
||||
|
||||
expectReleasedOwnClaim();
|
||||
expect(vmOf(wrapper).state).toBe("exited");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Desktop claims that outlive the view", () => {
|
||||
it("hands back a claim that answers after the view is gone", async () => {
|
||||
const { promise, answer } = deferred();
|
||||
mocks.claimDesktop.mockReturnValue(promise);
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
const wrapper = await mountDesktop();
|
||||
|
||||
wrapper.unmount();
|
||||
mounted = null;
|
||||
answer(CLAIM);
|
||||
await flushPromises();
|
||||
|
||||
expectReleasedOwnClaim();
|
||||
});
|
||||
|
||||
it("hands back a claim that answers while the leave is still resolving", async () => {
|
||||
const { promise, answer } = deferred();
|
||||
mocks.claimDesktop.mockReturnValue(promise);
|
||||
mocks.releaseSession.mockResolvedValue({});
|
||||
const wrapper = await mountDesktop();
|
||||
|
||||
expect(await mocks.routeLeave?.()).toBe(true);
|
||||
answer(CLAIM);
|
||||
await flushPromises();
|
||||
wrapper.unmount();
|
||||
mounted = null;
|
||||
await flushPromises();
|
||||
|
||||
expectReleasedOwnClaim();
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@
|
||||
import { RAlert, RBtn, RSpinner } from "@v2/lib";
|
||||
import { useEventListener, useIntervalFn } from "@vueuse/core";
|
||||
import { isAxiosError } from "axios";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
|
||||
import { ROUTES } from "@/plugins/router";
|
||||
@@ -21,8 +21,10 @@ import { type SessionTermination, useStreamingStore } from "@/stores/streaming";
|
||||
import SessionEndedReason from "@/v2/components/Player/SessionEndedReason.vue";
|
||||
import StreamStage from "@/v2/components/Player/StreamStage.vue";
|
||||
import { useConfirm } from "@/v2/composables/useConfirm";
|
||||
import { useIsAlive } from "@/v2/composables/useIsAlive";
|
||||
import { usePageTitle } from "@/v2/composables/usePageTitle";
|
||||
import { useSocketEvent } from "@/v2/composables/useSocketEvent";
|
||||
import { usePlayingWhile } from "@/v2/composables/useStageActive";
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
@@ -55,6 +57,19 @@ const claimedAt = ref("");
|
||||
|
||||
usePageTitle(() => t("play.desktop-title"));
|
||||
|
||||
// The emulator inside the desktop owns the controller, so pad presses must not
|
||||
// also drive RomM behind the stream (B would go back and prompt to end it).
|
||||
const sessionActive = computed(
|
||||
() => state.value === "loading" || state.value === "running",
|
||||
);
|
||||
usePlayingWhile(sessionActive);
|
||||
// With B muted, useGamepad's Select+Start hold is the pad's way out.
|
||||
useEventListener(window, "gamepad:exitchord", () => void handleExit());
|
||||
|
||||
// Leaving mid-claim is allowed, so a claim that answers after unmount is
|
||||
// released at once; otherwise it would hold the container until it went stale.
|
||||
const alive = useIsAlive();
|
||||
|
||||
async function openDesktop(): Promise<void> {
|
||||
if (!containerName.value) {
|
||||
state.value = "error";
|
||||
@@ -69,6 +84,10 @@ async function openDesktop(): Promise<void> {
|
||||
platform.value = data.platform;
|
||||
claimedAt.value = data.claimed_at;
|
||||
holdsClaim.value = true;
|
||||
if (!alive.value) {
|
||||
void release();
|
||||
return;
|
||||
}
|
||||
state.value = "running";
|
||||
} catch (err: unknown) {
|
||||
state.value = "error";
|
||||
@@ -218,6 +237,12 @@ useEventListener(window, "pagehide", onPageHide);
|
||||
onMounted(() => {
|
||||
void openDesktop();
|
||||
});
|
||||
|
||||
// A claim that answered after the leave guard let navigation through, while
|
||||
// the next route was still resolving, is still held here.
|
||||
onBeforeUnmount(() => {
|
||||
if (holdsClaim.value) void release();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -165,7 +165,10 @@ vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useStageActive", () => ({ useStageActive: vi.fn() }));
|
||||
vi.mock("@/v2/composables/useStageActive", () => ({
|
||||
useStageActive: vi.fn(),
|
||||
usePlayingWhile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useUnloadGuard", () => ({ useUnloadGuard: vi.fn() }));
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
} from "@v2/lib";
|
||||
import { useEventListener, useLocalStorage } from "@vueuse/core";
|
||||
import type { Emitter } from "mitt";
|
||||
import { storeToRefs } from "pinia";
|
||||
import {
|
||||
computed,
|
||||
defineAsyncComponent,
|
||||
@@ -49,7 +48,6 @@ import romApi from "@/services/api/rom";
|
||||
import { AUTOSAVE_SLOT, SAVE_SLOT_MAX_LENGTH } from "@/services/api/save";
|
||||
import storeConfig from "@/stores/config";
|
||||
import { useNativeStore } from "@/stores/native";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import {
|
||||
@@ -77,7 +75,10 @@ import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { usePlayerNav } from "@/v2/composables/usePlayerNav";
|
||||
import { useSaveStateTabs } from "@/v2/composables/useSaveStateTabs";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useStageActive } from "@/v2/composables/useStageActive";
|
||||
import {
|
||||
usePlayingWhile,
|
||||
useStageActive,
|
||||
} from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import type { AssetType } from "@/v2/utils/assets";
|
||||
import { joinNames } from "@/v2/utils/lists";
|
||||
@@ -135,10 +136,8 @@ const Player = defineAsyncComponent(
|
||||
const { t, locale } = useI18n();
|
||||
const snackbar = useSnackbar();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const playingStore = storePlaying();
|
||||
const configStore = storeConfig();
|
||||
const nativeStore = useNativeStore();
|
||||
const { playing } = storeToRefs(playingStore);
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
useFullscreenFallback();
|
||||
const playSession = usePlaySession();
|
||||
@@ -199,6 +198,7 @@ const exit = usePlayerExit(
|
||||
// quiet for the full navigation it turns into.
|
||||
useUnloadGuard(() => gameRunning.value && !exit.departing.value);
|
||||
useStageActive(gameRunning);
|
||||
usePlayingWhile(gameRunning);
|
||||
onBeforeRouteLeave(exit.guard);
|
||||
|
||||
// Stage-scoped so the non-passive listener never taxes touches elsewhere.
|
||||
@@ -471,7 +471,6 @@ async function onPlay() {
|
||||
|
||||
gameRunning.value = true;
|
||||
window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value;
|
||||
playing.value = true;
|
||||
|
||||
const { EJS_NETPLAY_ENABLED } = configStore.config;
|
||||
const EMULATORJS_VERSION = EJS_NETPLAY_ENABLED ? "nightly" : "4.2.3";
|
||||
@@ -500,7 +499,6 @@ async function onPlay() {
|
||||
// No emulator booted, so drop back to the config screen instead of
|
||||
// leaving the unload guard and the input mute armed.
|
||||
gameRunning.value = false;
|
||||
playing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -674,9 +672,6 @@ onBeforeUnmount(() => {
|
||||
// the user never exited the game to the config screen first. flush() is
|
||||
// idempotent, so an exit that already flushed via the watch is a no-op.
|
||||
endSession();
|
||||
// Hand the keyboard and gamepad back to the UI; the flag otherwise
|
||||
// stays true and pad/hotkey navigation is dead until a reload.
|
||||
playing.value = false;
|
||||
exitEmulatorOnce();
|
||||
emitter?.off("saveSelected", selectSave);
|
||||
emitter?.off("stateSelected", selectState);
|
||||
|
||||
@@ -344,9 +344,9 @@ describe("JsDos player exit", () => {
|
||||
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
|
||||
expect(mocks.routerReplace).not.toHaveBeenCalled();
|
||||
expect(mocks.flushPlaySession).toHaveBeenCalledOnce();
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
wrapper.unmount();
|
||||
expect(handle.stop).toHaveBeenCalledOnce();
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
// A player document opened directly is cross-origin isolated, and the rest
|
||||
@@ -402,7 +402,7 @@ describe("JsDos player exit", () => {
|
||||
expect(mocks.routerReplace).not.toHaveBeenCalled();
|
||||
expect(mocks.locationReplace).not.toHaveBeenCalled();
|
||||
expect(mocks.flushPlaySession).not.toHaveBeenCalled();
|
||||
expect(mocks.setPlaying).not.toHaveBeenCalledWith(false);
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(true);
|
||||
expect(
|
||||
wrapper.get(".r-v2-player__quit").attributes("disabled"),
|
||||
).toBeUndefined();
|
||||
@@ -419,9 +419,9 @@ describe("JsDos player exit", () => {
|
||||
|
||||
expect(handle.stop).toHaveBeenCalledOnce();
|
||||
expect(mocks.flushPlaySession).toHaveBeenCalledOnce();
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
|
||||
wrapper.unmount();
|
||||
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("keeps the player open when the final save fails", async () => {
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useI18n } from "vue-i18n";
|
||||
import { onBeforeRouteLeave } from "vue-router";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { JsDosProps } from "@/types/js-dos";
|
||||
import { getDownloadPath } from "@/utils";
|
||||
@@ -23,12 +22,12 @@ import { usePlaySession } from "@/v2/composables/usePlaySession";
|
||||
import { usePlayerExit } from "@/v2/composables/usePlayerExit";
|
||||
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { usePlayingWhile } from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import { loadJsDosRuntime } from "./jsDosRuntime";
|
||||
|
||||
const { t } = useI18n();
|
||||
const authStore = storeAuth();
|
||||
const playingStore = storePlaying();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
useFullscreenFallback();
|
||||
const playSession = usePlaySession();
|
||||
@@ -41,6 +40,7 @@ const exit = usePlayerExit(() => runtimeBound);
|
||||
|
||||
const rom = shallowRef<DetailedRom | null>(null);
|
||||
const gameRunning = ref(false);
|
||||
usePlayingWhile(gameRunning);
|
||||
const quitting = ref(false);
|
||||
const stage = ref<HTMLDivElement | null>(null);
|
||||
|
||||
@@ -81,13 +81,10 @@ async function onPlay() {
|
||||
return;
|
||||
}
|
||||
gameRunning.value = true;
|
||||
// Let the emulator own keyboard input while running.
|
||||
playingStore.setPlaying(true);
|
||||
|
||||
await nextTick();
|
||||
if (!stage.value) {
|
||||
gameRunning.value = false;
|
||||
playingStore.setPlaying(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -136,7 +133,6 @@ async function saveQuietly(handle: JsDosProps) {
|
||||
|
||||
function teardown() {
|
||||
playSession.flush();
|
||||
playingStore.setPlaying(false);
|
||||
stopDos();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useEventListener } from "@vueuse/core";
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import { getDownloadPath } from "@/utils";
|
||||
import PlayerShell from "@/v2/components/Player/PlayerShell.vue";
|
||||
@@ -15,6 +14,7 @@ import { usePlaySession } from "@/v2/composables/usePlaySession";
|
||||
import { usePlayerFullscreen } from "@/v2/composables/usePlayerFullscreen";
|
||||
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { usePlayingWhile } from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import { createPico8Audio, type Pico8Audio } from "@/v2/utils/pico8Audio";
|
||||
import { createPico8Input } from "@/v2/utils/pico8Input";
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
} from "@/v2/utils/pico8Runtime";
|
||||
|
||||
const { t } = useI18n();
|
||||
const playingStore = storePlaying();
|
||||
const playSession = usePlaySession();
|
||||
const snackbar = useSnackbar();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
@@ -37,6 +36,7 @@ const alive = useIsAlive();
|
||||
|
||||
const rom = shallowRef<DetailedRom | null>(null);
|
||||
const gameRunning = ref(false);
|
||||
usePlayingWhile(gameRunning);
|
||||
const loading = ref(false);
|
||||
const stage = ref<HTMLDivElement | null>(null);
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
@@ -186,7 +186,6 @@ function releaseGame() {
|
||||
audio = null;
|
||||
input.reset();
|
||||
playSession.flush();
|
||||
playingStore.setPlaying(false);
|
||||
gameRunning.value = false;
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -211,7 +210,6 @@ async function onPlay() {
|
||||
|
||||
gameRunning.value = true;
|
||||
loading.value = true;
|
||||
playingStore.setPlaying(true);
|
||||
await nextTick();
|
||||
|
||||
if (!gameRunning.value) return;
|
||||
|
||||
@@ -7,7 +7,6 @@ import { RIcon, RSwitch } from "@v2/lib";
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { RuffleSourceAPI } from "@/types/ruffle";
|
||||
import { getDownloadPath } from "@/utils";
|
||||
@@ -16,6 +15,7 @@ import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback";
|
||||
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
|
||||
import { usePlaySession } from "@/v2/composables/usePlaySession";
|
||||
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { usePlayingWhile } from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import { colorCanvas } from "@/v2/tokens";
|
||||
|
||||
@@ -25,11 +25,12 @@ const DEFAULT_BACKGROUND_COLOR = colorCanvas.bgDeep;
|
||||
const { t } = useI18n();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
useFullscreenFallback();
|
||||
const playingStore = storePlaying();
|
||||
const playSession = usePlaySession();
|
||||
|
||||
const rom = shallowRef<DetailedRom | null>(null);
|
||||
const gameRunning = ref(false);
|
||||
// Flash games are keyboard-driven, so hotkeys and pad navigation stay muted.
|
||||
usePlayingWhile(gameRunning);
|
||||
const backgroundColor = ref<string>(DEFAULT_BACKGROUND_COLOR);
|
||||
|
||||
useUnloadGuard(gameRunning);
|
||||
@@ -56,14 +57,10 @@ const { romId, heroRom, title, platformLabel } = usePlayerHero(rom);
|
||||
// Nothing is running, so drop the guard and the input mute the launch armed.
|
||||
function abortPlay() {
|
||||
gameRunning.value = false;
|
||||
playingStore.setPlaying(false);
|
||||
}
|
||||
|
||||
function onPlay() {
|
||||
gameRunning.value = true;
|
||||
// Flash games are keyboard-driven; flag the session so global hotkeys
|
||||
// and pad-to-UI translation stay muted while the game owns input.
|
||||
playingStore.setPlaying(true);
|
||||
|
||||
nextTick(() => {
|
||||
if (!rom.value) {
|
||||
@@ -147,8 +144,6 @@ onBeforeUnmount(() => {
|
||||
// Every exit path (Quit, back links, route change) unmounts the view, so
|
||||
// this is the single choke point for recording the session.
|
||||
playSession.flush();
|
||||
// Hand the keyboard and gamepad back to the UI on any exit path.
|
||||
playingStore.setPlaying(false);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -154,6 +154,7 @@ vi.mock("@/v2/composables/useSocketEvent", () => ({
|
||||
|
||||
vi.mock("@/v2/composables/useStageActive", () => ({
|
||||
useStageActive: vi.fn(),
|
||||
usePlayingWhile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useUnloadGuard", () => ({
|
||||
@@ -476,6 +477,7 @@ type StreamVm = {
|
||||
claimedAt: string | null;
|
||||
playerState: string;
|
||||
endedDialogOpen: boolean;
|
||||
exitDialogOpen: boolean;
|
||||
holdsClaim: boolean;
|
||||
containerHost: string;
|
||||
errorMessage: string;
|
||||
@@ -626,6 +628,26 @@ describe("Stream session-ended notices", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stream exit chord", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.claimSession.mockResolvedValue(CLAIM);
|
||||
});
|
||||
|
||||
it("opens the exit dialog from the pad's exit chord", async () => {
|
||||
// B is muted with the rest of the pad, so the chord is the pad's way out.
|
||||
const wrapper = await launch({ picker: false });
|
||||
await vmOf(wrapper).onPlay();
|
||||
await launchReady();
|
||||
expect(vmOf(wrapper).playerState).toBe("playing");
|
||||
|
||||
window.dispatchEvent(new Event("gamepad:exitchord"));
|
||||
await flushPromises();
|
||||
|
||||
expect(vmOf(wrapper).exitDialogOpen).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stream claim hygiene", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
@@ -51,7 +51,6 @@ import streamingApi, {
|
||||
type MemoryCardImportDetail,
|
||||
} from "@/services/api/streaming";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms";
|
||||
import {
|
||||
type SessionStatus,
|
||||
@@ -82,7 +81,10 @@ import { usePlayerNav } from "@/v2/composables/usePlayerNav";
|
||||
import { romIdFromRoute } from "@/v2/composables/useRouteRom";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useSocketEvent } from "@/v2/composables/useSocketEvent";
|
||||
import { useStageActive } from "@/v2/composables/useStageActive";
|
||||
import {
|
||||
usePlayingWhile,
|
||||
useStageActive,
|
||||
} from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
@@ -97,7 +99,6 @@ const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const auth = storeAuth();
|
||||
const playingStore = storePlaying();
|
||||
const streamingStore = useStreamingStore();
|
||||
const snackbar = useSnackbar();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
@@ -160,8 +161,8 @@ const holdsClaim = ref(false);
|
||||
const sessionActive = computed(
|
||||
() => playerState.value === "playing" || playerState.value === "loading",
|
||||
);
|
||||
usePlayingWhile(sessionActive);
|
||||
watch(sessionActive, (active) => {
|
||||
playingStore.setPlaying(active);
|
||||
if (active) startSessionPoll();
|
||||
else stopSessionPoll();
|
||||
});
|
||||
@@ -1265,69 +1266,9 @@ async function exitWithoutSaving(): Promise<void> {
|
||||
(leave ?? backToRom)();
|
||||
}
|
||||
|
||||
// Dialogs have no automatic spatial navigation, so cycle focus between
|
||||
// the action buttons on arrow keys (the d-pad arrives as synthetic
|
||||
// ArrowLeft/ArrowRight keydowns from useGamepad).
|
||||
function onExitDialogKeydown(event: KeyboardEvent): void {
|
||||
const arrows = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"];
|
||||
if (!arrows.includes(event.key)) return;
|
||||
const root = event.currentTarget as HTMLElement;
|
||||
const buttons = Array.from(
|
||||
root.querySelectorAll<HTMLElement>("button:not([disabled])"),
|
||||
);
|
||||
if (buttons.length === 0) return;
|
||||
const idx = buttons.indexOf(document.activeElement as HTMLElement);
|
||||
const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : -1;
|
||||
buttons[(idx + step + buttons.length) % buttons.length]?.focus();
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// ── Select+Start exit chord ────────────────────────────────────────
|
||||
// useGamepad is muted for the whole session (launch included), so the
|
||||
// chord is read straight from the Gamepad API here; polling while
|
||||
// "loading" keeps the cancel dialog reachable by pad if a launch hangs.
|
||||
// The 1.5s hold filters out anything a game itself binds to Select+Start.
|
||||
// Only standard-mapped pads participate: elsewhere indices 8/9 are not
|
||||
// guaranteed to be Select+Start.
|
||||
const EXIT_CHORD_HOLD_MS = 1500;
|
||||
// A 1.5s hold needs nowhere near frame resolution, and this runs on the thread
|
||||
// compositing the stream for as long as the session lasts.
|
||||
const EXIT_CHORD_POLL_MS = 100;
|
||||
let chordHeldSince = 0;
|
||||
|
||||
function pollExitChord(): void {
|
||||
const pads = navigator.getGamepads ? navigator.getGamepads() : [];
|
||||
const held = Array.from(pads).some(
|
||||
(pad) =>
|
||||
pad &&
|
||||
pad.mapping === "standard" &&
|
||||
pad.buttons[8]?.pressed &&
|
||||
pad.buttons[9]?.pressed,
|
||||
);
|
||||
const now = performance.now();
|
||||
if (!held) {
|
||||
chordHeldSince = 0;
|
||||
} else if (!chordHeldSince) {
|
||||
chordHeldSince = now;
|
||||
} else if (now - chordHeldSince >= EXIT_CHORD_HOLD_MS) {
|
||||
chordHeldSince = 0;
|
||||
if (!exitDialogOpen.value) void openExitDialog();
|
||||
}
|
||||
}
|
||||
|
||||
const exitChordPoll = useIntervalFn(pollExitChord, EXIT_CHORD_POLL_MS, {
|
||||
immediate: false,
|
||||
});
|
||||
|
||||
function stopExitChordPoll(): void {
|
||||
exitChordPoll.pause();
|
||||
chordHeldSince = 0;
|
||||
}
|
||||
|
||||
watch(sessionActive, (active) => {
|
||||
if (active) exitChordPoll.resume();
|
||||
else stopExitChordPoll();
|
||||
});
|
||||
// useGamepad is muted for the whole session (launch included), so its
|
||||
// Select+Start hold is the pad's only way to the exit dialog.
|
||||
useEventListener(window, "gamepad:exitchord", () => void openExitDialog());
|
||||
|
||||
function formatTime(iso: string): string {
|
||||
try {
|
||||
@@ -1405,7 +1346,6 @@ onBeforeUnmount(() => {
|
||||
// Every exit path (Stop, Save & Exit, back nav) unmounts the view, so this
|
||||
// is the single choke point for recording the session.
|
||||
playSession.flush();
|
||||
playingStore.setPlaying(false);
|
||||
if (volumeDebounce) clearTimeout(volumeDebounce);
|
||||
// The polls clear themselves with the scope; the presence board does not
|
||||
// know the player has gone until it is told.
|
||||
@@ -1880,7 +1820,7 @@ onBeforeUnmount(() => {
|
||||
</template>
|
||||
<template #footer>
|
||||
<!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -- arrow keys rove focus between this container's real buttons, which stay the interactive elements; the listener sits here to catch keydowns bubbling from either of them -->
|
||||
<div class="r-v2-stream__exit-actions" @keydown="onExitDialogKeydown">
|
||||
<div class="r-v2-stream__exit-actions">
|
||||
<!-- eslint-disable vuejs-accessibility/no-autofocus -- RDialog reads [autofocus] to place initial focus, and the least destructive action is the intended target -->
|
||||
<RBtn
|
||||
autofocus
|
||||
|
||||
@@ -2704,19 +2704,19 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "tornado"
|
||||
version = "6.5.8"
|
||||
version = "6.5.9"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/10/d3/343e5bb989d6515b1646cf3d40135d73f3d5e45339bded401b56cdac24dd/tornado-6.5.8.tar.gz", hash = "sha256:9452e1b208a8bd771e2cb1f2ff564985b9b214bdebbe622793e1799e0a6bd23f", size = 520493, upload-time = "2026-08-07T02:12:42.971Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/22/15/ca7aaebb77f850493cba71ace508aeffb896d1ad8976417b48b79823dbd2/tornado-6.5.9.tar.gz", hash = "sha256:4d868544ebdf2fc155239a74397f65ebfea9b4d3635296c96b5dfb0701c354f5", size = 536145, upload-time = "2026-09-14T18:08:37.434Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/d5/007086fd8df5489338e204f65adce33fd4f21a4999dbb2b9cff2f897b5f4/tornado-6.5.8-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc6aa787d7cfab7c3d35189dc7a56fbd2399a569624c730c6b55b3d6531d0403", size = 449487, upload-time = "2026-08-07T02:12:28.682Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/c8/5a24a99495903f594f6a199dd7beead1cbc0a13e2cb9102727bcaaf2a997/tornado-6.5.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9715b5eb79735b2bcd454ce216a9275b7c0470e64ea1bf5742f78b2f72b26eeb", size = 447649, upload-time = "2026-08-07T02:12:30.306Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/de/f2e733f386b85962d1b1dc82cd63d169b5b4580062b35397eac9244a41fe/tornado-6.5.8-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:547d63f450d570c14fe0e8db2cfb14c9bbd1c2503b4a6612586267955aa47b58", size = 450707, upload-time = "2026-08-07T02:12:31.95Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/94/20efeee9a01c141e9ac47c397f81679dfda24b32768fc4fff24e76d36c2c/tornado-6.5.8-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e2360a0ffbe145eca8af0b19cb7203d79b1a98dd4cccdd6b368f6f49c2e3808", size = 451677, upload-time = "2026-08-07T02:12:33.512Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/ec/a96ccb8ccf0de2b7bc2c5fa1608a4803735018242e90c4882365a9fd418f/tornado-6.5.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5d242290bdf7ab3151bc1065fdd75c0dcc21cbc7b49f22a4c56329c2d6566d22", size = 451510, upload-time = "2026-08-07T02:12:35.346Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/29/b5/93185859245ad3f00e62175f29607346788b696369347f0146e0421286bb/tornado-6.5.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7b94ff0e128fe0542f3bd331fb44d06260fc4ac16881545159f34ef08aad4195", size = 450917, upload-time = "2026-08-07T02:12:36.963Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/cf/fe33cf062834487d34d1559746a4a12521033c22645b6d74d4bca702e018/tornado-6.5.8-cp39-abi3-win32.whl", hash = "sha256:67832909c4779c64942380cb5f044a5c6163d00831472d80e25e115de9917836", size = 451952, upload-time = "2026-08-07T02:12:38.512Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/e1/468ad54333e92ccb62627e62cb88e5fc14a2171daa67ed47b1b8542d5b86/tornado-6.5.8-cp39-abi3-win_amd64.whl", hash = "sha256:11881db6b7c168494be2c2d12e65931451bdf7ee718535418ae1d8855dd5a0ee", size = 452391, upload-time = "2026-08-07T02:12:39.971Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/3e/cd5e4f06e34cde33b8ef66cf36aa2b5ad46354cc1af7d2136bbe365fee1d/tornado-6.5.8-cp39-abi3-win_arm64.whl", hash = "sha256:68a7468c7e289f8514d7d664101753903217eff1bb6822c6b5994a0b5f5bcb26", size = 451411, upload-time = "2026-08-07T02:12:41.469Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/4a/4d3459fd2f360dd99233f69f22b36012a42856ace526da2c6da3cb0e6df2/tornado-6.5.9-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:dea3bee433b73d6312d993ce89ad5f2b8d3ed9fde56e79ba5342b9edb78d342a", size = 464279, upload-time = "2026-09-14T18:08:20.909Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/4b/5af2f7dcd674e2f1cacef763456f79823404f50954789d6e1ec7a70cd58a/tornado-6.5.9-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:22bed49cdb55292d1d58f46008ba2cc3020e5b84995ef6ae749676c8b5309514", size = 462440, upload-time = "2026-09-14T18:08:22.711Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/0f/38f8d16011de3b1ce2babb4c3bcefb126d2dc47d04878ae3ad5c39a00caa/tornado-6.5.9-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0cc0876a58eee9143476f24901b1b8eb4d52443283ade2b6bca650dd1da04f84", size = 465496, upload-time = "2026-09-14T18:08:24.407Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/e9/3888f265d1e287fc63cd61a6696f96a650024e32f9e89c0b1817ac5c40f4/tornado-6.5.9-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dc0d703cc7ec92b47ebfe236c97cd765c1f2e45744a2e156e6677e54c948274d", size = 466468, upload-time = "2026-09-14T18:08:25.928Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d6/8b/d2bcf417981fa6f7698ab84a52394a76cf608e6704d266e2e0e29f1fd9d0/tornado-6.5.9-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:93f9ab0226ef625b94cacb7981a5af104f1735ea02f92282abe5c389109fb31d", size = 466303, upload-time = "2026-09-14T18:08:27.566Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7e/a5/c5cfab11420c3f908238a6c861b8f3864fdbd2b2b87e30c9c16f36a11512/tornado-6.5.9-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5801bbf94dfde8d21087b6aa0b17f3a5dab6110dfe44e7e4492df5de393ac15b", size = 465706, upload-time = "2026-09-14T18:08:29.182Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/36/5a5da0aa15b7afdd46ece09c004a75af7d00f6a96b692bf696ff94bc2a55/tornado-6.5.9-cp39-abi3-win32.whl", hash = "sha256:dca9f377e80efe5dd4d52a2776b67492a81a39b2d931de169b6b36d0c1da444c", size = 466750, upload-time = "2026-09-14T18:08:30.836Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/34/d7/2446cf3125372e2b4be6483b4b93f360dc50ce2493864755484b23bb50f2/tornado-6.5.9-cp39-abi3-win_amd64.whl", hash = "sha256:f810730ac71eadf009e6e5cb6d534d096887310f5649cff19d7e0d19c0bf4ee7", size = 467191, upload-time = "2026-09-14T18:08:32.521Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/70/f1024364bf78fa921c63ef2883d36a3b3b705750c98ae174593afaab7a65/tornado-6.5.9-cp39-abi3-win_arm64.whl", hash = "sha256:b5f4d92798337260c6d9f9f0e400c7539dd5e55cf93479a3f8508c9aa09c2b3b", size = 466211, upload-time = "2026-09-14T18:08:35.18Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user