Site: downloads and 1-5 star ratings on /mods

- The list shows each project's rating (stars, mean and count) and its
  downloads ("12.3k downloads"), ordered by downloads by default; an Order
  menu also sorts by rating or name (?sort= too).
- A project's page shows the same, then a rating control: five stars when
  signed in (the account's own rating lit), "Sign in with GitHub to rate"
  (coming back to the page) when not, a note for its owners.
- Ratings come from the registry service's GET /api/mods/ratings; a rating
  is POSTed with the session's CSRF token. Until the service answers, the
  pages show downloads only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-26 14:29:02 +01:00
parent ec7a2e22a7
commit f49d5d91e6
6 changed files with 229 additions and 18 deletions
+4
View File
@@ -515,6 +515,10 @@ published. Players find them at [playhorizon.dev/mods](https://playhorizon.dev/m
5. A reviewer merges it: within minutes the file is a release of horizon-mods, and the project is on the site and in
the launcher.
Once it is published, its page and its card in the launcher show its downloads (GitHub's counts of its files,
refreshed every hour) and its rating: players signed in with GitHub on its page give it 1 to 5 stars, one rating per
account, which they can change. Its owners can't rate it, and nobody sees who rated.
An update is the same form with a new version; only the project's `owners` can publish one, signed with its key if it
has one. A published file never changes. Without the form, open the pull request by hand (the repository's README
says how). The formats: [api/mod-index.md](api/mod-index.md).
+3 -2
View File
@@ -18,7 +18,7 @@ import { CPUS, GPUS, singleThread } from "./src/hardware.js";
import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js";
import { contributorsFrom, contributorsHtml } from "./src/contributors.js";
import { areaFilterHtml, boardFilterHtml, boardFrom, boardHtml, creditFrom, creditHtml, helpWantedHtml, journalFrom, journalHtml, journalJson, overviewHtml, roadmapHtml, slimIssue, suggestItemsHtml } from "./src/hub.js";
import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex, submitHtml } from "./src/mods.js";
import { INDEX_URL, KINDS, SORTS, SUBMIT, listHtml, projectHtml, readIndex, sorted, submitHtml } from "./src/mods.js";
const site = dirname(fileURLToPath(import.meta.url));
const dist = join(site, "dist");
@@ -484,10 +484,11 @@ const modsList = ` <p class="kicker"><span>Mods</span>Made for Horizon, r
<button type="button" class="button secondary small" data-kind-filter="all" aria-pressed="true">All</button>
${KINDS.map(([k, label]) => ` <button type="button" class="button secondary small" data-kind-filter="${k}" aria-pressed="false">${label}</button>`).join("\n")}
</div>
<select class="mod-search mod-sort" id="mod-sort" aria-label="Order">${SORTS.map(([k, label]) => `<option value="${k}">${label}</option>`).join("")}</select>
</div>
<p class="meta release-count" data-mod-count>${modProjects.length} of ${modProjects.length}</p>
<div class="mod-list" id="mod-list" aria-live="polite">
${listHtml(modProjects)}
${listHtml(sorted(modProjects, "downloads"))}
</div>`;
const modPages = [
{ file: "mods.html", path: "/mods", title: "Mods", description: "Mods, modpacks and resource packs made for Horizon, reviewed, each with what it may do and how to install it.", main: modsList },
+89 -9
View File
@@ -1,32 +1,47 @@
// /mods and /mods/<id>: the registry's list (kind filter, search) and a project's page. The pages are baked from
// the index at build time; this fetches the published index again so a project merged since shows at once.
import { INDEX_URL, KINDS, listHtml, matches, projectHtml, readIndex } from "./mods.js";
// /mods and /mods/<id>: the registry's list (kind filter, search, order) and a project's page. The pages are baked
// from the index at build time; this fetches the published index again so a project merged since shows at once,
// the ratings (crates/horizon-mod-registry), and on a project's page the signed-in player's own rating to change.
import { API, INDEX_URL, KINDS, RATINGS, SORTS, listHtml, matches, projectHtml, rateHtml, ratingOf, readIndex, sorted, starsHtml } from "./mods.js";
import { cached, setUpMenu, setUpTheme } from "./chrome.js";
import { escape } from "./markdown.js";
const root = document.getElementById("mods");
const baked = readIndex(JSON.parse(document.getElementById("mods-index").textContent || "null")) || [];
let projects = baked;
// Every project's ratings, once the service answered.
let ratings = null;
let kind = "all";
let text = "";
let order = "downloads";
// On a project's page: the signed-in account ({login, csrf}) or null, and its own rating of the project.
let me;
let mine = null;
const id = (location.pathname.match(/^\/mods\/([a-z0-9_]+)\/?$/) || [])[1];
function showList() {
const list = root.querySelector("#mod-list");
if (!list) return;
const shown = projects.filter((p) => matches(p, kind, text));
list.innerHTML = listHtml(shown);
const shown = sorted(projects.filter((p) => matches(p, kind, text)), order, ratings);
list.innerHTML = listHtml(shown, ratings);
root.querySelector("[data-mod-count]").textContent = `${shown.length} of ${projects.length}`;
root.querySelectorAll("[data-kind-filter]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.kindFilter === kind)));
}
function showRate(p, message = "") {
const rate = root.querySelector("#mod-rate");
if (!rate || me === undefined) return;
rate.innerHTML = rateHtml(p, me, mine) + (message ? `<p class="mod-error">${escape(message)}</p>` : "");
}
function showProject() {
const p = projects.find((x) => x.id === id);
const page = root.querySelector(".mod-page, .mod-missing");
if (!page) return;
if (p) {
page.outerHTML = projectHtml(p);
page.outerHTML = projectHtml(p, ratings ? ratingOf(ratings, p.id) : undefined);
document.title = `${p.name} · Horizon`;
showRate(p);
} else {
page.outerHTML = `<div class="mod-missing"><h1 class="display page-title">Not in the registry</h1><p class="lede">No project is called ${id} here. It may not be published yet, or it was taken down.</p><a class="button secondary" href="/mods">Every mod</a></div>`;
}
@@ -37,7 +52,56 @@ function render() {
else showList();
}
if (!id) {
// The signed-in account and its own rating, for the page's rating control.
async function signIn() {
try {
const r = await fetch(`${API}/me`, { credentials: "same-origin" });
me = r.ok ? await r.json() : null;
if (me) {
const own = await fetch(`${API}/${id}/rating`, { credentials: "same-origin" });
mine = own.ok ? (await own.json()).stars : null;
}
} catch {
me = null;
}
const p = projects.find((x) => x.id === id);
if (p) showRate(p);
}
async function rate(stars) {
const p = projects.find((x) => x.id === id);
if (!p || !me) return;
root.querySelectorAll(".mod-star").forEach((b) => (b.disabled = true));
let message = "";
try {
const r = await fetch(`${API}/${id}/rating`, {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": me.csrf },
body: JSON.stringify({ stars }),
});
const json = await r.json().catch(() => ({}));
if (r.ok) {
mine = json.stars;
ratings = { ...ratings, [id]: { average: json.average, count: json.count } };
const line = root.querySelector("[data-mod-rating]");
if (line) line.innerHTML = `${starsHtml(ratingOf(ratings, id))} · `;
} else {
message = json.error || `The service answered ${r.status}.`;
}
} catch {
message = "The service didn't answer. Try again in a minute.";
}
showRate(p, message);
}
if (id) {
root.addEventListener("click", (e) => {
const star = e.target.closest?.("[data-stars]");
if (star) rate(Number(star.dataset.stars));
});
signIn();
} else {
root.querySelectorAll("[data-kind-filter]").forEach((b) =>
b.addEventListener("click", () => {
kind = b.dataset.kindFilter;
@@ -48,8 +112,15 @@ if (!id) {
text = e.target.value;
showList();
});
const wanted = new URLSearchParams(location.search).get("kind");
if (KINDS.some(([k]) => k === wanted)) kind = wanted;
root.querySelector("#mod-sort")?.addEventListener("change", (e) => {
order = e.target.value;
showList();
});
const query = new URLSearchParams(location.search);
if (KINDS.some(([k]) => k === query.get("kind"))) kind = query.get("kind");
if (SORTS.some(([k]) => k === query.get("sort"))) order = query.get("sort");
const select = root.querySelector("#mod-sort");
if (select) select.value = order;
}
setUpTheme();
@@ -64,3 +135,12 @@ cached("horizon:mod-index", () => fetch(INDEX_URL).then((r) => (r.ok ? r.json()
}
})
.catch(() => {});
fetch(RATINGS)
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${r.status}`))))
.then((json) => {
if (json && typeof json.projects === "object") {
ratings = json.projects;
render();
}
})
.catch(() => {});
+66 -6
View File
@@ -8,6 +8,8 @@ const REGISTRY = "https://github.com/ludovic111/horizon-mods";
export const SUBMIT = "/mods/submit";
// The submission form's service (crates/horizon-mod-registry), behind the site's own address.
export const API = "/api/mods";
// Every project's ratings: {projects: {<id>: {average, count}}}.
export const RATINGS = `${API}/ratings`;
export const SCHEMA = 1;
// The kinds the site shows, in the filter's order. Kinds a newer index adds are left out until the site knows them.
@@ -43,21 +45,66 @@ const initial = (p) => escape((p.name || p.id).trim().charAt(0).toUpperCase());
const icon = (p) =>
https(p.icon) ? `<img class="mod-icon" src="${escape(p.icon)}" alt="" width="48" height="48" loading="lazy">` : `<span class="mod-icon" aria-hidden="true">${initial(p)}</span>`;
// A count as the launcher writes it: 999, 12.3k, 4.1M.
export function count(n) {
if (n < 1000) return String(n);
if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
return `${(n / 1e6).toFixed(1)}M`;
}
const downloads = (p) => {
const n = Number.isSafeInteger(p.downloads) && p.downloads > 0 ? p.downloads : 0;
return `${count(n)} download${n === 1 ? "" : "s"}`;
};
// A project's ratings from the service's answer, or null when it has none.
export function ratingOf(ratings, id) {
const r = ratings?.[id];
return r && Number.isFinite(r.average) && Number.isSafeInteger(r.count) && r.count > 0 ? r : null;
}
// Five stars, the mean's nearest whole number of them filled, and the mean and count beside.
export function starsHtml(r) {
if (!r) return `<span class="mod-stars-none">No ratings yet</span>`;
const on = Math.min(5, Math.max(0, Math.round(r.average)));
const mean = r.average.toFixed(1);
return `<span class="mod-rating-line" title="${mean} out of 5 from ${r.count} rating${r.count === 1 ? "" : "s"}"><span class="mod-stars" aria-hidden="true"><span class="on">${"★".repeat(on)}</span>${"★".repeat(5 - on)}</span><span class="sr-only">Rated ${mean} out of 5</span> ${mean} (${count(r.count)})</span>`;
}
// The list's orders: the most downloaded first (the default), the best rated, or by name.
export const SORTS = [
["downloads", "Most downloaded"],
["rating", "Best rated"],
["name", "Name"],
];
export function sorted(projects, by, ratings) {
const avg = (p) => ratingOf(ratings, p.id)?.average || 0;
const votes = (p) => ratingOf(ratings, p.id)?.count || 0;
const name = (a, b) => a.name.localeCompare(b.name);
const order = {
downloads: (a, b) => (b.downloads || 0) - (a.downloads || 0) || name(a, b),
rating: (a, b) => avg(b) - avg(a) || votes(b) - votes(a) || name(a, b),
name,
}[by] || (() => 0);
return [...projects].sort(order);
}
export function matches(p, kind, text) {
if (kind !== "all" && p.kind !== kind) return false;
const hay = `${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase();
return text.toLowerCase().split(/\s+/).filter(Boolean).every((w) => hay.includes(w));
}
// The list: a row per project, newest version and kind on the right.
export function listHtml(projects) {
// The list: a row per project; its kind, ratings (once `ratings` is known), downloads and newest version on the right.
export function listHtml(projects, ratings = null) {
if (!projects.length) return `<p class="lede mod-empty">Nothing here yet. <a href="${SUBMIT}">Submit yours</a>.</p>`;
return projects
.map(
(p) => `<a class="mod-row" href="/mods/${p.id}" data-kind="${escape(p.kind)}" data-search="${escape(`${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase())}">
${icon(p)}
<span class="mod-text"><span class="mod-name">${escape(p.name)}</span><span class="mod-summary">${escape(p.summary || "")}</span></span>
<span class="mod-side"><span class="badge">${escape(KIND_NAMES[p.kind] || p.kind)}</span><span class="mod-version">${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))}</span></span>
<span class="mod-side"><span class="badge">${escape(KIND_NAMES[p.kind] || p.kind)}</span><span class="mod-stats">${ratings ? `${starsHtml(ratingOf(ratings, p.id))} · ` : ""}${downloads(p)}</span><span class="mod-version">${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))}</span></span>
</a>`,
)
.join("\n");
@@ -92,8 +139,19 @@ export function ownersHtml(p) {
return `<p class="meta mod-owners">Published by ${links}</p>`;
}
// One project's page.
export function projectHtml(p) {
// The rating control under a project's ratings: five stars to press when signed in (`mine`, the account's own
// rating, pressed), a sign-in link when not, a note for the project's owners.
export function rateHtml(p, me, mine) {
if (!me) return `<a class="button secondary small" href="${API}/auth/login?back=/mods/${escape(p.id)}">Sign in with GitHub to rate</a>`;
if ((p.owners || []).some((o) => o.toLowerCase() === String(me.login).toLowerCase())) return `<p class="meta">You publish it: players rate it.</p>`;
const stars = [1, 2, 3, 4, 5]
.map((n) => `<button type="button" class="mod-star${n <= (mine || 0) ? " lit" : ""}" data-stars="${n}" aria-pressed="${mine === n}" aria-label="${n} star${n === 1 ? "" : "s"}">★</button>`)
.join("");
return `<span class="mod-rate-label">${mine ? "Your rating" : "Rate it"}</span><span class="mod-rate-stars" role="group" aria-label="Your rating">${stars}</span>`;
}
// One project's page; `rating` is its ratings (null: none yet), left out when they aren't known.
export function projectHtml(p, rating) {
const v = p.versions[0];
const caps = v.capabilities || [];
const capsHtml = caps.length
@@ -108,7 +166,9 @@ export function projectHtml(p) {
return `<article class="mod-page" data-id="${escape(p.id)}">
<header class="mod-head">${icon(p)}<div><p class="kicker"><span>${escape(KIND_NAMES[p.kind] || p.kind)}</span>${escape((p.authors || []).join(", "))}</p>${ownersHtml(p)}
<h1 class="display page-title">${escape(p.name)}</h1><p class="lede">${escape(p.summary || "")}</p>
<p class="mod-badges">${trust(p)} <span class="badge">${escape(p.license)}</span> <span class="badge">${escape(v.version)}</span>${v.side ? ` <span class="badge">${escape(v.side)}</span>` : ""}</p></div></header>
<p class="mod-badges">${trust(p)} <span class="badge">${escape(p.license)}</span> <span class="badge">${escape(v.version)}</span>${v.side ? ` <span class="badge">${escape(v.side)}</span>` : ""}</p>
<p class="mod-stats mod-page-stats"><span data-mod-rating>${rating === undefined ? "" : `${starsHtml(rating)} · `}</span>${downloads(p)}</p>
<div class="mod-rate" id="mod-rate" aria-live="polite"></div></div></header>
${p.description ? `<div class="prose">${markdown(p.description)}</div>` : ""}
${p.kind === "mod" ? `<h2 class="heading">What it may do</h2>${capsHtml}<p class="meta">Mods run in a sandbox with no file, network or clock access. The game refuses a mod whose code uses more than this list.</p>` : ""}
${requires}
+48 -1
View File
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { CAPABILITIES, entryFrom, listHtml, matches, projectHtml, readIndex, submitHtml } from "./mods.js";
import { CAPABILITIES, count, entryFrom, listHtml, matches, projectHtml, rateHtml, ratingOf, readIndex, sorted, starsHtml, submitHtml } from "./mods.js";
const project = (over = {}) => ({
id: "coords_hud", kind: "mod", name: "Coordinates HUD", summary: "Where you are.", authors: ["Horizon"],
@@ -61,3 +61,50 @@ test("a project's page links its owners' GitHub profiles, and only valid logins"
for (const bad of ["bad login", "github.com/-x", "a--b", "<script>"]) assert.ok(!html.includes(bad), bad);
assert.ok(!projectHtml(project()).includes("Published by"));
});
test("downloads read short, as in the launcher, and a missing count is 0", () => {
assert.equal(count(999), "999");
assert.equal(count(12_345), "12.3k");
assert.equal(count(51_404_735), "51.4M");
assert.ok(listHtml([project({ downloads: 12_345 })]).includes("12.3k downloads"));
assert.ok(listHtml([project({ downloads: 1 })]).includes("1 download<"));
assert.ok(projectHtml(project({ downloads: "9999<script>" })).includes("0 downloads"));
});
test("ratings show their mean and count, and nothing a broken answer holds", () => {
const ratings = { coords_hud: { average: 4.26, count: 12 }, zoom: { average: "<b>", count: 3 } };
assert.deepEqual(ratingOf(ratings, "coords_hud"), { average: 4.26, count: 12 });
assert.equal(ratingOf(ratings, "zoom"), null);
assert.equal(ratingOf(ratings, "__proto__"), null);
const stars = starsHtml(ratingOf(ratings, "coords_hud"));
assert.ok(stars.includes(`<span class="on">★★★★</span>★`), stars);
assert.ok(stars.includes("4.3 (12)"));
assert.ok(starsHtml(null).includes("No ratings yet"));
assert.ok(listHtml([project()], ratings).includes("4.3 (12)"));
// Before the service answers (or without it), no stars at all.
assert.ok(!listHtml([project()]).includes("No ratings yet"));
assert.ok(!projectHtml(project()).includes("No ratings yet"));
assert.ok(projectHtml(project(), null).includes("No ratings yet"));
});
test("the list orders by downloads, by rating or by name", () => {
const a = project({ id: "a", name: "Alpha", downloads: 5 });
const b = project({ id: "b", name: "Beta", downloads: 50 });
const c = project({ id: "c", name: "Gamma" });
const ratings = { a: { average: 4.5, count: 2 }, c: { average: 4.5, count: 9 } };
const ids = (by) => sorted([a, b, c], by, ratings).map((p) => p.id);
assert.deepEqual(ids("downloads"), ["b", "a", "c"]);
assert.deepEqual(ids("rating"), ["c", "a", "b"]);
assert.deepEqual(ids("name"), ["a", "b", "c"]);
});
test("rating: a sign-in link signed out, stars signed in, none for the project's owners", () => {
const p = project({ owners: ["Alice"] });
assert.ok(rateHtml(p, null, null).includes('href="/api/mods/auth/login?back=/mods/coords_hud">Sign in with GitHub to rate'));
assert.ok(rateHtml(p, { login: "alice" }, null).includes("You publish it"));
const mine = rateHtml(p, { login: "bob" }, 3);
assert.equal((mine.match(/data-stars=/g) || []).length, 5);
assert.equal((mine.match(/mod-star lit/g) || []).length, 3);
assert.ok(mine.includes('data-stars="3" aria-pressed="true"'));
assert.ok(rateHtml(p, { login: "bob" }, null).includes("Rate it"));
});
+19
View File
@@ -881,6 +881,25 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou
.mod-side .badge { margin-right: 0; }
.mod-version { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); }
.mod-empty a { color: var(--accent); }
.mod-sort { width: auto; }
.mod-stats { font-size: var(--text-ui); color: var(--muted); white-space: nowrap; }
.mod-stars { color: color-mix(in srgb, var(--muted) 45%, transparent); letter-spacing: 0.08em; }
.mod-stars .on { color: var(--warn); }
.mod-page-stats { margin: 12px 0 0; }
.mod-rate { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 12px; }
.mod-rate:empty { display: none; }
.mod-rate .meta, .mod-rate .mod-error { margin: 0; flex-basis: 100%; }
.mod-rate-label { font-size: var(--text-ui); color: var(--muted); }
.mod-rate-stars { display: inline-flex; }
.mod-star {
padding: 0 3px; border: 0; background: none; cursor: pointer; font-size: 26px; line-height: 1;
color: color-mix(in srgb, var(--muted) 45%, transparent);
transition: color var(--quick) var(--ease-quick);
}
/* The rating's stars are lit; hovering lights a star and those before it. */
.mod-star.lit, .mod-rate-stars:hover .mod-star { color: var(--warn); }
.mod-rate-stars .mod-star:hover ~ .mod-star { color: color-mix(in srgb, var(--muted) 45%, transparent); }
.mod-star:disabled { cursor: progress; }
.badge-signed { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); }
.badge-unsigned { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); }
.mod-page { display: grid; gap: 16px; max-width: calc(var(--measure) + 240px); }