From a7fd45f0a89f353d9cc25a6e6e648894433d2dc9 Mon Sep 17 00:00:00 2001 From: Yevhen Boichuk Date: Thu, 22 Oct 2026 12:06:12 +0300 Subject: [PATCH] feat: bring back ratings, for signed-in users, at almost no Worker cost - Only signed-in users rate (not their own items); everyone sees the average. PUT /apps/:slug/rating answers with the fresh average, the same stars again write nothing, DELETE removes a rating, a ban drops the user's ratings. - Showing costs no Worker request: averages are in listing.json on Pages (aggregated once per hourly export), and the user's own ratings come with the /auth/me call the site already makes. - Migration 0006: index ratings (user_id) for that lookup and the ban. - Site: stars in the details view with your rating pre-selected, "Remove rating", card badge, "Top rated" sort; the details view loads the static listing when opened from Authors or a direct link. - smoke.sh: 124 checks. Co-Authored-By: Claude Opus 5.5 --- api/README.md | 6 +- api/migrations/0006_ratings_by_user.sql | 4 + api/scripts/smoke.sh | 25 ++++- api/src/apps.ts | 43 ++++++++ api/src/auth.ts | 14 ++- api/src/catalog.ts | 11 +- api/src/moderation.ts | 3 +- site/community.js | 139 +++++++++++++++++++++++- site/index.html | 1 + site/script.js | 23 +++- site/styles.css | 47 ++++++++ 11 files changed, 304 insertions(+), 12 deletions(-) create mode 100644 api/migrations/0006_ratings_by_user.sql diff --git a/api/README.md b/api/README.md index 477f0a7..e2669b0 100644 --- a/api/README.md +++ b/api/README.md @@ -22,7 +22,7 @@ flowchart LR subgraph CF["lilka-catalog-api · Cloudflare Worker (api/)"] API["API routes
/auth · /apps · /mod · /scan"] CAT["/catalog/…
/catalog/export.json"] - D1[("D1
users · sessions · apps
versions · reports")] + D1[("D1
users · sessions · apps
versions · ratings · reports")] R2[("R2
<id>-<name>/v/<version>/<file>")] end @@ -171,7 +171,7 @@ All bodies are JSON unless noted. Authenticated calls send | GET | `/auth/login?return=` | anyone | Redirects to GitHub. `return` must be on `ALLOWED_ORIGINS`; the OAuth state is signed, nothing is stored | | GET | `/auth/callback` | GitHub | Redirects to `return#lilka_token=` | | POST | `/auth/logout` | user | Ends the session | -| GET | `/auth/me` | user | Current user | +| GET | `/auth/me` | user | Current user and `ratings` (slug → stars) they gave, so the site shows them without a request per app | | GET | `/catalog/{apps,wallpapers,mods}/index_.json` | mirror job | Ids of published items, 12 per page | | GET | `/catalog///index.json`, `index_short.json` | mirror job | Manifests in build.py's format | | GET | `/catalog///static/`, `package.zip` | mirror job | Files | @@ -183,6 +183,8 @@ All bodies are JSON unless noted. Authenticated calls send | POST | `/apps` | user | Create draft; `kind`: `app`, `wallpaper` or `mod` | | PATCH | `/apps/:slug` | owner, mod | Edit metadata, `status: hidden \| published`; moderators also `author`, `owner` (login) | | POST | `/apps/:slug/versions` | owner, mod | Multipart: `version`, `keira_version`, `entry_type` (`lua`, `js`, `binary`, `archive`), `changelog`, files `entry`, `files[]`, `icon`, `screenshots[]`. Mods: no entry, model files as `files[]` | +| PUT | `/apps/:slug/rating` | user (not owner) | `{ "stars": 1..5 }` → `{ my_rating, average, count }`; sending the same stars again writes nothing | +| DELETE | `/apps/:slug/rating` | user | Removes your rating | | POST | `/apps/:slug/reports` | user | `{ "reason": "..." }` | | GET | `/users/:login/apps[?versions]` | user | Apps of a user (all of them, with versions, for the user themself or a moderator) | | GET | `/files/:slug/:version/:name` | owner, mod | File by version id, for "My apps" and moderation previews | diff --git a/api/migrations/0006_ratings_by_user.sql b/api/migrations/0006_ratings_by_user.sql new file mode 100644 index 0000000..7d6c355 --- /dev/null +++ b/api/migrations/0006_ratings_by_user.sql @@ -0,0 +1,4 @@ +-- /auth/me returns the signed-in user's own ratings with the session check, +-- so the site needs no request per app to show them; this keeps that lookup +-- to the user's own rows instead of a scan of every rating. +CREATE INDEX ratings_user ON ratings (user_id); diff --git a/api/scripts/smoke.sh b/api/scripts/smoke.sh index c736741..100bddf 100755 --- a/api/scripts/smoke.sh +++ b/api/scripts/smoke.sh @@ -94,6 +94,19 @@ call 404 "approved file is not served to strangers" "${fan[@]}" "$API/files/smok call 200 "owner gets the approved file" "${user[@]}" "$API/files/smoke-hello/$version_id/hello.lua" call 200 "HEAD for the owner" -I "${user[@]}" "$API/files/smoke-hello/$version_id/hello.lua" +call 401 "rating needs a session" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":5}' +call 403 "owner cannot rate own app" "${user[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":5}' +call 400 "stars must be 1..5" "${fan[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":6}' +call 200 "rate" "${fan[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":2}' +call 200 "change the rating" "${fan[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":4}' +check "rating answer has the fresh average" '{"my_rating":4,"average":4,"count":1}' "$(jq -c . "$work/body")" +call 200 "moderator rates too" "${mod[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":5}' +check "average of two" "4.5 2" "$(jq -r '"\(.average) \(.count)"' "$work/body")" +call 200 "own ratings come with the session check" "${fan[@]}" "$API/auth/me" +check "/auth/me carries the user's ratings" 4 "$(jq -r '.ratings["smoke-hello"]' "$work/body")" +call 200 "remove a rating" "${mod[@]}" -X DELETE "$API/apps/smoke-hello/rating" +check "removed rating is gone" null "$(curl -sS "${mod[@]}" "$API/auth/me" | jq -r '.ratings["smoke-hello"]')" +call 404 "no rating for a draft" "${fan[@]}" "${json[@]}" -X PUT "$API/apps/smoke-mod-x/rating" -d '{"stars":3}' call 201 "report" "${fan[@]}" "${json[@]}" -X POST "$API/apps/smoke-hello/reports" -d '{"reason":"smoke"}' call 200 "open reports" "${mod[@]}" "$API/mod/reports" @@ -113,9 +126,9 @@ jq -e '."@smoke-dev"[0].path == "smoke-hello"' "$work/body" >/dev/null || { echo call 404 "catalog unknown kind" "${mirror[@]}" "$API/catalog/games/index_0.json" call 401 "listing.json needs the mirror secret" "$API/catalog/apps/listing.json" call 200 "listing.json for the site" "${mirror[@]}" "$API/catalog/apps/listing.json" -jq -e '.items[] | select(.path == "smoke-hello") | (.added != null) and (.updated != null) and .author == "@smoke-dev"' \ +jq -e '.items[] | select(.path == "smoke-hello") | (.added != null) and (.updated != null) and .rating.average == 4 and .rating.count == 1 and .author == "@smoke-dev"' \ "$work/body" >/dev/null && li=ok || li="$(jq -c '.items[] | select(.path == "smoke-hello")' "$work/body")" -check "listing has dates and author" ok "$li" +check "listing has dates, rating and author" ok "$li" pub=$(npx wrangler d1 execute lilka-catalog --local --json --command "SELECT published_at FROM apps WHERE slug = 'smoke-hello'" 2>/dev/null | jq -r '.[0].results[0].published_at') check "published_at set on first approval" ok "$([ -n "$pub" ] && [ "$pub" != null ] && echo ok || echo missing)" @@ -245,6 +258,14 @@ sig=${state#*.}; first=${sig:0:1}; [ "$first" = A ] && swap=B || swap=A call 400 "tampered OAuth state refused" "$API/auth/callback?code=x&state=${state%%.*}.$swap${sig:1}" call 400 "made-up OAuth state refused" "$API/auth/callback?code=x&state=eyJyIjoiaHR0cHM6Ly9ldmlsLmV4YW1wbGUvIn0.AAAA" +npx wrangler d1 execute lilka-catalog --local --command " +INSERT INTO users (id, login, role) VALUES (5, 'smoke-troll', 'user'); +INSERT INTO sessions VALUES ('$(sha troll-token)', 5, datetime('now', '+1 day'));" >/dev/null +call 200 "troll rates" -H "Authorization: Bearer troll-token" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":1}' +call 200 "moderator bans the troll" "${mod[@]}" -X POST "$API/mod/users/smoke-troll/ban" +trolls=$(npx wrangler d1 execute lilka-catalog --local --json --command "SELECT COUNT(*) AS n FROM ratings WHERE user_id = 5" 2>/dev/null | jq -r '.[0].results[0].n') +check "a ban removes the user's ratings" 0 "$trolls" + # Last, because it uses up this IP's budget for a minute limited=$(seq 1 330 | xargs -P 30 -I{} curl -s -o /dev/null -w '%{http_code}\n' "$API/" | grep -c '^429$' || true) check "per-IP rate limit kicks in" yes "$([ "$limited" -gt 0 ] && echo yes || echo "no 429 in 330 requests")" diff --git a/api/src/apps.ts b/api/src/apps.ts index 829e6c1..7c18619 100644 --- a/api/src/apps.ts +++ b/api/src/apps.ts @@ -77,6 +77,11 @@ export const APP_SELECT = ` SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar FROM apps a JOIN users u ON u.id = a.owner_id`; +/** The rating block of listing.json and of PUT /apps/:slug/rating. */ +export function ratingSummary(count: number, total: number | null) { + return { average: count && total !== null ? Math.round((total / count) * 10) / 10 : null, count }; +} + export function fileUrl(env: Env, slug: string, versionId: number, name: string): string { return `${env.PUBLIC_URL.replace(/\/$/, '')}/files/${slug}/${versionId}/${encodeURIComponent(name)}`; } @@ -491,6 +496,44 @@ apps.post('/:slug/versions', async (c) => { return c.json(serializeVersion(c.env, app.slug, created!, true), 201); }); +/** + * One rating per user and app, changed by sending it again. + * + * Costs one app lookup, one upsert and one read of this app's ratings, and + * nothing is dispatched: the averages reach listing.json with the next hourly + * mirror run, while the site shows the new vote at once from this response. + */ +apps.put('/:slug/rating', async (c) => { + const user = requireUser(c); + const { stars } = await readJson<{ stars?: unknown }>(c); + if (typeof stars !== 'number' || !Number.isInteger(stars) || stars < 1 || stars > 5) { + fail(400, 'stars must be an integer from 1 to 5'); + } + const app = await c.env.DB.prepare(`SELECT id, owner_id, status FROM apps WHERE slug = ?`) + .bind(c.req.param('slug')) + .first<{ id: number; owner_id: number; status: string }>(); + if (!app || app.status !== 'published') fail(404, 'app not found'); + if (app.owner_id === user.id) fail(403, 'cannot rate your own app'); + const [, summary] = await c.env.DB.batch<{ n: number; total: number | null }>([ + c.env.DB.prepare( + `INSERT INTO ratings (app_id, user_id, stars) VALUES (?, ?, ?) + ON CONFLICT (app_id, user_id) DO UPDATE SET stars = excluded.stars, updated_at = datetime('now') + WHERE ratings.stars != excluded.stars`, + ).bind(app.id, user.id, stars), + c.env.DB.prepare(`SELECT COUNT(*) AS n, SUM(stars) AS total FROM ratings WHERE app_id = ?`).bind(app.id), + ]); + const row = summary.results[0]; + return c.json({ my_rating: stars, ...ratingSummary(row?.n ?? 0, row?.total ?? null) }); +}); + +apps.delete('/:slug/rating', async (c) => { + const user = requireUser(c); + await c.env.DB.prepare(`DELETE FROM ratings WHERE user_id = ? AND app_id = (SELECT id FROM apps WHERE slug = ?)`) + .bind(user.id, c.req.param('slug')) + .run(); + return c.json({ ok: true }); +}); + apps.post('/:slug/reports', async (c) => { const user = requireUser(c); const app = await findApp(c.env, c.req.param('slug')); diff --git a/api/src/auth.ts b/api/src/auth.ts index ad41930..7b728d6 100644 --- a/api/src/auth.ts +++ b/api/src/auth.ts @@ -172,7 +172,19 @@ auth.post('/logout', async (c) => { return c.json({ ok: true }); }); -auth.get('/me', (c) => c.json({ user: requireUser(c) })); +/** + * The session check the site makes once per page load. It also carries the + * user's own ratings, so showing "your rating" costs no request per app. + */ +auth.get('/me', async (c) => { + const user = requireUser(c); + const { results } = await c.env.DB.prepare( + `SELECT a.slug, r.stars FROM ratings r JOIN apps a ON a.id = r.app_id WHERE r.user_id = ? LIMIT 2000`, + ) + .bind(user.id) + .all<{ slug: string; stars: number }>(); + return c.json({ user, ratings: Object.fromEntries(results.map((r) => [r.slug, r.stars])) }); +}); /** * Creates or refreshes the user and opens a session. diff --git a/api/src/catalog.ts b/api/src/catalog.ts index 1ed0e16..71cc3c8 100644 --- a/api/src/catalog.ts +++ b/api/src/catalog.ts @@ -1,6 +1,6 @@ import { Hono, type Context } from 'hono'; import type { AppEnv, Env } from './env'; -import { displayAuthor, kindDir, type AppRow } from './apps'; +import { displayAuthor, kindDir, ratingSummary, type AppRow } from './apps'; import { contentTypeOf, fail, parseJsonArray, sha256Hex } from './util'; import { objectKey } from './versions'; @@ -48,6 +48,8 @@ interface CatalogRow extends AppRow { owner_blog: string | null; owner_location: string | null; owner_company: string | null; + rating_count: number; + rating_sum: number | null; } /** Published apps with their latest approved version, sorted like Python's sorted(os.listdir()). */ @@ -67,10 +69,12 @@ async function published(env: Env, kind?: AppRow['kind'], slug?: string): Promis u.bio AS owner_bio, u.blog AS owner_blog, u.location AS owner_location, u.company AS owner_company, v.id AS v_id, v.keira_version, v.entry_type, v.entry_file, v.files, v.files_meta, v.icon, v.icon_min, v.screenshots, v.changelog, v.changelog_en, v.package, v.security, v.storage_prefix, - v.approved_at + v.approved_at, COALESCE(r.n, 0) AS rating_count, r.total AS rating_sum FROM apps a JOIN users u ON u.id = a.owner_id JOIN versions v ON v.id = a.latest_version_id + -- Every rating once per export (the hourly mirror run), not per vote + LEFT JOIN (SELECT app_id, COUNT(*) AS n, SUM(stars) AS total FROM ratings GROUP BY app_id) r ON r.app_id = a.id WHERE ${where.join(' AND ')} ORDER BY a.slug COLLATE BINARY`, ) @@ -349,7 +353,7 @@ function authorsInfoDoc(rows: CatalogRow[]) { * listing.json: everything the website's list needs for one kind, in one file. * * Not part of the old build.py layout and not read by Keira, so it can carry - * what the catalog list sorts by (dates, author) without touching the + * what the catalog list sorts by (dates, author, rating) without touching the * manifests devices parse. It also turns a list page from 1 index plus 12 * manifests into one request. */ @@ -365,6 +369,7 @@ function listingDoc(rows: CatalogRow[]) { icon: row.icon ?? '', added: row.published_at ?? row.approved_at, updated: row.approved_at, + rating: ratingSummary(row.rating_count, row.rating_sum), }; if (Object.keys(loc).length) { entry.languages = Object.keys(loc); diff --git a/api/src/moderation.ts b/api/src/moderation.ts index 28dad99..0e1a3a4 100644 --- a/api/src/moderation.ts +++ b/api/src/moderation.ts @@ -186,7 +186,7 @@ moderation.get('/apps', async (c) => { }); }); -/** A ban also hides every app of the user and ends their sessions. */ +/** A ban also hides every app of the user, drops their ratings and ends their sessions. */ moderation.post('/users/:login/ban', async (c) => { const user = await c.env.DB.prepare(`SELECT id, role FROM users WHERE login = ? COLLATE NOCASE`) .bind(c.req.param('login')) @@ -200,6 +200,7 @@ moderation.post('/users/:login/ban', async (c) => { c.env.DB.prepare(`UPDATE apps SET status = 'hidden', updated_at = datetime('now') WHERE owner_id = ?`).bind( user.id, ), + c.env.DB.prepare(`DELETE FROM ratings WHERE user_id = ?`).bind(user.id), c.env.DB.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(user.id), ]); c.executionCtx.waitUntil(dispatch(c.env, c.env.CATALOG_REPO, 'api-sync', {})); diff --git a/site/community.js b/site/community.js index 53629d2..cbd468d 100644 --- a/site/community.js +++ b/site/community.js @@ -83,6 +83,20 @@ const COMMUNITY_STRINGS = { 'status-rejected': 'відхилено', 'status-infected': 'знайдено загрозу', 'review-note': 'Коментар модератора', + 'rating-title': 'Оцінка', + 'rating-none': 'Ще ніхто не оцінив.', + // Plural forms by Intl.PluralRules: one / few / many (and other) + 'rating-summary-one': '★ {average} · {count} оцінка', + 'rating-summary-few': '★ {average} · {count} оцінки', + 'rating-summary-many': '★ {average} · {count} оцінок', + 'rating-summary-other': '★ {average} · {count} оцінки', + 'rating-yours': 'Ваша оцінка:', + 'rating-star': '{n} з 5', + 'rating-sign-in': 'Увійдіть, щоб оцінити', + 'rating-thanks': 'Дякуємо! Ваша оцінка ({stars}★) зʼявиться в списку протягом години.', + 'rating-removed': 'Оцінку прибрано. Список оновиться протягом години.', + 'rating-remove': 'Прибрати оцінку', + 'rating-own': 'Свій застосунок оцінити не можна.', 'files-removed': 'Файли цієї версії видалено після відхилення.', 'file-gone': 'Цього файлу вже немає.', 'scan-detail': 'Результат антивірусу', @@ -205,6 +219,17 @@ const COMMUNITY_STRINGS = { 'status-rejected': 'rejected', 'status-infected': 'threat found', 'review-note': 'Moderator note', + 'rating-title': 'Rating', + 'rating-none': 'No ratings yet.', + 'rating-summary-one': '★ {average} · {count} rating', + 'rating-summary-other': '★ {average} · {count} ratings', + 'rating-yours': 'Your rating:', + 'rating-star': '{n} of 5', + 'rating-sign-in': 'Sign in to rate', + 'rating-thanks': 'Thanks! Your rating ({stars}★) shows in the list within an hour.', + 'rating-removed': 'Rating removed. The list updates within an hour.', + 'rating-remove': 'Remove rating', + 'rating-own': 'You cannot rate your own app.', 'files-removed': 'The files of this version were deleted when it was rejected.', 'file-gone': 'This file is no longer available.', 'scan-detail': 'Antivirus result', @@ -291,6 +316,8 @@ class CommunityUI { this.api = this.readApiUrl(); this.token = null; this.user = null; + // slug -> stars of the signed-in user, from /auth/me + this.ratings = {}; this.myApps = []; this.modStatus = 'pending_review'; // Resolves once the session is known, so routing can wait for it @@ -365,8 +392,9 @@ class CommunityUI { if (this.token) { try { - const {user} = await this.request('GET', '/auth/me'); + const {user, ratings} = await this.request('GET', '/auth/me'); this.user = user; + this.ratings = ratings || {}; } catch (e) { // Expired or revoked: behave as signed out. A rate limit or a network // hiccup is not a reason to sign the user out for good @@ -408,6 +436,7 @@ class CommunityUI { } this.saveToken(null); this.user = null; + this.ratings = {}; this.renderAccount(); if (this.views.includes(this.app.currentType)) this.show(this.app.currentType); } @@ -495,6 +524,114 @@ class CommunityUI { } } + // --- Rating in the details view ------------------------------------------ + + /** + * Requests: none to show the average (listing.json on Pages) or your own + * rating (it came with /auth/me), one to rate or remove a rating. Only + * signed-in users can rate; the list picks new averages up on the next + * hourly mirror run, this section shows them at once. + */ + async mountRating(modalBody, type, slug, entry) { + if (!this.enabled || !['apps', 'wallpapers', 'mods'].includes(type)) return; + const section = document.createElement('div'); + section.className = 'modal-section rating-section'; + const header = modalBody.querySelector('.modal-header'); + if (header) header.after(section); else modalBody.prepend(section); + section.innerHTML = ` +

${this.esc(this.t('rating-title'))}

+

+
+ `; + const summary = section.querySelector('.rating-summary'); + const showSummary = (rating) => { + summary.textContent = rating && rating.count ? + this.t(`rating-summary-${new Intl.PluralRules(this.app.currentLang).select(rating.count)}`, + {average: rating.average, count: rating.count}) : + this.t('rating-none'); + }; + // Opened from the Authors page or a direct link: the list of this kind may + // not be loaded yet. It is a static file on Pages, not a Worker request + if (!entry) { + await this.app.loadListing(type); + entry = this.app.listingEntry(type, slug); + } + showSummary(entry && entry.rating); + + await this.ready; + const action = section.querySelector('.rating-action'); + const message = section.querySelector('.rating-message'); + const say = (text) => { + message.textContent = text; + message.hidden = !text; + }; + if (!this.user) { + action.innerHTML = ``; + action.querySelector('button').addEventListener('click', () => this.signIn()); + return; + } + if (this.user.role === 'banned') return; + // The API refuses it too; this spares the request + if (entry && String(entry.author || '').toLowerCase() === `@${this.user.login}`.toLowerCase()) { + say(this.t('rating-own')); + return; + } + + action.innerHTML = `${this.esc(this.t('rating-yours'))} + ${[1, 2, 3, 4, 5].map(n => + ``).join('')} + `; + const stars = [...action.querySelectorAll('.rating-star')]; + const remove = action.querySelector('.rating-remove'); + const show = (n) => stars.forEach(b => { + b.classList.toggle('on', Number(b.dataset.stars) <= n); + b.setAttribute('aria-pressed', String(Number(b.dataset.stars) === (this.ratings[slug] || 0))); + }); + const settle = () => { + show(this.ratings[slug] || 0); + remove.hidden = !this.ratings[slug]; + }; + settle(); + action.querySelector('.rating-stars').addEventListener('mouseleave', settle); + const busy = (on) => [...stars, remove].forEach(b => { b.disabled = on; }); + + stars.forEach(button => { + button.addEventListener('mouseenter', () => show(Number(button.dataset.stars))); + button.addEventListener('click', async () => { + const n = Number(button.dataset.stars); + // Same stars again: nothing to send + if (this.ratings[slug] === n) return; + busy(true); + try { + const result = await this.request('PUT', `/apps/${encodeURIComponent(slug)}/rating`, {stars: n}); + this.ratings[slug] = n; + showSummary(result); + say(this.t('rating-thanks', {stars: n})); + if (window.umami) window.umami.track('rate', {item: slug, stars: n}); + } catch (error) { + say(error.status === 403 ? this.t('rating-own') : this.t('error', {message: error.message})); + } finally { + busy(false); + settle(); + } + }); + }); + remove.addEventListener('click', async () => { + busy(true); + try { + await this.request('DELETE', `/apps/${encodeURIComponent(slug)}/rating`); + delete this.ratings[slug]; + say(this.t('rating-removed')); + } catch (error) { + say(this.t('error', {message: error.message})); + } finally { + busy(false); + settle(); + } + }); + } + // --- API ------------------------------------------------------------------- async request(method, path, body) { diff --git a/site/index.html b/site/index.html index 2ec9689..0a73f00 100644 --- a/site/index.html +++ b/site/index.html @@ -65,6 +65,7 @@ diff --git a/site/script.js b/site/script.js index 4219807..5185a0c 100644 --- a/site/script.js +++ b/site/script.js @@ -1,7 +1,7 @@ // Static UI strings per language, applied to elements with [data-i18n] // Cards per page; listing.json holds every item, pages are cut here const PAGE_SIZE = 12; -const SORTS = ['newest', 'updated', 'name', 'author']; +const SORTS = ['newest', 'updated', 'rating', 'name', 'author']; const DEFAULT_SORT = 'newest'; const UI_STRINGS = { @@ -17,6 +17,7 @@ const UI_STRINGS = { 'sort-updated': 'Нещодавно оновлені', 'sort-name': 'Назва', 'sort-author': 'Автор', + 'sort-rating': 'Найкраща оцінка', 'sort-reverse': 'Зворотний порядок', 'card-added': 'Додано {date}', 'card-updated': 'Оновлено {date}', @@ -68,6 +69,7 @@ const UI_STRINGS = { 'sort-updated': 'Recently updated', 'sort-name': 'Name', 'sort-author': 'Author', + 'sort-rating': 'Top rated', 'sort-reverse': 'Reverse order', 'card-added': 'Added {date}', 'card-updated': 'Updated {date}', @@ -310,6 +312,9 @@ class LilkaRepository { const compare = { newest: byDate('added'), updated: byDate('updated'), + // Unrated last; more votes win a tie + rating: (a, b) => ((b.rating && b.rating.average) || 0) - ((a.rating && a.rating.average) || 0) || + ((b.rating && b.rating.count) || 0) - ((a.rating && a.rating.count) || 0) || byName(a, b), name: byName, author: (a, b) => collator.compare(String(a.author || ''), String(b.author || '')) || byName(a, b), }[this.sort] || byName; @@ -1073,9 +1078,18 @@ class LilkaRepository { return card; } - // Last update, from listing.json; manifests have none + listingEntry(type, path) { + return (this.listings[type] || []).find(e => e.path === path) || null; + } + + // Rating and last update, from listing.json; manifests have neither renderCardMeta(entry) { const parts = []; + if (entry.rating && entry.rating.count) { + parts.push(`★ ${ + this.escapeHtml(String(entry.rating.average))} (${ + this.escapeHtml(String(entry.rating.count))})`); + } // The date the list is sorted by; "updated" otherwise const key = this.sort === 'newest' ? 'added' : 'updated'; const date = this.formatDate(entry[key]); @@ -1392,6 +1406,11 @@ class LilkaRepository { }); } + // Stars and "rate this" for signed-in users (community.js) + if (this.community) { + this.community.mountRating(modalBody, type, manifestName, this.listingEntry(type, manifestName)); + } + // Copy-hash buttons modalBody.querySelectorAll('.copy-hash-btn').forEach(btn => { btn.addEventListener('click', (e) => { diff --git a/site/styles.css b/site/styles.css index 27f814a..675e979 100644 --- a/site/styles.css +++ b/site/styles.css @@ -2166,3 +2166,50 @@ footer { .list-toolbar[hidden] { display: none; } + +/* Ratings (script.js card badge, community.js mountRating) */ +.item-card .card-rating { + color: var(--warning); + font-weight: 600; +} + +.item-card .card-rating-count { + color: var(--text-muted); + font-weight: 400; +} + +.rating-section .rating-summary { + color: var(--text-secondary); + margin-bottom: 0.5rem; +} + +.rating-action { + display: flex; + align-items: center; + gap: 0.5rem; + flex-wrap: wrap; +} + +.rating-star { + background: none; + border: none; + color: var(--border-solid); + font-size: 1.5rem; + line-height: 1; + padding: 0 0.1rem; + cursor: pointer; + transition: color var(--transition), transform var(--transition); +} + +.rating-star.on, +.rating-star:focus-visible { + color: var(--warning); +} + +.rating-star:hover { + transform: scale(1.15); +} + +.rating-star:disabled { + cursor: wait; +}