Add latest memories page (#33)
Some checks failed
Build / build (push) Has been cancelled

This commit is contained in:
foxtacles 2026-04-13 19:17:24 -07:00 committed by GitHub
parent daf4f6bc52
commit e36a158c69
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 551 additions and 27 deletions

View File

@ -74,6 +74,37 @@ app.get("/api/memory/:eventId", async (c) => {
});
});
// Public endpoint: latest 10 unique memories for the global feed
app.get("/api/memories/latest", async (c) => {
const results = await c.env.DB.prepare(
`SELECT mc.anim_index, mc.event_id, mc.completed_at, mc.participants, mc.language
FROM memory_completions mc
INNER JOIN (
SELECT event_id, MAX(completed_at) AS max_completed_at
FROM memory_completions
GROUP BY event_id
ORDER BY max_completed_at DESC
LIMIT 10
) latest ON mc.event_id = latest.event_id AND mc.completed_at = latest.max_completed_at
GROUP BY mc.event_id
ORDER BY mc.completed_at DESC`
).all<{ anim_index: number; event_id: string; completed_at: number; participants: string; language: string }>();
const entries = results.results.map((r) => {
let participants: unknown[];
try { participants = JSON.parse(r.participants || "[]"); } catch { participants = []; }
return {
animIndex: r.anim_index,
eventId: r.event_id,
completedAt: r.completed_at,
participants,
language: r.language,
};
});
return c.json({ entries });
});
// Auth middleware for protected routes
const authMiddleware = async (c: Context<{ Bindings: Env; Variables: Variables }>, next: Next) => {
const auth = createAuth(c.env);

View File

@ -23,6 +23,7 @@
import ConfigToast from './lib/ConfigToast.svelte';
import DebugPanel from './lib/DebugPanel.svelte';
import ScenePlayerPage from './lib/ScenePlayerPage.svelte';
import LatestMemoriesPage from './lib/LatestMemoriesPage.svelte';
import MultiplayerOverlay from './lib/multiplayer/MultiplayerOverlay.svelte';
import WhatsNewBanner from './lib/WhatsNewBanner.svelte';
import CanvasWrapper from './lib/CanvasWrapper.svelte';
@ -208,6 +209,9 @@
<div class="page-wrapper" class:active={$currentPage === 'memories'}>
<MemoriesPage />
</div>
<div class="page-wrapper" class:active={$currentPage === 'latest-memories'}>
<LatestMemoriesPage />
</div>
<div class="page-wrapper" class:active={$currentPage === 'scene-player'}>
<ScenePlayerPage />
</div>

View File

@ -23,6 +23,12 @@ export function navigateToMultiplayer() {
history.pushState({ page: 'multiplayer', fromApp: true }, '', '#multiplayer');
}
export function navigateToLatestMemories() {
if (get(currentPage) === 'latest-memories') return;
currentPage.set('latest-memories');
history.pushState({ page: 'latest-memories', fromApp: true }, '', '/memories');
}
export function navigateToMemory(eventId) {
scenePlayerEventId.set(eventId);
scenePlayerData.set(null);

View File

@ -3,10 +3,12 @@
// building and actor thumbnails on a background thread using OffscreenCanvas.
// The main thread only receives finished data URLs — zero blocking.
//
// Subscribes to memoryCompletions so thumbnails are (re-)generated whenever
// the set of needed actors changes (e.g. after login, logout→login, new completions).
// Uses a work-queue pattern: any source can enqueue charIndices via
// enqueueActors(). A single worker processes the queue; when it finishes,
// any newly-queued indices trigger another run automatically.
import { writable } from 'svelte/store';
import { memoryCompletions } from '../stores.js';
import { API_URL } from './config.js';
/** Maps location label (e.g. "Pizzeria") to a data URL of the rendered building. */
export const buildingThumbnails = writable({});
@ -14,41 +16,71 @@ export const buildingThumbnails = writable({});
/** Maps charIndex (0-65) to a data URL of the rendered actor. */
export const actorThumbnails = writable({});
/** Collect unique charIndices from completion data. */
function getNeededActors(completions) {
const indices = new Set();
for (const c of completions) {
if (c.participants) {
for (const p of c.participants) {
indices.add(p.charIndex);
}
}
}
return [...indices];
}
/** Prefetched global feed entries (null = not fetched, [] = fetched but empty). */
export const latestMemoriesCache = writable(null);
// --- Work queue state ---
let renderedActors = new Set();
let buildingsRendered = false;
let activeWorker = null;
let pendingActors = new Set(); // indices waiting to be rendered
/**
* Add charIndices to the render queue and flush if no worker is active.
* Safe to call from any source at any time indices are deduplicated.
*/
function enqueueActors(indices) {
for (const i of indices) {
if (!renderedActors.has(i)) pendingActors.add(i);
}
flushQueue();
}
/** If there's pending work and no active worker, spawn one. */
function flushQueue() {
if (activeWorker) return;
const includeBuildings = !buildingsRendered;
const batch = [...pendingActors];
pendingActors.clear();
if (batch.length === 0 && !includeBuildings) return;
spawnWorker(batch, includeBuildings);
}
export function initThumbnails() {
memoryCompletions.subscribe(completions => {
if (completions === null) return;
const needed = getNeededActors(completions);
const missing = needed.filter(i => !renderedActors.has(i));
if (missing.length === 0 && buildingsRendered) return;
spawnWorker(missing, !buildingsRendered);
const indices = [];
for (const c of completions) {
if (c.participants) {
for (const p of c.participants) indices.push(p.charIndex);
}
}
enqueueActors(indices);
});
// Prefetch global feed so its actor thumbnails render alongside the user's own
prefetchLatestMemories();
}
async function prefetchLatestMemories() {
try {
const res = await fetch(`${API_URL}/api/memories/latest`);
if (!res.ok) return;
const data = await res.json();
const entries = data.entries || [];
latestMemoriesCache.set(entries);
const indices = [];
for (const e of entries) {
for (const p of e.participants) indices.push(p.charIndex);
}
if (indices.length > 0) enqueueActors(indices);
} catch {
// Non-critical — page will show fallback letters
}
}
function spawnWorker(actorIndices, includeBuildings) {
if (activeWorker) {
activeWorker.terminate();
activeWorker = null;
}
try {
const worker = new Worker(
new URL('./thumbnails.worker.js', import.meta.url),
@ -72,6 +104,8 @@ function spawnWorker(actorIndices, includeBuildings) {
for (const i of actorIndices) renderedActors.add(i);
worker.terminate();
activeWorker = null;
// Process anything that was enqueued while we were busy
flushQueue();
break;
case 'error':
console.warn('[Thumbnails] Worker error:', e.data.message);

View File

@ -6,7 +6,7 @@
import { API_URL } from '../core/config.js';
import { showToast } from '../core/toast.js';
import { currentPage } from '../stores.js';
import { navigateTo, navigateToMultiplayer } from '../core/navigation.js';
import { navigateTo, navigateToMultiplayer, navigateToLatestMemories } from '../core/navigation.js';
import SignInModal from './SignInModal.svelte';
import DiscordIcon from './icons/DiscordIcon.svelte';
@ -134,6 +134,10 @@
<svelte:window onclick={handleClickOutside} onkeydown={handleDeleteKeydown} />
<div class="nav-bar">
<button class="nav-circle memories-nav" onclick={navigateToLatestMemories} title="Latest Memories">
<img class="memories-nav-img" src="images/nick_closeup.webp" alt="Latest Memories" />
</button>
<div class="nav-menu-wrapper">
<button class="nav-circle" bind:this={navButtonEl} onclick={() => toggleMenu('nav')} title="Menu">
<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="1.8" stroke-linecap="round">
@ -266,6 +270,14 @@
pointer-events: none;
}
.memories-nav-img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 50%;
transform: scale(1.6);
}
.avatar-img {
position: absolute;
inset: 0;

View File

@ -0,0 +1,370 @@
<script>
import { actorThumbnails, latestMemoriesCache } from '../core/thumbnails.js';
import { AnimationTitles } from './multiplayer/animationCatalog.js';
import { ActorDisplayNames } from '../core/savegame/actorConstants.js';
import { navigateToMemory, navigateTo, formatDateTime } from '../core/navigation.js';
import BackButton from './BackButton.svelte';
const AV_CAP = 3;
function formatDateShort(timestamp) {
if (!timestamp) return '';
const d = new Date(timestamp * 1000);
const diffMs = Date.now() - d;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'Now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
$: loading = $latestMemoriesCache === null;
$: entries = $latestMemoriesCache || [];
function handleCardClick(e, eventId) {
e.preventDefault();
navigateToMemory(eventId);
}
function handleMemoriesLink(e) {
e.preventDefault();
navigateTo('memories');
}
</script>
{#snippet avatarStack(participants)}
<div class="card-avatars">
{#each participants.slice(0, AV_CAP) as p}
<div class="card-av" title="{p.displayName} as {ActorDisplayNames[p.charIndex] || `#${p.charIndex}`}">
{#if $actorThumbnails[p.charIndex]}
<img src={$actorThumbnails[p.charIndex]} alt={ActorDisplayNames[p.charIndex]} />
{:else}
<span class="card-av-fallback">{(ActorDisplayNames[p.charIndex] || '?')[0]}</span>
{/if}
</div>
{/each}
{#if participants.length > AV_CAP}
<div class="card-av card-av-overflow">+{participants.length - AV_CAP}</div>
{/if}
</div>
{/snippet}
<div class="page-content">
<BackButton />
<div class="page-inner-content latest-inner">
<!-- Hero -->
<div class="hero">
<img class="hero-avatar" src="images/nick_closeup.webp" alt="Nick Brick" />
<div class="hero-text">
<h1>Latest Memories</h1>
<p class="hero-subtitle">Players across the island are reenacting animations together in multiplayer. Here are the most recent ones. Want to start collecting your own? Visit <a href="#memories" onclick={handleMemoriesLink}>Nick Brick's Memories</a> to learn more.</p>
</div>
</div>
<!-- Content -->
{#if loading}
<div class="feed-list">
{#each Array(10) as _}
<div class="feed-card skeleton-card">
<div class="card-body">
<span class="skeleton-line skeleton-title skeleton-pulse"></span>
<span class="skeleton-line skeleton-names skeleton-pulse"></span>
<span class="skeleton-line skeleton-time skeleton-pulse"></span>
</div>
<div class="card-avatars">
<div class="card-av skeleton-pulse"></div>
<div class="card-av skeleton-pulse"></div>
</div>
</div>
{/each}
</div>
{:else}
<div class="feed-list">
{#each entries as entry}
<a class="feed-card" href="/memory/{entry.eventId}" onclick={e => handleCardClick(e, entry.eventId)}>
<div class="card-body">
<span class="card-title">{AnimationTitles[entry.animIndex] || `Animation #${entry.animIndex}`}</span>
<div class="card-participants">
{#each entry.participants as p, idx}
{#if idx < AV_CAP}
{#if idx > 0}<span class="card-sep">&middot;</span>{/if}
<span class="card-name">{p.displayName}<span class="card-char">as {ActorDisplayNames[p.charIndex] || `#${p.charIndex}`}</span></span>
{/if}
{/each}
{#if entry.participants.length > AV_CAP}
<span class="card-more">+{entry.participants.length - 3}</span>
{/if}
</div>
<span class="card-time" title={formatDateTime(entry.completedAt)}>{formatDateShort(entry.completedAt)}</span>
</div>
{@render avatarStack(entry.participants)}
</a>
{/each}
</div>
{/if}
</div>
</div>
<style>
.latest-inner {
display: flex;
flex-direction: column;
align-items: stretch;
text-align: left;
}
/* --- Hero --- */
.hero {
display: flex;
align-items: center;
gap: 14px;
padding-bottom: 16px;
}
.hero-avatar {
width: 64px;
height: 64px;
border-radius: 50%;
object-fit: cover;
flex-shrink: 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}
.hero-text {
flex: 1;
min-width: 0;
}
.hero-text h1 {
font-size: 1.05em;
font-weight: 700;
color: var(--color-text-light);
margin: 0;
line-height: 1.2;
}
.hero-subtitle {
font-size: 0.75em;
color: var(--color-text-muted);
margin: 4px 0 0;
line-height: 1.4;
}
.hero-subtitle a {
color: var(--color-primary);
text-decoration: none;
}
.hero-subtitle a:hover {
text-decoration: underline;
}
/* --- Feed list --- */
.feed-list {
display: flex;
flex-direction: column;
}
.feed-card {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 8px;
min-height: 52px;
border-bottom: 1px solid var(--color-border-dark);
cursor: pointer;
transition: background 0.12s;
text-decoration: none;
color: inherit;
border-radius: 4px;
}
.feed-card:last-child {
border-bottom: none;
}
.feed-card:hover {
background: rgba(255, 255, 255, 0.03);
}
/* --- Card body (left, fills available space) --- */
.card-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.card-title {
font-size: 0.85em;
font-weight: 600;
color: var(--color-text-light);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.3;
}
.card-participants {
display: flex;
align-items: baseline;
overflow: hidden;
white-space: nowrap;
line-height: 1.3;
}
.card-name {
font-size: 0.72em;
color: var(--color-text-medium);
overflow: hidden;
text-overflow: ellipsis;
}
.card-char {
font-size: 0.9em;
color: var(--color-text-muted);
margin-left: 3px;
}
.card-sep {
color: var(--color-text-muted);
margin: 0 5px;
flex-shrink: 0;
font-size: 0.72em;
}
.card-more {
font-size: 0.68em;
color: var(--color-text-muted);
margin-left: 5px;
flex-shrink: 0;
}
.card-time {
font-size: 0.65em;
color: var(--color-text-muted);
white-space: nowrap;
line-height: 1.3;
}
/* --- Avatar Stack (right side) --- */
.card-avatars {
display: flex;
flex-shrink: 0;
align-items: center;
}
.card-av {
width: 28px;
height: 28px;
border-radius: 50%;
overflow: hidden;
background: var(--color-bg-input);
border: 1.5px solid var(--color-bg-elevated);
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.card-av + .card-av {
margin-left: -8px;
}
.card-av img {
width: 100%;
height: 100%;
object-fit: contain;
}
.card-av-fallback {
font-size: 11px;
font-weight: 700;
color: var(--color-text-muted);
text-transform: uppercase;
}
.card-av-overflow {
font-size: 9px;
font-weight: 700;
color: var(--color-text-muted);
background: var(--color-border-dark);
border-color: var(--color-bg-elevated);
}
/* --- Skeleton loading --- */
.skeleton-card {
pointer-events: none;
}
.skeleton-pulse {
animation: skeleton-fade 1.2s ease-in-out infinite;
}
.card-av.skeleton-pulse {
background: var(--color-border-dark);
}
.skeleton-line {
display: block;
background: var(--color-border-dark);
border-radius: 3px;
}
.skeleton-title {
width: 55%;
height: 14px;
}
.skeleton-names {
width: 75%;
height: 12px;
}
.skeleton-time {
width: 30%;
height: 11px;
}
@keyframes skeleton-fade {
0%, 100% { opacity: 0.3; }
50% { opacity: 0.6; }
}
/* --- Responsive --- */
@media (max-width: 480px) {
.hero-text h1 {
font-size: 0.9em;
}
.hero-avatar {
width: 48px;
height: 48px;
}
.card-av {
width: 24px;
height: 24px;
}
.card-av + .card-av {
margin-left: -6px;
}
.card-char {
display: none;
}
.feed-card {
gap: 10px;
min-height: 44px;
}
}
</style>

View File

@ -26,6 +26,7 @@ function parseHash(hash) {
// Match a pathname against /memory/:id or /scene/:encoded path routes.
// Returns { eventId } or { sceneData } on match, null otherwise.
export function matchPathRoute(path) {
if (path === '/memories') return { latestMemories: true };
const memoryMatch = path.match(/^\/memory\/([A-Za-z0-9_-]+)$/);
if (memoryMatch) return { eventId: memoryMatch[1] };
const sceneMatch = path.match(/^\/scene\/([A-Za-z0-9_-]+)$/);
@ -37,7 +38,10 @@ export function matchPathRoute(path) {
export function parseRoute() {
if (typeof window === 'undefined') return { page: 'main', room: null };
const match = matchPathRoute(window.location.pathname);
if (match) return { page: 'scene-player', room: null, ...match };
if (match) {
if (match.latestMemories) return { page: 'latest-memories', room: null };
return { page: 'scene-player', room: null, ...match };
}
return parseHash(window.location.hash);
}

View File

@ -162,6 +162,54 @@ async function handleScene(encoded: string, request: Request, env: Env): Promise
}
}
async function handleLatestMemories(request: Request, env: Env): Promise<Response> {
let html = await getIndexHtml(request, env);
const url = new URL(request.url);
html = injectOgTags(
html,
'Latest Memories',
'The most recent animations reenacted by players across all LEGO Islands.',
url.href
);
const origin = url.origin;
try {
const apiRes = await fetch(`${env.API_URL}/api/memories/latest`);
if (apiRes.ok) {
const data = await apiRes.json() as {
entries: Array<{
animIndex: number;
eventId: string;
completedAt: number;
participants: Participant[];
language: string;
}>;
};
const titles = AnimationTitles as Record<string, string>;
const items = data.entries.map((entry) => {
const title = escapeHtml(titles[String(entry.animIndex)] || `Animation #${entry.animIndex}`);
const desc = escapeHtml(buildDescription(entry.participants, entry.completedAt));
const url = `${origin}/memory/${escapeHtml(entry.eventId)}`;
return `<li><a href="${url}"><strong>${title}</strong><br>${desc}</a></li>`;
}).join('\n');
const ssrBlock = `<div id="ssr-latest-memories" style="display:none" aria-hidden="true"><h1>Latest Memories</h1><p>The most recent animations reenacted by players across all LEGO Islands.</p><ol>${items}</ol></div>`;
html = html.replace('</body>', `${ssrBlock}\n</body>`);
}
} catch {
// Fail gracefully — SPA will fetch client-side
}
return new Response(html, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'public, max-age=300',
},
});
}
async function handleSitemap(request: Request, env: Env): Promise<Response> {
const origin = new URL(request.url).origin;
@ -179,6 +227,9 @@ async function handleSitemap(request: Request, env: Env): Promise<Response> {
` <url>`,
` <loc>${escapeHtml(origin)}/</loc>`,
` </url>`,
` <url>`,
` <loc>${escapeHtml(origin)}/memories</loc>`,
` </url>`,
];
for (const entry of data.entries) {
@ -218,6 +269,10 @@ export default {
return handleSitemap(request, env);
}
if (path === '/memories') {
return handleLatestMemories(request, env);
}
const memoryMatch = path.match(/^\/memory\/([A-Za-z0-9_-]+)$/);
if (memoryMatch) {
return handleMemory(memoryMatch[1], request, env);

View File

@ -21,6 +21,10 @@ bucket_name = "isle"
[env.production.vars]
API_URL = "https://api.isle.pizza"
[[env.production.routes]]
pattern = "isle.pizza/memories"
zone_name = "isle.pizza"
[[env.production.routes]]
pattern = "isle.pizza/memory/*"
zone_name = "isle.pizza"
@ -33,6 +37,10 @@ zone_name = "isle.pizza"
pattern = "isle.pizza/sitemap.xml"
zone_name = "isle.pizza"
[[env.production.routes]]
pattern = "dev.isle.pizza/memories"
zone_name = "isle.pizza"
[[env.production.routes]]
pattern = "dev.isle.pizza/memory/*"
zone_name = "isle.pizza"