Skip to content

Open-source music player for YouTube Music's catalog, with genres, full albums and playlists. Windows, macOS, Linux, Android, iPhone and Docker. No account needed.

TypeScript

feat: Musike 1.1.0 — buscar lista, explorar por gênero e atualização segura

Ernani48b2d7b53ecf
diff --git a/README.md b/README.md
index 678b77c..ecb6b63 100644
--- a/README.md
+++ b/README.md
@@ -51,6 +51,8 @@ O Musike nasceu da ideia dos antigos bots de música do Discord: um servidor que
**Ouvir**
- Busca no YouTube Music com abas **Músicas** e **Vídeos** e sugestões enquanto você digita
- Cole um **link do YouTube** na busca para tocar direto
+- **Explorar por gênero:** o filtro **Gêneros** na busca abre os gêneros do YouTube Music (Rock, Sertanejo, MPB, Metal...). Cada um mostra as bandas e artistas do gênero (toque em um para ver os maiores sucessos) ou todas as músicas numa lista só, com seleção para tocar, favoritar ou mandar para uma playlist
+- **Buscar lista:** escreva várias músicas separadas por vírgula ("Evidências, Trem-Bala, ..."); o Musike busca cada uma, já seleciona o melhor resultado (dá para trocar) e você toca, favorita ou manda as selecionadas para uma playlist nova ou existente
- Fila com tocar a seguir, aleatório e repetir (fila ou faixa)
- **Rádio automático:** quando a fila acaba, continua com músicas parecidas
- Avanço e retrocesso instantâneos (streaming com HTTP Range) e próxima faixa pré-carregada
@@ -155,6 +157,9 @@ Na primeira abertura, uma tela mostra o download das ferramentas oficiais: **yt-
| `bin` | yt-dlp, Deno e FFmpeg do próprio Musike (atualizáveis em Ajustes) |
| `data` | `library.json` com playlists, favoritas e histórico |
| `cache` | vídeos HD já baixados |
+| `backups` | cópias da biblioteca feitas a cada atualização |
+
+**Atualizar é só instalar a versão nova por cima.** A pasta `%APPDATA%\Musike` fica fora da pasta do programa e nem a atualização nem a desinstalação a apagam. Por segurança, antes de trocar a versão o instalador ainda copia a biblioteca para `backups\library-antes-de-instalar-<versão>.json`, e o app guarda outra cópia datada na primeira abertura de cada versão (mantém as 5 mais recentes). Para restaurar uma delas, feche o Musike e copie o arquivo por cima de `data\library.json`.
> O instalador não é assinado digitalmente. Na primeira execução o Windows mostra "O Windows protegeu o computador": clique em **Mais informações** e depois **Executar assim mesmo**.
@@ -261,16 +266,21 @@ Todas as rotas respondem JSON. Erros vêm como `{ "error": "mensagem", "code"?:
| `GET` | `/api/search?q=&type=song\|video` | Busca no YouTube Music |
| `GET` | `/api/suggest?q=` | Sugestões de busca |
| `GET` | `/api/radio/:id` | Faixas relacionadas (rádio) |
+| `GET` | `/api/genres` | Gêneros do YouTube Music |
+| `GET` | `/api/genres/:gid` | Artistas e músicas de um gênero |
+| `GET` | `/api/genres/:gid/artists?offset=` | Mais artistas do gênero ("Carregar mais") |
+| `GET` | `/api/artists/:aid` | Maiores sucessos de um artista |
| `GET` | `/api/video-for/:id?title=&artist=&duration=` | Clipe oficial de uma música |
| `POST` | `/api/prepare/:id` | Resolve o stream antes de tocar |
| `GET` | `/api/stream/:id/audio` | Áudio com HTTP Range |
| `GET` | `/api/stream/:id/video?q=sd\|hd` | Vídeo com HTTP Range |
| `GET` | `/api/library` | Biblioteca completa |
| `PUT` / `DELETE` | `/api/favorites/:id` | Favoritar / desfavoritar |
+| `POST` | `/api/favorites` | Favorita várias de uma vez (`{ tracks }`) |
| `POST` | `/api/history` | Registra uma faixa tocada |
| `POST` | `/api/playlists` | Cria playlist |
| `PATCH` / `DELETE` | `/api/playlists/:pid` | Renomeia / exclui |
-| `POST` / `DELETE` | `/api/playlists/:pid/tracks[/:id]` | Adiciona / remove faixa |
+| `POST` / `DELETE` | `/api/playlists/:pid/tracks[/:id]` | Adiciona (uma faixa ou `{ tracks }`) / remove faixa |
| `POST` | `/api/library/import` | Importa backup (`{ backup, mode: "merge" \| "replace" }`) |
| `GET` | `/api/system` | Versões do yt-dlp, Deno, FFmpeg e downloads |
| `POST` | `/api/system/ytdlp` | Atualiza ou instala o yt-dlp (`{ channel: "stable" \| "nightly" }`) |
diff --git a/desktop/build/installer.nsh b/desktop/build/installer.nsh
new file mode 100644
index 0000000..d686885
--- /dev/null
+++ b/desktop/build/installer.nsh
@@ -0,0 +1,16 @@
+; Musike: hooks for the electron-builder NSIS installer (picked up automatically from build/installer.nsh).
+;
+; The user's library lives in %APPDATA%\Musike\data, outside the install folder, and the installer
+; never removes it ("deleteAppDataOnUninstall": false, and updates always keep app data).
+; As a second safety net, copy it aside before the old version is replaced.
+
+!macro customInit
+ Push $R0
+ ; Electron keeps app data per user, whatever the install mode: use the user's own Roaming folder.
+ ReadEnvStr $R0 APPDATA
+ IfFileExists "$R0\Musike\data\library.json" 0 musike_no_library
+ CreateDirectory "$R0\Musike\backups"
+ CopyFiles /SILENT "$R0\Musike\data\library.json" "$R0\Musike\backups\library-antes-de-instalar-${VERSION}.json"
+ musike_no_library:
+ Pop $R0
+!macroend
diff --git a/desktop/package.json b/desktop/package.json
index bc89c15..ac1bede 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "musike-desktop",
"productName": "Musike",
- "version": "0.1.0",
+ "version": "1.1.0",
"description": "Sua música, sem interrupção.",
"author": "Musike",
"private": true,
@@ -58,7 +58,8 @@
"pt_BR"
],
"language": "1046",
- "deleteAppDataOnUninstall": false
+ "deleteAppDataOnUninstall": false,
+ "include": "build/installer.nsh"
}
},
"devDependencies": {
diff --git a/desktop/src/backup.ts b/desktop/src/backup.ts
new file mode 100644
index 0000000..0850967
--- /dev/null
+++ b/desktop/src/backup.ts
@@ -0,0 +1,43 @@
+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const BACKUPS_KEPT = 5;
+
+/**
+ * First launch of a new version: keep a dated copy of the library from before the update,
+ * so nothing the user saved can be lost to one. Returns the backup's path, if one was made.
+ * Never throws: a failed backup must not keep the app from opening (it retries on the next launch).
+ */
+export function backupLibraryOnUpdate(userData: string, version: string, now = new Date()): string | null {
+ const versionFile = path.join(userData, "version.json");
+ let previous: string | undefined;
+ try {
+ previous = (JSON.parse(readFileSync(versionFile, "utf8")) as { version?: string }).version;
+ } catch {
+ // first launch, or a version from before this file existed
+ }
+ if (previous === version) return null;
+
+ try {
+ let made: string | null = null;
+ const library = path.join(userData, "data", "library.json");
+ if (existsSync(library)) {
+ const dir = path.join(userData, "backups");
+ mkdirSync(dir, { recursive: true });
+ // Sortable by name: library-2026-10-13_14-05-00-antes-da-1.1.0.json
+ const stamp = now.toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-");
+ made = path.join(dir, `library-${stamp}-antes-da-${version}.json`);
+ copyFileSync(library, made);
+ const dated = readdirSync(dir)
+ .filter((f) => /^library-\d{4}-\d\d-\d\d_/.test(f))
+ .sort()
+ .reverse();
+ for (const old of dated.slice(BACKUPS_KEPT)) rmSync(path.join(dir, old), { force: true });
+ }
+ writeFileSync(versionFile, JSON.stringify({ version }));
+ return made;
+ } catch (err) {
+ console.error("Backup da biblioteca falhou:", err);
+ return null;
+ }
+}
diff --git a/desktop/src/main.mts b/desktop/src/main.mts
index fc8e80a..efd3fe3 100644
--- a/desktop/src/main.mts
+++ b/desktop/src/main.mts
@@ -3,6 +3,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { app, BrowserWindow, ipcMain, Menu, screen, shell } from "electron";
import type { RunningServer } from "../../server/src/app.js";
+import { backupLibraryOnUpdate } from "./backup.js";
// No top-level await in this file: Electron only fires "ready" after the entry module finishes
// evaluating, so awaiting it at the top level would hang forever.
@@ -22,6 +23,9 @@ process.env.MUSIKE_CACHE_DIR = path.join(userData, "cache");
process.env.MUSIKE_BIN_DIR = path.join(userData, "bin");
process.env.MUSIKE_WEB_DIST = app.isPackaged ? path.join(process.resourcesPath, "web") : path.resolve(here, "..", "..", "web", "dist");
+// A copy of the library from before each update, in userData/backups (the installer makes one too).
+backupLibraryOnUpdate(userData, app.getVersion());
+
// The server reads its config when first imported, so load it only after the env above is set.
const loadServer = async () => ({
...(await import("../../server/src/app.js")),
diff --git a/package.json b/package.json
index 88c9051..42f6d28 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "musike",
"private": true,
- "version": "0.1.0",
+ "version": "1.1.0",
"type": "module",
"scripts": {
"dev": "pnpm --parallel --filter ./server --filter ./web dev",
diff --git a/server/package.json b/server/package.json
index c78d124..6f65eaa 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,7 +1,7 @@
{
"name": "@musike/server",
"private": true,
- "version": "0.1.0",
+ "version": "1.1.0",
"type": "module",
"scripts": {
"dev": "tsx watch --clear-screen=false src/index.ts",
diff --git a/server/src/app.ts b/server/src/app.ts
index a47ca13..5d0a381 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
import { createServer } from "node:net";
import fastifyStatic from "@fastify/static";
import Fastify from "fastify";
+import { ARTIST_ID, artist, GENRE_ID, genre, genreArtists, genres } from "./browse.js";
import { config } from "./config.js";
import * as library from "./library.js";
import { findVideoFor, radio, search, suggestions } from "./search.js";
@@ -74,6 +75,31 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
app.get("/api/radio/:id", async (req) => ({ tracks: await radio(videoId(req.params)) }));
+ // Browse by genre: genre → its artists or all its songs → an artist's top songs
+
+ app.get("/api/genres", async () => ({ genres: await genres("") }));
+
+ app.get("/api/genres/:gid", async (req) => {
+ const { gid } = req.params as { gid: string };
+ if (!GENRE_ID.test(gid)) throw new HttpError(400, "Gênero inválido.");
+ return genre(gid);
+ });
+
+ /** "Load more" for a genre's artists: `offset` is how many the app already shows. */
+ app.get("/api/genres/:gid/artists", async (req) => {
+ const { gid } = req.params as { gid: string };
+ const offset = Number((req.query as { offset?: string }).offset ?? 0);
+ if (!GENRE_ID.test(gid)) throw new HttpError(400, "Gênero inválido.");
+ if (!Number.isInteger(offset) || offset < 0 || offset > 1000) throw new HttpError(400, "Posição inválida.");
+ return genreArtists(gid, offset);
+ });
+
+ app.get("/api/artists/:aid", async (req) => {
+ const { aid } = req.params as { aid: string };
+ if (!ARTIST_ID.test(aid)) throw new HttpError(400, "Artista inválido.");
+ return artist(aid);
+ });
+
/** The music video for a song, so "Vídeo" mode can show the clip instead of a still cover. */
app.get("/api/video-for/:id", async (req) => {
const { title, artist, duration } = req.query as { title?: string; artist?: string; duration?: string };
@@ -122,6 +148,13 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
return { favorites: await library.addFavorite(track) };
});
+ /** Bulk add, e.g. from the list search. */
+ app.post("/api/favorites", async (req) => {
+ const { tracks } = (req.body ?? {}) as { tracks?: unknown };
+ if (!Array.isArray(tracks)) throw new HttpError(400, "Envie uma lista de faixas.");
+ return { favorites: await library.addFavorites(tracks.slice(0, 500).map(library.sanitizeTrack)) };
+ });
+
app.delete("/api/favorites/:id", async (req) => ({ favorites: await library.removeFavorite(videoId(req.params)) }));
app.post("/api/history", async (req) => ({ history: await library.pushHistory(library.sanitizeTrack(req.body)) }));
@@ -143,9 +176,12 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
return reply.code(204).send();
});
- app.post("/api/playlists/:pid/tracks", async (req) =>
- library.addToPlaylist((req.params as { pid: string }).pid, library.sanitizeTrack(req.body)),
- );
+ /** One track, or `{ tracks: [...] }` to add many at once. */
+ app.post("/api/playlists/:pid/tracks", async (req) => {
+ const body = (req.body ?? {}) as { tracks?: unknown };
+ const tracks = Array.isArray(body.tracks) ? body.tracks.slice(0, 500).map(library.sanitizeTrack) : library.sanitizeTrack(req.body);
+ return library.addToPlaylist((req.params as { pid: string }).pid, tracks);
+ });
app.delete("/api/playlists/:pid/tracks/:id", async (req) =>
library.removeFromPlaylist((req.params as { pid: string }).pid, videoId(req.params)),
diff --git a/server/src/browse.ts b/server/src/browse.ts
new file mode 100644
index 0000000..3bfb5d0
--- /dev/null
+++ b/server/src/browse.ts
@@ -0,0 +1,274 @@
+import type { Innertube } from "youtubei.js";
+import { sized, text, toTrack, withClient } from "./search.js";
+import type { Track } from "./types.js";
+import { HttpError } from "./types.js";
+
+export interface Genre {
+ /** YouTube Music's opaque "params" for the genre page. */
+ id: string;
+ name: string;
+}
+
+export interface GenreArtist {
+ id: string;
+ name: string;
+ /** Cover of one of their releases in this genre (artist photos would cost a request each). */
+ thumb: string;
+ art: string;
+ /** A few of their songs in this genre, to recognize them by. */
+ hits: string[];
+}
+
+export interface GenrePage {
+ id: string;
+ name: string;
+ /** The first page of artists; more come from `genreArtists`. */
+ artists: GenreArtist[];
+ hasMoreArtists: boolean;
+ tracks: Track[];
+}
+
+export interface ArtistPage {
+ id: string;
+ name: string;
+ description: string;
+ banner: string;
+ tracks: Track[];
+}
+
+export const GENRE_ID = /^[\w-]{8,120}={0,2}$/;
+export const ARTIST_ID = /^UC[\w-]{22}$/;
+
+const MINUTE = 60_000;
+const ARTISTS_PAGE = 40;
+/** Enough for anyone browsing; stops reading playlists after that. */
+const MAX_ARTISTS = 600;
+const PLAYLISTS_PER_ROUND = 4;
+const MAX_GENRE_TRACKS = 150;
+const MAX_HITS = 50;
+
+/** Time-boxed memo: these pages change slowly, and going back and forth between them should be instant. */
+function cached<T>(ttl: number, load: (key: string) => Promise<T>): (key: string) => Promise<T> {
+ const memo = new Map<string, { at: number; value: Promise<T> }>();
+ return (key) => {
+ const hit = memo.get(key);
+ if (hit && Date.now() - hit.at < ttl) return hit.value;
+ if (memo.size > 200) memo.delete(memo.keys().next().value!);
+ const value = load(key);
+ memo.set(key, { at: Date.now(), value });
+ // Failures are not cached, so the next visit tries again.
+ value.catch(() => memo.get(key)?.value === value && memo.delete(key));
+ return value;
+ };
+}
+
+// youtubei.js has no typed helper for the genre pages, so these responses are read defensively.
+const browse = (yt: Innertube, payload: Record<string, unknown>): Promise<any> =>
+ yt.actions.execute("/browse", { ...payload, client: "YTMUSIC", parse: true });
+
+function shelvesOf(page: any): any[] {
+ const root = typeof page?.contents?.item === "function" ? page.contents.item() : page?.contents;
+ return root?.tabs?.[0]?.content?.contents ?? [];
+}
+
+const itemsOf = (shelf: any): any[] => shelf?.contents ?? shelf?.items ?? [];
+
+function imagesOf(item: any): { thumb: string; art: string } {
+ const thumbs = item?.thumbnail?.contents ?? item?.thumbnail ?? item?.thumbnails ?? [];
+ const url: string | undefined = Array.isArray(thumbs) ? thumbs[0]?.url : undefined;
+ return { thumb: sized(url, 240), art: sized(url, 544) };
+}
+
+/** Same song twice (another upload, a playlist repeat) only shows once. */
+function uniqueTracks(tracks: (Track | null)[]): Track[] {
+ const seen = new Set<string>();
+ return tracks.filter((t): t is Track => {
+ if (!t) return false;
+ const key = `${t.title}|${t.artist}`.toLocaleLowerCase("pt-BR");
+ if (seen.has(t.id) || seen.has(key)) return false;
+ seen.add(t.id);
+ seen.add(key);
+ return true;
+ });
+}
+
+/** [[a1, a2], [b1]] → [a1, b1, a2] */
+function roundRobin<T>(lists: T[][]): T[] {
+ const out: T[] = [];
+ for (let i = 0; lists.some((l) => i < l.length); i++) for (const l of lists) if (i < l.length) out.push(l[i]!);
+ return out;
+}
+
+/** "Céu Azul (Ao Vivo)" → "Céu Azul": enough to recognize the song in a short preview. */
+const bareTitle = (title: string) => title.replace(/\s*[([].*?[)\]]/g, "").trim() || title;
+
+export const genres = cached(6 * 60 * MINUTE, async (): Promise<Genre[]> => {
+ const page = await withClient((yt) => browse(yt, { browseId: "FEmusic_moods_and_genres" })).catch(() => {
+ throw new HttpError(502, "Não foi possível carregar os gêneros agora. Tente de novo.");
+ });
+ const grids = shelvesOf(page);
+ // The page has "moods" then "genres"; match the title in any language, falling back to the last grid.
+ const grid = grids.find((g) => /g[eéê]ne?r/i.test(text(g.header?.title ?? g.title))) ?? grids.at(-1);
+ return itemsOf(grid)
+ .map((b) => ({ id: String(b.endpoint?.payload?.params ?? ""), name: text(b.button_text ?? b.title) }))
+ .filter((g) => GENRE_ID.test(g.id) && g.name);
+});
+
+async function playlistItems(id: string, limit: number): Promise<any[]> {
+ try {
+ const list = await withClient((yt) => yt.music.getPlaylist(id));
+ return ((list as any).items ?? (list as any).contents ?? []).slice(0, limit);
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Ranks the artists credited on `sources` by how often they show up (times the source's weight),
+ * skipping the ones already `known`. Channels that are not artist pages (labels, uploaders) are left out.
+ */
+function rankArtists(sources: { items: any[]; weight: number; hits: boolean }[], known: Set<string>): GenreArtist[] {
+ const ranked = new Map<string, GenreArtist & { score: number }>();
+ for (const { items, weight, hits } of sources) {
+ for (const item of items) {
+ const hit = hits ? bareTitle(text(item.title)) : "";
+ for (const a of item.artists ?? []) {
+ const pageType = a?.endpoint?.payload?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
+ if (!ARTIST_ID.test(a?.channel_id ?? "") || known.has(a.channel_id)) continue;
+ if (pageType && pageType !== "MUSIC_PAGE_TYPE_ARTIST") continue;
+ let entry = ranked.get(a.channel_id);
+ if (!entry) {
+ entry = { id: a.channel_id, name: text(a.name), ...imagesOf(item), hits: [], score: 0 };
+ ranked.set(a.channel_id, entry);
+ }
+ entry.score += weight;
+ if (hit && entry.hits.length < 3 && !entry.hits.includes(hit)) entry.hits.push(hit);
+ }
+ }
+ }
+ return [...ranked.values()]
+ .filter((a) => a.name)
+ .sort((a, b) => b.score - a.score)
+ .map(({ score: _, ...a }) => a);
+}
+
+/** What a genre has turned up so far. "Load more" keeps reading its playlists for artists not seen yet. */
+interface GenreState {
+ page: GenrePage;
+ /** Every artist found so far, in a fixed order: later pages append, never reshuffle earlier ones. */
+ pool: GenreArtist[];
+ /** Playlists not read yet. */
+ queue: string[];
+ extending?: Promise<void>;
+}
+
+/**
+ * A genre's songs and the artists behind them. The page lists ~50 songs, playlists and albums;
+ * two editorial playlists widen the song list (and are all there is for pages like "Décadas").
+ */
+const genreState = cached(30 * MINUTE, async (id): Promise<GenreState> => {
+ const [all, page] = await Promise.all([
+ genres("").catch(() => [] as Genre[]),
+ withClient((yt) => browse(yt, { browseId: "FEmusic_moods_and_genres_category", params: id })).catch(() => {
+ throw new HttpError(502, "Não foi possível abrir este gênero agora. Tente de novo.");
+ }),
+ ]);
+ const shelves = shelvesOf(page);
+ const items = shelves.flatMap(itemsOf);
+ const songs = items.filter((i) => i.item_type === "song");
+ const albums = items.filter((i) => i.item_type === "album");
+
+ // One playlist from each shelf in turn (so "Décadas" mixes decades), editorial ("RDCLAK...") before
+ // community ones, which are hit and miss.
+ const perShelf = shelves.map((s) => itemsOf(s).filter((i) => i.item_type === "playlist" && typeof i.id === "string"));
+ const editorial = (p: any) => /RDCLAK/.test(p.id);
+ const playlists = [
+ ...new Set(
+ [...roundRobin(perShelf.map((list) => list.filter(editorial))), ...roundRobin(perShelf.map((list) => list.filter((p) => !editorial(p))))].map(
+ (p): string => p.id,
+ ),
+ ),
+ ];
+ const first = songs.length >= 10 ? 2 : 4;
+ const fromPlaylists = (await Promise.all(playlists.slice(0, first).map((p) => playlistItems(p, 60)))).flat();
+
+ const tracks = uniqueTracks([...songs, ...fromPlaylists].map((i) => toTrack(i, "song"))).slice(0, MAX_GENRE_TRACKS);
+ if (!tracks.length && !albums.length) throw new HttpError(404, "Nada encontrado para este gênero.");
+
+ // The genre's own song and album shelves weigh more than playlists.
+ const pool = rankArtists(
+ [
+ { items: songs, weight: 2, hits: true },
+ { items: albums, weight: 2, hits: false },
+ { items: fromPlaylists, weight: 1, hits: true },
+ ],
+ new Set(),
+ );
+ // More artists come from the remaining editorial playlists; community ones only when there is nothing else.
+ const rest = playlists.slice(first);
+ const queue = rest.some((p) => /RDCLAK/.test(p)) ? rest.filter((p) => /RDCLAK/.test(p)) : rest;
+
+ return {
+ page: {
+ id,
+ name: all.find((g) => g.id === id)?.name ?? "",
+ artists: pool.slice(0, ARTISTS_PAGE),
+ hasMoreArtists: pool.length > ARTISTS_PAGE || queue.length > 0,
+ tracks,
+ },
+ pool,
+ queue,
+ };
+});
+
+export const genre = async (id: string): Promise<GenrePage> => (await genreState(id)).page;
+
+/** Reads the next few playlists of the genre and appends the artists they bring. */
+async function extend(state: GenreState): Promise<void> {
+ const batch = state.queue.splice(0, PLAYLISTS_PER_ROUND);
+ const items = (await Promise.all(batch.map((p) => playlistItems(p, 100)))).flat();
+ state.pool.push(...rankArtists([{ items, weight: 1, hits: true }], new Set(state.pool.map((a) => a.id))));
+ if (state.pool.length >= MAX_ARTISTS) state.queue.length = 0;
+}
+
+/** The next page of a genre's artists, reading more of its playlists when the ones found so far run out. */
+export async function genreArtists(id: string, offset: number): Promise<{ artists: GenreArtist[]; hasMore: boolean }> {
+ const state = await genreState(id);
+ // A few rounds at most per request, so a run of playlists with no new names can't stall it.
+ for (let round = 0; round < 5 && state.pool.length < offset + ARTISTS_PAGE && state.queue.length; round++) {
+ // Two "load more" taps at once share the same read instead of skipping playlists.
+ state.extending ??= extend(state).finally(() => (state.extending = undefined));
+ await state.extending;
+ }
+ return {
+ artists: state.pool.slice(offset, offset + ARTISTS_PAGE),
+ hasMore: state.pool.length > offset + ARTISTS_PAGE || state.queue.length > 0,
+ };
+}
+
+/** An artist's most played songs (the "Top songs" shelf, expanded to its full list). */
+export const artist = cached(30 * MINUTE, async (id): Promise<ArtistPage> => {
+ const page = await withClient((yt) => yt.music.getArtist(id)).catch(() => {
+ throw new HttpError(502, "Não foi possível abrir este artista agora. Tente de novo.");
+ });
+ const header: any = page.header;
+ const shelf: any = page.sections.find((s) => s.type === "MusicShelf");
+ let items: any[] = itemsOf(shelf);
+ // The shelf shows 5; its "show all" link is a playlist with the full ranking.
+ const fullList = shelf?.endpoint?.payload?.browseId;
+ if (typeof fullList === "string" && fullList.startsWith("VL")) {
+ const more = await playlistItems(fullList, MAX_HITS * 2);
+ if (more.length) items = more;
+ }
+ const banner = (header?.thumbnail?.contents ?? header?.thumbnail ?? [])[0]?.url;
+ const name = text(header?.title);
+ const tracks = uniqueTracks(items.map((i) => toTrack(i, "song"))).slice(0, MAX_HITS);
+ if (!name && !tracks.length) throw new HttpError(404, "Artista não encontrado.");
+ return {
+ id,
+ name,
+ description: text(header?.description),
+ banner: typeof banner === "string" && banner.startsWith("https://") ? banner : "",
+ tracks,
+ };
+});
diff --git a/server/src/library.ts b/server/src/library.ts
index 56a0d02..7ec0242 100644
--- a/server/src/library.ts
+++ b/server/src/library.ts
@@ -72,6 +72,16 @@ export async function addFavorite(track: Track): Promise<Track[]> {
return lib.favorites;
}
+/** Adds many at once (in the given order, on top), skipping ones already there. */
+export async function addFavorites(tracks: Track[]): Promise<Track[]> {
+ const lib = await load();
+ const seen = new Set(lib.favorites.map((t) => t.id));
+ const added = tracks.filter((t) => !seen.has(t.id) && !!seen.add(t.id));
+ lib.favorites = [...added, ...lib.favorites];
+ await persist();
+ return lib.favorites;
+}
+
export async function removeFavorite(id: string): Promise<Track[]> {
const lib = await load();
lib.favorites = lib.favorites.filter((t) => t.id !== id);
@@ -115,10 +125,12 @@ export async function deletePlaylist(pid: string): Promise<void> {
await persist();
}
-export async function addToPlaylist(pid: string, track: Track): Promise<Playlist> {
+export async function addToPlaylist(pid: string, tracks: Track | Track[]): Promise<Playlist> {
const lib = await load();
const p = findPlaylist(lib, pid);
- if (!p.tracks.some((t) => t.id === track.id)) p.tracks.push(track);
+ for (const track of Array.isArray(tracks) ? tracks : [tracks]) {
+ if (!p.tracks.some((t) => t.id === track.id)) p.tracks.push(track);
+ }
p.updatedAt = Date.now();
await persist();
return p;
diff --git a/server/src/search.ts b/server/src/search.ts
index e7d0fe8..f7cca5b 100644
--- a/server/src/search.ts
+++ b/server/src/search.ts
@@ -15,7 +15,7 @@ function yt(): Promise<Innertube> {
}
/** Retries once with a fresh InnerTube session, since sessions can go stale. */
-async function withClient<T>(fn: (yt: Innertube) => Promise<T>): Promise<T> {
+export async function withClient<T>(fn: (yt: Innertube) => Promise<T>): Promise<T> {
try {
return await fn(await yt());
} catch {
@@ -24,7 +24,7 @@ async function withClient<T>(fn: (yt: Innertube) => Promise<T>): Promise<T> {
}
}
-function sized(url: string | undefined, px: number): string {
+export function sized(url: string | undefined, px: number): string {
if (!url) return "";
// googleusercontent / ggpht thumbnails encode their size after "="
if (/googleusercontent\.com|ggpht\.com/.test(url)) return url.replace(/=w\d+-h\d+[^&]*$/, `=w${px}-h${px}-l90-rj`);
@@ -36,10 +36,10 @@ function videoThumbs(id: string) {
return { thumb: `https://i.ytimg.com/vi/${id}/mqdefault.jpg`, art: `https://i.ytimg.com/vi/${id}/hq720.jpg` };
}
-const text = (v: unknown): string => (v == null ? "" : typeof v === "string" ? v : String((v as { toString(): string }).toString()));
+export const text = (v: unknown): string => (v == null ? "" : typeof v === "string" ? v : String((v as { toString(): string }).toString()));
// youtubei.js node shapes differ between item types, so read them defensively.
-function toTrack(item: any, kind: Track["kind"]): Track | null {
+export function toTrack(item: any, kind: Track["kind"]): Track | null {
const id: string | undefined = item.id ?? item.video_id;
if (!id || !VIDEO_ID.test(id)) return null;
const artists: string[] = (item.artists ?? item.authors ?? []).map((a: { name: string }) => a.name).filter(Boolean);
diff --git a/web/package.json b/web/package.json
index 455951e..a0e0b5d 100644
--- a/web/package.json
+++ b/web/package.json
@@ -1,7 +1,7 @@
{
"name": "@musike/web",
"private": true,
- "version": "0.1.0",
+ "version": "1.1.0",
"type": "module",
"scripts": {
"dev": "vite --host",
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 3e42ebb..3a0b0e0 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef } from "react";
-import { Route, Routes, useLocation, useNavigate } from "react-router";
+import { useEffect, useLayoutEffect, useRef } from "react";
+import { Route, Routes, useLocation, useNavigate, useNavigationType } from "react-router";
import { AddToPlaylistDialog, ShortcutsDialog } from "./components/Dialogs";
import { MiniPlayer, TabBar } from "./components/MobileChrome";
import { NowPlayingSheet, PanelDrawer, SidePanel } from "./components/NowPlaying";
@@ -18,7 +18,10 @@ import { usePlayer } from "./player/player";
import { useLibrary } from "./stores/library";
import { openSettings, useSystem } from "./stores/system";
import { toast, useUi } from "./stores/ui";
+import Artist from "./views/Artist";
+import BatchSearch from "./views/BatchSearch";
import Collection from "./views/Collection";
+import Genre from "./views/Genre";
import Home from "./views/Home";
import Library from "./views/Library";
import Search from "./views/Search";
@@ -28,6 +31,7 @@ const SHEET_HASH = "#tocando";
export default function App() {
const location = useLocation();
const navigate = useNavigate();
+ const navigationType = useNavigationType();
const isMd = useMediaQuery(MD);
const panelOpen = useUi((s) => s.panelOpen);
const hasTrack = usePlayer((s) => s.queue.length > 0);
@@ -65,9 +69,25 @@ export default function App() {
return () => clearTimeout(t);
}, [loadSystem]);
- // New page, back to the top (the sheet hash is not a page change).
+ // Where each history entry was scrolled to, so Back returns to the same spot (say, deep in a genre's artists).
+ const scrollMemo = useRef(new Map<string, number>());
+ const entryKey = useRef(location.key);
useEffect(() => {
+ const el = main.current;
+ if (!el) return;
+ const onScroll = () => scrollMemo.current.set(entryKey.current, el.scrollTop);
+ el.addEventListener("scroll", onScroll, { passive: true });
+ return () => el.removeEventListener("scroll", onScroll);
+ }, []);
+
+ // New page, back to the top; Back and Forward return to where it was (the sheet hash is not a page change).
+ // A layout effect, so the scroll the old page's removal causes is already filed under the new entry.
+ useLayoutEffect(() => {
+ entryKey.current = location.key;
+ const saved = navigationType === "POP" ? scrollMemo.current.get(location.key) : undefined;
main.current?.scrollTo({ top: 0 });
+ // Pages that keep their data (genre, artist) render in full right away, so one frame is enough.
+ if (saved) requestAnimationFrame(() => main.current?.scrollTo({ top: saved }));
}, [location.pathname]);
const sheetOpen = !isMd && location.hash === SHEET_HASH;
@@ -94,6 +114,9 @@ export default function App() {
<Routes>
<Route path="/" element={<Home />} />
<Route path="/buscar" element={<Search />} />
+ <Route path="/buscar/lista" element={<BatchSearch />} />
+ <Route path="/buscar/genero/:id" element={<Genre />} />
+ <Route path="/buscar/artista/:id" element={<Artist />} />
<Route path="/biblioteca" element={<Library />} />
<Route path="/favoritas" element={<Collection kind="favorites" />} />
<Route path="/historico" element={<Collection kind="history" />} />
diff --git a/web/src/components/Dialogs.tsx b/web/src/components/Dialogs.tsx
index 649aec4..30b4d5c 100644
--- a/web/src/components/Dialogs.tsx
+++ b/web/src/components/Dialogs.tsx
@@ -7,30 +7,35 @@ import { Artwork } from "./Artwork";
import { Modal } from "./Modal";
export function AddToPlaylistDialog() {
- const track = useUi((s) => s.addToPlaylist);
+ const tracks = useUi((s) => s.addToPlaylist);
const close = useUi((s) => s.openAddToPlaylist);
const playlists = useLibrary((s) => s.playlists);
const add = useLibrary((s) => s.addToPlaylist);
const create = useLibrary((s) => s.createPlaylist);
const [creating, setCreating] = useState(false);
const [name, setName] = useState("");
+ const many = !!tracks && tracks.length > 1;
useEffect(() => {
- if (track) {
+ if (tracks) {
setCreating(playlists.length === 0);
setName("");
}
- }, [track]);
+ }, [tracks]);
const onCreate = async (e: FormEvent) => {
e.preventDefault();
- if (!track || !name.trim()) return;
- const p = await create(name, [track]);
+ if (!tracks || !name.trim()) return;
+ const p = await create(name, tracks);
if (p) close(null);
};
return (
- <Modal open={!!track} onClose={() => close(null)} title="Adicionar à playlist">
+ <Modal
+ open={!!tracks}
+ onClose={() => close(null)}
+ title={many ? `Adicionar ${tracks?.length} faixas à playlist` : "Adicionar à playlist"}
+ >
{creating ? (
<form onSubmit={onCreate} className="flex flex-col gap-3">
<label htmlFor="new-playlist" className="text-sm text-fg-2">
@@ -73,15 +78,16 @@ export function AddToPlaylistDialog() {
<span className="font-medium">Nova playlist</span>
</button>
{playlists.map((p) => {
- const has = !!track && p.tracks.some((t) => t.id === track.id);
+ // Done only when it already has every track being added.
+ const has = !!tracks && tracks.every((x) => p.tracks.some((t) => t.id === x.id));
return (
<button
key={p.id}
type="button"
disabled={has}
onClick={() => {
- if (!track) return;
- void add(p.id, track);
+ if (!tracks) return;
+ void add(p.id, many ? tracks : tracks[0]);
close(null);
}}
className={cn("flex items-center gap-3 rounded-xl px-2 py-2 text-left hover:bg-surface-3", has && "opacity-60")}
diff --git a/web/src/components/GenrePanel.tsx b/web/src/components/GenrePanel.tsx
new file mode 100644
index 0000000..83f1e5d
--- /dev/null
+++ b/web/src/components/GenrePanel.tsx
@@ -0,0 +1,48 @@
+import { Link } from "react-router";
+import { useRemote } from "../hooks/useRemote";
+import { api } from "../lib/api";
+import type { Genre } from "../lib/types";
+
+/** YouTube Music's genre list as chips; each opens the genre's artists and songs. */
+export function GenrePanel({ id }: { id: string }) {
+ const genres = useRemote<Genre[]>("genres", () => api.genres());
+
+ return (
+ <div id={id} className="rounded-[16px] bg-surface-2 p-3 ring-1 ring-line">
+ <p className="mb-2.5 px-1 text-xs font-medium text-fg-2">Explorar por gênero</p>
+
+ {genres.status === "loading" && (
+ <div aria-label="Carregando" className="flex flex-wrap gap-2">
+ {Array.from({ length: 14 }, (_, i) => (
+ <span key={i} className="skeleton h-9 rounded-full" style={{ width: `${64 + ((i * 23) % 56)}px` }} />
+ ))}
+ </div>
+ )}
+
+ {genres.status === "error" && (
+ <p className="px-1 text-sm text-fg-2">
+ {genres.message}{" "}
+ <button type="button" onClick={genres.retry} className="font-medium text-fg underline-offset-2 hover:underline">
+ Tentar de novo
+ </button>
+ </p>
+ )}
+
+ {genres.status === "ok" && (
+ <ul className="flex flex-wrap gap-2">
+ {genres.data.map((g) => (
+ <li key={g.id}>
+ <Link
+ to={`/buscar/genero/${encodeURIComponent(g.id)}`}
+ state={{ name: g.name }}
+ className="block h-9 rounded-full bg-surface-3 px-4 text-sm leading-9 transition-colors hover:bg-surface-4"
+ >
+ {g.name}
+ </Link>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/Page.tsx b/web/src/components/Page.tsx
index 30507ce..680b87b 100644
--- a/web/src/components/Page.tsx
+++ b/web/src/components/Page.tsx
@@ -1,5 +1,6 @@
-import { GearSixIcon } from "@phosphor-icons/react";
+import { ArrowLeftIcon, GearSixIcon } from "@phosphor-icons/react";
import type { ReactNode } from "react";
+import { useNavigate } from "react-router";
import { cn } from "../lib/format";
import { needsAttention, useSystem } from "../stores/system";
import { useUi } from "../stores/ui";
@@ -60,6 +61,20 @@ export function Section({ title, action, children, className }: { title: string;
);
}
+/** Back in history when there is somewhere to go back to (in the app), else to `fallback`. */
+export function BackButton({ fallback, label = "Voltar" }: { fallback: string; label?: string }) {
+ const navigate = useNavigate();
+ return (
+ <button
+ type="button"
+ onClick={() => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate(fallback))}
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-full px-3 text-sm font-medium text-fg-2 hover:bg-surface-3 hover:text-fg"
+ >
+ <ArrowLeftIcon size={16} /> {label}
+ </button>
+ );
+}
+
export function EmptyState({ icon, title, body, action }: { icon: ReactNode; title: string; body: string; action?: ReactNode }) {
return (
<div className="flex flex-col items-center gap-3 px-6 py-16 text-center">
diff --git a/web/src/components/Selection.tsx b/web/src/components/Selection.tsx
new file mode 100644
index 0000000..8649a83
--- /dev/null
+++ b/web/src/components/Selection.tsx
@@ -0,0 +1,244 @@
+import { CheckIcon, HeartIcon, PlayIcon, PlaylistIcon, VideoCameraIcon } from "@phosphor-icons/react";
+import { useState, type ReactNode } from "react";
+import { cn, formatTime, plural } from "../lib/format";
+import type { Track } from "../lib/types";
+import { selectCurrent, usePlayer } from "../player/player";
+import { useLibrary } from "../stores/library";
+import { useUi } from "../stores/ui";
+import { Artwork } from "./Artwork";
+import { Equalizer } from "./Brand";
+
+export function Check({ on }: { on: boolean }) {
+ return (
+ <span
+ className={cn(
+ "grid size-6 shrink-0 place-items-center rounded-md ring-1 transition-colors",
+ on ? "bg-accent text-accent-ink ring-accent" : "ring-line-strong",
+ )}
+ >
+ {on && <CheckIcon size={15} weight="bold" />}
+ </span>
+ );
+}
+
+function Action({
+ icon,
+ label,
+ onClick,
+ disabled,
+ primary,
+}: {
+ icon: ReactNode;
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+ primary?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={label}
+ title={label}
+ className={cn(
+ "flex h-9 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-sm font-medium whitespace-nowrap transition-transform active:scale-[0.97] disabled:opacity-40 sm:px-3.5",
+ primary ? "bg-accent text-accent-ink" : "bg-surface-3 text-fg hover:bg-surface-4",
+ )}
+ >
+ {icon}
+ {/* Phones keep only "Tocar"; the icons are familiar enough for the rest. */}
+ {primary ? <Short phone="Tocar" wide={label} /> : <span className="hidden sm:inline">{label}</span>}
+ </button>
+ );
+}
+
+/** Phones get the short text, so the bar keeps its buttons on one line at 320 px. */
+export function Short({ phone, wide }: { phone: ReactNode; wide: ReactNode }) {
+ return (
+ <>
+ <span className="sm:hidden">{phone}</span>
+ <span className="hidden sm:inline">{wide}</span>
+ </>
+ );
+}
+
+/** "3 de 150 músicas", or "3 de 150" on phones. */
+export function SelectedCount({ n, total }: { n: number; total: number }) {
+ return <Short phone={`${n} de ${total}`} wide={`${n} de ${plural(total, "música", "músicas")}`} />;
+}
+
+/**
+ * Sticky bar under the page header: select all, then play, favorite or add the selection to a playlist.
+ * With nothing selected, "Tocar tudo" plays every track.
+ */
+export function SelectionBar({
+ chosen,
+ all,
+ allSelected,
+ onToggleAll,
+ label,
+ className,
+}: {
+ chosen: Track[];
+ all: Track[];
+ allSelected: boolean;
+ onToggleAll: () => void;
+ label: ReactNode;
+ className?: string;
+}) {
+ const playList = usePlayer((s) => s.playList);
+ const addFavorites = useLibrary((s) => s.addFavorites);
+ const openAddToPlaylist = useUi((s) => s.openAddToPlaylist);
+ const toPlay = chosen.length ? chosen : all;
+
+ return (
+ <div
+ className={cn(
+ "sticky top-[calc(3.5rem+env(safe-area-inset-top))] z-[5] border-b border-line bg-bg/80 px-4 py-2.5 backdrop-blur-xl md:top-16 md:bg-surface-1/80 md:px-6",
+ className,
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={allSelected}
+ disabled={!all.length}
+ onClick={onToggleAll}
+ className="flex h-9 min-w-0 items-center gap-2 rounded-full pr-1 pl-1.5 text-sm font-medium text-fg-2 hover:text-fg disabled:opacity-40 sm:pr-3"
+ >
+ <Check on={allSelected} />
+ <span className="truncate">{label}</span>
+ </button>
+ <span className="flex-1" />
+ <Action
+ primary
+ icon={<PlayIcon size={16} weight="fill" />}
+ label={chosen.length ? "Tocar" : "Tocar tudo"}
+ disabled={!toPlay.length}
+ onClick={() => playList(toPlay, 0)}
+ />
+ <Action icon={<HeartIcon size={16} />} label="Favoritar" disabled={!chosen.length} onClick={() => void addFavorites(chosen)} />
+ <Action icon={<PlaylistIcon size={16} />} label="Playlist" disabled={!chosen.length} onClick={() => openAddToPlaylist(chosen)} />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A track row with a checkbox. The artwork plays; the title toggles the selection,
+ * so picking many songs is a run of taps on the text.
+ */
+export function SelectableRow({
+ track,
+ selected,
+ onToggle,
+ onPlay,
+ position,
+ note,
+ trailing,
+}: {
+ track: Track;
+ selected: boolean;
+ onToggle: () => void;
+ onPlay: () => void;
+ position?: number;
+ /** Extra context after the artist, e.g. what was searched. */
+ note?: ReactNode;
+ trailing?: ReactNode;
+}) {
+ const isCurrent = usePlayer((s) => selectCurrent(s)?.id === track.id);
+ const isPlaying = usePlayer((s) => s.status === "playing" || s.status === "loading");
+ const isFavorite = useLibrary((s) => s.favorites.some((t) => t.id === track.id));
+
+ return (
+ <div className="group flex items-center gap-3 rounded-xl px-2 py-1.5 transition-colors hover:bg-surface-2 md:px-3">
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={selected}
+ aria-label={`Selecionar ${track.title}`}
+ onClick={onToggle}
+ className="-m-2 p-2"
+ >
+ <Check on={selected} />
+ </button>
+
+ {position !== undefined && (
+ <span className="hidden w-6 shrink-0 text-center font-mono text-[13px] text-fg-3 tabular-nums md:block">{position}</span>
+ )}
+
+ <button type="button" onClick={onPlay} aria-label={`Tocar ${track.title}`} className="group/art relative shrink-0">
+ <Artwork src={track.thumb} className="size-11 rounded-[10px]" />
+ <span
+ className={cn(
+ "absolute inset-0 grid place-items-center rounded-[10px] bg-black/45 text-white transition-opacity",
+ isCurrent ? "opacity-100" : "opacity-0 group-hover/art:opacity-100 group-focus-visible/art:opacity-100",
+ )}
+ >
+ {isCurrent ? <Equalizer live={isPlaying} /> : <PlayIcon size={18} weight="fill" />}
+ </span>
+ </button>
+
+ <button type="button" onClick={onToggle} className={cn("min-w-0 flex-1 text-left", !selected && "opacity-60")}>
+ <span className={cn("block truncate text-[15px] leading-tight font-medium", isCurrent && "text-accent-text")}>{track.title}</span>
+ <span className="mt-0.5 flex items-center gap-1.5 text-[13px] text-fg-2">
+ {track.kind === "video" && <VideoCameraIcon size={13} className="shrink-0 text-fg-3" aria-label="Vídeo" />}
+ <span className="truncate">
+ {track.artist || "YouTube"}
+ {note}
+ </span>
+ </span>
+ </button>
+
+ {isFavorite && <HeartIcon size={15} weight="fill" className="shrink-0 text-accent-text" aria-label="Nas Favoritas" />}
+
+ <span className="hidden w-11 shrink-0 text-right font-mono text-[13px] text-fg-3 tabular-nums md:block">
+ {track.duration ? formatTime(track.duration) : ""}
+ </span>
+
+ {trailing}
+ </div>
+ );
+}
+
+/** A plain list of tracks to pick from, with its own selection bar. Remount (via `key`) to reset the selection. */
+export function SelectableTrackList({ tracks, numbered }: { tracks: Track[]; numbered?: boolean }) {
+ const [selected, setSelected] = useState<Set<string>>(() => new Set());
+ const playList = usePlayer((s) => s.playList);
+ const chosen = tracks.filter((t) => selected.has(t.id));
+ const allSelected = tracks.length > 0 && chosen.length === tracks.length;
+
+ const toggle = (id: string) =>
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (!next.delete(id)) next.add(id);
+ return next;
+ });
+
+ return (
+ <>
+ <SelectionBar
+ chosen={chosen}
+ all={tracks}
+ allSelected={allSelected}
+ onToggleAll={() => setSelected(allSelected ? new Set() : new Set(tracks.map((t) => t.id)))}
+ label={chosen.length ? <SelectedCount n={chosen.length} total={tracks.length} /> : <Short phone="Todas" wide="Selecionar todas" />}
+ />
+ <ul className="mt-2 flex flex-col px-2 md:px-3">
+ {tracks.map((t, i) => (
+ <li key={t.id}>
+ <SelectableRow
+ track={t}
+ position={numbered ? i + 1 : undefined}
+ selected={selected.has(t.id)}
+ onToggle={() => toggle(t.id)}
+ onPlay={() => playList(tracks, i)}
+ />
+ </li>
+ ))}
+ </ul>
+ </>
+ );
+}
diff --git a/web/src/components/TrackMenu.tsx b/web/src/components/TrackMenu.tsx
index b63b530..eb6404b 100644
--- a/web/src/components/TrackMenu.tsx
+++ b/web/src/components/TrackMenu.tsx
@@ -91,7 +91,7 @@ export function TrackMenu() {
>
{isFavorite ? "Remover das Favoritas" : "Adicionar às Favoritas"}
</Item>
- <Item icon={<PlaylistIcon size={18} />} onClick={() => openAddToPlaylist(menu.track)}>
+ <Item icon={<PlaylistIcon size={18} />} onClick={() => openAddToPlaylist([menu.track])}>
Adicionar à playlist
</Item>
{menu.playlistId && (
diff --git a/web/src/hooks/useRemote.ts b/web/src/hooks/useRemote.ts
new file mode 100644
index 0000000..619a3a7
--- /dev/null
+++ b/web/src/hooks/useRemote.ts
@@ -0,0 +1,29 @@
+import { useEffect, useState } from "react";
+
+export type Remote<T> = { status: "loading" } | { status: "ok"; data: T } | { status: "error"; message: string };
+
+// Session memo, so going back from an artist to its genre shows the page instantly.
+const memo = new Map<string, unknown>();
+const MEMO_LIMIT = 60;
+
+/** Loads `key` once per session; `retry` refetches after an error. */
+export function useRemote<T>(key: string, load: (signal: AbortSignal) => Promise<T>): Remote<T> & { retry: () => void } {
+ const [state, setState] = useState<Remote<T>>(() => (memo.has(key) ? { status: "ok", data: memo.get(key) as T } : { status: "loading" }));
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ if (memo.has(key)) return setState({ status: "ok", data: memo.get(key) as T });
+ const ctrl = new AbortController();
+ setState({ status: "loading" });
+ load(ctrl.signal)
+ .then((data) => {
+ if (memo.size >= MEMO_LIMIT) memo.delete(memo.keys().next().value!);
+ memo.set(key, data);
+ setState({ status: "ok", data });
+ })
+ .catch((e: Error) => e.name !== "AbortError" && setState({ status: "error", message: e.message }));
+ return () => ctrl.abort();
+ }, [key, attempt]);
+
+ return { ...state, retry: () => setAttempt((n) => n + 1) };
+}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index c66e49d..416ef7c 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1,4 +1,4 @@
-import type { Library, Playlist, Track } from "./types";
+import type { ArtistPage, Genre, GenreArtist, GenrePage, Library, Playlist, Track } from "./types";
export type ErrorCode = "tool_missing" | "maybe_outdated" | "bot_check";
@@ -62,6 +62,11 @@ export const api = {
suggest: (q: string, signal?: AbortSignal) =>
request<{ suggestions: string[] }>(`/api/suggest?q=${encodeURIComponent(q)}`, { signal }).then((r) => r.suggestions),
radio: (id: string) => request<{ tracks: Track[] }>(`/api/radio/${id}`).then((r) => r.tracks),
+ genres: () => request<{ genres: Genre[] }>("/api/genres").then((r) => r.genres),
+ genre: (id: string, signal?: AbortSignal) => request<GenrePage>(`/api/genres/${encodeURIComponent(id)}`, { signal }),
+ genreArtists: (id: string, offset: number) =>
+ request<{ artists: GenreArtist[]; hasMore: boolean }>(`/api/genres/${encodeURIComponent(id)}/artists?offset=${offset}`),
+ artist: (id: string, signal?: AbortSignal) => request<ArtistPage>(`/api/artists/${encodeURIComponent(id)}`, { signal }),
/** The music video matching a song, or null when YouTube has none. */
videoFor: (t: Track) =>
request<{ track: Track | null }>(
@@ -75,13 +80,15 @@ export const api = {
library: () => request<Library>("/api/library"),
addFavorite: (t: Track) => request<{ favorites: Track[] }>(`/api/favorites/${t.id}`, { method: "PUT", json: t }),
+ addFavorites: (tracks: Track[]) => request<{ favorites: Track[] }>("/api/favorites", { method: "POST", json: { tracks } }),
removeFavorite: (id: string) => request<{ favorites: Track[] }>(`/api/favorites/${id}`, { method: "DELETE" }),
pushHistory: (t: Track) => request<{ history: Track[] }>("/api/history", { method: "POST", json: t }),
createPlaylist: (name: string, tracks: Track[] = []) =>
request<Playlist>("/api/playlists", { method: "POST", json: { name, tracks } }),
renamePlaylist: (id: string, name: string) => request<Playlist>(`/api/playlists/${id}`, { method: "PATCH", json: { name } }),
deletePlaylist: (id: string) => request<void>(`/api/playlists/${id}`, { method: "DELETE" }),
- addToPlaylist: (id: string, t: Track) => request<Playlist>(`/api/playlists/${id}/tracks`, { method: "POST", json: t }),
+ addToPlaylist: (id: string, t: Track | Track[]) =>
+ request<Playlist>(`/api/playlists/${id}/tracks`, { method: "POST", json: Array.isArray(t) ? { tracks: t } : t }),
removeFromPlaylist: (id: string, trackId: string) =>
request<Playlist>(`/api/playlists/${id}/tracks/${trackId}`, { method: "DELETE" }),
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
index ae10d6a..46f7a6a 100644
--- a/web/src/lib/types.ts
+++ b/web/src/lib/types.ts
@@ -22,3 +22,35 @@ export interface Library {
playlists: Playlist[];
history: Track[];
}
+
+export interface Genre {
+ id: string;
+ name: string;
+}
+
+export interface GenreArtist {
+ id: string;
+ name: string;
+ /** Cover of one of their releases in the genre. */
+ thumb: string;
+ art: string;
+ /** A few of their songs in the genre. */
+ hits: string[];
+}
+
+export interface GenrePage {
+ id: string;
+ name: string;
+ /** First page of artists; `api.genreArtists` brings the next ones. */
+ artists: GenreArtist[];
+ hasMoreArtists: boolean;
+ tracks: Track[];
+}
+
+export interface ArtistPage {
+ id: string;
+ name: string;
+ description: string;
+ banner: string;
+ tracks: Track[];
+}
diff --git a/web/src/stores/library.ts b/web/src/stores/library.ts
index 2e05def..7b9f5c1 100644
--- a/web/src/stores/library.ts
+++ b/web/src/stores/library.ts
@@ -8,11 +8,12 @@ interface LibraryState extends Library {
load: () => Promise<void>;
isFavorite: (id: string) => boolean;
toggleFavorite: (t: Track) => Promise<void>;
+ addFavorites: (tracks: Track[]) => Promise<void>;
recordPlay: (t: Track) => void;
createPlaylist: (name: string, tracks?: Track[]) => Promise<Playlist | null>;
renamePlaylist: (id: string, name: string) => Promise<void>;
deletePlaylist: (id: string) => Promise<void>;
- addToPlaylist: (id: string, t: Track) => Promise<void>;
+ addToPlaylist: (id: string, t: Track | Track[]) => Promise<void>;
removeFromPlaylist: (id: string, trackId: string) => Promise<void>;
}
@@ -51,6 +52,21 @@ export const useLibrary = create<LibraryState>((set, get) => ({
}
},
+ addFavorites: async (tracks) => {
+ const prev = get().favorites;
+ const fresh = tracks.filter((t) => !prev.some((f) => f.id === t.id));
+ if (!fresh.length) return toast("Já estavam todas nas Favoritas");
+ set({ favorites: [...fresh, ...prev] });
+ try {
+ const { favorites } = await api.addFavorites(fresh);
+ set({ favorites });
+ toast(fresh.length === 1 ? "Adicionada às Favoritas" : `${fresh.length} faixas adicionadas às Favoritas`);
+ } catch (e) {
+ set({ favorites: prev });
+ toast((e as Error).message, "error");
+ }
+ },
+
recordPlay: (track) => {
set((s) => ({ history: [track, ...s.history.filter((t) => t.id !== track.id)].slice(0, 60) }));
api.pushHistory(track).catch(() => {});
@@ -89,11 +105,14 @@ export const useLibrary = create<LibraryState>((set, get) => ({
}
},
- addToPlaylist: async (id, track) => {
+ addToPlaylist: async (id, tracks) => {
try {
- const p = await api.addToPlaylist(id, track);
+ const before = get().playlists.find((p) => p.id === id)?.tracks.length ?? 0;
+ const p = await api.addToPlaylist(id, tracks);
set((s) => ({ playlists: replacePlaylist(s.playlists, p) }));
- toast(`Adicionada a "${p.name}"`);
+ const added = p.tracks.length - before;
+ if (!Array.isArray(tracks) || added === 1) toast(`Adicionada a "${p.name}"`);
+ else toast(added ? `${added} faixas adicionadas a "${p.name}"` : `Já estavam todas em "${p.name}"`);
} catch (e) {
toast((e as Error).message, "error");
}
diff --git a/web/src/stores/ui.ts b/web/src/stores/ui.ts
index 2f25a73..ad2e340 100644
--- a/web/src/stores/ui.ts
+++ b/web/src/stores/ui.ts
@@ -32,7 +32,8 @@ interface UiState {
panelTab: PanelTab;
toasts: Toast[];
menu: TrackMenuState | null;
- addToPlaylist: Track | null;
+ /** Tracks waiting for the "add to playlist" dialog: one from a track menu, many from the list search. */
+ addToPlaylist: Track[] | null;
shortcutsOpen: boolean;
settingsOpen: boolean;
/** Cinema view: the video maximized over everything. */
@@ -46,7 +47,7 @@ interface UiState {
dismissToast: (id: number) => void;
openMenu: (m: TrackMenuState) => void;
closeMenu: () => void;
- openAddToPlaylist: (t: Track | null) => void;
+ openAddToPlaylist: (tracks: Track[] | null) => void;
setShortcutsOpen: (open: boolean) => void;
setSettingsOpen: (open: boolean) => void;
setTheater: (open: boolean) => void;
diff --git a/web/src/views/Artist.tsx b/web/src/views/Artist.tsx
new file mode 100644
index 0000000..274a992
--- /dev/null
+++ b/web/src/views/Artist.tsx
@@ -0,0 +1,79 @@
+import { MusicNotesIcon, WarningCircleIcon } from "@phosphor-icons/react";
+import { useState } from "react";
+import { useLocation, useParams } from "react-router";
+import { Artwork } from "../components/Artwork";
+import { BackButton, EmptyState, PageHeader } from "../components/Page";
+import { SelectableTrackList } from "../components/Selection";
+import { TrackListSkeleton } from "../components/TrackList";
+import { useRemote } from "../hooks/useRemote";
+import { api } from "../lib/api";
+import { cn } from "../lib/format";
+import type { ArtistPage } from "../lib/types";
+
+/** An artist's greatest hits, ready to pick from. */
+export default function Artist() {
+ const { id = "" } = useParams();
+ const location = useLocation();
+ const page = useRemote<ArtistPage>(`artist:${id}`, (signal) => api.artist(id, signal));
+ const [fullBio, setFullBio] = useState(false);
+ const name = (page.status === "ok" && page.data.name) || (location.state as { name?: string } | null)?.name || "Artista";
+
+ return (
+ <div className="pb-8">
+ <PageHeader title={name} actions={<BackButton fallback="/buscar" />} />
+
+ <div className="relative mx-4 overflow-hidden rounded-[20px] bg-surface-2 ring-1 ring-line md:mx-6">
+ {page.status === "ok" && page.data.banner && (
+ <div className="absolute inset-0">
+ <Artwork src={page.data.banner} className="size-full" />
+ </div>
+ )}
+ {page.status === "loading" && <div className="skeleton absolute inset-0" />}
+ <div aria-hidden="true" className="absolute inset-0 bg-linear-to-t from-black/80 via-black/25 to-transparent" />
+ <div className="relative flex min-h-44 flex-col justify-end gap-1 p-5 md:min-h-60 md:p-8">
+ <span className="text-xs font-medium text-white/75">Artista</span>
+ <h1 className="text-[28px] leading-[1.1] font-bold tracking-tight break-words text-white md:text-5xl">{name}</h1>
+ </div>
+ </div>
+
+ {page.status === "ok" && page.data.description && (
+ <button
+ type="button"
+ onClick={() => setFullBio((v) => !v)}
+ aria-expanded={fullBio}
+ className={cn("mx-4 mt-4 max-w-[75ch] text-left text-sm text-fg-2 hover:text-fg md:mx-6", !fullBio && "line-clamp-3")}
+ >
+ {page.data.description}
+ </button>
+ )}
+
+ <h2 className="px-4 pt-6 pb-1 text-xl font-semibold tracking-tight md:px-6">Maiores sucessos</h2>
+
+ {page.status === "loading" && <TrackListSkeleton />}
+
+ {page.status === "error" && (
+ <EmptyState
+ icon={<WarningCircleIcon size={28} />}
+ title="Não deu para abrir este artista"
+ body={page.message}
+ action={
+ <button
+ type="button"
+ onClick={page.retry}
+ className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm font-medium hover:bg-surface-4"
+ >
+ Tentar de novo
+ </button>
+ }
+ />
+ )}
+
+ {page.status === "ok" &&
+ (page.data.tracks.length ? (
+ <SelectableTrackList key={id} tracks={page.data.tracks} numbered />
+ ) : (
+ <EmptyState icon={<MusicNotesIcon size={28} />} title="Nenhuma música encontrada" body="O YouTube Music não lista sucessos para este artista." />
+ ))}
+ </div>
+ );
+}
diff --git a/web/src/views/BatchSearch.tsx b/web/src/views/BatchSearch.tsx
new file mode 100644
index 0000000..142cecc
--- /dev/null
+++ b/web/src/views/BatchSearch.tsx
@@ -0,0 +1,303 @@
+import { ArrowLeftIcon, ArrowsClockwiseIcon, CaretDownIcon, CheckIcon, ListBulletsIcon, WarningCircleIcon } from "@phosphor-icons/react";
+import { useEffect, useRef, useState } from "react";
+import { Link, useLocation, useNavigate } from "react-router";
+import { create } from "zustand";
+import { Artwork } from "../components/Artwork";
+import { EmptyState, PageHeader } from "../components/Page";
+import { SelectableRow, SelectedCount, SelectionBar } from "../components/Selection";
+import { api } from "../lib/api";
+import { cn, plural } from "../lib/format";
+import type { Track } from "../lib/types";
+import { usePlayer } from "../player/player";
+
+const MAX_TERMS = 50;
+/** Results kept per term, so a wrong first match can be swapped for the right one. */
+const OPTIONS = 5;
+const CONCURRENCY = 3;
+
+/** "a, b\nc, a" → ["a", "b", "c"]. Commas or line breaks separate songs; repeats are dropped. */
+export function parseList(text: string): string[] {
+ const seen = new Set<string>();
+ return text
+ .split(/[,\n]+/)
+ .map((s) => s.trim())
+ .filter((s) => {
+ const key = s.toLocaleLowerCase("pt-BR");
+ if (!s || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
+ .slice(0, MAX_TERMS);
+}
+
+interface Entry {
+ query: string;
+ status: "loading" | "ok" | "empty" | "error";
+ options: Track[];
+ pick: number;
+ selected: boolean;
+}
+
+interface BatchState {
+ text: string;
+ entries: Entry[];
+ setText: (text: string) => void;
+ run: (terms: string[]) => Promise<void>;
+ retry: (i: number) => void;
+ update: (i: number, patch: Partial<Entry>) => void;
+ selectAll: (on: boolean) => void;
+}
+
+// Bumped on every new run, so slow answers from an older list never land in the new one.
+let runId = 0;
+
+// Module-level store: the list survives leaving the page to play or check a playlist and coming back.
+const useBatch = create<BatchState>((set, get) => {
+ const lookup = async (id: number, i: number) => {
+ const query = get().entries[i]?.query;
+ if (!query) return;
+ get().update(i, { status: "loading" });
+ try {
+ const options = (await api.search(query, "song")).slice(0, OPTIONS);
+ if (id !== runId) return;
+ get().update(i, options.length ? { status: "ok", options, pick: 0, selected: true } : { status: "empty", options, selected: false });
+ } catch {
+ if (id === runId) get().update(i, { status: "error", selected: false });
+ }
+ };
+
+ return {
+ text: "",
+ entries: [],
+ setText: (text) => set({ text }),
+ update: (i, patch) => set((s) => ({ entries: s.entries.map((e, j) => (j === i ? { ...e, ...patch } : e)) })),
+ selectAll: (on) => set((s) => ({ entries: s.entries.map((e) => (e.status === "ok" ? { ...e, selected: on } : e)) })),
+ retry: (i) => void lookup(runId, i),
+ run: async (terms) => {
+ const id = ++runId;
+ set({ entries: terms.map((query): Entry => ({ query, status: "loading", options: [], pick: 0, selected: false })) });
+ // A few at a time: fast enough, without hammering YouTube with 50 searches at once.
+ let next = 0;
+ const worker = async () => {
+ while (id === runId && next < terms.length) await lookup(id, next++);
+ };
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, terms.length) }, worker));
+ },
+ };
+});
+
+/** The chosen track of each found (or only each selected) entry, without repeats: two names can find the same song. */
+function pickedTracks(entries: Entry[], onlySelected: boolean): Track[] {
+ const seen = new Set<string>();
+ return entries
+ .filter((e) => e.status === "ok" && (e.selected || !onlySelected))
+ .map((e) => e.options[e.pick])
+ .filter((t): t is Track => !!t && !seen.has(t.id) && !!seen.add(t.id));
+}
+
+export default function BatchSearch() {
+ const { text, entries, setText, run, selectAll } = useBatch();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const input = useRef<HTMLTextAreaElement>(null);
+
+ const terms = parseList(text);
+ const chosen = pickedTracks(entries, true);
+ const found = pickedTracks(entries, false);
+ const pending = entries.some((e) => e.status === "loading");
+ const allSelected = found.length > 0 && entries.every((e) => e.status !== "ok" || e.selected);
+
+ const submit = () => {
+ if (!terms.length) return;
+ input.current?.blur();
+ void run(terms);
+ };
+
+ // Arriving from the regular search with a comma-separated query: search it right away.
+ useEffect(() => {
+ const incoming = (location.state as { text?: string } | null)?.text;
+ if (!incoming) return;
+ setText(incoming);
+ void run(parseList(incoming));
+ navigate(".", { replace: true, state: null });
+ }, []);
+
+ return (
+ <div className="pb-8">
+ <PageHeader
+ title="Buscar lista"
+ actions={
+ <Link
+ to="/buscar"
+ className="flex h-9 items-center gap-1.5 rounded-full px-3 text-sm font-medium text-fg-2 hover:bg-surface-3 hover:text-fg"
+ >
+ <ArrowLeftIcon size={16} /> Busca simples
+ </Link>
+ }
+ />
+
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ submit();
+ }}
+ className="flex flex-col gap-3 px-4 pt-1 md:px-6"
+ >
+ <label htmlFor="batch-input" className="text-sm text-fg-2">
+ Escreva as músicas separadas por vírgula (ou uma por linha). Dá para incluir o artista: "Evidências Chitãozinho".
+ </label>
+ <textarea
+ id="batch-input"
+ ref={input}
+ rows={3}
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ // Enter searches; Shift+Enter keeps the line break for one-per-line lists.
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ placeholder="Ex.: Evidências, Trem-Bala, Garota de Ipanema"
+ className="scroll-area min-h-24 w-full resize-y rounded-[20px] border border-line-strong bg-surface-2 px-5 py-3.5 text-[16px] placeholder:text-fg-3 focus:border-accent focus:bg-surface-1 focus:outline-none"
+ />
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-sm text-fg-3">
+ {terms.length === MAX_TERMS ? `Máximo de ${MAX_TERMS} por vez` : terms.length ? plural(terms.length, "música", "músicas") : ""}
+ </span>
+ <button
+ type="submit"
+ disabled={!terms.length}
+ className="h-11 rounded-full bg-accent px-6 text-sm font-semibold text-accent-ink transition-transform active:scale-[0.97] disabled:opacity-40"
+ >
+ {terms.length > 1 ? `Buscar ${terms.length} músicas` : "Buscar"}
+ </button>
+ </div>
+ </form>
+
+ {entries.length > 0 && (
+ <>
+ <SelectionBar
+ className="mt-4"
+ chosen={chosen}
+ all={found}
+ allSelected={allSelected}
+ onToggleAll={() => selectAll(!allSelected)}
+ label={pending ? `Buscando… ${found.length}/${entries.length}` : <SelectedCount n={chosen.length} total={entries.length} />}
+ />
+
+ <ul className="mt-2 flex flex-col px-2 md:px-3">
+ {entries.map((e, i) => (
+ <EntryRow key={`${i}-${e.query}`} entry={e} index={i} />
+ ))}
+ </ul>
+ </>
+ )}
+
+ {entries.length === 0 && (
+ <EmptyState
+ icon={<ListBulletsIcon size={28} />}
+ title="Várias músicas de uma vez"
+ body="O Musike busca cada uma e já seleciona o melhor resultado. Confira, troque o que vier errado e depois toque, favorite ou mande tudo para uma playlist."
+ />
+ )}
+ </div>
+ );
+}
+
+function EntryRow({ entry, index }: { entry: Entry; index: number }) {
+ const update = useBatch((s) => s.update);
+ const retry = useBatch((s) => s.retry);
+ const playTrack = usePlayer((s) => s.playTrack);
+ const [open, setOpen] = useState(false);
+ const track = entry.options[entry.pick];
+
+ if (entry.status === "loading") {
+ return (
+ <li className="flex items-center gap-3 px-2 py-1.5 md:px-3">
+ <span className="size-6 shrink-0" />
+ <span className="skeleton size-11 shrink-0 rounded-[10px]" />
+ <span className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <span className="truncate text-[15px] text-fg-3">{entry.query}</span>
+ <span className="skeleton h-3 w-1/4 rounded-full" />
+ </span>
+ </li>
+ );
+ }
+
+ if (!track) {
+ return (
+ <li className="flex items-center gap-3 px-2 py-1.5 md:px-3">
+ <span className="size-6 shrink-0" />
+ <span className="grid size-11 shrink-0 place-items-center rounded-[10px] bg-surface-2 text-fg-3">
+ <WarningCircleIcon size={20} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[15px] font-medium">{entry.query}</span>
+ <span className="block text-[13px] text-fg-2">{entry.status === "empty" ? "Nada encontrado" : "A busca falhou"}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => retry(index)}
+ className="h-9 rounded-full bg-surface-3 px-4 text-sm font-medium hover:bg-surface-4"
+ >
+ Tentar de novo
+ </button>
+ </li>
+ );
+ }
+
+ return (
+ <li className="flex flex-col">
+ <SelectableRow
+ track={track}
+ selected={entry.selected}
+ onToggle={() => update(index, { selected: !entry.selected })}
+ onPlay={() => playTrack(track)}
+ note={<span className="text-fg-3"> · buscou "{entry.query}"</span>}
+ trailing={
+ entry.options.length > 1 && (
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ title="Trocar por outro resultado"
+ className="flex h-9 shrink-0 items-center gap-1 rounded-full px-2.5 text-sm text-fg-2 hover:bg-surface-3 hover:text-fg"
+ >
+ <ArrowsClockwiseIcon size={16} />
+ <span className="hidden sm:inline">Trocar</span>
+ <CaretDownIcon size={12} className={cn("transition-transform", open && "rotate-180")} />
+ </button>
+ )
+ }
+ />
+
+ {open && (
+ <ul className="mb-2 ml-11 flex flex-col border-l border-line pl-2 md:ml-12">
+ {entry.options.map((opt, j) => (
+ <li key={opt.id}>
+ <button
+ type="button"
+ onClick={() => {
+ update(index, { pick: j, selected: true });
+ setOpen(false);
+ }}
+ className="flex w-full items-center gap-3 rounded-xl px-2 py-1.5 text-left hover:bg-surface-2"
+ >
+ <Artwork src={opt.thumb} className="size-9 rounded-[8px]" />
+ <span className="min-w-0 flex-1">
+ <span className={cn("block truncate text-sm font-medium", j === entry.pick && "text-accent-text")}>{opt.title}</span>
+ <span className="block truncate text-[13px] text-fg-2">
+ {[opt.artist, opt.album].filter(Boolean).join(" · ") || "YouTube"}
+ </span>
+ </span>
+ {j === entry.pick && <CheckIcon size={16} className="text-accent-text" />}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+}
diff --git a/web/src/views/Genre.tsx b/web/src/views/Genre.tsx
new file mode 100644
index 0000000..4aa6395
--- /dev/null
+++ b/web/src/views/Genre.tsx
@@ -0,0 +1,187 @@
+import { CircleNotchIcon, MusicNotesIcon, WarningCircleIcon } from "@phosphor-icons/react";
+import { useState, type ReactNode } from "react";
+import { Link, useLocation, useParams, useSearchParams } from "react-router";
+import { Artwork } from "../components/Artwork";
+import { BackButton, EmptyState, PageHeader } from "../components/Page";
+import { SelectableTrackList, Short } from "../components/Selection";
+import { TrackListSkeleton } from "../components/TrackList";
+import { useRemote } from "../hooks/useRemote";
+import { api } from "../lib/api";
+import { cn, plural } from "../lib/format";
+import type { GenreArtist, GenrePage } from "../lib/types";
+
+type View = "artists" | "tracks";
+
+/** A genre: its bands and artists (each opens their greatest hits) or all its songs in one list. */
+export default function Genre() {
+ const { id = "" } = useParams();
+ // Keyed, so switching genres starts from a clean state.
+ return <GenreBody key={id} id={id} />;
+}
+
+interface MoreArtists {
+ artists: GenreArtist[];
+ hasMore: boolean;
+}
+
+// Artists added with "Carregar mais", kept per genre: coming back from an artist shows the same long list.
+const moreMemo = new Map<string, MoreArtists>();
+
+function GenreBody({ id }: { id: string }) {
+ const location = useLocation();
+ const [params, setParams] = useSearchParams();
+ const view: View = params.get("ver") === "musicas" ? "tracks" : "artists";
+ const page = useRemote<GenrePage>(`genre:${id}`, (signal) => api.genre(id, signal));
+ const name = (page.status === "ok" && page.data.name) || (location.state as { name?: string } | null)?.name || "Gênero";
+ const [more, setMore] = useState<MoreArtists | undefined>(() => moreMemo.get(id));
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [moreError, setMoreError] = useState("");
+
+ const artists = page.status === "ok" ? [...page.data.artists, ...(more?.artists ?? [])] : [];
+ const hasMore = page.status === "ok" && (more ? more.hasMore : page.data.hasMoreArtists);
+
+ const loadMore = async () => {
+ setLoadingMore(true);
+ setMoreError("");
+ try {
+ const next = await api.genreArtists(id, artists.length);
+ const known = new Set(artists.map((a) => a.id));
+ const merged = { artists: [...(more?.artists ?? []), ...next.artists.filter((a) => !known.has(a.id))], hasMore: next.hasMore };
+ moreMemo.set(id, merged);
+ setMore(merged);
+ } catch (e) {
+ setMoreError((e as Error).message);
+ } finally {
+ setLoadingMore(false);
+ }
+ };
+
+ const tab = (v: View, label: ReactNode, count?: string | number) => (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={view === v}
+ onClick={() => setParams(v === "tracks" ? { ver: "musicas" } : {}, { replace: true, state: location.state })}
+ className={cn(
+ "h-9 rounded-full px-4 text-sm font-medium whitespace-nowrap transition-colors duration-200",
+ view === v ? "bg-fg text-bg" : "bg-surface-3 text-fg-2 hover:text-fg",
+ )}
+ >
+ {label}
+ {count !== undefined && <span className="ml-1.5 font-mono text-xs opacity-60">{count}</span>}
+ </button>
+ );
+
+ return (
+ <div className="pb-8">
+ <PageHeader title={name} actions={<BackButton fallback="/buscar" />} />
+
+ <div role="tablist" aria-label="Ver por" className="flex gap-2 px-4 pt-1 pb-4 md:px-6">
+ {tab("artists", <Short phone="Artistas" wide="Bandas e artistas" />, page.status === "ok" ? `${artists.length}${hasMore ? "+" : ""}` : undefined)}
+ {tab("tracks", <Short phone="Músicas" wide="Todas as músicas" />, page.status === "ok" ? page.data.tracks.length : undefined)}
+ </div>
+
+ {page.status === "loading" && (view === "artists" ? <ArtistGridSkeleton /> : <TrackListSkeleton />)}
+
+ {page.status === "error" && (
+ <EmptyState
+ icon={<WarningCircleIcon size={28} />}
+ title="Não deu para abrir este gênero"
+ body={page.message}
+ action={
+ <button
+ type="button"
+ onClick={page.retry}
+ className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm font-medium hover:bg-surface-4"
+ >
+ Tentar de novo
+ </button>
+ }
+ />
+ )}
+
+ {page.status === "ok" && view === "artists" && (
+ artists.length ? (
+ <>
+ <p className="px-4 pb-3 text-sm text-fg-2 md:px-6">Escolha uma banda ou artista para ver os maiores sucessos.</p>
+ <ul className="grid grid-cols-2 gap-x-3 gap-y-5 px-4 sm:grid-cols-3 md:px-6 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">
+ {artists.map((a) => (
+ <li key={a.id}>
+ <Link to={`/buscar/artista/${a.id}`} state={{ name: a.name }} className="group flex flex-col gap-2">
+ <span className="block overflow-hidden rounded-[14px]">
+ <Artwork
+ src={a.art}
+ fallback={a.thumb}
+ className="aspect-square w-full transition-transform duration-300 ease-out-expo group-hover:scale-[1.04]"
+ />
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-sm font-semibold">{a.name}</span>
+ <span className="block truncate text-xs text-fg-2">{a.hits.join(" · ")}</span>
+ </span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+
+ <div className="flex flex-col items-center gap-2 px-4 pt-8 md:px-6">
+ {hasMore ? (
+ <button
+ type="button"
+ onClick={() => void loadMore()}
+ disabled={loadingMore}
+ className="flex h-11 items-center gap-2 rounded-full bg-surface-3 px-6 text-sm font-medium transition-transform hover:bg-surface-4 active:scale-[0.97] disabled:opacity-70"
+ >
+ {loadingMore ? (
+ <>
+ <CircleNotchIcon size={18} className="animate-spin" /> Procurando mais artistas…
+ </>
+ ) : (
+ "Carregar mais"
+ )}
+ </button>
+ ) : (
+ artists.length > page.data.artists.length && (
+ <p className="text-sm text-fg-3">Fim da lista: {plural(artists.length, "artista", "artistas")}</p>
+ )
+ )}
+ {moreError && (
+ <p role="alert" className="text-sm text-danger">
+ {moreError}
+ </p>
+ )}
+ </div>
+ </>
+ ) : (
+ <EmptyState
+ icon={<MusicNotesIcon size={28} />}
+ title="Nenhum artista listado"
+ body="Este gênero só tem playlists. Veja todas as músicas na outra aba."
+ />
+ )
+ )}
+
+ {page.status === "ok" && view === "tracks" && (
+ page.data.tracks.length ? (
+ <SelectableTrackList key={id} tracks={page.data.tracks} />
+ ) : (
+ <EmptyState icon={<MusicNotesIcon size={28} />} title="Nenhuma música listada" body="Tente outro gênero." />
+ )
+ )}
+ </div>
+ );
+}
+
+function ArtistGridSkeleton() {
+ return (
+ <ul aria-label="Carregando" className="grid grid-cols-2 gap-x-3 gap-y-5 px-4 sm:grid-cols-3 md:px-6 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">
+ {Array.from({ length: 12 }, (_, i) => (
+ <li key={i} className="flex flex-col gap-2">
+ <span className="skeleton aspect-square w-full rounded-[14px]" />
+ <span className="skeleton h-3.5 w-2/3 rounded-full" />
+ <span className="skeleton h-3 w-1/2 rounded-full" />
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/web/src/views/Search.tsx b/web/src/views/Search.tsx
index de54282..29a0a87 100644
--- a/web/src/views/Search.tsx
+++ b/web/src/views/Search.tsx
@@ -1,7 +1,18 @@
-import { ArrowUpLeftIcon, LinkIcon, MagnifyingGlassIcon, PlayIcon, WarningCircleIcon, XIcon } from "@phosphor-icons/react";
+import {
+ ArrowRightIcon,
+ ArrowUpLeftIcon,
+ FunnelSimpleIcon,
+ LinkIcon,
+ ListBulletsIcon,
+ MagnifyingGlassIcon,
+ PlayIcon,
+ WarningCircleIcon,
+ XIcon,
+} from "@phosphor-icons/react";
import { useEffect, useRef, useState } from "react";
-import { useSearchParams } from "react-router";
+import { Link, useSearchParams } from "react-router";
import { Artwork } from "../components/Artwork";
+import { GenrePanel } from "../components/GenrePanel";
import { EmptyState, PageHeader } from "../components/Page";
import { TrackList, TrackListSkeleton } from "../components/TrackList";
import { MD, useMediaQuery } from "../hooks/useMediaQuery";
@@ -9,6 +20,7 @@ import { api } from "../lib/api";
import { cn } from "../lib/format";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
+import { parseList } from "./BatchSearch";
const RECENT_KEY = "musike:recent-searches";
@@ -42,6 +54,9 @@ function videoIdFromUrl(text: string): string | null {
type Kind = "song" | "video";
+// The genre panel stays open when coming back from a genre page.
+let genresOpenMemo = false;
+
export default function Search() {
const [params, setParams] = useSearchParams();
const q = params.get("q") ?? "";
@@ -54,11 +69,19 @@ export default function Search() {
const [recent, setRecent] = useState(readRecent);
const [linkTrack, setLinkTrack] = useState<Track | "loading" | "error" | null>(null);
const [retry, setRetry] = useState(0);
+ const [genresOpen, setGenresOpenState] = useState(() => genresOpenMemo);
const input = useRef<HTMLInputElement>(null);
const isMd = useMediaQuery(MD);
const playTrack = usePlayer((s) => s.playTrack);
const linkId = videoIdFromUrl(text);
+ // "a, b, c" probably means three songs; offer to search each one (titles can have commas, so only offer).
+ const listTerms = linkId || !text.includes(",") ? [] : parseList(text);
+
+ const setGenresOpen = (open: boolean) => {
+ genresOpenMemo = open;
+ setGenresOpenState(open);
+ };
const setQuery = (next: string, nextKind = kind) => {
const p = new URLSearchParams();
@@ -207,6 +230,21 @@ export default function Search() {
</div>
</form>
+ {listTerms.length > 1 && (
+ <Link
+ to="/buscar/lista"
+ state={{ text }}
+ className="flex items-center gap-3 rounded-[16px] bg-accent-soft px-4 py-3 text-sm ring-1 ring-line transition-colors hover:bg-surface-3"
+ >
+ <ListBulletsIcon size={20} className="shrink-0 text-accent-text" />
+ <span className="min-w-0 flex-1">
+ <span className="font-medium">Buscar {listTerms.length} músicas separadamente</span>
+ <span className="block truncate text-fg-2">{listTerms.join(" · ")}</span>
+ </span>
+ <ArrowRightIcon size={18} className="shrink-0 text-fg-2" />
+ </Link>
+ )}
+
{suggestions.length > 0 && (
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4 md:mx-0 md:flex-wrap md:px-0">
{suggestions.map((s) => (
@@ -226,11 +264,38 @@ export default function Search() {
)}
{!linkId && (
- <div role="tablist" aria-label="Tipo de resultado" className="flex gap-2">
- {tab("song", "Músicas")}
- {tab("video", "Vídeos")}
+ <div className="flex flex-wrap items-center gap-2">
+ <div role="tablist" aria-label="Tipo de resultado" className="flex gap-2">
+ {tab("song", "Músicas")}
+ {tab("video", "Vídeos")}
+ </div>
+ <span className="flex-1" />
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ aria-expanded={genresOpen}
+ aria-controls="genre-panel"
+ onClick={() => setGenresOpen(!genresOpen)}
+ className={cn(
+ "flex h-9 items-center gap-1.5 rounded-full px-3 text-sm font-medium transition-colors",
+ genresOpen ? "bg-accent-soft text-accent-text" : "text-fg-2 hover:bg-surface-3 hover:text-fg",
+ )}
+ >
+ <FunnelSimpleIcon size={16} /> Gêneros
+ </button>
+ <Link
+ to="/buscar/lista"
+ aria-label="Buscar lista"
+ title="Buscar lista"
+ className="flex h-9 items-center gap-1.5 rounded-full px-3 text-sm font-medium text-fg-2 hover:bg-surface-3 hover:text-fg"
+ >
+ <ListBulletsIcon size={16} /> <span className="hidden sm:inline">Buscar lista</span>
+ </Link>
+ </div>
</div>
)}
+
+ {!linkId && genresOpen && <GenrePanel id="genre-panel" />}
</div>
<div className="mt-4 px-2 md:px-3">