feat(web): random games page

/random rolls one to five games from the catalogue (five to start with):
any type, online or offline, dead games only when asked, never one marked
unsafe. Roll again avoids the games on screen while enough others remain;
a smaller count keeps the first picks, a larger one adds to them.

- lib/random-pick.ts: crypto.getRandomValues with rejection sampling and a
  sparse Fisher-Yates, never Math.random (SonarCloud S2245), plus the pool
  rules, read off appidIndex so each game appears once.
- lib/random.svelte.ts: the picks as appids, module-level and memory only,
  so Back from a game keeps them and no f2p:* key is needed (a new key
  means a privacy-policy edit, which reopens the consent gate). Only the
  reader rolls; a revalidation only drops a pick that left the catalogue
  or stopped qualifying.
- The page, an entry in the sidebar, drawer and palette (nav.ts) and a
  dashboard button. Top-level on purpose: the header search, isActive and
  the PWA's globIgnores all treat /games/* specially. The empty state joins
  verify-dist's BAKED_EMPTY_STATES; the sitemap ranks the page low.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-11-03 19:27:31 +07:00
1 parent 751898ed08
commit 69c8964842
12 files changed
+866 -2

No files matched your search

+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;
+15
View File
@@ -64,6 +64,7 @@
"nav": {
"dashboard": "Dashboard",
"games": "Games",
"random": "Random games",
"topOnline": "Top Online",
"topOffline": "Top Offline",
"charts": "Charts",
@@ -197,6 +198,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.",
+15
View File
@@ -64,6 +64,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 +198,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.",
+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" },