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: implement internationalization for various views and components

Ernanife62004ed341
diff --git a/README.md b/README.md
index ecb6b63..ff0c757 100644
--- a/README.md
+++ b/README.md
@@ -68,6 +68,7 @@ O Musike nasceu da ideia dos antigos bots de música do Discord: um servidor que
- **Backup em arquivo** para levar tudo a outra instância: juntar ou substituir, com prévia antes de importar
**Interface**
+- **Em inglês por padrão, com troca de idioma em Ajustes > Language** (English e Português do Brasil). A escolha vale por aparelho e traduz também as mensagens do servidor e os nomes de gêneros e biografias que vêm do YouTube Music
- Tema escuro e claro, layout responsivo do celular de 320 px ao monitor ultrawide
- Controles na tela de bloqueio, fones e teclas de mídia (Media Session)
- Retoma a fila e a posição de onde você parou
@@ -159,7 +160,7 @@ Na primeira abertura, uma tela mostra o download das ferramentas oficiais: **yt-
| `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`.
+**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-before-install-<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**.
@@ -255,7 +256,7 @@ Variáveis de ambiente do servidor (todas opcionais):
| `MUSIKE_CACHE_DIR` | `server/cache` | Vídeos HD baixados |
| `MUSIKE_CACHE_MAX_MB` | `2048` | Limite do cache de vídeo (apaga os menos tocados) |
| `MUSIKE_BIN_DIR` | | Pasta privada de ferramentas (o app desktop usa `%APPDATA%\Musike\bin`) |
-| `MUSIKE_LANG` / `MUSIKE_LOCATION` | `pt` / `BR` | Idioma e região da busca |
+| `MUSIKE_LANG` / `MUSIKE_LOCATION` | `en` / `BR` | Idioma do YouTube Music quando a requisição não informa um (o app sempre informa o idioma escolhido) e região da busca |
## API
diff --git a/desktop/build/installer.nsh b/desktop/build/installer.nsh
index d686885..84bee66 100644
--- a/desktop/build/installer.nsh
+++ b/desktop/build/installer.nsh
@@ -10,7 +10,7 @@
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"
+ CopyFiles /SILENT "$R0\Musike\data\library.json" "$R0\Musike\backups\library-before-install-${VERSION}.json"
musike_no_library:
Pop $R0
!macroend
diff --git a/desktop/package.json b/desktop/package.json
index ac1bede..60b1eb4 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -1,8 +1,8 @@
{
"name": "musike-desktop",
"productName": "Musike",
- "version": "1.1.0",
- "description": "Sua música, sem interrupção.",
+ "version": "1.2.0",
+ "description": "Your music, uninterrupted.",
"author": "Musike",
"private": true,
"main": "dist/main.mjs",
@@ -55,9 +55,10 @@
"installerIcon": "build/icon.ico",
"uninstallerIcon": "build/icon.ico",
"installerLanguages": [
+ "en_US",
"pt_BR"
],
- "language": "1046",
+ "language": "1033",
"deleteAppDataOnUninstall": false,
"include": "build/installer.nsh"
}
diff --git a/desktop/src/backup.ts b/desktop/src/backup.ts
index 0850967..6e8821a 100644
--- a/desktop/src/backup.ts
+++ b/desktop/src/backup.ts
@@ -24,9 +24,9 @@ export function backupLibraryOnUpdate(userData: string, version: string, now = n
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
+ // Sortable by name: library-2026-10-15_14-05-00-before-1.2.0.json
const stamp = now.toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-");
- made = path.join(dir, `library-${stamp}-antes-da-${version}.json`);
+ made = path.join(dir, `library-${stamp}-before-${version}.json`);
copyFileSync(library, made);
const dated = readdirSync(dir)
.filter((f) => /^library-\d{4}-\d\d-\d\d_/.test(f))
diff --git a/desktop/src/main.mts b/desktop/src/main.mts
index efd3fe3..62aec8a 100644
--- a/desktop/src/main.mts
+++ b/desktop/src/main.mts
@@ -31,6 +31,8 @@ const loadServer = async () => ({
...(await import("../../server/src/app.js")),
...(await import("../../server/src/bootstrap.js")),
...(await import("../../server/src/tools.js")),
+ ...(await import("../../server/src/i18n.js")),
+ HttpError: (await import("../../server/src/types.js")).HttpError,
});
const THEME = {
@@ -49,6 +51,23 @@ interface WindowState {
const stateFile = path.join(userData, "window.json");
+// The language picked in the web app, kept here so the splash screen (shown before the web app loads) uses it too.
+type Lang = "en" | "pt-BR";
+const settingsFile = path.join(userData, "settings.json");
+const isLang = (v: unknown): v is Lang => v === "en" || v === "pt-BR";
+
+function readLang(): Lang {
+ try {
+ const { lang } = JSON.parse(readFileSync(settingsFile, "utf8")) as { lang?: unknown };
+ if (isLang(lang)) return lang;
+ } catch {
+ // first launch
+ }
+ return "en";
+}
+
+let lang = readLang();
+
function readWindowState(): WindowState {
try {
const s = JSON.parse(readFileSync(stateFile, "utf8")) as WindowState;
@@ -82,7 +101,7 @@ function createSplash(): BrowserWindow {
backgroundColor: THEME.dark.color,
webPreferences: { preload: path.join(here, "preload.cjs"), sandbox: true, contextIsolation: true },
});
- void splash.loadFile(path.join(here, "splash.html"));
+ void splash.loadFile(path.join(here, "splash.html"), { query: { lang } });
splash.once("ready-to-show", () => splash.show());
return splash;
}
@@ -139,7 +158,7 @@ async function launch() {
const s = await loadServer();
// Show progress while yt-dlp and Deno download on the first launch.
const report = setInterval(() => {
- splash.webContents.executeJavaScript(`window.update(${JSON.stringify(s.downloads())})`).catch(() => {});
+ splash.webContents.executeJavaScript(`window.update(${JSON.stringify(s.downloads(lang))})`).catch(() => {});
}, 250);
try {
@@ -150,7 +169,7 @@ async function launch() {
s.ensureComponent("ffmpeg").catch(() => {});
} catch (err) {
clearInterval(report);
- const message = JSON.stringify((err as Error).message);
+ const message = JSON.stringify(err instanceof s.HttpError ? s.tr(lang, err.text) : (err as Error).message);
await splash.webContents.executeJavaScript(`window.fail(${message})`).catch(() => {});
return;
}
@@ -167,6 +186,16 @@ ipcMain.on("musike:theme", (event, theme: "dark" | "light") => {
win?.setBackgroundColor(colors.color);
});
+ipcMain.on("musike:lang", (_event, next: unknown) => {
+ if (!isLang(next) || next === lang) return;
+ lang = next;
+ try {
+ writeFileSync(settingsFile, JSON.stringify({ lang }));
+ } catch {
+ /* not critical: the splash falls back to English */
+ }
+});
+
ipcMain.on("musike:retry", (event) => {
const failed = BrowserWindow.fromWebContents(event.sender);
// Open the new splash before closing the old one, or "window-all-closed" would quit the app.
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 88f74e6..57b6787 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -4,5 +4,6 @@ import { contextBridge, ipcRenderer } from "electron";
contextBridge.exposeInMainWorld("musikeDesktop", {
platform: process.platform,
setTheme: (theme: "dark" | "light") => ipcRenderer.send("musike:theme", theme),
+ setLanguage: (lang: string) => ipcRenderer.send("musike:lang", lang),
retry: () => ipcRenderer.send("musike:retry"),
});
diff --git a/desktop/src/splash.html b/desktop/src/splash.html
index 38e9baa..e679f41 100644
--- a/desktop/src/splash.html
+++ b/desktop/src/splash.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html lang="pt-BR">
+<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'" />
@@ -123,23 +123,49 @@
</svg>
musike
</div>
- <div id="status">Iniciando</div>
+ <div id="status"></div>
<div class="rows" id="rows"></div>
</main>
<script>
- const names = { "yt-dlp": "yt-dlp (busca no YouTube)", deno: "Deno (desafios do YouTube)", ffmpeg: "FFmpeg (vídeo HD)" };
+ // The app's language, passed by the desktop shell (?lang=); English until the user picks another.
+ const TEXTS = {
+ en: {
+ starting: "Starting",
+ downloading: "Downloading components on first launch",
+ ready: "ready",
+ extracting: "extracting",
+ of: (got, total) => `${got} of ${total} MB`,
+ failed: "Couldn't start: ",
+ retry: "Try again",
+ names: { "yt-dlp": "yt-dlp (YouTube search)", deno: "Deno (YouTube challenges)", ffmpeg: "FFmpeg (HD video)" },
+ },
+ "pt-BR": {
+ starting: "Iniciando",
+ downloading: "Baixando componentes na primeira execução",
+ ready: "pronto",
+ extracting: "extraindo",
+ of: (got, total) => `${got} de ${total} MB`,
+ failed: "Não foi possível iniciar: ",
+ retry: "Tentar de novo",
+ names: { "yt-dlp": "yt-dlp (busca no YouTube)", deno: "Deno (desafios do YouTube)", ffmpeg: "FFmpeg (vídeo HD)" },
+ },
+ };
+ const lang = new URLSearchParams(location.search).get("lang");
+ const t = TEXTS[lang] ?? TEXTS.en;
+ document.documentElement.lang = TEXTS[lang] ? lang : "en";
+ document.getElementById("status").textContent = t.starting;
const mb = (n) => (n / 1048576).toFixed(1);
window.update = (state) => {
const essentials = Object.entries(state).filter(([k]) => k !== "ffmpeg");
if (!essentials.length) return;
- document.getElementById("status").textContent = "Baixando componentes na primeira execução";
+ document.getElementById("status").textContent = t.downloading;
document.getElementById("rows").innerHTML = essentials
.map(([key, s]) => {
const pct = s.total ? Math.round((s.received / s.total) * 100) : 0;
- const label = s.status === "done" ? "pronto" : s.status === "extracting" ? "extraindo" : s.total ? `${mb(s.received)} de ${mb(s.total)} MB` : `${mb(s.received)} MB`;
+ const label = s.status === "done" ? t.ready : s.status === "extracting" ? t.extracting : s.total ? t.of(mb(s.received), mb(s.total)) : `${mb(s.received)} MB`;
const width = s.status === "done" || s.status === "extracting" ? 100 : pct;
- return `<div class="row"><span><b>${names[key] ?? key}</b><em>${label}</em></span><div class="bar"><i style="width:${width}%"></i></div></div>`;
+ return `<div class="row"><span><b>${t.names[key] ?? key}</b><em>${label}</em></span><div class="bar"><i style="width:${width}%"></i></div></div>`;
})
.join("");
};
@@ -147,9 +173,9 @@
window.fail = (message) => {
const status = document.getElementById("status");
status.className = "error";
- status.textContent = "Não foi possível iniciar: " + message;
+ status.textContent = t.failed + message;
const retry = document.createElement("button");
- retry.textContent = "Tentar de novo";
+ retry.textContent = t.retry;
retry.onclick = () => window.musikeDesktop.retry();
document.querySelector("main").appendChild(retry);
};
diff --git a/package.json b/package.json
index 42f6d28..947dcff 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "musike",
"private": true,
- "version": "1.1.0",
+ "version": "1.2.0",
"type": "module",
"scripts": {
"dev": "pnpm --parallel --filter ./server --filter ./web dev",
diff --git a/server/package.json b/server/package.json
index 6f65eaa..55e85a3 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,7 +1,7 @@
{
"name": "@musike/server",
"private": true,
- "version": "1.1.0",
+ "version": "1.2.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 5d0a381..fa53a63 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -7,20 +7,21 @@ import { config } from "./config.js";
import * as library from "./library.js";
import { findVideoFor, radio, search, suggestions } from "./search.js";
import { proxyStream, serveFile } from "./stream.js";
-import { startJob, systemInfo, type Channel } from "./system.js";
+import { langOf, msg, tr } from "./i18n.js";
+import { presentJob, startJob, systemInfo, type Channel } from "./system.js";
import { refreshTools, type Tools } from "./tools.js";
import { HttpError, VIDEO_ID } from "./types.js";
import { downloadHd, pruneCache, resolveStreams } from "./ytdlp.js";
function videoId(params: unknown): string {
const id = (params as { id?: string }).id ?? "";
- if (!VIDEO_ID.test(id)) throw new HttpError(400, "ID de vídeo inválido.");
+ if (!VIDEO_ID.test(id)) throw new HttpError(400, msg("invalidVideoId"));
return id;
}
function query(q: unknown): string {
const s = typeof q === "string" ? q.trim() : "";
- if (!s) throw new HttpError(400, "Digite algo para buscar.");
+ if (!s) throw new HttpError(400, msg("emptyQuery"));
return s.slice(0, 200);
}
@@ -42,68 +43,70 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
const found = await refreshTools();
const app = Fastify({ logger: { level: process.env.LOG_LEVEL ?? "warn" } });
- app.setErrorHandler((err, _req, reply) => {
+ app.setErrorHandler((err, req, reply) => {
const e = err as Error & { statusCode?: number };
const status = e instanceof HttpError ? e.status : e.statusCode ?? 500;
if (status >= 500) app.log.error(e);
- if (!reply.sent) reply.code(status).send({ error: e.message, code: e instanceof HttpError ? e.code : undefined });
+ // Musike's own errors are translated into the language the app asked for.
+ const error = e instanceof HttpError ? tr(langOf(req), e.text) : e.message;
+ if (!reply.sent) reply.code(status).send({ error, code: e instanceof HttpError ? e.code : undefined });
});
app.get("/api/health", async () => ({ ok: true }));
// System: yt-dlp status and one-click update
- app.get("/api/system", () => systemInfo());
+ app.get("/api/system", (req) => systemInfo(langOf(req)));
app.post("/api/system/ytdlp", async (req) => {
const { channel } = (req.body ?? {}) as { channel?: string };
- return startJob((channel === "nightly" ? "nightly" : "stable") satisfies Channel);
+ return presentJob(startJob((channel === "nightly" ? "nightly" : "stable") satisfies Channel), langOf(req));
});
// Discovery
app.get("/api/search", async (req) => {
const { q, type } = req.query as { q?: string; type?: string };
- return { tracks: await search(query(q), type === "video" ? "video" : "song") };
+ return { tracks: await search(query(q), type === "video" ? "video" : "song", langOf(req)) };
});
app.get("/api/suggest", async (req) => {
const { q } = req.query as { q?: string };
if (!q?.trim()) return { suggestions: [] };
- return { suggestions: await suggestions(q.trim().slice(0, 100)).catch(() => []) };
+ return { suggestions: await suggestions(q.trim().slice(0, 100), langOf(req)).catch(() => []) };
});
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", async (req) => ({ genres: await genres(langOf(req)) }));
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);
+ if (!GENRE_ID.test(gid)) throw new HttpError(400, msg("invalidGenre"));
+ return genre(gid, langOf(req));
});
/** "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);
+ if (!GENRE_ID.test(gid)) throw new HttpError(400, msg("invalidGenre"));
+ if (!Number.isInteger(offset) || offset < 0 || offset > 1000) throw new HttpError(400, msg("invalidOffset"));
+ return genreArtists(gid, offset, langOf(req));
});
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);
+ if (!ARTIST_ID.test(aid)) throw new HttpError(400, msg("invalidArtist"));
+ return artist(aid, langOf(req));
});
/** 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 };
- if (!title?.trim()) throw new HttpError(400, "Informe o título da música.");
+ if (!title?.trim()) throw new HttpError(400, msg("missingTitle"));
const track = await findVideoFor(videoId(req.params), title.slice(0, 200), (artist ?? "").slice(0, 200), Number(duration) || 0);
return { track };
});
@@ -135,23 +138,23 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
app.post("/api/library/import", { bodyLimit: 25 * 1024 * 1024 }, async (req) => {
const body = (req.body ?? {}) as { backup?: { format?: unknown; version?: unknown; library?: unknown }; mode?: unknown };
const backup = body.backup;
- if (backup?.format !== "musike-backup") throw new HttpError(400, "Este arquivo não é um backup do Musike.");
+ if (backup?.format !== "musike-backup") throw new HttpError(400, msg("notBackup"));
if (typeof backup.version !== "number" || backup.version > 1) {
- throw new HttpError(400, "Backup de uma versão mais nova do Musike. Atualize o app para importar.");
+ throw new HttpError(400, msg("newerBackup"));
}
return library.importLibrary(backup.library, body.mode === "replace" ? "replace" : "merge");
});
app.put("/api/favorites/:id", async (req) => {
const track = library.sanitizeTrack(req.body);
- if (track.id !== videoId(req.params)) throw new HttpError(400, "ID não confere.");
+ if (track.id !== videoId(req.params)) throw new HttpError(400, msg("idMismatch"));
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.");
+ if (!Array.isArray(tracks)) throw new HttpError(400, msg("tracksRequired"));
return { favorites: await library.addFavorites(tracks.slice(0, 500).map(library.sanitizeTrack)) };
});
@@ -194,7 +197,7 @@ export async function startServer(opts: StartOptions = {}): Promise<RunningServe
await app.register(fastifyStatic, { root: config.webDist });
app.setNotFoundHandler((req, reply) => {
if (req.method === "GET" && !req.url.startsWith("/api/")) return reply.sendFile("index.html");
- reply.code(404).send({ error: "Rota não encontrada." });
+ reply.code(404).send({ error: tr(langOf(req), msg("routeNotFound")) });
});
}
@@ -218,5 +221,5 @@ async function freePort(start: number, host: string): Promise<number> {
});
if (free) return port;
}
- throw new Error(`Nenhuma porta livre entre ${start} e ${start + 9}.`);
+ throw new HttpError(500, msg("noFreePort", { from: start, to: start + 9 }));
}
diff --git a/server/src/bootstrap.ts b/server/src/bootstrap.ts
index e1e6eb3..685f101 100644
--- a/server/src/bootstrap.ts
+++ b/server/src/bootstrap.ts
@@ -7,6 +7,7 @@ import { pipeline } from "node:stream/promises";
import { promisify } from "node:util";
import { config } from "./config.js";
import { refreshTools, tools } from "./tools.js";
+import { msg, tr, type Lang, type Text } from "./i18n.js";
import { HttpError } from "./types.js";
const exec = promisify(execFile);
@@ -17,7 +18,7 @@ export interface DownloadState {
received: number;
total: number;
status: "downloading" | "extracting" | "done" | "error";
- error?: string;
+ error?: Text;
}
/** Official Windows builds. FFmpeg is the LGPL "shared" build: about half the size of the static one. */
@@ -30,7 +31,9 @@ const SOURCES: Record<Component, string> = {
const states = new Map<Component, DownloadState>();
const inflight = new Map<Component, Promise<void>>();
-export const downloads = (): Partial<Record<Component, DownloadState>> => Object.fromEntries(states);
+/** Download progress, with errors in `lang`. */
+export const downloads = (lang: Lang = "en"): Partial<Record<Component, Omit<DownloadState, "error"> & { error?: string }>> =>
+ Object.fromEntries([...states].map(([c, s]) => [c, { ...s, error: s.error === undefined ? undefined : tr(lang, s.error) }]));
const isInstalled = (c: Component) => !!(c === "yt-dlp" ? tools().ytdlp : c === "deno" ? tools().deno : tools().ffmpeg);
@@ -38,7 +41,7 @@ const isInstalled = (c: Component) => !!(c === "yt-dlp" ? tools().ytdlp : c ===
export function ensureComponent(c: Component): Promise<void> {
if (isInstalled(c)) return Promise.resolve();
const bin = config.binDir;
- if (!bin) return Promise.reject(new HttpError(503, `${c} não encontrado neste computador.`, "tool_missing"));
+ if (!bin) return Promise.reject(new HttpError(503, msg("toolMissing", { tool: c }), "tool_missing"));
const running = inflight.get(c);
if (running) return running;
@@ -49,7 +52,7 @@ export function ensureComponent(c: Component): Promise<void> {
await mkdir(bin, { recursive: true });
const tmp = path.join(bin, `.${c}.download`);
const res = await fetch(SOURCES[c], { headers: { "user-agent": "musike" }, redirect: "follow" });
- if (!res.ok || !res.body) throw new Error(`Download de ${c} falhou (HTTP ${res.status}).`);
+ if (!res.ok || !res.body) throw new HttpError(502, msg("downloadFailed", { tool: c, status: res.status }));
state.total = Number(res.headers.get("content-length")) || 0;
const count = new Transform({
@@ -75,7 +78,7 @@ export function ensureComponent(c: Component): Promise<void> {
} else {
// ffmpeg-<build>/bin holds ffmpeg.exe, ffprobe.exe and the DLLs they need.
const root = (await readdir(out)).find((d) => d.startsWith("ffmpeg"));
- if (!root) throw new Error("Pacote do FFmpeg inesperado.");
+ if (!root) throw new HttpError(502, msg("ffmpegPackage"));
const target = path.join(bin, "ffmpeg");
await rm(target, { recursive: true, force: true });
await cp(path.join(out, root, "bin"), target, { recursive: true });
@@ -89,7 +92,7 @@ export function ensureComponent(c: Component): Promise<void> {
})()
.catch((err: Error) => {
state.status = "error";
- state.error = err.message;
+ state.error = err instanceof HttpError ? err.text : err.message;
throw err;
})
.finally(() => inflight.delete(c));
diff --git a/server/src/browse.ts b/server/src/browse.ts
index 3bfb5d0..11fddd3 100644
--- a/server/src/browse.ts
+++ b/server/src/browse.ts
@@ -1,4 +1,5 @@
import type { Innertube } from "youtubei.js";
+import { isLang, msg, type Lang } from "./i18n.js";
import { sized, text, toTrack, withClient } from "./search.js";
import type { Track } from "./types.js";
import { HttpError } from "./types.js";
@@ -102,9 +103,17 @@ function roundRobin<T>(lists: T[][]): T[] {
/** "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.");
+// Pages are cached per language: YouTube Music words genre names and bios in the session's language.
+const keyOf = (lang: Lang, id = "") => `${lang}|${id}`;
+function parseKey(key: string): { lang: Lang; id: string } {
+ const [lang = "", ...rest] = key.split("|");
+ return { lang: isLang(lang) ? lang : "en", id: rest.join("|") };
+}
+
+const genreList = cached(6 * 60 * MINUTE, async (key): Promise<Genre[]> => {
+ const { lang } = parseKey(key);
+ const page = await withClient((yt) => browse(yt, { browseId: "FEmusic_moods_and_genres" }), lang).catch(() => {
+ throw new HttpError(502, msg("genresUnavailable"));
});
const grids = shelvesOf(page);
// The page has "moods" then "genres"; match the title in any language, falling back to the last grid.
@@ -114,9 +123,11 @@ export const genres = cached(6 * 60 * MINUTE, async (): Promise<Genre[]> => {
.filter((g) => GENRE_ID.test(g.id) && g.name);
});
-async function playlistItems(id: string, limit: number): Promise<any[]> {
+export const genres = (lang: Lang) => genreList(keyOf(lang));
+
+async function playlistItems(id: string, limit: number, lang: Lang): Promise<any[]> {
try {
- const list = await withClient((yt) => yt.music.getPlaylist(id));
+ const list = await withClient((yt) => yt.music.getPlaylist(id), lang);
return ((list as any).items ?? (list as any).contents ?? []).slice(0, limit);
} catch {
return [];
@@ -159,6 +170,7 @@ interface GenreState {
pool: GenreArtist[];
/** Playlists not read yet. */
queue: string[];
+ lang: Lang;
extending?: Promise<void>;
}
@@ -166,11 +178,12 @@ interface GenreState {
* 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 genreState = cached(30 * MINUTE, async (key): Promise<GenreState> => {
+ const { lang, id } = parseKey(key);
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.");
+ genres(lang).catch(() => [] as Genre[]),
+ withClient((yt) => browse(yt, { browseId: "FEmusic_moods_and_genres_category", params: id }), lang).catch(() => {
+ throw new HttpError(502, msg("genreUnavailable"));
}),
]);
const shelves = shelvesOf(page);
@@ -190,10 +203,10 @@ const genreState = cached(30 * MINUTE, async (id): Promise<GenreState> => {
),
];
const first = songs.length >= 10 ? 2 : 4;
- const fromPlaylists = (await Promise.all(playlists.slice(0, first).map((p) => playlistItems(p, 60)))).flat();
+ const fromPlaylists = (await Promise.all(playlists.slice(0, first).map((p) => playlistItems(p, 60, lang)))).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.");
+ if (!tracks.length && !albums.length) throw new HttpError(404, msg("genreEmpty"));
// The genre's own song and album shelves weigh more than playlists.
const pool = rankArtists(
@@ -218,22 +231,23 @@ const genreState = cached(30 * MINUTE, async (id): Promise<GenreState> => {
},
pool,
queue,
+ lang,
};
});
-export const genre = async (id: string): Promise<GenrePage> => (await genreState(id)).page;
+export const genre = async (id: string, lang: Lang): Promise<GenrePage> => (await genreState(keyOf(lang, 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();
+ const items = (await Promise.all(batch.map((p) => playlistItems(p, 100, state.lang)))).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);
+export async function genreArtists(id: string, offset: number, lang: Lang): Promise<{ artists: GenreArtist[]; hasMore: boolean }> {
+ const state = await genreState(keyOf(lang, 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.
@@ -247,9 +261,10 @@ export async function genreArtists(id: string, offset: number): Promise<{ artist
}
/** 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 artistPage = cached(30 * MINUTE, async (key): Promise<ArtistPage> => {
+ const { lang, id } = parseKey(key);
+ const page = await withClient((yt) => yt.music.getArtist(id), lang).catch(() => {
+ throw new HttpError(502, msg("artistUnavailable"));
});
const header: any = page.header;
const shelf: any = page.sections.find((s) => s.type === "MusicShelf");
@@ -257,13 +272,13 @@ export const artist = cached(30 * MINUTE, async (id): Promise<ArtistPage> => {
// 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);
+ const more = await playlistItems(fullList, MAX_HITS * 2, lang);
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.");
+ if (!name && !tracks.length) throw new HttpError(404, msg("artistNotFound"));
return {
id,
name,
@@ -272,3 +287,5 @@ export const artist = cached(30 * MINUTE, async (id): Promise<ArtistPage> => {
tracks,
};
});
+
+export const artist = (id: string, lang: Lang) => artistPage(keyOf(lang, id));
diff --git a/server/src/config.ts b/server/src/config.ts
index 449e7b0..2223574 100644
--- a/server/src/config.ts
+++ b/server/src/config.ts
@@ -21,6 +21,7 @@ export const config = {
* Searched before the system PATH, and where "Instalar" puts the tools when set.
*/
binDir: process.env.MUSIKE_BIN_DIR || null,
- lang: process.env.MUSIKE_LANG ?? "pt",
+ /** YouTube Music language when a request doesn't say (the app always does). */
+ lang: process.env.MUSIKE_LANG ?? "en",
location: process.env.MUSIKE_LOCATION ?? "BR",
};
diff --git a/server/src/i18n.ts b/server/src/i18n.ts
new file mode 100644
index 0000000..b278b97
--- /dev/null
+++ b/server/src/i18n.ts
@@ -0,0 +1,128 @@
+/**
+ * Messages the server sends to people (errors, update progress), in every language the app speaks.
+ * They are kept as keys and translated when sent, so each device gets its own language.
+ */
+
+export type Lang = "en" | "pt-BR";
+type Params = Record<string, string | number>;
+
+const en = {
+ invalidVideoId: "Invalid video ID.",
+ emptyQuery: "Type something to search.",
+ missingTitle: "Give the song's title.",
+ notBackup: "This file isn't a Musike backup.",
+ newerBackup: "This backup was made by a newer Musike. Update the app to import it.",
+ idMismatch: "The ID doesn't match.",
+ tracksRequired: "Send a list of tracks.",
+ invalidGenre: "Invalid genre.",
+ invalidOffset: "Invalid position.",
+ invalidArtist: "Invalid artist.",
+ routeNotFound: "Route not found.",
+ noFreePort: "No free port between {from} and {to}.",
+ invalidTrack: "Invalid track.",
+ playlistNotFound: "Playlist not found.",
+ playlistNameRequired: "Give the playlist a name.",
+ genresUnavailable: "Couldn't load the genres right now. Try again.",
+ genreUnavailable: "Couldn't open this genre right now. Try again.",
+ genreEmpty: "Nothing found for this genre.",
+ artistUnavailable: "Couldn't open this artist right now. Try again.",
+ artistNotFound: "Artist not found.",
+ ytdlpMissing: "yt-dlp wasn't found on this computer. Open Settings in Musike to install it.",
+ ytdlpTimeout: "yt-dlp took too long to answer.",
+ ytdlpCantRun: "Couldn't run yt-dlp ({error}). Open Settings in Musike.",
+ botCheck: "YouTube asked for an anti-bot check. Set YTDLP_EXTRA_ARGS with cookies (see the README).",
+ videoUnavailable: "This video isn't available on YouTube.",
+ ageRestricted: "Age-restricted video. It needs cookies from a signed-in account.",
+ ytdlpFailed: "yt-dlp failed.",
+ ytdlpOutdated: "{detail} YouTube may have changed: update yt-dlp in Settings.",
+ noAudio: "No audio format available for this video.",
+ noSdVideo: "This video has no combined SD version. Use HD.",
+ streamRefused: "YouTube refused the stream (HTTP {status}). Try updating yt-dlp in Settings.",
+ noWinget: "yt-dlp wasn't found and winget isn't available. Install it manually: https://github.com/yt-dlp/yt-dlp",
+ installingYtdlp: "Installing yt-dlp",
+ updatingYtdlp: "Updating yt-dlp",
+ directUpdateFailed: "Direct update failed, trying winget",
+ downloadingTools: "Downloading yt-dlp and Deno from GitHub",
+ alreadyLatest: "Already on the latest version ({version})",
+ ytdlpReady: "yt-dlp {version} is ready to use",
+ updateFailed: "Couldn't update yt-dlp.",
+ toolMissing: "{tool} wasn't found on this computer.",
+ downloadFailed: "Downloading {tool} failed (HTTP {status}).",
+ ffmpegPackage: "Unexpected FFmpeg package.",
+};
+
+export type MsgKey = keyof typeof en;
+
+const pt: Record<MsgKey, string> = {
+ invalidVideoId: "ID de vídeo inválido.",
+ emptyQuery: "Digite algo para buscar.",
+ missingTitle: "Informe o título da música.",
+ notBackup: "Este arquivo não é um backup do Musike.",
+ newerBackup: "Backup de uma versão mais nova do Musike. Atualize o app para importar.",
+ idMismatch: "ID não confere.",
+ tracksRequired: "Envie uma lista de faixas.",
+ invalidGenre: "Gênero inválido.",
+ invalidOffset: "Posição inválida.",
+ invalidArtist: "Artista inválido.",
+ routeNotFound: "Rota não encontrada.",
+ noFreePort: "Nenhuma porta livre entre {from} e {to}.",
+ invalidTrack: "Faixa inválida.",
+ playlistNotFound: "Playlist não encontrada.",
+ playlistNameRequired: "Dê um nome à playlist.",
+ genresUnavailable: "Não foi possível carregar os gêneros agora. Tente de novo.",
+ genreUnavailable: "Não foi possível abrir este gênero agora. Tente de novo.",
+ genreEmpty: "Nada encontrado para este gênero.",
+ artistUnavailable: "Não foi possível abrir este artista agora. Tente de novo.",
+ artistNotFound: "Artista não encontrado.",
+ ytdlpMissing: "O yt-dlp não foi encontrado neste computador. Abra Ajustes no Musike para instalar.",
+ ytdlpTimeout: "O yt-dlp demorou demais para responder.",
+ ytdlpCantRun: "Não foi possível executar o yt-dlp ({error}). Abra Ajustes no Musike.",
+ botCheck: "O YouTube pediu verificação anti-bot. Configure YTDLP_EXTRA_ARGS com cookies (veja o README).",
+ videoUnavailable: "Vídeo indisponível no YouTube.",
+ ageRestricted: "Vídeo com restrição de idade. Requer cookies de uma conta logada.",
+ ytdlpFailed: "Falha no yt-dlp.",
+ ytdlpOutdated: "{detail} O YouTube pode ter mudado: atualize o yt-dlp em Ajustes.",
+ noAudio: "Nenhum formato de áudio disponível para este vídeo.",
+ noSdVideo: "Este vídeo não tem versão SD combinada. Use HD.",
+ streamRefused: "O YouTube recusou o stream (HTTP {status}). Tente atualizar o yt-dlp em Ajustes.",
+ noWinget: "yt-dlp não encontrado e o winget não está disponível. Instale manualmente: https://github.com/yt-dlp/yt-dlp",
+ installingYtdlp: "Instalando yt-dlp",
+ updatingYtdlp: "Atualizando yt-dlp",
+ directUpdateFailed: "Atualização direta falhou, tentando pelo winget",
+ downloadingTools: "Baixando yt-dlp e Deno do GitHub",
+ alreadyLatest: "Já está na versão mais recente ({version})",
+ ytdlpReady: "yt-dlp {version} pronto para uso",
+ updateFailed: "Não foi possível atualizar o yt-dlp.",
+ toolMissing: "{tool} não encontrado neste computador.",
+ downloadFailed: "Download de {tool} falhou (HTTP {status}).",
+ ffmpegPackage: "Pacote do FFmpeg inesperado.",
+};
+
+const CATALOG: Record<Lang, Record<MsgKey, string>> = { en, "pt-BR": pt };
+
+/** A message translated when it is sent: a key plus the values for its {placeholders}. */
+export interface Msg {
+ key: MsgKey;
+ params?: Params;
+}
+
+/** Something to show a person: a message to translate, or text that needs none (tool output). */
+export type Text = Msg | string;
+
+export const msg = (key: MsgKey, params?: Params): Msg => ({ key, params });
+
+export function tr(lang: Lang, text: Text): string {
+ if (typeof text === "string") return text;
+ return CATALOG[lang][text.key].replace(/\{(\w+)\}/g, (all, name: string) => String(text.params?.[name] ?? all));
+}
+
+export const isLang = (v: unknown): v is Lang => v === "en" || v === "pt-BR";
+
+/** The language a request asked for. The app always says; anything else (media elements, curl) gets English. */
+export function langOf(req: { headers: Record<string, string | string[] | undefined> }): Lang {
+ const asked = req.headers["x-musike-lang"];
+ return isLang(asked) ? asked : "en";
+}
+
+/** The code YouTube Music uses for its own words (genre names, artist bios). */
+export const youtubeLang = (lang: Lang) => (lang === "pt-BR" ? "pt" : "en");
diff --git a/server/src/index.ts b/server/src/index.ts
index 7e2b92d..e2e53b6 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -10,11 +10,11 @@ const lan = Object.values(networkInterfaces())
.flat()
.filter((i) => i && i.family === "IPv4" && !i.internal)
.map((i) => `http://${i!.address}:${port}`);
-console.log(`\n Musike rodando`);
-console.log(` Local: http://localhost:${port}`);
-for (const url of lan) console.log(` Rede: ${url}`);
-if (!existsSync(config.webDist)) console.log(` (web não compilado: rode "pnpm build" ou use "pnpm dev")`);
-console.log(` yt-dlp: ${tools.ytdlp ?? "NÃO ENCONTRADO (instale pelo Musike em Ajustes)"}`);
-if (!tools.deno) console.log(` Deno: não encontrado (o YouTube pode falhar sem ele)`);
-if (!tools.ffmpeg) console.log(` FFmpeg: não encontrado (vídeo HD indisponível)`);
-console.log(` Dados: ${path.relative(process.cwd(), config.dataDir) || config.dataDir}\n`);
+console.log(`\n Musike is running`);
+console.log(` Local: http://localhost:${port}`);
+for (const url of lan) console.log(` Network: ${url}`);
+if (!existsSync(config.webDist)) console.log(` (web app not built: run "pnpm build" or use "pnpm dev")`);
+console.log(` yt-dlp: ${tools.ytdlp ?? "NOT FOUND (install it from Musike's Settings)"}`);
+if (!tools.deno) console.log(` Deno: not found (YouTube may fail without it)`);
+if (!tools.ffmpeg) console.log(` FFmpeg: not found (HD video unavailable)`);
+console.log(` Data: ${path.relative(process.cwd(), config.dataDir) || config.dataDir}\n`);
diff --git a/server/src/library.ts b/server/src/library.ts
index 7ec0242..d1984ef 100644
--- a/server/src/library.ts
+++ b/server/src/library.ts
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { config } from "./config.js";
+import { msg } from "./i18n.js";
import { HttpError, VIDEO_ID, type Library, type Playlist, type Track } from "./types.js";
const FILE = path.join(config.dataDir, "library.json");
@@ -38,14 +39,14 @@ const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max
export function sanitizeTrack(input: unknown): Track {
const t = (input ?? {}) as Record<string, unknown>;
const id = str(t.id, 11);
- if (!VIDEO_ID.test(id)) throw new HttpError(400, "Faixa inválida.");
+ if (!VIDEO_ID.test(id)) throw new HttpError(400, msg("invalidTrack"));
const url = (v: unknown) => {
const s = str(v, 500);
return /^https:\/\//.test(s) ? s : "";
};
return {
id,
- title: str(t.title, 300) || "Sem título",
+ title: str(t.title, 300) || "Untitled",
artist: str(t.artist, 300),
album: str(t.album, 300) || undefined,
duration: typeof t.duration === "number" && Number.isFinite(t.duration) ? Math.max(0, Math.round(t.duration)) : 0,
@@ -57,7 +58,7 @@ export function sanitizeTrack(input: unknown): Track {
function findPlaylist(lib: Library, pid: string): Playlist {
const p = lib.playlists.find((x) => x.id === pid);
- if (!p) throw new HttpError(404, "Playlist não encontrada.");
+ if (!p) throw new HttpError(404, msg("playlistNotFound"));
return p;
}
@@ -99,7 +100,7 @@ export async function pushHistory(track: Track): Promise<Track[]> {
export async function createPlaylist(name: string, tracks: Track[] = []): Promise<Playlist> {
const lib = await load();
const clean = name.trim().slice(0, 80);
- if (!clean) throw new HttpError(400, "Dê um nome à playlist.");
+ if (!clean) throw new HttpError(400, msg("playlistNameRequired"));
const now = Date.now();
const playlist: Playlist = { id: randomUUID(), name: clean, createdAt: now, updatedAt: now, tracks };
lib.playlists.unshift(playlist);
@@ -111,7 +112,7 @@ export async function renamePlaylist(pid: string, name: string): Promise<Playlis
const lib = await load();
const p = findPlaylist(lib, pid);
const clean = name.trim().slice(0, 80);
- if (!clean) throw new HttpError(400, "Dê um nome à playlist.");
+ if (!clean) throw new HttpError(400, msg("playlistNameRequired"));
p.name = clean;
p.updatedAt = Date.now();
await persist();
diff --git a/server/src/search.ts b/server/src/search.ts
index f7cca5b..66cd08a 100644
--- a/server/src/search.ts
+++ b/server/src/search.ts
@@ -1,26 +1,36 @@
import { Innertube } from "youtubei.js";
import { config } from "./config.js";
+import { youtubeLang, type Lang } from "./i18n.js";
import type { Track } from "./types.js";
import { VIDEO_ID } from "./types.js";
import { ytdlpSearch } from "./ytdlp.js";
-let client: Promise<Innertube> | null = null;
-
-function yt(): Promise<Innertube> {
- client ??= Innertube.create({ retrieve_player: false, lang: config.lang, location: config.location }).catch((err) => {
- client = null;
- throw err;
- });
+// One session per language: YouTube Music words its own texts (genre names, artist bios) in the session's language.
+const clients = new Map<string, Promise<Innertube>>();
+
+function yt(hl: string): Promise<Innertube> {
+ let client = clients.get(hl);
+ if (!client) {
+ client = Innertube.create({ retrieve_player: false, lang: hl, location: config.location }).catch((err) => {
+ clients.delete(hl);
+ throw err;
+ });
+ clients.set(hl, client);
+ }
return client;
}
-/** Retries once with a fresh InnerTube session, since sessions can go stale. */
-export async function withClient<T>(fn: (yt: Innertube) => Promise<T>): Promise<T> {
+/**
+ * Runs `fn` with a YouTube Music session in `lang` (the server default when the caller has none).
+ * Retries once with a fresh session, since sessions can go stale.
+ */
+export async function withClient<T>(fn: (yt: Innertube) => Promise<T>, lang?: Lang): Promise<T> {
+ const hl = lang ? youtubeLang(lang) : config.lang;
try {
- return await fn(await yt());
+ return await fn(await yt(hl));
} catch {
- client = null;
- return fn(await yt());
+ clients.delete(hl);
+ return fn(await yt(hl));
}
}
@@ -59,9 +69,9 @@ export function toTrack(item: any, kind: Track["kind"]): Track | null {
};
}
-export async function search(query: string, type: "song" | "video"): Promise<Track[]> {
+export async function search(query: string, type: "song" | "video", lang?: Lang): Promise<Track[]> {
try {
- const result = await withClient((yt) => yt.music.search(query, { type }));
+ const result = await withClient((yt) => yt.music.search(query, { type }), lang);
const shelf = result.contents?.[0] as { contents?: unknown[] } | undefined;
const tracks = (shelf?.contents ?? []).map((i) => toTrack(i, type)).filter((t): t is Track => !!t);
if (tracks.length) return tracks;
@@ -81,8 +91,8 @@ export async function search(query: string, type: "song" | "video"): Promise<Tra
}));
}
-export async function suggestions(query: string): Promise<string[]> {
- const sections = await withClient((yt) => yt.music.getSearchSuggestions(query));
+export async function suggestions(query: string, lang?: Lang): Promise<string[]> {
+ const sections = await withClient((yt) => yt.music.getSearchSuggestions(query), lang);
const first = sections[0] as { contents?: { suggestion?: unknown }[] } | undefined;
return (first?.contents ?? [])
.map((s) => text(s.suggestion))
diff --git a/server/src/stream.ts b/server/src/stream.ts
index ca0d6bb..e6b91ac 100644
--- a/server/src/stream.ts
+++ b/server/src/stream.ts
@@ -2,6 +2,7 @@ import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import type { FastifyReply, FastifyRequest } from "fastify";
+import { msg } from "./i18n.js";
import { HttpError } from "./types.js";
import { invalidate, resolveStreams, type StreamFormat } from "./ytdlp.js";
@@ -16,7 +17,7 @@ export async function proxyStream(req: FastifyRequest, reply: FastifyReply, id:
if (fresh) invalidate(id);
const resolved = await resolveStreams(id);
const fmt = kind === "audio" ? resolved.audio : resolved.video;
- if (!fmt) throw new HttpError(404, "Este vídeo não tem versão SD combinada. Use HD.");
+ if (!fmt) throw new HttpError(404, msg("noSdVideo"));
return fmt;
};
@@ -41,7 +42,7 @@ export async function proxyStream(req: FastifyRequest, reply: FastifyReply, id:
upstream = await request(fmt);
}
if (!upstream.ok || !upstream.body) {
- throw new HttpError(502, `O YouTube recusou o stream (HTTP ${upstream.status}). Tente atualizar o yt-dlp em Sistema.`, "maybe_outdated");
+ throw new HttpError(502, msg("streamRefused", { status: upstream.status }), "maybe_outdated");
}
reply.code(upstream.status);
diff --git a/server/src/system.ts b/server/src/system.ts
index 6230c59..ea94501 100644
--- a/server/src/system.ts
+++ b/server/src/system.ts
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
import { downloads, ensureEssentials } from "./bootstrap.js";
import { config } from "./config.js";
import { refreshTools, tools } from "./tools.js";
+import { msg, tr, type Lang, type Text } from "./i18n.js";
import { HttpError } from "./types.js";
import { clearResolved, holdDuring } from "./ytdlp.js";
@@ -15,8 +16,9 @@ export interface Job {
finishedAt?: number;
from: string | null;
to: string | null;
- message: string;
- log: string[];
+ message: Text;
+ /** Tool output as it came, plus Musike's own lines (translated when sent). */
+ log: Text[];
}
const RELEASES: Record<Channel, string> = {
@@ -89,7 +91,12 @@ function newer(a: string, b: string): boolean {
return false;
}
-export async function systemInfo() {
+/** A job as the app shows it: its messages in `lang`. */
+export function presentJob(job: Job, lang: Lang) {
+ return { ...job, message: tr(lang, job.message), log: job.log.map((line) => tr(lang, line)) };
+}
+
+export async function systemInfo(lang: Lang) {
const t = tools();
// Re-read when yt-dlp showed up since the last check (e.g. downloaded on first launch).
if (version === undefined || (version === null && t.ytdlp)) version = await readVersion();
@@ -107,8 +114,8 @@ export async function systemInfo() {
deno: t.deno,
ffmpeg: t.ffmpeg,
canInstall: !!t.winget || !!config.binDir,
- downloads: downloads(),
- job,
+ downloads: downloads(lang),
+ job: job && presentJob(job, lang),
};
}
@@ -117,7 +124,7 @@ export function startJob(channel: Channel) {
const t = tools();
const kind: Job["kind"] = t.ytdlp ? "update" : "install";
if (kind === "install" && !t.winget && !config.binDir) {
- throw new HttpError(400, "yt-dlp não encontrado e o winget não está disponível. Instale manualmente: https://github.com/yt-dlp/yt-dlp");
+ throw new HttpError(400, msg("noWinget"));
}
const current: Job = {
@@ -127,11 +134,11 @@ export function startJob(channel: Channel) {
startedAt: Date.now(),
from: version ?? null,
to: null,
- message: kind === "install" ? "Instalando yt-dlp" : "Atualizando yt-dlp",
+ message: msg(kind === "install" ? "installingYtdlp" : "updatingYtdlp"),
log: [],
};
job = current;
- const log = (line: string) => {
+ const log = (line: Text) => {
current.log = [...current.log, line].slice(-40);
};
@@ -141,15 +148,15 @@ export function startJob(channel: Channel) {
code = await stream(t.ytdlp!, ["--update-to", channel], log, 5 * 60_000);
// Builds that can't self-update (e.g. installed by a package manager) fall back to winget.
if (code !== 0 && t.winget) {
- log("Atualização direta falhou, tentando pelo winget");
+ log(msg("directUpdateFailed"));
code = await stream(t.winget, wingetArgs("upgrade"), log, 10 * 60_000);
}
} else if (config.binDir) {
// Desktop app: download the official builds into Musike's own folder (no admin, no winget).
- log("Baixando yt-dlp e Deno do GitHub");
+ log(msg("downloadingTools"));
code = await ensureEssentials().then(
() => 0,
- (err: Error) => (log(err.message), 1),
+ (err: Error) => (log(err instanceof HttpError ? err.text : err.message), 1),
);
} else {
code = await stream(t.winget!, wingetArgs("install"), log, 10 * 60_000);
@@ -162,18 +169,18 @@ export function startJob(channel: Channel) {
current.finishedAt = Date.now();
if (version && (code === 0 || current.from !== version)) {
current.status = "done";
- current.message =
- current.from === version ? `Já está na versão mais recente (${version})` : `yt-dlp ${version} pronto para uso`;
+ current.message = msg(current.from === version ? "alreadyLatest" : "ytdlpReady", { version });
} else {
current.status = "error";
- current.message = current.log.findLast((l) => /error|erro|failed|falha/i.test(l)) ?? "Não foi possível atualizar o yt-dlp.";
+ // The tool's own error line says the most; Musike's lines are never errors.
+ current.message = current.log.findLast((l) => typeof l === "string" && /error|failed/i.test(l)) ?? msg("updateFailed");
}
};
void holdDuring(work().catch((err: Error) => {
current.status = "error";
current.finishedAt = Date.now();
- current.message = err.message;
+ current.message = err instanceof HttpError ? err.text : err.message;
}));
return current;
}
diff --git a/server/src/types.ts b/server/src/types.ts
index 0be4f9c..46183f4 100644
--- a/server/src/types.ts
+++ b/server/src/types.ts
@@ -23,13 +23,20 @@ export interface Library {
history: Track[];
}
+import { tr, type Text } from "./i18n.js";
+
export const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
/** Machine-readable reason so the web app can offer the right fix (e.g. "update yt-dlp"). */
export type ErrorCode = "tool_missing" | "maybe_outdated" | "bot_check";
+/** An error for the person using the app: its text is translated into each request's language when sent. */
export class HttpError extends Error {
- constructor(public status: number, message: string, public code?: ErrorCode) {
- super(message);
+ constructor(
+ public status: number,
+ public text: Text,
+ public code?: ErrorCode,
+ ) {
+ super(tr("en", text));
}
}
diff --git a/server/src/ytdlp.ts b/server/src/ytdlp.ts
index 504e1f4..3c1cd34 100644
--- a/server/src/ytdlp.ts
+++ b/server/src/ytdlp.ts
@@ -5,6 +5,7 @@ import path from "node:path";
import { ensureComponent } from "./bootstrap.js";
import { config } from "./config.js";
import { tools } from "./tools.js";
+import { msg } from "./i18n.js";
import { HttpError } from "./types.js";
export interface StreamFormat {
@@ -53,7 +54,7 @@ async function run(args: string[], timeoutMs: number): Promise<string> {
if (maintenance) await maintenance.catch(() => {});
const { ytdlp, env } = tools();
if (!ytdlp) {
- throw new HttpError(503, "O yt-dlp não foi encontrado neste computador. Abra Sistema no Musike para instalar.", "tool_missing");
+ throw new HttpError(503, msg("ytdlpMissing"), "tool_missing");
}
return new Promise((resolve, reject) => {
const child = spawn(ytdlp, [...config.ytdlpExtraArgs, ...args], { windowsHide: true, env });
@@ -61,13 +62,13 @@ async function run(args: string[], timeoutMs: number): Promise<string> {
let stderr = "";
const timer = setTimeout(() => {
child.kill();
- reject(new HttpError(504, "O yt-dlp demorou demais para responder."));
+ reject(new HttpError(504, msg("ytdlpTimeout")));
}, timeoutMs);
child.stdout.on("data", (d) => (stdout += d));
child.stderr.on("data", (d) => (stderr += d));
child.on("error", (err) => {
clearTimeout(timer);
- reject(new HttpError(503, `Não foi possível executar o yt-dlp (${err.message}). Abra Sistema no Musike.`, "tool_missing"));
+ reject(new HttpError(503, msg("ytdlpCantRun", { error: err.message }), "tool_missing"));
});
child.on("close", (code) => {
clearTimeout(timer);
@@ -83,18 +84,18 @@ const OUTDATED = /nsig|signature|n challenge|JavaScript runtime|Unable to extrac
function toHttpError(stderr: string): HttpError {
const line = stderr.split("\n").find((l) => l.includes("ERROR")) ?? stderr.trim().split("\n").pop() ?? "";
if (/confirm you.re not a bot|Sign in to confirm/i.test(line)) {
- return new HttpError(503, "O YouTube pediu verificação anti-bot. Configure YTDLP_EXTRA_ARGS com cookies (veja o README).", "bot_check");
+ return new HttpError(503, msg("botCheck"), "bot_check");
}
if (/Video unavailable|Private video|removed/i.test(line)) {
- return new HttpError(404, "Vídeo indisponível no YouTube.");
+ return new HttpError(404, msg("videoUnavailable"));
}
if (/age-restricted|inappropriate|confirm your age/i.test(line)) {
- return new HttpError(403, "Vídeo com restrição de idade. Requer cookies de uma conta logada.");
- }
- const detail = line.replace(/^ERROR:\s*/, "").slice(0, 240) || "Falha no yt-dlp.";
- if (OUTDATED.test(stderr)) {
- return new HttpError(502, `${detail} O YouTube pode ter mudado: atualize o yt-dlp em Sistema.`, "maybe_outdated");
+ return new HttpError(403, msg("ageRestricted"));
}
+ // yt-dlp's own words stay as they are (English); only the advice around them is translated.
+ const detail = line.replace(/^ERROR:\s*/, "").slice(0, 240);
+ if (!detail) return new HttpError(502, msg("ytdlpFailed"), "maybe_outdated");
+ if (OUTDATED.test(stderr)) return new HttpError(502, msg("ytdlpOutdated", { detail }), "maybe_outdated");
return new HttpError(502, detail, "maybe_outdated");
}
@@ -147,7 +148,7 @@ export function resolveStreams(id: string): Promise<Resolved> {
.then((stdout) => {
const info = JSON.parse(stdout) as { title: string; duration?: number; formats: RawFormat[] };
const audio = pickAudio(info.formats);
- if (!audio) throw new HttpError(404, "Nenhum formato de áudio disponível para este vídeo.");
+ if (!audio) throw new HttpError(404, msg("noAudio"));
const video = pickVideo(info.formats);
const resolved: Resolved = {
id,
diff --git a/web/index.html b/web/index.html
index acc60bd..f347624 100644
--- a/web/index.html
+++ b/web/index.html
@@ -1,10 +1,10 @@
<!doctype html>
-<html lang="pt-BR" data-theme="dark">
+<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0B0C0F" />
- <meta name="description" content="Sua música, sem interrupção." />
+ <meta name="description" content="Your music, uninterrupted." />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Musike" />
@@ -15,6 +15,9 @@
try {
var t = localStorage.getItem("musike:theme");
if (t === "light" || t === "dark") document.documentElement.dataset.theme = t;
+ // Before the app loads, so screen readers and the browser see the chosen language right away.
+ var l = localStorage.getItem("musike:lang");
+ if (l === "en" || l === "pt-BR") document.documentElement.lang = l;
} catch (e) {}
</script>
</head>
diff --git a/web/package.json b/web/package.json
index a0e0b5d..07c1551 100644
--- a/web/package.json
+++ b/web/package.json
@@ -1,7 +1,7 @@
{
"name": "@musike/web",
"private": true,
- "version": "1.1.0",
+ "version": "1.2.0",
"type": "module",
"scripts": {
"dev": "vite --host",
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 3a0b0e0..c61b7d3 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef } from "react";
-import { Route, Routes, useLocation, useNavigate, useNavigationType } from "react-router";
+import { Navigate, 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";
@@ -13,7 +13,9 @@ import { TrackMenu } from "./components/TrackMenu";
import { FloatingVideo, Theater } from "./components/Video";
import { MD, useMediaQuery } from "./hooks/useMediaQuery";
import { useShortcuts } from "./hooks/useShortcuts";
+import { getT } from "./i18n";
import { cn } from "./lib/format";
+import { legacyRedirect, NOW_PLAYING_HASH, paths } from "./lib/routes";
import { usePlayer } from "./player/player";
import { useLibrary } from "./stores/library";
import { openSettings, useSystem } from "./stores/system";
@@ -26,10 +28,11 @@ import Home from "./views/Home";
import Library from "./views/Library";
import Search from "./views/Search";
-const SHEET_HASH = "#tocando";
+const SHEET_HASH = `#${NOW_PLAYING_HASH}`;
export default function App() {
const location = useLocation();
+ const legacy = legacyRedirect(location.pathname, location.search, location.hash);
const navigate = useNavigate();
const navigationType = useNavigationType();
const isMd = useMediaQuery(MD);
@@ -51,8 +54,9 @@ export default function App() {
await loadSystem();
const info = useSystem.getState().info;
if (!info) return;
+ const t = getT();
if (!info.ytdlp.path) {
- toast("O yt-dlp não foi encontrado. Sem ele nenhuma música toca.", "error", { label: "Instalar", run: openSettings });
+ toast(t.toasts.ytdlpMissing, "error", { label: t.common.install, run: openSettings });
return;
}
const latest = info.ytdlp.latest[info.ytdlp.channel];
@@ -63,7 +67,7 @@ export default function App() {
} catch {
/* private mode */
}
- toast(`Nova versão do yt-dlp disponível (${latest})`, "info", { label: "Atualizar", run: openSettings });
+ toast(t.toasts.ytdlpUpdate(latest), "info", { label: t.common.update, run: openSettings });
}
}, 1500);
return () => clearTimeout(t);
@@ -111,18 +115,22 @@ export default function App() {
"md:pb-0",
)}
>
- <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" />} />
- <Route path="/playlist/:id" element={<Collection kind="playlist" />} />
- <Route path="*" element={<Home />} />
- </Routes>
+ {legacy ? (
+ <Navigate to={legacy} replace />
+ ) : (
+ <Routes>
+ <Route path={paths.home} element={<Home />} />
+ <Route path={paths.search} element={<Search />} />
+ <Route path={paths.searchList} element={<BatchSearch />} />
+ <Route path="/search/genre/:id" element={<Genre />} />
+ <Route path="/search/artist/:id" element={<Artist />} />
+ <Route path={paths.library} element={<Library />} />
+ <Route path={paths.favorites} element={<Collection kind="favorites" />} />
+ <Route path={paths.history} element={<Collection kind="history" />} />
+ <Route path="/playlist/:id" element={<Collection kind="playlist" />} />
+ <Route path="*" element={<Home />} />
+ </Routes>
+ )}
</main>
{panelOpen && hasTrack && <SidePanel />}
</div>
diff --git a/web/src/components/BackupSection.tsx b/web/src/components/BackupSection.tsx
index 3ae31f9..c507139 100644
--- a/web/src/components/BackupSection.tsx
+++ b/web/src/components/BackupSection.tsx
@@ -1,7 +1,8 @@
import { ArrowsMergeIcon, DownloadSimpleIcon, SwapIcon, UploadSimpleIcon } from "@phosphor-icons/react";
import { useRef, useState } from "react";
import { createBackup, downloadBackup, readBackup, restoreBackup, summarize, type Backup } from "../lib/backup";
-import { cn, plural } from "../lib/format";
+import { useT } from "../i18n";
+import { cn } from "../lib/format";
import { toast } from "../stores/ui";
type Mode = "merge" | "replace";
@@ -14,6 +15,7 @@ export function BackupSection() {
const [withSettings, setWithSettings] = useState(true);
const [busy, setBusy] = useState<"export" | "import" | null>(null);
const [confirmReplace, setConfirmReplace] = useState(false);
+ const t = useT();
const onExport = async () => {
setBusy("export");
@@ -21,7 +23,7 @@ export function BackupSection() {
const backup = await createBackup();
downloadBackup(backup);
const s = summarize(backup);
- toast(`Backup criado: ${plural(s.playlists, "playlist", "playlists")} e ${plural(s.favorites, "favorita", "favoritas")}`);
+ toast(t.backup.created(s.playlists, s.favorites));
} catch (e) {
toast((e as Error).message, "error");
} finally {
@@ -49,12 +51,12 @@ export function BackupSection() {
try {
const r = await restoreBackup(pending.backup, mode, withSettings);
const parts = [
- r.playlistsAdded && plural(r.playlistsAdded, "playlist nova", "playlists novas"),
- r.playlistsMerged && plural(r.playlistsMerged, "playlist atualizada", "playlists atualizadas"),
- r.tracksAdded && plural(r.tracksAdded, "faixa adicionada", "faixas adicionadas"),
- r.favoritesAdded && plural(r.favoritesAdded, "favorita", "favoritas"),
- ].filter(Boolean);
- toast(parts.length ? `Importado: ${parts.join(", ")}` : "Nada novo: sua biblioteca já tinha tudo deste backup");
+ r.playlistsAdded && t.backup.newPlaylists(r.playlistsAdded),
+ r.playlistsMerged && t.backup.updatedPlaylists(r.playlistsMerged),
+ r.tracksAdded && t.backup.addedTracks(r.tracksAdded),
+ r.favoritesAdded && t.backup.addedFavorites(r.favoritesAdded),
+ ].filter((p): p is string => !!p);
+ toast(parts.length ? t.backup.imported(parts) : t.backup.nothingNew);
setPending(null);
} catch (e) {
toast((e as Error).message, "error");
@@ -68,24 +70,22 @@ export function BackupSection() {
return (
<section className="flex flex-col gap-3">
- <h3 className="text-xs font-medium text-fg-3">Seus dados</h3>
- <p className="text-sm text-fg-2">
- Leve playlists, favoritas e histórico para outro computador ou para o app desktop: exporte um arquivo aqui e importe na outra instância do Musike.
- </p>
+ <h3 className="text-xs font-medium text-fg-3">{t.backup.yourData}</h3>
+ <p className="text-sm text-fg-2">{t.backup.body}</p>
<div className="grid grid-cols-2 gap-2">
<button type="button" onClick={onExport} disabled={!!busy} className={cn(action, "bg-surface-1 ring-1 ring-line hover:bg-surface-3")}>
- <DownloadSimpleIcon size={18} /> {busy === "export" ? "Exportando" : "Exportar"}
+ <DownloadSimpleIcon size={18} /> {busy === "export" ? t.backup.exporting : t.backup.export}
</button>
<button type="button" onClick={() => input.current?.click()} disabled={!!busy} className={cn(action, "bg-surface-1 ring-1 ring-line hover:bg-surface-3")}>
- <UploadSimpleIcon size={18} /> Importar
+ <UploadSimpleIcon size={18} /> {t.backup.import}
</button>
<input
ref={input}
type="file"
accept=".json,application/json"
className="hidden"
- aria-label="Escolher arquivo de backup do Musike"
+ aria-label={t.backup.pickFile}
onChange={(e) => void onPick(e.target.files?.[0])}
/>
</div>
@@ -97,17 +97,20 @@ export function BackupSection() {
{pending.file}
</p>
<p className="text-xs text-fg-2">
- Exportado em {s.exportedAt.toLocaleDateString("pt-BR")} às {s.exportedAt.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" })}
+ {t.backup.exportedAt(
+ s.exportedAt.toLocaleDateString(t.locale),
+ s.exportedAt.toLocaleTimeString(t.locale, { hour: "2-digit", minute: "2-digit" }),
+ )}
</p>
</div>
<ul className="grid grid-cols-3 gap-2 text-center">
{[
- [s.playlists, s.playlists === 1 ? "playlist" : "playlists", `${s.playlistTracks} faixas`],
- [s.favorites, s.favorites === 1 ? "favorita" : "favoritas", null],
- [s.history, "no histórico", null],
- ].map(([n, label, sub]) => (
- <li key={String(label)} className="rounded-[12px] bg-surface-2 px-2 py-2.5">
+ ["playlists", s.playlists, t.backup.playlistsWord(s.playlists), t.backup.tracksIn(s.playlistTracks)],
+ ["favorites", s.favorites, t.backup.favoritesWord(s.favorites), null],
+ ["history", s.history, t.backup.inHistory, null],
+ ].map(([key, n, label, sub]) => (
+ <li key={key} className="rounded-[12px] bg-surface-2 px-2 py-2.5">
<span className="block font-mono text-lg font-semibold tabular-nums">{n}</span>
<span className="block text-xs text-fg-2">{label}</span>
{sub && <span className="block text-[11px] text-fg-3">{sub}</span>}
@@ -115,11 +118,11 @@ export function BackupSection() {
))}
</ul>
- <div role="radiogroup" aria-label="Como importar" className="grid gap-2">
+ <div role="radiogroup" aria-label={t.backup.howToImport} className="grid gap-2">
{(
[
- ["merge", ArrowsMergeIcon, "Juntar com a minha biblioteca", "Adiciona o que falta. Nada é apagado; playlists com o mesmo nome ganham as faixas novas."],
- ["replace", SwapIcon, "Substituir tudo", "Apaga a biblioteca atual e deixa exatamente como no backup."],
+ ["merge", ArrowsMergeIcon, t.backup.mergeTitle, t.backup.mergeBody],
+ ["replace", SwapIcon, t.backup.replaceTitle, t.backup.replaceBody],
] as const
).map(([value, Icon, title, body]) => (
<button
@@ -148,19 +151,19 @@ export function BackupSection() {
{pending.backup.settings && (
<label className="flex cursor-pointer items-center gap-2.5 text-sm text-fg-2">
<input type="checkbox" checked={withSettings} onChange={(e) => setWithSettings(e.target.checked)} className="size-4 accent-[var(--accent)]" />
- Aplicar também tema e preferências do player
+ {t.backup.applySettings}
</label>
)}
{confirmReplace && (
<p role="alert" className="text-sm text-danger">
- Isso apaga suas playlists, favoritas e histórico atuais. Toque em "Substituir agora" para confirmar.
+ {t.backup.confirmReplace}
</p>
)}
<div className="flex justify-end gap-2">
<button type="button" onClick={() => setPending(null)} className="h-11 rounded-full px-5 text-sm font-medium text-fg-2 hover:text-fg">
- Cancelar
+ {t.common.cancel}
</button>
<button
type="button"
@@ -171,7 +174,7 @@ export function BackupSection() {
mode === "replace" ? "bg-danger text-white" : "bg-accent text-accent-ink",
)}
>
- {busy === "import" ? "Importando" : mode === "replace" ? (confirmReplace ? "Substituir agora" : "Substituir") : "Importar"}
+ {busy === "import" ? t.backup.importing : mode === "replace" ? (confirmReplace ? t.backup.replaceNow : t.backup.replace) : t.backup.import}
</button>
</div>
</div>
diff --git a/web/src/components/Controls.tsx b/web/src/components/Controls.tsx
index 47b6c6a..9f21e72 100644
--- a/web/src/components/Controls.tsx
+++ b/web/src/components/Controls.tsx
@@ -15,6 +15,7 @@ import {
} from "@phosphor-icons/react";
import { useState } from "react";
import { useShallow } from "zustand/react/shallow";
+import { useT } from "../i18n";
import { cn, formatTime } from "../lib/format";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
@@ -31,6 +32,7 @@ export function PlayPauseIcon({ size = 22 }: { size?: number }) {
}
export function Transport({ big = false }: { big?: boolean }) {
+ const t = useT();
const p = usePlayer(
useShallow((s) => ({
hasQueue: s.queue.length > 0,
@@ -46,13 +48,13 @@ export function Transport({ big = false }: { big?: boolean }) {
);
const hasTrack = p.hasQueue;
const RepeatGlyph = p.repeat === "one" ? RepeatOnceIcon : RepeatIcon;
- const repeatLabel = { off: "Repetir: desligado", all: "Repetir: fila", one: "Repetir: faixa" }[p.repeat];
+ const repeatLabel = { off: t.player.repeatOff, all: t.player.repeatAll, one: t.player.repeatOne }[p.repeat];
const iconSize = big ? 26 : 19;
return (
<div className={cn("flex items-center", big ? "justify-between" : "gap-2")}>
<IconButton
- label={p.shuffle ? "Ordem aleatória: ligada" : "Ordem aleatória: desligada"}
+ label={p.shuffle ? t.player.shuffleOn : t.player.shuffleOff}
active={p.shuffle}
size={big ? "lg" : "sm"}
onClick={p.toggleShuffle}
@@ -61,18 +63,18 @@ export function Transport({ big = false }: { big?: boolean }) {
<ShuffleIcon size={big ? 22 : 17} />
{p.shuffle && <span className="absolute bottom-0.5 size-1 rounded-full bg-accent-text" />}
</IconButton>
- <IconButton label="Anterior" size={big ? "lg" : "md"} onClick={p.prev} disabled={!hasTrack} className="text-fg">
+ <IconButton label={t.player.previous} size={big ? "lg" : "md"} onClick={p.prev} disabled={!hasTrack} className="text-fg">
<SkipBackIcon size={iconSize} weight="fill" />
</IconButton>
<PlayDisc
- label={p.status === "playing" ? "Pausar" : "Tocar"}
+ label={p.status === "playing" ? t.common.pause : t.common.play}
px={big ? 72 : 40}
onClick={p.toggle}
disabled={!hasTrack}
>
<PlayPauseIcon size={big ? 30 : 20} />
</PlayDisc>
- <IconButton label="Próxima" size={big ? "lg" : "md"} onClick={p.next} disabled={!hasTrack} className="text-fg">
+ <IconButton label={t.player.next} size={big ? "lg" : "md"} onClick={p.next} disabled={!hasTrack} className="text-fg">
<SkipForwardIcon size={iconSize} weight="fill" />
</IconButton>
<IconButton
@@ -90,6 +92,7 @@ export function Transport({ big = false }: { big?: boolean }) {
}
export function Scrubber({ touch = false, className }: { touch?: boolean; className?: string }) {
+ const t = useT();
const position = usePlayer((s) => s.position);
const duration = usePlayer((s) => s.duration);
const buffered = usePlayer((s) => s.buffered);
@@ -103,7 +106,7 @@ export function Scrubber({ touch = false, className }: { touch?: boolean; classN
if (touch) {
return (
<div className={className}>
- <Slider label="Progresso" value={position} max={duration} buffered={buffered} onChange={seek} onScrub={setScrub} showThumb step={5} valueText={formatTime} />
+ <Slider label={t.player.progress} value={position} max={duration} buffered={buffered} onChange={seek} onScrub={setScrub} showThumb step={5} valueText={formatTime} />
<div className="mt-0.5 flex justify-between">
{time}
{total}
@@ -114,13 +117,14 @@ export function Scrubber({ touch = false, className }: { touch?: boolean; classN
return (
<div className={cn("flex items-center gap-2", className)}>
<span className="text-right">{time}</span>
- <Slider label="Progresso" value={position} max={duration} buffered={buffered} onChange={seek} onScrub={setScrub} step={5} valueText={formatTime} className="flex-1" />
+ <Slider label={t.player.progress} value={position} max={duration} buffered={buffered} onChange={seek} onScrub={setScrub} step={5} valueText={formatTime} className="flex-1" />
{total}
</div>
);
}
export function Volume({ className }: { className?: string }) {
+ const t = useT();
const volume = usePlayer((s) => s.volume);
const muted = usePlayer((s) => s.muted);
const setVolume = usePlayer((s) => s.setVolume);
@@ -129,10 +133,10 @@ export function Volume({ className }: { className?: string }) {
const Glyph = level === 0 ? SpeakerXIcon : level < 0.5 ? SpeakerLowIcon : SpeakerHighIcon;
return (
<div className={cn("flex items-center gap-1", className)}>
- <IconButton label={muted ? "Ativar som" : "Mudo"} size="sm" onClick={toggleMute}>
+ <IconButton label={muted ? t.player.unmute : t.player.mute} size="sm" onClick={toggleMute}>
<Glyph size={18} />
</IconButton>
- <Slider label="Volume" value={level} max={1} step={0.05} live onChange={setVolume} valueText={(v) => `${Math.round(v * 100)}%`} className="w-24" />
+ <Slider label={t.player.volume} value={level} max={1} step={0.05} live onChange={setVolume} valueText={(v) => `${Math.round(v * 100)}%`} className="w-24" />
</div>
);
}
@@ -140,9 +144,10 @@ export function Volume({ className }: { className?: string }) {
export function FavoriteButton({ track, size = "md" }: { track: Track | null; size?: "sm" | "md" | "lg" }) {
const isFavorite = useLibrary((s) => !!track && s.favorites.some((t) => t.id === track.id));
const toggle = useLibrary((s) => s.toggleFavorite);
+ const t = useT();
return (
<IconButton
- label={isFavorite ? "Remover das Favoritas" : "Adicionar às Favoritas"}
+ label={isFavorite ? t.common.removeFromFavorites : t.common.addToFavorites}
active={isFavorite}
size={size}
disabled={!track}
@@ -155,6 +160,7 @@ export function FavoriteButton({ track, size = "md" }: { track: Track | null; si
/** Audio / Video segmented switch. For songs, Video plays the song's music video when YouTube has one. */
export function ModeSwitch({ className }: { className?: string }) {
+ const t = useT();
const preferVideo = usePlayer((s) => s.preferVideo);
const setPreferVideo = usePlayer((s) => s.setPreferVideo);
const quality = usePlayer((s) => s.quality);
@@ -169,9 +175,9 @@ export function ModeSwitch({ className }: { className?: string }) {
return (
<div className={cn("flex items-center gap-2", className)}>
- <div role="radiogroup" aria-label="Modo de reprodução" className="flex rounded-full bg-surface-1 p-1 ring-1 ring-line">
+ <div role="radiogroup" aria-label={t.player.mode} className="flex rounded-full bg-surface-1 p-1 ring-1 ring-line">
<button type="button" role="radio" aria-checked={!preferVideo} className={seg(!preferVideo)} onClick={() => setPreferVideo(false)}>
- <MusicNotesIcon size={15} /> Áudio
+ <MusicNotesIcon size={15} /> {t.player.audio}
</button>
<button
type="button"
@@ -179,16 +185,16 @@ export function ModeSwitch({ className }: { className?: string }) {
aria-checked={preferVideo}
className={seg(preferVideo)}
onClick={() => setPreferVideo(true)}
- title="Ver o clipe"
+ title={t.player.watchClip}
>
- <VideoCameraIcon size={15} /> Vídeo
+ <VideoCameraIcon size={15} /> {t.player.video}
</button>
</div>
{showingVideo && (
<button
type="button"
onClick={() => setQuality(quality === "sd" ? "hd" : "sd")}
- title={quality === "sd" ? "Mudar para HD (720p, baixa antes de tocar)" : "Mudar para SD (360p, começa mais rápido quando disponível)"}
+ title={quality === "sd" ? t.player.toHd : t.player.toSd}
className={cn(
"h-9 rounded-full px-3 font-mono text-[12px] font-semibold ring-1 transition-colors",
quality === "hd" ? "bg-accent-soft text-accent-text ring-accent/40" : "text-fg-2 ring-line hover:text-fg",
diff --git a/web/src/components/Dialogs.tsx b/web/src/components/Dialogs.tsx
index 30b4d5c..6b806e4 100644
--- a/web/src/components/Dialogs.tsx
+++ b/web/src/components/Dialogs.tsx
@@ -1,6 +1,7 @@
import { CheckIcon, PlusIcon } from "@phosphor-icons/react";
import { useEffect, useState, type FormEvent } from "react";
-import { cn, plural } from "../lib/format";
+import { useT, type Messages } from "../i18n";
+import { cn } from "../lib/format";
import { useLibrary } from "../stores/library";
import { useUi } from "../stores/ui";
import { Artwork } from "./Artwork";
@@ -15,6 +16,7 @@ export function AddToPlaylistDialog() {
const [creating, setCreating] = useState(false);
const [name, setName] = useState("");
const many = !!tracks && tracks.length > 1;
+ const t = useT();
useEffect(() => {
if (tracks) {
@@ -34,12 +36,12 @@ export function AddToPlaylistDialog() {
<Modal
open={!!tracks}
onClose={() => close(null)}
- title={many ? `Adicionar ${tracks?.length} faixas à playlist` : "Adicionar à playlist"}
+ title={many ? t.dialogs.addManyToPlaylist(tracks?.length ?? 0) : t.dialogs.addToPlaylist}
>
{creating ? (
<form onSubmit={onCreate} className="flex flex-col gap-3">
<label htmlFor="new-playlist" className="text-sm text-fg-2">
- Nome da nova playlist
+ {t.dialogs.newPlaylistName}
</label>
<input
id="new-playlist"
@@ -47,13 +49,13 @@ export function AddToPlaylistDialog() {
value={name}
maxLength={80}
onChange={(e) => setName(e.target.value)}
- placeholder="Ex.: Treino, Foco, Estrada"
+ placeholder={t.dialogs.namePlaceholder}
className="h-12 rounded-full border border-line-strong bg-surface-1 px-5 text-[15px] placeholder:text-fg-3 focus:border-accent focus:outline-none"
/>
<div className="flex justify-end gap-2 pt-1">
{playlists.length > 0 && (
<button type="button" onClick={() => setCreating(false)} className="h-11 rounded-full px-5 text-sm font-medium text-fg-2 hover:text-fg">
- Voltar
+ {t.common.back}
</button>
)}
<button
@@ -61,7 +63,7 @@ export function AddToPlaylistDialog() {
disabled={!name.trim()}
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"
>
- Criar e adicionar
+ {t.dialogs.createAndAdd}
</button>
</div>
</form>
@@ -75,7 +77,7 @@ export function AddToPlaylistDialog() {
<span className="grid size-11 place-items-center rounded-[10px] bg-accent-soft text-accent-text">
<PlusIcon size={20} />
</span>
- <span className="font-medium">Nova playlist</span>
+ <span className="font-medium">{t.nav.newPlaylist}</span>
</button>
{playlists.map((p) => {
// Done only when it already has every track being added.
@@ -95,7 +97,7 @@ export function AddToPlaylistDialog() {
<Artwork src={p.tracks[0]?.thumb} className="size-11 rounded-[10px]" />
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{p.name}</span>
- <span className="block text-sm text-fg-2">{plural(p.tracks.length, "faixa", "faixas")}</span>
+ <span className="block text-sm text-fg-2">{t.common.tracks(p.tracks.length)}</span>
</span>
{has && <CheckIcon size={18} className="text-accent-text" />}
</button>
@@ -123,6 +125,7 @@ export function NamePlaylistDialog({
onClose: () => void;
}) {
const [name, setName] = useState(initial);
+ const t = useT();
useEffect(() => {
if (open) setName(initial);
}, [open, initial]);
@@ -137,7 +140,7 @@ export function NamePlaylistDialog({
className="flex flex-col gap-3"
>
<label htmlFor="playlist-name" className="text-sm text-fg-2">
- Nome
+ {t.dialogs.name}
</label>
<input
id="playlist-name"
@@ -145,7 +148,7 @@ export function NamePlaylistDialog({
value={name}
maxLength={80}
onChange={(e) => setName(e.target.value)}
- placeholder="Ex.: Treino, Foco, Estrada"
+ placeholder={t.dialogs.namePlaceholder}
className="h-12 rounded-full border border-line-strong bg-surface-1 px-5 text-[15px] placeholder:text-fg-3 focus:border-accent focus:outline-none"
/>
<div className="flex justify-end pt-1">
@@ -162,34 +165,35 @@ export function NamePlaylistDialog({
);
}
-const SHORTCUTS: [string, string][] = [
- ["Espaço", "Tocar / pausar"],
- ["← →", "Voltar / avançar 5 s"],
- ["Shift + ← →", "Faixa anterior / próxima"],
- ["↑ ↓", "Volume"],
- ["M", "Mudo"],
- ["L", "Favoritar faixa atual"],
- ["S", "Ordem aleatória"],
- ["R", "Repetir"],
- ["V", "Alternar vídeo"],
- ["F", "Maximizar vídeo"],
- ["Q", "Fila"],
- ["/", "Buscar"],
- ["?", "Esta lista"],
+const SHORTCUTS: [string | null, keyof Messages["dialogs"]["shortcuts"]][] = [
+ [null, "playPause"], // the Space key, named in each language
+ ["← →", "seek"],
+ ["Shift + ← →", "skip"],
+ ["↑ ↓", "volume"],
+ ["M", "mute"],
+ ["L", "favorite"],
+ ["S", "shuffle"],
+ ["R", "repeat"],
+ ["V", "video"],
+ ["F", "theater"],
+ ["Q", "queue"],
+ ["/", "search"],
+ ["?", "help"],
];
export function ShortcutsDialog() {
const open = useUi((s) => s.shortcutsOpen);
const setOpen = useUi((s) => s.setShortcutsOpen);
+ const t = useT();
return (
- <Modal open={open} onClose={() => setOpen(false)} title="Atalhos de teclado">
+ <Modal open={open} onClose={() => setOpen(false)} title={t.dialogs.shortcutsTitle}>
<dl className="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2.5 text-sm">
{SHORTCUTS.map(([keys, what]) => (
- <div key={keys} className="contents">
+ <div key={what} className="contents">
<dt className="flex justify-end">
- <kbd className="kbd">{keys}</kbd>
+ <kbd className="kbd">{keys ?? t.dialogs.space}</kbd>
</dt>
- <dd className="text-fg-2">{what}</dd>
+ <dd className="text-fg-2">{t.dialogs.shortcuts[what]}</dd>
</div>
))}
</dl>
diff --git a/web/src/components/GenrePanel.tsx b/web/src/components/GenrePanel.tsx
index 83f1e5d..7f3f47a 100644
--- a/web/src/components/GenrePanel.tsx
+++ b/web/src/components/GenrePanel.tsx
@@ -1,18 +1,23 @@
import { Link } from "react-router";
import { useRemote } from "../hooks/useRemote";
+import { useI18n, useT } from "../i18n";
import { api } from "../lib/api";
+import { paths } from "../lib/routes";
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());
+ const lang = useI18n((s) => s.lang);
+ const t = useT();
+ // Genre names come from YouTube Music in the app language, so each language has its own list.
+ const genres = useRemote<Genre[]>(`genres:${lang}`, () => 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>
+ <p className="mb-2.5 px-1 text-xs font-medium text-fg-2">{t.search.exploreGenres}</p>
{genres.status === "loading" && (
- <div aria-label="Carregando" className="flex flex-wrap gap-2">
+ <div aria-label={t.common.loading} 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` }} />
))}
@@ -23,7 +28,7 @@ export function GenrePanel({ id }: { id: string }) {
<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
+ {t.common.retry}
</button>
</p>
)}
@@ -33,7 +38,7 @@ export function GenrePanel({ id }: { id: string }) {
{genres.data.map((g) => (
<li key={g.id}>
<Link
- to={`/buscar/genero/${encodeURIComponent(g.id)}`}
+ to={paths.genre(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"
>
diff --git a/web/src/components/MobileChrome.tsx b/web/src/components/MobileChrome.tsx
index 24d88d0..f47afbf 100644
--- a/web/src/components/MobileChrome.tsx
+++ b/web/src/components/MobileChrome.tsx
@@ -1,24 +1,27 @@
import { BooksIcon, HouseIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
import { NavLink, useNavigate } from "react-router";
import { cn } from "../lib/format";
-import { selectCurrent, usePlayer } from "../player/player";
+import { useT } from "../i18n";
+import { NOW_PLAYING_HASH, paths } from "../lib/routes";
+import { selectCurrent, usePlayer, useStatusText } from "../player/player";
import { Artwork } from "./Artwork";
import { PlayPauseIcon } from "./Controls";
const tabs = [
- { to: "/", label: "Início", Icon: HouseIcon, end: true },
- { to: "/buscar", label: "Buscar", Icon: MagnifyingGlassIcon, end: false },
- { to: "/biblioteca", label: "Biblioteca", Icon: BooksIcon, end: false },
-];
+ { to: paths.home, key: "home", Icon: HouseIcon, end: true },
+ { to: paths.search, key: "search", Icon: MagnifyingGlassIcon, end: false },
+ { to: paths.library, key: "library", Icon: BooksIcon, end: false },
+] as const;
export function TabBar() {
+ const t = useT();
return (
<nav
- aria-label="Navegação principal"
+ aria-label={t.nav.main}
className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-bg/85 backdrop-blur-xl"
>
<ul className="mx-auto grid h-16 max-w-md grid-cols-3">
- {tabs.map(({ to, label, Icon, end }) => (
+ {tabs.map(({ to, key, Icon, end }) => (
<li key={to}>
<NavLink
to={to}
@@ -39,7 +42,7 @@ export function TabBar() {
)}
/>
<Icon size={24} weight={isActive ? "fill" : "regular"} />
- {label}
+ {t.nav[key]}
</>
)}
</NavLink>
@@ -55,8 +58,9 @@ export function MiniPlayer() {
const position = usePlayer((s) => s.position);
const duration = usePlayer((s) => s.duration);
const status = usePlayer((s) => s.status);
- const statusText = usePlayer((s) => s.statusText);
+ const statusText = useStatusText();
const toggle = usePlayer((s) => s.toggle);
+ const t = useT();
const navigate = useNavigate();
if (!track) return null;
const pct = duration > 0 ? Math.min(100, (position / duration) * 100) : 0;
@@ -67,9 +71,9 @@ export function MiniPlayer() {
<div className="island-core relative flex h-14 items-center gap-3 overflow-hidden pr-1 pl-1.5">
<button
type="button"
- onClick={() => navigate({ hash: "tocando" })}
+ onClick={() => navigate({ hash: NOW_PLAYING_HASH })}
className="flex min-w-0 flex-1 items-center gap-3 text-left"
- aria-label={`Abrir Tocando agora: ${track.title}`}
+ aria-label={t.player.openNowPlaying(track.title)}
>
<Artwork src={track.thumb} className="size-11 rounded-[10px]" />
<span className="min-w-0">
@@ -82,7 +86,7 @@ export function MiniPlayer() {
<button
type="button"
onClick={toggle}
- aria-label={status === "playing" ? "Pausar" : "Tocar"}
+ aria-label={status === "playing" ? t.common.pause : t.common.play}
className="grid size-11 shrink-0 place-items-center rounded-full text-fg active:scale-90"
>
<PlayPauseIcon size={24} />
diff --git a/web/src/components/Modal.tsx b/web/src/components/Modal.tsx
index b0d7a74..a07b617 100644
--- a/web/src/components/Modal.tsx
+++ b/web/src/components/Modal.tsx
@@ -3,6 +3,7 @@ import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { MD, useMediaQuery } from "../hooks/useMediaQuery";
+import { useT } from "../i18n";
import { IconButton } from "./IconButton";
/**
@@ -19,6 +20,7 @@ interface Props {
export function Modal({ open, onClose, title, children }: Props) {
const isMd = useMediaQuery(MD);
const reduce = useReducedMotion();
+ const t = useT();
useEffect(() => {
if (!open) return;
@@ -53,7 +55,7 @@ export function Modal({ open, onClose, title, children }: Props) {
<div className="island-core p-4 md:p-5">
<div className="mb-3 flex items-center justify-between gap-3">
<h2 className="text-lg font-semibold tracking-tight">{title}</h2>
- <IconButton label="Fechar" size="sm" onClick={onClose}>
+ <IconButton label={t.common.close} size="sm" onClick={onClose}>
<XIcon size={18} />
</IconButton>
</div>
diff --git a/web/src/components/NowPlaying.tsx b/web/src/components/NowPlaying.tsx
index af51758..dc08182 100644
--- a/web/src/components/NowPlaying.tsx
+++ b/web/src/components/NowPlaying.tsx
@@ -9,9 +9,10 @@ import {
import { AnimatePresence, motion, useDragControls, useReducedMotion } from "motion/react";
import { useState } from "react";
import { createPortal } from "react-dom";
+import { useT } from "../i18n";
import { cn } from "../lib/format";
import type { Track } from "../lib/types";
-import { selectCurrent, usePlayer } from "../player/player";
+import { selectCurrent, usePlayer, useStatusText } from "../player/player";
import { useUi, type PanelTab } from "../stores/ui";
import { Artwork } from "./Artwork";
import { FavoriteButton, ModeSwitch, Scrubber, Transport } from "./Controls";
@@ -21,11 +22,12 @@ import { SLOT, VideoSlot } from "./Video";
/** Artwork or the live video, with a soft ambient glow from the cover behind it. */
function Stage({ track, slot, className }: { track: Track; slot: number; className?: string }) {
+ const t = useT();
const showsVideo = usePlayer((s) => s.mediaKind === "video");
const aspect = usePlayer((s) => s.videoAspect);
// In Video mode on a song: say we're looking for its clip, or that it has none.
const note = usePlayer((s) =>
- s.preferVideo ? (s.videoNote ?? (s.statusText === "Procurando o clipe" ? s.statusText : null)) : null,
+ s.preferVideo ? (s.videoNote ?? (s.statusText === "findingClip" ? s.statusText : null)) : null,
);
if (showsVideo) {
const portrait = aspect < 1;
@@ -51,18 +53,18 @@ function Stage({ track, slot, className }: { track: Track; slot: number; classNa
<Artwork
src={track.art}
fallback={track.thumb}
- alt={`Capa de ${track.title}`}
+ alt={t.nowPlaying.coverOf(track.title)}
iconSize={48}
className="relative size-full rounded-[18px] shadow-[0_24px_60px_rgb(0_0_0/0.45)]"
/>
{note && (
<span className="absolute inset-x-3 bottom-3 flex items-center justify-center gap-2 rounded-full bg-black/65 px-3 py-2 text-center text-[13px] font-medium text-white backdrop-blur-md">
- {note === "Procurando o clipe" ? (
+ {note === "findingClip" ? (
<MagnifyingGlassIcon size={16} className="shrink-0" />
) : (
<VideoCameraSlashIcon size={16} className="shrink-0" />
)}{" "}
- {note}
+ {note === "findingClip" ? t.player.status.findingClip : t.player.noClip}
</span>
)}
</div>
@@ -70,7 +72,7 @@ function Stage({ track, slot, className }: { track: Track; slot: number; classNa
}
function TrackHeading({ track, large = false }: { track: Track; large?: boolean }) {
- const statusText = usePlayer((s) => s.statusText);
+ const statusText = useStatusText();
const status = usePlayer((s) => s.status);
return (
<div className="flex items-center gap-3">
@@ -90,10 +92,11 @@ function PanelBody({ tab, slot }: { tab: PanelTab; slot: number }) {
const startRadio = usePlayer((s) => s.startRadio);
const queue = usePlayer((s) => s.queue);
const index = usePlayer((s) => s.index);
+ const t = useT();
if (tab === "queue") return <QueueList />;
if (!track) {
- return <p className="px-2 py-16 text-center text-sm text-fg-2">Toque algo para ver aqui.</p>;
+ return <p className="px-2 py-16 text-center text-sm text-fg-2">{t.nowPlaying.playSomething}</p>;
}
const nextUp = queue[index + 1];
return (
@@ -106,11 +109,11 @@ function PanelBody({ tab, slot }: { tab: PanelTab; slot: number }) {
onClick={() => void startRadio(track)}
className="flex h-11 items-center justify-center gap-2 rounded-full bg-surface-1 text-sm font-medium ring-1 ring-line transition-colors hover:bg-surface-3 active:scale-[0.98]"
>
- <RadioIcon size={18} /> Iniciar rádio desta faixa
+ <RadioIcon size={18} /> {t.nowPlaying.startRadio}
</button>
{nextUp && (
<div className="rounded-[14px] bg-surface-1 p-3 ring-1 ring-line">
- <p className="pb-2 text-xs font-medium text-fg-3">A seguir</p>
+ <p className="pb-2 text-xs font-medium text-fg-3">{t.nowPlaying.upNext}</p>
<div className="flex items-center gap-3">
<Artwork src={nextUp.thumb} className="size-10 rounded-[8px]" />
<div className="min-w-0">
@@ -125,12 +128,13 @@ function PanelBody({ tab, slot }: { tab: PanelTab; slot: number }) {
}
function PanelTabs({ tab, onTab }: { tab: PanelTab; onTab: (t: PanelTab) => void }) {
+ const t = useT();
return (
<div role="tablist" className="flex gap-1">
{(
[
- ["playing", "Tocando"],
- ["queue", "Fila"],
+ ["playing", t.nowPlaying.tabPlaying],
+ ["queue", t.nowPlaying.tabQueue],
] as const
).map(([id, label]) => (
<button
@@ -156,12 +160,13 @@ export function SidePanel() {
const tab = useUi((s) => s.panelTab);
const openPanel = useUi((s) => s.openPanel);
const togglePanel = useUi((s) => s.togglePanel);
+ const t = useT();
return (
- <aside className="island hidden w-[360px] shrink-0 xl:flex" aria-label="Tocando agora e fila">
+ <aside className="island hidden w-[360px] shrink-0 xl:flex" aria-label={t.nowPlaying.panel}>
<div className="island-core flex w-full flex-col overflow-hidden">
<div className="flex h-16 items-center justify-between px-3">
<PanelTabs tab={tab} onTab={openPanel} />
- <IconButton label="Fechar painel" size="sm" onClick={() => togglePanel(tab)}>
+ <IconButton label={t.nowPlaying.closePanel} size="sm" onClick={() => togglePanel(tab)}>
<XIcon size={18} />
</IconButton>
</div>
@@ -180,6 +185,7 @@ export function PanelDrawer() {
const openPanel = useUi((s) => s.openPanel);
const close = useUi((s) => s.closePanel);
const reduce = useReducedMotion();
+ const t = useT();
return createPortal(
<AnimatePresence>
@@ -187,7 +193,7 @@ export function PanelDrawer() {
<div className="fixed inset-0 z-40 hidden md:block xl:hidden">
<motion.div className="absolute inset-0 bg-scrim" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={close} />
<motion.aside
- aria-label="Tocando agora e fila"
+ aria-label={t.nowPlaying.panel}
initial={reduce ? { opacity: 0 } : { x: "105%" }}
animate={{ x: 0, opacity: 1 }}
exit={reduce ? { opacity: 0 } : { x: "105%" }}
@@ -197,7 +203,7 @@ export function PanelDrawer() {
<div className="island-core flex w-full flex-col overflow-hidden">
<div className="flex h-16 items-center justify-between px-3">
<PanelTabs tab={tab} onTab={openPanel} />
- <IconButton label="Fechar" size="sm" onClick={close}>
+ <IconButton label={t.common.close} size="sm" onClick={close}>
<XIcon size={18} />
</IconButton>
</div>
@@ -219,6 +225,7 @@ export function NowPlayingSheet({ open, onClose }: { open: boolean; onClose: ()
const reduce = useReducedMotion();
const drag = useDragControls();
const [view, setView] = useState<"player" | "queue">("player");
+ const t = useT();
return createPortal(
<AnimatePresence onExitComplete={() => setView("player")}>
@@ -226,7 +233,7 @@ export function NowPlayingSheet({ open, onClose }: { open: boolean; onClose: ()
<motion.div
role="dialog"
aria-modal="true"
- aria-label="Tocando agora"
+ aria-label={t.nowPlaying.title}
initial={reduce ? { opacity: 0 } : { y: "100%" }}
animate={{ y: 0, opacity: 1 }}
exit={reduce ? { opacity: 0 } : { y: "100%" }}
@@ -251,12 +258,12 @@ export function NowPlayingSheet({ open, onClose }: { open: boolean; onClose: ()
<div className="overlay-top relative flex flex-1 flex-col px-5">
<div className="flex h-14 touch-none items-center justify-between" onPointerDown={(e) => drag.start(e)}>
- <IconButton label="Fechar" onClick={onClose} className="-ml-2 text-fg">
+ <IconButton label={t.common.close} onClick={onClose} className="-ml-2 text-fg">
<CaretDownIcon size={24} />
</IconButton>
<div className="mx-auto mt-0 h-1 w-10 rounded-full bg-fg-3/50" />
<IconButton
- label={view === "queue" ? "Voltar ao player" : "Ver fila"}
+ label={view === "queue" ? t.nowPlaying.backToPlayer : t.nowPlaying.showQueue}
active={view === "queue"}
onClick={() => setView(view === "queue" ? "player" : "queue")}
className="-mr-2"
diff --git a/web/src/components/Page.tsx b/web/src/components/Page.tsx
index 680b87b..b93afd8 100644
--- a/web/src/components/Page.tsx
+++ b/web/src/components/Page.tsx
@@ -1,6 +1,7 @@
import { ArrowLeftIcon, GearSixIcon } from "@phosphor-icons/react";
import type { ReactNode } from "react";
import { useNavigate } from "react-router";
+import { useT } from "../i18n";
import { cn } from "../lib/format";
import { needsAttention, useSystem } from "../stores/system";
import { useUi } from "../stores/ui";
@@ -22,6 +23,7 @@ export function PageHeader({
}) {
const setSettingsOpen = useUi((s) => s.setSettingsOpen);
const attention = useSystem((s) => needsAttention(s.info));
+ const t = useT();
return (
<header
className={cn(
@@ -37,7 +39,7 @@ export function PageHeader({
{!title && <span className="flex-1" />}
{actions}
<IconButton
- label={attention ? "Ajustes (atualização do yt-dlp disponível)" : "Ajustes"}
+ label={attention ? t.nav.settingsUpdate : t.nav.settings}
onClick={() => setSettingsOpen(true)}
className="-mr-2 md:hidden"
>
@@ -62,15 +64,16 @@ 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 }) {
+export function BackButton({ fallback, label }: { fallback: string; label?: string }) {
const navigate = useNavigate();
+ const t = useT();
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}
+ <ArrowLeftIcon size={16} /> {label ?? t.common.back}
</button>
);
}
diff --git a/web/src/components/PlayerBar.tsx b/web/src/components/PlayerBar.tsx
index 8189387..5561f08 100644
--- a/web/src/components/PlayerBar.tsx
+++ b/web/src/components/PlayerBar.tsx
@@ -1,6 +1,7 @@
import { KeyboardIcon, QueueIcon, SidebarSimpleIcon } from "@phosphor-icons/react";
import { cn } from "../lib/format";
-import { selectCurrent, usePlayer } from "../player/player";
+import { useT } from "../i18n";
+import { selectCurrent, usePlayer, useStatusText } from "../player/player";
import { useUi } from "../stores/ui";
import { Artwork } from "./Artwork";
import { FavoriteButton, ModeSwitch, Scrubber, Transport, Volume } from "./Controls";
@@ -9,7 +10,8 @@ import { IconButton } from "./IconButton";
/** Desktop and tablet player: a floating island under the content. */
export function PlayerBar() {
const track = usePlayer(selectCurrent);
- const statusText = usePlayer((s) => s.statusText);
+ const statusText = useStatusText();
+ const t = useT();
const status = usePlayer((s) => s.status);
const panelOpen = useUi((s) => s.panelOpen || s.drawerOpen);
const panelTab = useUi((s) => s.panelTab);
@@ -25,7 +27,7 @@ export function PlayerBar() {
<button
type="button"
onClick={() => togglePanel("playing")}
- aria-label="Mostrar Tocando agora"
+ aria-label={t.player.showNowPlaying}
className="group relative shrink-0 rounded-[10px] transition-transform active:scale-[0.96]"
>
<Artwork src={track.thumb} className="size-14 rounded-[10px]" />
@@ -39,7 +41,7 @@ export function PlayerBar() {
<FavoriteButton track={track} size="sm" />
</>
) : (
- <p className="truncate pl-1 text-sm text-fg-3">Nada tocando. Busque algo para começar.</p>
+ <p className="truncate pl-1 text-sm text-fg-3">{t.player.nothingPlaying}</p>
)}
</div>
@@ -51,7 +53,7 @@ export function PlayerBar() {
<div className="flex items-center justify-end gap-1">
<ModeSwitch className="max-2xl:hidden" />
<IconButton
- label="Fila"
+ label={t.player.queue}
size="sm"
active={panelOpen && panelTab === "queue"}
onClick={() => togglePanel("queue")}
@@ -59,7 +61,7 @@ export function PlayerBar() {
<QueueIcon size={18} />
</IconButton>
<IconButton
- label="Painel Tocando agora"
+ label={t.player.nowPlayingPanel}
size="sm"
active={panelOpen && panelTab === "playing"}
onClick={() => togglePanel("playing")}
@@ -67,7 +69,7 @@ export function PlayerBar() {
<SidebarSimpleIcon size={18} mirrored />
</IconButton>
<Volume className="max-lg:hidden" />
- <IconButton label="Atalhos de teclado (?)" size="sm" onClick={() => setShortcutsOpen(true)} className="max-xl:hidden">
+ <IconButton label={t.player.shortcuts} size="sm" onClick={() => setShortcutsOpen(true)} className="max-xl:hidden">
<KeyboardIcon size={18} />
</IconButton>
</div>
diff --git a/web/src/components/Queue.tsx b/web/src/components/Queue.tsx
index a562ed6..bafa8b3 100644
--- a/web/src/components/Queue.tsx
+++ b/web/src/components/Queue.tsx
@@ -1,10 +1,12 @@
import { QueueIcon, XIcon } from "@phosphor-icons/react";
+import { useT } from "../i18n";
import { cn, formatTime } from "../lib/format";
import { usePlayer } from "../player/player";
import { Artwork } from "./Artwork";
import { Equalizer } from "./Brand";
export function QueueList({ compact = false }: { compact?: boolean }) {
+ const t = useT();
const queue = usePlayer((s) => s.queue);
const index = usePlayer((s) => s.index);
const live = usePlayer((s) => s.status === "playing" || s.status === "loading");
@@ -23,34 +25,34 @@ export function QueueList({ compact = false }: { compact?: boolean }) {
<span className="grid size-14 place-items-center rounded-[14px] bg-surface-3 text-fg-3">
<QueueIcon size={26} />
</span>
- <p className="font-medium">A fila está vazia</p>
- <p className="max-w-[28ch] text-sm text-fg-2">Toque uma música ou use "Adicionar à fila" no menu de qualquer faixa.</p>
+ <p className="font-medium">{t.queue.emptyTitle}</p>
+ <p className="max-w-[28ch] text-sm text-fg-2">{t.queue.emptyBody}</p>
</div>
);
}
const row = (i: number, isCurrent: boolean) => {
- const t = queue[i];
+ const track = queue[i];
return (
- <li key={`${t.id}-${i}`} className="group relative flex items-center gap-3 rounded-xl px-2 py-1.5 hover:bg-surface-3">
- <button type="button" onClick={() => jumpTo(i)} className="absolute inset-0 rounded-xl" aria-label={`Tocar ${t.title}`} />
- <Artwork src={t.thumb} className="pointer-events-none size-10 rounded-[8px]" />
+ <li key={`${track.id}-${i}`} className="group relative flex items-center gap-3 rounded-xl px-2 py-1.5 hover:bg-surface-3">
+ <button type="button" onClick={() => jumpTo(i)} className="absolute inset-0 rounded-xl" aria-label={t.common.playX(track.title)} />
+ <Artwork src={track.thumb} className="pointer-events-none size-10 rounded-[8px]" />
<div className="pointer-events-none min-w-0 flex-1">
- <p className={cn("truncate text-sm font-medium", isCurrent ? "text-accent-text" : "text-fg")}>{t.title}</p>
- <p className="truncate text-xs text-fg-2">{t.artist}</p>
+ <p className={cn("truncate text-sm font-medium", isCurrent ? "text-accent-text" : "text-fg")}>{track.title}</p>
+ <p className="truncate text-xs text-fg-2">{track.artist}</p>
</div>
{isCurrent ? (
<Equalizer live={live} className="mr-2" />
) : (
<>
<span className="pointer-events-none font-mono text-xs text-fg-3 tabular-nums group-hover:hidden">
- {t.duration ? formatTime(t.duration) : ""}
+ {track.duration ? formatTime(track.duration) : ""}
</span>
<button
type="button"
onClick={() => removeAt(i)}
- aria-label={`Remover ${t.title} da fila`}
- title="Remover da fila"
+ aria-label={t.queue.removeX(track.title)}
+ title={t.queue.remove}
className="relative z-10 hidden size-8 place-items-center rounded-full text-fg-2 hover:bg-surface-4 hover:text-fg group-hover:grid max-md:grid"
>
<XIcon size={16} />
@@ -64,32 +66,34 @@ export function QueueList({ compact = false }: { compact?: boolean }) {
return (
<div className={cn("flex flex-col gap-4", compact ? "" : "pb-4")}>
<section>
- <h3 className="px-2 pb-1.5 text-xs font-medium text-fg-3">Tocando agora</h3>
+ <h3 className="px-2 pb-1.5 text-xs font-medium text-fg-3">{t.queue.nowPlaying}</h3>
<ul>{row(index, true)}</ul>
</section>
<section>
<div className="flex items-center justify-between px-2 pb-1.5">
<h3 className="text-xs font-medium text-fg-3">
- A seguir <span className="font-mono">{upcoming.length}</span>
+ {t.queue.upNext} <span className="font-mono">{upcoming.length}</span>
</h3>
{upcoming.length > 0 && (
<button type="button" onClick={clearUpcoming} className="text-xs font-medium text-fg-2 hover:text-fg">
- Limpar
+ {t.queue.clear}
</button>
)}
</div>
{upcoming.length ? (
<ul>{upcoming.map((_, k) => row(index + 1 + k, false))}</ul>
) : (
- <p className="px-2 text-sm text-fg-2">Nada na fila. {autoRadio ? "O rádio continua quando acabar." : ""}</p>
+ <p className="px-2 text-sm text-fg-2">
+ {t.queue.nothingQueued} {autoRadio ? t.queue.radioContinues : ""}
+ </p>
)}
</section>
<label className="mx-2 flex cursor-pointer items-center justify-between gap-3 rounded-xl bg-surface-1 px-3 py-2.5 ring-1 ring-line">
<span>
- <span className="block text-sm font-medium">Rádio automático</span>
- <span className="block text-xs text-fg-2">Continua com músicas parecidas quando a fila acabar</span>
+ <span className="block text-sm font-medium">{t.queue.autoRadio}</span>
+ <span className="block text-xs text-fg-2">{t.queue.autoRadioBody}</span>
</span>
<input
type="checkbox"
diff --git a/web/src/components/Rail.tsx b/web/src/components/Rail.tsx
index aceed3d..6ce2854 100644
--- a/web/src/components/Rail.tsx
+++ b/web/src/components/Rail.tsx
@@ -9,7 +9,9 @@ import {
} from "@phosphor-icons/react";
import { useState, type ReactNode } from "react";
import { NavLink, useNavigate } from "react-router";
-import { cn, plural } from "../lib/format";
+import { useT } from "../i18n";
+import { cn } from "../lib/format";
+import { paths } from "../lib/routes";
import { useLibrary } from "../stores/library";
import { needsAttention, useSystem } from "../stores/system";
import { useUi } from "../stores/ui";
@@ -18,13 +20,14 @@ import { Logo, LogoMark } from "./Brand";
import { NamePlaylistDialog } from "./Dialogs";
const nav = [
- { to: "/", label: "Início", Icon: HouseIcon, end: true },
- { to: "/buscar", label: "Buscar", Icon: MagnifyingGlassIcon, end: false },
- { to: "/biblioteca", label: "Biblioteca", Icon: BooksIcon, end: false },
-];
+ { to: paths.home, key: "home", Icon: HouseIcon, end: true },
+ { to: paths.search, key: "search", Icon: MagnifyingGlassIcon, end: false },
+ { to: paths.library, key: "library", Icon: BooksIcon, end: false },
+] as const;
-/** Settings entry. Shows a dot (and on the wide rail, an "Atualizar" pill) when yt-dlp needs attention. */
+/** Settings entry. Shows a dot (and on the wide rail, an "Update" pill) when yt-dlp needs attention. */
function SettingsButton() {
+ const t = useT();
const info = useSystem((s) => s.info);
const setOpen = useUi((s) => s.setSettingsOpen);
const attention = needsAttention(info);
@@ -33,17 +36,17 @@ function SettingsButton() {
<button
type="button"
onClick={() => setOpen(true)}
- aria-label={attention ? "Ajustes (atenção necessária)" : "Ajustes"}
- title="Ajustes"
+ aria-label={attention ? t.nav.settingsAttention : t.nav.settings}
+ title={t.nav.settings}
className="relative flex h-10 w-full items-center justify-center gap-2 rounded-full px-3 text-sm text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg xl:justify-start"
>
<GearSixIcon size={19} />
- <span className="hidden flex-1 text-left xl:inline">Ajustes</span>
+ <span className="hidden flex-1 text-left xl:inline">{t.nav.settings}</span>
{attention && (
<>
<span className="absolute top-2 right-[calc(50%-14px)] size-2 rounded-full bg-accent ring-2 ring-surface-2 xl:hidden" />
<span className="hidden rounded-full bg-accent-soft px-2 py-0.5 text-[11px] font-semibold text-accent-text xl:inline">
- {updatable ? "Atualizar" : "Verificar"}
+ {updatable ? t.nav.updatePill : t.nav.checkPill}
</span>
</>
)}
@@ -89,6 +92,7 @@ function RailLink({ to, label, sub, end, children }: { to: string; label: string
}
export function Rail() {
+ const t = useT();
const playlists = useLibrary((s) => s.playlists);
const favorites = useLibrary((s) => s.favorites);
const createPlaylist = useLibrary((s) => s.createPlaylist);
@@ -105,13 +109,13 @@ export function Rail() {
</span>
</div>
- <nav aria-label="Navegação principal" className="flex flex-col gap-1 px-2">
- {nav.map(({ to, label, Icon, end }) => (
+ <nav aria-label={t.nav.main} className="flex flex-col gap-1 px-2">
+ {nav.map(({ to, key, Icon, end }) => (
<NavLink
key={to}
to={to}
end={end}
- title={label}
+ title={t.nav[key]}
className={({ isActive }) =>
cn(
"flex h-11 items-center justify-center gap-3 rounded-full transition-colors duration-200 xl:justify-start xl:px-4",
@@ -122,7 +126,7 @@ export function Rail() {
{({ isActive }) => (
<>
<Icon size={22} weight={isActive ? "fill" : "regular"} />
- <span className="hidden text-sm font-medium xl:inline">{label}</span>
+ <span className="hidden text-sm font-medium xl:inline">{t.nav[key]}</span>
</>
)}
</NavLink>
@@ -132,12 +136,12 @@ export function Rail() {
<div className="mx-4 my-3 h-px bg-line" />
<div className="flex items-center justify-between px-4 pb-1">
- <span className="hidden text-xs font-medium text-fg-3 xl:block">Sua coleção</span>
+ <span className="hidden text-xs font-medium text-fg-3 xl:block">{t.nav.yourCollection}</span>
<button
type="button"
onClick={() => setCreating(true)}
- aria-label="Nova playlist"
- title="Nova playlist"
+ aria-label={t.nav.newPlaylist}
+ title={t.nav.newPlaylist}
className="mx-auto grid size-8 place-items-center rounded-full text-fg-2 transition-colors hover:bg-surface-3 hover:text-fg xl:mx-0"
>
<PlusIcon size={18} />
@@ -145,18 +149,18 @@ export function Rail() {
</div>
<div className="scroll-area flex flex-1 flex-col gap-0.5 overflow-y-auto px-2 pb-2">
- <RailLink to="/favoritas" label="Favoritas" sub={plural(favorites.length, "faixa", "faixas")}>
+ <RailLink to={paths.favorites} label={t.nav.favorites} sub={t.common.tracks(favorites.length)}>
<span className="grid size-full place-items-center bg-accent-soft text-accent-text">
<HeartIcon size={20} weight="fill" />
</span>
</RailLink>
- <RailLink to="/historico" label="Tocadas recentemente" sub="Histórico">
+ <RailLink to={paths.history} label={t.nav.recentlyPlayed} sub={t.nav.history}>
<span className="grid size-full place-items-center bg-surface-3 text-fg-2">
<ClockCounterClockwiseIcon size={20} />
</span>
</RailLink>
{playlists.map((p) => (
- <RailLink key={p.id} to={`/playlist/${p.id}`} label={p.name} sub={plural(p.tracks.length, "faixa", "faixas")}>
+ <RailLink key={p.id} to={paths.playlist(p.id)} label={p.name} sub={t.common.tracks(p.tracks.length)}>
<Artwork src={p.tracks[0]?.thumb} className="size-full" iconSize={18} />
</RailLink>
))}
@@ -169,13 +173,13 @@ export function Rail() {
<NamePlaylistDialog
open={creating}
- title="Nova playlist"
- action="Criar"
+ title={t.nav.newPlaylist}
+ action={t.library.create}
onClose={() => setCreating(false)}
onSubmit={async (name) => {
const p = await createPlaylist(name);
setCreating(false);
- if (p) navigate(`/playlist/${p.id}`);
+ if (p) navigate(paths.playlist(p.id));
}}
/>
</aside>
diff --git a/web/src/components/Selection.tsx b/web/src/components/Selection.tsx
index 8649a83..5826a33 100644
--- a/web/src/components/Selection.tsx
+++ b/web/src/components/Selection.tsx
@@ -1,6 +1,7 @@
import { CheckIcon, HeartIcon, PlayIcon, PlaylistIcon, VideoCameraIcon } from "@phosphor-icons/react";
import { useState, type ReactNode } from "react";
-import { cn, formatTime, plural } from "../lib/format";
+import { useT } from "../i18n";
+import { cn, formatTime } from "../lib/format";
import type { Track } from "../lib/types";
import { selectCurrent, usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
@@ -24,12 +25,14 @@ export function Check({ on }: { on: boolean }) {
function Action({
icon,
label,
+ phoneLabel,
onClick,
disabled,
primary,
}: {
icon: ReactNode;
label: string;
+ phoneLabel?: string;
onClick: () => void;
disabled?: boolean;
primary?: boolean;
@@ -47,8 +50,8 @@ function Action({
)}
>
{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>}
+ {/* Phones keep only "Play"; the icons are familiar enough for the rest. */}
+ {primary ? <Short phone={phoneLabel ?? label} wide={label} /> : <span className="hidden sm:inline">{label}</span>}
</button>
);
}
@@ -63,14 +66,15 @@ export function Short({ phone, wide }: { phone: ReactNode; wide: ReactNode }) {
);
}
-/** "3 de 150 músicas", or "3 de 150" on phones. */
+/** "3 of 150 songs", or "3 of 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")}`} />;
+ const t = useT();
+ return <Short phone={t.selection.countShort(n, total)} wide={t.selection.count(n, total)} />;
}
/**
* 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.
+ * With nothing selected, "Play all" plays every track.
*/
export function SelectionBar({
chosen,
@@ -91,6 +95,7 @@ export function SelectionBar({
const addFavorites = useLibrary((s) => s.addFavorites);
const openAddToPlaylist = useUi((s) => s.openAddToPlaylist);
const toPlay = chosen.length ? chosen : all;
+ const t = useT();
return (
<div
@@ -115,12 +120,13 @@ export function SelectionBar({
<Action
primary
icon={<PlayIcon size={16} weight="fill" />}
- label={chosen.length ? "Tocar" : "Tocar tudo"}
+ label={chosen.length ? t.common.play : t.common.playAll}
+ phoneLabel={t.common.play}
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)} />
+ <Action icon={<HeartIcon size={16} />} label={t.common.favorite} disabled={!chosen.length} onClick={() => void addFavorites(chosen)} />
+ <Action icon={<PlaylistIcon size={16} />} label={t.common.playlist} disabled={!chosen.length} onClick={() => openAddToPlaylist(chosen)} />
</div>
</div>
);
@@ -150,7 +156,8 @@ export function SelectableRow({
}) {
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));
+ const isFavorite = useLibrary((s) => s.favorites.some((f) => f.id === track.id));
+ const t = useT();
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">
@@ -158,7 +165,7 @@ export function SelectableRow({
type="button"
role="checkbox"
aria-checked={selected}
- aria-label={`Selecionar ${track.title}`}
+ aria-label={t.selection.select(track.title)}
onClick={onToggle}
className="-m-2 p-2"
>
@@ -169,7 +176,7 @@ export function SelectableRow({
<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">
+ <button type="button" onClick={onPlay} aria-label={t.common.playX(track.title)} className="group/art relative shrink-0">
<Artwork src={track.thumb} className="size-11 rounded-[10px]" />
<span
className={cn(
@@ -184,15 +191,15 @@ export function SelectableRow({
<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" />}
+ {track.kind === "video" && <VideoCameraIcon size={13} className="shrink-0 text-fg-3" aria-label={t.common.video} />}
<span className="truncate">
- {track.artist || "YouTube"}
+ {track.artist || t.common.youtube}
{note}
</span>
</span>
</button>
- {isFavorite && <HeartIcon size={15} weight="fill" className="shrink-0 text-accent-text" aria-label="Nas Favoritas" />}
+ {isFavorite && <HeartIcon size={15} weight="fill" className="shrink-0 text-accent-text" aria-label={t.common.inFavorites} />}
<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) : ""}
@@ -209,6 +216,7 @@ export function SelectableTrackList({ tracks, numbered }: { tracks: Track[]; num
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 t = useT();
const toggle = (id: string) =>
setSelected((prev) => {
@@ -224,7 +232,7 @@ export function SelectableTrackList({ tracks, numbered }: { tracks: Track[]; num
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" />}
+ label={chosen.length ? <SelectedCount n={chosen.length} total={tracks.length} /> : <Short phone={t.selection.all} wide={t.selection.selectAll} />}
/>
<ul className="mt-2 flex flex-col px-2 md:px-3">
{tracks.map((t, i) => (
diff --git a/web/src/components/SettingsDialog.tsx b/web/src/components/SettingsDialog.tsx
index 38d80a8..7c808f1 100644
--- a/web/src/components/SettingsDialog.tsx
+++ b/web/src/components/SettingsDialog.tsx
@@ -4,9 +4,11 @@ import {
DownloadSimpleIcon,
MoonIcon,
SunIcon,
+ TranslateIcon,
WarningCircleIcon,
} from "@phosphor-icons/react";
import { useEffect, useRef, useState, type ReactNode } from "react";
+import { LANGUAGES, useI18n, useT, type Lang } from "../i18n";
import type { Channel } from "../lib/api";
import { cn } from "../lib/format";
import { useSystem } from "../stores/system";
@@ -47,6 +49,7 @@ function Segmented<T extends string>({
}
function Dependency({ name, role, path, fix }: { name: string; role: string; path: string | null; fix: string }) {
+ const t = useT();
return (
<li className="flex items-center gap-3 py-2.5" title={path ?? undefined}>
{path ? (
@@ -61,7 +64,7 @@ function Dependency({ name, role, path, fix }: { name: string; role: string; pat
role
) : (
<>
- Não encontrado. No terminal: <code className="font-mono text-fg">{fix}</code> e reinicie o Musike.
+ {t.settings.depMissingBefore} <code className="font-mono text-fg">{fix}</code> {t.settings.depMissingAfter}
</>
)}
</span>
@@ -78,6 +81,9 @@ export function SettingsDialog() {
const { info, status, load, update } = useSystem();
const [channel, setChannel] = useState<Channel>("stable");
const logBox = useRef<HTMLPreElement>(null);
+ const t = useT();
+ const lang = useI18n((s) => s.lang);
+ const setLang = useI18n((s) => s.setLang);
useEffect(() => {
if (open) void load();
@@ -100,74 +106,86 @@ export function SettingsDialog() {
const target = y?.latest[channel];
let action: string;
- if (running) action = job?.kind === "install" ? "Instalando" : "Atualizando";
- else if (missing) action = "Instalar yt-dlp";
- else if (switching) action = channel === "nightly" ? "Mudar para Nightly" : "Voltar para Estável";
- else if (y?.updateAvailable && target) action = `Atualizar para ${target}`;
- else action = "Verificar e atualizar";
+ if (running) action = job?.kind === "install" ? t.settings.installing : t.settings.updating;
+ else if (missing) action = t.settings.install;
+ else if (switching) action = channel === "nightly" ? t.settings.toNightly : t.settings.toStable;
+ else if (y?.updateAvailable && target) action = t.settings.updateTo(target);
+ else action = t.settings.check;
const chip = !info ? null : missing ? (
- <span className="rounded-full bg-danger/15 px-2.5 py-1 text-xs font-medium text-danger">Não encontrado</span>
+ <span className="rounded-full bg-danger/15 px-2.5 py-1 text-xs font-medium text-danger">{t.settings.chipMissing}</span>
) : y?.updateAvailable ? (
- <span className="rounded-full bg-accent-soft px-2.5 py-1 text-xs font-medium text-accent-text">Atualização disponível</span>
+ <span className="rounded-full bg-accent-soft px-2.5 py-1 text-xs font-medium text-accent-text">{t.settings.chipUpdate}</span>
) : (
- <span className="rounded-full bg-surface-3 px-2.5 py-1 text-xs font-medium text-fg-2">Atualizado</span>
+ <span className="rounded-full bg-surface-3 px-2.5 py-1 text-xs font-medium text-fg-2">{t.settings.chipOk}</span>
);
return (
- <Modal open={open} onClose={() => setOpen(false)} title="Ajustes">
+ <Modal open={open} onClose={() => setOpen(false)} title={t.settings.title}>
{/* Side padding keeps outset rings and the scrollbar from clipping the cards' edges. */}
<div className="scroll-area -mx-2 flex max-h-[70dvh] flex-col gap-5 overflow-y-auto px-2 pb-1">
<section className="flex flex-col gap-2">
- <h3 className="text-xs font-medium text-fg-3">Aparência</h3>
+ <h3 className="text-xs font-medium text-fg-3">{t.settings.appearance}</h3>
<Segmented
- label="Tema"
+ label={t.settings.theme}
value={theme}
onChange={setTheme}
options={[
- ["dark", <><MoonIcon size={15} /> Escuro</>],
- ["light", <><SunIcon size={15} /> Claro</>],
+ ["dark", <><MoonIcon size={15} /> {t.settings.dark}</>],
+ ["light", <><SunIcon size={15} /> {t.settings.light}</>],
]}
/>
</section>
+ <section className="flex flex-col gap-2">
+ <h3 className="flex items-center gap-1.5 text-xs font-medium text-fg-3">
+ <TranslateIcon size={14} /> {t.settings.language}
+ </h3>
+ <Segmented
+ label={t.settings.language}
+ value={lang}
+ onChange={setLang}
+ options={LANGUAGES.map(({ id, name }): [Lang, ReactNode] => [id, <span lang={id}>{name}</span>])}
+ />
+ </section>
+
<BackupSection />
<section className="flex flex-col gap-3">
- <h3 className="text-xs font-medium text-fg-3">Motor do YouTube</h3>
+ <h3 className="text-xs font-medium text-fg-3">{t.settings.engine}</h3>
<div className="flex flex-col gap-4 rounded-[16px] bg-surface-1 p-4 ring-1 ring-line">
<div className="flex items-start justify-between gap-3">
<div>
<p className="font-semibold tracking-tight">yt-dlp</p>
<p className="font-mono text-[13px] text-fg-2 tabular-nums">
- {status === "loading" && !info ? "verificando" : y?.version ?? "sem versão"}
- {y?.version && <span className="text-fg-3"> · {y.channel === "nightly" ? "nightly" : "estável"}</span>}
+ {status === "loading" && !info ? t.settings.checking : y?.version ?? t.settings.noVersion}
+ {y?.version && <span className="text-fg-3"> · {y.channel === "nightly" ? t.settings.nightly : t.settings.stable}</span>}
</p>
</div>
{chip}
</div>
<p className="text-sm text-fg-2">
- É quem busca o áudio e o vídeo no YouTube. O YouTube muda com frequência: se as músicas pararem de tocar, atualize aqui.
+ {t.settings.engineBody}
</p>
{!missing && (
<div className="flex flex-col gap-1.5">
<Segmented
- label="Canal de atualização"
+ label={t.settings.channel}
value={channel}
onChange={setChannel}
options={[
- ["stable", "Estável"],
- ["nightly", "Nightly"],
+ ["stable", t.settings.stableOption],
+ ["nightly", t.settings.nightlyOption],
]}
/>
<p className="px-1 text-xs text-fg-3">
{channel === "nightly"
- ? `Recebe correções no mesmo dia em que o YouTube muda.${y?.latest.nightly ? ` Última: ${y.latest.nightly}` : ""}`
- : `Versões testadas, lançadas a cada poucas semanas.${y?.latest.stable ? ` Última: ${y.latest.stable}` : ""}`}
+ ? t.settings.nightlyBody + (y?.latest.nightly ? t.settings.latest(y.latest.nightly) : "")
+ : t.settings.stableBody + (y?.latest.stable ? t.settings.latest(y.latest.stable) : "")}
</p>
</div>
)}
@@ -190,7 +208,7 @@ export function SettingsDialog() {
{missing && info && !info.canInstall && (
<p className="text-sm text-danger">
- O winget não está disponível. Instale o yt-dlp manualmente e reinicie o Musike.
+ {t.settings.noWinget}
</p>
)}
@@ -206,7 +224,7 @@ export function SettingsDialog() {
aria-live="polite"
className="max-h-36 overflow-y-auto rounded-[10px] bg-bg p-3 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-fg-2 scroll-area"
>
- {job.log.length ? job.log.join("\n") : "Iniciando"}
+ {job.log.length ? job.log.join("\n") : t.settings.starting}
</pre>
</div>
)}
@@ -214,8 +232,8 @@ export function SettingsDialog() {
{info && (
<ul className="divide-y divide-line px-1">
- <Dependency name="Deno" role="Resolve os desafios do YouTube" path={info.deno} fix="winget install DenoLand.Deno" />
- <Dependency name="FFmpeg" role="Junta vídeo e áudio no modo HD" path={info.ffmpeg} fix="winget install yt-dlp.FFmpeg" />
+ <Dependency name="Deno" role={t.settings.denoRole} path={info.deno} fix="winget install DenoLand.Deno" />
+ <Dependency name="FFmpeg" role={t.settings.ffmpegRole} path={info.ffmpeg} fix="winget install yt-dlp.FFmpeg" />
</ul>
)}
</section>
diff --git a/web/src/components/Toasts.tsx b/web/src/components/Toasts.tsx
index 8a1ef5c..c3106fb 100644
--- a/web/src/components/Toasts.tsx
+++ b/web/src/components/Toasts.tsx
@@ -1,10 +1,12 @@
import { CheckCircleIcon, WarningCircleIcon } from "@phosphor-icons/react";
import { AnimatePresence, motion } from "motion/react";
+import { useT } from "../i18n";
import { useUi } from "../stores/ui";
export function Toasts() {
const toasts = useUi((s) => s.toasts);
const dismiss = useUi((s) => s.dismissToast);
+ const t = useT();
return (
<div
@@ -12,9 +14,9 @@ export function Toasts() {
className="pointer-events-none fixed inset-x-0 bottom-[calc(140px+env(safe-area-inset-bottom))] z-[60] flex flex-col items-center gap-2 px-4 md:bottom-28"
>
<AnimatePresence initial={false}>
- {toasts.map((t) => (
+ {toasts.map((toast) => (
<motion.div
- key={t.id}
+ key={toast.id}
layout
initial={{ opacity: 0, y: 12, scale: 0.96 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
@@ -22,24 +24,24 @@ export function Toasts() {
transition={{ type: "spring", stiffness: 500, damping: 40 }}
className="pointer-events-auto flex max-w-md items-center gap-2.5 rounded-full border border-line-strong bg-surface-3 py-1.5 pr-1.5 pl-3 text-sm shadow-[0_8px_30px_rgb(0_0_0/0.35)]"
>
- <button type="button" onClick={() => dismiss(t.id)} className="flex min-w-0 items-center gap-2.5 py-1 text-left" aria-label={`${t.message}. Fechar aviso`}>
- {t.tone === "error" ? (
+ <button type="button" onClick={() => dismiss(toast.id)} className="flex min-w-0 items-center gap-2.5 py-1 text-left" aria-label={t.toasts.dismiss(toast.message)}>
+ {toast.tone === "error" ? (
<WarningCircleIcon size={18} weight="fill" className="shrink-0 text-danger" />
) : (
<CheckCircleIcon size={18} weight="fill" className="shrink-0 text-accent-text" />
)}
- <span className="line-clamp-2">{t.message}</span>
+ <span className="line-clamp-2">{toast.message}</span>
</button>
- {t.action ? (
+ {toast.action ? (
<button
type="button"
onClick={() => {
- t.action!.run();
- dismiss(t.id);
+ toast.action!.run();
+ dismiss(toast.id);
}}
className="h-8 shrink-0 rounded-full bg-accent px-3.5 text-[13px] font-semibold text-accent-ink transition-transform active:scale-95"
>
- {t.action.label}
+ {toast.action.label}
</button>
) : (
<span className="w-1.5" />
diff --git a/web/src/components/TrackList.tsx b/web/src/components/TrackList.tsx
index 0b0789f..1a18a28 100644
--- a/web/src/components/TrackList.tsx
+++ b/web/src/components/TrackList.tsx
@@ -1,5 +1,6 @@
import { ClockIcon, DotsThreeIcon, HeartIcon, VideoCameraIcon } from "@phosphor-icons/react";
import { memo, type MouseEvent } from "react";
+import { useT } from "../i18n";
import { cn, formatTime } from "../lib/format";
import type { Track } from "../lib/types";
import { selectCurrent, usePlayer } from "../player/player";
@@ -22,6 +23,7 @@ const TrackRow = memo(function TrackRow({ track, position, onPlay, playlistId, s
const isFavorite = useLibrary((s) => s.favorites.some((t) => t.id === track.id));
const toggleFavorite = useLibrary((s) => s.toggleFavorite);
const openMenu = useUi((s) => s.openMenu);
+ const t = useT();
const menuAt = (e: MouseEvent) => {
e.preventDefault();
@@ -44,7 +46,7 @@ const TrackRow = memo(function TrackRow({ track, position, onPlay, playlistId, s
<button
type="button"
onClick={onPlay}
- aria-label={`Tocar ${track.title}`}
+ aria-label={t.common.playX(track.title)}
className="absolute inset-0 rounded-xl focus-visible:outline-offset-[-2px]"
/>
@@ -66,8 +68,8 @@ const TrackRow = memo(function TrackRow({ track, position, onPlay, playlistId, s
{track.title}
</p>
<p className="mt-0.5 flex items-center gap-1.5 truncate 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"}</span>
+ {track.kind === "video" && <VideoCameraIcon size={13} className="shrink-0 text-fg-3" aria-label={t.common.video} />}
+ <span className="truncate">{track.artist || t.common.youtube}</span>
</p>
</div>
@@ -77,8 +79,8 @@ const TrackRow = memo(function TrackRow({ track, position, onPlay, playlistId, s
<button
type="button"
onClick={() => void toggleFavorite(track)}
- aria-label={isFavorite ? "Remover das Favoritas" : "Adicionar às Favoritas"}
- title={isFavorite ? "Remover das Favoritas" : "Adicionar às Favoritas"}
+ aria-label={isFavorite ? t.common.removeFromFavorites : t.common.addToFavorites}
+ title={isFavorite ? t.common.removeFromFavorites : t.common.addToFavorites}
className={cn(
"grid size-8 place-items-center rounded-full transition-[opacity,transform] active:scale-90",
isFavorite ? "text-accent-text" : "text-fg-2 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-fg",
@@ -94,8 +96,8 @@ const TrackRow = memo(function TrackRow({ track, position, onPlay, playlistId, s
<button
type="button"
onClick={menuAt}
- aria-label={`Mais opções para ${track.title}`}
- title="Mais opções"
+ aria-label={t.trackList.moreFor(track.title)}
+ title={t.trackList.more}
className="relative z-10 grid size-9 place-items-center rounded-full text-fg-2 transition-[opacity,background-color] hover:bg-surface-3 hover:text-fg md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100"
>
<DotsThreeIcon size={22} weight="bold" />
@@ -115,6 +117,7 @@ interface ListProps {
export function TrackList({ tracks, context, playlistId, showAlbum = true, header = true }: ListProps) {
const playList = usePlayer((s) => s.playList);
+ const t = useT();
return (
<div>
{header && (
@@ -128,10 +131,10 @@ export function TrackList({ tracks, context, playlistId, showAlbum = true, heade
>
<span className="text-center font-mono">#</span>
<span />
- <span>Título</span>
- {showAlbum && <span className="hidden lg:block">Álbum</span>}
+ <span>{t.trackList.title}</span>
+ {showAlbum && <span className="hidden lg:block">{t.trackList.album}</span>}
<span className="flex w-[84px] justify-end pr-0.5">
- <ClockIcon size={15} aria-label="Duração" />
+ <ClockIcon size={15} aria-label={t.trackList.duration} />
</span>
<span className="w-9" />
</div>
@@ -153,8 +156,9 @@ export function TrackList({ tracks, context, playlistId, showAlbum = true, heade
}
export function TrackListSkeleton({ rows = 8 }: { rows?: number }) {
+ const t = useT();
return (
- <ul aria-label="Carregando" className="flex flex-col gap-1">
+ <ul aria-label={t.common.loading} className="flex flex-col gap-1">
{Array.from({ length: rows }, (_, i) => (
<li key={i} className="flex items-center gap-3 px-2 py-1.5 md:px-3">
<span className="hidden w-7 md:block" />
diff --git a/web/src/components/TrackMenu.tsx b/web/src/components/TrackMenu.tsx
index eb6404b..3b676ba 100644
--- a/web/src/components/TrackMenu.tsx
+++ b/web/src/components/TrackMenu.tsx
@@ -12,6 +12,7 @@ import { AnimatePresence, motion } from "motion/react";
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { MD, useMediaQuery } from "../hooks/useMediaQuery";
+import { useT } from "../i18n";
import { cn } from "../lib/format";
import { usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
@@ -43,6 +44,7 @@ export function TrackMenu() {
const isFavorite = useLibrary((s) => (menu ? s.favorites.some((t) => t.id === menu.track.id) : false));
const isMd = useMediaQuery(MD);
const box = useRef<HTMLDivElement>(null);
+ const t = useT();
const [pos, setPos] = useState({ left: 0, top: 0 });
useLayoutEffect(() => {
@@ -71,28 +73,28 @@ export function TrackMenu() {
};
const content = menu && (
- <div role="menu" aria-label={`Ações para ${menu.track.title}`} className="flex flex-col">
+ <div role="menu" aria-label={t.trackMenu.actionsFor(menu.track.title)} className="flex flex-col">
<Item icon={<PlayIcon size={18} />} onClick={run(() => usePlayer.getState().playTrack(menu.track))}>
- Tocar agora
+ {t.trackMenu.playNow}
</Item>
<Item icon={<QueueIcon size={18} />} onClick={run(() => usePlayer.getState().playNext(menu.track))}>
- Tocar a seguir
+ {t.trackMenu.playNext}
</Item>
<Item icon={<ListPlusIcon size={18} />} onClick={run(() => usePlayer.getState().addToQueue(menu.track))}>
- Adicionar à fila
+ {t.trackMenu.addToQueue}
</Item>
<Item icon={<RadioIcon size={18} />} onClick={run(() => void usePlayer.getState().startRadio(menu.track))}>
- Iniciar rádio
+ {t.trackMenu.startRadio}
</Item>
<div className="mx-3 my-1 h-px bg-line" />
<Item
icon={<HeartIcon size={18} weight={isFavorite ? "fill" : "regular"} className={isFavorite ? "text-accent-text" : ""} />}
onClick={run(() => void useLibrary.getState().toggleFavorite(menu.track))}
>
- {isFavorite ? "Remover das Favoritas" : "Adicionar às Favoritas"}
+ {isFavorite ? t.common.removeFromFavorites : t.common.addToFavorites}
</Item>
<Item icon={<PlaylistIcon size={18} />} onClick={() => openAddToPlaylist([menu.track])}>
- Adicionar à playlist
+ {t.trackMenu.addToPlaylist}
</Item>
{menu.playlistId && (
<Item
@@ -100,7 +102,7 @@ export function TrackMenu() {
icon={<TrashIcon size={18} />}
onClick={run(() => void useLibrary.getState().removeFromPlaylist(menu.playlistId!, menu.track.id))}
>
- Remover desta playlist
+ {t.trackMenu.removeFromPlaylist}
</Item>
)}
<div className="mx-3 my-1 h-px bg-line" />
@@ -108,7 +110,7 @@ export function TrackMenu() {
icon={<ArrowSquareOutIcon size={18} />}
onClick={run(() => window.open(`https://www.youtube.com/watch?v=${menu.track.id}`, "_blank", "noopener"))}
>
- Abrir no YouTube
+ {t.trackMenu.openYoutube}
</Item>
</div>
);
diff --git a/web/src/components/Video.tsx b/web/src/components/Video.tsx
index b7582d6..61dc943 100644
--- a/web/src/components/Video.tsx
+++ b/web/src/components/Video.tsx
@@ -4,8 +4,9 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProp
import { createPortal } from "react-dom";
import { create } from "zustand";
import { MD, useMediaQuery } from "../hooks/useMediaQuery";
+import { useT } from "../i18n";
import { cn } from "../lib/format";
-import { selectCurrent, usePlayer, videoEl } from "../player/player";
+import { selectCurrent, usePlayer, useStatusText, videoEl } from "../player/player";
import { useUi } from "../stores/ui";
import { FavoriteButton, Scrubber, Transport, Volume } from "./Controls";
import { IconButton } from "./IconButton";
@@ -49,6 +50,7 @@ export function VideoSlot({
/** Offer a "maximize" button (and double-click) that opens the cinema view. */
expandable?: boolean;
}) {
+ const t = useT();
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const id = ++seq;
@@ -71,8 +73,8 @@ export function VideoSlot({
<button
type="button"
onClick={openTheater}
- aria-label="Maximizar vídeo"
- title="Maximizar (F)"
+ aria-label={t.video.maximize}
+ title={t.video.maximizeKey}
className="absolute top-2 right-2 grid size-9 place-items-center rounded-full bg-black/55 text-white backdrop-blur-sm transition-[opacity,transform] duration-200 active:scale-90 md:opacity-0 md:group-hover/video:opacity-100 md:focus-visible:opacity-100"
>
<ArrowsOutIcon size={18} />
@@ -86,6 +88,7 @@ export function VideoSlot({
export function FloatingVideo() {
const isVideo = usePlayer((s) => s.mediaKind === "video" && s.queue.length > 0);
const top = useSlots((s) => s.top);
+ const t = useT();
const isMd = useMediaQuery(MD);
const show = isVideo && top < SLOT.panel;
@@ -108,7 +111,7 @@ export function FloatingVideo() {
<button
type="button"
onClick={openTheater}
- aria-label="Maximizar vídeo"
+ aria-label={t.video.maximize}
className="absolute inset-0 grid place-items-end p-2 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100"
>
<span className="grid size-8 place-items-center rounded-full bg-black/60 text-white backdrop-blur-sm">
@@ -134,8 +137,9 @@ export function Theater() {
const playing = usePlayer((s) => s.status === "playing");
const toggle = usePlayer((s) => s.toggle);
const track = usePlayer(selectCurrent);
- const statusText = usePlayer((s) => s.statusText);
+ const statusText = useStatusText();
const reduce = useReducedMotion();
+ const t = useT();
const box = useRef<HTMLDivElement>(null);
const idle = useRef<ReturnType<typeof setTimeout> | null>(null);
const [chrome, setChrome] = useState(true);
@@ -205,7 +209,7 @@ export function Theater() {
ref={box}
role="dialog"
aria-modal="true"
- aria-label={`Vídeo: ${track.title}`}
+ aria-label={t.video.label(track.title)}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97 }}
@@ -231,13 +235,13 @@ export function Theater() {
<p className="truncate text-sm text-white/70">{statusText ?? track.artist}</p>
</div>
<IconButton
- label={fullscreen ? "Sair da tela cheia" : "Tela cheia"}
+ label={fullscreen ? t.video.exitFullscreen : t.video.fullscreen}
onClick={toggleFullscreen}
className="text-white/85 hover:bg-white/15 hover:text-white"
>
{fullscreen ? <CornersInIcon size={22} /> : <CornersOutIcon size={22} />}
</IconButton>
- <IconButton label="Fechar vídeo (Esc)" onClick={close} className="text-white/85 hover:bg-white/15 hover:text-white">
+ <IconButton label={t.video.close} onClick={close} className="text-white/85 hover:bg-white/15 hover:text-white">
{fullscreen ? <ArrowsInIcon size={22} /> : <XIcon size={22} />}
</IconButton>
</div>
diff --git a/web/src/hooks/useShortcuts.ts b/web/src/hooks/useShortcuts.ts
index 2729844..e451266 100644
--- a/web/src/hooks/useShortcuts.ts
+++ b/web/src/hooks/useShortcuts.ts
@@ -1,5 +1,6 @@
import { useEffect } from "react";
import { useNavigate } from "react-router";
+import { paths } from "../lib/routes";
import { selectCurrent, usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
import { useUi } from "../stores/ui";
@@ -75,7 +76,7 @@ export function useShortcuts() {
break;
case "/":
handled();
- navigate("/buscar");
+ navigate(paths.search);
requestAnimationFrame(() => document.getElementById("search-input")?.focus());
break;
case "?":
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
new file mode 100644
index 0000000..3d1657c
--- /dev/null
+++ b/web/src/i18n/en.ts
@@ -0,0 +1,392 @@
+/**
+ * English: Musike's own language and the source of truth for every other one.
+ * Other languages are typed as `Messages`, so a missing or extra key fails the build.
+ */
+
+const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+
+export const en = {
+ locale: "en-US",
+
+ common: {
+ close: "Close",
+ back: "Back",
+ cancel: "Cancel",
+ retry: "Try again",
+ loading: "Loading",
+ play: "Play",
+ pause: "Pause",
+ playX: (title: string) => `Play ${title}`,
+ playAll: "Play all",
+ favorite: "Favorite",
+ playlist: "Playlist",
+ addToFavorites: "Add to Favorites",
+ removeFromFavorites: "Remove from Favorites",
+ inFavorites: "In Favorites",
+ video: "Video",
+ youtube: "YouTube",
+ searchMusic: "Search music",
+ install: "Install",
+ update: "Update",
+ tracks: (n: number) => count(n, "track", "tracks"),
+ songs: (n: number) => count(n, "song", "songs"),
+ artists: (n: number) => count(n, "artist", "artists"),
+ },
+
+ time: {
+ greeting: (hour: number): string =>
+ hour < 5 ? "Good night" : hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening",
+ /** Total length of a list, e.g. "1 hr 5 min". */
+ total: (seconds: number) => {
+ const m = Math.round(seconds / 60);
+ return m < 60 ? `${m} min` : `${Math.floor(m / 60)} hr ${m % 60} min`;
+ },
+ },
+
+ nav: {
+ main: "Main navigation",
+ home: "Home",
+ search: "Search",
+ library: "Library",
+ settings: "Settings",
+ settingsAttention: "Settings (needs attention)",
+ settingsUpdate: "Settings (yt-dlp update available)",
+ updatePill: "Update",
+ checkPill: "Check",
+ yourCollection: "Your collection",
+ newPlaylist: "New playlist",
+ favorites: "Favorites",
+ recentlyPlayed: "Recently played",
+ history: "History",
+ },
+
+ home: {
+ startTitle: "Start with search",
+ startBody: "Find any song or music video on YouTube. It plays as audio or video, with no ads.",
+ seeAll: "See all",
+ yourFavorites: "Your favorites",
+ },
+
+ library: {
+ backup: "Library backup (export or import)",
+ newShort: "New",
+ create: "Create",
+ playlistSub: (n: number) => `Playlist · ${count(n, "track", "tracks")}`,
+ noPlaylists: "You don't have any playlists yet. Create one here or use any track's menu to start one.",
+ },
+
+ collection: {
+ labelPlaylist: "Playlist",
+ labelFavorites: "Collection",
+ labelHistory: "History",
+ notFoundTitle: "Playlist not found",
+ notFoundBody: "It may have been deleted.",
+ goToLibrary: "Go to Library",
+ shuffle: "Shuffle play",
+ more: "More playlist options",
+ emptyHistory: "Nothing played yet",
+ empty: "Still empty",
+ emptyFavoritesBody: "Tap the heart on any track to keep it here.",
+ emptyHistoryBody: "Songs you listen to show up here.",
+ emptyPlaylistBody: 'Search for songs and use "Add to playlist" in any track\'s menu.',
+ rename: "Rename",
+ renameTitle: "Rename playlist",
+ save: "Save",
+ deletePlaylist: "Delete playlist",
+ deleteTitle: "Delete playlist?",
+ deleteBody: (name: string, tracks: number) =>
+ `"${name}" and its list of ${count(tracks, "track", "tracks")} will be deleted. This can't be undone.`,
+ delete: "Delete",
+ },
+
+ dialogs: {
+ addToPlaylist: "Add to playlist",
+ addManyToPlaylist: (n: number) => `Add ${n} tracks to a playlist`,
+ newPlaylistName: "New playlist name",
+ name: "Name",
+ namePlaceholder: "E.g. Workout, Focus, Road trip",
+ createAndAdd: "Create and add",
+ shortcutsTitle: "Keyboard shortcuts",
+ space: "Space",
+ shortcuts: {
+ playPause: "Play / pause",
+ seek: "Back / forward 5 s",
+ skip: "Previous / next track",
+ volume: "Volume",
+ mute: "Mute",
+ favorite: "Favorite the current track",
+ shuffle: "Shuffle",
+ repeat: "Repeat",
+ video: "Toggle video",
+ theater: "Maximize video",
+ queue: "Queue",
+ search: "Search",
+ help: "This list",
+ },
+ },
+
+ player: {
+ repeatOff: "Repeat: off",
+ repeatAll: "Repeat: queue",
+ repeatOne: "Repeat: track",
+ shuffleOn: "Shuffle: on",
+ shuffleOff: "Shuffle: off",
+ previous: "Previous",
+ next: "Next",
+ progress: "Progress",
+ mute: "Mute",
+ unmute: "Unmute",
+ volume: "Volume",
+ mode: "Playback mode",
+ audio: "Audio",
+ video: "Video",
+ watchClip: "Watch the music video",
+ toHd: "Switch to HD (720p, downloads before playing)",
+ toSd: "Switch to SD (360p, starts faster when available)",
+ nothingPlaying: "Nothing playing. Search for something to start.",
+ showNowPlaying: "Show Now playing",
+ queue: "Queue",
+ nowPlayingPanel: "Now playing panel",
+ shortcuts: "Keyboard shortcuts (?)",
+ openNowPlaying: (title: string) => `Open Now playing: ${title}`,
+ status: {
+ findingClip: "Looking for the music video",
+ preparingHd: "Preparing HD video",
+ loadingVideo: "Loading video",
+ fetchingRadio: "Finding radio",
+ },
+ noClip: "This song has no music video on YouTube",
+ radioContinuing: (title: string) => `Continuing with radio from "${title}"`,
+ playsNext: (title: string) => `"${title}" plays next`,
+ addedToQueue: (title: string) => `"${title}" added to the queue`,
+ startingRadio: (title: string) => `Building radio from "${title}"`,
+ cantPlay: (title: string, reason: string) => `Couldn't play "${title}". ${reason}`,
+ aTrack: "this track",
+ browserCantPlay: "The browser couldn't play this format.",
+ serverDown: "Can't reach the Musike server. Is it running?",
+ httpError: (status: number) => `Error ${status}`,
+ },
+
+ nowPlaying: {
+ title: "Now playing",
+ coverOf: (title: string) => `Cover of ${title}`,
+ playSomething: "Play something to see it here.",
+ startRadio: "Start radio from this track",
+ upNext: "Up next",
+ tabPlaying: "Playing",
+ tabQueue: "Queue",
+ panel: "Now playing and queue",
+ closePanel: "Close panel",
+ backToPlayer: "Back to the player",
+ showQueue: "Show queue",
+ },
+
+ queue: {
+ emptyTitle: "The queue is empty",
+ emptyBody: 'Play a song or use "Add to queue" in any track\'s menu.',
+ removeX: (title: string) => `Remove ${title} from the queue`,
+ remove: "Remove from queue",
+ nowPlaying: "Now playing",
+ upNext: "Up next",
+ clear: "Clear",
+ nothingQueued: "Nothing in the queue.",
+ radioContinues: "Radio keeps going when it ends.",
+ autoRadio: "Autoplay radio",
+ autoRadioBody: "Keeps playing similar songs when the queue ends",
+ },
+
+ video: {
+ maximize: "Maximize video",
+ maximizeKey: "Maximize (F)",
+ label: (title: string) => `Video: ${title}`,
+ fullscreen: "Full screen",
+ exitFullscreen: "Exit full screen",
+ close: "Close video (Esc)",
+ },
+
+ trackMenu: {
+ actionsFor: (title: string) => `Actions for ${title}`,
+ playNow: "Play now",
+ playNext: "Play next",
+ addToQueue: "Add to queue",
+ startRadio: "Start radio",
+ addToPlaylist: "Add to playlist",
+ removeFromPlaylist: "Remove from this playlist",
+ openYoutube: "Open on YouTube",
+ },
+
+ trackList: {
+ moreFor: (title: string) => `More options for ${title}`,
+ more: "More options",
+ title: "Title",
+ album: "Album",
+ duration: "Duration",
+ },
+
+ search: {
+ title: "Search",
+ inputLabel: "Search songs, artists, videos or paste a YouTube link",
+ placeholder: "Songs, artists or a YouTube link",
+ clear: "Clear search",
+ searchSeparately: (n: number) => `Search ${n} songs separately`,
+ resultType: "Result type",
+ songs: "Songs",
+ videos: "Videos",
+ genres: "Genres",
+ list: "Search a list",
+ youtubeLink: "YouTube link",
+ linkError: "Couldn't open this link. Check that the video is public.",
+ failed: "Search failed",
+ nothingFound: "Nothing found",
+ nothingFoundBody: (query: string, otherTab: string) => `No results for "${query}". Try another term or the ${otherTab} tab.`,
+ recent: "Recent searches",
+ clearRecent: "Clear",
+ idleTitle: "What's playing today?",
+ idleBody:
+ "Search for a song, artist or album. For music videos and live performances, use the Videos tab. You can also paste a YouTube link.",
+ exploreGenres: "Browse by genre",
+ },
+
+ batch: {
+ title: "Search a list",
+ simple: "Simple search",
+ label: 'Write the songs separated by commas (or one per line). You can add the artist: "Bohemian Rhapsody Queen".',
+ placeholder: "E.g. Bohemian Rhapsody, Hotel California, Smells Like Teen Spirit",
+ max: (n: number) => `Up to ${n} at a time`,
+ searchN: (n: number) => `Search ${n} songs`,
+ search: "Search",
+ searching: (done: number, total: number) => `Searching… ${done}/${total}`,
+ searched: (query: string) => ` · searched "${query}"`,
+ swap: "Swap for another result",
+ swapShort: "Swap",
+ notFound: "Nothing found",
+ failed: "Search failed",
+ emptyTitle: "Many songs at once",
+ emptyBody:
+ "Musike searches for each one and picks the best match. Check them, swap any that came out wrong, then play, favorite or send them all to a playlist.",
+ },
+
+ selection: {
+ select: (title: string) => `Select ${title}`,
+ selectAll: "Select all",
+ all: "All",
+ countShort: (n: number, total: number) => `${n} of ${total}`,
+ count: (n: number, total: number) => `${n} of ${count(total, "song", "songs")}`,
+ },
+
+ genre: {
+ fallbackName: "Genre",
+ viewBy: "View by",
+ artistsTab: "Bands & artists",
+ artistsShort: "Artists",
+ songsTab: "All songs",
+ songsShort: "Songs",
+ openFailed: "Couldn't open this genre",
+ pickArtist: "Pick a band or artist to see their greatest hits.",
+ loadMore: "Load more",
+ loadingMore: "Finding more artists…",
+ endOfList: (n: number) => `End of the list: ${count(n, "artist", "artists")}`,
+ noArtists: "No artists listed",
+ noArtistsBody: "This genre only has playlists. See all its songs in the other tab.",
+ noSongs: "No songs listed",
+ noSongsBody: "Try another genre.",
+ },
+
+ artist: {
+ fallbackName: "Artist",
+ label: "Artist",
+ hits: "Greatest hits",
+ openFailed: "Couldn't open this artist",
+ noHits: "No songs found",
+ noHitsBody: "YouTube Music doesn't list hits for this artist.",
+ },
+
+ settings: {
+ title: "Settings",
+ appearance: "Appearance",
+ theme: "Theme",
+ dark: "Dark",
+ light: "Light",
+ language: "Language",
+ engine: "YouTube engine",
+ checking: "checking",
+ noVersion: "no version",
+ stable: "stable",
+ nightly: "nightly",
+ chipMissing: "Not found",
+ chipUpdate: "Update available",
+ chipOk: "Up to date",
+ engineBody: "It's what fetches audio and video from YouTube. YouTube changes often: if songs stop playing, update it here.",
+ channel: "Update channel",
+ stableOption: "Stable",
+ nightlyOption: "Nightly",
+ nightlyBody: "Gets fixes the same day YouTube changes.",
+ stableBody: "Tested releases, out every few weeks.",
+ latest: (version: string) => ` Latest: ${version}`,
+ installing: "Installing",
+ updating: "Updating",
+ install: "Install yt-dlp",
+ toNightly: "Switch to Nightly",
+ toStable: "Back to Stable",
+ updateTo: (version: string) => `Update to ${version}`,
+ check: "Check and update",
+ noWinget: "winget isn't available. Install yt-dlp manually and restart Musike.",
+ starting: "Starting",
+ denoRole: "Solves YouTube's challenges",
+ ffmpegRole: "Merges video and audio in HD mode",
+ depMissingBefore: "Not found. In a terminal:",
+ depMissingAfter: "and restart Musike.",
+ },
+
+ backup: {
+ yourData: "Your data",
+ body: "Take your playlists, favorites and history to another computer or to the desktop app: export a file here and import it into the other Musike.",
+ export: "Export",
+ exporting: "Exporting",
+ import: "Import",
+ importing: "Importing",
+ pickFile: "Choose a Musike backup file",
+ created: (playlists: number, favorites: number) =>
+ `Backup created: ${count(playlists, "playlist", "playlists")} and ${count(favorites, "favorite", "favorites")}`,
+ exportedAt: (date: string, time: string) => `Exported on ${date} at ${time}`,
+ playlistsWord: (n: number): string => (n === 1 ? "playlist" : "playlists"),
+ favoritesWord: (n: number): string => (n === 1 ? "favorite" : "favorites"),
+ tracksIn: (n: number) => count(n, "track", "tracks"),
+ inHistory: "in history",
+ howToImport: "How to import",
+ mergeTitle: "Merge with my library",
+ mergeBody: "Adds what's missing. Nothing is deleted; playlists with the same name get the new tracks.",
+ replaceTitle: "Replace everything",
+ replaceBody: "Deletes the current library and makes it exactly like the backup.",
+ applySettings: "Also apply theme, language and player preferences",
+ confirmReplace: 'This deletes your current playlists, favorites and history. Tap "Replace now" to confirm.',
+ replace: "Replace",
+ replaceNow: "Replace now",
+ imported: (parts: string[]) => `Imported: ${parts.join(", ")}`,
+ nothingNew: "Nothing new: your library already had everything in this backup",
+ newPlaylists: (n: number) => count(n, "new playlist", "new playlists"),
+ updatedPlaylists: (n: number) => count(n, "updated playlist", "updated playlists"),
+ addedTracks: (n: number) => count(n, "track added", "tracks added"),
+ addedFavorites: (n: number) => count(n, "favorite", "favorites"),
+ unreadable: "Couldn't read the file. It needs to be a .musike.json backup.",
+ notBackup: "This file isn't a Musike backup.",
+ newer: "This backup was made by a newer Musike. Update the app to import it.",
+ },
+
+ toasts: {
+ dismiss: (message: string) => `${message}. Close notice`,
+ addedFavorite: "Added to Favorites",
+ removedFavorite: "Removed from Favorites",
+ allAlreadyFavorites: "They were all in Favorites already",
+ addedFavorites: (n: number) => `${n} tracks added to Favorites`,
+ playlistCreated: (name: string) => `Playlist "${name}" created`,
+ playlistDeleted: "Playlist deleted",
+ addedTo: (name: string) => `Added to "${name}"`,
+ addedManyTo: (n: number, name: string) => `${n} tracks added to "${name}"`,
+ allAlreadyIn: (name: string) => `They were all in "${name}" already`,
+ ytdlpMissing: "yt-dlp wasn't found. No song plays without it.",
+ ytdlpUpdate: (version: string) => `New yt-dlp version available (${version})`,
+ },
+};
+
+export type Messages = typeof en;
diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts
new file mode 100644
index 0000000..9086857
--- /dev/null
+++ b/web/src/i18n/index.ts
@@ -0,0 +1,65 @@
+import { create } from "zustand";
+import { desktop } from "../lib/desktop";
+import { en, type Messages } from "./en";
+import { pt } from "./pt";
+
+export type { Messages };
+export type Lang = "en" | "pt-BR";
+
+/** Each language named in itself, as language pickers do. */
+export const LANGUAGES: { id: Lang; name: string }[] = [
+ { id: "en", name: "English" },
+ { id: "pt-BR", name: "Português (Brasil)" },
+];
+
+const MESSAGES: Record<Lang, Messages> = { en, "pt-BR": pt };
+const KEY = "musike:lang";
+
+export const isLang = (v: unknown): v is Lang => v === "en" || v === "pt-BR";
+
+/** Musike speaks English until the user picks another language in Settings. */
+function readLang(): Lang {
+ try {
+ const saved = localStorage.getItem(KEY);
+ if (isLang(saved)) return saved;
+ } catch {
+ /* private mode */
+ }
+ return "en";
+}
+
+function apply(lang: Lang) {
+ document.documentElement.lang = lang;
+ // The desktop shell shows its splash screen before the web app loads: tell it which language to use.
+ desktop?.setLanguage?.(lang);
+}
+
+interface I18nState {
+ lang: Lang;
+ t: Messages;
+ setLang: (lang: Lang) => void;
+}
+
+const initial = readLang();
+apply(initial);
+
+export const useI18n = create<I18nState>((set) => ({
+ lang: initial,
+ t: MESSAGES[initial],
+ setLang: (lang) => {
+ apply(lang);
+ try {
+ localStorage.setItem(KEY, lang);
+ } catch {
+ /* private mode */
+ }
+ set({ lang, t: MESSAGES[lang] });
+ },
+}));
+
+/** The current language's messages; re-renders when the language changes. */
+export const useT = () => useI18n((s) => s.t);
+
+/** For code outside React components (stores, the player): read at the moment of use. */
+export const getT = () => useI18n.getState().t;
+export const getLang = () => useI18n.getState().lang;
diff --git a/web/src/i18n/pt.ts b/web/src/i18n/pt.ts
new file mode 100644
index 0000000..25af8de
--- /dev/null
+++ b/web/src/i18n/pt.ts
@@ -0,0 +1,384 @@
+import type { Messages } from "./en";
+
+const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+
+export const pt: Messages = {
+ locale: "pt-BR",
+
+ common: {
+ close: "Fechar",
+ back: "Voltar",
+ cancel: "Cancelar",
+ retry: "Tentar de novo",
+ loading: "Carregando",
+ play: "Tocar",
+ pause: "Pausar",
+ playX: (title) => `Tocar ${title}`,
+ playAll: "Tocar tudo",
+ favorite: "Favoritar",
+ playlist: "Playlist",
+ addToFavorites: "Adicionar às Favoritas",
+ removeFromFavorites: "Remover das Favoritas",
+ inFavorites: "Nas Favoritas",
+ video: "Vídeo",
+ youtube: "YouTube",
+ searchMusic: "Buscar música",
+ install: "Instalar",
+ update: "Atualizar",
+ tracks: (n) => count(n, "faixa", "faixas"),
+ songs: (n) => count(n, "música", "músicas"),
+ artists: (n) => count(n, "artista", "artistas"),
+ },
+
+ time: {
+ greeting: (hour) => (hour < 5 ? "Boa madrugada" : hour < 12 ? "Bom dia" : hour < 18 ? "Boa tarde" : "Boa noite"),
+ total: (seconds) => {
+ const m = Math.round(seconds / 60);
+ return m < 60 ? `${m} min` : `${Math.floor(m / 60)} h ${m % 60} min`;
+ },
+ },
+
+ nav: {
+ main: "Navegação principal",
+ home: "Início",
+ search: "Buscar",
+ library: "Biblioteca",
+ settings: "Ajustes",
+ settingsAttention: "Ajustes (atenção necessária)",
+ settingsUpdate: "Ajustes (atualização do yt-dlp disponível)",
+ updatePill: "Atualizar",
+ checkPill: "Verificar",
+ yourCollection: "Sua coleção",
+ newPlaylist: "Nova playlist",
+ favorites: "Favoritas",
+ recentlyPlayed: "Tocadas recentemente",
+ history: "Histórico",
+ },
+
+ home: {
+ startTitle: "Comece pela busca",
+ startBody: "Procure qualquer música ou clipe do YouTube. Toca como áudio ou vídeo, sem anúncios.",
+ seeAll: "Ver tudo",
+ yourFavorites: "Suas favoritas",
+ },
+
+ library: {
+ backup: "Backup da biblioteca (exportar ou importar)",
+ newShort: "Nova",
+ create: "Criar",
+ playlistSub: (n) => `Playlist · ${count(n, "faixa", "faixas")}`,
+ noPlaylists: "Você ainda não tem playlists. Crie uma aqui ou use o menu de qualquer faixa para começar uma.",
+ },
+
+ collection: {
+ labelPlaylist: "Playlist",
+ labelFavorites: "Coleção",
+ labelHistory: "Histórico",
+ notFoundTitle: "Playlist não encontrada",
+ notFoundBody: "Ela pode ter sido excluída.",
+ goToLibrary: "Ir para a Biblioteca",
+ shuffle: "Tocar em ordem aleatória",
+ more: "Mais opções da playlist",
+ emptyHistory: "Nada tocado ainda",
+ empty: "Ainda vazia",
+ emptyFavoritesBody: "Toque no coração de qualquer faixa para guardá-la aqui.",
+ emptyHistoryBody: "As músicas que você ouvir aparecem aqui.",
+ emptyPlaylistBody: 'Busque músicas e use "Adicionar à playlist" no menu de cada faixa.',
+ rename: "Renomear",
+ renameTitle: "Renomear playlist",
+ save: "Salvar",
+ deletePlaylist: "Excluir playlist",
+ deleteTitle: "Excluir playlist?",
+ deleteBody: (name, tracks) => `"${name}" e a lista de ${count(tracks, "faixa", "faixas")} serão apagadas. Isso não pode ser desfeito.`,
+ delete: "Excluir",
+ },
+
+ dialogs: {
+ addToPlaylist: "Adicionar à playlist",
+ addManyToPlaylist: (n) => `Adicionar ${n} faixas à playlist`,
+ newPlaylistName: "Nome da nova playlist",
+ name: "Nome",
+ namePlaceholder: "Ex.: Treino, Foco, Estrada",
+ createAndAdd: "Criar e adicionar",
+ shortcutsTitle: "Atalhos de teclado",
+ space: "Espaço",
+ shortcuts: {
+ playPause: "Tocar / pausar",
+ seek: "Voltar / avançar 5 s",
+ skip: "Faixa anterior / próxima",
+ volume: "Volume",
+ mute: "Mudo",
+ favorite: "Favoritar faixa atual",
+ shuffle: "Ordem aleatória",
+ repeat: "Repetir",
+ video: "Alternar vídeo",
+ theater: "Maximizar vídeo",
+ queue: "Fila",
+ search: "Buscar",
+ help: "Esta lista",
+ },
+ },
+
+ player: {
+ repeatOff: "Repetir: desligado",
+ repeatAll: "Repetir: fila",
+ repeatOne: "Repetir: faixa",
+ shuffleOn: "Ordem aleatória: ligada",
+ shuffleOff: "Ordem aleatória: desligada",
+ previous: "Anterior",
+ next: "Próxima",
+ progress: "Progresso",
+ mute: "Mudo",
+ unmute: "Ativar som",
+ volume: "Volume",
+ mode: "Modo de reprodução",
+ audio: "Áudio",
+ video: "Vídeo",
+ watchClip: "Ver o clipe",
+ toHd: "Mudar para HD (720p, baixa antes de tocar)",
+ toSd: "Mudar para SD (360p, começa mais rápido quando disponível)",
+ nothingPlaying: "Nada tocando. Busque algo para começar.",
+ showNowPlaying: "Mostrar Tocando agora",
+ queue: "Fila",
+ nowPlayingPanel: "Painel Tocando agora",
+ shortcuts: "Atalhos de teclado (?)",
+ openNowPlaying: (title) => `Abrir Tocando agora: ${title}`,
+ status: {
+ findingClip: "Procurando o clipe",
+ preparingHd: "Preparando vídeo HD",
+ loadingVideo: "Carregando vídeo",
+ fetchingRadio: "Buscando rádio",
+ },
+ noClip: "Esta música não tem clipe no YouTube",
+ radioContinuing: (title) => `Continuando com o rádio de "${title}"`,
+ playsNext: (title) => `"${title}" toca a seguir`,
+ addedToQueue: (title) => `"${title}" adicionada à fila`,
+ startingRadio: (title) => `Montando rádio de "${title}"`,
+ cantPlay: (title, reason) => `Não foi possível tocar "${title}". ${reason}`,
+ aTrack: "esta faixa",
+ browserCantPlay: "O navegador não conseguiu reproduzir este formato.",
+ serverDown: "Servidor do Musike inacessível. Ele está rodando?",
+ httpError: (status) => `Erro ${status}`,
+ },
+
+ nowPlaying: {
+ title: "Tocando agora",
+ coverOf: (title) => `Capa de ${title}`,
+ playSomething: "Toque algo para ver aqui.",
+ startRadio: "Iniciar rádio desta faixa",
+ upNext: "A seguir",
+ tabPlaying: "Tocando",
+ tabQueue: "Fila",
+ panel: "Tocando agora e fila",
+ closePanel: "Fechar painel",
+ backToPlayer: "Voltar ao player",
+ showQueue: "Ver fila",
+ },
+
+ queue: {
+ emptyTitle: "A fila está vazia",
+ emptyBody: 'Toque uma música ou use "Adicionar à fila" no menu de qualquer faixa.',
+ removeX: (title) => `Remover ${title} da fila`,
+ remove: "Remover da fila",
+ nowPlaying: "Tocando agora",
+ upNext: "A seguir",
+ clear: "Limpar",
+ nothingQueued: "Nada na fila.",
+ radioContinues: "O rádio continua quando acabar.",
+ autoRadio: "Rádio automático",
+ autoRadioBody: "Continua com músicas parecidas quando a fila acabar",
+ },
+
+ video: {
+ maximize: "Maximizar vídeo",
+ maximizeKey: "Maximizar (F)",
+ label: (title) => `Vídeo: ${title}`,
+ fullscreen: "Tela cheia",
+ exitFullscreen: "Sair da tela cheia",
+ close: "Fechar vídeo (Esc)",
+ },
+
+ trackMenu: {
+ actionsFor: (title) => `Ações para ${title}`,
+ playNow: "Tocar agora",
+ playNext: "Tocar a seguir",
+ addToQueue: "Adicionar à fila",
+ startRadio: "Iniciar rádio",
+ addToPlaylist: "Adicionar à playlist",
+ removeFromPlaylist: "Remover desta playlist",
+ openYoutube: "Abrir no YouTube",
+ },
+
+ trackList: {
+ moreFor: (title) => `Mais opções para ${title}`,
+ more: "Mais opções",
+ title: "Título",
+ album: "Álbum",
+ duration: "Duração",
+ },
+
+ search: {
+ title: "Buscar",
+ inputLabel: "Buscar músicas, artistas, vídeos ou colar um link do YouTube",
+ placeholder: "Músicas, artistas ou link do YouTube",
+ clear: "Limpar busca",
+ searchSeparately: (n) => `Buscar ${n} músicas separadamente`,
+ resultType: "Tipo de resultado",
+ songs: "Músicas",
+ videos: "Vídeos",
+ genres: "Gêneros",
+ list: "Buscar lista",
+ youtubeLink: "Link do YouTube",
+ linkError: "Não foi possível abrir esse link. Confira se o vídeo é público.",
+ failed: "A busca falhou",
+ nothingFound: "Nada encontrado",
+ nothingFoundBody: (query, otherTab) => `Nenhum resultado para "${query}". Tente outro termo ou a aba ${otherTab}.`,
+ recent: "Buscas recentes",
+ clearRecent: "Limpar",
+ idleTitle: "O que vai tocar hoje?",
+ idleBody:
+ "Busque por música, artista ou álbum. Para clipes e ao vivo, use a aba Vídeos. Também dá para colar um link do YouTube.",
+ exploreGenres: "Explorar por gênero",
+ },
+
+ batch: {
+ title: "Buscar lista",
+ simple: "Busca simples",
+ label: 'Escreva as músicas separadas por vírgula (ou uma por linha). Dá para incluir o artista: "Evidências Chitãozinho".',
+ placeholder: "Ex.: Evidências, Trem-Bala, Garota de Ipanema",
+ max: (n) => `Máximo de ${n} por vez`,
+ searchN: (n) => `Buscar ${n} músicas`,
+ search: "Buscar",
+ searching: (done, total) => `Buscando… ${done}/${total}`,
+ searched: (query) => ` · buscou "${query}"`,
+ swap: "Trocar por outro resultado",
+ swapShort: "Trocar",
+ notFound: "Nada encontrado",
+ failed: "A busca falhou",
+ emptyTitle: "Várias músicas de uma vez",
+ emptyBody:
+ "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.",
+ },
+
+ selection: {
+ select: (title) => `Selecionar ${title}`,
+ selectAll: "Selecionar todas",
+ all: "Todas",
+ countShort: (n, total) => `${n} de ${total}`,
+ count: (n, total) => `${n} de ${count(total, "música", "músicas")}`,
+ },
+
+ genre: {
+ fallbackName: "Gênero",
+ viewBy: "Ver por",
+ artistsTab: "Bandas e artistas",
+ artistsShort: "Artistas",
+ songsTab: "Todas as músicas",
+ songsShort: "Músicas",
+ openFailed: "Não deu para abrir este gênero",
+ pickArtist: "Escolha uma banda ou artista para ver os maiores sucessos.",
+ loadMore: "Carregar mais",
+ loadingMore: "Procurando mais artistas…",
+ endOfList: (n) => `Fim da lista: ${count(n, "artista", "artistas")}`,
+ noArtists: "Nenhum artista listado",
+ noArtistsBody: "Este gênero só tem playlists. Veja todas as músicas na outra aba.",
+ noSongs: "Nenhuma música listada",
+ noSongsBody: "Tente outro gênero.",
+ },
+
+ artist: {
+ fallbackName: "Artista",
+ label: "Artista",
+ hits: "Maiores sucessos",
+ openFailed: "Não deu para abrir este artista",
+ noHits: "Nenhuma música encontrada",
+ noHitsBody: "O YouTube Music não lista sucessos para este artista.",
+ },
+
+ settings: {
+ title: "Ajustes",
+ appearance: "Aparência",
+ theme: "Tema",
+ dark: "Escuro",
+ light: "Claro",
+ language: "Idioma",
+ engine: "Motor do YouTube",
+ checking: "verificando",
+ noVersion: "sem versão",
+ stable: "estável",
+ nightly: "nightly",
+ chipMissing: "Não encontrado",
+ chipUpdate: "Atualização disponível",
+ chipOk: "Atualizado",
+ engineBody: "É quem busca o áudio e o vídeo no YouTube. O YouTube muda com frequência: se as músicas pararem de tocar, atualize aqui.",
+ channel: "Canal de atualização",
+ stableOption: "Estável",
+ nightlyOption: "Nightly",
+ nightlyBody: "Recebe correções no mesmo dia em que o YouTube muda.",
+ stableBody: "Versões testadas, lançadas a cada poucas semanas.",
+ latest: (version) => ` Última: ${version}`,
+ installing: "Instalando",
+ updating: "Atualizando",
+ install: "Instalar yt-dlp",
+ toNightly: "Mudar para Nightly",
+ toStable: "Voltar para Estável",
+ updateTo: (version) => `Atualizar para ${version}`,
+ check: "Verificar e atualizar",
+ noWinget: "O winget não está disponível. Instale o yt-dlp manualmente e reinicie o Musike.",
+ starting: "Iniciando",
+ denoRole: "Resolve os desafios do YouTube",
+ ffmpegRole: "Junta vídeo e áudio no modo HD",
+ depMissingBefore: "Não encontrado. No terminal:",
+ depMissingAfter: "e reinicie o Musike.",
+ },
+
+ backup: {
+ yourData: "Seus dados",
+ body: "Leve playlists, favoritas e histórico para outro computador ou para o app desktop: exporte um arquivo aqui e importe na outra instância do Musike.",
+ export: "Exportar",
+ exporting: "Exportando",
+ import: "Importar",
+ importing: "Importando",
+ pickFile: "Escolher arquivo de backup do Musike",
+ created: (playlists, favorites) =>
+ `Backup criado: ${count(playlists, "playlist", "playlists")} e ${count(favorites, "favorita", "favoritas")}`,
+ exportedAt: (date, time) => `Exportado em ${date} às ${time}`,
+ playlistsWord: (n) => (n === 1 ? "playlist" : "playlists"),
+ favoritesWord: (n) => (n === 1 ? "favorita" : "favoritas"),
+ tracksIn: (n) => count(n, "faixa", "faixas"),
+ inHistory: "no histórico",
+ howToImport: "Como importar",
+ mergeTitle: "Juntar com a minha biblioteca",
+ mergeBody: "Adiciona o que falta. Nada é apagado; playlists com o mesmo nome ganham as faixas novas.",
+ replaceTitle: "Substituir tudo",
+ replaceBody: "Apaga a biblioteca atual e deixa exatamente como no backup.",
+ applySettings: "Aplicar também tema, idioma e preferências do player",
+ confirmReplace: 'Isso apaga suas playlists, favoritas e histórico atuais. Toque em "Substituir agora" para confirmar.',
+ replace: "Substituir",
+ replaceNow: "Substituir agora",
+ imported: (parts) => `Importado: ${parts.join(", ")}`,
+ nothingNew: "Nada novo: sua biblioteca já tinha tudo deste backup",
+ newPlaylists: (n) => count(n, "playlist nova", "playlists novas"),
+ updatedPlaylists: (n) => count(n, "playlist atualizada", "playlists atualizadas"),
+ addedTracks: (n) => count(n, "faixa adicionada", "faixas adicionadas"),
+ addedFavorites: (n) => count(n, "favorita", "favoritas"),
+ unreadable: "Não foi possível ler o arquivo. Ele precisa ser um backup .musike.json.",
+ notBackup: "Este arquivo não é um backup do Musike.",
+ newer: "Backup feito por uma versão mais nova do Musike. Atualize o app para importar.",
+ },
+
+ toasts: {
+ dismiss: (message) => `${message}. Fechar aviso`,
+ addedFavorite: "Adicionada às Favoritas",
+ removedFavorite: "Removida das Favoritas",
+ allAlreadyFavorites: "Já estavam todas nas Favoritas",
+ addedFavorites: (n) => `${n} faixas adicionadas às Favoritas`,
+ playlistCreated: (name) => `Playlist "${name}" criada`,
+ playlistDeleted: "Playlist excluída",
+ addedTo: (name) => `Adicionada a "${name}"`,
+ addedManyTo: (n, name) => `${n} faixas adicionadas a "${name}"`,
+ allAlreadyIn: (name) => `Já estavam todas em "${name}"`,
+ ytdlpMissing: "O yt-dlp não foi encontrado. Sem ele nenhuma música toca.",
+ ytdlpUpdate: (version) => `Nova versão do yt-dlp disponível (${version})`,
+ },
+};
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 416ef7c..81b7230 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1,3 +1,4 @@
+import { getLang, getT } from "../i18n";
import type { ArtistPage, Genre, GenreArtist, GenrePage, Library, Playlist, Track } from "./types";
export type ErrorCode = "tool_missing" | "maybe_outdated" | "bot_check";
@@ -43,16 +44,23 @@ export interface SystemInfo {
job: SystemJob | null;
}
+/** The server answers errors (and YouTube Music answers names, like genres) in the app's language. */
+const LANG_HEADER = "x-musike-lang";
+
async function request<T>(path: string, init?: RequestInit & { json?: unknown }): Promise<T> {
const { json, ...rest } = init ?? {};
const res = await fetch(path, {
...rest,
- headers: json !== undefined ? { "content-type": "application/json", ...rest.headers } : rest.headers,
+ headers: {
+ [LANG_HEADER]: getLang(),
+ ...(json !== undefined ? { "content-type": "application/json" } : {}),
+ ...(rest.headers as Record<string, string> | undefined),
+ },
body: json !== undefined ? JSON.stringify(json) : rest.body,
});
if (res.status === 204) return undefined as T;
const body = await res.json().catch(() => ({}));
- if (!res.ok) throw new ApiError(res.status, body.error ?? `Erro ${res.status}`, body.code);
+ if (!res.ok) throw new ApiError(res.status, body.error ?? getT().player.httpError(res.status), body.code);
return body as T;
}
@@ -104,12 +112,13 @@ export const streamUrl = (id: string, kind: "audio" | "video", quality: "sd" | "
/** Media elements hide the HTTP error body; fetch it to show the real reason. */
export async function explainStreamError(url: string): Promise<{ message: string; code?: ErrorCode }> {
+ const t = getT();
try {
- const res = await fetch(url, { headers: { Range: "bytes=0-0" } });
- if (res.ok) return { message: "O navegador não conseguiu reproduzir este formato." };
+ const res = await fetch(url, { headers: { Range: "bytes=0-0", [LANG_HEADER]: getLang() } });
+ if (res.ok) return { message: t.player.browserCantPlay };
const body = await res.json().catch(() => ({}));
- return { message: body.error ?? `Erro ${res.status}`, code: body.code };
+ return { message: body.error ?? t.player.httpError(res.status), code: body.code };
} catch {
- return { message: "Servidor do Musike inacessível. Ele está rodando?" };
+ return { message: t.player.serverDown };
}
}
diff --git a/web/src/lib/backup.ts b/web/src/lib/backup.ts
index 995e898..b67a8b0 100644
--- a/web/src/lib/backup.ts
+++ b/web/src/lib/backup.ts
@@ -1,3 +1,4 @@
+import { getLang, getT, isLang, useI18n } from "../i18n";
import { usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
import { useUi } from "../stores/ui";
@@ -16,6 +17,7 @@ export interface Backup {
library: Library;
settings?: {
theme?: "dark" | "light";
+ lang?: string;
preferVideo?: boolean;
quality?: "sd" | "hd";
autoRadio?: boolean;
@@ -34,6 +36,7 @@ export async function createBackup(): Promise<Backup> {
library: { favorites: library.favorites, playlists: library.playlists, history: library.history },
settings: {
theme: useUi.getState().theme,
+ lang: getLang(),
preferVideo: p.preferVideo,
quality: p.quality,
autoRadio: p.autoRadio,
@@ -60,11 +63,11 @@ export async function readBackup(file: File): Promise<Backup> {
try {
data = JSON.parse(await file.text()) as Partial<Backup>;
} catch {
- throw new Error("Não foi possível ler o arquivo. Ele precisa ser um backup .musike.json.");
+ throw new Error(getT().backup.unreadable);
}
- if (data?.format !== "musike-backup" || !data.library) throw new Error("Este arquivo não é um backup do Musike.");
+ if (data?.format !== "musike-backup" || !data.library) throw new Error(getT().backup.notBackup);
if (typeof data.version !== "number" || data.version > 1) {
- throw new Error("Backup feito por uma versão mais nova do Musike. Atualize o app para importar.");
+ throw new Error(getT().backup.newer);
}
return data as Backup;
}
@@ -87,6 +90,7 @@ export async function restoreBackup(backup: Backup, mode: "merge" | "replace", a
if (applySettings && s) {
const player = usePlayer.getState();
if (s.theme === "dark" || s.theme === "light") useUi.getState().setTheme(s.theme);
+ if (isLang(s.lang)) useI18n.getState().setLang(s.lang);
if (typeof s.autoRadio === "boolean") player.setAutoRadio(s.autoRadio);
if (typeof s.volume === "number") player.setVolume(s.volume);
if (s.quality === "sd" || s.quality === "hd") player.setQuality(s.quality);
diff --git a/web/src/lib/desktop.ts b/web/src/lib/desktop.ts
index 8d20060..c3c41d3 100644
--- a/web/src/lib/desktop.ts
+++ b/web/src/lib/desktop.ts
@@ -2,6 +2,8 @@
interface DesktopBridge {
platform: string;
setTheme: (theme: "dark" | "light") => void;
+ /** Missing in desktop builds older than 1.2. */
+ setLanguage?: (lang: string) => void;
}
export const desktop = (window as Window & { musikeDesktop?: DesktopBridge }).musikeDesktop;
diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts
index f03b97c..bae63a2 100644
--- a/web/src/lib/format.ts
+++ b/web/src/lib/format.ts
@@ -7,23 +7,7 @@ export function formatTime(seconds: number): string {
return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
}
-export function formatTotal(seconds: number): string {
- const m = Math.round(seconds / 60);
- if (m < 60) return `${m} min`;
- return `${Math.floor(m / 60)} h ${m % 60} min`;
-}
-
-export function plural(n: number, one: string, many: string): string {
- return `${n} ${n === 1 ? one : many}`;
-}
-
-export function greeting(date = new Date()): string {
- const h = date.getHours();
- if (h < 5) return "Boa madrugada";
- if (h < 12) return "Bom dia";
- if (h < 18) return "Boa tarde";
- return "Boa noite";
-}
+// Words (plurals, greetings, totals) live in the language files under src/i18n.
export const cn = (...parts: (string | false | null | undefined)[]) => parts.filter(Boolean).join(" ");
diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.ts
new file mode 100644
index 0000000..e07d5aa
--- /dev/null
+++ b/web/src/lib/routes.ts
@@ -0,0 +1,49 @@
+/** Every page's address, in one place. */
+export const paths = {
+ home: "/",
+ search: "/search",
+ searchList: "/search/list",
+ genre: (id: string) => `/search/genre/${encodeURIComponent(id)}`,
+ artist: (id: string) => `/search/artist/${id}`,
+ library: "/library",
+ favorites: "/favorites",
+ history: "/history",
+ playlist: (id: string) => `/playlist/${id}`,
+};
+
+/** Hash that opens the full-screen Now Playing sheet on phones (so Back closes it). */
+export const NOW_PLAYING_HASH = "now-playing";
+
+// Musike 1.1 and earlier used Portuguese addresses; bookmarks and installed shortcuts may still point there.
+const LEGACY_PATHS: [string, string][] = [
+ ["/buscar/lista", paths.searchList],
+ ["/buscar/genero/", "/search/genre/"],
+ ["/buscar/artista/", "/search/artist/"],
+ ["/buscar", paths.search],
+ ["/biblioteca", paths.library],
+ ["/favoritas", paths.favorites],
+ ["/historico", paths.history],
+];
+
+/** The current address for an old one, or null when it is already current. */
+export function legacyRedirect(pathname: string, search: string, hash: string): string | null {
+ let path = pathname;
+ for (const [from, to] of LEGACY_PATHS) {
+ if (pathname === from || pathname.startsWith(from.endsWith("/") ? from : `${from}/`)) {
+ path = to + pathname.slice(from.length);
+ break;
+ }
+ }
+ let query = search;
+ const params = new URLSearchParams(search);
+ if (params.has("tipo") || params.has("ver")) {
+ if (params.get("tipo") === "videos") params.set("type", "videos");
+ if (params.get("ver") === "musicas") params.set("view", "songs");
+ params.delete("tipo");
+ params.delete("ver");
+ query = params.toString() ? `?${params}` : "";
+ }
+ const fragment = hash === "#tocando" ? `#${NOW_PLAYING_HASH}` : hash;
+ const next = path + query + fragment;
+ return next === pathname + search + hash ? null : next;
+}
diff --git a/web/src/player/player.ts b/web/src/player/player.ts
index 7742cec..efd4474 100644
--- a/web/src/player/player.ts
+++ b/web/src/player/player.ts
@@ -1,4 +1,5 @@
import { create } from "zustand";
+import { getT, useT } from "../i18n";
import { api, explainStreamError, streamUrl } from "../lib/api";
import { shuffled } from "../lib/format";
import type { Track } from "../lib/types";
@@ -7,6 +8,8 @@ import { openSettings } from "../stores/system";
import { toast } from "../stores/ui";
export type Repeat = "off" | "all" | "one";
+/** A code translated where it is shown (so switching languages updates it), or a server error already in the right language. */
+export type StatusNote = "findingClip" | "preparingHd" | "loadingVideo" | "fetchingRadio" | { error: string };
export type Status = "idle" | "loading" | "playing" | "paused" | "error";
type Kind = "audio" | "video";
type Quality = "sd" | "hd";
@@ -17,11 +20,12 @@ interface PlayerState {
original: Track[] | null;
index: number;
status: Status;
- statusText: string | null;
+ /** What playback is busy with (or why it failed), shown instead of the artist. See `useStatusText`. */
+ statusText: StatusNote | null;
/** Which media element is driving playback right now. */
mediaKind: Kind;
/** Set when Video mode is on but the current song has no music video on YouTube. */
- videoNote: string | null;
+ videoNote: "noClip" | null;
/** Intrinsic width/height of the current video, so vertical videos get a vertical stage. */
videoAspect: number;
position: number;
@@ -105,7 +109,6 @@ const saved = readSaved();
*/
const clipFor = new Map<string, string | null>();
const clipLookups = new Map<string, Promise<string | null>>();
-const NO_CLIP = "Esta música não tem clipe no YouTube";
function lookupClip(track: Track): Promise<string | null> {
if (track.kind === "video") return Promise.resolve(track.id);
@@ -138,7 +141,7 @@ export const usePlayer = create<PlayerState>((set, get) => {
const mediaIdFor = (track: Track, kind: Kind) =>
kind === "video" && track.kind !== "video" ? clipFor.get(track.id)! : track.id;
const noteFor = (track: Track) =>
- get().preferVideo && track.kind === "song" && clipFor.get(track.id) === null ? NO_CLIP : null;
+ get().preferVideo && track.kind === "song" && clipFor.get(track.id) === null ? ("noClip" as const) : null;
const activeMedia = (): HTMLMediaElement | null => (loaded ? mediaFor(loaded.kind) : null);
function play(media: HTMLMediaElement) {
@@ -159,7 +162,7 @@ export const usePlayer = create<PlayerState>((set, get) => {
set({
index,
status: "loading",
- statusText: "Procurando o clipe",
+ statusText: "findingClip",
videoNote: null,
position: opts.startAt ?? 0,
duration: track.duration,
@@ -189,7 +192,7 @@ export const usePlayer = create<PlayerState>((set, get) => {
mediaKind: kind,
status: autoplay ? "loading" : "paused",
// Video may need a server-side download first (HD, or videos without a combined SD stream).
- statusText: kind === "video" ? (s.quality === "hd" ? "Preparando vídeo HD" : "Carregando vídeo") : null,
+ statusText: kind === "video" ? (s.quality === "hd" ? "preparingHd" : "loadingVideo") : null,
videoNote: noteFor(track),
position: pendingSeek,
duration: track.duration,
@@ -206,16 +209,16 @@ export const usePlayer = create<PlayerState>((set, get) => {
const s = get();
const last = s.queue[s.index];
if (!last) return;
- set({ status: "loading", statusText: "Buscando rádio" });
+ set({ status: "loading", statusText: "fetchingRadio" });
try {
const known = new Set(get().queue.map((t) => t.id));
const more = (await api.radio(last.id)).filter((t) => !known.has(t.id)).slice(0, 25);
- if (!more.length) throw new Error("vazio");
+ if (!more.length) throw new Error("empty");
set((st) => ({
queue: [...st.queue, ...more],
original: st.original ? [...st.original, ...more] : null,
}));
- toast(`Continuando com o rádio de "${last.title}"`);
+ toast(getT().player.radioContinuing(last.title));
load(get().index + 1);
} catch {
set({ status: "paused", statusText: null, position: 0 });
@@ -257,14 +260,15 @@ export const usePlayer = create<PlayerState>((set, get) => {
set({ status: "error" });
explainStreamError(url).then(({ message, code }) => {
if (mine !== token) return;
- set({ statusText: message });
+ set({ statusText: { error: message } });
const track = get().queue[get().index];
// Tool problems hit every track: offer the fix instead of skipping through the whole queue.
const toolProblem = code === "tool_missing" || code === "maybe_outdated";
+ const t = getT();
toast(
- `Não foi possível tocar "${track?.title ?? "faixa"}". ${message}`,
+ t.player.cantPlay(track?.title ?? t.player.aTrack, message),
"error",
- toolProblem ? { label: code === "tool_missing" ? "Instalar" : "Atualizar", run: openSettings } : undefined,
+ toolProblem ? { label: code === "tool_missing" ? t.common.install : t.common.update, run: openSettings } : undefined,
);
if (code !== "tool_missing" && get().index < get().queue.length - 1) {
setTimeout(() => mine === token && get().next(), 2500);
@@ -385,14 +389,14 @@ export const usePlayer = create<PlayerState>((set, get) => {
queue: [...s.queue.slice(0, insert), track, ...s.queue.slice(insert)],
original: s.original ? [...s.original, track] : null,
});
- toast(`"${track.title}" toca a seguir`);
+ toast(getT().player.playsNext(track.title));
},
addToQueue: (track) => {
const s = get();
if (!s.queue.length) return get().playList([track]);
set({ queue: [...s.queue, track], original: s.original ? [...s.original, track] : null });
- toast(`"${track.title}" adicionada à fila`);
+ toast(getT().player.addedToQueue(track.title));
},
removeAt: (i) => {
@@ -422,7 +426,7 @@ export const usePlayer = create<PlayerState>((set, get) => {
},
startRadio: async (track) => {
- toast(`Montando rádio de "${track.title}"`);
+ toast(getT().player.startingRadio(track.title));
try {
const related = await api.radio(track.id);
get().playList([track, ...related.filter((t) => t.id !== track.id)], 0);
@@ -613,3 +617,11 @@ if ("mediaSession" in navigator) {
const restored = selectCurrent(usePlayer.getState());
if (restored) setMetadata(restored);
}
+
+/** The player's status line in the current language, or null when there is nothing to say. */
+export function useStatusText(): string | null {
+ const note = usePlayer((s) => s.statusText);
+ const t = useT();
+ if (note === null) return null;
+ return typeof note === "string" ? t.player.status[note] : note.error;
+}
diff --git a/web/src/stores/library.ts b/web/src/stores/library.ts
index 7b9f5c1..dd279ad 100644
--- a/web/src/stores/library.ts
+++ b/web/src/stores/library.ts
@@ -1,4 +1,5 @@
import { create } from "zustand";
+import { getT } from "../i18n";
import { api } from "../lib/api";
import type { Library, Playlist, Track } from "../lib/types";
import { toast } from "./ui";
@@ -45,7 +46,7 @@ export const useLibrary = create<LibraryState>((set, get) => ({
try {
const { favorites } = on ? await api.addFavorite(track) : await api.removeFavorite(track.id);
set({ favorites });
- toast(on ? "Adicionada às Favoritas" : "Removida das Favoritas");
+ toast(on ? getT().toasts.addedFavorite : getT().toasts.removedFavorite);
} catch (e) {
set({ favorites: prev });
toast((e as Error).message, "error");
@@ -55,12 +56,12 @@ 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");
+ if (!fresh.length) return toast(getT().toasts.allAlreadyFavorites);
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`);
+ toast(fresh.length === 1 ? getT().toasts.addedFavorite : getT().toasts.addedFavorites(fresh.length));
} catch (e) {
set({ favorites: prev });
toast((e as Error).message, "error");
@@ -76,7 +77,7 @@ export const useLibrary = create<LibraryState>((set, get) => ({
try {
const p = await api.createPlaylist(name, tracks);
set((s) => ({ playlists: [p, ...s.playlists] }));
- toast(`Playlist "${p.name}" criada`);
+ toast(getT().toasts.playlistCreated(p.name));
return p;
} catch (e) {
toast((e as Error).message, "error");
@@ -98,7 +99,7 @@ export const useLibrary = create<LibraryState>((set, get) => ({
set({ playlists: prev.filter((p) => p.id !== id) });
try {
await api.deletePlaylist(id);
- toast("Playlist excluída");
+ toast(getT().toasts.playlistDeleted);
} catch (e) {
set({ playlists: prev });
toast((e as Error).message, "error");
@@ -111,8 +112,9 @@ export const useLibrary = create<LibraryState>((set, get) => ({
const p = await api.addToPlaylist(id, tracks);
set((s) => ({ playlists: replacePlaylist(s.playlists, p) }));
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}"`);
+ const t = getT();
+ if (!Array.isArray(tracks) || added === 1) toast(t.toasts.addedTo(p.name));
+ else toast(added ? t.toasts.addedManyTo(added, p.name) : t.toasts.allAlreadyIn(p.name));
} catch (e) {
toast((e as Error).message, "error");
}
diff --git a/web/src/views/Artist.tsx b/web/src/views/Artist.tsx
index 274a992..0eb1de7 100644
--- a/web/src/views/Artist.tsx
+++ b/web/src/views/Artist.tsx
@@ -6,7 +6,9 @@ import { BackButton, EmptyState, PageHeader } from "../components/Page";
import { SelectableTrackList } from "../components/Selection";
import { TrackListSkeleton } from "../components/TrackList";
import { useRemote } from "../hooks/useRemote";
+import { useI18n, useT } from "../i18n";
import { api } from "../lib/api";
+import { paths } from "../lib/routes";
import { cn } from "../lib/format";
import type { ArtistPage } from "../lib/types";
@@ -14,13 +16,16 @@ import type { ArtistPage } from "../lib/types";
export default function Artist() {
const { id = "" } = useParams();
const location = useLocation();
- const page = useRemote<ArtistPage>(`artist:${id}`, (signal) => api.artist(id, signal));
+ const lang = useI18n((s) => s.lang);
+ const t = useT();
+ // The bio comes from YouTube Music in the app language.
+ const page = useRemote<ArtistPage>(`artist:${lang}:${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";
+ const name = (page.status === "ok" && page.data.name) || (location.state as { name?: string } | null)?.name || t.artist.fallbackName;
return (
<div className="pb-8">
- <PageHeader title={name} actions={<BackButton fallback="/buscar" />} />
+ <PageHeader title={name} actions={<BackButton fallback={paths.search} />} />
<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 && (
@@ -31,7 +36,7 @@ export default function Artist() {
{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>
+ <span className="text-xs font-medium text-white/75">{t.artist.label}</span>
<h1 className="text-[28px] leading-[1.1] font-bold tracking-tight break-words text-white md:text-5xl">{name}</h1>
</div>
</div>
@@ -47,14 +52,14 @@ export default function Artist() {
</button>
)}
- <h2 className="px-4 pt-6 pb-1 text-xl font-semibold tracking-tight md:px-6">Maiores sucessos</h2>
+ <h2 className="px-4 pt-6 pb-1 text-xl font-semibold tracking-tight md:px-6">{t.artist.hits}</h2>
{page.status === "loading" && <TrackListSkeleton />}
{page.status === "error" && (
<EmptyState
icon={<WarningCircleIcon size={28} />}
- title="Não deu para abrir este artista"
+ title={t.artist.openFailed}
body={page.message}
action={
<button
@@ -62,7 +67,7 @@ export default function Artist() {
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
+ {t.common.retry}
</button>
}
/>
@@ -72,7 +77,7 @@ export default function Artist() {
(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." />
+ <EmptyState icon={<MusicNotesIcon size={28} />} title={t.artist.noHits} body={t.artist.noHitsBody} />
))}
</div>
);
diff --git a/web/src/views/BatchSearch.tsx b/web/src/views/BatchSearch.tsx
index 142cecc..10b3eb1 100644
--- a/web/src/views/BatchSearch.tsx
+++ b/web/src/views/BatchSearch.tsx
@@ -6,7 +6,9 @@ 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 { useT } from "../i18n";
+import { cn } from "../lib/format";
+import { paths } from "../lib/routes";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
@@ -100,6 +102,7 @@ export default function BatchSearch() {
const location = useLocation();
const navigate = useNavigate();
const input = useRef<HTMLTextAreaElement>(null);
+ const t = useT();
const terms = parseList(text);
const chosen = pickedTracks(entries, true);
@@ -125,13 +128,13 @@ export default function BatchSearch() {
return (
<div className="pb-8">
<PageHeader
- title="Buscar lista"
+ title={t.batch.title}
actions={
<Link
- to="/buscar"
+ to={paths.search}
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
+ <ArrowLeftIcon size={16} /> {t.batch.simple}
</Link>
}
/>
@@ -144,7 +147,7 @@ export default function BatchSearch() {
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".
+ {t.batch.label}
</label>
<textarea
id="batch-input"
@@ -159,19 +162,19 @@ export default function BatchSearch() {
submit();
}
}}
- placeholder="Ex.: Evidências, Trem-Bala, Garota de Ipanema"
+ placeholder={t.batch.placeholder}
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") : ""}
+ {terms.length === MAX_TERMS ? t.batch.max(MAX_TERMS) : terms.length ? t.common.songs(terms.length) : ""}
</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"}
+ {terms.length > 1 ? t.batch.searchN(terms.length) : t.batch.search}
</button>
</div>
</form>
@@ -184,7 +187,7 @@ export default function BatchSearch() {
all={found}
allSelected={allSelected}
onToggleAll={() => selectAll(!allSelected)}
- label={pending ? `Buscando… ${found.length}/${entries.length}` : <SelectedCount n={chosen.length} total={entries.length} />}
+ label={pending ? t.batch.searching(found.length, entries.length) : <SelectedCount n={chosen.length} total={entries.length} />}
/>
<ul className="mt-2 flex flex-col px-2 md:px-3">
@@ -198,8 +201,8 @@ export default function BatchSearch() {
{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."
+ title={t.batch.emptyTitle}
+ body={t.batch.emptyBody}
/>
)}
</div>
@@ -212,6 +215,7 @@ function EntryRow({ entry, index }: { entry: Entry; index: number }) {
const playTrack = usePlayer((s) => s.playTrack);
const [open, setOpen] = useState(false);
const track = entry.options[entry.pick];
+ const t = useT();
if (entry.status === "loading") {
return (
@@ -235,14 +239,14 @@ function EntryRow({ entry, index }: { entry: Entry; index: number }) {
</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 className="block text-[13px] text-fg-2">{entry.status === "empty" ? t.batch.notFound : t.batch.failed}</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
+ {t.common.retry}
</button>
</li>
);
@@ -255,18 +259,18 @@ function EntryRow({ entry, index }: { entry: Entry; index: number }) {
selected={entry.selected}
onToggle={() => update(index, { selected: !entry.selected })}
onPlay={() => playTrack(track)}
- note={<span className="text-fg-3"> · buscou "{entry.query}"</span>}
+ note={<span className="text-fg-3">{t.batch.searched(entry.query)}</span>}
trailing={
entry.options.length > 1 && (
<button
type="button"
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
- title="Trocar por outro resultado"
+ title={t.batch.swap}
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>
+ <span className="hidden sm:inline">{t.batch.swapShort}</span>
<CaretDownIcon size={12} className={cn("transition-transform", open && "rotate-180")} />
</button>
)
@@ -289,7 +293,7 @@ function EntryRow({ entry, index }: { entry: Entry; index: number }) {
<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"}
+ {[opt.artist, opt.album].filter(Boolean).join(" · ") || t.common.youtube}
</span>
</span>
{j === entry.pick && <CheckIcon size={16} className="text-accent-text" />}
diff --git a/web/src/views/Collection.tsx b/web/src/views/Collection.tsx
index 56de283..01654d5 100644
--- a/web/src/views/Collection.tsx
+++ b/web/src/views/Collection.tsx
@@ -7,7 +7,9 @@ import { IconButton, PlayDisc } from "../components/IconButton";
import { Modal } from "../components/Modal";
import { EmptyState, PageHeader } from "../components/Page";
import { TrackList } from "../components/TrackList";
-import { formatTotal, plural, shuffled } from "../lib/format";
+import { useT } from "../i18n";
+import { shuffled } from "../lib/format";
+import { paths } from "../lib/routes";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
@@ -28,11 +30,13 @@ export default function Collection({ kind }: Props) {
const [renaming, setRenaming] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [moreOpen, setMoreOpen] = useState(false);
+ const t = useT();
const playlist = kind === "playlist" ? lib.playlists.find((p) => p.id === id) : undefined;
const tracks: Track[] = kind === "favorites" ? lib.favorites : kind === "history" ? lib.history : playlist?.tracks ?? [];
- const name = kind === "favorites" ? "Favoritas" : kind === "history" ? "Tocadas recentemente" : playlist?.name ?? "";
- const label = kind === "playlist" ? "Playlist" : kind === "favorites" ? "Coleção" : "Histórico";
+ const name = kind === "favorites" ? t.nav.favorites : kind === "history" ? t.nav.recentlyPlayed : playlist?.name ?? "";
+ const label =
+ kind === "playlist" ? t.collection.labelPlaylist : kind === "favorites" ? t.collection.labelFavorites : t.collection.labelHistory;
if (kind === "playlist" && !playlist) {
if (lib.status !== "ready") return <PageHeader />;
@@ -41,11 +45,11 @@ export default function Collection({ kind }: Props) {
<PageHeader />
<EmptyState
icon={<MagnifyingGlassIcon size={28} />}
- title="Playlist não encontrada"
- body="Ela pode ter sido excluída."
+ title={t.collection.notFoundTitle}
+ body={t.collection.notFoundBody}
action={
- <Link to="/biblioteca" className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm leading-[44px] font-medium">
- Ir para a Biblioteca
+ <Link to={paths.library} className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm leading-[44px] font-medium">
+ {t.collection.goToLibrary}
</Link>
}
/>
@@ -75,8 +79,8 @@ export default function Collection({ kind }: Props) {
<span className="hidden text-xs font-medium text-fg-2 md:block">{label}</span>
<h1 className="max-w-full text-[28px] leading-[1.1] font-bold tracking-tight break-words md:text-5xl lg:text-6xl">{name}</h1>
<p className="font-mono text-[13px] text-fg-2">
- {plural(tracks.length, "faixa", "faixas")}
- {total > 0 && <> · {formatTotal(total)}</>}
+ {t.common.tracks(tracks.length)}
+ {total > 0 && <> · {t.time.total(total)}</>}
</p>
</div>
</div>
@@ -84,7 +88,7 @@ export default function Collection({ kind }: Props) {
<div className="flex items-center gap-2 px-4 pb-4 md:px-6">
<PlayDisc
- label={playing ? "Pausar" : `Tocar ${name}`}
+ label={playing ? t.common.pause : t.common.playX(name)}
px={56}
disabled={!tracks.length}
onClick={() => (isThisPlaying ? toggle() : playList(tracks, 0))}
@@ -92,7 +96,7 @@ export default function Collection({ kind }: Props) {
{playing ? <PauseIcon size={24} weight="fill" /> : <PlayIcon size={24} weight="fill" />}
</PlayDisc>
<IconButton
- label="Tocar em ordem aleatória"
+ label={t.collection.shuffle}
size="lg"
disabled={!tracks.length}
onClick={() => {
@@ -103,7 +107,7 @@ export default function Collection({ kind }: Props) {
<ShuffleIcon size={24} />
</IconButton>
{kind === "playlist" && (
- <IconButton label="Mais opções da playlist" size="lg" onClick={() => setMoreOpen(true)}>
+ <IconButton label={t.collection.more} size="lg" onClick={() => setMoreOpen(true)}>
<DotsThreeIcon size={26} weight="bold" />
</IconButton>
)}
@@ -115,17 +119,17 @@ export default function Collection({ kind }: Props) {
) : (
<EmptyState
icon={<MagnifyingGlassIcon size={28} />}
- title={kind === "history" ? "Nada tocado ainda" : "Ainda vazia"}
+ title={kind === "history" ? t.collection.emptyHistory : t.collection.empty}
body={
kind === "favorites"
- ? "Toque no coração de qualquer faixa para guardá-la aqui."
+ ? t.collection.emptyFavoritesBody
: kind === "history"
- ? "As músicas que você ouvir aparecem aqui."
- : 'Busque músicas e use "Adicionar à playlist" no menu de cada faixa.'
+ ? t.collection.emptyHistoryBody
+ : t.collection.emptyPlaylistBody
}
action={
- <Link to="/buscar" className="mt-2 h-11 rounded-full bg-accent px-6 text-sm leading-[44px] font-semibold text-accent-ink">
- Buscar música
+ <Link to={paths.search} className="mt-2 h-11 rounded-full bg-accent px-6 text-sm leading-[44px] font-semibold text-accent-ink">
+ {t.common.searchMusic}
</Link>
}
/>
@@ -144,7 +148,7 @@ export default function Collection({ kind }: Props) {
}}
className="flex items-center gap-3 rounded-xl px-3 py-3 text-left hover:bg-surface-3"
>
- <PencilSimpleIcon size={18} className="text-fg-2" /> Renomear
+ <PencilSimpleIcon size={18} className="text-fg-2" /> {t.collection.rename}
</button>
<button
type="button"
@@ -154,7 +158,7 @@ export default function Collection({ kind }: Props) {
}}
className="flex items-center gap-3 rounded-xl px-3 py-3 text-left text-danger hover:bg-surface-3"
>
- <TrashIcon size={18} /> Excluir playlist
+ <TrashIcon size={18} /> {t.collection.deletePlaylist}
</button>
</div>
</Modal>
@@ -162,8 +166,8 @@ export default function Collection({ kind }: Props) {
<NamePlaylistDialog
open={renaming}
initial={playlist.name}
- title="Renomear playlist"
- action="Salvar"
+ title={t.collection.renameTitle}
+ action={t.collection.save}
onClose={() => setRenaming(false)}
onSubmit={(n) => {
void lib.renamePlaylist(playlist.id, n);
@@ -171,24 +175,24 @@ export default function Collection({ kind }: Props) {
}}
/>
- <Modal open={confirmDelete} onClose={() => setConfirmDelete(false)} title="Excluir playlist?">
+ <Modal open={confirmDelete} onClose={() => setConfirmDelete(false)} title={t.collection.deleteTitle}>
<p className="text-sm text-fg-2">
- "{playlist.name}" e a lista de {plural(playlist.tracks.length, "faixa", "faixas")} serão apagadas. Isso não pode ser desfeito.
+ {t.collection.deleteBody(playlist.name, playlist.tracks.length)}
</p>
<div className="mt-5 flex justify-end gap-2">
<button type="button" onClick={() => setConfirmDelete(false)} className="h-11 rounded-full px-5 text-sm font-medium text-fg-2 hover:text-fg">
- Cancelar
+ {t.common.cancel}
</button>
<button
type="button"
onClick={() => {
setConfirmDelete(false);
void lib.deletePlaylist(playlist.id);
- navigate("/biblioteca");
+ navigate(paths.library);
}}
className="h-11 rounded-full bg-danger px-6 text-sm font-semibold text-white"
>
- Excluir
+ {t.collection.delete}
</button>
</div>
</Modal>
diff --git a/web/src/views/Genre.tsx b/web/src/views/Genre.tsx
index 4aa6395..4397410 100644
--- a/web/src/views/Genre.tsx
+++ b/web/src/views/Genre.tsx
@@ -7,7 +7,9 @@ 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 { useI18n, useT, type Lang } from "../i18n";
+import { cn } from "../lib/format";
+import { paths } from "../lib/routes";
import type { GenreArtist, GenrePage } from "../lib/types";
type View = "artists" | "tracks";
@@ -15,8 +17,9 @@ 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} />;
+ const lang = useI18n((s) => s.lang);
+ // Keyed, so switching genres (or languages: names and artists come from YouTube in it) starts clean.
+ return <GenreBody key={`${lang}:${id}`} id={id} lang={lang} />;
}
interface MoreArtists {
@@ -24,16 +27,18 @@ interface MoreArtists {
hasMore: boolean;
}
-// Artists added with "Carregar mais", kept per genre: coming back from an artist shows the same long list.
+// Artists added with "Load more", kept per genre and language: coming back from an artist shows the same long list.
const moreMemo = new Map<string, MoreArtists>();
-function GenreBody({ id }: { id: string }) {
+function GenreBody({ id, lang }: { id: string; lang: Lang }) {
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 view: View = params.get("view") === "songs" ? "tracks" : "artists";
+ const t = useT();
+ const page = useRemote<GenrePage>(`genre:${lang}:${id}`, (signal) => api.genre(id, signal));
+ const name = (page.status === "ok" && page.data.name) || (location.state as { name?: string } | null)?.name || t.genre.fallbackName;
+ const memoKey = `${lang}:${id}`;
+ const [more, setMore] = useState<MoreArtists | undefined>(() => moreMemo.get(memoKey));
const [loadingMore, setLoadingMore] = useState(false);
const [moreError, setMoreError] = useState("");
@@ -47,7 +52,7 @@ function GenreBody({ id }: { id: string }) {
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);
+ moreMemo.set(memoKey, merged);
setMore(merged);
} catch (e) {
setMoreError((e as Error).message);
@@ -61,7 +66,7 @@ function GenreBody({ id }: { id: string }) {
type="button"
role="tab"
aria-selected={view === v}
- onClick={() => setParams(v === "tracks" ? { ver: "musicas" } : {}, { replace: true, state: location.state })}
+ onClick={() => setParams(v === "tracks" ? { view: "songs" } : {}, { 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",
@@ -74,11 +79,11 @@ function GenreBody({ id }: { id: string }) {
return (
<div className="pb-8">
- <PageHeader title={name} actions={<BackButton fallback="/buscar" />} />
+ <PageHeader title={name} actions={<BackButton fallback={paths.search} />} />
- <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 role="tablist" aria-label={t.genre.viewBy} className="flex gap-2 px-4 pt-1 pb-4 md:px-6">
+ {tab("artists", <Short phone={t.genre.artistsShort} wide={t.genre.artistsTab} />, page.status === "ok" ? `${artists.length}${hasMore ? "+" : ""}` : undefined)}
+ {tab("tracks", <Short phone={t.genre.songsShort} wide={t.genre.songsTab} />, page.status === "ok" ? page.data.tracks.length : undefined)}
</div>
{page.status === "loading" && (view === "artists" ? <ArtistGridSkeleton /> : <TrackListSkeleton />)}
@@ -86,7 +91,7 @@ function GenreBody({ id }: { id: string }) {
{page.status === "error" && (
<EmptyState
icon={<WarningCircleIcon size={28} />}
- title="Não deu para abrir este gênero"
+ title={t.genre.openFailed}
body={page.message}
action={
<button
@@ -94,7 +99,7 @@ function GenreBody({ id }: { id: string }) {
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
+ {t.common.retry}
</button>
}
/>
@@ -103,11 +108,11 @@ function GenreBody({ id }: { id: string }) {
{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>
+ <p className="px-4 pb-3 text-sm text-fg-2 md:px-6">{t.genre.pickArtist}</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">
+ <Link to={paths.artist(a.id)} state={{ name: a.name }} className="group flex flex-col gap-2">
<span className="block overflow-hidden rounded-[14px]">
<Artwork
src={a.art}
@@ -134,15 +139,15 @@ function GenreBody({ id }: { id: string }) {
>
{loadingMore ? (
<>
- <CircleNotchIcon size={18} className="animate-spin" /> Procurando mais artistas…
+ <CircleNotchIcon size={18} className="animate-spin" /> {t.genre.loadingMore}
</>
) : (
- "Carregar mais"
+ t.genre.loadMore
)}
</button>
) : (
artists.length > page.data.artists.length && (
- <p className="text-sm text-fg-3">Fim da lista: {plural(artists.length, "artista", "artistas")}</p>
+ <p className="text-sm text-fg-3">{t.genre.endOfList(artists.length)}</p>
)
)}
{moreError && (
@@ -155,8 +160,8 @@ function GenreBody({ id }: { id: string }) {
) : (
<EmptyState
icon={<MusicNotesIcon size={28} />}
- title="Nenhum artista listado"
- body="Este gênero só tem playlists. Veja todas as músicas na outra aba."
+ title={t.genre.noArtists}
+ body={t.genre.noArtistsBody}
/>
)
)}
@@ -165,7 +170,7 @@ function GenreBody({ id }: { id: string }) {
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." />
+ <EmptyState icon={<MusicNotesIcon size={28} />} title={t.genre.noSongs} body={t.genre.noSongsBody} />
)
)}
</div>
@@ -173,8 +178,9 @@ function GenreBody({ id }: { id: string }) {
}
function ArtistGridSkeleton() {
+ const t = useT();
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">
+ <ul aria-label={t.common.loading} 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]" />
diff --git a/web/src/views/Home.tsx b/web/src/views/Home.tsx
index a4df775..c0684bf 100644
--- a/web/src/views/Home.tsx
+++ b/web/src/views/Home.tsx
@@ -5,13 +5,15 @@ import { Artwork } from "../components/Artwork";
import { LogoMark } from "../components/Brand";
import { PageHeader, Section } from "../components/Page";
import { TrackList, TrackListSkeleton } from "../components/TrackList";
-import { greeting } from "../lib/format";
+import { useT } from "../i18n";
+import { paths } from "../lib/routes";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
import { useLibrary } from "../stores/library";
function Shortcut({ to, label, tracks, cover }: { to: string; label: string; tracks: Track[]; cover: ReactNode }) {
const playList = usePlayer((s) => s.playList);
+ const t = useT();
return (
<div className="group relative flex h-14 items-center gap-3 overflow-hidden rounded-[12px] bg-surface-2 pr-2 transition-colors hover:bg-surface-3 md:h-16">
<Link to={to} className="absolute inset-0" aria-label={label} />
@@ -21,7 +23,7 @@ function Shortcut({ to, label, tracks, cover }: { to: string; label: string; tra
<button
type="button"
onClick={() => playList(tracks, 0)}
- aria-label={`Tocar ${label}`}
+ aria-label={t.common.playX(label)}
className="relative z-10 hidden size-10 shrink-0 place-items-center rounded-full bg-accent text-accent-ink opacity-0 shadow-[0_6px_18px_rgb(0_0_0/0.35)] transition-[opacity,transform] duration-200 ease-out-expo group-hover:opacity-100 hover:scale-105 active:scale-95 md:grid"
>
<PlayIcon size={18} weight="fill" />
@@ -52,6 +54,7 @@ export default function Home() {
const { favorites, playlists, history, status } = useLibrary();
const playList = usePlayer((s) => s.playList);
const navigate = useNavigate();
+ const t = useT();
const empty = status === "ready" && !favorites.length && !playlists.length && !history.length;
return (
@@ -59,7 +62,7 @@ export default function Home() {
<PageHeader />
<div className="px-4 pt-2 pb-6 md:px-6 md:pt-8">
- <h1 className="text-[28px] leading-tight font-semibold tracking-tight md:text-4xl">{greeting()}</h1>
+ <h1 className="text-[28px] leading-tight font-semibold tracking-tight md:text-4xl">{t.time.greeting(new Date().getHours())}</h1>
</div>
{status === "loading" && <TrackListSkeleton rows={6} />}
@@ -70,17 +73,15 @@ export default function Home() {
<LogoMark className="size-10" />
</span>
<div className="flex-1">
- <p className="text-xl font-semibold tracking-tight">Comece pela busca</p>
- <p className="mt-1 max-w-[52ch] text-sm text-fg-2">
- Procure qualquer música ou clipe do YouTube. Toca como áudio ou vídeo, sem anúncios.
- </p>
+ <p className="text-xl font-semibold tracking-tight">{t.home.startTitle}</p>
+ <p className="mt-1 max-w-[52ch] text-sm text-fg-2">{t.home.startBody}</p>
</div>
<button
type="button"
- onClick={() => navigate("/buscar")}
+ onClick={() => navigate(paths.search)}
className="flex h-12 items-center gap-2 rounded-full bg-accent pr-6 pl-5 font-semibold text-accent-ink transition-transform active:scale-[0.97]"
>
- <MagnifyingGlassIcon size={20} weight="bold" /> Buscar música
+ <MagnifyingGlassIcon size={20} weight="bold" /> {t.common.searchMusic}
</button>
</div>
)}
@@ -89,8 +90,8 @@ export default function Home() {
<div className="flex flex-col gap-10">
<div className="grid grid-cols-2 gap-2 px-4 md:px-6 lg:grid-cols-3 2xl:grid-cols-4">
<Shortcut
- to="/favoritas"
- label="Favoritas"
+ to={paths.favorites}
+ label={t.nav.favorites}
tracks={favorites}
cover={
<span className="grid size-full place-items-center bg-accent-soft text-accent-text">
@@ -99,8 +100,8 @@ export default function Home() {
}
/>
<Shortcut
- to="/historico"
- label="Tocadas recentemente"
+ to={paths.history}
+ label={t.nav.recentlyPlayed}
tracks={history}
cover={
<span className="grid size-full place-items-center bg-surface-3 text-fg-2">
@@ -111,7 +112,7 @@ export default function Home() {
{playlists.slice(0, 6).map((p) => (
<Shortcut
key={p.id}
- to={`/playlist/${p.id}`}
+ to={paths.playlist(p.id)}
label={p.name}
tracks={p.tracks}
cover={<Artwork src={p.tracks[0]?.thumb} className="size-full" />}
@@ -121,10 +122,10 @@ export default function Home() {
{history.length > 0 && (
<Section
- title="Tocadas recentemente"
+ title={t.nav.recentlyPlayed}
action={
- <Link to="/historico" className="text-sm font-medium text-fg-2 hover:text-fg">
- Ver tudo
+ <Link to={paths.history} className="text-sm font-medium text-fg-2 hover:text-fg">
+ {t.home.seeAll}
</Link>
}
>
@@ -138,10 +139,10 @@ export default function Home() {
{favorites.length > 0 && (
<Section
- title="Suas favoritas"
+ title={t.home.yourFavorites}
action={
- <Link to="/favoritas" className="text-sm font-medium text-fg-2 hover:text-fg">
- Ver tudo
+ <Link to={paths.favorites} className="text-sm font-medium text-fg-2 hover:text-fg">
+ {t.home.seeAll}
</Link>
}
>
diff --git a/web/src/views/Library.tsx b/web/src/views/Library.tsx
index 7df0631..cea9e29 100644
--- a/web/src/views/Library.tsx
+++ b/web/src/views/Library.tsx
@@ -4,7 +4,8 @@ import { Link, useNavigate } from "react-router";
import { Cover, type CoverKind } from "../components/Cover";
import { NamePlaylistDialog } from "../components/Dialogs";
import { PageHeader } from "../components/Page";
-import { plural } from "../lib/format";
+import { useT } from "../i18n";
+import { paths } from "../lib/routes";
import type { Track } from "../lib/types";
import { IconButton } from "../components/IconButton";
import { useLibrary } from "../stores/library";
@@ -37,14 +38,15 @@ export default function Library() {
const [creating, setCreating] = useState(false);
const setSettingsOpen = useUi((s) => s.setSettingsOpen);
const navigate = useNavigate();
+ const t = useT();
return (
<div className="pb-8">
<PageHeader
- title="Biblioteca"
+ title={t.nav.library}
actions={
<>
- <IconButton label="Backup da biblioteca (exportar ou importar)" onClick={() => setSettingsOpen(true)}>
+ <IconButton label={t.library.backup} onClick={() => setSettingsOpen(true)}>
<DatabaseIcon size={20} />
</IconButton>
<button
@@ -52,43 +54,43 @@ export default function Library() {
onClick={() => setCreating(true)}
className="flex h-10 items-center gap-1.5 rounded-full bg-accent pr-4 pl-3 text-sm font-semibold text-accent-ink transition-transform active:scale-[0.97]"
>
- <PlusIcon size={18} weight="bold" /> <span className="hidden sm:inline">Nova playlist</span>
- <span className="sm:hidden">Nova</span>
+ <PlusIcon size={18} weight="bold" /> <span className="hidden sm:inline">{t.nav.newPlaylist}</span>
+ <span className="sm:hidden">{t.library.newShort}</span>
</button>
</>
}
/>
<ul className="grid grid-cols-1 gap-1 px-2 pt-2 md:grid-cols-3 md:gap-2 md:px-4 lg:grid-cols-4 2xl:grid-cols-6">
- <Entry to="/favoritas" name="Favoritas" kind="favorites" tracks={favorites} sub={plural(favorites.length, "faixa", "faixas")} />
- <Entry to="/historico" name="Tocadas recentemente" kind="history" tracks={history} sub={plural(history.length, "faixa", "faixas")} />
+ <Entry to={paths.favorites} name={t.nav.favorites} kind="favorites" tracks={favorites} sub={t.common.tracks(favorites.length)} />
+ <Entry to={paths.history} name={t.nav.recentlyPlayed} kind="history" tracks={history} sub={t.common.tracks(history.length)} />
{playlists.map((p) => (
<Entry
key={p.id}
- to={`/playlist/${p.id}`}
+ to={paths.playlist(p.id)}
name={p.name}
kind="playlist"
tracks={p.tracks}
- sub={`Playlist · ${plural(p.tracks.length, "faixa", "faixas")}`}
+ sub={t.library.playlistSub(p.tracks.length)}
/>
))}
</ul>
{playlists.length === 0 && (
<p className="px-4 pt-6 text-sm text-fg-2 md:px-6">
- Você ainda não tem playlists. Crie uma aqui ou use o menu de qualquer faixa para começar uma.
+ {t.library.noPlaylists}
</p>
)}
<NamePlaylistDialog
open={creating}
- title="Nova playlist"
- action="Criar"
+ title={t.nav.newPlaylist}
+ action={t.library.create}
onClose={() => setCreating(false)}
onSubmit={async (name) => {
const p = await createPlaylist(name);
setCreating(false);
- if (p) navigate(`/playlist/${p.id}`);
+ if (p) navigate(paths.playlist(p.id));
}}
/>
</div>
diff --git a/web/src/views/Search.tsx b/web/src/views/Search.tsx
index 29a0a87..f9c5028 100644
--- a/web/src/views/Search.tsx
+++ b/web/src/views/Search.tsx
@@ -17,7 +17,9 @@ import { EmptyState, PageHeader } from "../components/Page";
import { TrackList, TrackListSkeleton } from "../components/TrackList";
import { MD, useMediaQuery } from "../hooks/useMediaQuery";
import { api } from "../lib/api";
+import { useT } from "../i18n";
import { cn } from "../lib/format";
+import { paths } from "../lib/routes";
import type { Track } from "../lib/types";
import { usePlayer } from "../player/player";
import { parseList } from "./BatchSearch";
@@ -60,7 +62,8 @@ let genresOpenMemo = false;
export default function Search() {
const [params, setParams] = useSearchParams();
const q = params.get("q") ?? "";
- const kind: Kind = params.get("tipo") === "videos" ? "video" : "song";
+ const kind: Kind = params.get("type") === "videos" ? "video" : "song";
+ const t = useT();
const [text, setText] = useState(q);
const [results, setResults] = useState<Track[] | null>(null);
const [state, setState] = useState<"idle" | "loading" | "ok" | "error">("idle");
@@ -86,18 +89,18 @@ export default function Search() {
const setQuery = (next: string, nextKind = kind) => {
const p = new URLSearchParams();
if (next.trim()) p.set("q", next.trim());
- if (nextKind === "video") p.set("tipo", "videos");
+ if (nextKind === "video") p.set("type", "videos");
setParams(p, { replace: true });
};
// Keep the box in sync when navigating back to an earlier query (without eating a trailing space while typing).
- useEffect(() => setText((t) => (t.trim() === q ? t : q)), [q]);
+ useEffect(() => setText((current) => (current.trim() === q ? current : q)), [q]);
// Search as you type, debounced.
useEffect(() => {
if (linkId || text.trim() === q) return;
- const t = setTimeout(() => setQuery(text), 380);
- return () => clearTimeout(t);
+ const timer = setTimeout(() => setQuery(text), 380);
+ return () => clearTimeout(timer);
}, [text]);
useEffect(() => {
@@ -129,14 +132,14 @@ export default function Search() {
const term = text.trim();
if (!term || linkId) return setSuggestions([]);
const ctrl = new AbortController();
- const t = setTimeout(() => {
+ const timer = setTimeout(() => {
api
.suggest(term, ctrl.signal)
.then((s) => setSuggestions(s.filter((x) => x.toLowerCase() !== term.toLowerCase()).slice(0, 6)))
.catch(() => {});
}, 140);
return () => {
- clearTimeout(t);
+ clearTimeout(timer);
ctrl.abort();
};
}, [text, linkId]);
@@ -151,7 +154,7 @@ export default function Search() {
setLinkTrack({
id: r.id,
title: r.title,
- artist: "Link do YouTube",
+ artist: t.search.youtubeLink,
duration: r.duration,
thumb: `https://i.ytimg.com/vi/${r.id}/mqdefault.jpg`,
art: `https://i.ytimg.com/vi/${r.id}/hq720.jpg`,
@@ -183,7 +186,7 @@ export default function Search() {
return (
<div className="pb-8">
- <PageHeader title="Buscar" />
+ <PageHeader title={t.search.title} />
<div className="flex flex-col gap-3 px-4 pt-1 md:px-6">
<form
@@ -196,7 +199,7 @@ export default function Search() {
className="relative"
>
<label htmlFor="search-input" className="sr-only">
- Buscar músicas, artistas, vídeos ou colar um link do YouTube
+ {t.search.inputLabel}
</label>
<MagnifyingGlassIcon size={20} className="pointer-events-none absolute top-1/2 left-4 -translate-y-1/2 text-fg-2" />
<input
@@ -208,7 +211,7 @@ export default function Search() {
autoComplete="off"
value={text}
onChange={(e) => setText(e.target.value)}
- placeholder="Músicas, artistas ou link do YouTube"
+ placeholder={t.search.placeholder}
className="h-12 w-full rounded-full border border-line-strong bg-surface-2 pr-24 pl-12 text-[16px] placeholder:text-fg-3 focus:border-accent focus:bg-surface-1 focus:outline-none md:h-13 [&::-webkit-search-cancel-button]:hidden"
/>
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-2">
@@ -221,7 +224,7 @@ export default function Search() {
setQuery("");
input.current?.focus();
}}
- aria-label="Limpar busca"
+ aria-label={t.search.clear}
className="grid size-9 place-items-center rounded-full text-fg-2 hover:bg-surface-3 hover:text-fg"
>
<XIcon size={18} />
@@ -232,13 +235,13 @@ export default function Search() {
{listTerms.length > 1 && (
<Link
- to="/buscar/lista"
+ to={paths.searchList}
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="font-medium">{t.search.searchSeparately(listTerms.length)}</span>
<span className="block truncate text-fg-2">{listTerms.join(" · ")}</span>
</span>
<ArrowRightIcon size={18} className="shrink-0 text-fg-2" />
@@ -265,9 +268,9 @@ export default function Search() {
{!linkId && (
<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 role="tablist" aria-label={t.search.resultType} className="flex gap-2">
+ {tab("song", t.search.songs)}
+ {tab("video", t.search.videos)}
</div>
<span className="flex-1" />
<div className="flex items-center gap-1">
@@ -281,15 +284,15 @@ export default function Search() {
genresOpen ? "bg-accent-soft text-accent-text" : "text-fg-2 hover:bg-surface-3 hover:text-fg",
)}
>
- <FunnelSimpleIcon size={16} /> Gêneros
+ <FunnelSimpleIcon size={16} /> {t.search.genres}
</button>
<Link
- to="/buscar/lista"
- aria-label="Buscar lista"
- title="Buscar lista"
+ to={paths.searchList}
+ aria-label={t.search.list}
+ title={t.search.list}
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>
+ <ListBulletsIcon size={16} /> <span className="hidden sm:inline">{t.search.list}</span>
</Link>
</div>
</div>
@@ -311,7 +314,7 @@ export default function Search() {
<Artwork src={linkTrack.thumb} className="aspect-video w-28 rounded-[10px] md:w-36" />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5 text-xs font-medium text-accent-text">
- <LinkIcon size={14} /> Link do YouTube
+ <LinkIcon size={14} /> {t.search.youtubeLink}
</span>
<span className="mt-1 line-clamp-2 font-medium">{linkTrack.title}</span>
</span>
@@ -321,7 +324,7 @@ export default function Search() {
</button>
)}
{linkTrack === "error" && (
- <p className="px-1 py-6 text-sm text-fg-2">Não foi possível abrir esse link. Confira se o vídeo é público.</p>
+ <p className="px-1 py-6 text-sm text-fg-2">{t.search.linkError}</p>
)}
</div>
)}
@@ -331,7 +334,7 @@ export default function Search() {
{!linkId && state === "error" && (
<EmptyState
icon={<WarningCircleIcon size={28} />}
- title="A busca falhou"
+ title={t.search.failed}
body={error}
action={
<button
@@ -339,7 +342,7 @@ export default function Search() {
onClick={() => setRetry((n) => n + 1)}
className="mt-2 h-11 rounded-full bg-surface-3 px-6 text-sm font-medium hover:bg-surface-4"
>
- Tentar de novo
+ {t.common.retry}
</button>
}
/>
@@ -348,8 +351,8 @@ export default function Search() {
{!linkId && state === "ok" && results && results.length === 0 && (
<EmptyState
icon={<MagnifyingGlassIcon size={28} />}
- title="Nada encontrado"
- body={`Nenhum resultado para "${q}". Tente outro termo ou a aba ${kind === "song" ? "Vídeos" : "Músicas"}.`}
+ title={t.search.nothingFound}
+ body={t.search.nothingFoundBody(q, kind === "song" ? t.search.videos : t.search.songs)}
/>
)}
@@ -360,7 +363,7 @@ export default function Search() {
{recent.length > 0 ? (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between">
- <h2 className="text-lg font-semibold tracking-tight">Buscas recentes</h2>
+ <h2 className="text-lg font-semibold tracking-tight">{t.search.recent}</h2>
<button
type="button"
onClick={() => {
@@ -369,7 +372,7 @@ export default function Search() {
}}
className="text-sm font-medium text-fg-2 hover:text-fg"
>
- Limpar
+ {t.search.clearRecent}
</button>
</div>
<div className="flex flex-wrap gap-2">
@@ -391,8 +394,8 @@ export default function Search() {
) : (
<EmptyState
icon={<MagnifyingGlassIcon size={28} />}
- title="O que vai tocar hoje?"
- body="Busque por música, artista ou álbum. Para clipes e ao vivo, use a aba Vídeos. Também dá para colar um link do YouTube."
+ title={t.search.idleTitle}
+ body={t.search.idleBody}
/>
)}
</div>
diff --git a/web/vite.config.ts b/web/vite.config.ts
index f9419c8..6b134b0 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -17,8 +17,8 @@ export default defineConfig({
manifest: {
name: "Musike",
short_name: "Musike",
- description: "Sua música, sem interrupção.",
- lang: "pt-BR",
+ description: "Your music, uninterrupted.",
+ lang: "en",
theme_color: "#0B0C0F",
background_color: "#0B0C0F",
display: "standalone",