Merge branch 'feat/diashow-completeness-display'

This commit is contained in:
MechaCat02
2026-07-19 17:53:57 +02:00
11 changed files with 643 additions and 151 deletions

View File

@@ -0,0 +1,28 @@
-- Drop the view (frees the column dependency), remove the column, then restore the
-- pre-016 view definition (matches migration 011).
DROP VIEW IF EXISTS v_feed;
ALTER TABLE upload DROP COLUMN display_path;
CREATE VIEW v_feed AS
SELECT
u.id,
u.event_id,
u.user_id,
usr.display_name AS uploader_name,
usr.is_banned,
usr.uploads_hidden,
u.preview_path,
u.thumbnail_path,
u.mime_type,
u.caption,
u.created_at,
COUNT(DISTINCT l.user_id) AS like_count,
COUNT(DISTINCT c.id) AS comment_count
FROM upload u
JOIN "user" usr ON u.user_id = usr.id
LEFT JOIN "like" l ON l.upload_id = u.id
LEFT JOIN comment c ON c.upload_id = u.id AND c.deleted_at IS NULL
WHERE u.deleted_at IS NULL
AND usr.uploads_hidden = FALSE
AND usr.is_banned = FALSE
GROUP BY u.id, usr.display_name, usr.is_banned, usr.uploads_hidden;

View File

@@ -0,0 +1,34 @@
-- Display derivative: a big-screen-quality image (~2048px long edge) for the diashow.
-- The 800px `preview_path` is sized for phone feeds (data saver); upscaled on a projector
-- it looks soft. The diashow uses `display_path` instead — bounded in size (safe to decode
-- on weak kiosk hardware) yet sharp on 1080p/4K. NULL until the compression worker (or the
-- one-time backfill) generates it; consumers fall back to the original when absent.
ALTER TABLE upload ADD COLUMN display_path TEXT;
-- Recreate (not CREATE OR REPLACE, which only allows appending columns at the end) so the
-- new column can sit alongside preview_path/thumbnail_path.
DROP VIEW IF EXISTS v_feed;
CREATE VIEW v_feed AS
SELECT
u.id,
u.event_id,
u.user_id,
usr.display_name AS uploader_name,
usr.is_banned,
usr.uploads_hidden,
u.preview_path,
u.thumbnail_path,
u.display_path,
u.mime_type,
u.caption,
u.created_at,
COUNT(DISTINCT l.user_id) AS like_count,
COUNT(DISTINCT c.id) AS comment_count
FROM upload u
JOIN "user" usr ON u.user_id = usr.id
LEFT JOIN "like" l ON l.upload_id = u.id
LEFT JOIN comment c ON c.upload_id = u.id AND c.deleted_at IS NULL
WHERE u.deleted_at IS NULL
AND usr.uploads_hidden = FALSE
AND usr.is_banned = FALSE
GROUP BY u.id, usr.display_name, usr.is_banned, usr.uploads_hidden;

View File

@@ -27,6 +27,8 @@ pub struct FeedUpload {
pub uploader_name: String, pub uploader_name: String,
pub preview_url: Option<String>, pub preview_url: Option<String>,
pub thumbnail_url: Option<String>, pub thumbnail_url: Option<String>,
/// Big-screen (~2048px) variant for the diashow. Absent until the derivative exists.
pub display_url: Option<String>,
pub mime_type: String, pub mime_type: String,
pub caption: Option<String>, pub caption: Option<String>,
pub like_count: i64, pub like_count: i64,
@@ -48,6 +50,7 @@ struct FeedRow {
uploader_name: String, uploader_name: String,
preview_path: Option<String>, preview_path: Option<String>,
thumbnail_path: Option<String>, thumbnail_path: Option<String>,
display_path: Option<String>,
mime_type: String, mime_type: String,
caption: Option<String>, caption: Option<String>,
like_count: i64, like_count: i64,
@@ -94,7 +97,8 @@ pub async fn feed(
let tag = hashtag.trim().trim_start_matches('#').to_lowercase(); let tag = hashtag.trim().trim_start_matches('#').to_lowercase();
sqlx::query_as::<_, FeedRow>( sqlx::query_as::<_, FeedRow>(
"SELECT v.id, v.user_id, v.uploader_name, v.preview_path, v.thumbnail_path, "SELECT v.id, v.user_id, v.uploader_name, v.preview_path, v.thumbnail_path,
v.mime_type, v.caption, v.like_count, v.comment_count, v.created_at v.display_path, v.mime_type, v.caption, v.like_count, v.comment_count,
v.created_at
FROM v_feed v FROM v_feed v
JOIN upload_hashtag uh ON uh.upload_id = v.id JOIN upload_hashtag uh ON uh.upload_id = v.id
JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1 JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1
@@ -113,7 +117,7 @@ pub async fn feed(
} else { } else {
sqlx::query_as::<_, FeedRow>( sqlx::query_as::<_, FeedRow>(
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path, "SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
mime_type, caption, like_count, comment_count, created_at display_path, mime_type, caption, like_count, comment_count, created_at
FROM v_feed FROM v_feed
WHERE event_id = $1 WHERE event_id = $1
AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3)) AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3))
@@ -154,6 +158,10 @@ pub async fn feed(
.thumbnail_path .thumbnail_path
.as_ref() .as_ref()
.map(|_| format!("/api/v1/upload/{}/thumbnail", r.id)); .map(|_| format!("/api/v1/upload/{}/thumbnail", r.id));
let display_url = r
.display_path
.as_ref()
.map(|_| format!("/api/v1/upload/{}/display", r.id));
FeedUpload { FeedUpload {
liked_by_me: liked_set.contains(&r.id), liked_by_me: liked_set.contains(&r.id),
id: r.id, id: r.id,
@@ -161,6 +169,7 @@ pub async fn feed(
uploader_name: r.uploader_name, uploader_name: r.uploader_name,
preview_url, preview_url,
thumbnail_url, thumbnail_url,
display_url,
mime_type: r.mime_type, mime_type: r.mime_type,
caption: r.caption, caption: r.caption,
like_count: r.like_count, like_count: r.like_count,
@@ -247,7 +256,7 @@ pub async fn feed_delta(
// response's `server_time`, so this doesn't re-fetch on every subsequent delta. // response's `server_time`, so this doesn't re-fetch on every subsequent delta.
let rows = sqlx::query_as::<_, FeedRow>( let rows = sqlx::query_as::<_, FeedRow>(
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path, "SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
mime_type, caption, like_count, comment_count, created_at display_path, mime_type, caption, like_count, comment_count, created_at
FROM v_feed FROM v_feed
WHERE event_id = $1 AND created_at >= $2 WHERE event_id = $1 AND created_at >= $2
ORDER BY created_at DESC, id DESC ORDER BY created_at DESC, id DESC
@@ -304,6 +313,10 @@ pub async fn feed_delta(
.thumbnail_path .thumbnail_path
.as_ref() .as_ref()
.map(|_| format!("/api/v1/upload/{}/thumbnail", r.id)), .map(|_| format!("/api/v1/upload/{}/thumbnail", r.id)),
display_url: r
.display_path
.as_ref()
.map(|_| format!("/api/v1/upload/{}/display", r.id)),
mime_type: r.mime_type, mime_type: r.mime_type,
caption: r.caption, caption: r.caption,
like_count: r.like_count, like_count: r.like_count,

View File

@@ -747,6 +747,30 @@ pub async fn get_preview(
.await .await
} }
/// Streaming access to an upload's big-screen **display** derivative (~2048px), used by the
/// diashow. Gated identically to [`get_preview`]. 404s when the derivative doesn't exist yet
/// (still compressing, or an old upload the backfill hasn't reached) — the diashow then falls
/// back to the original.
pub async fn get_display(
State(state): State<AppState>,
Path(upload_id): Path<Uuid>,
) -> Result<axum::response::Response, AppError> {
let media = Upload::find_visible_media(&state.pool, upload_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
let rel = media
.display_path
.ok_or_else(|| AppError::NotFound("Anzeige nicht verfügbar.".into()))?;
let absolute = state.config.media_path.join(&rel);
stream_media_file(
&absolute,
"image/jpeg".to_string(),
"inline",
"private, max-age=300",
)
.await
}
/// Streaming access to an upload's **thumbnail** (video poster). Gated identically to /// Streaming access to an upload's **thumbnail** (video poster). Gated identically to
/// [`get_preview`]. /// [`get_preview`].
pub async fn get_thumbnail( pub async fn get_thumbnail(

View File

@@ -45,6 +45,11 @@ async fn main() -> Result<()> {
let state = AppState::new(pool.clone(), config.clone()); let state = AppState::new(pool.clone(), config.clone());
// Backfill the big-screen display derivative for image uploads processed before it
// existed (v0.17.x). Fire-and-forget behind the compression semaphore; each upload
// falls back to its original in the diashow until its display is generated.
state.compression.backfill_missing_display().await;
// Re-spawn exports for events that were released but whose keepsake never finished // Re-spawn exports for events that were released but whose keepsake never finished
// (crash mid-export). Needs the media/export paths + SSE sender, so it runs here // (crash mid-export). Needs the media/export paths + SSE sender, so it runs here
// rather than inside `startup_recovery`. Fire-and-forget: the workers run in the // rather than inside `startup_recovery`. Fire-and-forget: the workers run in the
@@ -106,6 +111,10 @@ async fn main() -> Result<()> {
"/api/v1/upload/{id}/preview", "/api/v1/upload/{id}/preview",
get(handlers::upload::get_preview), get(handlers::upload::get_preview),
) )
.route(
"/api/v1/upload/{id}/display",
get(handlers::upload::get_display),
)
.route( .route(
"/api/v1/upload/{id}/thumbnail", "/api/v1/upload/{id}/thumbnail",
get(handlers::upload::get_thumbnail), get(handlers::upload::get_thumbnail),
@@ -241,6 +250,10 @@ async fn main() -> Result<()> {
"/media/previews", "/media/previews",
get(|| async { axum::http::StatusCode::NOT_FOUND }), get(|| async { axum::http::StatusCode::NOT_FOUND }),
) )
.nest_service(
"/media/displays",
get(|| async { axum::http::StatusCode::NOT_FOUND }),
)
.nest_service( .nest_service(
"/media/thumbnails", "/media/thumbnails",
get(|| async { axum::http::StatusCode::NOT_FOUND }), get(|| async { axum::http::StatusCode::NOT_FOUND }),

View File

@@ -46,6 +46,7 @@ pub struct VisibleMedia {
pub original_path: String, pub original_path: String,
pub preview_path: Option<String>, pub preview_path: Option<String>,
pub thumbnail_path: Option<String>, pub thumbnail_path: Option<String>,
pub display_path: Option<String>,
pub mime_type: String, pub mime_type: String,
} }
@@ -93,7 +94,7 @@ impl Upload {
id: Uuid, id: Uuid,
) -> Result<Option<VisibleMedia>, sqlx::Error> { ) -> Result<Option<VisibleMedia>, sqlx::Error> {
sqlx::query_as::<_, VisibleMedia>( sqlx::query_as::<_, VisibleMedia>(
"SELECT up.original_path, up.preview_path, up.thumbnail_path, up.mime_type "SELECT up.original_path, up.preview_path, up.thumbnail_path, up.display_path, up.mime_type
FROM upload up FROM upload up
JOIN \"user\" u ON u.id = up.user_id JOIN \"user\" u ON u.id = up.user_id
WHERE up.id = $1 AND up.deleted_at IS NULL WHERE up.id = $1 AND up.deleted_at IS NULL
@@ -134,6 +135,19 @@ impl Upload {
Ok(()) Ok(())
} }
pub async fn set_display_path(
pool: &PgPool,
id: Uuid,
display_path: &str,
) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE upload SET display_path = $2 WHERE id = $1")
.bind(id)
.bind(display_path)
.execute(pool)
.await?;
Ok(())
}
pub async fn set_thumbnail_path( pub async fn set_thumbnail_path(
pool: &PgPool, pool: &PgPool,
id: Uuid, id: Uuid,

View File

@@ -112,11 +112,12 @@ impl CompressionWorker {
let original = self.media_path.join(original_path); let original = self.media_path.join(original_path);
if mime_type.starts_with("image/") { if mime_type.starts_with("image/") {
let preview_rel = self let (preview_rel, display_rel) = self
.generate_image_preview(upload_id, &original, mime_type) .generate_image_derivatives(upload_id, &original, mime_type)
.await?; .await?;
Upload::set_preview_path(&self.pool, upload_id, &preview_rel).await?; Upload::set_preview_path(&self.pool, upload_id, &preview_rel).await?;
tracing::info!("preview generated for upload {upload_id}"); Upload::set_display_path(&self.pool, upload_id, &display_rel).await?;
tracing::info!("preview + display generated for upload {upload_id}");
} else if mime_type.starts_with("video/") { } else if mime_type.starts_with("video/") {
let thumb_rel = self.generate_video_thumbnail(upload_id, &original).await?; let thumb_rel = self.generate_video_thumbnail(upload_id, &original).await?;
Upload::set_thumbnail_path(&self.pool, upload_id, &thumb_rel).await?; Upload::set_thumbnail_path(&self.pool, upload_id, &thumb_rel).await?;
@@ -127,20 +128,33 @@ impl CompressionWorker {
Ok(()) Ok(())
} }
async fn generate_image_preview( /// Longest edge of the big-screen "display" derivative used by the diashow. Sized to be
/// sharp on 1080p/4K while staying bounded (a ~2048px JPEG decodes to ~16 MB — trivial
/// for any kiosk, unlike a raw multi-thousand-pixel original).
const DISPLAY_MAX_EDGE: u32 = 2048;
/// Longest edge of the phone-feed "preview" (data-saver default).
const PREVIEW_MAX_EDGE: u32 = 800;
/// Decode the image ONCE and emit both derivatives — the 800px `preview` (phone feed)
/// and the 2048px `display` (diashow). Returns `(preview_rel, display_rel)`.
async fn generate_image_derivatives(
&self, &self,
upload_id: Uuid, upload_id: Uuid,
original: &Path, original: &Path,
mime_type: &str, mime_type: &str,
) -> Result<String> { ) -> Result<(String, String)> {
let previews_dir = self.media_path.join("previews"); let previews_dir = self.media_path.join("previews");
let displays_dir = self.media_path.join("displays");
tokio::fs::create_dir_all(&previews_dir).await?; tokio::fs::create_dir_all(&previews_dir).await?;
tokio::fs::create_dir_all(&displays_dir).await?;
let preview_filename = format!("{upload_id}.jpg"); let filename = format!("{upload_id}.jpg");
let preview_path = previews_dir.join(&preview_filename); let preview_path = previews_dir.join(&filename);
let display_path = displays_dir.join(&filename);
let original = original.to_path_buf(); let original = original.to_path_buf();
let preview_path_clone = preview_path.clone();
let mime_owned = mime_type.to_string(); let mime_owned = mime_type.to_string();
let preview_max = Self::PREVIEW_MAX_EDGE;
let display_max = Self::DISPLAY_MAX_EDGE;
// Run blocking image operations in a spawn_blocking task // Run blocking image operations in a spawn_blocking task
tokio::task::spawn_blocking(move || -> Result<()> { tokio::task::spawn_blocking(move || -> Result<()> {
@@ -160,11 +174,29 @@ impl CompressionWorker {
reader.limits(limits); reader.limits(limits);
let img = reader.decode().context("failed to decode image")?; let img = reader.decode().context("failed to decode image")?;
// Resize to max 800px wide, preserving aspect ratio // Preview: max 800px, preserving aspect ratio (data-saver feed).
let preview = img.resize(800, 800, image::imageops::FilterType::Lanczos3); img.resize(
preview preview_max,
.save_with_format(&preview_path_clone, image::ImageFormat::Jpeg) preview_max,
.context("failed to save preview")?; image::imageops::FilterType::Lanczos3,
)
.save_with_format(&preview_path, image::ImageFormat::Jpeg)
.context("failed to save preview")?;
// Display: max 2048px for the diashow. Only DOWNSCALE — never upscale a smaller
// original (that adds bytes with no quality gain); re-encode it as JPEG as-is.
let display = if img.width() > display_max || img.height() > display_max {
img.resize(
display_max,
display_max,
image::imageops::FilterType::Lanczos3,
)
} else {
img
};
display
.save_with_format(&display_path, image::ImageFormat::Jpeg)
.context("failed to save display")?;
// If the original is PNG, try lossless compression in-place // If the original is PNG, try lossless compression in-place
if mime_owned == "image/png" { if mime_owned == "image/png" {
@@ -183,7 +215,61 @@ impl CompressionWorker {
}) })
.await??; .await??;
Ok(format!("previews/{preview_filename}")) Ok((
format!("previews/{filename}"),
format!("displays/{filename}"),
))
}
/// One-time backfill: existing image uploads processed before the display derivative
/// existed have a preview but no `display_path`. Regenerate both derivatives for them
/// (decode is cheap and idempotent) and set the path. Unlike the failure path in
/// `process`, a backfill error is logged and skipped — it must NEVER soft-delete an
/// upload that already has a working preview. Fire-and-forget from startup.
pub async fn backfill_missing_display(&self) {
let rows = sqlx::query_as::<_, (Uuid, String, String)>(
"SELECT id, original_path, mime_type FROM upload
WHERE display_path IS NULL AND preview_path IS NOT NULL
AND deleted_at IS NULL AND mime_type LIKE 'image/%'",
)
.fetch_all(&self.pool)
.await;
let rows = match rows {
Ok(r) => r,
Err(e) => {
tracing::warn!(error = ?e, "display backfill query failed");
return;
}
};
if rows.is_empty() {
return;
}
tracing::info!(
"backfilling display derivative for {} upload(s)",
rows.len()
);
for (id, original_path, mime_type) in rows {
let worker = self.clone();
tokio::spawn(async move {
let _permit = worker.semaphore.acquire().await;
let original = worker.media_path.join(&original_path);
match worker
.generate_image_derivatives(id, &original, &mime_type)
.await
{
Ok((preview_rel, display_rel)) => {
let _ = Upload::set_preview_path(&worker.pool, id, &preview_rel).await;
let _ = Upload::set_display_path(&worker.pool, id, &display_rel).await;
tracing::info!("display backfilled for upload {id}");
}
Err(e) => {
// Leave the existing preview intact; the diashow falls back to the
// original for this upload until a later successful pass.
tracing::warn!(error = ?e, %id, "display backfill failed; leaving as-is");
}
}
});
}
} }
async fn generate_video_thumbnail(&self, upload_id: Uuid, original: &Path) -> Result<String> { async fn generate_video_thumbnail(&self, upload_id: Uuid, original: &Path) -> Result<String> {

View File

@@ -0,0 +1,141 @@
import { describe, it, expect } from 'vitest';
import { SlideQueue } from './queue';
import type { FeedUpload } from '$lib/types';
// Minimal FeedUpload factory — the queue only reads id, user_id, preview_url, thumbnail_url.
const up = (
id: string,
opts: { user?: string; preview?: boolean; thumb?: boolean } = {}
): FeedUpload =>
({
id,
user_id: opts.user ?? 'u1',
preview_url: opts.preview === false ? null : `/p/${id}`,
thumbnail_url: opts.thumb ? `/t/${id}` : null
}) as unknown as FeedUpload;
const drain = (q: SlideQueue, n: number): string[] => {
const out: string[] = [];
for (let i = 0; i < n; i++) {
const s = q.next();
if (!s) break;
out.push(s.id);
}
return out;
};
describe('SlideQueue.merge', () => {
it('dedups by id and reports the count actually added', () => {
const q = new SlideQueue();
expect(q.merge([up('a'), up('b')], { live: false })).toBe(2);
expect(q.merge([up('b'), up('c')], { live: false })).toBe(1); // b already known
expect(q.stats().known).toBe(3);
});
it('skips uploads with no preview or thumbnail (still compressing)', () => {
const q = new SlideQueue();
const added = q.merge([up('a'), up('pending', { preview: false }), up('t', { thumb: true })], {
live: false
});
expect(added).toBe(2); // a + t; pending has neither preview nor thumb
expect(q.has('pending')).toBe(false);
});
it('live items drain before the shuffle pool', () => {
const q = new SlideQueue();
q.merge([up('s1'), up('s2')], { live: false });
q.merge([up('L1'), up('L2')], { live: true });
// Live first, in FIFO order, then the pool.
expect(drain(q, 2)).toEqual(['L1', 'L2']);
expect(drain(q, 2).sort()).toEqual(['s1', 's2']);
});
});
describe('SlideQueue completeness', () => {
it('eventually shows every merged item across one full cycle (500 items, paged)', () => {
const q = new SlideQueue();
const all = new Set<string>();
// Simulate a paginated load of 500 across 5 pages of 100.
for (let page = 0; page < 5; page++) {
const batch = Array.from({ length: 100 }, (_, i) => {
const id = `img-${page * 100 + i}`;
all.add(id);
return up(id);
});
q.merge(batch, { live: false });
}
q.reshuffle();
expect(q.stats().known).toBe(500);
// Drain generously more than the set size; every id must appear at least once.
const shown = new Set(drain(q, 500 + 50));
for (const id of all) expect(shown.has(id)).toBe(true);
});
it('a burst of live items are all shown before falling back to the pool', () => {
const q = new SlideQueue();
q.merge([up('old1'), up('old2')], { live: false });
const burst = Array.from({ length: 250 }, (_, i) => up(`burst-${i}`));
q.merge(burst, { live: true });
const firstBurst = drain(q, 250);
expect(new Set(firstBurst).size).toBe(250);
expect(firstBurst.every((id) => id.startsWith('burst-'))).toBe(true);
});
});
describe('SlideQueue removals', () => {
it('remove() reports whether the removed id was current', () => {
const q = new SlideQueue();
q.merge([up('a'), up('b')], { live: false });
expect(q.remove('a', 'a').wasCurrent).toBe(true);
expect(q.remove('b', 'a').wasCurrent).toBe(false);
expect(q.stats().known).toBe(0);
});
it('removeByUser() evicts a whole user and flags current', () => {
const q = new SlideQueue();
q.merge([up('a', { user: 'x' }), up('b', { user: 'y' }), up('c', { user: 'x' })], {
live: false
});
const res = q.removeByUser('x', 'c');
expect(res.wasCurrent).toBe(true);
expect(q.has('a')).toBe(false);
expect(q.has('c')).toBe(false);
expect(q.has('b')).toBe(true);
});
});
describe('SlideQueue.knownIds + reconcile eviction', () => {
it('knownIds snapshots exactly the current set', () => {
const q = new SlideQueue();
q.merge([up('a'), up('b')], { live: false });
expect(new Set(q.knownIds())).toEqual(new Set(['a', 'b']));
});
// Mirrors the page's reconcile: evict only pre-scan ids the feed no longer lists, so an
// upload that lands mid-scan survives.
const reconcileEvict = (q: SlideQueue, before: Set<string>, seen: Set<string>) => {
for (const id of before) if (!seen.has(id)) q.remove(id, null);
};
it('drops a slide the server no longer lists (deleted/banned we missed)', () => {
const q = new SlideQueue();
q.merge([up('a'), up('b'), up('c')], { live: false });
const before = new Set(q.knownIds());
reconcileEvict(q, before, new Set(['a', 'c'])); // feed no longer has b
expect(q.has('b')).toBe(false);
expect(q.has('a')).toBe(true);
expect(q.has('c')).toBe(true);
});
it('never evicts an upload that arrived mid-scan (not in the pre-scan snapshot)', () => {
const q = new SlideQueue();
q.merge([up('a'), up('b')], { live: false });
const before = new Set(q.knownIds()); // {a, b}
// A live upload lands during the scan; the scan's `seen` predates it.
q.merge([up('fresh')], { live: true });
reconcileEvict(q, before, new Set(['a', 'b']));
expect(q.has('fresh')).toBe(true); // survives — not an eviction candidate
expect(q.has('a')).toBe(true);
});
});

View File

@@ -5,13 +5,18 @@
// (minus the most recent N items) once it empties. A new live post pushes onto the // (minus the most recent N items) once it empties. A new live post pushes onto the
// live queue and waits for the next slide transition — it never interrupts the // live queue and waits for the next slide transition — it never interrupts the
// current slide. // current slide.
//
// Completeness is the whole point: `allKnown` is meant to converge to the server's full
// set of eligible uploads. The page feeds it via `merge` (incremental / paginated) and
// `retainOnly` (evict anything the server no longer returns — deletions, bans, hides),
// so every eligible image is eventually shown and no ineligible one lingers.
import type { FeedUpload } from '$lib/types'; import type { FeedUpload } from '$lib/types';
const RECENT_RING_SIZE = 5; const RECENT_RING_SIZE = 5;
export class SlideQueue { export class SlideQueue {
/** Live queue — FIFO. New uploads land here via `pushLive`. */ /** Live queue — FIFO. New uploads land here via `merge(_, { live: true })`. */
private liveQueue: FeedUpload[] = []; private liveQueue: FeedUpload[] = [];
/** Shuffle queue — refilled from `allKnown` minus `recentlyShown` when emptied. */ /** Shuffle queue — refilled from `allKnown` minus `recentlyShown` when emptied. */
private shuffleQueue: FeedUpload[] = []; private shuffleQueue: FeedUpload[] = [];
@@ -20,19 +25,35 @@ export class SlideQueue {
/** Ring buffer of the last N shown ids — excluded from the next shuffle pool. */ /** Ring buffer of the last N shown ids — excluded from the next shuffle pool. */
private recentlyShown: string[] = []; private recentlyShown: string[] = [];
/** Seed the shuffle pool from an initial fetch of the feed. */ /**
seed(initial: FeedUpload[]): void { * Add uploads, de-duplicated by id. Only *displayable* items (preview- or
for (const slide of initial) { * thumbnail-ready) are kept — a still-compressing upload has no image yet, so it's
this.allKnown.set(slide.id, slide); * skipped until a later sync brings it with a preview. `live` items jump onto the live
* queue (shown next); otherwise they join the shuffle pool. Returns the count newly added.
*/
merge(uploads: FeedUpload[], opts: { live: boolean }): number {
let added = 0;
for (const u of uploads) {
if (!u.preview_url && !u.thumbnail_url) continue;
if (this.allKnown.has(u.id)) continue;
this.allKnown.set(u.id, u);
if (opts.live) this.liveQueue.push(u);
else this.shuffleQueue.push(u);
added++;
} }
this.shuffleQueue = shuffle(Array.from(this.allKnown.values())); return added;
} }
/** Add a slide pushed by a new SSE upload-processed event. */ /** True if this id is already in the known set — used to stop a catch-up scan once it
pushLive(slide: FeedUpload): void { * reaches territory we've already ingested. */
if (this.allKnown.has(slide.id)) return; has(id: string): boolean {
this.allKnown.set(slide.id, slide); return this.allKnown.has(id);
this.liveQueue.push(slide); }
/** Re-randomise the not-yet-shown shuffle pool. Called once after the initial paginated
* load so the first cycle isn't just newest-first (merge appends in feed order). */
reshuffle(): void {
this.shuffleQueue = shuffle(this.shuffleQueue);
} }
/** Pop the next slide. Returns null while both queues are empty (event has no posts). */ /** Pop the next slide. Returns null while both queues are empty (event has no posts). */
@@ -85,9 +106,21 @@ export class SlideQueue {
} }
this.liveQueue = this.liveQueue.filter((s) => s.user_id !== userId); this.liveQueue = this.liveQueue.filter((s) => s.user_id !== userId);
this.shuffleQueue = this.shuffleQueue.filter((s) => s.user_id !== userId); this.shuffleQueue = this.shuffleQueue.filter((s) => s.user_id !== userId);
this.recentlyShown = this.recentlyShown.filter((sid) => this.allKnown.has(sid));
return { wasCurrent }; return { wasCurrent };
} }
/**
* Snapshot of all currently-known ids. The page captures this BEFORE a reconcile scan,
* then evicts only ids that were known before AND the server no longer lists — the
* reconciliation half of `merge`. Snapshotting first means an upload that lands *during*
* the scan (not in the snapshot) is never wrongly evicted, so a busy event doesn't
* flicker freshly-added slides out and back in.
*/
knownIds(): string[] {
return Array.from(this.allKnown.keys());
}
/** Look up a slide by id — for the diashow page to render the current slide. */ /** Look up a slide by id — for the diashow page to render the current slide. */
get(id: string): FeedUpload | undefined { get(id: string): FeedUpload | undefined {
return this.allKnown.get(id); return this.allKnown.get(id);

View File

@@ -9,6 +9,8 @@ export interface FeedUpload {
uploader_name: string; uploader_name: string;
preview_url: string | null; preview_url: string | null;
thumbnail_url: string | null; thumbnail_url: string | null;
/** Big-screen (~2048px) variant for the diashow; null until the derivative exists. */
display_url: string | null;
mime_type: string; mime_type: string;
caption: string | null; caption: string | null;
like_count: number; like_count: number;

View File

@@ -4,7 +4,6 @@
import { api } from '$lib/api'; import { api } from '$lib/api';
import { getToken } from '$lib/auth'; import { getToken } from '$lib/auth';
import { showBottomNav } from '$lib/ui-store'; import { showBottomNav } from '$lib/ui-store';
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse'; import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
import { SlideQueue } from '$lib/diashow/queue'; import { SlideQueue } from '$lib/diashow/queue';
import { transitions, findTransition } from '$lib/diashow/transitions'; import { transitions, findTransition } from '$lib/diashow/transitions';
@@ -12,6 +11,17 @@
import type { FeedUpload, FeedResponse, DeltaResponse } from '$lib/types'; import type { FeedUpload, FeedResponse, DeltaResponse } from '$lib/types';
const DWELL_OPTIONS = [3000, 6000, 10000]; const DWELL_OPTIONS = [3000, 6000, 10000];
// Cap on how long we wait for the next image to decode before showing it anyway.
const PRELOAD_TIMEOUT_MS = 4000;
// If every source for a slide is unreadable we skip it — but bail out of skipping after
// this many in a row so a total media outage can't hot-loop the show.
const MAX_CONSECUTIVE_SKIPS = 5;
// Feed pagination: the server caps `limit` at 100, so we page to cover larger events.
const FEED_PAGE = 100;
const MAX_PAGES = 100; // safety bound (~10k images) against a runaway pagination loop
// Periodic full reconcile — the completeness backstop for anything a live event missed
// (dropped SSE, rate-limited fetch, an add/remove that never arrived).
const RECONCILE_INTERVAL_MS = 120_000;
let queue = new SlideQueue(); let queue = new SlideQueue();
let current = $state<FeedUpload | null>(null); let current = $state<FeedUpload | null>(null);
@@ -25,8 +35,11 @@
type SlideLayer = { key: string; src: string; isVideo: boolean; phase: 'enter' | 'exit' }; type SlideLayer = { key: string; src: string; isVideo: boolean; phase: 'enter' | 'exit' };
let layers = $state<SlideLayer[]>([]); let layers = $state<SlideLayer[]>([]);
let dropPrevTimer: ReturnType<typeof setTimeout> | null = null; let dropPrevTimer: ReturnType<typeof setTimeout> | null = null;
let reconcileInterval: ReturnType<typeof setInterval> | null = null;
// Guards the async (decode-gated) layer commit against a newer advance superseding it. // Guards the async (decode-gated) layer commit against a newer advance superseding it.
let slideToken = 0; let slideToken = 0;
// Consecutive slides skipped because no source decoded — reset the moment one shows.
let consecutiveSkips = 0;
let dwellMs = $state(6000); let dwellMs = $state(6000);
let transitionId = $state('crossfade'); let transitionId = $state('crossfade');
let paused = $state(false); let paused = $state(false);
@@ -66,18 +79,31 @@
} }
} }
function advance() { // `immediate` = hard-cut with no exiting layer, used when the outgoing slide was just
// removed (deleted / banned): it must vanish at once, not linger through the transition.
function advance(immediate = false) {
const next = queue.next(); const next = queue.next();
showSlide(next); showSlide(next, immediate);
if (current) scheduleNext(); if (current) scheduleNext();
} }
// Swap in the next slide as the top layer while holding the outgoing one beneath it // The diashow is a big screen (usually on good connectivity), so it ALWAYS prefers the
// for the length of the transition. For images we decode the incoming frame first so // crisp ~2048px `display` derivative — decoupled from the per-device data-saver mode,
// the fade reveals a painted picture rather than a blank one; the outgoing slide stays // which is about a guest's phone data plan and irrelevant here. It falls back to the
// visible until then, so there's never a black gap. Videos can't be pre-decoded, so // original (uploads without a display yet) and then the 800px preview.
// they swap in immediately. function imageCandidates(u: FeedUpload): string[] {
function showSlide(next: FeedUpload | null) { const displayOrOriginal = u.display_url ?? `/api/v1/upload/${u.id}/original`;
const list = [displayOrOriginal];
if (u.preview_url && u.preview_url !== displayOrOriginal) list.push(u.preview_url);
return list;
}
// Swap in the next slide as the top layer while holding the outgoing one beneath it for
// the length of the transition. Images are decode-gated (the fade reveals a painted
// frame, not a blank one) and try each source in turn; the outgoing slide stays visible
// until one commits, so there's never a black gap. Videos can't be pre-decoded, so they
// swap in immediately.
function showSlide(next: FeedUpload | null, immediate = false) {
const token = ++slideToken; const token = ++slideToken;
if (dropPrevTimer) { if (dropPrevTimer) {
clearTimeout(dropPrevTimer); clearTimeout(dropPrevTimer);
@@ -88,21 +114,26 @@
layers = []; layers = [];
return; return;
} }
const slide: SlideLayer = { const isVid = next.mime_type.startsWith('video/');
key: next.id,
src: pickMediaUrl($dataMode, next),
isVideo: next.mime_type.startsWith('video/'),
phase: 'enter'
};
const prev = layers.length ? layers[layers.length - 1] : null; const prev = layers.length ? layers[layers.length - 1] : null;
// Re-showing the same slide (e.g. a feed re-fetch resolved to the current head) —
// just replace it; never stack a slide on top of itself. const commit = (src: string) => {
if (prev && prev.key === slide.key) {
layers = [slide];
return;
}
const commit = () => {
if (token !== slideToken) return; // superseded by a newer advance — drop this frame if (token !== slideToken) return; // superseded by a newer advance — drop this frame
consecutiveSkips = 0; // a slide actually reached the screen — reset the skip guard
const slide: SlideLayer = { key: next.id, src, isVideo: isVid, phase: 'enter' };
// Re-showing the same slide id (e.g. a re-fetch resolved to the current head) —
// just replace it; never stack a slide on itself.
if (prev && prev.key === slide.key) {
layers = [slide];
return;
}
// Removal-driven advance: drop the outgoing (removed) frame instantly — no exiting
// layer. A brief blank over black beats showing a just-deleted/banned photo for
// another second while it slides away.
if (immediate) {
layers = [slide];
return;
}
// Mark the outgoing frame as exiting so slide transitions push it off in step with // Mark the outgoing frame as exiting so slide transitions push it off in step with
// the incoming one. Crossfade/Ken Burns ignore `phase` and just hold it opaque. // the incoming one. Crossfade/Ken Burns ignore `phase` and just hold it opaque.
const exiting = prev ? { ...prev, phase: 'exit' as const } : null; const exiting = prev ? { ...prev, phase: 'exit' as const } : null;
@@ -114,43 +145,141 @@
}, transitionDef.defaultDurationMs + 80); }, transitionDef.defaultDurationMs + 80);
} }
}; };
if (slide.isVideo) {
commit(); // Videos play the original file directly (can't be pre-decoded) — show immediately.
if (isVid) {
commit(`/api/v1/upload/${next.id}/original`);
return; return;
} }
const pre = new Image();
pre.src = slide.src; // Try each image source in order. A decoded one is shown; a SLOW one is shown after
// decode() resolves once the bitmap is ready to paint; on failure just commit anyway // the timeout (don't stall the wall); a BROKEN one (fast decode reject) falls through
// (a broken image should still advance the show rather than stall it). // to the next source. If every source is unreadable, skip to a different slide rather
pre.decode().then(commit).catch(commit); // than parking a broken frame — guarded so a full media outage can't hot-loop.
const candidates = imageCandidates(next);
const tryCandidate = (i: number) => {
if (token !== slideToken) return;
if (i >= candidates.length) {
if (consecutiveSkips < MAX_CONSECUTIVE_SKIPS) {
consecutiveSkips++;
advance();
} else {
consecutiveSkips = 0;
commit(candidates[candidates.length - 1]); // give up skipping; show last try
}
return;
}
let settled = false;
let timer: ReturnType<typeof setTimeout>;
const done = (action: () => void) => {
if (settled || token !== slideToken) return;
settled = true;
clearTimeout(timer);
action();
};
timer = setTimeout(() => done(() => commit(candidates[i])), PRELOAD_TIMEOUT_MS);
const pre = new Image();
pre.src = candidates[i];
pre.decode().then(
() => done(() => commit(candidates[i])),
() => done(() => tryCandidate(i + 1))
);
};
tryCandidate(0);
} }
// A video finished before its dwell/12s cap — advance immediately (unless paused). // A video finished before its dwell/12s cap — advance immediately (unless paused).
// The {#key current.id} block destroys the old <video> on advance, so a fallback // `onended` is only wired to the layer whose key === current.id (see the template), so a
// timer that already fired can't trigger this handler for a stale slide. // stale/exiting <video> that ends mid-transition can't trigger an advance.
function handleVideoEnded() { function handleVideoEnded() {
if (!paused) advance(); if (!paused) advance();
} }
async function loadInitial() { // Full reconcile: page the ENTIRE eligible feed, merge everything, then evict anything
// the server no longer returns. v_feed already excludes deleted/banned/hidden, so the
// feed's id-set IS the eligible set — retaining exactly those ids converges the show to
// the server truth in both directions, catching any add/remove a live event missed.
// Runs on mount (initial fill), on reconnect deltas, and periodically as the backstop.
// `initial` reshuffles once the whole set is in, so the first cycle isn't newest-first.
async function reconcile(initial = false) {
// Ids known BEFORE the scan — only these are eviction candidates, so an upload that
// arrives mid-scan (not in this snapshot) is never wrongly pruned.
const before = new Set(queue.knownIds());
const seen = new Set<string>();
let cursor: string | null = null;
let complete = false;
try { try {
const feed = await api.get<FeedResponse>('/feed?limit=200'); for (let page = 0; page < MAX_PAGES; page++) {
queue.seed(feed.uploads); const qs: string = cursor ? `?limit=${FEED_PAGE}&cursor=${cursor}` : `?limit=${FEED_PAGE}`;
advance(); const feed: FeedResponse = await api.get<FeedResponse>(`/feed${qs}`);
for (const u of feed.uploads) seen.add(u.id);
queue.merge(feed.uploads, { live: false });
if (!current) advance(); // start the show the moment the first page lands
if (feed.next_cursor == null) {
complete = true;
break;
}
cursor = feed.next_cursor;
}
} catch { } catch {
// Silent — placeholder stays shown // Partial fetch (network / rate-limit): keep what we merged but DON'T prune — a
// truncated `seen` set must never evict valid slides. The next reconcile retries.
complete = false;
}
if (complete) {
if (initial) queue.reshuffle();
// Evict only pre-existing slides the server no longer lists (deletions/bans/hides
// we missed a live event for). Hard-cut if the current slide was one of them.
let removedCurrent = false;
for (const id of before) {
if (!seen.has(id) && queue.remove(id, current?.id ?? null).wasCurrent) {
removedCurrent = true;
}
}
if (removedCurrent) advance(true);
}
if (!current) advance();
}
// Live catch-up after `upload-processed`. Pages from the newest downward, merging onto
// the live queue (shown soon), and stops at the first page overlapping what we already
// know — so a burst larger than one 100-item page is fully captured, while a steady
// trickle costs a single request. We deliberately ignore `new-upload` (fires before
// compression, so preview_url is still null and the item isn't displayable yet).
async function catchUpNew() {
let cursor: string | null = null;
try {
for (let page = 0; page < MAX_PAGES; page++) {
const qs: string = cursor ? `?limit=${FEED_PAGE}&cursor=${cursor}` : `?limit=${FEED_PAGE}`;
const feed: FeedResponse = await api.get<FeedResponse>(`/feed${qs}`);
// A known id marks the boundary: everything below it we already have.
const reachedKnown = feed.uploads.some((u) => queue.has(u.id));
queue.merge(feed.uploads, { live: true });
if (!current) advance();
if (feed.next_cursor == null || reachedKnown) break;
cursor = feed.next_cursor;
}
} catch {
// transient — the max-wait debounce re-fires and the periodic reconcile backstops
} }
} }
// `upload-processed` carries only `{ upload_id }`; we re-fetch from /feed to get the // Debounce `upload-processed` into a single catch-up, BUT with a max-wait: a sustained
// preview/thumbnail URLs that just became available. We deliberately do NOT listen // burst (every guest uploading at once) would otherwise keep resetting a plain trailing
// to `new-upload` here — its payload arrives before compression finishes // debounce and never fire. The max-wait forces a catch-up at least every 2s mid-burst.
// (preview_url is still null), and `SlideQueue.pushLive` dedupes by id, so the
// preview would never be picked up if we enqueued the pre-processed version first.
// COALESCE the fetch: a host bulk-uploading fires dozens of `upload-processed` events in
// seconds; one `/feed` fetch per event trips the per-user feed rate limit (429) and drops
// slides. Debounce into a single fetch of the newest slice instead.
let processedDebounce: ReturnType<typeof setTimeout> | null = null; let processedDebounce: ReturnType<typeof setTimeout> | null = null;
let processedMaxWait: ReturnType<typeof setTimeout> | null = null;
function fireCatchUp() {
if (processedDebounce) {
clearTimeout(processedDebounce);
processedDebounce = null;
}
if (processedMaxWait) {
clearTimeout(processedMaxWait);
processedMaxWait = null;
}
void catchUpNew();
}
function handleUploadProcessed(data: string) { function handleUploadProcessed(data: string) {
try { try {
const { upload_id } = JSON.parse(data) as { upload_id: string }; const { upload_id } = JSON.parse(data) as { upload_id: string };
@@ -159,97 +288,55 @@
return; return;
} }
if (processedDebounce) clearTimeout(processedDebounce); if (processedDebounce) clearTimeout(processedDebounce);
processedDebounce = setTimeout(() => { processedDebounce = setTimeout(fireCatchUp, 500);
processedDebounce = null; if (!processedMaxWait) processedMaxWait = setTimeout(fireCatchUp, 2000);
void refreshRecentFromFeed();
}, 500);
}
async function refreshRecentFromFeed() {
try {
const feed = await api.get<FeedResponse>('/feed?limit=50');
for (const upload of feed.uploads) {
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
}
if (!current) advance();
} catch {
// ignore — silent recovery; the next event or reconnect delta retries
}
} }
function handleUploadDeleted(data: string) { function handleUploadDeleted(data: string) {
try { try {
const payload = JSON.parse(data) as { upload_id: string }; const { upload_id } = JSON.parse(data) as { upload_id: string };
const result = queue.remove(payload.upload_id, current?.id ?? null); // Hard-cut: a just-deleted photo must not linger through the exit transition.
if (result.wasCurrent) advance(); if (queue.remove(upload_id, current?.id ?? null).wasCurrent) advance(true);
} catch { } catch {
// ignore // ignore
} }
} }
// After an all-night projector reconnects (SSE drop, network blip), the live events
// it missed are gone. The SSE client fans out a `feed-delta` of everything since the
// last seen timestamp — merge it so the show backfills the gap instead of silently
// stalling on a stale set.
function handleFeedDelta(data: string) {
try {
const delta = JSON.parse(data) as DeltaResponse;
// Apply deletions + ban-hides FIRST and unconditionally: both are explicit, uncapped
// lists, so a moderated/removed photo (or a banned user's whole set) must leave the
// rotation even when the delta is truncated. This replays a `user-hidden`/delete the
// projector missed while disconnected — the reason a banned guest's slides used to
// keep cycling all night. (We can't infer removals by absence from a capped /feed
// backfill — older slides beyond the newest 200 would be falsely dropped.)
for (const id of delta.deleted_ids) {
const result = queue.remove(id, current?.id ?? null);
if (result.wasCurrent) advance();
}
for (const userId of delta.hidden_user_ids) {
const result = queue.removeByUser(userId, current?.id ?? null);
if (result.wasCurrent) advance();
}
// A truncated delta's `uploads` is only the newest slice of a larger gap; merging it
// alone would skip the older-but-still-new items in between. Backfill new uploads from
// a full feed fetch (pushLive dedupes by id, so the current slide isn't disturbed).
if (delta.truncated) {
void backfillFromFeed();
return;
}
for (const upload of delta.uploads) {
// Only enqueue displayable (processed) items; pushLive dedupes by id, so a
// later `upload-processed` still refines anything that arrives raw.
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
}
if (!current) advance();
} catch {
// ignore — non-fatal; the next live event keeps the show moving
}
}
// Full-feed backfill used when a reconnect delta overflows the cap. Merges via
// pushLive (id-deduped) so a long-running projector recovers the whole gap.
async function backfillFromFeed() {
try {
const feed = await api.get<FeedResponse>('/feed?limit=200');
for (const upload of feed.uploads) {
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
}
if (!current) advance();
} catch {
// ignore — the next live event keeps the show moving
}
}
function handleUserHidden(data: string) { function handleUserHidden(data: string) {
try { try {
const payload = JSON.parse(data) as { user_id: string }; const { user_id } = JSON.parse(data) as { user_id: string };
const result = queue.removeByUser(payload.user_id, current?.id ?? null); if (queue.removeByUser(user_id, current?.id ?? null).wasCurrent) advance(true);
if (result.wasCurrent) advance();
} catch { } catch {
// ignore // ignore
} }
} }
// Reconnect after an SSE drop: the client fans out a delta of everything since the last
// seen timestamp. Apply removals first (hard-cut off the current slide if affected),
// then merge additions; a truncated delta means the gap overflowed the cap, so fall back
// to a full catch-up scan.
function handleFeedDelta(data: string) {
try {
const delta = JSON.parse(data) as DeltaResponse;
let removedCurrent = false;
for (const id of delta.deleted_ids) {
if (queue.remove(id, current?.id ?? null).wasCurrent) removedCurrent = true;
}
for (const userId of delta.hidden_user_ids) {
if (queue.removeByUser(userId, current?.id ?? null).wasCurrent) removedCurrent = true;
}
if (removedCurrent) advance(true); // one advance regardless of how many were removed
if (delta.truncated) {
void catchUpNew();
return;
}
queue.merge(delta.uploads, { live: true });
if (!current) advance();
} catch {
// ignore — non-fatal; the periodic reconcile backstops anything dropped here
}
}
// Reveal the control cluster on any pointer/keyboard activity and re-arm the idle timer. // Reveal the control cluster on any pointer/keyboard activity and re-arm the idle timer.
// Controls stay up while the settings panel is open so it can't vanish mid-interaction. // Controls stay up while the settings panel is open so it can't vanish mid-interaction.
function showControls() { function showControls() {
@@ -340,7 +427,10 @@
// (no-ops if the feed page already opened it). Subscriptions are registered above // (no-ops if the feed page already opened it). Subscriptions are registered above
// first so no early event is missed. // first so no early event is missed.
connectSse(); connectSse();
void loadInitial(); void reconcile(true); // initial full load
// Completeness backstop: periodically re-sync the whole eligible set, so a dropped
// SSE event, a rate-limited catch-up, or any missed add/remove self-heals.
reconcileInterval = setInterval(() => void reconcile(), RECONCILE_INTERVAL_MS);
}); });
onDestroy(() => { onDestroy(() => {
@@ -348,6 +438,8 @@
clearTimer(); clearTimer();
if (controlsHideTimer) clearTimeout(controlsHideTimer); if (controlsHideTimer) clearTimeout(controlsHideTimer);
if (processedDebounce) clearTimeout(processedDebounce); if (processedDebounce) clearTimeout(processedDebounce);
if (processedMaxWait) clearTimeout(processedMaxWait);
if (reconcileInterval) clearInterval(reconcileInterval);
if (dropPrevTimer) clearTimeout(dropPrevTimer); if (dropPrevTimer) clearTimeout(dropPrevTimer);
document.removeEventListener('fullscreenchange', handleFullscreenChange); document.removeEventListener('fullscreenchange', handleFullscreenChange);
// Leave fullscreen when exiting the show, so /feed isn't stuck fullscreen. // Leave fullscreen when exiting the show, so /feed isn't stuck fullscreen.
@@ -426,7 +518,13 @@
> >
{#if isFullscreen} {#if isFullscreen}
<!-- arrows pointing in --> <!-- arrows pointing in -->
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"> <svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.8"
>
<path <path
stroke-linecap="round" stroke-linecap="round"
stroke-linejoin="round" stroke-linejoin="round"
@@ -435,7 +533,13 @@
</svg> </svg>
{:else} {:else}
<!-- arrows pointing out --> <!-- arrows pointing out -->
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"> <svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.8"
>
<path <path
stroke-linecap="round" stroke-linecap="round"
stroke-linejoin="round" stroke-linejoin="round"