Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316/** * Flattening the harvested song list into render-ready rows: * artist section → album section → tracks, sorted case-insensitively. * Pure functions so the list view stays dumb and this is unit-tested. */import type { LibrarySong } from "../harvest/types";
export type LibraryRow = | { kind: "artist"; key: string; label: string; songs: number; albums: number; artistId?: string } | { kind: "album"; key: string; label: string; artist: string; year?: number; songs: number; duration?: number; albumId?: string; coverArt?: string; } | { kind: "track"; key: string; song: LibrarySong; trackNo?: number };
const UNKNOWN_ARTIST = "(unknown artist)";const NO_ALBUM = "(no album)";// \uffff sentinel sinks unknown buckets to the end of the orderingconst END = "\uffff";
/** * The form a name takes when it decides *identity*, not appearance. * * Tags carry whitespace nobody meant as a difference. A re-rip whose ALBUM ARTIST * is `"Luis Hernandez "` — one trailing space — is the same artist, but compared * lowercased it is a different string, and it landed in a second `Luis Hernandez` * section with its own album sections inside it (the album row key is * `` `${artistKey}\u0000${albumKey}` ``). Navidrome trims and case-folds its order * fields and shows one artist; a client that compares tags raw splits a library * the server says is one thing. * * Keys only. The labels the rows carry stay exactly as the server tagged them, so * nothing here edits what the user reads. * * Narrower than `fold()` in `library/normalize.ts` on purpose: that one drops * accents and punctuation so a search for `acdc` finds `AC/DC`, which is what * typing at a filter wants and what identity does not. *Live* and *Live!* are two * releases, and an identity fold that merged them would hand two records one * repeat group. */export function nameKey(name: string | undefined): string { if (!name) return ""; // NFKC first: a compatibility fold turns a full-width or ligatured spelling // into the same text the rest of the library is spelled with, after which // case, the ends, and any run of interior whitespace are the only differences // left to lose. return name.normalize("NFKC").toLowerCase().trim().replace(/\s+/g, " ");}
function artistKey(s: LibrarySong): string { const key = nameKey(s.artist); return key || END + UNKNOWN_ARTIST;}function albumKey(s: LibrarySong): string { const key = nameKey(s.album); return key || END + NO_ALBUM;}
// Shared with the grid view (grid.ts): both orderings must be the same sort, or// flipping modes reshuffles the collection under the cursor.export const sortKeys = { artistKey, albumKey, END };
const num = (n: number | undefined, d = 0) => (Number.isFinite(n) ? (n as number) : d);// unnumbered tracks sink to the end of their discconst trackKey = (s: LibrarySong) => Number.isFinite(s.track) ? (s.track as number) : Number.MAX_SAFE_INTEGER;
export interface DurationParts { /** Leading `00:` segments that carry no information — render de-emphasised. */ faded: string; /** The shortest reading that still says how long the thing is. */ strong: string;}
/** * hh:mm:ss split into *padding* and *signal*. The column is always 8 chars so * the grid stays straight, but `00:00:07` is not three measurements — the two * leading segments are scaffolding, so they come back here to be faded out. * * Leading zeros are only insignificant while nothing above them is set: at * `01:12:05` the hour is the news, so nothing fades. */export function durationParts(seconds: number | undefined): DurationParts { if (seconds === undefined || seconds === null || !Number.isFinite(seconds)) { return { faded: "", strong: "" }; } const s = Math.round(seconds); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const sec = s % 60; const pad = (n: number) => String(n).padStart(2, "0"); if (h > 0) return { faded: "", strong: `${pad(h)}:${pad(m)}:${pad(sec)}` }; if (m > 0) return { faded: "00:", strong: `${pad(m)}:${pad(sec)}` }; return { faded: "00:00:", strong: pad(sec) };}
/** Flat `hh:mm:ss` — the faded and strong halves joined. */export function fmtDuration(seconds: number | undefined): string { const { faded, strong } = durationParts(seconds); return faded + strong;}
/** Which measurement a chip carries. Only `codec` carries a hue. */export type BadgeKind = "codec" | "bitrate" | "depth" | "rate";
export interface TrackBadge { label: string; kind: BadgeKind; /** Normalized format id for `codec` chips — selects the hue in CSS. */ codec?: string; /** * The container that reached the speaker is not the one the file was written * in: the server transcoded it because the browser could not decode the * original. Only the player can know this (the index only knows the file), so * only the transport bar sets it — and a chip that omits it is a lie about * what the listener is hearing. */ transcoded?: boolean;}
/** * Server-reported container and codec names folded onto one hue key. Navidrome * hands us whatever the scanner found — the extension (`WAVE`, `AIF`) or, once the * native harvest supplies `codec`, ffprobe's name for the stream inside it * (`Vorbis`, `pcm_s24le`, `dsd_msbf_planar`) — and two spellings of the same format * must not show up in two different colors. */const CODEC_ALIASES: Record<string, string> = { vorbis: "ogg", oga: "ogg", wave: "wav", pcm: "wav", aif: "aiff", aifc: "aiff", mp4a: "m4a", alac: "alac", apple_lossless: "alac",};
export function codecKey(name: string | undefined): string | undefined { const raw = name?.trim().toLowerCase(); if (!raw) return undefined; // ffprobe qualifies PCM and DSD by their bit order (`pcm_s16le`, `pcm_f32be`, // `dsd_lsbf_planar`); that is a detail of the same two formats as far as a hue // is concerned. if (raw.startsWith("pcm")) return CODEC_ALIASES.pcm; if (raw.startsWith("dsd")) return "dsd"; return CODEC_ALIASES[raw] ?? raw;}
/** * Identity for "the same album", as one unit — used by `albumRuns` below and by * the player's group repeat. The id when the server has one: two records both * called *Live* are not the same album, and an unbroken block of titles would * loop across two artists' work. Where there is no id, the *folded* title decides * — the same fold the list sorts by, so a run cannot split on whitespace between * two tracks of one album and cut a repeat in half. */export function albumGroupKey(s: LibrarySong): string { return s.albumId ?? nameKey(s.album);}
/** The artist-wide twin, for repeat=artist. */export function artistGroupKey(s: LibrarySong): string { return s.artistId ?? nameKey(s.artist);}
/** * Contiguous runs of one album, in the order given. * * Contiguous on purpose: the list sorts artist → album → disc → track, so an * album is one unbroken block, and that is also the block `repeat: album` loops * inside. Feeding it the visible queue is what makes "play a random album" mean * a random album *of what you can see*. */export function albumRuns(songs: LibrarySong[]): LibrarySong[][] { const runs: LibrarySong[][] = []; let key: string | null = null; for (const s of songs) { const k = albumGroupKey(s); if (runs.length > 0 && k === key) runs[runs.length - 1]!.push(s); else { key = k; runs.push([s]); } } return runs;}
/** * Codec + format chips for a track row, in reading order: what the file *is* * (flac / mp3) first, then how much of it there is. Empty array = no metadata * worth a chip; callers render nothing rather than empty pills. * * The codec chip prefers what the server probed (`codec`) over what the file is * called (`suffix`), because only the probe survives a mislabelled file; when the * harvest came from a server that reports no probe, the extension answers. * * Color means *format*: the codec chip carries a `codec` id for CSS to tint, * and the measurements stay neutral so a hue never reads as "something is off * with this bitrate". Unmapped formats fall back to the neutral chip look. */export function trackBadges(s: LibrarySong): TrackBadge[] { const out: TrackBadge[] = []; const codec = codecKey(s.codec) ?? codecKey(s.suffix); if (codec) out.push({ label: codec, kind: "codec", codec }); if (s.bitRate) out.push({ label: `${Math.round(s.bitRate)}k`, kind: "bitrate" }); if (s.bitDepth) out.push({ label: `${s.bitDepth}b`, kind: "depth" }); if (s.sampleRate) out.push({ label: `${+(s.sampleRate / 1000).toFixed(1)}hz`, kind: "rate" }); return out;}
export function buildRows(songs: LibrarySong[]): LibraryRow[] { // Decorate once, sort on precomputed keys: the naive comparator ran // toLowerCase + localeCompare on *every* comparison — ~300k comparisons at // 20k songs, hundreds of ms of the boot long task. One collator, keys built // once per song. const collator = new Intl.Collator(); const decorated = songs.map((s) => ({ song: s, ak: artistKey(s), bk: albumKey(s), disc: num(s.disc), tk: trackKey(s), title: s.title ?? "", })); decorated.sort((a, b) => { if (a.ak !== b.ak) return collator.compare(a.ak, b.ak); if (a.bk !== b.bk) return collator.compare(a.bk, b.bk); if (a.disc !== b.disc) return a.disc - b.disc; if (a.tk !== b.tk) return a.tk - b.tk; return collator.compare(a.title, b.title); });
// pass 1: section aggregates for the header rows const albumAgg = new Map< string, { songs: number; duration: number; year?: number; albumId?: string; coverArt?: string } >(); const artistAgg = new Map<string, { songs: number; albums: Set<string>; artistId?: string }>(); for (const d of decorated) { const s = d.song; const { ak, bk } = d; const key = `${ak}\u0000${bk}`; const alb = albumAgg.get(key) ?? { songs: 0, duration: 0 }; alb.songs += 1; alb.duration += num(s.duration); if (alb.year === undefined && s.year) alb.year = s.year; if (alb.albumId === undefined && s.albumId) alb.albumId = s.albumId; if (alb.coverArt === undefined && s.coverArt) alb.coverArt = s.coverArt; albumAgg.set(key, alb); const art = artistAgg.get(ak) ?? { songs: 0, albums: new Set<string>() }; art.songs += 1; art.albums.add(bk); // The id the server gives this artist, taken from the first track that carries // one — the same rule the album row uses for its own id. Nothing here favorites an // artist; the id is what a "where is this?" request from the player bar is answered // against (`lib/locate.ts`), and /api/song names the artist id on the *track*, never // on a row for the artist, so aggregating it here is the only place to pick it up. if (art.artistId === undefined && s.artistId) art.artistId = s.artistId; artistAgg.set(ak, art); }
// pass 2: emit rows, deduping section headers as we cross boundaries const rows: LibraryRow[] = []; let lastArtist: string | null = null; let lastAlbum: string | null = null; for (const d of decorated) { const s = d.song; const { ak, bk } = d; const key = `${ak}\u0000${bk}`; if (ak !== lastArtist) { lastArtist = ak; lastAlbum = null; // new artist always opens a new album section const agg = artistAgg.get(ak)!; rows.push({ kind: "artist", key: `a:${ak}`, label: s.artist ?? UNKNOWN_ARTIST, songs: agg.songs, albums: agg.albums.size, artistId: agg.artistId, }); } if (key !== lastAlbum) { lastAlbum = key; const agg = albumAgg.get(key)!; rows.push({ kind: "album", key: `al:${key}`, label: s.album ?? NO_ALBUM, artist: s.artist ?? UNKNOWN_ARTIST, year: agg.year, songs: agg.songs, duration: agg.duration, albumId: agg.albumId, coverArt: agg.coverArt, }); } rows.push({ kind: "track", key: `t:${s.id}`, song: s, trackNo: s.track, }); } return rows;}