diff --git a/README.md b/README.md index 85ecd19..8b211f3 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ File names: Latin letters, digits, `.`, `_` and `-`. Up to 8 MB per file and catalog.lilka.dev (GitHub Pages) site/ the website; reads the mirror below, and the API for sign-in, publishing and moderation - apps/ wallpapers/ mods/ authors.json + apps/ wallpapers/ mods/ authors.json authors_info.json static mirror of the API's /catalog for Keira devices lilka-catalog-api (api/, Cloudflare) diff --git a/api/README.md b/api/README.md index e50d557..477f0a7 100644 --- a/api/README.md +++ b/api/README.md @@ -175,7 +175,8 @@ All bodies are JSON unless noted. Authenticated calls send | 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 | -| GET | `/catalog/authors.json` | mirror job | Items grouped by author | +| GET | `/catalog/authors.json` | mirror job | Items grouped by author line (build.py's format) | +| GET | `/catalog/authors_info.json` | mirror job | The website's Authors tab: one entry per person (GitHub logins merged ignoring case), public GitHub profile of authors who signed in, Printables links for mod authors, item counts and dates | | GET | `/catalog/export.json` | mirror job | Everything above in one response, plus versions and a stamp | | GET | `/apps?kind=&q=&page=` | user | Published apps, 24 per page | | GET | `/apps/:slug` | user / owner | Detail with versions; owner also sees drafts and statuses | diff --git a/api/migrations/0005_profiles.sql b/api/migrations/0005_profiles.sql new file mode 100644 index 0000000..69ca7e5 --- /dev/null +++ b/api/migrations/0005_profiles.sql @@ -0,0 +1,7 @@ +-- Public GitHub profile fields for the Authors page, refreshed at every +-- sign-in from the same /user response that gives the login. Only authors with +-- a published item are shown there. +ALTER TABLE users ADD COLUMN bio TEXT; +ALTER TABLE users ADD COLUMN blog TEXT; +ALTER TABLE users ADD COLUMN location TEXT; +ALTER TABLE users ADD COLUMN company TEXT; diff --git a/api/scripts/smoke.sh b/api/scripts/smoke.sh index 08b0835..c736741 100755 --- a/api/scripts/smoke.sh +++ b/api/scripts/smoke.sh @@ -16,7 +16,8 @@ sha() { printf '%s' "$1" | shasum -a 256 | cut -d' ' -f1; } npx wrangler d1 execute lilka-catalog --local --command " DELETE FROM sessions; DELETE FROM ratings; DELETE FROM reports; UPDATE apps SET latest_version_id = NULL; DELETE FROM versions; DELETE FROM apps; DELETE FROM users WHERE id != 0; -INSERT INTO users (id, login, role) VALUES (1, 'smoke-dev', 'user'), (2, 'smoke-mod', 'moderator'), (3, 'smoke-fan', 'user'); +INSERT INTO users (id, login, role, bio, blog) VALUES (1, 'smoke-dev', 'user', 'Makes tests', 'https://example.com/'); +INSERT INTO users (id, login, role) VALUES (2, 'smoke-mod', 'moderator'), (3, 'smoke-fan', 'user'); INSERT INTO sessions VALUES ('$(sha $USER_TOKEN)', 1, datetime('now', '+1 day')); INSERT INTO sessions VALUES ('$(sha $MOD_TOKEN)', 2, datetime('now', '+1 day')); INSERT INTO sessions VALUES ('$(sha fan-token)', 3, datetime('now', '+1 day'));" >/dev/null @@ -223,9 +224,16 @@ call 401 "anonymous user list refused" "$API/users/smoke-dev/apps" call 401 "catalog without the mirror secret" "$API/catalog/export.json" call 401 "catalog with a wrong secret" -H "Authorization: Bearer nope" "$API/catalog/apps/index_0.json" call 401 "scanner route with the mirror secret" "${mirror[@]}" "$API/scan/pending" +# An author line naming someone else gets no profile: the owner's stays theirs +call 200 "author info: export with a foreign author line" "${mirror[@]}" "$API/catalog/authors_info.json" +jq -e '.authors | length == 1 and .[0].id == "historic" and .[0].registered == false and .[0].bio == null' "$work/body" >/dev/null && fa=ok || fa=bad +check "a foreign author line does not borrow the owner's profile" ok "$fa" +call 200 "moderator clears the author line" "${mod[@]}" "${json[@]}" -X PATCH "$API/apps/smoke-hello" -d '{"author":null}' call 200 "export for the mirror job" "${mirror[@]}" "$API/catalog/export.json" jq -e '.items["apps/smoke-hello"].version and .documents["apps/smoke-hello/index.json"]' "$work/body" >/dev/null && ex=ok || ex=bad check "export lists the app" ok "$ex" +jq -e '.documents["authors_info.json"] | fromjson | .authors[] | select(.id == "smoke-dev") | .registered and .login == "smoke-dev" and .bio == "Makes tests" and .blog == "https://example.com/" and .counts.apps >= 1' "$work/body" >/dev/null && ai=ok || ai=bad +check "authors_info.json: one author per login, with the profile" ok "$ai" latest=$(npx wrangler d1 execute lilka-catalog --local --json --command "SELECT latest_version_id FROM apps WHERE slug = 'smoke-hello'" 2>/dev/null | jq -r '.[0].results[0].latest_version_id') check "latest_version_id is the approved version, not the infected one" "$version_id" "$latest" location=$(curl -sS -o /dev/null -w '%{redirect_url}' "$API/auth/login?return=http://localhost:8000/") diff --git a/api/src/auth.ts b/api/src/auth.ts index 1ced009..ad41930 100644 --- a/api/src/auth.ts +++ b/api/src/auth.ts @@ -57,6 +57,29 @@ interface GithubUser { login: string; name: string | null; avatar_url: string | null; + bio?: string | null; + blog?: string | null; + location?: string | null; + company?: string | null; +} + +/** Profile text is shown on the public Authors page: short, single-line, trimmed. */ +function profileText(value: unknown, max: number): string | null { + if (typeof value !== 'string') return null; + const text = value.replace(/\s+/g, ' ').trim(); + return text ? text.slice(0, max) : null; +} + +/** GitHub lets "blog" be anything, often without a scheme; only http(s) links are kept. */ +function profileUrl(value: unknown): string | null { + const text = profileText(value, 200); + if (!text) return null; + try { + const url = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`); + return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null; + } catch { + return null; + } } export const auth = new Hono(); @@ -176,13 +199,28 @@ export async function createSession(env: Env, gh: GithubUser): Promise { gh.id, ), env.DB.prepare( - `INSERT INTO users (id, login, name, avatar_url, role) VALUES (?1, ?2, ?3, ?4, ?5) + `INSERT INTO users (id, login, name, avatar_url, role, bio, blog, location, company) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT (id) DO UPDATE SET login = excluded.login, name = excluded.name, avatar_url = excluded.avatar_url, + bio = excluded.bio, + blog = excluded.blog, + location = excluded.location, + company = excluded.company, role = CASE WHEN users.role = 'banned' THEN 'banned' ELSE excluded.role END`, - ).bind(gh.id, gh.login, gh.name, gh.avatar_url, role), + ).bind( + gh.id, + gh.login, + profileText(gh.name, 100), + gh.avatar_url, + role, + profileText(gh.bio, 300), + profileUrl(gh.blog), + profileText(gh.location, 100), + profileText(gh.company, 100), + ), env.DB.prepare( `INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, datetime('now', ?))`, ).bind(tokenHash, gh.id, `+${SESSION_DAYS} days`), diff --git a/api/src/catalog.ts b/api/src/catalog.ts index 75c5916..1ed0e16 100644 --- a/api/src/catalog.ts +++ b/api/src/catalog.ts @@ -12,6 +12,7 @@ import { objectKey } from './versions'; * /catalog///index.json, index_short.json, package.zip * /catalog///static/ * /catalog/authors.json + * /catalog/authors_info.json (website only, see authorsInfoDoc) * * Keira's lilcatalog requests these paths under CATALOG_BASE_URL, and the * Pages mirror is a plain copy of this tree, so every field name and its order @@ -42,6 +43,11 @@ interface CatalogRow extends AppRow { package: string | null; security: string | null; storage_prefix: string; + owner_name: string | null; + owner_bio: string | null; + owner_blog: string | null; + owner_location: string | null; + owner_company: string | null; } /** Published apps with their latest approved version, sorted like Python's sorted(os.listdir()). */ @@ -57,7 +63,8 @@ async function published(env: Env, kind?: AppRow['kind'], slug?: string): Promis params.push(slug); } const { results } = await env.DB.prepare( - `SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar, + `SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar, u.name AS owner_name, + 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 @@ -225,6 +232,119 @@ function authorsDoc(rows: CatalogRow[]): Record { return sorted; } +const GITHUB_LOGIN = /^@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)$/; +/** Mods credit their Printables author as `@Name_12345`, which is that profile's address. */ +const PRINTABLES_HANDLE = /^@([A-Za-z0-9_-]+_\d+)$/; + +/** + * authors_info.json: the website's Authors tab, one entry per person. + * + * authors.json groups by the exact author line, so "@ImbirWithoutSugar" from + * an old manifest and the owner's login "imbirwithoutsugar" were two authors. + * Here a line that is a GitHub login is grouped by that login, ignoring case, + * and an author who has signed in gets their public GitHub profile. Free-text + * lines (mods credit Printables names) stay as they are, without a profile. + * Keira does not read this file. + */ +function authorsInfoDoc(rows: CatalogRow[]) { + interface Author { + id: string; + name: string; + handle: string | null; + login: string | null; + github: string | null; + printables: string | null; + avatar: string | null; + bio: string | null; + location: string | null; + company: string | null; + blog: string | null; + registered: boolean; + aliases: string[]; + counts: Record<'apps' | 'wallpapers' | 'mods', number>; + first_added: string | null; + last_updated: string | null; + items: Record[]; + } + const authors = new Map(); + const min = (a: string | null, b: string | null) => (!a ? b : !b ? a : a < b ? a : b); + const max = (a: string | null, b: string | null) => (!a ? b : !b ? a : a > b ? a : b); + + for (const row of rows) { + const line = displayAuthor(row); + const login = GITHUB_LOGIN.exec(line)?.[1] ?? null; + // The profile is the owner's only when the line names the owner + const own = !!login && login.toLowerCase() === row.owner_login.toLowerCase() && row.owner_id !== 0; + const id = login ? login.toLowerCase() : line.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '') || 'unknown'; + let author = authors.get(id); + if (!author) { + const printables = !login && PRINTABLES_HANDLE.test(line); + author = { + id, + // "@BFB_Workshop_1838755" reads as "BFB Workshop"; the handle stays in `handle` + name: login ?? (printables ? line.slice(1).replace(/_\d+$/, '').replace(/_/g, ' ') : line), + handle: login ? `@${login}` : printables ? line : null, + login, + github: login ? `https://github.com/${login}` : null, + printables: printables ? `https://www.printables.com/${line}` : null, + // github.com/.png redirects to the avatar, also for people who never signed in here + avatar: login ? `https://github.com/${login}.png?size=160` : null, + bio: null, + location: null, + company: null, + blog: null, + registered: false, + aliases: [], + counts: { apps: 0, wallpapers: 0, mods: 0 }, + first_added: null, + last_updated: null, + items: [], + }; + authors.set(id, author); + } + if (own && !author.registered) { + Object.assign(author, { + // GitHub's spelling of the login, not the old manifest's + name: row.owner_name || row.owner_login, + handle: `@${row.owner_login}`, + login: row.owner_login, + github: `https://github.com/${row.owner_login}`, + avatar: row.owner_avatar ?? author.avatar, + bio: row.owner_bio, + location: row.owner_location, + company: row.owner_company, + blog: row.owner_blog, + registered: true, + }); + } + if (!author.aliases.includes(line)) author.aliases.push(line); + + const dir = kindDir(row.kind); + const added = row.published_at ?? row.approved_at; + author.counts[dir] += 1; + author.first_added = min(author.first_added, added); + author.last_updated = max(author.last_updated, row.approved_at); + const loc = localization(row); + const entry: Record = { + name: pick(loc, 'name'), + short_description: pick(loc, 'short_description'), + icon: row.icon ?? '', + path: row.slug, + type: dir, + added, + updated: row.approved_at, + }; + if (Object.keys(loc).length) { + entry.languages = Object.keys(loc); + entry.localization = onlyFields(loc, ['name', 'short_description']); + } + author.items.push(entry); + } + const list = [...authors.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + for (const author of list) author.items.sort((a, b) => String(b.updated ?? '').localeCompare(String(a.updated ?? ''))); + return { authors: list }; +} + /** * listing.json: everything the website's list needs for one kind, in one file. * @@ -267,6 +387,7 @@ function indexDocs(rows: CatalogRow[]) { } catalog.get('/authors.json', async (c) => json(c, authorsDoc(await published(c.env)))); +catalog.get('/authors_info.json', async (c) => json(c, authorsInfoDoc(await published(c.env)))); catalog.get('/:dir/listing.json', async (c) => json(c, listingDoc(await published(c.env, dirKind(c.req.param('dir')))))); @@ -289,7 +410,10 @@ catalog.get('/:dir/:page{index_[0-9]+\\.json}', async (c) => { */ catalog.get('/export.json', async (c) => { const rows = await published(c.env); - const documents: Record = { 'authors.json': text(authorsDoc(rows)) }; + const documents: Record = { + 'authors.json': text(authorsDoc(rows)), + 'authors_info.json': text(authorsInfoDoc(rows)), + }; const items: Record = {}; for (const dir of Object.keys(DIRS)) { const ofKind = rows.filter((row) => kindDir(row.kind) === dir); diff --git a/site/script.js b/site/script.js index 56602f9..4219807 100644 --- a/site/script.js +++ b/site/script.js @@ -20,6 +20,35 @@ const UI_STRINGS = { 'sort-reverse': 'Зворотний порядок', 'card-added': 'Додано {date}', 'card-updated': 'Оновлено {date}', + 'authors-title': 'Автори', + 'authors-summary': 'Авторів: {authors} · елементів: {items}', + 'authors-search': 'Пошук автора або додатка', + 'authors-sort-items': 'Найбільше елементів', + 'authors-sort-recent': 'Нещодавно активні', + 'authors-sort-name': 'Імʼя', + 'authors-sort-newest': 'Нові автори', + 'authors-all': 'Усі', + 'authors-empty': 'Нікого не знайдено.', + 'authors-error': 'Не вдалося завантажити авторів: {message}', + 'author-back': 'Усі автори', + 'author-github': 'Профіль GitHub', + 'author-website': 'Сайт', + 'author-printables': 'Профіль Printables', + 'author-first': 'Перший елемент: {date}', + 'author-last': 'Останнє оновлення: {date}', + 'author-active': 'Активність: {date}', + 'author-copy': 'Копіювати посилання', + 'author-copied': 'Скопійовано', + 'author-verified': 'Підтверджений GitHub', + 'author-verified-hint': 'Увійшов на сайт через GitHub і володіє цими елементами', + 'author-not-found': 'Автора «{name}» не знайдено.', + 'author-items': 'Роботи', + 'kind-apps': 'Додатки', + 'kind-wallpapers': 'Шпалери', + 'kind-mods': 'Моди', + 'kind-one-apps': 'Додаток', + 'kind-one-wallpapers': 'Шпалери', + 'kind-one-mods': 'Мод', 'av-info-title': 'Як ми перевіряємо файли', 'av-info-1': 'Кожен файл для завантаження (включно з package.zip) перевіряється антивірусом ClamAV у GitHub Actions одразу після завантаження в каталог, ще до публікації.', 'av-info-2': 'Перед скануванням бази сигнатур оновлюються до найновіших (freshclam).', @@ -42,6 +71,35 @@ const UI_STRINGS = { 'sort-reverse': 'Reverse order', 'card-added': 'Added {date}', 'card-updated': 'Updated {date}', + 'authors-title': 'Authors', + 'authors-summary': '{authors} authors · {items} items', + 'authors-search': 'Search authors or items', + 'authors-sort-items': 'Most items', + 'authors-sort-recent': 'Recently active', + 'authors-sort-name': 'Name', + 'authors-sort-newest': 'Newest authors', + 'authors-all': 'All', + 'authors-empty': 'Nobody found.', + 'authors-error': 'Failed to load authors: {message}', + 'author-back': 'All authors', + 'author-github': 'GitHub profile', + 'author-website': 'Website', + 'author-printables': 'Printables profile', + 'author-first': 'First item: {date}', + 'author-last': 'Last update: {date}', + 'author-active': 'Active {date}', + 'author-copy': 'Copy link', + 'author-copied': 'Copied', + 'author-verified': 'Verified GitHub', + 'author-verified-hint': 'Signed in with GitHub and owns these items', + 'author-not-found': 'Author "{name}" not found.', + 'author-items': 'Works', + 'kind-apps': 'Apps', + 'kind-wallpapers': 'Wallpapers', + 'kind-mods': 'Mods', + 'kind-one-apps': 'App', + 'kind-one-wallpapers': 'Wallpaper', + 'kind-one-mods': 'Mod', 'av-info-title': 'How we check files', 'av-info-1': 'Every downloadable file (including package.zip) is scanned with the ClamAV antivirus in GitHub Actions right after it is uploaded, before it is published.', 'av-info-2': 'Virus signature databases are updated to the latest version (freshclam) right before scanning.', @@ -131,7 +189,7 @@ class LilkaRepository { if (this.isCommunityView(this.currentType)) { this.community.refresh(); } else if (this.currentType === 'authors') { - this.showAuthors(); + this.showAuthors({push: false}); } else { this.loadPage(); } @@ -139,7 +197,7 @@ class LilkaRepository { const modal = document.getElementById('modal'); if (modal && modal.style.display === 'block' && this._currentManifest && this._currentManifestName) { - this.showModal(this._currentManifest, this._currentManifestName); + this.showModal(this._currentManifest, this._currentManifestName, this._currentManifestType); } } @@ -312,18 +370,8 @@ class LilkaRepository { // Handle authors page if (type === 'authors') { this.currentType = type; - const authorParam = params.get('author'); - await this.showAuthors(); - if (authorParam) { - const sectionId = `author-${this.authorSlug(authorParam)}`; - const section = document.getElementById(sectionId); - if (section) { - section.classList.remove('collapsed'); - section.scrollIntoView({behavior: 'smooth', block: 'start'}); - section.classList.add('author-highlight'); - setTimeout(() => section.classList.remove('author-highlight'), 2000); - } - } + this.authorId = params.get('author') || null; + await this.showAuthors({push: false}); return; } @@ -451,6 +499,7 @@ class LilkaRepository { if (this.isCommunityView(type)) { this.community.show(type); } else if (type === 'authors') { + this.authorId = null; this.showAuthors(); } else { this.switchType(type); @@ -527,7 +576,15 @@ class LilkaRepository { document.getElementById('modal').style.display = 'none'; this._currentManifest = null; this._currentManifestName = null; - // Return to list view URL + // Return to list view URL; on the Authors page, to the author + if (this.currentType === 'authors') { + const params = new URLSearchParams({type: 'authors'}); + if (this.authorId) params.set('author', this.authorId); + if (location.search !== `?${params}`) { + window.history.pushState({type: 'authors', author: this.authorId}, '', `?${params}`); + } + return; + } this.updateURL(this.currentType, this.currentPage); } @@ -544,108 +601,339 @@ class LilkaRepository { window.scrollTo({top: 0}); } - async showAuthors() { - this.showView('authors'); - const authorsContainer = document.getElementById('authors'); + ui(key, vars = {}) { + const strings = UI_STRINGS[this.currentLang] || UI_STRINGS[this.defaultLanguage]; + return String(strings[key] ?? key).replace(/\{(\w+)\}/g, (m, name) => + name in vars ? String(vars[name]) : m); + } + + /** + * authors_info.json: one entry per person, with profile and stats. A + * mirror built before it existed only has authors.json (author line -> + * items), which is turned into the same shape without profiles. + */ + async loadAuthors() { + if (this.authorsData) return this.authorsData; + const info = await fetch(this.dataUrl('authors_info.json')); + if (info.ok) { + this.authorsData = (await info.json()).authors || []; + return this.authorsData; + } + const response = await fetch(this.dataUrl('authors.json')); + if (!response.ok) throw new Error(`authors.json: ${response.status}`); + const old = await response.json(); + this.authorsData = Object.entries(old).map(([line, items]) => { + const login = (/^@([A-Za-z0-9-]+)$/.exec(line) || [])[1] || null; + const counts = {apps: 0, wallpapers: 0, mods: 0}; + items.forEach(item => { counts[item.type] = (counts[item.type] || 0) + 1; }); + return { + id: login ? login.toLowerCase() : this.authorSlug(line), + name: login || line, login, + github: login ? `https://github.com/${login}` : null, + avatar: login ? `https://github.com/${login}.png?size=160` : null, + aliases: [line], counts, items, registered: false, + }; + }); + return this.authorsData; + } - this.updateURL('authors'); + /** An author by id, or by the author line an item card links with. */ + findAuthor(authors, key) { + const wanted = String(key || '').toLowerCase(); + return authors.find(a => a.id === wanted || + (a.aliases || []).some(alias => alias.toLowerCase() === wanted)) || null; + } + async showAuthors({push = true} = {}) { + this.currentType = 'authors'; + this.showView('authors'); + const box = document.getElementById('authors'); + if (push) { + const params = new URLSearchParams({type: 'authors'}); + if (this.authorId) params.set('author', this.authorId); + if (location.search !== `?${params}`) { + window.history.pushState({type: 'authors', author: this.authorId}, '', `?${params}`); + } + } + if (!this.authorsData) { + box.innerHTML = `
${this.escapeHtml(this.ui('loading'))}
`; + } try { - const response = await fetch(this.dataUrl('authors.json')); - if (!response.ok) { - throw new Error('Failed to load authors data'); + const authors = await this.loadAuthors(); + if (this.authorId) { + this.renderAuthorPage(box, authors); + } else { + this.renderAuthorsGrid(box, authors); } - const authors = await response.json(); - authorsContainer.innerHTML = this.renderAuthorsPage(authors); - - // Add click handlers for author item cards - authorsContainer.querySelectorAll('.author-item-card').forEach(card => { - card.addEventListener('click', async () => { - const itemType = card.dataset.itemType; - const itemPath = card.dataset.itemPath; - try { - const manifestPath = `${itemType}/${itemPath}/index.json`; - const resp = await fetch(this.dataUrl(manifestPath)); - if (!resp.ok) throw new Error(`Item not found: ${itemPath}`); - const manifest = await resp.json(); - this.currentType = itemType; - this.showModal(manifest, itemPath); - } catch (err) { - console.error('Error opening item from authors:', err); - } + } catch (error) { + box.innerHTML = `

${ + this.escapeHtml(this.ui('authors-error', {message: error.message}))}

`; + } + } + + openAuthor(id) { + this.authorId = id; + this.showAuthors(); + window.scrollTo({top: 0}); + } + + /** Only http(s) links from the data reach an href. */ + safeUrl(value) { + return typeof value === 'string' && /^https?:\/\//i.test(value) ? value : null; + } + + authorHandle(a) { + return a.handle || (a.login ? `@${a.login}` : ''); + } + + renderAvatar(author, size) { + const initial = ((author.name || '').match(/[\p{L}\p{N}]/u) || ['?'])[0].toUpperCase(); + // The initial stays underneath; a broken image hides itself + return ``; + } + + renderAuthorCounts(counts) { + return ['apps', 'wallpapers', 'mods'].filter(kind => counts[kind]).map(kind => + `${this.escapeHtml(this.ui(`kind-${kind}`))} ${ + counts[kind]}`).join(''); + } + + totalItems(author) { + const c = author.counts || {}; + return (c.apps || 0) + (c.wallpapers || 0) + (c.mods || 0); + } + + renderAuthorsGrid(box, authors) { + this.authorsSort = this.authorsSort || 'items'; + this.authorsKind = this.authorsKind || 'all'; + const sorts = ['items', 'recent', 'name', 'newest']; + const kinds = ['all', 'apps', 'wallpapers', 'mods']; + const total = authors.reduce((n, a) => n + this.totalItems(a), 0); + box.innerHTML = ` +
+
+

${this.escapeHtml(this.ui('authors-title'))}

+

${this.escapeHtml(this.ui('authors-summary', {authors: authors.length, items: total}))}

+
+
+
+ +
+ ${kinds.map(kind => ``).join('')} +
+ +
+
`; + + const grid = box.querySelector('.authors-grid'); + const draw = () => { + const q = (this.authorsQuery || '').trim().toLowerCase(); + const collator = new Intl.Collator(this.currentLang, {sensitivity: 'base'}); + const byName = (a, b) => collator.compare(a.name, b.name); + const compare = { + items: (a, b) => this.totalItems(b) - this.totalItems(a) || byName(a, b), + recent: (a, b) => String(b.last_updated || '').localeCompare(String(a.last_updated || '')) || byName(a, b), + newest: (a, b) => String(b.first_added || '').localeCompare(String(a.first_added || '')) || byName(a, b), + name: byName, + }[this.authorsSort]; + const shown = authors.filter(a => { + if (this.authorsKind !== 'all' && !(a.counts || {})[this.authorsKind]) return false; + if (!q) return true; + const haystack = [a.name, a.login, a.bio, ...(a.aliases || []), + ...a.items.map(i => this.localized(i, 'name'))].join(' ').toLowerCase(); + return haystack.includes(q); + }).sort(compare); + grid.innerHTML = shown.length ? shown.map(a => this.renderAuthorCard(a)).join('') : + `

${this.escapeHtml(this.ui('authors-empty'))}

`; + grid.querySelectorAll('.author-card').forEach(card => { + card.addEventListener('click', (e) => { + // The GitHub link opens GitHub; a modified click opens a new tab + if (e.target.closest('.author-card-ext')) return; + if (e.metaKey || e.ctrlKey || e.shiftKey) return; + e.preventDefault(); + this.openAuthor(card.dataset.author); }); }); + }; + draw(); - // Collapsible author sections - authorsContainer.querySelectorAll('.author-section-header') - .forEach(header => { - header.addEventListener('click', () => { - const section = header.closest('.author-section'); - section.classList.toggle('collapsed'); - }); - }); - } catch (error) { - authorsContainer.innerHTML = - `

Failed to load authors: ${ - error.message}

`; - } + const search = box.querySelector('.authors-search'); + search.addEventListener('input', () => { + this.authorsQuery = search.value; + draw(); + }); + box.querySelectorAll('.authors-chip').forEach(chip => chip.addEventListener('click', () => { + this.authorsKind = chip.dataset.kind; + box.querySelectorAll('.authors-chip').forEach(c => c.classList.toggle('active', c === chip)); + draw(); + })); + box.querySelector('.authors-sort').addEventListener('change', (e) => { + this.authorsSort = e.target.value; + draw(); + }); } - renderAuthorsPage(authors) { - const authorNames = Object.keys(authors); - let html = `

Authors (${authorNames.length})

`; - - for (const author of authorNames) { - const items = authors[author]; - const apps = items.filter(i => i.type === 'apps'); - const wallpapers = items.filter(i => i.type === 'wallpapers'); - const mods = items.filter(i => i.type === 'mods'); - const badge = []; - if (apps.length) - badge.push(`${apps.length} app${apps.length > 1 ? 's' : ''}`); - if (wallpapers.length) - badge.push(`${wallpapers.length} wallpaper${ - wallpapers.length > 1 ? 's' : ''}`); - if (mods.length) - badge.push(`${mods.length} mod${mods.length > 1 ? 's' : ''}`); - - const sectionId = `author-${this.authorSlug(author)}`; - html += `
`; - html += `
`; - html += - `${this.escapeHtml(author)}`; - html += `${badge.join(', ')}`; - html += `▼`; - html += `
`; - html += `
`; - html += `
`; - - for (const item of items) { - const iconPath = - item.icon ? this.dataUrl(`${item.type}/${item.path}/static/${item.icon}`) : ''; - const typeLabel = - {apps: 'App', wallpapers: 'Wallpaper', mods: 'Mod'}[item.type]; - const itemName = this.localized(item, 'name'); - const itemShortDesc = this.localized(item, 'short_description') || ''; - html += `
`; - if (item.icon) { - html += `${
-              this.escapeHtml(
-                  itemName)}`; - } - html += `

${this.escapeHtml(itemName)}

`; - html += `${ - typeLabel}`; - html += - `
${this.escapeHtml(itemShortDesc)}
`; - html += `
`; - } + renderAuthorCard(a) { + const href = `?type=authors&author=${encodeURIComponent(a.id)}`; + const active = this.formatDate(a.last_updated); + // The whole card opens the author; the title is the real link, for the + // keyboard and for opening in a new tab + return ` +
+
+ ${this.renderAvatar(a, 'md')} +
+

${this.escapeHtml(a.name)}${a.registered ? + ` ✓` : ''}

+ ${this.authorHandle(a) ? `` : ''} +
+
+ ${a.bio ? `

${this.escapeHtml(a.bio)}

` : ''} +
${this.renderAuthorCounts(a.counts || {})}
+
+ ${active ? this.escapeHtml(this.ui('author-active', {date: active})) : ''} + ${this.safeUrl(a.github) ? `GitHub ↗` : ''} + ${this.safeUrl(a.printables) ? `Printables ↗` : ''} +
+
`; + } - html += `
`; + renderAuthorPage(box, authors) { + const a = this.findAuthor(authors, this.authorId); + const back = ``; + if (!a) { + box.innerHTML = `${back}

${ + this.escapeHtml(this.ui('author-not-found', {name: this.authorId}))}

`; + box.querySelector('.author-back').addEventListener('click', () => this.openAuthor(null)); + return; + } + // A link by author line becomes the canonical one + if (a.id !== this.authorId) { + this.authorId = a.id; + window.history.replaceState({type: 'authors', author: a.id}, '', + `?type=authors&author=${encodeURIComponent(a.id)}`); } + this.authorItemsKind = this.authorItemsKind && (a.counts || {})[this.authorItemsKind] ? this.authorItemsKind : 'all'; + + const facts = []; + if (a.location) facts.push(`📍 ${this.escapeHtml(a.location)}`); + if (a.company) facts.push(`🏢 ${this.escapeHtml(a.company)}`); + if (this.safeUrl(a.blog)) { + const shown = a.blog.replace(/^https?:\/\//i, '').replace(/\/$/, ''); + facts.push(`🔗 ${ + this.escapeHtml(shown)}`); + } + const first = this.formatDate(a.first_added); + const last = this.formatDate(a.last_updated); + const kinds = ['all', ...['apps', 'wallpapers', 'mods'].filter(k => (a.counts || {})[k])]; + + box.innerHTML = ` + ${back} +
+ ${this.renderAvatar(a, 'lg')} +
+

${this.escapeHtml(a.name)}

+
+ ${this.authorHandle(a) ? `` : ''} + ${a.registered ? `✓ ${ + this.escapeHtml(this.ui('author-verified'))}` : ''} +
+ ${a.bio ? `

${this.escapeHtml(a.bio)}

` : ''} + ${facts.length ? `
${facts.join('')}
` : ''} +
${this.renderAuthorCounts(a.counts || {})}
+ +
+ ${this.safeUrl(a.github) ? `${ + this.escapeHtml(this.ui('author-github'))} ↗` : ''} + ${this.safeUrl(a.printables) ? `${ + this.escapeHtml(this.ui('author-printables'))} ↗` : ''} + +
+
+
+
+

${this.escapeHtml(this.ui('author-items'))}

+ ${kinds.length > 2 ? `
${kinds.map(kind => + ``).join('')}
` : ''} +
+
`; + + const grid = box.querySelector('.author-items-grid'); + const draw = () => { + const items = a.items.filter(i => this.authorItemsKind === 'all' || i.type === this.authorItemsKind); + grid.innerHTML = items.map(item => this.renderAuthorItem(item)).join(''); + grid.querySelectorAll('.author-item-card').forEach(card => { + const open = () => this.openAuthorItem(card.dataset.itemType, card.dataset.itemPath); + card.addEventListener('click', open); + card.addEventListener('keydown', (e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + open(); + } + }); + }); + }; + draw(); + + box.querySelector('.author-back').addEventListener('click', () => this.openAuthor(null)); + box.querySelectorAll('.authors-chip').forEach(chip => chip.addEventListener('click', () => { + this.authorItemsKind = chip.dataset.kind; + box.querySelectorAll('.authors-chip').forEach(c => c.classList.toggle('active', c === chip)); + draw(); + })); + const copy = box.querySelector('.author-copy'); + copy.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(location.href); + copy.textContent = this.ui('author-copied'); + setTimeout(() => { copy.textContent = this.ui('author-copy'); }, 1500); + } catch (e) { + prompt(this.ui('author-copy'), location.href); + } + }); + } - return html; + renderAuthorItem(item) { + const name = this.localized(item, 'name') || item.path; + const short = this.localized(item, 'short_description') || ''; + const icon = item.icon ? this.dataUrl(`${item.type}/${item.path}/static/${item.icon}`) : ''; + const updated = this.formatDate(item.updated); + return ` +
+ ${icon ? `${this.escapeHtml(name)}` : ''} +

${this.escapeHtml(name)}

+ ${this.escapeHtml(this.ui(`kind-one-${item.type}`))} +
${this.escapeHtml(short)}
+ ${updated ? `
${ + this.escapeHtml(this.ui('card-updated', {date: updated}))}
` : ''} +
`; + } + + async openAuthorItem(type, path) { + try { + const response = await fetch(this.dataUrl(`${type}/${path}/index.json`)); + if (!response.ok) throw new Error(`Item not found: ${path}`); + const manifest = await response.json(); + this.showModal(manifest, path, type); + } catch (err) { + console.error('Error opening item from authors:', err); + } } async loadPage() { @@ -1011,18 +1299,20 @@ class LilkaRepository { `; } - showModal(manifest, manifestName) { + showModal(manifest, manifestName, type = this.currentType) { // Remember the currently open manifest so it can be re-rendered when the - // language is switched while the modal is open. + // language is switched while the modal is open. The kind is passed in from + // the Authors page, where the list behind the modal is not of one kind this._currentManifest = manifest; this._currentManifestName = manifestName; + this._currentManifestType = type; const modalName = this.localized(manifest, 'name'); // Track manifest views if (window.umami) { window.umami.track('view-manifest', { - type: this.currentType, + type, name: manifest.name, manifest: manifestName, author: manifest.author @@ -1033,7 +1323,7 @@ class LilkaRepository { const modalBody = document.getElementById('modalBody'); // manifestName already includes the full path relative to type - const basePath = this.dataUrl(`${this.currentType}/${manifestName}`); + const basePath = this.dataUrl(`${type}/${manifestName}`); // Store screenshots for lightbox this.currentScreenshots = @@ -1272,31 +1562,13 @@ class LilkaRepository { return (author || '').replace(/[^a-zA-Z0-9_-]/g, '_').toLowerCase(); } - async navigateToAuthor(author) { - // Close modal if open + navigateToAuthor(author) { document.getElementById('modal').style.display = 'none'; - - // Load authors page - await this.showAuthors(); - - // Scroll to the author section & highlight it - const sectionId = `author-${this.authorSlug(author)}`; - const section = document.getElementById(sectionId); - if (section) { - // Make sure it's not collapsed - section.classList.remove('collapsed'); - section.scrollIntoView({behavior: 'smooth', block: 'start'}); - section.classList.add('author-highlight'); - setTimeout(() => section.classList.remove('author-highlight'), 2000); - } - - // Update URL - const params = new URLSearchParams(); - params.set('type', 'authors'); - params.set('author', author); - window.history.pushState( - {type: 'authors', author}, '', `?${params.toString()}`); + this._currentManifest = null; + this._currentManifestName = null; + this.openAuthor(author); } + } // Initialize the app when DOM is ready diff --git a/site/styles.css b/site/styles.css index d1b21df..27f814a 100644 --- a/site/styles.css +++ b/site/styles.css @@ -1117,66 +1117,321 @@ footer { letter-spacing: -0.02em; } -.author-section { +.authors-head { + display: flex; + justify-content: space-between; + align-items: flex-end; + gap: 1rem; + margin-bottom: 1.25rem; +} + +.authors-head .authors-title { + margin-bottom: 0.25rem; +} + +.authors-summary, +.authors-empty, +.author-login, +.author-dates { + color: var(--text-muted); + font-size: 0.9rem; +} + +.authors-error { + color: var(--error); +} + +.authors-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; + margin-bottom: 1.5rem; +} + +.authors-search, +.authors-sort { + font: inherit; + font-size: 0.9rem; + color: var(--text-primary); + background: var(--surface); + border: 1px solid var(--border-solid); + border-radius: var(--radius-xs); + padding: 0.5rem 0.75rem; +} + +.authors-search { + flex: 1 1 16rem; + min-width: 0; +} + +.authors-search:focus, +.authors-sort:focus { + outline: none; + border-color: var(--primary-color); + box-shadow: 0 0 0 3px var(--primary-glow); +} + +.authors-kinds { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.authors-chip { + font: inherit; + font-size: 0.82rem; + font-weight: 600; + color: var(--text-secondary); + background: var(--surface); + border: 1px solid var(--border-solid); + border-radius: 999px; + padding: 0.35rem 0.85rem; + cursor: pointer; + transition: all var(--transition); +} + +.authors-chip:hover { + border-color: var(--primary-color); +} + +.authors-chip.active { + color: var(--text-primary); + background: var(--primary-glow); + border-color: var(--primary-color); +} + +.authors-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 1rem; +} + +.author-card { + display: flex; + flex-direction: column; + gap: 0.75rem; background: var(--surface); border: 1px solid var(--border-solid); border-radius: var(--radius); - margin-bottom: 1.25rem; - overflow: hidden; + padding: 1.1rem 1.2rem; + cursor: pointer; transition: all var(--transition); + min-width: 0; } -.author-section:hover { +.author-card:hover { + transform: translateY(-3px); box-shadow: var(--shadow-lg); - border-color: rgba(244, 114, 182, 0.3); + border-color: rgba(244, 114, 182, 0.35); } -.author-section-header { +.author-card-top { display: flex; align-items: center; - gap: 1rem; - padding: 1.1rem 1.5rem; - cursor: pointer; - user-select: none; - transition: background-color var(--transition); + gap: 0.85rem; + min-width: 0; } -.author-section-header:hover { - background-color: var(--surface-light); +.author-card-names { + min-width: 0; } -.author-section-name { - color: var(--primary-color); - font-size: 1.2rem; +.author-card h3 { + font-size: 1.05rem; font-weight: 700; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } -.author-section-badge { - color: var(--text-muted); - font-size: 0.82rem; - background: var(--background-alt); - padding: 0.2rem 0.65rem; +.author-card-link { + color: var(--text-primary); + text-decoration: none; +} + +.author-card-link:focus-visible { + outline: 2px solid var(--primary-color); + outline-offset: 2px; + border-radius: 2px; +} + +.author-verified { + color: var(--success); + font-size: 0.85rem; +} + +.author-card-bio { + color: var(--text-secondary); + font-size: 0.85rem; + line-height: 1.45; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.author-counts { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.author-count { + font-size: 0.75rem; + font-weight: 600; + padding: 0.15rem 0.6rem; border-radius: 999px; border: 1px solid var(--border-solid); + color: var(--text-secondary); } -.author-section-toggle { - margin-left: auto; +.author-count.type-apps { border-color: rgba(129, 140, 248, 0.4); color: var(--primary-color); } +.author-count.type-wallpapers { border-color: rgba(251, 191, 36, 0.4); color: var(--warning); } +.author-count.type-mods { border-color: rgba(52, 211, 153, 0.4); color: var(--success); } + +.author-card-foot { + margin-top: auto; + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.5rem; color: var(--text-muted); - font-size: 0.85rem; - transition: transform 0.3s ease; + font-size: 0.8rem; } -.author-section.collapsed .author-section-toggle { - transform: rotate(-90deg); +.author-card-ext { + color: var(--primary-color); + text-decoration: none; + font-weight: 600; } -.author-section.collapsed .author-section-body { - display: none; +.author-card-ext:hover { + text-decoration: underline; +} + +.author-avatar { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 50%; + overflow: hidden; + color: var(--text-primary); + font-weight: 800; + background: linear-gradient(135deg, var(--primary-dark), var(--pink)); +} + +.author-avatar img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.author-avatar-md { width: 48px; height: 48px; font-size: 1.2rem; } +.author-avatar-lg { width: 112px; height: 112px; font-size: 2.6rem; } + +.author-back { + font: inherit; + font-size: 0.9rem; + color: var(--text-secondary); + background: none; + border: none; + cursor: pointer; + padding: 0.25rem 0; + margin-bottom: 1rem; +} + +.author-back:hover { + color: var(--primary-color); +} + +.author-profile { + display: flex; + gap: 1.5rem; + align-items: flex-start; + background: var(--surface); + border: 1px solid var(--border-solid); + border-radius: var(--radius); + padding: 1.5rem; + margin-bottom: 2rem; +} + +.author-profile-main { + display: flex; + flex-direction: column; + gap: 0.6rem; + min-width: 0; } -.author-section-body { - padding: 0 1.5rem 1.5rem; +.author-profile h2 { + font-size: 1.6rem; + font-weight: 800; + letter-spacing: -0.02em; + overflow-wrap: anywhere; +} + +.author-profile-sub, +.author-facts, +.author-dates, +.author-profile-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 1rem; +} + +.author-badge { + font-size: 0.75rem; + font-weight: 700; + color: var(--success); + border: 1px solid rgba(52, 211, 153, 0.4); + background: rgba(52, 211, 153, 0.1); + border-radius: 999px; + padding: 0.1rem 0.6rem; +} + +.author-profile-bio { + color: var(--text-secondary); + line-height: 1.5; + overflow-wrap: anywhere; +} + +.author-fact { + color: var(--text-secondary); + font-size: 0.9rem; + text-decoration: none; + overflow-wrap: anywhere; +} + +a.author-fact:hover { + color: var(--primary-color); + text-decoration: underline; +} + +.author-profile-actions .btn-sm { + text-decoration: none; +} + +.author-items-head { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: 0.75rem; + margin-bottom: 1rem; +} + +.author-items-head h3 { + font-size: 1.2rem; + font-weight: 700; +} + +.author-item-card .card-meta { + margin-top: 0.5rem; } .author-items-grid { @@ -1271,25 +1526,29 @@ footer { color: var(--pink); } -/* Highlight animation when scrolling to author */ -.author-highlight { - animation: authorPulse 2s ease; -} - -@keyframes authorPulse { - 0% { box-shadow: 0 0 0 0 rgba(244, 114, 182, 0.6); } - 30% { box-shadow: 0 0 0 6px rgba(244, 114, 182, 0.3); } - 70% { box-shadow: 0 0 0 6px rgba(244, 114, 182, 0.12); } - 100% { box-shadow: none; } -} - @media (max-width: 768px) { - .author-items-grid { + .author-items-grid, + .authors-grid { grid-template-columns: 1fr; } - .author-section-header { - flex-wrap: wrap; + .author-profile { + flex-direction: column; + align-items: center; + text-align: center; + padding: 1.25rem; + } + + .author-profile-main { + align-items: center; + } + + .author-profile-sub, + .author-facts, + .author-dates, + .author-profile-actions, + .author-profile .author-counts { + justify-content: center; } }