Files
client/app/renderer/js/badges.js
T

145 lines
6.3 KiB
JavaScript

// Client badges (official tree `ts-badges` small icons with the badge description as tooltip, and the client
// info "Badge Showcase" with detailed artwork and names). Metadata and artwork come from main's public catalog
// (app/main/badges.js): the renderer only sends badge UUIDs and receives SVG text.
//
// Caching: only successful results are kept, in bounded least-recently-used maps of plain data (catalog entries
// and SVG text). Unknown/failed lookups are forgotten as soon as they settle; badgeEpoch() changes at most every
// 30 s afterwards so rendered rows ask main again (main throttles network retries). Each <img> gets its own blob:
// URL, revoked once the image loaded or failed, so no Blob outlives its element and no cached value can be a
// revoked URL.
import { tp } from './core.js';
import { h, icon } from './dom.js';
import { t } from './i18n.js';
import { parseClientBadges } from './badges-model.js';
const MAX_INFO = 1000;
const MAX_ART = 200;
// Main accepts at most 64 UUIDs per badges:info call (MAX_REQUEST_UUIDS).
const INFO_BATCH = 64;
const UNKNOWN = Object.freeze({ known: false, name: '', description: '' });
const info = new Map(); // uuid → Promise<{ known, name, description }> (in flight or known)
const art = new Map(); // `${uuid}|${detailed}` → Promise<string|null> SVG text (in flight or found)
let queued = null; // uuid → resolve, waiting for the next batched badges:info request
export { parseClientBadges };
/** Least-recently-used lookup: a hit moves to the end; inserts evict the oldest beyond `max`. */
function cached(map, key, max, create) {
const hit = map.get(key);
if (hit) {
map.delete(key);
map.set(key, hit);
return hit;
}
const promise = create();
map.set(key, promise);
while (map.size > max) map.delete(map.keys().next().value);
return promise;
}
// After a failed lookup, rows retry at most once per RETRY_MS: the tree includes badgeEpoch() in its row signature.
const RETRY_MS = 30000;
let epoch = 0;
let retryTimer = null;
/** Changes (at most once per RETRY_MS) after lookups failed, so rendered badge slots ask again. */
export function badgeEpoch() {
return epoch;
}
/** Drops `key` once its promise settled with `failed(value)`, unless a newer promise replaced it meanwhile. */
function forgetFailure(map, key, promise, failed) {
promise.then((value) => {
if (!failed(value)) return;
if (map.get(key) === promise) map.delete(key);
retryTimer ??= setTimeout(() => { retryTimer = null; epoch += 1; }, RETRY_MS);
});
return promise;
}
function flushInfo() {
const pending = [...queued];
queued = null;
const settle = (resolve, badge) => resolve(badge?.known ? { known: true, name: badge.name, description: badge.description } : UNKNOWN);
for (let i = 0; i < pending.length; i += INFO_BATCH) {
const batch = pending.slice(i, i + INFO_BATCH);
const request = typeof tp?.badgeInfo === 'function' ? tp.badgeInfo(batch.map(([uuid]) => uuid)) : Promise.resolve(null);
request.then((r) => {
const byId = new Map((r?.ok ? r.badges : []).map((b) => [b.uuid, b]));
for (const [uuid, resolve] of batch) settle(resolve, byId.get(uuid));
}, () => {
for (const [, resolve] of batch) settle(resolve, null);
});
}
}
/** Catalog name/description; requests made in the same task are batched into one IPC call. */
export function badgeInfo(uuid) {
return cached(info, uuid, MAX_INFO, () => {
let resolveInfo;
const promise = new Promise((resolve) => { resolveInfo = resolve; });
if (!queued) { queued = new Map(); queueMicrotask(flushInfo); }
queued.set(uuid, resolveInfo);
return forgetFailure(info, uuid, promise, (value) => !value.known);
});
}
/** SVG text of the small (tree) or detailed (showcase) artwork, or null when no source has it right now. */
function badgeSvg(uuid, detailed) {
const key = `${uuid}|${detailed}`;
return cached(art, key, MAX_ART, () => {
const request = typeof tp?.badgeArt === 'function' ? tp.badgeArt(uuid, detailed) : Promise.resolve(null);
const promise = request.then((r) => (r?.ok && typeof r.svg === 'string' ? r.svg : null), () => null);
return forgetFailure(art, key, promise, (svg) => svg === null);
});
}
/** An <img> owning a one-off blob: URL, revoked as soon as the image has been decoded (or failed). */
function svgImage(svg) {
const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
const img = h('img', { alt: '', draggable: 'false' });
const revoke = () => URL.revokeObjectURL(url);
img.addEventListener('load', revoke, { once: true });
img.addEventListener('error', revoke, { once: true });
img.src = url;
return img;
}
/** Tree slot icons (official order: after group icons, before the country flag). Badges without artwork stay hidden. */
export function badgeIcons(raw) {
return parseClientBadges(raw).map((uuid) => {
const el = h('span', { class: 'client-badge', role: 'img', hidden: true, 'aria-label': t('client.info.badges.title') });
void badgeInfo(uuid).then(({ known, name, description }) => {
if (!known) return;
el.title = description || name;
el.setAttribute('aria-label', name || description);
});
void badgeSvg(uuid, false).then((svg) => {
if (!svg) return;
el.replaceChildren(svgImage(svg));
el.hidden = false;
});
return el;
});
}
/**
* Official client info "Badge Showcase" (ts-badges detailMode): detailed artwork with the badge name, or the
* "No Badges" row. Shown there regardless of the tree option (settings.appearance.server.show.badges.disabled).
*/
export function badgeShowcase(raw) {
const uuids = parseClientBadges(raw);
if (!uuids.length) return h('div', { class: 'ts-badges-info-container' }, icon('empty'), h('span', { text: t('client.info.badges.empty') }));
return h('div', { class: 'ts-badges ts-account-badges-area' }, ...uuids.map((uuid) => {
const image = h('span', { class: 'ts-account-badges-icon' });
const label = h('span', { class: 'ts-account-badges-text' });
const cell = h('div', { class: 'ts-account-badges-icon-container' }, image, label);
void badgeInfo(uuid).then(({ known, name, description }) => {
label.textContent = known ? name : t('universal.unknown');
if (known && description) cell.title = description;
});
void badgeSvg(uuid, true).then((svg) => { if (svg) image.replaceChildren(svgImage(svg)); });
return cell;
}));
}