Files
otunes/packages/convex/client/playlist-cover.ts
T
joshuafhigginsandClaude Opus 5.5 Verified 886c8f0643 feat: playlist cover artwork
Playlists draw a 2x2 of their first albums automatically. Owners can pick
from random grids, reshuffle, or upload an image on web and mobile.
Covers are rendered once into Convex storage and redrawn only when the
playlist's albums change. Web and iPad sidebars show playlist covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:15:21 -05:00

53 lines
1.6 KiB
TypeScript

import type { Id } from "../convex/_generated/dataModel"
import { COVER_GRID_ALBUMS } from "../convex/limits"
import type { BrowseSong } from "../convex/types"
export { COVER_GRID_ALBUMS }
export type CoverAlbum = BrowseSong["album"]
/** Distinct albums that have artwork, in playlist order. */
export function playlistCoverAlbums(songs: readonly BrowseSong[]) {
const albums = new Map<string, CoverAlbum>()
for (const song of songs) {
if (song.album.cover !== null && !albums.has(song.album.id)) {
albums.set(song.album.id, song.album)
}
}
return [...albums.values()]
}
/** `count` distinct items in random order (Fisher-Yates prefix). */
function sample<T>(items: readonly T[], count: number) {
const pool = [...items]
for (let index = 0; index < count; index++) {
const swap = index + Math.floor(Math.random() * (pool.length - index))
;[pool[index], pool[swap]] = [pool[swap], pool[index]]
}
return pool.slice(0, count)
}
/**
* Cover options to pick from, as album ids for `setPlaylistCoverAlbums`.
* With four or more albums: `count` random 2x2 grids, avoiding repeats.
* With fewer: each album's cover alone.
*/
export function randomPlaylistCovers(
albums: readonly CoverAlbum[],
count = 4
): Id<"albums">[][] {
const ids = albums.map((album) => album.id)
if (ids.length < COVER_GRID_ALBUMS) return ids.map((id) => [id])
const options = new Map<string, Id<"albums">[]>()
for (
let attempt = 0;
options.size < count && attempt < count * 10;
attempt++
) {
const option = sample(ids, COVER_GRID_ALBUMS)
options.set(option.join(","), option)
}
return [...options.values()]
}