Merge pull request #239 from poli0981/feat/random-games-leave

v4.7.0 Lucky Dip: random games page, Leave site, Decline quits the apps
This commit is contained in:
poli0981 authored and GitHub committed 2026-11-03 19:33:52 +07:00
commit ce2e1e014b
26 files changed
+1330 -22

No files matched your search

+42
View File
@@ -4,6 +4,42 @@ All notable changes to this awesome noob repo will be documented here.
## [Unreleased]
## [v4.7.0] – 2026-11-03 (The "Lucky Dip" Edition)
Two small additions. A Random games page picks up to five games from the
catalogue when you cannot decide what to play, and the first-run terms screen
gets a way out: on the website, "Leave site" takes you back to the page you
came from; in the apps, Decline now quits, which on Android it never did. No
legal document changed, so nobody is asked to accept the terms again. Desktop
and Android bumped `2.4.1` → `2.5.0`; repo public-facing version `4.6.1` →
`4.7.0`. The desktop app offers 2.5.0 through its updater once the release is
published; on Android, install the new APK over the old one.
### ✨ Added
- **Random games.** `/random`, in the sidebar, the menu and the command
palette, with a dice button on the dashboard, rolls one to five games (five
to start with): online, offline or either, dead games only when you ask for
them, and never one marked unsafe. Roll again for a set that avoids the
games on screen; a smaller count keeps the first ones, a larger one adds to
them. Opening a game and coming back keeps the picks, and nothing is
stored: a reload rolls anew.
- **Leave site**, on the first-run terms screen and on the notice after
Decline (website only). A page may not open the browser's own start page,
so it goes back to the page before the site - the new-tab page when you
typed the address there, the search results when you came from a search -
past every page of the site you opened in between. When the site is the
first page in its tab, it says so and offers to close the tab; that takes a
second click, because closing the last tab closes the browser window too.
### 🐛 Fixed
- Declining the terms quits the Android app. It did nothing at all: the app
asked its window to close, which does nothing on Android. Both apps now quit
through Tauri's own exit, and the declined notice appears if an app is ever
still open afterwards. The apps also drop a permission nothing uses any more
(closing a window from script) for the one quitting needs.
### 🧰 Tooling & misc
- Dependencies: SvelteKit 3.1.1 and adapter-static 4.0.1, Svelte 5.57.3,
@@ -16,6 +52,12 @@ All notable changes to this awesome noob repo will be documented here.
- The undici override is gone: wrangler 4.156.0's local simulator pins the
patched undici 7.30.1 itself.
### 📚 Docs
- `CLAUDE.md`: how `/random` rolls and why it stores nothing; how Leave site
finds the page before the site, and why Decline quits through `exit()`.
- Both READMEs list the random page and its modules.
## [v4.6.1] – 2026-10-31 (The "Zip Tie" Edition)
A security pass. The desktop app's updater takes the patched zip reader
+41
View File
@@ -1118,6 +1118,28 @@ scraping pipeline (`scripts/`) driven by GitHub Actions.
The gate renders only after `consent.hydrated`: rendered before storage was
read, it was baked into every prerendered page and flashed for returning
visitors.
- **Declining or leaving at the gate.** In the apps Decline calls `exit()` from
`@tauri-apps/api/app` (capability `core:app:allow-exit` in
`capabilities/default.json`), never `getCurrentWindow().close()`: on Android
that resolves without closing anything (tao reports a destroyed window only
from the Activity's `onDestroy`), so Decline did nothing there before 2.5.0.
`exit()` finishes the activity on Android and ends the process on the
desktop; the declined notice appears if the app is still alive 2 s later. On
the web, "Leave site" (`lib/leave-site.ts`, hidden under Tauri) goes back to
the page before the site, because no page may open the browser's own start
page (`chrome://newtab`, `about:home`). Rules:
- It steps over ALL of the site's entries at once,
`history.go(-(navigation.currentEntry.index + 1))`: `entries()` is the
contiguous same-origin run, other documents and SvelteKit's pushState
entries included. Without the Navigation API it is one step back.
- `history.go()` is silent when there is nowhere to go (the foreign entries
can all be forward ones), so a 1.5 s watchdog shows "Nothing to go back
to"; `beforeunload`, `pagehide` and `popstate` cancel it. `pagehide`
matters: timers freeze in the back/forward cache and resume on restore.
- When every entry is the site's, closing the tab is a SECOND, explicit click
(`closeTab()`): closing the last tab closes the browser window with it.
- `consent-gate.test.ts` holds the exit import, the capability and the two
guarded Leave buttons; `leave-site.test.ts` holds the algorithm.
- **`/welcome` is shown once, by the layout, and only to a visit that STARTED
on `/`** (not a deep link, not `/#/…`, not mid-session), after consent and
the human check. It
@@ -1135,6 +1157,25 @@ scraping pipeline (`scripts/`) driven by GitHub Actions.
from a game keeps the page and a changed filter starts again at page 1.
The language filter (`?lang=`) offers the names stored in `languages`,
Steam's English ones: data, never i18n keys.
- **`/random` keeps its picks in memory, and only the reader rolls.**
`lib/random.svelte.ts` holds appids, module-level so Back from a game shows
the same games, and NO `f2p:*` key: the Privacy Policy lists every stored
key, and editing it reopens the consent gate for everyone. Rules:
- A roll happens in a handler, or once in an `untrack`ed effect when the
catalogue first arrives - never in `$derived` or markup, which would roll
again on every revalidation or language switch. `resolve()` is the
deterministic part: it drops a pick that left the catalogue or stopped
qualifying, and nothing tops it back up.
- Randomness is `crypto.getRandomValues` with rejection sampling and a sparse
Fisher-Yates (`lib/random-pick.ts`). Never `Math.random`: SonarCloud
reports it as hotspot S2245, and an unreviewed hotspot fails the gate.
- Never a game marked unsafe or without an appid; dead games only on
request. The route is top-level on purpose: under `/games/` the header
search would stop jumping to /games, `isActive` would light Games too, and
the PWA's `globIgnores` would leave it out of the precache.
- A plural key needs its base key (`random.pool` beside `random.pool_one`):
`t()` falls back from `_other` to the base, and the i18n test requires
every literal key to exist.
- **Search folds; storage never does.** `lib/search-fold.ts` `fold()` is NFKC
plus hiragana to katakana, applied to BOTH sides of every search box
(`/games`' Fuse index, the palette, /developers, /publishers, the anti-cheat
+1
View File
@@ -46,6 +46,7 @@ A SvelteKit 2 / Svelte 5 app, prerendered and served by a Cloudflare Worker that
- **Browse** — virtualised table (TanStack Virtual), filters for genre, type, platform, status, anti-cheat and safety, Fuse.js fuzzy search, sortable columns, 50/100/200/500/all pages. Filters live in the URL, so a filtered view can be shared.
- **Charts** — Apache ECharts: dashboard KPIs, genres, platforms, languages, tags, anti-cheat (chart and a searchable index), reviews, player tiers, release years and catalogue growth, DRM/DLC, delisted games, plus a stats page (Metacritic, retention, games that went quiet).
- **A page per game** — `/games/:appid` is prerendered for search engines and filled with live player counts and reviews in the browser.
- **Random games** — `/random` rolls one to five games when you cannot decide: online, offline or either, dead games only if you ask, never one marked unsafe. Roll again for a new set; opening a game and coming back keeps the picks.
- **Fresh data, verified** — `data/index.json` carries a SHA-256 per shard; the app only caches a generation it could verify, keeps the last good one offline, and re-checks when you come back to the tab.
- **Installable** — a web app you can install, with an offline mode and an update prompt.
- **i18n** vi / en — auto-detected, switchable from the welcome page or Settings.
+3 -1
View File
@@ -94,13 +94,15 @@ web/
│ ├── routes/ # pages; +layout, +error, sitemap.xml
│ ├── params/ # route param matchers (legal document slugs)
│ ├── lib/
│ │ ├── *.svelte.ts # rune state: games, filters, prefs, i18n, pwa
│ │ ├── *.svelte.ts # rune state: games, filters, random picks, prefs, i18n, pwa
│ │ ├── schema.ts # mirrors scripts/core/constants.py
│ │ ├── games-loader.ts # verified shard generations, offline fallback
│ │ ├── cache.ts # IndexedDB read/write
│ │ ├── fallback-route.ts # re-renders routes served the SPA shell
│ │ ├── consent.svelte.ts # legal consent, hashed per document
│ │ ├── diff.ts # the line diff the consent gate shows
│ │ ├── leave-site.ts # the consent gate's "Leave site": back to the page before
│ │ ├── random-pick.ts # /random: crypto sampling and who may come up
│ │ ├── analytics.ts # the beacon, appended only after consent
│ │ ├── human-check.ts # the Turnstile check's rules (+ -state.svelte.ts, turnstile.ts)
│ │ ├── gates.ts # the routes no first-run gate covers
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "free-steam-games-web",
"version": "2.4.1",
"version": "2.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "free-steam-games-web",
"version": "2.4.1",
"version": "2.5.0",
"dependencies": {
"@fontsource-variable/bricolage-grotesque": "^5.3.0",
"@fontsource-variable/ibm-plex-sans": "^5.3.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "free-steam-games-web",
"private": true,
"version": "2.4.1",
"version": "2.5.0",
"type": "module",
"imports": {
"#lib/*": "./src/lib/*"
+1 -1
View File
@@ -150,7 +150,7 @@ const TURNSTILE_HOST = "https://challenges.cloudflare.com";
const MEDIA_HOST = "https://media.free-steam-games.win";
// Strings that must never be baked into a page before data exists.
const BAKED_EMPTY_STATES = [en.games.noResults, en.health.allClear, en.studios.notFound];
const BAKED_EMPTY_STATES = [en.games.noResults, en.health.allClear, en.studios.notFound, en.random.noMatch];
const CONSENT_TITLE = en.consent.title;
const HUMAN_CHECK_TITLE = en.humanCheck.title;
+1 -1
View File
@@ -938,7 +938,7 @@ dependencies = [
[[package]]
name = "f2p-tracker"
version = "2.4.1"
version = "2.5.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "f2p-tracker"
version = "2.4.1"
version = "2.5.0"
description = "Desktop wrapper around the Steam F2P Tracker web app"
authors = ["poli0981"]
license = "MIT"
+2 -2
View File
@@ -1,13 +1,13 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Cross-platform capabilities for the main window. The frontend is a static SvelteKit app that fetches its data from free-steam-games.win over plain HTTP, so shell:open is the only native bridge it needs - it opens external links, which the webview otherwise blocks. The desktop-only updater lives in updater.json so the Android/iOS build, which does not compile that plugin, does not fail ACL resolution.",
"description": "Cross-platform capabilities for the main window. The frontend is a static SvelteKit app that fetches its data from free-steam-games.win over plain HTTP, so it needs two native bridges: shell:open, which opens external links the webview otherwise blocks, and app exit, which quits the app when the reader declines the terms (core:default does not include it, and the window's close() does nothing on Android). The desktop-only updater lives in updater.json so the Android/iOS build, which does not compile that plugin, does not fail ACL resolution.",
"windows": [
"main"
],
"permissions": [
"core:default",
"core:window:allow-close",
"core:app:allow-exit",
"shell:allow-open"
]
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "F2P Tracker",
"version": "2.4.1",
"version": "2.5.0",
"identifier": "io.github.poli0981.f2p-tracker",
"build": {
"beforeBuildCommand": "npm run build:desktop",
+22 -1
View File
@@ -17,7 +17,13 @@
"decline": "Decline",
"declinedTitle": "You need to accept the terms",
"declinedBody": "You must accept the licences, EULA, Privacy Policy, Disclaimer, and Terms of Use to use F2P Tracker.",
"back": "Back"
"back": "Back",
"leave": "Leave site",
"leaveNowhereTitle": "Nothing to go back to",
"leaveNowhereBody": "This site is the first page in this tab or window, so there is no earlier page to return to. Close it to leave.",
"leaveCloseTab": "Close this tab",
"leaveCloseWindow": "Close this window",
"leaveRefused": "The browser does not let a page close a tab that has a history. Close the tab or window yourself to leave."
},
"humanCheck": {
"title": "Checking you are human",
@@ -64,6 +70,7 @@
"nav": {
"dashboard": "Dashboard",
"games": "Games",
"random": "Random games",
"topOnline": "Top Online",
"topOffline": "Top Offline",
"charts": "Charts",
@@ -197,6 +204,20 @@
"topOffline": {
"subtitle": "Top 100 single-player or non-online F2P titles by concurrent players."
},
"random": {
"subtitle": "Can't decide what to play? Roll up to five free games from the catalogue.",
"seoDescription": "Free-to-play Steam games picked at random - online or offline, with or without the ones nobody plays any more.",
"roll": "Roll the dice",
"rollAgain": "Roll again",
"countLabel": "How many",
"includeDead": "Include dead games",
"pool": "Picked from {{total}} games",
"pool_one": "Picked from {{total}} game",
"announce": "{{count}} games picked: {{names}}",
"announce_one": "1 game picked: {{names}}",
"noMatch": "No game matches these settings.",
"openOnSteam": "Open on Steam"
},
"settings": {
"title": "Settings",
"subtitle": "Language, theme, and preferences.",
+22 -1
View File
@@ -17,7 +17,13 @@
"decline": "Từ chối",
"declinedTitle": "Bạn cần chấp nhận điều khoản",
"declinedBody": "Bạn phải chấp nhận các giấy phép, EULA, Chính sách quyền riêng tư, Tuyên bố miễn trừ và Điều khoản sử dụng để dùng F2P Tracker.",
"back": "Quay lại"
"back": "Quay lại",
"leave": "Rời trang",
"leaveNowhereTitle": "Không có trang nào để quay về",
"leaveNowhereBody": "Trang này là trang đầu tiên trong thẻ hoặc cửa sổ này, nên không có trang nào trước đó để quay về. Hãy đóng nó để rời đi.",
"leaveCloseTab": "Đóng thẻ này",
"leaveCloseWindow": "Đóng cửa sổ này",
"leaveRefused": "Trình duyệt không cho trang tự đóng một thẻ đã có lịch sử duyệt. Hãy tự đóng thẻ hoặc cửa sổ để rời đi."
},
"humanCheck": {
"title": "Đang xác minh bạn là người thật",
@@ -64,6 +70,7 @@
"nav": {
"dashboard": "Tổng quan",
"games": "Trò chơi",
"random": "Game ngẫu nhiên",
"topOnline": "Top Online",
"topOffline": "Top Offline",
"charts": "Biểu đồ",
@@ -197,6 +204,20 @@
"topOffline": {
"subtitle": "Top 100 game F2P single-player / không-online theo số người chơi đồng thời."
},
"random": {
"subtitle": "Chưa biết chơi gì? Gieo xúc xắc để chọn tối đa năm game miễn phí trong danh sách.",
"seoDescription": "Game miễn phí trên Steam được chọn ngẫu nhiên - online hay offline, có hoặc không tính những game không còn ai chơi.",
"roll": "Gieo xúc xắc",
"rollAgain": "Gieo lại",
"countLabel": "Số lượng",
"includeDead": "Tính cả game đã chết",
"pool": "Chọn từ {{total}} game",
"pool_one": "Chọn từ {{total}} game",
"announce": "Đã chọn {{count}} game: {{names}}",
"announce_one": "Đã chọn 1 game: {{names}}",
"noMatch": "Không có game nào khớp với các lựa chọn này.",
"openOnSteam": "Mở trên Steam"
},
"settings": {
"title": "Cài đặt",
"subtitle": "Ngôn ngữ, giao diện và tuỳ chọn.",
+72 -9
View File
@@ -3,6 +3,7 @@
import ShieldCheck from "@lucide/svelte/icons/shield-check";
import ChevronRight from "@lucide/svelte/icons/chevron-right";
import FileDiff from "@lucide/svelte/icons/file-diff";
import House from "@lucide/svelte/icons/house";
import { page } from "$app/state";
import { consent } from "../consent.svelte";
import { CONSENT_DOCS, legalDocSlug } from "../legal";
@@ -10,6 +11,8 @@
import { i18n } from "../i18n.svelte";
import { isTauri } from "../external-open";
import { isUngatedPath } from "../gates";
import { closeTab, leaveSite } from "../leave-site";
import { pwa } from "../pwa-state.svelte";
import Button from "../ui/Button.svelte";
const t = i18n.t;
@@ -17,6 +20,15 @@
let checked = $state(false);
let declined = $state(false);
// The apps have no browser to go back in, and Decline already quits them.
// Settled when the component is created in the page; the server render that
// reads it never shows the gate (`open` waits for consent.hydrated).
const canLeave = !isTauri();
/** "nowhere": the site is the first page in this tab, so the only way out is
* closing it. "refused": the browser would not let the page do that either. */
let leaving = $state<"idle" | "nowhere" | "refused">("idle");
// /error/* and /legal/* stay readable before consent; lib/gates.ts says why,
// and HumanCheck.svelte exempts exactly the same routes.
const exempt = $derived(isUngatedPath(page.url.pathname));
@@ -89,36 +101,81 @@
// overflow-auto, so wheel events over it never reach the page beneath.
async function decline() {
// Desktop: declining means you do not get the app, so quit it. On the web
// there is nothing to quit, so show a blocking notice with a way back.
// Apps: declining means you do not get the app, so quit it - with exit()
// from the app module (capability core:app:allow-exit), not the window's
// close(). On Android close() does nothing at all: tao reports a destroyed
// window only from the Activity's onDestroy, so Decline sat there dead.
// exit() finishes the activity there (back to the home screen) and ends
// the process on the desktop. On the web there is nothing to quit, so show
// a blocking notice with a way back.
if (isTauri()) {
try {
const { getCurrentWindow } = await import("@tauri-apps/api/window");
await getCurrentWindow().close();
const { exit } = await import("@tauri-apps/api/app");
await exit(0);
// exit() can resolve before Android's closing transition has run.
// Still here a while later means it did not happen: say so.
setTimeout(() => (declined = true), 2000);
return;
} catch (err) {
console.error("ConsentGate: failed to close window", err);
console.error("ConsentGate: failed to quit the app", err);
}
}
declined = true;
}
// Web only (canLeave): back to the page before the site; lib/leave-site.ts
// has why that is the nearest a page can get to the browser's start page.
function leave() {
leaveSite(window, () => (leaving = "nowhere"));
}
function closeThisTab() {
if (!closeTab(window)) leaving = "refused";
}
</script>
<!-- Both cards below centre with m-auto, not items-center: auto margins centre
<!-- The cards below centre with m-auto, not items-center: auto margins centre
a card that fits and collapse for one that does not, so on a short phone
the card scrolls from its top instead of losing it above the screen.
p-safe-or-4 keeps it clear of the Android system bars. -->
{#if !open}
<!-- nothing: the page underneath is already rendered -->
{:else if leaving !== "idle"}
<div class="fixed inset-0 z-[60] flex overflow-auto bg-background/95 p-safe-or-4 backdrop-blur-sm">
<div class="m-auto w-full max-w-md rounded-lg border bg-card p-8 text-center">
<House class="mx-auto mb-4 size-10 text-muted-foreground" />
<h1 class="mb-2 text-xl font-semibold">{t("consent.leaveNowhereTitle")}</h1>
<p role="status" class="text-sm text-muted-foreground">
{leaving === "refused" ? t("consent.leaveRefused") : t("consent.leaveNowhereBody")}
</p>
<div class="mt-6 flex flex-wrap justify-center gap-2">
{#if leaving === "nowhere"}
<Button onclick={closeThisTab}>
{pwa.standalone ? t("consent.leaveCloseWindow") : t("consent.leaveCloseTab")}
</Button>
{/if}
<!-- Back to whichever card was showing: the terms, or the declined notice. -->
<Button variant="outline" onclick={() => (leaving = "idle")}>{t("consent.back")}</Button>
</div>
</div>
</div>
{:else if declined}
<div class="fixed inset-0 z-[60] flex overflow-auto bg-background/95 p-safe-or-4 backdrop-blur-sm">
<div class="m-auto w-full max-w-md rounded-lg border border-warning/40 bg-warning/5 p-8 text-center">
<ShieldCheck class="mx-auto mb-4 size-10 text-warning" />
<h1 class="mb-2 text-xl font-semibold">{t("consent.declinedTitle")}</h1>
<p class="text-sm text-muted-foreground">{t("consent.declinedBody")}</p>
<Button class="mt-6" variant="outline" onclick={() => (declined = false)}>
{t("consent.back")}
</Button>
<div class="mt-6 flex flex-wrap justify-center gap-2">
<Button variant="outline" onclick={() => (declined = false)}>
{t("consent.back")}
</Button>
{#if canLeave}
<Button variant="ghost" onclick={leave}>
<House class="size-4" />
{t("consent.leave")}
</Button>
{/if}
</div>
</div>
</div>
{:else}
@@ -206,6 +263,12 @@
{reviewing ? t("consent.acceptChanges") : t("consent.continue")}
</Button>
<Button variant="ghost" onclick={decline}>{t("consent.decline")}</Button>
{#if canLeave}
<Button variant="ghost" class="sm:ml-auto" onclick={leave}>
<House class="size-4" />
{t("consent.leave")}
</Button>
{/if}
</div>
</div>
</div>
+35
View File
@@ -0,0 +1,35 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { withoutBlockComments } from "./testing/source";
const gate = withoutBlockComments(
readFileSync(join(process.cwd(), "src", "lib", "common", "ConsentGate.svelte"), "utf-8"),
);
const capability = JSON.parse(
readFileSync(join(process.cwd(), "src-tauri", "capabilities", "default.json"), "utf-8"),
) as { permissions: string[] };
describe("declining the terms in the apps", () => {
it("quits through the app module, not the window", () => {
// getCurrentWindow().close() does nothing on Android, where Decline sat
// there dead. exit() finishes the activity.
expect(gate).toContain('import("@tauri-apps/api/app")');
expect(gate).not.toContain('import("@tauri-apps/api/window")');
});
it("is allowed to quit, and to do nothing more", () => {
// Without the permission exit() throws, and Decline only shows a notice.
expect(capability.permissions).toContain("core:app:allow-exit");
// Closing a window from script was Decline's alone; nothing needs it now.
expect(capability.permissions).not.toContain("core:window:allow-close");
});
});
describe("leaving the site from the terms", () => {
it("offers Leave on the terms card and on the declined notice, on the web only", () => {
expect(gate.match(/onclick=\{leave\}/g)).toHaveLength(2);
expect(gate.match(/\{#if canLeave\}/g)).toHaveLength(2);
expect(gate).toContain("const canLeave = !isTauri();");
});
});
+146
View File
@@ -0,0 +1,146 @@
import { describe, expect, it, vi } from "vitest";
import { LEAVE_TIMEOUT_MS, closeTab, leaveSite, type LeaveWindow } from "./leave-site";
interface FakeOptions {
/** history.length: every entry in the tab. */
length: number;
/** navigation.entries().length; leave out for a browser without the API. */
ours?: number;
/** navigation.currentEntry.index, null for no current entry. */
index?: number | null;
/** Whether close() is accepted. */
closes?: boolean;
}
/** A window whose history, timers and events the test drives by hand. */
function fakeWindow({ length, ours, index, closes = false }: FakeOptions) {
const listeners = new Map<string, Set<() => void>>();
const timers = new Map<number, { handler: () => void; timeout: number }>();
let nextId = 1;
const go = vi.fn<(delta: number) => void>();
const win = {
history: { length, go },
navigation:
ours === undefined
? undefined
: {
currentEntry: index === null ? null : { index: index ?? ours - 1 },
entries: () => new Array<unknown>(ours),
},
closed: false as boolean,
close() {
if (closes) win.closed = true;
},
setTimeout(handler: () => void, timeout: number) {
const id = nextId++;
timers.set(id, { handler, timeout });
return id;
},
clearTimeout(id: number) {
timers.delete(id);
},
addEventListener(type: string, listener: () => void) {
if (!listeners.has(type)) listeners.set(type, new Set());
listeners.get(type)!.add(listener);
},
removeEventListener(type: string, listener: () => void) {
listeners.get(type)?.delete(listener);
},
} satisfies LeaveWindow;
return {
win,
go,
fire(type: string) {
for (const listener of [...(listeners.get(type) ?? [])]) listener();
},
runTimers() {
for (const [id, timer] of [...timers]) {
timers.delete(id);
timer.handler();
}
},
timeouts: () => [...timers.values()].map((t) => t.timeout),
listening: () => [...listeners.values()].reduce((n, set) => n + set.size, 0),
};
}
describe("leaving the site", () => {
it("steps back past every page of the site, to the one before it", () => {
// New-tab page, then three entries of ours (a legal document among them).
const tab = fakeWindow({ length: 4, ours: 3, index: 2 });
const nowhere = vi.fn();
expect(leaveSite(tab.win, nowhere)).toBe("traversing");
expect(tab.go).toHaveBeenCalledExactlyOnceWith(-3);
expect(tab.timeouts()).toEqual([LEAVE_TIMEOUT_MS]);
expect(nowhere).not.toHaveBeenCalled();
});
it("says at once when every entry in the tab is the site's", () => {
const tab = fakeWindow({ length: 2, ours: 2 });
const nowhere = vi.fn();
expect(leaveSite(tab.win, nowhere)).toBe("nowhere");
expect(nowhere).toHaveBeenCalledOnce();
expect(tab.go).not.toHaveBeenCalled();
expect(tab.timeouts()).toEqual([]);
});
it("says so later when the only other entries are forward ones", () => {
// The reader went on to another site and came Back: go(-1) is out of
// range, and the browser answers that with silence.
const tab = fakeWindow({ length: 2, ours: 1, index: 0 });
const nowhere = vi.fn();
leaveSite(tab.win, nowhere);
expect(tab.go).toHaveBeenCalledWith(-1);
expect(nowhere).not.toHaveBeenCalled();
tab.runTimers();
expect(nowhere).toHaveBeenCalledOnce();
expect(tab.listening()).toBe(0);
});
it.each(["beforeunload", "pagehide", "popstate"])("stands the watchdog down on %s", (event) => {
const tab = fakeWindow({ length: 3, ours: 1, index: 0 });
const nowhere = vi.fn();
leaveSite(tab.win, nowhere);
tab.fire(event);
expect(tab.timeouts()).toEqual([]);
expect(tab.listening()).toBe(0);
tab.runTimers();
expect(nowhere).not.toHaveBeenCalled();
});
it("ignores a second click while the first is under way", () => {
const tab = fakeWindow({ length: 3, ours: 1, index: 0 });
leaveSite(tab.win, vi.fn());
expect(leaveSite(tab.win, vi.fn())).toBe("traversing");
expect(tab.go).toHaveBeenCalledOnce();
// Brought back from the back/forward cache: a new click works again.
tab.fire("pagehide");
leaveSite(tab.win, vi.fn());
expect(tab.go).toHaveBeenCalledTimes(2);
});
it("takes one step back without the Navigation API", () => {
const tab = fakeWindow({ length: 3 });
leaveSite(tab.win, vi.fn());
expect(tab.go).toHaveBeenCalledWith(-1);
const fresh = fakeWindow({ length: 1 });
const nowhere = vi.fn();
expect(leaveSite(fresh.win, nowhere)).toBe("nowhere");
expect(nowhere).toHaveBeenCalledOnce();
expect(fresh.go).not.toHaveBeenCalled();
});
it("takes one step back when the API has no current entry", () => {
const tab = fakeWindow({ length: 3, ours: 2, index: null });
leaveSite(tab.win, vi.fn());
expect(tab.go).toHaveBeenCalledWith(-1);
});
});
describe("closing the tab", () => {
it("reports whether the browser agreed", () => {
expect(closeTab(fakeWindow({ length: 1, closes: true }).win)).toBe(true);
expect(closeTab(fakeWindow({ length: 2 }).win)).toBe(false);
});
});
+102
View File
@@ -0,0 +1,102 @@
/**
* "Leave site" on the first-run terms screen.
*
* A page cannot open the browser's own start page: chrome://newtab, about:home
* and edge://newtab are all refused to websites. The closest thing is the page
* this tab showed before the site - the new-tab page when the address was typed
* there, the search results when the reader came from a search - so that is
* where this goes.
*
* The Navigation API (Baseline since 2026-01) knows this site's run of entries
* in the tab: entries() is the contiguous same-origin stretch around the
* current entry, other documents of this origin and SvelteKit's own pushState
* entries included, and currentEntry.index is the position in it. So
* history.go(-(index + 1)) lands on the entry just before the site, in one
* step, however many of the site's own pages (a legal document, say) came in
* between. Without the API it is one step back, which may land on one of the
* site's pages; the reader clicks again.
*
* history.go() says nothing when there is nowhere to go - the foreign entries
* may all be FORWARD ones (the reader went on to another site and came back) -
* so a watchdog calls onNowhere if the page is still here LEAVE_TIMEOUT_MS
* later. beforeunload (a traversal leaving the document has started), pagehide
* (the page is going, into the back/forward cache too) and popstate (a landing
* inside the document, the legacy path) cancel it. Timers freeze in the
* back/forward cache and resume on restore, so pagehide clears it whether or
* not the page is kept: a page brought back by Forward must not then claim it
* had nowhere to go.
*
* When every entry is the site's (the tab, or the installed app's window, was
* opened on it) there is nothing to go back to, and onNowhere runs at once.
* Closing is then a separate, deliberate click (closeTab): closing the last tab
* closes the window, and the browser with it, which "leave this site" never
* asked for.
*/
export const LEAVE_TIMEOUT_MS = 1500;
type LeaveEvent = "beforeunload" | "pagehide" | "popstate";
const SETTLED: readonly LeaveEvent[] = ["beforeunload", "pagehide", "popstate"];
/** The parts of `window` this needs; the real window satisfies it as it is. */
export interface LeaveWindow {
readonly history: { readonly length: number; go(delta: number): void };
readonly navigation?: {
readonly currentEntry: { readonly index: number } | null;
entries(): readonly unknown[];
};
readonly closed: boolean;
close(): void;
setTimeout(handler: () => void, timeout: number): number;
clearTimeout(id: number): void;
addEventListener(type: LeaveEvent, listener: () => void): void;
removeEventListener(type: LeaveEvent, listener: () => void): void;
}
export type LeaveStart = "traversing" | "nowhere";
// A second click while the first traversal is starting must neither arm a
// second watchdog nor step back twice.
const watching = new WeakSet<LeaveWindow>();
/** Back to the page before this site. `onNowhere` runs now when there is none,
* or later when the traversal never started. */
export function leaveSite(win: LeaveWindow, onNowhere: () => void): LeaveStart {
if (watching.has(win)) return "traversing";
const nav = win.navigation;
const current = nav?.currentEntry;
let delta = -1;
if (nav && current) {
if (win.history.length <= nav.entries().length) {
onNowhere();
return "nowhere";
}
delta = -(current.index + 1);
} else if (win.history.length <= 1) {
onNowhere();
return "nowhere";
}
let timer = 0;
const settle = () => {
win.clearTimeout(timer);
for (const type of SETTLED) win.removeEventListener(type, settle);
watching.delete(win);
};
watching.add(win);
for (const type of SETTLED) win.addEventListener(type, settle);
timer = win.setTimeout(() => {
settle();
onNowhere();
}, LEAVE_TIMEOUT_MS);
win.history.go(delta);
return "traversing";
}
/** Close the tab; true when the browser agreed. A script may close only a tab
* whose history holds this one page (or one a script opened), and `closed`
* turns true at once when the browser accepts. */
export function closeTab(win: Pick<LeaveWindow, "close" | "closed">): boolean {
win.close();
return win.closed;
}
+11
View File
@@ -26,4 +26,15 @@ describe("navigation lists", () => {
it("publishers is reachable from the sidebar", () => {
expect(PRIMARY.some((r) => r.to === "/publishers")).toBe(true);
});
it("random games are reachable from the sidebar", () => {
expect(PRIMARY.some((r) => r.to === "/random")).toBe(true);
});
it("the sidebar's icons are all distinct", () => {
// An icon shared by two rows is useless for finding either (nav.ts). EXTRA
// is left out: it is palette-only, and /welcome shares About's icon.
const icons = [...PRIMARY, ...SECONDARY].map((r) => r.icon);
expect(new Set(icons).size).toBe(icons.length);
});
});
+2
View File
@@ -12,6 +12,7 @@
*/
import type { Component } from "svelte";
import BarChart3 from "@lucide/svelte/icons/chart-column";
import Dices from "@lucide/svelte/icons/dices";
import Gamepad2 from "@lucide/svelte/icons/gamepad-2";
import Heart from "@lucide/svelte/icons/heart";
import HeartPulse from "@lucide/svelte/icons/heart-pulse";
@@ -42,6 +43,7 @@ export interface NavItem {
export const PRIMARY: NavItem[] = [
{ to: "/", i18n: "nav.dashboard", icon: LayoutDashboard, exact: true },
{ to: "/games", i18n: "nav.games", icon: Gamepad2 },
{ to: "/random", i18n: "nav.random", icon: Dices },
{ to: "/top-online", i18n: "nav.topOnline", icon: Users },
{ to: "/top-offline", i18n: "nav.topOffline", icon: Trophy },
{ to: "/charts", i18n: "nav.charts", icon: BarChart3 },
+198
View File
@@ -0,0 +1,198 @@
import { describe, expect, it } from "vitest";
import { buildIndex } from "./data-store";
import {
MAX_PICKS,
PICK_COUNTS,
buildPool,
clampCount,
isEligible,
randomBelow,
samplePicks,
type RandomSource,
} from "./random-pick";
import { SKELETON_TEMPLATE, type GameRecord } from "./schema";
/** Fixed words in order, then a loud failure: a test that draws more than it
* planned is a wrong test. */
function replay(...values: number[]): RandomSource {
let i = 0;
return () => {
if (i >= values.length) throw new Error("replay: out of values");
return values[i++];
};
}
/** xorshift32: deterministic, even enough to compare frequencies, and no
* Math.random even in a test. */
function xorshift(seed: number): RandomSource {
let x = seed | 0 || 1;
return () => {
x ^= x << 13;
x ^= x >>> 17;
x ^= x << 5;
return x >>> 0;
};
}
function game(appid: number, overrides: Partial<GameRecord> = {}): GameRecord {
return {
...SKELETON_TEMPLATE,
link: `https://store.steampowered.com/app/${appid}/`,
name: `Game ${appid}`,
type_game: "online",
...overrides,
};
}
function catalogue(records: GameRecord[]) {
return { records, appidIndex: buildIndex(records) };
}
/** `safe` is typed y/n/?/"", but it is typed in by hand, and the data carries
* spellings outside that (safety.ts normalises them). */
function handTyped(safe: string): GameRecord["safe"] {
return safe as GameRecord["safe"];
}
const ANY = { type: "any", includeDead: false } as const;
describe("randomBelow", () => {
it("throws away the words that would favour low results", () => {
// 2^32 % 3 === 1: 0xFFFFFFFF is the one word that would make 0 likelier.
const next = replay(0xffffffff, 0xfffffffe);
expect(randomBelow(3, next)).toBe(2);
expect(() => next()).toThrow(/out of values/);
// The worst case: just under half of all words are rejected.
expect(randomBelow(2 ** 31 + 1, replay(2 ** 31 + 1, 5))).toBe(5);
});
it("rejects nothing when n divides 2^32", () => {
expect(randomBelow(4, replay(0xffffffff))).toBe(3);
expect(randomBelow(2 ** 32, replay(0xffffffff))).toBe(0xffffffff);
expect(randomBelow(1, replay(123_456))).toBe(0);
});
it("fails loudly on a source that never produces a usable word", () => {
expect(() => randomBelow(3, () => 0xffffffff)).toThrow(/never produced/);
});
it("refuses an n it cannot draw from", () => {
for (const n of [0, -1, 1.5, Number.NaN, 2 ** 32 + 1]) {
expect(() => randomBelow(n, replay(1))).toThrow(RangeError);
}
});
it("draws from crypto by default, and evenly", () => {
const bins = new Array<number>(7).fill(0);
for (let i = 0; i < 70_000; i++) bins[randomBelow(7)]++;
// 10,000 expected per bin; one standard deviation is about 93.
for (const count of bins) expect(Math.abs(count - 10_000)).toBeLessThan(600);
});
});
describe("samplePicks", () => {
const POOL = Array.from({ length: 100 }, (_, i) => `g${i}`);
it("never returns the same entry twice, even from a pool that repeats one", () => {
const picks = samplePicks(["a", "a", "b"], 3, { next: xorshift(1) });
expect([...picks].sort()).toEqual(["a", "b"]);
});
it("returns at most the count, and at most the pool", () => {
for (const count of [0, -3, Number.NaN]) expect(samplePicks(POOL, count)).toEqual([]);
expect(samplePicks(POOL, 2.7)).toHaveLength(2);
expect(samplePicks([], 5)).toEqual([]);
expect([...samplePicks(["x", "y", "z"], 5)].sort()).toEqual(["x", "y", "z"]);
for (const id of samplePicks(POOL, 5)) expect(POOL).toContain(id);
});
it("avoids the games on screen while enough others remain", () => {
const avoid = new Set(POOL.slice(0, 5));
const next = xorshift(2);
for (let i = 0; i < 1000; i++) {
const picks = samplePicks(POOL, 5, { avoid, next });
expect(picks).toHaveLength(5);
expect(picks.some((id) => avoid.has(id))).toBe(false);
}
});
it("falls back on the games on screen when the pool is too small", () => {
const pool = ["a", "b", "c", "d", "e", "f", "g"];
const avoid = new Set(["a", "b", "c", "d", "e"]);
const picks = samplePicks(pool, 5, { avoid, next: xorshift(3) });
expect(picks).toHaveLength(5);
expect(new Set(picks).size).toBe(5);
// The two fresh ones first, then the shown ones to make up the number.
expect([...picks.slice(0, 2)].sort()).toEqual(["f", "g"]);
for (const id of picks.slice(2)) expect(avoid.has(id)).toBe(true);
});
it("never picks an excluded entry, even when that leaves fewer", () => {
const pool = ["a", "b", "c", "d", "e", "f", "g"];
const exclude = new Set(["a", "b", "c", "d", "e"]);
expect([...samplePicks(pool, 5, { exclude, next: xorshift(4) })].sort()).toEqual(["f", "g"]);
});
it("puts every order equally often", () => {
const counts = new Map<string, number>();
const next = xorshift(5);
for (let i = 0; i < 60_000; i++) {
const key = samplePicks(["a", "b", "c"], 3, { next }).join("");
counts.set(key, (counts.get(key) ?? 0) + 1);
}
expect([...counts.keys()].sort()).toEqual(["abc", "acb", "bac", "bca", "cab", "cba"]);
// 10,000 expected per order; one standard deviation is about 91.
for (const count of counts.values()) expect(Math.abs(count - 10_000)).toBeLessThan(500);
});
});
describe("the pool", () => {
it("leaves out what must never come up", () => {
const data = catalogue([
game(1),
game(2, { status: "delisted" }),
game(3, { safe: "n" }),
game(4, { safe: handTyped("no") }),
game(5, { is_dead: true }),
game(6, { safe: "y" }),
game(7, { safe: "" }),
game(0, { link: "" }),
]);
expect(buildPool(data, ANY)).toEqual(["1", "6", "7"]);
expect(buildPool(data, { ...ANY, includeDead: true })).toEqual(["1", "5", "6", "7"]);
});
it("narrows to one type", () => {
const data = catalogue([game(1), game(2, { type_game: "offline" }), game(3, { type_game: "" })]);
expect(buildPool(data, ANY)).toEqual(["1", "2", "3"]);
expect(buildPool(data, { ...ANY, type: "online" })).toEqual(["1"]);
expect(buildPool(data, { ...ANY, type: "offline" })).toEqual(["2"]);
});
it("lists an appid once, however many records carry it", () => {
const data = catalogue([game(1), game(2), game(1, { name: "Again" })]);
expect(buildPool(data, ANY)).toEqual(["1", "2"]);
});
it("judges a single record the same way", () => {
expect(isEligible(game(1), ANY)).toBe(true);
expect(isEligible(game(1, { safe: handTyped(" N ") }), ANY)).toBe(false);
expect(isEligible(game(1, { is_dead: true }), { ...ANY, includeDead: true })).toBe(true);
expect(isEligible(game(1, { type_game: "offline" }), { ...ANY, type: "online" })).toBe(false);
});
});
describe("clampCount", () => {
it("keeps the count between one and the maximum", () => {
expect(clampCount(0)).toBe(1);
expect(clampCount(-2)).toBe(1);
expect(clampCount(3.9)).toBe(3);
expect(clampCount(7)).toBe(MAX_PICKS);
expect(clampCount(Number.NaN)).toBe(MAX_PICKS);
});
it("matches what the control offers", () => {
expect(Math.max(...PICK_COUNTS)).toBe(MAX_PICKS);
expect(PICK_COUNTS.map(clampCount)).toEqual([...PICK_COUNTS]);
});
});
+143
View File
@@ -0,0 +1,143 @@
/**
* Picking games at random, for /random.
*
* Pure: no runes and no catalogue import, so the rules are tested without
* Svelte, and nothing here pulls in the search index (games/filtering.ts brings
* Fuse with it - the reason safety.ts is a module of its own).
*
* The randomness comes from crypto.getRandomValues, never Math.random. Nothing
* about a game pick is secret, but SonarCloud reports every Math.random as a
* security hotspot (S2245), and an unreviewed hotspot fails the quality gate.
*/
import { safeClass } from "./safety";
import type { GameRecord } from "./schema";
/** The most games one roll shows. */
export const MAX_PICKS = 5;
/** What the count control offers. */
export const PICK_COUNTS = [1, 2, 3, 4, 5] as const;
export type TypeChoice = "any" | "online" | "offline";
export interface PoolOptions {
type: TypeChoice;
includeDead: boolean;
}
/** What a roll reads of the catalogue. GamesData satisfies it as it is. */
export interface Catalogue {
readonly records: readonly GameRecord[];
readonly appidIndex: ReadonlyMap<string, number>;
}
/** A uniformly random integer in [0, 2^32). Injectable, so tests are exact. */
export type RandomSource = () => number;
const word = new Uint32Array(1);
const cryptoRandom: RandomSource = () => crypto.getRandomValues(word)[0];
const RANGE = 2 ** 32;
// The worst case, n = 2^31 + 1, rejects just under half of all words, so 64
// tries in a row fail with probability ~2^-64: only a broken source gets there.
const MAX_TRIES = 64;
/**
* A uniformly random integer in [0, n).
*
* `x % n` on its own favours the low remainders whenever n does not divide
* 2^32, so the top `2^32 % n` words are thrown away and drawn again.
*/
export function randomBelow(n: number, next: RandomSource = cryptoRandom): number {
if (!Number.isInteger(n) || n < 1 || n > RANGE) {
throw new RangeError(`randomBelow(${n}): n must be an integer from 1 to 2^32`);
}
const limit = RANGE - (RANGE % n);
for (let tries = 0; tries < MAX_TRIES; tries++) {
const x = next();
if (x < limit) return x % n;
}
throw new Error("randomBelow: the random source never produced a usable value");
}
/**
* 0..n-1 in uniformly random order, produced lazily.
*
* A Fisher-Yates shuffle that stores only the slots it has swapped: a roll
* reads five positions out of ~15,000, and shuffling a full copy of the pool
* for that would be 15,000 writes for five reads.
*/
function* shuffledPositions(n: number, next: RandomSource): Generator<number> {
const moved = new Map<number, number>();
for (let i = 0; i < n; i++) {
const j = i + randomBelow(n - i, next);
const value = moved.get(j) ?? j;
moved.set(j, moved.get(i) ?? i);
// Slot i is never read again. Dropping it keeps the map as small as the
// number of draws, and is also right when j === i.
moved.delete(i);
yield value;
}
}
export interface SampleOptions {
/** Never picked: the picks being KEPT when the count grows. */
exclude?: ReadonlySet<string>;
/** Picked only when too few others remain: the picks a re-roll replaces. */
avoid?: ReadonlySet<string>;
next?: RandomSource;
}
/**
* Up to `count` DISTINCT entries of `pool`, uniformly, in random order.
*
* Distinct even when the pool repeats one: the page keys its list on the
* appid, and a duplicate key in a keyed each throws in a production build.
*/
export function samplePicks(pool: readonly string[], count: number, opts: SampleOptions = {}): string[] {
const { exclude, avoid, next = cryptoRandom } = opts;
const want = Math.min(Math.max(Math.trunc(count) || 0, 0), pool.length);
const fresh: string[] = [];
if (want === 0) return fresh;
const held: string[] = [];
const seen = new Set<string>();
for (const at of shuffledPositions(pool.length, next)) {
const id = pool[at];
if (seen.has(id) || exclude?.has(id)) continue;
seen.add(id);
if (avoid?.has(id)) held.push(id);
else fresh.push(id);
if (fresh.length === want) return fresh;
}
// Too few games besides the ones on screen: make up the number with those,
// in the order they came up.
return [...fresh, ...held.slice(0, want - fresh.length)];
}
/** Whether a record may come up at all. */
export function isEligible(r: GameRecord, { type, includeDead }: PoolOptions): boolean {
if (r.status !== "active") return false;
// Reviewed and found unsafe: never suggested, whatever the settings.
if (safeClass(r.safe) === "n") return false;
if (r.is_dead && !includeDead) return false;
return type === "any" || r.type_game === type;
}
/**
* The appids a roll draws from. Read off appidIndex rather than the records:
* it holds exactly one entry per appid and none for a record without one,
* which is what a /games/<appid> link needs.
*/
export function buildPool(data: Catalogue, opts: PoolOptions): string[] {
const out: string[] = [];
for (const [appid, i] of data.appidIndex) {
const r = data.records[i];
if (r && isEligible(r, opts)) out.push(appid);
}
return out;
}
/** The count control's value, kept to 1..MAX_PICKS. */
export function clampCount(n: number): number {
return Number.isFinite(n) ? Math.min(MAX_PICKS, Math.max(1, Math.trunc(n))) : MAX_PICKS;
}
+131
View File
@@ -0,0 +1,131 @@
import { describe, expect, it } from "vitest";
import { buildIndex } from "./data-store";
import { RandomPicks } from "./random.svelte";
import type { RandomSource } from "./random-pick";
import { SKELETON_TEMPLATE, type GameRecord } from "./schema";
function xorshift(seed: number): RandomSource {
let x = seed | 0 || 1;
return () => {
x ^= x << 13;
x ^= x >>> 17;
x ^= x << 5;
return x >>> 0;
};
}
function game(appid: number, overrides: Partial<GameRecord> = {}): GameRecord {
return {
...SKELETON_TEMPLATE,
link: `https://store.steampowered.com/app/${appid}/`,
name: `Game ${appid}`,
type_game: appid % 2 ? "offline" : "online",
...overrides,
};
}
function catalogue(records: GameRecord[]) {
return { records, appidIndex: buildIndex(records) };
}
const GAMES = Array.from({ length: 40 }, (_, i) => game(i + 1));
describe("the /random picks", () => {
it("rolls once when the catalogue arrives, and never again by itself", () => {
const picks = new RandomPicks(xorshift(1));
picks.rollOnce(catalogue(GAMES));
const first = picks.appids;
expect(first).toHaveLength(5);
// A revalidation hands over a new catalogue object; the picks stay.
picks.rollOnce(catalogue([...GAMES]));
expect(picks.appids).toBe(first);
});
it("rolls a set that avoids the games on screen", () => {
const picks = new RandomPicks(xorshift(2));
const data = catalogue(GAMES);
picks.roll(data);
for (let i = 0; i < 50; i++) {
const before = new Set(picks.appids);
picks.roll(data);
expect(picks.appids).toHaveLength(5);
expect(picks.appids.some((appid) => before.has(appid))).toBe(false);
}
});
it("keeps the first picks for a smaller count, and adds to them for a larger one", () => {
const picks = new RandomPicks(xorshift(3));
const data = catalogue(GAMES);
picks.roll(data);
const five = [...picks.appids];
picks.setCount(3, data);
expect(picks.appids).toEqual(five.slice(0, 3));
picks.setCount(5, data);
expect(picks.appids.slice(0, 3)).toEqual(five.slice(0, 3));
expect(new Set(picks.appids).size).toBe(5);
picks.setCount(9, data);
expect(picks.count).toBe(5);
});
it("rolls again within a new type", () => {
const picks = new RandomPicks(xorshift(4));
const data = catalogue(GAMES);
picks.roll(data);
picks.setType("offline", data);
const shown = picks.resolve(data);
expect(shown).toHaveLength(5);
for (const { record } of shown) expect(record.type_game).toBe("offline");
});
it("brings dead games in only when asked", () => {
const data = catalogue(GAMES.map((g, i) => (i < 30 ? { ...g, is_dead: true } : g)));
const picks = new RandomPicks(xorshift(5));
for (let i = 0; i < 20; i++) {
picks.roll(data);
for (const { record } of picks.resolve(data)) expect(record.is_dead).toBe(false);
}
picks.setIncludeDead(true, data);
let sawDead = false;
for (let i = 0; i < 20 && !sawDead; i++) {
picks.roll(data);
sawDead = picks.resolve(data).some(({ record }) => record.is_dead);
}
expect(sawDead).toBe(true);
});
it("uses settings chosen before the catalogue arrived for the first roll", () => {
const picks = new RandomPicks(xorshift(6));
picks.setCount(2);
picks.setType("online");
expect(picks.appids).toEqual([]);
const data = catalogue(GAMES);
picks.rollOnce(data);
const shown = picks.resolve(data);
expect(shown).toHaveLength(2);
for (const { record } of shown) expect(record.type_game).toBe("online");
});
it("drops a pick that left the catalogue or turned unsafe, without rolling", () => {
const picks = new RandomPicks(xorshift(7));
picks.roll(catalogue(GAMES));
const [a, b, c, d, e] = picks.appids;
const next = catalogue(
GAMES.filter((g) => !g.link.includes(`/app/${a}/`)).map((g) =>
g.link.includes(`/app/${c}/`) ? { ...g, safe: "n" as const } : g,
),
);
expect(picks.resolve(next).map((p) => p.appid)).toEqual([b, d, e]);
expect(picks.appids).toEqual([a, b, c, d, e]);
});
it("shows what a small pool has, and nothing from an empty one", () => {
const picks = new RandomPicks(xorshift(8));
const three = catalogue(GAMES.slice(0, 3));
picks.roll(three);
expect(picks.appids).toHaveLength(3);
picks.roll(three);
expect(new Set(picks.appids).size).toBe(3);
picks.roll(catalogue(GAMES.map((g) => ({ ...g, is_dead: true }))));
expect(picks.appids).toEqual([]);
});
});
+109
View File
@@ -0,0 +1,109 @@
/**
* The picks /random shows, kept for the session.
*
* Module-level, like filters.svelte.ts, so opening a game and coming Back
* shows the same games rather than a new roll. Memory only, on purpose: the
* Privacy Policy lists every key the app stores, and editing it changes the
* document's hash, which asks every reader to accept the terms again. A reload
* rolls anew, which is what reloading a random page should do anyway.
*
* The picks are appids, resolved against whichever catalogue is current, so a
* revalidation that brings new data never re-rolls: it only drops a pick that
* left the catalogue or no longer qualifies. Nothing tops a dropped pick back
* up - that would be a roll the reader did not ask for.
*/
import {
MAX_PICKS,
buildPool,
clampCount,
isEligible,
samplePicks,
type Catalogue,
type PoolOptions,
type RandomSource,
type TypeChoice,
} from "./random-pick";
import type { GameRecord } from "./schema";
export interface ShownPick {
appid: string;
record: GameRecord;
}
export class RandomPicks {
count = $state(MAX_PICKS);
type = $state<TypeChoice>("any");
includeDead = $state(false);
/** In display order. Replaced whole, never mutated. */
appids = $state.raw<readonly string[]>([]);
#rolled = false;
readonly #next: RandomSource | undefined;
/** `next` replaces the crypto source, for tests only. */
constructor(next?: RandomSource) {
this.#next = next;
}
get options(): PoolOptions {
return { type: this.type, includeDead: this.includeDead };
}
/** The picks still in `data` that still qualify, in order. Deterministic,
* so it is safe inside a $derived. */
resolve(data: Catalogue): ShownPick[] {
const opts = this.options;
const out: ShownPick[] = [];
const seen = new Set<string>();
for (const appid of this.appids) {
const i = data.appidIndex.get(appid);
const record = i === undefined ? undefined : data.records[i];
if (!record || seen.has(appid) || !isEligible(record, opts)) continue;
seen.add(appid);
out.push({ appid, record });
}
return out;
}
/** The first roll, once the catalogue is here; a no-op ever after. */
rollOnce(data: Catalogue): void {
if (!this.#rolled) this.roll(data);
}
/** A new set, avoiding the games on screen while enough others remain. */
roll(data: Catalogue): void {
const shown = new Set(this.resolve(data).map((p) => p.appid));
this.appids = samplePicks(buildPool(data, this.options), this.count, { avoid: shown, next: this.#next });
this.#rolled = true;
}
/** Fewer keeps the first ones; more adds new games beside the ones shown.
* Without a catalogue yet it only records the choice for the first roll. */
setCount(n: number, data?: Catalogue): void {
this.count = clampCount(n);
if (!data) return;
const kept = this.resolve(data)
.slice(0, this.count)
.map((p) => p.appid);
const missing = this.count - kept.length;
this.appids =
missing > 0
? [...kept, ...samplePicks(buildPool(data, this.options), missing, { exclude: new Set(kept), next: this.#next })]
: kept;
this.#rolled = true;
}
/** A different type changes which games qualify, so it rolls again. */
setType(type: TypeChoice, data?: Catalogue): void {
this.type = type;
if (data) this.roll(data);
}
/** As setType: the pool changes, so the picks do too. */
setIncludeDead(on: boolean, data?: Catalogue): void {
this.includeDead = on;
if (data) this.roll(data);
}
}
export const randomPicks = new RandomPicks();
+10 -1
View File
@@ -7,6 +7,7 @@
import Trash2 from "@lucide/svelte/icons/trash-2";
import TrendingUp from "@lucide/svelte/icons/trending-up";
import ArrowRight from "@lucide/svelte/icons/arrow-right";
import Dices from "@lucide/svelte/icons/dices";
import { games, removedGames } from "#lib/games.svelte.js";
import { computeKpis, countBy, topByPlayers } from "#lib/stats.js";
import { i18n } from "#lib/i18n.svelte.js";
@@ -20,6 +21,7 @@
import EChart from "#lib/charts/EChart.svelte";
import { chartTheme, gridBox } from "#lib/chart-theme.js";
import Seo from "#lib/common/Seo.svelte";
import Button from "#lib/ui/Button.svelte";
const t = i18n.t;
@@ -73,7 +75,14 @@
subtitle={games.data
? t("dashboard.subtitle", { count: formatNumber(kpis.total) })
: t("dashboard.seoDescription")}
/>
>
{#snippet actions()}
<Button variant="outline" size="sm" href="/random">
<Dices class="size-4" />
{t("nav.random")}
</Button>
{/snippet}
</PageHeader>
<QueryState loading={games.pending} error={games.error} retry={() => games.refetch()}>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
+229
View File
@@ -0,0 +1,229 @@
<script lang="ts">
import { untrack } from "svelte";
import Dices from "@lucide/svelte/icons/dices";
import ExternalLink from "@lucide/svelte/icons/external-link";
import { games } from "#lib/games.svelte.js";
import { i18n } from "#lib/i18n.svelte.js";
import { randomPicks } from "#lib/random.svelte.js";
import { PICK_COUNTS, buildPool, type TypeChoice } from "#lib/random-pick.js";
import { heroFallback, heroImage } from "#lib/image.js";
import { imgFallback } from "#lib/img-fallback.js";
import { steamWebUrl } from "#lib/steam-link.js";
import { cn, formatNumber, parseReviewPercent, reviewLabel } from "#lib/utils.js";
import { reviewTone } from "#lib/games/columns.js";
import QueryState from "#lib/common/QueryState.svelte";
import PageHeader from "#lib/common/PageHeader.svelte";
import Seo from "#lib/common/Seo.svelte";
import Badge from "#lib/ui/Badge.svelte";
import Button from "#lib/ui/Button.svelte";
const t = i18n.t;
const TYPES: { value: TypeChoice; label: string }[] = [
{ value: "any", label: "common.all" },
{ value: "online", label: "charts.kpi.online" },
{ value: "offline", label: "charts.kpi.offline" },
];
const pool = $derived(games.data ? buildPool(games.data, randomPicks.options) : []);
const picks = $derived(games.data ? randomPicks.resolve(games.data) : []);
// The first roll, as soon as the catalogue is here. untrack: a revalidation
// (a new games.data), coming Back to this page or switching the language
// must never roll again - only the reader does that.
$effect(() => {
const data = games.data;
if (data) untrack(() => randomPicks.rollOnce(data));
});
// Read out after every change the reader makes. The first roll is not: it
// arrives together with the page.
let announcement = $state("");
function announce() {
if (!games.data) return;
const shown = randomPicks.resolve(games.data);
const names = shown.map((p) => p.record.name).join(", ");
announcement = shown.length ? t("random.announce", { count: shown.length, names }) : t("random.noMatch");
}
function roll() {
if (!games.data) return;
randomPicks.roll(games.data);
announce();
}
function changeCount(n: number) {
randomPicks.setCount(n, games.data);
announce();
}
function changeType(type: TypeChoice) {
randomPicks.setType(type, games.data);
announce();
}
function changeDead(on: boolean) {
randomPicks.setIncludeDead(on, games.data);
announce();
}
function choice(selected: boolean) {
return cn(
"rounded-md border px-3 py-1.5 text-sm transition-colors",
selected ? "border-primary/50 bg-primary/10" : "hover:border-border-strong hover:bg-accent",
);
}
</script>
<Seo title={t("nav.random")} description={t("random.seoDescription")} />
<PageHeader title={t("nav.random")} subtitle={t("random.subtitle")}>
{#snippet actions()}
<!-- Outside the keyed list below, so focus stays on it from roll to roll. -->
<Button onclick={roll} disabled={!games.data || pool.length === 0}>
<Dices class="size-4" />
{picks.length ? t("random.rollAgain") : t("random.roll")}
</Button>
{/snippet}
</PageHeader>
<!-- Prerendered with the store's defaults (five, any type, no dead games), so
hydration finds the same pressed buttons. A choice made before the
catalogue arrives is kept for the first roll. -->
<div class="mb-5 flex flex-wrap items-end gap-x-6 gap-y-3">
<div class="min-w-0">
<p id="random-count" class="mb-1.5 text-xs font-medium text-muted-foreground">{t("random.countLabel")}</p>
<div role="group" aria-labelledby="random-count" class="flex flex-wrap gap-1">
{#each PICK_COUNTS as n (n)}
<button
type="button"
onclick={() => changeCount(n)}
aria-pressed={randomPicks.count === n}
class={cn(choice(randomPicks.count === n), "w-10 px-0 tnum")}
>
{n}
</button>
{/each}
</div>
</div>
<div class="min-w-0">
<p id="random-type" class="mb-1.5 text-xs font-medium text-muted-foreground">{t("detail.labelType")}</p>
<div role="group" aria-labelledby="random-type" class="flex flex-wrap gap-1">
{#each TYPES as option (option.value)}
<button
type="button"
onclick={() => changeType(option.value)}
aria-pressed={randomPicks.type === option.value}
class={choice(randomPicks.type === option.value)}
>
{t(option.label)}
</button>
{/each}
</div>
</div>
<label class="flex cursor-pointer items-center gap-2 py-2 text-sm" title={t("games.deadTitle")}>
<input
type="checkbox"
checked={randomPicks.includeDead}
onchange={(e) => changeDead(e.currentTarget.checked)}
class="size-4 shrink-0 accent-[hsl(var(--primary))]"
/>
{t("random.includeDead")}
</label>
</div>
<p class="sr-only" role="status" aria-live="polite" aria-atomic="true">{announcement}</p>
<QueryState loading={games.pending} error={games.error} retry={() => games.refetch()}>
{#if pool.length === 0}
<div class="rounded-lg border bg-card py-16 text-center">
<p class="text-sm text-muted-foreground">{t("random.noMatch")}</p>
</div>
{:else}
<p class="mb-3 text-xs text-muted-foreground tnum">
{t("random.pool", { count: pool.length, total: formatNumber(pool.length) })}
</p>
<ul class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{#each picks as { appid, record: r } (appid)}
{@const pct = parseReviewPercent(r.reviews)}
<li class="flex min-w-0 flex-col overflow-hidden rounded-lg border bg-card transition-colors hover:border-border-strong">
<a href="/games/{appid}" class="group block">
<!-- The 460 px hero, not the 230 px thumbnail: a card is 235-480 px
wide, and the thumbnail went soft scaled up that far. -->
{#if r.header_image}
<img
src={heroImage(r.header_image)}
{@attach imgFallback(heroFallback(r.header_image))}
alt=""
loading="lazy"
decoding="async"
referrerpolicy="no-referrer"
width="460"
height="215"
class="aspect-[460/215] w-full bg-muted object-cover"
/>
{:else}
<div class="aspect-[460/215] w-full bg-muted"></div>
{/if}
<h2 class="flex items-center gap-1.5 px-4 pt-3 text-base font-semibold group-hover:text-primary">
{#if r.is_dead}<span title={t("games.deadTitle")}>💀</span>{/if}
<span class="min-w-0 truncate">{r.name || "—"}</span>
</h2>
</a>
<div class="flex flex-wrap items-center gap-1 px-4 pt-2">
{#if r.type_game}
<Badge variant={r.type_game === "online" ? "success" : "secondary"}>
{t(r.type_game === "online" ? "common.online" : "common.offline")}
</Badge>
{/if}
{#if r.genre}<Badge variant="outline">{r.genre}</Badge>{/if}
{#if r.anti_cheat && r.anti_cheat !== "-"}
<Badge variant={r.is_kernel_ac ? "destructive" : "warning"} class="block max-w-full truncate">
{r.anti_cheat}
</Badge>
{/if}
</div>
<dl class="grid grid-cols-2 gap-2 px-4 py-3 text-sm">
<div class="min-w-0">
<dt class="text-xs text-muted-foreground">{t("detail.labelPlayers")}</dt>
<dd class="font-mono tnum">{formatNumber(r.current_players)}</dd>
</div>
<div class="min-w-0">
<dt class="text-xs text-muted-foreground">{t("detail.labelReviews")}</dt>
<dd class="truncate">
{#if pct !== null}
<span class="font-mono tnum {reviewTone(pct)}">{pct}%</span>
<span class="text-xs text-muted-foreground">{reviewLabel(r.reviews) ?? ""}</span>
{:else}
—
{/if}
</dd>
</div>
</dl>
<div class="mt-auto border-t px-4 py-2.5">
<!-- A plain external link. In the apps the capture-phase interceptor
(lib/external-link-interceptor.ts) hands it to the shell plugin,
exactly like the game page's Web button. -->
<a
href={steamWebUrl(appid)}
target="_blank"
rel="noreferrer"
class="inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
>
<ExternalLink class="size-3.5" />
<!-- The separator is an expression: Svelte trims a leading space
inside an element, and the name ran into the label. -->
{t("random.openOnSteam")}<span class="sr-only">{` - ${r.name}`}</span>
</a>
</div>
</li>
{/each}
</ul>
{/if}
</QueryState>
+2
View File
@@ -33,6 +33,8 @@ export const prerender = true;
const HINTS: Record<string, { freq: string; priority: string }> = {
"/": { freq: "daily", priority: "1.0" },
"/games": { freq: "daily", priority: "0.9" },
// Mostly controls until the catalogue has loaded; a different roll every visit.
"/random": { freq: "monthly", priority: "0.4" },
"/top-online": { freq: "daily", priority: "0.8" },
"/top-offline": { freq: "daily", priority: "0.8" },
"/stats": { freq: "weekly", priority: "0.8" },