Merge pull request #4971 from andest01/fix/wcag-aa-misc-fixes

chore(wcag): AA misc fixes
This commit is contained in:
Georges-Antoine Assi
2026-10-01 08:36:12 -04:00
committed by GitHub
46 changed files with 996 additions and 162 deletions

View File

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

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "Всички игри са заредени",
"back-to-top": "Към началото",
"column-actions": "Действия",
"column-cover": "Корица",
"filters": "Филтри",
"firmware-files-count": "{count} файла",
"firmware-selected-count": "{count} избрани",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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)",

View File

@@ -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",

View File

@@ -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",

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "すべてのゲームが読み込まれました",
"back-to-top": "トップへ戻る",
"column-actions": "操作",
"column-cover": "カバー",
"filters": "フィルタ",
"firmware-files-count": "{count}件のファイル",
"firmware-selected-count": "{count}件選択中",

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "모든 게임이 불러와졌습니다",
"back-to-top": "맨 위로",
"column-actions": "작업",
"column-cover": "커버",
"filters": "필터",
"firmware-files-count": "{count}개 파일",
"firmware-selected-count": "{count}개 선택됨",

View File

@@ -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",

View File

@@ -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)",

View File

@@ -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",

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "Все игры загружены",
"back-to-top": "Наверх",
"column-actions": "Действия",
"column-cover": "Обложка",
"filters": "Фильтры",
"firmware-files-count": "{count} файлов",
"firmware-selected-count": "{count} выбрано",

View File

@@ -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",

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "所有游戏已加载",
"back-to-top": "返回顶部",
"column-actions": "操作",
"column-cover": "封面",
"filters": "筛选器",
"firmware-files-count": "{count} 个文件",
"firmware-selected-count": "已选择 {count} 个",

View File

@@ -1,6 +1,8 @@
{
"all-loaded": "所有遊戲已載入",
"back-to-top": "回到頂端",
"column-actions": "操作",
"column-cover": "封面",
"filters": "篩選器",
"firmware-files-count": "{count} 個檔案",
"firmware-selected-count": "已選擇 {count} 個",

View File

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

View File

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

View File

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

View File

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

View File

@@ -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);

View File

@@ -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}`,
);
});
});

View File

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

View File

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

View File

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

View File

@@ -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>
`,
}),

View File

@@ -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");
});
});

View File

@@ -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"
/>

View File

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

View File

@@ -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"]);
});
});

View File

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

View File

@@ -27,12 +27,12 @@ onMounted(installInputModality);
<!-- Bottom bar: language selector pinned left, version tag right. A
single row so the "one on each side" split holds at every width
(absolute on desktop, in normal flow below the card on phones). -->
<div class="r-v2-auth__footer">
<footer class="r-v2-auth__footer">
<div class="r-v2-auth__lang">
<LanguageSelector />
</div>
<VersionTag class="r-v2-auth__version" />
</div>
</footer>
<NotificationHost />
</div>
</template>

View File

@@ -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 = {

View File

@@ -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");
});
});

View File

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

View File

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

View File

@@ -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(() => {

View File

@@ -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();
});
});

View File

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

View File

@@ -16,10 +16,10 @@ import DevicePair from "@/v2/views/DevicePair.vue";
<main class="r-v2-devpair-shell__stage">
<DevicePair />
</main>
<div class="r-v2-devpair-shell__lang">
<footer class="r-v2-devpair-shell__footer">
<LanguageSelector />
</div>
<VersionTag class="r-v2-devpair-shell__version" />
<VersionTag />
</footer>
</div>
</template>
@@ -68,17 +68,16 @@ import DevicePair from "@/v2/views/DevicePair.vue";
max-width: 460px;
}
.r-v2-devpair-shell__lang {
/* 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);
bottom: var(--r-space-3);
z-index: 1;
}
.r-v2-devpair-shell__version {
position: absolute;
right: var(--r-space-4);
bottom: var(--r-space-3);
z-index: 1;
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--r-space-3);
}
</style>

View File

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

View File

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

View File

@@ -13,10 +13,10 @@ import Pair from "@/v2/views/Pair.vue";
<main class="r-v2-pair-shell__stage">
<Pair />
</main>
<div class="r-v2-pair-shell__lang">
<footer class="r-v2-pair-shell__footer">
<LanguageSelector />
</div>
<VersionTag class="r-v2-pair-shell__version" />
<VersionTag />
</footer>
</div>
</template>
@@ -55,17 +55,16 @@ import Pair from "@/v2/views/Pair.vue";
max-width: 440px;
}
.r-v2-pair-shell__lang {
/* 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);
bottom: var(--r-space-3);
z-index: 1;
}
.r-v2-pair-shell__version {
position: absolute;
right: var(--r-space-4);
bottom: var(--r-space-3);
z-index: 1;
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--r-space-3);
}
</style>