feat: add table sorting, accessibility and session filters
CI / test (push) Successful in 3m18s

This commit is contained in:
strsv committed 2026-11-06 19:20:18 +03:00
1 parent a6db306847
commit 7e4fa74cd6
13 files changed
+363 -63

No files matched your search

+161 -20
View File
@@ -11,6 +11,8 @@ const PER_PAGE = 60;
const THEME_KEY = "sb.theme";
const VIEWS_KEY = "sb.views";
const LAYOUT_KEY = "sb.layout";
const SORT_KEY = "sb.sort";
const COLS_KEY = "sb.cols";
function defaultFilters() {
return {
@@ -24,6 +26,7 @@ const state = {
view: "library",
page: 1,
sort: "review",
dir: "desc",
q: "",
filters: defaultFilters(),
preset: null,
@@ -85,10 +88,12 @@ function applyFiltersState() {
pin.classList.toggle("active", pinned);
pin.setAttribute("aria-pressed", String(pinned));
pin.title = pinned ? "Открепить фильтры" : "Закрепить фильтры";
pin.setAttribute("aria-label", pin.title);
toggle.classList.toggle("active", open);
toggle.setAttribute("aria-expanded", String(open));
toggle.title = open ? "Скрыть фильтры" : "Показать фильтры";
toggle.setAttribute("aria-label", toggle.title);
}
function toggleFilters() {
@@ -158,6 +163,8 @@ function syncThemeButton() {
themeToggle.title = light ? "Тёмная тема" : "Светлая тема";
themeToggle.setAttribute("aria-label", themeToggle.title);
themeToggle.setAttribute("aria-pressed", String(light));
const themeColor = $("#themeColor");
if (themeColor) themeColor.content = light ? "#f4f1e9" : "#090c12";
}
themeToggle.addEventListener("click", () => {
const light = document.documentElement.dataset.theme === "light";
@@ -226,6 +233,42 @@ function fmtDuration(h) {
return `≈${h >= 10 ? Math.round(h) : h.toFixed(1).replace(".0", "")} ч`;
}
function defaultDir(field) {
return ["hours", "review", "year", "added"].includes(field) ? "desc" : "asc";
}
function loadSort() {
try {
const saved = JSON.parse(localStorage.getItem(SORT_KEY) || "null");
if (saved && saved.sort) {
state.sort = saved.sort;
state.dir = saved.dir === "asc" ? "asc" : "desc";
}
} catch (_) {}
}
function saveSort() {
try {
localStorage.setItem(SORT_KEY, JSON.stringify({ sort: state.sort, dir: state.dir }));
} catch (_) {}
}
function loadTableWidths() {
try {
const saved = JSON.parse(localStorage.getItem(COLS_KEY) || "{}");
return saved && typeof saved === "object" ? saved : {};
} catch (_) {
return {};
}
}
function saveTableWidth(key, width) {
if (!Number.isFinite(width)) return;
const widths = loadTableWidths();
widths[key] = Math.round(width);
try { localStorage.setItem(COLS_KEY, JSON.stringify(widths)); } catch (_) {}
}
function initials(name) {
return name.split(/\s+/).slice(0, 2).map((w) => w[0] || "").join("").toUpperCase();
}
@@ -268,7 +311,8 @@ function cardHtml(g, mode = "library") {
return `
<article class="card" data-appid="${g.appid}" tabindex="0" role="button" aria-label="Открыть ${esc(g.name)}">
<div class="cover">
<img data-appid="${g.appid}" loading="lazy" src="${coverUrl(g.appid)}" alt="">
<img data-appid="${g.appid}" loading="lazy" width="300" height="450"
src="${coverUrl(g.appid)}" alt="">
<div class="fallback">${esc(initials(g.name))}</div>
${review}${installed}${selectBox}
</div>
@@ -285,6 +329,37 @@ function cardHtml(g, mode = "library") {
</article>`;
}
const TABLE_COLS = [
{ key: "select", label: "", width: 32, cls: "t-select" },
{ key: "name", label: "Игра", width: 300, cls: "", sort: "name" },
{ key: "year", label: "Год", width: 64, cls: "t-year", sort: "year" },
{ key: "review", label: "Отзывы", width: 76, cls: "", sort: "review" },
{ key: "hours", label: "Часы", width: 80, cls: "", sort: "hours" },
{ key: "duration", label: "Длительность", width: 104, cls: "t-duration", sort: "duration" },
{ key: "genres", label: "Жанры", width: 180, cls: "t-genres" },
{ key: "fav", label: "★", width: 30, cls: "t-fav" },
];
function tableHead() {
const widths = loadTableWidths();
const cols = TABLE_COLS.map((col) => {
return `<col data-col="${col.key}" style="width:${widths[col.key] || col.width}px">`;
}).join("");
const heads = TABLE_COLS.map((col) => {
const active = col.sort && state.sort === col.sort;
const arrow = active ? (state.dir === "asc" ? " ▲" : " ▼") : "";
const aria = col.sort
? ` aria-sort="${active ? (state.dir === "asc" ? "ascending" : "descending") : "none"}"`
: "";
const sort = col.sort ? ` data-sort="${col.sort}"` : "";
const resizer = col.key === "select" || col.key === "fav"
? "" : '<span class="col-resizer" data-col="' + col.key + '" aria-hidden="true"></span>';
const label = col.sort ? `<span class="th-label">${col.label}${arrow}</span>` : col.label;
return `<th class="${col.cls}" data-col="${col.key}"${sort}${aria}>${label}${resizer}</th>`;
}).join("");
return { cols, heads };
}
function rowHtml(g) {
const select = state.selectionMode
? `<input type="checkbox" data-select="${g.appid}"${state.selected.has(g.appid) ? " checked" : ""} aria-label="Выбрать игру">`
@@ -296,7 +371,8 @@ function rowHtml(g) {
<td class="t-select">${select}</td>
<td class="t-name">
<div class="cover-inline">
<img data-appid="${g.appid}" loading="lazy" src="${coverUrl(g.appid)}" alt="">
<img data-appid="${g.appid}" loading="lazy" width="34" height="51"
src="${coverUrl(g.appid)}" alt="">
<div class="fallback">${esc(initials(g.name))}</div>
</div>
<span class="t-title">${esc(g.name)}</span>
@@ -316,22 +392,43 @@ function modeHours(g) {
}
function tableHtml(items) {
const { cols, heads } = tableHead();
return `
<table class="game-table">
<thead><tr>
<th class="t-select"></th>
<th>Игра</th>
<th class="t-year">Год</th>
<th>Отзывы</th>
<th>Часы</th>
<th class="t-duration">Длительность</th>
<th class="t-genres">Жанры</th>
<th class="t-fav">★</th>
</tr></thead>
<table class="game-table" aria-label="Библиотека игр">
<colgroup>${cols}</colgroup>
<thead><tr>${heads}</tr></thead>
<tbody>${items.map(rowHtml).join("")}</tbody>
</table>`;
}
function bindColumnResizers(root) {
root.querySelectorAll(".col-resizer").forEach((handle) => {
if (handle.dataset.bound) return;
handle.dataset.bound = "1";
handle.addEventListener("pointerdown", (event) => {
event.preventDefault();
event.stopPropagation();
const col = handle.dataset.col;
const th = handle.closest("th");
const colEl = root.querySelector(`col[data-col="${col}"]`);
if (!th || !colEl) return;
const startX = event.clientX;
const startWidth = th.getBoundingClientRect().width;
const move = (moveEvent) => {
const width = Math.max(40, Math.round(startWidth + moveEvent.clientX - startX));
colEl.style.width = `${width}px`;
};
const up = () => {
document.removeEventListener("pointermove", move);
document.removeEventListener("pointerup", up);
saveTableWidth(col, parseFloat(colEl.style.width));
};
document.addEventListener("pointermove", move);
document.addEventListener("pointerup", up, { once: true });
});
});
}
function bindRows(root) {
root.querySelectorAll("tr[data-appid]").forEach((row) => {
if (row.dataset.bound) return;
@@ -349,6 +446,7 @@ function bindRows(root) {
}
});
});
bindColumnResizers(root);
bindImages(root);
}
@@ -440,6 +538,8 @@ function toast(message, action = null) {
el = document.createElement("div");
el.id = "toast";
el.className = "toast";
el.setAttribute("role", "status");
el.setAttribute("aria-live", "polite");
document.body.appendChild(el);
}
el.innerHTML = "";
@@ -589,12 +689,15 @@ function applySavedView(view) {
const saved = view.filters || {};
state.q = view.q || "";
state.sort = view.sort || "review";
state.dir = view.dir || defaultDir(state.sort);
state.filters = {
...defaultFilters(),
...saved,
genres: [...(saved.genres || [])],
tags: [...(saved.tags || [])],
};
$("#sort").value = state.sort;
saveSort();
syncFilterControls();
loadGames(true);
}
@@ -681,6 +784,7 @@ function filterParams() {
if (state.filters.unplayed) p.set("unplayed", "1");
if (state.filters.favorite) p.set("favorite", "1");
if (state.filters.duration) p.set("duration", state.filters.duration);
p.set("dir", state.dir);
[
["minHours", "min_hours"], ["maxHours", "max_hours"],
["minYear", "min_year"], ["maxYear", "max_year"],
@@ -781,6 +885,7 @@ async function runRecommend(scroll = true) {
include_tribute: $("#optTribute").checked,
include_nostalgia: $("#optNostalgia").checked,
min_review: Number($("#optReview").value),
session: $("#optSession").value || null,
limit: 36,
};
state.recommendContext = { preset: state.preset, mood: state.preset ? null : text };
@@ -909,14 +1014,14 @@ function renderModal(g) {
<div class="modal-grid">
<div class="modal-cover" id="modalCover">
<div class="cover-blur" id="modalCoverBlur"></div>
<img data-appid="${g.appid}" src="${coverUrl(g.appid)}" alt="">
<img data-appid="${g.appid}" width="600" height="900" src="${coverUrl(g.appid)}" alt="">
<div class="fallback">${esc(g.name)}</div>
</div>
<div class="modal-body">
<div class="modal-top">
${modalStack.length > 1 ? `<button class="modal-back" id="modalBack" title="Назад">←</button>` : ""}
<h2 class="modal-title">${esc(g.name)}</h2>
<button class="modal-close" id="modalClose" title="Закрыть">×</button>
${modalStack.length > 1 ? `<button class="modal-back" id="modalBack" title="Назад" aria-label="Назад">←</button>` : ""}
<h2 class="modal-title" id="modalTitle">${esc(g.name)}</h2>
<button class="modal-close" id="modalClose" title="Закрыть" aria-label="Закрыть">×</button>
</div>
<div class="modal-meta">${meta}</div>
<div class="chip-row">${genres}</div>
@@ -984,7 +1089,12 @@ function debounce(fn, ms) {
function switchView(view) {
state.view = view;
if (view !== "library") closeFilters();
document.querySelectorAll(".tab").forEach((t) => t.classList.toggle("active", t.dataset.view === view));
document.querySelectorAll(".tab").forEach((tab) => {
const active = tab.dataset.view === view;
tab.classList.toggle("active", active);
tab.setAttribute("aria-selected", String(active));
tab.tabIndex = active ? 0 : -1;
});
$("#libraryView").classList.toggle("hidden", view !== "library");
$("#recommendView").classList.toggle("hidden", view !== "recommend");
try {
@@ -995,9 +1105,19 @@ function switchView(view) {
} catch (_) {}
}
document.querySelectorAll(".tab").forEach((tab) => {
const tabButtons = [...document.querySelectorAll(".tab")];
tabButtons.forEach((tab) => {
tab.addEventListener("click", () => switchView(tab.dataset.view));
});
document.querySelector(".tabs").addEventListener("keydown", (event) => {
if (!["ArrowLeft", "ArrowRight"].includes(event.key)) return;
event.preventDefault();
const current = tabButtons.findIndex((tab) => tab.dataset.view === state.view);
const delta = event.key === "ArrowRight" ? 1 : -1;
const next = tabButtons[(current + delta + tabButtons.length) % tabButtons.length];
next.focus();
switchView(next.dataset.view);
});
$("#search").addEventListener("input", debounce((e) => {
state.q = e.target.value.trim();
@@ -1006,6 +1126,8 @@ $("#search").addEventListener("input", debounce((e) => {
$("#sort").addEventListener("change", (e) => {
state.sort = e.target.value;
state.dir = defaultDir(state.sort);
saveSort();
loadGames(true);
});
@@ -1048,7 +1170,8 @@ $("#saveView").addEventListener("click", () => {
const name = (prompt("Название вида:", "") || "").trim();
if (!name) return;
const views = loadViews();
const view = { name, q: state.q, sort: state.sort, filters: cloneFilters(state.filters) };
const view = { name, q: state.q, sort: state.sort, dir: state.dir,
filters: cloneFilters(state.filters) };
const existing = views.findIndex((item) => item.name === name);
let selected;
if (existing >= 0) {
@@ -1095,6 +1218,22 @@ grid.addEventListener("change", (event) => {
if (input) setSelected(Number(input.value), input.checked);
});
grid.addEventListener("click", (event) => {
if (!grid.classList.contains("table-view")) return;
const header = event.target instanceof Element && event.target.closest("th[data-sort]");
if (!header || event.target.closest(".col-resizer")) return;
const field = header.dataset.sort;
if (state.sort === field) {
state.dir = state.dir === "asc" ? "desc" : "asc";
} else {
state.sort = field;
state.dir = defaultDir(field);
}
$("#sort").value = state.sort;
saveSort();
loadGames(true);
});
function applyLayout(mode) {
if (!["grid", "list", "table"].includes(mode)) mode = "grid";
grid.dataset.layout = mode;
@@ -1343,6 +1482,8 @@ if ("serviceWorker" in navigator) {
}
(async function boot() {
loadSort();
$("#sort").value = state.sort;
await Promise.all([loadMeta(), loadMoods()]);
await loadGames(true);