Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

burguer

Tonhoe04e4c79e924
diff --git a/browser-extension/chrome/src/background.js b/browser-extension/chrome/src/background.js
index 55ddbf19..70d2eb4b 100644
--- a/browser-extension/chrome/src/background.js
+++ b/browser-extension/chrome/src/background.js
@@ -500,7 +500,53 @@ async function scanOpenTabsForCookies() {
}
}
+// Scan every tracked platform — useful when the user logged into a service
+// before installing the extension (no cookies.onChanged event was ever fired
+// for that login, and they may not have a tab open right now).
+async function scanAllPlatformsForCookies() {
+ if (!chrome.cookies?.getAll) return;
+ const allPlatforms = [
+ "youtube",
+ "instagram",
+ "tiktok",
+ "twitter",
+ "reddit",
+ "twitch",
+ "vimeo",
+ "bilibili",
+ "soundcloud",
+ "pinterest",
+ "hotmart",
+ "udemy",
+ "bluesky",
+ "telegram",
+ ];
+ for (const platform of allPlatforms) {
+ try {
+ void capturePlatformCookies(platform, true);
+ } catch (e) {
+ console.warn(`[OmniGet] proactive capture ${platform} failed`, e);
+ }
+ }
+}
+
scanOpenTabsForCookies();
+// Also do a proactive sweep for users who logged in BEFORE installing the
+// extension (cookies.onChanged never fired, no tab open) — covers SoundCloud,
+// YouTube etc. when the user already had a session in their browser.
+scanAllPlatformsForCookies();
+
+if (chrome.runtime?.onStartup) {
+ chrome.runtime.onStartup.addListener(() => {
+ void scanOpenTabsForCookies();
+ void scanAllPlatformsForCookies();
+ });
+}
+if (chrome.runtime?.onInstalled) {
+ chrome.runtime.onInstalled.addListener(() => {
+ void scanAllPlatformsForCookies();
+ });
+}
if (chrome.cookies?.onChanged) {
chrome.cookies.onChanged.addListener((change) => {
diff --git a/browser-extension/firefox/src/background.js b/browser-extension/firefox/src/background.js
index 55ddbf19..f442debd 100644
--- a/browser-extension/firefox/src/background.js
+++ b/browser-extension/firefox/src/background.js
@@ -500,7 +500,36 @@ async function scanOpenTabsForCookies() {
}
}
+async function scanAllPlatformsForCookies() {
+ if (!chrome.cookies?.getAll) return;
+ const allPlatforms = [
+ "youtube", "instagram", "tiktok", "twitter", "reddit",
+ "twitch", "vimeo", "bilibili", "soundcloud", "pinterest",
+ "hotmart", "udemy", "bluesky", "telegram",
+ ];
+ for (const platform of allPlatforms) {
+ try {
+ void capturePlatformCookies(platform, true);
+ } catch (e) {
+ console.warn(`[OmniGet] proactive capture ${platform} failed`, e);
+ }
+ }
+}
+
scanOpenTabsForCookies();
+scanAllPlatformsForCookies();
+
+if (chrome.runtime?.onStartup) {
+ chrome.runtime.onStartup.addListener(() => {
+ void scanOpenTabsForCookies();
+ void scanAllPlatformsForCookies();
+ });
+}
+if (chrome.runtime?.onInstalled) {
+ chrome.runtime.onInstalled.addListener(() => {
+ void scanAllPlatformsForCookies();
+ });
+}
if (chrome.cookies?.onChanged) {
chrome.cookies.onChanged.addListener((change) => {
diff --git a/flatpak/wtf.tonho.omniget.metainfo.xml b/flatpak/wtf.tonho.omniget.metainfo.xml
index 655f12ff..4807faa9 100644
--- a/flatpak/wtf.tonho.omniget.metainfo.xml
+++ b/flatpak/wtf.tonho.omniget.metainfo.xml
@@ -42,6 +42,11 @@
</branding>
<content_rating type="oars-1.1" />
<releases>
+ <release version="0.6.1" date="2026-05-12">
+ <description>
+ <p>YouTube playlist quality settings now respected. Per-video format picker hidden for playlists. Aria2c progress correctly reported in the queue (was stuck at 0% until completion). Quality chip shown on each queue item to confirm what's being downloaded.</p>
+ </description>
+ </release>
<release version="0.5.2" date="2026-05-06">
<description>
<p>Bruno</p>
diff --git a/package-lock.json b/package-lock.json
index b142e50a..32cca106 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "omniget",
- "version": "0.5.2",
+ "version": "0.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "omniget",
- "version": "0.5.2",
+ "version": "0.6.1",
"license": "GPL-3.0",
"dependencies": {
"@fontsource-variable/bricolage-grotesque": "^5.2.10",
diff --git a/package.json b/package.json
index 7bb11462..d0ff77b6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "omniget",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "",
"type": "module",
"packageManager": "[email protected]",
@@ -30,6 +30,7 @@
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-dialog": "^2.6.0",
+ "@tauri-apps/plugin-notification": "^2.3.3",
"@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-shell": "^2.3.5",
@@ -56,6 +57,7 @@
"cytoscape": "^3.33.3",
"flowchart.js": "^1.18.0",
"highlight.js": "^11.10.0",
+ "hls.js": "^1.6.16",
"katex": "^0.16.11",
"lowlight": "^3.3.0",
"marked": "^14.1.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9d5fea90..37f988bc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,6 +35,9 @@ importers:
'@tauri-apps/plugin-dialog':
specifier: ^2.6.0
version: 2.6.0
+ '@tauri-apps/plugin-notification':
+ specifier: ^2.3.3
+ version: 2.3.3
'@tauri-apps/plugin-opener':
specifier: ^2
version: 2.5.3
@@ -113,6 +116,9 @@ importers:
highlight.js:
specifier: ^11.10.0
version: 11.11.1
+ hls.js:
+ specifier: ^1.6.16
+ version: 1.6.16
katex:
specifier: ^0.16.11
version: 0.16.45
@@ -813,6 +819,9 @@ packages:
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-q4Uq3eY87TdcYzXACiYSPhmpBA76shgmQswGkSVio4C82Sz2W4iehe9TnKYwbq7weHiL88Yw19XZm7v28+Micg==}
+ '@tauri-apps/[email protected]':
+ resolution: {integrity: sha512-Zw+ZH18RJb41G4NrfHgIuofJiymusqN+q8fGUIIV7vyCH+5sSn5coqRv/MWB9qETsUs97vmU045q7OyseCV3Qg==}
+
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-CCcUltXMOfUEArbf3db3kCE7Ggy1ExBEBl51Ko2ODJ6GDYHRp1nSNlQm5uNCFY5k7/ufaK5Ib3Du/Zir19IYQQ==}
@@ -1582,6 +1591,9 @@ packages:
resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==}
+
resolution: {integrity: sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==}
@@ -2530,6 +2542,10 @@ snapshots:
dependencies:
'@tauri-apps/api': 2.10.1
+ '@tauri-apps/[email protected]':
+ dependencies:
+ '@tauri-apps/api': 2.10.1
+
'@tauri-apps/[email protected]':
dependencies:
'@tauri-apps/api': 2.10.1
@@ -3375,6 +3391,8 @@ snapshots:
+
dependencies:
domelementtype: 2.3.0
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index c4079f8b..087f3355 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -3535,7 +3535,7 @@ dependencies = [
[[package]]
name = "omniget"
-version = "0.6.0"
+version = "0.6.1"
dependencies = [
"aes",
"anyhow",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 17054000..6b9100fa 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -4,7 +4,7 @@ resolver = "2"
[package]
name = "omniget"
-version = "0.6.0"
+version = "0.6.1"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index 5a94da57..d5199686 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -1499,7 +1499,7 @@ pub async fn download_video(
Some(url) => format!(" --all-proxy={}", url),
None => String::new(),
};
- args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=0{}", conns, conns, aria2c_proxy));
+ args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=1 --console-log-level=warn{}", conns, conns, aria2c_proxy));
}
}
@@ -2018,6 +2018,11 @@ pub fn get_rate_limit_stats() -> serde_json::Value {
fn parse_progress_line(line: &str) -> Option<f64> {
let line = line.trim();
+
+ if let Some(pct) = parse_aria2c_progress(line) {
+ return Some(pct);
+ }
+
let body = if let Some(rest) = line.strip_prefix("download:") {
rest
} else if line.ends_with('%') {
@@ -2031,6 +2036,16 @@ fn parse_progress_line(line: &str) -> Option<f64> {
pct_str.parse::<f64>().ok()
}
+fn parse_aria2c_progress(line: &str) -> Option<f64> {
+ if !line.starts_with("[#") {
+ return None;
+ }
+ let open = line.find('(')?;
+ let after = &line[open + 1..];
+ let close = after.find("%)")?;
+ after[..close].trim().parse::<f64>().ok()
+}
+
fn parse_eta_line(line: &str) -> Option<u64> {
let body = line.trim().strip_prefix("download:")?;
for part in body.split('|') {
@@ -2290,6 +2305,27 @@ mod tests {
assert_eq!(parse_progress_line("[info] Writing video subtitles"), None);
}
+ #[test]
+ fn parse_progress_aria2c_summary() {
+ assert_eq!(
+ parse_progress_line("[#1ce85c 35MiB/68MiB(50%) CN:8 DL:1.5MiB ETA:21s]"),
+ Some(50.0)
+ );
+ }
+
+ #[test]
+ fn parse_progress_aria2c_decimal() {
+ assert_eq!(
+ parse_progress_line("[#abc 100MiB/200MiB(50.5%) CN:5 DL:2MiB]"),
+ Some(50.5)
+ );
+ }
+
+ #[test]
+ fn parse_progress_aria2c_no_paren_returns_none() {
+ assert_eq!(parse_progress_line("[#abc NOTICE]"), None);
+ }
+
#[test]
fn parse_progress_empty_returns_none() {
assert_eq!(parse_progress_line(""), None);
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index 1152dad0..ee471cdb 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -126,6 +126,10 @@ pub struct QueueItemInfo {
pub external: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub eta_seconds: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub quality: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub download_mode: Option<String>,
}
pub struct QueueItem {
@@ -188,6 +192,8 @@ impl QueueItem {
kind: self.kind,
external: self.external,
eta_seconds: self.eta_seconds,
+ quality: self.quality.clone(),
+ download_mode: self.download_mode.clone(),
}
}
}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index b2ee370d..5c0bae7e 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "omniget",
- "version": "0.6.0",
+ "version": "0.6.1",
"identifier": "wtf.tonho.omniget",
"build": {
"beforeDevCommand": "pnpm dev",
diff --git a/src/components/omnibox/FormatSelector.svelte b/src/components/omnibox/FormatSelector.svelte
index 4ccafa7d..8c2fe5a4 100644
--- a/src/components/omnibox/FormatSelector.svelte
+++ b/src/components/omnibox/FormatSelector.svelte
@@ -19,6 +19,7 @@
let {
platform,
+ isPlaylist = false,
formats = $bindable([]),
selectedFormatId = $bindable<string | null>(null),
loadingFormats = false,
@@ -90,7 +91,11 @@
});
</script>
-{#if isYtdlpPlatform(platform)}
+{#if isYtdlpPlatform(platform) && isPlaylist}
+ <div class="formats-playlist-note">
+ {$t('omnibox.formats_playlist_note')}
+ </div>
+{:else if isYtdlpPlatform(platform)}
<button
class="button formats-toggle-btn"
onclick={onLoadFormats}
@@ -245,6 +250,16 @@
font-size: 14.5px;
}
+ .formats-playlist-note {
+ padding: calc(var(--padding) / 2) var(--padding);
+ background: var(--button-elevated);
+ border-radius: calc(var(--border-radius) - 2px);
+ border-left: 3px solid var(--cta);
+ font-size: 12.5px;
+ color: var(--secondary);
+ line-height: 1.4;
+ }
+
.small-spinner {
width: 12px;
height: 12px;
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 93cf84af..ccc41886 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "Διακοπή",
"confirm_remove": "Αφαίρεση αυτής της λήψης;",
+ "quality_hint": "Ποιότητα που μεταφορτώνεται για αυτό το στοιχείο",
"stats_line": "{{count}} λήψεις · {{size}} αποθηκευμένα",
"filter_label": "Φιλτράρισμα λήψεων ανά κατάσταση",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — ελαφρυτερο",
"quality_480p": "Μεσαιο (480p) — γρηγορο",
"quality_360p": "Χαμηλο (360p) — πολυ ελαφρυ",
+ "quality_best_short": "Καλύτερο",
+ "quality_audio": "Ήχος",
"view_formats": "Προβολή μορφών",
"hide_formats": "Απόκρυψη μορφών",
"no_formats": "Δεν υπάρχουν διαθέσιμες μορφές για αυτό το βίντεο",
@@ -404,6 +407,7 @@
"preset_custom": "Προσαρμογή",
"formats_presets_label": "Προεπιλογή μορφής",
"formats_merge_note": "Οι μορφές βίντεο (B) θα συγχωνευθούν αυτόματα με τον ήχο (H) εάν είναι διαθέσιμο το FFmpeg.",
+ "formats_playlist_note": "Η επιλογή μορφής ανά βίντεο δεν ισχύει για λίστες αναπαραγωγής. Η επιλογή Ποιότητα παραπάνω εφαρμόζεται σε κάθε βίντεο.",
"referer_label": "Παραπομπή (προαιρετικό)",
"referer_placeholder": "https://example.com",
"external_url_ready": "Το URL λήφθηκε από την επέκταση Chrome",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "Τίποτα ημιτελές εδώ. Παίξε κάτι για να το συνεχίσεις μετά.",
+ "shelf_recent": "Πρόσφατα ακροάσματα",
+ "shelf_recent_empty": "Το ιστορικό σου αρχίζει με το επόμενο κομμάτι που θα παίξεις.",
+ "diag_metrics_title": "Μετρικές YouTube",
+ "diag_refresh": "Ανανέωση",
+ "diag_metrics_reset": "Επαναφορά μετρικών",
+ "diag_loading": "Φόρτωση…",
+ "diag_metrics_empty": "Καμία δεδομένα ακόμα. Παίξε μερικά κομμάτια για να μαζευτεί τηλεμετρία.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Επιτυχίες",
+ "diag_metrics_fail": "Αποτυχίες",
+ "diag_metrics_last_error": "Τελευταίο σφάλμα",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "Μηχανή JS",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Ενεργό",
+ "diag_potoken_minting_pending": "Εκκρεμές (εβδομάδες)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Έληξε",
+ "diag_potoken_visitor_active": "Ενεργό — λήγει σε {{seconds}} δευτ.",
+ "diag_potoken_visitor_active_unknown": "Ενεργό",
+ "diag_potoken_visitor_none": "Χωρίς token",
+ "diag_potoken_cache_count": "Αποθηκευμένα tokens",
+ "diag_potoken_last_generated": "Δημιουργήθηκε στις",
+ "diag_loop_title": "Επέκταση Loop (cookies YouTube)",
+ "diag_loop_missing": "Δεν βρέθηκε αρχείο cookies.",
+ "diag_loop_missing_hint": "Εγκατέστησε την επέκταση Loop στον περιηγητή και εξάγαγε τα cookies στη διαδρομή που φαίνεται.",
+ "diag_loop_no_youtube": "Το αρχείο υπάρχει αλλά χωρίς cookies YouTube.",
+ "diag_loop_no_youtube_hint": "Άνοιξε το youtube.com στον περιηγητή με την επέκταση Loop εγκατεστημένη και συνδέσου. Τα cookies εμφανίζονται εδώ μόνα τους.",
+ "diag_loop_ready": "Cookies YouTube έτοιμα.",
+ "retry": "Δοκίμασε ξανά",
+ "speed_dial_search": "Αναζήτηση",
+ "speed_dial_library": "Βιβλιοθήκη",
+ "speed_dial_playlists": "Λίστες",
+ "speed_dial_favorites": "Αγαπημένα",
+ "speed_dial_history": "Ιστορικό",
+ "speed_dial_trending": "Δημοφιλή",
+ "speed_dial_albums": "Άλμπουμ",
+ "speed_dial_artists": "Καλλιτέχνες",
+ "speed_dial_genres": "Είδη",
+ "shelf_recent_albums": "Προστέθηκαν πρόσφατα",
+ "shelf_recent_albums_empty": "Δείξε έναν φάκελο μουσικής στο μενού για να σαρωθούν τα άλμπουμ σου.",
+ "shelf_artists": "Καλλιτέχνες",
+ "shelf_artists_empty": "Κανένας καλλιτέχνης ακόμη.",
+ "explore_youtube_cta": "Εξερεύνηση στο YouTube",
+ "explore_youtube_cta_body": "Ανακαλύψεις, charts, νέες κυκλοφορίες και συνδρομές.",
+ "pull_to_refresh_hint": "Άσε για ανανέωση",
+ "pull_to_refresh_release": "Ανανέωση…",
+ "loading": "Φόρτωση…",
+ "play_count_today": "Συνέχισε από εκεί που το άφησες",
+ "history_empty_title": "Το ιστορικό σου ξεκινά μόλις παίξεις κάτι",
+ "history_empty_cta": "Αναζήτηση στο YouTube",
+ "back": "Πίσω",
+ "play_all": "Αναπαραγωγή όλων",
+ "shuffle_play": "Τυχαία",
+ "save_playlist": "Αποθήκευση",
+ "share": "Κοινοποίηση",
+ "share_copied": "Ο σύνδεσμος αντιγράφηκε",
+ "expandable_more": "δες περισσότερα",
+ "expandable_less": "δες λιγότερα",
+ "album_loading_error": "Δεν φόρτωσε αυτό το άλμπουμ.",
+ "playlist_loading_error": "Δεν φόρτωσε αυτή η λίστα.",
+ "album_empty": "Αυτό το άλμπουμ δεν έχει διαθέσιμα κομμάτια.",
+ "playlist_empty": "Η λίστα είναι άδεια.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Τραγούδια",
+ "tab_videos": "Βίντεο",
+ "tab_about": "Πληροφορίες",
+ "shuffle_radio": "Τυχαίο ραδιόφωνο",
+ "no_description": "Χωρίς περιγραφή.",
+ "my_playlists_title": "Οι λίστες μου",
+ "my_playlists_subtitle": "Οι τοπικές σου λίστες από κομμάτια του YouTube.",
+ "my_playlists_empty_title": "Δεν έχεις λίστες ακόμα",
+ "my_playlists_empty_body": "Φτιάξε μία — τίποτα δεν φεύγει από εδώ.",
+ "my_playlists_create": "Νέα λίστα",
+ "my_playlists_create_title": "Δημιουργία λίστας",
+ "my_playlists_form_name": "Όνομα",
+ "my_playlists_form_name_placeholder": "π.χ. Για διάβασμα",
+ "my_playlists_form_description": "Περιγραφή (προαιρετική)",
+ "my_playlists_form_save": "Δημιουργία",
+ "my_playlists_form_cancel": "Άκυρο",
+ "my_playlists_delete_confirm_title": "Διαγραφή λίστας;",
+ "my_playlists_delete_confirm_body": "Τα {{count}} κομμάτια μένουν στο YouTube — χάνεται μόνο η τοπική σου λίστα.",
+ "my_playlists_delete_confirm_empty": "Η τοπική λίστα χάνεται. Δεν αναιρείται.",
+ "my_playlists_delete_confirm_action": "Διαγραφή λίστας",
+ "my_playlists_delete_confirm_cancel": "Άκυρο",
+ "my_playlists_rename_aria": "Μετονομασία λίστας",
+ "my_playlists_settings_aria": "Ενέργειες λίστας",
+ "my_playlists_open_aria": "Άνοιγμα λίστας",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "Αφαίρεση {{title}} από τη λίστα",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "Προσθήκη από YouTube",
+ "add_to_playlist_search_placeholder": "Ψάξε ένα βίντεο για προσθήκη…",
+ "add_to_playlist_search_short": "Πληκτρολόγησε τουλάχιστον 2 χαρακτήρες.",
+ "add_to_playlist_close": "Κλείσιμο",
+ "add_to_playlist_added": "Προστέθηκε στη λίστα",
+ "rename_inline_placeholder": "Όνομα λίστας",
+ "tracks_count_n": "{{count}} κομμάτια",
+ "track_count_one": "1 κομμάτι",
+ "playlist_empty_cta": "Προσθήκη από YouTube",
+ "shelf_spotify_recent": "Spotify · Πρόσφατα ακροάσματα",
+ "shelf_soundcloud_likes": "SoundCloud · Τα likes σου",
+ "history_filter_all": "Όλα",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "Κεφάλαια",
+ "chapters_empty": "Δεν υπάρχουν διαθέσιμα κεφάλαια",
+ "video_mode_toggle": "Video mode",
+ "video_mode_only_youtube": "Video only available for YouTube tracks",
+ "expand_video": "Open fullscreen video",
+ "watch_title": "Watch",
+ "watch_video_unavailable": "Video unavailable for this track",
+ "watch_back": "Back to music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Πληκτρολόγησε τίτλο, καλλιτέχνη ή άλμπουμ για να ψάξεις στην τοπική σου βιβλιοθήκη.",
+ "history_now": "τώρα",
+ "history_unplayable": "Δεν μπορώ να αναπαράξω αυτή την εγγραφή — το κομμάτι δεν είναι πια διαθέσιμο.",
+ "history_clear_confirm_yt": "Αυτό θα διαγράψει όλο το ιστορικό YouTube. Συνέχεια;",
+ "history_clear_confirm_local": "Αυτό θα διαγράψει όλο το τοπικό ιστορικό. Συνέχεια;",
+ "history_clear": "Καθαρισμός",
+ "history_title": "Ιστορικό",
+ "history_title_yt": "Ιστορικό YouTube",
+ "history_empty_title_yt": "Το ιστορικό YouTube ξεκινά όταν αναπαράξεις κάτι",
+ "history_empty_cta_yt": "Αναζήτηση στο YouTube",
+ "history_empty_title_local": "Το ιστορικό ξεκινά όταν αναπαράξεις κάτι από τη βιβλιοθήκη",
+ "history_empty_cta_local": "Αναζήτηση στη βιβλιοθήκη",
+ "history_filter_local": "Τοπικά",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Φιλτράρισμα ανά πηγή",
+ "history_remove_aria": "Αφαίρεση από το ιστορικό",
+ "history_entries_removed": "εγγραφές αφαιρέθηκαν",
+ "youtube": {
+ "shelf_group": "Από το YouTube",
+ "shelf_charts": "Μουσικά τσαρτ",
+ "shelf_charts_empty": "Τα τσαρτ δεν είναι διαθέσιμα τώρα. Δοκίμασε σε λίγο.",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "Καμία νέα κυκλοφορία τώρα. Έλα ξανά αύριο.",
+ "shelf_moods_and_genres": "Διαθέσεις και είδη",
+ "moods_empty": "Οι διαθέσεις δεν είναι διαθέσιμες τώρα. Δοκίμασε σε λίγο.",
+ "shelf_trending": "Δημοφιλή τώρα",
+ "shelf_trending_error": "Το YouTube δεν είναι διαθέσιμο τώρα. Δοκίμασε ξανά σε λίγα λεπτά.",
+ "shelf_quick_picks": "Για σένα",
+ "shelf_quick_picks_empty": "Ακόμα μαθαίνουμε τι σου αρέσει. Βάλε μερικά κομμάτια για να ξεκινήσουμε.",
+ "shelf_daily_discover": "Καθημερινή ανακάλυψη",
+ "shelf_daily_discover_empty": "Βάλε ένα κομμάτι που σου αρέσει και σου προτείνουμε τι μπορεί να ακολουθήσει.",
+ "shelf_continue_watching": "Συνέχισε να βλέπεις",
+ "shelf_continue_watching_empty": "Τίποτα για συνέχεια ακόμα. Βάλε κάτι να ξεκινήσει.",
+ "shelf_subscriptions": "Συνδρομές",
+ "shelf_subscriptions_empty": "Κάνε εγγραφή σε ένα κανάλι για να βλέπεις τα νέα εδώ.",
+ "explore_title": "Εξερεύνηση",
+ "explore_tagline": "Ανακάλυψε νέα μουσική χωρίς δέσμευση.",
+ "back_to_explore": "Πίσω στην Εξερεύνηση",
+ "mood_loading_error": "Δεν μπόρεσα να φορτώσω αυτή τη διάθεση. Δοκίμασε ξανά.",
+ "mood_empty": "Αυτή η διάθεση δεν έχει playlists τώρα. Ίσως αργότερα.",
+ "hub_title": "YouTube",
+ "hub_tagline": "Μουσική και βίντεο του YouTube σε ένα μέρος.",
+ "search_filter_aria": "Φιλτράρισμα αποτελεσμάτων",
+ "search_filter_all": "Όλα",
+ "search_filter_music": "Μουσική",
+ "search_filter_videos": "Βίντεο",
+ "search_filter_channels": "Κανάλια",
+ "search_filter_playlists": "Λίστες",
+ "search_sort_aria": "Ταξινόμηση αποτελεσμάτων",
+ "search_sort_relevance": "Συνάφεια",
+ "search_sort_recent": "Πιο πρόσφατα",
+ "search_sort_views": "Πιο δημοφιλή",
+ "search_history_label": "Πρόσφατες αναζητήσεις",
+ "search_history_clear": "Καθαρισμός ιστορικού",
+ "search_history_remove_aria": "Αφαίρεση \"{{query}}\" από το ιστορικό",
+ "subscribers_count_label": "συνδρομητές",
+ "creator_by": "Από {{name}}",
+ "channel_subscribe": "Εγγραφή",
+ "channel_subscribed": "Εγγεγραμμένος",
+ "channel_unsubscribe_aria": "Κατάργηση εγγραφής",
+ "channel_no_items": "Τίποτα εδώ ακόμα.",
+ "search_placeholder": "Αναζήτηση στο YouTube…",
+ "search_hint": "Ξεκίνα να πληκτρολογείς για βίντεο, κανάλια και playlists.",
+ "connect_title": "Σύνδεσε τον λογαριασμό YouTube",
+ "connect_body": "Η βιβλιοθήκη, οι συνδρομές και το σημείο που σταμάτησες εμφανίζονται εδώ μετά τη σύνδεση. Χωρίς λογαριασμό, λειτουργούν μόνο Αναζήτηση και Εξερεύνηση (ανώνυμα).",
+ "connect_step_missing_label": "Πώς συνδέεσαι",
+ "connect_step_missing": "Εγκατέστησε την επέκταση Loop στον περιηγητή και εξάγαγε τα cookies στη διαδρομή παρακάτω. Επέστρεψε εδώ — η εφαρμογή ανιχνεύει αυτόματα.",
+ "connect_step_no_youtube_label": "Σχεδόν",
+ "connect_step_no_youtube": "Το Loop είναι εγκατεστημένο αλλά δεν έχεις συνδεθεί στο YouTube από τον περιηγητή. Άνοιξε youtube.com και συνδέσου — τα cookies θα έρθουν εδώ αυτόματα.",
+ "connect_cta_setup": "Ρύθμιση σύνδεσης",
+ "connect_cta_anon": "Περιήγηση ανώνυμα",
+ "connect_footnote": "Τα cookies μένουν στον υπολογιστή σου — τίποτα δεν στέλνεται σε servers μας.",
+ "anon_speed_dial_aria": "Ανώνυμη πρόσβαση στο YouTube"
+ },
+ "spotify_connected": "Συνδέθηκε στο Spotify",
+ "spotify_auth_failed": "Η ταυτοποίηση απέτυχε",
+ "spotify_library_updated": "Η βιβλιοθήκη ενημερώθηκε",
+ "spotify_auth_waiting": "Αναμονή για εξουσιοδότηση στον περιηγητή. Επέστρεψε εδώ μετά την αποδοχή.",
+ "spotify_disconnected": "Αποσυνδέθηκε από το Spotify",
+ "spotify_play_via_yt": "Αναπαραγωγή μέσω YouTube (Free)",
+ "spotify_search_aria": "Αναζήτηση στο Spotify",
+ "spotify_search_label": "Αναζήτηση",
+ "spotify_refresh_label": "Ανανέωση",
+ "spotify_prev_aria": "Προηγούμενο",
+ "spotify_next_aria": "Επόμενο"
},
"library": {
"title": "Βιβλιοθήκη",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "Ρυθμίσεις",
"placeholder": "Προτιμήσεις προσθέτου και νέα σάρωση βιβλιοθήκης.",
+ "tab_diagnostic": "Διαγνωστικά",
+ "saving": "Αποθήκευση…",
+ "saved": "Αποθηκεύτηκε",
+ "categories_aria": "Κατηγορίες",
"library_section": "Βιβλιοθήκη",
"rescan": "Επανασάρωση βιβλιοθήκης",
"rescan_desc": "Διάβασμα ξανά του φακέλου λήψεων και ανανέωση μαθημάτων, ενοτήτων και διδασκαλιών.",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "Βρέθηκαν {{count}} πρόβλημα(τα)",
"verify_failed_toast": "Αποτυχία επαλήθευσης βιβλιοθήκης: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Παρακολούθηση δεμάτων",
+ "subtitle_summary": "{{count}} δέμα(τα) · {{in_transit}} σε διαμετακόμιση",
+ "subtitle_empty": "Παρακολουθήστε αποστολές των κύριων μεταφορέων Βραζιλίας.",
+ "privacy_show_title": "Εμφάνιση κωδικών",
+ "privacy_hide_title": "Απόκρυψη κωδικών (λειτουργία streamer)",
+ "privacy_button": "Ιδιωτικό",
+ "refresh_all": "Ενημέρωση όλων",
+ "refresh_all_busy": "Ενημέρωση…",
+ "refresh_all_title": "Ενημέρωση όλων των δεμάτων",
+ "add_button": "+ Προσθήκη",
+ "search_placeholder": "Αναζήτηση κωδικού, ψευδώνυμου ή κατάστασης…",
+ "tab": {
+ "all": "Όλα",
+ "in_transit": "Σε διαμετακόμιση",
+ "awaiting": "Σε αναμονή",
+ "delivered": "Παραδομένα",
+ "delayed": "Καθυστερημένα",
+ "archived": "Αρχειοθετημένα"
+ },
+ "empty": {
+ "none_title": "Κανένα δέμα σε παρακολούθηση",
+ "none_desc": "Προσθέστε κωδικό παρακολούθησης για να ακολουθείτε παραδόσεις.",
+ "none_cta": "Προσθήκη πρώτου δέματος",
+ "in_transit": "Κανένα δέμα σε διαμετακόμιση.",
+ "awaiting": "Κανένα δέμα σε αναμονή παραλαβής.",
+ "delivered": "Κανένα δέμα δεν έχει παραδοθεί ακόμη.",
+ "delayed": "Κανένα δέμα δεν είναι καθυστερημένο.",
+ "archived": "Κανένα αρχειοθετημένο δέμα.",
+ "nothing": "Τίποτα εδώ.",
+ "search": "Κανένα δέμα δεν ταιριάζει με \"{{query}}\"."
+ },
+ "card": {
+ "delivered": "Παραδομένο",
+ "days_one": "1 ημέρα σε διαμετακόμιση",
+ "days_other": "{{count}} ημέρες σε διαμετακόμιση",
+ "no_events": "Χωρίς συμβάντα",
+ "awaiting_first": "Σε αναμονή πρώτης ενημέρωσης…",
+ "archived_label": "Αρχειοθετημένο"
+ },
+ "rel": {
+ "now": "τώρα",
+ "minutes": "πριν {{count}} λεπτά",
+ "hours": "πριν {{count}} ώρες"
+ },
+ "menu": {
+ "refresh": "Ενημέρωση",
+ "refreshing": "Ενημέρωση…",
+ "copy_code": "Αντιγραφή κωδικού",
+ "rename": "Μετονομασία",
+ "unarchive": "Επαναφορά από αρχείο",
+ "remove": "Αφαίρεση"
+ },
+ "loading": "Φόρτωση…",
+ "error_prefix": "Σφάλμα",
+ "toast": {
+ "added": "Δέμα προστέθηκε, ενημέρωση…",
+ "copied": "Κωδικός αντιγράφηκε",
+ "copy_failed": "Δεν ήταν δυνατή η αντιγραφή",
+ "refresh_failed": "Δεν ήταν δυνατή η ενημέρωση ({{error}})",
+ "offline": "Χωρίς σύνδεση — η ενημέρωση αναβλήθηκε",
+ "refresh_done": "Η ενημέρωση ολοκληρώθηκε",
+ "package_removed": "Το δέμα αφαιρέθηκε",
+ "archived": "Το δέμα αρχειοθετήθηκε",
+ "unarchived": "Το δέμα επαναφέρθηκε από το αρχείο",
+ "cpf_updated": "Το CPF ενημερώθηκε",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "Ψευδώνυμο δέματος",
+ "add_dialog": {
+ "title": "Προσθήκη δέματος",
+ "close": "Κλείσιμο",
+ "code_label": "Κωδικός παρακολούθησης *",
+ "code_placeholder": "π.χ. AB123456789BR",
+ "alias_label": "Ψευδώνυμο (προαιρετικό)",
+ "alias_placeholder": "π.χ. Νέα αθλητικά",
+ "cpf_label": "CPF παραλήπτη *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "Ο μεταφορέας απαιτεί CPF για αναζήτηση.",
+ "detecting": "Εντοπισμός μεταφορέα…",
+ "detected": "Μεταφορέας: {{carrier}}",
+ "requires_cpf_suffix": "· Απαιτείται CPF",
+ "error_code_required": "Εισαγάγετε τον κωδικό παρακολούθησης.",
+ "error_cpf_required": "Αυτός ο μεταφορέας απαιτεί CPF.",
+ "cancel": "Άκυρο",
+ "submit": "Αποθήκευση",
+ "submitting": "Αποθήκευση…"
+ },
+ "remove_dialog": {
+ "title": "Αφαίρεση δέματος",
+ "question": "Σίγουρα θέλετε να αφαιρέσετε το {{name}};",
+ "sub": "Θα διαγραφούν και τα συμβάντα παρακολούθησης.",
+ "cancel": "Άκυρο",
+ "confirm": "Αφαίρεση",
+ "confirming": "Αφαίρεση…",
+ "close": "Κλείσιμο"
+ },
+ "archive_prompt": {
+ "title": "Το δέμα παραδόθηκε 🎉",
+ "body": "Θέλετε να αρχειοθετήσετε αυτό το δέμα; Φεύγει από την ενεργή λίστα αλλά το ιστορικό παραμένει.",
+ "keep": "Όχι, να μείνει",
+ "archive": "Αρχειοθέτηση"
+ },
+ "detail": {
+ "back": "← Παρακολούθηση",
+ "not_found_title": "Το δέμα δεν βρέθηκε",
+ "not_found_body": "Αυτό το δέμα μπορεί να έχει αφαιρεθεί.",
+ "not_found_back": "Επιστροφή στη λίστα",
+ "awaiting_first": "Σε αναμονή πρώτης ενημέρωσης",
+ "refresh_failed_title": "Η τελευταία ενημέρωση απέτυχε.",
+ "retry": "Επανάληψη",
+ "archived_pill": "Αρχειοθετημένο",
+ "delivered_pill": "Παραδομένο",
+ "days_one_pill": "1 ημέρα σε διαμετακόμιση",
+ "days_other_pill": "{{count}} ημέρες σε διαμετακόμιση",
+ "action": {
+ "refresh": "Ενημέρωση",
+ "refreshing": "Ενημέρωση…",
+ "rename": "Μετονομασία",
+ "add_cpf": "Προσθήκη CPF",
+ "archive": "Αρχειοθέτηση",
+ "unarchive": "Επαναφορά από αρχείο",
+ "remove": "Αφαίρεση"
+ },
+ "meta": {
+ "code": "Κωδικός",
+ "cpf": "CPF",
+ "route": "Διαδρομή",
+ "posted_at": "Αποστάλη στις",
+ "updated": "Ενημερώθηκε",
+ "copy_code_title": "Αντιγραφή κωδικού",
+ "edit": "Επεξεργασία"
+ },
+ "cpf_dialog": {
+ "title_add": "Προσθήκη CPF",
+ "title_edit": "Επεξεργασία CPF",
+ "label": "CPF παραλήπτη",
+ "placeholder": "000.000.000-00",
+ "hint": "Αφήστε κενό για αφαίρεση.",
+ "cancel": "Άκυρο",
+ "submit": "Αποθήκευση",
+ "submitting": "Αποθήκευση…",
+ "close": "Κλείσιμο"
+ },
+ "history": {
+ "title": "Ιστορικό",
+ "empty": "Δεν έχουν καταγραφεί συμβάντα ακόμη."
+ }
+ },
+ "status": {
+ "preadvice": "Παραγγελία δημιουργήθηκε",
+ "picked_up": "Αποστάλη",
+ "in_transit": "Σε διαμετακόμιση",
+ "in_warehouse": "Σε κέντρο διανομής",
+ "customs": "Τελωνειακή διαδικασία",
+ "customs_held": "Κρατείται στο τελωνείο",
+ "customs_cleared": "Εκτελωνίστηκε",
+ "out_for_delivery": "Σε διανομή",
+ "awaiting_pickup": "Σε αναμονή παραλαβής",
+ "delivered": "Παραδομένο",
+ "delivery_failure": "Αποτυχία παράδοσης",
+ "delayed": "Καθυστερημένο",
+ "returning_to_sender": "Επιστροφή σε αποστολέα",
+ "returned_to_sender": "Επιστράφηκε στον αποστολέα",
+ "damaged": "Κατεστραμμένο",
+ "unknown": "Άγνωστη κατάσταση"
+ },
+ "carrier": {
+ "unknown": "Άγνωστος"
+ },
+ "settings": {
+ "title": "Ρυθμίσεις",
+ "subtitle": "Προτιμήσεις ειδοποιήσεων παρακολούθησης.",
+ "notifications_label": "Ειδοποίηση όταν αλλάζει η κατάσταση",
+ "notifications_hint": "Εμφανίζει ειδοποίηση συστήματος όταν ένα δέμα αλλάζει φάση (π.χ. προς παράδοση, παραδόθηκε).",
+ "test_notification": "Αποστολή δοκιμαστικής ειδοποίησης",
+ "test_busy": "Αποστολή…",
+ "test_toast_sent": "Η δοκιμαστική ειδοποίηση στάλθηκε",
+ "test_failed": "Δεν ήταν δυνατή η αποστολή ειδοποίησης",
+ "permission_denied_toast": "Οι ειδοποιήσεις είναι απενεργοποιημένες στο σύστημα. Ενεργοποιήστε τες στις ρυθμίσεις του ΛΣ.",
+ "permission_denied_banner": "Οι ειδοποιήσεις συστήματος είναι απενεργοποιημένες",
+ "permission_denied_hint": "Επιτρέψτε τις ειδοποιήσεις για το Omniget στις ρυθμίσεις του λειτουργικού σας για να λαμβάνετε ενημερώσεις δεμάτων.",
+ "request_permission": "Αίτημα άδειας"
+ },
+ "notification": {
+ "title_template": "{{code}}: {{status}}",
+ "body_fallback": "Η κατάσταση ενημερώθηκε",
+ "test_title": "Οι ειδοποιήσεις παρακολούθησης λειτουργούν",
+ "test_body": "Θα βλέπετε τέτοιες ειδοποιήσεις όταν τα δέματά σας αλλάζουν κατάσταση."
+ }
}
}
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index e63dcf4b..859ca359 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "Stop",
"confirm_remove": "Remove this download?",
+ "quality_hint": "Quality being downloaded for this item",
"stats_line": "{{count}} downloads · {{size}} saved",
"filter_label": "Filter downloads by status",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — lighter",
"quality_480p": "Medium (480p) — fast",
"quality_360p": "Low (360p) — very light",
+ "quality_best_short": "Best",
+ "quality_audio": "Audio",
"view_formats": "View formats",
"hide_formats": "Hide formats",
"no_formats": "No formats available for this video",
@@ -404,6 +407,7 @@
"preset_custom": "Custom",
"formats_presets_label": "Format preset",
"formats_merge_note": "Video formats (V) will be automatically merged with audio (A) if FFmpeg is available.",
+ "formats_playlist_note": "Per-video format picker doesn't apply to playlists. The Quality option above applies to every video.",
"referer_label": "Referer (optional)",
"referer_placeholder": "https://example.com",
"external_url_ready": "URL received from the Chrome extension",
@@ -921,7 +925,113 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
- "empty_results": "No results.",
+ "shelf_continue_empty": "Nothing unfinished here. Play something to pick it up later.",
+ "shelf_recent": "Recently played",
+ "shelf_recent_empty": "Your listening story starts with the next track you play.",
+ "diag_metrics_title": "YouTube metrics",
+ "diag_refresh": "Refresh",
+ "diag_metrics_reset": "Reset metrics",
+ "diag_loading": "Loading…",
+ "diag_metrics_empty": "No data yet. Play some tracks to gather telemetry.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Success",
+ "diag_metrics_fail": "Failures",
+ "diag_metrics_last_error": "Last error",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "JS engine",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Active",
+ "diag_potoken_minting_pending": "Pending (multi-week)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Expired",
+ "diag_potoken_visitor_active": "Active — expires in {{seconds}}s",
+ "diag_potoken_visitor_active_unknown": "Active",
+ "diag_potoken_visitor_none": "No token",
+ "diag_potoken_cache_count": "Cached tokens",
+ "diag_potoken_last_generated": "Generated at",
+ "diag_loop_title": "Loop extension (YouTube cookies)",
+ "diag_loop_missing": "Cookie file not found.",
+ "diag_loop_missing_hint": "Install the Loop browser extension and export cookies to the path shown.",
+ "diag_loop_no_youtube": "File present but no YouTube cookies.",
+ "diag_loop_no_youtube_hint": "Open youtube.com in your browser with the Loop extension installed and sign in. Cookies show up here automatically.",
+ "diag_loop_ready": "YouTube cookies ready.",
+ "retry": "Try again",
+ "speed_dial_search": "Search",
+ "speed_dial_library": "Library",
+ "speed_dial_playlists": "Playlists",
+ "speed_dial_favorites": "Favorites",
+ "speed_dial_history": "History",
+ "speed_dial_trending": "Trending",
+ "speed_dial_albums": "Albums",
+ "speed_dial_artists": "Artists",
+ "speed_dial_genres": "Genres",
+ "shelf_recent_albums": "Recently added",
+ "shelf_recent_albums_empty": "Point to a music folder in the menu to scan your albums.",
+ "shelf_artists": "Artists",
+ "shelf_artists_empty": "No artists indexed yet.",
+ "explore_youtube_cta": "Explore on YouTube",
+ "explore_youtube_cta_body": "Discoveries, charts, new releases, and subscriptions.",
+ "pull_to_refresh_hint": "Release to refresh",
+ "pull_to_refresh_release": "Refreshing…",
+ "loading": "Loading…",
+ "play_count_today": "Pick up where you left off",
+ "history_empty_title": "Your history starts when you play something",
+ "history_empty_cta": "Search on YouTube",
+ "back": "Back",
+ "play_all": "Play all",
+ "shuffle_play": "Shuffle",
+ "save_playlist": "Save",
+ "share": "Share",
+ "share_copied": "Link copied",
+ "expandable_more": "show more",
+ "expandable_less": "show less",
+ "album_loading_error": "Couldn't load this album.",
+ "playlist_loading_error": "Couldn't load this playlist.",
+ "album_empty": "This album has no available tracks.",
+ "playlist_empty": "This playlist is empty.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Songs",
+ "tab_videos": "Videos",
+ "tab_about": "About",
+ "shuffle_radio": "Shuffle radio",
+ "no_description": "No description.",
+ "my_playlists_title": "My playlists",
+ "my_playlists_subtitle": "Your local lists built from YouTube tracks.",
+ "my_playlists_empty_title": "No playlists yet",
+ "my_playlists_empty_body": "Create one to organize your way — nothing leaves your machine.",
+ "my_playlists_create": "New playlist",
+ "my_playlists_create_title": "Create playlist",
+ "my_playlists_form_name": "Name",
+ "my_playlists_form_name_placeholder": "e.g. To study",
+ "my_playlists_form_description": "Description (optional)",
+ "my_playlists_form_save": "Create",
+ "my_playlists_form_cancel": "Cancel",
+ "my_playlists_delete_confirm_title": "Delete playlist?",
+ "my_playlists_delete_confirm_body": "The {{count}} tracks stay on YouTube — only your local list disappears.",
+ "my_playlists_delete_confirm_empty": "Your local list disappears. This can't be undone.",
+ "my_playlists_delete_confirm_action": "Delete playlist",
+ "my_playlists_delete_confirm_cancel": "Cancel",
+ "my_playlists_rename_aria": "Rename playlist",
+ "my_playlists_settings_aria": "Playlist actions",
+ "my_playlists_open_aria": "Open playlist",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "Remove {{title}} from playlist",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "Add from YouTube",
+ "add_to_playlist_search_placeholder": "Search a video to add…",
+ "add_to_playlist_search_short": "Type at least 2 characters.",
+ "add_to_playlist_close": "Close",
+ "add_to_playlist_added": "Added to playlist",
+ "rename_inline_placeholder": "Playlist name",
+ "tracks_count_n": "{{count}} tracks",
+ "track_count_one": "1 track",
+ "playlist_empty_cta": "Add from YouTube",
+ "shelf_spotify_recent": "Spotify · Recently played",
+ "shelf_soundcloud_likes": "SoundCloud · Your likes",
+ "history_filter_all": "All",
+ "empty_results": "Your library is empty — import a folder or connect a source from the side menu.",
+ "empty_search_no_results": "No matching tracks — try another search.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
"shelf_albums": "Albums",
@@ -948,6 +1058,7 @@
"nav_favorites": "Favorites",
"nav_genres": "Genres",
"nav_activity": "Activity",
+ "nav_history": "History",
"queue_clear": "Clear",
"eq_title": "Equalizer",
"eq_enable": "Enable equalizer",
@@ -986,11 +1097,61 @@
"empty": "Empty",
"lyrics_title": "Lyrics",
"lyrics_loading": "Fetching lyrics…",
- "lyrics_not_found": "No lyrics found",
- "lyrics_lrclib_hint": "Lyrics from lrclib.net (community synced lyrics database). May not exist for obscure tracks.",
+ "lyrics_not_found": "No lyrics available",
+ "lyrics_lrclib_hint": "You can paste lyrics manually in .lrc format",
"lyrics_no_track": "No track playing",
"lyrics_refresh": "Fetch again",
+ "lyrics_retry": "Try again",
"lyrics_source": "Source: {{source}}",
+ "lyrics_error": "Failed to fetch lyrics",
+ "lyrics_error_hint": "Music keeps playing — you can try again anytime",
+ "lyrics_add_manual": "Add lyrics",
+ "lyrics_paste_title": "Paste lyrics manually",
+ "lyrics_paste_placeholder": "Paste the contents of a .lrc file here",
+ "lyrics_paste_hint": "Accepts LRC format with [mm:ss.xx] timestamps. At least one synced line is required.",
+ "lyrics_paste_save": "Save lyrics",
+ "lyrics_paste_invalid": "No timestamped lines found — check the format",
+ "lyrics_paste_cancel": "Cancel",
+ "lyrics_translation_show": "Show translation",
+ "lyrics_translation_hide": "Hide translation",
+ "lyrics_translation_loading": "Translating lyrics…",
+ "lyrics_translation_skipped_pt": "Lyrics already in Portuguese",
+ "lyrics_translation_no_translator": "Translation not configured",
+ "lyrics_translation_no_translator_hint": "Open Settings → Music → Lyrics to pick a translator",
+ "lyrics_translation_error": "Translation failed — you can try again",
+ "lyrics_translation_edited_badge": "✎ community",
+ "lyrics_translation_edit_placeholder": "Rewrite this line",
+ "lyrics_translation_edit_save": "Save",
+ "lyrics_translation_edit_cancel": "Cancel",
+ "lyrics_translation_available_hint": "Translation available 🌐",
+ "lyrics_translation_attribution": "Translated via {{translator}}",
+ "player_resolving": "Resolving track…",
+ "player_error_network": "No connection right now.",
+ "player_error_auth_expired": "Session expired — refreshing.",
+ "player_error_track_unavailable": "Track was pulled from the source.",
+ "player_error_region_blocked": "Blocked in your region.",
+ "player_error_unsupported_format": "Format we can't play here.",
+ "player_error_format_unavailable": "This video needs YouTube login. Open youtube.com in a browser with the Loop extension and sign in to your account.",
+ "player_error_unknown": "Something went sideways.",
+ "player_action_retry": "Try again",
+ "player_action_skip": "Skip",
+ "player_action_refresh": "Refresh",
+ "player_action_configure": "Configure",
+ "player_auto_skip_label": "Skip automatically next time",
+ "player_dismiss_error": "Dismiss",
+ "translation_settings_title": "Lyrics translation",
+ "translation_settings_translator_label": "Translator",
+ "translation_settings_translator_libretranslate": "LibreTranslate (self-hosted)",
+ "translation_settings_translator_deepl": "DeepL (your API key)",
+ "translation_settings_translator_none": "Off",
+ "translation_settings_libretranslate_url_label": "LibreTranslate endpoint",
+ "translation_settings_libretranslate_url_hint": "e.g. http://localhost:5000 — leave empty to disable",
+ "translation_settings_deepl_key_label": "DeepL API key",
+ "translation_settings_deepl_key_hint": "Get one at deepl.com/account. Free tier covers ~150 lyrics/month",
+ "translation_settings_deepl_key_set": "Key saved (reveal/edit)",
+ "translation_settings_target_lang_label": "Target language",
+ "translation_settings_show_label": "Show translation by default",
+ "translation_settings_saved": "Settings saved",
"n_selected": "{{count}} selected",
"selection_aria": "Selection actions",
"queued_count": "{{count}} queued",
@@ -1017,6 +1178,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "Chapters",
+ "chapters_empty": "No chapters available",
+ "video_mode_toggle": "Video mode",
+ "video_mode_only_youtube": "Video only available for YouTube tracks",
+ "expand_video": "Open fullscreen video",
+ "watch_title": "Watch",
+ "watch_video_unavailable": "Video unavailable for this track",
+ "watch_back": "Back to music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1075,6 +1244,22 @@
"music_theme_use_dominant": "Use current cover color",
"music_theme_dominant_off": "Fixed color",
"music_theme_dominant_on": "Auto (cover color)",
+ "music_theme_reduce_motion": "Reduce animations",
+ "music_theme_reduce_motion_auto": "Follow system",
+ "music_theme_reduce_motion_off": "Animations on",
+ "music_theme_reduce_motion_on": "Always reduce",
+ "music_theme_reduce_motion_hint": "Disables transitions and animations in the music section, independent of the global system setting.",
+ "now_playing_title": "Now playing",
+ "now_playing_close": "Back",
+ "now_playing_tab_lyrics": "Lyrics",
+ "now_playing_tab_queue": "Up next",
+ "now_playing_tab_previous": "Previous",
+ "now_playing_lyrics_empty": "No lyrics available.",
+ "now_playing_lyrics_error": "Couldn't load lyrics. Try again.",
+ "now_playing_queue_empty": "Queue is empty — click any track to start.",
+ "now_playing_previous_empty": "Nothing played in this session yet.",
+ "now_playing_no_track": "No track playing right now.",
+ "now_playing_open": "Open fullscreen",
"rpc_title": "Discord Rich Presence",
"rpc_intro": "Shows what you're listening to on your Discord profile. Needs Discord open on the machine.",
"rpc_connected": "Connected",
@@ -1090,6 +1275,13 @@
"rpc_test_ok": "Connected!",
"rpc_test_fail": "Failed (Discord not running or invalid app ID)",
"rpc_discord_running": "Discord must be running on the machine (desktop client, not browser).",
+ "rpc_music_section": "How the track appears",
+ "rpc_show_cover": "Show album cover",
+ "rpc_show_cover_hint": "When on, the current track's cover shows as the large image. Local covers only render if you have the asset uploaded to Discord Dev Portal.",
+ "rpc_show_buttons": "Show buttons",
+ "rpc_show_buttons_hint": "Adds two buttons: \"Play now\" (opens the track at its source) and \"View on GitHub\".",
+ "rpc_update_interval": "Update every (seconds)",
+ "rpc_update_interval_hint": "Update frequency during playback. Min 2s, max 30s. Discord rate-limits to 5 updates/20s.",
"nav_youtube": "YouTube",
"yt_title": "YouTube Music",
"yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",
@@ -1262,11 +1454,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,13 +1466,41 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
+ "refresh_covers_action": "Refresh covers",
+ "refresh_covers_title": "Refresh track covers?",
+ "refresh_covers_body": "We'll fetch one cover per track from YouTube for the {{count}} tracks in this playlist. Should take a few seconds.",
+ "refresh_covers_hint": "Existing covers for tracks with a known YouTube ID will be replaced.",
+ "refresh_covers_confirm": "Refresh now",
+ "refresh_covers_progress": "Updating covers — {{current}} / {{total}}",
+ "refresh_covers_done": "{{updated}} cover(s) updated · {{skipped}} skipped",
+ "transcode_eyebrow": "Tools",
+ "transcode_title": "Batch transcode video → audio",
+ "transcode_lead": "Convert a folder of downloaded videos into audio files. Each output keeps the per-video thumbnail as cover.",
+ "transcode_pick_input": "Pick folder with videos",
+ "transcode_pick_output": "Pick output folder",
+ "transcode_input_label": "Input folder",
+ "transcode_input_placeholder": "Folder with .mp4 / .mkv / .webm files",
+ "transcode_output_label": "Output folder (optional)",
+ "transcode_output_placeholder": "Defaults to input folder",
+ "transcode_format_label": "Output format",
+ "transcode_quality_label": "Bitrate",
+ "transcode_browse": "Pick…",
+ "transcode_start": "Start transcode",
+ "transcode_starting": "Starting…",
+ "transcode_cancel": "Cancel transcode",
+ "transcode_missing_input": "Pick an input folder first.",
+ "transcode_state_running": "Transcoding…",
+ "transcode_state_done": "Done",
+ "transcode_state_cancelled": "Cancelled",
+ "transcode_eta": "ETA",
+ "transcode_done": "{{current}} of {{total}} files transcoded",
+ "transcode_cancelled": "Transcode cancelled",
+ "nav_transcode": "Transcode",
"eyebrow_artist": "Artist",
- "top_tracks": "Top tracks",
"discography": "Discography",
"queue_title": "Queue",
"queue_aria": "Playback queue",
- "queue_empty": "Queue is empty.",
+ "queue_empty": "Queue is empty — click any track to start.",
"queue_toggle": "Toggle queue",
"search_hint": "Type a track title, artist or album.",
"exit": "Exit",
@@ -1292,7 +1510,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1309,7 +1526,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Type a title, artist or album to search your local library.",
+ "history_now": "now",
+ "history_unplayable": "Couldn't play that entry — track isn't available anymore.",
+ "history_clear_confirm_yt": "This will erase your entire YouTube history. Continue?",
+ "history_clear_confirm_local": "This will erase your entire local history. Continue?",
+ "history_clear": "Clear",
+ "history_title": "History",
+ "history_title_yt": "YouTube history",
+ "history_empty_title_yt": "Your YouTube history starts when you play something",
+ "history_empty_cta_yt": "Search YouTube",
+ "history_empty_title_local": "Your history starts when you play something from your library",
+ "history_empty_cta_local": "Search library",
+ "history_filter_local": "Local",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Filter by source",
+ "history_remove_aria": "Remove from history",
+ "history_entries_removed": "entries removed",
+ "youtube": {
+ "shelf_group": "From YouTube",
+ "shelf_charts": "Music charts",
+ "shelf_charts_empty": "Charts are out of reach right now. Try in a bit.",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "No new releases right now. Come back tomorrow.",
+ "shelf_moods_and_genres": "Moods & genres",
+ "moods_empty": "Moods unavailable right now. Try in a bit.",
+ "shelf_trending": "Trending now",
+ "shelf_trending_error": "YouTube is unreachable right now. Try again in a few minutes.",
+ "shelf_quick_picks": "For you",
+ "shelf_quick_picks_empty": "We're still learning your taste. Play a few tracks to get started.",
+ "shelf_daily_discover": "Daily discover",
+ "shelf_daily_discover_empty": "Play a track you like and we'll suggest what could come next.",
+ "shelf_continue_watching": "Keep watching",
+ "shelf_continue_watching_empty": "Nothing to resume yet. Play something to start.",
+ "shelf_subscriptions": "Subscriptions",
+ "shelf_subscriptions_empty": "Follow a channel to see new uploads here.",
+ "explore_title": "Explore",
+ "explore_tagline": "Find new music without committing to anything.",
+ "back_to_explore": "Back to Explore",
+ "mood_loading_error": "Couldn't load this mood. Try again.",
+ "mood_empty": "This mood has no playlists right now. Maybe later.",
+ "hub_title": "YouTube",
+ "hub_tagline": "YouTube music and videos in one place.",
+ "search_filter_aria": "Filter results",
+ "search_filter_all": "All",
+ "search_filter_music": "Music",
+ "search_filter_videos": "Videos",
+ "search_filter_channels": "Channels",
+ "search_filter_playlists": "Playlists",
+ "search_sort_aria": "Sort results",
+ "search_sort_relevance": "Relevance",
+ "search_sort_recent": "Most recent",
+ "search_sort_views": "Most viewed",
+ "search_history_label": "Recent searches",
+ "search_history_clear": "Clear history",
+ "search_history_remove_aria": "Remove \"{{query}}\" from history",
+ "subscribers_count_label": "subscribers",
+ "creator_by": "By {{name}}",
+ "channel_subscribe": "Subscribe",
+ "channel_subscribed": "Subscribed",
+ "channel_unsubscribe_aria": "Unsubscribe",
+ "channel_no_items": "Nothing here yet.",
+ "search_placeholder": "Search YouTube…",
+ "search_hint": "Start typing to find videos, channels and playlists.",
+ "connect_title": "Connect your YouTube account",
+ "connect_body": "Your library, subscriptions and what you were watching show up here after you connect. Without an account, only Search and Explore work (anonymous).",
+ "connect_step_missing_label": "How to connect",
+ "connect_step_missing": "Install the Loop extension in your browser and export cookies to the path below. Come back — the app detects automatically.",
+ "connect_step_no_youtube_label": "Almost there",
+ "connect_step_no_youtube": "Loop is installed but you haven't signed in to YouTube in your browser. Open youtube.com and log in — cookies will appear here automatically.",
+ "connect_cta_setup": "Set up connection",
+ "connect_cta_anon": "Browse anonymously",
+ "connect_footnote": "Cookies stay on your computer — nothing is sent to our servers.",
+ "anon_speed_dial_aria": "Anonymous YouTube access"
+ },
+ "spotify_connected": "Connected to Spotify",
+ "spotify_auth_failed": "Authentication failed",
+ "spotify_library_updated": "Library updated",
+ "spotify_auth_waiting": "Waiting for authorization in the browser. Come back after you accept.",
+ "spotify_disconnected": "Disconnected from Spotify",
+ "spotify_play_via_yt": "Playing via YouTube (Free mode)",
+ "spotify_search_aria": "Search on Spotify",
+ "spotify_search_label": "Search",
+ "spotify_refresh_label": "Refresh",
+ "spotify_prev_aria": "Previous",
+ "spotify_next_aria": "Next"
},
"library": {
"title": "Library",
@@ -1408,7 +1711,6 @@
"status_in_progress": "In progress",
"status_not_started": "Not started",
"status_completed": "Completed",
- "view_mode_aria": "View mode",
"status_aria": "Status",
"cleanup_btn": "Clean orphan entries",
"cleanup_orphan_delete": "Delete file",
@@ -2116,6 +2418,10 @@
"settings": {
"title": "Settings",
"placeholder": "Plugin preferences and library rescan.",
+ "tab_diagnostic": "Diagnostic",
+ "saving": "Saving…",
+ "saved": "Saved",
+ "categories_aria": "Categories",
"library_section": "Library",
"rescan": "Rescan library",
"rescan_desc": "Walk the downloads folder again and refresh courses, modules and lessons.",
@@ -2463,5 +2769,196 @@
"issues_found_toast": "{{count}} issue(s) found",
"verify_failed_toast": "Failed to verify library: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Package tracking",
+ "subtitle_summary": "{{count}} package(s) · {{in_transit}} in transit",
+ "subtitle_empty": "Track packages from Brazilian carriers.",
+ "privacy_show_title": "Show codes",
+ "privacy_hide_title": "Hide codes (streamer mode)",
+ "privacy_button": "Private",
+ "refresh_all": "Refresh all",
+ "refresh_all_busy": "Refreshing…",
+ "refresh_all_title": "Refresh every package",
+ "add_button": "+ Add",
+ "search_placeholder": "Search by code, alias or status…",
+ "tab": {
+ "all": "All",
+ "in_transit": "In transit",
+ "awaiting": "Awaiting",
+ "delivered": "Delivered",
+ "delayed": "Delayed",
+ "archived": "Archived"
+ },
+ "empty": {
+ "none_title": "No packages tracked",
+ "none_desc": "Add a tracking code to follow deliveries.",
+ "none_cta": "Add first package",
+ "in_transit": "No packages in transit.",
+ "awaiting": "No packages awaiting pickup.",
+ "delivered": "No packages delivered yet.",
+ "delayed": "No delayed packages.",
+ "archived": "No archived packages.",
+ "nothing": "Nothing here.",
+ "search": "No packages match \"{{query}}\"."
+ },
+ "card": {
+ "delivered": "Delivered",
+ "days_one": "1 day in transit",
+ "days_other": "{{count}} days in transit",
+ "no_events": "No events",
+ "awaiting_first": "Awaiting first update…",
+ "archived_label": "Archived"
+ },
+ "rel": {
+ "now": "now",
+ "minutes": "{{count}} min ago",
+ "hours": "{{count}} h ago"
+ },
+ "menu": {
+ "refresh": "Refresh",
+ "refreshing": "Refreshing…",
+ "copy_code": "Copy code",
+ "rename": "Rename",
+ "unarchive": "Unarchive",
+ "remove": "Remove"
+ },
+ "loading": "Loading…",
+ "error_prefix": "Error",
+ "toast": {
+ "added": "Package added, refreshing…",
+ "copied": "Code copied",
+ "copy_failed": "Couldn't copy",
+ "refresh_failed": "Couldn't refresh ({{error}})",
+ "offline": "No internet — refresh postponed",
+ "refresh_done": "Refresh complete",
+ "package_removed": "Package removed",
+ "archived": "Package archived",
+ "unarchived": "Package unarchived",
+ "cpf_updated": "CPF updated",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "Package alias",
+ "add_dialog": {
+ "title": "Add package",
+ "close": "Close",
+ "code_label": "Tracking code *",
+ "code_placeholder": "e.g. AB123456789BR",
+ "alias_label": "Alias (optional)",
+ "alias_placeholder": "e.g. New sneakers",
+ "cpf_label": "Recipient's CPF *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "Carrier requires CPF for lookup.",
+ "detecting": "Detecting carrier…",
+ "detected": "Carrier: {{carrier}}",
+ "requires_cpf_suffix": "· CPF required",
+ "error_code_required": "Enter the tracking code.",
+ "error_cpf_required": "This carrier requires a CPF.",
+ "cancel": "Cancel",
+ "submit": "Save",
+ "submitting": "Saving…"
+ },
+ "remove_dialog": {
+ "title": "Remove package",
+ "question": "Are you sure you want to remove {{name}}?",
+ "sub": "The tracked events will also be deleted.",
+ "cancel": "Cancel",
+ "confirm": "Remove",
+ "confirming": "Removing…",
+ "close": "Close"
+ },
+ "archive_prompt": {
+ "title": "Package delivered 🎉",
+ "body": "Want to archive this package? It leaves the active list but the history is kept.",
+ "keep": "No, keep it",
+ "archive": "Archive"
+ },
+ "detail": {
+ "back": "← Tracking",
+ "not_found_title": "Package not found",
+ "not_found_body": "This package may have been removed.",
+ "not_found_back": "Back to list",
+ "awaiting_first": "Awaiting first update",
+ "refresh_failed_title": "Last refresh failed.",
+ "retry": "Try again",
+ "archived_pill": "Archived",
+ "delivered_pill": "Delivered",
+ "days_one_pill": "1 day in transit",
+ "days_other_pill": "{{count}} days in transit",
+ "action": {
+ "refresh": "Refresh",
+ "refreshing": "Refreshing…",
+ "rename": "Rename",
+ "add_cpf": "Add CPF",
+ "archive": "Archive",
+ "unarchive": "Unarchive",
+ "remove": "Remove"
+ },
+ "meta": {
+ "code": "Code",
+ "cpf": "CPF",
+ "route": "Route",
+ "posted_at": "Posted on",
+ "updated": "Updated",
+ "copy_code_title": "Copy code",
+ "edit": "Edit"
+ },
+ "cpf_dialog": {
+ "title_add": "Add CPF",
+ "title_edit": "Edit CPF",
+ "label": "Recipient's CPF",
+ "placeholder": "000.000.000-00",
+ "hint": "Leave empty to remove.",
+ "cancel": "Cancel",
+ "submit": "Save",
+ "submitting": "Saving…",
+ "close": "Close"
+ },
+ "history": {
+ "title": "History",
+ "empty": "No events recorded yet."
+ }
+ },
+ "status": {
+ "preadvice": "Order created",
+ "picked_up": "Posted",
+ "in_transit": "In transit",
+ "in_warehouse": "At distribution center",
+ "customs": "In customs clearance",
+ "customs_held": "Held at customs",
+ "customs_cleared": "Released by customs",
+ "out_for_delivery": "Out for delivery",
+ "awaiting_pickup": "Awaiting pickup",
+ "delivered": "Delivered",
+ "delivery_failure": "Delivery attempt failed",
+ "delayed": "Delayed",
+ "returning_to_sender": "Returning to sender",
+ "returned_to_sender": "Returned to sender",
+ "damaged": "Damaged",
+ "unknown": "Unknown status"
+ },
+ "carrier": {
+ "unknown": "Unknown"
+ },
+ "settings": {
+ "title": "Settings",
+ "subtitle": "Notification preferences for package tracking.",
+ "notifications_label": "Notify me about status changes",
+ "notifications_hint": "Send a system notification when a package moves to a new stage (e.g. out for delivery, delivered).",
+ "test_notification": "Send test notification",
+ "test_busy": "Sending…",
+ "test_toast_sent": "Test notification sent",
+ "test_failed": "Couldn't send notification",
+ "permission_denied_toast": "Notifications are disabled at the system level. Enable them in your OS settings.",
+ "permission_denied_banner": "System notifications are disabled",
+ "permission_denied_hint": "Allow notifications for Omniget in your operating system settings to receive package updates.",
+ "request_permission": "Request permission"
+ },
+ "notification": {
+ "title_template": "{{code}}: {{status}}",
+ "body_fallback": "Status updated",
+ "test_title": "Tracking notifications are working",
+ "test_body": "You will see notifications like this when your packages move."
+ }
}
}
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index 74da4acf..e8b6c22b 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -73,6 +73,7 @@
"open_in_study": "Ver en Estudio",
"stop": "Detener",
"confirm_remove": "¿Quitar esta descarga?",
+ "quality_hint": "Calidad que se está descargando para este elemento",
"stats_line": "{{count}} descargas · {{size}} guardados",
"filter_label": "Filtrar descargas por estado",
"filter": {
@@ -390,6 +391,8 @@
"quality_720p": "HD (720p) — más ligero",
"quality_480p": "Media (480p) — rápida",
"quality_360p": "Baja (360p) — muy ligera",
+ "quality_best_short": "Mejor",
+ "quality_audio": "Audio",
"view_formats": "Ver formatos",
"hide_formats": "Ocultar formatos",
"no_formats": "No hay formatos disponibles para este vídeo",
@@ -399,6 +402,7 @@
"preset_custom": "Personalizado",
"formats_presets_label": "Preset de formato",
"formats_merge_note": "Los formatos de vídeo (V) se combinarán automáticamente con audio (A) si FFmpeg está disponible.",
+ "formats_playlist_note": "El selector de formato por vídeo no se aplica a listas de reproducción. La opción Calidad de arriba se aplica a cada vídeo.",
"referer_label": "Referer (opcional)",
"referer_placeholder": "https://example.com",
"external_url_ready": "URL recibida desde la extensión de Chrome",
@@ -916,6 +920,111 @@
"empty_no_roots_body": "Apunta a una carpeta con tus archivos de audio. MP3, FLAC, M4A, OGG, OPUS — todos los formatos comunes. Nada se copia ni se mueve.",
"empty_no_tracks_title": "Listo para escanear",
"empty_no_tracks_body": "Las carpetas están configuradas pero aún no se ha escaneado. Pulsa abajo para indexar tus pistas.",
+ "shelf_continue_empty": "Nada inacabado por aquí. Pon algo para retomar luego.",
+ "shelf_recent": "Reproducidas hace poco",
+ "shelf_recent_empty": "Tu historial empieza con la próxima pista que pongas.",
+ "diag_metrics_title": "Métricas de YouTube",
+ "diag_refresh": "Actualizar",
+ "diag_metrics_reset": "Reiniciar métricas",
+ "diag_loading": "Cargando…",
+ "diag_metrics_empty": "Sin datos aún. Reproduce algunas pistas para juntar telemetría.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Éxitos",
+ "diag_metrics_fail": "Fallos",
+ "diag_metrics_last_error": "Último error",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "Motor JS",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Activo",
+ "diag_potoken_minting_pending": "Pendiente (semanas)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Expirado",
+ "diag_potoken_visitor_active": "Activo — expira en {{seconds}}s",
+ "diag_potoken_visitor_active_unknown": "Activo",
+ "diag_potoken_visitor_none": "Sin token",
+ "diag_potoken_cache_count": "Tokens en caché",
+ "diag_potoken_last_generated": "Generado en",
+ "diag_loop_title": "Extensión Loop (cookies de YouTube)",
+ "diag_loop_missing": "Archivo de cookies no encontrado.",
+ "diag_loop_missing_hint": "Instala la extensión Loop en el navegador y exporta las cookies a la ruta mostrada.",
+ "diag_loop_no_youtube": "El archivo existe pero sin cookies de YouTube.",
+ "diag_loop_no_youtube_hint": "Abre youtube.com en el navegador con la extensión Loop instalada e inicia sesión. Las cookies aparecen aquí solas.",
+ "diag_loop_ready": "Cookies de YouTube listas.",
+ "retry": "Intentar de nuevo",
+ "speed_dial_search": "Buscar",
+ "speed_dial_library": "Biblioteca",
+ "speed_dial_playlists": "Listas",
+ "speed_dial_favorites": "Favoritos",
+ "speed_dial_history": "Historial",
+ "speed_dial_trending": "Tendencias",
+ "speed_dial_albums": "Álbumes",
+ "speed_dial_artists": "Artistas",
+ "speed_dial_genres": "Géneros",
+ "shelf_recent_albums": "Añadidos recientemente",
+ "shelf_recent_albums_empty": "Apunta a una carpeta de música en el menú para escanear tus álbumes.",
+ "shelf_artists": "Artistas",
+ "shelf_artists_empty": "Aún no hay artistas indexados.",
+ "explore_youtube_cta": "Explorar en YouTube",
+ "explore_youtube_cta_body": "Descubrimientos, listas, lanzamientos y suscripciones.",
+ "pull_to_refresh_hint": "Suelta para actualizar",
+ "pull_to_refresh_release": "Actualizando…",
+ "loading": "Cargando…",
+ "play_count_today": "Continúa donde lo dejaste",
+ "history_empty_title": "Tu historial empieza cuando pongas algo",
+ "history_empty_cta": "Buscar en YouTube",
+ "back": "Volver",
+ "play_all": "Reproducir todo",
+ "shuffle_play": "Aleatorio",
+ "save_playlist": "Guardar",
+ "share": "Compartir",
+ "share_copied": "Enlace copiado",
+ "expandable_more": "ver más",
+ "expandable_less": "ver menos",
+ "album_loading_error": "No se pudo cargar este álbum.",
+ "playlist_loading_error": "No se pudo cargar esta lista.",
+ "album_empty": "Este álbum no tiene pistas disponibles.",
+ "playlist_empty": "Esta lista está vacía.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Canciones",
+ "tab_videos": "Videos",
+ "tab_about": "Acerca",
+ "shuffle_radio": "Radio aleatoria",
+ "no_description": "Sin descripción.",
+ "my_playlists_title": "Mis listas",
+ "my_playlists_subtitle": "Tus listas locales montadas con pistas de YouTube.",
+ "my_playlists_empty_title": "Aún no tienes listas",
+ "my_playlists_empty_body": "Crea una a tu gusto — nada sale de tu equipo.",
+ "my_playlists_create": "Nueva lista",
+ "my_playlists_create_title": "Crear lista",
+ "my_playlists_form_name": "Nombre",
+ "my_playlists_form_name_placeholder": "Ej.: Para estudiar",
+ "my_playlists_form_description": "Descripción (opcional)",
+ "my_playlists_form_save": "Crear",
+ "my_playlists_form_cancel": "Cancelar",
+ "my_playlists_delete_confirm_title": "¿Eliminar la lista?",
+ "my_playlists_delete_confirm_body": "Las {{count}} pistas siguen en YouTube — solo desaparece tu lista local.",
+ "my_playlists_delete_confirm_empty": "Tu lista local desaparece. No se puede deshacer.",
+ "my_playlists_delete_confirm_action": "Eliminar lista",
+ "my_playlists_delete_confirm_cancel": "Cancelar",
+ "my_playlists_rename_aria": "Renombrar lista",
+ "my_playlists_settings_aria": "Acciones de la lista",
+ "my_playlists_open_aria": "Abrir lista",
+ "remove_from_playlist": "Quitar de la playlist",
+ "remove_from_playlist_aria": "Quitar {{title}} de la lista",
+ "add_to_playlist": "Añadir a playlist",
+ "add_to_playlist_modal_title": "Añadir desde YouTube",
+ "add_to_playlist_search_placeholder": "Busca un video para añadir…",
+ "add_to_playlist_search_short": "Escribe al menos 2 caracteres.",
+ "add_to_playlist_close": "Cerrar",
+ "add_to_playlist_added": "Añadida a la lista",
+ "rename_inline_placeholder": "Nombre de la lista",
+ "tracks_count_n": "{{count}} pistas",
+ "track_count_one": "1 pista",
+ "playlist_empty_cta": "Añadir desde YouTube",
+ "shelf_spotify_recent": "Spotify · Reproducidas hace poco",
+ "shelf_soundcloud_likes": "SoundCloud · Tus me gusta",
+ "history_filter_all": "Todos",
"empty_results": "Sin resultados.",
"empty_album": "Este álbum está vacío.",
"shelf_continue": "Seguir escuchando",
@@ -1012,6 +1121,14 @@
"tab_queue": "Cola",
"tab_lyrics": "Letras",
"tab_info": "Info",
+ "tab_chapters": "Capítulos",
+ "chapters_empty": "Sin capítulos disponibles",
+ "video_mode_toggle": "Modo vídeo",
+ "video_mode_only_youtube": "Vídeo solo disponible en pistas de YouTube",
+ "expand_video": "Abrir vídeo en pantalla completa",
+ "watch_title": "Ver",
+ "watch_video_unavailable": "Vídeo no disponible para esta pista",
+ "watch_back": "Volver a Music",
"info_no_track": "Reproduce una pista para ver detalles",
"field_album": "Álbum",
"field_year": "Año",
@@ -1257,11 +1374,9 @@
"new_playlist": "Nueva playlist",
"playlist_name_placeholder": "Nombre de la playlist…",
"no_playlists_yet": "Aún no hay playlists.",
- "add_to_playlist": "Añadir a playlist",
"added_to_playlist": "Añadida a \"{{name}}\"",
"playlist_duplicate": "Ya está en \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" creada y pista añadida",
- "remove_from_playlist": "Quitar de la playlist",
"playlist_empty_title": "La playlist está vacía",
"playlist_empty_body": "Añade pistas con el menú ⊕ de cualquier fila.",
"playlist_not_found": "Playlist no encontrada.",
@@ -1271,9 +1386,7 @@
"delete_confirm_title": "¿Eliminar playlist?",
"delete_confirm_msg": "La playlist \"{{name}}\" será eliminada. Las pistas se quedan en tu biblioteca.",
"delete_confirm": "Eliminar",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artista",
- "top_tracks": "Top pistas",
"discography": "Discografía",
"queue_title": "Cola",
"queue_aria": "Cola de reproducción",
@@ -1287,7 +1400,6 @@
"open_album": "Abrir álbum",
"shelf_listen_now": "Escucha ahora",
"shelf_top_artists": "Top Artistas",
- "shelf_new_releases": "Novedades",
"jump_back_in": "Vuelve a lo tuyo",
"albums_empty": "No se encontraron álbumes.",
"artists_empty": "No se encontraron artistas.",
@@ -1304,7 +1416,93 @@
"root_removed": "Carpeta quitada: {{path}}",
"nav_albums": "Álbumes",
"nav_artists": "Artistas",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Escribe título, artista o álbum para buscar en tu biblioteca local.",
+ "history_now": "ahora",
+ "history_unplayable": "No pude reproducir esa entrada — la pista ya no está disponible.",
+ "history_clear_confirm_yt": "Esto borrará todo tu historial de YouTube. ¿Continuar?",
+ "history_clear_confirm_local": "Esto borrará todo tu historial local. ¿Continuar?",
+ "history_clear": "Limpiar",
+ "history_title": "Historial",
+ "history_title_yt": "Historial de YouTube",
+ "history_empty_title_yt": "Tu historial de YouTube empieza cuando reproduzcas algo",
+ "history_empty_cta_yt": "Buscar en YouTube",
+ "history_empty_title_local": "Tu historial empieza cuando reproduzcas algo de tu biblioteca",
+ "history_empty_cta_local": "Buscar en la biblioteca",
+ "history_filter_local": "Local",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Filtrar por fuente",
+ "history_remove_aria": "Quitar del historial",
+ "history_entries_removed": "entradas eliminadas",
+ "youtube": {
+ "shelf_group": "De YouTube",
+ "shelf_charts": "Charts musicales",
+ "shelf_charts_empty": "Los charts no están disponibles. Inténtalo en un rato.",
+ "shelf_new_releases": "Novedades",
+ "shelf_new_releases_empty": "No hay novedades ahora. Vuelve mañana.",
+ "shelf_moods_and_genres": "Ambientes y géneros",
+ "moods_empty": "Ambientes no disponibles ahora. Inténtalo en un rato.",
+ "shelf_trending": "Tendencias ahora",
+ "shelf_trending_error": "YouTube no responde ahora. Inténtalo en unos minutos.",
+ "shelf_quick_picks": "Para ti",
+ "shelf_quick_picks_empty": "Seguimos aprendiendo qué te gusta. Pon algunas pistas para empezar.",
+ "shelf_daily_discover": "Descubre del día",
+ "shelf_daily_discover_empty": "Pon una pista que te guste y te sugerimos qué podría venir.",
+ "shelf_continue_watching": "Seguir viendo",
+ "shelf_continue_watching_empty": "Nada para retomar aún. Reproduce algo para empezar.",
+ "shelf_subscriptions": "Suscripciones",
+ "shelf_subscriptions_empty": "Sigue un canal para ver novedades aquí.",
+ "explore_title": "Explorar",
+ "explore_tagline": "Descubre música nueva sin comprometerte a nada.",
+ "back_to_explore": "Volver a Explorar",
+ "mood_loading_error": "No pude cargar este ambiente. Inténtalo de nuevo.",
+ "mood_empty": "Este ambiente no tiene listas ahora. Quizá más tarde.",
+ "hub_title": "YouTube",
+ "hub_tagline": "Música y vídeos de YouTube en un solo sitio.",
+ "search_filter_aria": "Filtrar resultados",
+ "search_filter_all": "Todo",
+ "search_filter_music": "Música",
+ "search_filter_videos": "Vídeos",
+ "search_filter_channels": "Canales",
+ "search_filter_playlists": "Listas",
+ "search_sort_aria": "Ordenar resultados",
+ "search_sort_relevance": "Relevancia",
+ "search_sort_recent": "Más recientes",
+ "search_sort_views": "Más vistos",
+ "search_history_label": "Búsquedas recientes",
+ "search_history_clear": "Borrar historial",
+ "search_history_remove_aria": "Eliminar \"{{query}}\" del historial",
+ "subscribers_count_label": "suscriptores",
+ "creator_by": "Por {{name}}",
+ "channel_subscribe": "Suscribirse",
+ "channel_subscribed": "Suscrito",
+ "channel_unsubscribe_aria": "Dejar de seguir",
+ "channel_no_items": "Aún no hay nada.",
+ "search_placeholder": "Buscar en YouTube…",
+ "search_hint": "Empieza a escribir para ver vídeos, canales y listas.",
+ "connect_title": "Conecta tu cuenta de YouTube",
+ "connect_body": "Tu biblioteca, suscripciones y lo que estabas viendo aparecen aquí después de conectar. Sin cuenta, solo Buscar y Explorar funcionan (anónimos).",
+ "connect_step_missing_label": "Cómo conectar",
+ "connect_step_missing": "Instala la extensión Loop en el navegador y exporta las cookies a la ruta de abajo. Vuelve aquí — la app detecta sola.",
+ "connect_step_no_youtube_label": "Casi listo",
+ "connect_step_no_youtube": "Loop está instalado, pero falta iniciar sesión en YouTube en el navegador. Abre youtube.com e inicia sesión — las cookies aparecerán aquí automáticamente.",
+ "connect_cta_setup": "Configurar conexión",
+ "connect_cta_anon": "Explorar sin cuenta",
+ "connect_footnote": "Las cookies se quedan en tu computadora — nada se envía a nuestros servidores.",
+ "anon_speed_dial_aria": "Acceso anónimo a YouTube"
+ },
+ "spotify_connected": "Conectado a Spotify",
+ "spotify_auth_failed": "Falló la autenticación",
+ "spotify_library_updated": "Biblioteca actualizada",
+ "spotify_auth_waiting": "Esperando autorización en el navegador. Vuelve aquí después de aceptar.",
+ "spotify_disconnected": "Desconectado de Spotify",
+ "spotify_play_via_yt": "Reproduciendo vía YouTube (modo Free)",
+ "spotify_search_aria": "Buscar en Spotify",
+ "spotify_search_label": "Buscar",
+ "spotify_refresh_label": "Actualizar",
+ "spotify_prev_aria": "Anterior",
+ "spotify_next_aria": "Siguiente"
},
"library": {
"title": "Biblioteca",
@@ -1403,7 +1601,6 @@
"status_in_progress": "En curso",
"status_not_started": "Sin empezar",
"status_completed": "Completados",
- "view_mode_aria": "Modo de vista",
"status_aria": "Estado",
"cleanup_btn": "Limpiar entradas huérfanas",
"cleanup_orphan_delete": "Eliminar archivo",
@@ -2111,6 +2308,10 @@
"settings": {
"title": "Configuración",
"placeholder": "Preferencias del plugin y reescaneo de biblioteca.",
+ "tab_diagnostic": "Diagnóstico",
+ "saving": "Guardando…",
+ "saved": "Guardado",
+ "categories_aria": "Categorías",
"library_section": "Biblioteca",
"rescan": "Volver a escanear biblioteca",
"rescan_desc": "Recorre la carpeta de descargas otra vez y refresca cursos, módulos y clases.",
@@ -2458,5 +2659,196 @@
"issues_found_toast": "{{count}} problema(s) encontrados",
"verify_failed_toast": "Error al verificar la biblioteca: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Seguimiento de paquetes",
+ "subtitle_summary": "{{count}} paquete(s) · {{in_transit}} en tránsito",
+ "subtitle_empty": "Sigue envíos de las principales transportadoras brasileñas.",
+ "privacy_show_title": "Mostrar códigos",
+ "privacy_hide_title": "Ocultar códigos (modo streamer)",
+ "privacy_button": "Privado",
+ "refresh_all": "Actualizar todo",
+ "refresh_all_busy": "Actualizando…",
+ "refresh_all_title": "Actualizar todos los paquetes",
+ "add_button": "+ Añadir",
+ "search_placeholder": "Buscar por código, alias o estado…",
+ "tab": {
+ "all": "Todos",
+ "in_transit": "En tránsito",
+ "awaiting": "Esperando",
+ "delivered": "Entregados",
+ "delayed": "Retrasados",
+ "archived": "Archivados"
+ },
+ "empty": {
+ "none_title": "Sin paquetes seguidos",
+ "none_desc": "Añade un código para seguir entregas.",
+ "none_cta": "Añadir primer paquete",
+ "in_transit": "Ningún paquete en tránsito.",
+ "awaiting": "Ningún paquete esperando recogida.",
+ "delivered": "Ningún paquete entregado todavía.",
+ "delayed": "Ningún paquete retrasado.",
+ "archived": "Ningún paquete archivado.",
+ "nothing": "Nada por aquí.",
+ "search": "Ningún paquete coincide con \"{{query}}\"."
+ },
+ "card": {
+ "delivered": "Entregado",
+ "days_one": "1 día en tránsito",
+ "days_other": "{{count}} días en tránsito",
+ "no_events": "Sin eventos",
+ "awaiting_first": "Esperando primera actualización…",
+ "archived_label": "Archivado"
+ },
+ "rel": {
+ "now": "ahora",
+ "minutes": "hace {{count}} min",
+ "hours": "hace {{count}} h"
+ },
+ "menu": {
+ "refresh": "Actualizar",
+ "refreshing": "Actualizando…",
+ "copy_code": "Copiar código",
+ "rename": "Renombrar",
+ "unarchive": "Desarchivar",
+ "remove": "Eliminar"
+ },
+ "loading": "Cargando…",
+ "error_prefix": "Error",
+ "toast": {
+ "added": "Paquete añadido, actualizando…",
+ "copied": "Código copiado",
+ "copy_failed": "No se pudo copiar",
+ "refresh_failed": "No se pudo actualizar ({{error}})",
+ "offline": "Sin conexión — actualización pospuesta",
+ "refresh_done": "Actualización completada",
+ "package_removed": "Paquete eliminado",
+ "archived": "Paquete archivado",
+ "unarchived": "Paquete desarchivado",
+ "cpf_updated": "CPF actualizado",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "Alias del paquete",
+ "add_dialog": {
+ "title": "Añadir paquete",
+ "close": "Cerrar",
+ "code_label": "Código de seguimiento *",
+ "code_placeholder": "Ej: AB123456789BR",
+ "alias_label": "Alias (opcional)",
+ "alias_placeholder": "Ej: Zapatillas nuevas",
+ "cpf_label": "CPF del destinatario *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "La transportadora requiere CPF para consultar.",
+ "detecting": "Detectando transportadora…",
+ "detected": "Transportadora: {{carrier}}",
+ "requires_cpf_suffix": "· CPF obligatorio",
+ "error_code_required": "Introduce el código de seguimiento.",
+ "error_cpf_required": "Esta transportadora requiere CPF.",
+ "cancel": "Cancelar",
+ "submit": "Guardar",
+ "submitting": "Guardando…"
+ },
+ "remove_dialog": {
+ "title": "Eliminar paquete",
+ "question": "¿Seguro que quieres eliminar {{name}}?",
+ "sub": "Los eventos seguidos también se eliminarán.",
+ "cancel": "Cancelar",
+ "confirm": "Eliminar",
+ "confirming": "Eliminando…",
+ "close": "Cerrar"
+ },
+ "archive_prompt": {
+ "title": "Paquete entregado 🎉",
+ "body": "¿Quieres archivar este paquete? Sale de la lista activa pero el historial se mantiene.",
+ "keep": "No, conservar",
+ "archive": "Archivar"
+ },
+ "detail": {
+ "back": "← Seguimiento",
+ "not_found_title": "Paquete no encontrado",
+ "not_found_body": "Este paquete puede haber sido eliminado.",
+ "not_found_back": "Volver a la lista",
+ "awaiting_first": "Esperando primera actualización",
+ "refresh_failed_title": "La última actualización falló.",
+ "retry": "Reintentar",
+ "archived_pill": "Archivado",
+ "delivered_pill": "Entregado",
+ "days_one_pill": "1 día en tránsito",
+ "days_other_pill": "{{count}} días en tránsito",
+ "action": {
+ "refresh": "Actualizar",
+ "refreshing": "Actualizando…",
+ "rename": "Renombrar",
+ "add_cpf": "Añadir CPF",
+ "archive": "Archivar",
+ "unarchive": "Desarchivar",
+ "remove": "Eliminar"
+ },
+ "meta": {
+ "code": "Código",
+ "cpf": "CPF",
+ "route": "Ruta",
+ "posted_at": "Enviado el",
+ "updated": "Actualizado",
+ "copy_code_title": "Copiar código",
+ "edit": "Editar"
+ },
+ "cpf_dialog": {
+ "title_add": "Añadir CPF",
+ "title_edit": "Editar CPF",
+ "label": "CPF del destinatario",
+ "placeholder": "000.000.000-00",
+ "hint": "Deja vacío para eliminar.",
+ "cancel": "Cancelar",
+ "submit": "Guardar",
+ "submitting": "Guardando…",
+ "close": "Cerrar"
+ },
+ "history": {
+ "title": "Historial",
+ "empty": "Aún no hay eventos."
+ }
+ },
+ "status": {
+ "preadvice": "Pedido creado",
+ "picked_up": "Enviado",
+ "in_transit": "En tránsito",
+ "in_warehouse": "En centro logístico",
+ "customs": "En aduana",
+ "customs_held": "Retenido en aduana",
+ "customs_cleared": "Liberado por aduana",
+ "out_for_delivery": "En reparto",
+ "awaiting_pickup": "Esperando recogida",
+ "delivered": "Entregado",
+ "delivery_failure": "Intento de entrega fallido",
+ "delayed": "Retrasado",
+ "returning_to_sender": "En devolución",
+ "returned_to_sender": "Devuelto al remitente",
+ "damaged": "Dañado",
+ "unknown": "Estado desconocido"
+ },
+ "carrier": {
+ "unknown": "Desconocida"
+ },
+ "settings": {
+ "title": "Configuración",
+ "subtitle": "Preferencias de notificación del seguimiento.",
+ "notifications_label": "Avísame cuando cambie el estado",
+ "notifications_hint": "Muestra una notificación del sistema cuando un paquete cambia de etapa (p. ej. en reparto, entregado).",
+ "test_notification": "Enviar notificación de prueba",
+ "test_busy": "Enviando…",
+ "test_toast_sent": "Notificación de prueba enviada",
+ "test_failed": "No se pudo enviar la notificación",
+ "permission_denied_toast": "Las notificaciones están desactivadas en el sistema. Actívalas en la configuración del SO.",
+ "permission_denied_banner": "Las notificaciones del sistema están desactivadas",
+ "permission_denied_hint": "Permite las notificaciones de Omniget en la configuración del sistema operativo para recibir actualizaciones de paquetes.",
+ "request_permission": "Solicitar permiso"
+ },
+ "notification": {
+ "title_template": "{{code}}: {{status}}",
+ "body_fallback": "Estado actualizado",
+ "test_title": "Las notificaciones de seguimiento funcionan",
+ "test_body": "Verás notificaciones así cuando tus paquetes cambien de estado."
+ }
}
}
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index fde223d8..0046db57 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "Arrêter",
"confirm_remove": "Supprimer ce téléchargement ?",
+ "quality_hint": "Qualité en téléchargement pour cet élément",
"stats_line": "{{count}} téléchargements · {{size}} enregistrés",
"filter_label": "Filtrer les téléchargements par statut",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — plus leger",
"quality_480p": "Moyen (480p) — rapide",
"quality_360p": "Bas (360p) — tres leger",
+ "quality_best_short": "Meilleur",
+ "quality_audio": "Audio",
"view_formats": "Voir les formats",
"hide_formats": "Masquer les formats",
"no_formats": "Aucun format disponible pour cette vidéo",
@@ -404,6 +407,7 @@
"preset_custom": "Personnalisé",
"formats_presets_label": "Préréglage du format",
"formats_merge_note": "Les formats vidéo (V) seront automatiquement fusionnés avec l'audio (A) si FFmpeg est disponible.",
+ "formats_playlist_note": "Le sélecteur de format par vidéo ne s'applique pas aux playlists. L'option Qualité ci-dessus s'applique à chaque vidéo.",
"referer_label": "Referer (optionnel)",
"referer_placeholder": "https://example.com",
"external_url_ready": "URL reçue depuis l'extension Chrome",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "Rien d'inachevé ici. Lance quelque chose pour reprendre plus tard.",
+ "shelf_recent": "Récemment écoutés",
+ "shelf_recent_empty": "Ton historique commence avec le prochain morceau que tu lances.",
+ "diag_metrics_title": "Métriques YouTube",
+ "diag_refresh": "Actualiser",
+ "diag_metrics_reset": "Réinitialiser les métriques",
+ "diag_loading": "Chargement…",
+ "diag_metrics_empty": "Aucune donnée pour l'instant. Joue quelques pistes pour collecter de la télémétrie.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Succès",
+ "diag_metrics_fail": "Échecs",
+ "diag_metrics_last_error": "Dernière erreur",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "Moteur JS",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Actif",
+ "diag_potoken_minting_pending": "En attente (plusieurs semaines)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Expiré",
+ "diag_potoken_visitor_active": "Actif — expire dans {{seconds}}s",
+ "diag_potoken_visitor_active_unknown": "Actif",
+ "diag_potoken_visitor_none": "Pas de token",
+ "diag_potoken_cache_count": "Tokens en cache",
+ "diag_potoken_last_generated": "Généré le",
+ "diag_loop_title": "Extension Loop (cookies YouTube)",
+ "diag_loop_missing": "Fichier de cookies introuvable.",
+ "diag_loop_missing_hint": "Installe l'extension Loop dans ton navigateur et exporte les cookies vers le chemin indiqué.",
+ "diag_loop_no_youtube": "Le fichier existe mais sans cookies YouTube.",
+ "diag_loop_no_youtube_hint": "Ouvre youtube.com dans ton navigateur avec l'extension Loop installée et connecte-toi. Les cookies apparaîtront ici tout seuls.",
+ "diag_loop_ready": "Cookies YouTube prêts.",
+ "retry": "Réessayer",
+ "speed_dial_search": "Rechercher",
+ "speed_dial_library": "Bibliothèque",
+ "speed_dial_playlists": "Playlists",
+ "speed_dial_favorites": "Favoris",
+ "speed_dial_history": "Historique",
+ "speed_dial_trending": "Tendances",
+ "speed_dial_albums": "Albums",
+ "speed_dial_artists": "Artistes",
+ "speed_dial_genres": "Genres",
+ "shelf_recent_albums": "Ajoutés récemment",
+ "shelf_recent_albums_empty": "Indique un dossier de musique dans le menu pour scanner tes albums.",
+ "shelf_artists": "Artistes",
+ "shelf_artists_empty": "Aucun artiste indexé pour l'instant.",
+ "explore_youtube_cta": "Explorer sur YouTube",
+ "explore_youtube_cta_body": "Découvertes, classements, nouveautés et abonnements.",
+ "pull_to_refresh_hint": "Relâche pour actualiser",
+ "pull_to_refresh_release": "Actualisation…",
+ "loading": "Chargement…",
+ "play_count_today": "Reprends là où tu en étais",
+ "history_empty_title": "Ton historique démarre quand tu lances quelque chose",
+ "history_empty_cta": "Chercher sur YouTube",
+ "back": "Retour",
+ "play_all": "Tout lire",
+ "shuffle_play": "Aléatoire",
+ "save_playlist": "Enregistrer",
+ "share": "Partager",
+ "share_copied": "Lien copié",
+ "expandable_more": "voir plus",
+ "expandable_less": "voir moins",
+ "album_loading_error": "Impossible de charger cet album.",
+ "playlist_loading_error": "Impossible de charger cette playlist.",
+ "album_empty": "Cet album n'a aucune piste disponible.",
+ "playlist_empty": "Cette playlist est vide.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Titres",
+ "tab_videos": "Vidéos",
+ "tab_about": "À propos",
+ "shuffle_radio": "Radio aléatoire",
+ "no_description": "Pas de description.",
+ "my_playlists_title": "Mes playlists",
+ "my_playlists_subtitle": "Tes listes locales construites à partir de YouTube.",
+ "my_playlists_empty_title": "Pas encore de playlist",
+ "my_playlists_empty_body": "Crées-en une — rien ne sort de ta machine.",
+ "my_playlists_create": "Nouvelle playlist",
+ "my_playlists_create_title": "Créer une playlist",
+ "my_playlists_form_name": "Nom",
+ "my_playlists_form_name_placeholder": "Ex : Pour étudier",
+ "my_playlists_form_description": "Description (facultatif)",
+ "my_playlists_form_save": "Créer",
+ "my_playlists_form_cancel": "Annuler",
+ "my_playlists_delete_confirm_title": "Supprimer la playlist ?",
+ "my_playlists_delete_confirm_body": "Les {{count}} pistes restent sur YouTube — seule ta liste locale disparaît.",
+ "my_playlists_delete_confirm_empty": "Ta liste locale disparaît. Action irréversible.",
+ "my_playlists_delete_confirm_action": "Supprimer la playlist",
+ "my_playlists_delete_confirm_cancel": "Annuler",
+ "my_playlists_rename_aria": "Renommer la playlist",
+ "my_playlists_settings_aria": "Actions de la playlist",
+ "my_playlists_open_aria": "Ouvrir la playlist",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "Retirer {{title}} de la playlist",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "Ajouter depuis YouTube",
+ "add_to_playlist_search_placeholder": "Cherche une vidéo à ajouter…",
+ "add_to_playlist_search_short": "Tape au moins 2 caractères.",
+ "add_to_playlist_close": "Fermer",
+ "add_to_playlist_added": "Ajoutée à la playlist",
+ "rename_inline_placeholder": "Nom de la playlist",
+ "tracks_count_n": "{{count}} pistes",
+ "track_count_one": "1 piste",
+ "playlist_empty_cta": "Ajouter depuis YouTube",
+ "shelf_spotify_recent": "Spotify · Récemment écoutés",
+ "shelf_soundcloud_likes": "SoundCloud · Tes coups de cœur",
+ "history_filter_all": "Tous",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "Chapitres",
+ "chapters_empty": "Pas de chapitres disponibles",
+ "video_mode_toggle": "Mode vidéo",
+ "video_mode_only_youtube": "Vidéo disponible uniquement pour les pistes YouTube",
+ "expand_video": "Ouvrir la vidéo en plein écran",
+ "watch_title": "Regarder",
+ "watch_video_unavailable": "Vidéo indisponible pour cette piste",
+ "watch_back": "Retour à Music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Tape un titre, un artiste ou un album pour chercher dans ta bibliothèque locale.",
+ "history_now": "maintenant",
+ "history_unplayable": "Impossible de lire cette entrée — le morceau n'est plus disponible.",
+ "history_clear_confirm_yt": "Ceci va effacer tout ton historique YouTube. Continuer ?",
+ "history_clear_confirm_local": "Ceci va effacer tout ton historique local. Continuer ?",
+ "history_clear": "Effacer",
+ "history_title": "Historique",
+ "history_title_yt": "Historique YouTube",
+ "history_empty_title_yt": "Ton historique YouTube commence quand tu lis quelque chose",
+ "history_empty_cta_yt": "Chercher sur YouTube",
+ "history_empty_title_local": "Ton historique commence quand tu lis quelque chose de ta bibliothèque",
+ "history_empty_cta_local": "Chercher dans la bibliothèque",
+ "history_filter_local": "Local",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Filtrer par source",
+ "history_remove_aria": "Retirer de l'historique",
+ "history_entries_removed": "entrées supprimées",
+ "youtube": {
+ "shelf_group": "Depuis YouTube",
+ "shelf_charts": "Charts musicaux",
+ "shelf_charts_empty": "Les charts ne répondent pas. Réessaye dans un moment.",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "Pas de nouveautés pour l'instant. Reviens demain.",
+ "shelf_moods_and_genres": "Ambiances et genres",
+ "moods_empty": "Ambiances indisponibles. Réessaye dans un moment.",
+ "shelf_trending": "Tendances",
+ "shelf_trending_error": "YouTube est injoignable. Réessaye dans quelques minutes.",
+ "shelf_quick_picks": "Pour toi",
+ "shelf_quick_picks_empty": "On apprend encore ce que tu aimes. Lance quelques morceaux pour démarrer.",
+ "shelf_daily_discover": "Découverte du jour",
+ "shelf_daily_discover_empty": "Lance un morceau que tu aimes et on te suggère la suite.",
+ "shelf_continue_watching": "Reprendre",
+ "shelf_continue_watching_empty": "Rien à reprendre pour l'instant. Lance quelque chose pour commencer.",
+ "shelf_subscriptions": "Abonnements",
+ "shelf_subscriptions_empty": "Suis une chaîne pour voir les nouveautés ici.",
+ "explore_title": "Explorer",
+ "explore_tagline": "Découvre de la nouvelle musique sans rien décider.",
+ "back_to_explore": "Retour à Explorer",
+ "mood_loading_error": "Impossible de charger cette ambiance. Réessaye.",
+ "mood_empty": "Cette ambiance n'a aucune playlist pour l'instant. Peut-être plus tard.",
+ "hub_title": "YouTube",
+ "hub_tagline": "Musique et vidéos YouTube en un seul endroit.",
+ "search_filter_aria": "Filtrer les résultats",
+ "search_filter_all": "Tout",
+ "search_filter_music": "Musique",
+ "search_filter_videos": "Vidéos",
+ "search_filter_channels": "Chaînes",
+ "search_filter_playlists": "Playlists",
+ "search_sort_aria": "Trier les résultats",
+ "search_sort_relevance": "Pertinence",
+ "search_sort_recent": "Plus récents",
+ "search_sort_views": "Plus vus",
+ "search_history_label": "Recherches récentes",
+ "search_history_clear": "Effacer l'historique",
+ "search_history_remove_aria": "Retirer \"{{query}}\" de l'historique",
+ "subscribers_count_label": "abonnés",
+ "creator_by": "Par {{name}}",
+ "channel_subscribe": "S'abonner",
+ "channel_subscribed": "Abonné",
+ "channel_unsubscribe_aria": "Se désabonner",
+ "channel_no_items": "Rien ici pour l'instant.",
+ "search_placeholder": "Rechercher sur YouTube…",
+ "search_hint": "Commencez à taper pour voir vidéos, chaînes et playlists.",
+ "connect_title": "Connecte ton compte YouTube",
+ "connect_body": "Ta bibliothèque, abonnements et ce que tu regardais apparaissent ici une fois connecté. Sans compte, seules Recherche et Découvrir fonctionnent (anonyme).",
+ "connect_step_missing_label": "Comment se connecter",
+ "connect_step_missing": "Installe l'extension Loop dans ton navigateur et exporte les cookies vers le chemin ci-dessous. Reviens ici — l'app détecte toute seule.",
+ "connect_step_no_youtube_label": "Presque",
+ "connect_step_no_youtube": "Loop est installé mais tu n'es pas connecté à YouTube dans ton navigateur. Ouvre youtube.com et connecte-toi — les cookies arriveront ici automatiquement.",
+ "connect_cta_setup": "Configurer la connexion",
+ "connect_cta_anon": "Explorer anonymement",
+ "connect_footnote": "Les cookies restent sur ton ordinateur — rien n'est envoyé à nos serveurs.",
+ "anon_speed_dial_aria": "Accès anonyme à YouTube"
+ },
+ "spotify_connected": "Connecté à Spotify",
+ "spotify_auth_failed": "Échec de l'authentification",
+ "spotify_library_updated": "Bibliothèque mise à jour",
+ "spotify_auth_waiting": "En attente d'autorisation dans le navigateur. Reviens ici après avoir accepté.",
+ "spotify_disconnected": "Déconnecté de Spotify",
+ "spotify_play_via_yt": "Lecture via YouTube (mode Free)",
+ "spotify_search_aria": "Chercher sur Spotify",
+ "spotify_search_label": "Chercher",
+ "spotify_refresh_label": "Rafraîchir",
+ "spotify_prev_aria": "Précédent",
+ "spotify_next_aria": "Suivant"
},
"library": {
"title": "Bibliothèque",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "Paramètres",
"placeholder": "Préférences du plugin et nouvelle analyse de la bibliothèque.",
+ "tab_diagnostic": "Diagnostic",
+ "saving": "Enregistrement…",
+ "saved": "Enregistré",
+ "categories_aria": "Catégories",
"library_section": "Bibliothèque",
"rescan": "Ré-analyser la bibliothèque",
"rescan_desc": "Reparcourir le dossier de téléchargements et actualiser les cours, modules et leçons.",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "{{count}} problème(s) trouvé(s)",
"verify_failed_toast": "Échec de la vérification de la bibliothèque : {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Suivi de colis",
+ "subtitle_summary": "{{count}} colis · {{in_transit}} en transit",
+ "subtitle_empty": "Suivez les colis des principaux transporteurs brésiliens.",
+ "privacy_show_title": "Afficher les codes",
+ "privacy_hide_title": "Masquer les codes (mode streamer)",
+ "privacy_button": "Privé",
+ "refresh_all": "Tout actualiser",
+ "refresh_all_busy": "Actualisation…",
+ "refresh_all_title": "Actualiser tous les colis",
+ "add_button": "+ Ajouter",
+ "search_placeholder": "Rechercher par code, alias ou statut…",
+ "tab": {
+ "all": "Tous",
+ "in_transit": "En transit",
+ "awaiting": "En attente",
+ "delivered": "Livrés",
+ "delayed": "En retard",
+ "archived": "Archivés"
+ },
+ "empty": {
+ "none_title": "Aucun colis suivi",
+ "none_desc": "Ajoutez un code de suivi pour suivre vos livraisons.",
+ "none_cta": "Ajouter un premier colis",
+ "in_transit": "Aucun colis en transit.",
+ "awaiting": "Aucun colis en attente de retrait.",
+ "delivered": "Aucun colis livré pour le moment.",
+ "delayed": "Aucun colis en retard.",
+ "archived": "Aucun colis archivé.",
+ "nothing": "Rien ici.",
+ "search": "Aucun colis ne correspond à « {{query}} »."
+ },
+ "card": {
+ "delivered": "Livré",
+ "days_one": "1 jour en transit",
+ "days_other": "{{count}} jours en transit",
+ "no_events": "Aucun événement",
+ "awaiting_first": "En attente du premier suivi…",
+ "archived_label": "Archivé"
+ },
+ "rel": {
+ "now": "à l'instant",
+ "minutes": "il y a {{count}} min",
+ "hours": "il y a {{count}} h"
+ },
+ "menu": {
+ "refresh": "Actualiser",
+ "refreshing": "Actualisation…",
+ "copy_code": "Copier le code",
+ "rename": "Renommer",
+ "unarchive": "Désarchiver",
+ "remove": "Supprimer"
+ },
+ "loading": "Chargement…",
+ "error_prefix": "Erreur",
+ "toast": {
+ "added": "Colis ajouté, actualisation…",
+ "copied": "Code copié",
+ "copy_failed": "Impossible de copier",
+ "refresh_failed": "Échec de la mise à jour ({{error}})",
+ "offline": "Hors ligne — mise à jour reportée",
+ "refresh_done": "Mise à jour terminée",
+ "package_removed": "Colis supprimé",
+ "archived": "Colis archivé",
+ "unarchived": "Colis désarchivé",
+ "cpf_updated": "CPF mis à jour",
+ "status_changed": "{{code}} : {{status}}"
+ },
+ "rename_prompt": "Alias du colis",
+ "add_dialog": {
+ "title": "Ajouter un colis",
+ "close": "Fermer",
+ "code_label": "Code de suivi *",
+ "code_placeholder": "Ex : AB123456789BR",
+ "alias_label": "Alias (facultatif)",
+ "alias_placeholder": "Ex : Nouvelles baskets",
+ "cpf_label": "CPF du destinataire *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "Le transporteur exige un CPF pour la consultation.",
+ "detecting": "Détection du transporteur…",
+ "detected": "Transporteur : {{carrier}}",
+ "requires_cpf_suffix": "· CPF requis",
+ "error_code_required": "Saisissez le code de suivi.",
+ "error_cpf_required": "Ce transporteur exige un CPF.",
+ "cancel": "Annuler",
+ "submit": "Enregistrer",
+ "submitting": "Enregistrement…"
+ },
+ "remove_dialog": {
+ "title": "Supprimer le colis",
+ "question": "Voulez-vous vraiment supprimer {{name}} ?",
+ "sub": "Les événements suivis seront également supprimés.",
+ "cancel": "Annuler",
+ "confirm": "Supprimer",
+ "confirming": "Suppression…",
+ "close": "Fermer"
+ },
+ "archive_prompt": {
+ "title": "Colis livré 🎉",
+ "body": "Voulez-vous archiver ce colis ? Il sortira de la liste active mais l'historique sera conservé.",
+ "keep": "Non, garder",
+ "archive": "Archiver"
+ },
+ "detail": {
+ "back": "← Suivi",
+ "not_found_title": "Colis introuvable",
+ "not_found_body": "Ce colis a peut-être été supprimé.",
+ "not_found_back": "Retour à la liste",
+ "awaiting_first": "En attente du premier suivi",
+ "refresh_failed_title": "La dernière mise à jour a échoué.",
+ "retry": "Réessayer",
+ "archived_pill": "Archivé",
+ "delivered_pill": "Livré",
+ "days_one_pill": "1 jour en transit",
+ "days_other_pill": "{{count}} jours en transit",
+ "action": {
+ "refresh": "Actualiser",
+ "refreshing": "Actualisation…",
+ "rename": "Renommer",
+ "add_cpf": "Ajouter un CPF",
+ "archive": "Archiver",
+ "unarchive": "Désarchiver",
+ "remove": "Supprimer"
+ },
+ "meta": {
+ "code": "Code",
+ "cpf": "CPF",
+ "route": "Trajet",
+ "posted_at": "Posté le",
+ "updated": "Mis à jour",
+ "copy_code_title": "Copier le code",
+ "edit": "Modifier"
+ },
+ "cpf_dialog": {
+ "title_add": "Ajouter un CPF",
+ "title_edit": "Modifier le CPF",
+ "label": "CPF du destinataire",
+ "placeholder": "000.000.000-00",
+ "hint": "Laissez vide pour supprimer.",
+ "cancel": "Annuler",
+ "submit": "Enregistrer",
+ "submitting": "Enregistrement…",
+ "close": "Fermer"
+ },
+ "history": {
+ "title": "Historique",
+ "empty": "Aucun événement enregistré."
+ }
+ },
+ "status": {
+ "preadvice": "Commande créée",
+ "picked_up": "Posté",
+ "in_transit": "En transit",
+ "in_warehouse": "Au centre de distribution",
+ "customs": "En dédouanement",
+ "customs_held": "Retenu en douane",
+ "customs_cleared": "Dédouané",
+ "out_for_delivery": "En cours de livraison",
+ "awaiting_pickup": "En attente de retrait",
+ "delivered": "Livré",
+ "delivery_failure": "Tentative de livraison échouée",
+ "delayed": "En retard",
+ "returning_to_sender": "En retour",
+ "returned_to_sender": "Retourné à l'expéditeur",
+ "damaged": "Endommagé",
+ "unknown": "Statut inconnu"
+ },
+ "carrier": {
+ "unknown": "Inconnu"
+ },
+ "settings": {
+ "title": "Paramètres",
+ "subtitle": "Préférences de notification du suivi.",
+ "notifications_label": "Me notifier lors d'un changement de statut",
+ "notifications_hint": "Affiche une notification système lorsqu'un colis change d'étape (ex. en livraison, livré).",
+ "test_notification": "Envoyer une notification test",
+ "test_busy": "Envoi…",
+ "test_toast_sent": "Notification de test envoyée",
+ "test_failed": "Impossible d'envoyer la notification",
+ "permission_denied_toast": "Les notifications sont désactivées au niveau du système. Activez-les dans les paramètres de votre SE.",
+ "permission_denied_banner": "Notifications système désactivées",
+ "permission_denied_hint": "Autorisez les notifications d'Omniget dans les paramètres du système d'exploitation pour recevoir les mises à jour des colis.",
+ "request_permission": "Demander l'autorisation"
+ },
+ "notification": {
+ "title_template": "{{code}} : {{status}}",
+ "body_fallback": "Statut mis à jour",
+ "test_title": "Les notifications de suivi fonctionnent",
+ "test_body": "Vous verrez ce type de notification lorsque vos colis évoluent."
+ }
}
}
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index c9876963..bdc02270 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "Ferma",
"confirm_remove": "Rimuovere questo download?",
+ "quality_hint": "Qualità in download per questo elemento",
"stats_line": "{{count}} download · {{size}} salvati",
"filter_label": "Filtra download per stato",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — leggero",
"quality_480p": "Medio (480p) — veloce",
"quality_360p": "Basso (360p) — molto leggero",
+ "quality_best_short": "Migliore",
+ "quality_audio": "Audio",
"view_formats": "Mostra formati",
"hide_formats": "Nascondi formati",
"no_formats": "Nessun formato disponibile per questo video",
@@ -404,6 +407,7 @@
"preset_custom": "Personalizzato",
"formats_presets_label": "Preset del formato",
"formats_merge_note": "I formati video (V) verranno automaticamente uniti con l'audio (A) se FFmpeg è disponibile.",
+ "formats_playlist_note": "La selezione del formato per video non si applica alle playlist. L'opzione Qualità sopra vale per ogni video.",
"referer_label": "Referer (opzionale)",
"referer_placeholder": "https://example.com",
"external_url_ready": "URL ricevuto dall'estensione Chrome",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "Niente in sospeso qui. Metti qualcosa per riprenderlo dopo.",
+ "shelf_recent": "Ascoltati di recente",
+ "shelf_recent_empty": "La tua cronologia inizia con il prossimo brano che farai partire.",
+ "diag_metrics_title": "Metriche YouTube",
+ "diag_refresh": "Aggiorna",
+ "diag_metrics_reset": "Reimposta metriche",
+ "diag_loading": "Caricamento…",
+ "diag_metrics_empty": "Nessun dato ancora. Riproduci alcuni brani per raccogliere telemetria.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Successi",
+ "diag_metrics_fail": "Fallimenti",
+ "diag_metrics_last_error": "Ultimo errore",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "Motore JS",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Attivo",
+ "diag_potoken_minting_pending": "In attesa (più settimane)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Scaduto",
+ "diag_potoken_visitor_active": "Attivo — scade tra {{seconds}}s",
+ "diag_potoken_visitor_active_unknown": "Attivo",
+ "diag_potoken_visitor_none": "Nessun token",
+ "diag_potoken_cache_count": "Token in cache",
+ "diag_potoken_last_generated": "Generato il",
+ "diag_loop_title": "Estensione Loop (cookie YouTube)",
+ "diag_loop_missing": "File dei cookie non trovato.",
+ "diag_loop_missing_hint": "Installa l'estensione Loop nel browser ed esporta i cookie nel percorso mostrato.",
+ "diag_loop_no_youtube": "Il file esiste ma senza cookie di YouTube.",
+ "diag_loop_no_youtube_hint": "Apri youtube.com nel browser con l'estensione Loop installata e fai login. I cookie compaiono qui da soli.",
+ "diag_loop_ready": "Cookie YouTube pronti.",
+ "retry": "Riprova",
+ "speed_dial_search": "Cerca",
+ "speed_dial_library": "Libreria",
+ "speed_dial_playlists": "Playlist",
+ "speed_dial_favorites": "Preferiti",
+ "speed_dial_history": "Cronologia",
+ "speed_dial_trending": "Tendenze",
+ "speed_dial_albums": "Album",
+ "speed_dial_artists": "Artisti",
+ "speed_dial_genres": "Generi",
+ "shelf_recent_albums": "Aggiunti di recente",
+ "shelf_recent_albums_empty": "Indica una cartella di musica nel menu per scansionare i tuoi album.",
+ "shelf_artists": "Artisti",
+ "shelf_artists_empty": "Nessun artista indicizzato ancora.",
+ "explore_youtube_cta": "Esplora su YouTube",
+ "explore_youtube_cta_body": "Scoperte, classifiche, nuove uscite e iscrizioni.",
+ "pull_to_refresh_hint": "Rilascia per aggiornare",
+ "pull_to_refresh_release": "Aggiornamento…",
+ "loading": "Caricamento…",
+ "play_count_today": "Riprendi da dove eri rimasto",
+ "history_empty_title": "La tua cronologia parte quando fai partire qualcosa",
+ "history_empty_cta": "Cerca su YouTube",
+ "back": "Indietro",
+ "play_all": "Riproduci tutto",
+ "shuffle_play": "Casuale",
+ "save_playlist": "Salva",
+ "share": "Condividi",
+ "share_copied": "Link copiato",
+ "expandable_more": "altro",
+ "expandable_less": "meno",
+ "album_loading_error": "Impossibile caricare l'album.",
+ "playlist_loading_error": "Impossibile caricare la playlist.",
+ "album_empty": "Questo album non ha tracce disponibili.",
+ "playlist_empty": "Questa playlist è vuota.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Brani",
+ "tab_videos": "Video",
+ "tab_about": "Info",
+ "shuffle_radio": "Radio casuale",
+ "no_description": "Nessuna descrizione.",
+ "my_playlists_title": "Le mie playlist",
+ "my_playlists_subtitle": "Le tue liste locali costruite con video di YouTube.",
+ "my_playlists_empty_title": "Nessuna playlist",
+ "my_playlists_empty_body": "Creane una a modo tuo — non esce nulla da qui.",
+ "my_playlists_create": "Nuova playlist",
+ "my_playlists_create_title": "Crea playlist",
+ "my_playlists_form_name": "Nome",
+ "my_playlists_form_name_placeholder": "Es: Per studiare",
+ "my_playlists_form_description": "Descrizione (facoltativa)",
+ "my_playlists_form_save": "Crea",
+ "my_playlists_form_cancel": "Annulla",
+ "my_playlists_delete_confirm_title": "Eliminare la playlist?",
+ "my_playlists_delete_confirm_body": "Le {{count}} tracce restano su YouTube — sparisce solo la lista locale.",
+ "my_playlists_delete_confirm_empty": "La lista locale sparisce. Non si torna indietro.",
+ "my_playlists_delete_confirm_action": "Elimina playlist",
+ "my_playlists_delete_confirm_cancel": "Annulla",
+ "my_playlists_rename_aria": "Rinomina playlist",
+ "my_playlists_settings_aria": "Azioni della playlist",
+ "my_playlists_open_aria": "Apri playlist",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "Rimuovi {{title}} dalla playlist",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "Aggiungi da YouTube",
+ "add_to_playlist_search_placeholder": "Cerca un video da aggiungere…",
+ "add_to_playlist_search_short": "Scrivi almeno 2 caratteri.",
+ "add_to_playlist_close": "Chiudi",
+ "add_to_playlist_added": "Aggiunta alla playlist",
+ "rename_inline_placeholder": "Nome della playlist",
+ "tracks_count_n": "{{count}} tracce",
+ "track_count_one": "1 traccia",
+ "playlist_empty_cta": "Aggiungi da YouTube",
+ "shelf_spotify_recent": "Spotify · Ascoltati di recente",
+ "shelf_soundcloud_likes": "SoundCloud · I tuoi like",
+ "history_filter_all": "Tutti",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "Capitoli",
+ "chapters_empty": "Nessun capitolo disponibile",
+ "video_mode_toggle": "Modalità video",
+ "video_mode_only_youtube": "Video disponibile solo per le tracce YouTube",
+ "expand_video": "Apri video a schermo intero",
+ "watch_title": "Guarda",
+ "watch_video_unavailable": "Video non disponibile per questa traccia",
+ "watch_back": "Torna a Music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Scrivi titolo, artista o album per cercare nella tua libreria locale.",
+ "history_now": "ora",
+ "history_unplayable": "Non posso riprodurre questa voce — il brano non è più disponibile.",
+ "history_clear_confirm_yt": "Questo cancellerà tutta la cronologia YouTube. Continuare?",
+ "history_clear_confirm_local": "Questo cancellerà tutta la cronologia locale. Continuare?",
+ "history_clear": "Cancella",
+ "history_title": "Cronologia",
+ "history_title_yt": "Cronologia YouTube",
+ "history_empty_title_yt": "La cronologia YouTube parte quando riproduci qualcosa",
+ "history_empty_cta_yt": "Cerca su YouTube",
+ "history_empty_title_local": "La cronologia parte quando riproduci qualcosa dalla libreria",
+ "history_empty_cta_local": "Cerca nella libreria",
+ "history_filter_local": "Locale",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Filtra per fonte",
+ "history_remove_aria": "Rimuovi dalla cronologia",
+ "history_entries_removed": "voci rimosse",
+ "youtube": {
+ "shelf_group": "Da YouTube",
+ "shelf_charts": "Classifiche musicali",
+ "shelf_charts_empty": "Classifiche non disponibili ora. Riprova tra poco.",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "Nessuna novità per ora. Torna domani.",
+ "shelf_moods_and_genres": "Mood e generi",
+ "moods_empty": "Mood non disponibili ora. Riprova tra poco.",
+ "shelf_trending": "Di tendenza ora",
+ "shelf_trending_error": "YouTube non risponde ora. Riprova tra qualche minuto.",
+ "shelf_quick_picks": "Per te",
+ "shelf_quick_picks_empty": "Stiamo imparando i tuoi gusti. Metti qualche brano per iniziare.",
+ "shelf_daily_discover": "Scoperta del giorno",
+ "shelf_daily_discover_empty": "Metti un brano che ti piace e ti suggeriamo cosa potrebbe venire dopo.",
+ "shelf_continue_watching": "Continua a guardare",
+ "shelf_continue_watching_empty": "Niente da riprendere ancora. Riproduci qualcosa per iniziare.",
+ "shelf_subscriptions": "Iscrizioni",
+ "shelf_subscriptions_empty": "Segui un canale per vedere le novità qui.",
+ "explore_title": "Esplora",
+ "explore_tagline": "Scopri nuova musica senza impegnarti.",
+ "back_to_explore": "Torna a Esplora",
+ "mood_loading_error": "Non sono riuscito a caricare questo mood. Riprova.",
+ "mood_empty": "Questo mood non ha playlist ora. Magari più tardi.",
+ "hub_title": "YouTube",
+ "hub_tagline": "Musica e video di YouTube in un unico posto.",
+ "search_filter_aria": "Filtra i risultati",
+ "search_filter_all": "Tutto",
+ "search_filter_music": "Musica",
+ "search_filter_videos": "Video",
+ "search_filter_channels": "Canali",
+ "search_filter_playlists": "Playlist",
+ "search_sort_aria": "Ordina i risultati",
+ "search_sort_relevance": "Pertinenza",
+ "search_sort_recent": "Più recenti",
+ "search_sort_views": "Più visti",
+ "search_history_label": "Ricerche recenti",
+ "search_history_clear": "Cancella cronologia",
+ "search_history_remove_aria": "Rimuovi \"{{query}}\" dalla cronologia",
+ "subscribers_count_label": "iscritti",
+ "creator_by": "Di {{name}}",
+ "channel_subscribe": "Iscriviti",
+ "channel_subscribed": "Iscritto",
+ "channel_unsubscribe_aria": "Disiscrivermi",
+ "channel_no_items": "Niente qui per ora.",
+ "search_placeholder": "Cerca su YouTube…",
+ "search_hint": "Inizia a digitare per vedere video, canali e playlist.",
+ "connect_title": "Collega il tuo account YouTube",
+ "connect_body": "Libreria, iscrizioni e dove avevi lasciato compaiono qui dopo aver collegato. Senza account, funzionano solo Cerca ed Esplora (anonimi).",
+ "connect_step_missing_label": "Come collegare",
+ "connect_step_missing": "Installa l'estensione Loop nel browser ed esporta i cookie nel percorso qui sotto. Torna qui — l'app rileva da sola.",
+ "connect_step_no_youtube_label": "Quasi fatto",
+ "connect_step_no_youtube": "Loop è installato ma manca il login a YouTube nel browser. Apri youtube.com e accedi — i cookie arrivano qui automaticamente.",
+ "connect_cta_setup": "Configura connessione",
+ "connect_cta_anon": "Esplora senza account",
+ "connect_footnote": "I cookie restano sul tuo computer — niente viene inviato ai nostri server.",
+ "anon_speed_dial_aria": "Accesso anonimo a YouTube"
+ },
+ "spotify_connected": "Connesso a Spotify",
+ "spotify_auth_failed": "Autenticazione fallita",
+ "spotify_library_updated": "Libreria aggiornata",
+ "spotify_auth_waiting": "In attesa di autorizzazione nel browser. Torna qui dopo aver accettato.",
+ "spotify_disconnected": "Disconnesso da Spotify",
+ "spotify_play_via_yt": "In riproduzione via YouTube (modalità Free)",
+ "spotify_search_aria": "Cerca su Spotify",
+ "spotify_search_label": "Cerca",
+ "spotify_refresh_label": "Aggiorna",
+ "spotify_prev_aria": "Precedente",
+ "spotify_next_aria": "Successivo"
},
"library": {
"title": "Libreria",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "Impostazioni",
"placeholder": "Preferenze del plugin e nuova scansione della libreria.",
+ "tab_diagnostic": "Diagnostica",
+ "saving": "Salvataggio…",
+ "saved": "Salvato",
+ "categories_aria": "Categorie",
"library_section": "Libreria",
"rescan": "Ri-scansiona libreria",
"rescan_desc": "Scansiona di nuovo la cartella download e aggiorna corsi, moduli e lezioni.",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "{{count}} problema/i trovato/i",
"verify_failed_toast": "Verifica libreria fallita: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Tracciamento pacchi",
+ "subtitle_summary": "{{count}} pacco(i) · {{in_transit}} in transito",
+ "subtitle_empty": "Segui spedizioni dei principali corrieri brasiliani.",
+ "privacy_show_title": "Mostra codici",
+ "privacy_hide_title": "Nascondi codici (modalità streamer)",
+ "privacy_button": "Privato",
+ "refresh_all": "Aggiorna tutto",
+ "refresh_all_busy": "Aggiornamento…",
+ "refresh_all_title": "Aggiorna tutti i pacchi",
+ "add_button": "+ Aggiungi",
+ "search_placeholder": "Cerca per codice, alias o stato…",
+ "tab": {
+ "all": "Tutti",
+ "in_transit": "In transito",
+ "awaiting": "In attesa",
+ "delivered": "Consegnati",
+ "delayed": "In ritardo",
+ "archived": "Archiviati"
+ },
+ "empty": {
+ "none_title": "Nessun pacco tracciato",
+ "none_desc": "Aggiungi un codice di tracciamento per seguire le consegne.",
+ "none_cta": "Aggiungi primo pacco",
+ "in_transit": "Nessun pacco in transito.",
+ "awaiting": "Nessun pacco in attesa di ritiro.",
+ "delivered": "Nessun pacco ancora consegnato.",
+ "delayed": "Nessun pacco in ritardo.",
+ "archived": "Nessun pacco archiviato.",
+ "nothing": "Niente qui.",
+ "search": "Nessun pacco corrisponde a \"{{query}}\"."
+ },
+ "card": {
+ "delivered": "Consegnato",
+ "days_one": "1 giorno in transito",
+ "days_other": "{{count}} giorni in transito",
+ "no_events": "Nessun evento",
+ "awaiting_first": "In attesa del primo aggiornamento…",
+ "archived_label": "Archiviato"
+ },
+ "rel": {
+ "now": "ora",
+ "minutes": "{{count}} min fa",
+ "hours": "{{count}} h fa"
+ },
+ "menu": {
+ "refresh": "Aggiorna",
+ "refreshing": "Aggiornamento…",
+ "copy_code": "Copia codice",
+ "rename": "Rinomina",
+ "unarchive": "Disarchivia",
+ "remove": "Rimuovi"
+ },
+ "loading": "Caricamento…",
+ "error_prefix": "Errore",
+ "toast": {
+ "added": "Pacco aggiunto, aggiornamento…",
+ "copied": "Codice copiato",
+ "copy_failed": "Impossibile copiare",
+ "refresh_failed": "Impossibile aggiornare ({{error}})",
+ "offline": "Offline — aggiornamento rinviato",
+ "refresh_done": "Aggiornamento completato",
+ "package_removed": "Pacco rimosso",
+ "archived": "Pacco archiviato",
+ "unarchived": "Pacco disarchiviato",
+ "cpf_updated": "CPF aggiornato",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "Alias del pacco",
+ "add_dialog": {
+ "title": "Aggiungi pacco",
+ "close": "Chiudi",
+ "code_label": "Codice di tracciamento *",
+ "code_placeholder": "Es: AB123456789BR",
+ "alias_label": "Alias (opzionale)",
+ "alias_placeholder": "Es: Scarpe nuove",
+ "cpf_label": "CPF del destinatario *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "Il corriere richiede CPF per la consultazione.",
+ "detecting": "Rilevamento corriere…",
+ "detected": "Corriere: {{carrier}}",
+ "requires_cpf_suffix": "· CPF obbligatorio",
+ "error_code_required": "Inserisci il codice di tracciamento.",
+ "error_cpf_required": "Questo corriere richiede CPF.",
+ "cancel": "Annulla",
+ "submit": "Salva",
+ "submitting": "Salvataggio…"
+ },
+ "remove_dialog": {
+ "title": "Rimuovi pacco",
+ "question": "Sei sicuro di voler rimuovere {{name}}?",
+ "sub": "Anche gli eventi tracciati saranno eliminati.",
+ "cancel": "Annulla",
+ "confirm": "Rimuovi",
+ "confirming": "Rimozione…",
+ "close": "Chiudi"
+ },
+ "archive_prompt": {
+ "title": "Pacco consegnato 🎉",
+ "body": "Vuoi archiviare questo pacco? Esce dalla lista attiva ma la cronologia rimane.",
+ "keep": "No, mantieni",
+ "archive": "Archivia"
+ },
+ "detail": {
+ "back": "← Tracciamento",
+ "not_found_title": "Pacco non trovato",
+ "not_found_body": "Questo pacco potrebbe essere stato rimosso.",
+ "not_found_back": "Torna alla lista",
+ "awaiting_first": "In attesa del primo aggiornamento",
+ "refresh_failed_title": "Ultimo aggiornamento fallito.",
+ "retry": "Riprova",
+ "archived_pill": "Archiviato",
+ "delivered_pill": "Consegnato",
+ "days_one_pill": "1 giorno in transito",
+ "days_other_pill": "{{count}} giorni in transito",
+ "action": {
+ "refresh": "Aggiorna",
+ "refreshing": "Aggiornamento…",
+ "rename": "Rinomina",
+ "add_cpf": "Aggiungi CPF",
+ "archive": "Archivia",
+ "unarchive": "Disarchivia",
+ "remove": "Rimuovi"
+ },
+ "meta": {
+ "code": "Codice",
+ "cpf": "CPF",
+ "route": "Percorso",
+ "posted_at": "Spedito il",
+ "updated": "Aggiornato",
+ "copy_code_title": "Copia codice",
+ "edit": "Modifica"
+ },
+ "cpf_dialog": {
+ "title_add": "Aggiungi CPF",
+ "title_edit": "Modifica CPF",
+ "label": "CPF del destinatario",
+ "placeholder": "000.000.000-00",
+ "hint": "Lascia vuoto per rimuovere.",
+ "cancel": "Annulla",
+ "submit": "Salva",
+ "submitting": "Salvataggio…",
+ "close": "Chiudi"
+ },
+ "history": {
+ "title": "Cronologia",
+ "empty": "Nessun evento registrato."
+ }
+ },
+ "status": {
+ "preadvice": "Ordine creato",
+ "picked_up": "Spedito",
+ "in_transit": "In transito",
+ "in_warehouse": "Al centro di distribuzione",
+ "customs": "In sdoganamento",
+ "customs_held": "Bloccato in dogana",
+ "customs_cleared": "Sdoganato",
+ "out_for_delivery": "In consegna",
+ "awaiting_pickup": "In attesa di ritiro",
+ "delivered": "Consegnato",
+ "delivery_failure": "Tentativo di consegna fallito",
+ "delayed": "In ritardo",
+ "returning_to_sender": "In restituzione",
+ "returned_to_sender": "Restituito al mittente",
+ "damaged": "Danneggiato",
+ "unknown": "Stato sconosciuto"
+ },
+ "carrier": {
+ "unknown": "Sconosciuto"
+ },
+ "settings": {
+ "title": "Impostazioni",
+ "subtitle": "Preferenze di notifica del tracciamento.",
+ "notifications_label": "Avvisami quando lo stato cambia",
+ "notifications_hint": "Mostra una notifica di sistema quando un pacco cambia fase (es. in consegna, consegnato).",
+ "test_notification": "Invia notifica di prova",
+ "test_busy": "Invio…",
+ "test_toast_sent": "Notifica di prova inviata",
+ "test_failed": "Impossibile inviare la notifica",
+ "permission_denied_toast": "Le notifiche sono disattivate a livello di sistema. Attivale nelle impostazioni del SO.",
+ "permission_denied_banner": "Notifiche di sistema disattivate",
+ "permission_denied_hint": "Consenti le notifiche di Omniget nelle impostazioni del sistema operativo per ricevere aggiornamenti sui pacchi.",
+ "request_permission": "Richiedi autorizzazione"
+ },
+ "notification": {
+ "title_template": "{{code}}: {{status}}",
+ "body_fallback": "Stato aggiornato",
+ "test_title": "Le notifiche di tracciamento funzionano",
+ "test_body": "Vedrai notifiche come questa quando i tuoi pacchi cambiano stato."
+ }
}
}
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index 9b0ef7dc..b23405bb 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "停止",
"confirm_remove": "このダウンロードを削除しますか?",
+ "quality_hint": "この項目でダウンロード中の画質",
"stats_line": "{{count}} 件のダウンロード · {{size}} 保存済み",
"filter_label": "ステータスでダウンロードを絞り込む",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — 軽量",
"quality_480p": "中画質 (480p) — 高速",
"quality_360p": "低画質 (360p) — 超軽量",
+ "quality_best_short": "最高",
+ "quality_audio": "音声",
"view_formats": "フォーマットを表示",
"hide_formats": "フォーマットを隠す",
"no_formats": "この動画で利用可能なフォーマットはありません",
@@ -404,6 +407,7 @@
"preset_custom": "カスタム",
"formats_presets_label": "フォーマットプリセット",
"formats_merge_note": "FFmpeg が利用可能な場合、動画形式 (V) は自動的に音声 (A) と結合されます。",
+ "formats_playlist_note": "動画ごとのフォーマット選択はプレイリストには適用されません。上の「品質」設定がすべての動画に適用されます。",
"referer_label": "リファラー(任意)",
"referer_placeholder": "https://example.com",
"external_url_ready": "Chrome拡張機能からURLを受信しました",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "途中の曲はありません。何か再生すれば、続きから戻れます。",
+ "shelf_recent": "最近再生した曲",
+ "shelf_recent_empty": "次に再生する曲から履歴が始まります。",
+ "diag_metrics_title": "YouTube メトリクス",
+ "diag_refresh": "更新",
+ "diag_metrics_reset": "メトリクスをリセット",
+ "diag_loading": "読み込み中…",
+ "diag_metrics_empty": "まだデータがありません。何曲か再生してテレメトリを集めてください。",
+ "diag_metrics_endpoint": "エンドポイント",
+ "diag_metrics_success": "成功",
+ "diag_metrics_fail": "失敗",
+ "diag_metrics_last_error": "最後のエラー",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "JS エンジン",
+ "diag_potoken_snapshot": "スナップショット",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "有効",
+ "diag_potoken_minting_pending": "保留中(数週間)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "期限切れ",
+ "diag_potoken_visitor_active": "有効 — 残り {{seconds}} 秒",
+ "diag_potoken_visitor_active_unknown": "有効",
+ "diag_potoken_visitor_none": "トークンなし",
+ "diag_potoken_cache_count": "キャッシュ済みトークン",
+ "diag_potoken_last_generated": "生成日時",
+ "diag_loop_title": "Loop 拡張機能(YouTube クッキー)",
+ "diag_loop_missing": "クッキーファイルが見つかりません。",
+ "diag_loop_missing_hint": "ブラウザに Loop 拡張機能をインストールし、表示されたパスにクッキーをエクスポートしてください。",
+ "diag_loop_no_youtube": "ファイルは存在しますが YouTube のクッキーがありません。",
+ "diag_loop_no_youtube_hint": "Loop 拡張機能をインストールしたブラウザで youtube.com を開いてログインしてください。クッキーは自動で取り込まれます。",
+ "diag_loop_ready": "YouTube クッキーが利用可能です。",
+ "retry": "再試行",
+ "speed_dial_search": "検索",
+ "speed_dial_library": "ライブラリ",
+ "speed_dial_playlists": "プレイリスト",
+ "speed_dial_favorites": "お気に入り",
+ "speed_dial_history": "履歴",
+ "speed_dial_trending": "急上昇",
+ "speed_dial_albums": "アルバム",
+ "speed_dial_artists": "アーティスト",
+ "speed_dial_genres": "ジャンル",
+ "shelf_recent_albums": "最近追加",
+ "shelf_recent_albums_empty": "メニューから音楽フォルダを指定してアルバムをスキャンしてください。",
+ "shelf_artists": "アーティスト",
+ "shelf_artists_empty": "アーティストはまだ登録されていません。",
+ "explore_youtube_cta": "YouTube を見る",
+ "explore_youtube_cta_body": "発見、チャート、新作、登録チャンネル。",
+ "pull_to_refresh_hint": "離して更新",
+ "pull_to_refresh_release": "更新中…",
+ "loading": "読み込み中…",
+ "play_count_today": "続きから再生",
+ "history_empty_title": "履歴は次に再生する曲から始まります",
+ "history_empty_cta": "YouTube で検索",
+ "back": "戻る",
+ "play_all": "すべて再生",
+ "shuffle_play": "シャッフル",
+ "save_playlist": "保存",
+ "share": "共有",
+ "share_copied": "リンクをコピーしました",
+ "expandable_more": "もっと見る",
+ "expandable_less": "閉じる",
+ "album_loading_error": "このアルバムを読み込めませんでした。",
+ "playlist_loading_error": "このプレイリストを読み込めませんでした。",
+ "album_empty": "このアルバムには再生可能なトラックがありません。",
+ "playlist_empty": "このプレイリストは空です。",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "曲",
+ "tab_videos": "動画",
+ "tab_about": "概要",
+ "shuffle_radio": "シャッフル再生",
+ "no_description": "説明はありません。",
+ "my_playlists_title": "マイプレイリスト",
+ "my_playlists_subtitle": "YouTube の動画から作ったローカルのリスト。",
+ "my_playlists_empty_title": "プレイリストがありません",
+ "my_playlists_empty_body": "自由に整理するためのリストを作りましょう。手元だけに保存されます。",
+ "my_playlists_create": "新しいプレイリスト",
+ "my_playlists_create_title": "プレイリストを作成",
+ "my_playlists_form_name": "名前",
+ "my_playlists_form_name_placeholder": "例:勉強用",
+ "my_playlists_form_description": "説明(任意)",
+ "my_playlists_form_save": "作成",
+ "my_playlists_form_cancel": "キャンセル",
+ "my_playlists_delete_confirm_title": "プレイリストを削除しますか?",
+ "my_playlists_delete_confirm_body": "{{count}} 曲は YouTube に残ります — 消えるのはローカルのリストだけです。",
+ "my_playlists_delete_confirm_empty": "ローカルのリストが消えます。元に戻せません。",
+ "my_playlists_delete_confirm_action": "プレイリストを削除",
+ "my_playlists_delete_confirm_cancel": "キャンセル",
+ "my_playlists_rename_aria": "プレイリストの名前を変更",
+ "my_playlists_settings_aria": "プレイリストの操作",
+ "my_playlists_open_aria": "プレイリストを開く",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "{{title}} をプレイリストから削除",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "YouTube から追加",
+ "add_to_playlist_search_placeholder": "追加する動画を検索…",
+ "add_to_playlist_search_short": "2 文字以上入力してください。",
+ "add_to_playlist_close": "閉じる",
+ "add_to_playlist_added": "プレイリストに追加しました",
+ "rename_inline_placeholder": "プレイリスト名",
+ "tracks_count_n": "{{count}} 曲",
+ "track_count_one": "1 曲",
+ "playlist_empty_cta": "YouTube から追加",
+ "shelf_spotify_recent": "Spotify · 最近再生した曲",
+ "shelf_soundcloud_likes": "SoundCloud · お気に入り",
+ "history_filter_all": "すべて",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "チャプター",
+ "chapters_empty": "チャプターがありません",
+ "video_mode_toggle": "Video mode",
+ "video_mode_only_youtube": "Video only available for YouTube tracks",
+ "expand_video": "Open fullscreen video",
+ "watch_title": "Watch",
+ "watch_video_unavailable": "Video unavailable for this track",
+ "watch_back": "Back to music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "タイトル・アーティスト・アルバム名でローカルライブラリを検索できます。",
+ "history_now": "たった今",
+ "history_unplayable": "この履歴は再生できません — 曲がもう利用できません。",
+ "history_clear_confirm_yt": "YouTubeの履歴をすべて削除します。続けますか?",
+ "history_clear_confirm_local": "ローカルの履歴をすべて削除します。続けますか?",
+ "history_clear": "クリア",
+ "history_title": "履歴",
+ "history_title_yt": "YouTube履歴",
+ "history_empty_title_yt": "YouTubeで何かを再生すると履歴がここに表示されます",
+ "history_empty_cta_yt": "YouTubeで検索",
+ "history_empty_title_local": "ライブラリで何かを再生すると履歴がここに表示されます",
+ "history_empty_cta_local": "ライブラリを検索",
+ "history_filter_local": "ローカル",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "ソースで絞り込む",
+ "history_remove_aria": "履歴から削除",
+ "history_entries_removed": "件削除しました",
+ "youtube": {
+ "shelf_group": "YouTubeから",
+ "shelf_charts": "音楽チャート",
+ "shelf_charts_empty": "今はチャートを取得できません。少し時間を置いて再試行してください。",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "新着リリースはありません。明日また見てみましょう。",
+ "shelf_moods_and_genres": "ムードとジャンル",
+ "moods_empty": "ムードを取得できません。少し時間を置いて再試行してください。",
+ "shelf_trending": "急上昇中",
+ "shelf_trending_error": "YouTube に接続できません。数分後にもう一度お試しください。",
+ "shelf_quick_picks": "あなたへのおすすめ",
+ "shelf_quick_picks_empty": "好みを学習中です。まずは数曲再生してみてください。",
+ "shelf_daily_discover": "今日のディスカバリー",
+ "shelf_daily_discover_empty": "好きな曲を再生すると、次におすすめする曲が見つかります。",
+ "shelf_continue_watching": "視聴を再開",
+ "shelf_continue_watching_empty": "再開できる項目はまだありません。何か再生して始めましょう。",
+ "shelf_subscriptions": "登録チャンネル",
+ "shelf_subscriptions_empty": "チャンネル登録すると、ここに新着が表示されます。",
+ "explore_title": "探す",
+ "explore_tagline": "気軽に新しい音楽を見つけましょう。",
+ "back_to_explore": "「探す」に戻る",
+ "mood_loading_error": "このムードを読み込めませんでした。再試行してください。",
+ "mood_empty": "このムードには今プレイリストがありません。また後で見てみましょう。",
+ "hub_title": "YouTube",
+ "hub_tagline": "YouTube の音楽と動画を一か所で。",
+ "search_filter_aria": "結果を絞り込む",
+ "search_filter_all": "すべて",
+ "search_filter_music": "音楽",
+ "search_filter_videos": "動画",
+ "search_filter_channels": "チャンネル",
+ "search_filter_playlists": "プレイリスト",
+ "search_sort_aria": "結果を並べ替える",
+ "search_sort_relevance": "関連度",
+ "search_sort_recent": "新しい順",
+ "search_sort_views": "再生回数順",
+ "search_history_label": "最近の検索",
+ "search_history_clear": "履歴を消去",
+ "search_history_remove_aria": "履歴から「{{query}}」を削除",
+ "subscribers_count_label": "登録者",
+ "creator_by": "作成者:{{name}}",
+ "channel_subscribe": "登録",
+ "channel_subscribed": "登録済み",
+ "channel_unsubscribe_aria": "登録解除",
+ "channel_no_items": "まだ何もありません。",
+ "search_placeholder": "YouTubeで検索…",
+ "search_hint": "入力を始めると動画・チャンネル・プレイリストが表示されます。",
+ "connect_title": "YouTubeアカウントを接続",
+ "connect_body": "接続すると、ライブラリ・登録チャンネル・続きが表示されます。アカウントなしでは検索と発見のみ利用できます(匿名)。",
+ "connect_step_missing_label": "接続方法",
+ "connect_step_missing": "ブラウザにLoop拡張機能をインストールし、Cookieを下のパスにエクスポートしてください。戻ってくれば自動で検出されます。",
+ "connect_step_no_youtube_label": "もう少し",
+ "connect_step_no_youtube": "Loopはインストール済みですが、ブラウザでYouTubeにログインしていません。youtube.comを開いてログインしてください — Cookieが自動でここに届きます。",
+ "connect_cta_setup": "接続を設定",
+ "connect_cta_anon": "匿名で見る",
+ "connect_footnote": "Cookieはお使いのPCに保存され、当社のサーバーには送信されません。",
+ "anon_speed_dial_aria": "YouTubeへの匿名アクセス"
+ },
+ "spotify_connected": "Spotifyに接続しました",
+ "spotify_auth_failed": "認証に失敗しました",
+ "spotify_library_updated": "ライブラリを更新しました",
+ "spotify_auth_waiting": "ブラウザでの認可を待っています。承認後ここに戻ってください。",
+ "spotify_disconnected": "Spotifyから切断しました",
+ "spotify_play_via_yt": "YouTube経由で再生中(無料モード)",
+ "spotify_search_aria": "Spotifyで検索",
+ "spotify_search_label": "検索",
+ "spotify_refresh_label": "更新",
+ "spotify_prev_aria": "前へ",
+ "spotify_next_aria": "次へ"
},
"library": {
"title": "ライブラリ",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "設定",
"placeholder": "プラグインの設定とライブラリの再スキャン。",
+ "tab_diagnostic": "診断",
+ "saving": "保存中…",
+ "saved": "保存しました",
+ "categories_aria": "カテゴリ",
"library_section": "ライブラリ",
"rescan": "ライブラリを再スキャン",
"rescan_desc": "ダウンロードフォルダを再度走査し、コース、モジュール、レッスンを更新します。",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "{{count}} 件の問題が見つかりました",
"verify_failed_toast": "ライブラリの検証に失敗しました: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "荷物追跡",
+ "subtitle_summary": "{{count}} 件 · 配送中 {{in_transit}} 件",
+ "subtitle_empty": "ブラジルの主要配送業者の荷物を追跡できます。",
+ "privacy_show_title": "コードを表示",
+ "privacy_hide_title": "コードを非表示(配信者モード)",
+ "privacy_button": "非公開",
+ "refresh_all": "すべて更新",
+ "refresh_all_busy": "更新中…",
+ "refresh_all_title": "すべての荷物を更新",
+ "add_button": "+ 追加",
+ "search_placeholder": "コード・別名・ステータスで検索…",
+ "tab": {
+ "all": "すべて",
+ "in_transit": "配送中",
+ "awaiting": "待機中",
+ "delivered": "配達済",
+ "delayed": "遅延",
+ "archived": "アーカイブ"
+ },
+ "empty": {
+ "none_title": "追跡中の荷物なし",
+ "none_desc": "追跡コードを追加して配送状況を確認しましょう。",
+ "none_cta": "最初の荷物を追加",
+ "in_transit": "配送中の荷物はありません。",
+ "awaiting": "受取待ちの荷物はありません。",
+ "delivered": "まだ配達済みの荷物はありません。",
+ "delayed": "遅延している荷物はありません。",
+ "archived": "アーカイブされた荷物はありません。",
+ "nothing": "何もありません。",
+ "search": "「{{query}}」に一致する荷物はありません。"
+ },
+ "card": {
+ "delivered": "配達済",
+ "days_one": "配送 1 日目",
+ "days_other": "配送 {{count}} 日目",
+ "no_events": "イベントなし",
+ "awaiting_first": "最初の更新待ち…",
+ "archived_label": "アーカイブ済"
+ },
+ "rel": {
+ "now": "今",
+ "minutes": "{{count}} 分前",
+ "hours": "{{count}} 時間前"
+ },
+ "menu": {
+ "refresh": "更新",
+ "refreshing": "更新中…",
+ "copy_code": "コードをコピー",
+ "rename": "名前変更",
+ "unarchive": "アーカイブ解除",
+ "remove": "削除"
+ },
+ "loading": "読み込み中…",
+ "error_prefix": "エラー",
+ "toast": {
+ "added": "荷物を追加しました。更新中…",
+ "copied": "コードをコピーしました",
+ "copy_failed": "コピーできませんでした",
+ "refresh_failed": "更新できませんでした ({{error}})",
+ "offline": "オフライン — 更新を延期します",
+ "refresh_done": "更新完了",
+ "package_removed": "荷物を削除しました",
+ "archived": "荷物をアーカイブしました",
+ "unarchived": "荷物のアーカイブを解除しました",
+ "cpf_updated": "CPF を更新しました",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "荷物の別名",
+ "add_dialog": {
+ "title": "荷物を追加",
+ "close": "閉じる",
+ "code_label": "追跡コード *",
+ "code_placeholder": "例: AB123456789BR",
+ "alias_label": "別名(任意)",
+ "alias_placeholder": "例: 新しいスニーカー",
+ "cpf_label": "受取人の CPF *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "この配送業者は照会に CPF が必要です。",
+ "detecting": "配送業者を検出中…",
+ "detected": "配送業者: {{carrier}}",
+ "requires_cpf_suffix": "· CPF 必須",
+ "error_code_required": "追跡コードを入力してください。",
+ "error_cpf_required": "この配送業者は CPF が必要です。",
+ "cancel": "キャンセル",
+ "submit": "保存",
+ "submitting": "保存中…"
+ },
+ "remove_dialog": {
+ "title": "荷物を削除",
+ "question": "{{name}} を削除してよろしいですか?",
+ "sub": "追跡されたイベントも削除されます。",
+ "cancel": "キャンセル",
+ "confirm": "削除",
+ "confirming": "削除中…",
+ "close": "閉じる"
+ },
+ "archive_prompt": {
+ "title": "荷物が配達されました 🎉",
+ "body": "この荷物をアーカイブしますか?アクティブリストから外れますが、履歴は残ります。",
+ "keep": "いいえ、残す",
+ "archive": "アーカイブ"
+ },
+ "detail": {
+ "back": "← 追跡",
+ "not_found_title": "荷物が見つかりません",
+ "not_found_body": "この荷物は削除された可能性があります。",
+ "not_found_back": "リストに戻る",
+ "awaiting_first": "最初の更新待ち",
+ "refresh_failed_title": "前回の更新に失敗しました。",
+ "retry": "再試行",
+ "archived_pill": "アーカイブ済",
+ "delivered_pill": "配達済",
+ "days_one_pill": "配送 1 日目",
+ "days_other_pill": "配送 {{count}} 日目",
+ "action": {
+ "refresh": "更新",
+ "refreshing": "更新中…",
+ "rename": "名前変更",
+ "add_cpf": "CPF を追加",
+ "archive": "アーカイブ",
+ "unarchive": "アーカイブ解除",
+ "remove": "削除"
+ },
+ "meta": {
+ "code": "コード",
+ "cpf": "CPF",
+ "route": "ルート",
+ "posted_at": "発送日",
+ "updated": "更新日時",
+ "copy_code_title": "コードをコピー",
+ "edit": "編集"
+ },
+ "cpf_dialog": {
+ "title_add": "CPF を追加",
+ "title_edit": "CPF を編集",
+ "label": "受取人の CPF",
+ "placeholder": "000.000.000-00",
+ "hint": "空欄で削除します。",
+ "cancel": "キャンセル",
+ "submit": "保存",
+ "submitting": "保存中…",
+ "close": "閉じる"
+ },
+ "history": {
+ "title": "履歴",
+ "empty": "まだイベントは記録されていません。"
+ }
+ },
+ "status": {
+ "preadvice": "注文作成",
+ "picked_up": "発送済",
+ "in_transit": "配送中",
+ "in_warehouse": "配送センター",
+ "customs": "通関手続中",
+ "customs_held": "通関保留中",
+ "customs_cleared": "通関完了",
+ "out_for_delivery": "配達中",
+ "awaiting_pickup": "受取待ち",
+ "delivered": "配達済",
+ "delivery_failure": "配達失敗",
+ "delayed": "遅延",
+ "returning_to_sender": "返送中",
+ "returned_to_sender": "差出人に返送",
+ "damaged": "破損",
+ "unknown": "不明なステータス"
+ },
+ "carrier": {
+ "unknown": "不明"
+ },
+ "settings": {
+ "title": "設定",
+ "subtitle": "配送追跡の通知設定。",
+ "notifications_label": "ステータス変更を通知する",
+ "notifications_hint": "荷物のステータスが変わった時(配達中、配達完了など)にシステム通知を表示します。",
+ "test_notification": "テスト通知を送信",
+ "test_busy": "送信中…",
+ "test_toast_sent": "テスト通知を送信しました",
+ "test_failed": "通知を送信できませんでした",
+ "permission_denied_toast": "システムで通知が無効になっています。OSの設定で有効にしてください。",
+ "permission_denied_banner": "システム通知が無効です",
+ "permission_denied_hint": "荷物の更新を受け取るには、OSの設定でOmnigetの通知を許可してください。",
+ "request_permission": "許可をリクエスト"
+ },
+ "notification": {
+ "title_template": "{{code}}:{{status}}",
+ "body_fallback": "ステータスが更新されました",
+ "test_title": "追跡通知は有効です",
+ "test_body": "荷物のステータスが変わると、このような通知が表示されます。"
+ }
}
}
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index e614ab73..521b5eb0 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -181,6 +181,7 @@ export type TranslationKeys =
| 'downloads.phase_fetching_info'
| 'downloads.phase_preparing'
| 'downloads.phase_starting'
+ | 'downloads.quality_hint'
| 'downloads.resume'
| 'downloads.retry'
| 'downloads.section_finished'
@@ -351,6 +352,7 @@ export type TranslationKeys =
| 'omnibox.fmt_video'
| 'omnibox.formats_error'
| 'omnibox.formats_merge_note'
+ | 'omnibox.formats_playlist_note'
| 'omnibox.formats_presets_label'
| 'omnibox.go_to_hotmart'
| 'omnibox.hide_formats'
@@ -369,7 +371,9 @@ export type TranslationKeys =
| 'omnibox.quality_360p'
| 'omnibox.quality_480p'
| 'omnibox.quality_720p'
+ | 'omnibox.quality_audio'
| 'omnibox.quality_best'
+ | 'omnibox.quality_best_short'
| 'omnibox.referer_label'
| 'omnibox.referer_placeholder'
| 'omnibox.retry'
@@ -1330,14 +1334,23 @@ export type TranslationKeys =
| 'study.music.add_root'
| 'study.music.add_root_cta'
| 'study.music.add_to_playlist'
+ | 'study.music.add_to_playlist_added'
+ | 'study.music.add_to_playlist_close'
+ | 'study.music.add_to_playlist_modal_title'
+ | 'study.music.add_to_playlist_search_placeholder'
+ | 'study.music.add_to_playlist_search_short'
| 'study.music.add_to_queue'
| 'study.music.added_to_playlist'
+ | 'study.music.album_empty'
+ | 'study.music.album_loading_error'
| 'study.music.albums_count'
| 'study.music.albums_empty'
| 'study.music.artists_count'
| 'study.music.artists_empty'
+ | 'study.music.back'
| 'study.music.batch_done'
| 'study.music.by'
+ | 'study.music.chapters_empty'
| 'study.music.clear_covers'
| 'study.music.clear_covers_confirm'
| 'study.music.clear_covers_done'
@@ -1350,6 +1363,34 @@ export type TranslationKeys =
| 'study.music.delete_confirm_msg'
| 'study.music.delete_confirm_title'
| 'study.music.delete_playlist'
+ | 'study.music.diag_loading'
+ | 'study.music.diag_loop_missing'
+ | 'study.music.diag_loop_missing_hint'
+ | 'study.music.diag_loop_no_youtube'
+ | 'study.music.diag_loop_no_youtube_hint'
+ | 'study.music.diag_loop_ready'
+ | 'study.music.diag_loop_title'
+ | 'study.music.diag_metrics_empty'
+ | 'study.music.diag_metrics_endpoint'
+ | 'study.music.diag_metrics_fail'
+ | 'study.music.diag_metrics_last_error'
+ | 'study.music.diag_metrics_reset'
+ | 'study.music.diag_metrics_success'
+ | 'study.music.diag_metrics_title'
+ | 'study.music.diag_potoken_cache_count'
+ | 'study.music.diag_potoken_engine'
+ | 'study.music.diag_potoken_last_generated'
+ | 'study.music.diag_potoken_minting'
+ | 'study.music.diag_potoken_minting_active'
+ | 'study.music.diag_potoken_minting_pending'
+ | 'study.music.diag_potoken_snapshot'
+ | 'study.music.diag_potoken_title'
+ | 'study.music.diag_potoken_visitor'
+ | 'study.music.diag_potoken_visitor_active'
+ | 'study.music.diag_potoken_visitor_active_unknown'
+ | 'study.music.diag_potoken_visitor_expired'
+ | 'study.music.diag_potoken_visitor_none'
+ | 'study.music.diag_refresh'
| 'study.music.diagnostics'
| 'study.music.diagnostics_hint'
| 'study.music.diagnostics_title'
@@ -1374,6 +1415,7 @@ export type TranslationKeys =
| 'study.music.empty_no_tracks_body'
| 'study.music.empty_no_tracks_title'
| 'study.music.empty_results'
+ | 'study.music.empty_search_no_results'
| 'study.music.eq_enable'
| 'study.music.eq_preset'
| 'study.music.eq_preset_bass'
@@ -1388,6 +1430,11 @@ export type TranslationKeys =
| 'study.music.eq_reset'
| 'study.music.eq_title'
| 'study.music.exit'
+ | 'study.music.expand_video'
+ | 'study.music.expandable_less'
+ | 'study.music.expandable_more'
+ | 'study.music.explore_youtube_cta'
+ | 'study.music.explore_youtube_cta_body'
| 'study.music.eyebrow_album'
| 'study.music.eyebrow_artist'
| 'study.music.eyebrow_genre'
@@ -1407,6 +1454,26 @@ export type TranslationKeys =
| 'study.music.field_year'
| 'study.music.genres_subtitle'
| 'study.music.genres_title'
+ | 'study.music.history_clear'
+ | 'study.music.history_clear_confirm_local'
+ | 'study.music.history_clear_confirm_yt'
+ | 'study.music.history_empty_cta'
+ | 'study.music.history_empty_cta_local'
+ | 'study.music.history_empty_cta_yt'
+ | 'study.music.history_empty_title'
+ | 'study.music.history_empty_title_local'
+ | 'study.music.history_empty_title_yt'
+ | 'study.music.history_entries_removed'
+ | 'study.music.history_filter_all'
+ | 'study.music.history_filter_aria'
+ | 'study.music.history_filter_local'
+ | 'study.music.history_filter_soundcloud'
+ | 'study.music.history_filter_spotify'
+ | 'study.music.history_now'
+ | 'study.music.history_remove_aria'
+ | 'study.music.history_title'
+ | 'study.music.history_title_yt'
+ | 'study.music.history_unplayable'
| 'study.music.info_no_track'
| 'study.music.jump_back_in'
| 'study.music.lastfm_authorize'
@@ -1431,13 +1498,38 @@ export type TranslationKeys =
| 'study.music.lastfm_step3_title'
| 'study.music.lastfm_title'
| 'study.music.library_title'
+ | 'study.music.loading'
+ | 'study.music.local_search_hint'
+ | 'study.music.lyrics_add_manual'
+ | 'study.music.lyrics_error'
+ | 'study.music.lyrics_error_hint'
| 'study.music.lyrics_loading'
| 'study.music.lyrics_lrclib_hint'
| 'study.music.lyrics_no_track'
| 'study.music.lyrics_not_found'
+ | 'study.music.lyrics_paste_cancel'
+ | 'study.music.lyrics_paste_hint'
+ | 'study.music.lyrics_paste_invalid'
+ | 'study.music.lyrics_paste_placeholder'
+ | 'study.music.lyrics_paste_save'
+ | 'study.music.lyrics_paste_title'
| 'study.music.lyrics_refresh'
+ | 'study.music.lyrics_retry'
| 'study.music.lyrics_source'
| 'study.music.lyrics_title'
+ | 'study.music.lyrics_translation_attribution'
+ | 'study.music.lyrics_translation_available_hint'
+ | 'study.music.lyrics_translation_edit_cancel'
+ | 'study.music.lyrics_translation_edit_placeholder'
+ | 'study.music.lyrics_translation_edit_save'
+ | 'study.music.lyrics_translation_edited_badge'
+ | 'study.music.lyrics_translation_error'
+ | 'study.music.lyrics_translation_hide'
+ | 'study.music.lyrics_translation_loading'
+ | 'study.music.lyrics_translation_no_translator'
+ | 'study.music.lyrics_translation_no_translator_hint'
+ | 'study.music.lyrics_translation_show'
+ | 'study.music.lyrics_translation_skipped_pt'
| 'study.music.manage_folders'
| 'study.music.music_theme_accent'
| 'study.music.music_theme_dominant_off'
@@ -1449,11 +1541,35 @@ export type TranslationKeys =
| 'study.music.music_theme_preset_indigo'
| 'study.music.music_theme_preset_purple'
| 'study.music.music_theme_preset_spotify'
+ | 'study.music.music_theme_reduce_motion'
+ | 'study.music.music_theme_reduce_motion_auto'
+ | 'study.music.music_theme_reduce_motion_hint'
+ | 'study.music.music_theme_reduce_motion_off'
+ | 'study.music.music_theme_reduce_motion_on'
| 'study.music.music_theme_reset'
| 'study.music.music_theme_save'
| 'study.music.music_theme_subtitle'
| 'study.music.music_theme_title'
| 'study.music.music_theme_use_dominant'
+ | 'study.music.my_playlists_create'
+ | 'study.music.my_playlists_create_title'
+ | 'study.music.my_playlists_delete_confirm_action'
+ | 'study.music.my_playlists_delete_confirm_body'
+ | 'study.music.my_playlists_delete_confirm_cancel'
+ | 'study.music.my_playlists_delete_confirm_empty'
+ | 'study.music.my_playlists_delete_confirm_title'
+ | 'study.music.my_playlists_empty_body'
+ | 'study.music.my_playlists_empty_title'
+ | 'study.music.my_playlists_form_cancel'
+ | 'study.music.my_playlists_form_description'
+ | 'study.music.my_playlists_form_name'
+ | 'study.music.my_playlists_form_name_placeholder'
+ | 'study.music.my_playlists_form_save'
+ | 'study.music.my_playlists_open_aria'
+ | 'study.music.my_playlists_rename_aria'
+ | 'study.music.my_playlists_settings_aria'
+ | 'study.music.my_playlists_subtitle'
+ | 'study.music.my_playlists_title'
| 'study.music.n_selected'
| 'study.music.nav_activity'
| 'study.music.nav_albums'
@@ -1462,18 +1578,32 @@ export type TranslationKeys =
| 'study.music.nav_download'
| 'study.music.nav_favorites'
| 'study.music.nav_genres'
+ | 'study.music.nav_history'
| 'study.music.nav_home'
| 'study.music.nav_library'
| 'study.music.nav_playlists'
| 'study.music.nav_search'
| 'study.music.nav_soundcloud'
| 'study.music.nav_spotify'
+ | 'study.music.nav_transcode'
| 'study.music.nav_youtube'
| 'study.music.new_playlist'
| 'study.music.next'
| 'study.music.no_activity'
+ | 'study.music.no_description'
| 'study.music.no_genres'
| 'study.music.no_playlists_yet'
+ | 'study.music.now_playing_close'
+ | 'study.music.now_playing_lyrics_empty'
+ | 'study.music.now_playing_lyrics_error'
+ | 'study.music.now_playing_no_track'
+ | 'study.music.now_playing_open'
+ | 'study.music.now_playing_previous_empty'
+ | 'study.music.now_playing_queue_empty'
+ | 'study.music.now_playing_tab_lyrics'
+ | 'study.music.now_playing_tab_previous'
+ | 'study.music.now_playing_tab_queue'
+ | 'study.music.now_playing_title'
| 'study.music.open_album'
| 'study.music.pause'
| 'study.music.period_1y'
@@ -1482,11 +1612,30 @@ export type TranslationKeys =
| 'study.music.period_90d'
| 'study.music.period_all'
| 'study.music.play'
+ | 'study.music.play_all'
+ | 'study.music.play_count_today'
+ | 'study.music.player_action_configure'
+ | 'study.music.player_action_refresh'
+ | 'study.music.player_action_retry'
+ | 'study.music.player_action_skip'
| 'study.music.player_aria'
+ | 'study.music.player_auto_skip_label'
+ | 'study.music.player_dismiss_error'
+ | 'study.music.player_error_auth_expired'
+ | 'study.music.player_error_format_unavailable'
+ | 'study.music.player_error_network'
+ | 'study.music.player_error_region_blocked'
+ | 'study.music.player_error_track_unavailable'
+ | 'study.music.player_error_unknown'
+ | 'study.music.player_error_unsupported_format'
+ | 'study.music.player_resolving'
| 'study.music.playlist_deleted'
| 'study.music.playlist_duplicate'
+ | 'study.music.playlist_empty'
| 'study.music.playlist_empty_body'
+ | 'study.music.playlist_empty_cta'
| 'study.music.playlist_empty_title'
+ | 'study.music.playlist_loading_error'
| 'study.music.playlist_name_placeholder'
| 'study.music.playlist_not_found'
| 'study.music.playlists_empty_body'
@@ -1494,6 +1643,8 @@ export type TranslationKeys =
| 'study.music.playlists_section'
| 'study.music.playlists_title'
| 'study.music.prev'
+ | 'study.music.pull_to_refresh_hint'
+ | 'study.music.pull_to_refresh_release'
| 'study.music.qobuz_connect'
| 'study.music.qobuz_connected'
| 'study.music.qobuz_connected_hint'
@@ -1540,8 +1691,18 @@ export type TranslationKeys =
| 'study.music.queue_title'
| 'study.music.queue_toggle'
| 'study.music.queued_count'
+ | 'study.music.refresh_covers_action'
+ | 'study.music.refresh_covers_body'
+ | 'study.music.refresh_covers_confirm'
+ | 'study.music.refresh_covers_done'
+ | 'study.music.refresh_covers_hint'
+ | 'study.music.refresh_covers_progress'
+ | 'study.music.refresh_covers_title'
| 'study.music.remove_from_playlist'
+ | 'study.music.remove_from_playlist_aria'
+ | 'study.music.rename_inline_placeholder'
| 'study.music.repeat'
+ | 'study.music.retry'
| 'study.music.root_added'
| 'study.music.root_missing'
| 'study.music.root_remove'
@@ -1558,12 +1719,20 @@ export type TranslationKeys =
| 'study.music.rpc_image_hint'
| 'study.music.rpc_intro'
| 'study.music.rpc_large_image'
+ | 'study.music.rpc_music_section'
| 'study.music.rpc_save'
| 'study.music.rpc_saved'
+ | 'study.music.rpc_show_buttons'
+ | 'study.music.rpc_show_buttons_hint'
+ | 'study.music.rpc_show_cover'
+ | 'study.music.rpc_show_cover_hint'
| 'study.music.rpc_test'
| 'study.music.rpc_test_fail'
| 'study.music.rpc_test_ok'
| 'study.music.rpc_title'
+ | 'study.music.rpc_update_interval'
+ | 'study.music.rpc_update_interval_hint'
+ | 'study.music.save_playlist'
| 'study.music.sc_already_signed_in'
| 'study.music.sc_download_all'
| 'study.music.sc_download_bulk_done'
@@ -1617,14 +1786,26 @@ export type TranslationKeys =
| 'study.music.search_placeholder'
| 'study.music.see_all'
| 'study.music.selection_aria'
+ | 'study.music.share'
+ | 'study.music.share_copied'
| 'study.music.shelf_added'
| 'study.music.shelf_albums'
+ | 'study.music.shelf_artists'
+ | 'study.music.shelf_artists_empty'
| 'study.music.shelf_continue'
+ | 'study.music.shelf_continue_empty'
| 'study.music.shelf_listen_now'
| 'study.music.shelf_most_played'
- | 'study.music.shelf_new_releases'
+ | 'study.music.shelf_recent'
+ | 'study.music.shelf_recent_albums'
+ | 'study.music.shelf_recent_albums_empty'
+ | 'study.music.shelf_recent_empty'
+ | 'study.music.shelf_soundcloud_likes'
+ | 'study.music.shelf_spotify_recent'
| 'study.music.shelf_top_artists'
| 'study.music.shuffle'
+ | 'study.music.shuffle_play'
+ | 'study.music.shuffle_radio'
| 'study.music.sidebar_hint_body'
| 'study.music.sidebar_hint_title'
| 'study.music.sort_added'
@@ -1643,14 +1824,38 @@ export type TranslationKeys =
| 'study.music.sources_short'
| 'study.music.sources_subtitle'
| 'study.music.sources_title'
+ | 'study.music.speed_dial_albums'
+ | 'study.music.speed_dial_artists'
+ | 'study.music.speed_dial_favorites'
+ | 'study.music.speed_dial_genres'
+ | 'study.music.speed_dial_history'
+ | 'study.music.speed_dial_library'
+ | 'study.music.speed_dial_playlists'
+ | 'study.music.speed_dial_search'
+ | 'study.music.speed_dial_trending'
+ | 'study.music.spotify_auth_failed'
+ | 'study.music.spotify_auth_waiting'
+ | 'study.music.spotify_connected'
+ | 'study.music.spotify_disconnected'
+ | 'study.music.spotify_library_updated'
+ | 'study.music.spotify_next_aria'
+ | 'study.music.spotify_play_via_yt'
+ | 'study.music.spotify_prev_aria'
+ | 'study.music.spotify_refresh_label'
+ | 'study.music.spotify_search_aria'
+ | 'study.music.spotify_search_label'
| 'study.music.start_listening'
| 'study.music.subtitle'
+ | 'study.music.tab_about'
| 'study.music.tab_albums'
| 'study.music.tab_artists'
+ | 'study.music.tab_chapters'
| 'study.music.tab_info'
| 'study.music.tab_lyrics'
| 'study.music.tab_queue'
+ | 'study.music.tab_songs'
| 'study.music.tab_tracks'
+ | 'study.music.tab_videos'
| 'study.music.title'
| 'study.music.top_albums'
| 'study.music.top_artists'
@@ -1658,9 +1863,106 @@ export type TranslationKeys =
| 'study.music.top_tracks'
| 'study.music.total_listened'
| 'study.music.total_plays'
+ | 'study.music.track_count_one'
| 'study.music.tracks_count'
+ | 'study.music.tracks_count_n'
+ | 'study.music.transcode_browse'
+ | 'study.music.transcode_cancel'
+ | 'study.music.transcode_cancelled'
+ | 'study.music.transcode_done'
+ | 'study.music.transcode_eta'
+ | 'study.music.transcode_eyebrow'
+ | 'study.music.transcode_format_label'
+ | 'study.music.transcode_input_label'
+ | 'study.music.transcode_input_placeholder'
+ | 'study.music.transcode_lead'
+ | 'study.music.transcode_missing_input'
+ | 'study.music.transcode_output_label'
+ | 'study.music.transcode_output_placeholder'
+ | 'study.music.transcode_pick_input'
+ | 'study.music.transcode_pick_output'
+ | 'study.music.transcode_quality_label'
+ | 'study.music.transcode_start'
+ | 'study.music.transcode_starting'
+ | 'study.music.transcode_state_cancelled'
+ | 'study.music.transcode_state_done'
+ | 'study.music.transcode_state_running'
+ | 'study.music.transcode_title'
+ | 'study.music.translation_settings_deepl_key_hint'
+ | 'study.music.translation_settings_deepl_key_label'
+ | 'study.music.translation_settings_deepl_key_set'
+ | 'study.music.translation_settings_libretranslate_url_hint'
+ | 'study.music.translation_settings_libretranslate_url_label'
+ | 'study.music.translation_settings_saved'
+ | 'study.music.translation_settings_show_label'
+ | 'study.music.translation_settings_target_lang_label'
+ | 'study.music.translation_settings_title'
+ | 'study.music.translation_settings_translator_deepl'
+ | 'study.music.translation_settings_translator_label'
+ | 'study.music.translation_settings_translator_libretranslate'
+ | 'study.music.translation_settings_translator_none'
| 'study.music.unfavorite'
| 'study.music.unique_tracks'
+ | 'study.music.video_mode_only_youtube'
+ | 'study.music.video_mode_toggle'
+ | 'study.music.watch_back'
+ | 'study.music.watch_title'
+ | 'study.music.watch_video_unavailable'
+ | 'study.music.youtube.anon_speed_dial_aria'
+ | 'study.music.youtube.back_to_explore'
+ | 'study.music.youtube.channel_no_items'
+ | 'study.music.youtube.channel_subscribe'
+ | 'study.music.youtube.channel_subscribed'
+ | 'study.music.youtube.channel_unsubscribe_aria'
+ | 'study.music.youtube.connect_body'
+ | 'study.music.youtube.connect_cta_anon'
+ | 'study.music.youtube.connect_cta_setup'
+ | 'study.music.youtube.connect_footnote'
+ | 'study.music.youtube.connect_step_missing'
+ | 'study.music.youtube.connect_step_missing_label'
+ | 'study.music.youtube.connect_step_no_youtube'
+ | 'study.music.youtube.connect_step_no_youtube_label'
+ | 'study.music.youtube.connect_title'
+ | 'study.music.youtube.creator_by'
+ | 'study.music.youtube.explore_tagline'
+ | 'study.music.youtube.explore_title'
+ | 'study.music.youtube.hub_tagline'
+ | 'study.music.youtube.hub_title'
+ | 'study.music.youtube.mood_empty'
+ | 'study.music.youtube.mood_loading_error'
+ | 'study.music.youtube.moods_empty'
+ | 'study.music.youtube.search_filter_all'
+ | 'study.music.youtube.search_filter_aria'
+ | 'study.music.youtube.search_filter_channels'
+ | 'study.music.youtube.search_filter_music'
+ | 'study.music.youtube.search_filter_playlists'
+ | 'study.music.youtube.search_filter_videos'
+ | 'study.music.youtube.search_hint'
+ | 'study.music.youtube.search_history_clear'
+ | 'study.music.youtube.search_history_label'
+ | 'study.music.youtube.search_history_remove_aria'
+ | 'study.music.youtube.search_placeholder'
+ | 'study.music.youtube.search_sort_aria'
+ | 'study.music.youtube.search_sort_recent'
+ | 'study.music.youtube.search_sort_relevance'
+ | 'study.music.youtube.search_sort_views'
+ | 'study.music.youtube.shelf_charts'
+ | 'study.music.youtube.shelf_charts_empty'
+ | 'study.music.youtube.shelf_continue_watching'
+ | 'study.music.youtube.shelf_continue_watching_empty'
+ | 'study.music.youtube.shelf_daily_discover'
+ | 'study.music.youtube.shelf_daily_discover_empty'
+ | 'study.music.youtube.shelf_group'
+ | 'study.music.youtube.shelf_moods_and_genres'
+ | 'study.music.youtube.shelf_new_releases'
+ | 'study.music.youtube.shelf_new_releases_empty'
+ | 'study.music.youtube.shelf_quick_picks'
+ | 'study.music.youtube.shelf_quick_picks_empty'
+ | 'study.music.youtube.shelf_subscriptions'
+ | 'study.music.youtube.shelf_subscriptions_empty'
+ | 'study.music.youtube.shelf_trending'
+ | 'study.music.youtube.shelf_trending_error'
+ | 'study.music.youtube.subscribers_count_label'
| 'study.music.yt_add_playlist'
| 'study.music.yt_auth_desc'
| 'study.music.yt_auth_how'
@@ -2169,6 +2471,7 @@ export type TranslationKeys =
| 'study.search.notes'
| 'study.search.placeholder'
| 'study.settings.backup_section'
+ | 'study.settings.categories_aria'
| 'study.settings.export'
| 'study.settings.export_button'
| 'study.settings.export_desc'
@@ -2186,6 +2489,8 @@ export type TranslationKeys =
| 'study.settings.rescan_done'
| 'study.settings.rescan_error'
| 'study.settings.rescan_running'
+ | 'study.settings.saved'
+ | 'study.settings.saving'
| 'study.settings.stat_completed'
| 'study.settings.stat_courses'
| 'study.settings.stat_decks'
@@ -2194,6 +2499,7 @@ export type TranslationKeys =
| 'study.settings.stat_lessons'
| 'study.settings.stat_notes'
| 'study.settings.stats_section'
+ | 'study.settings.tab_diagnostic'
| 'study.settings.title'
| 'study.stats.chart.empty'
| 'study.stats.chart.time_per_course'
@@ -2312,6 +2618,160 @@ export type TranslationKeys =
| 'torrent.open_file'
+ | 'tracking.add_button'
+ | 'tracking.add_dialog.alias_label'
+ | 'tracking.add_dialog.alias_placeholder'
+ | 'tracking.add_dialog.cancel'
+ | 'tracking.add_dialog.close'
+ | 'tracking.add_dialog.code_label'
+ | 'tracking.add_dialog.code_placeholder'
+ | 'tracking.add_dialog.cpf_hint'
+ | 'tracking.add_dialog.cpf_label'
+ | 'tracking.add_dialog.cpf_placeholder'
+ | 'tracking.add_dialog.detected'
+ | 'tracking.add_dialog.detecting'
+ | 'tracking.add_dialog.error_code_required'
+ | 'tracking.add_dialog.error_cpf_required'
+ | 'tracking.add_dialog.requires_cpf_suffix'
+ | 'tracking.add_dialog.submit'
+ | 'tracking.add_dialog.submitting'
+ | 'tracking.add_dialog.title'
+ | 'tracking.archive_prompt.archive'
+ | 'tracking.archive_prompt.body'
+ | 'tracking.archive_prompt.keep'
+ | 'tracking.archive_prompt.title'
+ | 'tracking.card.archived_label'
+ | 'tracking.card.awaiting_first'
+ | 'tracking.card.days_one'
+ | 'tracking.card.days_other'
+ | 'tracking.card.delivered'
+ | 'tracking.card.no_events'
+ | 'tracking.carrier.unknown'
+ | 'tracking.detail.action.add_cpf'
+ | 'tracking.detail.action.archive'
+ | 'tracking.detail.action.refresh'
+ | 'tracking.detail.action.refreshing'
+ | 'tracking.detail.action.remove'
+ | 'tracking.detail.action.rename'
+ | 'tracking.detail.action.unarchive'
+ | 'tracking.detail.archived_pill'
+ | 'tracking.detail.awaiting_first'
+ | 'tracking.detail.back'
+ | 'tracking.detail.cpf_dialog.cancel'
+ | 'tracking.detail.cpf_dialog.close'
+ | 'tracking.detail.cpf_dialog.hint'
+ | 'tracking.detail.cpf_dialog.label'
+ | 'tracking.detail.cpf_dialog.placeholder'
+ | 'tracking.detail.cpf_dialog.submit'
+ | 'tracking.detail.cpf_dialog.submitting'
+ | 'tracking.detail.cpf_dialog.title_add'
+ | 'tracking.detail.cpf_dialog.title_edit'
+ | 'tracking.detail.days_one_pill'
+ | 'tracking.detail.days_other_pill'
+ | 'tracking.detail.delivered_pill'
+ | 'tracking.detail.history.empty'
+ | 'tracking.detail.history.title'
+ | 'tracking.detail.meta.code'
+ | 'tracking.detail.meta.copy_code_title'
+ | 'tracking.detail.meta.cpf'
+ | 'tracking.detail.meta.edit'
+ | 'tracking.detail.meta.posted_at'
+ | 'tracking.detail.meta.route'
+ | 'tracking.detail.meta.updated'
+ | 'tracking.detail.not_found_back'
+ | 'tracking.detail.not_found_body'
+ | 'tracking.detail.not_found_title'
+ | 'tracking.detail.refresh_failed_title'
+ | 'tracking.detail.retry'
+ | 'tracking.empty.archived'
+ | 'tracking.empty.awaiting'
+ | 'tracking.empty.delayed'
+ | 'tracking.empty.delivered'
+ | 'tracking.empty.in_transit'
+ | 'tracking.empty.none_cta'
+ | 'tracking.empty.none_desc'
+ | 'tracking.empty.none_title'
+ | 'tracking.empty.nothing'
+ | 'tracking.empty.search'
+ | 'tracking.error_prefix'
+ | 'tracking.loading'
+ | 'tracking.menu.copy_code'
+ | 'tracking.menu.refresh'
+ | 'tracking.menu.refreshing'
+ | 'tracking.menu.remove'
+ | 'tracking.menu.rename'
+ | 'tracking.menu.unarchive'
+ | 'tracking.notification.body_fallback'
+ | 'tracking.notification.test_body'
+ | 'tracking.notification.test_title'
+ | 'tracking.notification.title_template'
+ | 'tracking.privacy_button'
+ | 'tracking.privacy_hide_title'
+ | 'tracking.privacy_show_title'
+ | 'tracking.refresh_all'
+ | 'tracking.refresh_all_busy'
+ | 'tracking.refresh_all_title'
+ | 'tracking.rel.hours'
+ | 'tracking.rel.minutes'
+ | 'tracking.rel.now'
+ | 'tracking.remove_dialog.cancel'
+ | 'tracking.remove_dialog.close'
+ | 'tracking.remove_dialog.confirm'
+ | 'tracking.remove_dialog.confirming'
+ | 'tracking.remove_dialog.question'
+ | 'tracking.remove_dialog.sub'
+ | 'tracking.remove_dialog.title'
+ | 'tracking.rename_prompt'
+ | 'tracking.search_placeholder'
+ | 'tracking.settings.notifications_hint'
+ | 'tracking.settings.notifications_label'
+ | 'tracking.settings.permission_denied_banner'
+ | 'tracking.settings.permission_denied_hint'
+ | 'tracking.settings.permission_denied_toast'
+ | 'tracking.settings.request_permission'
+ | 'tracking.settings.subtitle'
+ | 'tracking.settings.test_busy'
+ | 'tracking.settings.test_failed'
+ | 'tracking.settings.test_notification'
+ | 'tracking.settings.test_toast_sent'
+ | 'tracking.settings.title'
+ | 'tracking.status.awaiting_pickup'
+ | 'tracking.status.customs'
+ | 'tracking.status.customs_cleared'
+ | 'tracking.status.customs_held'
+ | 'tracking.status.damaged'
+ | 'tracking.status.delayed'
+ | 'tracking.status.delivered'
+ | 'tracking.status.delivery_failure'
+ | 'tracking.status.in_transit'
+ | 'tracking.status.in_warehouse'
+ | 'tracking.status.out_for_delivery'
+ | 'tracking.status.picked_up'
+ | 'tracking.status.preadvice'
+ | 'tracking.status.returned_to_sender'
+ | 'tracking.status.returning_to_sender'
+ | 'tracking.status.unknown'
+ | 'tracking.subtitle_empty'
+ | 'tracking.subtitle_summary'
+ | 'tracking.tab.all'
+ | 'tracking.tab.archived'
+ | 'tracking.tab.awaiting'
+ | 'tracking.tab.delayed'
+ | 'tracking.tab.delivered'
+ | 'tracking.tab.in_transit'
+ | 'tracking.title'
+ | 'tracking.toast.added'
+ | 'tracking.toast.archived'
+ | 'tracking.toast.copied'
+ | 'tracking.toast.copy_failed'
+ | 'tracking.toast.cpf_updated'
+ | 'tracking.toast.offline'
+ | 'tracking.toast.package_removed'
+ | 'tracking.toast.refresh_done'
+ | 'tracking.toast.refresh_failed'
+ | 'tracking.toast.status_changed'
+ | 'tracking.toast.unarchived'
+
| 'udemy.authenticating'
| 'udemy.checking_session'
| 'udemy.choose_folder'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index b571a198..047cfa15 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -73,6 +73,7 @@
"open_in_study": "Assistir no Study",
"stop": "Parar",
"confirm_remove": "Remover este download?",
+ "quality_hint": "Qualidade que está sendo baixada para este item",
"stats_line": "{{count}} downloads · {{size}} salvos",
"filter_label": "Filtrar downloads por status",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "HD (720p) — leve",
"quality_480p": "Médio (480p) — rápido",
"quality_360p": "Baixo (360p) — muito leve",
+ "quality_best_short": "Melhor",
+ "quality_audio": "Áudio",
"view_formats": "Ver formatos",
"hide_formats": "Ocultar formatos",
"no_formats": "Nenhum formato disponível para este vídeo",
@@ -404,6 +407,7 @@
"preset_custom": "Personalizado",
"formats_presets_label": "Preset de formato",
"formats_merge_note": "Formatos de vídeo (V) serão automaticamente combinados com áudio (A) se o FFmpeg estiver disponível.",
+ "formats_playlist_note": "A seleção de formato por vídeo não se aplica a playlists. A opção Qualidade acima vale para cada vídeo.",
"referer_label": "Referer (opcional)",
"referer_placeholder": "https://exemplo.com",
"external_url_ready": "URL recebida da extensão do Chrome",
@@ -921,7 +925,113 @@
"empty_no_roots_body": "Aponte pra uma pasta com seus arquivos de áudio. MP3, FLAC, M4A, OGG, OPUS — todos os formatos comuns. Nada é copiado, nada é movido.",
"empty_no_tracks_title": "Tudo pronto pra escanear",
"empty_no_tracks_body": "As pastas estão configuradas, mas ainda não fizemos o scan. Clique abaixo pra indexar suas faixas.",
- "empty_results": "Nenhum resultado.",
+ "shelf_continue_empty": "Nada inacabado por aqui. Toque algo pra continuar depois.",
+ "shelf_recent": "Recém-tocadas",
+ "shelf_recent_empty": "Sua história de escuta começa quando a próxima faixa tocar.",
+ "diag_metrics_title": "Métricas YouTube",
+ "diag_refresh": "Atualizar",
+ "diag_metrics_reset": "Resetar métricas",
+ "diag_loading": "Carregando…",
+ "diag_metrics_empty": "Sem dados ainda. Toque algumas faixas pra acumular telemetria.",
+ "diag_metrics_endpoint": "Endpoint",
+ "diag_metrics_success": "Sucesso",
+ "diag_metrics_fail": "Falhas",
+ "diag_metrics_last_error": "Último erro",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "Engine JS",
+ "diag_potoken_snapshot": "Snapshot",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "Ativo",
+ "diag_potoken_minting_pending": "Pendente (multi-semana)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "Expirado",
+ "diag_potoken_visitor_active": "Ativo — expira em {{seconds}}s",
+ "diag_potoken_visitor_active_unknown": "Ativo",
+ "diag_potoken_visitor_none": "Sem token",
+ "diag_potoken_cache_count": "Tokens em cache",
+ "diag_potoken_last_generated": "Gerado em",
+ "diag_loop_title": "Extensão Loop (cookies YouTube)",
+ "diag_loop_missing": "Arquivo de cookies não encontrado.",
+ "diag_loop_missing_hint": "Instale a extensão Loop no navegador e exporte os cookies pro caminho mostrado.",
+ "diag_loop_no_youtube": "Arquivo existe mas sem cookies do YouTube.",
+ "diag_loop_no_youtube_hint": "Abre youtube.com no navegador com a extensão Loop instalada e faz login na sua conta. Os cookies aparecem aqui sozinhos.",
+ "diag_loop_ready": "Cookies do YouTube prontos.",
+ "retry": "Tentar de novo",
+ "speed_dial_search": "Buscar",
+ "speed_dial_library": "Biblioteca",
+ "speed_dial_playlists": "Playlists",
+ "speed_dial_favorites": "Favoritos",
+ "speed_dial_history": "Histórico",
+ "speed_dial_trending": "Em alta",
+ "speed_dial_albums": "Álbuns",
+ "speed_dial_artists": "Artistas",
+ "speed_dial_genres": "Gêneros",
+ "shelf_recent_albums": "Adicionados recentemente",
+ "shelf_recent_albums_empty": "Aponte uma pasta no menu pra escanear seus álbuns.",
+ "shelf_artists": "Artistas",
+ "shelf_artists_empty": "Sem artistas indexados ainda.",
+ "explore_youtube_cta": "Explorar no YouTube",
+ "explore_youtube_cta_body": "Descobertas, charts, lançamentos e inscrições.",
+ "pull_to_refresh_hint": "Solte pra atualizar",
+ "pull_to_refresh_release": "Atualizando…",
+ "loading": "Carregando…",
+ "play_count_today": "Voltar de onde parou",
+ "history_empty_title": "Seu histórico começa quando você tocar algo",
+ "history_empty_cta": "Buscar no YouTube",
+ "back": "Voltar",
+ "play_all": "Tocar tudo",
+ "shuffle_play": "Aleatório",
+ "save_playlist": "Salvar",
+ "share": "Compartilhar",
+ "share_copied": "Link copiado",
+ "expandable_more": "ver mais",
+ "expandable_less": "ver menos",
+ "album_loading_error": "Não consegui carregar este álbum.",
+ "playlist_loading_error": "Não consegui carregar esta playlist.",
+ "album_empty": "Este álbum não tem faixas disponíveis.",
+ "playlist_empty": "Esta playlist está vazia.",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "Músicas",
+ "tab_videos": "Vídeos",
+ "tab_about": "Sobre",
+ "shuffle_radio": "Ouvir aleatório",
+ "no_description": "Sem descrição.",
+ "my_playlists_title": "Minhas playlists",
+ "my_playlists_subtitle": "Suas listas locais montadas com faixas do YouTube.",
+ "my_playlists_empty_title": "Você ainda não tem playlists",
+ "my_playlists_empty_body": "Crie uma pra organizar do seu jeito — nada vai pro YouTube, fica só aqui.",
+ "my_playlists_create": "Nova playlist",
+ "my_playlists_create_title": "Criar playlist",
+ "my_playlists_form_name": "Nome",
+ "my_playlists_form_name_placeholder": "Ex: Pra estudar",
+ "my_playlists_form_description": "Descrição (opcional)",
+ "my_playlists_form_save": "Criar",
+ "my_playlists_form_cancel": "Cancelar",
+ "my_playlists_delete_confirm_title": "Excluir playlist?",
+ "my_playlists_delete_confirm_body": "As {{count}} faixas continuam no YouTube — só sua lista local some.",
+ "my_playlists_delete_confirm_empty": "Sua lista local some. Isso não pode ser desfeito.",
+ "my_playlists_delete_confirm_action": "Excluir playlist",
+ "my_playlists_delete_confirm_cancel": "Cancelar",
+ "my_playlists_rename_aria": "Renomear playlist",
+ "my_playlists_settings_aria": "Ações da playlist",
+ "my_playlists_open_aria": "Abrir playlist",
+ "remove_from_playlist": "Remover da playlist",
+ "remove_from_playlist_aria": "Remover {{title}} da playlist",
+ "add_to_playlist": "Adicionar à playlist",
+ "add_to_playlist_modal_title": "Adicionar do YouTube",
+ "add_to_playlist_search_placeholder": "Busque um vídeo pra adicionar…",
+ "add_to_playlist_search_short": "Digite ao menos 2 caracteres.",
+ "add_to_playlist_close": "Fechar",
+ "add_to_playlist_added": "Adicionada à playlist",
+ "rename_inline_placeholder": "Nome da playlist",
+ "tracks_count_n": "{{count}} faixas",
+ "track_count_one": "1 faixa",
+ "playlist_empty_cta": "Adicionar do YouTube",
+ "shelf_spotify_recent": "Spotify · Tocadas recentemente",
+ "shelf_soundcloud_likes": "SoundCloud · Suas curtidas",
+ "history_filter_all": "Todos",
+ "empty_results": "Sua biblioteca está vazia — importe uma pasta ou conecte uma fonte no menu lateral.",
+ "empty_search_no_results": "Nenhuma música encontrada — tente outro termo.",
"empty_album": "Este álbum está vazio.",
"shelf_continue": "Continue ouvindo",
"shelf_albums": "Álbuns",
@@ -948,6 +1058,7 @@
"nav_favorites": "Favoritos",
"nav_genres": "Gêneros",
"nav_activity": "Atividade",
+ "nav_history": "Histórico",
"queue_clear": "Limpar",
"eq_title": "Equalizador",
"eq_enable": "Ativar equalizador",
@@ -986,11 +1097,61 @@
"empty": "Vazio",
"lyrics_title": "Letras",
"lyrics_loading": "Buscando letras…",
- "lyrics_not_found": "Nenhuma letra encontrada",
- "lyrics_lrclib_hint": "Letras vêm de lrclib.net (banco de letras sincronizadas comunitário). Pode não ter pra faixas obscuras.",
+ "lyrics_not_found": "Sem letra disponível",
+ "lyrics_lrclib_hint": "Você pode colar a letra manualmente em formato .lrc",
"lyrics_no_track": "Nenhuma faixa tocando",
"lyrics_refresh": "Buscar de novo",
+ "lyrics_retry": "Tentar de novo",
"lyrics_source": "Fonte: {{source}}",
+ "lyrics_error": "Falha ao buscar a letra",
+ "lyrics_error_hint": "A música segue tocando — pode tentar de novo a qualquer hora",
+ "lyrics_add_manual": "Adicionar letra",
+ "lyrics_paste_title": "Colar letra manualmente",
+ "lyrics_paste_placeholder": "Cole aqui o conteúdo do arquivo .lrc",
+ "lyrics_paste_hint": "Aceita formato LRC com timestamps [mm:ss.xx]. Pelo menos uma linha sincronizada é necessária.",
+ "lyrics_paste_save": "Salvar letra",
+ "lyrics_paste_invalid": "Não encontramos linhas com timestamp — confira o formato",
+ "lyrics_paste_cancel": "Cancelar",
+ "lyrics_translation_show": "Mostrar tradução",
+ "lyrics_translation_hide": "Esconder tradução",
+ "lyrics_translation_loading": "Traduzindo letra…",
+ "lyrics_translation_skipped_pt": "Letra já está em português",
+ "lyrics_translation_no_translator": "Tradução não configurada",
+ "lyrics_translation_no_translator_hint": "Abra Configurações → Música → Letras para escolher um tradutor",
+ "lyrics_translation_error": "Falha ao traduzir — pode tentar de novo",
+ "lyrics_translation_edited_badge": "✎ comunidade",
+ "lyrics_translation_edit_placeholder": "Reescreva esta linha",
+ "lyrics_translation_edit_save": "Salvar",
+ "lyrics_translation_edit_cancel": "Cancelar",
+ "lyrics_translation_available_hint": "Tradução pt-BR disponível 🌐",
+ "lyrics_translation_attribution": "Tradução via {{translator}}",
+ "player_resolving": "Resolvendo faixa…",
+ "player_error_network": "Sem rede agora.",
+ "player_error_auth_expired": "Sessão expirou — vou renovar.",
+ "player_error_track_unavailable": "Faixa removida da fonte.",
+ "player_error_region_blocked": "Bloqueada na sua região.",
+ "player_error_unsupported_format": "Formato não tocável aqui.",
+ "player_error_format_unavailable": "Esse vídeo precisa de login no YouTube. Abra youtube.com num navegador com a extensão Loop instalada e logue na sua conta.",
+ "player_error_unknown": "Algo deu errado por aqui.",
+ "player_action_retry": "Tentar de novo",
+ "player_action_skip": "Pular",
+ "player_action_refresh": "Renovar",
+ "player_action_configure": "Configurar",
+ "player_auto_skip_label": "Pular automaticamente da próxima vez",
+ "player_dismiss_error": "Fechar",
+ "translation_settings_title": "Tradução de letras",
+ "translation_settings_translator_label": "Tradutor",
+ "translation_settings_translator_libretranslate": "LibreTranslate (auto-hospedado)",
+ "translation_settings_translator_deepl": "DeepL (chave API sua)",
+ "translation_settings_translator_none": "Desligado",
+ "translation_settings_libretranslate_url_label": "Endereço do LibreTranslate",
+ "translation_settings_libretranslate_url_hint": "Ex.: http://localhost:5000 — deixe vazio para desligar",
+ "translation_settings_deepl_key_label": "Chave API do DeepL",
+ "translation_settings_deepl_key_hint": "Você gera em deepl.com/account. Tier Free traduz ~150 letras/mês",
+ "translation_settings_deepl_key_set": "Chave salva (mostrar/editar)",
+ "translation_settings_target_lang_label": "Idioma alvo",
+ "translation_settings_show_label": "Mostrar tradução por padrão",
+ "translation_settings_saved": "Configuração salva",
"n_selected": "{{count}} selecionadas",
"selection_aria": "Ações em seleção",
"queued_count": "{{count}} adicionadas à fila",
@@ -1017,6 +1178,14 @@
"tab_queue": "Fila",
"tab_lyrics": "Letras",
"tab_info": "Info",
+ "tab_chapters": "Capítulos",
+ "chapters_empty": "Sem capítulos disponíveis",
+ "video_mode_toggle": "Modo vídeo",
+ "video_mode_only_youtube": "Vídeo só disponível para faixas do YouTube",
+ "expand_video": "Abrir vídeo em tela cheia",
+ "watch_title": "Assistir",
+ "watch_video_unavailable": "Vídeo indisponível para esta faixa",
+ "watch_back": "Voltar para Music",
"info_no_track": "Toque uma faixa pra ver detalhes",
"field_album": "Álbum",
"field_year": "Ano",
@@ -1075,6 +1244,22 @@
"music_theme_use_dominant": "Usar cor da capa atual",
"music_theme_dominant_off": "Cor fixa",
"music_theme_dominant_on": "Auto (cor da capa)",
+ "music_theme_reduce_motion": "Reduzir animações",
+ "music_theme_reduce_motion_auto": "Seguir sistema",
+ "music_theme_reduce_motion_off": "Animações ligadas",
+ "music_theme_reduce_motion_on": "Sempre reduzir",
+ "music_theme_reduce_motion_hint": "Desliga transições e animações da seção de música. Independente da configuração global do sistema.",
+ "now_playing_title": "Tocando agora",
+ "now_playing_close": "Voltar",
+ "now_playing_tab_lyrics": "Letra",
+ "now_playing_tab_queue": "Próximas",
+ "now_playing_tab_previous": "Anterior",
+ "now_playing_lyrics_empty": "Sem letra disponível.",
+ "now_playing_lyrics_error": "Não consegui carregar a letra. Tente novamente.",
+ "now_playing_queue_empty": "Fila vazia — clique em qualquer faixa para começar.",
+ "now_playing_previous_empty": "Nada tocado nesta sessão ainda.",
+ "now_playing_no_track": "Nenhuma música em reprodução agora.",
+ "now_playing_open": "Abrir tela cheia",
"rpc_title": "Discord Rich Presence",
"rpc_intro": "Mostra o que você tá ouvindo no seu perfil do Discord. Precisa do Discord aberto na máquina.",
"rpc_connected": "Conectado",
@@ -1090,6 +1275,13 @@
"rpc_test_ok": "Conectado!",
"rpc_test_fail": "Falhou (Discord não tá rodando ou app ID inválido)",
"rpc_discord_running": "O Discord precisa estar aberto na máquina (cliente desktop, não browser).",
+ "rpc_music_section": "Como a música aparece",
+ "rpc_show_cover": "Mostrar capa do álbum",
+ "rpc_show_cover_hint": "Quando ligado, a capa da faixa atual aparece como imagem grande. Capas locais sobem só se você tem o asset no Discord Dev Portal.",
+ "rpc_show_buttons": "Mostrar botões",
+ "rpc_show_buttons_hint": "Adiciona dois botões: \"Tocar agora\" (abre a faixa na fonte) e \"Ver no GitHub\".",
+ "rpc_update_interval": "Atualizar a cada (segundos)",
+ "rpc_update_interval_hint": "Frequência da atualização durante reprodução. Mínimo 2s, máximo 30s. Discord limita a 5 updates/20s.",
"nav_youtube": "YouTube",
"yt_title": "YouTube Music",
"yt_subtitle": "Importe playlists do YouTube e YouTube Music. Toca direto via stream — não baixa.",
@@ -1262,11 +1454,9 @@
"new_playlist": "Nova playlist",
"playlist_name_placeholder": "Nome da playlist…",
"no_playlists_yet": "Nenhuma playlist ainda.",
- "add_to_playlist": "Adicionar à playlist",
"added_to_playlist": "Adicionada a \"{{name}}\"",
"playlist_duplicate": "Já está em \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" criada e faixa adicionada",
- "remove_from_playlist": "Remover da playlist",
"playlist_empty_title": "Playlist vazia",
"playlist_empty_body": "Adicione faixas pelo menu ⊕ em qualquer track row.",
"playlist_not_found": "Playlist não encontrada.",
@@ -1276,12 +1466,41 @@
"delete_confirm_title": "Apagar playlist?",
"delete_confirm_msg": "A playlist \"{{name}}\" será apagada. As faixas continuam na sua biblioteca.",
"delete_confirm": "Apagar",
- "eyebrow_playlist": "Playlist",
+ "refresh_covers_action": "Atualizar capas",
+ "refresh_covers_title": "Atualizar capas das faixas?",
+ "refresh_covers_body": "Vamos baixar uma capa por faixa direto do YouTube para as {{count}} faixas dessa playlist. Costuma levar poucos segundos.",
+ "refresh_covers_hint": "As capas atuais das faixas com ID de vídeo conhecido serão substituídas.",
+ "refresh_covers_confirm": "Atualizar agora",
+ "refresh_covers_progress": "Atualizando capas — {{current}} de {{total}}",
+ "refresh_covers_done": "{{updated}} capa(s) atualizada(s) · {{skipped}} sem capa nova",
+ "transcode_eyebrow": "Ferramentas",
+ "transcode_title": "Transcodificar lote de vídeo → áudio",
+ "transcode_lead": "Converte uma pasta de vídeos baixados em arquivos de áudio. Cada saída mantém a thumbnail individual do vídeo como capa.",
+ "transcode_pick_input": "Escolher pasta com vídeos",
+ "transcode_pick_output": "Escolher pasta de saída",
+ "transcode_input_label": "Pasta de entrada",
+ "transcode_input_placeholder": "Pasta com arquivos .mp4 / .mkv / .webm",
+ "transcode_output_label": "Pasta de saída (opcional)",
+ "transcode_output_placeholder": "Por padrão, mesma pasta de entrada",
+ "transcode_format_label": "Formato de saída",
+ "transcode_quality_label": "Bitrate",
+ "transcode_browse": "Escolher…",
+ "transcode_start": "Iniciar transcodificação",
+ "transcode_starting": "Iniciando…",
+ "transcode_cancel": "Cancelar transcodificação",
+ "transcode_missing_input": "Escolha uma pasta de entrada primeiro.",
+ "transcode_state_running": "Transcodificando…",
+ "transcode_state_done": "Concluído",
+ "transcode_state_cancelled": "Cancelado",
+ "transcode_eta": "Tempo restante",
+ "transcode_done": "{{current}} de {{total}} arquivos transcodificados",
+ "transcode_cancelled": "Transcodificação cancelada",
+ "nav_transcode": "Transcodificar",
"eyebrow_artist": "Artista",
"discography": "Discografia",
"queue_title": "Fila",
"queue_aria": "Fila de reprodução",
- "queue_empty": "A fila está vazia.",
+ "queue_empty": "Fila vazia — clique em qualquer faixa para começar.",
"queue_toggle": "Alternar fila",
"search_hint": "Digite o título de uma faixa, artista ou álbum.",
"exit": "Sair",
@@ -1291,7 +1510,6 @@
"open_album": "Abrir álbum",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "Nenhum álbum encontrado.",
"artists_empty": "Nenhum artista encontrado.",
@@ -1308,7 +1526,93 @@
"root_removed": "Pasta removida: {{path}}",
"nav_albums": "Álbuns",
"nav_artists": "Artistas",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "Digite título, artista ou álbum pra buscar na sua biblioteca local.",
+ "history_now": "agora",
+ "history_unplayable": "Não consegui reproduzir essa entrada — faixa não está mais disponível.",
+ "history_clear_confirm_yt": "Isso vai apagar todo seu histórico de YouTube. Continuar?",
+ "history_clear_confirm_local": "Isso vai apagar todo seu histórico local. Continuar?",
+ "history_clear": "Limpar",
+ "history_title": "Histórico",
+ "history_title_yt": "Histórico do YouTube",
+ "history_empty_title_yt": "Seu histórico de YouTube começa quando você tocar algo",
+ "history_empty_cta_yt": "Buscar no YouTube",
+ "history_empty_title_local": "Seu histórico começa quando você tocar algo da sua biblioteca",
+ "history_empty_cta_local": "Buscar na biblioteca",
+ "history_filter_local": "Local",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "Filtrar por fonte",
+ "history_remove_aria": "Remover do histórico",
+ "history_entries_removed": "entradas removidas",
+ "youtube": {
+ "shelf_group": "Do YouTube",
+ "shelf_charts": "Paradas musicais",
+ "shelf_charts_empty": "Paradas indisponíveis agora. Tenta daqui a pouco.",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "Sem lançamentos novos agora. Volta amanhã.",
+ "shelf_moods_and_genres": "Climas e gêneros",
+ "moods_empty": "Climas indisponíveis agora. Tenta daqui a pouco.",
+ "shelf_trending": "Em alta agora",
+ "shelf_trending_error": "YouTube indisponível agora. Tenta de novo em alguns minutos.",
+ "shelf_quick_picks": "Pra você",
+ "shelf_quick_picks_empty": "A gente vai aprender o que você curte. Toque algumas faixas pra começar.",
+ "shelf_daily_discover": "Descoberta do dia",
+ "shelf_daily_discover_empty": "Toque uma faixa que você gosta pra a gente sugerir o que vem em seguida.",
+ "shelf_continue_watching": "Continue assistindo",
+ "shelf_continue_watching_empty": "Nada pra retomar ainda. Toque algo pra começar.",
+ "shelf_subscriptions": "Inscrições",
+ "shelf_subscriptions_empty": "Curta um canal pra ver novidades aqui.",
+ "explore_title": "Explorar",
+ "explore_tagline": "Descobre música nova sem decidir nada agora.",
+ "back_to_explore": "Voltar pra Explorar",
+ "mood_loading_error": "Não consegui carregar este clima. Tenta de novo.",
+ "mood_empty": "Esse clima não tem playlists agora. Talvez em outro horário.",
+ "hub_title": "YouTube",
+ "hub_tagline": "Música e vídeos do YouTube em um só lugar.",
+ "search_filter_aria": "Filtrar resultados",
+ "search_filter_all": "Tudo",
+ "search_filter_music": "Música",
+ "search_filter_videos": "Vídeos",
+ "search_filter_channels": "Canais",
+ "search_filter_playlists": "Playlists",
+ "search_sort_aria": "Ordenar resultados",
+ "search_sort_relevance": "Relevância",
+ "search_sort_recent": "Mais recentes",
+ "search_sort_views": "Mais vistos",
+ "search_history_label": "Buscas recentes",
+ "search_history_clear": "Limpar histórico",
+ "search_history_remove_aria": "Remover \"{{query}}\" do histórico",
+ "subscribers_count_label": "inscritos",
+ "creator_by": "Criada por {{name}}",
+ "channel_subscribe": "Inscrever-se",
+ "channel_subscribed": "Inscrito",
+ "channel_unsubscribe_aria": "Deixar de seguir",
+ "channel_no_items": "Nada por aqui ainda.",
+ "search_placeholder": "Buscar no YouTube…",
+ "search_hint": "Comece a digitar pra ver vídeos, canais e playlists do YouTube.",
+ "connect_title": "Conecta tua conta do YouTube",
+ "connect_body": "Sua biblioteca, inscrições e onde você parou aparecem aqui depois de conectar. Sem conta, só Buscar e Explorar funcionam (anônimos).",
+ "connect_step_missing_label": "Como conectar",
+ "connect_step_missing": "Instala a extensão Loop no navegador e exporta os cookies pro arquivo abaixo. Depois volta aqui — o painel detecta sozinho.",
+ "connect_step_no_youtube_label": "Quase lá",
+ "connect_step_no_youtube": "O Loop tá instalado, mas falta fazer login no YouTube no navegador. Abre youtube.com e entra na sua conta — os cookies vão pra cá automaticamente.",
+ "connect_cta_setup": "Configurar conexão",
+ "connect_cta_anon": "Explorar sem conta",
+ "connect_footnote": "Os cookies ficam no seu computador — nada vai pra servidor nosso.",
+ "anon_speed_dial_aria": "Acesso anônimo ao YouTube"
+ },
+ "spotify_connected": "Conectado ao Spotify",
+ "spotify_auth_failed": "Falha na autenticação",
+ "spotify_library_updated": "Biblioteca atualizada",
+ "spotify_auth_waiting": "Aguardando autorização no navegador. Volte aqui depois de aceitar.",
+ "spotify_disconnected": "Desconectado do Spotify",
+ "spotify_play_via_yt": "Tocando via YouTube (modo Free)",
+ "spotify_search_aria": "Buscar no Spotify",
+ "spotify_search_label": "Buscar",
+ "spotify_refresh_label": "Atualizar",
+ "spotify_prev_aria": "Anterior",
+ "spotify_next_aria": "Próximo"
},
"library": {
"title": "Biblioteca",
@@ -2114,6 +2418,10 @@
"settings": {
"title": "Configurações",
"placeholder": "Preferências do plugin e nova varredura da biblioteca.",
+ "tab_diagnostic": "Diagnóstico",
+ "saving": "Salvando…",
+ "saved": "Salvo",
+ "categories_aria": "Categorias",
"library_section": "Biblioteca",
"rescan": "Revarrer biblioteca",
"rescan_desc": "Percorre a pasta de downloads de novo e atualiza cursos, módulos e aulas.",
@@ -2461,5 +2769,196 @@
"issues_found_toast": "{{count}} problema(s) encontrado(s)",
"verify_failed_toast": "Falha ao verificar biblioteca: {{msg}}"
}
+ },
+ "tracking": {
+ "title": "Rastreamento",
+ "subtitle_summary": "{{count}} pacote(s) · {{in_transit}} em trânsito",
+ "subtitle_empty": "Acompanhe encomendas das principais transportadoras brasileiras.",
+ "privacy_show_title": "Mostrar códigos",
+ "privacy_hide_title": "Ocultar códigos (modo streamer)",
+ "privacy_button": "Privado",
+ "refresh_all": "Atualizar tudo",
+ "refresh_all_busy": "Atualizando…",
+ "refresh_all_title": "Atualizar todos os pacotes",
+ "add_button": "+ Adicionar",
+ "search_placeholder": "Buscar por código, apelido ou status…",
+ "tab": {
+ "all": "Todos",
+ "in_transit": "Em trânsito",
+ "awaiting": "Aguardando",
+ "delivered": "Entregues",
+ "delayed": "Atrasados",
+ "archived": "Arquivados"
+ },
+ "empty": {
+ "none_title": "Nenhum pacote rastreado",
+ "none_desc": "Adicione um código de rastreio para acompanhar entregas.",
+ "none_cta": "Adicionar primeiro pacote",
+ "in_transit": "Nenhum pacote em trânsito.",
+ "awaiting": "Nenhum pacote aguardando retirada.",
+ "delivered": "Nenhum pacote entregue ainda.",
+ "delayed": "Nenhum pacote com atraso.",
+ "archived": "Nenhum pacote arquivado.",
+ "nothing": "Nada por aqui.",
+ "search": "Nenhum pacote bate com \"{{query}}\"."
+ },
+ "card": {
+ "delivered": "Entregue",
+ "days_one": "1 dia em trânsito",
+ "days_other": "{{count}} dias em trânsito",
+ "no_events": "Sem eventos",
+ "awaiting_first": "Aguardando primeira atualização…",
+ "archived_label": "Arquivado"
+ },
+ "rel": {
+ "now": "agora",
+ "minutes": "há {{count}} min",
+ "hours": "há {{count}} h"
+ },
+ "menu": {
+ "refresh": "Atualizar",
+ "refreshing": "Atualizando…",
+ "copy_code": "Copiar código",
+ "rename": "Renomear",
+ "unarchive": "Desarquivar",
+ "remove": "Remover"
+ },
+ "loading": "Carregando…",
+ "error_prefix": "Erro",
+ "toast": {
+ "added": "Pacote adicionado, atualizando…",
+ "copied": "Código copiado",
+ "copy_failed": "Não foi possível copiar",
+ "refresh_failed": "Não foi possível atualizar ({{error}})",
+ "offline": "Sem internet — atualização adiada",
+ "refresh_done": "Atualização concluída",
+ "package_removed": "Pacote removido",
+ "archived": "Pacote arquivado",
+ "unarchived": "Pacote desarquivado",
+ "cpf_updated": "CPF atualizado",
+ "status_changed": "{{code}}: {{status}}"
+ },
+ "rename_prompt": "Apelido do pacote",
+ "add_dialog": {
+ "title": "Adicionar pacote",
+ "close": "Fechar",
+ "code_label": "Código de rastreio *",
+ "code_placeholder": "Ex: AB123456789BR",
+ "alias_label": "Apelido (opcional)",
+ "alias_placeholder": "Ex: Tênis novo",
+ "cpf_label": "CPF do destinatário *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "A transportadora exige CPF para consulta.",
+ "detecting": "Detectando transportadora…",
+ "detected": "Transportadora: {{carrier}}",
+ "requires_cpf_suffix": "· CPF obrigatório",
+ "error_code_required": "Informe o código de rastreio.",
+ "error_cpf_required": "Esta transportadora exige CPF.",
+ "cancel": "Cancelar",
+ "submit": "Salvar",
+ "submitting": "Salvando…"
+ },
+ "remove_dialog": {
+ "title": "Remover pacote",
+ "question": "Tem certeza que quer remover {{name}}?",
+ "sub": "Os eventos rastreados também serão apagados.",
+ "cancel": "Cancelar",
+ "confirm": "Remover",
+ "confirming": "Removendo…",
+ "close": "Fechar"
+ },
+ "archive_prompt": {
+ "title": "Pacote entregue 🎉",
+ "body": "Quer arquivar este pacote? Ele sai da lista ativa mas o histórico fica salvo.",
+ "keep": "Não, manter",
+ "archive": "Arquivar"
+ },
+ "detail": {
+ "back": "← Rastreamento",
+ "not_found_title": "Pacote não encontrado",
+ "not_found_body": "Esse pacote pode ter sido removido.",
+ "not_found_back": "Voltar para a lista",
+ "awaiting_first": "Aguardando primeira atualização",
+ "refresh_failed_title": "Última atualização falhou.",
+ "retry": "Tentar novamente",
+ "archived_pill": "Arquivado",
+ "delivered_pill": "Entregue",
+ "days_one_pill": "1 dia em trânsito",
+ "days_other_pill": "{{count}} dias em trânsito",
+ "action": {
+ "refresh": "Atualizar",
+ "refreshing": "Atualizando…",
+ "rename": "Renomear",
+ "add_cpf": "Adicionar CPF",
+ "archive": "Arquivar",
+ "unarchive": "Desarquivar",
+ "remove": "Remover"
+ },
+ "meta": {
+ "code": "Código",
+ "cpf": "CPF",
+ "route": "Trajeto",
+ "posted_at": "Postado em",
+ "updated": "Atualizado",
+ "copy_code_title": "Copiar código",
+ "edit": "Editar"
+ },
+ "cpf_dialog": {
+ "title_add": "Adicionar CPF",
+ "title_edit": "Editar CPF",
+ "label": "CPF do destinatário",
+ "placeholder": "000.000.000-00",
+ "hint": "Deixe vazio para remover.",
+ "cancel": "Cancelar",
+ "submit": "Salvar",
+ "submitting": "Salvando…",
+ "close": "Fechar"
+ },
+ "history": {
+ "title": "Histórico",
+ "empty": "Sem eventos registrados ainda."
+ }
+ },
+ "status": {
+ "preadvice": "Pedido criado",
+ "picked_up": "Postado",
+ "in_transit": "Em trânsito",
+ "in_warehouse": "Em centro de distribuição",
+ "customs": "Em desembaraço aduaneiro",
+ "customs_held": "Retido na alfândega",
+ "customs_cleared": "Liberado da alfândega",
+ "out_for_delivery": "Saiu para entrega",
+ "awaiting_pickup": "Aguardando retirada",
+ "delivered": "Entregue",
+ "delivery_failure": "Tentativa de entrega frustrada",
+ "delayed": "Atrasado",
+ "returning_to_sender": "Em devolução",
+ "returned_to_sender": "Devolvido ao remetente",
+ "damaged": "Avariado",
+ "unknown": "Status desconhecido"
+ },
+ "carrier": {
+ "unknown": "Desconhecida"
+ },
+ "settings": {
+ "title": "Configurações",
+ "subtitle": "Preferências de notificação do rastreamento.",
+ "notifications_label": "Avisar quando o status mudar",
+ "notifications_hint": "Mostra uma notificação do sistema quando um pacote muda de etapa (ex: saiu para entrega, entregue).",
+ "test_notification": "Enviar notificação de teste",
+ "test_busy": "Enviando…",
+ "test_toast_sent": "Notificação de teste enviada",
+ "test_failed": "Não foi possível enviar a notificação",
+ "permission_denied_toast": "As notificações estão desativadas no sistema. Ative nas configurações do seu SO.",
+ "permission_denied_banner": "Notificações do sistema desativadas",
+ "permission_denied_hint": "Permita notificações do Omniget nas configurações do sistema operacional para receber atualizações dos pacotes.",
+ "request_permission": "Solicitar permissão"
+ },
+ "notification": {
+ "title_template": "{{code}}: {{status}}",
+ "body_fallback": "Status atualizado",
+ "test_title": "As notificações de rastreamento estão funcionando",
+ "test_body": "Você verá notificações assim quando os pacotes mudarem de status."
+ }
}
}
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index bcd29e8a..61b8424b 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "停止",
"confirm_remove": "移除此下载?",
+ "quality_hint": "目前下載此項目的品質",
"stats_line": "{{count}} 次下载 · 已保存 {{size}}",
"filter_label": "依狀態篩選下載",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "720p",
"quality_480p": "480p",
"quality_360p": "360p",
+ "quality_best_short": "最佳",
+ "quality_audio": "音訊",
"view_formats": "檢視格式",
"hide_formats": "隱藏格式",
"no_formats": "此影片沒有可用格式",
@@ -404,6 +407,7 @@
"preset_custom": "自訂",
"formats_presets_label": "格式預設",
"formats_merge_note": "若系統可使用 FFmpeg,影片格式 (V) 會自動與音訊 (A) 合併。",
+ "formats_playlist_note": "單一影片的格式選擇不適用於播放清單。上方的「品質」選項會套用到每一支影片。",
"referer_label": "Referer (選填)",
"referer_placeholder": "https://example.com",
"external_url_ready": "已从 Chrome 扩展收到 URL",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "這裡沒有未完成的內容。播放些什麼,稍後再回來繼續。",
+ "shelf_recent": "最近播放",
+ "shelf_recent_empty": "你的播放紀錄從下一首開始。",
+ "diag_metrics_title": "YouTube 指標",
+ "diag_refresh": "重新整理",
+ "diag_metrics_reset": "重設指標",
+ "diag_loading": "載入中…",
+ "diag_metrics_empty": "尚無資料。播放幾首曲子來累積遙測資料吧。",
+ "diag_metrics_endpoint": "端點",
+ "diag_metrics_success": "成功",
+ "diag_metrics_fail": "失敗",
+ "diag_metrics_last_error": "最後錯誤",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "JS 引擎",
+ "diag_potoken_snapshot": "快照",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "已啟用",
+ "diag_potoken_minting_pending": "待發布(數週)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "已過期",
+ "diag_potoken_visitor_active": "活躍 — {{seconds}} 秒後過期",
+ "diag_potoken_visitor_active_unknown": "活躍",
+ "diag_potoken_visitor_none": "無 token",
+ "diag_potoken_cache_count": "已快取 token 數",
+ "diag_potoken_last_generated": "產生時間",
+ "diag_loop_title": "Loop 擴充功能 (YouTube cookies)",
+ "diag_loop_missing": "找不到 cookie 檔案。",
+ "diag_loop_missing_hint": "在瀏覽器安裝 Loop 擴充功能,並將 cookies 匯出到所示路徑。",
+ "diag_loop_no_youtube": "檔案存在但沒有 YouTube cookies。",
+ "diag_loop_no_youtube_hint": "用裝有 Loop 擴充功能的瀏覽器開啟 youtube.com 並登入,cookies 會自動出現在這裡。",
+ "diag_loop_ready": "YouTube cookies 就緒。",
+ "retry": "重試",
+ "speed_dial_search": "搜尋",
+ "speed_dial_library": "音樂庫",
+ "speed_dial_playlists": "歌單",
+ "speed_dial_favorites": "我的最愛",
+ "speed_dial_history": "歷史",
+ "speed_dial_trending": "熱門",
+ "speed_dial_albums": "專輯",
+ "speed_dial_artists": "藝人",
+ "speed_dial_genres": "類型",
+ "shelf_recent_albums": "最近新增",
+ "shelf_recent_albums_empty": "在選單中指定一個音樂資料夾來掃描您的專輯。",
+ "shelf_artists": "藝人",
+ "shelf_artists_empty": "尚未編入索引的藝人。",
+ "explore_youtube_cta": "在 YouTube 中瀏覽",
+ "explore_youtube_cta_body": "發現、排行榜、新發行和訂閱。",
+ "pull_to_refresh_hint": "放開以重新整理",
+ "pull_to_refresh_release": "重新整理中…",
+ "loading": "載入中…",
+ "play_count_today": "從上次的位置繼續",
+ "history_empty_title": "你的播放紀錄從你播放的第一首開始",
+ "history_empty_cta": "在 YouTube 搜尋",
+ "back": "返回",
+ "play_all": "全部播放",
+ "shuffle_play": "隨機播放",
+ "save_playlist": "儲存",
+ "share": "分享",
+ "share_copied": "已複製連結",
+ "expandable_more": "看更多",
+ "expandable_less": "收合",
+ "album_loading_error": "無法載入這張專輯。",
+ "playlist_loading_error": "無法載入這份播放清單。",
+ "album_empty": "這張專輯沒有可用的曲目。",
+ "playlist_empty": "這份播放清單是空的。",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "歌曲",
+ "tab_videos": "影片",
+ "tab_about": "關於",
+ "shuffle_radio": "隨機電台",
+ "no_description": "沒有描述。",
+ "my_playlists_title": "我的播放清單",
+ "my_playlists_subtitle": "你用 YouTube 影片整理的本地清單。",
+ "my_playlists_empty_title": "還沒有播放清單",
+ "my_playlists_empty_body": "建立一份吧 — 資料只留在本機。",
+ "my_playlists_create": "新增播放清單",
+ "my_playlists_create_title": "建立播放清單",
+ "my_playlists_form_name": "名稱",
+ "my_playlists_form_name_placeholder": "如:讀書用",
+ "my_playlists_form_description": "描述(可選)",
+ "my_playlists_form_save": "建立",
+ "my_playlists_form_cancel": "取消",
+ "my_playlists_delete_confirm_title": "刪除播放清單?",
+ "my_playlists_delete_confirm_body": "{{count}} 部影片仍會留在 YouTube — 只有本地清單會消失。",
+ "my_playlists_delete_confirm_empty": "本地清單會消失。無法復原。",
+ "my_playlists_delete_confirm_action": "刪除播放清單",
+ "my_playlists_delete_confirm_cancel": "取消",
+ "my_playlists_rename_aria": "重新命名播放清單",
+ "my_playlists_settings_aria": "播放清單操作",
+ "my_playlists_open_aria": "開啟播放清單",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "把 {{title}} 從播放清單移除",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "從 YouTube 加入",
+ "add_to_playlist_search_placeholder": "搜尋要加入的影片…",
+ "add_to_playlist_search_short": "請輸入至少 2 個字元。",
+ "add_to_playlist_close": "關閉",
+ "add_to_playlist_added": "已加入播放清單",
+ "rename_inline_placeholder": "播放清單名稱",
+ "tracks_count_n": "{{count}} 首",
+ "track_count_one": "1 首",
+ "playlist_empty_cta": "從 YouTube 加入",
+ "shelf_spotify_recent": "Spotify · 最近播放",
+ "shelf_soundcloud_likes": "SoundCloud · 你的喜歡",
+ "history_filter_all": "全部",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "章節",
+ "chapters_empty": "沒有可用的章節",
+ "video_mode_toggle": "Video mode",
+ "video_mode_only_youtube": "Video only available for YouTube tracks",
+ "expand_video": "Open fullscreen video",
+ "watch_title": "Watch",
+ "watch_video_unavailable": "Video unavailable for this track",
+ "watch_back": "Back to music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "輸入標題、藝人或專輯名以搜尋您的本地音樂庫。",
+ "history_now": "剛剛",
+ "history_unplayable": "無法播放此項目 — 曲目已不可用。",
+ "history_clear_confirm_yt": "這將清除您所有的 YouTube 歷史記錄。繼續嗎?",
+ "history_clear_confirm_local": "這將清除您所有的本地歷史記錄。繼續嗎?",
+ "history_clear": "清除",
+ "history_title": "歷史記錄",
+ "history_title_yt": "YouTube 歷史記錄",
+ "history_empty_title_yt": "在 YouTube 上播放內容後,歷史記錄將出現在這裡",
+ "history_empty_cta_yt": "搜尋 YouTube",
+ "history_empty_title_local": "播放音樂庫中的內容後,歷史記錄將出現在這裡",
+ "history_empty_cta_local": "搜尋音樂庫",
+ "history_filter_local": "本地",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "依來源篩選",
+ "history_remove_aria": "從歷史記錄中移除",
+ "history_entries_removed": "筆記錄已移除",
+ "youtube": {
+ "shelf_group": "來自 YouTube",
+ "shelf_charts": "音樂排行",
+ "shelf_charts_empty": "現在無法取得排行,稍後再試。",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "目前沒有新發行。明天再來看看。",
+ "shelf_moods_and_genres": "情緒與曲風",
+ "moods_empty": "情緒暫時無法載入,稍後再試。",
+ "shelf_trending": "正在流行",
+ "shelf_trending_error": "現在無法連線 YouTube,幾分鐘後再試。",
+ "shelf_quick_picks": "為你推薦",
+ "shelf_quick_picks_empty": "我們還在學習你的喜好。先播放幾首歌開始吧。",
+ "shelf_daily_discover": "今日發現",
+ "shelf_daily_discover_empty": "播放一首你喜歡的,我們會推薦接下來可能想聽的。",
+ "shelf_continue_watching": "繼續觀看",
+ "shelf_continue_watching_empty": "暫時沒有可繼續的內容。播放一些來開始。",
+ "shelf_subscriptions": "訂閱",
+ "shelf_subscriptions_empty": "訂閱一個頻道,新影片會顯示在這裡。",
+ "explore_title": "探索",
+ "explore_tagline": "隨便看看,發掘新音樂。",
+ "back_to_explore": "返回探索",
+ "mood_loading_error": "無法載入這個情緒。重試。",
+ "mood_empty": "這個情緒暫時沒有歌單。稍後再來。",
+ "hub_title": "YouTube",
+ "hub_tagline": "YouTube 音樂和影片集中在同一處。",
+ "search_filter_aria": "篩選結果",
+ "search_filter_all": "全部",
+ "search_filter_music": "音樂",
+ "search_filter_videos": "影片",
+ "search_filter_channels": "頻道",
+ "search_filter_playlists": "歌單",
+ "search_sort_aria": "排序結果",
+ "search_sort_relevance": "相關度",
+ "search_sort_recent": "最新",
+ "search_sort_views": "最多觀看",
+ "search_history_label": "最近搜尋",
+ "search_history_clear": "清除歷史",
+ "search_history_remove_aria": "從歷史中移除「{{query}}」",
+ "subscribers_count_label": "訂閱者",
+ "creator_by": "由 {{name}} 建立",
+ "channel_subscribe": "訂閱",
+ "channel_subscribed": "已訂閱",
+ "channel_unsubscribe_aria": "取消訂閱",
+ "channel_no_items": "暫時還沒有內容。",
+ "search_placeholder": "搜尋 YouTube…",
+ "search_hint": "開始輸入以尋找影片、頻道與播放清單。",
+ "connect_title": "連接您的 YouTube 帳戶",
+ "connect_body": "連接後,您的音樂庫、訂閱和未看完的內容將顯示在這裡。不登入時僅搜尋和探索可用(匿名)。",
+ "connect_step_missing_label": "如何連接",
+ "connect_step_missing": "在瀏覽器中安裝 Loop 擴充功能,並將 cookies 匯出到下方路徑。回到這裡 — 應用程式會自動偵測。",
+ "connect_step_no_youtube_label": "就差一步",
+ "connect_step_no_youtube": "Loop 已安裝,但您還未在瀏覽器中登入 YouTube。開啟 youtube.com 並登入 — cookies 將自動出現在這裡。",
+ "connect_cta_setup": "設定連線",
+ "connect_cta_anon": "匿名瀏覽",
+ "connect_footnote": "Cookies 保留在您的電腦上 — 不會傳送到我們的伺服器。",
+ "anon_speed_dial_aria": "匿名存取 YouTube"
+ },
+ "spotify_connected": "已連接到 Spotify",
+ "spotify_auth_failed": "認證失敗",
+ "spotify_library_updated": "音樂庫已更新",
+ "spotify_auth_waiting": "正在瀏覽器中等待授權。授權完成後請回到此處。",
+ "spotify_disconnected": "已斷開 Spotify 連線",
+ "spotify_play_via_yt": "透過 YouTube 播放(免費模式)",
+ "spotify_search_aria": "在 Spotify 搜尋",
+ "spotify_search_label": "搜尋",
+ "spotify_refresh_label": "重新整理",
+ "spotify_prev_aria": "上一個",
+ "spotify_next_aria": "下一個"
},
"library": {
"title": "課程庫",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "設定",
"placeholder": "外掛偏好設定與課程庫重新掃描。",
+ "tab_diagnostic": "診斷",
+ "saving": "儲存中…",
+ "saved": "已儲存",
+ "categories_aria": "分類",
"library_section": "課程庫",
"rescan": "重新掃描課程庫",
"rescan_desc": "再次掃描下載資料夾,重新整理課程、模組和課時。",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "發現 {{count}} 個問題",
"verify_failed_toast": "驗證庫失敗:{{msg}}"
}
+ },
+ "tracking": {
+ "title": "包裹追蹤",
+ "subtitle_summary": "{{count}} 個包裹 · {{in_transit}} 運送中",
+ "subtitle_empty": "追蹤巴西主要承運商的包裹。",
+ "privacy_show_title": "顯示編碼",
+ "privacy_hide_title": "隱藏編碼(實況模式)",
+ "privacy_button": "私密",
+ "refresh_all": "全部更新",
+ "refresh_all_busy": "更新中…",
+ "refresh_all_title": "更新所有包裹",
+ "add_button": "+ 新增",
+ "search_placeholder": "依編碼、別名或狀態搜尋…",
+ "tab": {
+ "all": "全部",
+ "in_transit": "運送中",
+ "awaiting": "等待中",
+ "delivered": "已送達",
+ "delayed": "已延誤",
+ "archived": "已封存"
+ },
+ "empty": {
+ "none_title": "尚無追蹤包裹",
+ "none_desc": "新增追蹤編碼即可掌握配送進度。",
+ "none_cta": "新增第一個包裹",
+ "in_transit": "目前沒有運送中的包裹。",
+ "awaiting": "目前沒有等待領取的包裹。",
+ "delivered": "目前沒有已送達的包裹。",
+ "delayed": "目前沒有延誤的包裹。",
+ "archived": "目前沒有已封存的包裹。",
+ "nothing": "這裡什麼也沒有。",
+ "search": "找不到符合「{{query}}」的包裹。"
+ },
+ "card": {
+ "delivered": "已送達",
+ "days_one": "運送中 1 天",
+ "days_other": "運送中 {{count}} 天",
+ "no_events": "尚無事件",
+ "awaiting_first": "等待首次更新…",
+ "archived_label": "已封存"
+ },
+ "rel": {
+ "now": "剛剛",
+ "minutes": "{{count}} 分鐘前",
+ "hours": "{{count}} 小時前"
+ },
+ "menu": {
+ "refresh": "更新",
+ "refreshing": "更新中…",
+ "copy_code": "複製編碼",
+ "rename": "重新命名",
+ "unarchive": "取消封存",
+ "remove": "移除"
+ },
+ "loading": "載入中…",
+ "error_prefix": "錯誤",
+ "toast": {
+ "added": "已新增,正在更新…",
+ "copied": "編碼已複製",
+ "copy_failed": "無法複製",
+ "refresh_failed": "無法更新({{error}})",
+ "offline": "離線 — 已延後更新",
+ "refresh_done": "更新完成",
+ "package_removed": "包裹已移除",
+ "archived": "包裹已封存",
+ "unarchived": "包裹已取消封存",
+ "cpf_updated": "CPF 已更新",
+ "status_changed": "{{code}}:{{status}}"
+ },
+ "rename_prompt": "包裹別名",
+ "add_dialog": {
+ "title": "新增包裹",
+ "close": "關閉",
+ "code_label": "追蹤編碼 *",
+ "code_placeholder": "例如:AB123456789BR",
+ "alias_label": "別名(可選)",
+ "alias_placeholder": "例如:新球鞋",
+ "cpf_label": "收件人 CPF *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "承運商查詢需要 CPF。",
+ "detecting": "辨識承運商中…",
+ "detected": "承運商:{{carrier}}",
+ "requires_cpf_suffix": "· 需要 CPF",
+ "error_code_required": "請輸入追蹤編碼。",
+ "error_cpf_required": "此承運商需要 CPF。",
+ "cancel": "取消",
+ "submit": "儲存",
+ "submitting": "儲存中…"
+ },
+ "remove_dialog": {
+ "title": "移除包裹",
+ "question": "確定要移除 {{name}} 嗎?",
+ "sub": "追蹤事件也會一併刪除。",
+ "cancel": "取消",
+ "confirm": "移除",
+ "confirming": "移除中…",
+ "close": "關閉"
+ },
+ "archive_prompt": {
+ "title": "包裹已送達 🎉",
+ "body": "要封存此包裹嗎?它會離開活動清單,但歷史紀錄會保留。",
+ "keep": "不,保留",
+ "archive": "封存"
+ },
+ "detail": {
+ "back": "← 追蹤",
+ "not_found_title": "找不到包裹",
+ "not_found_body": "此包裹可能已被移除。",
+ "not_found_back": "返回清單",
+ "awaiting_first": "等待首次更新",
+ "refresh_failed_title": "上次更新失敗。",
+ "retry": "重試",
+ "archived_pill": "已封存",
+ "delivered_pill": "已送達",
+ "days_one_pill": "運送中 1 天",
+ "days_other_pill": "運送中 {{count}} 天",
+ "action": {
+ "refresh": "更新",
+ "refreshing": "更新中…",
+ "rename": "重新命名",
+ "add_cpf": "新增 CPF",
+ "archive": "封存",
+ "unarchive": "取消封存",
+ "remove": "移除"
+ },
+ "meta": {
+ "code": "編碼",
+ "cpf": "CPF",
+ "route": "路線",
+ "posted_at": "寄出日期",
+ "updated": "更新時間",
+ "copy_code_title": "複製編碼",
+ "edit": "編輯"
+ },
+ "cpf_dialog": {
+ "title_add": "新增 CPF",
+ "title_edit": "編輯 CPF",
+ "label": "收件人 CPF",
+ "placeholder": "000.000.000-00",
+ "hint": "留空即移除。",
+ "cancel": "取消",
+ "submit": "儲存",
+ "submitting": "儲存中…",
+ "close": "關閉"
+ },
+ "history": {
+ "title": "歷史",
+ "empty": "尚無事件紀錄。"
+ }
+ },
+ "status": {
+ "preadvice": "訂單已建立",
+ "picked_up": "已寄出",
+ "in_transit": "運送中",
+ "in_warehouse": "在配送中心",
+ "customs": "海關通關中",
+ "customs_held": "海關扣留",
+ "customs_cleared": "海關放行",
+ "out_for_delivery": "派送中",
+ "awaiting_pickup": "等待領取",
+ "delivered": "已送達",
+ "delivery_failure": "派送失敗",
+ "delayed": "已延誤",
+ "returning_to_sender": "退回中",
+ "returned_to_sender": "已退回寄件人",
+ "damaged": "已損壞",
+ "unknown": "狀態未知"
+ },
+ "carrier": {
+ "unknown": "未知"
+ },
+ "settings": {
+ "title": "設定",
+ "subtitle": "包裹追蹤的通知偏好。",
+ "notifications_label": "狀態變更時通知我",
+ "notifications_hint": "當包裹進入新階段(例如派送中、已送達)時,發送系統通知。",
+ "test_notification": "傳送測試通知",
+ "test_busy": "傳送中…",
+ "test_toast_sent": "已傳送測試通知",
+ "test_failed": "無法傳送通知",
+ "permission_denied_toast": "系統層級已停用通知。請至作業系統設定中啟用。",
+ "permission_denied_banner": "系統通知已停用",
+ "permission_denied_hint": "請至作業系統設定中允許 Omniget 傳送通知,以接收包裹更新。",
+ "request_permission": "請求權限"
+ },
+ "notification": {
+ "title_template": "{{code}}:{{status}}",
+ "body_fallback": "狀態已更新",
+ "test_title": "追蹤通知運作正常",
+ "test_body": "包裹狀態變化時,您將看到此類通知。"
+ }
}
}
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index a780497e..bf1dae9e 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -73,6 +73,7 @@
"open_in_study": "Watch in Study",
"stop": "停止",
"confirm_remove": "移除此下载?",
+ "quality_hint": "正在为此项下载的质量",
"stats_line": "{{count}} 次下载 · 已保存 {{size}}",
"filter_label": "按状态筛选下载",
"filter": {
@@ -395,6 +396,8 @@
"quality_720p": "高清 (720p) — 较小",
"quality_480p": "中等 (480p) — 快速",
"quality_360p": "低清 (360p) — 极小",
+ "quality_best_short": "最佳",
+ "quality_audio": "音频",
"view_formats": "查看格式",
"hide_formats": "隐藏格式",
"no_formats": "该视频没有可用格式",
@@ -404,6 +407,7 @@
"preset_custom": "自定义",
"formats_presets_label": "格式预设",
"formats_merge_note": "如果 FFmpeg 可用,视频格式 (V) 将自动与音频 (A) 合并。",
+ "formats_playlist_note": "单视频格式选择器不适用于播放列表。上方的「质量」选项将应用于每个视频。",
"referer_label": "Referer(可选)",
"referer_placeholder": "https://example.com",
"external_url_ready": "已从 Chrome 扩展收到 URL",
@@ -921,6 +925,111 @@
"empty_no_roots_body": "Point to a folder with your audio files. MP3, FLAC, M4A, OGG, OPUS — all common formats. Nothing is copied or moved.",
"empty_no_tracks_title": "Ready to scan",
"empty_no_tracks_body": "Folders are configured but we haven't scanned yet. Click below to index your tracks.",
+ "shelf_continue_empty": "这里没有未完成的内容。播放些什么,以后回来继续。",
+ "shelf_recent": "最近播放",
+ "shelf_recent_empty": "你的播放记录从下一首开始。",
+ "diag_metrics_title": "YouTube 指标",
+ "diag_refresh": "刷新",
+ "diag_metrics_reset": "重置指标",
+ "diag_loading": "加载中…",
+ "diag_metrics_empty": "暂无数据。播放几首曲子来积累遥测数据吧。",
+ "diag_metrics_endpoint": "端点",
+ "diag_metrics_success": "成功",
+ "diag_metrics_fail": "失败",
+ "diag_metrics_last_error": "最近错误",
+ "diag_potoken_title": "PoToken",
+ "diag_potoken_engine": "JS 引擎",
+ "diag_potoken_snapshot": "快照",
+ "diag_potoken_minting": "Mint",
+ "diag_potoken_minting_active": "已激活",
+ "diag_potoken_minting_pending": "待发布(数周)",
+ "diag_potoken_visitor": "Visitor token",
+ "diag_potoken_visitor_expired": "已过期",
+ "diag_potoken_visitor_active": "活跃 — {{seconds}} 秒后过期",
+ "diag_potoken_visitor_active_unknown": "活跃",
+ "diag_potoken_visitor_none": "无 token",
+ "diag_potoken_cache_count": "缓存 token 数",
+ "diag_potoken_last_generated": "生成时间",
+ "diag_loop_title": "Loop 扩展 (YouTube cookies)",
+ "diag_loop_missing": "未找到 cookie 文件。",
+ "diag_loop_missing_hint": "在浏览器中安装 Loop 扩展,并将 cookies 导出到所示路径。",
+ "diag_loop_no_youtube": "文件存在但没有 YouTube cookies。",
+ "diag_loop_no_youtube_hint": "用安装了 Loop 扩展的浏览器打开 youtube.com 并登录,cookies 会自动出现在这里。",
+ "diag_loop_ready": "YouTube cookies 就绪。",
+ "retry": "重试",
+ "speed_dial_search": "搜索",
+ "speed_dial_library": "音乐库",
+ "speed_dial_playlists": "歌单",
+ "speed_dial_favorites": "收藏",
+ "speed_dial_history": "历史",
+ "speed_dial_trending": "热门",
+ "speed_dial_albums": "专辑",
+ "speed_dial_artists": "艺术家",
+ "speed_dial_genres": "类型",
+ "shelf_recent_albums": "最近添加",
+ "shelf_recent_albums_empty": "在菜单中指定一个音乐文件夹来扫描你的专辑。",
+ "shelf_artists": "艺术家",
+ "shelf_artists_empty": "尚未索引艺术家。",
+ "explore_youtube_cta": "在 YouTube 中浏览",
+ "explore_youtube_cta_body": "发现、排行榜、新发布和订阅。",
+ "pull_to_refresh_hint": "释放刷新",
+ "pull_to_refresh_release": "正在刷新…",
+ "loading": "加载中…",
+ "play_count_today": "从上次的位置继续",
+ "history_empty_title": "你的播放记录从你播放的第一首开始",
+ "history_empty_cta": "在 YouTube 搜索",
+ "back": "返回",
+ "play_all": "全部播放",
+ "shuffle_play": "随机播放",
+ "save_playlist": "保存",
+ "share": "分享",
+ "share_copied": "已复制链接",
+ "expandable_more": "查看更多",
+ "expandable_less": "收起",
+ "album_loading_error": "无法加载这张专辑。",
+ "playlist_loading_error": "无法加载这个播放列表。",
+ "album_empty": "这张专辑没有可用的曲目。",
+ "playlist_empty": "这个播放列表是空的。",
+ "eyebrow_playlist": "Playlist",
+ "tab_songs": "歌曲",
+ "tab_videos": "视频",
+ "tab_about": "关于",
+ "shuffle_radio": "随机电台",
+ "no_description": "没有描述。",
+ "my_playlists_title": "我的播放列表",
+ "my_playlists_subtitle": "你用 YouTube 视频整理的本地列表。",
+ "my_playlists_empty_title": "还没有播放列表",
+ "my_playlists_empty_body": "创建一个吧 — 数据只留在本地。",
+ "my_playlists_create": "新建播放列表",
+ "my_playlists_create_title": "创建播放列表",
+ "my_playlists_form_name": "名称",
+ "my_playlists_form_name_placeholder": "如:学习专用",
+ "my_playlists_form_description": "描述(可选)",
+ "my_playlists_form_save": "创建",
+ "my_playlists_form_cancel": "取消",
+ "my_playlists_delete_confirm_title": "删除播放列表?",
+ "my_playlists_delete_confirm_body": "{{count}} 个视频仍然在 YouTube 上 — 仅本地的列表消失。",
+ "my_playlists_delete_confirm_empty": "本地列表会消失。无法撤销。",
+ "my_playlists_delete_confirm_action": "删除播放列表",
+ "my_playlists_delete_confirm_cancel": "取消",
+ "my_playlists_rename_aria": "重命名播放列表",
+ "my_playlists_settings_aria": "播放列表操作",
+ "my_playlists_open_aria": "打开播放列表",
+ "remove_from_playlist": "Remove from playlist",
+ "remove_from_playlist_aria": "把 {{title}} 从播放列表移除",
+ "add_to_playlist": "Add to playlist",
+ "add_to_playlist_modal_title": "从 YouTube 添加",
+ "add_to_playlist_search_placeholder": "搜索要添加的视频…",
+ "add_to_playlist_search_short": "请输入至少 2 个字符。",
+ "add_to_playlist_close": "关闭",
+ "add_to_playlist_added": "已添加到播放列表",
+ "rename_inline_placeholder": "播放列表名称",
+ "tracks_count_n": "{{count}} 首",
+ "track_count_one": "1 首",
+ "playlist_empty_cta": "从 YouTube 添加",
+ "shelf_spotify_recent": "Spotify · 最近播放",
+ "shelf_soundcloud_likes": "SoundCloud · 你的喜欢",
+ "history_filter_all": "全部",
"empty_results": "No results.",
"empty_album": "This album is empty.",
"shelf_continue": "Continue listening",
@@ -1017,6 +1126,14 @@
"tab_queue": "Queue",
"tab_lyrics": "Lyrics",
"tab_info": "Info",
+ "tab_chapters": "章节",
+ "chapters_empty": "没有可用的章节",
+ "video_mode_toggle": "Video mode",
+ "video_mode_only_youtube": "Video only available for YouTube tracks",
+ "expand_video": "Open fullscreen video",
+ "watch_title": "Watch",
+ "watch_video_unavailable": "Video unavailable for this track",
+ "watch_back": "Back to music",
"info_no_track": "Play a track to see details",
"field_album": "Album",
"field_year": "Year",
@@ -1262,11 +1379,9 @@
"new_playlist": "New playlist",
"playlist_name_placeholder": "Playlist name…",
"no_playlists_yet": "No playlists yet.",
- "add_to_playlist": "Add to playlist",
"added_to_playlist": "Added to \"{{name}}\"",
"playlist_duplicate": "Already in \"{{name}}\"",
"created_playlist_with_track": "\"{{name}}\" created and track added",
- "remove_from_playlist": "Remove from playlist",
"playlist_empty_title": "Playlist is empty",
"playlist_empty_body": "Add tracks via the ⊕ menu on any track row.",
"playlist_not_found": "Playlist not found.",
@@ -1276,7 +1391,6 @@
"delete_confirm_title": "Delete playlist?",
"delete_confirm_msg": "Playlist \"{{name}}\" will be deleted. Tracks remain in your library.",
"delete_confirm": "Delete",
- "eyebrow_playlist": "Playlist",
"eyebrow_artist": "Artist",
"discography": "Discography",
"queue_title": "Queue",
@@ -1291,7 +1405,6 @@
"open_album": "Open album",
"shelf_listen_now": "Listen now",
"shelf_top_artists": "Top Artists",
- "shelf_new_releases": "New releases",
"jump_back_in": "Jump back in",
"albums_empty": "No albums found.",
"artists_empty": "No artists found.",
@@ -1308,7 +1421,93 @@
"root_removed": "Folder removed: {{path}}",
"nav_albums": "Albums",
"nav_artists": "Artists",
- "nav_playlists": "Playlists"
+ "nav_playlists": "Playlists",
+ "local_search_hint": "输入标题、艺人或专辑名以搜索您的本地音乐库。",
+ "history_now": "刚刚",
+ "history_unplayable": "无法播放此条目 — 曲目已不可用。",
+ "history_clear_confirm_yt": "这将清除您所有的 YouTube 历史记录。继续吗?",
+ "history_clear_confirm_local": "这将清除您所有的本地历史记录。继续吗?",
+ "history_clear": "清除",
+ "history_title": "历史记录",
+ "history_title_yt": "YouTube 历史记录",
+ "history_empty_title_yt": "在 YouTube 上播放内容后,历史记录将出现在这里",
+ "history_empty_cta_yt": "搜索 YouTube",
+ "history_empty_title_local": "播放音乐库中的内容后,历史记录将出现在这里",
+ "history_empty_cta_local": "搜索音乐库",
+ "history_filter_local": "本地",
+ "history_filter_spotify": "Spotify",
+ "history_filter_soundcloud": "SoundCloud",
+ "history_filter_aria": "按来源筛选",
+ "history_remove_aria": "从历史记录中移除",
+ "history_entries_removed": "条记录已移除",
+ "youtube": {
+ "shelf_group": "来自 YouTube",
+ "shelf_charts": "音乐榜单",
+ "shelf_charts_empty": "现在无法获取榜单,稍后再试。",
+ "shelf_new_releases": "New releases",
+ "shelf_new_releases_empty": "目前没有新发布。明天再来看看。",
+ "shelf_moods_and_genres": "情绪与流派",
+ "moods_empty": "情绪暂时无法加载,稍后再试。",
+ "shelf_trending": "正在流行",
+ "shelf_trending_error": "现在无法连接 YouTube,几分钟后再试。",
+ "shelf_quick_picks": "为你推荐",
+ "shelf_quick_picks_empty": "我们还在学习你的喜好。先播放几首歌开始吧。",
+ "shelf_daily_discover": "今日发现",
+ "shelf_daily_discover_empty": "播放一首你喜欢的,我们会推荐接下来可能想听的。",
+ "shelf_continue_watching": "继续观看",
+ "shelf_continue_watching_empty": "暂时没有可继续的内容。播放一些来开始。",
+ "shelf_subscriptions": "订阅",
+ "shelf_subscriptions_empty": "关注一个频道,新视频会显示在这里。",
+ "explore_title": "探索",
+ "explore_tagline": "随便看看,发现新音乐。",
+ "back_to_explore": "返回探索",
+ "mood_loading_error": "无法加载这个情绪。重试。",
+ "mood_empty": "这个情绪暂时没有歌单。稍后再来。",
+ "hub_title": "YouTube",
+ "hub_tagline": "YouTube 音乐和视频集中在一处。",
+ "search_filter_aria": "筛选结果",
+ "search_filter_all": "全部",
+ "search_filter_music": "音乐",
+ "search_filter_videos": "视频",
+ "search_filter_channels": "频道",
+ "search_filter_playlists": "歌单",
+ "search_sort_aria": "排序结果",
+ "search_sort_relevance": "相关度",
+ "search_sort_recent": "最新",
+ "search_sort_views": "最多观看",
+ "search_history_label": "最近搜索",
+ "search_history_clear": "清除历史",
+ "search_history_remove_aria": "从历史中移除「{{query}}」",
+ "subscribers_count_label": "订阅者",
+ "creator_by": "由 {{name}} 创建",
+ "channel_subscribe": "订阅",
+ "channel_subscribed": "已订阅",
+ "channel_unsubscribe_aria": "取消订阅",
+ "channel_no_items": "暂时还没有内容。",
+ "search_placeholder": "搜索 YouTube…",
+ "search_hint": "开始输入以查找视频、频道和播放列表。",
+ "connect_title": "连接您的 YouTube 账户",
+ "connect_body": "连接后,您的音乐库、订阅和未看完的内容将显示在这里。不登录时仅搜索和发现可用(匿名)。",
+ "connect_step_missing_label": "如何连接",
+ "connect_step_missing": "在浏览器中安装 Loop 扩展程序,并将 cookies 导出到下方路径。回到这里 — 应用会自动检测。",
+ "connect_step_no_youtube_label": "就差一步",
+ "connect_step_no_youtube": "Loop 已安装,但您还未在浏览器中登录 YouTube。打开 youtube.com 并登录 — cookies 将自动出现在这里。",
+ "connect_cta_setup": "设置连接",
+ "connect_cta_anon": "匿名浏览",
+ "connect_footnote": "Cookies 保留在您的电脑上 — 不会发送到我们的服务器。",
+ "anon_speed_dial_aria": "匿名访问 YouTube"
+ },
+ "spotify_connected": "已连接到 Spotify",
+ "spotify_auth_failed": "认证失败",
+ "spotify_library_updated": "音乐库已更新",
+ "spotify_auth_waiting": "正在浏览器中等待授权。授权完成后请返回此处。",
+ "spotify_disconnected": "已断开 Spotify 连接",
+ "spotify_play_via_yt": "通过 YouTube 播放(免费模式)",
+ "spotify_search_aria": "在 Spotify 中搜索",
+ "spotify_search_label": "搜索",
+ "spotify_refresh_label": "刷新",
+ "spotify_prev_aria": "上一个",
+ "spotify_next_aria": "下一个"
},
"library": {
"title": "课程库",
@@ -2114,6 +2313,10 @@
"settings": {
"title": "设置",
"placeholder": "插件首选项与课程库重新扫描。",
+ "tab_diagnostic": "诊断",
+ "saving": "保存中…",
+ "saved": "已保存",
+ "categories_aria": "分类",
"library_section": "课程库",
"rescan": "重新扫描课程库",
"rescan_desc": "再次扫描下载文件夹,刷新课程、模块和课时。",
@@ -2461,5 +2664,196 @@
"issues_found_toast": "发现 {{count}} 个问题",
"verify_failed_toast": "验证库失败:{{msg}}"
}
+ },
+ "tracking": {
+ "title": "包裹追踪",
+ "subtitle_summary": "{{count}} 个包裹 · {{in_transit}} 运输中",
+ "subtitle_empty": "追踪巴西主要承运商的包裹。",
+ "privacy_show_title": "显示编码",
+ "privacy_hide_title": "隐藏编码(主播模式)",
+ "privacy_button": "私密",
+ "refresh_all": "全部刷新",
+ "refresh_all_busy": "刷新中…",
+ "refresh_all_title": "刷新所有包裹",
+ "add_button": "+ 添加",
+ "search_placeholder": "按编码、别名或状态搜索…",
+ "tab": {
+ "all": "全部",
+ "in_transit": "运输中",
+ "awaiting": "等待中",
+ "delivered": "已送达",
+ "delayed": "已延误",
+ "archived": "已归档"
+ },
+ "empty": {
+ "none_title": "暂无追踪包裹",
+ "none_desc": "添加追踪编码即可跟进配送进度。",
+ "none_cta": "添加首个包裹",
+ "in_transit": "暂无运输中的包裹。",
+ "awaiting": "暂无等待自提的包裹。",
+ "delivered": "暂无已送达的包裹。",
+ "delayed": "暂无延误包裹。",
+ "archived": "暂无已归档包裹。",
+ "nothing": "这里什么也没有。",
+ "search": "未找到与「{{query}}」匹配的包裹。"
+ },
+ "card": {
+ "delivered": "已送达",
+ "days_one": "运输中 1 天",
+ "days_other": "运输中 {{count}} 天",
+ "no_events": "暂无事件",
+ "awaiting_first": "等待首次更新…",
+ "archived_label": "已归档"
+ },
+ "rel": {
+ "now": "刚刚",
+ "minutes": "{{count}} 分钟前",
+ "hours": "{{count}} 小时前"
+ },
+ "menu": {
+ "refresh": "刷新",
+ "refreshing": "刷新中…",
+ "copy_code": "复制编码",
+ "rename": "重命名",
+ "unarchive": "取消归档",
+ "remove": "删除"
+ },
+ "loading": "加载中…",
+ "error_prefix": "错误",
+ "toast": {
+ "added": "已添加,正在刷新…",
+ "copied": "编码已复制",
+ "copy_failed": "无法复制",
+ "refresh_failed": "无法刷新({{error}})",
+ "offline": "离线 — 已暂缓刷新",
+ "refresh_done": "刷新完成",
+ "package_removed": "包裹已删除",
+ "archived": "包裹已归档",
+ "unarchived": "包裹已取消归档",
+ "cpf_updated": "CPF 已更新",
+ "status_changed": "{{code}}:{{status}}"
+ },
+ "rename_prompt": "包裹别名",
+ "add_dialog": {
+ "title": "添加包裹",
+ "close": "关闭",
+ "code_label": "追踪编码 *",
+ "code_placeholder": "例如:AB123456789BR",
+ "alias_label": "别名(可选)",
+ "alias_placeholder": "例如:新球鞋",
+ "cpf_label": "收件人 CPF *",
+ "cpf_placeholder": "000.000.000-00",
+ "cpf_hint": "承运商查询需要 CPF。",
+ "detecting": "正在识别承运商…",
+ "detected": "承运商:{{carrier}}",
+ "requires_cpf_suffix": "· 需要 CPF",
+ "error_code_required": "请输入追踪编码。",
+ "error_cpf_required": "该承运商需要 CPF。",
+ "cancel": "取消",
+ "submit": "保存",
+ "submitting": "保存中…"
+ },
+ "remove_dialog": {
+ "title": "删除包裹",
+ "question": "确定要删除 {{name}} 吗?",
+ "sub": "追踪事件也会一并删除。",
+ "cancel": "取消",
+ "confirm": "删除",
+ "confirming": "删除中…",
+ "close": "关闭"
+ },
+ "archive_prompt": {
+ "title": "包裹已送达 🎉",
+ "body": "要归档这个包裹吗?它会离开活动列表,但历史记录会保留。",
+ "keep": "不,保留",
+ "archive": "归档"
+ },
+ "detail": {
+ "back": "← 追踪",
+ "not_found_title": "包裹未找到",
+ "not_found_body": "该包裹可能已被删除。",
+ "not_found_back": "返回列表",
+ "awaiting_first": "等待首次更新",
+ "refresh_failed_title": "上次刷新失败。",
+ "retry": "重试",
+ "archived_pill": "已归档",
+ "delivered_pill": "已送达",
+ "days_one_pill": "运输中 1 天",
+ "days_other_pill": "运输中 {{count}} 天",
+ "action": {
+ "refresh": "刷新",
+ "refreshing": "刷新中…",
+ "rename": "重命名",
+ "add_cpf": "添加 CPF",
+ "archive": "归档",
+ "unarchive": "取消归档",
+ "remove": "删除"
+ },
+ "meta": {
+ "code": "编码",
+ "cpf": "CPF",
+ "route": "路线",
+ "posted_at": "寄出日期",
+ "updated": "更新",
+ "copy_code_title": "复制编码",
+ "edit": "编辑"
+ },
+ "cpf_dialog": {
+ "title_add": "添加 CPF",
+ "title_edit": "编辑 CPF",
+ "label": "收件人 CPF",
+ "placeholder": "000.000.000-00",
+ "hint": "留空则删除。",
+ "cancel": "取消",
+ "submit": "保存",
+ "submitting": "保存中…",
+ "close": "关闭"
+ },
+ "history": {
+ "title": "历史",
+ "empty": "尚无事件记录。"
+ }
+ },
+ "status": {
+ "preadvice": "订单已创建",
+ "picked_up": "已寄出",
+ "in_transit": "运输中",
+ "in_warehouse": "在配送中心",
+ "customs": "海关清关中",
+ "customs_held": "海关扣留",
+ "customs_cleared": "海关放行",
+ "out_for_delivery": "派送中",
+ "awaiting_pickup": "等待自提",
+ "delivered": "已送达",
+ "delivery_failure": "派送失败",
+ "delayed": "已延误",
+ "returning_to_sender": "退回中",
+ "returned_to_sender": "已退回寄件人",
+ "damaged": "已损坏",
+ "unknown": "状态未知"
+ },
+ "carrier": {
+ "unknown": "未知"
+ },
+ "settings": {
+ "title": "设置",
+ "subtitle": "包裹跟踪的通知偏好。",
+ "notifications_label": "状态变更时通知我",
+ "notifications_hint": "当包裹进入新阶段(例如派送中、已送达)时,发送系统通知。",
+ "test_notification": "发送测试通知",
+ "test_busy": "发送中…",
+ "test_toast_sent": "已发送测试通知",
+ "test_failed": "无法发送通知",
+ "permission_denied_toast": "系统级别已禁用通知。请在操作系统设置中启用。",
+ "permission_denied_banner": "系统通知已禁用",
+ "permission_denied_hint": "请在操作系统设置中允许 Omniget 发送通知,以接收包裹更新。",
+ "request_permission": "请求权限"
+ },
+ "notification": {
+ "title_template": "{{code}}:{{status}}",
+ "body_fallback": "状态已更新",
+ "test_title": "跟踪通知正常工作",
+ "test_body": "包裹状态变化时,您将看到此类通知。"
+ }
}
}
diff --git a/src/lib/stores/changelog-store.svelte.ts b/src/lib/stores/changelog-store.svelte.ts
index f2932f7c..b4b1ee69 100644
--- a/src/lib/stores/changelog-store.svelte.ts
+++ b/src/lib/stores/changelog-store.svelte.ts
@@ -39,7 +39,7 @@ export async function initChangelog(): Promise<void> {
try {
currentVersion = await getVersion();
} catch {
- currentVersion = "0.6.0";
+ currentVersion = "0.6.1";
}
const lastSeen = localStorage.getItem(STORAGE_KEY);
diff --git a/src/lib/stores/download-store.svelte.ts b/src/lib/stores/download-store.svelte.ts
index 4fc2edcc..d5c8ad0d 100644
--- a/src/lib/stores/download-store.svelte.ts
+++ b/src/lib/stores/download-store.svelte.ts
@@ -46,6 +46,8 @@ export type GenericDownloadItem = BaseItem & {
filePath?: string;
fileCount?: number;
thumbnail_url?: string | null;
+ quality?: string | null;
+ downloadMode?: string | null;
};
export type DownloadItem = CourseDownloadItem | GenericDownloadItem;
@@ -242,6 +244,8 @@ type QueueItemInfo = {
kind?: QueueKind;
external?: boolean;
eta_seconds?: number | null;
+ quality?: string | null;
+ download_mode?: string | null;
};
function queueStatusToDownloadStatus(status: { type: string; data?: unknown }): DownloadStatus {
@@ -308,6 +312,8 @@ export function syncQueueState(items: QueueItemInfo[]) {
thumbnail_url: qi.thumbnail_url,
queueKind: qi.kind,
external: qi.external,
+ quality: qi.quality ?? null,
+ downloadMode: qi.download_mode ?? null,
});
if (dlStatus === "downloading" || dlStatus === "seeding") {
@@ -388,6 +394,8 @@ export function upsertGenericProgress(
status: resolvedStatus,
startedAt: existing?.startedAt ?? now,
lastUpdateAt: now,
+ quality: existing?.kind === "generic" ? existing.quality : undefined,
+ downloadMode: existing?.kind === "generic" ? existing.downloadMode : undefined,
});
if (resolvedStatus === "downloading") {
diff --git a/src/lib/study-bridge.ts b/src/lib/study-bridge.ts
index 73629ff4..33581fc5 100644
--- a/src/lib/study-bridge.ts
+++ b/src/lib/study-bridge.ts
@@ -611,3 +611,753 @@ export async function studySubjectsActivity(args: {
}): Promise<SubjectActivityRow[]> {
return pluginInvoke<SubjectActivityRow[]>("study", "study:subjects:activity", args);
}
+
+export type YoutubeStreamFormat = {
+ itag: number;
+ url: string | null;
+ mime_type: string;
+ bitrate: number;
+ width: number | null;
+ height: number | null;
+ fps: number | null;
+ quality_label: string | null;
+ audio_quality: string | null;
+ audio_sample_rate: number | null;
+ content_length: number | null;
+ approx_duration_ms: number | null;
+ last_modified: number | null;
+ is_adaptive: boolean;
+};
+
+export type YoutubeVideoDetails = {
+ video_id: string;
+ title: string;
+ author: string;
+ channel_id: string;
+ length_seconds: number;
+ is_live: boolean;
+ view_count: number;
+ keywords: string[];
+};
+
+export type YoutubeChapter = {
+ start_ms: number;
+ end_ms: number;
+ title: string;
+};
+
+export type YoutubePlayerResult = {
+ video_id: string;
+ status: { state: string; reason: string | null; playable: boolean };
+ video_details: YoutubeVideoDetails;
+ formats: YoutubeStreamFormat[];
+ adaptive_formats: YoutubeStreamFormat[];
+ dash_manifest_url: string | null;
+ hls_manifest_url: string | null;
+ expires_at: number;
+ has_potoken: boolean;
+ client_used: string;
+ cached: boolean;
+ chapters?: YoutubeChapter[];
+};
+
+export async function studyYoutubePlayer(args: {
+ videoId: string;
+}): Promise<YoutubePlayerResult> {
+ return pluginInvoke<YoutubePlayerResult>("study", "study:youtube:player", {
+ video_id: args.videoId,
+ });
+}
+
+export async function studyYoutubePlayerCacheClear(): Promise<{ ok: boolean }> {
+ return pluginInvoke<{ ok: boolean }>("study", "study:youtube:player_cache_clear", {});
+}
+
+export type SponsorBlockCategory =
+ | "sponsor"
+ | "selfpromo"
+ | "interaction"
+ | "intro"
+ | "outro"
+ | "preview"
+ | "music_offtopic"
+ | "filler";
+
+export type SponsorBlockSegment = {
+ category: SponsorBlockCategory | string;
+ action_type: string;
+ start_ms: number;
+ end_ms: number;
+ uuid: string;
+ votes: number;
+};
+
+export type SponsorBlockLookupResult = {
+ video_id: string;
+ segments: SponsorBlockSegment[];
+ error?: string;
+};
+
+export async function studyYoutubeSponsorblock(args: {
+ videoId: string;
+ categories?: SponsorBlockCategory[] | string[];
+}): Promise<SponsorBlockLookupResult> {
+ return pluginInvoke<SponsorBlockLookupResult>("study", "study:youtube:sponsorblock", {
+ video_id: args.videoId,
+ categories: args.categories,
+ });
+}
+
+export type YoutubeChaptersResult = {
+ video_id_or_url: string;
+ chapters: YoutubeChapter[];
+};
+
+export async function studyYoutubeChapters(args: {
+ videoId: string;
+}): Promise<YoutubeChaptersResult> {
+ return pluginInvoke<YoutubeChaptersResult>("study", "study:youtube:chapters", {
+ video_id: args.videoId,
+ });
+}
+
+export type YoutubeSearchFilter = "all" | "music" | "videos" | "channels" | "playlists" | "live";
+
+export type YoutubeSearchVideoItem = {
+ kind: "video";
+ video_id: string;
+ title: string;
+ channel_id: string | null;
+ channel_title: string | null;
+ thumbnail_url: string | null;
+ duration_text: string | null;
+ published_time_text: string | null;
+ view_count_text: string | null;
+ short_description: string | null;
+ is_live: boolean;
+};
+
+export type YoutubeSearchChannelItem = {
+ kind: "channel";
+ channel_id: string;
+ title: string;
+ handle: string | null;
+ avatar_url: string | null;
+ subscribers_text: string | null;
+ video_count_text: string | null;
+ description: string | null;
+};
+
+export type YoutubeSearchPlaylistItem = {
+ kind: "playlist";
+ playlist_id: string;
+ title: string;
+ thumbnail_url: string | null;
+ video_count: number | null;
+ channel_title: string | null;
+};
+
+export type YoutubeSearchMixItem = {
+ kind: "mix";
+ playlist_id: string;
+ title: string;
+ thumbnail_url: string | null;
+ first_video_id: string | null;
+};
+
+export type YoutubeSearchShelfItem = {
+ kind: "shelf";
+ title: string;
+ items: YoutubeSearchItem[];
+};
+
+export type YoutubeSearchItem =
+ | YoutubeSearchVideoItem
+ | YoutubeSearchChannelItem
+ | YoutubeSearchPlaylistItem
+ | YoutubeSearchMixItem
+ | YoutubeSearchShelfItem;
+
+export type YoutubeSearchResultGroup = {
+ kind: string;
+ title: string | null;
+ items: YoutubeSearchItem[];
+};
+
+export type YoutubeSearchResult = {
+ query: string;
+ filter: string;
+ estimated_results: number | null;
+ groups: YoutubeSearchResultGroup[];
+ continuation: string | null;
+};
+
+export async function studyYoutubeSearch(args: {
+ query: string;
+ filter?: YoutubeSearchFilter;
+}): Promise<YoutubeSearchResult> {
+ return pluginInvoke<YoutubeSearchResult>("study", "study:youtube:search", {
+ query: args.query,
+ filter: args.filter,
+ });
+}
+
+export type YoutubeChannelTab = "home" | "videos" | "playlists" | "shorts" | "live" | "about";
+
+export type YoutubeChannelHeader = {
+ channel_id: string;
+ title: string;
+ handle: string | null;
+ avatar_url: string | null;
+ banner_url: string | null;
+ subscribers_text: string | null;
+ video_count_text: string | null;
+ description: string | null;
+};
+
+export type YoutubeChannel = {
+ header: YoutubeChannelHeader;
+ tab: string;
+ items: YoutubeSearchItem[];
+ continuation: string | null;
+};
+
+export async function studyYoutubeChannel(args: {
+ channelId: string;
+ tab?: YoutubeChannelTab;
+}): Promise<YoutubeChannel> {
+ return pluginInvoke<YoutubeChannel>("study", "study:youtube:channel", {
+ channel_id: args.channelId,
+ tab: args.tab,
+ });
+}
+
+export type YoutubePlaylistVideo = {
+ video_id: string;
+ title: string;
+ channel_id: string | null;
+ channel_title: string | null;
+ thumbnail_url: string | null;
+ duration_text: string | null;
+ duration_seconds: number | null;
+ position: number;
+};
+
+export type YoutubePlaylistInfo = {
+ playlist_id: string;
+ title: string;
+ description: string | null;
+ thumbnail_url: string | null;
+ video_count: number | null;
+ view_count_text: string | null;
+ owner_title: string | null;
+ owner_channel_id: string | null;
+};
+
+export type YoutubePlaylist = {
+ info: YoutubePlaylistInfo;
+ videos: YoutubePlaylistVideo[];
+ continuation: string | null;
+};
+
+export async function studyYoutubePlaylist(args: {
+ playlistId: string;
+}): Promise<YoutubePlaylist> {
+ return pluginInvoke<YoutubePlaylist>("study", "study:youtube:playlist", {
+ playlist_id: args.playlistId,
+ });
+}
+
+export type YoutubeTrendingCategory = "now" | "music" | "gaming" | "movies";
+
+export type YoutubeTrendingResult = {
+ category: string;
+ items: YoutubeSearchItem[];
+};
+
+export async function studyYoutubeTrending(args?: {
+ category?: YoutubeTrendingCategory;
+}): Promise<YoutubeTrendingResult> {
+ return pluginInvoke<YoutubeTrendingResult>("study", "study:youtube:trending", {
+ category: args?.category,
+ });
+}
+
+export type YoutubeMoodCategory = {
+ title: string;
+ mood_id: string;
+ params: string | null;
+ color: string | null;
+};
+
+export type YoutubeMoodSection = {
+ title: string;
+ items: YoutubeMoodCategory[];
+};
+
+export type YoutubeMoodsResult = {
+ sections: YoutubeMoodSection[];
+};
+
+export async function studyYoutubeMoodsAndGenres(): Promise<YoutubeMoodsResult> {
+ return pluginInvoke<YoutubeMoodsResult>("study", "study:youtube:moods_and_genres", {});
+}
+
+export type YoutubeMoodPlaylistItem = {
+ playlist_id: string;
+ title: string;
+ subtitle: string | null;
+ thumbnail_url: string | null;
+};
+
+export type YoutubeMoodShelf = {
+ title: string;
+ items: YoutubeMoodPlaylistItem[];
+};
+
+export type YoutubeMoodDetail = {
+ mood_id: string;
+ title: string | null;
+ shelves: YoutubeMoodShelf[];
+};
+
+export async function studyYoutubeMoodDetail(args: {
+ moodId: string;
+ params?: string | null;
+}): Promise<YoutubeMoodDetail> {
+ return pluginInvoke<YoutubeMoodDetail>("study", "study:youtube:mood_detail", {
+ mood_id: args.moodId,
+ params: args.params ?? undefined,
+ });
+}
+
+export type YoutubeNewReleaseAlbum = {
+ browse_id: string;
+ playlist_id: string | null;
+ title: string;
+ artist: string | null;
+ year: string | null;
+ thumbnail_url: string | null;
+};
+
+export type YoutubeNewReleasesResult = {
+ albums: YoutubeNewReleaseAlbum[];
+};
+
+export async function studyYoutubeNewReleases(): Promise<YoutubeNewReleasesResult> {
+ return pluginInvoke<YoutubeNewReleasesResult>("study", "study:youtube:new_releases", {});
+}
+
+export type LoopCookieStatus = {
+ available: boolean;
+ file_path: string;
+ has_youtube: boolean;
+};
+
+export async function studyMusicLoopCookieStatus(): Promise<LoopCookieStatus> {
+ return pluginInvoke<LoopCookieStatus>("study", "study:music:loop_cookie_status", {});
+}
+
+export type YoutubePotokenStatus = {
+ engine: string;
+ snapshot_version: string;
+ minting_available: boolean;
+ minting_status: string;
+ visitor: {
+ has_token: boolean;
+ expires_in_seconds: number | null;
+ expired: boolean | null;
+ };
+ content_cached_count: number;
+ last_generated_at: number | null;
+};
+
+export async function studyYoutubePotokenStatus(): Promise<YoutubePotokenStatus> {
+ return pluginInvoke<YoutubePotokenStatus>("study", "study:youtube:potoken_status", {});
+}
+
+export type YoutubeSubscription = {
+ channel_id: string;
+ title: string;
+ thumbnail_url: string | null;
+ added_at: number;
+ last_notified_at: number | null;
+};
+
+export async function studyYoutubeSubsList(): Promise<{ subs: YoutubeSubscription[] }> {
+ return pluginInvoke<{ subs: YoutubeSubscription[] }>("study", "study:youtube:subs:list", {});
+}
+
+export async function studyYoutubeSubsAdd(args: {
+ channelId: string;
+ title: string;
+ thumbnailUrl?: string;
+}): Promise<{ ok: boolean; channel_id: string }> {
+ return pluginInvoke("study", "study:youtube:subs:add", {
+ channel_id: args.channelId,
+ title: args.title,
+ thumbnail_url: args.thumbnailUrl,
+ });
+}
+
+export async function studyYoutubeSubsRemove(args: {
+ channelId: string;
+}): Promise<{ ok: boolean; removed: boolean }> {
+ return pluginInvoke("study", "study:youtube:subs:remove", {
+ channel_id: args.channelId,
+ });
+}
+
+export async function studyYoutubeSubsIsSubscribed(args: {
+ channelId: string;
+}): Promise<{ subscribed: boolean }> {
+ return pluginInvoke("study", "study:youtube:subs:is_subscribed", {
+ channel_id: args.channelId,
+ });
+}
+
+export type YoutubeSubsFeedEntry = {
+ channel_id: string;
+ channel_title: string;
+ items: YoutubeSearchItem[];
+ error: string | null;
+};
+
+export async function studyYoutubeSubsFeed(): Promise<{ entries: YoutubeSubsFeedEntry[] }> {
+ return pluginInvoke<{ entries: YoutubeSubsFeedEntry[] }>("study", "study:youtube:subs:feed", {});
+}
+
+export type MusicHistorySource = "local" | "spotify" | "youtube" | "soundcloud";
+
+export type MusicHistoryEntry = {
+ id: number;
+ source: MusicHistorySource;
+ external_id: string | null;
+ track_id: number | null;
+ title: string;
+ artist: string | null;
+ album: string | null;
+ cover_url: string | null;
+ duration_ms: number | null;
+ position_ms: number;
+ played_at: number;
+ metadata: unknown | null;
+};
+
+export async function studyMusicHistoryAdd(args: {
+ source: MusicHistorySource;
+ title: string;
+ externalId?: string;
+ trackId?: number;
+ artist?: string;
+ album?: string;
+ coverUrl?: string;
+ durationMs?: number;
+ positionMs?: number;
+ metadata?: Record<string, unknown>;
+}): Promise<{ ok: boolean; id: number; played_at: number }> {
+ return pluginInvoke("study", "study:music:history:add", {
+ source: args.source,
+ title: args.title,
+ external_id: args.externalId,
+ track_id: args.trackId,
+ artist: args.artist,
+ album: args.album,
+ cover_url: args.coverUrl,
+ duration_ms: args.durationMs,
+ position_ms: args.positionMs ?? 0,
+ metadata: args.metadata,
+ });
+}
+
+export async function studyMusicHistoryList(args?: {
+ limit?: number;
+ source?: MusicHistorySource;
+}): Promise<{ entries: MusicHistoryEntry[] }> {
+ return pluginInvoke<{ entries: MusicHistoryEntry[] }>("study", "study:music:history:list", {
+ limit: args?.limit,
+ source: args?.source,
+ });
+}
+
+export async function studyMusicHistoryClear(args?: {
+ source?: MusicHistorySource;
+}): Promise<{ ok: boolean; removed: number }> {
+ return pluginInvoke("study", "study:music:history:clear", {
+ source: args?.source,
+ });
+}
+
+export async function studyMusicHistoryRemove(args: {
+ id: number;
+}): Promise<{ ok: boolean; removed: number }> {
+ return pluginInvoke("study", "study:music:history:remove", {
+ id: args.id,
+ });
+}
+
+export type MusicQuickPickEntry = {
+ source: MusicHistorySource;
+ external_id: string | null;
+ track_id: number | null;
+ title: string;
+ artist: string | null;
+ cover_url: string | null;
+ origin: "favorite" | "history" | "trending";
+};
+
+export async function studyMusicQuickPicks(): Promise<{
+ entries: MusicQuickPickEntry[];
+ seed: number;
+}> {
+ return pluginInvoke<{ entries: MusicQuickPickEntry[]; seed: number }>(
+ "study",
+ "study:music:quick_picks",
+ {},
+ );
+}
+
+export type MusicContinueEntry = {
+ source: MusicHistorySource;
+ external_id: string | null;
+ track_id: number | null;
+ title: string;
+ artist: string | null;
+ album: string | null;
+ cover_url: string | null;
+ duration_ms: number | null;
+ position_ms: number;
+ played_at: number;
+ progress: number;
+};
+
+export async function studyMusicContinueListening(args?: {
+ limit?: number;
+}): Promise<{ entries: MusicContinueEntry[] }> {
+ return pluginInvoke<{ entries: MusicContinueEntry[] }>(
+ "study",
+ "study:music:continue_listening",
+ { limit: args?.limit },
+ );
+}
+
+export type MusicDiscoverEntry = {
+ external_id: string;
+ title: string;
+ artist: string | null;
+ album: string | null;
+ cover_url: string | null;
+ duration_ms: number | null;
+};
+
+export async function studyMusicDailyDiscover(args?: {
+ refresh?: boolean;
+}): Promise<{
+ entries: MusicDiscoverEntry[];
+ seed_video_id: string | null;
+ seed_title: string | null;
+ from_cache: boolean;
+}> {
+ return pluginInvoke<{
+ entries: MusicDiscoverEntry[];
+ seed_video_id: string | null;
+ seed_title: string | null;
+ from_cache: boolean;
+ }>("study", "study:music:daily_discover", { refresh: args?.refresh ?? false });
+}
+
+export type YoutubeUserPlaylistSummary = {
+ id: number;
+ title: string;
+ description: string | null;
+ created_at: number;
+ updated_at: number;
+ item_count: number;
+};
+
+export type YoutubeUserPlaylistItem = {
+ video_id: string;
+ position: number;
+ added_at: number;
+ title: string | null;
+ channel_title: string | null;
+ thumbnail_url: string | null;
+ duration_ms: number | null;
+};
+
+export type YoutubeUserPlaylistDetail = {
+ summary: YoutubeUserPlaylistSummary;
+ items: YoutubeUserPlaylistItem[];
+};
+
+export async function studyYoutubeUserPlaylistCreate(args: {
+ title: string;
+ description?: string;
+}): Promise<{ id: number }> {
+ return pluginInvoke<{ id: number }>("study", "study:youtube:user_playlist:create", args);
+}
+
+export async function studyYoutubeUserPlaylistRename(args: {
+ playlistId: number;
+ title: string;
+ description?: string;
+}): Promise<{ ok: boolean; updated: boolean }> {
+ return pluginInvoke("study", "study:youtube:user_playlist:rename", {
+ playlist_id: args.playlistId,
+ title: args.title,
+ description: args.description,
+ });
+}
+
+export async function studyYoutubeUserPlaylistDelete(args: {
+ playlistId: number;
+}): Promise<{ ok: boolean; removed: boolean }> {
+ return pluginInvoke("study", "study:youtube:user_playlist:delete", {
+ playlist_id: args.playlistId,
+ });
+}
+
+export async function studyYoutubeUserPlaylistList(): Promise<{
+ playlists: YoutubeUserPlaylistSummary[];
+}> {
+ return pluginInvoke<{ playlists: YoutubeUserPlaylistSummary[] }>(
+ "study",
+ "study:youtube:user_playlist:list",
+ {},
+ );
+}
+
+export async function studyYoutubeUserPlaylistGet(args: {
+ playlistId: number;
+}): Promise<YoutubeUserPlaylistDetail> {
+ return pluginInvoke<YoutubeUserPlaylistDetail>("study", "study:youtube:user_playlist:get", {
+ playlist_id: args.playlistId,
+ });
+}
+
+export async function studyYoutubeUserPlaylistAddItem(args: {
+ playlistId: number;
+ item: {
+ video_id: string;
+ title?: string;
+ channel_title?: string;
+ thumbnail_url?: string;
+ duration_ms?: number;
+ };
+ position?: number;
+}): Promise<{ ok: boolean; position: number }> {
+ return pluginInvoke("study", "study:youtube:user_playlist:add_item", {
+ playlist_id: args.playlistId,
+ item: args.item,
+ position: args.position,
+ });
+}
+
+export async function studyYoutubeUserPlaylistRemoveItem(args: {
+ playlistId: number;
+ videoId: string;
+}): Promise<{ ok: boolean; removed: boolean }> {
+ return pluginInvoke("study", "study:youtube:user_playlist:remove_item", {
+ playlist_id: args.playlistId,
+ video_id: args.videoId,
+ });
+}
+
+export async function studyYoutubeUserPlaylistReorder(args: {
+ playlistId: number;
+ videoIds: string[];
+}): Promise<{ ok: boolean }> {
+ return pluginInvoke("study", "study:youtube:user_playlist:reorder", {
+ playlist_id: args.playlistId,
+ video_ids: args.videoIds,
+ });
+}
+
+export type YoutubeEndpointMetrics = {
+ endpoint: string;
+ success_count: number;
+ fail_count: number;
+ last_success_ts: number | null;
+ last_fail_ts: number | null;
+ last_error: string | null;
+};
+
+export async function studyYoutubeMetricsGet(): Promise<{
+ metrics: YoutubeEndpointMetrics[];
+}> {
+ return pluginInvoke<{ metrics: YoutubeEndpointMetrics[] }>(
+ "study",
+ "study:youtube:metrics:get",
+ {},
+ );
+}
+
+export async function studyYoutubeMetricsReset(): Promise<{ removed: number }> {
+ return pluginInvoke<{ removed: number }>("study", "study:youtube:metrics:reset", {});
+}
+
+export async function studyYoutubeHumanizeError(args: {
+ error: string;
+}): Promise<{ humanized: string; original: string }> {
+ return pluginInvoke<{ humanized: string; original: string }>(
+ "study",
+ "study:youtube:humanize_error",
+ { error: args.error },
+ );
+}
+
+export async function studySoundcloudHumanizeError(args: {
+ error: string;
+}): Promise<{ humanized: string; original: string }> {
+ return pluginInvoke<{ humanized: string; original: string }>(
+ "study",
+ "study:soundcloud:humanize_error",
+ { error: args.error },
+ );
+}
+
+export type LocalArtistTrack = {
+ id: number;
+ path: string;
+ title: string | null;
+ artist: string | null;
+ album: string | null;
+ album_artist: string | null;
+ year: number | null;
+ duration_ms: number | null;
+ cover_path: string | null;
+ play_count: number;
+ favorite: boolean;
+};
+
+export async function studyMusicArtistTracksLocal(args: {
+ artist: string;
+ limit?: number;
+}): Promise<{ artist: string; normalized: string; tracks: LocalArtistTrack[] }> {
+ return pluginInvoke<{ artist: string; normalized: string; tracks: LocalArtistTrack[] }>(
+ "study",
+ "study:music:artist:tracks_local",
+ { artist: args.artist, limit: args.limit ?? 100 },
+ );
+}
+
+export type AlbumLookupHit = {
+ playlist_id: string;
+ title: string;
+ thumbnail_url: string | null;
+ video_count: number | null;
+ channel_title: string | null;
+ score: number;
+};
+
+export async function studyMusicAlbumOnlineLookup(args: {
+ album: string;
+ artist?: string;
+ year?: number;
+}): Promise<{ query: string; best: AlbumLookupHit | null; candidates: AlbumLookupHit[] }> {
+ return pluginInvoke<{ query: string; best: AlbumLookupHit | null; candidates: AlbumLookupHit[] }>(
+ "study",
+ "study:music:album:online_lookup",
+ { album: args.album, artist: args.artist, year: args.year },
+ );
+}
diff --git a/src/lib/study-components/player/ChaptersList.svelte b/src/lib/study-components/player/ChaptersList.svelte
new file mode 100644
index 00000000..0c55b059
--- /dev/null
+++ b/src/lib/study-components/player/ChaptersList.svelte
@@ -0,0 +1,123 @@
+<script lang="ts">
+ import type { YoutubeChapter } from "$lib/study-bridge";
+
+ type Props = {
+ chapters: YoutubeChapter[];
+ currentTimeMs: number;
+ onJump: (toMs: number) => void;
+ compact?: boolean;
+ };
+
+ let { chapters, currentTimeMs, onJump, compact = false }: Props = $props();
+
+ const activeIndex = $derived.by(() => {
+ for (let i = 0; i < chapters.length; i += 1) {
+ const c = chapters[i];
+ if (currentTimeMs >= c.start_ms && currentTimeMs < c.end_ms) return i;
+ }
+ return -1;
+ });
+
+ function formatTime(ms: number): string {
+ const totalSec = Math.floor(ms / 1000);
+ const h = Math.floor(totalSec / 3600);
+ const m = Math.floor((totalSec % 3600) / 60);
+ const s = totalSec % 60;
+ if (h > 0) {
+ return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
+ }
+ return `${m}:${s.toString().padStart(2, "0")}`;
+ }
+
+ function handleClick(c: YoutubeChapter) {
+ onJump(c.start_ms);
+ }
+</script>
+
+{#if chapters.length > 0}
+ <ol class="chapters" class:compact aria-label="Capítulos">
+ {#each chapters as chapter, i (chapter.start_ms + ":" + chapter.title)}
+ <li>
+ <button
+ type="button"
+ class="chapter"
+ class:active={i === activeIndex}
+ onclick={() => handleClick(chapter)}
+ aria-current={i === activeIndex ? "true" : undefined}
+ >
+ <span class="time" aria-hidden="true">{formatTime(chapter.start_ms)}</span>
+ <span class="title">{chapter.title}</span>
+ </button>
+ </li>
+ {/each}
+ </ol>
+{/if}
+
+<style>
+ .chapters {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ .chapter {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ align-items: baseline;
+ gap: 10px;
+ width: 100%;
+ padding: 8px 12px;
+ background: transparent;
+ border: none;
+ border-radius: 6px;
+ color: var(--text);
+ text-align: left;
+ cursor: pointer;
+ font: inherit;
+ }
+
+ .chapter:hover {
+ background: color-mix(in oklab, var(--accent) 12%, transparent);
+ }
+
+ .chapter.active {
+ background: color-mix(in oklab, var(--accent) 18%, transparent);
+ color: var(--accent);
+ }
+
+ .chapter.active .title {
+ font-weight: 600;
+ }
+
+ .time {
+ font-variant-numeric: tabular-nums;
+ font-size: 12px;
+ color: color-mix(in oklab, var(--text) 55%, transparent);
+ min-width: 3.5ch;
+ }
+
+ .chapter.active .time {
+ color: var(--accent);
+ }
+
+ .title {
+ font-size: 13px;
+ line-height: 1.35;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+
+ .compact .chapter {
+ padding: 6px 10px;
+ }
+
+ .compact .title {
+ font-size: 12px;
+ }
+</style>
diff --git a/src/lib/study-components/player/PlayerShell.svelte b/src/lib/study-components/player/PlayerShell.svelte
index aab8e562..5de9e2e5 100644
--- a/src/lib/study-components/player/PlayerShell.svelte
+++ b/src/lib/study-components/player/PlayerShell.svelte
@@ -2,6 +2,8 @@
import { onMount } from "svelte";
import { convertFileSrc } from "@tauri-apps/api/core";
import SkipGapsButton from "./SkipGapsButton.svelte";
+ import SponsorBlockOverlay from "./SponsorBlockOverlay.svelte";
+ import ChaptersList from "./ChaptersList.svelte";
import ThumbnailScrubber from "./ThumbnailScrubber.svelte";
import type {
SubtitleTrack,
@@ -9,6 +11,8 @@
SkipGaps,
ThumbnailSlice,
StudySettings,
+ SponsorBlockSegment,
+ YoutubeChapter,
} from "$lib/study-bridge";
type Props = {
@@ -23,6 +27,9 @@
audioTracks: AudioTrack[];
skipGaps: SkipGaps | null;
thumbnails: ThumbnailSlice[];
+ sponsorBlockSegments?: SponsorBlockSegment[];
+ sponsorBlockAutoSkip?: boolean;
+ chapters?: YoutubeChapter[];
settings: StudySettings["player"] | null;
selectedSubtitleLang: string | null;
selectedAudioLang: string | null;
@@ -54,6 +61,9 @@
audioTracks,
skipGaps,
thumbnails,
+ sponsorBlockSegments = [],
+ sponsorBlockAutoSkip = false,
+ chapters = [],
settings,
selectedSubtitleLang,
selectedAudioLang,
@@ -283,6 +293,7 @@
});
let toolbarPickerOpen = $state<"subs" | "audio" | "speed" | null>(null);
+ let chaptersOpen = $state(false);
const SPEED_OPTIONS = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0];
let volumeCloseTimer: ReturnType<typeof setTimeout> | null = null;
@@ -408,6 +419,38 @@
onSkip={onSkipGap}
/>
+ <SponsorBlockOverlay
+ segments={sponsorBlockSegments}
+ {currentTimeMs}
+ autoSkip={sponsorBlockAutoSkip}
+ onSkip={(toMs) => {
+ if (videoEl) videoEl.currentTime = toMs / 1000;
+ }}
+ />
+
+ {#if chapters.length > 0 && chaptersOpen}
+ <aside class="chapters-drawer" aria-label="Capítulos">
+ <header class="chapters-drawer__header">
+ <span>Capítulos</span>
+ <button type="button" class="icon-btn" onclick={() => (chaptersOpen = false)} aria-label="Fechar capítulos">
+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+ </header>
+ <div class="chapters-drawer__body">
+ <ChaptersList
+ {chapters}
+ {currentTimeMs}
+ onJump={(toMs) => {
+ if (videoEl) videoEl.currentTime = toMs / 1000;
+ }}
+ />
+ </div>
+ </aside>
+ {/if}
+
<header class="top-bar">
<a class="back" href={backHref} aria-label="Voltar">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -572,6 +615,24 @@
</svg>
</button>
{/if}
+ {#if chapters.length > 0}
+ <button
+ type="button"
+ class="icon-btn"
+ class:active={chaptersOpen}
+ onclick={(e) => { e.stopPropagation(); chaptersOpen = !chaptersOpen; }}
+ aria-label="Capítulos"
+ >
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="8" y1="6" x2="21" y2="6" />
+ <line x1="8" y1="12" x2="21" y2="12" />
+ <line x1="8" y1="18" x2="21" y2="18" />
+ <line x1="3" y1="6" x2="3.01" y2="6" />
+ <line x1="3" y1="12" x2="3.01" y2="12" />
+ <line x1="3" y1="18" x2="3.01" y2="18" />
+ </svg>
+ </button>
+ {/if}
<button
type="button"
class="icon-btn speed-trigger"
@@ -1136,4 +1197,59 @@
transition: none;
}
}
+
+ .chapters-drawer {
+ position: absolute;
+ top: 64px;
+ right: 16px;
+ bottom: 96px;
+ width: 320px;
+ max-width: 38vw;
+ background: color-mix(in oklab, black 80%, transparent);
+ border: 1px solid color-mix(in oklab, white 12%, transparent);
+ border-radius: 12px;
+ backdrop-filter: blur(10px);
+ color: white;
+ z-index: 6;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ box-shadow: 0 12px 32px color-mix(in oklab, black 50%, transparent);
+ animation: drawer-in 200ms ease-out;
+ }
+
+ .chapters-drawer__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 14px;
+ border-bottom: 1px solid color-mix(in oklab, white 10%, transparent);
+ font-size: 13px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ }
+
+ .chapters-drawer__body {
+ flex: 1 1 auto;
+ overflow-y: auto;
+ padding: 6px;
+ }
+
+ @keyframes drawer-in {
+ from {
+ opacity: 0;
+ transform: translateX(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateX(0);
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .chapters-drawer {
+ animation: none;
+ }
+ }
</style>
diff --git a/src/lib/study-components/player/SponsorBlockOverlay.svelte b/src/lib/study-components/player/SponsorBlockOverlay.svelte
new file mode 100644
index 00000000..2063ad92
--- /dev/null
+++ b/src/lib/study-components/player/SponsorBlockOverlay.svelte
@@ -0,0 +1,168 @@
+<script lang="ts">
+ import type { SponsorBlockSegment } from "$lib/study-bridge";
+
+ type Props = {
+ segments: SponsorBlockSegment[];
+ currentTimeMs: number;
+ autoSkip?: boolean;
+ onSkip: (toMs: number, category: string) => void;
+ onDismiss?: (uuid: string) => void;
+ };
+
+ let {
+ segments,
+ currentTimeMs,
+ autoSkip = false,
+ onSkip,
+ onDismiss,
+ }: Props = $props();
+
+ const CATEGORY_LABELS: Record<string, string> = {
+ sponsor: "patrocinado",
+ selfpromo: "auto-promoção",
+ intro: "intro",
+ outro: "encerramento",
+ interaction: "pedido de interação",
+ preview: "prévia",
+ music_offtopic: "trecho não-musical",
+ filler: "enrolação",
+ };
+
+ let dismissed = $state<Set<string>>(new Set());
+ let autoSkipped = $state<Set<string>>(new Set());
+
+ const activeSegment = $derived.by(() => {
+ for (const seg of segments) {
+ if (dismissed.has(seg.uuid)) continue;
+ if (
+ currentTimeMs >= seg.start_ms &&
+ currentTimeMs < seg.start_ms + 2_000 &&
+ currentTimeMs < seg.end_ms
+ ) {
+ return seg;
+ }
+ }
+ return null;
+ });
+
+ $effect(() => {
+ if (!autoSkip) return;
+ if (!activeSegment) return;
+ if (autoSkipped.has(activeSegment.uuid)) return;
+ autoSkipped.add(activeSegment.uuid);
+ autoSkipped = new Set(autoSkipped);
+ onSkip(activeSegment.end_ms, activeSegment.category);
+ });
+
+ $effect(() => {
+ if (segments.length === 0) {
+ dismissed = new Set();
+ autoSkipped = new Set();
+ }
+ });
+
+ function label(category: string): string {
+ return CATEGORY_LABELS[category] ?? category;
+ }
+
+ function handleSkip() {
+ if (!activeSegment) return;
+ onSkip(activeSegment.end_ms, activeSegment.category);
+ }
+
+ function handleDismiss() {
+ if (!activeSegment) return;
+ dismissed.add(activeSegment.uuid);
+ dismissed = new Set(dismissed);
+ onDismiss?.(activeSegment.uuid);
+ }
+</script>
+
+{#if activeSegment && !autoSkip}
+ <div class="sb-overlay" role="region" aria-label="SponsorBlock">
+ <button type="button" class="skip-btn" onclick={handleSkip}>
+ <span>Pular {label(activeSegment.category)}</span>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="13 17 18 12 13 7" />
+ <polyline points="6 17 11 12 6 7" />
+ </svg>
+ </button>
+ <button type="button" class="dismiss-btn" onclick={handleDismiss} aria-label="Dispensar">
+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+ </div>
+{/if}
+
+<style>
+ .sb-overlay {
+ position: absolute;
+ bottom: 64px;
+ right: 16px;
+ display: inline-flex;
+ align-items: stretch;
+ gap: 0;
+ z-index: 5;
+ animation: slide-in 200ms ease-out;
+ }
+
+ .skip-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 14px;
+ background: color-mix(in oklab, black 75%, transparent);
+ color: white;
+ border: 1px solid color-mix(in oklab, white 20%, transparent);
+ border-right: none;
+ border-radius: 6px 0 0 6px;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ backdrop-filter: blur(6px);
+ box-shadow: 0 4px 12px color-mix(in oklab, black 30%, transparent);
+ }
+
+ .skip-btn:hover {
+ background: color-mix(in oklab, var(--accent) 60%, black);
+ border-color: var(--accent);
+ }
+
+ .dismiss-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0 10px;
+ background: color-mix(in oklab, black 75%, transparent);
+ color: color-mix(in oklab, white 70%, transparent);
+ border: 1px solid color-mix(in oklab, white 20%, transparent);
+ border-radius: 0 6px 6px 0;
+ cursor: pointer;
+ backdrop-filter: blur(6px);
+ box-shadow: 0 4px 12px color-mix(in oklab, black 30%, transparent);
+ }
+
+ .dismiss-btn:hover {
+ color: white;
+ background: color-mix(in oklab, black 60%, transparent);
+ }
+
+ @keyframes slide-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .sb-overlay {
+ animation: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-components/settings/DiagnosticTab.svelte b/src/lib/study-components/settings/DiagnosticTab.svelte
new file mode 100644
index 00000000..682ce145
--- /dev/null
+++ b/src/lib/study-components/settings/DiagnosticTab.svelte
@@ -0,0 +1,374 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { t } from "$lib/i18n";
+ import {
+ studyYoutubeMetricsGet,
+ studyYoutubeMetricsReset,
+ studyYoutubePotokenStatus,
+ studyMusicLoopCookieStatus,
+ type YoutubeEndpointMetrics,
+ type LoopCookieStatus,
+ } from "$lib/study-bridge";
+
+ let metrics = $state<YoutubeEndpointMetrics[]>([]);
+ let metricsLoading = $state(false);
+ let metricsError = $state<string | null>(null);
+ let resetBusy = $state(false);
+
+ type PotokenStatus = {
+ engine?: string;
+ snapshot_version?: string;
+ minting_available?: boolean;
+ minting_status?: string;
+ visitor?: {
+ has_token: boolean;
+ expires_in_seconds: number | null;
+ expired: boolean | null;
+ };
+ content_cached_count?: number;
+ last_generated_at?: number | null;
+ };
+
+ let potoken = $state<PotokenStatus | null>(null);
+ let potokenLoading = $state(false);
+ let potokenError = $state<string | null>(null);
+
+ let loop = $state<LoopCookieStatus | null>(null);
+ let loopLoading = $state(false);
+ let loopError = $state<string | null>(null);
+
+ async function loadMetrics() {
+ metricsLoading = true;
+ metricsError = null;
+ try {
+ const res = await studyYoutubeMetricsGet();
+ metrics = res.metrics ?? [];
+ } catch (e) {
+ metricsError = e instanceof Error ? e.message : String(e);
+ } finally {
+ metricsLoading = false;
+ }
+ }
+
+ async function resetMetrics() {
+ if (resetBusy) return;
+ resetBusy = true;
+ try {
+ await studyYoutubeMetricsReset();
+ await loadMetrics();
+ } catch (e) {
+ metricsError = e instanceof Error ? e.message : String(e);
+ } finally {
+ resetBusy = false;
+ }
+ }
+
+ async function loadPotoken() {
+ potokenLoading = true;
+ potokenError = null;
+ try {
+ potoken = (await studyYoutubePotokenStatus()) as PotokenStatus;
+ } catch (e) {
+ potokenError = e instanceof Error ? e.message : String(e);
+ } finally {
+ potokenLoading = false;
+ }
+ }
+
+ async function loadLoop() {
+ loopLoading = true;
+ loopError = null;
+ try {
+ loop = await studyMusicLoopCookieStatus();
+ } catch (e) {
+ loopError = e instanceof Error ? e.message : String(e);
+ } finally {
+ loopLoading = false;
+ }
+ }
+
+ function formatDateTs(ts: number | null | undefined): string {
+ if (!ts) return "—";
+ try {
+ const d = new Date(ts * 1000);
+ return d.toLocaleString();
+ } catch {
+ return String(ts);
+ }
+ }
+
+ onMount(() => {
+ void loadMetrics();
+ void loadPotoken();
+ void loadLoop();
+ });
+</script>
+
+<div class="diag">
+ <section class="card">
+ <header class="card-head">
+ <h2>{$t("study.music.diag_metrics_title")}</h2>
+ <div class="actions">
+ <button type="button" class="ghost" onclick={loadMetrics} disabled={metricsLoading}>
+ {$t("study.music.diag_refresh")}
+ </button>
+ <button type="button" class="danger" onclick={resetMetrics} disabled={resetBusy || metrics.length === 0}>
+ {$t("study.music.diag_metrics_reset")}
+ </button>
+ </div>
+ </header>
+ {#if metricsLoading && metrics.length === 0}
+ <p class="muted">{$t("study.music.diag_loading")}</p>
+ {:else if metricsError}
+ <p class="error">{metricsError}</p>
+ {:else if metrics.length === 0}
+ <p class="muted">{$t("study.music.diag_metrics_empty")}</p>
+ {:else}
+ <table>
+ <thead>
+ <tr>
+ <th>{$t("study.music.diag_metrics_endpoint")}</th>
+ <th class="num">{$t("study.music.diag_metrics_success")}</th>
+ <th class="num">{$t("study.music.diag_metrics_fail")}</th>
+ <th>{$t("study.music.diag_metrics_last_error")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each metrics as m (m.endpoint)}
+ <tr>
+ <td>{m.endpoint}</td>
+ <td class="num">{m.success_count}</td>
+ <td class="num" class:has-fails={m.fail_count > 0}>{m.fail_count}</td>
+ <td class="error-cell">{m.last_error ?? "—"}</td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+ {/if}
+ </section>
+
+ <section class="card">
+ <header class="card-head">
+ <h2>{$t("study.music.diag_potoken_title")}</h2>
+ <div class="actions">
+ <button type="button" class="ghost" onclick={loadPotoken} disabled={potokenLoading}>
+ {$t("study.music.diag_refresh")}
+ </button>
+ </div>
+ </header>
+ {#if potokenLoading && !potoken}
+ <p class="muted">{$t("study.music.diag_loading")}</p>
+ {:else if potokenError}
+ <p class="error">{potokenError}</p>
+ {:else if potoken}
+ <dl>
+ <dt>{$t("study.music.diag_potoken_engine")}</dt>
+ <dd>{potoken.engine ?? "—"}</dd>
+ <dt>{$t("study.music.diag_potoken_snapshot")}</dt>
+ <dd>{potoken.snapshot_version ?? "—"}</dd>
+ <dt>{$t("study.music.diag_potoken_minting")}</dt>
+ <dd>
+ {#if potoken.minting_available}
+ <span class="ok">{$t("study.music.diag_potoken_minting_active")}</span>
+ {:else}
+ <span class="pending">{$t("study.music.diag_potoken_minting_pending")}</span>
+ {/if}
+ </dd>
+ <dt>{$t("study.music.diag_potoken_visitor")}</dt>
+ <dd>
+ {#if potoken.visitor?.has_token}
+ {#if potoken.visitor.expired}
+ <span class="warn">{$t("study.music.diag_potoken_visitor_expired")}</span>
+ {:else if potoken.visitor.expires_in_seconds != null}
+ <span class="ok">
+ {$t("study.music.diag_potoken_visitor_active", { seconds: potoken.visitor.expires_in_seconds })}
+ </span>
+ {:else}
+ <span class="ok">{$t("study.music.diag_potoken_visitor_active_unknown")}</span>
+ {/if}
+ {:else}
+ <span class="muted">{$t("study.music.diag_potoken_visitor_none")}</span>
+ {/if}
+ </dd>
+ <dt>{$t("study.music.diag_potoken_cache_count")}</dt>
+ <dd>{potoken.content_cached_count ?? 0}</dd>
+ <dt>{$t("study.music.diag_potoken_last_generated")}</dt>
+ <dd>{formatDateTs(potoken.last_generated_at)}</dd>
+ </dl>
+ {/if}
+ </section>
+
+ <section class="card">
+ <header class="card-head">
+ <h2>{$t("study.music.diag_loop_title")}</h2>
+ <div class="actions">
+ <button type="button" class="ghost" onclick={loadLoop} disabled={loopLoading}>
+ {$t("study.music.diag_refresh")}
+ </button>
+ </div>
+ </header>
+ {#if loopLoading && !loop}
+ <p class="muted">{$t("study.music.diag_loading")}</p>
+ {:else if loopError}
+ <p class="error">{loopError}</p>
+ {:else if loop}
+ {#if !loop.available}
+ <p class="muted">{$t("study.music.diag_loop_missing")}</p>
+ <p class="hint">{$t("study.music.diag_loop_missing_hint")}</p>
+ {#if loop.file_path}
+ <code class="path">{loop.file_path}</code>
+ {/if}
+ {:else if !loop.has_youtube}
+ <p class="warn">{$t("study.music.diag_loop_no_youtube")}</p>
+ <p class="hint">{$t("study.music.diag_loop_no_youtube_hint")}</p>
+ {#if loop.file_path}
+ <code class="path">{loop.file_path}</code>
+ {/if}
+ {:else}
+ <p class="ok">{$t("study.music.diag_loop_ready")}</p>
+ {#if loop.file_path}
+ <code class="path">{loop.file_path}</code>
+ {/if}
+ {/if}
+ {/if}
+ </section>
+</div>
+
+<style>
+ .diag {
+ display: grid;
+ gap: 16px;
+ }
+ .card {
+ background: color-mix(in oklab, var(--button) 30%, transparent);
+ border: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);
+ border-radius: 12px;
+ padding: 16px 20px;
+ display: grid;
+ gap: 10px;
+ }
+ .card-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+ .card-head h2 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 700;
+ color: var(--secondary);
+ }
+ .actions {
+ display: flex;
+ gap: 8px;
+ }
+ .ghost,
+ .danger {
+ padding: 6px 12px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ background: transparent;
+ color: var(--secondary);
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .ghost:hover:not(:disabled) {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .danger {
+ color: var(--error, #dc2626);
+ border-color: color-mix(in oklab, var(--error, #dc2626) 50%, transparent);
+ }
+ .danger:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--error, #dc2626) 10%, transparent);
+ }
+ .ghost:disabled,
+ .danger:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+ }
+ th,
+ td {
+ padding: 8px 10px;
+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);
+ text-align: left;
+ vertical-align: top;
+ }
+ th {
+ font-weight: 600;
+ color: var(--tertiary);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ font-size: 11px;
+ }
+ .num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ }
+ .has-fails {
+ color: var(--error, #dc2626);
+ }
+ .error-cell {
+ max-width: 220px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: var(--tertiary);
+ font-size: 11px;
+ }
+ dl {
+ margin: 0;
+ display: grid;
+ grid-template-columns: minmax(140px, max-content) 1fr;
+ gap: 6px 12px;
+ font-size: 13px;
+ }
+ dt {
+ color: var(--tertiary);
+ font-size: 12px;
+ }
+ dd {
+ margin: 0;
+ color: var(--secondary);
+ }
+ .ok {
+ color: var(--success, #16a34a);
+ }
+ .warn,
+ .pending {
+ color: var(--warning, #f59e0b);
+ }
+ .muted {
+ color: var(--tertiary);
+ font-size: 13px;
+ margin: 0;
+ }
+ .error {
+ color: var(--error, #dc2626);
+ font-size: 13px;
+ margin: 0;
+ }
+ .hint {
+ color: var(--tertiary);
+ font-size: 12px;
+ margin: 0;
+ line-height: 1.5;
+ }
+ .path {
+ display: block;
+ padding: 6px 10px;
+ background: color-mix(in oklab, var(--button) 50%, transparent);
+ border-radius: 6px;
+ font-size: 11px;
+ word-break: break-all;
+ color: var(--tertiary);
+ }
+</style>
diff --git a/src/lib/study-components/settings/MusicSettingsTab.svelte b/src/lib/study-components/settings/MusicSettingsTab.svelte
new file mode 100644
index 00000000..634c5d4f
--- /dev/null
+++ b/src/lib/study-components/settings/MusicSettingsTab.svelte
@@ -0,0 +1,118 @@
+<script lang="ts">
+ import SettingsField from "./SettingsField.svelte";
+ import SettingsToggle from "./SettingsToggle.svelte";
+ import type { StudySettings } from "$lib/study-bridge";
+
+ type Props = {
+ settings: StudySettings;
+ onPatch: (patch: StudySettings) => void;
+ };
+
+ let { settings, onPatch }: Props = $props();
+
+ const ALL_CATEGORIES = [
+ { key: "sponsor", label: "Patrocinado" },
+ { key: "selfpromo", label: "Auto-promoção" },
+ { key: "intro", label: "Intro" },
+ { key: "outro", label: "Encerramento" },
+ { key: "interaction", label: "Pedido de interação" },
+ { key: "preview", label: "Prévia" },
+ { key: "music_offtopic", label: "Trecho não-musical" },
+ { key: "filler", label: "Enrolação" },
+ ];
+
+ const music = $derived(((settings as unknown as { music?: Record<string, unknown> }).music ?? {}) as Record<string, unknown>);
+
+ const enabled = $derived(Boolean(music.sponsorblock_enabled ?? true));
+ const autoSkip = $derived(Boolean(music.sponsorblock_auto_skip ?? false));
+ const categories = $derived(
+ Array.isArray(music.sponsorblock_categories)
+ ? (music.sponsorblock_categories as string[])
+ : ["sponsor", "selfpromo"],
+ );
+
+ function setMusic(key: string, value: unknown) {
+ const next: Record<string, unknown> = { ...music, [key]: value };
+ onPatch({ music: next } as unknown as StudySettings);
+ }
+
+ function toggleCategory(cat: string) {
+ const has = categories.includes(cat);
+ const next = has ? categories.filter((c) => c !== cat) : [...categories, cat];
+ setMusic("sponsorblock_categories", next);
+ }
+</script>
+
+<section class="tab">
+ <SettingsField
+ label="SponsorBlock"
+ description="Pula trechos patrocinados detectados pela comunidade. A request usa hash-prefix do video ID, preservando privacidade."
+ >
+ <SettingsToggle
+ value={enabled}
+ onChange={(v) => setMusic("sponsorblock_enabled", v)}
+ ariaLabel="SponsorBlock"
+ />
+ </SettingsField>
+
+ {#if enabled}
+ <SettingsField
+ label="Pular automaticamente"
+ description="Quando ativo, segmentos são pulados sem pedir confirmação. Recomendado: deixar desligado para respeitar criadores."
+ >
+ <SettingsToggle
+ value={autoSkip}
+ onChange={(v) => setMusic("sponsorblock_auto_skip", v)}
+ ariaLabel="Pular automaticamente"
+ />
+ </SettingsField>
+
+ <SettingsField
+ label="Categorias monitoradas"
+ description="Tipos de segmento que mostram o botão de pular"
+ >
+ <div class="categories">
+ {#each ALL_CATEGORIES as cat (cat.key)}
+ <label class="cat" class:active={categories.includes(cat.key)}>
+ <input
+ type="checkbox"
+ checked={categories.includes(cat.key)}
+ onchange={() => toggleCategory(cat.key)}
+ />
+ <span>{cat.label}</span>
+ </label>
+ {/each}
+ </div>
+ </SettingsField>
+ {/if}
+</section>
+
+<style>
+ .tab {
+ display: flex;
+ flex-direction: column;
+ }
+ .categories {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 8px;
+ }
+ .cat {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ border: 1px solid color-mix(in oklab, var(--text) 14%, transparent);
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 13px;
+ user-select: none;
+ }
+ .cat.active {
+ border-color: var(--accent);
+ background: color-mix(in oklab, var(--accent) 12%, transparent);
+ }
+ .cat input {
+ accent-color: var(--accent);
+ }
+</style>
diff --git a/src/lib/study-music-components/ChipsRow.svelte b/src/lib/study-music-components/ChipsRow.svelte
new file mode 100644
index 00000000..c9bdc2c5
--- /dev/null
+++ b/src/lib/study-music-components/ChipsRow.svelte
@@ -0,0 +1,65 @@
+<script lang="ts">
+ type Chip = {
+ id: string;
+ label: string;
+ };
+ type Props = {
+ chips: Chip[];
+ activeId?: string | null;
+ onSelect?: (id: string) => void;
+ ariaLabel?: string;
+ };
+ let { chips, activeId = null, onSelect, ariaLabel }: Props = $props();
+</script>
+
+<div class="chips-row" role="tablist" aria-label={ariaLabel ?? undefined}>
+ {#each chips as chip (chip.id)}
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeId === chip.id}
+ class="chip"
+ class:active={activeId === chip.id}
+ onclick={() => onSelect?.(chip.id)}
+ >
+ {chip.label}
+ </button>
+ {/each}
+</div>
+
+<style>
+ .chips-row {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding: 4px 2px;
+ scrollbar-width: none;
+ }
+ .chips-row::-webkit-scrollbar { display: none; }
+ .chip {
+ flex: 0 0 auto;
+ padding: 8px 16px;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.78);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background 160ms ease, color 160ms ease, border-color 160ms ease;
+ }
+ .chip:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: white;
+ }
+ .chip.active {
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ border-color: transparent;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .chip { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/DiscordRpcPanel.svelte b/src/lib/study-music-components/DiscordRpcPanel.svelte
index f1b0f0b9..cc289a74 100644
--- a/src/lib/study-music-components/DiscordRpcPanel.svelte
+++ b/src/lib/study-music-components/DiscordRpcPanel.svelte
@@ -11,6 +11,12 @@
connected: boolean;
};
+ type MusicSettings = {
+ show_cover: boolean;
+ show_buttons: boolean;
+ update_interval_ms: number;
+ };
+
type Props = {
open: boolean;
onClose: () => void;
@@ -19,6 +25,8 @@
let { open, onClose }: Props = $props();
let status = $state<Status | null>(null);
+ let music = $state<MusicSettings | null>(null);
+ let intervalSecondsInput = $state(5);
let appIdInput = $state("");
let imageKeyInput = $state("");
let busy = $state(false);
@@ -32,6 +40,15 @@
} catch {
status = null;
}
+ try {
+ music = await pluginInvoke<MusicSettings>(
+ "study",
+ "study:music:rpc:music_settings:get",
+ );
+ intervalSecondsInput = Math.round((music.update_interval_ms ?? 5000) / 1000);
+ } catch {
+ music = null;
+ }
}
$effect(() => {
@@ -41,6 +58,45 @@
}
});
+ async function setMusicField(
+ patch: Partial<MusicSettings>,
+ ): Promise<MusicSettings | null> {
+ if (busy) return null;
+ busy = true;
+ try {
+ const res = await pluginInvoke<MusicSettings>(
+ "study",
+ "study:music:rpc:music_settings:set",
+ patch,
+ );
+ music = res;
+ intervalSecondsInput = Math.round((res.update_interval_ms ?? 5000) / 1000);
+ return res;
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ return null;
+ } finally {
+ busy = false;
+ }
+ }
+
+ function toggleShowCover() {
+ if (!music) return;
+ void setMusicField({ show_cover: !music.show_cover });
+ }
+
+ function toggleShowButtons() {
+ if (!music) return;
+ void setMusicField({ show_buttons: !music.show_buttons });
+ }
+
+ function commitInterval() {
+ if (!music) return;
+ const seconds = Math.max(2, Math.min(30, Math.floor(Number(intervalSecondsInput) || 5)));
+ intervalSecondsInput = seconds;
+ void setMusicField({ update_interval_ms: seconds * 1000 });
+ }
+
async function toggleEnabled() {
if (!status || busy) return;
busy = true;
@@ -153,6 +209,52 @@
<span>{$t("study.music.rpc_enable")}</span>
</label>
+ {#if music && status.enabled}
+ <section class="music-section">
+ <h4>{$t("study.music.rpc_music_section")}</h4>
+ <label class="row">
+ <input
+ type="checkbox"
+ checked={music.show_cover}
+ onchange={toggleShowCover}
+ disabled={busy}
+ />
+ <div class="row-text">
+ <span>{$t("study.music.rpc_show_cover")}</span>
+ <small>{$t("study.music.rpc_show_cover_hint")}</small>
+ </div>
+ </label>
+ <label class="row">
+ <input
+ type="checkbox"
+ checked={music.show_buttons}
+ onchange={toggleShowButtons}
+ disabled={busy}
+ />
+ <div class="row-text">
+ <span>{$t("study.music.rpc_show_buttons")}</span>
+ <small>{$t("study.music.rpc_show_buttons_hint")}</small>
+ </div>
+ </label>
+ <label class="row interval">
+ <div class="row-text">
+ <span>{$t("study.music.rpc_update_interval")}</span>
+ <small>{$t("study.music.rpc_update_interval_hint")}</small>
+ </div>
+ <input
+ type="number"
+ min="2"
+ max="30"
+ step="1"
+ bind:value={intervalSecondsInput}
+ onblur={commitInterval}
+ onchange={commitInterval}
+ disabled={busy}
+ />
+ </label>
+ </section>
+ {/if}
+
<details class="advanced">
<summary>{$t("study.music.rpc_advanced")}</summary>
<div class="adv-body">
@@ -296,6 +398,67 @@
border-radius: 10px;
}
.toggle input { width: 14px; height: 14px; accent-color: var(--accent); }
+ .music-section {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 12px 14px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 10px;
+ }
+ .music-section h4 {
+ margin: 0;
+ font-size: 11px;
+ font-weight: 700;
+ color: rgba(255, 255, 255, 0.55);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ }
+ .row {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ cursor: pointer;
+ }
+ .row input[type="checkbox"] {
+ width: 14px;
+ height: 14px;
+ margin-top: 2px;
+ accent-color: var(--accent);
+ }
+ .row.interval {
+ align-items: center;
+ justify-content: space-between;
+ cursor: default;
+ }
+ .row.interval input[type="number"] {
+ width: 72px;
+ padding: 6px 8px;
+ background: rgba(0, 0, 0, 0.3);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 6px;
+ color: rgba(255, 255, 255, 0.95);
+ font-family: ui-monospace, monospace;
+ font-size: 12px;
+ outline: none;
+ text-align: right;
+ }
+ .row.interval input[type="number"]:focus { border-color: var(--accent); }
+ .row-text {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .row-text span {
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.9);
+ }
+ .row-text small {
+ font-size: 11px;
+ line-height: 1.4;
+ color: rgba(255, 255, 255, 0.45);
+ }
.advanced {
background: rgba(0, 0, 0, 0.2);
border: 1px solid rgba(255, 255, 255, 0.06);
diff --git a/src/lib/study-music-components/DownloadsDock.svelte b/src/lib/study-music-components/DownloadsDock.svelte
new file mode 100644
index 00000000..32d4ca2d
--- /dev/null
+++ b/src/lib/study-music-components/DownloadsDock.svelte
@@ -0,0 +1,579 @@
+<script lang="ts">
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ downloadStore,
+ type DownloadJobState,
+ } from "$lib/study-music/download-store.svelte";
+ import { soundcloudStore } from "$lib/study-music/soundcloud-store.svelte";
+ import { colorFromString } from "$lib/study-music/format";
+ import { getLastCodec, getLastDownloadDir } from "$lib/study-music/local-prefs";
+
+ const jobs = $derived(downloadStore.jobsList);
+ const activeCount = $derived(downloadStore.activeCount);
+ const hasJobs = $derived(downloadStore.hasJobs);
+ const drawerOpen = $derived(downloadStore.drawerOpen);
+
+ function stageLabel(job: DownloadJobState): string {
+ if (job.error) return "Falhou";
+ if (job.stage === "pending") return "Aguardando…";
+ if (job.stage === "starting") return "Preparando…";
+ if (job.stage === "downloading") {
+ if (job.kind === "bulk") {
+ return `Baixando ${job.currentCount ?? 0}/${job.totalCount ?? 0}`;
+ }
+ return "Salvando faixa…";
+ }
+ if (job.stage === "skipped") return "Já tinha";
+ if (job.stage === "done") {
+ if (job.kind === "bulk") {
+ const ok = job.successCount ?? 0;
+ const fail = job.failedCount ?? 0;
+ return `Pronto · ${ok} ok${fail > 0 ? ` · ${fail} falhou` : ""}`;
+ }
+ return "Pronto";
+ }
+ return job.stage;
+ }
+
+ function fallbackColor(job: DownloadJobState): string {
+ return colorFromString(job.title || "track");
+ }
+
+ async function retrySingle(job: DownloadJobState) {
+ if (job.trackId === undefined) return;
+ const codec = getLastCodec() ?? "mp3";
+ const dir = getLastDownloadDir();
+ if (!dir) {
+ showToast("error", "Escolhe a pasta de novo no botão de baixar.");
+ downloadStore.removeJob(job.id);
+ return;
+ }
+ downloadStore.removeJob(job.id);
+ const optimisticId = downloadStore.addOptimisticSingleJob({
+ trackId: job.trackId,
+ title: job.title,
+ artist: job.artist,
+ artwork: job.artwork,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: job.trackId,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ } catch (e) {
+ downloadStore.markJobError(
+ optimisticId,
+ e instanceof Error ? e.message : String(e),
+ );
+ }
+ }
+
+ async function retryFailedFromBulk(
+ job: DownloadJobState,
+ failed: { id: number; title: string; error?: string },
+ ) {
+ const codec = job.codec ?? getLastCodec() ?? "mp3";
+ const dir = job.outputDir ?? getLastDownloadDir();
+ if (!dir) {
+ showToast("error", "Escolhe a pasta de novo no botão de baixar.");
+ return;
+ }
+ downloadStore.removeFailedTrackFromBulk(job.id, failed.id);
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: failed.id,
+ title: failed.title,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: failed.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function retryAllFailed(job: DownloadJobState) {
+ const codec = job.codec ?? getLastCodec() ?? "mp3";
+ const dir = job.outputDir ?? getLastDownloadDir();
+ if (!dir) {
+ showToast("error", "Escolhe a pasta de novo no botão de baixar.");
+ return;
+ }
+ const failed = downloadStore.consumeFailedTracks(job.id);
+ if (failed.length === 0) return;
+ for (const f of failed) {
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: f.id,
+ title: f.title,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: f.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+ }
+
+ function toggleExpand(job: DownloadJobState) {
+ downloadStore.toggleExpanded(job.id);
+ }
+
+ function dismiss(job: DownloadJobState) {
+ downloadStore.removeJob(job.id);
+ }
+
+ function openExternal(url?: string | null) {
+ if (!url) return;
+ void (async () => {
+ try {
+ const opener = await import("@tauri-apps/plugin-opener");
+ await opener.openUrl(url);
+ } catch {
+ try {
+ window.open(url, "_blank");
+ } catch {
+ /* ignore */
+ }
+ }
+ })();
+ }
+
+ function toggleDrawer() {
+ downloadStore.toggleDrawer();
+ }
+
+ function clearDone() {
+ downloadStore.clearCompleted();
+ }
+</script>
+
+{#if hasJobs}
+ <button
+ type="button"
+ class="fab"
+ class:active={activeCount > 0}
+ onclick={toggleDrawer}
+ aria-label={drawerOpen ? "Fechar downloads" : "Abrir downloads"}
+ title={drawerOpen ? "Fechar downloads" : "Downloads"}
+ >
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="7 10 12 15 17 10"/>
+ <line x1="12" y1="15" x2="12" y2="3"/>
+ </svg>
+ {#if activeCount > 0}
+ <span class="badge">{activeCount}</span>
+ {/if}
+ </button>
+{/if}
+
+{#if drawerOpen && hasJobs}
+ <aside class="drawer" role="dialog" aria-label="Downloads">
+ <header class="drawer-head">
+ <span class="drawer-title">
+ Downloads <span class="muted">({jobs.length})</span>
+ </span>
+ <div class="head-actions">
+ <button type="button" class="link" onclick={clearDone}>Limpar concluídos</button>
+ <button type="button" class="close" onclick={toggleDrawer} aria-label="Fechar">×</button>
+ </div>
+ </header>
+
+ <div class="list">
+ {#each jobs as job (job.id)}
+ {@const failedList = job.failedTracks ?? []}
+ {@const canExpand = job.kind === "bulk" && failedList.length > 0}
+ <div class="row" class:err={!!job.error}>
+ <div class="cover">
+ {#if job.artwork}
+ <img src={job.artwork} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fb" style:background={fallbackColor(job)}></div>
+ {/if}
+ </div>
+ <div class="meta">
+ <span class="title" title={job.title}>{job.title}</span>
+ <span class="sub">
+ {#if job.kind === "single" && job.artist}
+ {job.artist} ·
+ {/if}
+ {stageLabel(job)}
+ </span>
+ {#if job.kind === "bulk" && job.stage === "downloading" && job.currentTrackTitle}
+ <span class="sub thin">↳ {job.currentTrackTitle}</span>
+ {/if}
+ <div class="bar" class:err={!!job.error}>
+ <div class="fill" style:width={`${job.progressPct}%`}></div>
+ </div>
+ {#if job.error}
+ <span class="err-text" title={job.error}>{job.error}</span>
+ {/if}
+ {#if canExpand}
+ <div class="bulk-actions">
+ <button
+ type="button"
+ class="expand-btn"
+ onclick={() => toggleExpand(job)}
+ aria-expanded={!!job.expanded}
+ >
+ <span class="chev" class:open={job.expanded}>▸</span>
+ {failedList.length} {failedList.length === 1 ? "falhou" : "falharam"}
+ </button>
+ <button
+ type="button"
+ class="retry-all"
+ onclick={() => retryAllFailed(job)}
+ title="Tentar todas falhadas"
+ >
+ Tentar todas
+ </button>
+ </div>
+ {#if job.expanded}
+ <ul class="failed-list">
+ {#each failedList as ft (ft.id)}
+ <li class="failed-row">
+ <span class="failed-title" title={ft.title}>{ft.title}</span>
+ {#if ft.error}
+ <span class="failed-err" title={ft.error}>{ft.error}</span>
+ {/if}
+ <button
+ type="button"
+ class="failed-retry"
+ onclick={() => retryFailedFromBulk(job, ft)}
+ >
+ Tentar
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ {/if}
+ </div>
+ <div class="row-actions">
+ {#if job.error && job.kind === "single"}
+ <button type="button" class="action-btn" onclick={() => retrySingle(job)}>
+ Tentar de novo
+ </button>
+ {/if}
+ {#if job.stage === "done" && job.permalinkUrl}
+ <button
+ type="button"
+ class="ghost-btn"
+ onclick={() => openExternal(job.permalinkUrl)}
+ title="Abrir no SoundCloud"
+ aria-label="Abrir no SoundCloud"
+ >
+ ↗
+ </button>
+ {/if}
+ {#if job.stage === "done" || job.stage === "skipped" || job.error}
+ <button
+ type="button"
+ class="ghost-btn"
+ onclick={() => dismiss(job)}
+ aria-label="Remover"
+ title="Remover"
+ >
+ ×
+ </button>
+ {/if}
+ </div>
+ </div>
+ {/each}
+ </div>
+ </aside>
+{/if}
+
+<style>
+ .fab {
+ position: fixed;
+ bottom: 96px;
+ right: 18px;
+ width: 52px;
+ height: 52px;
+ border-radius: 50%;
+ background: #ff5500;
+ color: white;
+ border: 0;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ box-shadow: 0 6px 22px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(0, 0, 0, 0.18) inset;
+ z-index: 110;
+ transition: transform 160ms ease, background 200ms ease;
+ }
+ .fab:hover { background: #ff7733; transform: translateY(-1px); }
+ .fab:focus-visible { outline: 2px solid white; outline-offset: 2px; }
+ .fab.active { animation: pulse 2.4s ease-in-out infinite; }
+ @keyframes pulse {
+ 0%, 100% { box-shadow: 0 6px 22px rgba(0, 0, 0, 0.35), 0 0 0 0 rgba(255, 85, 0, 0.45); }
+ 50% { box-shadow: 0 6px 22px rgba(0, 0, 0, 0.35), 0 0 0 12px rgba(255, 85, 0, 0); }
+ }
+ .badge {
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ min-width: 20px;
+ height: 20px;
+ padding: 0 5px;
+ border-radius: 10px;
+ background: white;
+ color: #ff5500;
+ font-size: 11px;
+ font-weight: 800;
+ display: grid;
+ place-items: center;
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
+ }
+ .drawer {
+ position: fixed;
+ bottom: 96px;
+ right: 86px;
+ width: min(420px, calc(100vw - 32px));
+ max-height: min(70vh, 640px);
+ background: rgba(20, 20, 20, 0.97);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 14px;
+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);
+ z-index: 109;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ color: white;
+ backdrop-filter: blur(16px);
+ -webkit-backdrop-filter: blur(16px);
+ animation: slide-in 200ms ease;
+ }
+ @keyframes slide-in {
+ from { opacity: 0; transform: translateY(8px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+ .drawer-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 16px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .drawer-title { font-size: 13px; font-weight: 700; letter-spacing: 0.02em; }
+ .muted { color: rgba(255, 255, 255, 0.5); font-weight: 500; }
+ .head-actions { display: flex; align-items: center; gap: 8px; }
+ .link {
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.6);
+ font-family: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ padding: 4px 6px;
+ border-radius: 4px;
+ }
+ .link:hover { color: white; background: rgba(255, 255, 255, 0.05); }
+ .close {
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 22px;
+ line-height: 1;
+ cursor: pointer;
+ padding: 0 6px;
+ border-radius: 4px;
+ }
+ .close:hover { color: white; }
+ .list {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .row {
+ display: grid;
+ grid-template-columns: 40px 1fr auto;
+ gap: 12px;
+ padding: 10px 10px;
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid transparent;
+ align-items: flex-start;
+ }
+ .row.err { border-color: rgba(226, 33, 52, 0.4); background: rgba(226, 33, 52, 0.06); }
+ .cover {
+ width: 40px;
+ height: 40px;
+ border-radius: 6px;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.05);
+ flex-shrink: 0;
+ }
+ .cover img { width: 100%; height: 100%; object-fit: cover; }
+ .cover-fb { width: 100%; height: 100%; }
+ .meta { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
+ .title {
+ font-size: 13px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sub {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sub.thin { color: rgba(255, 255, 255, 0.4); }
+ .bar {
+ height: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 2px;
+ overflow: hidden;
+ margin-top: 2px;
+ }
+ .bar.err .fill { background: #e22134; }
+ .fill {
+ height: 100%;
+ background: #ff5500;
+ transition: width 200ms ease;
+ }
+ .err-text {
+ font-size: 11px;
+ color: #e22134;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .row-actions {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 4px;
+ }
+ .action-btn {
+ padding: 4px 10px;
+ background: #ff5500;
+ color: white;
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 700;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+ .action-btn:hover { background: #ff7733; }
+ .ghost-btn {
+ padding: 2px 8px;
+ background: rgba(255, 255, 255, 0.06);
+ color: rgba(255, 255, 255, 0.7);
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ line-height: 1.3;
+ }
+ .ghost-btn:hover { background: rgba(255, 255, 255, 0.12); color: white; }
+ .bulk-actions {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ margin-top: 4px;
+ flex-wrap: wrap;
+ }
+ .expand-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 8px;
+ background: rgba(226, 33, 52, 0.12);
+ color: #ffb4ba;
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .expand-btn:hover { background: rgba(226, 33, 52, 0.2); color: white; }
+ .chev {
+ display: inline-block;
+ transition: transform 160ms ease;
+ font-size: 9px;
+ }
+ .chev.open { transform: rotate(90deg); }
+ .retry-all {
+ padding: 3px 10px;
+ background: #ff5500;
+ color: white;
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .retry-all:hover { background: #ff7733; }
+ .failed-list {
+ margin: 6px 0 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: 180px;
+ overflow-y: auto;
+ }
+ .failed-row {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 8px;
+ align-items: center;
+ padding: 6px 8px;
+ background: rgba(255, 255, 255, 0.03);
+ border-radius: 6px;
+ font-size: 11px;
+ }
+ .failed-title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: rgba(255, 255, 255, 0.85);
+ }
+ .failed-err {
+ display: none;
+ }
+ .failed-retry {
+ padding: 3px 10px;
+ background: rgba(255, 85, 0, 0.18);
+ color: #ff8c4d;
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .failed-retry:hover { background: #ff5500; color: white; }
+
+ @media (prefers-reduced-motion: reduce) {
+ .drawer { animation: none; }
+ .fab { transition: none; }
+ .fab.active { animation: none; }
+ .fill { transition: none; }
+ .chev { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/DraggableList.svelte b/src/lib/study-music-components/DraggableList.svelte
new file mode 100644
index 00000000..183a1194
--- /dev/null
+++ b/src/lib/study-music-components/DraggableList.svelte
@@ -0,0 +1,108 @@
+<script lang="ts" generics="T extends { id: string | number }">
+ import type { Snippet } from "svelte";
+
+ type Props = {
+ items: T[];
+ onReorder: (orderedIds: Array<string | number>) => void;
+ item: Snippet<[T, number, boolean]>;
+ disabled?: boolean;
+ };
+
+ let { items, onReorder, item, disabled = false }: Props = $props();
+
+ let draggingIndex = $state<number | null>(null);
+ let overIndex = $state<number | null>(null);
+
+ function onDragStart(e: DragEvent, idx: number) {
+ if (disabled || items.length < 2) {
+ e.preventDefault();
+ return;
+ }
+ draggingIndex = idx;
+ if (e.dataTransfer) {
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData("text/plain", String(idx));
+ }
+ }
+
+ function onDragOver(e: DragEvent, idx: number) {
+ if (disabled) return;
+ if (draggingIndex === null) return;
+ e.preventDefault();
+ if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
+ if (overIndex !== idx) overIndex = idx;
+ }
+
+ function onDragLeave(idx: number) {
+ if (overIndex === idx) overIndex = null;
+ }
+
+ function onDrop(e: DragEvent, target: number) {
+ if (disabled) return;
+ e.preventDefault();
+ const from = draggingIndex;
+ draggingIndex = null;
+ overIndex = null;
+ if (from === null || from === target) return;
+ const next = items.slice();
+ const [moved] = next.splice(from, 1);
+ next.splice(target, 0, moved);
+ onReorder(next.map((it) => it.id));
+ }
+
+ function onDragEnd() {
+ draggingIndex = null;
+ overIndex = null;
+ }
+</script>
+
+<ul class="drag-list" class:disabled>
+ {#each items as it, idx (it.id)}
+ <li
+ class="drag-item"
+ class:dragging={draggingIndex === idx}
+ class:drag-over={overIndex === idx && draggingIndex !== idx}
+ draggable={!disabled && items.length >= 2}
+ ondragstart={(e) => onDragStart(e, idx)}
+ ondragover={(e) => onDragOver(e, idx)}
+ ondragleave={() => onDragLeave(idx)}
+ ondrop={(e) => onDrop(e, idx)}
+ ondragend={onDragEnd}
+ >
+ {@render item(it, idx, draggingIndex === idx)}
+ </li>
+ {/each}
+</ul>
+
+<style>
+ .drag-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .drag-item {
+ position: relative;
+ transition: transform 120ms ease, opacity 120ms ease;
+ cursor: grab;
+ }
+ .drag-item:active {
+ cursor: grabbing;
+ }
+ .drag-item.dragging {
+ opacity: 0.45;
+ }
+ .drag-item.drag-over {
+ box-shadow: inset 0 2px 0 0 var(--accent);
+ }
+ .drag-list.disabled .drag-item {
+ cursor: default;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .drag-item {
+ transition: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-music-components/EmptyPlaceholder.svelte b/src/lib/study-music-components/EmptyPlaceholder.svelte
new file mode 100644
index 00000000..057f8ab0
--- /dev/null
+++ b/src/lib/study-music-components/EmptyPlaceholder.svelte
@@ -0,0 +1,90 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+ type Props = {
+ title: string;
+ body?: string | null;
+ ctaLabel?: string | null;
+ onCta?: (() => void) | null;
+ ctaHref?: string | null;
+ icon?: Snippet;
+ compact?: boolean;
+ };
+ let {
+ title,
+ body = null,
+ ctaLabel = null,
+ onCta = null,
+ ctaHref = null,
+ icon,
+ compact = false,
+ }: Props = $props();
+</script>
+
+<div class="empty" class:compact>
+ {#if icon}
+ <div class="icon">{@render icon()}</div>
+ {/if}
+ <h3>{title}</h3>
+ {#if body}<p>{body}</p>{/if}
+ {#if ctaLabel && ctaHref}
+ <a class="cta" href={ctaHref}>{ctaLabel}</a>
+ {:else if ctaLabel && onCta}
+ <button type="button" class="cta" onclick={() => onCta?.()}>{ctaLabel}</button>
+ {/if}
+</div>
+
+<style>
+ .empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 40px 24px;
+ text-align: center;
+ color: rgba(255, 255, 255, 0.85);
+ border-radius: 16px;
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px dashed rgba(255, 255, 255, 0.06);
+ }
+ .empty.compact {
+ padding: 24px 16px;
+ gap: 6px;
+ }
+ .icon {
+ width: 44px;
+ height: 44px;
+ display: grid;
+ place-items: center;
+ color: rgba(255, 255, 255, 0.55);
+ margin-bottom: 4px;
+ }
+ h3 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 700;
+ color: white;
+ }
+ p {
+ margin: 0;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 13px;
+ line-height: 1.5;
+ max-width: 42ch;
+ }
+ .cta {
+ margin-top: 10px;
+ padding: 9px 20px;
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ border: 0;
+ border-radius: 999px;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ text-decoration: none;
+ }
+ .cta:hover {
+ filter: brightness(1.08);
+ }
+</style>
diff --git a/src/lib/study-music-components/ExpandableText.svelte b/src/lib/study-music-components/ExpandableText.svelte
new file mode 100644
index 00000000..dad8220b
--- /dev/null
+++ b/src/lib/study-music-components/ExpandableText.svelte
@@ -0,0 +1,97 @@
+<script lang="ts">
+ import { t } from "$lib/i18n";
+
+ type Props = {
+ text?: string | null;
+ maxLines?: number;
+ moreLabel?: string;
+ lessLabel?: string;
+ };
+
+ let {
+ text = null,
+ maxLines = 3,
+ moreLabel,
+ lessLabel,
+ }: Props = $props();
+
+ let expanded = $state(false);
+ let overflows = $state(false);
+ let contentEl: HTMLDivElement | null = $state(null);
+
+ const showButton = $derived(overflows);
+ const labelMore = $derived(moreLabel ?? $t("study.music.expandable_more"));
+ const labelLess = $derived(lessLabel ?? $t("study.music.expandable_less"));
+
+ $effect(() => {
+ if (!contentEl) return;
+ if (!text) {
+ overflows = false;
+ return;
+ }
+ const el = contentEl;
+ requestAnimationFrame(() => {
+ overflows = el.scrollHeight > el.clientHeight + 1;
+ });
+ });
+</script>
+
+{#if text && text.trim() !== ""}
+ <div class="expandable">
+ <div
+ class="content"
+ class:clamped={!expanded && showButton}
+ style:--max-lines={maxLines}
+ bind:this={contentEl}
+ >
+ {text}
+ </div>
+ {#if showButton}
+ <button
+ type="button"
+ class="toggle"
+ onclick={() => (expanded = !expanded)}
+ aria-expanded={expanded}
+ >
+ {expanded ? labelLess : labelMore}
+ </button>
+ {/if}
+ </div>
+{/if}
+
+<style>
+ .expandable {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .content {
+ font-size: 13px;
+ line-height: 1.5;
+ color: rgba(255, 255, 255, 0.78);
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+ .clamped {
+ display: -webkit-box;
+ -webkit-line-clamp: var(--max-lines);
+ line-clamp: var(--max-lines);
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .toggle {
+ align-self: flex-start;
+ margin-top: 2px;
+ padding: 4px 0;
+ background: transparent;
+ border: 0;
+ color: var(--accent);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .toggle:hover {
+ text-decoration: underline;
+ }
+</style>
diff --git a/src/lib/study-music-components/HeroGradient.svelte b/src/lib/study-music-components/HeroGradient.svelte
new file mode 100644
index 00000000..31bc777d
--- /dev/null
+++ b/src/lib/study-music-components/HeroGradient.svelte
@@ -0,0 +1,68 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+ import { palettePathOrUrl, rgbToCssAlpha, type RGB } from "$lib/study-music/dominant-color";
+
+ type Props = {
+ coverUrl?: string | null;
+ minHeight?: number;
+ children: Snippet;
+ };
+ let { coverUrl = null, minHeight = 240, children }: Props = $props();
+
+ let palette = $state<RGB[] | null>(null);
+
+ $effect(() => {
+ let cancelled = false;
+ palette = null;
+ if (!coverUrl) return;
+ void palettePathOrUrl(coverUrl).then((p) => {
+ if (!cancelled) palette = p;
+ });
+ return () => {
+ cancelled = true;
+ };
+ });
+
+ const c1 = $derived(rgbToCssAlpha(palette?.[0] ?? null, 0.55));
+ const c2 = $derived(rgbToCssAlpha(palette?.[1] ?? palette?.[0] ?? null, 0.35));
+</script>
+
+<div
+ class="hero-gradient"
+ style:--c1={c1}
+ style:--c2={c2}
+ style:min-height={`${minHeight}px`}
+>
+ <div class="bg" aria-hidden="true"></div>
+ <div class="content">
+ {@render children()}
+ </div>
+</div>
+
+<style>
+ .hero-gradient {
+ position: relative;
+ border-radius: 24px;
+ overflow: hidden;
+ isolation: isolate;
+ }
+ .bg {
+ position: absolute;
+ inset: 0;
+ background:
+ radial-gradient(120% 80% at 0% 0%, var(--c1) 0%, transparent 60%),
+ radial-gradient(120% 80% at 100% 100%, var(--c2) 0%, transparent 60%),
+ linear-gradient(135deg, rgba(20, 20, 24, 0.6), rgba(10, 10, 12, 0.85));
+ backdrop-filter: blur(40px);
+ z-index: 0;
+ transition: opacity 400ms ease;
+ }
+ .content {
+ position: relative;
+ z-index: 1;
+ height: 100%;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .bg { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/LyricsPanel.svelte b/src/lib/study-music-components/LyricsPanel.svelte
index 653e9b8e..839eca0f 100644
--- a/src/lib/study-music-components/LyricsPanel.svelte
+++ b/src/lib/study-music-components/LyricsPanel.svelte
@@ -4,16 +4,37 @@
import { musicUI } from "$lib/study-music/ui-store.svelte";
import { lyricsStore } from "$lib/study-music/lyrics-store.svelte";
import { t } from "$lib/i18n";
+ import PasteLyricsModal from "./PasteLyricsModal.svelte";
+
+ const USER_SCROLL_LOCKOUT_MS = 750;
+ const AUTO_SCROLL_THROTTLE_MS = 33;
+ const VIRTUALIZE_THRESHOLD = 300;
let containerEl = $state<HTMLDivElement | null>(null);
- let lineRefs: HTMLLIElement[] = [];
+ let lineRefs: HTMLLIElement[] = $state([]);
+ let pasteOpen = $state(false);
+ let reduceMotion = $state(false);
+ let editingIdx = $state<number | null>(null);
+ let editDraft = $state("");
+
+ let _lastUserScrollAt = 0;
+ let _lastAutoScrollAt = 0;
+ let _isAutoScrolling = false;
+ let _autoScrollTimeout: ReturnType<typeof setTimeout> | null = null;
+ let _resizeObserver: ResizeObserver | null = null;
+ const _lineHeights = new Map<number, number>();
const trackId = $derived(musicPlayer.currentTrack?.id ?? null);
+ const status = $derived(lyricsStore.status);
const activeIdx = $derived(
- lyricsStore.lines.length > 0
+ status === "synced" && lyricsStore.lines.length > 0
? lyricsStore.activeIndex(musicPlayer.currentTime)
: -1,
);
+ const shouldVirtualize = $derived(lyricsStore.lines.length > VIRTUALIZE_THRESHOLD);
+ const showTranslation = $derived(lyricsStore.showTranslation);
+ const translationStatus = $derived(lyricsStore.translationStatus);
+ const translations = $derived(lyricsStore.translations);
$effect(() => {
if (!musicUI.lyricsOpen) return;
@@ -24,21 +45,48 @@
void lyricsStore.loadFor(trackId);
});
+ $effect(() => {
+ if (!musicUI.lyricsOpen) return;
+ if (!showTranslation) return;
+ if (status !== "synced" || lyricsStore.lines.length === 0) return;
+ void lyricsStore.loadTranslation("pt");
+ });
+
$effect(() => {
if (!musicUI.lyricsOpen) return;
void activeIdx;
- void tick().then(() => {
- const el = lineRefs[activeIdx];
- if (el && containerEl) {
- const rect = el.getBoundingClientRect();
- const cRect = containerEl.getBoundingClientRect();
- const offset =
- el.offsetTop - containerEl.offsetTop - cRect.height / 2 + rect.height / 2;
- containerEl.scrollTo({ top: offset, behavior: "smooth" });
- }
- });
+ if (activeIdx < 0) return;
+ if (!containerEl) return;
+ const now = performance.now();
+ if (now - _lastUserScrollAt < USER_SCROLL_LOCKOUT_MS) return;
+ if (now - _lastAutoScrollAt < AUTO_SCROLL_THROTTLE_MS) return;
+ _lastAutoScrollAt = now;
+ void scrollToActive();
});
+ async function scrollToActive() {
+ await tick();
+ const el = lineRefs[activeIdx];
+ if (!el || !containerEl) return;
+ _isAutoScrolling = true;
+ const cRect = containerEl.getBoundingClientRect();
+ const offset =
+ el.offsetTop - containerEl.offsetTop - cRect.height / 2 + el.offsetHeight / 2;
+ containerEl.scrollTo({
+ top: offset,
+ behavior: reduceMotion ? "instant" : "smooth",
+ });
+ if (_autoScrollTimeout) clearTimeout(_autoScrollTimeout);
+ _autoScrollTimeout = setTimeout(() => {
+ _isAutoScrolling = false;
+ }, 400);
+ }
+
+ function onUserInput() {
+ if (_isAutoScrolling) return;
+ _lastUserScrollAt = performance.now();
+ }
+
function close() {
musicUI.closeLyrics();
}
@@ -49,6 +97,68 @@
}
}
+ function openPaste() {
+ pasteOpen = true;
+ }
+
+ function closePaste() {
+ pasteOpen = false;
+ }
+
+ function toggleTranslationClick() {
+ lyricsStore.toggleTranslation("pt");
+ }
+
+ function startEdit(idx: number) {
+ if (!showTranslation) return;
+ editingIdx = idx;
+ editDraft = translations.get(idx)?.translation ?? "";
+ }
+
+ function cancelEdit() {
+ editingIdx = null;
+ editDraft = "";
+ }
+
+ async function saveEdit() {
+ if (editingIdx === null) return;
+ const idx = editingIdx;
+ const text = editDraft.trim();
+ if (text.length === 0) {
+ cancelEdit();
+ return;
+ }
+ await lyricsStore.setTranslationLine(idx, text);
+ cancelEdit();
+ }
+
+ function onEditKeydown(e: KeyboardEvent) {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ void saveEdit();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ cancelEdit();
+ }
+ }
+
+ async function handleSavedLocal() {
+ pasteOpen = false;
+ }
+
+ onMount(() => {
+ if (typeof document === "undefined") return;
+ if (typeof window !== "undefined" && "matchMedia" in window) {
+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
+ reduceMotion = mq.matches;
+ const listener = (e: MediaQueryListEvent) => {
+ reduceMotion = e.matches;
+ };
+ mq.addEventListener("change", listener);
+ return () => mq.removeEventListener("change", listener);
+ }
+ });
+
onMount(() => {
if (typeof document === "undefined") return;
const handler = (e: KeyboardEvent) => {
@@ -64,12 +174,43 @@
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
- close();
+ if (pasteOpen) {
+ closePaste();
+ } else {
+ close();
+ }
}
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
});
+
+ $effect(() => {
+ if (typeof ResizeObserver === "undefined") return;
+ if (!containerEl) return;
+ void lyricsStore.lines.length;
+ if (_resizeObserver) {
+ _resizeObserver.disconnect();
+ }
+ _resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const el = entry.target as HTMLElement;
+ const idx = Number(el.dataset.idx);
+ if (Number.isFinite(idx)) {
+ _lineHeights.set(idx, entry.contentRect.height);
+ }
+ }
+ });
+ for (const el of lineRefs) {
+ if (el) _resizeObserver.observe(el);
+ }
+ return () => {
+ if (_resizeObserver) {
+ _resizeObserver.disconnect();
+ _resizeObserver = null;
+ }
+ };
+ });
</script>
{#if musicUI.lyricsOpen}
@@ -77,6 +218,19 @@
<header class="head">
<h3>{$t("study.music.lyrics_title")}</h3>
<div class="actions">
+ <button
+ type="button"
+ class="toggle"
+ class:on={showTranslation}
+ onclick={toggleTranslationClick}
+ aria-pressed={showTranslation}
+ title={(showTranslation
+ ? $t("study.music.lyrics_translation_hide")
+ : $t("study.music.lyrics_translation_show")) as string}
+ >
+ <span class="dot"></span>
+ <span class="lbl">PT</span>
+ </button>
<button
type="button"
class="ico"
@@ -98,39 +252,128 @@
</div>
</header>
+ {#if showTranslation && status === "synced"}
+ {#if translationStatus === "loading"}
+ <div class="translation-banner banner-info">
+ <span>{$t("study.music.lyrics_translation_loading")}</span>
+ </div>
+ {:else if translationStatus === "skipped"}
+ <div class="translation-banner banner-muted">
+ <span>{$t("study.music.lyrics_translation_skipped_pt")}</span>
+ </div>
+ {:else if translationStatus === "no_translator"}
+ <button
+ type="button"
+ class="translation-banner banner-warn banner-clickable"
+ onclick={() => musicUI.openTranslationSettings()}
+ >
+ <strong>{$t("study.music.lyrics_translation_no_translator")}</strong>
+ <span class="muted-inline">{$t("study.music.lyrics_translation_no_translator_hint")}</span>
+ </button>
+ {:else if translationStatus === "error"}
+ <div class="translation-banner banner-error">
+ <span>{$t("study.music.lyrics_translation_error")}</span>
+ </div>
+ {/if}
+ {/if}
+
{#if !musicPlayer.currentTrack}
<div class="empty">
<p>{$t("study.music.lyrics_no_track")}</p>
</div>
- {:else if lyricsStore.loading}
- <div class="loading">
- <span class="spinner"></span>
- <p>{$t("study.music.lyrics_loading")}</p>
+ {:else if status === "loading"}
+ <div class="loading-skeleton" aria-busy="true" aria-live="polite">
+ <span class="skel skel-a"></span>
+ <span class="skel skel-b"></span>
+ <span class="skel skel-c"></span>
+ <p class="muted">{$t("study.music.lyrics_loading")}</p>
</div>
- {:else if lyricsStore.notFound}
+ {:else if status === "notfound"}
<div class="empty">
- <p>{$t("study.music.lyrics_not_found")}</p>
+ <p class="empty-title">{$t("study.music.lyrics_not_found")}</p>
<p class="muted">{$t("study.music.lyrics_lrclib_hint")}</p>
+ <button type="button" class="cta" onclick={openPaste}>
+ {$t("study.music.lyrics_add_manual")}
+ </button>
</div>
- {:else if lyricsStore.lines.length > 0}
- <div bind:this={containerEl} class="scroll synced">
+ {:else if status === "error"}
+ <div class="empty">
+ <p class="empty-title">{$t("study.music.lyrics_error")}</p>
+ <p class="muted">{$t("study.music.lyrics_error_hint")}</p>
+ <div class="error-actions">
+ <button type="button" class="cta" onclick={refresh}>
+ {$t("study.music.lyrics_retry")}
+ </button>
+ <button type="button" class="cta cta-ghost" onclick={openPaste}>
+ {$t("study.music.lyrics_add_manual")}
+ </button>
+ </div>
+ </div>
+ {:else if status === "synced" && lyricsStore.lines.length > 0}
+ <div
+ bind:this={containerEl}
+ class="scroll synced"
+ class:virtualized={shouldVirtualize}
+ onwheel={onUserInput}
+ ontouchstart={onUserInput}
+ onkeydown={onUserInput}
+ role="presentation"
+ >
<ul class="lines">
{#each lyricsStore.lines as line, i (i)}
<li
bind:this={lineRefs[i]}
+ data-idx={i}
class="line"
class:active={i === activeIdx}
class:past={i < activeIdx}
>
- {line.text || "♪"}
+ <span class="line-original">{line.text || "♪"}</span>
+ {#if showTranslation && translationStatus === "available"}
+ {#if editingIdx === i}
+ <div class="line-edit">
+ <input
+ type="text"
+ class="line-edit-input"
+ bind:value={editDraft}
+ placeholder={$t("study.music.lyrics_translation_edit_placeholder") as string}
+ onkeydown={onEditKeydown}
+ autofocus
+ />
+ <button type="button" class="line-edit-btn save" onclick={saveEdit}>
+ {$t("study.music.lyrics_translation_edit_save")}
+ </button>
+ <button type="button" class="line-edit-btn cancel" onclick={cancelEdit}>
+ {$t("study.music.lyrics_translation_edit_cancel")}
+ </button>
+ </div>
+ {:else}
+ <button
+ type="button"
+ class="line-translation"
+ class:edited={translations.get(i)?.edited ?? false}
+ onclick={() => startEdit(i)}
+ title={$t("study.music.lyrics_translation_edit_placeholder") as string}
+ >
+ <span class="translation-text">
+ {translations.get(i)?.translation || "—"}
+ </span>
+ {#if translations.get(i)?.edited}
+ <span class="edited-badge">
+ {$t("study.music.lyrics_translation_edited_badge")}
+ </span>
+ {/if}
+ </button>
+ {/if}
+ {/if}
</li>
{/each}
</ul>
</div>
- {:else if lyricsStore.plain}
+ {:else if status === "plain" && lyricsStore.plain}
<div class="scroll plain">
{#each lyricsStore.plain.split(/\r?\n/) as line, i (i)}
- <p class="plain-line">{line || " "}</p>
+ <p class="plain-line">{line || " "}</p>
{/each}
</div>
{/if}
@@ -138,9 +381,20 @@
{#if lyricsStore.source}
<footer class="foot">
<span>{$t("study.music.lyrics_source", { source: lyricsStore.source })}</span>
+ {#if showTranslation && translationStatus === "available" && lyricsStore.translator && lyricsStore.translator !== "skipped"}
+ <span class="foot-sep">·</span>
+ <span>{$t("study.music.lyrics_translation_attribution", { translator: lyricsStore.translator })}</span>
+ {/if}
</footer>
{/if}
</aside>
+
+ <PasteLyricsModal
+ open={pasteOpen}
+ {trackId}
+ onclose={closePaste}
+ onsaved={handleSavedLocal}
+ />
{/if}
<style>
@@ -189,12 +443,145 @@
cursor: pointer;
}
.ico:hover { color: white; background: rgba(255, 255, 255, 0.08); }
+ .toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 10px;
+ height: 26px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ cursor: pointer;
+ transition: color 160ms ease, background 160ms ease, border-color 160ms ease;
+ }
+ .toggle .dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.3);
+ transition: background 160ms ease, box-shadow 160ms ease;
+ }
+ .toggle.on {
+ color: white;
+ background: color-mix(in oklab, var(--accent, #7c5cff) 25%, transparent);
+ border-color: color-mix(in oklab, var(--accent, #7c5cff) 60%, transparent);
+ }
+ .toggle.on .dot {
+ background: var(--accent, #7c5cff);
+ box-shadow: 0 0 8px color-mix(in oklab, var(--accent, #7c5cff) 80%, transparent);
+ }
+ .toggle:hover { color: white; }
+ .translation-banner {
+ padding: 8px 14px;
+ font-size: 12px;
+ line-height: 1.4;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ }
+ .banner-info { color: rgba(255, 255, 255, 0.7); }
+ .banner-muted { color: rgba(255, 255, 255, 0.45); font-style: italic; }
+ .banner-warn { color: rgba(255, 200, 120, 0.95); background: rgba(255, 200, 120, 0.06); }
+ .banner-clickable {
+ width: 100%;
+ text-align: left;
+ border: 0;
+ cursor: pointer;
+ align-items: flex-start;
+ }
+ .banner-clickable:hover { background: rgba(255, 200, 120, 0.12); }
+ .banner-error { color: rgba(255, 130, 130, 0.95); background: rgba(255, 130, 130, 0.06); }
+ .muted-inline { color: rgba(255, 255, 255, 0.55); font-size: 11px; }
+ .line-original { display: block; }
+ .line-translation {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 4px;
+ padding: 2px 4px;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 14px;
+ font-style: italic;
+ line-height: 1.35;
+ text-align: left;
+ cursor: text;
+ transition: background 160ms ease, color 160ms ease;
+ }
+ .line-translation:hover {
+ background: rgba(255, 255, 255, 0.04);
+ color: rgba(255, 255, 255, 0.8);
+ }
+ .line.active .line-translation { color: rgba(255, 255, 255, 0.78); }
+ .line-translation.edited { color: rgba(180, 220, 255, 0.85); }
+ .edited-badge {
+ display: inline-flex;
+ align-items: center;
+ height: 16px;
+ padding: 0 6px;
+ border-radius: 999px;
+ background: rgba(120, 180, 255, 0.14);
+ color: rgba(180, 220, 255, 0.85);
+ font-size: 9px;
+ font-style: normal;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ }
+ .line-edit {
+ display: flex;
+ gap: 4px;
+ margin-top: 4px;
+ }
+ .line-edit-input {
+ flex: 1;
+ min-width: 0;
+ padding: 6px 10px;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ border-radius: 8px;
+ color: white;
+ font-size: 14px;
+ font-style: italic;
+ }
+ .line-edit-input:focus {
+ outline: none;
+ border-color: var(--accent, #7c5cff);
+ background: rgba(255, 255, 255, 0.08);
+ }
+ .line-edit-btn {
+ padding: 0 10px;
+ height: 32px;
+ background: rgba(255, 255, 255, 0.06);
+ border: 0;
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.85);
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .line-edit-btn.save {
+ background: var(--accent, #7c5cff);
+ color: white;
+ }
+ .line-edit-btn:hover { filter: brightness(1.15); }
.scroll {
flex: 1;
overflow-y: auto;
padding: 16px 22px 32px;
scrollbar-width: thin;
}
+ .scroll.virtualized .line {
+ content-visibility: auto;
+ contain-intrinsic-size: 0 36px;
+ }
.lines {
list-style: none;
margin: 0;
@@ -207,17 +594,20 @@
font-size: 18px;
line-height: 1.4;
color: rgba(255, 255, 255, 0.4);
- transition: color 220ms ease, transform 220ms ease, font-size 220ms ease;
+ transition: color 220ms ease, transform 220ms ease, font-size 220ms ease, opacity 220ms ease;
transform-origin: left;
+ opacity: 0.85;
}
.line.past {
color: rgba(255, 255, 255, 0.25);
+ opacity: 0.6;
}
.line.active {
color: white;
font-weight: 700;
font-size: 22px;
transform: scale(1.02);
+ opacity: 1;
}
.plain-line {
margin: 0 0 10px;
@@ -226,29 +616,81 @@
color: rgba(255, 255, 255, 0.85);
}
.empty,
- .loading {
+ .loading-skeleton {
flex: 1;
display: flex;
flex-direction: column;
- gap: 8px;
+ gap: 12px;
align-items: center;
justify-content: center;
padding: 24px;
- color: rgba(255, 255, 255, 0.5);
+ color: rgba(255, 255, 255, 0.65);
font-size: 13px;
text-align: center;
}
- .muted { color: rgba(255, 255, 255, 0.35); font-size: 11px; }
- .spinner {
- width: 18px;
- height: 18px;
- border: 2px solid rgba(255, 255, 255, 0.15);
- border-top-color: var(--accent);
- border-radius: 50%;
- animation: spin 0.7s linear infinite;
+ .empty-title {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.92);
+ }
+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 12px; max-width: 280px; }
+ .cta {
+ margin-top: 4px;
+ padding: 10px 18px;
+ background: var(--accent, #7c5cff);
+ color: white;
+ border: 0;
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 180ms ease, transform 180ms ease;
+ }
+ .cta:hover { filter: brightness(1.1); }
+ .cta:active { transform: scale(0.98); }
+ .cta-ghost {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ color: rgba(255, 255, 255, 0.85);
}
- @keyframes spin {
- to { transform: rotate(360deg); }
+ .error-actions {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ flex-wrap: wrap;
+ justify-content: center;
+ }
+ .loading-skeleton {
+ gap: 14px;
+ }
+ .skel {
+ display: block;
+ height: 14px;
+ border-radius: 6px;
+ background: linear-gradient(
+ 90deg,
+ rgba(255, 255, 255, 0.06),
+ rgba(255, 255, 255, 0.16),
+ rgba(255, 255, 255, 0.06)
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.4s ease-in-out infinite;
+ }
+ .skel-a { width: 68%; }
+ .skel-b { width: 82%; }
+ .skel-c { width: 54%; }
+ @keyframes shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .line {
+ transition: none;
+ }
+ .skel {
+ animation: none;
+ }
}
.foot {
padding: 8px 14px;
@@ -256,5 +698,10 @@
color: rgba(255, 255, 255, 0.35);
font-size: 10px;
text-align: right;
+ display: flex;
+ justify-content: flex-end;
+ gap: 6px;
+ flex-wrap: wrap;
}
+ .foot-sep { opacity: 0.4; }
</style>
diff --git a/src/lib/study-music-components/LyricsTranslationPanel.svelte b/src/lib/study-music-components/LyricsTranslationPanel.svelte
new file mode 100644
index 00000000..0e59351e
--- /dev/null
+++ b/src/lib/study-music-components/LyricsTranslationPanel.svelte
@@ -0,0 +1,325 @@
+<script lang="ts">
+ import { pluginInvoke } from "$lib/plugin-invoke";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { t } from "$lib/i18n";
+ import { lyricsStore, type TranslationSettings } from "$lib/study-music/lyrics-store.svelte";
+
+ type Props = {
+ open: boolean;
+ onClose: () => void;
+ };
+
+ let { open, onClose }: Props = $props();
+
+ let settings = $state<TranslationSettings | null>(null);
+ let translatorInput = $state<"libretranslate" | "deepl" | "none">("libretranslate");
+ let urlInput = $state("");
+ let targetLangInput = $state("pt");
+ let showTranslationInput = $state(false);
+ let deeplKeyDraft = $state("");
+ let deeplKeyEditing = $state(false);
+ let busy = $state(false);
+
+ async function load() {
+ try {
+ const res = await pluginInvoke<TranslationSettings>(
+ "study",
+ "study:music:lyrics:translation_settings:get",
+ );
+ settings = res;
+ translatorInput = res.translator;
+ urlInput = res.libretranslate_url;
+ targetLangInput = res.target_lang;
+ showTranslationInput = res.show_translation;
+ deeplKeyDraft = "";
+ deeplKeyEditing = !res.deepl_api_key_set;
+ lyricsStore.showTranslation = res.show_translation;
+ } catch {
+ settings = null;
+ }
+ }
+
+ $effect(() => {
+ if (open) void load();
+ });
+
+ async function save() {
+ if (busy) return;
+ busy = true;
+ try {
+ const payload: Record<string, unknown> = {
+ translator: translatorInput,
+ libretranslate_url: urlInput.trim(),
+ target_lang: targetLangInput.trim() || "pt",
+ show_translation: showTranslationInput,
+ };
+ if (deeplKeyEditing) {
+ payload.deepl_api_key = deeplKeyDraft;
+ }
+ await pluginInvoke("study", "study:music:lyrics:translation_settings:set", payload);
+ lyricsStore.showTranslation = showTranslationInput;
+ showToast("success", $t("study.music.translation_settings_saved") as string);
+ deeplKeyDraft = "";
+ await load();
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ busy = false;
+ }
+ }
+
+ function onKey(e: KeyboardEvent) {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ onClose();
+ }
+ }
+
+ function startEditDeeplKey() {
+ deeplKeyEditing = true;
+ deeplKeyDraft = "";
+ }
+</script>
+
+{#if open}
+ <div
+ class="overlay"
+ role="presentation"
+ onclick={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ onkeydown={onKey}
+ >
+ <div class="dialog" role="dialog" aria-modal="true" tabindex="-1">
+ <header class="head">
+ <h3>{$t("study.music.translation_settings_title")}</h3>
+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>
+ </header>
+ <div class="body">
+ {#if settings === null}
+ <p class="muted">{$t("study.common.loading")}</p>
+ {:else}
+ <label class="field">
+ <span>{$t("study.music.translation_settings_translator_label")}</span>
+ <select bind:value={translatorInput} disabled={busy}>
+ <option value="libretranslate">{$t("study.music.translation_settings_translator_libretranslate")}</option>
+ <option value="deepl">{$t("study.music.translation_settings_translator_deepl")}</option>
+ <option value="none">{$t("study.music.translation_settings_translator_none")}</option>
+ </select>
+ </label>
+
+ {#if translatorInput === "libretranslate"}
+ <label class="field">
+ <span>{$t("study.music.translation_settings_libretranslate_url_label")}</span>
+ <input
+ type="text"
+ bind:value={urlInput}
+ placeholder="http://localhost:5000"
+ autocomplete="off"
+ disabled={busy}
+ />
+ <small>{$t("study.music.translation_settings_libretranslate_url_hint")}</small>
+ </label>
+ {/if}
+
+ {#if translatorInput === "deepl"}
+ <label class="field">
+ <span>{$t("study.music.translation_settings_deepl_key_label")}</span>
+ {#if deeplKeyEditing}
+ <input
+ type="password"
+ bind:value={deeplKeyDraft}
+ placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:fx"
+ autocomplete="off"
+ disabled={busy}
+ />
+ {:else}
+ <div class="key-saved">
+ <span class="key-saved-text">••••••••••••••••</span>
+ <button type="button" class="cta-ghost" onclick={startEditDeeplKey}>
+ {$t("study.music.translation_settings_deepl_key_set")}
+ </button>
+ </div>
+ {/if}
+ <small>{$t("study.music.translation_settings_deepl_key_hint")}</small>
+ </label>
+ {/if}
+
+ <label class="field">
+ <span>{$t("study.music.translation_settings_target_lang_label")}</span>
+ <select bind:value={targetLangInput} disabled={busy}>
+ <option value="pt">Português (PT-BR)</option>
+ <option value="es">Español</option>
+ <option value="fr">Français</option>
+ <option value="de">Deutsch</option>
+ <option value="it">Italiano</option>
+ <option value="ja">日本語</option>
+ </select>
+ </label>
+
+ <label class="toggle-row">
+ <input
+ type="checkbox"
+ bind:checked={showTranslationInput}
+ disabled={busy}
+ />
+ <span>{$t("study.music.translation_settings_show_label")}</span>
+ </label>
+
+ <div class="actions">
+ <button type="button" class="cta" onclick={save} disabled={busy}>
+ {$t("study.music.translation_settings_saved")}
+ </button>
+ </div>
+ {/if}
+ </div>
+ </div>
+ </div>
+{/if}
+
+<style>
+ .overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.55);
+ z-index: 320;
+ display: grid;
+ place-items: center;
+ backdrop-filter: blur(4px);
+ }
+ .dialog {
+ background: rgb(20, 20, 20);
+ color: rgba(255, 255, 255, 0.95);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 14px;
+ width: min(540px, 92vw);
+ max-height: 86vh;
+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+ .head {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 16px 18px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .head h3 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.9);
+ }
+ .close {
+ width: 32px;
+ height: 32px;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ }
+ .close:hover { color: white; background: rgba(255, 255, 255, 0.08); }
+ .body {
+ padding: 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ overflow-y: auto;
+ }
+ .muted { color: rgba(255, 255, 255, 0.45); font-size: 13px; margin: 0; }
+ .field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .field > span {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.65);
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .field input, .field select {
+ padding: 10px 12px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 10px;
+ color: white;
+ font-size: 14px;
+ }
+ .field input:focus, .field select:focus {
+ outline: none;
+ border-color: var(--accent, #7c5cff);
+ background: rgba(255, 255, 255, 0.08);
+ }
+ .field small {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.45);
+ line-height: 1.5;
+ }
+ .toggle-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.85);
+ cursor: pointer;
+ }
+ .toggle-row input { width: 16px; height: 16px; cursor: pointer; }
+ .key-saved {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .key-saved-text {
+ flex: 1;
+ padding: 10px 12px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 10px;
+ color: rgba(255, 255, 255, 0.6);
+ font-family: monospace;
+ letter-spacing: 0.1em;
+ font-size: 14px;
+ }
+ .cta-ghost {
+ padding: 10px 14px;
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.85);
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .cta-ghost:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: white;
+ }
+ .actions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 4px;
+ }
+ .cta {
+ padding: 10px 18px;
+ background: var(--accent, #7c5cff);
+ border: 0;
+ border-radius: 999px;
+ color: white;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 160ms ease, transform 160ms ease;
+ }
+ .cta:hover { filter: brightness(1.1); }
+ .cta:active { transform: scale(0.98); }
+ .cta:disabled { opacity: 0.5; cursor: not-allowed; }
+</style>
diff --git a/src/lib/study-music-components/MediaHero.svelte b/src/lib/study-music-components/MediaHero.svelte
new file mode 100644
index 00000000..b10027dc
--- /dev/null
+++ b/src/lib/study-music-components/MediaHero.svelte
@@ -0,0 +1,245 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+ import HeroGradient from "./HeroGradient.svelte";
+
+ type Action = {
+ id: string;
+ label: string;
+ icon?: Snippet;
+ onClick: () => void;
+ primary?: boolean;
+ busy?: boolean;
+ disabled?: boolean;
+ ariaLabel?: string;
+ };
+
+ type Stat = {
+ label: string;
+ value?: string | null;
+ };
+
+ type Props = {
+ coverUrl?: string | null;
+ eyebrow?: string | null;
+ title: string;
+ subtitle?: string | null;
+ stats?: Stat[];
+ actions?: Action[];
+ description?: Snippet;
+ coverShape?: "square" | "circle";
+ };
+
+ let {
+ coverUrl = null,
+ eyebrow = null,
+ title,
+ subtitle = null,
+ stats = [],
+ actions = [],
+ description,
+ coverShape = "square",
+ }: Props = $props();
+
+ const visibleStats = $derived(stats.filter((s) => s.value && s.value.trim() !== ""));
+</script>
+
+<HeroGradient coverUrl={coverUrl} minHeight={280}>
+ <div class="hero-row">
+ <div class="cover" class:circle={coverShape === "circle"}>
+ {#if coverUrl}
+ <img src={coverUrl} alt="" loading="eager" />
+ {:else}
+ <div class="cover-fallback" aria-hidden="true"></div>
+ {/if}
+ </div>
+ <div class="meta">
+ {#if eyebrow}
+ <p class="eyebrow">{eyebrow}</p>
+ {/if}
+ <h1 class="title">{title}</h1>
+ {#if subtitle}
+ <p class="subtitle">{subtitle}</p>
+ {/if}
+ {#if visibleStats.length > 0}
+ <p class="stats">
+ {#each visibleStats as stat, idx (stat.label + idx)}
+ {#if idx > 0}<span class="sep" aria-hidden="true">·</span>{/if}
+ <span class="stat"><span class="stat-value">{stat.value}</span>{#if stat.label}
+ <span class="stat-label"> {stat.label}</span>
+ {/if}</span>
+ {/each}
+ </p>
+ {/if}
+ {#if description}
+ <div class="description">{@render description()}</div>
+ {/if}
+ {#if actions.length > 0}
+ <div class="actions">
+ {#each actions as action (action.id)}
+ <button
+ type="button"
+ class="action"
+ class:primary={action.primary}
+ disabled={action.disabled || action.busy}
+ onclick={action.onClick}
+ aria-label={action.ariaLabel ?? action.label}
+ >
+ {#if action.icon}
+ <span class="icon">{@render action.icon()}</span>
+ {/if}
+ <span>{action.label}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ </div>
+</HeroGradient>
+
+<style>
+ .hero-row {
+ display: flex;
+ flex-direction: row;
+ gap: 24px;
+ padding: 24px 24px 28px;
+ align-items: flex-end;
+ min-height: 280px;
+ }
+ .cover {
+ flex: 0 0 auto;
+ width: 200px;
+ height: 200px;
+ border-radius: 12px;
+ overflow: hidden;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ box-shadow: 0 12px 24px rgba(0, 0, 0, 0.35);
+ }
+ .cover.circle {
+ border-radius: 50%;
+ }
+ .cover img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .cover-fallback {
+ width: 100%;
+ height: 100%;
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02));
+ }
+ .meta {
+ flex: 1 1 auto;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ color: rgba(255, 255, 255, 0.95);
+ }
+ .eyebrow {
+ margin: 0;
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: rgba(255, 255, 255, 0.65);
+ }
+ .title {
+ margin: 0;
+ font-size: clamp(28px, 4vw, 44px);
+ font-weight: 800;
+ line-height: 1.05;
+ color: #fff;
+ word-break: break-word;
+ }
+ .subtitle {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.85);
+ }
+ .stats {
+ margin: 0;
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.7);
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ align-items: baseline;
+ }
+ .sep {
+ color: rgba(255, 255, 255, 0.35);
+ }
+ .stat-value {
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.85);
+ }
+ .description {
+ margin-top: 4px;
+ color: rgba(255, 255, 255, 0.78);
+ font-size: 13px;
+ line-height: 1.5;
+ max-width: 720px;
+ }
+ .actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 8px;
+ }
+ .action {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 18px;
+ background: rgba(255, 255, 255, 0.1);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ color: rgba(255, 255, 255, 0.92);
+ border-radius: 999px;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ transition: background 160ms ease, transform 160ms ease;
+ }
+ .action:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.16);
+ }
+ .action:active:not(:disabled) {
+ transform: scale(0.98);
+ }
+ .action:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .action.primary {
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ border-color: transparent;
+ }
+ .action.primary:hover:not(:disabled) {
+ filter: brightness(1.08);
+ }
+ .icon {
+ display: inline-grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ }
+ @media (max-width: 720px) {
+ .hero-row {
+ flex-direction: column;
+ align-items: flex-start;
+ padding: 16px;
+ }
+ .cover {
+ width: 140px;
+ height: 140px;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .action {
+ transition: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-music-components/MusicSidebar.svelte b/src/lib/study-music-components/MusicSidebar.svelte
index f57e62b0..304f008e 100644
--- a/src/lib/study-music-components/MusicSidebar.svelte
+++ b/src/lib/study-music-components/MusicSidebar.svelte
@@ -69,12 +69,24 @@
icon: "M3 12h4l3-9 4 18 3-9h4",
match: "prefix",
},
+ {
+ href: "/study/music/history",
+ labelKey: "study.music.nav_history",
+ icon: "M12 8v4l3 3 M3.05 11a9 9 0 1 1 .5 4 M3 3v6h6",
+ match: "prefix",
+ },
{
href: "/study/music/download",
labelKey: "study.music.nav_download",
icon: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4 M7 10l5 5 5-5 M12 15V3",
match: "prefix",
},
+ {
+ href: "/study/music/transcode",
+ labelKey: "study.music.nav_transcode",
+ icon: "M4 4h16v16H4z M9 9l6 3-6 3z",
+ match: "prefix",
+ },
{
href: "/study/music/youtube",
labelKey: "study.music.nav_youtube",
@@ -230,8 +242,8 @@
<style>
.music-sidebar {
- display: grid;
- grid-template-rows: auto auto auto 1fr auto;
+ display: flex;
+ flex-direction: column;
gap: 12px;
padding: 16px 12px;
height: 100%;
@@ -240,6 +252,17 @@
border-right: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);
scrollbar-width: thin;
}
+ .brand,
+ .divider,
+ .footer-nav {
+ flex: 0 0 auto;
+ }
+ .nav {
+ flex: 0 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ scrollbar-width: thin;
+ }
.brand {
display: flex;
align-items: center;
@@ -307,7 +330,8 @@
display: flex;
flex-direction: column;
gap: 4px;
- min-height: 0;
+ flex: 1 1 200px;
+ min-height: 160px;
overflow-y: auto;
overflow-x: hidden;
}
diff --git a/src/lib/study-music-components/MusicThemePanel.svelte b/src/lib/study-music-components/MusicThemePanel.svelte
index 30a27deb..4eb5b0fb 100644
--- a/src/lib/study-music-components/MusicThemePanel.svelte
+++ b/src/lib/study-music-components/MusicThemePanel.svelte
@@ -1,7 +1,9 @@
<script lang="ts">
- import { musicTheme, PRESET_ACCENTS, type MusicThemePreset } from "$lib/study-music/theme-store.svelte";
+ import { musicTheme, PRESET_ACCENTS, type MusicThemePreset, type ReduceAnimationsMode } from "$lib/study-music/theme-store.svelte";
import { t } from "$lib/i18n";
+ const REDUCE_MODES: ReduceAnimationsMode[] = ["auto", "off", "on"];
+
type Props = {
open: boolean;
onClose: () => void;
@@ -109,6 +111,21 @@
</div>
</section>
+ <section class="row">
+ <span class="label">{$t("study.music.music_theme_reduce_motion")}</span>
+ <div class="dom-toggle">
+ {#each REDUCE_MODES as mode (mode)}
+ <button
+ type="button"
+ class="seg"
+ class:active={musicTheme.reduceAnimations === mode}
+ onclick={() => musicTheme.setReduceAnimations(mode)}
+ >{$t(`study.music.music_theme_reduce_motion_${mode}`)}</button>
+ {/each}
+ </div>
+ <p class="hint subtle">{$t("study.music.music_theme_reduce_motion_hint")}</p>
+ </section>
+
<div class="actions">
<button type="button" class="reset" onclick={() => musicTheme.reset()}>
{$t("study.music.music_theme_reset")}
@@ -178,6 +195,10 @@
font-size: 13px;
line-height: 1.5;
}
+ .hint.subtle {
+ font-size: 11.5px;
+ color: rgba(255, 255, 255, 0.4);
+ }
.row {
display: flex;
flex-direction: column;
diff --git a/src/lib/study-music-components/NavigationTile.svelte b/src/lib/study-music-components/NavigationTile.svelte
new file mode 100644
index 00000000..5da050ae
--- /dev/null
+++ b/src/lib/study-music-components/NavigationTile.svelte
@@ -0,0 +1,101 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+ type Props = {
+ title: string;
+ subtitle?: string | null;
+ href?: string | null;
+ onClick?: (() => void) | null;
+ icon?: Snippet;
+ accent?: string | null;
+ };
+ let { title, subtitle = null, href = null, onClick = null, icon, accent = null }: Props = $props();
+ const tag = href ? "a" : "button";
+ function handle() {
+ onClick?.();
+ }
+</script>
+
+{#if href}
+ <a class="nav-tile" {href} style:--tile-accent={accent ?? "rgba(255,255,255,0.05)"}>
+ <span class="icon">
+ {#if icon}{@render icon()}{/if}
+ </span>
+ <span class="text">
+ <span class="title">{title}</span>
+ {#if subtitle}<span class="sub">{subtitle}</span>{/if}
+ </span>
+ </a>
+{:else}
+ <button
+ type="button"
+ class="nav-tile"
+ style:--tile-accent={accent ?? "rgba(255,255,255,0.05)"}
+ onclick={handle}
+ >
+ <span class="icon">
+ {#if icon}{@render icon()}{/if}
+ </span>
+ <span class="text">
+ <span class="title">{title}</span>
+ {#if subtitle}<span class="sub">{subtitle}</span>{/if}
+ </span>
+ </button>
+{/if}
+
+<style>
+ .nav-tile {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 16px 20px;
+ background: linear-gradient(135deg, var(--tile-accent), rgba(255,255,255,0.02));
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 16px;
+ color: inherit;
+ cursor: pointer;
+ text-align: left;
+ text-decoration: none;
+ font: inherit;
+ transition: transform 160ms ease, background 160ms ease, border-color 160ms ease;
+ min-width: 0;
+ }
+ .nav-tile:hover {
+ transform: translateY(-2px);
+ border-color: rgba(255, 255, 255, 0.18);
+ }
+ .icon {
+ flex: 0 0 auto;
+ width: 36px;
+ height: 36px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.07);
+ display: grid;
+ place-items: center;
+ color: rgba(255, 255, 255, 0.95);
+ }
+ .text {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+ }
+ .title {
+ font-size: 14px;
+ font-weight: 700;
+ color: white;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sub {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.55);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .nav-tile { transition: none; }
+ .nav-tile:hover { transform: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/NavigationTitle.svelte b/src/lib/study-music-components/NavigationTitle.svelte
new file mode 100644
index 00000000..c41c8088
--- /dev/null
+++ b/src/lib/study-music-components/NavigationTitle.svelte
@@ -0,0 +1,65 @@
+<script lang="ts">
+ import { t } from "$lib/i18n";
+ type Props = {
+ title: string;
+ seeAllHref?: string | null;
+ onSeeAll?: (() => void) | null;
+ };
+ let { title, seeAllHref = null, onSeeAll = null }: Props = $props();
+</script>
+
+<header class="nav-title">
+ <h2>{title}</h2>
+ {#if onSeeAll}
+ <button type="button" class="see-all" onclick={() => onSeeAll?.()}>
+ {$t("study.music.see_all")} <span class="arr" aria-hidden="true">→</span>
+ </button>
+ {:else if seeAllHref}
+ <a class="see-all" href={seeAllHref}>
+ {$t("study.music.see_all")} <span class="arr" aria-hidden="true">→</span>
+ </a>
+ {/if}
+</header>
+
+<style>
+ .nav-title {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ h2 {
+ margin: 0;
+ font-size: 20px;
+ font-weight: 800;
+ letter-spacing: -0.01em;
+ color: rgba(255, 255, 255, 0.95);
+ }
+ .see-all {
+ background: transparent;
+ border: 0;
+ padding: 4px 8px;
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.6);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ text-decoration: none;
+ transition: color 160ms ease;
+ }
+ .see-all:hover {
+ color: white;
+ }
+ .arr {
+ display: inline-block;
+ margin-left: 4px;
+ transition: transform 160ms ease;
+ }
+ .see-all:hover .arr {
+ transform: translateX(2px);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .see-all, .arr { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/PasteLyricsModal.svelte b/src/lib/study-music-components/PasteLyricsModal.svelte
new file mode 100644
index 00000000..fdff3b6f
--- /dev/null
+++ b/src/lib/study-music-components/PasteLyricsModal.svelte
@@ -0,0 +1,248 @@
+<script lang="ts">
+ import { lyricsStore } from "$lib/study-music/lyrics-store.svelte";
+ import { t } from "$lib/i18n";
+
+ type Props = {
+ open: boolean;
+ trackId: number | null;
+ onclose: () => void;
+ onsaved?: () => void;
+ };
+
+ let { open, trackId, onclose, onsaved }: Props = $props();
+
+ let text = $state("");
+ let saving = $state(false);
+ let invalid = $state(false);
+ let textareaEl = $state<HTMLTextAreaElement | null>(null);
+
+ const TIMESTAMP_RE = /\[\d{1,2}:\d{2}(?:[.:]\d{1,3})?\]/;
+
+ $effect(() => {
+ if (open) {
+ text = "";
+ invalid = false;
+ saving = false;
+ requestAnimationFrame(() => {
+ textareaEl?.focus();
+ });
+ }
+ });
+
+ function validateClientSide(value: string): boolean {
+ if (!value || value.trim().length === 0) return false;
+ return TIMESTAMP_RE.test(value);
+ }
+
+ async function save() {
+ if (trackId === null) return;
+ if (!validateClientSide(text)) {
+ invalid = true;
+ return;
+ }
+ invalid = false;
+ saving = true;
+ const ok = await lyricsStore.setLocal(trackId, text);
+ saving = false;
+ if (ok) {
+ onsaved?.();
+ onclose();
+ } else {
+ invalid = true;
+ }
+ }
+
+ function cancel() {
+ if (saving) return;
+ onclose();
+ }
+
+ function handleKey(e: KeyboardEvent) {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ cancel();
+ }
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ void save();
+ }
+ }
+</script>
+
+{#if open}
+ <div
+ class="overlay"
+ role="presentation"
+ onclick={cancel}
+ >
+ <div
+ class="modal"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="paste-lyrics-title"
+ onkeydown={handleKey}
+ onclick={(e) => e.stopPropagation()}
+ >
+ <header class="head">
+ <h3 id="paste-lyrics-title">{$t("study.music.lyrics_paste_title")}</h3>
+ <button
+ type="button"
+ class="ico"
+ onclick={cancel}
+ aria-label={$t("study.common.close") as string}
+ >×</button>
+ </header>
+
+ <p class="hint">{$t("study.music.lyrics_paste_hint")}</p>
+
+ <textarea
+ bind:this={textareaEl}
+ bind:value={text}
+ placeholder={$t("study.music.lyrics_paste_placeholder") as string}
+ rows="14"
+ spellcheck="false"
+ autocomplete="off"
+ class:invalid
+ ></textarea>
+
+ {#if invalid}
+ <p class="error">{$t("study.music.lyrics_paste_invalid")}</p>
+ {/if}
+
+ <footer class="foot">
+ <button type="button" class="ghost" onclick={cancel} disabled={saving}>
+ {$t("study.music.lyrics_paste_cancel")}
+ </button>
+ <button
+ type="button"
+ class="primary"
+ onclick={save}
+ disabled={saving || text.trim().length === 0}
+ >
+ {saving ? "…" : $t("study.music.lyrics_paste_save")}
+ </button>
+ </footer>
+ </div>
+ </div>
+{/if}
+
+<style>
+ .overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ backdrop-filter: blur(4px);
+ z-index: 200;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ }
+ .modal {
+ width: min(560px, 100%);
+ background: rgb(24, 24, 24);
+ color: rgba(255, 255, 255, 0.92);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 16px;
+ box-shadow: 0 32px 80px rgba(0, 0, 0, 0.7);
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 20px 20px 16px;
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .head h3 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 700;
+ }
+ .ico {
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ }
+ .ico:hover { color: white; background: rgba(255, 255, 255, 0.08); }
+ .hint {
+ margin: 0;
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.55);
+ line-height: 1.5;
+ }
+ textarea {
+ width: 100%;
+ resize: vertical;
+ min-height: 220px;
+ padding: 12px 14px;
+ background: rgb(14, 14, 14);
+ color: rgba(255, 255, 255, 0.95);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 10px;
+ font-family: ui-monospace, "Cascadia Mono", Menlo, Consolas, monospace;
+ font-size: 13px;
+ line-height: 1.55;
+ box-sizing: border-box;
+ transition: border-color 160ms ease, box-shadow 160ms ease;
+ }
+ textarea:focus {
+ outline: none;
+ border-color: var(--accent, #7c5cff);
+ box-shadow: 0 0 0 3px rgba(124, 92, 255, 0.18);
+ }
+ textarea.invalid {
+ border-color: rgb(255, 107, 107);
+ box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.18);
+ }
+ .error {
+ margin: 0;
+ font-size: 12px;
+ color: rgb(255, 138, 138);
+ }
+ .foot {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding-top: 6px;
+ }
+ .ghost,
+ .primary {
+ padding: 9px 16px;
+ border-radius: 999px;
+ border: 0;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 160ms ease, transform 160ms ease, opacity 160ms ease;
+ }
+ .ghost {
+ background: transparent;
+ color: rgba(255, 255, 255, 0.7);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ }
+ .ghost:hover:not(:disabled) {
+ color: white;
+ border-color: rgba(255, 255, 255, 0.28);
+ }
+ .primary {
+ background: var(--accent, #7c5cff);
+ color: white;
+ }
+ .primary:hover:not(:disabled) { filter: brightness(1.1); }
+ .primary:active:not(:disabled) { transform: scale(0.98); }
+ .primary:disabled,
+ .ghost:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+</style>
diff --git a/src/lib/study-music-components/PlayerBar.svelte b/src/lib/study-music-components/PlayerBar.svelte
index 694929e0..02637863 100644
--- a/src/lib/study-music-components/PlayerBar.svelte
+++ b/src/lib/study-music-components/PlayerBar.svelte
@@ -1,23 +1,83 @@
<script lang="ts">
+ import { goto } from "$app/navigation";
import { musicPlayer } from "$lib/study-music/player-store.svelte";
import { musicUI } from "$lib/study-music/ui-store.svelte";
import { t } from "$lib/i18n";
import CoverImage from "./CoverImage.svelte";
import ProgressBar from "./ProgressBar.svelte";
import VolumeControl from "./VolumeControl.svelte";
+ import PlayerErrorBanner from "./PlayerErrorBanner.svelte";
const t_ = $derived(musicPlayer.currentTrack);
+ const videoSupported = $derived(t_?.source === "youtube");
+ const showVideoOverlay = $derived(
+ musicUI.videoMode && videoSupported && !!musicPlayer.youtubeVideoUrl,
+ );
+ const isResolving = $derived(musicPlayer.status === "resolving");
+
+ let videoEl = $state<HTMLVideoElement | null>(null);
+
+ $effect(() => {
+ if (!videoEl) return;
+ const drift = Math.abs(videoEl.currentTime - musicPlayer.currentTime);
+ if (drift > 0.3 && Number.isFinite(musicPlayer.currentTime)) {
+ try {
+ videoEl.currentTime = musicPlayer.currentTime;
+ } catch {
+ /* readyState may be too low */
+ }
+ }
+ });
+
+ $effect(() => {
+ if (!videoEl) return;
+ if (musicPlayer.paused) {
+ videoEl.pause();
+ } else {
+ void videoEl.play().catch(() => {});
+ }
+ });
function favoriteToggle() {
if (!t_) return;
void musicPlayer.toggleFavorite(t_.id);
}
+
+ function openWatch() {
+ if (!t_ || !videoSupported || !musicPlayer.youtubeVideoUrl) return;
+ goto(`/study/music/watch/${t_.id}`);
+ }
+
+ function openNowPlaying() {
+ if (!t_) return;
+ goto("/study/music/now-playing");
+ }
+
+ function toggleVideoMode() {
+ if (!videoSupported) return;
+ musicUI.toggleVideoMode();
+ }
</script>
{#if t_}
+ <PlayerErrorBanner />
<div class="player-bar" role="region" aria-label={$t("study.music.player_aria")}>
<div class="left">
- <div class="cover-mini">
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="cover-mini"
+ class:expandable={showVideoOverlay}
+ class:resolving={isResolving}
+ onclick={showVideoOverlay ? openWatch : undefined}
+ role={showVideoOverlay ? "button" : undefined}
+ title={showVideoOverlay
+ ? ($t("study.music.expand_video") as string)
+ : isResolving
+ ? ($t("study.music.player_resolving") as string)
+ : undefined}
+ aria-busy={isResolving}
+ >
<CoverImage
src={t_.cover_path}
alt={t_.title ?? t_.path}
@@ -25,13 +85,38 @@
rounded="md"
trackId={t_.id}
/>
+ {#if isResolving}
+ <span class="resolve-spinner" aria-hidden="true"></span>
+ {/if}
+ {#if videoSupported && musicPlayer.youtubeVideoUrl}
+ {#key musicPlayer.youtubeVideoUrl}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video
+ bind:this={videoEl}
+ class="cover-video"
+ class:visible={showVideoOverlay}
+ src={musicPlayer.youtubeVideoUrl}
+ muted
+ playsinline
+ preload="auto"
+ tabindex="-1"
+ aria-hidden={!showVideoOverlay}
+ ></video>
+ {/key}
+ {/if}
</div>
- <div class="info">
+ <button
+ type="button"
+ class="info-btn"
+ onclick={openNowPlaying}
+ aria-label={$t("study.music.now_playing_open") as string}
+ title={$t("study.music.now_playing_open") as string}
+ >
<span class="title">{t_.title ?? t_.path}</span>
{#if t_.artist}
<span class="artist">{t_.artist}</span>
{/if}
- </div>
+ </button>
<button
type="button"
class="fav"
@@ -133,6 +218,24 @@
</div>
<div class="right">
+ <button
+ type="button"
+ class="ctrl-btn"
+ class:active={musicUI.videoMode && videoSupported}
+ disabled={!videoSupported}
+ onclick={toggleVideoMode}
+ aria-label={(videoSupported
+ ? $t("study.music.video_mode_toggle")
+ : $t("study.music.video_mode_only_youtube")) as string}
+ title={(videoSupported
+ ? $t("study.music.video_mode_toggle")
+ : $t("study.music.video_mode_only_youtube")) as string}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <rect x="2" y="6" width="14" height="12" rx="2"/>
+ <polygon points="22 8 16 12 22 16 22 8" fill={musicUI.videoMode && videoSupported ? "currentColor" : "none"}/>
+ </svg>
+ </button>
<button
type="button"
class="ctrl-btn"
@@ -226,19 +329,101 @@
min-width: 0;
}
.cover-mini {
+ position: relative;
flex-shrink: 0;
width: 56px;
height: 56px;
box-shadow: 0 2px 8px color-mix(in oklab, black 20%, transparent);
border-radius: 6px;
overflow: hidden;
+ background: rgba(40, 40, 40, 0.6);
}
- .info {
+ .cover-mini.expandable {
+ cursor: zoom-in;
+ }
+ .cover-mini.resolving :global(img),
+ .cover-mini.resolving :global(.cover-fallback) {
+ opacity: 0.45;
+ filter: saturate(0.6);
+ transition: opacity 200ms ease, filter 200ms ease;
+ }
+ .resolve-spinner {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 22px;
+ height: 22px;
+ margin: -11px 0 0 -11px;
+ border: 2px solid rgba(255, 255, 255, 0.45);
+ border-top-color: var(--accent);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ pointer-events: none;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .resolve-spinner { animation: none; border-top-color: rgba(255, 255, 255, 0.7); }
+ .cover-mini.resolving :global(img),
+ .cover-mini.resolving :global(.cover-fallback) {
+ transition: none;
+ }
+ }
+ .cover-mini.expandable:hover::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: color-mix(in oklab, black 30%, transparent);
+ border-radius: inherit;
+ pointer-events: none;
+ }
+ .cover-video {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ opacity: 0;
+ transition: opacity 200ms ease;
+ background: black;
+ pointer-events: none;
+ }
+ .cover-video.visible {
+ opacity: 1;
+ }
+ .ctrl-btn:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+ }
+ .ctrl-btn:disabled:hover {
+ color: var(--tertiary);
+ background: transparent;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .cover-video {
+ transition: none;
+ }
+ }
+ .info-btn {
display: flex;
flex-direction: column;
+ align-items: flex-start;
min-width: 0;
overflow: hidden;
flex: 1;
+ padding: 4px 6px;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ color: inherit;
+ cursor: pointer;
+ text-align: left;
+ font-family: inherit;
+ transition: background 120ms ease;
+ }
+ .info-btn:hover { background: rgba(255, 255, 255, 0.04); }
+ .info-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
}
.title {
font-size: 13px;
diff --git a/src/lib/study-music-components/PlayerErrorBanner.svelte b/src/lib/study-music-components/PlayerErrorBanner.svelte
new file mode 100644
index 00000000..1aa96079
--- /dev/null
+++ b/src/lib/study-music-components/PlayerErrorBanner.svelte
@@ -0,0 +1,180 @@
+<script lang="ts">
+ import { musicPlayer, type PlayerErrorKind } from "$lib/study-music/player-store.svelte";
+ import { t } from "$lib/i18n";
+
+ const err = $derived(musicPlayer.lastError);
+
+ const messageKeys: Record<PlayerErrorKind, string> = {
+ network: "study.music.player_error_network",
+ auth_expired: "study.music.player_error_auth_expired",
+ track_unavailable: "study.music.player_error_track_unavailable",
+ region_blocked: "study.music.player_error_region_blocked",
+ unsupported_format: "study.music.player_error_unsupported_format",
+ format_unavailable: "study.music.player_error_format_unavailable",
+ unknown: "study.music.player_error_unknown",
+ };
+
+ function primary() {
+ if (!err) return;
+ if (err.primaryAction === "refresh") {
+ void musicPlayer.refreshAndRetry();
+ } else if (err.primaryAction === "retry") {
+ musicPlayer.retry();
+ } else {
+ musicPlayer.skipOnError();
+ }
+ }
+
+ function secondary() {
+ if (!err) return;
+ musicPlayer.skipOnError();
+ }
+
+ function dismiss() {
+ musicPlayer.clearError();
+ }
+
+ function toggleAutoSkip(e: Event) {
+ const target = e.currentTarget as HTMLInputElement;
+ void musicPlayer.setAutoSkipOnError(target.checked);
+ }
+</script>
+
+{#if err}
+ <div class="banner" role="alert" aria-live="polite">
+ <div class="msg">{$t(messageKeys[err.kind])}</div>
+ <div class="actions">
+ <button type="button" class="primary" onclick={primary}>
+ {#if err.primaryAction === "refresh"}
+ {$t("study.music.player_action_refresh")}
+ {:else if err.primaryAction === "retry"}
+ {$t("study.music.player_action_retry")}
+ {:else}
+ {$t("study.music.player_action_skip")}
+ {/if}
+ </button>
+ {#if err.primaryAction !== "skip"}
+ <button type="button" class="secondary" onclick={secondary}>
+ {$t("study.music.player_action_skip")}
+ </button>
+ {/if}
+ <label class="auto-skip" title={$t("study.music.player_auto_skip_label") as string}>
+ <input
+ type="checkbox"
+ checked={musicPlayer.autoSkipOnError}
+ onchange={toggleAutoSkip}
+ />
+ <span>{$t("study.music.player_auto_skip_label")}</span>
+ </label>
+ <button
+ type="button"
+ class="dismiss"
+ onclick={dismiss}
+ aria-label={$t("study.music.player_dismiss_error") as string}
+ title={$t("study.music.player_dismiss_error") as string}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="18" y1="6" x2="6" y2="18"/>
+ <line x1="6" y1="6" x2="18" y2="18"/>
+ </svg>
+ </button>
+ </div>
+ </div>
+{/if}
+
+<style>
+ .banner {
+ position: fixed;
+ right: 18px;
+ bottom: 96px;
+ z-index: 100;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ max-width: min(520px, calc(100vw - 36px));
+ padding: 10px 14px;
+ background: color-mix(in oklab, var(--accent) 8%, var(--primary));
+ border: 1px solid color-mix(in oklab, var(--accent) 35%, transparent);
+ border-radius: 12px;
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ font-size: 13px;
+ color: var(--secondary);
+ animation: banner-in 220ms ease-out both;
+ }
+ @keyframes banner-in {
+ from { transform: translateY(8px); opacity: 0; }
+ to { transform: translateY(0); opacity: 1; }
+ }
+ :global(.music-shell[data-reduce-animations="true"]) .banner {
+ animation: none;
+ }
+ .msg {
+ flex: 0 1 auto;
+ font-weight: 500;
+ line-height: 1.35;
+ }
+ .actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-left: auto;
+ flex-shrink: 0;
+ }
+ .primary {
+ padding: 5px 12px;
+ border: 0;
+ border-radius: 999px;
+ background: var(--accent);
+ color: var(--on-accent, white);
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 120ms ease, transform 100ms ease;
+ }
+ .primary:hover { filter: brightness(1.1); }
+ .primary:active { transform: scale(0.97); }
+ .secondary {
+ padding: 5px 10px;
+ border: 1px solid color-mix(in oklab, var(--content-border) 80%, transparent);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--secondary);
+ font-size: 12px;
+ cursor: pointer;
+ transition: background 120ms ease;
+ }
+ .secondary:hover {
+ background: color-mix(in oklab, var(--secondary) 8%, transparent);
+ }
+ .auto-skip {
+ display: none;
+ }
+ .dismiss {
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: transparent;
+ color: var(--tertiary);
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ }
+ .dismiss:hover { color: var(--secondary); }
+ @media (max-width: 760px) {
+ .banner {
+ left: 12px;
+ right: 12px;
+ bottom: 92px;
+ max-width: none;
+ flex-wrap: wrap;
+ padding: 10px 12px;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .primary { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/ProgressBar.svelte b/src/lib/study-music-components/ProgressBar.svelte
index 239f35b2..9c6f1e8b 100644
--- a/src/lib/study-music-components/ProgressBar.svelte
+++ b/src/lib/study-music-components/ProgressBar.svelte
@@ -116,12 +116,10 @@
inset: 50% auto auto 0;
transform: translateY(-50%);
height: 4px;
- background: var(--secondary);
+ background: var(--music-scrubber-gradient, var(--music-accent, var(--secondary)));
border-radius: 2px;
pointer-events: none;
- }
- .track:hover .filled {
- background: var(--accent);
+ transition: background 400ms ease;
}
.thumb {
position: absolute;
@@ -130,11 +128,12 @@
height: 12px;
margin-left: -6px;
margin-top: -6px;
- background: var(--secondary);
+ background: var(--music-highlight, var(--secondary));
border-radius: 50%;
pointer-events: none;
opacity: 0;
- transition: opacity 120ms ease;
+ transition: opacity 120ms ease, background 400ms ease;
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
}
.track:hover .thumb {
opacity: 1;
diff --git a/src/lib/study-music-components/RightBar.svelte b/src/lib/study-music-components/RightBar.svelte
index 2b019d21..def6d839 100644
--- a/src/lib/study-music-components/RightBar.svelte
+++ b/src/lib/study-music-components/RightBar.svelte
@@ -6,6 +6,7 @@
import { fmtDuration, fmtDurationLong, trackDisplayTitle } from "$lib/study-music/format";
import { t } from "$lib/i18n";
import CoverImage from "./CoverImage.svelte";
+ import ChaptersList from "$lib/study-components/player/ChaptersList.svelte";
let lyricsContainer = $state<HTMLDivElement | null>(null);
let lineRefs: HTMLLIElement[] = [];
@@ -135,6 +136,22 @@
</svg>
<span>{$t("study.music.tab_info")}</span>
</button>
+ {#if musicPlayer.youtubeChapters.length > 0}
+ <button
+ type="button"
+ role="tab"
+ class="tab"
+ class:active={musicUI.rightbarTab === "chapters"}
+ aria-selected={musicUI.rightbarTab === "chapters"}
+ onclick={() => setTab("chapters")}
+ >
+ <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M3 6h18M3 12h18M3 18h18"/>
+ </svg>
+ <span>{$t("study.music.tab_chapters")}</span>
+ <span class="badge">{musicPlayer.youtubeChapters.length}</span>
+ </button>
+ {/if}
</nav>
<button type="button" class="close" onclick={close} aria-label={$t("study.common.close") as string}>×</button>
</header>
@@ -257,6 +274,20 @@
<p class="info-path" title={currentTrack.path}>{currentTrack.path}</p>
</div>
{/if}
+ {:else if musicUI.rightbarTab === "chapters"}
+ {#if musicPlayer.youtubeChapters.length === 0}
+ <p class="empty">{$t("study.music.chapters_empty")}</p>
+ {:else}
+ <div class="chapters-wrap">
+ <ChaptersList
+ chapters={musicPlayer.youtubeChapters}
+ currentTimeMs={Math.round(musicPlayer.currentTime * 1000)}
+ onJump={(toMs) => {
+ musicPlayer.seek(toMs / 1000);
+ }}
+ />
+ </div>
+ {/if}
{/if}
</div>
</aside>
@@ -540,4 +571,7 @@
color: rgba(255, 255, 255, 0.45);
word-break: break-all;
}
+ .chapters-wrap {
+ padding: 4px 0;
+ }
</style>
diff --git a/src/lib/study-music-components/Skeleton.svelte b/src/lib/study-music-components/Skeleton.svelte
new file mode 100644
index 00000000..b2ba2531
--- /dev/null
+++ b/src/lib/study-music-components/Skeleton.svelte
@@ -0,0 +1,51 @@
+<script lang="ts">
+ type Props = {
+ width?: string;
+ height?: string;
+ rounded?: "sm" | "md" | "lg" | "full" | "none";
+ block?: boolean;
+ };
+
+ let { width = "100%", height = "16px", rounded = "sm", block = false }: Props = $props();
+
+ const radius = $derived(
+ rounded === "full"
+ ? "999px"
+ : rounded === "lg"
+ ? "12px"
+ : rounded === "md"
+ ? "8px"
+ : rounded === "sm"
+ ? "4px"
+ : "0",
+ );
+</script>
+
+<span
+ class="skel"
+ class:block
+ style:width
+ style:height
+ style:border-radius={radius}
+ aria-hidden="true"
+></span>
+
+<style>
+ .skel {
+ display: inline-block;
+ background: linear-gradient(
+ 90deg,
+ color-mix(in oklab, var(--secondary) 8%, transparent) 0%,
+ color-mix(in oklab, var(--secondary) 16%, transparent) 50%,
+ color-mix(in oklab, var(--secondary) 8%, transparent) 100%
+ );
+ background-size: 200% 100%;
+ animation: skel-shimmer 1.4s ease-in-out infinite;
+ vertical-align: middle;
+ }
+ .block { display: block; }
+ @keyframes skel-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+</style>
diff --git a/src/lib/study-music-components/SoundCloudDownloadButton.svelte b/src/lib/study-music-components/SoundCloudDownloadButton.svelte
new file mode 100644
index 00000000..52c0d057
--- /dev/null
+++ b/src/lib/study-music-components/SoundCloudDownloadButton.svelte
@@ -0,0 +1,107 @@
+<script lang="ts">
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import type { ScTrack } from "$lib/study-music/soundcloud-store.svelte";
+
+ type Props = {
+ track: ScTrack;
+ onTrigger: (track: ScTrack, advanced: boolean) => void;
+ };
+
+ let { track, onTrigger }: Props = $props();
+
+ const job = $derived(downloadStore.getJobByTrackId(track.id));
+ const busy = $derived(
+ !!job && job.stage !== "done" && job.stage !== "skipped" && !job.error,
+ );
+ const pct = $derived(job?.progressPct ?? 0);
+ const stage = $derived(job?.stage);
+</script>
+
+{#if busy}
+ <button
+ type="button"
+ class="btn busy"
+ disabled
+ aria-label={`Baixando — ${pct}%`}
+ title={`Baixando — ${pct}%`}
+ >
+ <span class="ring" style="--pct: {pct}">
+ <span class="pct">{pct < 1 ? "" : pct}</span>
+ </span>
+ </button>
+{:else if job && (job.stage === "done" || job.stage === "skipped") && !job.error}
+ <button
+ type="button"
+ class="btn done"
+ aria-label="Baixado"
+ title="Baixado"
+ onclick={(e) => { e.stopPropagation(); onTrigger(track, e.shiftKey); }}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="20 6 9 17 4 12"/>
+ </svg>
+ </button>
+{:else}
+ <button
+ type="button"
+ class="btn"
+ onclick={(e) => { e.stopPropagation(); onTrigger(track, e.shiftKey); }}
+ aria-label="Baixar"
+ title={"Baixar (Shift = avançado)"}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="7 10 12 15 17 10"/>
+ <line x1="12" y1="15" x2="12" y2="3"/>
+ </svg>
+ </button>
+{/if}
+
+<style>
+ .btn {
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.5);
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ border-radius: 4px;
+ transition: background 200ms ease, color 200ms ease;
+ }
+ .btn:hover { background: rgba(255, 255, 255, 0.1); color: #ff5500; }
+ .btn:disabled { cursor: default; }
+ .btn.busy:hover { background: transparent; }
+ .btn.done { color: #4ade80; }
+ .btn.done:hover { color: #4ade80; background: rgba(74, 222, 128, 0.12); }
+ .ring {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background:
+ conic-gradient(#ff5500 calc(var(--pct, 0) * 1%), rgba(255, 255, 255, 0.16) 0);
+ display: grid;
+ place-items: center;
+ position: relative;
+ }
+ .ring::after {
+ content: "";
+ position: absolute;
+ inset: 3px;
+ background: var(--button, #1a1a1a);
+ border-radius: 50%;
+ }
+ .pct {
+ position: relative;
+ z-index: 1;
+ font-size: 8px;
+ font-weight: 700;
+ color: #ff5500;
+ line-height: 1;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .btn { transition: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/SoundCloudDownloadDialog.svelte b/src/lib/study-music-components/SoundCloudDownloadDialog.svelte
index a95efef7..a4a3df9a 100644
--- a/src/lib/study-music-components/SoundCloudDownloadDialog.svelte
+++ b/src/lib/study-music-components/SoundCloudDownloadDialog.svelte
@@ -1,12 +1,20 @@
<script lang="ts">
import { onMount } from "svelte";
- import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { showToast } from "$lib/stores/toast-store.svelte";
import {
soundcloudStore,
- type ScQuality,
type ScTrack,
} from "$lib/study-music/soundcloud-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import {
+ getLastCodec,
+ getLastDownloadDir,
+ getRememberDefaults,
+ setFirstDownloadDone,
+ setLastCodec,
+ setLastDownloadDir,
+ setRememberDefaults,
+ } from "$lib/study-music/local-prefs";
type Props = {
track: ScTrack;
@@ -15,17 +23,38 @@
let { track, onClose }: Props = $props();
- let qualities = $state<ScQuality[]>([]);
- let selectedQuality = $state<string>("");
+ type Mode = "mp3" | "flac" | "advanced";
+ let mode = $state<Mode>("mp3");
let codec = $state<string>("mp3");
+ let quality = $state<string>("progressive");
let outputDir = $state<string>("");
- let loading = $state(true);
- let downloading = $state(false);
- let progressMs = $state(0);
- let stage = $state<string>("");
- let unlisten: UnlistenFn | null = null;
+ let remember = $state<boolean>(true);
+ let downloading = $state<boolean>(false);
+
+ onMount(() => {
+ const lastCodec = getLastCodec();
+ const lastDir = getLastDownloadDir();
+ remember = getRememberDefaults();
+ if (lastDir) outputDir = lastDir;
+ if (lastCodec === "flac") {
+ mode = "flac";
+ codec = "flac";
+ } else if (lastCodec && lastCodec !== "mp3") {
+ mode = "advanced";
+ codec = lastCodec;
+ } else {
+ mode = "mp3";
+ codec = "mp3";
+ }
+ });
+
+ function setMode(next: Mode) {
+ mode = next;
+ if (next === "mp3") codec = "mp3";
+ else if (next === "flac") codec = "flac";
+ }
- const codecs = [
+ const advCodecs = [
{ id: "mp3", label: "MP3 192k" },
{ id: "opus", label: "Opus 96k" },
{ id: "vorbis", label: "Vorbis q3" },
@@ -34,42 +63,6 @@
{ id: "wav", label: "WAV PCM" },
];
- onMount(() => {
- void (async () => {
- try {
- qualities = await soundcloudStore.listQualities(track.id);
- const original = qualities.find((q) => q.quality === "original");
- const hq = qualities.find((q) => q.is_premium);
- const prog = qualities.find((q) => q.protocol === "progressive");
- selectedQuality = (original ?? hq ?? prog ?? qualities[0])?.quality ?? "progressive";
- } catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
- } finally {
- loading = false;
- }
-
- try {
- unlisten = await listen<{
- job_id: number;
- track_id: number;
- stage: string;
- progress_ms?: number;
- error?: string;
- }>("study-soundcloud-download-progress", (e) => {
- if (e.payload.track_id !== track.id) return;
- stage = e.payload.stage;
- if (typeof e.payload.progress_ms === "number") progressMs = e.payload.progress_ms;
- });
- } catch {
- /* ignore */
- }
- })();
-
- return () => {
- unlisten?.();
- };
- });
-
async function pickFolder() {
try {
const dialog = await import("@tauri-apps/plugin-dialog");
@@ -82,37 +75,64 @@
}
}
+ function folderName(dir: string): string {
+ const parts = dir.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] ?? dir;
+ }
+
async function startDownload() {
if (!outputDir) {
- showToast("error", "Escolha uma pasta de destino");
+ showToast("error", "Escolhe uma pasta primeiro");
return;
}
downloading = true;
- progressMs = 0;
- stage = "starting";
+ if (remember) {
+ setLastCodec(codec);
+ setLastDownloadDir(outputDir);
+ }
+ setRememberDefaults(remember);
+ setFirstDownloadDone();
+
+ const optimisticId = downloadStore.addOptimisticSingleJob({
+ trackId: track.id,
+ title: track.title,
+ artist: track.user.username,
+ artwork:
+ soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url) ?? null,
+ });
+ onClose();
+
try {
- const res = await soundcloudStore.download({
+ await soundcloudStore.download({
trackId: track.id,
codec,
outputDir,
- quality: selectedQuality,
+ quality,
});
- showToast("success", `Salvo em: ${res.path}`);
- onClose();
+ showToast("success", `Pronto — salvo na pasta ${folderName(outputDir)}`);
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
- downloading = false;
+ downloadStore.markJobError(
+ optimisticId,
+ e instanceof Error ? e.message : String(e),
+ );
}
}
-
- const totalMs = $derived(track.duration);
- const progressPct = $derived(
- totalMs > 0 ? Math.min(100, Math.round((progressMs / totalMs) * 100)) : 0,
- );
</script>
-<div class="backdrop" role="presentation" onclick={onClose} onkeydown={(e) => { if (e.key === "Escape") onClose(); }}>
- <div class="dialog" role="dialog" aria-modal="true" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()} tabindex="-1">
+<div
+ class="backdrop"
+ role="presentation"
+ onclick={onClose}
+ onkeydown={(e) => { if (e.key === "Escape") onClose(); }}
+>
+ <div
+ class="dialog"
+ role="dialog"
+ aria-modal="true"
+ onclick={(e) => e.stopPropagation()}
+ onkeydown={(e) => e.stopPropagation()}
+ tabindex="-1"
+ >
<header class="head">
<div class="info">
{#if track.artwork_url}
@@ -126,81 +146,97 @@
<button type="button" class="close" onclick={onClose} aria-label="Fechar">×</button>
</header>
- {#if loading}
- <p class="muted">Carregando opções de qualidade…</p>
- {:else}
- <section class="section">
- <h3>Qualidade</h3>
- <div class="quality-grid">
- {#each qualities as q (q.id)}
- <label class="quality-card" class:on={selectedQuality === q.quality}>
- <input
- type="radio"
- name="quality"
- value={q.quality}
- bind:group={selectedQuality}
- />
- <div class="quality-content">
- <span class="quality-label">{q.label}</span>
- <span class="quality-meta">
- {q.protocol === "download" ? "Download direto" : q.protocol.toUpperCase()}
- {#if q.is_premium}
- <span class="premium-tag">Go+</span>
- {/if}
- </span>
- </div>
- </label>
- {/each}
- </div>
- </section>
-
- <section class="section">
- <h3>Formato de saída</h3>
- <div class="codec-row">
- {#each codecs as c (c.id)}
- <button
- type="button"
- class="codec-pill"
- class:on={codec === c.id}
- onclick={() => (codec = c.id)}
- >
- {c.label}
- </button>
- {/each}
- </div>
- </section>
-
- <section class="section">
- <h3>Salvar em</h3>
- <div class="folder-row">
- <input type="text" bind:value={outputDir} placeholder="Escolha a pasta…" readonly />
- <button type="button" class="ghost" onclick={pickFolder}>Procurar…</button>
- </div>
- </section>
-
- {#if downloading}
- <div class="progress-block">
- <div class="progress-bar">
- <div class="progress-fill" style:width={`${progressPct}%`}></div>
- </div>
- <p class="progress-text">{stage} · {progressPct}%</p>
- </div>
- {/if}
-
- <footer class="actions">
- <button type="button" class="ghost" onclick={onClose} disabled={downloading}>
- Cancelar
+ <section class="section">
+ <h3>Como salvar?</h3>
+ <div class="mode-pills">
+ <button
+ type="button"
+ class="mode-pill"
+ class:on={mode === "mp3"}
+ onclick={() => setMode("mp3")}
+ >
+ <span class="pill-title">MP3</span>
+ <span class="pill-sub">Recomendado · funciona em tudo</span>
</button>
<button
type="button"
- class="cta"
- onclick={startDownload}
- disabled={downloading || !outputDir || !selectedQuality}
+ class="mode-pill"
+ class:on={mode === "flac"}
+ onclick={() => setMode("flac")}
>
- {downloading ? "Baixando…" : "Baixar"}
+ <span class="pill-title">FLAC</span>
+ <span class="pill-sub">Sem perda · arquivo grande</span>
</button>
- </footer>
- {/if}
+ <button
+ type="button"
+ class="mode-pill ghost"
+ class:on={mode === "advanced"}
+ onclick={() => setMode("advanced")}
+ >
+ <span class="pill-title">⚙ Avançado…</span>
+ <span class="pill-sub">Outros codecs</span>
+ </button>
+ </div>
+
+ {#if mode === "advanced"}
+ <div class="adv-block">
+ <div class="adv-row">
+ <span class="adv-label" id="codec-group-label">Codec</span>
+ <div class="codec-row" role="group" aria-labelledby="codec-group-label">
+ {#each advCodecs as c (c.id)}
+ <button
+ type="button"
+ class="codec-pill"
+ class:on={codec === c.id}
+ onclick={() => (codec = c.id)}
+ >
+ {c.label}
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="adv-row">
+ <label class="adv-label" for="quality-select">Fonte</label>
+ <select id="quality-select" class="quality-select" bind:value={quality}>
+ <option value="progressive">Progressivo MP3 128 (padrão)</option>
+ <option value="hq">HQ AAC ~256 (Go+)</option>
+ <option value="original">Original do uploader (se permitido)</option>
+ </select>
+ </div>
+ </div>
+ {/if}
+ </section>
+
+ <section class="section">
+ <h3>Onde salvar?</h3>
+ <div class="folder-row">
+ <input
+ type="text"
+ bind:value={outputDir}
+ placeholder="Escolhe uma pasta…"
+ readonly
+ />
+ <button type="button" class="ghost" onclick={pickFolder}>Procurar…</button>
+ </div>
+ <label class="remember">
+ <input type="checkbox" bind:checked={remember} />
+ <span>Lembrar pasta e formato pra próxima</span>
+ </label>
+ </section>
+
+ <footer class="actions">
+ <button type="button" class="ghost" onclick={onClose} disabled={downloading}>
+ Cancelar
+ </button>
+ <button
+ type="button"
+ class="cta"
+ onclick={startDownload}
+ disabled={downloading || !outputDir}
+ >
+ {downloading ? "Iniciando…" : "Baixar"}
+ </button>
+ </footer>
</div>
</div>
@@ -222,32 +258,38 @@
.artist { font-size: 12px; color: rgba(255,255,255,0.55); }
.close { background: transparent; border: 0; color: rgba(255,255,255,0.6); font-size: 24px; cursor: pointer; line-height: 1; }
.close:hover { color: white; }
- .section { display: flex; flex-direction: column; gap: 8px; }
+ .section { display: flex; flex-direction: column; gap: 10px; }
.section h3 { margin: 0; font-size: 13px; font-weight: 700; color: rgba(255,255,255,0.7); text-transform: uppercase; letter-spacing: 0.05em; }
- .quality-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
- .quality-card { display: flex; gap: 8px; padding: 10px 12px; background: rgba(255,255,255,0.04); border: 1px solid transparent; border-radius: 8px; cursor: pointer; }
- .quality-card:hover { background: rgba(255,255,255,0.06); }
- .quality-card.on { border-color: #ff5500; background: rgba(255, 85, 0, 0.1); }
- .quality-card input { display: none; }
- .quality-content { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
- .quality-label { font-size: 13px; font-weight: 600; }
- .quality-meta { font-size: 11px; color: rgba(255,255,255,0.5); display: flex; align-items: center; gap: 6px; }
- .premium-tag { background: linear-gradient(90deg, #ff5500, #ffd700); color: black; padding: 1px 6px; border-radius: 3px; font-size: 9px; font-weight: 800; text-transform: uppercase; }
+ .mode-pills { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+ .mode-pill {
+ display: flex; flex-direction: column; gap: 2px; align-items: flex-start;
+ padding: 12px 14px; background: rgba(255,255,255,0.04); border: 1px solid transparent;
+ border-radius: 10px; color: white; cursor: pointer; text-align: left;
+ transition: background 200ms ease, border-color 200ms ease;
+ }
+ .mode-pill:hover { background: rgba(255,255,255,0.08); }
+ .mode-pill.on { border-color: #ff5500; background: rgba(255, 85, 0, 0.12); }
+ .mode-pill.ghost { background: rgba(255,255,255,0.025); }
+ .pill-title { font-size: 14px; font-weight: 700; }
+ .pill-sub { font-size: 11px; color: rgba(255,255,255,0.55); }
+ .mode-pill.on .pill-sub { color: rgba(255,255,255,0.7); }
+ .adv-block { display: flex; flex-direction: column; gap: 10px; padding: 12px; background: rgba(255,255,255,0.03); border-radius: 8px; }
+ .adv-row { display: flex; flex-direction: column; gap: 6px; }
+ .adv-label { font-size: 11px; font-weight: 700; color: rgba(255,255,255,0.55); text-transform: uppercase; letter-spacing: 0.05em; }
.codec-row { display: flex; flex-wrap: wrap; gap: 6px; }
.codec-pill { padding: 6px 14px; background: rgba(255,255,255,0.06); border: 1px solid transparent; border-radius: 999px; color: white; font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer; transition: background 200ms ease; }
.codec-pill:hover { background: rgba(255,255,255,0.1); }
.codec-pill.on { background: #ff5500; color: white; }
+ .quality-select { background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.08); border-radius: 6px; color: white; padding: 8px 10px; font-family: inherit; font-size: 13px; }
+ .quality-select:focus { outline: 0; border-color: #ff5500; }
.folder-row { display: flex; gap: 8px; }
.folder-row input { flex: 1; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; color: white; padding: 8px 12px; font-family: inherit; font-size: 13px; outline: none; }
- .progress-block { display: flex; flex-direction: column; gap: 6px; }
- .progress-bar { height: 6px; background: rgba(255,255,255,0.1); border-radius: 3px; overflow: hidden; }
- .progress-fill { height: 100%; background: #ff5500; transition: width 200ms ease; }
- .progress-text { margin: 0; font-size: 12px; color: rgba(255,255,255,0.6); }
+ .remember { display: flex; align-items: center; gap: 8px; font-size: 12px; color: rgba(255,255,255,0.7); cursor: pointer; user-select: none; }
+ .remember input { accent-color: #ff5500; }
.actions { display: flex; justify-content: flex-end; gap: 8px; }
.ghost { padding: 8px 18px; background: rgba(255,255,255,0.05); border: 0; border-radius: 999px; color: white; font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer; }
.ghost:hover:not(:disabled) { background: rgba(255,255,255,0.1); }
.cta { padding: 8px 24px; background: #ff5500; border: 0; border-radius: 999px; color: white; font-family: inherit; font-size: 13px; font-weight: 700; cursor: pointer; transition: background 200ms ease; }
.cta:hover:not(:disabled) { background: #ff7733; }
.cta:disabled, .ghost:disabled { opacity: 0.5; cursor: default; }
- .muted { color: rgba(255,255,255,0.5); font-size: 13px; }
</style>
diff --git a/src/lib/study-music-components/SoundCloudError.svelte b/src/lib/study-music-components/SoundCloudError.svelte
new file mode 100644
index 00000000..498e98ac
--- /dev/null
+++ b/src/lib/study-music-components/SoundCloudError.svelte
@@ -0,0 +1,213 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { studySoundcloudHumanizeError } from "$lib/study-bridge";
+ import MascotSlot from "$lib/components/MascotSlot.svelte";
+ import { petsGetActive } from "$lib/pets/sync";
+
+ type Props = {
+ error: string;
+ trackUrl?: string;
+ onRetry?: () => void;
+ };
+ let { error, trackUrl, onRetry }: Props = $props();
+
+ let humanized = $state<string>("Erro tecnico. Toca os detalhes pra ver o que aconteceu");
+ let petSlug = $state<string | null>(null);
+
+ onMount(() => {
+ let active = true;
+ petsGetActive()
+ .then((slug) => {
+ if (active) petSlug = slug;
+ })
+ .catch(() => {
+ if (active) petSlug = null;
+ });
+ return () => {
+ active = false;
+ };
+ });
+
+ async function resolve(err: string) {
+ try {
+ const res = await studySoundcloudHumanizeError({ error: err });
+ humanized = res.humanized;
+ } catch {}
+ }
+
+ async function openInSoundcloud() {
+ if (!trackUrl) return;
+ try {
+ const { openUrl } = await import("@tauri-apps/plugin-opener");
+ await openUrl(trackUrl);
+ } catch {
+ window.open(trackUrl, "_blank", "noopener,noreferrer");
+ }
+ }
+
+ $effect(() => {
+ void resolve(error);
+ console.warn("[study-music] sc error:", error);
+ });
+</script>
+
+<div class="sc-error" role="alert">
+ <div class="pet" aria-hidden="true">
+ <MascotSlot slug={petSlug} event="syncError" scale={0.23} fallback="warn" />
+ </div>
+ <div class="body">
+ <p class="kicker">SoundCloud</p>
+ <p class="msg">{humanized}</p>
+ <p class="hint">Tentamos outras qualidades antes de mostrar esse aviso.</p>
+ <div class="actions">
+ {#if onRetry}
+ <button type="button" class="btn primary" onclick={onRetry}>Tentar de novo</button>
+ {/if}
+ {#if trackUrl}
+ <button type="button" class="btn ghost" onclick={openInSoundcloud}>
+ Abrir no SoundCloud
+ </button>
+ {/if}
+ </div>
+ <details class="details">
+ <summary>Detalhes tecnicos</summary>
+ <pre class="raw">{error}</pre>
+ </details>
+ </div>
+</div>
+
+<style>
+ .sc-error {
+ --sc-accent: oklch(66% 0.22 38);
+ --sc-accent-soft: oklch(66% 0.22 38 / 0.12);
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 14px;
+ align-items: start;
+ padding: 16px;
+ background: color-mix(in oklab, var(--sc-accent-soft) 72%, var(--surface, transparent));
+ border: 1px solid color-mix(in oklab, var(--sc-accent) 36%, transparent);
+ border-radius: 12px;
+ color: var(--secondary);
+ }
+
+ .pet {
+ width: 48px;
+ min-height: 48px;
+ display: grid;
+ place-items: center;
+ color: var(--sc-accent);
+ overflow: hidden;
+ }
+
+ .pet :global(.slot-fallback) {
+ color: var(--sc-accent);
+ }
+
+ .body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+ }
+
+ .kicker {
+ margin: 0;
+ color: var(--sc-accent);
+ font-size: 11px;
+ font-weight: 800;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ }
+
+ .msg {
+ margin: 0;
+ color: var(--primary);
+ font-size: 14px;
+ font-weight: 700;
+ line-height: 1.35;
+ }
+
+ .hint {
+ margin: 0;
+ color: var(--tertiary);
+ font-size: 12px;
+ line-height: 1.45;
+ }
+
+ .actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ }
+
+ .btn {
+ min-height: 30px;
+ padding: 0 12px;
+ border-radius: 999px;
+ border: 0;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+
+ .btn.primary {
+ background: var(--sc-accent);
+ color: oklch(99% 0.01 75);
+ }
+
+ .btn.primary:hover {
+ background: oklch(72% 0.22 38);
+ }
+
+ .btn.ghost {
+ background: color-mix(in oklab, var(--button) 55%, transparent);
+ color: var(--secondary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 58%, transparent);
+ }
+
+ .btn.ghost:hover {
+ color: var(--primary);
+ background: color-mix(in oklab, var(--button) 80%, transparent);
+ }
+
+ .details {
+ color: var(--tertiary);
+ font-size: 12px;
+ }
+
+ .details summary {
+ width: max-content;
+ cursor: pointer;
+ font-weight: 600;
+ }
+
+ .details summary:hover {
+ color: var(--secondary);
+ }
+
+ .raw {
+ margin: 8px 0 0;
+ padding: 9px 10px;
+ background: color-mix(in oklab, var(--button) 76%, transparent);
+ border-radius: 8px;
+ font-size: 11px;
+ font-family: var(--mono, ui-monospace, monospace);
+ color: var(--tertiary);
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 200px;
+ overflow: auto;
+ }
+
+ @media (max-width: 560px) {
+ .sc-error {
+ grid-template-columns: 1fr;
+ }
+
+ .pet {
+ display: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-music-components/SpeedDialGridItem.svelte b/src/lib/study-music-components/SpeedDialGridItem.svelte
new file mode 100644
index 00000000..df7d56fd
--- /dev/null
+++ b/src/lib/study-music-components/SpeedDialGridItem.svelte
@@ -0,0 +1,79 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+ type Props = {
+ label: string;
+ href?: string | null;
+ onClick?: (() => void) | null;
+ icon?: Snippet;
+ accentTint?: string | null;
+ };
+ let { label, href = null, onClick = null, icon, accentTint = null }: Props = $props();
+</script>
+
+{#if href}
+ <a class="dial-item" {href} style:--tint={accentTint ?? "rgba(255,255,255,0.08)"}>
+ <span class="icon-wrap">
+ {#if icon}{@render icon()}{/if}
+ </span>
+ <span class="label">{label}</span>
+ </a>
+{:else}
+ <button
+ type="button"
+ class="dial-item"
+ style:--tint={accentTint ?? "rgba(255,255,255,0.08)"}
+ onclick={() => onClick?.()}
+ >
+ <span class="icon-wrap">
+ {#if icon}{@render icon()}{/if}
+ </span>
+ <span class="label">{label}</span>
+ </button>
+{/if}
+
+<style>
+ .dial-item {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 14px 8px 12px;
+ background: var(--tint);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 16px;
+ color: white;
+ font: inherit;
+ cursor: pointer;
+ text-decoration: none;
+ transition: transform 160ms ease, background 160ms ease, border-color 160ms ease;
+ min-width: 0;
+ }
+ .dial-item:hover {
+ transform: translateY(-2px);
+ border-color: rgba(255, 255, 255, 0.2);
+ }
+ .icon-wrap {
+ width: 44px;
+ height: 44px;
+ border-radius: 14px;
+ background: rgba(255, 255, 255, 0.08);
+ display: grid;
+ place-items: center;
+ color: white;
+ }
+ .label {
+ font-size: 12px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.92);
+ text-align: center;
+ line-height: 1.2;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 100%;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .dial-item { transition: none; }
+ .dial-item:hover { transform: none; }
+ }
+</style>
diff --git a/src/lib/study-music-components/StickyHeader.svelte b/src/lib/study-music-components/StickyHeader.svelte
new file mode 100644
index 00000000..5f687bce
--- /dev/null
+++ b/src/lib/study-music-components/StickyHeader.svelte
@@ -0,0 +1,51 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import type { Snippet } from "svelte";
+
+ type Props = {
+ threshold?: number;
+ children: Snippet;
+ };
+ let { threshold = 64, children }: Props = $props();
+
+ let scrolled = $state(false);
+
+ onMount(() => {
+ const scrollEl = document.scrollingElement ?? document.documentElement;
+ function check() {
+ scrolled = scrollEl.scrollTop > threshold;
+ }
+ check();
+ window.addEventListener("scroll", check, { passive: true });
+ return () => {
+ window.removeEventListener("scroll", check);
+ };
+ });
+</script>
+
+<div class="sticky-header" class:opaque={scrolled}>
+ {@render children()}
+</div>
+
+<style>
+ .sticky-header {
+ position: sticky;
+ top: 0;
+ z-index: 20;
+ padding: 12px 24px;
+ background: transparent;
+ border-bottom: 1px solid transparent;
+ transition: background 200ms ease, border-color 200ms ease,
+ backdrop-filter 200ms ease;
+ }
+ .sticky-header.opaque {
+ background: color-mix(in oklab, var(--background, #0e0e10) 88%, transparent);
+ border-bottom-color: rgba(255, 255, 255, 0.08);
+ backdrop-filter: blur(24px);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .sticky-header {
+ transition: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-music-components/TrackListRow.svelte b/src/lib/study-music-components/TrackListRow.svelte
new file mode 100644
index 00000000..ef920c2a
--- /dev/null
+++ b/src/lib/study-music-components/TrackListRow.svelte
@@ -0,0 +1,161 @@
+<script lang="ts">
+ import type { Snippet } from "svelte";
+
+ type Props = {
+ index?: number | null;
+ coverUrl?: string | null;
+ title: string;
+ subtitle?: string | null;
+ durationText?: string | null;
+ isPlaying?: boolean;
+ showIndex?: boolean;
+ onPlay?: () => void;
+ actions?: Snippet;
+ ariaLabelPlay?: string;
+ };
+
+ let {
+ index = null,
+ coverUrl = null,
+ title,
+ subtitle = null,
+ durationText = null,
+ isPlaying = false,
+ showIndex = true,
+ onPlay,
+ actions,
+ ariaLabelPlay,
+ }: Props = $props();
+
+ function handleKey(e: KeyboardEvent) {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onPlay?.();
+ }
+ }
+</script>
+
+<div class="row" class:is-playing={isPlaying} role="row">
+ <button
+ type="button"
+ class="leading"
+ onclick={() => onPlay?.()}
+ onkeydown={handleKey}
+ aria-label={ariaLabelPlay ?? title}
+ >
+ {#if coverUrl}
+ <img class="cover-mini" src={coverUrl} alt="" loading="lazy" />
+ {:else if showIndex && index != null}
+ <span class="index tabular-nums">{index + 1}</span>
+ {:else}
+ <span class="index tabular-nums" aria-hidden="true">–</span>
+ {/if}
+ </button>
+ <button
+ type="button"
+ class="body"
+ onclick={() => onPlay?.()}
+ aria-label={ariaLabelPlay ?? title}
+ >
+ <span class="title-line" title={title}>{title}</span>
+ {#if subtitle}
+ <span class="subtitle" title={subtitle}>{subtitle}</span>
+ {/if}
+ </button>
+ {#if durationText}
+ <span class="duration tabular-nums" aria-hidden="true">{durationText}</span>
+ {/if}
+ {#if actions}
+ <div class="actions">{@render actions()}</div>
+ {/if}
+</div>
+
+<style>
+ .row {
+ display: grid;
+ grid-template-columns: 48px 1fr auto auto;
+ align-items: center;
+ gap: 12px;
+ padding: 6px 8px;
+ border-radius: 8px;
+ transition: background 120ms ease;
+ }
+ .row:hover {
+ background: rgba(255, 255, 255, 0.04);
+ }
+ .row.is-playing {
+ background: color-mix(in oklab, var(--accent) 14%, transparent);
+ }
+ .leading {
+ width: 48px;
+ height: 48px;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ overflow: hidden;
+ padding: 0;
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ color: rgba(255, 255, 255, 0.55);
+ }
+ .cover-mini {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .index {
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: rgba(255, 255, 255, 0.55);
+ }
+ .row.is-playing .index {
+ color: var(--accent);
+ }
+ .body {
+ text-align: left;
+ background: transparent;
+ border: 0;
+ padding: 0;
+ min-width: 0;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ color: inherit;
+ }
+ .title-line {
+ font-size: 14px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.92);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .row.is-playing .title-line {
+ color: var(--accent);
+ }
+ .subtitle {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.55);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .duration {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.55);
+ padding: 0 8px;
+ }
+ .actions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .row {
+ transition: none;
+ }
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeChannelCard.svelte b/src/lib/study-music-youtube-components/YoutubeChannelCard.svelte
new file mode 100644
index 00000000..c3bdd58b
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeChannelCard.svelte
@@ -0,0 +1,67 @@
+<script lang="ts">
+ import { goto } from "$app/navigation";
+ import type { YoutubeSearchChannelItem } from "$lib/study-bridge";
+
+ type Props = { item: YoutubeSearchChannelItem };
+ let { item }: Props = $props();
+
+ function open() {
+ goto(`/study/music/youtube/channel/${item.channel_id}`);
+ }
+</script>
+
+<button class="card" onclick={open} type="button">
+ <div class="avatar">
+ {#if item.avatar_url}
+ <img src={item.avatar_url} alt="" loading="lazy" />
+ {/if}
+ </div>
+ <p class="title" title={item.title}>{item.title}</p>
+ {#if item.handle}
+ <p class="handle">{item.handle}</p>
+ {/if}
+ {#if item.subscribers_text}
+ <p class="subs">{item.subscribers_text}</p>
+ {/if}
+</button>
+
+<style>
+ .card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ padding: 12px 8px;
+ background: transparent;
+ border: 0;
+ border-radius: 12px;
+ color: var(--secondary);
+ cursor: pointer;
+ text-align: center;
+ }
+ .card:hover { background: color-mix(in oklab, var(--button) 30%, transparent); }
+ .avatar {
+ width: 96px;
+ height: 96px;
+ border-radius: 50%;
+ overflow: hidden;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ display: block;
+ }
+ .avatar img { width: 100%; height: 100%; object-fit: cover; }
+ .title {
+ margin: 6px 0 0 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--primary);
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .handle, .subs {
+ margin: 0;
+ font-size: 11px;
+ color: var(--tertiary);
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeConnectHero.svelte b/src/lib/study-music-youtube-components/YoutubeConnectHero.svelte
new file mode 100644
index 00000000..3131c42b
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeConnectHero.svelte
@@ -0,0 +1,178 @@
+<script lang="ts">
+ import { t } from "$lib/i18n";
+ import { musicUI } from "$lib/study-music/ui-store.svelte";
+ import { goto } from "$app/navigation";
+
+ type Props = {
+ status: "missing" | "no_youtube";
+ filePath: string;
+ };
+
+ let { status, filePath }: Props = $props();
+
+ function openConfigPanel() {
+ musicUI.openYoutube();
+ }
+
+ function exploreAnonymously() {
+ goto("/study/music/youtube/explore");
+ }
+</script>
+
+<section class="connect-hero">
+ <div class="hero-card">
+ <div class="hero-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M23 12s-3-7-11-7-11 7-11 7 3 7 11 7 11-7 11-7z"/>
+ <circle cx="12" cy="12" r="3"/>
+ </svg>
+ </div>
+
+ <h1 class="hero-title">{$t("study.music.youtube.connect_title")}</h1>
+ <p class="hero-body">{$t("study.music.youtube.connect_body")}</p>
+
+ {#if status === "missing"}
+ <div class="hint-block">
+ <p class="hint-label">{$t("study.music.youtube.connect_step_missing_label")}</p>
+ <p class="hint-text">{$t("study.music.youtube.connect_step_missing")}</p>
+ {#if filePath}
+ <code class="path">{filePath}</code>
+ {/if}
+ </div>
+ {:else}
+ <div class="hint-block">
+ <p class="hint-label">{$t("study.music.youtube.connect_step_no_youtube_label")}</p>
+ <p class="hint-text">{$t("study.music.youtube.connect_step_no_youtube")}</p>
+ </div>
+ {/if}
+
+ <div class="cta-row">
+ <button type="button" class="cta-primary" onclick={openConfigPanel}>
+ {$t("study.music.youtube.connect_cta_setup")}
+ </button>
+ <button type="button" class="cta-secondary" onclick={exploreAnonymously}>
+ {$t("study.music.youtube.connect_cta_anon")}
+ </button>
+ </div>
+
+ <p class="footnote">{$t("study.music.youtube.connect_footnote")}</p>
+ </div>
+</section>
+
+<style>
+ .connect-hero {
+ display: flex;
+ justify-content: center;
+ padding: 40px 20px;
+ }
+ .hero-card {
+ max-width: 560px;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 14px;
+ padding: 32px 28px;
+ background: color-mix(in oklab, var(--button) 30%, transparent);
+ border: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);
+ border-radius: 16px;
+ }
+ .hero-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ background: rgba(255, 0, 0, 0.12);
+ color: #ff4444;
+ margin-bottom: 4px;
+ }
+ .hero-title {
+ margin: 0;
+ font-size: 22px;
+ font-weight: 700;
+ color: var(--primary);
+ line-height: 1.25;
+ }
+ .hero-body {
+ margin: 0;
+ font-size: 14px;
+ color: var(--secondary);
+ line-height: 1.5;
+ }
+ .hint-block {
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 14px 16px;
+ background: color-mix(in oklab, var(--button) 40%, transparent);
+ border-left: 3px solid var(--accent);
+ border-radius: 0 8px 8px 0;
+ }
+ .hint-label {
+ margin: 0;
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--tertiary);
+ }
+ .hint-text {
+ margin: 0;
+ font-size: 13px;
+ color: var(--secondary);
+ line-height: 1.5;
+ }
+ .path {
+ display: inline-block;
+ margin-top: 4px;
+ padding: 3px 8px;
+ font-family: ui-monospace, "Cascadia Code", "Source Code Pro", monospace;
+ font-size: 11px;
+ color: var(--tertiary);
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ border-radius: 4px;
+ word-break: break-all;
+ }
+ .cta-row {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-top: 6px;
+ }
+ .cta-primary {
+ padding: 9px 18px;
+ background: var(--accent);
+ color: #fff;
+ border: 0;
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: filter 120ms;
+ }
+ .cta-primary:hover { filter: brightness(1.1); }
+ .cta-secondary {
+ padding: 9px 18px;
+ background: transparent;
+ color: var(--secondary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: border-color 120ms, color 120ms;
+ }
+ .cta-secondary:hover {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .footnote {
+ margin: 8px 0 0;
+ font-size: 11px;
+ color: var(--tertiary);
+ line-height: 1.5;
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeError.svelte b/src/lib/study-music-youtube-components/YoutubeError.svelte
new file mode 100644
index 00000000..9bc2bdcd
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeError.svelte
@@ -0,0 +1,120 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { studyYoutubeHumanizeError } from "$lib/study-bridge";
+
+ type Props = {
+ error: string;
+ onRetry?: () => void;
+ fallbackLabel?: string;
+ onFallback?: () => void;
+ };
+ let { error, onRetry, fallbackLabel, onFallback }: Props = $props();
+
+ let humanized = $state<string>("Algo deu errado ao falar com o YouTube");
+ let showDetails = $state(false);
+
+ async function resolve(err: string) {
+ try {
+ const res = await studyYoutubeHumanizeError({ error: err });
+ humanized = res.humanized;
+ } catch {
+ /* keep default */
+ }
+ }
+
+ $effect(() => {
+ void resolve(error);
+ console.warn("[study-music] yt error:", error);
+ });
+</script>
+
+<div class="yt-error" role="alert">
+ <svg
+ viewBox="0 0 24 24"
+ width="22"
+ height="22"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <circle cx="12" cy="12" r="10" />
+ <line x1="12" y1="8" x2="12" y2="13" />
+ <line x1="12" y1="16" x2="12" y2="16.01" />
+ </svg>
+ <div class="body">
+ <p class="msg">{humanized}</p>
+ <div class="actions">
+ {#if onRetry}
+ <button type="button" class="btn primary" onclick={onRetry}>Tentar de novo</button>
+ {/if}
+ {#if onFallback}
+ <button type="button" class="btn ghost" onclick={onFallback}>{fallbackLabel ?? "Ouvir só áudio"}</button>
+ {/if}
+ <button
+ type="button"
+ class="btn link"
+ onclick={() => (showDetails = !showDetails)}
+ aria-expanded={showDetails}
+ >
+ {showDetails ? "Esconder detalhes" : "Detalhes técnicos"}
+ </button>
+ </div>
+ {#if showDetails}
+ <pre class="raw">{error}</pre>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .yt-error {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 12px;
+ padding: 14px 16px;
+ background: color-mix(in oklab, var(--button) 40%, transparent);
+ border: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);
+ border-radius: 10px;
+ color: var(--secondary);
+ }
+ .yt-error svg { color: var(--tertiary); margin-top: 2px; }
+ .body { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
+ .msg { margin: 0; font-size: 14px; color: var(--primary); }
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; }
+ .btn {
+ padding: 6px 12px;
+ border-radius: 999px;
+ border: 0;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .btn.primary { background: var(--accent); color: #fff; }
+ .btn.ghost {
+ background: transparent;
+ color: var(--secondary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ }
+ .btn.link {
+ background: transparent;
+ color: var(--tertiary);
+ padding: 6px 0;
+ font-weight: 500;
+ }
+ .btn.link:hover { color: var(--secondary); }
+ .raw {
+ margin: 0;
+ padding: 8px 10px;
+ background: color-mix(in oklab, var(--button) 70%, transparent);
+ border-radius: 6px;
+ font-size: 11px;
+ font-family: var(--mono, monospace);
+ color: var(--tertiary);
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 200px;
+ overflow: auto;
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeItem.svelte b/src/lib/study-music-youtube-components/YoutubeItem.svelte
new file mode 100644
index 00000000..7906527a
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeItem.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import type { YoutubeSearchItem } from "$lib/study-bridge";
+ import YoutubeVideoCard from "./YoutubeVideoCard.svelte";
+ import YoutubeChannelCard from "./YoutubeChannelCard.svelte";
+ import YoutubePlaylistCard from "./YoutubePlaylistCard.svelte";
+
+ type Props = {
+ item: YoutubeSearchItem;
+ onPlay?: (videoId: string) => void;
+ onPlaylistOpen?: (playlistId: string) => void;
+ };
+ let { item, onPlay, onPlaylistOpen }: Props = $props();
+</script>
+
+{#if item.kind === "video"}
+ <YoutubeVideoCard item={item} {onPlay} />
+{:else if item.kind === "channel"}
+ <YoutubeChannelCard item={item} />
+{:else if item.kind === "playlist" || item.kind === "mix"}
+ <YoutubePlaylistCard item={item} onOpen={onPlaylistOpen} />
+{/if}
diff --git a/src/lib/study-music-components/YoutubePanel.svelte b/src/lib/study-music-youtube-components/YoutubePanel.svelte
similarity index 100%
rename from src/lib/study-music-components/YoutubePanel.svelte
rename to src/lib/study-music-youtube-components/YoutubePanel.svelte
diff --git a/src/lib/study-music-youtube-components/YoutubePlaylistCard.svelte b/src/lib/study-music-youtube-components/YoutubePlaylistCard.svelte
new file mode 100644
index 00000000..922ab294
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubePlaylistCard.svelte
@@ -0,0 +1,94 @@
+<script lang="ts">
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import type { YoutubeSearchPlaylistItem, YoutubeSearchMixItem } from "$lib/study-bridge";
+
+ type Props = {
+ item: YoutubeSearchPlaylistItem | YoutubeSearchMixItem;
+ onOpen?: (playlistId: string) => void;
+ };
+ let { item, onOpen }: Props = $props();
+
+ function open() {
+ if (onOpen) {
+ onOpen(item.playlist_id);
+ return;
+ }
+ const route = item.playlist_id.startsWith("OLAK") ? "album" : "playlist";
+ void goto(`/study/music/youtube/${route}/${encodeURIComponent(item.playlist_id)}`);
+ }
+
+ let videoCount = $derived(item.kind === "playlist" ? item.video_count : null);
+ let channelTitle = $derived(item.kind === "playlist" ? item.channel_title : null);
+</script>
+
+<button class="card" onclick={open} type="button">
+ <div class="thumb-wrap">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="thumb-placeholder"></div>
+ {/if}
+ <div class="stack-edge"></div>
+ {#if videoCount != null}
+ <span class="count tabular-nums">{$t("study.music.tracks_count_n", { count: videoCount })}</span>
+ {/if}
+ </div>
+ <p class="title" title={item.title}>{item.title}</p>
+ {#if channelTitle}
+ <p class="meta">{channelTitle}</p>
+ {/if}
+</button>
+
+<style>
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ text-align: left;
+ cursor: pointer;
+ color: var(--secondary);
+ }
+ .thumb-wrap {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ border-radius: 8px;
+ overflow: hidden;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ }
+ .thumb-wrap img { width: 100%; height: 100%; object-fit: cover; display: block; }
+ .stack-edge {
+ position: absolute;
+ right: -2px;
+ top: 4px;
+ bottom: 4px;
+ width: 4px;
+ border-radius: 0 8px 8px 0;
+ background: color-mix(in oklab, var(--button) 80%, transparent);
+ }
+ .count {
+ position: absolute;
+ right: 6px;
+ bottom: 6px;
+ padding: 2px 6px;
+ border-radius: 4px;
+ background: rgba(0, 0, 0, 0.75);
+ color: #fff;
+ font-size: 11px;
+ }
+ .title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--primary);
+ line-height: 1.3;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .meta { margin: 0; font-size: 11px; color: var(--tertiary); }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeShelf.svelte b/src/lib/study-music-youtube-components/YoutubeShelf.svelte
new file mode 100644
index 00000000..b22300ec
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeShelf.svelte
@@ -0,0 +1,39 @@
+<script lang="ts">
+ import type { YoutubeSearchItem } from "$lib/study-bridge";
+ import YoutubeItem from "./YoutubeItem.svelte";
+
+ type Props = {
+ title?: string | null;
+ items: YoutubeSearchItem[];
+ onPlay?: (videoId: string) => void;
+ onPlaylistOpen?: (playlistId: string) => void;
+ minCard?: number;
+ };
+ let { title, items, onPlay, onPlaylistOpen, minCard = 220 }: Props = $props();
+</script>
+
+<section class="shelf">
+ {#if title}
+ <h3 class="title">{title}</h3>
+ {/if}
+ <div class="grid" style="--min-card: {minCard}px">
+ {#each items as item, idx (idx)}
+ <YoutubeItem item={item} {onPlay} {onPlaylistOpen} />
+ {/each}
+ </div>
+</section>
+
+<style>
+ .shelf { display: flex; flex-direction: column; gap: 12px; }
+ .title {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 700;
+ color: var(--secondary);
+ }
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(var(--min-card, 220px), 1fr));
+ gap: 18px 14px;
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeSkeleton.svelte b/src/lib/study-music-youtube-components/YoutubeSkeleton.svelte
new file mode 100644
index 00000000..a50d6bd1
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeSkeleton.svelte
@@ -0,0 +1,72 @@
+<script lang="ts">
+ type Kind = "card" | "channel" | "row";
+ type Props = { kind?: Kind; count?: number };
+ let { kind = "card", count = 1 }: Props = $props();
+
+ let total = $derived(Math.max(1, count));
+</script>
+
+{#each Array(total) as _, idx (idx)}
+ {#if kind === "card"}
+ <div class="skel-card" aria-hidden="true">
+ <div class="thumb shimmer"></div>
+ <div class="line shimmer wide"></div>
+ <div class="line shimmer mid"></div>
+ </div>
+ {:else if kind === "channel"}
+ <div class="skel-channel" aria-hidden="true">
+ <div class="avatar shimmer"></div>
+ <div class="line shimmer wide"></div>
+ <div class="line shimmer narrow"></div>
+ </div>
+ {:else}
+ <div class="skel-row" aria-hidden="true">
+ <div class="row-thumb shimmer"></div>
+ <div class="row-info">
+ <div class="line shimmer wide"></div>
+ <div class="line shimmer mid"></div>
+ </div>
+ </div>
+ {/if}
+{/each}
+
+<style>
+ .skel-card { display: flex; flex-direction: column; gap: 8px; }
+ .skel-card .thumb { aspect-ratio: 16 / 9; border-radius: 8px; }
+ .skel-channel { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 8px; }
+ .skel-channel .avatar { width: 96px; height: 96px; border-radius: 50%; }
+ .skel-row {
+ display: grid;
+ grid-template-columns: 160px 1fr;
+ gap: 14px;
+ align-items: center;
+ padding: 8px;
+ border-radius: 10px;
+ }
+ .skel-row .row-thumb { width: 160px; aspect-ratio: 16 / 9; border-radius: 8px; }
+ .row-info { display: flex; flex-direction: column; gap: 6px; }
+ .line {
+ height: 12px;
+ border-radius: 4px;
+ }
+ .line.wide { width: 90%; }
+ .line.mid { width: 60%; }
+ .line.narrow { width: 40%; }
+ .shimmer {
+ background: linear-gradient(
+ 90deg,
+ color-mix(in oklab, var(--button) 40%, transparent) 0%,
+ color-mix(in oklab, var(--button) 80%, transparent) 50%,
+ color-mix(in oklab, var(--button) 40%, transparent) 100%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.6s linear infinite;
+ }
+ @keyframes shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .shimmer { animation: none; background: color-mix(in oklab, var(--button) 60%, transparent); }
+ }
+</style>
diff --git a/src/lib/study-music-youtube-components/YoutubeVideoCard.svelte b/src/lib/study-music-youtube-components/YoutubeVideoCard.svelte
new file mode 100644
index 00000000..d3742385
--- /dev/null
+++ b/src/lib/study-music-youtube-components/YoutubeVideoCard.svelte
@@ -0,0 +1,150 @@
+<script lang="ts">
+ import { goto } from "$app/navigation";
+ import type { YoutubeSearchVideoItem } from "$lib/study-bridge";
+
+ type Props = {
+ item: YoutubeSearchVideoItem;
+ onPlay?: (videoId: string) => void;
+ };
+ let { item, onPlay }: Props = $props();
+
+ function play() {
+ if (onPlay) onPlay(item.video_id);
+ }
+
+ function openChannel(e: MouseEvent) {
+ e.stopPropagation();
+ if (item.channel_id) goto(`/study/music/youtube/channel/${item.channel_id}`);
+ }
+</script>
+
+<div class="card">
+ <button type="button" class="thumb-wrap" onclick={play} aria-label={item.title}>
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="thumb-placeholder"></div>
+ {/if}
+ {#if item.duration_text}
+ <span class="duration tabular-nums">{item.duration_text}</span>
+ {/if}
+ {#if item.is_live}
+ <span class="live">AO VIVO</span>
+ {/if}
+ </button>
+ <div class="meta">
+ <button type="button" class="title-btn" onclick={play} title={item.title}>
+ <span class="title">{item.title}</span>
+ </button>
+ {#if item.channel_title}
+ <button class="channel" onclick={openChannel} type="button" title={item.channel_title}>
+ {item.channel_title}
+ </button>
+ {/if}
+ <p class="stats">
+ {#if item.view_count_text}<span>{item.view_count_text}</span>{/if}
+ {#if item.view_count_text && item.published_time_text}<span> · </span>{/if}
+ {#if item.published_time_text}<span>{item.published_time_text}</span>{/if}
+ </p>
+ </div>
+</div>
+
+<style>
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 0;
+ color: var(--secondary);
+ }
+ .thumb-wrap {
+ position: relative;
+ aspect-ratio: 16 / 9;
+ border-radius: 8px;
+ overflow: hidden;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ padding: 0;
+ border: 0;
+ cursor: pointer;
+ display: block;
+ width: 100%;
+ }
+ .thumb-wrap:hover { transform: translateY(-2px); transition: transform 120ms; }
+ .title-btn {
+ padding: 0;
+ background: transparent;
+ border: 0;
+ text-align: left;
+ cursor: pointer;
+ color: inherit;
+ width: 100%;
+ }
+ .title-btn:hover .title { color: var(--accent); }
+ .thumb-wrap img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .thumb-placeholder {
+ width: 100%;
+ height: 100%;
+ background: color-mix(in oklab, var(--button) 50%, transparent);
+ }
+ .duration {
+ position: absolute;
+ right: 6px;
+ bottom: 6px;
+ padding: 2px 6px;
+ border-radius: 4px;
+ background: rgba(0, 0, 0, 0.75);
+ color: #fff;
+ font-size: 11px;
+ font-weight: 500;
+ }
+ .live {
+ position: absolute;
+ left: 6px;
+ top: 6px;
+ padding: 2px 6px;
+ border-radius: 4px;
+ background: #d33;
+ color: #fff;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ }
+ .meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+ .title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--primary);
+ line-height: 1.3;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .channel {
+ margin: 0;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ font-size: 12px;
+ cursor: pointer;
+ text-align: left;
+ align-self: flex-start;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .channel:hover { color: var(--accent); }
+ .stats {
+ margin: 0;
+ font-size: 11px;
+ color: var(--tertiary);
+ }
+</style>
diff --git a/src/lib/study-music/dominant-color.ts b/src/lib/study-music/dominant-color.ts
index 73de368a..e1f0ff39 100644
--- a/src/lib/study-music/dominant-color.ts
+++ b/src/lib/study-music/dominant-color.ts
@@ -3,7 +3,9 @@ import { convertFileSrc } from "@tauri-apps/api/core";
export type RGB = { r: number; g: number; b: number };
const cache = new Map<string, RGB>();
+const paletteCache = new Map<string, RGB[]>();
const inFlight = new Map<string, Promise<RGB | null>>();
+const paletteInFlight = new Map<string, Promise<RGB[] | null>>();
const FALLBACK: RGB = { r: 35, g: 35, b: 38 };
@@ -57,6 +59,12 @@ function vibrantize(rgb: RGB): RGB {
return hslToRgb(h, boostedS, adjustedL);
}
+function harmonize(rgb: RGB, targetLightness: number, satBoost: number): RGB {
+ const [h, s, _l] = rgbToHsl(rgb.r, rgb.g, rgb.b);
+ const sat = Math.min(1, Math.max(0.15, s * satBoost));
+ return hslToRgb(h, sat, targetLightness);
+}
+
async function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
@@ -108,6 +116,89 @@ function sampleAverage(img: HTMLImageElement): RGB {
};
}
+type Bucket = {
+ rSum: number;
+ gSum: number;
+ bSum: number;
+ count: number;
+ sat: number;
+};
+
+function samplePalette(img: HTMLImageElement, k: number): RGB[] {
+ const W = 48;
+ const H = 48;
+ const canvas = document.createElement("canvas");
+ canvas.width = W;
+ canvas.height = H;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return [];
+ ctx.drawImage(img, 0, 0, W, H);
+ let data: ImageData;
+ try {
+ data = ctx.getImageData(0, 0, W, H);
+ } catch {
+ return [];
+ }
+ const buf = data.data;
+ const HUE_BINS = 12;
+ const LIGHT_BINS = 3;
+ const buckets = new Map<number, Bucket>();
+ for (let i = 0; i < buf.length; i += 4) {
+ const alpha = buf[i + 3];
+ if (alpha < 200) continue;
+ const rr = buf[i];
+ const gg = buf[i + 1];
+ const bb = buf[i + 2];
+ const [h, s, l] = rgbToHsl(rr, gg, bb);
+ if (l < 0.12 || l > 0.88) continue;
+ const hueIdx = Math.min(HUE_BINS - 1, Math.floor(h * HUE_BINS));
+ const lightIdx = Math.min(LIGHT_BINS - 1, Math.floor(l * LIGHT_BINS));
+ const key = hueIdx * LIGHT_BINS + lightIdx;
+ let b = buckets.get(key);
+ if (!b) {
+ b = { rSum: 0, gSum: 0, bSum: 0, count: 0, sat: 0 };
+ buckets.set(key, b);
+ }
+ b.rSum += rr;
+ b.gSum += gg;
+ b.bSum += bb;
+ b.count++;
+ b.sat += s;
+ }
+ if (buckets.size === 0) return [];
+ const scored = Array.from(buckets.values())
+ .map((b) => ({
+ rgb: {
+ r: (b.rSum / b.count) | 0,
+ g: (b.gSum / b.count) | 0,
+ b: (b.bSum / b.count) | 0,
+ },
+ score: b.count * (0.4 + 0.6 * (b.sat / b.count)),
+ }))
+ .sort((a, b) => b.score - a.score);
+ const out: RGB[] = [];
+ for (const entry of scored) {
+ if (out.length >= k) break;
+ const [, , l] = rgbToHsl(entry.rgb.r, entry.rgb.g, entry.rgb.b);
+ if (l < 0.15 || l > 0.85) continue;
+ out.push(entry.rgb);
+ }
+ if (out.length === 0 && scored.length > 0) {
+ out.push(scored[0].rgb);
+ }
+ return out;
+}
+
+function buildHarmonizedPalette(raw: RGB[]): RGB[] {
+ if (raw.length === 0) return [];
+ const dominant = vibrantize(raw[0]);
+ const accentSource = raw[1] ?? raw[0];
+ const accent = harmonize(accentSource, 0.42, 1.3);
+ const highlightSource = raw[2] ?? raw[1] ?? raw[0];
+ const highlight = harmonize(highlightSource, 0.6, 1.15);
+ return [dominant, accent, highlight];
+}
+
export async function dominantColorFromPath(path: string | null | undefined): Promise<RGB | null> {
if (!path) return null;
if (cache.has(path)) return cache.get(path)!;
@@ -137,6 +228,37 @@ export async function dominantColorFromPath(path: string | null | undefined): Pr
return promise;
}
+export async function palettePathOrUrl(input: string | null | undefined): Promise<RGB[] | null> {
+ if (!input) return null;
+ if (paletteCache.has(input)) return paletteCache.get(input)!;
+ const existing = paletteInFlight.get(input);
+ if (existing) return existing;
+ const promise = (async () => {
+ try {
+ const url = (() => {
+ if (/^https?:\/\//i.test(input)) return input;
+ try {
+ return convertFileSrc(input);
+ } catch {
+ return input;
+ }
+ })();
+ const img = await loadImage(url);
+ const raw = samplePalette(img, 4);
+ const harmonized = buildHarmonizedPalette(raw);
+ if (harmonized.length === 0) return null;
+ paletteCache.set(input, harmonized);
+ return harmonized;
+ } catch {
+ return null;
+ } finally {
+ paletteInFlight.delete(input);
+ }
+ })();
+ paletteInFlight.set(input, promise);
+ return promise;
+}
+
export function rgbToCss(rgb: RGB | null): string {
if (!rgb) return "rgb(35,35,38)";
return `rgb(${rgb.r},${rgb.g},${rgb.b})`;
diff --git a/src/lib/study-music/download-store.svelte.ts b/src/lib/study-music/download-store.svelte.ts
new file mode 100644
index 00000000..1fe42fca
--- /dev/null
+++ b/src/lib/study-music/download-store.svelte.ts
@@ -0,0 +1,376 @@
+import { listen, type UnlistenFn } from "@tauri-apps/api/event";
+
+export type DownloadJobStage =
+ | "pending"
+ | "starting"
+ | "downloading"
+ | "done"
+ | "skipped"
+ | "error";
+
+export type DownloadJobKind = "single" | "bulk";
+
+export type DownloadJobState = {
+ id: string;
+ kind: DownloadJobKind;
+ trackId?: number;
+ playlistId?: number;
+ title: string;
+ artist?: string;
+ artwork?: string | null;
+ stage: DownloadJobStage;
+ progressPct: number;
+ totalCount?: number;
+ currentCount?: number;
+ successCount?: number;
+ failedCount?: number;
+ currentTrackTitle?: string;
+ failedTracks?: { id: number; title: string; error?: string }[];
+ codec?: string;
+ outputDir?: string;
+ error?: string;
+ path?: string;
+ permalinkUrl?: string;
+ startedAt: number;
+ updatedAt: number;
+ expanded?: boolean;
+};
+
+type SinglePayload = {
+ job_id: number;
+ track_id?: number;
+ title?: string;
+ artist?: string;
+ duration_ms?: number;
+ stage: string;
+ progress_ms?: number;
+ error?: string;
+ path?: string;
+ permalink_url?: string;
+ reason?: string;
+};
+
+type BulkPayload = {
+ playlist_id: number;
+ stage: string;
+ current?: number;
+ total?: number;
+ success?: number;
+ failed?: number;
+ title?: string;
+ failed_track_id?: number;
+ failed_track_title?: string;
+ failed_track_error?: string;
+};
+
+function pctFromMs(progressMs: number, totalMs: number, fallback: number): number {
+ if (totalMs > 0) return Math.min(100, Math.round((progressMs / totalMs) * 100));
+ return fallback;
+}
+
+function pctFromCount(current: number, total: number, fallback: number): number {
+ if (total > 0) return Math.min(100, Math.round((current / total) * 100));
+ return fallback;
+}
+
+class DownloadStore {
+ jobs = $state<Map<string, DownloadJobState>>(new Map());
+ drawerOpen = $state(false);
+
+ private pendingByTrackId = new Map<number, string>();
+ private listeners: UnlistenFn[] = [];
+ private nonce = 0;
+ private started = false;
+
+ start() {
+ if (this.started) return;
+ this.started = true;
+ void (async () => {
+ try {
+ const single = await listen<SinglePayload>(
+ "study-soundcloud-download-progress",
+ (e) => this.handleSingle(e.payload),
+ );
+ this.listeners.push(single);
+ } catch (err) {
+ console.warn("[sc-download-store] listen single failed", err);
+ }
+ try {
+ const bulk = await listen<BulkPayload>(
+ "study-soundcloud-download-bulk-progress",
+ (e) => this.handleBulk(e.payload),
+ );
+ this.listeners.push(bulk);
+ } catch (err) {
+ console.warn("[sc-download-store] listen bulk failed", err);
+ }
+ })();
+ }
+
+ stop() {
+ for (const u of this.listeners) {
+ try {
+ u();
+ } catch {
+ /* ignore */
+ }
+ }
+ this.listeners = [];
+ this.started = false;
+ }
+
+ private handleSingle(p: SinglePayload) {
+ if (typeof p.job_id !== "number") return;
+ const key = `single-${p.job_id}`;
+ const trackId = typeof p.track_id === "number" ? p.track_id : undefined;
+ const next = new Map(this.jobs);
+ let prev = next.get(key);
+ if (!prev && trackId !== undefined) {
+ const optimisticKey = this.pendingByTrackId.get(trackId);
+ if (optimisticKey) {
+ const opt = next.get(optimisticKey);
+ if (opt) prev = opt;
+ next.delete(optimisticKey);
+ this.pendingByTrackId.delete(trackId);
+ }
+ }
+ const rawStage = (p.stage ?? "downloading") as DownloadJobStage;
+ const stage: DownloadJobStage = rawStage;
+ const totalMs = typeof p.duration_ms === "number" ? p.duration_ms : 0;
+ const progressMs = typeof p.progress_ms === "number" ? p.progress_ms : 0;
+ const fallbackPct = prev?.progressPct ?? 0;
+ const progressPct =
+ stage === "done" || stage === "skipped"
+ ? 100
+ : pctFromMs(progressMs, totalMs, fallbackPct);
+ const job: DownloadJobState = {
+ id: key,
+ kind: "single",
+ trackId,
+ title: p.title ?? prev?.title ?? "Faixa",
+ artist: p.artist ?? prev?.artist,
+ artwork: prev?.artwork ?? null,
+ stage,
+ progressPct,
+ error: stage === "error" ? p.error ?? "Erro desconhecido" : prev?.error,
+ path: p.path ?? prev?.path,
+ permalinkUrl: p.permalink_url ?? prev?.permalinkUrl,
+ startedAt: prev?.startedAt ?? Date.now(),
+ updatedAt: Date.now(),
+ };
+ next.set(key, job);
+ this.jobs = next;
+ }
+
+ private handleBulk(p: BulkPayload) {
+ if (typeof p.playlist_id !== "number") return;
+ const key = `bulk-${p.playlist_id}`;
+ const next = new Map(this.jobs);
+ const prev = next.get(key);
+ const rawStage = (p.stage ?? "downloading") as DownloadJobStage;
+ const stage: DownloadJobStage = rawStage;
+ const total = p.total ?? prev?.totalCount ?? 0;
+ const current = p.current ?? prev?.currentCount ?? 0;
+ const fallbackPct = prev?.progressPct ?? 0;
+ const progressPct =
+ stage === "done" ? 100 : pctFromCount(current, total, fallbackPct);
+ const currentTrackTitle = stage === "downloading" ? p.title : prev?.currentTrackTitle;
+ const failedTracks = (prev?.failedTracks ?? []).slice();
+ if (
+ typeof p.failed_track_id === "number" &&
+ !failedTracks.some((ft) => ft.id === p.failed_track_id)
+ ) {
+ failedTracks.push({
+ id: p.failed_track_id,
+ title: p.failed_track_title ?? `Faixa ${p.failed_track_id}`,
+ error: p.failed_track_error,
+ });
+ }
+ const job: DownloadJobState = {
+ id: key,
+ kind: "bulk",
+ playlistId: p.playlist_id,
+ title: prev?.title ?? `Playlist #${p.playlist_id}`,
+ artwork: prev?.artwork ?? null,
+ stage,
+ progressPct,
+ totalCount: total,
+ currentCount: current,
+ successCount: p.success ?? prev?.successCount,
+ failedCount: p.failed ?? prev?.failedCount,
+ currentTrackTitle,
+ failedTracks,
+ codec: prev?.codec,
+ outputDir: prev?.outputDir,
+ startedAt: prev?.startedAt ?? Date.now(),
+ updatedAt: Date.now(),
+ expanded: prev?.expanded ?? false,
+ };
+ next.set(key, job);
+ this.jobs = next;
+ }
+
+ addOptimisticSingleJob(input: {
+ trackId: number;
+ title: string;
+ artist?: string;
+ artwork?: string | null;
+ }): string {
+ this.nonce += 1;
+ const id = `pending-${input.trackId}-${this.nonce}`;
+ const next = new Map(this.jobs);
+ next.set(id, {
+ id,
+ kind: "single",
+ trackId: input.trackId,
+ title: input.title,
+ artist: input.artist,
+ artwork: input.artwork ?? null,
+ stage: "pending",
+ progressPct: 0,
+ startedAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ this.jobs = next;
+ this.pendingByTrackId.set(input.trackId, id);
+ return id;
+ }
+
+ addOptimisticBulkJob(input: {
+ playlistId: number;
+ title: string;
+ total: number;
+ artwork?: string | null;
+ codec?: string;
+ outputDir?: string;
+ }): string {
+ const id = `bulk-${input.playlistId}`;
+ const next = new Map(this.jobs);
+ const prev = next.get(id);
+ next.set(id, {
+ id,
+ kind: "bulk",
+ playlistId: input.playlistId,
+ title: input.title,
+ artwork: input.artwork ?? null,
+ stage: prev?.stage ?? "pending",
+ progressPct: prev?.progressPct ?? 0,
+ totalCount: input.total,
+ currentCount: prev?.currentCount ?? 0,
+ successCount: prev?.successCount,
+ failedCount: prev?.failedCount,
+ currentTrackTitle: prev?.currentTrackTitle,
+ failedTracks: prev?.failedTracks ?? [],
+ codec: input.codec ?? prev?.codec,
+ outputDir: input.outputDir ?? prev?.outputDir,
+ startedAt: prev?.startedAt ?? Date.now(),
+ updatedAt: Date.now(),
+ expanded: prev?.expanded ?? false,
+ });
+ this.jobs = next;
+ return id;
+ }
+
+ consumeFailedTracks(jobId: string): { id: number; title: string; error?: string }[] {
+ const job = this.jobs.get(jobId);
+ if (!job || !job.failedTracks?.length) return [];
+ const taken = job.failedTracks.slice();
+ const next = new Map(this.jobs);
+ next.set(jobId, { ...job, failedTracks: [], updatedAt: Date.now() });
+ this.jobs = next;
+ return taken;
+ }
+
+ removeFailedTrackFromBulk(jobId: string, failedTrackId: number) {
+ const job = this.jobs.get(jobId);
+ if (!job || !job.failedTracks?.length) return;
+ const next = new Map(this.jobs);
+ next.set(jobId, {
+ ...job,
+ failedTracks: job.failedTracks.filter((ft) => ft.id !== failedTrackId),
+ updatedAt: Date.now(),
+ });
+ this.jobs = next;
+ }
+
+ markJobError(jobId: string, error: string) {
+ const next = new Map(this.jobs);
+ const prev = next.get(jobId);
+ if (!prev) return;
+ next.set(jobId, {
+ ...prev,
+ stage: "error",
+ error,
+ updatedAt: Date.now(),
+ });
+ this.jobs = next;
+ if (prev.trackId !== undefined && this.pendingByTrackId.get(prev.trackId) === jobId) {
+ this.pendingByTrackId.delete(prev.trackId);
+ }
+ }
+
+ removeJob(jobId: string) {
+ const next = new Map(this.jobs);
+ const prev = next.get(jobId);
+ if (!prev) return;
+ next.delete(jobId);
+ this.jobs = next;
+ if (prev.trackId !== undefined && this.pendingByTrackId.get(prev.trackId) === jobId) {
+ this.pendingByTrackId.delete(prev.trackId);
+ }
+ }
+
+ clearCompleted() {
+ const next = new Map(this.jobs);
+ for (const [id, job] of Array.from(next)) {
+ if ((job.stage === "done" || job.stage === "skipped") && !job.error) {
+ next.delete(id);
+ }
+ }
+ this.jobs = next;
+ }
+
+ toggleExpanded(jobId: string) {
+ const next = new Map(this.jobs);
+ const prev = next.get(jobId);
+ if (!prev) return;
+ next.set(jobId, { ...prev, expanded: !prev.expanded });
+ this.jobs = next;
+ }
+
+ toggleDrawer(force?: boolean) {
+ this.drawerOpen = typeof force === "boolean" ? force : !this.drawerOpen;
+ }
+
+ get jobsList(): DownloadJobState[] {
+ return Array.from(this.jobs.values()).sort((a, b) => b.startedAt - a.startedAt);
+ }
+
+ get activeCount(): number {
+ let n = 0;
+ for (const job of this.jobs.values()) {
+ if (job.stage !== "done" && job.stage !== "skipped" && job.stage !== "error") {
+ n += 1;
+ }
+ }
+ return n;
+ }
+
+ get hasJobs(): boolean {
+ return this.jobs.size > 0;
+ }
+
+ getJobByTrackId(trackId: number): DownloadJobState | null {
+ let active: DownloadJobState | null = null;
+ let any: DownloadJobState | null = null;
+ for (const job of this.jobs.values()) {
+ if (job.trackId !== trackId) continue;
+ if (!any || job.updatedAt > any.updatedAt) any = job;
+ if (job.stage === "done" || job.stage === "skipped" || job.stage === "error") continue;
+ if (!active || job.updatedAt > active.updatedAt) active = job;
+ }
+ return active ?? any;
+ }
+}
+
+export const downloadStore = new DownloadStore();
diff --git a/src/lib/study-music/hls-loader.svelte.ts b/src/lib/study-music/hls-loader.svelte.ts
index caf636f1..26e71b8a 100644
--- a/src/lib/study-music/hls-loader.svelte.ts
+++ b/src/lib/study-music/hls-loader.svelte.ts
@@ -1,40 +1,4 @@
-declare global {
- interface Window {
- Hls?: any;
- }
-}
-
-const HLS_CDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/hls.min.js";
-
-let loadingPromise: Promise<void> | null = null;
-
-export async function ensureHlsLoaded(): Promise<void> {
- if (typeof window === "undefined") return;
- if (window.Hls) return;
- if (loadingPromise) return loadingPromise;
-
- loadingPromise = new Promise<void>((resolve, reject) => {
- const existing = document.querySelector(`script[src="${HLS_CDN}"]`);
- if (existing) {
- existing.addEventListener("load", () => resolve());
- existing.addEventListener("error", () =>
- reject(new Error("Falha ao carregar hls.js")),
- );
- return;
- }
- const script = document.createElement("script");
- script.src = HLS_CDN;
- script.async = true;
- script.onload = () => resolve();
- script.onerror = () => reject(new Error("Falha ao carregar hls.js"));
- document.head.appendChild(script);
- }).catch((e) => {
- loadingPromise = null;
- throw e;
- });
-
- return loadingPromise;
-}
+import Hls from "hls.js";
export type HlsHandle = {
destroy: () => void;
@@ -47,19 +11,16 @@ export async function attachHls(audio: HTMLAudioElement, m3u8Url: string): Promi
destroy: () => {
try {
audio.src = "";
- } catch {
- /* ignore */
- }
+ } catch {}
},
};
}
- await ensureHlsLoaded();
- if (!window.Hls || !window.Hls.isSupported()) {
- throw new Error("HLS não é suportado neste navegador");
+ if (!Hls.isSupported()) {
+ throw new Error("HLS nao e suportado neste navegador");
}
- const hls = new window.Hls({
+ const hls = new Hls({
enableWorker: false,
lowLatencyMode: false,
});
@@ -70,9 +31,7 @@ export async function attachHls(audio: HTMLAudioElement, m3u8Url: string): Promi
destroy: () => {
try {
hls.destroy();
- } catch {
- /* ignore */
- }
+ } catch {}
},
};
}
diff --git a/src/lib/study-music/local-prefs.ts b/src/lib/study-music/local-prefs.ts
new file mode 100644
index 00000000..46e50550
--- /dev/null
+++ b/src/lib/study-music/local-prefs.ts
@@ -0,0 +1,74 @@
+const PREFIX = "study-music-sc-";
+const KEY_FIRST_DONE = `${PREFIX}firstDownloadDone`;
+const KEY_LAST_CODEC = `${PREFIX}lastCodec`;
+const KEY_LAST_DIR = `${PREFIX}lastDownloadDir`;
+const KEY_REMEMBER = `${PREFIX}rememberDefaults`;
+
+function safeGet(key: string): string | null {
+ if (typeof window === "undefined") return null;
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function safeSet(key: string, value: string) {
+ if (typeof window === "undefined") return;
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ /* ignore quota / disabled */
+ }
+}
+
+export function getFirstDownloadDone(): boolean {
+ return safeGet(KEY_FIRST_DONE) === "1";
+}
+
+export function setFirstDownloadDone() {
+ safeSet(KEY_FIRST_DONE, "1");
+}
+
+export function getLastCodec(): string | null {
+ const v = safeGet(KEY_LAST_CODEC);
+ return v && v.trim() ? v : null;
+}
+
+export function setLastCodec(codec: string) {
+ safeSet(KEY_LAST_CODEC, codec);
+}
+
+export function getLastDownloadDir(): string | null {
+ const v = safeGet(KEY_LAST_DIR);
+ return v && v.trim() ? v : null;
+}
+
+export function setLastDownloadDir(dir: string) {
+ safeSet(KEY_LAST_DIR, dir);
+}
+
+export function getRememberDefaults(): boolean {
+ const v = safeGet(KEY_REMEMBER);
+ return v === null ? true : v === "1";
+}
+
+export function setRememberDefaults(remember: boolean) {
+ safeSet(KEY_REMEMBER, remember ? "1" : "0");
+}
+
+export type ScDownloadPrefs = {
+ firstDone: boolean;
+ lastCodec: string | null;
+ lastDir: string | null;
+ remember: boolean;
+};
+
+export function readPrefs(): ScDownloadPrefs {
+ return {
+ firstDone: getFirstDownloadDone(),
+ lastCodec: getLastCodec(),
+ lastDir: getLastDownloadDir(),
+ remember: getRememberDefaults(),
+ };
+}
diff --git a/src/lib/study-music/lyrics-store.svelte.ts b/src/lib/study-music/lyrics-store.svelte.ts
index 92e5bfde..09cc70ce 100644
--- a/src/lib/study-music/lyrics-store.svelte.ts
+++ b/src/lib/study-music/lyrics-store.svelte.ts
@@ -1,67 +1,106 @@
import { pluginInvoke } from "$lib/plugin-invoke";
-export type LyricsLine = { time: number; text: string };
+export type Syllable = { time_ms: number; text: string };
+export type LyricsLine = {
+ time_ms: number;
+ text: string;
+ syllables?: Syllable[] | null;
+};
+export type LyricsKind = "synced" | "plain" | "notfound" | "error";
+export type LyricsStatus = "idle" | "loading" | LyricsKind;
+export type TranslationStatus =
+ | "idle"
+ | "loading"
+ | "available"
+ | "skipped"
+ | "no_translator"
+ | "error";
+
+export type TranslationLine = {
+ original: string;
+ translation: string;
+ edited: boolean;
+};
+
+export type TranslationSettings = {
+ translator: "libretranslate" | "deepl" | "none";
+ libretranslate_url: string;
+ deepl_api_key_set: boolean;
+ target_lang: string;
+ show_translation: boolean;
+};
type FetchResult = {
track_id: number;
found: boolean;
- synced: string | null;
- plain: string | null;
+ kind: LyricsKind;
source: string | null;
+ lines: LyricsLine[] | null;
+ plain: string | null;
+ meta: Record<string, string> | null;
+ fetched_at: number;
cached?: boolean;
+ error?: string | null;
+ synced?: string | null;
};
-function parseTimestamp(s: string): number | null {
- const parts = s.split(":");
- if (parts.length !== 2) return null;
- const m = parseFloat(parts[0]);
- const sec = parseFloat(parts[1]);
- if (!Number.isFinite(m) || !Number.isFinite(sec)) return null;
- return m * 60 + sec;
-}
-
-export function parseLrc(lrc: string): LyricsLine[] {
- const out: LyricsLine[] = [];
- for (const line of lrc.split(/\r?\n/)) {
- let i = 0;
- const stamps: number[] = [];
- while (i < line.length && line[i] === "[") {
- const close = line.indexOf("]", i);
- if (close < 0) break;
- const inner = line.slice(i + 1, close);
- const t = parseTimestamp(inner);
- if (t === null) break;
- stamps.push(t);
- i = close + 1;
- }
- if (stamps.length === 0) continue;
- const text = line.slice(i).trim();
- for (const t of stamps) {
- out.push({ time: t, text });
- }
- }
- out.sort((a, b) => a.time - b.time);
- return out;
-}
+type TranslateResult = {
+ track_id: number;
+ target_lang: string;
+ translator: string;
+ cached: boolean;
+ skipped: boolean;
+ error?: string | null;
+ lines: Array<{
+ time_ms: number;
+ original: string;
+ translation: string;
+ edited_by_user: boolean;
+ }>;
+};
class LyricsStore {
trackId = $state<number | null>(null);
lines = $state<LyricsLine[]>([]);
plain = $state<string | null>(null);
loading = $state(false);
- notFound = $state(false);
+ status = $state<LyricsStatus>("idle");
source = $state<string | null>(null);
+ meta = $state<Record<string, string>>({});
+ error = $state<string | null>(null);
+
+ translations = $state<Map<number, TranslationLine>>(new Map());
+ translationStatus = $state<TranslationStatus>("idle");
+ translationError = $state<string | null>(null);
+ translator = $state<string | null>(null);
+ showTranslation = $state(false);
+
+ private _lastIdx = -1;
+ private _lastTranslationKey: string | null = null;
+
+ get notFound(): boolean {
+ return this.status === "notfound";
+ }
async loadFor(trackId: number, force = false) {
- if (this.trackId === trackId && !force && (this.lines.length > 0 || this.plain || this.notFound)) {
+ if (
+ this.trackId === trackId &&
+ !force &&
+ this.status !== "idle" &&
+ this.status !== "loading"
+ ) {
return;
}
this.trackId = trackId;
this.lines = [];
this.plain = null;
- this.notFound = false;
+ this.meta = {};
this.source = null;
+ this.error = null;
+ this._lastIdx = -1;
+ this._resetTranslation();
this.loading = true;
+ this.status = "loading";
try {
const res = await pluginInvoke<FetchResult>(
"study",
@@ -69,19 +108,12 @@ class LyricsStore {
{ id: trackId, force },
);
if (this.trackId !== trackId) return;
- if (!res.found) {
- this.notFound = true;
- return;
- }
- this.source = res.source;
- if (res.synced) {
- this.lines = parseLrc(res.synced);
- }
- if (res.plain) {
- this.plain = res.plain;
+ this._applyResult(res);
+ } catch (e) {
+ if (this.trackId === trackId) {
+ this.status = "error";
+ this.error = e instanceof Error ? e.message : String(e);
}
- } catch {
- this.notFound = true;
} finally {
if (this.trackId === trackId) {
this.loading = false;
@@ -89,17 +121,34 @@ class LyricsStore {
}
}
+ async setLocal(trackId: number, lrcText: string): Promise<boolean> {
+ try {
+ const res = await pluginInvoke<FetchResult>(
+ "study",
+ "study:music:lyrics:set_local",
+ { track_id: trackId, lrc_text: lrcText },
+ );
+ if (this.trackId === trackId) {
+ this._applyResult(res);
+ }
+ return true;
+ } catch (e) {
+ if (this.trackId === trackId) {
+ this.status = "error";
+ this.error = e instanceof Error ? e.message : String(e);
+ }
+ return false;
+ }
+ }
+
async clear(trackId: number) {
try {
await pluginInvoke("study", "study:music:lyrics:clear", { id: trackId });
} catch {
- /* ignore */
+ /* swallow — clear is best-effort */
}
if (this.trackId === trackId) {
- this.lines = [];
- this.plain = null;
- this.notFound = false;
- this.source = null;
+ this.reset();
}
}
@@ -107,27 +156,168 @@ class LyricsStore {
this.trackId = null;
this.lines = [];
this.plain = null;
- this.notFound = false;
+ this.meta = {};
this.source = null;
+ this.error = null;
+ this.status = "idle";
this.loading = false;
+ this._lastIdx = -1;
+ this._resetTranslation();
+ }
+
+ private _resetTranslation() {
+ this.translations = new Map();
+ this.translationStatus = "idle";
+ this.translationError = null;
+ this.translator = null;
+ this._lastTranslationKey = null;
+ }
+
+ async loadTranslation(target = "pt"): Promise<void> {
+ const trackId = this.trackId;
+ if (trackId === null) return;
+ if (this.status !== "synced" || this.lines.length === 0) {
+ this.translationStatus = "idle";
+ return;
+ }
+ const key = `${trackId}:${target}`;
+ if (this._lastTranslationKey === key && this.translationStatus === "available") {
+ return;
+ }
+ this._lastTranslationKey = key;
+ this.translationStatus = "loading";
+ this.translationError = null;
+ try {
+ const res = await pluginInvoke<TranslateResult>(
+ "study",
+ "study:music:lyrics:translate",
+ { track_id: trackId, target_lang: target },
+ );
+ if (this.trackId !== trackId) return;
+ if (res.error === "no_translator") {
+ this.translationStatus = "no_translator";
+ this.translations = new Map();
+ this.translator = null;
+ return;
+ }
+ if (res.error) {
+ this.translationStatus = "error";
+ this.translationError = res.error;
+ return;
+ }
+ if (res.skipped) {
+ this.translationStatus = "skipped";
+ this.translations = new Map();
+ this.translator = "skipped";
+ return;
+ }
+ const map = new Map<number, TranslationLine>();
+ for (let i = 0; i < res.lines.length; i++) {
+ const item = res.lines[i];
+ map.set(i, {
+ original: item.original,
+ translation: item.translation,
+ edited: item.edited_by_user,
+ });
+ }
+ this.translations = map;
+ this.translator = res.translator || null;
+ this.translationStatus = "available";
+ } catch (e) {
+ if (this.trackId === trackId) {
+ this.translationStatus = "error";
+ this.translationError = e instanceof Error ? e.message : String(e);
+ }
+ }
+ }
+
+ async setTranslationLine(idx: number, text: string): Promise<boolean> {
+ const trackId = this.trackId;
+ if (trackId === null) return false;
+ const existing = this.translations.get(idx);
+ const original = existing?.original ?? this.lines[idx]?.text ?? "";
+ try {
+ await pluginInvoke("study", "study:music:lyrics:set_translation_line", {
+ track_id: trackId,
+ line_idx: idx,
+ text,
+ });
+ const map = new Map(this.translations);
+ map.set(idx, { original, translation: text, edited: true });
+ this.translations = map;
+ return true;
+ } catch (e) {
+ this.translationError = e instanceof Error ? e.message : String(e);
+ return false;
+ }
+ }
+
+ toggleTranslation(target = "pt"): void {
+ this.showTranslation = !this.showTranslation;
+ if (this.showTranslation) {
+ void this.loadTranslation(target);
+ }
}
activeIndex(currentTime: number): number {
- if (this.lines.length === 0) return -1;
+ const lines = this.lines;
+ if (lines.length === 0) return -1;
+ const targetMs = currentTime * 1000;
+ const last = this._lastIdx;
+ if (last >= 0 && last < lines.length) {
+ const at = lines[last].time_ms;
+ const next = last + 1 < lines.length ? lines[last + 1].time_ms : Infinity;
+ if (at <= targetMs && targetMs < next) {
+ return last;
+ }
+ if (last + 1 < lines.length && lines[last + 1].time_ms <= targetMs) {
+ const nextNext =
+ last + 2 < lines.length ? lines[last + 2].time_ms : Infinity;
+ if (targetMs < nextNext) {
+ this._lastIdx = last + 1;
+ return last + 1;
+ }
+ }
+ }
let lo = 0;
- let hi = this.lines.length - 1;
+ let hi = lines.length - 1;
let result = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
- if (this.lines[mid].time <= currentTime) {
+ if (lines[mid].time_ms <= targetMs) {
result = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
+ this._lastIdx = result;
return result;
}
+
+ private _applyResult(res: FetchResult) {
+ this.source = res.source;
+ this.meta = res.meta ?? {};
+ this.error = res.error ?? null;
+ if (res.kind === "synced" && Array.isArray(res.lines) && res.lines.length > 0) {
+ this.lines = res.lines;
+ this.plain = res.plain;
+ this.status = "synced";
+ } else if (res.kind === "plain" && res.plain) {
+ this.lines = [];
+ this.plain = res.plain;
+ this.status = "plain";
+ } else if (res.kind === "error") {
+ this.lines = [];
+ this.plain = null;
+ this.status = "error";
+ } else {
+ this.lines = [];
+ this.plain = null;
+ this.status = "notfound";
+ }
+ this._lastIdx = -1;
+ }
}
export const lyricsStore = new LyricsStore();
diff --git a/src/lib/study-music/player-store.svelte.ts b/src/lib/study-music/player-store.svelte.ts
index 6474fa23..d523adbd 100644
--- a/src/lib/study-music/player-store.svelte.ts
+++ b/src/lib/study-music/player-store.svelte.ts
@@ -1,6 +1,6 @@
import { convertFileSrc } from "@tauri-apps/api/core";
import { pluginInvoke } from "$lib/plugin-invoke";
-import { dominantColorFromPath, type RGB } from "./dominant-color";
+import { dominantColorFromPath, palettePathOrUrl, type RGB } from "./dominant-color";
import { spotifySdk, type SpotifySdkState } from "./spotify-sdk.svelte";
import { attachHls, type HlsHandle } from "./hls-loader.svelte";
@@ -39,6 +39,136 @@ export type MusicTrack = {
export type RepeatMode = "off" | "all" | "one";
+export type PlayerStatus = "idle" | "resolving" | "playing" | "paused" | "error";
+
+export type PlayerErrorKind =
+ | "network"
+ | "auth_expired"
+ | "track_unavailable"
+ | "region_blocked"
+ | "unsupported_format"
+ | "format_unavailable"
+ | "unknown";
+
+export type PlayerErrorAction = "retry" | "refresh" | "skip";
+
+export type PlayerError = {
+ kind: PlayerErrorKind;
+ message: string;
+ source: TrackSource;
+ trackId: number;
+ retriable: boolean;
+ primaryAction: PlayerErrorAction;
+};
+
+const TERMINAL_KINDS: ReadonlySet<PlayerErrorKind> = new Set([
+ "track_unavailable",
+ "region_blocked",
+ "unsupported_format",
+ "format_unavailable",
+]);
+
+function classifyPlayerError(
+ raw: unknown,
+ source: TrackSource,
+ trackId: number,
+ hint?: { audioCode?: number },
+): PlayerError {
+ const baseMsg = raw instanceof Error
+ ? raw.message
+ : typeof raw === "string"
+ ? raw
+ : raw == null
+ ? ""
+ : String(raw);
+ const lower = baseMsg.toLowerCase();
+ let kind: PlayerErrorKind = "unknown";
+
+ if (hint?.audioCode === 4) {
+ kind = "unsupported_format";
+ } else if (hint?.audioCode === 2) {
+ kind = "network";
+ } else if (lower.includes("region") || lower.includes("country") || lower.includes("geographic")) {
+ kind = "region_blocked";
+ } else if (
+ lower.includes("removed") ||
+ lower.includes("private") ||
+ lower.includes("video not found") ||
+ lower.includes("track not found")
+ ) {
+ kind = "track_unavailable";
+ } else if (
+ lower.includes("requested format is not available") ||
+ lower.includes("requested format") ||
+ lower.includes("no audio formats") ||
+ lower.includes("no formats found") ||
+ lower.includes("sign in to confirm") ||
+ lower.includes("sign in") ||
+ lower.includes("potoken") ||
+ lower.includes("unplayable") ||
+ lower.includes("playabilitystatus") ||
+ lower.includes("video unavailable") ||
+ lower.includes("not available") ||
+ lower.includes("unavailable")
+ ) {
+ kind = "format_unavailable";
+ } else if (
+ lower.includes("401") ||
+ lower.includes("403") ||
+ lower.includes("unauthorized") ||
+ lower.includes("forbidden") ||
+ lower.includes("expired") ||
+ lower.includes("token") ||
+ lower.includes("login")
+ ) {
+ kind = "auth_expired";
+ } else if (
+ lower.includes("cipher") ||
+ lower.includes("no audio with direct url") ||
+ lower.includes("formato") ||
+ lower.includes("decod")
+ ) {
+ kind = "unsupported_format";
+ } else if (
+ lower.includes("network") ||
+ lower.includes("fetch") ||
+ lower.includes("timeout") ||
+ lower.includes("connection") ||
+ lower.includes("connect") ||
+ lower.includes("dns") ||
+ lower.includes("reset") ||
+ lower.includes("rede")
+ ) {
+ kind = "network";
+ } else if (/\b5\d{2}\b/.test(lower)) {
+ kind = "network";
+ } else if (/\b4\d{2}\b/.test(lower)) {
+ kind = "track_unavailable";
+ }
+
+ const terminal = TERMINAL_KINDS.has(kind);
+ const retriable = !terminal;
+ let primaryAction: PlayerErrorAction = "skip";
+ if (kind === "auth_expired") primaryAction = "refresh";
+ else if (retriable) primaryAction = "retry";
+
+ console.info("[player] classify error", {
+ kind,
+ source,
+ trackId,
+ snippet: baseMsg.slice(0, 200),
+ });
+
+ return {
+ kind,
+ message: baseMsg,
+ source,
+ trackId,
+ retriable,
+ primaryAction,
+ };
+}
+
export type EqPreset =
| "flat"
| "bass"
@@ -67,6 +197,49 @@ export const EQ_PRESETS: Record<EqPreset, number[]> = {
const PERSIST_KEY = "study.music.player.v1";
const QUEUE_KEY = "study.music.queue.v1";
+type YoutubePlayerLike = {
+ formats: Array<{
+ url: string | null;
+ mime_type: string;
+ bitrate: number;
+ audio_quality: string | null;
+ width?: number | null;
+ height?: number | null;
+ }>;
+ adaptive_formats: Array<{
+ url: string | null;
+ mime_type: string;
+ bitrate: number;
+ audio_quality: string | null;
+ width?: number | null;
+ height?: number | null;
+ }>;
+};
+
+function pickBestYoutubeAudio(res: YoutubePlayerLike): string | null {
+ const audioOnly = res.adaptive_formats.filter(
+ (f) => f.url && f.mime_type.startsWith("audio/"),
+ );
+ audioOnly.sort((a, b) => (b.bitrate ?? 0) - (a.bitrate ?? 0));
+ if (audioOnly[0]?.url) return audioOnly[0].url;
+ const muxed = res.formats.filter((f) => f.url);
+ muxed.sort((a, b) => (b.bitrate ?? 0) - (a.bitrate ?? 0));
+ return muxed[0]?.url ?? null;
+}
+
+export function pickBestYoutubeVideo(res: YoutubePlayerLike): string | null {
+ const muxed = res.formats.filter(
+ (f) => f.url && f.mime_type.startsWith("video/"),
+ );
+ muxed.sort((a, b) => {
+ const heightDelta = (b.height ?? 0) - (a.height ?? 0);
+ if (heightDelta !== 0) return heightDelta;
+ return (b.bitrate ?? 0) - (a.bitrate ?? 0);
+ });
+ const capped = muxed.find((f) => (f.height ?? 0) <= 720 && (f.height ?? 0) > 0);
+ return capped?.url ?? muxed[0]?.url ?? null;
+}
+
class MusicPlayerStore {
private audio: HTMLAudioElement | null = null;
private playStartedAt = 0;
@@ -77,6 +250,35 @@ class MusicPlayerStore {
private eqSource: MediaElementAudioSourceNode | null = null;
private eqFilters: BiquadFilterNode[] = [];
private eqGainNode: GainNode | null = null;
+ private youtubeRefreshTimer: ReturnType<typeof setTimeout> | null = null;
+ private youtubeCurrentVideoId: string | null = null;
+ private historyRecorded: Set<string> = new Set();
+ private youtubeRefreshFailureCount: number = 0;
+ private static YOUTUBE_REFRESH_MAX_FAILURES = 3;
+ private static YOUTUBE_REFRESH_RETRY_DELAY_SECS = 30;
+
+ private _spotifyLastKnownPositionMs = 0;
+ private _spotifyLastEventAt = 0;
+ private _spotifyIsPlaying = false;
+ private _spotifyPlaybackRate = 1;
+ private _spotifyRafHandle: number | null = null;
+ private _spotifyHeartbeatHandle: ReturnType<typeof setInterval> | null = null;
+ private _spotifyHeartbeatEnabled = true;
+ private _spotifyHeartbeatMs = 30_000;
+ private _spotifyVisibilityListener: (() => void) | null = null;
+ private _spotifySettingsLoaded = false;
+ private static SPOTIFY_SYNC_THRESHOLD_MS = 250;
+ private static SPOTIFY_HEARTBEAT_MIN_MS = 5_000;
+ private static SPOTIFY_HEARTBEAT_MAX_MS = 300_000;
+
+ private _rpcShowCover = true;
+ private _rpcShowButtons = true;
+ private _rpcUpdateIntervalMs = 5_000;
+ private _rpcTimer: ReturnType<typeof setInterval> | null = null;
+ private _rpcSettingsLoaded = false;
+ private static RPC_UPDATE_INTERVAL_MIN_MS = 2_000;
+ private static RPC_UPDATE_INTERVAL_MAX_MS = 30_000;
+ private static RPC_UPDATE_INTERVAL_DEFAULT_MS = 5_000;
currentTrack = $state<MusicTrack | null>(null);
queue = $state<MusicTrack[]>([]);
@@ -91,10 +293,19 @@ class MusicPlayerStore {
ready = $state(false);
loading = $state(false);
error = $state<string | null>(null);
+ status = $state<PlayerStatus>("idle");
+ lastError = $state<PlayerError | null>(null);
+ autoSkipOnError = $state(false);
+ private playerSettingsLoaded = false;
eqEnabled = $state(false);
eqGains = $state<number[]>([0, 0, 0, 0, 0]);
eqPreset = $state<EqPreset>("flat");
dominantColor = $state<RGB | null>(null);
+ palette = $state<RGB[] | null>(null);
+ private paletteRefreshToken = 0;
+ youtubeVideoUrl = $state<string | null>(null);
+ youtubeChapters = $state<import("$lib/study-bridge").YoutubeChapter[]>([]);
+ youtubeSponsorBlockSegments = $state<import("$lib/study-bridge").SponsorBlockSegment[]>([]);
private mediaSessionInstalled = false;
init() {
@@ -105,13 +316,16 @@ class MusicPlayerStore {
audio.addEventListener("play", () => {
this.paused = false;
+ this.status = "playing";
this.playStartedAt = Date.now();
if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
navigator.mediaSession.playbackState = "playing";
}
+ this.rpcOnPlaybackChange();
});
audio.addEventListener("pause", () => {
this.paused = true;
+ if (this.status !== "error") this.status = "paused";
if (this.playStartedAt > 0) {
this.accumulatedPlayedMs += Date.now() - this.playStartedAt;
this.playStartedAt = 0;
@@ -120,6 +334,7 @@ class MusicPlayerStore {
if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
navigator.mediaSession.playbackState = "paused";
}
+ this.rpcOnPlaybackChange();
});
audio.addEventListener("timeupdate", () => {
this.currentTime = audio.currentTime;
@@ -145,7 +360,9 @@ class MusicPlayerStore {
audio.addEventListener("error", () => {
const err = audio.error;
let msg = "Erro ao carregar áudio";
+ let code: number | undefined;
if (err) {
+ code = err.code;
const codeMap: Record<number, string> = {
1: "abortado",
2: "rede falhou",
@@ -153,13 +370,20 @@ class MusicPlayerStore {
4: "formato não suportado",
};
const reason = codeMap[err.code] ?? `code ${err.code}`;
- msg = `Erro de áudio: ${reason}${err.message ? ` (${err.message})` : ""}`;
+ msg = `${reason}${err.message ? ` (${err.message})` : ""}`;
console.error(
"[player] audio error",
- { code: err.code, message: err.message, src: audio.src.slice(0, 200) },
+ { code: err.code, src: audio.src.slice(0, 80) },
+ );
+ }
+ const track = this.currentTrack;
+ if (track) {
+ this.setError(
+ classifyPlayerError(msg, track.source ?? "local", track.id, { audioCode: code }),
);
+ } else {
+ this.error = msg;
}
- this.error = msg;
this.loading = false;
});
audio.addEventListener("volumechange", () => {
@@ -207,30 +431,167 @@ class MusicPlayerStore {
this.installMediaSession();
this.restoreQueue();
this.installSpotifySync();
+ void this.loadPlayerSettings();
+ void this.loadSpotifySettings();
+ void this.loadRpcSettings();
+ if (this.queue.some((t) => t.source === "spotify" && t.spotify_uri)) {
+ void spotifySdk.ensureLoaded().catch(() => {
+ /* prewarm best-effort */
+ });
+ }
+ }
+
+ private async loadPlayerSettings() {
+ if (this.playerSettingsLoaded) return;
+ this.playerSettingsLoaded = true;
+ try {
+ const res = await pluginInvoke<{
+ auto_skip_on_error?: boolean;
+ }>("study", "study:music:player:settings:get", {});
+ this.autoSkipOnError = !!res?.auto_skip_on_error;
+ } catch (e) {
+ console.warn("[player] failed loading player settings", e);
+ }
+ }
+
+ async setAutoSkipOnError(value: boolean) {
+ this.autoSkipOnError = value;
+ try {
+ await pluginInvoke("study", "study:music:player:settings:set", {
+ auto_skip_on_error: value,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving auto_skip_on_error", e);
+ }
+ }
+
+ private setError(err: PlayerError) {
+ this.lastError = err;
+ this.error = err.message || null;
+ this.status = "error";
+ this.loading = false;
+ if (this.autoSkipOnError && !err.retriable) {
+ const skipDelay = 300;
+ setTimeout(() => {
+ if (this.lastError && this.lastError.trackId === err.trackId) {
+ this.skipOnError();
+ }
+ }, skipDelay);
+ }
+ }
+
+ clearError() {
+ this.lastError = null;
+ this.error = null;
+ if (this.status === "error") {
+ this.status = this.paused ? "paused" : "idle";
+ }
+ }
+
+ retry() {
+ const track = this.currentTrack;
+ if (!track) return;
+ this.clearError();
+ void this.play(track, this.queue.length > 0 ? this.queue : undefined);
+ }
+
+ async refreshAndRetry() {
+ const track = this.currentTrack;
+ if (!track) return;
+ this.clearError();
+ this.status = "resolving";
+ this.loading = true;
+ if (track.source === "youtube" && track.youtube_video_id) {
+ try {
+ await pluginInvoke("study", "study:music:track:refresh_url", {
+ source: "youtube_music",
+ external_id: track.youtube_video_id,
+ });
+ } catch (e) {
+ console.warn("[player] refresh_url failed", e);
+ }
+ }
+ void this.play(track, this.queue.length > 0 ? this.queue : undefined);
+ }
+
+ skipOnError() {
+ this.clearError();
+ this.next();
}
private spotifyUnsub: (() => void) | null = null;
private installSpotifySync() {
if (this.spotifyUnsub) return;
this.spotifyUnsub = spotifySdk.onState((state) => this.applySpotifyState(state));
+ if (typeof document !== "undefined" && !this._spotifyVisibilityListener) {
+ const listener = () => {
+ if (document.visibilityState === "visible" && this.isSpotify()) {
+ void this.spotifyResyncFromSdk();
+ }
+ };
+ this._spotifyVisibilityListener = listener;
+ document.addEventListener("visibilitychange", listener);
+ }
}
private applySpotifyState(state: SpotifySdkState | null) {
if (this.currentTrack?.source !== "spotify") return;
if (!state) return;
+
+ const sdkUri = state.track_window?.current_track?.uri;
+ const isTrackChange =
+ !!sdkUri &&
+ !!this.currentTrack.spotify_uri &&
+ sdkUri !== this.currentTrack.spotify_uri;
+
+ const extrapolatedMs = this._spotifyIsPlaying
+ ? this._spotifyLastKnownPositionMs +
+ (performance.now() - this._spotifyLastEventAt) * this._spotifyPlaybackRate
+ : this._spotifyLastKnownPositionMs;
+ const drift = Math.abs(state.position - extrapolatedMs);
+ const shouldSync =
+ isTrackChange ||
+ drift > MusicPlayerStore.SPOTIFY_SYNC_THRESHOLD_MS ||
+ this._spotifyIsPlaying === state.paused;
+
+ this._spotifyLastKnownPositionMs = state.position;
+ this._spotifyLastEventAt = performance.now();
+ const stateRate = (state as unknown as { playback_rate?: number }).playback_rate;
+ this._spotifyPlaybackRate =
+ typeof stateRate === "number" && stateRate > 0 ? stateRate : 1;
+ const wasPlaying = this._spotifyIsPlaying;
+ this._spotifyIsPlaying = !state.paused;
+
this.paused = state.paused;
- this.currentTime = state.position / 1000;
- this.duration = (state.duration || this.currentTrack.duration_ms || 0) / 1000;
+ if (state.paused) {
+ if (this.status !== "error") this.status = "paused";
+ } else {
+ this.status = "playing";
+ }
+ if (state.duration) {
+ this.duration = state.duration / 1000;
+ } else if (this.currentTrack.duration_ms) {
+ this.duration = this.currentTrack.duration_ms / 1000;
+ }
this.ready = true;
this.loading = false;
- this.updateMediaSessionPosition();
- const sdkUri = state.track_window?.current_track?.uri;
- if (
- sdkUri &&
- this.currentTrack.spotify_uri &&
- sdkUri !== this.currentTrack.spotify_uri
- ) {
+ if (shouldSync) {
+ const clamped =
+ this.duration > 0
+ ? Math.min(state.position / 1000, this.duration)
+ : state.position / 1000;
+ this.currentTime = clamped;
+ this.updateMediaSessionPosition();
+ }
+
+ if (this._spotifyIsPlaying && (!wasPlaying || !this._spotifyRafHandle)) {
+ this.ensureSpotifyTick();
+ } else if (!this._spotifyIsPlaying && wasPlaying) {
+ this.stopSpotifyTick();
+ }
+
+ if (isTrackChange) {
const inQueue = this.queue.find((t) => t.spotify_uri === sdkUri);
if (inQueue) {
this.currentTrack = inQueue;
@@ -238,6 +599,350 @@ class MusicPlayerStore {
this.updateMediaSessionMetadata(inQueue);
}
}
+
+ this.rpcOnPlaybackChange();
+ }
+
+ private ensureSpotifyTick() {
+ if (typeof window === "undefined") return;
+ if (!this.isSpotify()) return;
+ if (!this._spotifyIsPlaying) return;
+ if (this._spotifyRafHandle != null) return;
+ const tick = () => {
+ if (!this.isSpotify() || !this._spotifyIsPlaying) {
+ this._spotifyRafHandle = null;
+ return;
+ }
+ const elapsed = performance.now() - this._spotifyLastEventAt;
+ const positionMs =
+ this._spotifyLastKnownPositionMs + elapsed * this._spotifyPlaybackRate;
+ const seconds = positionMs / 1000;
+ if (this.duration > 0 && seconds >= this.duration) {
+ this.currentTime = this.duration;
+ } else if (seconds >= 0) {
+ this.currentTime = seconds;
+ }
+ this.updateMediaSessionPosition();
+ this._spotifyRafHandle = window.requestAnimationFrame(tick);
+ };
+ this._spotifyRafHandle = window.requestAnimationFrame(tick);
+ }
+
+ private stopSpotifyTick() {
+ if (this._spotifyRafHandle != null && typeof window !== "undefined") {
+ window.cancelAnimationFrame(this._spotifyRafHandle);
+ }
+ this._spotifyRafHandle = null;
+ }
+
+ private startSpotifyHeartbeat() {
+ if (this._spotifyHeartbeatHandle) return;
+ if (!this._spotifyHeartbeatEnabled) return;
+ if (typeof window === "undefined") return;
+ const intervalMs = Math.min(
+ MusicPlayerStore.SPOTIFY_HEARTBEAT_MAX_MS,
+ Math.max(MusicPlayerStore.SPOTIFY_HEARTBEAT_MIN_MS, this._spotifyHeartbeatMs),
+ );
+ this._spotifyHeartbeatHandle = setInterval(() => {
+ if (!this.isSpotify()) return;
+ void this.spotifyResyncFromSdk();
+ }, intervalMs);
+ }
+
+ private stopSpotifyHeartbeat() {
+ if (this._spotifyHeartbeatHandle) {
+ clearInterval(this._spotifyHeartbeatHandle);
+ this._spotifyHeartbeatHandle = null;
+ }
+ }
+
+ private async spotifyResyncFromSdk() {
+ try {
+ const state = await spotifySdk.getCurrentState();
+ if (state) this.applySpotifyState(state);
+ } catch (e) {
+ console.warn("[player] spotify heartbeat resync failed", e);
+ }
+ }
+
+ private async loadSpotifySettings() {
+ if (this._spotifySettingsLoaded) return;
+ this._spotifySettingsLoaded = true;
+ try {
+ const res = await pluginInvoke<{
+ heartbeat_enabled?: boolean;
+ heartbeat_interval_ms?: number;
+ }>("study", "study:music:spotify:settings:get", {});
+ this._spotifyHeartbeatEnabled = res?.heartbeat_enabled ?? true;
+ const ms = Number(res?.heartbeat_interval_ms ?? 30_000);
+ this._spotifyHeartbeatMs = Number.isFinite(ms)
+ ? Math.min(
+ MusicPlayerStore.SPOTIFY_HEARTBEAT_MAX_MS,
+ Math.max(MusicPlayerStore.SPOTIFY_HEARTBEAT_MIN_MS, ms),
+ )
+ : 30_000;
+ } catch (e) {
+ console.warn("[player] failed loading spotify settings", e);
+ }
+ }
+
+ async setSpotifyHeartbeatEnabled(value: boolean) {
+ this._spotifyHeartbeatEnabled = value;
+ try {
+ await pluginInvoke("study", "study:music:spotify:settings:set", {
+ heartbeat_enabled: value,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving spotify heartbeat_enabled", e);
+ }
+ if (value && this.isSpotify() && this._spotifyIsPlaying) {
+ this.startSpotifyHeartbeat();
+ } else if (!value) {
+ this.stopSpotifyHeartbeat();
+ }
+ }
+
+ async setSpotifyHeartbeatIntervalMs(ms: number) {
+ const clamped = Math.min(
+ MusicPlayerStore.SPOTIFY_HEARTBEAT_MAX_MS,
+ Math.max(
+ MusicPlayerStore.SPOTIFY_HEARTBEAT_MIN_MS,
+ Math.floor(Number(ms) || 30_000),
+ ),
+ );
+ this._spotifyHeartbeatMs = clamped;
+ try {
+ await pluginInvoke("study", "study:music:spotify:settings:set", {
+ heartbeat_interval_ms: clamped,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving spotify heartbeat_interval_ms", e);
+ }
+ if (this._spotifyHeartbeatHandle) {
+ this.stopSpotifyHeartbeat();
+ if (this.isSpotify() && this._spotifyIsPlaying) this.startSpotifyHeartbeat();
+ }
+ }
+
+ getSpotifyHeartbeatEnabled(): boolean {
+ return this._spotifyHeartbeatEnabled;
+ }
+
+ getSpotifyHeartbeatIntervalMs(): number {
+ return this._spotifyHeartbeatMs;
+ }
+
+ private static clampRpcInterval(ms: number): number {
+ return Math.min(
+ MusicPlayerStore.RPC_UPDATE_INTERVAL_MAX_MS,
+ Math.max(
+ MusicPlayerStore.RPC_UPDATE_INTERVAL_MIN_MS,
+ Math.floor(Number(ms) || MusicPlayerStore.RPC_UPDATE_INTERVAL_DEFAULT_MS),
+ ),
+ );
+ }
+
+ private async loadRpcSettings() {
+ if (this._rpcSettingsLoaded) return;
+ this._rpcSettingsLoaded = true;
+ try {
+ const res = await pluginInvoke<{
+ show_cover?: boolean;
+ show_buttons?: boolean;
+ update_interval_ms?: number;
+ }>("study", "study:music:rpc:music_settings:get", {});
+ if (typeof res?.show_cover === "boolean") this._rpcShowCover = res.show_cover;
+ if (typeof res?.show_buttons === "boolean") this._rpcShowButtons = res.show_buttons;
+ if (typeof res?.update_interval_ms === "number") {
+ this._rpcUpdateIntervalMs = MusicPlayerStore.clampRpcInterval(
+ res.update_interval_ms,
+ );
+ }
+ } catch (e) {
+ console.warn("[player] failed loading rpc music_settings", e);
+ }
+ }
+
+ getRpcShowCover(): boolean {
+ return this._rpcShowCover;
+ }
+
+ getRpcShowButtons(): boolean {
+ return this._rpcShowButtons;
+ }
+
+ getRpcUpdateIntervalMs(): number {
+ return this._rpcUpdateIntervalMs;
+ }
+
+ async setRpcShowCover(value: boolean) {
+ this._rpcShowCover = value;
+ try {
+ await pluginInvoke("study", "study:music:rpc:music_settings:set", {
+ show_cover: value,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving rpc show_cover", e);
+ }
+ this.rpcOnPlaybackChange();
+ }
+
+ async setRpcShowButtons(value: boolean) {
+ this._rpcShowButtons = value;
+ try {
+ await pluginInvoke("study", "study:music:rpc:music_settings:set", {
+ show_buttons: value,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving rpc show_buttons", e);
+ }
+ this.rpcOnPlaybackChange();
+ }
+
+ async setRpcUpdateIntervalMs(ms: number) {
+ const clamped = MusicPlayerStore.clampRpcInterval(ms);
+ this._rpcUpdateIntervalMs = clamped;
+ try {
+ await pluginInvoke("study", "study:music:rpc:music_settings:set", {
+ update_interval_ms: clamped,
+ });
+ } catch (e) {
+ console.warn("[player] failed saving rpc update_interval_ms", e);
+ }
+ if (this._rpcTimer !== null) {
+ this.stopRpcLoop();
+ this.startRpcLoop();
+ }
+ }
+
+ private rpcSnapshot(): {
+ title: string;
+ artist: string;
+ album: string;
+ duration: number;
+ position: number;
+ paused: boolean;
+ large_image_key: string | null;
+ large_image_text: string | null;
+ small_image_key: string | null;
+ small_image_text: string | null;
+ primary_button_url: string | null;
+ } | null {
+ const track = this.currentTrack;
+ if (!track) return null;
+ const source: TrackSource = track.source ?? "local";
+ const title = (track.title ?? "").trim() || "Música";
+ const artist = (track.artist ?? "").trim();
+ const album = (track.album ?? "").trim();
+ const duration = Math.max(
+ 0,
+ Math.floor((track.duration_ms ?? this.duration * 1000) / 1000),
+ );
+ const position = Math.max(0, Math.floor(this.currentTime || 0));
+ const paused = this.paused;
+
+ let coverUrl: string | null = null;
+ if (this._rpcShowCover) {
+ if (source === "spotify" && track.spotify_cover_url) {
+ coverUrl = track.spotify_cover_url;
+ } else if (source === "youtube" && track.youtube_thumbnail) {
+ coverUrl = track.youtube_thumbnail;
+ } else if (source === "soundcloud" && track.soundcloud_artwork_url) {
+ coverUrl = track.soundcloud_artwork_url;
+ }
+ }
+
+ let primaryButtonUrl: string | null = null;
+ if (source === "youtube") {
+ if (track.youtube_url) primaryButtonUrl = track.youtube_url;
+ else if (track.youtube_video_id) {
+ primaryButtonUrl = `https://www.youtube.com/watch?v=${track.youtube_video_id}`;
+ }
+ } else if (source === "spotify" && track.spotify_uri) {
+ const m = /^spotify:track:([A-Za-z0-9]+)/.exec(track.spotify_uri);
+ if (m) primaryButtonUrl = `https://open.spotify.com/track/${m[1]}`;
+ }
+
+ const smallImageKey =
+ source === "youtube"
+ ? "yt_logo"
+ : source === "spotify"
+ ? "spotify_logo"
+ : source === "soundcloud"
+ ? "soundcloud_logo"
+ : null;
+ const smallImageText =
+ source === "youtube"
+ ? "YouTube"
+ : source === "spotify"
+ ? "Spotify"
+ : source === "soundcloud"
+ ? "SoundCloud"
+ : source === "local"
+ ? "Biblioteca local"
+ : null;
+
+ return {
+ title,
+ artist,
+ album,
+ duration,
+ position,
+ paused,
+ large_image_key: coverUrl,
+ large_image_text: artist || "omniget · study",
+ small_image_key: smallImageKey,
+ small_image_text: smallImageText,
+ primary_button_url: primaryButtonUrl,
+ };
+ }
+
+ private async fireRpcUpdate() {
+ const snap = this.rpcSnapshot();
+ if (!snap) return;
+ try {
+ await pluginInvoke("study", "study:music:rpc:set", snap);
+ } catch {
+ /* ignore — discord may be offline */
+ }
+ }
+
+ private startRpcLoop() {
+ if (typeof window === "undefined") return;
+ this.stopRpcLoop();
+ this._rpcTimer = setInterval(() => {
+ void this.fireRpcUpdate();
+ }, this._rpcUpdateIntervalMs);
+ }
+
+ private stopRpcLoop() {
+ if (this._rpcTimer !== null) {
+ clearInterval(this._rpcTimer);
+ this._rpcTimer = null;
+ }
+ }
+
+ private rpcOnPlaybackChange() {
+ if (!this.currentTrack) {
+ this.stopRpcLoop();
+ void pluginInvoke("study", "study:music:rpc:clear", {}).catch(() => {});
+ return;
+ }
+ void this.fireRpcUpdate();
+ if (this.paused) {
+ this.stopRpcLoop();
+ } else {
+ this.startRpcLoop();
+ }
+ }
+
+ private async fireRpcClear() {
+ this.stopRpcLoop();
+ try {
+ await pluginInvoke("study", "study:music:rpc:clear", {});
+ } catch {
+ /* ignore */
+ }
}
private isSpotify(): boolean {
@@ -325,13 +1030,40 @@ class MusicPlayerStore {
}
private async refreshDominantColor(track: MusicTrack | null) {
- if (!track || !track.cover_path) {
+ if (!track) {
+ this.dominantColor = null;
+ this.palette = null;
+ return;
+ }
+ const source =
+ track.cover_path ??
+ (track as { spotify_cover_url?: string | null }).spotify_cover_url ??
+ (track as { youtube_thumbnail?: string | null }).youtube_thumbnail ??
+ null;
+ if (!source) {
this.dominantColor = null;
+ this.palette = null;
return;
}
- const c = await dominantColorFromPath(track.cover_path);
- if (this.currentTrack?.id === track.id) {
- this.dominantColor = c;
+ const token = ++this.paletteRefreshToken;
+ const trackId = track.id;
+ const [single, palette] = await Promise.all([
+ track.cover_path
+ ? dominantColorFromPath(track.cover_path)
+ : Promise.resolve<RGB | null>(null),
+ palettePathOrUrl(source),
+ ]);
+ if (token !== this.paletteRefreshToken) return;
+ if (this.currentTrack?.id !== trackId) return;
+ if (palette && palette.length > 0) {
+ this.palette = palette;
+ this.dominantColor = single ?? palette[0];
+ } else if (single) {
+ this.palette = [single];
+ this.dominantColor = single;
+ } else {
+ this.palette = null;
+ this.dominantColor = null;
}
}
@@ -516,6 +1248,9 @@ class MusicPlayerStore {
this.currentTrack = track;
this.error = null;
+ this.lastError = null;
+ this.status = "resolving";
+ this.loading = true;
this.ready = false;
this.currentTime = 0;
this.duration = (track.duration_ms ?? 0) / 1000;
@@ -523,6 +1258,28 @@ class MusicPlayerStore {
this.playStartedAt = 0;
this.lastReportTrackId = track.source === "spotify" ? null : track.id;
+ if (track.source !== "youtube") {
+ this.cancelYoutubeRefresh();
+ this.youtubeCurrentVideoId = null;
+ this.youtubeVideoUrl = null;
+ this.youtubeChapters = [];
+ this.youtubeSponsorBlockSegments = [];
+ }
+
+ if (track.source !== "spotify") {
+ this.stopSpotifyTick();
+ this.stopSpotifyHeartbeat();
+ this._spotifyIsPlaying = false;
+ this._spotifyLastKnownPositionMs = 0;
+ this._spotifyLastEventAt = 0;
+ this._spotifyPlaybackRate = 1;
+ } else {
+ this._spotifyLastKnownPositionMs = 0;
+ this._spotifyLastEventAt = performance.now();
+ this._spotifyPlaybackRate = 1;
+ this._spotifyIsPlaying = false;
+ }
+
if (track.source === "spotify") {
await this.playSpotify(track);
} else if (track.source === "youtube") {
@@ -532,6 +1289,46 @@ class MusicPlayerStore {
} else {
await this.playLocal(track);
}
+
+ this.recordHistory(track);
+ }
+
+ private recordHistory(track: MusicTrack) {
+ const source = track.source ?? "local";
+ const externalId =
+ source === "youtube"
+ ? track.youtube_video_id ?? null
+ : source === "spotify"
+ ? track.spotify_uri ?? null
+ : source === "soundcloud"
+ ? track.path
+ : null;
+ const dedupeKey = `${source}|${externalId ?? track.id}`;
+ if (this.historyRecorded.has(dedupeKey)) return;
+ this.historyRecorded.add(dedupeKey);
+
+ const coverUrl =
+ track.spotify_cover_url ??
+ track.youtube_thumbnail ??
+ track.soundcloud_artwork_url ??
+ undefined;
+
+ void import("$lib/study-bridge")
+ .then((mod) =>
+ mod.studyMusicHistoryAdd({
+ source: source as "local" | "spotify" | "youtube" | "soundcloud",
+ title: track.title ?? "Música",
+ externalId: externalId ?? undefined,
+ trackId: track.id,
+ artist: track.artist ?? undefined,
+ album: track.album ?? undefined,
+ coverUrl,
+ durationMs: track.duration_ms ?? undefined,
+ }),
+ )
+ .catch(() => {
+ /* fire-and-forget */
+ });
}
soundcloudResolver:
@@ -539,27 +1336,45 @@ class MusicPlayerStore {
| null = null;
private hlsHandle: HlsHandle | null = null;
- private async playSoundcloud(track: MusicTrack) {
- if (!this.audio) return;
- if (!this.soundcloudResolver) {
- this.error = "SoundCloud resolver não configurado";
- return;
- }
- this.loading = true;
+ private async stopCurrentPlayback(opts?: { keepSpotify?: boolean }) {
try {
+ this.audio?.pause();
+ } catch {
+ /* ignore */
+ }
+ if (!opts?.keepSpotify) {
try {
await spotifySdk.pause();
} catch {
/* ignore */
}
- if (this.hlsHandle) {
- try {
- this.hlsHandle.destroy();
- } catch {
- /* ignore */
- }
- this.hlsHandle = null;
+ }
+ if (this.hlsHandle) {
+ try {
+ this.hlsHandle.destroy();
+ } catch {
+ /* ignore */
}
+ this.hlsHandle = null;
+ }
+ this.cancelYoutubeRefresh();
+ }
+
+ private async playSoundcloud(track: MusicTrack) {
+ if (!this.audio) return;
+ if (!this.soundcloudResolver) {
+ this.setError(
+ classifyPlayerError(
+ "soundcloud resolver não configurado",
+ "soundcloud",
+ track.id,
+ ),
+ );
+ return;
+ }
+ this.loading = true;
+ await this.stopCurrentPlayback();
+ try {
const { url, is_hls } = await this.soundcloudResolver(track);
if (is_hls || url.includes(".m3u8")) {
this.hlsHandle = await attachHls(this.audio, url);
@@ -571,8 +1386,7 @@ class MusicPlayerStore {
this.saveQueueNow();
this.updateMediaSessionMetadata(track);
} catch (e) {
- this.error = e instanceof Error ? e.message : "Erro ao tocar SoundCloud";
- this.loading = false;
+ this.setError(classifyPlayerError(e, "soundcloud", track.id));
throw e;
}
}
@@ -581,19 +1395,25 @@ class MusicPlayerStore {
if (!this.audio) return;
const videoId = track.youtube_video_id;
if (!videoId) {
- this.error = "Video ID ausente";
- this.loading = false;
+ this.setError(
+ classifyPlayerError("video id ausente — track removed", "youtube", track.id),
+ );
return;
}
this.loading = true;
+ await this.stopCurrentPlayback();
+ this.youtubeCurrentVideoId = videoId;
+ this.youtubeVideoUrl = null;
+ this.youtubeChapters = [];
+ this.youtubeSponsorBlockSegments = [];
+ this.youtubeRefreshFailureCount = 0;
try {
- const res = await pluginInvoke<{ url: string }>(
- "study",
- "study:music:youtube:track_stream_url",
- { video_id: videoId },
- );
- if (!res.url) throw new Error("empty stream url");
- this.audio.src = res.url;
+ const { audio: audioUrl, video: videoUrl } =
+ await this.resolveYoutubeMedia(videoId);
+ if (!audioUrl) throw new Error("empty stream url");
+ this.audio.src = audioUrl;
+ this.youtubeVideoUrl = videoUrl;
+ void this.refreshYoutubeSponsorBlock(videoId);
await this.audio.play();
this.ensureEqGraph();
this.saveQueueNow();
@@ -603,19 +1423,117 @@ class MusicPlayerStore {
video_id: videoId,
}).catch(() => {});
} catch (e) {
- this.error = e instanceof Error ? e.message : "Erro ao tocar (YouTube)";
- this.loading = false;
+ this.setError(classifyPlayerError(e, "youtube", track.id));
}
}
- private async playLocal(track: MusicTrack) {
+ private cancelYoutubeRefresh() {
+ if (this.youtubeRefreshTimer) {
+ clearTimeout(this.youtubeRefreshTimer);
+ this.youtubeRefreshTimer = null;
+ }
+ }
+
+ private async resolveYoutubeMedia(
+ videoId: string,
+ ): Promise<{ audio: string | null; video: string | null; legacy: boolean }> {
+ try {
+ const { studyYoutubePlayer } = await import("$lib/study-bridge");
+ const res = await studyYoutubePlayer({ videoId });
+ const audio = pickBestYoutubeAudio(res);
+ const video = pickBestYoutubeVideo(res);
+ if (!audio) throw new Error("no audio format returned");
+ this.youtubeChapters = res.chapters ?? [];
+ this.scheduleYoutubeRefresh(videoId, res.expires_at);
+ return { audio, video, legacy: false };
+ } catch (err) {
+ console.warn(
+ "[study-music] study:youtube:player falhou, caindo para track_stream_url:",
+ err,
+ );
+ const legacy = await pluginInvoke<{ url: string }>(
+ "study",
+ "study:music:youtube:track_stream_url",
+ { video_id: videoId },
+ );
+ return { audio: legacy.url || null, video: null, legacy: true };
+ }
+ }
+
+ private scheduleYoutubeRefresh(videoId: string, expiresAt: number) {
+ this.cancelYoutubeRefresh();
+ const now = Math.floor(Date.now() / 1000);
+ const delaySecs = Math.max(30, expiresAt - now - 60);
+ this.youtubeRefreshTimer = setTimeout(() => {
+ void this.refreshYoutubeStream(videoId);
+ }, delaySecs * 1000);
+ }
+
+ private async refreshYoutubeStream(videoId: string) {
if (!this.audio) return;
+ if (this.youtubeCurrentVideoId !== videoId) return;
+ if (this.currentTrack?.youtube_video_id !== videoId) return;
try {
- try {
- await spotifySdk.pause();
- } catch {
- /* ignore */
+ const { studyYoutubePlayer } = await import("$lib/study-bridge");
+ console.info("[study-music] yt refresh start", { videoId });
+ const res = await studyYoutubePlayer({ videoId });
+ const url = pickBestYoutubeAudio(res);
+ const videoUrl = pickBestYoutubeVideo(res);
+ if (!url) throw new Error("refresh returned no audio format");
+ const wasPaused = this.audio.paused;
+ const t = this.audio.currentTime;
+ this.audio.src = url;
+ this.audio.currentTime = t;
+ this.youtubeVideoUrl = videoUrl;
+ if (!wasPaused) await this.audio.play();
+ this.youtubeChapters = res.chapters ?? this.youtubeChapters;
+ this.youtubeRefreshFailureCount = 0;
+ this.scheduleYoutubeRefresh(videoId, res.expires_at);
+ console.info("[study-music] yt refresh ok", { videoId, expires_at: res.expires_at });
+ } catch (err) {
+ this.youtubeRefreshFailureCount += 1;
+ console.warn(
+ "[study-music] yt refresh failed",
+ { videoId, attempt: this.youtubeRefreshFailureCount },
+ err,
+ );
+ if (
+ this.youtubeRefreshFailureCount >= MusicPlayerStore.YOUTUBE_REFRESH_MAX_FAILURES
+ ) {
+ try {
+ this.audio.pause();
+ } catch {
+ /* ignore */
+ }
+ const track = this.currentTrack;
+ if (track) {
+ this.setError(classifyPlayerError("auth_expired", "youtube", track.id));
+ }
+ this.youtubeRefreshFailureCount = 0;
+ return;
}
+ this.cancelYoutubeRefresh();
+ this.youtubeRefreshTimer = setTimeout(() => {
+ void this.refreshYoutubeStream(videoId);
+ }, MusicPlayerStore.YOUTUBE_REFRESH_RETRY_DELAY_SECS * 1000);
+ }
+ }
+
+ private async refreshYoutubeSponsorBlock(videoId: string) {
+ try {
+ const { studyYoutubeSponsorblock } = await import("$lib/study-bridge");
+ const res = await studyYoutubeSponsorblock({ videoId });
+ if (this.youtubeCurrentVideoId !== videoId) return;
+ this.youtubeSponsorBlockSegments = res.segments ?? [];
+ } catch (err) {
+ console.warn("[study-music] sponsorblock lookup failed:", err);
+ }
+ }
+
+ private async playLocal(track: MusicTrack) {
+ if (!this.audio) return;
+ await this.stopCurrentPlayback();
+ try {
const isHttpUrl =
track.path.startsWith("http://") || track.path.startsWith("https://");
this.audio.src = isHttpUrl ? track.path : convertFileSrc(track.path);
@@ -625,8 +1543,7 @@ class MusicPlayerStore {
this.updateMediaSessionMetadata(track);
void this.refreshDominantColor(track);
} catch (e) {
- this.error = e instanceof Error ? e.message : "Erro ao tocar";
- this.loading = false;
+ this.setError(classifyPlayerError(e, track.source ?? "local", track.id));
}
}
@@ -634,20 +1551,17 @@ class MusicPlayerStore {
private async playSpotify(track: MusicTrack) {
if (!track.spotify_uri) {
- this.error = "Faixa Spotify sem URI";
+ this.setError(classifyPlayerError("track removed: spotify uri ausente", "spotify", track.id));
return;
}
- if (this.audio && !this.audio.paused) {
- try {
- this.audio.pause();
- } catch {
- /* ignore */
- }
- }
+ const t0 = performance.now();
this.loading = true;
+ await this.stopCurrentPlayback({ keepSpotify: true });
+ const tStop = performance.now();
let sdkErr: unknown = null;
try {
await spotifySdk.ensureLoaded();
+ const tReady = performance.now();
const queueUris = this.queue
.filter((t) => t.source === "spotify" && t.spotify_uri)
.map((t) => t.spotify_uri as string);
@@ -658,11 +1572,22 @@ class MusicPlayerStore {
return [...queueUris.slice(idx), ...queueUris.slice(0, idx)];
})();
await spotifySdk.play({ uris: orderedUris });
+ const tPlay = performance.now();
+ console.info(
+ "[player] spotify timing",
+ {
+ stop_ms: Math.round(tStop - t0),
+ ready_ms: Math.round(tReady - tStop),
+ play_ms: Math.round(tPlay - tReady),
+ total_ms: Math.round(tPlay - t0),
+ },
+ );
this.saveQueueNow();
this.updateMediaSessionMetadata(track);
if (track.spotify_cover_url) {
void this.refreshDominantColorFromUrl(track.spotify_cover_url);
}
+ if (this._spotifyHeartbeatEnabled) this.startSpotifyHeartbeat();
return;
} catch (e) {
sdkErr = e;
@@ -670,12 +1595,8 @@ class MusicPlayerStore {
}
if (!this.spotifyFreeFallback || !this.audio) {
- this.error =
- sdkErr instanceof Error
- ? sdkErr.message
- : "Não foi possível tocar via Spotify SDK e nenhum fallback disponível";
- this.loading = false;
- throw sdkErr ?? new Error(String(this.error));
+ this.setError(classifyPlayerError(sdkErr ?? "spotify sdk failed", "spotify", track.id));
+ throw sdkErr ?? new Error("spotify sdk failed");
}
try {
@@ -687,17 +1608,29 @@ class MusicPlayerStore {
this.saveQueueNow();
this.updateMediaSessionMetadata(track);
} catch (e) {
- this.error =
- e instanceof Error
- ? `Spotify e YouTube falharam: ${e.message}`
- : "Falha ao resolver áudio";
- this.loading = false;
+ this.setError(classifyPlayerError(e, "spotify", track.id));
throw e;
}
}
- private async refreshDominantColorFromUrl(_url: string) {
- this.dominantColor = null;
+ private async refreshDominantColorFromUrl(url: string) {
+ if (!url) {
+ this.dominantColor = null;
+ this.palette = null;
+ return;
+ }
+ const token = ++this.paletteRefreshToken;
+ const trackId = this.currentTrack?.id ?? null;
+ const palette = await palettePathOrUrl(url);
+ if (token !== this.paletteRefreshToken) return;
+ if (trackId !== null && this.currentTrack?.id !== trackId) return;
+ if (palette && palette.length > 0) {
+ this.palette = palette;
+ this.dominantColor = palette[0];
+ } else {
+ this.palette = null;
+ this.dominantColor = null;
+ }
}
togglePlay() {
@@ -710,7 +1643,10 @@ class MusicPlayerStore {
if (!this.audio) return;
if (this.paused) {
this.audio.play().catch((e) => {
- this.error = e instanceof Error ? e.message : String(e);
+ const track = this.currentTrack;
+ if (track) {
+ this.setError(classifyPlayerError(e, track.source ?? "local", track.id));
+ }
});
this.ensureEqGraph();
} else {
@@ -783,14 +1719,25 @@ class MusicPlayerStore {
seek(seconds: number) {
if (this.isSpotify()) {
- const ms = Math.max(0, seconds * 1000);
+ const dur = this.duration;
+ const target =
+ Number.isFinite(dur) && dur > 0
+ ? Math.max(0, Math.min(dur, seconds))
+ : Math.max(0, seconds);
+ const ms = Math.floor(target * 1000);
+ this._spotifyLastKnownPositionMs = ms;
+ this._spotifyLastEventAt = performance.now();
+ this.currentTime = target;
+ this.updateMediaSessionPosition();
void spotifySdk.seek(ms);
+ void this.fireRpcUpdate();
return;
}
if (!this.audio) return;
const dur = this.audio.duration || this.duration;
if (!Number.isFinite(dur) || dur <= 0) return;
this.audio.currentTime = Math.max(0, Math.min(dur, seconds));
+ void this.fireRpcUpdate();
}
seekRatio(ratio: number) {
@@ -840,12 +1787,24 @@ class MusicPlayerStore {
clearQueue() {
this.audio?.pause();
+ this.cancelYoutubeRefresh();
+ this.youtubeCurrentVideoId = null;
+ this.youtubeVideoUrl = null;
+ this.youtubeChapters = [];
+ this.youtubeSponsorBlockSegments = [];
+ this.stopSpotifyTick();
+ this.stopSpotifyHeartbeat();
+ this._spotifyIsPlaying = false;
+ this._spotifyLastKnownPositionMs = 0;
+ this._spotifyLastEventAt = 0;
this.queue = [];
this.queueIndex = 0;
this.currentTrack = null;
this.currentTime = 0;
this.duration = 0;
+ this.historyRecorded.clear();
this.saveQueueNow();
+ void this.fireRpcClear();
}
private handleEnded() {
@@ -901,6 +1860,33 @@ class MusicPlayerStore {
void this.flushPlayReport();
this.saveQueueNow();
}
+
+ suspendAudioForWatch(): { currentTime: number; wasPlaying: boolean } {
+ if (!this.audio) return { currentTime: 0, wasPlaying: false };
+ const snap = {
+ currentTime: this.audio.currentTime || 0,
+ wasPlaying: !this.audio.paused,
+ };
+ try {
+ this.audio.pause();
+ } catch {
+ /* ignore */
+ }
+ return snap;
+ }
+
+ resumeAudioFromWatch(currentTime: number, shouldPlay: boolean) {
+ if (!this.audio) return;
+ try {
+ this.audio.currentTime = currentTime;
+ } catch {
+ /* ignore */
+ }
+ if (shouldPlay) {
+ this.audio.play().catch(() => {});
+ this.ensureEqGraph();
+ }
+ }
}
export const musicPlayer = new MusicPlayerStore();
diff --git a/src/lib/study-music/soundcloud-store.svelte.ts b/src/lib/study-music/soundcloud-store.svelte.ts
index 7f0f1aeb..3cf84181 100644
--- a/src/lib/study-music/soundcloud-store.svelte.ts
+++ b/src/lib/study-music/soundcloud-store.svelte.ts
@@ -197,10 +197,41 @@ class SoundCloudStore {
this.playlists = [];
this.followings = [];
this.streamFeed = [];
+ this.status = { has_client_id: this.status.has_client_id, has_oauth: false, user_id: null };
+ this.error = null;
await this.refreshStatus();
}
}
+ async loginWithWebview(): Promise<void> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ this.error = null;
+ const result = await invoke<{
+ cookies: { name: string; value: string; domain: string; path: string }[];
+ finalUrl: string;
+ }>("open_auth_webview", {
+ request: {
+ url: "https://soundcloud.com/signin",
+ title: "Entrar com SoundCloud",
+ cookieDomains: [".soundcloud.com", "soundcloud.com"],
+ successUrlContains: null,
+ waitForCookie: "oauth_token",
+ initializationScript: null,
+ },
+ });
+ if (!result?.cookies || result.cookies.length === 0) {
+ throw new Error("Não capturei seu login. Tenta de novo.");
+ }
+ const cookiesJson = JSON.stringify(result.cookies);
+ await pluginInvoke("study", "study:soundcloud:auth:set_cookies", {
+ cookies_json: cookiesJson,
+ });
+ await this.refreshStatus();
+ if (this.isLoggedIn) {
+ await this.loadAll();
+ }
+ }
+
async loadAll() {
if (!this.isLoggedIn) return;
this.loading = true;
@@ -384,15 +415,7 @@ async function resolveSoundcloudStream(
"study:soundcloud:stream:resolve",
{ trackId: scId, quality: "progressive" },
);
- if (!res.url) {
- const fallback = await pluginInvoke<{ url: string; is_hls: boolean }>(
- "study",
- "study:soundcloud:stream:resolve",
- { trackId: scId, quality: "hq" },
- );
- if (!fallback.url) throw new Error("SoundCloud não retornou URL");
- return fallback;
- }
+ if (!res.url) throw new Error("SoundCloud nao retornou URL");
return res;
}
diff --git a/src/lib/study-music/spotify-sdk.svelte.ts b/src/lib/study-music/spotify-sdk.svelte.ts
index c1971b8c..c0f9296b 100644
--- a/src/lib/study-music/spotify-sdk.svelte.ts
+++ b/src/lib/study-music/spotify-sdk.svelte.ts
@@ -257,7 +257,16 @@ class SpotifySdkController {
}
async seek(positionMs: number): Promise<void> {
- if (this.player) await this.player.seek(positionMs);
+ if (this.player) await this.player.seek(Math.max(0, Math.floor(positionMs)));
+ }
+
+ async getCurrentState(): Promise<SpotifySdkState | null> {
+ if (!this.player) return null;
+ try {
+ return await this.player.getCurrentState();
+ } catch {
+ return null;
+ }
}
async next(): Promise<void> {
diff --git a/src/lib/study-music/theme-store.svelte.ts b/src/lib/study-music/theme-store.svelte.ts
index cd65c4f3..9cf74a1f 100644
--- a/src/lib/study-music/theme-store.svelte.ts
+++ b/src/lib/study-music/theme-store.svelte.ts
@@ -6,10 +6,13 @@ export type MusicThemePreset =
| "amber"
| "custom";
+export type ReduceAnimationsMode = "auto" | "on" | "off";
+
export type MusicTheme = {
preset: MusicThemePreset;
accent: string;
useDominant: boolean;
+ reduceAnimations: ReduceAnimationsMode;
};
const STORAGE_KEY = "study.music.theme.v1";
@@ -26,8 +29,11 @@ const DEFAULT_THEME: MusicTheme = {
preset: "default",
accent: "",
useDominant: true,
+ reduceAnimations: "auto",
};
+const REDUCE_ANIMATIONS_MODES: ReduceAnimationsMode[] = ["auto", "on", "off"];
+
function isHexColor(value: string): boolean {
return /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value);
}
@@ -36,8 +42,21 @@ class MusicThemeStore {
preset = $state<MusicThemePreset>("default");
accent = $state("");
useDominant = $state(true);
+ reduceAnimations = $state<ReduceAnimationsMode>("auto");
+ private prefersReducedMotion = $state(false);
load() {
+ if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
+ try {
+ const mql = window.matchMedia("(prefers-reduced-motion: reduce)");
+ this.prefersReducedMotion = mql.matches;
+ mql.addEventListener?.("change", (e) => {
+ this.prefersReducedMotion = e.matches;
+ });
+ } catch {
+ /* ignore */
+ }
+ }
if (typeof localStorage === "undefined") return;
try {
const raw = localStorage.getItem(STORAGE_KEY);
@@ -54,6 +73,12 @@ class MusicThemeStore {
if (typeof data.useDominant === "boolean") {
this.useDominant = data.useDominant;
}
+ if (
+ typeof data.reduceAnimations === "string" &&
+ REDUCE_ANIMATIONS_MODES.includes(data.reduceAnimations as ReduceAnimationsMode)
+ ) {
+ this.reduceAnimations = data.reduceAnimations as ReduceAnimationsMode;
+ }
} catch {
/* ignore */
}
@@ -68,6 +93,7 @@ class MusicThemeStore {
preset: this.preset,
accent: this.accent,
useDominant: this.useDominant,
+ reduceAnimations: this.reduceAnimations,
}),
);
} catch {
@@ -75,6 +101,17 @@ class MusicThemeStore {
}
}
+ setReduceAnimations(mode: ReduceAnimationsMode) {
+ this.reduceAnimations = mode;
+ this.persist();
+ }
+
+ get reduceAnimationsActive(): boolean {
+ if (this.reduceAnimations === "on") return true;
+ if (this.reduceAnimations === "off") return false;
+ return this.prefersReducedMotion;
+ }
+
setPreset(preset: MusicThemePreset) {
this.preset = preset;
if (preset !== "custom") {
@@ -99,6 +136,7 @@ class MusicThemeStore {
this.preset = DEFAULT_THEME.preset;
this.accent = DEFAULT_THEME.accent;
this.useDominant = DEFAULT_THEME.useDominant;
+ this.reduceAnimations = DEFAULT_THEME.reduceAnimations;
this.persist();
}
diff --git a/src/lib/study-music/ui-store.svelte.ts b/src/lib/study-music/ui-store.svelte.ts
index 70c8dbd5..e849514e 100644
--- a/src/lib/study-music/ui-store.svelte.ts
+++ b/src/lib/study-music/ui-store.svelte.ts
@@ -7,7 +7,18 @@ export type ContextMenuState = {
track: MusicTrack | null;
};
-export type RightBarTab = "queue" | "lyrics" | "info";
+export type RightBarTab = "queue" | "lyrics" | "info" | "chapters";
+
+const VIDEO_MODE_KEY = "study.music.video_mode";
+
+function loadVideoMode(): boolean {
+ if (typeof localStorage === "undefined") return false;
+ try {
+ return localStorage.getItem(VIDEO_MODE_KEY) === "true";
+ } catch {
+ return false;
+ }
+}
class MusicUI {
addToPlaylistTrack = $state<MusicTrack | null>(null);
@@ -18,6 +29,7 @@ class MusicUI {
selectedIds = $state<Set<number>>(new Set());
selectionAnchor = $state<{ trackId: number; queue: MusicTrack[] } | null>(null);
contextMenu = $state<ContextMenuState>({ open: false, x: 0, y: 0, track: null });
+ videoMode = $state<boolean>(loadVideoMode());
get queueOpen(): boolean {
return this.rightbarTab === "queue";
@@ -110,6 +122,13 @@ class MusicUI {
closeQobuz() {
this.qobuzOpen = false;
}
+ translationSettingsOpen = $state(false);
+ openTranslationSettings() {
+ this.translationSettingsOpen = true;
+ }
+ closeTranslationSettings() {
+ this.translationSettingsOpen = false;
+ }
openContextMenu(track: MusicTrack, x: number, y: number) {
this.contextMenu = { open: true, x, y, track };
}
@@ -160,6 +179,18 @@ class MusicUI {
selectedCount(): number {
return this.selectedIds.size;
}
+ toggleVideoMode() {
+ this.setVideoMode(!this.videoMode);
+ }
+ setVideoMode(enabled: boolean) {
+ this.videoMode = enabled;
+ if (typeof localStorage === "undefined") return;
+ try {
+ localStorage.setItem(VIDEO_MODE_KEY, enabled ? "true" : "false");
+ } catch {
+ /* ignore */
+ }
+ }
}
export const musicUI = new MusicUI();
diff --git a/src/lib/study-music/youtube-play-helper.ts b/src/lib/study-music/youtube-play-helper.ts
new file mode 100644
index 00000000..ab1828a2
--- /dev/null
+++ b/src/lib/study-music/youtube-play-helper.ts
@@ -0,0 +1,80 @@
+import { pluginInvoke } from "$lib/plugin-invoke";
+import {
+ musicPlayer,
+ type MusicTrack,
+} from "$lib/study-music/player-store.svelte";
+import type { YoutubeSearchVideoItem } from "$lib/study-bridge";
+
+export type PlayableVideo = {
+ video_id: string;
+ title: string;
+ channel_title: string | null;
+ thumbnail_url: string | null;
+ duration_ms?: number | null;
+};
+
+function toPlayable(item: YoutubeSearchVideoItem): PlayableVideo {
+ return {
+ video_id: item.video_id,
+ title: item.title,
+ channel_title: item.channel_title,
+ thumbnail_url: item.thumbnail_url,
+ duration_ms: null,
+ };
+}
+
+async function ensureTrack(rt: PlayableVideo): Promise<MusicTrack> {
+ const ensured = await pluginInvoke<{ id: number }>(
+ "study",
+ "study:music:youtube:ensure_external_track",
+ {
+ video_id: rt.video_id,
+ title: rt.title,
+ artist: rt.channel_title ?? "",
+ album: null,
+ duration_ms: rt.duration_ms ?? null,
+ thumbnail: rt.thumbnail_url ?? null,
+ },
+ );
+ return {
+ id: ensured.id,
+ path: `external://youtube/${rt.video_id}`,
+ title: rt.title,
+ artist: rt.channel_title ?? null,
+ album: null,
+ duration_ms: rt.duration_ms ?? null,
+ cover_path: rt.thumbnail_url ?? null,
+ source: "youtube",
+ youtube_url: `https://www.youtube.com/watch?v=${rt.video_id}`,
+ youtube_video_id: rt.video_id,
+ youtube_thumbnail: rt.thumbnail_url ?? undefined,
+ };
+}
+
+export async function playYoutubeVideoItem(
+ item: YoutubeSearchVideoItem,
+ queue?: YoutubeSearchVideoItem[],
+): Promise<void> {
+ const items = queue && queue.length > 0 ? queue : [item];
+ const playableQueue = items.map(toPlayable);
+ const tracks = await Promise.all(playableQueue.map(ensureTrack));
+ const target = tracks.find((t) => t.youtube_video_id === item.video_id);
+ if (target) await musicPlayer.play(target, tracks);
+}
+
+export async function playYoutubeVideoId(
+ videoId: string,
+ title: string,
+ channelTitle: string | null,
+ thumbnailUrl: string | null,
+): Promise<void> {
+ const playable: PlayableVideo = {
+ video_id: videoId,
+ title,
+ channel_title: channelTitle,
+ thumbnail_url: thumbnailUrl,
+ duration_ms: null,
+ };
+ const track = await ensureTrack(playable);
+ await musicPlayer.play(track, [track]);
+}
diff --git a/src/lib/tracker-bridge.ts b/src/lib/tracker-bridge.ts
new file mode 100644
index 00000000..0df9a8a1
--- /dev/null
+++ b/src/lib/tracker-bridge.ts
@@ -0,0 +1,175 @@
+import { listen, type UnlistenFn } from "@tauri-apps/api/event";
+import { pluginInvoke } from "$lib/plugin-invoke";
+
+export type Carrier =
+ | "loggi"
+ | "cainiao"
+ | "melhor_envio"
+ | "anjun"
+ | "shopee"
+ | "total_express"
+ | "jt_express"
+ | "correios"
+ | "unknown";
+
+export type CanonicalStatus =
+ | "preadvice"
+ | "picked_up"
+ | "in_transit"
+ | "in_warehouse"
+ | "customs"
+ | "customs_held"
+ | "customs_cleared"
+ | "out_for_delivery"
+ | "awaiting_pickup"
+ | "delivered"
+ | "delivery_failure"
+ | "delayed"
+ | "returning_to_sender"
+ | "returned_to_sender"
+ | "damaged"
+ | "unknown";
+
+export type TrackedPackage = {
+ id: number;
+ code: string;
+ alias: string | null;
+ carrier: Carrier | string;
+ cpf: string | null;
+ last_status: string | null;
+ last_event_at_ms: number | null;
+ days_in_transit: string | null;
+ created_at_ms: number;
+ updated_at_ms: number;
+ is_delivered: boolean;
+ canonical_status: CanonicalStatus | null;
+ is_archived: boolean;
+ archive_prompt_dismissed: boolean;
+};
+
+export type ListFilter = "active" | "archived" | "all";
+
+export type TrackingEvent = {
+ id: number;
+ package_id: number;
+ seq: number;
+ status: string | null;
+ date: string | null;
+ time: string | null;
+ location: string | null;
+ sub_status: string[];
+};
+
+export type NewPackageInput = {
+ code: string;
+ alias?: string;
+ carrier_hint?: string;
+ cpf?: string;
+};
+
+export type CarrierDetection = {
+ carrier: Carrier | string;
+ display_name: string;
+ requires_cpf: boolean;
+};
+
+export type TrackingGetResponse = {
+ package: TrackedPackage;
+ events: TrackingEvent[];
+} | null;
+
+export type RefreshResult = {
+ ok: boolean;
+ id: number;
+ events_added?: number;
+ status_changed?: boolean;
+};
+
+export type TrackerEventName =
+ | "status-changed"
+ | "refresh-started"
+ | "refresh-progress"
+ | "refresh-done";
+
+export type TrackerEventPayload = {
+ "status-changed": {
+ id: number;
+ code: string;
+ old_status: string | null;
+ new_status: string;
+ old_canonical: CanonicalStatus | null;
+ new_canonical: CanonicalStatus | null;
+ canonical_changed: boolean;
+ location: string | null;
+ };
+ "refresh-started": { id: number; code: string; carrier: string };
+ "refresh-progress": { id: number; ok: boolean };
+ "refresh-done": {
+ id: number;
+ events_added: number;
+ status_changed: boolean;
+ error?: string;
+ };
+};
+
+const PLUGIN_ID = "misc";
+
+export function trackerList(filter: ListFilter = "active"): Promise<TrackedPackage[]> {
+ return pluginInvoke<TrackedPackage[]>(PLUGIN_ID, "misc:tracking:list", { filter });
+}
+
+export function trackerGet(id: number): Promise<TrackingGetResponse> {
+ return pluginInvoke<TrackingGetResponse>(PLUGIN_ID, "misc:tracking:get", { id });
+}
+
+export function trackerAdd(input: NewPackageInput): Promise<TrackedPackage> {
+ const args: Record<string, unknown> = { code: input.code };
+ if (input.alias != null) args.alias = input.alias;
+ if (input.carrier_hint != null) args.carrier_hint = input.carrier_hint;
+ if (input.cpf != null) args.cpf = input.cpf;
+ return pluginInvoke<TrackedPackage>(PLUGIN_ID, "misc:tracking:add", args);
+}
+
+export function trackerRemove(id: number): Promise<{ ok: boolean; id: number }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:remove", { id });
+}
+
+export function trackerRefresh(id: number): Promise<RefreshResult> {
+ return pluginInvoke<RefreshResult>(PLUGIN_ID, "misc:tracking:refresh", { id });
+}
+
+export function trackerRefreshAll(): Promise<{ ok: boolean }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:refresh_all", {});
+}
+
+export function trackerDetectCarrier(code: string): Promise<CarrierDetection> {
+ return pluginInvoke<CarrierDetection>(PLUGIN_ID, "misc:tracking:detect_carrier", { code });
+}
+
+export function trackerSetAlias(id: number, alias: string | null): Promise<{ ok: boolean; id: number }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:set_alias", { id, alias });
+}
+
+export function trackerSetCpf(id: number, cpf: string | null): Promise<{ ok: boolean; id: number }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:set_cpf", { id, cpf });
+}
+
+export function trackerSetArchived(
+ id: number,
+ archived: boolean,
+): Promise<{ ok: boolean; id: number; archived: boolean }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:set_archived", { id, archived });
+}
+
+export function trackerDismissArchivePrompt(
+ id: number,
+): Promise<{ ok: boolean; id: number }> {
+ return pluginInvoke(PLUGIN_ID, "misc:tracking:dismiss_archive_prompt", { id });
+}
+
+export async function onTrackerEvent<N extends TrackerEventName>(
+ name: N,
+ cb: (payload: TrackerEventPayload[N]) => void,
+): Promise<UnlistenFn> {
+ return listen<TrackerEventPayload[N]>(`misc:tracking:${name}`, (e) => cb(e.payload));
+}
diff --git a/src/lib/tracker-carrier-icons.ts b/src/lib/tracker-carrier-icons.ts
new file mode 100644
index 00000000..c4166590
--- /dev/null
+++ b/src/lib/tracker-carrier-icons.ts
@@ -0,0 +1,83 @@
+import type { Carrier } from "$lib/tracker-bridge";
+
+export type CarrierIcon = {
+ svgPath: string;
+ color: string;
+ /// Nome de exibição. Nomes de transportadora são marcas registradas e
+ /// permanecem literais em todos os idiomas — exceto `unknown`, que usa
+ /// `labelKey` pra resolver via i18n. Quando `labelKey` está presente, o
+ /// caller deve preferi-la sobre `label`.
+ label: string;
+ labelKey?: string;
+};
+
+const ICONS: Record<Carrier, CarrierIcon> = {
+ correios: {
+ label: "Correios",
+ color: "#FFB300",
+ svgPath: "M4 6h16v12H4z M4 6l8 6 8-6",
+ },
+ loggi: {
+ label: "Loggi",
+ color: "#FF6F00",
+ svgPath: "M3 17V7h11v10 M14 11h4l3 3v3h-7 M7 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z M17 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",
+ },
+ shopee: {
+ label: "Shopee",
+ color: "#EE4D2D",
+ svgPath: "M5 8h14l-1 12H6L5 8z M9 8V5a3 3 0 0 1 6 0v3",
+ },
+ cainiao: {
+ label: "Cainiao",
+ color: "#1E88E5",
+ svgPath: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M2 12h20 M12 2a15 15 0 0 1 0 20 M12 2a15 15 0 0 0 0 20",
+ },
+ melhor_envio: {
+ label: "Melhor Envio",
+ color: "#43A047",
+ svgPath: "M4 13h16v8H4z M4 13l2-4h12l2 4 M12 9V2 M8.5 5.5 12 2l3.5 3.5",
+ },
+ anjun: {
+ label: "Anjun",
+ color: "#8E24AA",
+ svgPath: "M21 16v-2l-8-5V3.5a1.5 1.5 0 0 0-3 0V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z",
+ },
+ total_express: {
+ label: "Total Express",
+ color: "#E53935",
+ svgPath: "M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M7.5 4.21 12 6.81l4.5-2.6 M7.5 19.79V14.6L3 12 M21 12l-4.5 2.6v5.19 M3.27 6.96 12 12.01l8.73-5.05 M12 22.08V12",
+ },
+ jt_express: {
+ label: "J&T Express",
+ color: "#C62828",
+ svgPath: "M4 10h11v8H4z M4 10l2-3h7l2 3 M17 11h3 M17 14h3 M17 17h3",
+ },
+ unknown: {
+ label: "Unknown",
+ labelKey: "tracking.carrier.unknown",
+ color: "#757575",
+ svgPath: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3 M12 17h.01",
+ },
+};
+
+export function getCarrierIcon(carrier: string): CarrierIcon {
+ return ICONS[(carrier as Carrier)] ?? ICONS.unknown;
+}
+
+export type CarrierRoute = { from: string; to: string };
+
+const ROUTES: Record<Carrier, CarrierRoute | null> = {
+ correios: { from: "BRA", to: "BRA" },
+ loggi: { from: "BRA", to: "BRA" },
+ shopee: { from: "BRA", to: "BRA" },
+ melhor_envio: { from: "BRA", to: "BRA" },
+ total_express: { from: "BRA", to: "BRA" },
+ jt_express: { from: "BRA", to: "BRA" },
+ cainiao: { from: "CHN", to: "BRA" },
+ anjun: { from: "CHN", to: "BRA" },
+ unknown: null,
+};
+
+export function getCarrierRoute(carrier: string): CarrierRoute | null {
+ return ROUTES[(carrier as Carrier)] ?? null;
+}
diff --git a/src/lib/tracker-notifications.svelte.ts b/src/lib/tracker-notifications.svelte.ts
new file mode 100644
index 00000000..a853d2ba
--- /dev/null
+++ b/src/lib/tracker-notifications.svelte.ts
@@ -0,0 +1,132 @@
+import {
+ isPermissionGranted,
+ requestPermission,
+ sendNotification,
+} from "@tauri-apps/plugin-notification";
+import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
+import { get } from "svelte/store";
+
+import { onTrackerEvent, type TrackerEventPayload } from "$lib/tracker-bridge";
+import { getTrackerSettings } from "$lib/tracker-settings.svelte";
+import { privacyEnabled, maskCode } from "$lib/tracker-privacy.svelte";
+import { t } from "$lib/i18n";
+
+const NOTIFICATION_DEBOUNCE_MS = 60_000;
+const lastNotifiedAt = new Map<number, number>();
+
+let registered = false;
+let permissionCache: boolean | null = null;
+
+async function ensurePermissionGranted(): Promise<boolean> {
+ if (permissionCache === true) return true;
+ try {
+ if (await isPermissionGranted()) {
+ permissionCache = true;
+ return true;
+ }
+ const status = await requestPermission();
+ const granted = status === "granted";
+ permissionCache = granted;
+ return granted;
+ } catch (e) {
+ console.warn("[tracker-notifications] permission check failed", e);
+ return false;
+ }
+}
+
+async function windowIsFocused(): Promise<boolean> {
+ try {
+ return await getCurrentWebviewWindow().isFocused();
+ } catch {
+ return false;
+ }
+}
+
+function tStr(key: string, params?: Record<string, unknown>): string {
+ const fn = get(t);
+ return fn(key, params) as unknown as string;
+}
+
+function buildNotificationTitle(code: string, status: string): string {
+ const displayCode = privacyEnabled() ? maskCode(code) : code;
+ return tStr("tracking.notification.title_template", {
+ code: displayCode,
+ status,
+ });
+}
+
+function buildNotificationBody(location: string | null): string {
+ if (location && location.trim().length > 0) return location;
+ return tStr("tracking.notification.body_fallback");
+}
+
+async function handleStatusChanged(p: TrackerEventPayload["status-changed"]) {
+ const settings = getTrackerSettings();
+ if (!settings.notificationsEnabled) return;
+ if (!p.canonical_changed) return;
+
+ // Suppress when foreground — in-app toast on /misc/tracking already covers it.
+ if (await windowIsFocused()) return;
+
+ const now = Date.now();
+ const last = lastNotifiedAt.get(p.id) ?? 0;
+ if (now - last < NOTIFICATION_DEBOUNCE_MS) return;
+
+ if (!(await ensurePermissionGranted())) return;
+
+ try {
+ await sendNotification({
+ title: buildNotificationTitle(p.code, p.new_status),
+ body: buildNotificationBody(p.location),
+ });
+ lastNotifiedAt.set(p.id, now);
+ } catch (e) {
+ console.warn("[tracker-notifications] sendNotification failed", e);
+ }
+}
+
+export async function ensureTrackerNotifications(): Promise<void> {
+ if (registered) return;
+ registered = true;
+
+ // Best-effort upfront permission probe — don't block startup if it fails.
+ void ensurePermissionGranted();
+
+ try {
+ await onTrackerEvent("status-changed", (p) => {
+ void handleStatusChanged(p);
+ });
+ } catch (e) {
+ console.warn("[tracker-notifications] listener registration failed", e);
+ registered = false;
+ }
+}
+
+export async function requestNotificationPermission(): Promise<boolean> {
+ permissionCache = null;
+ return await ensurePermissionGranted();
+}
+
+export async function isNotificationPermissionGranted(): Promise<boolean> {
+ try {
+ return await isPermissionGranted();
+ } catch {
+ return false;
+ }
+}
+
+export async function sendTestNotification(): Promise<{ ok: boolean; denied: boolean }> {
+ if (!(await ensurePermissionGranted())) {
+ return { ok: false, denied: true };
+ }
+ try {
+ await sendNotification({
+ title: tStr("tracking.notification.test_title"),
+ body: tStr("tracking.notification.test_body"),
+ });
+ return { ok: true, denied: false };
+ } catch (e) {
+ console.warn("[tracker-notifications] test send failed", e);
+ return { ok: false, denied: false };
+ }
+}
diff --git a/src/lib/tracker-privacy.svelte.ts b/src/lib/tracker-privacy.svelte.ts
new file mode 100644
index 00000000..e90a8086
--- /dev/null
+++ b/src/lib/tracker-privacy.svelte.ts
@@ -0,0 +1,41 @@
+const STORAGE_KEY = "omniget.tracking.privacy";
+
+function readInitial(): boolean {
+ if (typeof localStorage === "undefined") return false;
+ try {
+ return localStorage.getItem(STORAGE_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+let enabled = $state(readInitial());
+
+function persist() {
+ try {
+ localStorage.setItem(STORAGE_KEY, enabled ? "1" : "0");
+ } catch {
+ // localStorage unavailable — state still works in-memory
+ }
+}
+
+export function privacyEnabled(): boolean {
+ return enabled;
+}
+
+export function togglePrivacy() {
+ enabled = !enabled;
+ persist();
+}
+
+export function setPrivacy(v: boolean) {
+ enabled = v;
+ persist();
+}
+
+export function maskCode(code: string | null | undefined): string {
+ if (!code) return "";
+ if (!enabled) return code;
+ if (code.length <= 6) return "•".repeat(code.length);
+ return code.slice(0, 2) + "•".repeat(code.length - 5) + code.slice(-3);
+}
diff --git a/src/lib/tracker-settings.svelte.ts b/src/lib/tracker-settings.svelte.ts
new file mode 100644
index 00000000..c4a58afc
--- /dev/null
+++ b/src/lib/tracker-settings.svelte.ts
@@ -0,0 +1,40 @@
+const STORAGE_KEY = "omniget.tracking.settings";
+
+export type TrackerSettings = {
+ notificationsEnabled: boolean;
+};
+
+const DEFAULTS: TrackerSettings = {
+ notificationsEnabled: true,
+};
+
+function readInitial(): TrackerSettings {
+ if (typeof localStorage === "undefined") return { ...DEFAULTS };
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return { ...DEFAULTS };
+ const parsed = JSON.parse(raw) as Partial<TrackerSettings>;
+ return { ...DEFAULTS, ...parsed };
+ } catch {
+ return { ...DEFAULTS };
+ }
+}
+
+let settings = $state<TrackerSettings>(readInitial());
+
+function persist() {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
+ } catch {
+ // localStorage unavailable — state still works in-memory
+ }
+}
+
+export function getTrackerSettings(): TrackerSettings {
+ return settings;
+}
+
+export function updateTrackerSettings(patch: Partial<TrackerSettings>) {
+ settings = { ...settings, ...patch };
+ persist();
+}
diff --git a/src/lib/tracker-status-icons.ts b/src/lib/tracker-status-icons.ts
new file mode 100644
index 00000000..1f1846e4
--- /dev/null
+++ b/src/lib/tracker-status-icons.ts
@@ -0,0 +1,293 @@
+// Ícones de estado canônico (Sessão 7 + Sessão 8). A UI usa esses paths SVG
+// inline pra distinguir visualmente cada estado. Cores são **tokens semânticos
+// do design system do host** (`--success`, `--danger`, `--warning`,
+// `--info`, `--orange`, `--gray`), de modo que cada tema apresente
+// status com cores coerentes com o resto da UI (catppuccin, dracula, eink
+// etc). Mapeamento:
+// - `--info` → movimento (picked_up / in_transit / in_warehouse).
+// `--info` aliases `--cta` no app.css, que é um azul real em todos os
+// temas (mesmo nos defaults light/dark, onde `--blue` aliases o accent
+// laranja da marca e portanto não serve).
+// - `--orange` → ação ativa/atenção (customs / out_for_delivery /
+// awaiting_pickup).
+// - `--warning` → atraso sem problema concreto (delayed).
+// - `--danger` → problema (customs_held / delivery_failure / damaged).
+// - `--success` → estado terminal feliz (delivered / customs_cleared).
+// - `--gray` → inerte/desconhecido (preadvice / returning / returned
+// / unknown).
+//
+// Os SVG paths usam o estilo Feather/Lucide (stroke-only, `viewBox="0 0 24 24"`,
+// `stroke-width="1.6"`, sem fills). Cada `svgPath` é uma string concatenada de
+// múltiplos `M ... L ...` subpaths que serão renderizados num único `<path>`.
+
+import type { CanonicalStatus } from "$lib/tracker-bridge";
+
+export type StatusIcon = {
+ svgPath: string;
+ /// CSS color expression — tipicamente `var(--info)`, `var(--success)`, etc.
+ /// O caller injeta via `style="--status-color: {icon.color}"`, então
+ /// qualquer expressão CSS válida funciona.
+ color: string;
+ /// i18n key (no formato `tracking.status.*`). O caller resolve via `$t(...)`.
+ labelKey: string;
+};
+
+const ICONS: Record<CanonicalStatus, StatusIcon> = {
+ preadvice: {
+ labelKey: "tracking.status.preadvice",
+ color: "var(--gray)",
+ // Caixa lacrada — package outline com um quadrado interno (a etiqueta).
+ svgPath:
+ "M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96 12 12.01l8.73-5.05 M12 22.08V12 M9 12.5h6",
+ },
+ picked_up: {
+ labelKey: "tracking.status.picked_up",
+ color: "var(--info)",
+ // Caixa + check pequeno em cima — coletado/postado.
+ svgPath:
+ "M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96 12 12.01l8.73-5.05 M9 16l2 2 4-4",
+ },
+ in_transit: {
+ labelKey: "tracking.status.in_transit",
+ color: "var(--info)",
+ // Caminhão clássico (Feather "truck").
+ svgPath:
+ "M3 17V7h11v10 M14 11h4l3 3v3h-7 M7 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z M17 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",
+ },
+ in_warehouse: {
+ labelKey: "tracking.status.in_warehouse",
+ color: "var(--info)",
+ // Galpão — telhado de duas águas + portão central.
+ svgPath:
+ "M3 21V10l9-6 9 6v11 M3 21h18 M9 21v-7h6v7 M10 15h4",
+ },
+ customs: {
+ labelKey: "tracking.status.customs",
+ color: "var(--orange)",
+ // Edifício com colunas (landmark-style).
+ svgPath:
+ "M3 21h18 M5 21V10 M9 21V10 M15 21V10 M19 21V10 M3 10h18 M12 3 3 8h18l-9-5z",
+ },
+ customs_held: {
+ labelKey: "tracking.status.customs_held",
+ color: "var(--danger)",
+ // Edifício + cadeado.
+ svgPath:
+ "M3 21h12 M5 21V11 M9 21V11 M13 21V11 M3 11h12 M9 4 3 8h12 M16 17a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v4h-6v-4z M18 15v-2a2 2 0 1 1 4 0v2",
+ },
+ customs_cleared: {
+ labelKey: "tracking.status.customs_cleared",
+ color: "var(--success)",
+ // Edifício + check.
+ svgPath:
+ "M3 21h12 M5 21V11 M9 21V11 M13 21V11 M3 11h12 M9 4 3 8h12 M16 17l2 2 4-4",
+ },
+ out_for_delivery: {
+ labelKey: "tracking.status.out_for_delivery",
+ color: "var(--orange)",
+ // Caminhão acelerando — truck com linhas de movimento atrás.
+ svgPath:
+ "M5 17V8h9v9 M14 12h3l3 3v2h-6 M9 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z M18 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z M1 9h3 M1 12h2 M1 15h3",
+ },
+ awaiting_pickup: {
+ labelKey: "tracking.status.awaiting_pickup",
+ color: "var(--orange)",
+ // Pin de localização (Feather "map-pin") — aponta onde retirar.
+ svgPath:
+ "M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0z M12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",
+ },
+ delivered: {
+ labelKey: "tracking.status.delivered",
+ color: "var(--success)",
+ // Check-circle (Feather).
+ svgPath: "M22 11.08V12a10 10 0 1 1-5.93-9.14 M22 4 12 14.01l-3-3",
+ },
+ delivery_failure: {
+ labelKey: "tracking.status.delivery_failure",
+ color: "var(--danger)",
+ // Alert-circle (Feather).
+ svgPath:
+ "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 8v4 M12 16h.01",
+ },
+ delayed: {
+ labelKey: "tracking.status.delayed",
+ color: "var(--warning)",
+ // Clock (Feather).
+ svgPath: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 6v6l4 2",
+ },
+ returning_to_sender: {
+ labelKey: "tracking.status.returning_to_sender",
+ color: "var(--gray)",
+ // Corner-up-left arrow (Feather).
+ svgPath: "M9 14 4 9l5-5 M4 9h11a5 5 0 0 1 5 5v6",
+ },
+ returned_to_sender: {
+ labelKey: "tracking.status.returned_to_sender",
+ color: "var(--gray)",
+ // Corner-up-left + dot fechado.
+ svgPath: "M9 14 4 9l5-5 M4 9h11a5 5 0 0 1 5 5v6 M20 18h-4",
+ },
+ damaged: {
+ labelKey: "tracking.status.damaged",
+ color: "var(--danger)",
+ // Alert-triangle (Feather).
+ svgPath:
+ "m10.29 3.86-8.18 14.18A2 2 0 0 0 3.84 21h16.32a2 2 0 0 0 1.73-2.96L13.71 3.86a2 2 0 0 0-3.42 0z M12 9v4 M12 17h.01",
+ },
+ unknown: {
+ labelKey: "tracking.status.unknown",
+ color: "var(--gray)",
+ // Help-circle (Feather).
+ svgPath:
+ "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3 M12 17h.01",
+ },
+};
+
+export function getStatusIcon(status: CanonicalStatus | string | null | undefined): StatusIcon {
+ if (status == null) return ICONS.unknown;
+ const key = status as CanonicalStatus;
+ return ICONS[key] ?? ICONS.unknown;
+}
+
+/// Classificador client-side espelhando `classify_text` do backend Rust. Usado
+/// na timeline da página de detalhe pra dar a cada evento seu próprio ícone
+/// canônico sem precisar de uma round-trip ao plugin. Mantém a mesma ordem de
+/// precedência (`Delivered` ganha de `OutForDelivery`, etc).
+export function classifyEvent(rawStatus: string | null | undefined, rawLocation?: string | null): CanonicalStatus {
+ const t = `${rawStatus ?? ""} ${rawLocation ?? ""}`.toLowerCase().trim();
+ if (!t) return "unknown";
+
+ // Terminais.
+ if (
+ t.includes("devolvido ao remetente") ||
+ t.includes("objeto devolvido") ||
+ t.includes("returned to sender") ||
+ t.includes("devolução concluída")
+ )
+ return "returned_to_sender";
+ if (
+ t.includes("entrega realizada") ||
+ t.includes("entregue ao destinat") ||
+ t.includes("objeto entregue") ||
+ t.includes("pacote entregue") ||
+ t.includes("delivered") ||
+ t.includes("recebido por") ||
+ t.includes("assinado pelo destinat") ||
+ (t.startsWith("entregue") && !t.includes("não foi"))
+ )
+ return "delivered";
+
+ // Problemas.
+ if (t.includes("avariad") || t.includes("danific") || t.includes("damaged") || t.includes("destru"))
+ return "damaged";
+ if (
+ t.includes("não foi possível entregar") ||
+ t.includes("tentativa de entrega") ||
+ t.includes("entrega não realizada") ||
+ t.includes("destinatário ausente") ||
+ t.includes("delivery failure") ||
+ t.includes("delivery attempted")
+ )
+ return "delivery_failure";
+ if (
+ t.includes("em devolução") ||
+ t.includes("retornando ao remetente") ||
+ t.includes("returning to sender")
+ )
+ return "returning_to_sender";
+
+ // Retirada.
+ if (
+ t.includes("disponível para retirada") ||
+ t.includes("aguardando retirada") ||
+ t.includes("pronto para retirada") ||
+ t.includes("retirar na agência") ||
+ t.includes("ready for pickup") ||
+ t.includes("available for pickup")
+ )
+ return "awaiting_pickup";
+
+ // Alfândega.
+ if (
+ t.includes("liberado pela alfândega") ||
+ t.includes("liberado pela aduana") ||
+ t.includes("customs released") ||
+ t.includes("customs cleared") ||
+ (t.includes("liberado") && (t.includes("alfândega") || t.includes("aduane")))
+ )
+ return "customs_cleared";
+ if (
+ t.includes("retido na alfândega") ||
+ t.includes("retido na aduana") ||
+ t.includes("aguardando pagamento") ||
+ t.includes("aguardando documento") ||
+ t.includes("customs held")
+ )
+ return "customs_held";
+ if (
+ t.includes("desembaraço aduaneiro") ||
+ t.includes("alfândega") ||
+ t.includes("aduana") ||
+ t.includes("customs")
+ )
+ return "customs";
+
+ // Saiu pra entrega antes de in_transit.
+ if (
+ t.includes("saiu para entrega") ||
+ t.includes("em rota de entrega") ||
+ t.includes("em rota") ||
+ t.includes("rota de entrega") ||
+ t.includes("em entrega") ||
+ t.includes("out for delivery")
+ )
+ return "out_for_delivery";
+
+ // Warehouse.
+ if (
+ t.includes("centro de distribuição") ||
+ t.includes("centro logístico") ||
+ t.includes("chegou ao centro") ||
+ t.includes("triagem") ||
+ t.includes("unidade de tratamento") ||
+ t.includes("warehouse") ||
+ t.includes("sorting center") ||
+ t.includes("left sorting")
+ )
+ return "in_warehouse";
+
+ if (t.includes("atras") || t.includes("delayed") || t.includes("sem movimenta")) return "delayed";
+
+ if (
+ t.includes("em trânsito") ||
+ t.includes("em transito") ||
+ t.includes("encaminhado") ||
+ t.includes("in transit") ||
+ t.includes("trânsito para")
+ )
+ return "in_transit";
+
+ if (
+ t.includes("objeto postado") ||
+ t.includes("postagem") ||
+ t.includes("postado") ||
+ t.includes("coletado") ||
+ t.includes("collected") ||
+ t.includes("picked up") ||
+ t.includes("recebido pelo") ||
+ t.includes("origem")
+ )
+ return "picked_up";
+
+ if (
+ t.includes("pedido criado") ||
+ t.includes("aguardando coleta") ||
+ t.includes("preparing") ||
+ t.includes("preadvice") ||
+ t.includes("etiqueta gerada") ||
+ t.includes("pending pickup")
+ )
+ return "preadvice";
+
+ return "unknown";
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index b8581f02..df79253f 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -27,6 +27,7 @@
import { needsOnboarding } from "$lib/stores/onboarding-store.svelte";
import { isYtdlpAvailable, isDepsChecked, refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
import { showToast } from "$lib/stores/toast-store.svelte";
+ import { ensureTrackerNotifications } from "$lib/tracker-notifications.svelte";
import { t, locale } from "$lib/i18n";
import { get } from "svelte/store";
import { CORE_NAV_ITEMS, type NavItem } from "$lib/nav-config";
@@ -106,6 +107,7 @@
let unlistenMusicHotkey: (() => void) | undefined;
initDownloadListener().then((fn) => (cleanup = fn));
setTimeout(() => void checkAutoVacuum(), 5000);
+ void ensureTrackerNotifications();
import("$lib/rpc").then(({ rpcSyncIdleStats }) => rpcSyncIdleStats());
listen<{ url: string }>("music-hotkey-pressed", async (event) => {
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index e90a59ee..c45c6e74 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -288,10 +288,14 @@
function handleInput() {
if (debounceTimer) clearTimeout(debounceTimer);
clearMediaPreview();
- const saved = getSettings()?.last_download_options;
+ const currentSettings = getSettings();
+ const saved = currentSettings?.last_download_options;
const savedQuality = saved?.quality;
const savedMode = saved?.mode;
- selectedQuality = savedQuality && typeof savedQuality === "string" ? savedQuality : "best";
+ const settingsQuality = currentSettings?.download.video_quality;
+ selectedQuality = savedQuality && typeof savedQuality === "string"
+ ? savedQuality
+ : (settingsQuality && typeof settingsQuality === "string" ? settingsQuality : "best");
downloadMode = savedMode === "audio" || savedMode === "mute" ? savedMode : "auto";
selectedFormatId = null;
formats = [];
@@ -722,6 +726,7 @@
<FormatSelector
platform={omniState.info.platform}
+ isPlaylist={omniState.info.content_type === "playlist"}
bind:formats
bind:selectedFormatId
{loadingFormats}
diff --git a/src/routes/about/project/+page.svelte b/src/routes/about/project/+page.svelte
index 3d030017..2108f186 100644
--- a/src/routes/about/project/+page.svelte
+++ b/src/routes/about/project/+page.svelte
@@ -3,7 +3,7 @@
import { t } from "$lib/i18n";
const GITHUB_URL = "https://github.com/tonhowtf/omniget";
- const APP_VERSION = "0.6.0";
+ const APP_VERSION = "0.6.1";
async function openGitHub() {
await open(GITHUB_URL);
diff --git a/src/routes/courses/[platform]/+page.svelte b/src/routes/courses/[platform]/+page.svelte
index 98200686..bdf0da4f 100644
--- a/src/routes/courses/[platform]/+page.svelte
+++ b/src/routes/courses/[platform]/+page.svelte
@@ -57,9 +57,14 @@
const ITEMS_PER_PAGE = 12;
let currentPage = $state(1);
- let totalPages = $derived(Math.max(1, Math.ceil(items.length / ITEMS_PER_PAGE)));
+ let filteredItems = $derived.by(() => {
+ const q = searchQuery.trim().toLowerCase();
+ if (!q) return items;
+ return items.filter((it) => getItemName(it).toLowerCase().includes(q));
+ });
+ let totalPages = $derived(Math.max(1, Math.ceil(filteredItems.length / ITEMS_PER_PAGE)));
let paginatedItems = $derived(
- items.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE)
+ filteredItems.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE)
);
let pageNumbers = $derived((): number[] => {
@@ -445,20 +450,21 @@
{$t("hotmart.logged_as", { email: sessionDisplay() })}
</span>
<div class="session-actions">
- {#if config.features.has_search}
- <div class="search-bar">
- <input
- class="search-input"
- type="text"
- placeholder={$t("courses.search_placeholder")}
- bind:value={searchQuery}
- onkeydown={(e) => { if (e.key === "Enter") handleSearch(); }}
- />
+ <div class="search-bar">
+ <input
+ class="search-input"
+ type="text"
+ placeholder={$t("courses.search_placeholder")}
+ bind:value={searchQuery}
+ oninput={() => { currentPage = 1; }}
+ onkeydown={(e) => { if (e.key === "Enter" && config.features.has_search) handleSearch(); }}
+ />
+ {#if config.features.has_search}
<button class="button" onclick={handleSearch} disabled={!searchQuery.trim()}>
{$t("courses.search_btn") ?? "Search"}
</button>
- </div>
- {/if}
+ {/if}
+ </div>
<button class="button" onclick={refreshItems} disabled={refreshing} aria-label={$t("hotmart.refresh")}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class:spinning={refreshing}>
<path d="M21 2v6h-6" /><path d="M3 12a9 9 0 0115-6.7L21 8" /><path d="M3 22v-6h6" /><path d="M21 12a9 9 0 01-15 6.7L3 16" />
@@ -480,11 +486,17 @@
</div>
{:else if items.length === 0}
<p class="empty-text">{$t("hotmart.no_courses")}</p>
- {:else}
+ {:else if filteredItems.length === 0}
<div class="courses-header">
<h2>{config.name}</h2>
<span class="subtext">{items.length === 1 ? $t("hotmart.course_count_one", { count: items.length }) : $t("hotmart.course_count", { count: items.length })}</span>
</div>
+ <p class="empty-text">{$t("courses.no_search_results") ?? "No matching courses"}</p>
+ {:else}
+ <div class="courses-header">
+ <h2>{config.name}</h2>
+ <span class="subtext">{filteredItems.length === 1 ? $t("hotmart.course_count_one", { count: filteredItems.length }) : $t("hotmart.course_count", { count: filteredItems.length })}</span>
+ </div>
<div class="courses-grid">
{#each paginatedItems as item, idx (`${getItemId(item)}_${idx}`)}
@@ -503,7 +515,7 @@
{#if totalPages > 1}
<div class="pagination">
<span class="pagination-info">
- {$t("hotmart.page_of", { current: currentPage, total: totalPages })} &middot; {items.length === 1 ? $t("hotmart.course_count_one", { count: items.length }) : $t("hotmart.course_count", { count: items.length })}
+ {$t("hotmart.page_of", { current: currentPage, total: totalPages })} &middot; {filteredItems.length === 1 ? $t("hotmart.course_count_one", { count: filteredItems.length }) : $t("hotmart.course_count", { count: filteredItems.length })}
</span>
<div class="pagination-controls">
<button class="button pagination-btn" disabled={currentPage <= 1} onclick={() => goToPage(currentPage - 1)}>&lt;</button>
diff --git a/src/routes/downloads/+page.svelte b/src/routes/downloads/+page.svelte
index eaaebc9d..c5f09c28 100644
--- a/src/routes/downloads/+page.svelte
+++ b/src/routes/downloads/+page.svelte
@@ -41,6 +41,15 @@
}
});
+ function qualityChip(item: GenericDownloadItem): string | null {
+ if (item.downloadMode === "audio") return $t('omnibox.quality_audio') as string;
+ if (!item.quality) return null;
+ const q = item.quality.toLowerCase();
+ if (q === "best" || q === "highest") return $t('omnibox.quality_best_short') as string;
+ if (q === "audio") return $t('omnibox.quality_audio') as string;
+ return item.quality;
+ }
+
function canOpenInStudy(item: GenericDownloadItem): boolean {
return (
studyAvailable &&
@@ -310,6 +319,9 @@
<PlatformIcon platform={item.platform} size={16} />
<QueueKindBadge kind={item.queueKind} size={14} />
<span class="item-name">{item.name}</span>
+ {#if qualityChip(item)}
+ <span class="quality-chip" title={$t('downloads.quality_hint')}>{qualityChip(item)}</span>
+ {/if}
</div>
<div class="item-header-actions">
{#if item.status === "downloading"}
@@ -1004,6 +1016,20 @@
font-variant-numeric: tabular-nums;
}
+ .quality-chip {
+ padding: 1px 7px;
+ font-size: 10.5px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: var(--secondary);
+ background: var(--button-elevated);
+ border: 1px solid var(--button-stroke);
+ border-radius: 999px;
+ letter-spacing: 0.2px;
+ flex-shrink: 0;
+ font-variant-numeric: tabular-nums;
+ }
+
.show-more-btn {
align-self: center;
font-size: 13px;
diff --git a/src/routes/misc/+page.svelte b/src/routes/misc/+page.svelte
index 41ea91bf..b99b4f7f 100644
--- a/src/routes/misc/+page.svelte
+++ b/src/routes/misc/+page.svelte
@@ -35,6 +35,13 @@
iconPath: "M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20",
badge: "NEW",
},
+ {
+ href: "/misc/tracking",
+ title: "Rastreamento",
+ desc: "8 transportadoras BR, refresh automático. Acompanhe seus pacotes em um só lugar.",
+ iconPath: "M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96 12 12.01l8.73-5.05 M12 22.08V12",
+ badge: "NEW",
+ },
];
</script>
diff --git a/src/routes/misc/tracking/+page.svelte b/src/routes/misc/tracking/+page.svelte
new file mode 100644
index 00000000..b5deeec4
--- /dev/null
+++ b/src/routes/misc/tracking/+page.svelte
@@ -0,0 +1,1460 @@
+<script lang="ts">
+ import { onDestroy, onMount, tick } from "svelte";
+ import type { UnlistenFn } from "@tauri-apps/api/event";
+ import { t } from "$lib/i18n";
+ import {
+ onTrackerEvent,
+ trackerAdd,
+ trackerDetectCarrier,
+ trackerList,
+ trackerRefresh,
+ trackerRefreshAll,
+ trackerRemove,
+ trackerSetAlias,
+ trackerSetArchived,
+ type CarrierDetection,
+ type TrackedPackage,
+ } from "$lib/tracker-bridge";
+ import { getCarrierIcon } from "$lib/tracker-carrier-icons";
+ import { getStatusIcon } from "$lib/tracker-status-icons";
+ import { maskCode, privacyEnabled, togglePrivacy } from "$lib/tracker-privacy.svelte";
+
+ type Toast = { id: number; kind: "info" | "success" | "error"; text: string };
+ type Tab = "all" | "in_transit" | "awaiting" | "delivered" | "delayed" | "archived";
+
+ const TAB_STORAGE_KEY = "omniget.tracking.tab";
+
+ // Abas "ativas" (não-arquivados) compartilham a mesma listagem do backend
+ // (ListFilter::Active); só "archived" muda o filter. Filtragem entre as
+ // ativas é client-side via TAB_BUCKETS.
+ function backendFilter(t: Tab): "active" | "archived" {
+ return t === "archived" ? "archived" : "active";
+ }
+
+ // Buckets de cada aba "ativa", mapeados pra `canonical_status`. Pacotes
+ // sem canonical (pré-v2 ainda não backfillado, ou sem nenhum evento) usam
+ // o fallback `is_delivered` legado. `archived` não tem bucket — é filtrado
+ // direto pelo backend via ListFilter.
+ type BucketTab = Exclude<Tab, "all" | "archived">;
+ const TAB_BUCKETS: Record<BucketTab, readonly string[]> = {
+ in_transit: [
+ "preadvice",
+ "picked_up",
+ "in_transit",
+ "in_warehouse",
+ "customs",
+ "customs_cleared",
+ "out_for_delivery",
+ ],
+ awaiting: ["awaiting_pickup", "customs_held"],
+ delivered: ["delivered"],
+ delayed: ["delayed", "delivery_failure", "damaged"],
+ };
+
+ function inBucket(pkg: TrackedPackage, tab: BucketTab): boolean {
+ if (pkg.canonical_status) return TAB_BUCKETS[tab].includes(pkg.canonical_status);
+ // Fallback pra pacotes sem canonical: só "in_transit" vs "delivered"
+ // funcionam de forma sensata via `is_delivered`.
+ if (tab === "delivered") return pkg.is_delivered;
+ if (tab === "in_transit") return !pkg.is_delivered;
+ return false;
+ }
+
+ let items = $state<TrackedPackage[]>([]);
+ // Mantém a contagem mais recente de arquivados pra exibir no chip mesmo
+ // quando a aba ativa está em "Ativos". Atualizada toda vez que `refresh()`
+ // roda na aba archived ou via heartbeat opcional (Sessão 9).
+ let archivedCount = $state<number | null>(null);
+ let loading = $state(true);
+ let query = $state("");
+ let tab = $state<Tab>("all");
+ let lastError = $state<string | null>(null);
+ let refreshingAll = $state(false);
+ let busyIds = $state<Record<number, boolean>>({});
+ let menuOpenId = $state<number | null>(null);
+
+ let confirmTarget = $state<TrackedPackage | null>(null);
+ let confirmRemoving = $state(false);
+
+ let showAddDialog = $state(false);
+ let addCode = $state("");
+ let addAlias = $state("");
+ let addCpf = $state("");
+ let addDetect = $state<CarrierDetection | null>(null);
+ let addDetecting = $state(false);
+ let addSubmitting = $state(false);
+ let addError = $state<string | null>(null);
+ let codeInputEl: HTMLInputElement | undefined = $state();
+
+ let toasts = $state<Toast[]>([]);
+ let toastSeq = 0;
+ let detectDebounce: number | null = null;
+
+ let unlistenStarted: UnlistenFn | null = null;
+ let unlistenDone: UnlistenFn | null = null;
+ let unlistenStatus: UnlistenFn | null = null;
+
+ const inTransitCount = $derived(items.filter((p) => inBucket(p, "in_transit")).length);
+ const awaitingCount = $derived(items.filter((p) => inBucket(p, "awaiting")).length);
+ const deliveredCount = $derived(items.filter((p) => inBucket(p, "delivered")).length);
+ const delayedCount = $derived(items.filter((p) => inBucket(p, "delayed")).length);
+
+ const filtered = $derived.by(() => {
+ let list = items;
+ // Em "archived", a listagem do backend já vem filtrada por
+ // `is_archived = 1`; client-side só aplica a busca.
+ const t = tab;
+ if (t !== "all" && t !== "archived") list = list.filter((p) => inBucket(p, t));
+ const q = query.trim().toLowerCase();
+ if (!q) return list;
+ return list.filter((p) => {
+ const hay = [p.code, p.alias ?? "", p.last_status ?? ""].join(" ").toLowerCase();
+ return hay.includes(q);
+ });
+ });
+
+ onMount(() => {
+ try {
+ const saved = localStorage.getItem(TAB_STORAGE_KEY);
+ if (
+ saved === "all" ||
+ saved === "in_transit" ||
+ saved === "awaiting" ||
+ saved === "delivered" ||
+ saved === "delayed" ||
+ saved === "archived"
+ ) {
+ tab = saved;
+ }
+ } catch {
+ // localStorage may be unavailable (private mode, etc.) — fall back to default
+ }
+ void refresh();
+ void initListeners();
+ document.addEventListener("keydown", onGlobalKey);
+ document.addEventListener("click", onGlobalClick);
+ });
+
+ function setTab(next: Tab) {
+ const prev = tab;
+ tab = next;
+ try {
+ localStorage.setItem(TAB_STORAGE_KEY, next);
+ } catch {
+ // ignore — non-fatal
+ }
+ // Trocar entre Ativos↔Arquivados muda o filter do backend; refetch.
+ if (backendFilter(prev) !== backendFilter(next)) void refresh();
+ }
+
+ onDestroy(() => {
+ unlistenStarted?.();
+ unlistenDone?.();
+ unlistenStatus?.();
+ document.removeEventListener("keydown", onGlobalKey);
+ document.removeEventListener("click", onGlobalClick);
+ });
+
+ function onGlobalKey(e: KeyboardEvent) {
+ if (e.key === "Escape") {
+ if (confirmTarget) confirmTarget = null;
+ else if (showAddDialog) closeAddDialog();
+ else if (menuOpenId != null) menuOpenId = null;
+ }
+ }
+
+ function onGlobalClick(e: MouseEvent) {
+ if (menuOpenId == null) return;
+ const t = e.target as HTMLElement | null;
+ if (t && !t.closest(".kebab-wrap")) menuOpenId = null;
+ }
+
+ async function initListeners() {
+ unlistenStarted = await onTrackerEvent("refresh-started", () => {
+ // no-op: per-card spinner already managed by busyIds when user-initiated
+ });
+ unlistenDone = await onTrackerEvent("refresh-done", async (p) => {
+ busyIds = { ...busyIds, [p.id]: false };
+ if (p.error) {
+ pushToast(
+ "error",
+ $t("tracking.toast.refresh_failed", { error: truncate(p.error, 80) }),
+ );
+ }
+ await refresh();
+ });
+ unlistenStatus = await onTrackerEvent("status-changed", async (p) => {
+ pushToast(
+ "success",
+ $t("tracking.toast.status_changed", { code: p.code, status: p.new_status }),
+ );
+ await refresh();
+ });
+ }
+
+ async function refresh() {
+ loading = true;
+ lastError = null;
+ const want = backendFilter(tab);
+ try {
+ // Quando a aba ativa é "archived", a chamada principal já devolve a
+ // contagem. Caso contrário, faço uma 2ª chamada barata só pra contar
+ // arquivados — SQLite local, lista pequena, sem custo perceptível.
+ if (want === "archived") {
+ const list = await trackerList("archived");
+ items = list;
+ archivedCount = list.length;
+ } else {
+ const [active, archived] = await Promise.all([
+ trackerList("active"),
+ trackerList("archived"),
+ ]);
+ items = active;
+ archivedCount = archived.length;
+ }
+ } catch (e) {
+ lastError = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function onRefreshAll() {
+ if (refreshingAll) return;
+ refreshingAll = true;
+ try {
+ await trackerRefreshAll();
+ await refresh();
+ pushToast("info", $t("tracking.toast.refresh_done"));
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (looksLikeOffline(msg)) {
+ pushToast("error", $t("tracking.toast.offline"));
+ } else {
+ pushToast("error", msg);
+ }
+ } finally {
+ refreshingAll = false;
+ }
+ }
+
+ function looksLikeOffline(msg: string): boolean {
+ const m = msg.toLowerCase();
+ return (
+ m.includes("no network") ||
+ m.includes("offline") ||
+ m.includes("network is unreachable") ||
+ m.includes("dns") ||
+ m.includes("name resolution") ||
+ m.includes("failed to lookup") ||
+ m.includes("connection refused") ||
+ m.includes("os error 11001")
+ );
+ }
+
+ async function onRefreshOne(id: number) {
+ if (busyIds[id]) return;
+ busyIds = { ...busyIds, [id]: true };
+ menuOpenId = null;
+ try {
+ await trackerRefresh(id);
+ await refresh();
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ busyIds = { ...busyIds, [id]: false };
+ }
+ }
+
+ function onRemove(pkg: TrackedPackage) {
+ menuOpenId = null;
+ confirmTarget = pkg;
+ }
+
+ async function onUnarchive(pkg: TrackedPackage) {
+ menuOpenId = null;
+ try {
+ await trackerSetArchived(pkg.id, false);
+ await refresh();
+ pushToast("info", $t("tracking.toast.unarchived"));
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function confirmRemove() {
+ const pkg = confirmTarget;
+ if (!pkg || confirmRemoving) return;
+ confirmRemoving = true;
+ try {
+ await trackerRemove(pkg.id);
+ confirmTarget = null;
+ await refresh();
+ pushToast("info", $t("tracking.toast.package_removed"));
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ confirmRemoving = false;
+ }
+ }
+
+ async function copyCode(code: string) {
+ try {
+ await navigator.clipboard.writeText(code);
+ pushToast("info", $t("tracking.toast.copied"));
+ } catch {
+ pushToast("error", $t("tracking.toast.copy_failed"));
+ }
+ }
+
+ async function onRename(pkg: TrackedPackage) {
+ menuOpenId = null;
+ const next = prompt($t("tracking.rename_prompt"), pkg.alias ?? "");
+ if (next == null) return;
+ const trimmed = next.trim();
+ try {
+ await trackerSetAlias(pkg.id, trimmed.length ? trimmed : null);
+ await refresh();
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function openAddDialog() {
+ addCode = "";
+ addAlias = "";
+ addCpf = "";
+ addDetect = null;
+ addError = null;
+ showAddDialog = true;
+ void tick().then(() => codeInputEl?.focus());
+ }
+
+ function closeAddDialog() {
+ showAddDialog = false;
+ if (detectDebounce != null) {
+ clearTimeout(detectDebounce);
+ detectDebounce = null;
+ }
+ }
+
+ function onCodeInput() {
+ addDetect = null;
+ if (detectDebounce != null) clearTimeout(detectDebounce);
+ const code = addCode.trim();
+ if (code.length < 4) return;
+ addDetecting = true;
+ detectDebounce = window.setTimeout(async () => {
+ try {
+ addDetect = await trackerDetectCarrier(code);
+ } catch {
+ addDetect = null;
+ } finally {
+ addDetecting = false;
+ }
+ }, 300);
+ }
+
+ async function onSubmitAdd(e: Event) {
+ e.preventDefault();
+ if (addSubmitting) return;
+ const code = addCode.trim();
+ if (!code) {
+ addError = $t("tracking.add_dialog.error_code_required");
+ return;
+ }
+ if (addDetect?.requires_cpf && !addCpf.trim()) {
+ addError = $t("tracking.add_dialog.error_cpf_required");
+ return;
+ }
+ addSubmitting = true;
+ addError = null;
+ try {
+ const alias = addAlias.trim();
+ const cpf = addCpf.trim();
+ await trackerAdd({
+ code,
+ alias: alias.length ? alias : undefined,
+ cpf: cpf.length ? cpf : undefined,
+ });
+ closeAddDialog();
+ pushToast("info", $t("tracking.toast.added"));
+ await refresh();
+ } catch (e) {
+ addError = e instanceof Error ? e.message : String(e);
+ } finally {
+ addSubmitting = false;
+ }
+ }
+
+ function pushToast(kind: Toast["kind"], text: string) {
+ const id = ++toastSeq;
+ toasts = [...toasts, { id, kind, text }];
+ setTimeout(() => {
+ toasts = toasts.filter((t) => t.id !== id);
+ }, 4500);
+ }
+
+ function dismissToast(id: number) {
+ toasts = toasts.filter((t) => t.id !== id);
+ }
+
+ function fmtDaysInTransit(s: string | null): string {
+ if (!s) return "";
+ const n = parseInt(s, 10);
+ if (!Number.isFinite(n)) return s;
+ return n === 1 ? $t("tracking.card.days_one") : $t("tracking.card.days_other", { count: n });
+ }
+
+ function fmtRel(ms: number | null): string {
+ if (!ms) return "—";
+ const diff = (Date.now() - ms) / 1000;
+ if (diff < 60) return $t("tracking.rel.now");
+ if (diff < 3600) return $t("tracking.rel.minutes", { count: Math.floor(diff / 60) });
+ if (diff < 86400) return $t("tracking.rel.hours", { count: Math.floor(diff / 3600) });
+ return new Intl.DateTimeFormat(undefined, { day: "2-digit", month: "short" }).format(new Date(ms));
+ }
+
+ function truncate(s: string, max: number): string {
+ return s.length <= max ? s : s.slice(0, max - 1) + "…";
+ }
+
+ function truncateCode(code: string): string {
+ return code.length <= 18 ? code : code.slice(0, 10) + "…" + code.slice(-4);
+ }
+</script>
+
+<section class="tracking-page">
+ <header class="head">
+ <div class="head-text">
+ <h1>{$t("tracking.title")}</h1>
+ <p class="subtitle">
+ {#if items.length > 0}
+ {$t("tracking.subtitle_summary", {
+ count: items.length,
+ in_transit: items.filter((p) => !p.is_delivered).length,
+ })}
+ {:else}
+ {$t("tracking.subtitle_empty")}
+ {/if}
+ </p>
+ </div>
+ <div class="head-actions">
+ <button
+ type="button"
+ class="privacy-btn"
+ onclick={togglePrivacy}
+ aria-pressed={privacyEnabled()}
+ title={privacyEnabled() ? $t("tracking.privacy_show_title") : $t("tracking.privacy_hide_title")}
+ >
+ {#if privacyEnabled()}
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
+ <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
+ <path d="M14.12 14.12A3 3 0 1 1 9.88 9.88"/>
+ <line x1="1" y1="1" x2="23" y2="23"/>
+ </svg>
+ {:else}
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
+ <circle cx="12" cy="12" r="3"/>
+ </svg>
+ {/if}
+ <span>{$t("tracking.privacy_button")}</span>
+ </button>
+ <button
+ type="button"
+ class="btn-secondary"
+ onclick={onRefreshAll}
+ disabled={refreshingAll || items.length === 0}
+ title={$t("tracking.refresh_all_title")}
+ >
+ {refreshingAll ? $t("tracking.refresh_all_busy") : $t("tracking.refresh_all")}
+ </button>
+ <a
+ class="settings-link"
+ href="/misc/tracking/settings"
+ title={$t("tracking.settings.title")}
+ aria-label={$t("tracking.settings.title")}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="12" cy="12" r="3" />
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h0a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h0a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v0a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
+ </svg>
+ </a>
+ <button type="button" class="btn-primary" onclick={openAddDialog}>{$t("tracking.add_button")}</button>
+ </div>
+ </header>
+
+ {#if items.length > 0}
+ <input
+ type="search"
+ class="search-input"
+ placeholder={$t("tracking.search_placeholder")}
+ bind:value={query}
+ />
+ <div class="kind-chips" role="tablist" aria-label={$t("tracking.title")}>
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "all"}
+ role="tab"
+ aria-selected={tab === "all"}
+ onclick={() => setTab("all")}
+ >
+ {$t("tracking.tab.all")} ({items.length})
+ </button>
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "in_transit"}
+ role="tab"
+ aria-selected={tab === "in_transit"}
+ onclick={() => setTab("in_transit")}
+ >
+ {$t("tracking.tab.in_transit")} ({inTransitCount})
+ </button>
+ {#if awaitingCount > 0}
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "awaiting"}
+ role="tab"
+ aria-selected={tab === "awaiting"}
+ onclick={() => setTab("awaiting")}
+ >
+ {$t("tracking.tab.awaiting")} ({awaitingCount})
+ </button>
+ {/if}
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "delivered"}
+ role="tab"
+ aria-selected={tab === "delivered"}
+ onclick={() => setTab("delivered")}
+ >
+ {$t("tracking.tab.delivered")} ({deliveredCount})
+ </button>
+ {#if delayedCount > 0}
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "delayed"}
+ role="tab"
+ aria-selected={tab === "delayed"}
+ onclick={() => setTab("delayed")}
+ >
+ {$t("tracking.tab.delayed")} ({delayedCount})
+ </button>
+ {/if}
+ {#if archivedCount != null && archivedCount > 0}
+ <button
+ type="button"
+ class="chip"
+ class:active={tab === "archived"}
+ role="tab"
+ aria-selected={tab === "archived"}
+ onclick={() => setTab("archived")}
+ >
+ {$t("tracking.tab.archived")} ({archivedCount})
+ </button>
+ {/if}
+ </div>
+ {/if}
+
+ {#if lastError}
+ <div class="error" role="alert"><strong>{$t("tracking.error_prefix")}:</strong> {lastError}</div>
+ {/if}
+
+ {#if loading}
+ <p class="empty">{$t("tracking.loading")}</p>
+ {:else if items.length === 0}
+ <div class="empty-state">
+ <div class="empty-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
+ <path d="M3.27 6.96 12 12.01l8.73-5.05" />
+ <path d="M12 22.08V12" />
+ </svg>
+ </div>
+ <h2 class="empty-title">{$t("tracking.empty.none_title")}</h2>
+ <p class="empty-desc">{$t("tracking.empty.none_desc")}</p>
+ <button type="button" class="btn-primary" onclick={openAddDialog}>{$t("tracking.empty.none_cta")}</button>
+ </div>
+ {:else if filtered.length === 0}
+ {#if query.trim()}
+ <p class="empty">{$t("tracking.empty.search", { query })}</p>
+ {:else if tab === "in_transit"}
+ <p class="empty">{$t("tracking.empty.in_transit")}</p>
+ {:else if tab === "awaiting"}
+ <p class="empty">{$t("tracking.empty.awaiting")}</p>
+ {:else if tab === "delivered"}
+ <p class="empty">{$t("tracking.empty.delivered")}</p>
+ {:else if tab === "delayed"}
+ <p class="empty">{$t("tracking.empty.delayed")}</p>
+ {:else if tab === "archived"}
+ <p class="empty">{$t("tracking.empty.archived")}</p>
+ {:else}
+ <p class="empty">{$t("tracking.empty.nothing")}</p>
+ {/if}
+ {:else}
+ <div class="grid">
+ {#each filtered as pkg (pkg.id)}
+ {@const icon = getCarrierIcon(pkg.carrier)}
+ {@const carrierLabel = icon.labelKey ? $t(icon.labelKey) : icon.label}
+ {@const status = getStatusIcon(pkg.canonical_status)}
+ {@const statusLabel = $t(status.labelKey)}
+ {@const title = pkg.alias?.trim() || maskCode(pkg.code)}
+ <article class="card" class:delivered={pkg.is_delivered} class:archived={pkg.is_archived}>
+ {#if pkg.is_archived}
+ <span class="archived-badge" aria-label={$t("tracking.card.archived_label")}>{$t("tracking.card.archived_label")}</span>
+ {/if}
+ <a class="card-link" href="/misc/tracking/{pkg.id}" aria-label={title}>
+ <div class="card-head">
+ <div class="carrier-icon" style="--carrier-color: {icon.color}" title={carrierLabel} aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <path d={icon.svgPath} />
+ </svg>
+ </div>
+ <div class="card-titles">
+ <span class="card-title" title={title}>{title}</span>
+ {#if pkg.alias?.trim()}
+ <span class="card-code mono" title={maskCode(pkg.code)}>{truncateCode(maskCode(pkg.code))}</span>
+ {:else}
+ <span class="card-code mono carrier-label">{carrierLabel}</span>
+ {/if}
+ </div>
+ {#if pkg.canonical_status}
+ <span
+ class="status-icon"
+ style="--status-color: {status.color}"
+ title={statusLabel}
+ aria-label={statusLabel}
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d={status.svgPath} />
+ </svg>
+ </span>
+ {/if}
+ </div>
+
+ <div class="card-body">
+ {#if pkg.canonical_status}
+ <span class="status-badge" style="--status-color: {status.color}">
+ {statusLabel}
+ </span>
+ {:else if pkg.last_status}
+ <span class="status-badge">{pkg.last_status}</span>
+ {:else}
+ <span class="status-badge pending">{$t("tracking.card.awaiting_first")}</span>
+ {/if}
+ </div>
+
+ <div class="card-foot">
+ <span class="meta-bit">
+ {#if pkg.is_delivered}
+ {$t("tracking.card.delivered")}
+ {:else if pkg.days_in_transit}
+ {fmtDaysInTransit(pkg.days_in_transit)}
+ {:else}
+ {$t("tracking.card.no_events")}
+ {/if}
+ </span>
+ <span class="meta-bit">{fmtRel(pkg.last_event_at_ms ?? pkg.updated_at_ms)}</span>
+ </div>
+ </a>
+
+ <div class="kebab-wrap">
+ <button
+ type="button"
+ class="kebab"
+ aria-label={$t("tracking.menu.refresh")}
+ aria-haspopup="menu"
+ aria-expanded={menuOpenId === pkg.id}
+ onclick={(e) => {
+ e.stopPropagation();
+ menuOpenId = menuOpenId === pkg.id ? null : pkg.id;
+ }}
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>
+ </button>
+ {#if menuOpenId === pkg.id}
+ <div class="menu" role="menu">
+ {#if !pkg.is_archived}
+ <button type="button" class="menu-item" role="menuitem" onclick={() => onRefreshOne(pkg.id)} disabled={busyIds[pkg.id]}>
+ {busyIds[pkg.id] ? $t("tracking.menu.refreshing") : $t("tracking.menu.refresh")}
+ </button>
+ {/if}
+ <button type="button" class="menu-item" role="menuitem" onclick={() => { menuOpenId = null; void copyCode(pkg.code); }}>
+ {$t("tracking.menu.copy_code")}
+ </button>
+ <button type="button" class="menu-item" role="menuitem" onclick={() => onRename(pkg)}>
+ {$t("tracking.menu.rename")}
+ </button>
+ {#if pkg.is_archived}
+ <button type="button" class="menu-item" role="menuitem" onclick={() => onUnarchive(pkg)}>
+ {$t("tracking.menu.unarchive")}
+ </button>
+ {/if}
+ <button type="button" class="menu-item danger" role="menuitem" onclick={() => onRemove(pkg)}>
+ {$t("tracking.menu.remove")}
+ </button>
+ </div>
+ {/if}
+ </div>
+
+ {#if busyIds[pkg.id]}
+ <div class="card-busy" aria-hidden="true"></div>
+ {/if}
+ </article>
+ {/each}
+ </div>
+ {/if}
+</section>
+
+{#if showAddDialog}
+ <div
+ class="dialog-overlay"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="add-dialog-title"
+ onclick={(e) => { if (e.target === e.currentTarget) closeAddDialog(); }}
+ >
+ <form class="dialog" onsubmit={onSubmitAdd}>
+ <header class="dialog-head">
+ <h2 id="add-dialog-title">{$t("tracking.add_dialog.title")}</h2>
+ <button type="button" class="dialog-close" onclick={closeAddDialog} aria-label={$t("tracking.add_dialog.close")}>
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18 M6 6l12 12"/></svg>
+ </button>
+ </header>
+
+ <div class="dialog-body">
+ <label class="field">
+ <span class="field-label">{$t("tracking.add_dialog.code_label")}</span>
+ <input
+ bind:this={codeInputEl}
+ type="text"
+ class="field-input mono"
+ placeholder={$t("tracking.add_dialog.code_placeholder")}
+ bind:value={addCode}
+ oninput={onCodeInput}
+ autocomplete="off"
+ spellcheck="false"
+ required
+ />
+ {#if addDetecting}
+ <span class="field-hint">{$t("tracking.add_dialog.detecting")}</span>
+ {:else if addDetect}
+ <span class="field-hint">
+ {$t("tracking.add_dialog.detected", { carrier: addDetect.display_name })}
+ {#if addDetect.requires_cpf}
+ {$t("tracking.add_dialog.requires_cpf_suffix")}
+ {/if}
+ </span>
+ {/if}
+ </label>
+
+ <label class="field">
+ <span class="field-label">{$t("tracking.add_dialog.alias_label")}</span>
+ <input
+ type="text"
+ class="field-input"
+ placeholder={$t("tracking.add_dialog.alias_placeholder")}
+ bind:value={addAlias}
+ autocomplete="off"
+ />
+ </label>
+
+ {#if addDetect?.requires_cpf}
+ <label class="field">
+ <span class="field-label">{$t("tracking.add_dialog.cpf_label")}</span>
+ <input
+ type="text"
+ class="field-input mono"
+ placeholder={$t("tracking.add_dialog.cpf_placeholder")}
+ bind:value={addCpf}
+ autocomplete="off"
+ required
+ />
+ <span class="field-hint">{$t("tracking.add_dialog.cpf_hint")}</span>
+ </label>
+ {/if}
+
+ {#if addError}
+ <div class="error" role="alert">{addError}</div>
+ {/if}
+ </div>
+
+ <footer class="dialog-foot">
+ <button type="button" class="btn-secondary" onclick={closeAddDialog} disabled={addSubmitting}>
+ {$t("tracking.add_dialog.cancel")}
+ </button>
+ <button type="submit" class="btn-primary" disabled={addSubmitting || !addCode.trim()}>
+ {addSubmitting ? $t("tracking.add_dialog.submitting") : $t("tracking.add_dialog.submit")}
+ </button>
+ </footer>
+ </form>
+ </div>
+{/if}
+
+{#if confirmTarget}
+ {@const target = confirmTarget}
+ <div
+ class="dialog-overlay"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="confirm-remove-title"
+ onclick={(e) => { if (e.target === e.currentTarget && !confirmRemoving) confirmTarget = null; }}
+ >
+ <div class="dialog confirm-dialog">
+ <header class="dialog-head">
+ <h2 id="confirm-remove-title">{$t("tracking.remove_dialog.title")}</h2>
+ <button
+ type="button"
+ class="dialog-close"
+ onclick={() => (confirmTarget = null)}
+ disabled={confirmRemoving}
+ aria-label={$t("tracking.remove_dialog.close")}
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18 M6 6l12 12"/></svg>
+ </button>
+ </header>
+ <div class="dialog-body">
+ <p class="confirm-msg">
+ {$t("tracking.remove_dialog.question", { name: target.alias?.trim() || maskCode(target.code) })}
+ </p>
+ <p class="confirm-sub">{$t("tracking.remove_dialog.sub")}</p>
+ </div>
+ <footer class="dialog-foot">
+ <button type="button" class="btn-secondary" onclick={() => (confirmTarget = null)} disabled={confirmRemoving}>
+ {$t("tracking.remove_dialog.cancel")}
+ </button>
+ <button type="button" class="btn-danger" onclick={confirmRemove} disabled={confirmRemoving}>
+ {confirmRemoving ? $t("tracking.remove_dialog.confirming") : $t("tracking.remove_dialog.confirm")}
+ </button>
+ </footer>
+ </div>
+ </div>
+{/if}
+
+{#if toasts.length > 0}
+ <div class="toast-stack" aria-live="polite" aria-atomic="false">
+ {#each toasts as t (t.id)}
+ <button
+ type="button"
+ class="toast toast-{t.kind}"
+ onclick={() => dismissToast(t.id)}
+ >
+ {t.text}
+ </button>
+ {/each}
+ </div>
+{/if}
+
+<style>
+ .tracking-page {
+ display: flex;
+ flex-direction: column;
+ gap: calc(var(--padding) * 2);
+ width: 100%;
+ max-width: 1100px;
+ margin-inline: auto;
+ padding: 16px 20px 80px;
+ }
+
+ .head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ flex-wrap: wrap;
+ }
+ .head-text {
+ min-width: 0;
+ }
+ .head h1 {
+ margin: 0 0 4px;
+ font-size: 22px;
+ font-weight: 500;
+ letter-spacing: -0.5px;
+ color: var(--secondary);
+ }
+ .subtitle {
+ margin: 0;
+ font-size: 13px;
+ color: var(--tertiary);
+ }
+ .head-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+
+ .search-input {
+ width: 100%;
+ padding: 9px 12px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 13px;
+ font-family: inherit;
+ }
+ .search-input:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+ .kind-chips {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .chip {
+ padding: 5px 12px;
+ border: 1px solid var(--input-border);
+ border-radius: 999px;
+ background: var(--surface);
+ color: var(--tertiary);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ transition: border-color 120ms ease, color 120ms ease, background 120ms ease;
+ }
+ .chip:hover {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .chip.active {
+ border-color: var(--accent);
+ color: var(--accent);
+ background: color-mix(in oklab, var(--accent) 12%, var(--surface));
+ }
+
+ .error {
+ padding: 10px 14px;
+ border-radius: var(--border-radius);
+ background: color-mix(in oklab, var(--danger) 14%, transparent);
+ color: var(--danger);
+ font-size: 13px;
+ }
+
+ .empty {
+ color: var(--tertiary);
+ font-size: 13px;
+ margin: 0;
+ padding: 20px 0;
+ }
+
+ .empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ padding: 48px 20px;
+ text-align: center;
+ border: 1px dashed var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ }
+ .empty-icon {
+ color: var(--accent);
+ opacity: 0.7;
+ margin-bottom: 4px;
+ }
+ .empty-title {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .empty-desc {
+ margin: 0 0 12px;
+ font-size: 13px;
+ color: var(--tertiary);
+ max-width: 320px;
+ }
+
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 12px;
+ }
+
+ .card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ transition: border-color 150ms ease, transform 100ms ease;
+ }
+ .card:hover {
+ border-color: var(--accent);
+ transform: translateY(-1px);
+ }
+ .card.delivered {
+ opacity: 0.78;
+ }
+ .card.archived {
+ opacity: 0.6;
+ background: color-mix(in oklab, var(--surface) 92%, var(--tertiary));
+ }
+ .card.archived:hover {
+ opacity: 0.85;
+ }
+ .archived-badge {
+ position: absolute;
+ bottom: 10px;
+ right: 10px;
+ z-index: 2;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--tertiary) 24%, transparent);
+ color: var(--tertiary);
+ font-size: 10px;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ pointer-events: none;
+ }
+
+ .card-link {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 16px;
+ text-decoration: none;
+ color: inherit;
+ min-width: 0;
+ }
+
+ .card-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .carrier-icon {
+ flex-shrink: 0;
+ width: 36px;
+ height: 36px;
+ display: grid;
+ place-items: center;
+ border-radius: 8px;
+ background: color-mix(in oklab, var(--carrier-color) 16%, transparent);
+ color: var(--carrier-color);
+ }
+ .card-titles {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .card-title {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--secondary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .card-code {
+ font-size: 11px;
+ color: var(--tertiary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .carrier-label {
+ font-family: inherit;
+ }
+ .status-icon {
+ flex-shrink: 0;
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: color-mix(in oklab, var(--status-color) 18%, transparent);
+ color: var(--status-color);
+ }
+
+ .card-body {
+ display: flex;
+ align-items: center;
+ }
+ .status-badge {
+ --status-color: var(--accent);
+ display: inline-block;
+ padding: 4px 9px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--status-color) 14%, transparent);
+ color: var(--status-color);
+ font-size: 11px;
+ font-weight: 500;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .status-badge.pending {
+ background: color-mix(in oklab, var(--input-border) 50%, transparent);
+ color: var(--tertiary);
+ }
+
+ .card-foot {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 11px;
+ color: var(--tertiary);
+ }
+ .meta-bit {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .kebab-wrap {
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ }
+ .kebab {
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border: none;
+ background: transparent;
+ color: var(--tertiary);
+ cursor: pointer;
+ border-radius: 6px;
+ }
+ .kebab:hover {
+ background: color-mix(in oklab, var(--input-border) 50%, transparent);
+ color: var(--secondary);
+ }
+ .menu {
+ position: absolute;
+ top: 30px;
+ right: 0;
+ min-width: 140px;
+ background: var(--surface);
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ box-shadow: 0 4px 18px color-mix(in oklab, black 18%, transparent);
+ display: flex;
+ flex-direction: column;
+ padding: 4px;
+ z-index: 10;
+ }
+ .menu-item {
+ padding: 7px 10px;
+ background: transparent;
+ border: none;
+ text-align: left;
+ color: var(--secondary);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ border-radius: 4px;
+ }
+ .menu-item:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--accent) 12%, transparent);
+ }
+ .menu-item:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .menu-item.danger {
+ color: var(--danger);
+ }
+ .menu-item.danger:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--danger) 12%, transparent);
+ }
+
+ .card-busy {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background: color-mix(in oklab, var(--accent) 5%, transparent);
+ border-radius: var(--border-radius);
+ animation: pulse 1.2s ease-in-out infinite;
+ }
+ @keyframes pulse {
+ 0%, 100% { opacity: 0.3; }
+ 50% { opacity: 0.7; }
+ }
+
+ .settings-link {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ border-radius: 999px;
+ border: 1px solid var(--input-border);
+ background: var(--surface);
+ color: var(--tertiary);
+ text-decoration: none;
+ cursor: pointer;
+ }
+ .settings-link:hover {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+
+ .privacy-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 6px 10px;
+ border-radius: 999px;
+ border: 1px solid var(--input-border);
+ background: var(--surface);
+ color: var(--tertiary);
+ font-size: 11px;
+ font-family: inherit;
+ font-weight: 500;
+ cursor: pointer;
+ }
+ .privacy-btn:hover {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .privacy-btn[aria-pressed="true"] {
+ background: color-mix(in oklab, var(--accent) 14%, transparent);
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+
+ .btn-primary,
+ .btn-secondary,
+ .btn-danger {
+ padding: 7px 14px;
+ border-radius: var(--border-radius);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ font-weight: 500;
+ }
+ .btn-primary {
+ border: 1px solid var(--accent);
+ background: var(--accent);
+ color: var(--on-accent);
+ }
+ .btn-primary:hover:not(:disabled) {
+ filter: brightness(1.05);
+ }
+ .btn-primary:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .btn-secondary {
+ border: 1px solid var(--input-border);
+ background: transparent;
+ color: var(--secondary);
+ }
+ .btn-secondary:hover:not(:disabled) {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .btn-secondary:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .btn-danger {
+ border: 1px solid color-mix(in oklab, var(--danger) 60%, var(--input-border));
+ background: transparent;
+ color: var(--danger);
+ }
+ .btn-danger:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--danger) 14%, transparent);
+ }
+ .btn-danger:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .confirm-dialog {
+ max-width: 380px;
+ }
+ .confirm-msg {
+ margin: 0 0 6px;
+ font-size: 14px;
+ color: var(--secondary);
+ line-height: 1.4;
+ }
+ .confirm-sub {
+ margin: 0;
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+
+ .dialog-overlay {
+ position: fixed;
+ inset: 0;
+ background: color-mix(in oklab, black 50%, transparent);
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ z-index: 100;
+ }
+ .dialog {
+ width: 100%;
+ max-width: 440px;
+ background: var(--surface);
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ display: flex;
+ flex-direction: column;
+ max-height: calc(100vh - 32px);
+ }
+ .dialog-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--input-border);
+ }
+ .dialog-head h2 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .dialog-close {
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border: none;
+ background: transparent;
+ color: var(--tertiary);
+ cursor: pointer;
+ border-radius: 6px;
+ }
+ .dialog-close:hover {
+ background: color-mix(in oklab, var(--input-border) 50%, transparent);
+ color: var(--secondary);
+ }
+ .dialog-body {
+ padding: 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ overflow-y: auto;
+ }
+ .dialog-foot {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 18px;
+ border-top: 1px solid var(--input-border);
+ }
+
+ .field {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ }
+ .field-label {
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+ .field-input {
+ width: 100%;
+ padding: 8px 11px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 13px;
+ font-family: inherit;
+ }
+ .field-input:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+ .field-hint {
+ font-size: 11px;
+ color: var(--tertiary);
+ }
+
+ .toast-stack {
+ position: fixed;
+ top: 16px;
+ right: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ z-index: 200;
+ pointer-events: none;
+ }
+ .toast {
+ pointer-events: auto;
+ padding: 10px 14px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 12px;
+ font-family: inherit;
+ text-align: left;
+ box-shadow: 0 4px 14px color-mix(in oklab, black 15%, transparent);
+ max-width: 320px;
+ cursor: pointer;
+ animation: toast-in 180ms ease-out;
+ }
+ .toast-success {
+ border-color: color-mix(in oklab, var(--success) 50%, var(--input-border));
+ }
+ .toast-error {
+ border-color: color-mix(in oklab, var(--danger) 50%, var(--input-border));
+ color: var(--danger);
+ }
+ @keyframes toast-in {
+ from { transform: translateY(-6px); opacity: 0; }
+ to { transform: translateY(0); opacity: 1; }
+ }
+
+ .mono {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-variant-numeric: tabular-nums;
+ }
+
+ @media (max-width: 480px) {
+ .head {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ .head-actions {
+ justify-content: stretch;
+ }
+ .head-actions .btn-primary,
+ .head-actions .btn-secondary {
+ flex: 1;
+ }
+ .grid {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .card {
+ transition: none;
+ }
+ .card:hover {
+ transform: none;
+ }
+ .card-busy {
+ animation: none;
+ }
+ .toast {
+ animation: none;
+ }
+ }
+</style>
diff --git a/src/routes/misc/tracking/[id]/+page.svelte b/src/routes/misc/tracking/[id]/+page.svelte
new file mode 100644
index 00000000..b1eae876
--- /dev/null
+++ b/src/routes/misc/tracking/[id]/+page.svelte
@@ -0,0 +1,1343 @@
+<script lang="ts">
+ import { onDestroy, onMount } from "svelte";
+ import { goto } from "$app/navigation";
+ import { page } from "$app/state";
+ import type { UnlistenFn } from "@tauri-apps/api/event";
+ import { t } from "$lib/i18n";
+ import {
+ onTrackerEvent,
+ trackerDismissArchivePrompt,
+ trackerGet,
+ trackerRefresh,
+ trackerRemove,
+ trackerSetAlias,
+ trackerSetArchived,
+ trackerSetCpf,
+ type TrackedPackage,
+ type TrackingEvent,
+ } from "$lib/tracker-bridge";
+ import { getCarrierIcon, getCarrierRoute } from "$lib/tracker-carrier-icons";
+ import { classifyEvent, getStatusIcon } from "$lib/tracker-status-icons";
+ import { maskCode, privacyEnabled, togglePrivacy } from "$lib/tracker-privacy.svelte";
+
+ type Toast = { id: number; kind: "info" | "success" | "error"; text: string };
+
+ const id = $derived(parseInt(page.params.id ?? "", 10));
+
+ let pkg = $state<TrackedPackage | null>(null);
+ let events = $state<TrackingEvent[]>([]);
+ let loading = $state(true);
+ let notFound = $state(false);
+ let lastError = $state<string | null>(null);
+ let refreshing = $state(false);
+
+ let showCpfDialog = $state(false);
+ let cpfValue = $state("");
+ let cpfSubmitting = $state(false);
+ let cpfError = $state<string | null>(null);
+
+ let showRemoveConfirm = $state(false);
+ let removing = $state(false);
+
+ let toasts = $state<Toast[]>([]);
+ let toastSeq = 0;
+
+ let unlistenStatus: UnlistenFn | null = null;
+ let unlistenDone: UnlistenFn | null = null;
+
+ $effect(() => {
+ if (Number.isFinite(id)) {
+ void load(id);
+ } else {
+ notFound = true;
+ loading = false;
+ }
+ });
+
+ onMount(async () => {
+ document.addEventListener("keydown", onGlobalKey);
+ unlistenStatus = await onTrackerEvent("status-changed", async (p) => {
+ if (p.id !== id) return;
+ pushToast("success", p.new_status);
+ await load(id);
+ });
+ unlistenDone = await onTrackerEvent("refresh-done", async (p) => {
+ if (p.id !== id) return;
+ refreshing = false;
+ if (p.error) {
+ lastError = p.error;
+ } else {
+ lastError = null;
+ await load(id);
+ }
+ });
+ });
+
+ onDestroy(() => {
+ document.removeEventListener("keydown", onGlobalKey);
+ unlistenStatus?.();
+ unlistenDone?.();
+ });
+
+ function onGlobalKey(e: KeyboardEvent) {
+ if (e.key !== "Escape") return;
+ if (showRemoveConfirm && !removing) showRemoveConfirm = false;
+ else if (showCpfDialog && !cpfSubmitting) showCpfDialog = false;
+ }
+
+ async function load(packageId: number) {
+ if (!Number.isFinite(packageId)) {
+ notFound = true;
+ loading = false;
+ return;
+ }
+ try {
+ const res = await trackerGet(packageId);
+ if (packageId !== id) return;
+ if (!res) {
+ notFound = true;
+ pkg = null;
+ events = [];
+ } else {
+ notFound = false;
+ pkg = res.package;
+ events = res.events;
+ }
+ } catch (e) {
+ lastError = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function onRefresh() {
+ if (!pkg || refreshing) return;
+ refreshing = true;
+ lastError = null;
+ try {
+ await trackerRefresh(pkg.id);
+ await load(pkg.id);
+ } catch (e) {
+ lastError = e instanceof Error ? e.message : String(e);
+ pushToast("error", lastError);
+ } finally {
+ refreshing = false;
+ }
+ }
+
+ async function onRename() {
+ if (!pkg) return;
+ const next = prompt($t("tracking.rename_prompt"), pkg.alias ?? "");
+ if (next == null) return;
+ const trimmed = next.trim();
+ try {
+ await trackerSetAlias(pkg.id, trimmed.length ? trimmed : null);
+ await load(pkg.id);
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function onRemove() {
+ if (!pkg) return;
+ showRemoveConfirm = true;
+ }
+
+ async function confirmRemove() {
+ if (!pkg || removing) return;
+ removing = true;
+ try {
+ await trackerRemove(pkg.id);
+ showRemoveConfirm = false;
+ pushToast("info", $t("tracking.toast.package_removed"));
+ await goto("/misc/tracking");
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ removing = false;
+ }
+ }
+
+ async function onArchive() {
+ if (!pkg) return;
+ try {
+ await trackerSetArchived(pkg.id, true);
+ pushToast("info", $t("tracking.toast.archived"));
+ await goto("/misc/tracking");
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function onUnarchive() {
+ if (!pkg) return;
+ try {
+ await trackerSetArchived(pkg.id, false);
+ await load(pkg.id);
+ pushToast("info", $t("tracking.toast.unarchived"));
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function onDismissArchivePrompt() {
+ if (!pkg) return;
+ try {
+ await trackerDismissArchivePrompt(pkg.id);
+ // Atualiza só a flag local — economiza um roundtrip e mantém o feedback
+ // visual imediato (o card amarelo some).
+ pkg = { ...pkg, archive_prompt_dismissed: true };
+ } catch (e) {
+ pushToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function openCpfDialog() {
+ if (!pkg) return;
+ cpfValue = pkg.cpf ?? "";
+ cpfError = null;
+ showCpfDialog = true;
+ }
+
+ async function submitCpf(e: Event) {
+ e.preventDefault();
+ if (!pkg || cpfSubmitting) return;
+ cpfSubmitting = true;
+ cpfError = null;
+ try {
+ const trimmed = cpfValue.trim();
+ await trackerSetCpf(pkg.id, trimmed.length ? trimmed : null);
+ showCpfDialog = false;
+ await load(pkg.id);
+ pushToast("info", $t("tracking.toast.cpf_updated"));
+ } catch (err) {
+ cpfError = err instanceof Error ? err.message : String(err);
+ } finally {
+ cpfSubmitting = false;
+ }
+ }
+
+ async function copyCode() {
+ if (!pkg) return;
+ try {
+ await navigator.clipboard.writeText(pkg.code);
+ pushToast("info", $t("tracking.toast.copied"));
+ } catch {
+ pushToast("error", $t("tracking.toast.copy_failed"));
+ }
+ }
+
+ function pushToast(kind: Toast["kind"], text: string) {
+ const tid = ++toastSeq;
+ toasts = [...toasts, { id: tid, kind, text }];
+ setTimeout(() => {
+ toasts = toasts.filter((t) => t.id !== tid);
+ }, 4500);
+ }
+
+ function dismissToast(tid: number) {
+ toasts = toasts.filter((t) => t.id !== tid);
+ }
+
+ function maskCpf(cpf: string | null): string {
+ if (!cpf) return "—";
+ const digits = cpf.replace(/\D/g, "");
+ if (digits.length !== 11) return cpf;
+ return `***.***.${digits.slice(6, 9)}-${digits.slice(9)}`;
+ }
+
+ function fmtDate(d: string | null | undefined): string {
+ if (!d) return "—";
+ const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(d);
+ if (iso) return `${iso[3]}/${iso[2]}/${iso[1]}`;
+ return d;
+ }
+
+ function fmtRel(ms: number | null): string {
+ if (!ms) return "—";
+ const diff = (Date.now() - ms) / 1000;
+ if (diff < 60) return $t("tracking.rel.now");
+ if (diff < 3600) return $t("tracking.rel.minutes", { count: Math.floor(diff / 60) });
+ if (diff < 86400) return $t("tracking.rel.hours", { count: Math.floor(diff / 3600) });
+ return new Intl.DateTimeFormat(undefined, {
+ day: "2-digit",
+ month: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(ms));
+ }
+
+ function fmtDaysPill(s: string | null): string {
+ if (!s) return "";
+ const n = parseInt(s, 10);
+ if (!Number.isFinite(n)) return s;
+ return n === 1
+ ? $t("tracking.detail.days_one_pill")
+ : $t("tracking.detail.days_other_pill", { count: n });
+ }
+
+ function truncate(s: string, max: number): string {
+ return s.length <= max ? s : s.slice(0, max - 1) + "…";
+ }
+</script>
+
+<section class="detail">
+ <a class="back" href="/misc/tracking">{$t("tracking.detail.back")}</a>
+
+ {#if loading}
+ <div class="skeleton" aria-hidden="true">
+ <div class="sk-row sk-lg"></div>
+ <div class="sk-row sk-md"></div>
+ <div class="sk-card"></div>
+ <div class="sk-card"></div>
+ <div class="sk-card"></div>
+ </div>
+ {:else if notFound || !pkg}
+ <div class="empty-card">
+ <h1>{$t("tracking.detail.not_found_title")}</h1>
+ <p>{$t("tracking.detail.not_found_body")}</p>
+ <a class="btn-primary" href="/misc/tracking">{$t("tracking.detail.not_found_back")}</a>
+ </div>
+ {:else}
+ {@const icon = getCarrierIcon(pkg.carrier)}
+ {@const carrierLabel = icon.labelKey ? $t(icon.labelKey) : icon.label}
+ {@const status = getStatusIcon(pkg.canonical_status)}
+ {@const statusLabel = $t(status.labelKey)}
+ {@const route = getCarrierRoute(pkg.carrier)}
+ {@const title = pkg.alias?.trim() || pkg.code}
+ {@const postedDate = events.length > 0 ? events[events.length - 1].date : null}
+ {@const hasAlias = !!pkg.alias?.trim()}
+
+ <header class="hero">
+ <div
+ class="carrier-icon-lg"
+ style="--carrier-color: {icon.color}"
+ title={carrierLabel}
+ aria-hidden="true"
+ >
+ <svg
+ viewBox="0 0 24 24"
+ width="30"
+ height="30"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <path d={icon.svgPath} />
+ </svg>
+ </div>
+ {#if pkg.canonical_status}
+ <div
+ class="status-icon-lg"
+ style="--status-color: {status.color}"
+ title={statusLabel}
+ aria-label={statusLabel}
+ >
+ <svg
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.7"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d={status.svgPath} />
+ </svg>
+ </div>
+ {/if}
+ <div class="hero-text">
+ <h1>{hasAlias ? title : maskCode(pkg.code)}</h1>
+ <p class="hero-meta">
+ <span class="carrier-name" style="color: {icon.color}">{carrierLabel}</span>
+ {#if hasAlias}
+ <span class="dot-sep">·</span>
+ <span class="mono small">{maskCode(pkg.code)}</span>
+ {/if}
+ </p>
+ </div>
+ <button
+ type="button"
+ class="privacy-btn"
+ onclick={togglePrivacy}
+ aria-pressed={privacyEnabled()}
+ title={privacyEnabled() ? $t("tracking.privacy_show_title") : $t("tracking.privacy_hide_title")}
+ >
+ {#if privacyEnabled()}
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
+ <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
+ <path d="M14.12 14.12A3 3 0 1 1 9.88 9.88"/>
+ <line x1="1" y1="1" x2="23" y2="23"/>
+ </svg>
+ {:else}
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
+ <circle cx="12" cy="12" r="3"/>
+ </svg>
+ {/if}
+ <span>{$t("tracking.privacy_button")}</span>
+ </button>
+ </header>
+
+ <div class="status-row">
+ {#if pkg.canonical_status}
+ <span
+ class="status-badge-big"
+ class:delivered={pkg.is_delivered}
+ style="--status-color: {status.color}"
+ >
+ <span class="status-badge-label">{statusLabel}</span>
+ {#if pkg.last_status && pkg.last_status.toLowerCase() !== statusLabel.toLowerCase()}
+ <span class="status-badge-raw">· {pkg.last_status}</span>
+ {/if}
+ </span>
+ {:else}
+ <span class="status-badge-big" class:delivered={pkg.is_delivered}>
+ {pkg.last_status ?? $t("tracking.detail.awaiting_first")}
+ </span>
+ {/if}
+ {#if !pkg.is_delivered && pkg.days_in_transit}
+ <span class="days-pill">{fmtDaysPill(pkg.days_in_transit)}</span>
+ {/if}
+ {#if pkg.is_delivered}
+ <span class="days-pill delivered-pill">{$t("tracking.detail.delivered_pill")}</span>
+ {/if}
+ {#if pkg.is_archived}
+ <span class="days-pill archived-pill">{$t("tracking.detail.archived_pill")}</span>
+ {/if}
+ </div>
+
+ {#if pkg.canonical_status === "delivered" && !pkg.is_archived && !pkg.archive_prompt_dismissed}
+ <aside class="archive-prompt" role="note" aria-label={$t("tracking.archive_prompt.title")}>
+ <div class="archive-prompt-text">
+ <h3>{$t("tracking.archive_prompt.title")}</h3>
+ <p>{$t("tracking.archive_prompt.body")}</p>
+ </div>
+ <div class="archive-prompt-actions">
+ <button type="button" class="btn-secondary" onclick={onDismissArchivePrompt}>
+ {$t("tracking.archive_prompt.keep")}
+ </button>
+ <button type="button" class="btn-primary" onclick={onArchive}>
+ {$t("tracking.archive_prompt.archive")}
+ </button>
+ </div>
+ </aside>
+ {/if}
+
+ {#if lastError}
+ <div class="warn" role="alert">
+ <div>
+ <strong>{$t("tracking.detail.refresh_failed_title")}</strong>
+ <span class="warn-msg">{truncate(lastError, 140)}</span>
+ </div>
+ <button type="button" class="warn-btn" onclick={onRefresh} disabled={refreshing}>
+ {$t("tracking.detail.retry")}
+ </button>
+ </div>
+ {/if}
+
+ <dl class="meta">
+ <div class="meta-row">
+ <dt>{$t("tracking.detail.meta.code")}</dt>
+ <dd>
+ <code class="mono">{maskCode(pkg.code)}</code>
+ <button type="button" class="icon-btn" onclick={copyCode} title={$t("tracking.detail.meta.copy_code_title")} aria-label={$t("tracking.detail.meta.copy_code_title")}>
+ <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
+ </svg>
+ </button>
+ </dd>
+ </div>
+ {#if pkg.cpf}
+ <div class="meta-row">
+ <dt>{$t("tracking.detail.meta.cpf")}</dt>
+ <dd>
+ <span class="mono">{maskCpf(pkg.cpf)}</span>
+ <button type="button" class="text-btn" onclick={openCpfDialog}>{$t("tracking.detail.meta.edit")}</button>
+ </dd>
+ </div>
+ {/if}
+ {#if route}
+ <div class="meta-row">
+ <dt>{$t("tracking.detail.meta.route")}</dt>
+ <dd>
+ <span class="mono">{route.from}</span>
+ <span class="route-arrow" aria-hidden="true">→</span>
+ <span class="mono">{route.to}</span>
+ </dd>
+ </div>
+ {/if}
+ <div class="meta-row">
+ <dt>{$t("tracking.detail.meta.posted_at")}</dt>
+ <dd>{fmtDate(postedDate)}</dd>
+ </div>
+ <div class="meta-row">
+ <dt>{$t("tracking.detail.meta.updated")}</dt>
+ <dd>{fmtRel(pkg.last_event_at_ms ?? pkg.updated_at_ms)}</dd>
+ </div>
+ </dl>
+
+ <div class="actions">
+ <button type="button" class="btn-secondary" onclick={onRefresh} disabled={refreshing || pkg.is_archived}>
+ {refreshing ? $t("tracking.detail.action.refreshing") : $t("tracking.detail.action.refresh")}
+ </button>
+ <button type="button" class="btn-secondary" onclick={onRename}>{$t("tracking.detail.action.rename")}</button>
+ {#if pkg.is_archived}
+ <button type="button" class="btn-secondary" onclick={onUnarchive}>{$t("tracking.detail.action.unarchive")}</button>
+ {:else if pkg.canonical_status === "delivered"}
+ <button type="button" class="btn-secondary" onclick={onArchive}>{$t("tracking.detail.action.archive")}</button>
+ {:else if !pkg.cpf}
+ <button type="button" class="btn-secondary" onclick={openCpfDialog}>{$t("tracking.detail.action.add_cpf")}</button>
+ {/if}
+ <button type="button" class="btn-danger" onclick={onRemove}>{$t("tracking.detail.action.remove")}</button>
+ </div>
+
+ <section class="history">
+ <h2>{$t("tracking.detail.history.title")}</h2>
+ {#if events.length === 0}
+ <p class="muted">{$t("tracking.detail.history.empty")}</p>
+ {:else}
+ <ol class="timeline">
+ {#each events as ev, i (ev.id)}
+ {@const evCanonical = classifyEvent(ev.status, ev.location)}
+ {@const evIcon = getStatusIcon(evCanonical)}
+ {@const evLabel = $t(evIcon.labelKey)}
+ {@const samePrev = i > 0 ? classifyEvent(events[i - 1].status, events[i - 1].location) === evCanonical : false}
+ <li class="event" class:first={i === 0} class:repeat={samePrev}>
+ <div
+ class="event-icon"
+ style="--status-color: {evIcon.color}"
+ title={evLabel}
+ aria-label={evLabel}
+ >
+ <svg
+ viewBox="0 0 24 24"
+ width={samePrev ? "12" : "16"}
+ height={samePrev ? "12" : "16"}
+ fill="none"
+ stroke="currentColor"
+ stroke-width={samePrev ? "1.5" : "1.7"}
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d={evIcon.svgPath} />
+ </svg>
+ </div>
+ <div class="event-body">
+ {#if ev.location}
+ <p class="event-desc">{ev.location}</p>
+ {/if}
+ <p class="event-meta">
+ {#if ev.status}
+ <span class="event-status-chip" style="--status-color: {evIcon.color}">{ev.status}</span>
+ {/if}
+ {#if ev.date}<span>{fmtDate(ev.date)}</span>{/if}
+ {#if ev.time}<span class="dot-sep">·</span><span>{ev.time}</span>{/if}
+ </p>
+ {#if ev.sub_status && ev.sub_status.length > 0}
+ <ul class="sub-list">
+ {#each ev.sub_status as s}
+ <li>{s}</li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ </li>
+ {/each}
+ </ol>
+ {/if}
+ </section>
+ {/if}
+</section>
+
+{#if showCpfDialog && pkg}
+ <div
+ class="dialog-overlay"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="cpf-dialog-title"
+ onclick={(e) => { if (e.target === e.currentTarget) showCpfDialog = false; }}
+ >
+ <form class="dialog" onsubmit={submitCpf}>
+ <header class="dialog-head">
+ <h2 id="cpf-dialog-title">{pkg.cpf ? $t("tracking.detail.cpf_dialog.title_edit") : $t("tracking.detail.cpf_dialog.title_add")}</h2>
+ <button type="button" class="dialog-close" onclick={() => (showCpfDialog = false)} aria-label={$t("tracking.detail.cpf_dialog.close")}>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
+ <path d="M18 6 6 18 M6 6l12 12"/>
+ </svg>
+ </button>
+ </header>
+ <div class="dialog-body">
+ <label class="field">
+ <span class="field-label">{$t("tracking.detail.cpf_dialog.label")}</span>
+ <input
+ type="text"
+ class="field-input mono"
+ placeholder={$t("tracking.detail.cpf_dialog.placeholder")}
+ bind:value={cpfValue}
+ autocomplete="off"
+ />
+ <span class="field-hint">{$t("tracking.detail.cpf_dialog.hint")}</span>
+ </label>
+ {#if cpfError}
+ <div class="error" role="alert">{cpfError}</div>
+ {/if}
+ </div>
+ <footer class="dialog-foot">
+ <button type="button" class="btn-secondary" onclick={() => (showCpfDialog = false)} disabled={cpfSubmitting}>
+ {$t("tracking.detail.cpf_dialog.cancel")}
+ </button>
+ <button type="submit" class="btn-primary" disabled={cpfSubmitting}>
+ {cpfSubmitting ? $t("tracking.detail.cpf_dialog.submitting") : $t("tracking.detail.cpf_dialog.submit")}
+ </button>
+ </footer>
+ </form>
+ </div>
+{/if}
+
+{#if showRemoveConfirm && pkg}
+ {@const label = pkg.alias?.trim() || maskCode(pkg.code)}
+ <div
+ class="dialog-overlay"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="remove-confirm-title"
+ onclick={(e) => { if (e.target === e.currentTarget && !removing) showRemoveConfirm = false; }}
+ >
+ <div class="dialog confirm-dialog">
+ <header class="dialog-head">
+ <h2 id="remove-confirm-title">{$t("tracking.remove_dialog.title")}</h2>
+ <button
+ type="button"
+ class="dialog-close"
+ onclick={() => (showRemoveConfirm = false)}
+ disabled={removing}
+ aria-label={$t("tracking.remove_dialog.close")}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
+ <path d="M18 6 6 18 M6 6l12 12"/>
+ </svg>
+ </button>
+ </header>
+ <div class="dialog-body">
+ <p class="confirm-msg">
+ {$t("tracking.remove_dialog.question", { name: label })}
+ </p>
+ <p class="confirm-sub">{$t("tracking.remove_dialog.sub")}</p>
+ </div>
+ <footer class="dialog-foot">
+ <button type="button" class="btn-secondary" onclick={() => (showRemoveConfirm = false)} disabled={removing}>
+ {$t("tracking.remove_dialog.cancel")}
+ </button>
+ <button type="button" class="btn-danger" onclick={confirmRemove} disabled={removing}>
+ {removing ? $t("tracking.remove_dialog.confirming") : $t("tracking.remove_dialog.confirm")}
+ </button>
+ </footer>
+ </div>
+ </div>
+{/if}
+
+{#if toasts.length > 0}
+ <div class="toast-stack" aria-live="polite" aria-atomic="false">
+ {#each toasts as t (t.id)}
+ <button type="button" class="toast toast-{t.kind}" onclick={() => dismissToast(t.id)}>
+ {t.text}
+ </button>
+ {/each}
+ </div>
+{/if}
+
+<style>
+ .detail {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ width: 100%;
+ max-width: 720px;
+ margin-inline: auto;
+ padding: 16px 20px 80px;
+ }
+
+ .back {
+ color: var(--tertiary);
+ text-decoration: none;
+ font-size: 13px;
+ width: fit-content;
+ }
+ .back:hover {
+ color: var(--accent);
+ }
+
+ /* Skeleton */
+ .skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .sk-row,
+ .sk-card {
+ border-radius: var(--border-radius);
+ background: color-mix(in oklab, var(--input-border) 50%, transparent);
+ animation: pulse 1.2s ease-in-out infinite;
+ }
+ .sk-row {
+ height: 14px;
+ }
+ .sk-lg { width: 70%; height: 22px; }
+ .sk-md { width: 50%; }
+ .sk-card { height: 56px; }
+ @keyframes pulse {
+ 0%, 100% { opacity: 0.4; }
+ 50% { opacity: 0.8; }
+ }
+
+ /* Empty / not found */
+ .empty-card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ padding: 48px 20px;
+ text-align: center;
+ border: 1px dashed var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ }
+ .empty-card h1 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .empty-card p {
+ margin: 0 0 12px;
+ font-size: 13px;
+ color: var(--tertiary);
+ }
+
+ /* Hero */
+ .hero {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ }
+ .carrier-icon-lg {
+ flex-shrink: 0;
+ width: 48px;
+ height: 48px;
+ display: grid;
+ place-items: center;
+ border-radius: 10px;
+ background: color-mix(in oklab, var(--carrier-color) 16%, transparent);
+ color: var(--carrier-color);
+ }
+ .status-icon-lg {
+ flex-shrink: 0;
+ width: 40px;
+ height: 40px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: color-mix(in oklab, var(--status-color) 18%, transparent);
+ color: var(--status-color);
+ }
+ .hero-text {
+ flex: 1;
+ min-width: 0;
+ }
+ .hero h1 {
+ margin: 0 0 2px;
+ font-size: 20px;
+ font-weight: 500;
+ letter-spacing: -0.3px;
+ color: var(--secondary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .hero-meta {
+ margin: 0;
+ font-size: 12px;
+ color: var(--tertiary);
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .carrier-name {
+ font-weight: 500;
+ }
+ .dot-sep {
+ opacity: 0.6;
+ }
+ .privacy-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 6px 10px;
+ border-radius: 999px;
+ border: 1px solid var(--input-border);
+ background: var(--surface);
+ color: var(--tertiary);
+ font-size: 11px;
+ font-family: inherit;
+ font-weight: 500;
+ cursor: pointer;
+ flex-shrink: 0;
+ }
+ .privacy-btn:hover {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .privacy-btn[aria-pressed="true"] {
+ background: color-mix(in oklab, var(--accent) 14%, transparent);
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+
+ /* Status row */
+ .status-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+ .status-badge-big {
+ --status-color: var(--accent);
+ padding: 6px 14px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--status-color) 14%, transparent);
+ color: var(--status-color);
+ font-size: 13px;
+ font-weight: 500;
+ display: inline-flex;
+ align-items: baseline;
+ gap: 6px;
+ max-width: 100%;
+ }
+ .status-badge-big.delivered {
+ /* Quando `canonical_status === "delivered"`, --status-color já vem como
+ var(--success) via tracker-status-icons. Esse override só importa
+ quando o pacote tem `is_delivered` mas sem canonical (legado). */
+ background: color-mix(in oklab, var(--success) 18%, transparent);
+ color: var(--success);
+ }
+ .status-badge-label {
+ font-weight: 500;
+ }
+ .status-badge-raw {
+ font-weight: 400;
+ opacity: 0.75;
+ font-size: 12px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+ }
+ .days-pill {
+ padding: 4px 10px;
+ border-radius: 999px;
+ background: transparent;
+ border: 1px solid var(--input-border);
+ color: var(--tertiary);
+ font-size: 11px;
+ }
+ .delivered-pill {
+ border-color: color-mix(in oklab, var(--success) 50%, var(--input-border));
+ color: var(--success);
+ }
+ .archived-pill {
+ border-color: color-mix(in oklab, var(--tertiary) 50%, var(--input-border));
+ color: var(--tertiary);
+ background: color-mix(in oklab, var(--tertiary) 10%, transparent);
+ }
+
+ /* Archive prompt — aparece para pacotes Delivered ainda não arquivados.
+ Tom de "atenção positiva" (parabens, terminou + opção de arquivar) via
+ `--warning`. Texto principal usa `--secondary` (legibilidade) e o
+ título destaca em `--warning`. Em temas eink/light, `--warning` é
+ ambar escuro; em temas dark/dracula é amarelo saturado. Ambos
+ funcionam bem como tom positivo de notificação. */
+ .archive-prompt {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 12px 16px;
+ border-radius: var(--border-radius);
+ background: color-mix(in oklab, var(--warning) 16%, transparent);
+ border: 1px solid color-mix(in oklab, var(--warning) 35%, var(--input-border));
+ color: var(--secondary);
+ }
+ .archive-prompt-text {
+ min-width: 0;
+ flex: 1;
+ }
+ .archive-prompt-text h3 {
+ margin: 0 0 2px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--warning);
+ }
+ .archive-prompt-text p {
+ margin: 0;
+ font-size: 12px;
+ color: var(--secondary);
+ opacity: 0.85;
+ line-height: 1.4;
+ }
+ .archive-prompt-actions {
+ display: flex;
+ gap: 8px;
+ flex-shrink: 0;
+ }
+
+ /* Warn banner — refresh failure, tom de atenção (não erro fatal).
+ Usa `--warning` por consistência com archive-prompt; o problema é
+ transient e o usuário pode tentar de novo. */
+ .warn {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 10px 14px;
+ border-radius: var(--border-radius);
+ background: color-mix(in oklab, var(--warning) 16%, transparent);
+ border: 1px solid color-mix(in oklab, var(--warning) 30%, var(--input-border));
+ color: var(--secondary);
+ font-size: 12px;
+ }
+ .warn strong {
+ color: var(--warning);
+ }
+ .warn-msg {
+ margin-left: 4px;
+ opacity: 0.85;
+ }
+ .warn-btn {
+ padding: 4px 10px;
+ border-radius: var(--border-radius);
+ border: 1px solid currentColor;
+ background: transparent;
+ color: inherit;
+ font-size: 11px;
+ font-family: inherit;
+ cursor: pointer;
+ flex-shrink: 0;
+ }
+ .warn-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ /* Meta */
+ .meta {
+ margin: 0;
+ padding: 12px 16px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .meta-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .meta-row dt {
+ flex: 0 0 110px;
+ font-size: 11px;
+ color: var(--tertiary);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .meta-row dd {
+ margin: 0;
+ flex: 1;
+ min-width: 0;
+ font-size: 13px;
+ color: var(--secondary);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .icon-btn,
+ .text-btn {
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ font-family: inherit;
+ color: var(--tertiary);
+ padding: 4px;
+ border-radius: 4px;
+ }
+ .icon-btn:hover,
+ .text-btn:hover {
+ color: var(--accent);
+ background: color-mix(in oklab, var(--accent) 10%, transparent);
+ }
+ .text-btn {
+ font-size: 11px;
+ padding: 2px 6px;
+ }
+ .route-arrow {
+ color: var(--tertiary);
+ opacity: 0.7;
+ }
+
+ /* Actions */
+ .actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+
+ .btn-primary,
+ .btn-secondary,
+ .btn-danger {
+ padding: 7px 14px;
+ border-radius: var(--border-radius);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ font-weight: 500;
+ }
+ .btn-primary {
+ border: 1px solid var(--accent);
+ background: var(--accent);
+ color: var(--on-accent);
+ }
+ .btn-primary:hover:not(:disabled) {
+ filter: brightness(1.05);
+ }
+ .btn-primary:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .btn-secondary {
+ border: 1px solid var(--input-border);
+ background: transparent;
+ color: var(--secondary);
+ }
+ .btn-secondary:hover:not(:disabled) {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .btn-secondary:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .btn-danger {
+ border: 1px solid color-mix(in oklab, var(--danger) 60%, var(--input-border));
+ background: transparent;
+ color: var(--danger);
+ }
+ .btn-danger:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--danger) 14%, transparent);
+ }
+ .btn-danger:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .confirm-dialog {
+ max-width: 380px;
+ }
+ .confirm-msg {
+ margin: 0 0 6px;
+ font-size: 14px;
+ color: var(--secondary);
+ line-height: 1.4;
+ }
+ .confirm-sub {
+ margin: 0;
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+
+ /* Timeline */
+ .history {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .history h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .muted {
+ margin: 0;
+ color: var(--tertiary);
+ font-size: 13px;
+ }
+ .timeline {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ position: relative;
+ }
+ .timeline::before {
+ content: "";
+ position: absolute;
+ left: 13px;
+ top: 12px;
+ bottom: 12px;
+ width: 1px;
+ background: var(--input-border);
+ }
+ .event {
+ position: relative;
+ display: flex;
+ gap: 12px;
+ padding: 6px 0 14px 0;
+ }
+ .event:last-child {
+ padding-bottom: 0;
+ }
+ .event-icon {
+ flex-shrink: 0;
+ width: 28px;
+ height: 28px;
+ margin-top: 2px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: color-mix(in oklab, var(--status-color) 16%, var(--surface));
+ color: var(--status-color);
+ border: 1px solid color-mix(in oklab, var(--status-color) 30%, var(--input-border));
+ z-index: 1;
+ }
+ .event.first .event-icon {
+ background: color-mix(in oklab, var(--status-color) 24%, var(--surface));
+ border-color: var(--status-color);
+ box-shadow: 0 0 0 3px color-mix(in oklab, var(--status-color) 18%, transparent);
+ }
+ .event.repeat .event-icon {
+ width: 22px;
+ height: 22px;
+ margin-top: 5px;
+ margin-left: 3px;
+ opacity: 0.7;
+ }
+ .event-body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ }
+ .event-desc {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.45;
+ color: var(--secondary);
+ }
+ .event-meta {
+ margin: 0;
+ font-size: 11px;
+ color: var(--tertiary);
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .event-status-chip {
+ --status-color: var(--accent);
+ padding: 1px 7px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--status-color) 12%, transparent);
+ color: var(--status-color);
+ font-size: 10px;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .sub-list {
+ margin: 4px 0 0;
+ padding: 0 0 0 14px;
+ list-style: disc;
+ font-size: 11px;
+ color: var(--tertiary);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ /* Dialog */
+ .dialog-overlay {
+ position: fixed;
+ inset: 0;
+ background: color-mix(in oklab, black 50%, transparent);
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ z-index: 100;
+ }
+ .dialog {
+ width: 100%;
+ max-width: 440px;
+ background: var(--surface);
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ display: flex;
+ flex-direction: column;
+ max-height: calc(100vh - 32px);
+ }
+ .dialog-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--input-border);
+ }
+ .dialog-head h2 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .dialog-close {
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border: none;
+ background: transparent;
+ color: var(--tertiary);
+ cursor: pointer;
+ border-radius: 6px;
+ }
+ .dialog-close:hover {
+ background: color-mix(in oklab, var(--input-border) 50%, transparent);
+ color: var(--secondary);
+ }
+ .dialog-body {
+ padding: 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ overflow-y: auto;
+ }
+ .dialog-foot {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 18px;
+ border-top: 1px solid var(--input-border);
+ }
+
+ .field {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ }
+ .field-label {
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+ .field-input {
+ width: 100%;
+ padding: 8px 11px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 13px;
+ font-family: inherit;
+ }
+ .field-input:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+ .field-hint {
+ font-size: 11px;
+ color: var(--tertiary);
+ }
+ .error {
+ padding: 10px 14px;
+ border-radius: var(--border-radius);
+ background: color-mix(in oklab, var(--danger) 14%, transparent);
+ color: var(--danger);
+ font-size: 12px;
+ }
+
+ /* Toast */
+ .toast-stack {
+ position: fixed;
+ top: 16px;
+ right: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ z-index: 200;
+ pointer-events: none;
+ }
+ .toast {
+ pointer-events: auto;
+ padding: 10px 14px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 12px;
+ font-family: inherit;
+ text-align: left;
+ box-shadow: 0 4px 14px color-mix(in oklab, black 15%, transparent);
+ max-width: 320px;
+ cursor: pointer;
+ }
+ .toast-success {
+ border-color: color-mix(in oklab, var(--success) 50%, var(--input-border));
+ }
+ .toast-error {
+ border-color: color-mix(in oklab, var(--danger) 50%, var(--input-border));
+ color: var(--danger);
+ }
+
+ .mono {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-variant-numeric: tabular-nums;
+ }
+ .small {
+ font-size: 11px;
+ }
+
+ @media (max-width: 480px) {
+ .hero h1 {
+ font-size: 17px;
+ }
+ .meta-row {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ }
+ .meta-row dt {
+ flex: 0 0 auto;
+ }
+ .actions .btn-secondary,
+ .actions .btn-danger {
+ flex: 1;
+ min-width: 120px;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .sk-row,
+ .sk-card {
+ animation: none;
+ }
+ }
+</style>
diff --git a/src/routes/misc/tracking/settings/+page.svelte b/src/routes/misc/tracking/settings/+page.svelte
new file mode 100644
index 00000000..dffc9157
--- /dev/null
+++ b/src/routes/misc/tracking/settings/+page.svelte
@@ -0,0 +1,339 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { t } from "$lib/i18n";
+ import {
+ getTrackerSettings,
+ updateTrackerSettings,
+ } from "$lib/tracker-settings.svelte";
+ import {
+ isNotificationPermissionGranted,
+ requestNotificationPermission,
+ sendTestNotification,
+ } from "$lib/tracker-notifications.svelte";
+
+ type Toast = { id: number; kind: "info" | "success" | "error"; text: string };
+
+ let settings = $derived(getTrackerSettings());
+ let permissionGranted = $state<boolean | null>(null);
+ let testingNotification = $state(false);
+ let toasts = $state<Toast[]>([]);
+ let toastSeq = 0;
+
+ onMount(() => {
+ void refreshPermissionState();
+ });
+
+ async function refreshPermissionState() {
+ permissionGranted = await isNotificationPermissionGranted();
+ }
+
+ function onToggleNotifications(e: Event) {
+ const target = e.currentTarget as HTMLInputElement;
+ updateTrackerSettings({ notificationsEnabled: target.checked });
+ }
+
+ async function onRequestPermission() {
+ const granted = await requestNotificationPermission();
+ permissionGranted = granted;
+ if (!granted) {
+ pushToast("error", $t("tracking.settings.permission_denied_toast"));
+ }
+ }
+
+ async function onTestNotification() {
+ if (testingNotification) return;
+ testingNotification = true;
+ try {
+ const result = await sendTestNotification();
+ permissionGranted = !result.denied;
+ if (result.denied) {
+ pushToast("error", $t("tracking.settings.permission_denied_toast"));
+ } else if (result.ok) {
+ pushToast("info", $t("tracking.settings.test_toast_sent"));
+ } else {
+ pushToast("error", $t("tracking.settings.test_failed"));
+ }
+ } finally {
+ testingNotification = false;
+ }
+ }
+
+ function pushToast(kind: Toast["kind"], text: string) {
+ const id = ++toastSeq;
+ toasts = [...toasts, { id, kind, text }];
+ setTimeout(() => {
+ toasts = toasts.filter((x) => x.id !== id);
+ }, 4500);
+ }
+
+ function dismissToast(id: number) {
+ toasts = toasts.filter((x) => x.id !== id);
+ }
+</script>
+
+<section class="settings-page">
+ <a class="back" href="/misc/tracking">{$t("tracking.detail.back")}</a>
+ <header class="head">
+ <h1>{$t("tracking.settings.title")}</h1>
+ <p class="subtitle">{$t("tracking.settings.subtitle")}</p>
+ </header>
+
+ {#if permissionGranted === false}
+ <div class="banner" role="status">
+ <div class="banner-text">
+ <strong>{$t("tracking.settings.permission_denied_banner")}</strong>
+ <p>{$t("tracking.settings.permission_denied_hint")}</p>
+ </div>
+ <button
+ type="button"
+ class="btn-secondary"
+ onclick={onRequestPermission}
+ >
+ {$t("tracking.settings.request_permission")}
+ </button>
+ </div>
+ {/if}
+
+ <div class="card">
+ <div class="setting-row">
+ <div class="setting-text">
+ <label for="notif-toggle" class="setting-label">
+ {$t("tracking.settings.notifications_label")}
+ </label>
+ <p class="setting-hint">{$t("tracking.settings.notifications_hint")}</p>
+ </div>
+ <label class="switch">
+ <input
+ id="notif-toggle"
+ type="checkbox"
+ checked={settings.notificationsEnabled}
+ onchange={onToggleNotifications}
+ />
+ <span class="slider" aria-hidden="true"></span>
+ </label>
+ </div>
+
+ <div class="actions">
+ <button
+ type="button"
+ class="btn-secondary"
+ onclick={onTestNotification}
+ disabled={testingNotification || !settings.notificationsEnabled}
+ >
+ {testingNotification
+ ? $t("tracking.settings.test_busy")
+ : $t("tracking.settings.test_notification")}
+ </button>
+ </div>
+ </div>
+</section>
+
+{#if toasts.length > 0}
+ <div class="toast-stack" aria-live="polite" aria-atomic="false">
+ {#each toasts as toast (toast.id)}
+ <button
+ type="button"
+ class="toast toast-{toast.kind}"
+ onclick={() => dismissToast(toast.id)}
+ >
+ {toast.text}
+ </button>
+ {/each}
+ </div>
+{/if}
+
+<style>
+ .settings-page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ width: 100%;
+ max-width: 720px;
+ margin-inline: auto;
+ padding: 16px 20px 80px;
+ }
+
+ .back {
+ align-self: flex-start;
+ font-size: 12px;
+ color: var(--tertiary);
+ text-decoration: none;
+ }
+ .back:hover {
+ color: var(--accent);
+ }
+
+ .head h1 {
+ margin: 0 0 4px;
+ font-size: 22px;
+ font-weight: 500;
+ letter-spacing: -0.5px;
+ color: var(--secondary);
+ }
+ .subtitle {
+ margin: 0;
+ font-size: 13px;
+ color: var(--tertiary);
+ }
+
+ .banner {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 14px 18px;
+ border-radius: var(--border-radius);
+ border: 1px solid color-mix(in oklab, var(--warning) 50%, var(--input-border));
+ background: color-mix(in oklab, var(--warning) 12%, transparent);
+ color: var(--secondary);
+ }
+ .banner-text {
+ flex: 1;
+ min-width: 0;
+ }
+ .banner-text strong {
+ display: block;
+ margin-bottom: 4px;
+ color: var(--warning);
+ font-size: 13px;
+ }
+ .banner-text p {
+ margin: 0;
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 18px 20px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ }
+
+ .setting-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ }
+ .setting-text {
+ flex: 1;
+ min-width: 0;
+ }
+ .setting-label {
+ display: block;
+ margin-bottom: 4px;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+ .setting-hint {
+ margin: 0;
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+
+ .switch {
+ position: relative;
+ display: inline-block;
+ width: 40px;
+ height: 22px;
+ flex-shrink: 0;
+ }
+ .switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+ }
+ .slider {
+ position: absolute;
+ inset: 0;
+ background: var(--input-border);
+ border-radius: 999px;
+ transition: background 150ms ease;
+ cursor: pointer;
+ }
+ .slider::before {
+ content: "";
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 16px;
+ height: 16px;
+ background: var(--surface);
+ border-radius: 50%;
+ transition: transform 150ms ease;
+ }
+ .switch input:checked + .slider {
+ background: var(--accent);
+ }
+ .switch input:checked + .slider::before {
+ transform: translateX(18px);
+ }
+ .switch input:focus-visible + .slider {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+
+ .actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ border-top: 1px solid var(--input-border);
+ padding-top: 16px;
+ }
+
+ .btn-secondary {
+ padding: 7px 14px;
+ border-radius: var(--border-radius);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+ font-weight: 500;
+ border: 1px solid var(--input-border);
+ background: transparent;
+ color: var(--secondary);
+ }
+ .btn-secondary:hover:not(:disabled) {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .btn-secondary:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .toast-stack {
+ position: fixed;
+ top: 16px;
+ right: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ z-index: 200;
+ pointer-events: none;
+ }
+ .toast {
+ pointer-events: auto;
+ padding: 10px 14px;
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ background: var(--surface);
+ color: var(--secondary);
+ font-size: 12px;
+ font-family: inherit;
+ text-align: left;
+ box-shadow: 0 4px 14px color-mix(in oklab, black 15%, transparent);
+ max-width: 320px;
+ cursor: pointer;
+ }
+ .toast-success {
+ border-color: color-mix(in oklab, var(--success) 50%, var(--input-border));
+ }
+ .toast-error {
+ border-color: color-mix(in oklab, var(--danger) 50%, var(--input-border));
+ color: var(--danger);
+ }
+</style>
diff --git a/src/routes/study/+layout.svelte b/src/routes/study/+layout.svelte
index 746c12b5..3396adbe 100644
--- a/src/routes/study/+layout.svelte
+++ b/src/routes/study/+layout.svelte
@@ -25,10 +25,11 @@
import EqualizerPanel from "$lib/study-music-components/EqualizerPanel.svelte";
import LastFmPanel from "$lib/study-music-components/LastFmPanel.svelte";
import MusicThemePanel from "$lib/study-music-components/MusicThemePanel.svelte";
- import YoutubePanel from "$lib/study-music-components/YoutubePanel.svelte";
+ import YoutubePanel from "$lib/study-music-youtube-components/YoutubePanel.svelte";
import QualityPresetPanel from "$lib/study-music-components/QualityPresetPanel.svelte";
import SourceOrderPanel from "$lib/study-music-components/SourceOrderPanel.svelte";
import QobuzPanel from "$lib/study-music-components/QobuzPanel.svelte";
+ import LyricsTranslationPanel from "$lib/study-music-components/LyricsTranslationPanel.svelte";
import SelectionBar from "$lib/study-music-components/SelectionBar.svelte";
import ContextMenu, { type ContextMenuItem } from "$lib/study-music-components/ContextMenu.svelte";
@@ -103,11 +104,15 @@
}
}
- const PRESET_MINUTES: Record<string, number> = {
- "pomodoro-25": 25,
- "deep-50": 50,
- "stopwatch": 0,
- };
+ function focusPresetMinutes(presetId: string): number {
+ if (presetId === "stopwatch") return 0;
+ const match = presetId.match(/-(\d+)$/);
+ if (match) return Math.max(0, Number(match[1]) || 0);
+ if (presetId.startsWith("deep")) return 50;
+ if (presetId.startsWith("short-break")) return 5;
+ if (presetId.startsWith("long-break")) return 15;
+ return 25;
+ }
type FocusCurrent = {
id: number;
@@ -138,6 +143,19 @@
return labels[presetId] ?? presetId;
}
+ function presetLabelForRpc(presetId: string): string {
+ const minutes = focusPresetMinutes(presetId);
+ if (presetId === "stopwatch") return $t("study.focus.preset_custom") as string;
+ if (presetId.startsWith("short-break")) {
+ return `${$t("study.focus.preset_short_break")} ${minutes}`;
+ }
+ if (presetId.startsWith("long-break")) {
+ return `${$t("study.focus.preset_long_break")} ${minutes}`;
+ }
+ if (presetId.startsWith("deep")) return `${$t("study.focus.preset_deep")} ${minutes}`;
+ return `${$t("study.focus.preset_pomodoro")} ${minutes}`;
+ }
+
function loadFocusCustomText(): string {
if (typeof localStorage === "undefined") return "";
try {
@@ -153,10 +171,10 @@
return;
}
const customText = loadFocusCustomText().trim();
- const target = PRESET_MINUTES[cur.preset] ?? 0;
+ const target = focusPresetMinutes(cur.preset);
const startedMs = Date.parse(cur.started_at.replace(" ", "T") + "Z");
const elapsedSec = Math.max(0, Math.floor((Date.now() - startedMs) / 1000));
- const presetText = presetLabelStudy(cur.preset);
+ const presetText = presetLabelForRpc(cur.preset);
const details = customText || $t("study.focus.rpc_default") as string;
const stateText = customText
? (target > 0
@@ -180,7 +198,7 @@
const cur = await pluginInvoke<FocusCurrent>("study", "study:focus:current");
pushFocusRpc(cur);
if (!cur) return;
- const target = PRESET_MINUTES[cur.preset] ?? 0;
+ const target = focusPresetMinutes(cur.preset);
if (target <= 0) return;
const startedMs = Date.parse(cur.started_at.replace(" ", "T") + "Z");
const elapsedSec = Math.max(0, Math.floor((Date.now() - startedMs) / 1000));
@@ -772,6 +790,11 @@
onClose={() => musicUI.closeTheme()}
/>
+<LyricsTranslationPanel
+ open={musicUI.translationSettingsOpen}
+ onClose={() => musicUI.closeTranslationSettings()}
+/>
+
<YoutubePanel
open={musicUI.youtubeOpen}
onClose={() => musicUI.closeYoutube()}
diff --git a/src/routes/study/focus/+page.svelte b/src/routes/study/focus/+page.svelte
index e6eb6b19..69a4e5ae 100644
--- a/src/routes/study/focus/+page.svelte
+++ b/src/routes/study/focus/+page.svelte
@@ -1,17 +1,27 @@
<script lang="ts">
+ import { goto } from "$app/navigation";
import { onDestroy, onMount } from "svelte";
import { pluginInvoke } from "$lib/plugin-invoke";
import { awardXp, bumpCounter } from "$lib/study-gamification";
import { emitFocusBreakStart } from "$lib/study-focus-bridge";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+ import PlayerBar from "$lib/study-music-components/PlayerBar.svelte";
import { t } from "$lib/i18n";
- import PageHero from "$lib/study-components/PageHero.svelte";
- import AboutLink from "$lib/study-music-components/AboutLink.svelte";
+
+ type PresetKind = "pomodoro" | "short_break" | "long_break" | "deep" | "stopwatch";
+ type Panel = "settings" | "history" | "intent" | null;
+ type SettingsTab = "timer" | "appearance" | "sounds" | "automation";
+ type DisplayMode = "standard" | "line";
+ type SceneId = "room" | "garden" | "night" | "library" | "cafe" | "ocean";
+ type FocusMixId = "lofi" | "synthwave" | "rainy" | "deep";
+ type AmbientId = "rain" | "cafe" | "keyboard" | "waves" | "brown";
type Current = {
id: number;
preset: string;
started_at: string;
elapsed_minutes: number;
+ subject_id?: number | null;
} | null;
type Session = {
@@ -20,6 +30,8 @@
started_at: string;
ended_at: string | null;
minutes: number | null;
+ interrupted?: boolean;
+ subject_name?: string | null;
};
type History = {
@@ -28,11 +40,12 @@
week_minutes: number;
};
- const PRESETS: { id: string; labelKey: string; minutes: number }[] = [
- { id: "pomodoro-25", labelKey: "study.focus.preset_pomodoro", minutes: 25 },
- { id: "deep-50", labelKey: "study.focus.preset_deep", minutes: 50 },
- { id: "stopwatch", labelKey: "study.focus.preset_custom", minutes: 0 },
- ];
+ type XpState = {
+ xp: number;
+ level: number;
+ xp_to_next: number;
+ level_progress_pct: number;
+ };
type FocusSettings = {
pomodoro_minutes: number;
@@ -47,13 +60,13 @@
auto_start_focus: boolean;
};
- let current = $state<Current>(null);
- let history = $state<History>({ sessions: [], today_minutes: 0, week_minutes: 0 });
- let loading = $state(true);
- let tick = $state(0);
- let poll: number | null = null;
+ const RPC_TEXT_KEY = "study.focus.rpc_text.v1";
+ const SCENE_KEY = "study.focus.scene.v1";
+ const DISPLAY_KEY = "study.focus.display.v1";
+ const AUDIO_PREFS_KEY = "study.focus.audio.v1";
+ const AUTO_HIDE_KEY = "study.focus.auto_hide.v1";
- let settings = $state<FocusSettings>({
+ const DEFAULT_FOCUS_SETTINGS: FocusSettings = {
pomodoro_minutes: 25,
short_break_minutes: 5,
long_break_minutes: 15,
@@ -64,41 +77,131 @@
auto_pause_player: true,
auto_start_breaks: false,
auto_start_focus: false,
+ };
+
+ const MODES: {
+ kind: PresetKind;
+ labelKey: string;
+ fallbackMinutes: number;
+ badge: string;
+ }[] = [
+ { kind: "pomodoro", labelKey: "study.focus.preset_pomodoro", fallbackMinutes: 25, badge: "01" },
+ { kind: "short_break", labelKey: "study.focus.preset_short_break", fallbackMinutes: 5, badge: "02" },
+ { kind: "long_break", labelKey: "study.focus.preset_long_break", fallbackMinutes: 15, badge: "03" },
+ { kind: "deep", labelKey: "study.focus.preset_deep", fallbackMinutes: 50, badge: "04" },
+ { kind: "stopwatch", labelKey: "study.focus.preset_custom", fallbackMinutes: 0, badge: "05" },
+ ];
+
+ const SCENES: { id: SceneId; label: string; hint: string }[] = [
+ { id: "room", label: "Room", hint: "warm desk" },
+ { id: "library", label: "Library", hint: "quiet stacks" },
+ { id: "cafe", label: "Cafe", hint: "late table" },
+ { id: "garden", label: "Garden", hint: "green shade" },
+ { id: "night", label: "Night", hint: "blue hour" },
+ { id: "ocean", label: "Ocean", hint: "low tide" },
+ ];
+
+ const FOCUS_MIXES: {
+ id: FocusMixId;
+ label: string;
+ subtitle: string;
+ tones: number[];
+ mood: string;
+ }[] = [
+ { id: "lofi", label: "Lofi Desk", subtitle: "soft pad, slow pulse", tones: [174.61, 261.63, 329.63], mood: "study" },
+ { id: "synthwave", label: "Synth Grid", subtitle: "bright analog wash", tones: [130.81, 196, 392], mood: "flow" },
+ { id: "rainy", label: "Rain Window", subtitle: "darker keys, gentle noise", tones: [146.83, 220, 349.23], mood: "calm" },
+ { id: "deep", label: "Deep Work", subtitle: "minimal drone", tones: [110, 164.81, 220], mood: "quiet" },
+ ];
+
+ const AMBIENT_SOUNDS: { id: AmbientId; label: string; filter: BiquadFilterType; frequency: number }[] = [
+ { id: "rain", label: "Rain", filter: "bandpass", frequency: 1800 },
+ { id: "cafe", label: "Cafe", filter: "lowpass", frequency: 950 },
+ { id: "keyboard", label: "Keyboard", filter: "highpass", frequency: 2200 },
+ { id: "waves", label: "Waves", filter: "lowpass", frequency: 480 },
+ { id: "brown", label: "Brown noise", filter: "lowpass", frequency: 260 },
+ ];
+
+ const SETTINGS_TABS: {
+ id: SettingsTab;
+ labelKey: string;
+ icon: string;
+ }[] = [
+ { id: "timer", labelKey: "study.focus.acc_cycles_title", icon: "M12 6v6l4 2 M12 22a10 10 0 1 1 0-20 10 10 0 0 1 0 20z" },
+ { id: "appearance", labelKey: "settings.cat_appearance", icon: "M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.2a1.8 1.8 0 0 0-1.4 2.9l.3.4A1.7 1.7 0 0 1 12 22z M7 12h.01 M9 7h.01 M14 6h.01 M18 10h.01" },
+ { id: "sounds", labelKey: "study.focus.acc_sounds_title", icon: "M11 5 6.5 8.5H3v7h3.5L11 19V5z M16 9a5 5 0 0 1 0 6 M19 6a9 9 0 0 1 0 12" },
+ { id: "automation", labelKey: "study.focus.config_autostart", icon: "M5 12a7 7 0 0 1 12-5 M19 5v5h-5 M19 12a7 7 0 0 1-12 5 M5 19v-5h5" },
+ ];
+
+ let current = $state<Current>(null);
+ let history = $state<History>({ sessions: [], today_minutes: 0, week_minutes: 0 });
+ let xpState = $state<XpState | null>(null);
+ let loading = $state(true);
+ let tick = $state(0);
+ let poll: number | null = null;
+ let refreshPoll: number | null = null;
+ let panel = $state<Panel>(null);
+ let settingsTab = $state<SettingsTab>("timer");
+ let selectedKind = $state<PresetKind>("pomodoro");
+ let displayMode = $state<DisplayMode>("standard");
+ let sceneId = $state<SceneId>("room");
+ let rpcCustomText = $state("");
+ let activeMix = $state<FocusMixId>("lofi");
+ let focusRadioPlaying = $state(false);
+ let focusRadioVolume = $state(36);
+ let ambientPower = $state(false);
+ let ambientVolumes = $state<Record<AmbientId, number>>({
+ rain: 18,
+ cafe: 0,
+ keyboard: 0,
+ waves: 0,
+ brown: 12,
});
+ let autoHideUi = $state(true);
+ let uiIdle = $state(false);
let saveTimer: number | null = null;
let savingState = $state<"idle" | "saving" | "saved">("idle");
+ let idleTimer: number | null = null;
+ let audioCtx: AudioContext | null = null;
+ let radioGain: GainNode | null = null;
+ let radioNodes: (OscillatorNode | AudioBufferSourceNode)[] = [];
+ const ambientNodes = new Map<AmbientId, { source: AudioBufferSourceNode; gain: GainNode; filter: BiquadFilterNode }>();
- const activePreset = $derived(
- current ? PRESETS.find((p) => p.id === current!.preset) ?? null : null,
- );
+ let settings = $state<FocusSettings>({ ...DEFAULT_FOCUS_SETTINGS });
+
+ const activeKind = $derived(current ? presetKindFromId(current.preset) : selectedKind);
+ const activeMode = $derived(MODES.find((m) => m.kind === activeKind) ?? MODES[0]);
+ const targetMinutes = $derived(current ? presetMinutesFromId(current.preset) : minutesForKind(selectedKind));
const elapsedSec = $derived.by(() => {
void tick;
if (!current) return 0;
const startedMs = Date.parse(current.started_at.replace(" ", "T") + "Z");
- const now = Date.now();
- return Math.max(0, Math.floor((now - startedMs) / 1000));
+ return Math.max(0, Math.floor((Date.now() - startedMs) / 1000));
});
- const remaining = $derived.by(() => {
+ const remainingSec = $derived.by(() => {
void tick;
- if (!current) return null;
- const ap = activePreset;
- if (!ap || ap.minutes === 0) return null;
- const target = ap.minutes * 60;
- return Math.max(0, target - elapsedSec);
+ if (!current || targetMinutes <= 0) return null;
+ return Math.max(0, targetMinutes * 60 - elapsedSec);
});
- const sessionPct = $derived.by(() => {
+ const progressPct = $derived.by(() => {
void tick;
- const ap = activePreset;
- if (!ap || ap.minutes === 0 || !current) return 0;
- const target = ap.minutes * 60;
- return Math.min(100, Math.max(0, (elapsedSec / target) * 100));
+ if (!current || targetMinutes <= 0) return 0;
+ return Math.min(100, Math.max(0, (elapsedSec / (targetMinutes * 60)) * 100));
});
- const isLowTime = $derived(remaining != null && remaining > 0 && remaining <= 60);
- const isFinished = $derived(remaining === 0);
+ const isLowTime = $derived(remainingSec != null && remainingSec > 0 && remainingSec <= 60);
+ const isFinished = $derived(remainingSec === 0);
+ const timerText = $derived(remainingSec != null ? fmt(remainingSec) : fmt(elapsedSec));
+ const goalMinutes = $derived(Math.max(1, settings.pomodoro_minutes * settings.cycles_before_long_break));
+ const goalPct = $derived(Math.min(100, Math.round((history.today_minutes / goalMinutes) * 100)));
+ const cyclesToday = $derived(
+ Math.floor(history.today_minutes / Math.max(1, settings.pomodoro_minutes)),
+ );
+ const activeMixInfo = $derived(FOCUS_MIXES.find((mix) => mix.id === activeMix) ?? FOCUS_MIXES[0]);
+ const uiHidden = $derived(Boolean(autoHideUi && current && uiIdle && !panel));
let prevFinished = false;
$effect(() => {
@@ -109,6 +212,80 @@
prevFinished = finished;
});
+ function clamp(n: number, min: number, max: number) {
+ return Math.max(min, Math.min(max, Number.isFinite(n) ? n : min));
+ }
+
+ function adjustNumberSetting(
+ key:
+ | "pomodoro_minutes"
+ | "short_break_minutes"
+ | "long_break_minutes"
+ | "cycles_before_long_break",
+ delta: number,
+ min: number,
+ max: number,
+ ) {
+ settings[key] = clamp(Number(settings[key]) + delta, min, max);
+ void saveSettings();
+ }
+
+ function resetFocusSettings() {
+ settings = { ...DEFAULT_FOCUS_SETTINGS };
+ persistScene("room");
+ persistDisplay("standard");
+ activeMix = "lofi";
+ focusRadioVolume = 36;
+ ambientVolumes = { rain: 18, cafe: 0, keyboard: 0, waves: 0, brown: 12 };
+ persistAutoHide(true);
+ stopFocusRadio(false);
+ stopAmbient(false);
+ saveAudioPrefs();
+ void saveSettings();
+ }
+
+ function minutesForKind(kind: PresetKind): number {
+ if (kind === "pomodoro") return clamp(settings.pomodoro_minutes, 1, 120);
+ if (kind === "short_break") return clamp(settings.short_break_minutes, 1, 60);
+ if (kind === "long_break") return clamp(settings.long_break_minutes, 1, 60);
+ if (kind === "deep") return 50;
+ return 0;
+ }
+
+ function presetIdForKind(kind: PresetKind): string {
+ if (kind === "pomodoro") return `pomodoro-${minutesForKind(kind)}`;
+ if (kind === "short_break") return `short-break-${minutesForKind(kind)}`;
+ if (kind === "long_break") return `long-break-${minutesForKind(kind)}`;
+ if (kind === "deep") return "deep-50";
+ return "stopwatch";
+ }
+
+ function presetKindFromId(id: string): PresetKind {
+ if (id.startsWith("short-break")) return "short_break";
+ if (id.startsWith("long-break")) return "long_break";
+ if (id.startsWith("deep")) return "deep";
+ if (id === "stopwatch") return "stopwatch";
+ return "pomodoro";
+ }
+
+ function presetMinutesFromId(id: string): number {
+ if (id === "stopwatch") return 0;
+ const match = id.match(/-(\d+)$/);
+ if (match) return clamp(Number(match[1]), 0, 180);
+ const kind = presetKindFromId(id);
+ const fallback = MODES.find((m) => m.kind === kind)?.fallbackMinutes ?? 0;
+ return fallback;
+ }
+
+ function presetLabel(id: string): string {
+ const kind = presetKindFromId(id);
+ const mode = MODES.find((m) => m.kind === kind);
+ const minutes = presetMinutesFromId(id);
+ const label = mode ? $t(mode.labelKey) : id;
+ if (minutes <= 0) return label;
+ return `${label} ${minutes}`;
+ }
+
function fmt(sec: number): string {
const s = Math.floor(sec);
const h = Math.floor(s / 3600);
@@ -119,15 +296,293 @@
return `${pad(m)}:${pad(r)}`;
}
+ function formatDate(iso: string): string {
+ try {
+ return new Date(iso.replace(" ", "T") + "Z").toLocaleString();
+ } catch {
+ return iso;
+ }
+ }
+
+ function shouldIgnoreShortcut(target: EventTarget | null): boolean {
+ const el = target as HTMLElement | null;
+ if (!el) return false;
+ const tag = el.tagName;
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el.isContentEditable;
+ }
+
+ function persistScene(next: SceneId) {
+ sceneId = next;
+ try {
+ localStorage.setItem(SCENE_KEY, next);
+ } catch {}
+ }
+
+ function persistDisplay(next: DisplayMode) {
+ displayMode = next;
+ try {
+ localStorage.setItem(DISPLAY_KEY, next);
+ } catch {}
+ }
+
+ function persistAutoHide(next: boolean) {
+ autoHideUi = next;
+ if (!next) uiIdle = false;
+ try {
+ localStorage.setItem(AUTO_HIDE_KEY, next ? "1" : "0");
+ } catch {}
+ }
+
+ function saveAudioPrefs() {
+ if (typeof localStorage === "undefined") return;
+ try {
+ localStorage.setItem(
+ AUDIO_PREFS_KEY,
+ JSON.stringify({
+ activeMix,
+ focusRadioVolume,
+ ambientPower,
+ ambientVolumes,
+ }),
+ );
+ } catch {}
+ }
+
+ function isSceneId(value: string | null): value is SceneId {
+ return !!value && SCENES.some((scene) => scene.id === value);
+ }
+
+ function isFocusMixId(value: unknown): value is FocusMixId {
+ return typeof value === "string" && FOCUS_MIXES.some((mix) => mix.id === value);
+ }
+
+ function loadLocalPrefs() {
+ if (typeof localStorage === "undefined") return;
+ try {
+ rpcCustomText = localStorage.getItem(RPC_TEXT_KEY) ?? "";
+ const storedScene = localStorage.getItem(SCENE_KEY);
+ if (isSceneId(storedScene)) {
+ sceneId = storedScene;
+ }
+ const storedDisplay = localStorage.getItem(DISPLAY_KEY);
+ if (storedDisplay === "standard" || storedDisplay === "line") {
+ displayMode = storedDisplay;
+ }
+ autoHideUi = localStorage.getItem(AUTO_HIDE_KEY) !== "0";
+ const audioPrefs = JSON.parse(localStorage.getItem(AUDIO_PREFS_KEY) ?? "{}") as {
+ activeMix?: unknown;
+ focusRadioVolume?: unknown;
+ ambientPower?: unknown;
+ ambientVolumes?: Partial<Record<AmbientId, unknown>>;
+ };
+ if (isFocusMixId(audioPrefs.activeMix)) activeMix = audioPrefs.activeMix;
+ if (typeof audioPrefs.focusRadioVolume === "number") {
+ focusRadioVolume = clamp(audioPrefs.focusRadioVolume, 0, 100);
+ }
+ // Browser audio needs an explicit user gesture after reload, so we keep the mix saved but stopped.
+ ambientPower = false;
+ if (audioPrefs.ambientVolumes) {
+ for (const sound of AMBIENT_SOUNDS) {
+ const value = audioPrefs.ambientVolumes[sound.id];
+ if (typeof value === "number") ambientVolumes[sound.id] = clamp(value, 0, 100);
+ }
+ }
+ } catch {
+ rpcCustomText = "";
+ }
+ }
+
+ function saveRpcText(value: string) {
+ rpcCustomText = value;
+ if (typeof localStorage === "undefined") return;
+ try {
+ if (value.trim()) localStorage.setItem(RPC_TEXT_KEY, value.trim());
+ else localStorage.removeItem(RPC_TEXT_KEY);
+ } catch {}
+ }
+
+ function ensureAudioContext(): AudioContext | null {
+ if (typeof window === "undefined") return null;
+ if (audioCtx) return audioCtx;
+ const AudioCtor =
+ window.AudioContext ??
+ (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
+ if (!AudioCtor) return null;
+ audioCtx = new AudioCtor();
+ return audioCtx;
+ }
+
+ function createNoiseBuffer(ctx: AudioContext) {
+ const length = ctx.sampleRate * 2;
+ const buffer = ctx.createBuffer(1, length, ctx.sampleRate);
+ const data = buffer.getChannelData(0);
+ for (let i = 0; i < length; i += 1) {
+ data[i] = Math.random() * 2 - 1;
+ }
+ return buffer;
+ }
+
+ function stopFocusRadio(persist = true) {
+ for (const node of radioNodes) {
+ try {
+ node.stop();
+ } catch {}
+ try {
+ node.disconnect();
+ } catch {}
+ }
+ radioNodes = [];
+ try {
+ radioGain?.disconnect();
+ } catch {}
+ radioGain = null;
+ focusRadioPlaying = false;
+ if (persist) saveAudioPrefs();
+ }
+
+ async function startFocusRadio() {
+ const ctx = ensureAudioContext();
+ if (!ctx) return;
+ if (ctx.state === "suspended") await ctx.resume();
+ stopFocusRadio(false);
+
+ const mix = activeMixInfo;
+ radioGain = ctx.createGain();
+ radioGain.gain.value = (focusRadioVolume / 100) * 0.22;
+ radioGain.connect(ctx.destination);
+
+ mix.tones.forEach((freq, idx) => {
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+ osc.type = idx === 0 ? "triangle" : "sine";
+ osc.frequency.value = freq;
+ osc.detune.value = idx * 4 - 5;
+ gain.gain.value = idx === 0 ? 0.24 : 0.11;
+ osc.connect(gain);
+ gain.connect(radioGain!);
+ osc.start();
+ radioNodes.push(osc);
+ });
+
+ const texture = ctx.createBufferSource();
+ const filter = ctx.createBiquadFilter();
+ const textureGain = ctx.createGain();
+ texture.buffer = createNoiseBuffer(ctx);
+ texture.loop = true;
+ filter.type = activeMix === "synthwave" ? "highpass" : "lowpass";
+ filter.frequency.value = activeMix === "deep" ? 220 : activeMix === "synthwave" ? 1800 : 620;
+ textureGain.gain.value = activeMix === "rainy" ? 0.1 : 0.035;
+ texture.connect(filter);
+ filter.connect(textureGain);
+ textureGain.connect(radioGain);
+ texture.start();
+ radioNodes.push(texture);
+
+ focusRadioPlaying = true;
+ saveAudioPrefs();
+ }
+
+ function toggleFocusRadio() {
+ if (focusRadioPlaying) stopFocusRadio();
+ else void startFocusRadio();
+ }
+
+ function selectFocusMix(id: FocusMixId) {
+ activeMix = id;
+ if (focusRadioPlaying) void startFocusRadio();
+ else saveAudioPrefs();
+ }
+
+ function setFocusRadioVolume(value: number) {
+ focusRadioVolume = clamp(value, 0, 100);
+ if (radioGain) radioGain.gain.value = (focusRadioVolume / 100) * 0.22;
+ saveAudioPrefs();
+ }
+
+ function createAmbientLayer(ctx: AudioContext, sound: (typeof AMBIENT_SOUNDS)[number]) {
+ const source = ctx.createBufferSource();
+ const filter = ctx.createBiquadFilter();
+ const gain = ctx.createGain();
+ source.buffer = createNoiseBuffer(ctx);
+ source.loop = true;
+ filter.type = sound.filter;
+ filter.frequency.value = sound.frequency;
+ gain.gain.value = 0;
+ source.connect(filter);
+ filter.connect(gain);
+ gain.connect(ctx.destination);
+ source.start();
+ ambientNodes.set(sound.id, { source, gain, filter });
+ }
+
+ async function startAmbient() {
+ const ctx = ensureAudioContext();
+ if (!ctx) return;
+ if (ctx.state === "suspended") await ctx.resume();
+ ambientPower = true;
+ for (const sound of AMBIENT_SOUNDS) {
+ if (!ambientNodes.has(sound.id)) createAmbientLayer(ctx, sound);
+ }
+ syncAmbientVolumes();
+ saveAudioPrefs();
+ }
+
+ function stopAmbient(persist = true) {
+ for (const layer of ambientNodes.values()) {
+ try {
+ layer.source.stop();
+ } catch {}
+ try {
+ layer.source.disconnect();
+ layer.filter.disconnect();
+ layer.gain.disconnect();
+ } catch {}
+ }
+ ambientNodes.clear();
+ ambientPower = false;
+ if (persist) saveAudioPrefs();
+ }
+
+ function syncAmbientVolumes() {
+ for (const sound of AMBIENT_SOUNDS) {
+ const layer = ambientNodes.get(sound.id);
+ if (!layer) continue;
+ layer.gain.gain.value = ambientPower ? (ambientVolumes[sound.id] / 100) * 0.28 : 0;
+ }
+ }
+
+ function toggleAmbientPower() {
+ if (ambientPower) stopAmbient();
+ else void startAmbient();
+ }
+
+ function setAmbientVolume(id: AmbientId, value: number) {
+ ambientVolumes[id] = clamp(value, 0, 100);
+ syncAmbientVolumes();
+ saveAudioPrefs();
+ }
+
+ function markUiAwake() {
+ if (!autoHideUi) {
+ uiIdle = false;
+ return;
+ }
+ uiIdle = false;
+ if (idleTimer != null) clearTimeout(idleTimer);
+ if (current && !panel) {
+ idleTimer = window.setTimeout(() => {
+ uiIdle = true;
+ }, 4200);
+ }
+ }
+
async function loadSettings() {
try {
const all = await pluginInvoke<{ focus?: Partial<FocusSettings> }>(
"study",
"study:settings:get",
);
- if (all?.focus) {
- settings = { ...settings, ...all.focus };
- }
+ if (all?.focus) settings = { ...settings, ...all.focus };
} catch (e) {
console.error("loadSettings failed", e);
}
@@ -138,12 +593,18 @@
savingState = "saving";
saveTimer = window.setTimeout(async () => {
try {
- const all = await pluginInvoke<Record<string, unknown>>(
- "study",
- "study:settings:get",
- );
- const merged = { ...all, focus: settings };
- await pluginInvoke("study", "study:settings:save", { settings: merged });
+ settings = {
+ ...settings,
+ pomodoro_minutes: clamp(settings.pomodoro_minutes, 1, 120),
+ short_break_minutes: clamp(settings.short_break_minutes, 1, 60),
+ long_break_minutes: clamp(settings.long_break_minutes, 1, 60),
+ cycles_before_long_break: clamp(settings.cycles_before_long_break, 1, 10),
+ sound_volume: clamp(settings.sound_volume, 0, 100),
+ };
+ const all = await pluginInvoke<Record<string, unknown>>("study", "study:settings:get");
+ await pluginInvoke("study", "study:settings:save", {
+ settings: { ...all, focus: settings },
+ });
savingState = "saved";
setTimeout(() => (savingState = "idle"), 1500);
} catch (e) {
@@ -168,25 +629,37 @@
}
}
- async function start(presetId: string) {
+ async function refreshXpState() {
+ try {
+ xpState = await pluginInvoke<XpState>("study", "study:gamification:state");
+ } catch (e) {
+ console.error("xp state fetch failed", e);
+ }
+ }
+
+ async function start(kind = selectedKind) {
+ selectedKind = kind;
try {
- await pluginInvoke("study", "study:focus:start", { preset: presetId });
+ await pluginInvoke("study", "study:focus:start", { preset: presetIdForKind(kind) });
+ panel = null;
await refresh();
+ markUiAwake();
} catch (e) {
console.error("focus start failed", e);
}
}
- async function stop() {
+ async function stop(forceCompleted: boolean | null = null) {
+ if (!current) return;
+ const elapsedMin = Math.max(0, Math.floor(elapsedSec / 60));
+ const completed = forceCompleted ?? (targetMinutes <= 0 || isFinished);
try {
- const elapsedMin = current
- ? Math.floor((current.elapsed_minutes ?? 0) + elapsedSec / 60 - (current.elapsed_minutes ?? 0))
- : Math.floor(elapsedSec / 60);
- await pluginInvoke("study", "study:focus:stop");
+ await pluginInvoke("study", "study:focus:stop", { completed });
await refresh();
+ void refreshXpState();
+ uiIdle = false;
if (elapsedMin >= 1) {
- const xp = elapsedMin;
- void awardXp("focus_session", xp, { minutes: elapsedMin });
+ void awardXp("focus_session", elapsedMin, { minutes: elapsedMin, completed });
void bumpCounter("focus_minutes", elapsedMin);
}
} catch (e) {
@@ -194,899 +667,2051 @@
}
}
+ function togglePanel(next: Panel) {
+ panel = panel === next ? null : next;
+ uiIdle = false;
+ }
+
+ function exitFullscreen() {
+ void goto("/study");
+ }
+
+ function onKey(e: KeyboardEvent) {
+ if (shouldIgnoreShortcut(e.target)) return;
+ markUiAwake();
+ if (e.key === "Escape") {
+ e.preventDefault();
+ if (panel) panel = null;
+ else exitFullscreen();
+ return;
+ }
+ if (e.key === " ") {
+ e.preventDefault();
+ if (current) void stop();
+ else void start();
+ return;
+ }
+ if (e.key >= "1" && e.key <= "5") {
+ const mode = MODES[Number(e.key) - 1];
+ if (mode) selectedKind = mode.kind;
+ }
+ }
+
onMount(() => {
- refresh();
- loadSettings();
- loadRpcText();
+ loadLocalPrefs();
+ void loadSettings();
+ void refresh();
+ void refreshXpState();
poll = window.setInterval(() => {
tick += 1;
}, 1000);
+ refreshPoll = window.setInterval(() => {
+ void refresh();
+ void refreshXpState();
+ }, 30_000);
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("mousemove", markUiAwake);
+ window.addEventListener("pointerdown", markUiAwake);
});
onDestroy(() => {
- if (poll != null) {
- clearInterval(poll);
- poll = null;
- }
+ if (poll != null) clearInterval(poll);
+ if (refreshPoll != null) clearInterval(refreshPoll);
+ if (saveTimer != null) clearTimeout(saveTimer);
+ if (idleTimer != null) clearTimeout(idleTimer);
+ stopFocusRadio(false);
+ stopAmbient(false);
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("mousemove", markUiAwake);
+ window.removeEventListener("pointerdown", markUiAwake);
});
+</script>
- const RPC_TEXT_KEY = "study.focus.rpc_text.v1";
-
- let rpcCustomText = $state("");
+<svelte:head>
+ <title>{$t("study.focus.title")} | OmniGet</title>
+</svelte:head>
- function loadRpcText() {
- if (typeof localStorage === "undefined") return;
- try {
- rpcCustomText = localStorage.getItem(RPC_TEXT_KEY) ?? "";
- } catch {
- rpcCustomText = "";
- }
- }
+<div
+ class="focus-shell"
+ data-scene={sceneId}
+ data-active={current ? "1" : "0"}
+ data-low-time={isLowTime ? "1" : "0"}
+ data-display={displayMode}
+ data-ui-idle={uiHidden ? "1" : "0"}
+>
+ <div class="ambient-scene" aria-hidden="true">
+ <div class="scene-window"></div>
+ <div class="scene-shelf"></div>
+ <div class="scene-desk"></div>
+ <div class="scene-lamp"></div>
+ </div>
+ <div class="scene-shade" aria-hidden="true"></div>
- function saveRpcText(value: string) {
- rpcCustomText = value;
- if (typeof localStorage === "undefined") return;
- try {
- if (value.trim()) {
- localStorage.setItem(RPC_TEXT_KEY, value.trim());
- } else {
- localStorage.removeItem(RPC_TEXT_KEY);
- }
- } catch {
- /* ignore */
- }
- }
+ <header class="focus-status" aria-label={$t("study.focus.title") as string}>
+ <a class="focus-brand" href="/study" aria-label={$t("study.hub.title") as string}>
+ <span class="brand-mark">OG</span>
+ <span>{$t("study.focus.title")}</span>
+ </a>
+ <div class="level-block">
+ <span class="level-seed" aria-hidden="true">L</span>
+ <div class="level-copy">
+ <strong>{xpState ? `Level ${xpState.level}` : $t("study.common.loading")}</strong>
+ <span>{xpState ? `${xpState.xp} XP` : "XP"}</span>
+ </div>
+ <div class="level-meter" aria-hidden="true">
+ <div style="width: {xpState?.level_progress_pct ?? 0}%"></div>
+ </div>
+ </div>
+ </header>
- function formatDate(iso: string): string {
- try {
- return new Date(iso.replace(" ", "T") + "Z").toLocaleString();
- } catch {
- return iso;
- }
- }
+ <nav class="focus-rail" aria-label={$t("study.focus.settings_title") as string}>
+ <button
+ type="button"
+ class="rail-btn"
+ class:active={panel === "settings"}
+ onclick={() => togglePanel("settings")}
+ aria-label={$t("study.focus.settings_title") as string}
+ title={$t("study.focus.settings_title") as string}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M12 8.5a3.5 3.5 0 1 1 0 7a3.5 3.5 0 0 1 0-7Z" />
+ <path d="M19 13.5v-3l-2.1-.5a7 7 0 0 0-.7-1.6l1.1-1.9-2.1-2.1-1.9 1.1a7 7 0 0 0-1.6-.7L11.2 2H8.3l-.5 2.1a7 7 0 0 0-1.6.7L4.3 3.7 2.2 5.8l1.1 1.9a7 7 0 0 0-.7 1.6L.5 9.8v3l2.1.5a7 7 0 0 0 .7 1.6l-1.1 1.9 2.1 2.1 1.9-1.1a7 7 0 0 0 1.6.7l.5 2.1h2.9l.5-2.1a7 7 0 0 0 1.6-.7l1.9 1.1 2.1-2.1-1.1-1.9a7 7 0 0 0 .7-1.6l2.1-.5Z" />
+ </svg>
+ </button>
+ <button
+ type="button"
+ class="rail-btn"
+ class:active={panel === "history"}
+ onclick={() => togglePanel("history")}
+ aria-label={$t("study.focus.history") as string}
+ title={$t("study.focus.history") as string}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M4 19V5" />
+ <path d="M8 17V9" />
+ <path d="M12 15V7" />
+ <path d="M16 19V11" />
+ <path d="M20 13V5" />
+ </svg>
+ </button>
+ <button
+ type="button"
+ class="rail-btn"
+ class:active={panel === "intent"}
+ onclick={() => togglePanel("intent")}
+ aria-label={$t("study.focus.intent_label") as string}
+ title={$t("study.focus.intent_label") as string}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M12 3v18" />
+ <path d="M3 12h18" />
+ <circle cx="12" cy="12" r="7" />
+ </svg>
+ </button>
+ <a class="rail-btn" href="/study/progress" aria-label={$t("study.hub.progress") as string} title={$t("study.hub.progress") as string}>
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M4 18l5-5 4 4 7-9" />
+ <path d="M14 8h6v6" />
+ </svg>
+ </a>
+ <a class="rail-btn" href="/study/music" aria-label={$t("study.hub.music") as string} title={$t("study.hub.music") as string}>
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M9 18V5l11-2v13" />
+ <circle cx="6" cy="18" r="3" />
+ <circle cx="17" cy="16" r="3" />
+ </svg>
+ </a>
+ <button
+ type="button"
+ class="rail-btn exit"
+ onclick={exitFullscreen}
+ aria-label={$t("study.music.exit") as string}
+ title={$t("study.music.exit") as string}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M18 6 6 18" />
+ <path d="m6 6 12 12" />
+ </svg>
+ </button>
+ </nav>
- function presetLabel(id: string): string {
- const p = PRESETS.find((x) => x.id === id);
- return p ? $t(p.labelKey) : id;
- }
-</script>
+ <main class="timer-stage" aria-busy={loading}>
+ <div class="mode-tabs" role="tablist" aria-label={$t("study.focus.title") as string}>
+ {#each MODES as mode (mode.kind)}
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeKind === mode.kind}
+ class:active={activeKind === mode.kind}
+ onclick={() => {
+ if (!current) selectedKind = mode.kind;
+ }}
+ disabled={!!current}
+ >
+ <span>{mode.badge}</span>
+ {$t(mode.labelKey)}
+ </button>
+ {/each}
+ </div>
-<section
- class="study-page"
- data-mode={current ? "active" : "idle"}
- data-low-time={isLowTime ? "1" : "0"}
- data-finished={isFinished ? "1" : "0"}
->
- {#if !current}
- <PageHero title={$t("study.focus.title")} subtitle={$t("study.focus.placeholder")} />
- {/if}
+ <button
+ type="button"
+ class="goal-pill"
+ onclick={() => togglePanel("settings")}
+ aria-label={$t("study.focus.acc_cycles_title") as string}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <circle cx="12" cy="12" r="8" />
+ <circle cx="12" cy="12" r="3" />
+ </svg>
+ <span>{$t("study.focus.today_progress")}</span>
+ <strong>{history.today_minutes}/{goalMinutes}</strong>
+ </button>
- {#if loading}
- <p class="muted">{$t("study.common.loading")}</p>
- {:else if current}
- <div class="session">
- <div class="timer-stage">
- <div class="timer-display">
- {#if remaining != null}
- <span class="timer-big">{fmt(remaining)}</span>
- {:else}
- <span class="timer-big">{fmt(elapsedSec)}</span>
- {/if}
- </div>
- <div class="session-meta">
- <span class="status-dot" aria-hidden="true"></span>
- <span class="session-preset">{presetLabel(current.preset)}</span>
- </div>
- {#if rpcCustomText.trim()}
- <div class="session-intent">
- <span class="intent-label">{$t("study.focus.intent_for")}</span>
- <input
- type="text"
- class="intent-input intent-inline"
- value={rpcCustomText}
- oninput={(e) => saveRpcText((e.currentTarget as HTMLInputElement).value)}
- placeholder={$t("study.focus.intent_placeholder") as string}
- maxlength="48"
- />
+ <section class="timer-readout" aria-live="polite">
+ {#if displayMode === "standard"}
+ <div class="timer-big" class:finished={isFinished}>{timerText}</div>
+ {:else}
+ <div class="line-display" aria-label={timerText}>
+ <div class="line-track">
+ <div class="line-fill" style="width: {progressPct}%"></div>
+ <div class="line-knob" style="left: {progressPct}%"></div>
</div>
- {/if}
- <div class="session-actions">
- <button type="button" class="btn-stop" onclick={stop}>
- {$t("study.focus.stop")}
- </button>
+ <span>{timerText}</span>
</div>
+ {/if}
+ <div class="timer-meta">
+ <span class="live-dot" aria-hidden="true"></span>
+ <span>{current ? $t("study.focus.running") : $t(activeMode.labelKey)}</span>
+ {#if targetMinutes > 0}
+ <span>{targetMinutes}{$t("study.focus.min")}</span>
+ {/if}
</div>
- <div class="session-progress" aria-hidden="true">
- <div class="session-progress-fill" style="width: {sessionPct}%"></div>
- </div>
+ </section>
+
+ {#if rpcCustomText.trim()}
+ <button type="button" class="intent-pill" onclick={() => togglePanel("intent")}>
+ <span>{$t("study.focus.intent_for")}</span>
+ <strong>{rpcCustomText}</strong>
+ </button>
+ {/if}
+
+ <div class="timer-actions">
+ {#if current}
+ <button type="button" class="primary-action" onclick={() => stop()}>
+ {$t(isFinished ? "study.focus.session_ended" : "study.focus.stop")}
+ </button>
+ <button type="button" class="secondary-action" onclick={() => persistDisplay(displayMode === "standard" ? "line" : "standard")}>
+ {displayMode === "standard" ? "Line" : "Timer"}
+ </button>
+ {:else}
+ <button type="button" class="primary-action" disabled={loading} onclick={() => start()}>
+ {$t("study.focus.start")}
+ </button>
+ <button type="button" class="secondary-action" onclick={() => togglePanel("settings")}>
+ {$t("study.focus.settings_title")}
+ </button>
+ {/if}
</div>
- {:else}
- <div class="card-hero-start">
- <span class="hero-eyebrow">{$t("study.focus.start_now")}</span>
+ </main>
- <div class="intent-row">
- <label class="intent-label-block" for="focus-intent">
- {$t("study.focus.intent_label")}
- </label>
- <div class="intent-input-wrap">
- <span class="intent-prefix">{$t("study.focus.intent_prefix")}</span>
+ <aside class={`focus-panel ${panel === "settings" ? "settings-open" : ""}`} class:open={panel !== null} aria-hidden={panel === null}>
+ <button type="button" class="panel-close" onclick={() => (panel = null)} aria-label={$t("study.common.close") as string}>
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M18 6 6 18" />
+ <path d="m6 6 12 12" />
+ </svg>
+ </button>
+
+ {#if panel === "settings"}
+ <div class="settings-shell">
+ <header class="settings-head">
+ <div>
+ <p class="panel-kicker">Focus</p>
+ <h2>{$t("study.focus.settings_title")}</h2>
+ </div>
+ <span class="save-state">
+ {savingState === "saving"
+ ? $t("study.focus.settings_saving")
+ : savingState === "saved"
+ ? $t("study.focus.settings_saved")
+ : "Auto-save"}
+ </span>
+ </header>
+
+ <div class="settings-body">
+ <nav class="settings-tabs" aria-label={$t("study.focus.settings_title") as string}>
+ {#each SETTINGS_TABS as tab (tab.id)}
+ {@const active = settingsTab === tab.id}
+ <button
+ type="button"
+ class="settings-tab"
+ class:active
+ onclick={() => (settingsTab = tab.id)}
+ >
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d={tab.icon}></path>
+ </svg>
+ <span>{$t(tab.labelKey)}</span>
+ </button>
+ {/each}
+ </nav>
+
+ <div class="settings-content">
+ {#if settingsTab === "timer"}
+ <section class="settings-pane" aria-labelledby="focus-timer-settings">
+ <h3 id="focus-timer-settings">{$t("study.focus.acc_cycles_title")}</h3>
+ <p class="settings-note">{$t("study.focus.acc_cycles_summary", { focus: settings.pomodoro_minutes, break: settings.short_break_minutes, cycles: settings.cycles_before_long_break })}</p>
+
+ <div class="settings-group">
+ <div class="number-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_cycles_focus")}</strong>
+ <small>{$t("study.focus.preset_pomodoro")}</small>
+ </span>
+ <div class="number-stepper">
+ <button type="button" onclick={() => adjustNumberSetting("pomodoro_minutes", -1, 1, 120)} aria-label="Decrease">-</button>
+ <input type="number" min="1" max="120" bind:value={settings.pomodoro_minutes} oninput={saveSettings} />
+ <button type="button" onclick={() => adjustNumberSetting("pomodoro_minutes", 1, 1, 120)} aria-label="Increase">+</button>
+ </div>
+ </div>
+
+ <div class="number-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_cycles_short")}</strong>
+ <small>{$t("study.focus.preset_short_break")}</small>
+ </span>
+ <div class="number-stepper">
+ <button type="button" onclick={() => adjustNumberSetting("short_break_minutes", -1, 1, 60)} aria-label="Decrease">-</button>
+ <input type="number" min="1" max="60" bind:value={settings.short_break_minutes} oninput={saveSettings} />
+ <button type="button" onclick={() => adjustNumberSetting("short_break_minutes", 1, 1, 60)} aria-label="Increase">+</button>
+ </div>
+ </div>
+
+ <div class="number-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_cycles_long")}</strong>
+ <small>{$t("study.focus.preset_long_break")}</small>
+ </span>
+ <div class="number-stepper">
+ <button type="button" onclick={() => adjustNumberSetting("long_break_minutes", -1, 1, 60)} aria-label="Decrease">-</button>
+ <input type="number" min="1" max="60" bind:value={settings.long_break_minutes} oninput={saveSettings} />
+ <button type="button" onclick={() => adjustNumberSetting("long_break_minutes", 1, 1, 60)} aria-label="Increase">+</button>
+ </div>
+ </div>
+
+ <div class="number-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_cycles_count")}</strong>
+ <small>{$t("study.focus.cycles")}</small>
+ </span>
+ <div class="number-stepper">
+ <button type="button" onclick={() => adjustNumberSetting("cycles_before_long_break", -1, 1, 10)} aria-label="Decrease">-</button>
+ <input type="number" min="1" max="10" bind:value={settings.cycles_before_long_break} oninput={saveSettings} />
+ <button type="button" onclick={() => adjustNumberSetting("cycles_before_long_break", 1, 1, 10)} aria-label="Increase">+</button>
+ </div>
+ </div>
+ </div>
+ </section>
+ {:else if settingsTab === "appearance"}
+ <section class="settings-pane" aria-labelledby="focus-appearance-settings">
+ <h3 id="focus-appearance-settings">{$t("settings.cat_appearance")}</h3>
+ <p class="settings-note">Scene and timer display stay local to this device.</p>
+
+ <div class="settings-group">
+ <div class="option-setting">
+ <span class="setting-copy">
+ <strong>Scene</strong>
+ <small>Background mood</small>
+ </span>
+ <div class="visual-options">
+ {#each SCENES as scene (scene.id)}
+ <button type="button" class:active={sceneId === scene.id} onclick={() => persistScene(scene.id)}>
+ <strong>{scene.label}</strong>
+ <small>{scene.hint}</small>
+ </button>
+ {/each}
+ </div>
+ </div>
+
+ <div class="option-setting">
+ <span class="setting-copy">
+ <strong>Display</strong>
+ <small>Timer face</small>
+ </span>
+ <div class="visual-options">
+ <button type="button" class:active={displayMode === "standard"} onclick={() => persistDisplay("standard")}>
+ Timer
+ </button>
+ <button type="button" class:active={displayMode === "line"} onclick={() => persistDisplay("line")}>
+ Line
+ </button>
+ </div>
+ </div>
+ </div>
+ </section>
+ {:else if settingsTab === "sounds"}
+ <section class="settings-pane" aria-labelledby="focus-sound-settings">
+ <h3 id="focus-sound-settings">{$t("study.focus.acc_sounds_title")}</h3>
+ <p class="settings-note">
+ Focus Radio is local, instant and made for this screen. Use the music library for real tracks.
+ </p>
+
+ <div class="settings-group">
+ <div class="option-setting">
+ <span class="setting-copy">
+ <strong>Focus Radio</strong>
+ <small>{activeMixInfo.subtitle}</small>
+ </span>
+ <div class="visual-options mix-options">
+ {#each FOCUS_MIXES as mix (mix.id)}
+ <button type="button" class:active={activeMix === mix.id} onclick={() => selectFocusMix(mix.id)}>
+ <strong>{mix.label}</strong>
+ <small>{mix.mood}</small>
+ </button>
+ {/each}
+ </div>
+ </div>
+ <label class="range-setting">
+ <span class="setting-copy">
+ <strong>Radio volume</strong>
+ <small>{focusRadioPlaying ? "playing" : "ready"}</small>
+ </span>
+ <div class="range-control">
+ <input
+ type="range"
+ min="0"
+ max="100"
+ value={focusRadioVolume}
+ oninput={(e) => setFocusRadioVolume(Number((e.currentTarget as HTMLInputElement).value))}
+ />
+ <span>{focusRadioVolume}%</span>
+ </div>
+ </label>
+ </div>
+
+ <div class="settings-group">
+ <div class="ambient-head">
+ <span class="setting-copy">
+ <strong>Ambient mixer</strong>
+ <small>Rain, cafe, waves and low noise layers</small>
+ </span>
+ <button type="button" class="mini-toggle" class:active={ambientPower} onclick={toggleAmbientPower}>
+ {ambientPower ? "On" : "Off"}
+ </button>
+ </div>
+ {#each AMBIENT_SOUNDS as sound (sound.id)}
+ <label class="range-setting compact">
+ <span class="setting-copy">
+ <strong>{sound.label}</strong>
+ <small>{ambientVolumes[sound.id]}%</small>
+ </span>
+ <div class="range-control">
+ <input
+ type="range"
+ min="0"
+ max="100"
+ value={ambientVolumes[sound.id]}
+ oninput={(e) => setAmbientVolume(sound.id, Number((e.currentTarget as HTMLInputElement).value))}
+ />
+ <span>{ambientVolumes[sound.id]}%</span>
+ </div>
+ </label>
+ {/each}
+ </div>
+
+ <div class="settings-group">
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_sounds_check_notify")}</strong>
+ <small>{settings.notify_end ? $t("study.focus.acc_sounds_notify_on") : $t("study.focus.acc_sounds_notify_off")}</small>
+ </span>
+ <input type="checkbox" bind:checked={settings.notify_end} onchange={saveSettings} />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_sounds_check_sound")}</strong>
+ <small>{settings.notify_sound ? $t("study.focus.acc_sounds_sound_on", { n: settings.sound_volume }) : $t("study.focus.acc_sounds_sound_off")}</small>
+ </span>
+ <input type="checkbox" bind:checked={settings.notify_sound} onchange={saveSettings} />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+
+ <label class="range-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_sounds_volume", { n: settings.sound_volume })}</strong>
+ <small>{$t("study.focus.notifications.sound_volume")}</small>
+ </span>
+ <div class="range-control">
+ <input type="range" min="0" max="100" bind:value={settings.sound_volume} oninput={saveSettings} disabled={!settings.notify_sound} />
+ <span>{settings.sound_volume}%</span>
+ </div>
+ </label>
+ </div>
+ </section>
+ {:else if settingsTab === "automation"}
+ <section class="settings-pane" aria-labelledby="focus-automation-settings">
+ <h3 id="focus-automation-settings">{$t("study.focus.acc_breaks_title")}</h3>
+ <p class="settings-note">{$t("study.focus.config_autostart")}</p>
+
+ <div class="settings-group">
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_breaks_check_breaks")}</strong>
+ <small>{settings.auto_start_breaks ? $t("study.focus.acc_breaks_auto_yes") : $t("study.focus.acc_breaks_auto_no")}</small>
+ </span>
+ <input type="checkbox" bind:checked={settings.auto_start_breaks} onchange={saveSettings} />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_breaks_check_focus")}</strong>
+ <small>{settings.auto_start_focus ? $t("study.focus.acc_breaks_focus_yes") : $t("study.focus.acc_breaks_focus_no")}</small>
+ </span>
+ <input type="checkbox" bind:checked={settings.auto_start_focus} onchange={saveSettings} />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>{$t("study.focus.acc_breaks_check_player")}</strong>
+ <small>{settings.auto_pause_player ? $t("study.focus.acc_breaks_player_yes") : $t("study.focus.acc_breaks_player_no")}</small>
+ </span>
+ <input type="checkbox" bind:checked={settings.auto_pause_player} onchange={saveSettings} />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+
+ <label class="switch-setting">
+ <span class="setting-copy">
+ <strong>Auto-hide focus UI</strong>
+ <small>{autoHideUi ? "hides while the timer runs" : "always visible"}</small>
+ </span>
+ <input
+ type="checkbox"
+ checked={autoHideUi}
+ onchange={(e) => persistAutoHide((e.currentTarget as HTMLInputElement).checked)}
+ />
+ <span class="switch-visual" aria-hidden="true"></span>
+ </label>
+ </div>
+ </section>
+ {/if}
+ </div>
+ </div>
+
+ <footer class="settings-footer">
+ <button type="button" class="settings-reset" onclick={resetFocusSettings}>Reset</button>
+ <button type="button" class="settings-save" disabled>
+ {savingState === "saving"
+ ? $t("study.focus.settings_saving")
+ : savingState === "saved"
+ ? $t("study.focus.settings_saved")
+ : "Saved"}
+ </button>
+ </footer>
+ </div>
+ {:else if panel === "history"}
+ <div class="panel-section">
+ <p class="panel-kicker">{$t("study.focus.history")}</p>
+ <h2>{$t("study.focus.today_session", { n: cyclesToday, min: history.today_minutes })}</h2>
+ <div class="stat-row">
+ <span>{$t("study.focus.this_week")}</span>
+ <strong>{history.week_minutes}{$t("study.focus.min")}</strong>
+ </div>
+ <div class="stat-row">
+ <span>{$t("study.focus.today_progress")}</span>
+ <strong>{goalPct}%</strong>
+ </div>
+ </div>
+ <ol class="history-list">
+ {#each history.sessions.slice(0, 12) as s (s.id)}
+ <li>
+ <span>{presetLabel(s.preset)}</span>
+ <strong>{s.minutes ?? 0}{$t("study.focus.min")}</strong>
+ <small>{formatDate(s.started_at)}</small>
+ </li>
+ {:else}
+ <li class="empty-history">{$t("study.focus.no_history")}</li>
+ {/each}
+ </ol>
+ {:else if panel === "intent"}
+ <div class="panel-section">
+ <p class="panel-kicker">{$t("study.focus.intent_label")}</p>
+ <h2>{$t("study.focus.rpc_default")}</h2>
+ <label class="intent-editor">
+ <span>{$t("study.focus.intent_prefix")}</span>
<input
- id="focus-intent"
type="text"
- class="intent-input"
value={rpcCustomText}
oninput={(e) => saveRpcText((e.currentTarget as HTMLInputElement).value)}
placeholder={$t("study.focus.intent_placeholder") as string}
- autocomplete="off"
maxlength="48"
/>
- {#if rpcCustomText}
- <button
- type="button"
- class="intent-clear"
- onclick={() => saveRpcText("")}
- aria-label={$t("study.common.clear") as string}
- >×</button>
- {/if}
- </div>
- <p class="intent-hint">{$t("study.focus.intent_hint")}</p>
+ </label>
+ <p class="panel-note">{$t("study.focus.intent_hint")}</p>
</div>
+ {/if}
+ </aside>
- <div class="presets-row">
- {#each PRESETS as p (p.id)}
- <button type="button" class="preset" onclick={() => start(p.id)}>
- <span class="preset-time">
- {#if p.minutes > 0}
- <span class="preset-num">{p.minutes}</span>
- <span class="preset-unit">min</span>
- {:else}
- <span class="preset-free" aria-label={$t("study.focus.unlimited_aria") as string}>∞</span>
- {/if}
- </span>
- <span class="preset-label">{$t(p.labelKey)}</span>
+ {#if panel === null}
+ <a class="study-pill" href="/study/notes">
+ <span class="study-pill-arrow" aria-hidden="true">‹</span>
+ <span>
+ <strong>{$t("study.hub.notes")}</strong>
+ <small>{$t("study.hub.read")}</small>
+ </span>
+ </a>
+ {/if}
+
+ <div class="music-dock">
+ {#if musicPlayer.currentTrack}
+ <PlayerBar />
+ {:else}
+ <div class="focus-radio-dock">
+ <div class="radio-now">
+ <button
+ type="button"
+ class="radio-play"
+ class:playing={focusRadioPlaying}
+ onclick={toggleFocusRadio}
+ aria-label={focusRadioPlaying ? "Pause Focus Radio" : "Play Focus Radio"}
+ >
+ {focusRadioPlaying ? "Pause" : "Play"}
</button>
- {/each}
- </div>
- {#if history.today_minutes > 0}
- <div class="today-strip">
- <span class="strip-label">{$t("study.focus.today_progress")}</span>
- <span class="strip-value">{history.today_minutes}min</span>
+ <div>
+ <strong>{activeMixInfo.label}</strong>
+ <span>{activeMixInfo.subtitle}</span>
+ </div>
</div>
- {/if}
- </div>
- <div class="settings-accordions">
- <span class="settings-status" class:saving={savingState === "saving"} class:saved={savingState === "saved"}>
- {savingState === "saving"
- ? $t("study.focus.settings_saving")
- : savingState === "saved"
- ? $t("study.focus.settings_saved")
- : ""}
- </span>
-
- <details class="acc">
- <summary>
- <span class="acc-title">{$t("study.focus.acc_cycles_title")}</span>
- <span class="acc-summary">
- {$t("study.focus.acc_cycles_summary", {
- focus: settings.pomodoro_minutes,
- break: settings.short_break_minutes,
- cycles: settings.cycles_before_long_break,
- })}
- </span>
- </summary>
- <div class="acc-body">
- <label class="field">
- <span>{$t("study.focus.acc_cycles_focus")}</span>
- <input
- type="number"
- min="1"
- max="180"
- bind:value={settings.pomodoro_minutes}
- oninput={saveSettings}
- />
- </label>
- <label class="field">
- <span>{$t("study.focus.acc_cycles_short")}</span>
- <input
- type="number"
- min="1"
- max="60"
- bind:value={settings.short_break_minutes}
- oninput={saveSettings}
- />
- </label>
- <label class="field">
- <span>{$t("study.focus.acc_cycles_long")}</span>
- <input
- type="number"
- min="1"
- max="60"
- bind:value={settings.long_break_minutes}
- oninput={saveSettings}
- />
- </label>
- <label class="field">
- <span>{$t("study.focus.acc_cycles_count")}</span>
- <input
- type="number"
- min="2"
- max="10"
- bind:value={settings.cycles_before_long_break}
- oninput={saveSettings}
- />
- </label>
- </div>
- </details>
-
- <details class="acc">
- <summary>
- <span class="acc-title">{$t("study.focus.acc_breaks_title")}</span>
- <span class="acc-summary">
- {settings.auto_start_breaks
- ? $t("study.focus.acc_breaks_auto_yes")
- : $t("study.focus.acc_breaks_auto_no")} ·
- {settings.auto_start_focus
- ? $t("study.focus.acc_breaks_focus_yes")
- : $t("study.focus.acc_breaks_focus_no")} ·
- {settings.auto_pause_player
- ? $t("study.focus.acc_breaks_player_yes")
- : $t("study.focus.acc_breaks_player_no")}
- </span>
- </summary>
- <div class="acc-body">
- <label class="check">
- <input
- type="checkbox"
- bind:checked={settings.auto_start_breaks}
- onchange={saveSettings}
- />
- <span>{$t("study.focus.acc_breaks_check_breaks")}</span>
- </label>
- <label class="check">
- <input
- type="checkbox"
- bind:checked={settings.auto_start_focus}
- onchange={saveSettings}
- />
- <span>{$t("study.focus.acc_breaks_check_focus")}</span>
- </label>
- <label class="check">
- <input
- type="checkbox"
- bind:checked={settings.auto_pause_player}
- onchange={saveSettings}
- />
- <span>{$t("study.focus.acc_breaks_check_player")}</span>
- </label>
- </div>
- </details>
-
- <details class="acc">
- <summary>
- <span class="acc-title">{$t("study.focus.acc_sounds_title")}</span>
- <span class="acc-summary">
- {settings.notify_end
- ? $t("study.focus.acc_sounds_notify_on")
- : $t("study.focus.acc_sounds_notify_off")} ·
- {settings.notify_sound
- ? $t("study.focus.acc_sounds_sound_on", { n: settings.sound_volume })
- : $t("study.focus.acc_sounds_sound_off")}
- </span>
- </summary>
- <div class="acc-body">
- <label class="check">
- <input
- type="checkbox"
- bind:checked={settings.notify_end}
- onchange={saveSettings}
- />
- <span>{$t("study.focus.acc_sounds_check_notify")}</span>
- </label>
- <label class="check">
- <input
- type="checkbox"
- bind:checked={settings.notify_sound}
- onchange={saveSettings}
- />
- <span>{$t("study.focus.acc_sounds_check_sound")}</span>
- </label>
- <label class="field">
- <span>{$t("study.focus.acc_sounds_volume", { n: settings.sound_volume })}</span>
- <input
- type="range"
- min="0"
- max="100"
- bind:value={settings.sound_volume}
- oninput={saveSettings}
- disabled={!settings.notify_sound}
- />
- </label>
+ <div class="radio-mixes" aria-label="Focus radio mixes">
+ {#each FOCUS_MIXES as mix (mix.id)}
+ <button type="button" class:active={activeMix === mix.id} onclick={() => selectFocusMix(mix.id)}>
+ {mix.label}
+ </button>
+ {/each}
</div>
- </details>
- </div>
- {#if history.sessions.length > 0}
- <details class="history-section" open={history.sessions.length <= 5}>
- <summary>
- <span class="summary-label">{$t("study.focus.history")}</span>
- <span class="history-count">{history.sessions.length}</span>
- </summary>
- <ul class="list">
- {#each history.sessions as s (s.id)}
- <li class="row">
- <span class="preset-tag">{presetLabel(s.preset)}</span>
- <span class="minutes">{s.minutes ?? 0}min</span>
- <span class="date">{formatDate(s.started_at)}</span>
- </li>
- {/each}
- </ul>
- </details>
+ <div class="radio-actions">
+ <button type="button" class:active={ambientPower} onclick={toggleAmbientPower}>
+ Ambient
+ </button>
+ <a href="/study/music">Library</a>
+ </div>
+ </div>
{/if}
- {/if}
-
- <footer class="study-footer">
- <AboutLink variant="inline" />
- </footer>
-</section>
+ </div>
+</div>
<style>
- .study-page {
- display: flex;
- flex-direction: column;
- gap: calc(var(--padding) * 1.5);
- width: 100%;
- max-width: 900px;
- margin-inline: auto;
- }
- .study-footer {
- display: flex;
- justify-content: center;
- margin-top: var(--space-5, 20px);
- padding-top: 12px;
- border-top: 1px solid color-mix(in oklab, var(--border) 50%, transparent);
+ .focus-shell {
+ --focus-ink: oklch(96% 0.01 85);
+ --focus-muted: oklch(78% 0.025 235);
+ --focus-panel: oklch(18% 0.025 260 / 0.9);
+ --focus-panel-strong: oklch(14% 0.018 260 / 0.985);
+ --focus-border: oklch(96% 0.01 85 / 0.14);
+ --focus-accent: oklch(73% 0.16 185);
+ --focus-warm: oklch(78% 0.14 58);
+ --focus-danger: oklch(66% 0.2 25);
+ position: fixed;
+ inset: 0;
+ z-index: 90;
+ overflow: hidden;
+ color: var(--focus-ink);
+ background: oklch(13% 0.03 260);
}
- .study-page[data-mode="active"] {
- min-height: 60vh;
- justify-content: center;
- transition: background-color 10s ease;
+ .ambient-scene,
+ .scene-shade {
+ position: absolute;
+ inset: 0;
}
- .study-page[data-mode="active"][data-low-time="1"] {
- background: color-mix(in oklab, var(--warning, var(--accent)) 5%, transparent);
+
+ .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(24% 0.055 250), oklch(13% 0.035 260) 58%, oklch(10% 0.018 250)),
+ linear-gradient(90deg, oklch(18% 0.06 205), oklch(26% 0.06 35));
}
- .muted {
- color: var(--tertiary);
- font-size: 14px;
- text-align: center;
+ .focus-shell[data-scene="garden"] .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(32% 0.08 190), oklch(18% 0.06 155) 56%, oklch(11% 0.03 140)),
+ linear-gradient(90deg, oklch(23% 0.08 115), oklch(27% 0.08 65));
}
- .card-hero-start {
- display: flex;
- flex-direction: column;
- gap: var(--space-5);
- padding: var(--space-5);
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- background: var(--surface);
- box-shadow: var(--elev-1);
- }
- .hero-eyebrow {
- font-size: var(--text-xs);
- font-weight: 600;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-muted);
- }
- .intent-row {
- display: flex;
- flex-direction: column;
- gap: 6px;
- position: relative;
+ .focus-shell[data-scene="night"] .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(16% 0.07 285), oklch(10% 0.04 260) 58%, oklch(8% 0.025 235)),
+ linear-gradient(90deg, oklch(12% 0.06 225), oklch(19% 0.07 315));
}
- .intent-label-block {
- font-size: 12px;
- color: var(--text-muted);
- font-weight: 500;
+
+ .focus-shell[data-scene="library"] .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(24% 0.04 45), oklch(13% 0.028 55) 58%, oklch(8% 0.018 65)),
+ repeating-linear-gradient(90deg, oklch(34% 0.06 45 / 0.55) 0 2.2rem, oklch(19% 0.04 60 / 0.38) 2.2rem 3rem);
}
- .intent-input-wrap {
- display: flex;
- align-items: center;
- gap: 0;
- background: var(--input-bg, rgba(255, 255, 255, 0.04));
- border: 1px solid var(--border);
- border-radius: 999px;
- padding: 4px 4px 4px 14px;
- transition: border-color 120ms ease, background 120ms ease;
+
+ .focus-shell[data-scene="cafe"] .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(31% 0.055 70), oklch(17% 0.045 42) 56%, oklch(10% 0.026 36)),
+ radial-gradient(circle at 72% 22%, oklch(78% 0.13 72 / 0.18), transparent 30rem);
}
- .intent-input-wrap:focus-within {
- border-color: var(--accent);
- background: color-mix(in oklab, var(--accent) 4%, var(--surface));
+
+ .focus-shell[data-scene="ocean"] .ambient-scene {
+ background:
+ linear-gradient(180deg, oklch(34% 0.08 215), oklch(18% 0.07 205) 58%, oklch(9% 0.035 218)),
+ linear-gradient(110deg, oklch(58% 0.11 185 / 0.18), transparent 52%);
}
- .intent-prefix {
- color: var(--text-muted);
- font-size: 14px;
- font-weight: 500;
- padding-right: 6px;
- flex-shrink: 0;
+
+ .focus-shell[data-scene="library"] .scene-window {
+ width: min(22rem, 26vw);
+ background:
+ repeating-linear-gradient(90deg, oklch(72% 0.12 55 / 0.32) 0 1.4rem, transparent 1.4rem 2.1rem),
+ linear-gradient(180deg, oklch(31% 0.06 57 / 0.55), oklch(16% 0.04 50 / 0.24));
}
- .intent-input {
- flex: 1;
- border: 0;
- background: transparent;
- color: var(--text);
- font-family: inherit;
- font-size: 14px;
- padding: 8px 0;
- outline: none;
+
+ .focus-shell[data-scene="cafe"] .scene-lamp {
+ border-bottom-color: oklch(80% 0.14 72 / 0.95);
+ opacity: 1;
}
- .intent-input::placeholder {
- color: color-mix(in oklab, var(--text-muted) 70%, transparent);
+
+ .focus-shell[data-scene="ocean"] .scene-desk {
+ background:
+ linear-gradient(180deg, oklch(42% 0.08 205 / 0.72), oklch(15% 0.05 220 / 0.9)),
+ repeating-linear-gradient(90deg, transparent 0 7rem, oklch(80% 0.08 190 / 0.08) 7rem 7.5rem);
}
- .intent-clear {
- width: 26px;
- height: 26px;
- padding: 0;
- background: transparent;
- border: 0;
- border-radius: 50%;
- color: var(--text-muted);
- font-size: 16px;
- line-height: 1;
- cursor: pointer;
- flex-shrink: 0;
+
+ .scene-window {
+ position: absolute;
+ top: 8%;
+ left: 11%;
+ width: min(32rem, 34vw);
+ height: 42vh;
+ border: 1px solid oklch(96% 0.02 80 / 0.16);
+ border-radius: 8px;
+ background:
+ linear-gradient(90deg, transparent 49.5%, oklch(96% 0.02 80 / 0.13) 50%, transparent 50.5%),
+ linear-gradient(180deg, transparent 49.5%, oklch(96% 0.02 80 / 0.13) 50%, transparent 50.5%),
+ linear-gradient(180deg, oklch(55% 0.13 210 / 0.38), oklch(22% 0.08 260 / 0.22));
+ box-shadow: 0 34px 90px oklch(8% 0.03 260 / 0.42);
}
- .intent-clear:hover {
- background: color-mix(in oklab, var(--text-muted) 12%, transparent);
- color: var(--text);
+
+ .scene-shelf {
+ position: absolute;
+ top: 18%;
+ right: 10%;
+ width: min(27rem, 29vw);
+ height: 12rem;
+ border-bottom: 1rem solid oklch(30% 0.06 55 / 0.74);
+ background:
+ linear-gradient(90deg, oklch(78% 0.13 60 / 0.38) 0 8%, transparent 8% 13%, oklch(62% 0.15 30 / 0.38) 13% 20%, transparent 20% 28%, oklch(72% 0.1 155 / 0.38) 28% 34%, transparent 34%),
+ linear-gradient(180deg, transparent 68%, oklch(96% 0.02 80 / 0.08) 69% 72%, transparent 73%);
+ opacity: 0.72;
}
- .intent-suggestions {
+
+ .scene-desk {
position: absolute;
- top: 100%;
left: 0;
right: 0;
- margin-top: 4px;
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- padding: 8px;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- box-shadow: var(--elev-2, 0 8px 24px rgba(0, 0, 0, 0.2));
- z-index: 5;
+ bottom: 5rem;
+ height: 20vh;
+ background:
+ linear-gradient(180deg, oklch(36% 0.055 50 / 0.86), oklch(20% 0.045 50 / 0.92)),
+ linear-gradient(90deg, transparent, oklch(84% 0.09 70 / 0.12), transparent);
+ transform: skewY(-1deg);
+ transform-origin: left bottom;
}
- .suggestion {
- padding: 5px 12px;
- border: 1px solid var(--border);
- border-radius: 999px;
- background: transparent;
- color: var(--text-muted);
- font-family: inherit;
- font-size: 12px;
- cursor: pointer;
- transition: color 120ms ease, border-color 120ms ease, background 120ms ease;
+
+ .scene-lamp {
+ position: absolute;
+ right: 22%;
+ bottom: 22%;
+ width: 10rem;
+ height: 12rem;
+ border-bottom: 1.2rem solid oklch(76% 0.13 66 / 0.82);
+ background:
+ linear-gradient(90deg, transparent 42%, oklch(75% 0.05 70 / 0.28) 42% 48%, transparent 48%),
+ linear-gradient(135deg, transparent 18%, oklch(85% 0.14 70 / 0.2) 18% 48%, transparent 49%);
+ opacity: 0.82;
}
- .suggestion:hover {
- color: var(--accent);
- border-color: var(--accent);
- background: color-mix(in oklab, var(--accent) 8%, transparent);
+
+ .scene-shade {
+ background:
+ linear-gradient(180deg, oklch(0% 0 0 / 0.16), transparent 42%, oklch(0% 0 0 / 0.34)),
+ linear-gradient(90deg, oklch(0% 0 0 / 0.22), transparent 24%, transparent 70%, oklch(0% 0 0 / 0.18));
+ pointer-events: none;
+ }
+
+ .focus-shell[data-ui-idle="1"] .focus-status,
+ .focus-shell[data-ui-idle="1"] .focus-rail,
+ .focus-shell[data-ui-idle="1"] .mode-tabs,
+ .focus-shell[data-ui-idle="1"] .goal-pill,
+ .focus-shell[data-ui-idle="1"] .intent-pill,
+ .focus-shell[data-ui-idle="1"] .timer-actions,
+ .focus-shell[data-ui-idle="1"] .music-dock {
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(0.35rem);
}
- .intent-hint {
- margin: 2px 4px 0;
- font-size: 11px;
- color: var(--text-muted);
- line-height: 1.4;
+
+ .focus-status {
+ position: absolute;
+ top: calc(1rem + env(safe-area-inset-top));
+ left: calc(1rem + env(safe-area-inset-left));
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ width: min(20rem, calc(100vw - 6rem));
+ padding: 0.9rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: var(--focus-panel-strong);
+ box-shadow: 0 18px 48px oklch(0% 0 0 / 0.3);
}
- .session-intent {
+
+ .focus-brand,
+ .level-block {
display: flex;
align-items: center;
- gap: 6px;
- margin-top: 8px;
- color: var(--text-muted);
- font-size: 13px;
+ gap: 0.75rem;
+ color: var(--focus-ink);
+ text-decoration: none;
}
- .intent-label {
- text-transform: lowercase;
+
+ .brand-mark,
+ .level-seed {
+ display: grid;
+ place-items: center;
+ width: 2.4rem;
+ height: 2.4rem;
+ flex: 0 0 auto;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: oklch(96% 0.01 85 / 0.08);
+ font-weight: 800;
}
- .intent-input.intent-inline {
- border: 0;
- background: transparent;
- padding: 2px 0;
- border-bottom: 1px dashed color-mix(in oklab, var(--text-muted) 40%, transparent);
- color: var(--text);
- font-weight: 600;
- text-align: center;
- min-width: 200px;
+
+ .level-block {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ grid-template-rows: auto auto;
+ }
+
+ .level-copy {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ gap: 0.1rem;
}
- .intent-input.intent-inline:focus {
- border-bottom-color: var(--accent);
+
+ .level-copy strong {
+ font-size: 0.95rem;
}
- .presets-row {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
- gap: calc(var(--padding) * 1.5);
+
+ .level-copy span {
+ color: var(--focus-muted);
+ font-size: 0.78rem;
+ }
+
+ .level-meter {
+ grid-column: 1 / -1;
+ height: 0.35rem;
+ overflow: hidden;
+ border-radius: 999px;
+ background: oklch(96% 0.01 85 / 0.1);
+ }
+
+ .level-meter div {
+ height: 100%;
+ border-radius: inherit;
+ background: linear-gradient(90deg, var(--focus-accent), oklch(72% 0.16 315));
+ transition: width 180ms ease;
}
- .preset {
+
+ .focus-rail {
+ position: absolute;
+ top: calc(1rem + env(safe-area-inset-top));
+ right: calc(1rem + env(safe-area-inset-right));
+ z-index: 3;
display: flex;
flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 8px;
- padding: calc(var(--padding) * 2) var(--padding);
- border: 1px solid var(--input-border);
- border-radius: var(--border-radius);
- background: var(--bg);
- color: var(--secondary);
+ gap: 0.45rem;
+ }
+
+ .rail-btn {
+ display: grid;
+ place-items: center;
+ width: 2.75rem;
+ height: 2.75rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: var(--focus-panel-strong);
+ color: var(--focus-ink);
cursor: pointer;
- transition: border-color 150ms ease, transform 150ms ease, background 150ms ease;
+ transition: transform 140ms ease, border-color 140ms ease, background 140ms ease;
}
- .preset:hover {
- border-color: var(--accent);
+
+ .rail-btn:hover,
+ .rail-btn.active {
+ border-color: oklch(83% 0.12 190 / 0.72);
+ background: oklch(22% 0.035 245 / 0.96);
transform: translateY(-1px);
}
- .preset:focus-visible {
- outline: 2px solid var(--focus-ring, var(--accent));
- outline-offset: 2px;
+
+ .rail-btn.exit:hover {
+ border-color: var(--focus-danger);
}
- .preset:active {
- transform: translateY(0);
- background: color-mix(in oklab, var(--accent) 8%, var(--bg));
+
+ .rail-btn svg {
+ width: 1.05rem;
+ height: 1.05rem;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
}
- .preset-time {
- font-family: var(--font-mono, monospace);
- color: var(--secondary);
- line-height: 1;
- display: inline-flex;
- align-items: baseline;
- gap: 3px;
+
+ .timer-stage {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ min-height: calc(100vh - 6rem);
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 1.25rem;
+ padding: 6rem 1.5rem 8.5rem;
}
- .preset-num {
- font-size: 32px;
- font-weight: 500;
- font-variant-numeric: tabular-nums;
+
+ .mode-tabs {
+ display: flex;
+ gap: 0.35rem;
+ padding: 0.35rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: oklch(0% 0 0 / 0.24);
}
- .preset-unit {
- font-size: 11px;
- font-weight: 400;
- color: var(--tertiary);
- text-transform: uppercase;
+
+ .mode-tabs button {
+ min-width: 7.2rem;
+ height: 2.55rem;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--focus-muted);
+ font: inherit;
+ font-size: 0.9rem;
+ font-weight: 700;
+ cursor: pointer;
+ transition: background 140ms ease, color 140ms ease;
}
- .preset-free {
- font-size: 36px;
- color: var(--accent);
- font-weight: 500;
+
+ .mode-tabs button span {
+ margin-right: 0.45rem;
+ color: oklch(80% 0.03 240 / 0.72);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ font-size: 0.72rem;
}
- .preset-label {
- font-size: 12px;
- color: var(--tertiary);
- text-transform: uppercase;
- letter-spacing: 0.5px;
+
+ .mode-tabs button.active {
+ background: var(--focus-ink);
+ color: oklch(16% 0.025 255);
}
- .today-strip {
- display: flex;
- align-items: baseline;
- gap: 8px;
- padding-top: calc(var(--padding) * 1.5);
- border-top: 1px solid color-mix(in oklab, var(--input-border) 60%, transparent);
- font-size: 13px;
- }
- .strip-label {
- color: var(--tertiary);
- text-transform: uppercase;
- font-size: 10px;
- letter-spacing: 0.8px;
- }
- .strip-value {
- color: var(--secondary);
- font-family: var(--font-mono, monospace);
- font-weight: 500;
- font-variant-numeric: tabular-nums;
+
+ .mode-tabs button:disabled {
+ cursor: default;
}
- .session {
- display: flex;
- flex-direction: column;
+ .goal-pill,
+ .intent-pill {
+ display: inline-flex;
align-items: center;
- gap: calc(var(--padding) * 3);
+ gap: 0.55rem;
+ min-height: 2.35rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: oklch(0% 0 0 / 0.26);
+ color: var(--focus-muted);
+ padding: 0 0.95rem;
+ font: inherit;
+ font-size: 0.78rem;
+ font-weight: 700;
+ cursor: pointer;
}
- .timer-stage {
+
+ .goal-pill svg {
+ width: 0.95rem;
+ height: 0.95rem;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ }
+
+ .goal-pill strong,
+ .intent-pill strong {
+ color: var(--focus-ink);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ }
+
+ .timer-readout {
display: flex;
+ min-height: 11rem;
flex-direction: column;
align-items: center;
- gap: calc(var(--padding) * 2);
- }
- .timer-display {
- padding: calc(var(--padding) * 2) calc(var(--padding) * 4);
+ justify-content: center;
+ gap: 0.75rem;
}
+
.timer-big {
- font-size: 5rem;
- font-family: var(--font-mono, monospace);
- font-weight: 500;
- color: var(--secondary);
+ color: var(--focus-ink);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ font-size: 8.6rem;
+ font-weight: 800;
line-height: 1;
- letter-spacing: -2px;
font-variant-numeric: tabular-nums;
- transition: color 600ms ease;
- }
- .study-page[data-low-time="1"] .timer-big {
- color: var(--warning, var(--accent));
+ text-shadow: 0 16px 38px oklch(0% 0 0 / 0.36);
+ transition: color 260ms ease, opacity 260ms ease;
}
- .study-page[data-finished="1"] .timer-big {
- animation: pulse 1.2s ease-in-out 2;
+
+ .focus-shell[data-low-time="1"] .timer-big {
+ color: var(--focus-warm);
}
- @keyframes pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.4; }
+
+ .timer-big.finished {
+ opacity: 0.72;
}
- .session-meta {
+ .timer-meta {
display: inline-flex;
align-items: center;
- gap: 8px;
- padding: 6px 14px;
- border-radius: 999px;
- background: color-mix(in oklab, var(--accent) 10%, transparent);
- color: var(--secondary);
- font-size: 13px;
- }
- .status-dot {
- display: inline-block;
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: var(--accent);
- animation: dot-pulse 2s ease-in-out infinite;
- }
- @keyframes dot-pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.4; }
- }
- .session-preset {
- text-transform: uppercase;
- font-size: 11px;
- letter-spacing: 0.8px;
- color: var(--tertiary);
- }
- .session-actions {
- display: flex;
- gap: 12px;
+ gap: 0.7rem;
+ color: var(--focus-muted);
+ font-size: 0.86rem;
+ font-weight: 700;
}
- .btn-stop {
- background: transparent;
- border: 1px solid var(--input-border);
- color: var(--secondary);
- border-radius: var(--border-radius);
- padding: 8px 24px;
- font-size: 13px;
- cursor: pointer;
- transition: border-color 150ms ease, color 150ms ease;
+
+ .live-dot {
+ width: 0.55rem;
+ height: 0.55rem;
+ border-radius: 999px;
+ background: currentColor;
+ box-shadow: 0 0 0 0.35rem oklch(96% 0.01 85 / 0.08);
}
- .btn-stop:hover {
- border-color: var(--error);
- color: var(--error);
+
+ .focus-shell[data-active="1"] .live-dot {
+ background: var(--focus-accent);
}
- .btn-stop:focus-visible {
- outline: 2px solid var(--focus-ring, var(--accent));
- outline-offset: 2px;
+
+ .line-display {
+ display: grid;
+ grid-template-columns: minmax(18rem, 34rem) 5rem;
+ align-items: center;
+ gap: 1rem;
}
- .session-progress {
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- height: 2px;
- background: color-mix(in oklab, var(--input-border) 50%, transparent);
- z-index: 10;
- pointer-events: none;
+ .line-track {
+ position: relative;
+ height: 0.35rem;
+ border-radius: 999px;
+ background: oklch(96% 0.01 85 / 0.26);
}
- .session-progress-fill {
+
+ .line-fill {
height: 100%;
- background: var(--accent);
- transition: width 1s linear, background-color 600ms ease;
+ border-radius: inherit;
+ background: var(--focus-ink);
+ transition: width 1s linear;
}
- .study-page[data-low-time="1"] .session-progress-fill {
- background: var(--warning, var(--accent));
+
+ .line-knob {
+ position: absolute;
+ top: 50%;
+ width: 0.9rem;
+ height: 0.9rem;
+ border-radius: 999px;
+ background: var(--focus-ink);
+ transform: translate(-50%, -50%);
+ transition: left 1s linear;
}
- .history-section {
- margin-top: calc(var(--padding) * 0.5);
+ .line-display span {
+ color: var(--focus-ink);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ font-size: 1rem;
+ font-weight: 800;
}
- .history-section summary {
- cursor: pointer;
+
+ .timer-actions {
display: flex;
- align-items: center;
- gap: 8px;
- padding: 8px 0;
- font-size: 13px;
- font-weight: 500;
- color: var(--secondary);
- list-style: none;
+ gap: 0.75rem;
+ }
+
+ .primary-action,
+ .secondary-action {
+ min-width: 8.5rem;
+ height: 3rem;
+ border-radius: 8px;
+ font: inherit;
+ font-size: 1rem;
+ font-weight: 800;
+ cursor: pointer;
+ transition: transform 140ms ease, background 140ms ease, border-color 140ms ease;
}
- .history-section summary::-webkit-details-marker {
- display: none;
+
+ .primary-action {
+ border: 0;
+ background: var(--focus-ink);
+ color: oklch(16% 0.025 255);
}
- .history-section summary::before {
- content: "▸";
- color: var(--tertiary);
- transition: transform 150ms ease;
- display: inline-block;
+
+ .secondary-action {
+ border: 1px solid var(--focus-border);
+ background: oklch(0% 0 0 / 0.2);
+ color: var(--focus-ink);
}
- .history-section[open] summary::before {
- transform: rotate(90deg);
+
+ .primary-action:hover,
+ .secondary-action:hover {
+ transform: translateY(-1px);
}
- .summary-label {
- flex: 0 0 auto;
+
+ .primary-action:disabled {
+ cursor: wait;
+ opacity: 0.65;
}
- .history-count {
- font-family: var(--font-mono, monospace);
- font-size: 11px;
- color: var(--tertiary);
- padding: 1px 8px;
- background: var(--button-elevated);
- border-radius: 999px;
- font-variant-numeric: tabular-nums;
+
+ .focus-panel {
+ position: absolute;
+ top: calc(1rem + env(safe-area-inset-top));
+ right: calc(4.4rem + env(safe-area-inset-right));
+ bottom: calc(6.2rem + env(safe-area-inset-bottom));
+ z-index: 4;
+ width: min(25rem, calc(100vw - 6rem));
+ overflow-y: auto;
+ padding: 1rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: var(--focus-panel-strong);
+ box-shadow: 0 24px 80px oklch(0% 0 0 / 0.36);
+ transform: translateX(calc(100% + 6rem));
+ opacity: 0;
+ pointer-events: none;
+ transition: transform 220ms cubic-bezier(0.22, 1, 0.36, 1), opacity 160ms ease;
}
- .list {
- list-style: none;
- margin: 8px 0 0;
- padding: 0;
+
+ .focus-panel.settings-open {
display: flex;
- flex-direction: column;
- gap: 4px;
- }
- .row {
- display: grid;
- grid-template-columns: auto 80px 1fr;
- gap: var(--padding);
- padding: 8px 12px;
- border: 1px solid var(--input-border);
- border-radius: var(--border-radius);
- background: var(--button-elevated);
- font-size: 12px;
- color: var(--tertiary);
- align-items: center;
+ width: min(43rem, calc(100vw - 6rem));
+ overflow: hidden;
+ padding: 0;
}
- .preset-tag {
- color: var(--secondary);
- font-weight: 500;
+
+ .focus-panel.open {
+ transform: translateX(0);
+ opacity: 1;
+ pointer-events: auto;
}
- .minutes {
- font-family: var(--font-mono, monospace);
- color: var(--accent);
- font-variant-numeric: tabular-nums;
+
+ .panel-close {
+ position: sticky;
+ top: 0;
+ float: right;
+ display: grid;
+ place-items: center;
+ width: 2rem;
+ height: 2rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: oklch(0% 0 0 / 0.28);
+ color: var(--focus-ink);
+ cursor: pointer;
}
- .date {
- justify-self: end;
+
+ .panel-close svg {
+ width: 0.9rem;
+ height: 0.9rem;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 2;
}
- @media (prefers-reduced-motion: reduce) {
- .study-page[data-mode="active"],
- .timer-big,
- .session-progress-fill,
- .preset,
- .history-section summary::before,
- .btn-stop {
- transition: none;
- }
- .study-page[data-finished="1"] .timer-big,
- .status-dot {
- animation: none;
- }
+ .focus-panel.settings-open > .panel-close {
+ position: absolute;
+ top: 0.9rem;
+ right: 0.9rem;
+ z-index: 3;
+ float: none;
}
- .settings-accordions {
+
+ .settings-shell {
display: flex;
+ min-height: 0;
+ width: 100%;
flex-direction: column;
- gap: 4px;
- position: relative;
- margin-top: calc(var(--padding) * 2);
- }
- .settings-status {
- position: absolute;
- top: -22px;
- right: 0;
- font-size: 11px;
- color: var(--tertiary);
- transition: opacity 200ms ease;
}
- .settings-status.saving {
- color: var(--tertiary);
+
+ .settings-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ min-height: 4.5rem;
+ padding: 1rem 3.5rem 1rem 1.1rem;
+ border-bottom: 1px solid var(--focus-border);
}
- .settings-status.saved {
- color: var(--success, var(--accent));
+
+ .settings-head h2 {
+ margin: 0;
+ color: var(--focus-ink);
+ font-size: 1.08rem;
}
- .acc {
- border: 1px solid color-mix(in oklab, var(--input-border) 60%, transparent);
- border-radius: var(--border-radius);
- background: var(--surface);
- overflow: hidden;
- transition: border-color 150ms ease;
+
+ .settings-body {
+ display: grid;
+ grid-template-columns: 10.25rem minmax(0, 1fr);
+ min-height: 0;
+ flex: 1;
}
- .acc[open] {
- border-color: color-mix(in oklab, var(--accent) 40%, var(--input-border));
+
+ .settings-tabs {
+ display: flex;
+ min-height: 0;
+ flex-direction: column;
+ gap: 0.1rem;
+ overflow-y: auto;
+ padding: 0.55rem 0;
+ border-right: 1px solid var(--focus-border);
}
- .acc summary {
+
+ .settings-tab {
+ position: relative;
display: flex;
align-items: center;
- gap: 12px;
- padding: 12px 16px;
+ gap: 0.65rem;
+ width: 100%;
+ min-height: 2.85rem;
+ border: 0;
+ background: transparent;
+ color: var(--focus-muted);
+ padding: 0 0.95rem;
+ font: inherit;
+ font-size: 0.82rem;
+ font-weight: 800;
+ text-align: left;
cursor: pointer;
- list-style: none;
- }
- .acc summary::-webkit-details-marker {
- display: none;
+ transition: background 140ms ease, color 140ms ease;
}
- .acc summary::before {
- content: "›";
- color: var(--tertiary);
- font-size: 16px;
- transition: transform 180ms ease;
- flex-shrink: 0;
+
+ .settings-tab::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 0.45rem;
+ bottom: 0.45rem;
+ width: 2px;
+ border-radius: 999px;
+ background: transparent;
}
- .acc[open] summary::before {
- transform: rotate(90deg);
+
+ .settings-tab:hover,
+ .settings-tab.active {
+ background: oklch(96% 0.01 85 / 0.06);
+ color: var(--focus-ink);
}
- .acc summary:hover {
- background: color-mix(in oklab, var(--accent) 5%, transparent);
+
+ .settings-tab.active::before {
+ background: var(--focus-accent);
}
- .acc-title {
- font-size: 13px;
- font-weight: 600;
- color: var(--text);
+
+ .settings-tab svg {
+ width: 1.05rem;
+ height: 1.05rem;
+ flex: 0 0 auto;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
}
- .acc-summary {
- color: var(--text);
- font-size: var(--text-sm);
- margin-left: auto;
- text-align: right;
+
+ .settings-content {
+ min-height: 0;
+ overflow-y: auto;
+ padding: 1.1rem;
}
- .acc-body {
+
+ .settings-pane {
display: flex;
flex-direction: column;
- gap: 10px;
- padding: 0 16px 16px;
- border-top: 1px solid color-mix(in oklab, var(--input-border) 50%, transparent);
- padding-top: 12px;
+ gap: 0.8rem;
+ }
+
+ .settings-pane h3 {
+ margin: 0;
+ color: var(--focus-ink);
+ font-size: 1rem;
+ }
+
+ .settings-note {
+ margin: -0.25rem 0 0;
+ color: var(--focus-muted);
+ font-size: 0.78rem;
+ line-height: 1.45;
+ }
+
+ .settings-group {
+ overflow: hidden;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: oklch(0% 0 0 / 0.14);
+ }
+
+ .number-setting,
+ .switch-setting,
+ .range-setting,
+ .option-setting {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ min-height: 4.2rem;
+ padding: 0.85rem 0.95rem;
+ border-bottom: 1px solid var(--focus-border);
+ }
+
+ .settings-group > :last-child {
+ border-bottom: 0;
}
- .field {
+
+ .setting-copy {
display: flex;
+ min-width: 0;
flex-direction: column;
- gap: 4px;
- font-size: 12px;
- color: var(--tertiary);
- }
- .field input[type="number"] {
- width: 100px;
- padding: 6px 8px;
- border: 1px solid var(--input-border);
- border-radius: var(--border-radius);
- background: var(--bg);
- color: var(--text);
- font: inherit;
- font-size: 13px;
- font-family: var(--font-mono, ui-monospace, monospace);
+ gap: 0.15rem;
}
- .field input[type="range"] {
- width: 100%;
- accent-color: var(--accent);
+
+ .setting-copy strong {
+ color: var(--focus-ink);
+ font-size: 0.86rem;
}
- .field input:focus {
- outline: none;
- border-color: var(--accent);
+
+ .setting-copy small {
+ color: var(--focus-muted);
+ font-size: 0.72rem;
+ font-weight: 700;
}
- .check {
- display: flex;
+
+ .number-stepper {
+ display: grid;
+ grid-template-columns: 1.9rem 4.2rem 1.9rem;
align-items: center;
- gap: 8px;
- font-size: 13px;
- color: var(--secondary);
- cursor: pointer;
+ gap: 0.35rem;
+ flex: 0 0 auto;
}
- .check input {
- width: 16px;
- height: 16px;
- accent-color: var(--accent);
+
+ .number-stepper button,
+ .number-stepper input {
+ height: 2rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 6px;
+ background: oklch(96% 0.01 85 / 0.08);
+ color: var(--focus-ink);
+ font: inherit;
+ font-weight: 800;
+ }
+
+ .number-stepper button {
+ cursor: pointer;
+ }
+
+ .number-stepper button:hover {
+ border-color: var(--focus-accent);
+ }
+
+ .number-stepper input {
+ width: 100%;
+ text-align: center;
+ appearance: textfield;
+ -moz-appearance: textfield;
+ }
+
+ .number-stepper input::-webkit-outer-spin-button,
+ .number-stepper input::-webkit-inner-spin-button {
+ margin: 0;
+ -webkit-appearance: none;
+ }
+
+ .switch-setting {
+ position: relative;
+ cursor: pointer;
+ }
+
+ .switch-setting input {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .switch-visual {
+ position: relative;
+ width: 2.4rem;
+ height: 1.35rem;
+ flex: 0 0 auto;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: oklch(96% 0.01 85 / 0.08);
+ transition: background 140ms ease, border-color 140ms ease;
+ }
+
+ .switch-visual::after {
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 0.18rem;
+ width: 0.9rem;
+ height: 0.9rem;
+ border-radius: 999px;
+ background: var(--focus-muted);
+ transform: translateY(-50%);
+ transition: transform 140ms ease, background 140ms ease;
+ }
+
+ .switch-setting input:checked + .switch-visual {
+ border-color: oklch(78% 0.13 185 / 0.75);
+ background: oklch(58% 0.13 185 / 0.28);
+ }
+
+ .switch-setting input:checked + .switch-visual::after {
+ background: var(--focus-ink);
+ transform: translate(1.05rem, -50%);
+ }
+
+ .range-setting {
+ align-items: flex-start;
+ grid-template-columns: 1fr;
+ flex-direction: column;
+ }
+
+ .range-setting.compact {
+ min-height: 3.5rem;
+ padding-block: 0.65rem;
+ }
+
+ .range-control {
+ display: grid;
+ grid-template-columns: 1fr 3rem;
+ align-items: center;
+ gap: 0.75rem;
+ width: 100%;
+ }
+
+ .range-control input {
+ accent-color: var(--focus-accent);
+ }
+
+ .range-control input:disabled {
+ opacity: 0.4;
+ }
+
+ .range-control span {
+ color: var(--focus-muted);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ font-size: 0.76rem;
+ font-weight: 800;
+ text-align: right;
+ }
+
+ .option-setting {
+ align-items: flex-start;
+ grid-template-columns: 1fr;
+ flex-direction: column;
+ }
+
+ .visual-options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.45rem;
+ width: 100%;
+ }
+
+ .visual-options button {
+ display: inline-flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 0.08rem;
+ min-height: 2.1rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 6px;
+ background: oklch(96% 0.01 85 / 0.05);
+ color: var(--focus-muted);
+ font: inherit;
+ font-size: 0.78rem;
+ font-weight: 800;
+ padding: 0 0.75rem;
+ cursor: pointer;
+ }
+
+ .visual-options button strong {
+ color: currentColor;
+ font-size: 0.78rem;
+ }
+
+ .visual-options button small {
+ color: var(--focus-muted);
+ font-size: 0.65rem;
+ font-weight: 700;
+ }
+
+ .visual-options button:hover,
+ .visual-options button.active {
+ border-color: var(--focus-accent);
+ color: var(--focus-ink);
+ }
+
+ .mix-options button {
+ min-width: 6.4rem;
+ align-items: flex-start;
+ }
+
+ .ambient-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ min-height: 4rem;
+ padding: 0.85rem 0.95rem;
+ border-bottom: 1px solid var(--focus-border);
+ }
+
+ .mini-toggle {
+ min-width: 3.2rem;
+ min-height: 2rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: oklch(96% 0.01 85 / 0.07);
+ color: var(--focus-muted);
+ font: inherit;
+ font-size: 0.76rem;
+ font-weight: 900;
+ cursor: pointer;
+ }
+
+ .mini-toggle.active,
+ .mini-toggle:hover {
+ border-color: var(--focus-accent);
+ color: var(--focus-ink);
+ }
+
+ .settings-footer {
+ display: flex;
+ gap: 0.75rem;
+ padding: 0.75rem 1rem 1rem;
+ border-top: 1px solid var(--focus-border);
+ }
+
+ .settings-reset,
+ .settings-save {
+ min-height: 2.35rem;
+ flex: 1;
+ border-radius: 8px;
+ font: inherit;
+ font-size: 0.86rem;
+ font-weight: 800;
+ }
+
+ .settings-reset {
+ border: 1px solid var(--focus-border);
+ background: oklch(96% 0.01 85 / 0.07);
+ color: var(--focus-ink);
+ cursor: pointer;
+ }
+
+ .settings-save {
+ border: 0;
+ background: oklch(96% 0.01 85 / 0.16);
+ color: var(--focus-muted);
+ }
+
+ .panel-section {
+ display: flex;
+ flex-direction: column;
+ gap: 0.85rem;
+ padding: 0.55rem 0 1.1rem;
+ border-bottom: 1px solid var(--focus-border);
+ }
+
+ .panel-section:last-child {
+ border-bottom: 0;
+ }
+
+ .panel-kicker {
+ margin: 0;
+ color: var(--focus-muted);
+ font-size: 0.74rem;
+ font-weight: 800;
+ }
+
+ .panel-section h2 {
+ margin: 0;
+ color: var(--focus-ink);
+ font-size: 1.15rem;
+ }
+
+ .field-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.75rem;
+ }
+
+ .field-grid label,
+ .range-row,
+ .intent-editor {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+ color: var(--focus-muted);
+ font-size: 0.78rem;
+ font-weight: 700;
+ }
+
+ .field-grid input,
+ .intent-editor input {
+ width: 100%;
+ height: 2.35rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 6px;
+ background: oklch(0% 0 0 / 0.22);
+ color: var(--focus-ink);
+ font: inherit;
+ padding: 0 0.7rem;
+ }
+
+ .field-grid input:focus,
+ .intent-editor input:focus {
+ border-color: var(--focus-accent);
+ outline: none;
+ }
+
+ .switch-row {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ color: var(--focus-ink);
+ font-size: 0.88rem;
+ font-weight: 700;
+ }
+
+ .switch-row input {
+ width: 1.05rem;
+ height: 1.05rem;
+ accent-color: var(--focus-accent);
+ }
+
+ .range-row input {
+ accent-color: var(--focus-accent);
+ }
+
+ .scene-options {
+ display: flex;
+ gap: 0.45rem;
+ flex-wrap: wrap;
+ }
+
+ .scene-options button {
+ height: 2.15rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--focus-muted);
+ font: inherit;
+ font-size: 0.8rem;
+ font-weight: 800;
+ padding: 0 0.75rem;
+ cursor: pointer;
+ }
+
+ .scene-options button.active,
+ .scene-options button:hover {
+ border-color: var(--focus-accent);
+ color: var(--focus-ink);
+ }
+
+ .save-state,
+ .panel-note {
+ min-height: 1rem;
+ margin: 0;
+ color: var(--focus-muted);
+ font-size: 0.78rem;
+ }
+
+ .stat-row,
+ .history-list li {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 0.5rem;
+ align-items: center;
+ }
+
+ .stat-row {
+ color: var(--focus-muted);
+ font-size: 0.88rem;
+ }
+
+ .stat-row strong {
+ color: var(--focus-ink);
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
+ }
+
+ .history-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }
+
+ .history-list li {
+ padding: 0.7rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: oklch(96% 0.01 85 / 0.05);
+ color: var(--focus-ink);
+ }
+
+ .history-list small {
+ grid-column: 1 / -1;
+ color: var(--focus-muted);
+ }
+
+ .empty-history {
+ display: block;
+ color: var(--focus-muted);
+ }
+
+ .study-pill {
+ position: absolute;
+ right: calc(1rem + env(safe-area-inset-right));
+ bottom: calc(6.4rem + env(safe-area-inset-bottom));
+ z-index: 2;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.7rem;
+ min-height: 4rem;
+ padding: 0.7rem 1rem 0.7rem 0.75rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 8px;
+ background: var(--focus-panel);
+ color: var(--focus-ink);
+ text-decoration: none;
+ transition: opacity 140ms ease, transform 140ms ease;
+ }
+
+ .study-pill-arrow {
+ color: var(--focus-muted);
+ font-size: 1.55rem;
+ line-height: 1;
+ }
+
+ .study-pill span:last-child {
+ display: flex;
+ flex-direction: column;
+ gap: 0.1rem;
+ }
+
+ .study-pill small {
+ color: var(--focus-muted);
+ font-weight: 700;
+ }
+
+ .music-dock {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 5;
+ min-height: 5rem;
+ border-top: 1px solid var(--focus-border);
+ background: oklch(9% 0.018 250 / 0.92);
+ }
+
+ .focus-radio-dock {
+ display: grid;
+ grid-template-columns: minmax(16rem, 1fr) auto minmax(10rem, 1fr);
+ align-items: center;
+ gap: 1rem;
+ min-height: 5rem;
+ padding: 0.75rem 1rem;
+ }
+
+ .radio-now,
+ .radio-actions,
+ .radio-mixes {
+ display: flex;
+ align-items: center;
+ gap: 0.65rem;
+ }
+
+ .radio-now {
+ min-width: 0;
+ }
+
+ .radio-play {
+ min-width: 4.2rem;
+ min-height: 2.25rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: var(--focus-ink);
+ color: oklch(15% 0.025 255);
+ font: inherit;
+ font-size: 0.82rem;
+ font-weight: 900;
+ cursor: pointer;
+ }
+
+ .radio-play.playing {
+ background: oklch(74% 0.14 185);
+ }
+
+ .radio-now div {
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ gap: 0.1rem;
+ }
+
+ .radio-now strong {
+ color: var(--focus-ink);
+ font-size: 0.88rem;
+ }
+
+ .radio-now span {
+ color: var(--focus-muted);
+ font-size: 0.76rem;
+ font-weight: 700;
+ }
+
+ .radio-mixes {
+ justify-content: center;
+ overflow-x: auto;
+ }
+
+ .radio-mixes button,
+ .radio-actions button,
+ .radio-actions a {
+ min-height: 2rem;
+ border: 1px solid var(--focus-border);
+ border-radius: 999px;
+ background: oklch(96% 0.01 85 / 0.06);
+ color: var(--focus-muted);
+ font: inherit;
+ font-size: 0.76rem;
+ font-weight: 900;
+ padding: 0 0.75rem;
+ text-decoration: none;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+
+ .radio-mixes button.active,
+ .radio-mixes button:hover,
+ .radio-actions button.active,
+ .radio-actions button:hover,
+ .radio-actions a:hover {
+ border-color: var(--focus-accent);
+ color: var(--focus-ink);
+ }
+
+ .radio-actions {
+ justify-content: flex-end;
+ }
+
+ button:focus-visible,
+ a:focus-visible {
+ outline: 2px solid var(--focus-accent);
+ outline-offset: 2px;
+ }
+
+ @media (max-width: 900px) {
+ .focus-status {
+ width: min(17rem, calc(100vw - 5.5rem));
+ }
+
+ .mode-tabs {
+ max-width: calc(100vw - 2rem);
+ overflow-x: auto;
+ }
+
+ .mode-tabs button {
+ min-width: 6.8rem;
+ }
+
+ .timer-big {
+ font-size: 6.2rem;
+ }
+
+ .study-pill {
+ display: none;
+ }
+
+ .focus-radio-dock {
+ grid-template-columns: 1fr;
+ gap: 0.55rem;
+ padding: 0.65rem 0.8rem;
+ }
+
+ .radio-now,
+ .radio-actions,
+ .radio-mixes {
+ justify-content: flex-start;
+ }
+
+ .radio-mixes {
+ order: 3;
+ width: 100%;
+ padding-bottom: 0.2rem;
+ }
+ }
+
+ @media (max-width: 640px) {
+ .focus-status {
+ left: 0.75rem;
+ right: 4rem;
+ width: auto;
+ padding: 0.7rem;
+ }
+
+ .focus-brand {
+ font-size: 0.9rem;
+ }
+
+ .level-block {
+ display: none;
+ }
+
+ .focus-rail {
+ top: auto;
+ right: 0.75rem;
+ bottom: 10.2rem;
+ flex-direction: row;
+ }
+
+ .rail-btn {
+ width: 2.45rem;
+ height: 2.45rem;
+ }
+
+ .timer-stage {
+ min-height: calc(100vh - 5rem);
+ padding: 5rem 0.75rem 9rem;
+ gap: 1rem;
+ }
+
+ .timer-big {
+ font-size: 4.6rem;
+ }
+
+ .timer-actions {
+ width: 100%;
+ justify-content: center;
+ }
+
+ .primary-action,
+ .secondary-action {
+ min-width: 0;
+ width: 44%;
+ }
+
+ .focus-panel {
+ inset: auto 0.75rem 5.7rem 0.75rem;
+ width: auto;
+ max-height: 58vh;
+ transform: translateY(calc(100% + 6rem));
+ }
+
+ .focus-panel.settings-open {
+ width: auto;
+ max-height: 72vh;
+ }
+
+ .focus-panel.open {
+ transform: translateY(0);
+ }
+
+ .settings-body {
+ grid-template-columns: 1fr;
+ }
+
+ .settings-tabs {
+ flex-direction: row;
+ overflow-x: auto;
+ border-right: 0;
+ border-bottom: 1px solid var(--focus-border);
+ padding: 0.4rem;
+ }
+
+ .settings-tab {
+ width: auto;
+ min-width: max-content;
+ min-height: 2.35rem;
+ border-radius: 6px;
+ padding: 0 0.75rem;
+ }
+
+ .settings-tab::before {
+ display: none;
+ }
+
+ .settings-content {
+ padding: 0.85rem;
+ }
+
+ .number-setting,
+ .switch-setting {
+ align-items: flex-start;
+ grid-template-columns: 1fr;
+ }
+
+ .field-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .line-display {
+ grid-template-columns: minmax(10rem, 1fr);
+ width: min(28rem, calc(100vw - 2rem));
+ }
+
+ .music-dock {
+ min-height: 6.4rem;
+ }
+
+ .radio-now span {
+ display: none;
+ }
+
+ .radio-actions {
+ gap: 0.45rem;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .level-meter div,
+ .rail-btn,
+ .mode-tabs button,
+ .primary-action,
+ .secondary-action,
+ .focus-panel,
+ .line-fill,
+ .line-knob {
+ transition: none;
+ }
}
</style>
diff --git a/src/routes/study/music/+layout.svelte b/src/routes/study/music/+layout.svelte
index c7befff1..a16125af 100644
--- a/src/routes/study/music/+layout.svelte
+++ b/src/routes/study/music/+layout.svelte
@@ -1,27 +1,48 @@
<script lang="ts">
+ import { onDestroy, onMount } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
import { t } from "$lib/i18n";
import { musicUI } from "$lib/study-music/ui-store.svelte";
import { musicPlayer } from "$lib/study-music/player-store.svelte";
import { musicTheme } from "$lib/study-music/theme-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
import MusicSidebar from "$lib/study-music-components/MusicSidebar.svelte";
import PlayerBar from "$lib/study-music-components/PlayerBar.svelte";
+ import DownloadsDock from "$lib/study-music-components/DownloadsDock.svelte";
let { children } = $props();
- const accentBg = $derived.by(() => {
+ onMount(() => {
+ downloadStore.start();
+ });
+
+ onDestroy(() => {
+ downloadStore.stop();
+ });
+
+ const isFullscreen = $derived($page.url.pathname.startsWith("/study/music/now-playing"));
+
+ const paletteVars = $derived.by(() => {
if (!musicTheme.useDominant) return null;
- const c = musicPlayer.dominantColor;
- if (!c) return null;
+ const palette = musicPlayer.palette;
+ const dominant = palette?.[0] ?? musicPlayer.dominantColor;
+ if (!dominant) return null;
+ const accent = palette?.[1] ?? dominant;
+ const highlight = palette?.[2] ?? accent;
return {
- strong: `rgb(${c.r}, ${c.g}, ${c.b})`,
- mid: `rgba(${c.r}, ${c.g}, ${c.b}, 0.18)`,
- soft: `rgba(${c.r}, ${c.g}, ${c.b}, 0.08)`,
+ dominant: `rgb(${dominant.r}, ${dominant.g}, ${dominant.b})`,
+ accent: `rgb(${accent.r}, ${accent.g}, ${accent.b})`,
+ accentSoft: `rgba(${accent.r}, ${accent.g}, ${accent.b}, 0.18)`,
+ accentMid: `rgba(${accent.r}, ${accent.g}, ${accent.b}, 0.28)`,
+ highlight: `rgb(${highlight.r}, ${highlight.g}, ${highlight.b})`,
+ bgTint: `rgba(${dominant.r}, ${dominant.g}, ${dominant.b}, 0.10)`,
+ scrubberGradient: `linear-gradient(to right, rgb(${accent.r}, ${accent.g}, ${accent.b}), rgb(${highlight.r}, ${highlight.g}, ${highlight.b}))`,
};
});
const themeAccentOverride = $derived(musicTheme.effectiveAccent);
+ const reduceAnimationsAttr = $derived(musicTheme.reduceAnimationsActive ? "true" : null);
function exitFullscreen() {
if (typeof window === "undefined") {
@@ -64,8 +85,10 @@
if (musicUI.contextMenu.open) return;
if (musicUI.selectedCount() > 0) return;
e.preventDefault();
- // Drill-down: se está em subpage de /study/music, volta pra home da aba.
- // Se já está na home (/study/music), exit pra fora do music.
+ if ($page.url.pathname.startsWith("/study/music/now-playing")) {
+ goto("/study/music");
+ return;
+ }
if ($page.url.pathname !== "/study/music") {
goto("/study/music");
} else {
@@ -79,33 +102,45 @@
<div
class="music-shell"
- style:--music-accent={accentBg ? accentBg.strong : 'transparent'}
- style:--music-accent-mid={accentBg ? accentBg.mid : 'transparent'}
- style:--music-accent-soft={accentBg ? accentBg.soft : 'transparent'}
+ class:fullscreen={isFullscreen}
+ data-reduce-animations={reduceAnimationsAttr}
+ style:--music-accent={paletteVars?.accent ?? 'transparent'}
+ style:--music-accent-mid={paletteVars?.accentMid ?? 'transparent'}
+ style:--music-accent-soft={paletteVars?.accentSoft ?? 'transparent'}
+ style:--music-highlight={paletteVars?.highlight ?? 'transparent'}
+ style:--music-bg-tint={paletteVars?.bgTint ?? 'transparent'}
+ style:--music-scrubber-gradient={paletteVars?.scrubberGradient ?? null}
style:--accent={themeAccentOverride ?? null}
>
- <MusicSidebar />
- <main class="music-main">
- <button
- type="button"
- class="exit-btn"
- onclick={exitFullscreen}
- aria-label={$t("study.music.exit") as string}
- title={$t("study.music.exit") as string}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <line x1="18" y1="6" x2="6" y2="18"/>
- <line x1="6" y1="6" x2="18" y2="18"/>
- </svg>
- <span class="esc-hint">ESC</span>
- </button>
- <div class="music-content">
+ {#if !isFullscreen}
+ <MusicSidebar />
+ {/if}
+ <main class="music-main" class:fullscreen={isFullscreen}>
+ {#if !isFullscreen}
+ <button
+ type="button"
+ class="exit-btn"
+ onclick={exitFullscreen}
+ aria-label={$t("study.music.exit") as string}
+ title={$t("study.music.exit") as string}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="18" y1="6" x2="6" y2="18"/>
+ <line x1="6" y1="6" x2="18" y2="18"/>
+ </svg>
+ <span class="esc-hint">ESC</span>
+ </button>
+ {/if}
+ <div class="music-content" class:fullscreen={isFullscreen}>
{@render children()}
</div>
</main>
- <div class="music-player">
- <PlayerBar />
- </div>
+ {#if !isFullscreen}
+ <div class="music-player">
+ <PlayerBar />
+ </div>
+ {/if}
+ <DownloadsDock />
</div>
<style>
@@ -126,6 +161,11 @@
color: var(--secondary);
transition: background 600ms ease;
}
+ .music-shell.fullscreen {
+ grid-template-columns: 1fr;
+ grid-template-rows: 1fr;
+ grid-template-areas: "main";
+ }
.music-shell > :global(aside.music-sidebar) {
grid-area: side;
}
@@ -136,11 +176,20 @@
overflow-x: hidden;
scrollbar-width: thin;
}
+ .music-main.fullscreen {
+ overflow: hidden;
+ }
.music-content {
padding: 24px 32px 32px;
max-width: 1600px;
margin-inline: auto;
}
+ .music-content.fullscreen {
+ padding: 0;
+ max-width: none;
+ margin: 0;
+ height: 100%;
+ }
.music-player {
grid-area: player;
border-top: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
@@ -190,4 +239,12 @@
display: none;
}
}
+ :global(.music-shell[data-reduce-animations="true"] *),
+ :global(.music-shell[data-reduce-animations="true"] *::before),
+ :global(.music-shell[data-reduce-animations="true"] *::after) {
+ animation-duration: 0.001ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.001ms !important;
+ scroll-behavior: auto !important;
+ }
</style>
diff --git a/src/routes/study/music/+page.svelte b/src/routes/study/music/+page.svelte
index 8eb5b82a..46ad6ce1 100644
--- a/src/routes/study/music/+page.svelte
+++ b/src/routes/study/music/+page.svelte
@@ -16,9 +16,15 @@
type ScTrack,
} from "$lib/study-music/soundcloud-store.svelte";
import { colorFromString } from "$lib/study-music/format";
- import AlbumPill from "$lib/study-music-components/AlbumPill.svelte";
+ import {
+ studyMusicContinueListening,
+ type MusicContinueEntry,
+ } from "$lib/study-bridge";
+ import NavigationTitle from "$lib/study-music-components/NavigationTitle.svelte";
+ import SpeedDialGridItem from "$lib/study-music-components/SpeedDialGridItem.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
- type RootEntry = { path: string; enabled: boolean; exists: boolean };
type Album = {
name: string;
artist: string | null;
@@ -29,201 +35,143 @@
};
type Artist = { name: string; album_count: number; track_count: number };
- let roots = $state<RootEntry[]>([]);
- let allAlbums = $state<Album[]>([]);
+ let recentAlbums = $state<Album[]>([]);
let topArtists = $state<Artist[]>([]);
- let artistCovers = $state<Map<string, string>>(new Map());
- let loading = $state(true);
- let scanning = $state(false);
- let scanMsg = $state("");
- let heroAlbum = $state<Album | null>(null);
- let heroFavorite = $state(false);
-
- async function loadAll() {
- loading = true;
- try {
- const [rootsRes, albumsRes, artistsRes] = await Promise.allSettled([
- pluginInvoke<{ roots: RootEntry[] }>("study", "study:music:roots:list"),
- pluginInvoke<{ albums: Album[] }>(
- "study",
- "study:music:albums:list",
- { limit: 60 },
- ),
- pluginInvoke<{ artists: Artist[] }>(
- "study",
- "study:music:artists:list",
- { limit: 40 },
- ),
- ]);
-
- if (rootsRes.status === "fulfilled") roots = rootsRes.value.roots ?? [];
- if (albumsRes.status === "fulfilled") {
- allAlbums = albumsRes.value.albums ?? [];
- const withCover = allAlbums.filter((a) => a.cover_path);
- const pool = withCover.length > 0 ? withCover : allAlbums;
- if (pool.length > 0) {
- heroAlbum = pool[Math.floor(Math.random() * pool.length)];
- }
- }
- if (artistsRes.status === "fulfilled") {
- topArtists = artistsRes.value.artists ?? [];
- }
-
- void resolveArtistCovers();
- } finally {
- loading = false;
+ let continueEntries = $state<MusicContinueEntry[]>([]);
+
+ let loadingHome = $state(true);
+
+ let pullStartY = $state(0);
+ let pullDelta = $state(0);
+ let pullActive = $state(false);
+ let isMobile = $state(false);
+
+ async function loadHome() {
+ loadingHome = true;
+
+ const [continueRes, albumsRes, artistsRes] = await Promise.allSettled([
+ studyMusicContinueListening({ limit: 12 }),
+ pluginInvoke<{ albums: Album[] }>("study", "study:music:albums:list", {
+ sort: "added",
+ limit: 10,
+ }),
+ pluginInvoke<{ artists: Artist[] }>("study", "study:music:artists:list", {
+ limit: 40,
+ }),
+ ]);
+
+ if (continueRes.status === "fulfilled") {
+ continueEntries = (continueRes.value.entries ?? [])
+ .filter((e) => e.source !== "youtube")
+ .slice(0, 8);
}
- }
+ if (albumsRes.status === "fulfilled") recentAlbums = albumsRes.value.albums ?? [];
+ if (artistsRes.status === "fulfilled") topArtists = artistsRes.value.artists ?? [];
- async function resolveArtistCovers() {
- const next = new Map(artistCovers);
- const work = topArtists.slice(0, 20).filter((a) => !next.has(a.name));
- for (const a of work) {
- try {
- const res = await pluginInvoke<{ albums: Album[] }>(
- "study",
- "study:music:albums:list",
- { artist: a.name, limit: 1 },
- );
- const cover = res.albums?.[0]?.cover_path;
- if (cover) next.set(a.name, cover);
- } catch {
- /* ignore */
- }
- }
- artistCovers = next;
- }
-
- async function addRoot() {
- try {
- const dialog = await import("@tauri-apps/plugin-dialog");
- const picked = await dialog.open({ directory: true, multiple: false });
- if (typeof picked !== "string" || !picked) return;
- await pluginInvoke("study", "study:music:roots:add", { path: picked });
- showToast("success", $t("study.music.root_added", { path: picked }) as string);
- await loadAll();
- await runScan();
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- showToast("error", msg);
- }
+ loadingHome = false;
}
- async function runScan() {
- if (scanning) return;
- scanning = true;
- scanMsg = "";
+ function coverUrl(path: string | null | undefined): string | null {
+ if (!path) return null;
+ if (/^https?:\/\//i.test(path)) return path;
+ if (path.startsWith("external://")) return null;
try {
- const res = await pluginInvoke<{ added: number; updated: number; removed: number }>(
- "study",
- "study:music:scan",
- );
- scanMsg = $t("study.music.scan_done", res) as string;
- await loadAll();
- } catch (e) {
- scanMsg = e instanceof Error ? e.message : String(e);
- } finally {
- scanning = false;
- setTimeout(() => (scanMsg = ""), 6000);
+ return convertFileSrc(path);
+ } catch {
+ return path;
}
}
- async function playHero() {
- if (!heroAlbum) return;
+ async function playContinue(entry: MusicContinueEntry) {
try {
- const args: { name: string; artist?: string } = { name: heroAlbum.name };
- if (heroAlbum.artist) args.artist = heroAlbum.artist;
- const res = await pluginInvoke<{ tracks: MusicTrack[] }>(
- "study",
- "study:music:albums:get",
- args,
- );
- if (res.tracks && res.tracks.length > 0) {
- await musicPlayer.play(res.tracks[0], res.tracks);
+ if (entry.track_id != null) {
+ const res = await pluginInvoke<{ track: MusicTrack }>(
+ "study",
+ "study:music:tracks:get",
+ { id: entry.track_id },
+ );
+ if (res.track) await musicPlayer.play(res.track);
}
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- showToast("error", msg);
+ showToast("error", e instanceof Error ? e.message : String(e));
}
}
- function scrollContainer(id: string, dir: 1 | -1) {
- const el = document.getElementById(id);
- if (!el) return;
- el.scrollBy({ left: dir * 360, behavior: "smooth" });
- }
-
- function openAlbum(album: Album) {
+ async function openAlbum(album: Album) {
const params = new URLSearchParams({ name: album.name });
if (album.artist) params.set("artist", album.artist);
- goto(`/study/music/album/by-name?${params.toString()}`);
+ await goto(`/study/music/albums/by-name?${params.toString()}`);
}
- function openArtist(name: string) {
- goto(`/study/music/artist/by-name?name=${encodeURIComponent(name)}`);
+ async function openArtist(artist: Artist) {
+ const params = new URLSearchParams({ name: artist.name });
+ await goto(`/study/music/artist/by-name?${params.toString()}`);
}
function openPlaylist(p: Playlist) {
goto(`/study/music/playlists/${p.id}`);
}
- function coverUrl(path: string | null | undefined): string | null {
- if (!path) return null;
- try {
- return convertFileSrc(path);
- } catch {
- return path;
- }
+ function handleTouchStart(e: TouchEvent) {
+ if (!isMobile) return;
+ const scrollEl = document.scrollingElement ?? document.documentElement;
+ if (scrollEl.scrollTop > 4) return;
+ pullStartY = e.touches[0]?.clientY ?? 0;
+ pullActive = true;
+ }
+ function handleTouchMove(e: TouchEvent) {
+ if (!pullActive) return;
+ const y = e.touches[0]?.clientY ?? 0;
+ pullDelta = Math.max(0, y - pullStartY);
+ }
+ async function handleTouchEnd() {
+ if (!pullActive) return;
+ const should = pullDelta > 100;
+ pullActive = false;
+ pullDelta = 0;
+ if (should) await loadHome();
}
- onMount(async () => {
- void loadAll();
+ onMount(() => {
+ void loadHome();
void playlistsStore.load();
- await spotifyStore.refreshStatus();
- if (
- spotifyStore.status.logged_in &&
- spotifyStore.savedTracks.length === 0 &&
- spotifyStore.recentlyPlayed.length === 0
- ) {
- void spotifyStore.loadAll();
- }
- await soundcloudStore.refreshStatus();
- if (
- soundcloudStore.isLoggedIn &&
- soundcloudStore.likedTracks.length === 0
- ) {
- void soundcloudStore.loadAll();
- }
+ void spotifyStore.refreshStatus().then(() => {
+ if (
+ spotifyStore.status.logged_in &&
+ spotifyStore.savedTracks.length === 0 &&
+ spotifyStore.recentlyPlayed.length === 0
+ ) {
+ void spotifyStore.loadAll();
+ }
+ });
+ void soundcloudStore.refreshStatus().then(() => {
+ if (soundcloudStore.isLoggedIn && soundcloudStore.likedTracks.length === 0) {
+ void soundcloudStore.loadAll();
+ }
+ });
+ isMobile = window.matchMedia("(max-width: 760px)").matches;
});
+ function spotifyCover(images: { url: string; width?: number | null }[] | undefined): string | null {
+ return spotifyStore.pickImage(images, 300);
+ }
+
async function playSc(track: ScTrack, queue?: ScTrack[]) {
try {
await soundcloudStore.playTrack(track, queue);
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- showToast("error", msg);
+ showToast("error", e instanceof Error ? e.message : String(e));
}
}
async function playSpotifyTrack(track: SpotifyTrack, queue?: SpotifyTrack[]) {
try {
- const mode = await spotifyStore.playTrack(track, queue);
- if (mode === "youtube") {
- showToast("info", "Tocando via YouTube (modo Free)");
- }
+ await spotifyStore.playTrack(track, queue);
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- showToast("error", msg);
+ showToast("error", e instanceof Error ? e.message : String(e));
}
}
- function spotifyCover(images: { url: string; width?: number | null }[] | undefined): string | null {
- return spotifyStore.pickImage(images, 300);
- }
-
- const enabledRoots = $derived(roots.filter((r) => r.enabled));
- const noRoots = $derived(roots.length === 0);
- const hasContent = $derived(allAlbums.length > 0 || topArtists.length > 0);
const hasSpotifyContent = $derived(
spotifyStore.status.logged_in &&
(spotifyStore.savedTracks.length > 0 ||
@@ -237,875 +185,451 @@
soundcloudStore.playlists.length > 0 ||
soundcloudStore.streamFeed.length > 0),
);
-
- const recentAlbums = $derived(allAlbums.slice(0, 12));
- const listenNow = $derived.by(() => {
- if (!heroAlbum) return allAlbums.slice(0, 8);
- const heroKey = heroAlbum.name + "|" + (heroAlbum.artist ?? "");
- return allAlbums
- .filter((a) => a.name + "|" + (a.artist ?? "") !== heroKey)
- .slice(0, 8);
- });
</script>
+<svelte:window
+ ontouchstart={handleTouchStart}
+ ontouchmove={handleTouchMove}
+ ontouchend={handleTouchEnd}
+/>
+
<section class="music-home">
- <header class="page-head">
- <h1>{$t("study.music.nav_home")}</h1>
- <div class="head-actions">
- <button type="button" class="ghost-btn" onclick={addRoot}>
- + {$t("study.music.add_root")}
- </button>
- <button
- type="button"
- class="ghost-btn"
- onclick={runScan}
- disabled={scanning || enabledRoots.length === 0}
- >
- {scanning ? $t("study.music.scanning") : $t("study.music.scan_now")}
- </button>
+ {#if pullActive && pullDelta > 0}
+ <div class="pull-indicator" style:--p={Math.min(1, pullDelta / 100)}>
+ {pullDelta > 100 ? $t("study.music.pull_to_refresh_release") : $t("study.music.pull_to_refresh_hint")}
</div>
- </header>
-
- {#if scanMsg}
- <p class="scan-msg">{scanMsg}</p>
{/if}
- {#if loading && !hasSpotifyContent && !hasSoundcloudContent}
- <p class="muted">{$t("study.common.loading")}</p>
- {:else if noRoots && !hasSpotifyContent && !hasSoundcloudContent}
- <div class="empty-music">
- <h2>{$t("study.music.empty_no_roots_title")}</h2>
- <p>{$t("study.music.empty_no_roots_body")}</p>
- <button type="button" class="cta-big" onclick={addRoot}>
- {$t("study.music.add_root_cta")}
- </button>
- </div>
- {:else if !hasContent && !hasSpotifyContent && !hasSoundcloudContent}
- <div class="empty-music">
- <h2>{$t("study.music.empty_no_tracks_title")}</h2>
- <p>{$t("study.music.empty_no_tracks_body")}</p>
- <button type="button" class="cta-big" onclick={runScan} disabled={scanning}>
- {scanning ? $t("study.music.scanning") : $t("study.music.scan_now")}
- </button>
- </div>
- {:else if hasContent}
- {#if heroAlbum}
- <section class="hero">
- <div class="hero-bg" style:background-image={coverUrl(heroAlbum.cover_path) ? `url('${coverUrl(heroAlbum.cover_path)}')` : "none"}></div>
- <div class="hero-overlay"></div>
- <div class="hero-content">
- <span class="hero-eyebrow">
- <svg viewBox="0 0 24 24" width="9" height="9" fill="currentColor" aria-hidden="true">
- <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
- </svg>
- {$t("study.music.jump_back_in")}
- </span>
- <h1 class="hero-title">{heroAlbum.name}</h1>
- {#if heroAlbum.artist}
- <p class="hero-artist">{$t("study.music.by")} {heroAlbum.artist}</p>
- {/if}
- <div class="hero-actions">
- <button type="button" class="hero-play" onclick={playHero}>
- <svg viewBox="0 0 24 24" width="10" height="10" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>
- <span>{$t("study.music.start_listening")}</span>
- </button>
- <button
- type="button"
- class="hero-fav"
- class:on={heroFavorite}
- onclick={() => (heroFavorite = !heroFavorite)}
- aria-label={$t("study.music.favorite") as string}
- >
- <svg viewBox="0 0 24 24" width="13" height="13" fill={heroFavorite ? "currentColor" : "none"} stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
- </svg>
- </button>
- </div>
- </div>
- </section>
- {/if}
-
- {#if listenNow.length > 0}
- <section class="block">
- <header class="block-head">
- <h2>{$t("study.music.shelf_listen_now")}</h2>
- </header>
- <div class="album-pills-grid">
- {#each listenNow as album (album.name + (album.artist ?? ""))}
- <AlbumPill {album} />
- {/each}
- </div>
- </section>
- {/if}
+ <header class="page-head">
+ <h1>{$t("study.music.nav_home")}</h1>
+ </header>
- {#if topArtists.length > 0}
- <section class="block">
- <header class="block-head">
- <h2>{$t("study.music.shelf_top_artists")}</h2>
- <div class="scroll-arrows">
- <button type="button" class="arrow" onclick={() => scrollContainer("artists-scroll", -1)} aria-label="Anterior">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
- </button>
- <button type="button" class="arrow" onclick={() => scrollContainer("artists-scroll", 1)} aria-label="Próximo">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
- </button>
- </div>
- </header>
- <div id="artists-scroll" class="h-scroll">
- {#each topArtists.slice(0, 16) as a (a.name)}
- <div
- class="artist-card"
- role="button"
- tabindex="0"
- onclick={() => openArtist(a.name)}
- onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openArtist(a.name); } }}
- >
- <div class="artist-circle">
- {#if artistCovers.get(a.name)}
- <img src={coverUrl(artistCovers.get(a.name))} alt="" loading="lazy" />
- {:else}
- <div class="artist-fallback" style:background={colorFromString(a.name)}>
- {a.name.slice(0, 1).toUpperCase()}
- </div>
- {/if}
+ <div class="speed-dial-row">
+ <SpeedDialGridItem label={$t("study.music.speed_dial_library") as string} href="/study/music/library">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5v14"/><path d="M8 5v14"/><path d="M13 5h7v14h-7z"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_albums") as string} href="/study/music/albums">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_artists") as string} href="/study/music/artists">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M16 11a4 4 0 1 1-8 0 4 4 0 0 1 8 0z"/><path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_playlists") as string} href="/study/music/playlists">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15V6"/><path d="M3 18V9"/><path d="M3 18a3 3 0 1 0 6 0V9a3 3 0 1 0-6 0"/><path d="M15 6a3 3 0 1 0 6 0 3 3 0 1 0-6 0"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_favorites") as string} href="/study/music/favorites">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_genres") as string} href="/study/music/genres">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h10"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ </div>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.shelf_continue") as string} seeAllHref="/study/music/history" />
+ {#if loadingHome}
+ <YoutubeSkeleton kind="row" count={4} />
+ {:else if continueEntries.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.shelf_continue_empty") as string}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each continueEntries as entry (entry.source + (entry.external_id ?? entry.track_id ?? entry.title))}
+ <button
+ type="button"
+ class="continue-card"
+ onclick={() => playContinue(entry)}
+ >
+ <div class="cover">
+ {#if coverUrl(entry.cover_url)}
+ <img src={coverUrl(entry.cover_url)} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(entry.title)}></div>
+ {/if}
+ <div class="progress-track">
+ <div class="progress-fill" style:width={`${Math.round(entry.progress * 100)}%`}></div>
</div>
- <h3 class="artist-name">{a.name}</h3>
</div>
- {/each}
- </div>
- </section>
+ <h3 class="card-title">{entry.title}</h3>
+ {#if entry.artist}<p class="card-sub">{entry.artist}</p>{/if}
+ </button>
+ {/each}
+ </div>
{/if}
-
- {#if recentAlbums.length > 0}
- <section class="block">
- <header class="block-head">
- <h2>{$t("study.music.shelf_new_releases")}</h2>
- <div class="scroll-arrows">
- <button type="button" class="arrow" onclick={() => scrollContainer("albums-scroll", -1)} aria-label="Anterior">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
- </button>
- <button type="button" class="arrow" onclick={() => scrollContainer("albums-scroll", 1)} aria-label="Próximo">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
- </button>
- </div>
- </header>
- <div id="albums-scroll" class="h-scroll">
- {#each recentAlbums as album (album.name + (album.artist ?? ""))}
- <div
- class="album-card"
- role="button"
- tabindex="0"
- onclick={() => openAlbum(album)}
- onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openAlbum(album); } }}
- >
- <div class="album-card-cover">
- {#if coverUrl(album.cover_path)}
- <img src={coverUrl(album.cover_path)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(album.name + (album.artist ?? ""))}>
- <svg viewBox="0 0 24 24" width="40%" height="40%" fill="currentColor" aria-hidden="true"><circle cx="12" cy="12" r="10" opacity="0.2"/><circle cx="12" cy="12" r="3"/></svg>
- </div>
- {/if}
- <div class="album-card-overlay"></div>
- <button
- type="button"
- class="album-card-play"
- onclick={(e) => { e.stopPropagation(); openAlbum(album); }}
- aria-label="Tocar"
- >
- <svg viewBox="0 0 24 24" width="11" height="11" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>
- </button>
- </div>
- <h3 class="album-card-title">{album.name}</h3>
- {#if album.artist}
- <p class="album-card-sub">{album.artist}</p>
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.shelf_recent_albums") as string} seeAllHref="/study/music/albums" />
+ {#if loadingHome}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if recentAlbums.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.shelf_recent_albums_empty") as string}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each recentAlbums as album (album.name + (album.artist ?? ""))}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => openAlbum(album)}
+ >
+ <div class="cover">
+ {#if coverUrl(album.cover_path)}
+ <img src={coverUrl(album.cover_path)} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(album.name)}></div>
{/if}
</div>
- {/each}
- </div>
- </section>
+ <h3 class="card-title">{album.name}</h3>
+ {#if album.artist}<p class="card-sub">{album.artist}</p>{/if}
+ </button>
+ {/each}
+ </div>
{/if}
-
- {#if playlistsStore.list.length > 0}
- <section class="block">
- <header class="block-head">
- <h2>{$t("study.music.playlists_title")}</h2>
- <div class="scroll-arrows">
- <button type="button" class="arrow" onclick={() => scrollContainer("playlists-scroll", -1)} aria-label="Anterior">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
- </button>
- <button type="button" class="arrow" onclick={() => scrollContainer("playlists-scroll", 1)} aria-label="Próximo">
- <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
- </button>
- </div>
- </header>
- <div id="playlists-scroll" class="h-scroll">
- {#each playlistsStore.list as p (p.id)}
- <div
- class="album-card"
- role="button"
- tabindex="0"
- onclick={() => openPlaylist(p)}
- onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openPlaylist(p); } }}
- >
- <div class="album-card-cover">
- {#if coverUrl(p.resolved_cover)}
- <img src={coverUrl(p.resolved_cover)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(p.name)}>
- <svg viewBox="0 0 24 24" width="40%" height="40%" fill="currentColor" aria-hidden="true"><path d="M9 18V5l12-2v13" opacity="0.4"/><circle cx="6" cy="18" r="3" opacity="0.4"/><circle cx="18" cy="16" r="3" opacity="0.4"/></svg>
- </div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{p.name}</h3>
- <p class="album-card-sub">{p.track_count} faixa(s)</p>
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.shelf_artists") as string} seeAllHref="/study/music/artists" />
+ {#if loadingHome}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if topArtists.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.shelf_artists_empty") as string}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each topArtists.slice(0, 20) as artist (artist.name)}
+ <button
+ type="button"
+ class="artist-card"
+ onclick={() => openArtist(artist)}
+ >
+ <div class="artist-avatar" style:background={colorFromString(artist.name)}>
+ <span class="artist-initial">{artist.name.charAt(0).toUpperCase()}</span>
</div>
- {/each}
- </div>
- </section>
+ <h3 class="card-title artist-name">{artist.name}</h3>
+ <p class="card-sub">
+ {$t("study.music.albums_count", { count: artist.album_count })}
+ </p>
+ </button>
+ {/each}
+ </div>
{/if}
+ </section>
+
+ {#if playlistsStore.list.length > 0}
+ <section class="block">
+ <NavigationTitle title={$t("study.music.playlists_title") as string} seeAllHref="/study/music/playlists" />
+ <div class="h-scroll">
+ {#each playlistsStore.list.slice(0, 10) as p (p.id)}
+ <button type="button" class="discover-card" onclick={() => openPlaylist(p)}>
+ <div class="cover">
+ {#if coverUrl(p.resolved_cover)}
+ <img src={coverUrl(p.resolved_cover)} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(p.name)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{p.name}</h3>
+ <p class="card-sub">{$t("study.music.tracks_count", { count: p.track_count })}</p>
+ </button>
+ {/each}
+ </div>
+ </section>
{/if}
- {#if spotifyStore.status.logged_in}
- {#if spotifyStore.recentlyPlayed.length > 0}
- <section class="block spotify-block">
- <header class="block-head">
- <h2>
- <span class="spotify-mark" aria-hidden="true">
- <svg viewBox="0 0 168 168" width="14" height="14"><circle cx="84" cy="84" r="84" fill="#1db954"/><path fill="#000" d="M119.6 110.6c-1.5 2.5-4.7 3.3-7.2 1.8-19.7-12-44.5-14.7-73.7-8-2.8.6-5.6-1.1-6.3-3.9-.6-2.8 1.1-5.6 3.9-6.3 31.9-7.3 59.4-4.2 81.5 9.2 2.5 1.5 3.3 4.7 1.8 7.2zm9.5-21.2c-1.9 3.1-5.9 4.1-9 2.2-22.6-13.9-57-17.9-83.8-9.8-3.5 1.1-7.1-.9-8.2-4.3-1.1-3.5.9-7.1 4.3-8.2 30.6-9.3 68.5-4.8 94.5 11.1 3.1 1.9 4.1 5.9 2.2 9zm.8-22c-27-16-71.6-17.5-97.4-9.7-4.1 1.2-8.4-1.1-9.6-5.2-1.2-4.1 1.1-8.4 5.2-9.6 29.6-9 78.7-7.2 109.8 11.3 3.7 2.2 4.9 7 2.7 10.7-2.2 3.7-7 4.9-10.7 2.5z"/></svg>
- </span>
- Tocadas recentemente
- </h2>
- </header>
- <div class="h-scroll">
- {#each spotifyStore.recentlyPlayed.slice(0, 12) as track (track.id + (track.played_at ?? ""))}
- <button
- type="button"
- class="album-card"
- onclick={() => playSpotifyTrack(track, spotifyStore.recentlyPlayed)}
- >
- <div class="album-card-cover">
- {#if spotifyCover(track.album.images)}
- <img src={spotifyCover(track.album.images)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(track.album.name)}></div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{track.name}</h3>
- <p class="album-card-sub">{track.artists.map((a) => a.name).join(", ")}</p>
- </button>
- {/each}
- </div>
- </section>
- {/if}
-
- {#if spotifyStore.topArtists.length > 0}
- <section class="block spotify-block">
- <header class="block-head">
- <h2>
- <span class="spotify-mark" aria-hidden="true">
- <svg viewBox="0 0 168 168" width="14" height="14"><circle cx="84" cy="84" r="84" fill="#1db954"/><path fill="#000" d="M119.6 110.6c-1.5 2.5-4.7 3.3-7.2 1.8-19.7-12-44.5-14.7-73.7-8-2.8.6-5.6-1.1-6.3-3.9-.6-2.8 1.1-5.6 3.9-6.3 31.9-7.3 59.4-4.2 81.5 9.2 2.5 1.5 3.3 4.7 1.8 7.2zm9.5-21.2c-1.9 3.1-5.9 4.1-9 2.2-22.6-13.9-57-17.9-83.8-9.8-3.5 1.1-7.1-.9-8.2-4.3-1.1-3.5.9-7.1 4.3-8.2 30.6-9.3 68.5-4.8 94.5 11.1 3.1 1.9 4.1 5.9 2.2 9zm.8-22c-27-16-71.6-17.5-97.4-9.7-4.1 1.2-8.4-1.1-9.6-5.2-1.2-4.1 1.1-8.4 5.2-9.6 29.6-9 78.7-7.2 109.8 11.3 3.7 2.2 4.9 7 2.7 10.7-2.2 3.7-7 4.9-10.7 2.5z"/></svg>
- </span>
- Seus artistas
- </h2>
- </header>
- <div class="h-scroll">
- {#each spotifyStore.topArtists.slice(0, 16) as a (a.id)}
- <a
- class="artist-card"
- href={`/study/music/spotify/artist/${a.id}`}
- >
- <div class="artist-circle">
- {#if spotifyCover(a.images)}
- <img src={spotifyCover(a.images)} alt="" loading="lazy" />
- {:else}
- <div class="artist-fallback" style:background={colorFromString(a.name)}>
- {a.name.slice(0, 1).toUpperCase()}
- </div>
- {/if}
- </div>
- <h3 class="artist-name">{a.name}</h3>
- </a>
- {/each}
- </div>
- </section>
- {/if}
-
- {#if spotifyStore.savedTracks.length > 0}
- <section class="block spotify-block">
- <header class="block-head">
- <h2>
- <span class="spotify-mark" aria-hidden="true">
- <svg viewBox="0 0 168 168" width="14" height="14"><circle cx="84" cy="84" r="84" fill="#1db954"/><path fill="#000" d="M119.6 110.6c-1.5 2.5-4.7 3.3-7.2 1.8-19.7-12-44.5-14.7-73.7-8-2.8.6-5.6-1.1-6.3-3.9-.6-2.8 1.1-5.6 3.9-6.3 31.9-7.3 59.4-4.2 81.5 9.2 2.5 1.5 3.3 4.7 1.8 7.2zm9.5-21.2c-1.9 3.1-5.9 4.1-9 2.2-22.6-13.9-57-17.9-83.8-9.8-3.5 1.1-7.1-.9-8.2-4.3-1.1-3.5.9-7.1 4.3-8.2 30.6-9.3 68.5-4.8 94.5 11.1 3.1 1.9 4.1 5.9 2.2 9zm.8-22c-27-16-71.6-17.5-97.4-9.7-4.1 1.2-8.4-1.1-9.6-5.2-1.2-4.1 1.1-8.4 5.2-9.6 29.6-9 78.7-7.2 109.8 11.3 3.7 2.2 4.9 7 2.7 10.7-2.2 3.7-7 4.9-10.7 2.5z"/></svg>
- </span>
- Suas curtidas
- </h2>
- </header>
- <div class="h-scroll">
- {#each spotifyStore.savedTracks.slice(0, 16) as track (track.id)}
- <button
- type="button"
- class="album-card"
- onclick={() => playSpotifyTrack(track, spotifyStore.savedTracks)}
- >
- <div class="album-card-cover">
- {#if spotifyCover(track.album.images)}
- <img src={spotifyCover(track.album.images)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(track.album.name)}></div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{track.name}</h3>
- <p class="album-card-sub">{track.artists.map((a) => a.name).join(", ")}</p>
- </button>
- {/each}
- </div>
- </section>
- {/if}
-
- {#if spotifyStore.playlists.length > 0}
- <section class="block spotify-block">
- <header class="block-head">
- <h2>
- <span class="spotify-mark" aria-hidden="true">
- <svg viewBox="0 0 168 168" width="14" height="14"><circle cx="84" cy="84" r="84" fill="#1db954"/><path fill="#000" d="M119.6 110.6c-1.5 2.5-4.7 3.3-7.2 1.8-19.7-12-44.5-14.7-73.7-8-2.8.6-5.6-1.1-6.3-3.9-.6-2.8 1.1-5.6 3.9-6.3 31.9-7.3 59.4-4.2 81.5 9.2 2.5 1.5 3.3 4.7 1.8 7.2zm9.5-21.2c-1.9 3.1-5.9 4.1-9 2.2-22.6-13.9-57-17.9-83.8-9.8-3.5 1.1-7.1-.9-8.2-4.3-1.1-3.5.9-7.1 4.3-8.2 30.6-9.3 68.5-4.8 94.5 11.1 3.1 1.9 4.1 5.9 2.2 9zm.8-22c-27-16-71.6-17.5-97.4-9.7-4.1 1.2-8.4-1.1-9.6-5.2-1.2-4.1 1.1-8.4 5.2-9.6 29.6-9 78.7-7.2 109.8 11.3 3.7 2.2 4.9 7 2.7 10.7-2.2 3.7-7 4.9-10.7 2.5z"/></svg>
- </span>
- Suas playlists Spotify
- </h2>
- </header>
- <div class="h-scroll">
- {#each spotifyStore.playlists as p (p.id)}
- <a
- class="album-card"
- href={`/study/music/spotify/playlist/${p.id}`}
- >
- <div class="album-card-cover">
- {#if spotifyCover(p.images)}
- <img src={spotifyCover(p.images)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(p.name)}>
- <svg viewBox="0 0 24 24" width="40%" height="40%" fill="currentColor" aria-hidden="true"><path d="M9 18V5l12-2v13" opacity="0.4"/><circle cx="6" cy="18" r="3" opacity="0.4"/><circle cx="18" cy="16" r="3" opacity="0.4"/></svg>
- </div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{p.name}</h3>
- <p class="album-card-sub">{p.tracks_total} faixa(s){p.owner_name ? ` · ${p.owner_name}` : ""}</p>
- </a>
- {/each}
- </div>
- </section>
- {/if}
+ {#if hasSpotifyContent && spotifyStore.recentlyPlayed.length > 0}
+ <section class="block spotify-block">
+ <NavigationTitle title={$t("study.music.shelf_spotify_recent") as string} seeAllHref="/study/music/spotify" />
+ <div class="h-scroll">
+ {#each spotifyStore.recentlyPlayed.slice(0, 12) as track (track.id + (track.played_at ?? ""))}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playSpotifyTrack(track, spotifyStore.recentlyPlayed)}
+ >
+ <div class="cover">
+ {#if spotifyCover(track.album.images)}
+ <img src={spotifyCover(track.album.images)} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(track.album.name)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{track.name}</h3>
+ <p class="card-sub">{track.artists.map((a) => a.name).join(", ")}</p>
+ </button>
+ {/each}
+ </div>
+ </section>
{/if}
- {#if soundcloudStore.isLoggedIn}
- {#if soundcloudStore.likedTracks.length > 0}
- <section class="block sc-block">
- <header class="block-head">
- <h2><span class="sc-mark">●</span> Suas curtidas no SoundCloud</h2>
- </header>
- <div class="h-scroll">
- {#each soundcloudStore.likedTracks.slice(0, 16) as track (track.id)}
- <button
- type="button"
- class="album-card"
- onclick={() => playSc(track, soundcloudStore.likedTracks)}
- >
- <div class="album-card-cover">
- {#if track.artwork_url || track.user.avatar_url}
- <img src={soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(track.title)}></div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{track.title}</h3>
- <p class="album-card-sub">{track.user.username}</p>
- </button>
- {/each}
- </div>
- </section>
- {/if}
-
- {#if soundcloudStore.streamFeed.length > 0}
- <section class="block sc-block">
- <header class="block-head">
- <h2><span class="sc-mark">●</span> Stream do SoundCloud</h2>
- </header>
- <div class="h-scroll">
- {#each soundcloudStore.streamFeed.slice(0, 16) as track (track.id)}
- <button
- type="button"
- class="album-card"
- onclick={() => playSc(track, soundcloudStore.streamFeed)}
- >
- <div class="album-card-cover">
- {#if track.artwork_url || track.user.avatar_url}
- <img src={soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(track.title)}></div>
- {/if}
- <div class="album-card-overlay"></div>
- </div>
- <h3 class="album-card-title">{track.title}</h3>
- <p class="album-card-sub">{track.user.username}</p>
- </button>
- {/each}
- </div>
- </section>
- {/if}
-
- {#if soundcloudStore.playlists.length > 0}
- <section class="block sc-block">
- <header class="block-head">
- <h2><span class="sc-mark">●</span> Suas playlists SoundCloud</h2>
- </header>
- <div class="h-scroll">
- {#each soundcloudStore.playlists as p (p.id)}
- <a
- class="album-card"
- href={`/study/music/soundcloud/playlist/${p.id}`}
- >
- <div class="album-card-cover">
- {#if p.artwork_url}
- <img src={soundcloudStore.pickArtwork(p.artwork_url)} alt="" loading="lazy" />
- {:else}
- <div class="album-card-fallback" style:background={colorFromString(p.title)}></div>
- {/if}
- </div>
- <h3 class="album-card-title">{p.title}</h3>
- <p class="album-card-sub">{p.track_count} faixa(s) · {p.user.username}</p>
- </a>
- {/each}
- </div>
- </section>
- {/if}
+ {#if hasSoundcloudContent && soundcloudStore.likedTracks.length > 0}
+ <section class="block sc-block">
+ <NavigationTitle title={$t("study.music.shelf_soundcloud_likes") as string} seeAllHref="/study/music/soundcloud" />
+ <div class="h-scroll">
+ {#each soundcloudStore.likedTracks.slice(0, 12) as track (track.id)}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playSc(track, soundcloudStore.likedTracks)}
+ >
+ <div class="cover">
+ {#if track.artwork_url || track.user.avatar_url}
+ <img src={soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url)} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(track.title)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{track.title}</h3>
+ <p class="card-sub">{track.user.username}</p>
+ </button>
+ {/each}
+ </div>
+ </section>
{/if}
+
+ <a class="yt-cta" href="/study/music/youtube">
+ <span class="yt-cta-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/><polygon points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02" fill="#000"/></svg>
+ </span>
+ <span class="yt-cta-body">
+ <span class="yt-cta-title">{$t("study.music.explore_youtube_cta")}</span>
+ <span class="yt-cta-sub">{$t("study.music.explore_youtube_cta_body")}</span>
+ </span>
+ <span class="yt-cta-arrow" aria-hidden="true">→</span>
+ </a>
</section>
<style>
.music-home {
display: flex;
flex-direction: column;
- gap: 32px;
+ gap: 28px;
color: rgba(255, 255, 255, 0.95);
- }
- .page-head {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- gap: 16px;
- flex-wrap: wrap;
+ position: relative;
}
.page-head h1 {
margin: 0;
font-size: clamp(28px, 3.5vw, 40px);
font-weight: 900;
letter-spacing: -0.02em;
- color: rgba(255, 255, 255, 0.95);
- }
- .head-actions {
- display: flex;
- gap: 8px;
- flex-wrap: wrap;
- }
- .ghost-btn {
- padding: 7px 16px;
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid rgba(255, 255, 255, 0.05);
- border-radius: 999px;
- color: rgba(255, 255, 255, 0.85);
- font-family: inherit;
- font-size: 12px;
- font-weight: 600;
- cursor: pointer;
- transition: background 200ms ease, color 200ms ease;
- }
- .ghost-btn:hover:not(:disabled) {
- background: rgba(255, 255, 255, 0.1);
color: white;
}
- .ghost-btn:disabled { opacity: 0.5; cursor: default; }
- .scan-msg {
- margin: -20px 0 0;
- font-size: 12px;
- color: rgba(255, 255, 255, 0.5);
- }
- .empty-music {
+ .pull-indicator {
+ position: sticky;
+ top: 0;
+ z-index: 5;
text-align: center;
- padding: 64px 24px;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 12px;
- color: rgba(255, 255, 255, 0.85);
- }
- .empty-music h2 {
- margin: 0;
- font-size: 22px;
- font-weight: 800;
- }
- .empty-music p {
- margin: 0;
- color: rgba(255, 255, 255, 0.5);
- font-size: 14px;
- max-width: 50ch;
- line-height: 1.5;
- }
- .cta-big {
- margin-top: 8px;
- padding: 12px 28px;
- background: var(--accent);
- color: var(--on-accent, white);
- border: 0;
- border-radius: 999px;
- font-family: inherit;
- font-size: 14px;
- font-weight: 700;
- cursor: pointer;
- box-shadow: 0 4px 14px color-mix(in oklab, var(--accent) 30%, transparent);
- }
-
- .hero {
- position: relative;
- height: 350px;
- border-radius: 24px;
- overflow: hidden;
- margin-bottom: 16px;
- }
- .hero-bg {
- position: absolute;
- inset: 0;
- background-size: cover;
- background-position: center;
- background-color: rgba(40, 40, 40, 0.6);
- }
- .hero-overlay {
- position: absolute;
- inset: 0;
- background: linear-gradient(
- to right,
- rgba(0, 0, 0, 0.9) 0%,
- rgba(0, 0, 0, 0.4) 50%,
- transparent 100%
- );
- }
- .hero-content {
- position: relative;
- height: 100%;
- display: flex;
- flex-direction: column;
- justify-content: center;
- padding: 32px;
- color: white;
- }
- @media (min-width: 768px) {
- .hero-content { padding: 48px; }
- }
- .hero-eyebrow {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- font-size: 10px;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.16em;
- color: var(--accent);
- margin-bottom: 12px;
- text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
- }
- .hero-title {
- margin: 0 0 16px;
- font-size: clamp(30px, 4vw, 56px);
- line-height: 1.05;
- font-weight: 900;
- color: white;
- max-width: 36ch;
- overflow-wrap: anywhere;
- text-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
- }
- .hero-artist {
- margin: 0 0 32px;
- font-size: 16px;
- color: rgba(255, 255, 255, 0.6);
- font-weight: 500;
- max-width: 30ch;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- text-shadow: 0 1px 6px rgba(0, 0, 0, 0.4);
- }
- .hero-actions {
- display: flex;
- align-items: center;
- gap: 16px;
- }
- .hero-play {
- display: inline-flex;
- align-items: center;
- gap: 12px;
- padding: 12px 32px;
- background: white;
- color: black;
- border: 0;
- border-radius: 999px;
- font-family: inherit;
- font-size: 14px;
- font-weight: 700;
- cursor: pointer;
- transition: transform 200ms ease, background 200ms ease;
- }
- .hero-play:hover {
- background: rgba(255, 255, 255, 0.9);
- transform: scale(1.05);
- }
- .hero-play:active {
- transform: scale(0.95);
+ padding: 6px 0;
+ background: linear-gradient(180deg, rgba(0, 0, 0, 0.6), transparent);
+ color: rgba(255, 255, 255, 0.78);
+ font-size: 12px;
+ font-weight: 600;
+ opacity: var(--p, 1);
}
- .hero-fav {
- width: 44px;
- height: 44px;
- padding: 0;
- background: rgba(255, 255, 255, 0.1);
- border: 1px solid rgba(255, 255, 255, 0.2);
- border-radius: 50%;
- color: white;
- cursor: pointer;
+ .speed-dial-row {
display: grid;
- place-items: center;
- transition: background 200ms ease;
- }
- .hero-fav:hover {
- background: rgba(255, 255, 255, 0.2);
+ grid-template-columns: repeat(6, 1fr);
+ gap: 10px;
}
- .hero-fav.on {
- color: var(--accent);
+ @media (max-width: 760px) {
+ .speed-dial-row {
+ grid-template-columns: repeat(3, 1fr);
+ }
}
-
.block {
display: flex;
flex-direction: column;
- gap: 20px;
- }
- .block-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
- .block-head h2 {
- margin: 0;
- font-size: 22px;
- font-weight: 800;
- letter-spacing: -0.01em;
- color: rgba(255, 255, 255, 0.95);
- display: inline-flex;
- align-items: center;
- gap: 10px;
+ gap: 14px;
}
- .spotify-mark {
- display: inline-flex;
- align-items: center;
- }
- .spotify-block .album-card,
- .spotify-block .artist-card {
- text-decoration: none;
- }
- .sc-mark { color: #ff5500; font-size: 14px; }
- .sc-block .album-card { text-decoration: none; }
- .scroll-arrows {
- display: flex;
- gap: 8px;
- }
- .arrow {
- width: 32px;
- height: 32px;
- padding: 0;
- background: rgba(255, 255, 255, 0.05);
- border: 0;
- border-radius: 50%;
- color: white;
- cursor: pointer;
- display: grid;
- place-items: center;
- transition: background 200ms ease;
- }
- .arrow:hover {
- background: rgba(255, 255, 255, 0.1);
- }
-
- .album-pills-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
- gap: 16px;
- }
-
.h-scroll {
display: flex;
- gap: 24px;
+ gap: 18px;
overflow-x: auto;
overflow-y: visible;
- padding: 8px 4px 24px;
- scroll-behavior: smooth;
+ padding: 4px 2px 16px;
scrollbar-width: none;
+ scroll-behavior: smooth;
}
.h-scroll::-webkit-scrollbar { display: none; }
+ .continue-card,
+ .discover-card,
.artist-card {
- flex: 0 0 144px;
- cursor: pointer;
+ flex: 0 0 auto;
background: transparent;
border: 0;
- color: inherit;
padding: 0;
- text-align: center;
+ text-align: left;
+ color: inherit;
+ cursor: pointer;
+ font: inherit;
}
- .artist-circle {
+ .continue-card { width: 160px; }
+ .discover-card { width: 176px; }
+ .artist-card { width: 130px; text-align: center; }
+
+ .cover {
+ position: relative;
aspect-ratio: 1 / 1;
- border-radius: 50%;
- background: rgba(40, 40, 40, 0.8);
+ border-radius: 12px;
overflow: hidden;
- margin: 0 auto 16px;
- transition: transform 700ms ease;
- position: relative;
+ background: rgba(40, 40, 40, 0.6);
+ margin-bottom: 10px;
+ transition: transform 200ms ease;
}
- .artist-card:hover .artist-circle {
- transform: scale(1.04);
+ .continue-card:hover .cover,
+ .discover-card:hover .cover {
+ transform: scale(1.02);
}
- .artist-circle img {
+ .cover img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
- transition: transform 700ms ease;
}
- .artist-card:hover .artist-circle img {
- transform: scale(1.1);
- }
- .artist-fallback {
+ .cover-fallback {
width: 100%;
height: 100%;
+ }
+ .progress-track {
+ position: absolute;
+ left: 6px;
+ right: 6px;
+ bottom: 6px;
+ height: 3px;
+ background: rgba(0, 0, 0, 0.5);
+ border-radius: 2px;
+ overflow: hidden;
+ }
+ .progress-fill {
+ height: 100%;
+ background: var(--accent);
+ border-radius: inherit;
+ }
+ .artist-avatar {
+ width: 130px;
+ height: 130px;
+ border-radius: 50%;
display: grid;
place-items: center;
- color: white;
- font-size: 48px;
- font-weight: 800;
+ margin: 0 auto 10px;
+ transition: transform 200ms ease;
+ }
+ .artist-card:hover .artist-avatar {
+ transform: scale(1.04);
+ }
+ .artist-initial {
+ font-size: 42px;
+ font-weight: 900;
+ color: rgba(255, 255, 255, 0.92);
+ letter-spacing: -0.02em;
}
.artist-name {
+ text-align: center;
+ white-space: normal;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+ .card-title {
margin: 0;
- color: white;
+ font-size: 13px;
font-weight: 700;
- font-size: 14px;
+ color: white;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- padding: 0 4px;
- }
-
- .album-card {
- flex: 0 0 176px;
- cursor: pointer;
- background: transparent;
- border: 0;
- color: inherit;
- padding: 0;
- text-align: left;
+ padding: 0 2px;
}
- .album-card-cover {
- position: relative;
- aspect-ratio: 1 / 1;
- border-radius: 16px;
- background: rgba(40, 40, 40, 0.8);
+ .card-sub {
+ margin: 2px 0 0;
+ font-size: 11px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.55);
overflow: hidden;
- margin-bottom: 16px;
- transition: all 300ms ease;
- }
- .album-card-cover img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- transition: transform 500ms ease;
- }
- .album-card:hover .album-card-cover img {
- transform: scale(1.05);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 0 2px;
}
- .album-card-fallback {
- width: 100%;
- height: 100%;
+
+ .yt-cta {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 14px 18px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 14px;
+ color: rgba(255, 255, 255, 0.92);
+ text-decoration: none;
+ transition: background 160ms ease, border-color 160ms ease, transform 160ms ease;
+ max-width: 480px;
+ align-self: flex-start;
+ }
+ .yt-cta:hover {
+ background: rgba(255, 255, 255, 0.07);
+ border-color: rgba(255, 255, 255, 0.15);
+ transform: translateY(-1px);
+ }
+ .yt-cta-icon {
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+ background: #ff0033;
display: grid;
place-items: center;
color: white;
+ flex-shrink: 0;
}
- .album-card-overlay {
- position: absolute;
- inset: 0;
- background: rgba(0, 0, 0, 0);
- transition: background 300ms ease;
- border-radius: inherit;
- }
- .album-card:hover .album-card-overlay {
- background: rgba(0, 0, 0, 0.2);
- }
- .album-card-play {
- position: absolute;
- right: 12px;
- bottom: 12px;
- width: 40px;
- height: 40px;
- padding: 0;
- background: white;
- color: black;
- border: 0;
- border-radius: 50%;
- cursor: pointer;
- display: grid;
- place-items: center;
- opacity: 0;
- transform: translateY(8px);
- transition: opacity 300ms ease, transform 300ms ease;
- box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
- }
- .album-card:hover .album-card-play {
- opacity: 1;
- transform: translateY(0);
+ .yt-cta-body {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ flex: 1;
+ min-width: 0;
}
- .album-card-title {
- margin: 0;
- color: white;
- font-weight: 700;
+ .yt-cta-title {
font-size: 14px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- padding: 0 4px;
+ font-weight: 700;
+ color: white;
}
- .album-card-sub {
- margin: 4px 0 0;
- color: rgba(255, 255, 255, 0.5);
+ .yt-cta-sub {
font-size: 12px;
- font-weight: 600;
+ color: rgba(255, 255, 255, 0.6);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- padding: 0 4px;
}
-
- .muted {
- color: rgba(255, 255, 255, 0.5);
- font-size: 13px;
+ .yt-cta-arrow {
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 18px;
+ flex-shrink: 0;
}
@media (prefers-reduced-motion: reduce) {
- .hero-play, .hero-fav, .arrow, .album-card-cover img,
- .album-card-overlay, .album-card-play, .artist-circle, .artist-circle img {
+ .cover, .continue-card:hover .cover, .discover-card:hover .cover,
+ .artist-avatar, .artist-card:hover .artist-avatar, .yt-cta, .yt-cta:hover {
transition: none;
- }
- .hero-play:hover, .artist-card:hover .artist-circle,
- .artist-card:hover .artist-circle img,
- .album-card:hover .album-card-cover img {
transform: none;
}
}
diff --git a/src/routes/study/music/favorites/+page.svelte b/src/routes/study/music/favorites/+page.svelte
index d3b015bb..39be4854 100644
--- a/src/routes/study/music/favorites/+page.svelte
+++ b/src/routes/study/music/favorites/+page.svelte
@@ -3,6 +3,7 @@
import { pluginInvoke } from "$lib/plugin-invoke";
import { t } from "$lib/i18n";
import TrackRow from "$lib/study-music-components/TrackRow.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
import type { MusicTrack } from "$lib/study-music/player-store.svelte";
import {
spotifyStore,
@@ -69,9 +70,7 @@
{#if loading}
<p class="muted">{$t("study.common.loading")}</p>
{:else if tracks.length === 0}
- <div class="empty">
- <p>{$t("study.music.favorites_empty")}</p>
- </div>
+ <EmptyPlaceholder title={$t("study.music.favorites_empty") as string} />
{:else}
<ul class="track-list">
{#each tracks as track (track.id)}
@@ -86,6 +85,5 @@
.head h1 { margin: 0; font-size: 28px; font-weight: 800; color: var(--secondary); letter-spacing: -0.01em; }
.head .sub { margin: 4px 0 0; color: var(--tertiary); font-size: 13px; }
.track-list { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }
- .empty { padding: 48px 24px; text-align: center; color: var(--tertiary); }
.muted { color: var(--tertiary); font-size: 13px; }
</style>
diff --git a/src/routes/study/music/history/+page.svelte b/src/routes/study/music/history/+page.svelte
new file mode 100644
index 00000000..3479221a
--- /dev/null
+++ b/src/routes/study/music/history/+page.svelte
@@ -0,0 +1,330 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyMusicHistoryList,
+ studyMusicHistoryClear,
+ studyMusicHistoryRemove,
+ type MusicHistoryEntry,
+ type MusicHistorySource,
+ } from "$lib/study-bridge";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import { t } from "$lib/i18n";
+ import { goto } from "$app/navigation";
+
+ type LocalFilter = "all" | "local" | "spotify" | "soundcloud";
+ const FILTERS: { key: LocalFilter; labelKey: string }[] = [
+ { key: "all", labelKey: "study.music.history_filter_all" },
+ { key: "local", labelKey: "study.music.history_filter_local" },
+ { key: "spotify", labelKey: "study.music.history_filter_spotify" },
+ { key: "soundcloud", labelKey: "study.music.history_filter_soundcloud" },
+ ];
+
+ let entries = $state<MusicHistoryEntry[]>([]);
+ let loading = $state(true);
+ let error = $state<string | null>(null);
+ let activeFilter = $state<LocalFilter>("all");
+
+ async function load() {
+ loading = true;
+ error = null;
+ try {
+ if (activeFilter === "all") {
+ const res = await studyMusicHistoryList({ limit: 300 });
+ entries = (res.entries ?? []).filter((e) => e.source !== "youtube");
+ } else {
+ const res = await studyMusicHistoryList({
+ limit: 300,
+ source: activeFilter as MusicHistorySource,
+ });
+ entries = res.entries ?? [];
+ }
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function pickFilter(next: LocalFilter) {
+ if (next === activeFilter) return;
+ activeFilter = next;
+ void load();
+ }
+
+ function fmtAgo(tsMs: number): string {
+ const seconds = Math.floor((Date.now() - tsMs) / 1000);
+ if (seconds < 60) return $t("study.music.history_now") as string;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes} min`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours} h`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days} d`;
+ const months = Math.floor(days / 30);
+ if (months < 12) return `${months} m`;
+ const years = Math.floor(months / 12);
+ return `${years} a`;
+ }
+
+ function sourceLabel(source: MusicHistorySource): string {
+ if (source === "spotify") return "Spotify";
+ if (source === "soundcloud") return "SoundCloud";
+ return $t("study.music.history_filter_local") as string;
+ }
+
+ async function play(entry: MusicHistoryEntry) {
+ try {
+ if (entry.track_id != null) {
+ const track = musicPlayer.queue.find((t) => t.id === entry.track_id);
+ if (track) {
+ await musicPlayer.play(track);
+ return;
+ }
+ }
+ showToast("info", $t("study.music.history_unplayable") as string);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function remove(id: number) {
+ try {
+ await studyMusicHistoryRemove({ id });
+ entries = entries.filter((e) => e.id !== id);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function clearAll() {
+ if (!window.confirm($t("study.music.history_clear_confirm_local") as string)) return;
+ try {
+ if (activeFilter === "all") {
+ const res = await studyMusicHistoryClear({});
+ showToast("success", `${res.removed} ${$t("study.music.history_entries_removed") as string}`);
+ } else {
+ const res = await studyMusicHistoryClear({
+ source: activeFilter as MusicHistorySource,
+ });
+ showToast("success", `${res.removed} ${$t("study.music.history_entries_removed") as string}`);
+ }
+ entries = [];
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ onMount(() => {
+ void load();
+ });
+</script>
+
+<section class="history-page">
+ <header class="head">
+ <h1>{$t("study.music.history_title")}</h1>
+ {#if entries.length > 0}
+ <button class="clear-btn" onclick={clearAll} type="button">{$t("study.music.history_clear")}</button>
+ {/if}
+ </header>
+
+ <div class="filters" role="tablist" aria-label={$t("study.music.history_filter_aria") as string}>
+ {#each FILTERS as f (f.key)}
+ <button
+ type="button"
+ class="chip"
+ class:active={activeFilter === f.key}
+ role="tab"
+ aria-selected={activeFilter === f.key}
+ onclick={() => pickFilter(f.key)}
+ >
+ {$t(f.labelKey as never) as string}
+ </button>
+ {/each}
+ </div>
+
+ {#if loading}
+ <div class="skel-list">
+ {#each Array(6) as _, i (i)}
+ <div class="skel-row"></div>
+ {/each}
+ </div>
+ {:else if error}
+ <div class="error">
+ <p>{error}</p>
+ <button onclick={() => { error = null; void load(); }} type="button">{$t("study.music.retry")}</button>
+ </div>
+ {:else if entries.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.history_empty_title_local") as string}
+ ctaLabel={$t("study.music.history_empty_cta_local") as string}
+ onCta={() => goto("/study/music/search")}
+ />
+ {:else}
+ <ul class="list">
+ {#each entries as entry (entry.id)}
+ <li class="row">
+ <button class="thumb" onclick={() => play(entry)} type="button" aria-label={$t("study.music.play") as string}>
+ {#if entry.cover_url}
+ <img src={entry.cover_url} alt="" loading="lazy" />
+ {/if}
+ <span class="source-tag source-{entry.source}">{sourceLabel(entry.source)}</span>
+ </button>
+ <div class="info">
+ <button class="title-btn" onclick={() => play(entry)} type="button">
+ {entry.title}
+ </button>
+ <p class="meta">
+ {#if entry.artist}
+ <span>{entry.artist}</span>
+ <span> · </span>
+ {/if}
+ <span>{fmtAgo(entry.played_at)}</span>
+ </p>
+ </div>
+ <button class="remove" onclick={() => remove(entry.id)} aria-label={$t("study.music.history_remove_aria") as string} type="button">×</button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+</section>
+
+<style>
+ .history-page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 16px 20px 32px;
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .head h1 { margin: 0; font-size: 22px; font-weight: 700; color: var(--primary); }
+ .clear-btn {
+ padding: 6px 14px;
+ background: transparent;
+ color: var(--tertiary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ border-radius: 999px;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .clear-btn:hover { color: #d33; border-color: #d33; }
+ .filters {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+ .chip {
+ padding: 6px 14px;
+ background: transparent;
+ color: var(--tertiary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: color 120ms, border-color 120ms, background 120ms;
+ }
+ .chip:hover { color: var(--secondary); border-color: var(--accent); }
+ .chip.active {
+ color: #fff;
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ .list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
+ .row {
+ display: grid;
+ grid-template-columns: 120px 1fr auto;
+ align-items: center;
+ gap: 14px;
+ padding: 8px;
+ border-radius: 10px;
+ }
+ .row:hover { background: color-mix(in oklab, var(--button) 30%, transparent); }
+ .thumb {
+ position: relative;
+ width: 120px;
+ aspect-ratio: 16 / 9;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ border: 0;
+ border-radius: 8px;
+ overflow: hidden;
+ cursor: pointer;
+ padding: 0;
+ }
+ .thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
+ .source-tag {
+ position: absolute;
+ left: 6px;
+ bottom: 6px;
+ padding: 2px 6px;
+ font-size: 9px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ border-radius: 4px;
+ color: #fff;
+ background: rgba(0, 0, 0, 0.65);
+ }
+ .source-spotify { background: rgba(30, 215, 96, 0.85); color: #000; }
+ .source-soundcloud { background: rgba(255, 119, 0, 0.85); }
+ .source-local { background: rgba(0, 0, 0, 0.7); }
+ .info { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
+ .title-btn {
+ padding: 0;
+ background: transparent;
+ border: 0;
+ color: var(--primary);
+ font-size: 14px;
+ font-weight: 600;
+ text-align: left;
+ cursor: pointer;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .title-btn:hover { color: var(--accent); }
+ .meta { margin: 0; font-size: 12px; color: var(--tertiary); }
+ .remove {
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: var(--tertiary);
+ font-size: 18px;
+ cursor: pointer;
+ }
+ .remove:hover { color: #d33; background: color-mix(in oklab, var(--button) 40%, transparent); }
+ .skel-list { display: flex; flex-direction: column; gap: 8px; }
+ .skel-row {
+ height: 80px;
+ border-radius: 10px;
+ background: linear-gradient(90deg, color-mix(in oklab, var(--button) 40%, transparent) 0%, color-mix(in oklab, var(--button) 60%, transparent) 50%, color-mix(in oklab, var(--button) 40%, transparent) 100%);
+ background-size: 200% 100%;
+ animation: shimmer 1.5s ease-in-out infinite;
+ }
+ @keyframes shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ .error { padding: 24px; text-align: center; color: #d33; }
+ .error button {
+ margin-top: 8px;
+ padding: 6px 14px;
+ background: var(--accent);
+ color: #fff;
+ border: 0;
+ border-radius: 999px;
+ font-size: 12px;
+ cursor: pointer;
+ }
+</style>
diff --git a/src/routes/study/music/library/+page.svelte b/src/routes/study/music/library/+page.svelte
index e9a49783..adcc5031 100644
--- a/src/routes/study/music/library/+page.svelte
+++ b/src/routes/study/music/library/+page.svelte
@@ -3,6 +3,8 @@
import { pluginInvoke } from "$lib/plugin-invoke";
import { t } from "$lib/i18n";
import TrackRow from "$lib/study-music-components/TrackRow.svelte";
+ import Skeleton from "$lib/study-music-components/Skeleton.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
import type { MusicTrack } from "$lib/study-music/player-store.svelte";
import {
spotifyStore,
@@ -176,11 +178,22 @@
</div>
{#if loading && tracks.length === 0}
- <p class="muted">{$t("study.common.loading")}</p>
+ <ul class="track-list" aria-busy="true">
+ {#each Array(8) as _, i (i)}
+ <li class="skel-row">
+ <Skeleton width="36px" height="36px" rounded="sm" />
+ <div class="skel-text">
+ <Skeleton width="62%" height="13px" rounded="sm" block />
+ <Skeleton width="38%" height="11px" rounded="sm" block />
+ </div>
+ <Skeleton width="36px" height="11px" rounded="sm" />
+ </li>
+ {/each}
+ </ul>
{:else if tracks.length === 0}
- <div class="empty">
- <p>{$t("study.music.empty_results")}</p>
- </div>
+ <EmptyPlaceholder
+ title={(q.trim() ? $t("study.music.empty_search_no_results") : $t("study.music.empty_results")) as string}
+ />
{:else}
<p class="result-count">{tracks.length} de {total} faixa(s)</p>
<ul class="track-list">
@@ -246,5 +259,17 @@
text-align: center;
color: rgba(255, 255, 255, 0.5);
}
- .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }
+ .skel-row {
+ display: grid;
+ grid-template-columns: 36px 1fr auto;
+ align-items: center;
+ gap: 12px;
+ padding: 8px 4px;
+ }
+ .skel-text {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-width: 0;
+ }
</style>
diff --git a/src/routes/study/music/now-playing/+page.svelte b/src/routes/study/music/now-playing/+page.svelte
new file mode 100644
index 00000000..981488f6
--- /dev/null
+++ b/src/routes/study/music/now-playing/+page.svelte
@@ -0,0 +1,778 @@
+<script lang="ts">
+ import { goto } from "$app/navigation";
+ import { onMount, tick } from "svelte";
+ import { t } from "$lib/i18n";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+ import { musicTheme } from "$lib/study-music/theme-store.svelte";
+ import { lyricsStore } from "$lib/study-music/lyrics-store.svelte";
+ import { fmtDuration } from "$lib/study-music/format";
+ import CoverImage from "$lib/study-music-components/CoverImage.svelte";
+ import ProgressBar from "$lib/study-music-components/ProgressBar.svelte";
+ import VolumeControl from "$lib/study-music-components/VolumeControl.svelte";
+ import PlayerErrorBanner from "$lib/study-music-components/PlayerErrorBanner.svelte";
+
+ type Tab = "lyrics" | "queue" | "previous";
+ let tab = $state<Tab>("lyrics");
+
+ const track = $derived(musicPlayer.currentTrack);
+ const trackId = $derived(track?.id ?? null);
+ const lyricsLines = $derived(lyricsStore.lines);
+ const lyricsStatus = $derived(lyricsStore.status);
+ const activeLyricIdx = $derived(
+ lyricsStatus === "synced" && lyricsLines.length > 0
+ ? lyricsStore.activeIndex(musicPlayer.currentTime)
+ : -1,
+ );
+ const previousTracks = $derived(
+ musicPlayer.queue.slice(0, Math.max(0, musicPlayer.queueIndex)).reverse(),
+ );
+ const upNext = $derived(musicPlayer.queue.slice(musicPlayer.queueIndex + 1));
+
+ const reduceMotion = $derived(musicTheme.reduceAnimationsActive);
+
+ let lyricsContainer = $state<HTMLDivElement | null>(null);
+ let lineRefs: HTMLLIElement[] = $state([]);
+ let _lastScrollAt = 0;
+
+ $effect(() => {
+ if (trackId === null) {
+ lyricsStore.reset();
+ return;
+ }
+ void lyricsStore.loadFor(trackId);
+ });
+
+ $effect(() => {
+ if (tab !== "lyrics") return;
+ void activeLyricIdx;
+ if (activeLyricIdx < 0) return;
+ const now = performance.now();
+ if (now - _lastScrollAt < 200) return;
+ _lastScrollAt = now;
+ void scrollToActive();
+ });
+
+ async function scrollToActive() {
+ await tick();
+ const el = lineRefs[activeLyricIdx];
+ if (!el || !lyricsContainer) return;
+ const cRect = lyricsContainer.getBoundingClientRect();
+ const offset =
+ el.offsetTop - lyricsContainer.offsetTop - cRect.height / 2 + el.offsetHeight / 2;
+ lyricsContainer.scrollTo({
+ top: offset,
+ behavior: reduceMotion ? "instant" : "smooth",
+ });
+ }
+
+ function close() {
+ if (typeof window !== "undefined" && window.history.length > 1) {
+ history.back();
+ } else {
+ goto("/study/music");
+ }
+ }
+
+ function jumpTo(absoluteIdx: number) {
+ if (absoluteIdx < 0 || absoluteIdx >= musicPlayer.queue.length) return;
+ musicPlayer.queueIndex = absoluteIdx;
+ void musicPlayer.play(musicPlayer.queue[absoluteIdx], musicPlayer.queue);
+ }
+
+ onMount(() => {
+ if (!track) {
+ goto("/study/music");
+ }
+ });
+
+ function favoriteToggle() {
+ if (!track) return;
+ void musicPlayer.toggleFavorite(track.id);
+ }
+
+ const coverSrc = $derived(
+ track?.cover_path ??
+ track?.spotify_cover_url ??
+ track?.youtube_thumbnail ??
+ track?.soundcloud_artwork_url ??
+ null,
+ );
+</script>
+
+<svelte:head>
+ <title>{track?.title ?? $t("study.music.now_playing_title")} · omniget</title>
+</svelte:head>
+
+{#if track}
+ <div class="np-shell">
+ <PlayerErrorBanner />
+ <div class="np-backdrop" aria-hidden="true">
+ {#if coverSrc}
+ <CoverImage
+ src={coverSrc}
+ alt=""
+ fallbackSeed={track.album ?? track.title}
+ rounded="md"
+ trackId={track.id}
+ />
+ {/if}
+ </div>
+ <div class="np-veil" aria-hidden="true"></div>
+
+ <button
+ type="button"
+ class="np-close"
+ onclick={close}
+ aria-label={$t("study.music.now_playing_close") as string}
+ title={$t("study.music.now_playing_close") as string}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="6 9 12 15 18 9"/>
+ </svg>
+ <span>{$t("study.music.now_playing_close")}</span>
+ </button>
+
+ <div class="np-grid">
+ <section class="np-left">
+ <div class="np-cover-wrap">
+ <CoverImage
+ src={coverSrc}
+ alt={track.title ?? track.path}
+ fallbackSeed={track.album ?? track.title}
+ rounded="lg"
+ trackId={track.id}
+ />
+ </div>
+ <div class="np-meta">
+ <h1 class="np-title">{track.title ?? track.path}</h1>
+ {#if track.artist}
+ <p class="np-artist">{track.artist}</p>
+ {/if}
+ {#if track.album}
+ <p class="np-album">{track.album}</p>
+ {/if}
+ </div>
+ <ProgressBar
+ current={musicPlayer.currentTime}
+ duration={musicPlayer.duration}
+ onSeek={(s) => musicPlayer.seek(s)}
+ />
+ <div class="np-controls">
+ <button
+ type="button"
+ class="np-fav"
+ class:on={track.favorite}
+ onclick={favoriteToggle}
+ aria-label={track.favorite
+ ? ($t("study.music.unfavorite") as string)
+ : ($t("study.music.favorite") as string)}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18" fill={track.favorite ? "currentColor" : "none"} stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
+ </svg>
+ </button>
+ <button
+ type="button"
+ class="np-btn"
+ class:active={musicPlayer.shuffle}
+ onclick={() => musicPlayer.toggleShuffle()}
+ aria-label={$t("study.music.shuffle") as string}
+ title={$t("study.music.shuffle") as string}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="16 3 21 3 21 8"/>
+ <line x1="4" y1="20" x2="21" y2="3"/>
+ <polyline points="21 16 21 21 16 21"/>
+ <line x1="15" y1="15" x2="21" y2="21"/>
+ <line x1="4" y1="4" x2="9" y2="9"/>
+ </svg>
+ </button>
+ <button
+ type="button"
+ class="np-btn"
+ onclick={() => musicPlayer.prev()}
+ aria-label={$t("study.music.prev") as string}
+ >
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M19 20L9 12l10-8v16zM5 4h2v16H5z"/></svg>
+ </button>
+ <button
+ type="button"
+ class="np-play"
+ onclick={() => musicPlayer.togglePlay()}
+ aria-label={musicPlayer.paused
+ ? ($t("study.music.play") as string)
+ : ($t("study.music.pause") as string)}
+ >
+ {#if musicPlayer.loading}
+ <span class="np-spinner" aria-hidden="true"></span>
+ {:else if musicPlayer.paused}
+ <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>
+ {:else}
+ <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor" aria-hidden="true"><rect x="6" y="5" width="4" height="14"/><rect x="14" y="5" width="4" height="14"/></svg>
+ {/if}
+ </button>
+ <button
+ type="button"
+ class="np-btn"
+ onclick={() => musicPlayer.next()}
+ aria-label={$t("study.music.next") as string}
+ >
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M5 4l10 8-10 8V4zm12 0h2v16h-2z"/></svg>
+ </button>
+ <button
+ type="button"
+ class="np-btn"
+ class:active={musicPlayer.repeat !== "off"}
+ onclick={() => musicPlayer.cycleRepeat()}
+ aria-label={$t("study.music.repeat") as string}
+ title={$t("study.music.repeat") as string}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="17 1 21 5 17 9"/>
+ <path d="M3 11V9a4 4 0 0 1 4-4h14"/>
+ <polyline points="7 23 3 19 7 15"/>
+ <path d="M21 13v2a4 4 0 0 1-4 4H3"/>
+ {#if musicPlayer.repeat === "one"}
+ <text x="11" y="14" font-size="9" font-weight="bold" fill="currentColor" stroke="none">1</text>
+ {/if}
+ </svg>
+ </button>
+ <div class="np-volume">
+ <VolumeControl />
+ </div>
+ </div>
+ </section>
+
+ <section class="np-right">
+ <div class="np-tabs" role="tablist">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === "lyrics"}
+ class="np-tab"
+ class:active={tab === "lyrics"}
+ onclick={() => (tab = "lyrics")}
+ >{$t("study.music.now_playing_tab_lyrics")}</button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === "queue"}
+ class="np-tab"
+ class:active={tab === "queue"}
+ onclick={() => (tab = "queue")}
+ >{$t("study.music.now_playing_tab_queue")} <span class="np-tab-count">{upNext.length}</span></button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === "previous"}
+ class="np-tab"
+ class:active={tab === "previous"}
+ onclick={() => (tab = "previous")}
+ >{$t("study.music.now_playing_tab_previous")} <span class="np-tab-count">{previousTracks.length}</span></button>
+ </div>
+
+ <div class="np-tab-body">
+ {#if tab === "lyrics"}
+ {#if lyricsStatus === "loading"}
+ <div class="np-lyrics-skel" aria-hidden="true">
+ <span class="np-skel-bar" style:width="62%"></span>
+ <span class="np-skel-bar" style:width="48%"></span>
+ <span class="np-skel-bar" style:width="74%"></span>
+ </div>
+ {:else if lyricsStatus === "notfound"}
+ <p class="np-empty">{$t("study.music.now_playing_lyrics_empty")}</p>
+ {:else if lyricsStatus === "error"}
+ <p class="np-empty">{$t("study.music.now_playing_lyrics_error")}</p>
+ {:else if lyricsLines.length === 0}
+ <p class="np-empty">{$t("study.music.now_playing_lyrics_empty")}</p>
+ {:else}
+ <div bind:this={lyricsContainer} class="np-lyrics">
+ <ol>
+ {#each lyricsLines as line, i (i + ":" + line.text)}
+ <li
+ bind:this={lineRefs[i]}
+ class="np-line"
+ class:active={i === activeLyricIdx}
+ >{line.text || " "}</li>
+ {/each}
+ </ol>
+ </div>
+ {/if}
+ {:else if tab === "queue"}
+ {#if upNext.length === 0}
+ <p class="np-empty">{$t("study.music.now_playing_queue_empty")}</p>
+ {:else}
+ <ol class="np-list">
+ {#each upNext as qt, i (musicPlayer.queueIndex + 1 + i + ":" + qt.id)}
+ <li>
+ <button
+ type="button"
+ class="np-row"
+ onclick={() => jumpTo(musicPlayer.queueIndex + 1 + i)}
+ >
+ <span class="np-row-cover">
+ <CoverImage
+ src={qt.cover_path ?? qt.spotify_cover_url ?? qt.youtube_thumbnail ?? null}
+ alt={qt.title ?? qt.path}
+ size={36}
+ fallbackSeed={qt.album ?? qt.title}
+ rounded="sm"
+ trackId={qt.id}
+ />
+ </span>
+ <span class="np-row-meta">
+ <span class="np-row-title">{qt.title ?? qt.path}</span>
+ {#if qt.artist}<span class="np-row-artist">{qt.artist}</span>{/if}
+ </span>
+ <span class="np-row-time">{fmtDuration(qt.duration_ms ?? 0)}</span>
+ </button>
+ </li>
+ {/each}
+ </ol>
+ {/if}
+ {:else if tab === "previous"}
+ {#if previousTracks.length === 0}
+ <p class="np-empty">{$t("study.music.now_playing_previous_empty")}</p>
+ {:else}
+ <ol class="np-list">
+ {#each previousTracks as pt, i (musicPlayer.queueIndex - 1 - i + ":" + pt.id)}
+ <li>
+ <button
+ type="button"
+ class="np-row"
+ onclick={() => jumpTo(musicPlayer.queueIndex - 1 - i)}
+ >
+ <span class="np-row-cover">
+ <CoverImage
+ src={pt.cover_path ?? pt.spotify_cover_url ?? pt.youtube_thumbnail ?? null}
+ alt={pt.title ?? pt.path}
+ size={36}
+ fallbackSeed={pt.album ?? pt.title}
+ rounded="sm"
+ trackId={pt.id}
+ />
+ </span>
+ <span class="np-row-meta">
+ <span class="np-row-title">{pt.title ?? pt.path}</span>
+ {#if pt.artist}<span class="np-row-artist">{pt.artist}</span>{/if}
+ </span>
+ <span class="np-row-time">{fmtDuration(pt.duration_ms ?? 0)}</span>
+ </button>
+ </li>
+ {/each}
+ </ol>
+ {/if}
+ {/if}
+ </div>
+ </section>
+ </div>
+ </div>
+{:else}
+ <div class="np-shell np-empty-shell">
+ <p class="np-empty">{$t("study.music.now_playing_no_track")}</p>
+ <button type="button" class="np-close" onclick={close}>{$t("study.music.now_playing_close")}</button>
+ </div>
+{/if}
+
+<style>
+ .np-shell {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ color: var(--secondary);
+ isolation: isolate;
+ }
+ .np-empty-shell {
+ display: grid;
+ place-items: center;
+ gap: 12px;
+ }
+ .np-backdrop {
+ position: absolute;
+ inset: -10%;
+ z-index: -2;
+ filter: blur(60px) saturate(1.4);
+ opacity: 0.55;
+ pointer-events: none;
+ }
+ .np-backdrop :global(img),
+ .np-backdrop :global(.cover-fallback) {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: 0;
+ }
+ :global(.music-shell[data-reduce-animations="true"]) .np-backdrop {
+ filter: saturate(1.2);
+ opacity: 0.4;
+ }
+ .np-veil {
+ position: absolute;
+ inset: 0;
+ z-index: -1;
+ background:
+ radial-gradient(ellipse at 30% 0%, var(--music-accent-mid, transparent) 0%, transparent 60%),
+ linear-gradient(to bottom, rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.6));
+ pointer-events: none;
+ }
+ .np-close {
+ position: absolute;
+ top: 18px;
+ left: 22px;
+ z-index: 10;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 14px;
+ background: rgba(0, 0, 0, 0.35);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.9);
+ font-family: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ transition: background 120ms ease, border-color 120ms ease;
+ }
+ .np-close:hover {
+ background: rgba(0, 0, 0, 0.5);
+ border-color: rgba(255, 255, 255, 0.25);
+ }
+
+ .np-grid {
+ position: relative;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ width: 100%;
+ height: 100%;
+ max-width: 1400px;
+ margin-inline: auto;
+ padding: 80px 56px 48px;
+ gap: 56px;
+ box-sizing: border-box;
+ }
+
+ .np-left {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 24px;
+ min-width: 0;
+ }
+ .np-cover-wrap {
+ position: relative;
+ width: min(100%, 420px);
+ aspect-ratio: 1;
+ border-radius: 16px;
+ overflow: hidden;
+ box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);
+ align-self: flex-start;
+ }
+ .np-cover-wrap :global(img),
+ .np-cover-wrap :global(.cover-fallback) {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: inherit;
+ }
+
+ .np-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ }
+ .np-title {
+ font-size: 28px;
+ font-weight: 800;
+ line-height: 1.2;
+ margin: 0;
+ color: rgba(255, 255, 255, 0.98);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+ .np-artist {
+ font-size: 16px;
+ color: rgba(255, 255, 255, 0.8);
+ margin: 0;
+ }
+ .np-album {
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.55);
+ margin: 0;
+ }
+
+ .np-controls {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ }
+ .np-btn {
+ width: 38px;
+ height: 38px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: rgba(255, 255, 255, 0.85);
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ transition: color 120ms ease, background 120ms ease, transform 100ms ease;
+ }
+ .np-btn:hover { color: rgba(255, 255, 255, 1); background: rgba(255, 255, 255, 0.08); }
+ .np-btn.active { color: var(--music-highlight, var(--accent)); }
+ .np-btn:active { transform: scale(0.92); }
+ .np-play {
+ width: 60px;
+ height: 60px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.96);
+ color: #0f0f0f;
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
+ transition: transform 120ms ease, background 120ms ease;
+ }
+ .np-play:hover {
+ transform: scale(1.05);
+ background: rgba(255, 255, 255, 1);
+ }
+ .np-play:active { transform: scale(0.97); }
+ .np-spinner {
+ display: block;
+ width: 24px;
+ height: 24px;
+ border: 2px solid rgba(0, 0, 0, 0.3);
+ border-top-color: rgba(0, 0, 0, 0.85);
+ border-radius: 50%;
+ animation: np-spin 0.8s linear infinite;
+ }
+ @keyframes np-spin { to { transform: rotate(360deg); } }
+ .np-fav {
+ width: 38px;
+ height: 38px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: rgba(255, 255, 255, 0.7);
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ transition: color 120ms ease, background 120ms ease;
+ }
+ .np-fav:hover { color: rgba(255, 255, 255, 1); background: rgba(255, 255, 255, 0.08); }
+ .np-fav.on { color: var(--music-highlight, var(--accent)); }
+ .np-volume {
+ margin-left: auto;
+ }
+
+ .np-right {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+ background: rgba(0, 0, 0, 0.18);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 14px;
+ overflow: hidden;
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ }
+ .np-tabs {
+ display: flex;
+ gap: 4px;
+ padding: 10px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .np-tab {
+ flex: 1;
+ padding: 9px 12px;
+ background: transparent;
+ border: 0;
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.55);
+ font-family: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ transition: color 120ms ease, background 120ms ease;
+ }
+ .np-tab:hover { color: rgba(255, 255, 255, 0.85); background: rgba(255, 255, 255, 0.04); }
+ .np-tab.active {
+ color: rgba(255, 255, 255, 1);
+ background: rgba(255, 255, 255, 0.08);
+ }
+ .np-tab-count {
+ display: inline-block;
+ min-width: 18px;
+ padding: 0 6px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ font-size: 10px;
+ line-height: 16px;
+ color: rgba(255, 255, 255, 0.7);
+ }
+ .np-tab-body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 14px 16px 18px;
+ min-height: 0;
+ }
+
+ .np-empty {
+ margin: 0;
+ padding: 24px 8px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 13px;
+ text-align: center;
+ line-height: 1.5;
+ }
+
+ .np-lyrics {
+ height: 100%;
+ overflow-y: auto;
+ }
+ .np-lyrics ol {
+ list-style: none;
+ margin: 0;
+ padding: 18px 4px 50vh;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .np-line {
+ font-size: 17px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: rgba(255, 255, 255, 0.36);
+ transition: color 220ms ease, transform 220ms ease;
+ }
+ .np-line.active {
+ color: rgba(255, 255, 255, 1);
+ transform: scale(1.02);
+ transform-origin: left center;
+ }
+
+ .np-lyrics-skel {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 16px 4px;
+ }
+ .np-skel-bar {
+ height: 18px;
+ background: linear-gradient(
+ 90deg,
+ rgba(255, 255, 255, 0.06) 0%,
+ rgba(255, 255, 255, 0.12) 50%,
+ rgba(255, 255, 255, 0.06) 100%
+ );
+ background-size: 200% 100%;
+ border-radius: 6px;
+ animation: np-shimmer 1.4s ease-in-out infinite;
+ }
+ @keyframes np-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+
+ .np-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .np-row {
+ display: grid;
+ grid-template-columns: 36px 1fr auto;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 6px 8px;
+ background: transparent;
+ border: 0;
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.85);
+ font-family: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+ text-align: left;
+ transition: background 100ms ease;
+ }
+ .np-row:hover { background: rgba(255, 255, 255, 0.06); }
+ .np-row-cover {
+ width: 36px;
+ height: 36px;
+ border-radius: 5px;
+ overflow: hidden;
+ }
+ .np-row-cover :global(img),
+ .np-row-cover :global(.cover-fallback) {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .np-row-meta {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ overflow: hidden;
+ }
+ .np-row-title {
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: rgba(255, 255, 255, 0.95);
+ }
+ .np-row-artist {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .np-row-time {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ font-variant-numeric: tabular-nums;
+ }
+
+ @media (max-width: 960px) {
+ .np-grid {
+ grid-template-columns: 1fr;
+ grid-template-rows: auto 1fr;
+ padding: 76px 24px 24px;
+ gap: 24px;
+ overflow-y: auto;
+ height: auto;
+ min-height: 100%;
+ }
+ .np-cover-wrap {
+ width: min(70vw, 320px);
+ margin-inline: auto;
+ }
+ .np-meta { text-align: center; }
+ .np-title { -webkit-line-clamp: unset; line-clamp: unset; }
+ .np-controls { justify-content: center; flex-wrap: wrap; }
+ .np-volume { margin-left: 0; width: 100%; display: flex; justify-content: center; }
+ }
+</style>
diff --git a/src/routes/study/music/playlists/[id]/+page.svelte b/src/routes/study/music/playlists/[id]/+page.svelte
index b0f856bc..18080b3d 100644
--- a/src/routes/study/music/playlists/[id]/+page.svelte
+++ b/src/routes/study/music/playlists/[id]/+page.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
- import { onMount } from "svelte";
+ import { onMount, onDestroy } from "svelte";
+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { page } from "$app/stores";
import { goto } from "$app/navigation";
import { pluginInvoke } from "$lib/plugin-invoke";
@@ -35,6 +36,10 @@
let confirmDeleteOpen = $state(false);
let dragIndex = $state<number | null>(null);
let dragOver = $state<number | null>(null);
+ let confirmRefreshOpen = $state(false);
+ let refreshRunning = $state(false);
+ let refreshProgress = $state<{ current: number; total: number } | null>(null);
+ const refreshUnlisteners: UnlistenFn[] = [];
async function load() {
if (!Number.isFinite(playlistId)) return;
@@ -57,6 +62,45 @@
onMount(() => {
void load();
+ void (async () => {
+ const onStart = await listen<{ playlist_id: number; total: number }>(
+ "study:music:playlist:refresh_covers:start",
+ (e) => {
+ if (e.payload?.playlist_id !== playlistId) return;
+ refreshProgress = { current: 0, total: e.payload.total };
+ },
+ );
+ const onProgress = await listen<{
+ playlist_id: number;
+ current: number;
+ total: number;
+ }>("study:music:playlist:refresh_covers:progress", (e) => {
+ if (e.payload?.playlist_id !== playlistId) return;
+ refreshProgress = { current: e.payload.current, total: e.payload.total };
+ });
+ const onComplete = await listen<{
+ playlist_id: number;
+ updated: number;
+ errors: number;
+ skipped: number;
+ }>("study:music:playlist:refresh_covers:complete", (e) => {
+ if (e.payload?.playlist_id !== playlistId) return;
+ refreshRunning = false;
+ refreshProgress = null;
+ const p = e.payload;
+ const msg = ($t("study.music.refresh_covers_done", {
+ updated: p.updated,
+ skipped: p.skipped + p.errors,
+ }) as string) ?? `${p.updated} capa(s) atualizada(s)`;
+ showToast("success", msg);
+ void load();
+ });
+ refreshUnlisteners.push(onStart, onProgress, onComplete);
+ })();
+ });
+
+ onDestroy(() => {
+ for (const u of refreshUnlisteners) u();
});
$effect(() => {
@@ -182,6 +226,23 @@
dragIndex = null;
dragOver = null;
}
+
+ async function startRefreshCovers() {
+ if (refreshRunning) return;
+ refreshRunning = true;
+ confirmRefreshOpen = false;
+ refreshProgress = { current: 0, total: tracks.length };
+ try {
+ await pluginInvoke("study", "study:music:playlists:refresh_covers", {
+ playlistId,
+ });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ showToast("error", msg);
+ refreshRunning = false;
+ refreshProgress = null;
+ }
+ }
</script>
<section class="playlist-page">
@@ -244,6 +305,27 @@
<line x1="4" y1="4" x2="9" y2="9"/>
</svg>
</button>
+ <button
+ type="button"
+ class="ghost-big"
+ onclick={() => (confirmRefreshOpen = true)}
+ disabled={tracks.length === 0 || refreshRunning}
+ title={$t("study.music.refresh_covers_action") as string}
+ aria-label={$t("study.music.refresh_covers_action") as string}
+ >
+ {#if refreshRunning}
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class="spin">
+ <path d="M21 12a9 9 0 1 1-3-6.7"/>
+ <polyline points="21 4 21 10 15 10"/>
+ </svg>
+ {:else}
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
+ <circle cx="8.5" cy="8.5" r="1.5"/>
+ <polyline points="21 15 16 10 5 21"/>
+ </svg>
+ {/if}
+ </button>
<button
type="button"
class="ghost-big danger"
@@ -328,6 +410,43 @@
</ol>
{/if}
+ {#if refreshRunning && refreshProgress}
+ <div class="progress-strip" role="status" aria-live="polite">
+ <div class="progress-track">
+ <div
+ class="progress-fill"
+ style:width="{refreshProgress.total > 0
+ ? Math.round((refreshProgress.current / refreshProgress.total) * 100)
+ : 0}%"
+ ></div>
+ </div>
+ <span class="progress-label">
+ {$t("study.music.refresh_covers_progress", {
+ current: refreshProgress.current,
+ total: refreshProgress.total,
+ })}
+ </span>
+ </div>
+ {/if}
+
+ {#if confirmRefreshOpen}
+ <div class="confirm-overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) confirmRefreshOpen = false; }}>
+ <div class="confirm-dialog" role="dialog" aria-modal="true">
+ <h3>{$t("study.music.refresh_covers_title")}</h3>
+ <p>{$t("study.music.refresh_covers_body", { count: tracks.length })}</p>
+ <p class="hint">{$t("study.music.refresh_covers_hint")}</p>
+ <div class="confirm-actions">
+ <button type="button" class="ghost" onclick={() => (confirmRefreshOpen = false)}>
+ {$t("study.common.cancel")}
+ </button>
+ <button type="button" class="primary" onclick={startRefreshCovers}>
+ {$t("study.music.refresh_covers_confirm")}
+ </button>
+ </div>
+ </div>
+ </div>
+ {/if}
+
{#if confirmDeleteOpen}
<div class="confirm-overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) confirmDeleteOpen = false; }}>
<div class="confirm-dialog" role="dialog" aria-modal="true">
@@ -515,6 +634,53 @@
padding: 8px 14px; background: var(--error, #dc2626); color: white;
border: 0; border-radius: 8px; font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
}
+ .confirm-actions .primary {
+ padding: 8px 14px; background: var(--accent); color: var(--on-accent, white);
+ border: 0; border-radius: 8px; font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
+ }
+ .confirm-dialog .hint {
+ margin: -8px 0 16px;
+ font-size: 12px;
+ color: color-mix(in oklab, var(--tertiary) 80%, transparent);
+ }
+ .progress-strip {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ margin: 0 4px 4px;
+ border: 1px solid color-mix(in oklab, var(--accent) 40%, transparent);
+ border-radius: 8px;
+ background: color-mix(in oklab, var(--accent) 6%, transparent);
+ }
+ .progress-track {
+ flex: 1;
+ height: 4px;
+ border-radius: 4px;
+ background: color-mix(in oklab, var(--content-border) 50%, transparent);
+ overflow: hidden;
+ }
+ .progress-fill {
+ height: 100%;
+ background: var(--accent);
+ transition: width 200ms ease;
+ }
+ .progress-label {
+ font-size: 12px;
+ color: var(--tertiary);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ }
+ .spin {
+ animation: spin 1s linear infinite;
+ }
+ @keyframes spin {
+ to { transform: rotate(360deg); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .spin { animation: none; }
+ .progress-fill { transition: none; }
+ }
.muted { color: var(--tertiary); font-size: 13px; }
.error { color: var(--error, #dc2626); font-size: 13px; }
@media (max-width: 720px) {
diff --git a/src/routes/study/music/search/+page.svelte b/src/routes/study/music/search/+page.svelte
index b27731de..252bef11 100644
--- a/src/routes/study/music/search/+page.svelte
+++ b/src/routes/study/music/search/+page.svelte
@@ -76,6 +76,14 @@
timer = setTimeout(() => runSearch(q), 200);
}
+ function onSearchSubmit(e: Event) {
+ e.preventDefault();
+ const trimmed = q.trim();
+ if (!trimmed) return;
+ if (timer) clearTimeout(timer);
+ void runSearch(trimmed);
+ }
+
onMount(() => {
inputRef?.focus();
return () => {
@@ -86,7 +94,7 @@
<section class="search-page">
<header class="head">
- <div class="search-box">
+ <form class="search-box" onsubmit={onSearchSubmit}>
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="11" cy="11" r="7"/>
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
@@ -107,18 +115,20 @@
aria-label={$t("study.common.clear") as string}
>×</button>
{/if}
- </div>
+ </form>
</header>
{#if !q.trim()}
<div class="empty">
- <p>{$t("study.music.search_hint")}</p>
+ <p>{$t("study.music.local_search_hint")}</p>
</div>
{:else if loading}
- <p class="muted">{$t("study.common.loading")}</p>
+ <div class="empty muted">
+ <p>{$t("study.music.loading")}</p>
+ </div>
{:else if tracks.length === 0 && albums.length === 0 && artists.length === 0}
<div class="empty">
- <p>{$t("study.music.empty_results")}</p>
+ <p>{$t("study.music.empty_search_no_results")}</p>
</div>
{:else}
{#if tracks.length > 0}
@@ -199,6 +209,8 @@
}
.clear:hover { color: var(--secondary); }
.empty { padding: 48px 24px; text-align: center; color: var(--tertiary); font-size: 14px; }
+ .empty.muted p { font-style: italic; }
+ .head { display: flex; flex-direction: column; gap: 12px; }
.block { display: flex; flex-direction: column; gap: 10px; }
.block h2 { margin: 0; font-size: 16px; font-weight: 700; color: var(--secondary); }
.track-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }
@@ -231,5 +243,4 @@
color: var(--accent);
background: color-mix(in oklab, var(--accent) 8%, transparent);
}
- .muted { color: var(--tertiary); font-size: 13px; }
</style>
diff --git a/src/routes/study/music/soundcloud/+page.svelte b/src/routes/study/music/soundcloud/+page.svelte
index c98c366a..88d51b5e 100644
--- a/src/routes/study/music/soundcloud/+page.svelte
+++ b/src/routes/study/music/soundcloud/+page.svelte
@@ -7,8 +7,16 @@
soundcloudStore,
type ScTrack,
} from "$lib/study-music/soundcloud-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import {
+ getFirstDownloadDone,
+ getLastCodec,
+ getLastDownloadDir,
+ } from "$lib/study-music/local-prefs";
import { colorFromString } from "$lib/study-music/format";
import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";
+ import SoundCloudDownloadButton from "$lib/study-music-components/SoundCloudDownloadButton.svelte";
+ import SoundCloudError from "$lib/study-music-components/SoundCloudError.svelte";
let booting = $state(true);
let downloadTrack = $state<ScTrack | null>(null);
@@ -18,18 +26,35 @@
let importBusy = $state(false);
let importError = $state<string | null>(null);
+ let loginBusy = $state(false);
+ let loginError = $state<string | null>(null);
+
+ let loadError = $state<string | null>(null);
+ let playbackError = $state<string | null>(null);
+ let playbackTrack = $state<ScTrack | null>(null);
+ let playbackQueue = $state<ScTrack[] | null>(null);
let recommended = $state<ScTrack[]>([]);
let recommendedSeed = $state<ScTrack | null>(null);
onMount(async () => {
- await soundcloudStore.refreshStatus();
- if (soundcloudStore.isLoggedIn) {
- await soundcloudStore.loadAll();
- void loadRecommended();
- }
- booting = false;
+ await boot();
});
+ async function boot() {
+ loadError = null;
+ try {
+ await soundcloudStore.refreshStatus();
+ if (soundcloudStore.isLoggedIn) {
+ await soundcloudStore.loadAll();
+ void loadRecommended();
+ }
+ } catch (e) {
+ loadError = e instanceof Error ? e.message : String(e);
+ } finally {
+ booting = false;
+ }
+ }
+
async function loadRecommended() {
const seed = soundcloudStore.likedTracks[0] ?? soundcloudStore.streamFeed[0];
if (!seed) return;
@@ -43,24 +68,61 @@
}
async function refresh() {
- await soundcloudStore.refreshStatus();
- await soundcloudStore.loadAll();
- void loadRecommended();
+ loadError = null;
+ try {
+ await soundcloudStore.refreshStatus();
+ await soundcloudStore.loadAll();
+ void loadRecommended();
+ } catch (e) {
+ loadError = e instanceof Error ? e.message : String(e);
+ }
+ }
+
+ async function handleLogin() {
+ if (loginBusy) return;
+ loginBusy = true;
+ loginError = null;
+ try {
+ await soundcloudStore.loginWithWebview();
+ if (soundcloudStore.isLoggedIn) {
+ void loadRecommended();
+ } else {
+ loginError = "Não consegui completar o login. Tenta de novo.";
+ }
+ } catch (e) {
+ loginError = e instanceof Error ? e.message : String(e);
+ } finally {
+ loginBusy = false;
+ }
}
- async function openInBrowser() {
- const { open } = await import("@tauri-apps/plugin-shell");
- await open("https://soundcloud.com/signin");
+ async function handleLogout() {
+ try {
+ await soundcloudStore.logout();
+ recommended = [];
+ recommendedSeed = null;
+ loginError = null;
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
}
async function play(track: ScTrack, queue?: ScTrack[]) {
+ playbackError = null;
+ playbackTrack = track;
+ playbackQueue = queue ?? [track];
try {
await soundcloudStore.playTrack(track, queue);
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
+ playbackError = e instanceof Error ? e.message : String(e);
}
}
+ function retryPlayback() {
+ if (!playbackTrack) return;
+ void play(playbackTrack, playbackQueue ?? [playbackTrack]);
+ }
+
function fmtDuration(ms: number): string {
const total = Math.floor(ms / 1000);
const m = Math.floor(total / 60);
@@ -68,6 +130,46 @@
return `${m}:${s.toString().padStart(2, "0")}`;
}
+ function folderName(dir: string): string {
+ const parts = dir.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] ?? dir;
+ }
+
+ async function startInlineDownload(track: ScTrack) {
+ const codec = getLastCodec() ?? "mp3";
+ const dir = getLastDownloadDir();
+ if (!dir) {
+ downloadTrack = track;
+ return;
+ }
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: track.id,
+ title: track.title,
+ artist: track.user.username,
+ artwork:
+ soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url) ?? null,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: track.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ showToast("success", `Pronto — salvo na pasta ${folderName(dir)}`);
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function handleDownload(track: ScTrack, advanced: boolean) {
+ if (advanced || !getFirstDownloadDone() || !getLastDownloadDir()) {
+ downloadTrack = track;
+ return;
+ }
+ void startInlineDownload(track);
+ }
+
function openImport() {
importUrl = "";
importError = null;
@@ -170,7 +272,7 @@
{/if}
<span>{soundcloudStore.profile.username}</span>
</span>
- <button type="button" class="ghost-btn" onclick={() => soundcloudStore.logout()}>{$t('study.music.sc_logout')}</button>
+ <button type="button" class="ghost-btn" onclick={handleLogout}>{$t('study.music.sc_logout')}</button>
</div>
{/if}
</header>
@@ -184,18 +286,36 @@
<path d="M1.175 12.225c-.051 0-.094.046-.101.1l-.233 2.154.233 2.105c.007.058.05.098.101.098.05 0 .09-.04.099-.098l.255-2.105-.27-2.154c0-.057-.045-.1-.09-.1m-.899.828c-.06 0-.091.037-.104.094L0 14.479l.165 1.308c0 .055.045.094.09.094s.089-.045.104-.104l.21-1.319-.21-1.334c0-.061-.044-.1-.09-.1m1.83-1.229c-.061 0-.12.045-.12.104l-.21 2.563.225 2.458c0 .06.045.12.12.12.06 0 .12-.061.12-.12l.255-2.458-.27-2.563c0-.06-.045-.104-.12-.104m.945-.089c-.075 0-.135.06-.15.135l-.193 2.652.21 2.544c.016.077.075.135.149.135.075 0 .135-.058.15-.135l.225-2.544-.225-2.652c-.014-.075-.075-.135-.149-.135m1.139.07c-.089 0-.164.072-.164.163l-.21 2.602.193 2.581c0 .088.075.157.164.157.09 0 .166-.069.18-.157l.21-2.581-.21-2.602c-.014-.091-.09-.163-.18-.163m.93-.058c-.105 0-.18.07-.18.166l-.21 2.6.18 2.539c0 .106.075.179.179.179.111 0 .19-.073.19-.18l.224-2.539-.21-2.6c0-.094-.083-.165-.197-.165m.95-.082c-.12 0-.21.087-.21.207l-.165 2.6.165 2.482c0 .12.09.214.21.214.12 0 .211-.094.211-.214l.196-2.482-.196-2.6c0-.12-.091-.207-.21-.207m1.022-.034c-.135 0-.226.103-.226.225l-.165 2.616.165 2.466c0 .118.09.222.226.222.12 0 .21-.104.226-.222l.179-2.466-.18-2.616c-.015-.122-.105-.225-.225-.225m1.039-.225c-.135 0-.255.121-.255.255l-.135 2.84.135 2.453c0 .135.12.241.255.241s.255-.106.27-.241l.149-2.453-.15-2.84c-.014-.135-.135-.255-.27-.255m1.171.106c-.149 0-.27.121-.27.271l-.119 2.738.119 2.453c0 .15.121.27.27.27.15 0 .271-.12.286-.27l.135-2.453-.135-2.738c-.015-.15-.135-.27-.286-.271m1.205.345c-.165 0-.299.135-.299.301l-.105 2.379.105 2.469c0 .166.134.301.299.301.165 0 .3-.135.3-.3l.121-2.471-.121-2.379c0-.166-.135-.301-.3-.301m1.295-.106c-.18 0-.314.135-.314.314l-.091 2.47.091 2.453c0 .181.135.315.314.315.181 0 .315-.134.315-.315l.105-2.453-.105-2.47c0-.179-.135-.314-.315-.314m1.376-.241c-.196 0-.345.149-.345.345l-.075 2.692.075 2.452c0 .197.15.345.345.345.196 0 .346-.148.346-.345l.09-2.452-.09-2.692c0-.196-.151-.345-.346-.345m1.487 5.879H22.49a1.515 1.515 0 0 0 1.51-1.524 1.512 1.512 0 0 0-1.51-1.51c-.135 0-.27.014-.39.044C22.04 9.706 19.94 7.766 17.39 7.766c-.61 0-1.21.135-1.756.36-.15.06-.18.105-.18.255v9.117c.014.165.135.299.299.314z"/>
</svg>
</div>
- <h2>{$t('study.music.sc_signin_heading')}</h2>
- <p>{$t('study.music.sc_signin_body')}</p>
+ <h2>Entrar com SoundCloud</h2>
+ <p>Vai abrir uma janelinha do SoundCloud. Faça login e ela fecha sozinha quando você terminar.</p>
<div class="login-actions">
- <button type="button" class="cta" onclick={openInBrowser}>{$t('study.music.sc_open_in_browser')}</button>
- <button type="button" class="ghost-btn" onclick={refresh}>{$t('study.music.sc_already_signed_in')}</button>
+ <button type="button" class="cta" disabled={loginBusy} onclick={handleLogin}>
+ {loginBusy ? "Abrindo SoundCloud…" : "Entrar com SoundCloud"}
+ </button>
</div>
- {#if soundcloudStore.error}
- <p class="error">{soundcloudStore.error}</p>
+ {#if loginError}
+ <p class="error">{loginError}</p>
+ <details class="why-fail">
+ <summary>Por que pode falhar?</summary>
+ <ul>
+ <li>Conta nova: confirme o email primeiro no SoundCloud</li>
+ <li>2FA: termine o segundo passo antes de fechar a janela</li>
+ <li>Captcha: resolva no site, a janela espera você</li>
+ </ul>
+ </details>
{/if}
- <p class="hint">{$t('study.music.sc_status_client_id')}: {soundcloudStore.status.has_client_id ? '✓' : '✗'} · {$t('study.music.sc_status_oauth')}: {soundcloudStore.status.has_oauth ? '✓' : '✗'}</p>
</div>
{:else}
+ {#if loadError}
+ <SoundCloudError error={loadError} onRetry={refresh} />
+ {/if}
+ {#if playbackError}
+ <SoundCloudError
+ error={playbackError}
+ trackUrl={playbackTrack?.permalink_url}
+ onRetry={retryPlayback}
+ />
+ {/if}
{#if recommended.length > 0}
<section class="block">
<header class="block-head">
@@ -216,9 +336,7 @@
<span class="track-artist">{track.user.username}</span>
</div>
<span class="track-dur">{fmtDuration(track.duration)}</span>
- <button type="button" class="dl-btn" onclick={(e) => { e.stopPropagation(); downloadTrack = track; }} aria-label={$t('study.music.sc_download_track') as string}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton {track} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -243,9 +361,7 @@
<span class="track-artist">{track.user.username}</span>
</div>
<span class="track-dur">{fmtDuration(track.duration)}</span>
- <button type="button" class="dl-btn" onclick={(e) => { e.stopPropagation(); downloadTrack = track; }} aria-label={$t('study.music.sc_download_track') as string}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton {track} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -269,9 +385,7 @@
<span class="track-artist">{track.user.username}</span>
</div>
<span class="track-dur">{fmtDuration(track.duration)}</span>
- <button type="button" class="dl-btn" onclick={(e) => { e.stopPropagation(); downloadTrack = track; }} aria-label={$t('study.music.sc_download_track') as string}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton {track} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -341,7 +455,6 @@
placeholder={$t('study.music.sc_import_url_placeholder') as string}
bind:value={importUrl}
onkeydown={(e) => { if (e.key === 'Enter') submitImport(); }}
- autofocus
spellcheck="false"
/>
{#if importError}<p class="d-error">{importError}</p>{/if}
@@ -388,7 +501,12 @@
.cta { padding: 12px 32px; background: #ff5500; color: white; border: 0; border-radius: 999px; font-family: inherit; font-size: 14px; font-weight: 700; cursor: pointer; transition: background 200ms ease; }
.cta:hover { background: #ff7733; }
.error { color: #e22134; font-size: 13px; }
- .hint { font-size: 11px; color: rgba(255,255,255,0.4); }
+ .why-fail { margin-top: 4px; max-width: 44ch; text-align: left; color: rgba(255,255,255,0.65); font-size: 12px; }
+ .why-fail summary { cursor: pointer; color: rgba(255,255,255,0.55); padding: 2px 0; user-select: none; }
+ .why-fail summary:hover { color: rgba(255,255,255,0.85); }
+ .why-fail ul { margin: 8px 0 0; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; }
+ .why-fail li { line-height: 1.5; }
+ .cta:disabled { opacity: 0.6; cursor: not-allowed; }
.block { display: flex; flex-direction: column; gap: 16px; }
.block-head h2 { margin: 0; font-size: 22px; font-weight: 800; }
@@ -403,8 +521,6 @@
.track-title { font-size: 14px; font-weight: 600; color: white; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.track-artist { font-size: 12px; color: rgba(255,255,255,0.55); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.track-dur { font-size: 13px; color: rgba(255,255,255,0.55); text-align: right; font-variant-numeric: tabular-nums; }
- .dl-btn { width: 28px; height: 28px; padding: 0; background: transparent; border: 0; color: rgba(255,255,255,0.5); cursor: pointer; display: grid; place-items: center; border-radius: 4px; transition: background 200ms ease, color 200ms ease; }
- .dl-btn:hover { background: rgba(255,255,255,0.1); color: #ff5500; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 24px; }
.card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: left; text-decoration: none; }
diff --git a/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte b/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte
index 61ad69bb..a08a2b00 100644
--- a/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte
+++ b/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte
@@ -2,7 +2,6 @@
import { onMount } from "svelte";
import { page } from "$app/stores";
import { goto } from "$app/navigation";
- import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { t } from "$lib/i18n";
import { showToast } from "$lib/stores/toast-store.svelte";
import {
@@ -10,27 +9,39 @@
type ScPlaylist,
type ScTrack,
} from "$lib/study-music/soundcloud-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import {
+ getFirstDownloadDone,
+ getLastCodec,
+ getLastDownloadDir,
+ setLastCodec,
+ setLastDownloadDir,
+ } from "$lib/study-music/local-prefs";
import { colorFromString } from "$lib/study-music/format";
import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";
+ import SoundCloudDownloadButton from "$lib/study-music-components/SoundCloudDownloadButton.svelte";
+ import SoundCloudError from "$lib/study-music-components/SoundCloudError.svelte";
let playlist = $state<ScPlaylist | null>(null);
let tracks = $state<ScTrack[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
+ let playbackError = $state<string | null>(null);
+ let playbackTrack = $state<ScTrack | null>(null);
+ let playbackQueue = $state<ScTrack[] | null>(null);
let downloadTrack = $state<ScTrack | null>(null);
let bulkBusy = $state(false);
- let bulkCurrent = $state(0);
- let bulkTotal = $state(0);
- let bulkUnlisten: UnlistenFn | null = null;
const playlistId = $derived(parseInt($page.params.id ?? "0", 10));
- onMount(async () => {
+ async function load() {
if (!playlistId) {
goto("/study/music/soundcloud");
return;
}
+ loading = true;
+ error = null;
try {
const p = await soundcloudStore.getPlaylist(playlistId);
playlist = p;
@@ -40,18 +51,32 @@
} finally {
loading = false;
}
- });
+ }
- async function play(idx: number) {
- if (tracks.length === 0) return;
- const reordered = [...tracks.slice(idx), ...tracks.slice(0, idx)];
+ onMount(load);
+
+ async function playQueue(track: ScTrack, queue: ScTrack[]) {
+ playbackError = null;
+ playbackTrack = track;
+ playbackQueue = queue;
try {
- await soundcloudStore.playTrack(reordered[0], reordered);
+ await soundcloudStore.playTrack(track, queue);
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
+ playbackError = e instanceof Error ? e.message : String(e);
}
}
+ async function play(idx: number) {
+ if (tracks.length === 0) return;
+ const reordered = [...tracks.slice(idx), ...tracks.slice(0, idx)];
+ await playQueue(reordered[0], reordered);
+ }
+
+ function retryPlayback() {
+ if (!playbackTrack) return;
+ void playQueue(playbackTrack, playbackQueue ?? [playbackTrack]);
+ }
+
function fmtDuration(ms: number): string {
const total = Math.floor(ms / 1000);
const m = Math.floor(total / 60);
@@ -60,49 +85,87 @@
}
async function downloadAll() {
- if (bulkBusy || tracks.length === 0) return;
- const dialog = await import("@tauri-apps/plugin-dialog");
- const picked = await dialog.open({ directory: true, multiple: false });
- if (typeof picked !== "string" || !picked) return;
+ if (bulkBusy || tracks.length === 0 || !playlist) return;
+ const codec = getLastCodec() ?? "mp3";
+ let dir = getLastDownloadDir();
+ if (!dir) {
+ const dialog = await import("@tauri-apps/plugin-dialog");
+ const picked = await dialog.open({ directory: true, multiple: false });
+ if (typeof picked !== "string" || !picked) return;
+ dir = picked;
+ setLastDownloadDir(dir);
+ setLastCodec(codec);
+ }
bulkBusy = true;
- bulkCurrent = 0;
- bulkTotal = tracks.length;
+ downloadStore.addOptimisticBulkJob({
+ playlistId,
+ title: playlist.title,
+ total: tracks.length,
+ artwork: soundcloudStore.pickArtwork(playlist.artwork_url) ?? null,
+ codec,
+ outputDir: dir,
+ });
+ downloadStore.toggleDrawer(true);
try {
- bulkUnlisten = await listen<{
- playlist_id: number;
- stage: string;
- current: number;
- total: number;
- success?: number;
- failed?: number;
- }>("study-soundcloud-download-bulk-progress", (e) => {
- if (e.payload.playlist_id !== playlistId) return;
- bulkCurrent = e.payload.current;
- bulkTotal = e.payload.total;
- if (e.payload.stage === "done") {
- showToast(
- "success",
- $t("study.music.sc_download_bulk_done", {
- success: e.payload.success ?? 0,
- failed: e.payload.failed ?? 0,
- }) as string,
- );
- }
- });
- await soundcloudStore.downloadPlaylist({
+ const res = await soundcloudStore.downloadPlaylist({
playlistId,
- codec: "mp3",
- outputDir: picked,
+ codec,
+ outputDir: dir,
quality: "progressive",
});
+ showToast(
+ "success",
+ $t("study.music.sc_download_bulk_done", {
+ success: res.success,
+ failed: res.failed,
+ }) as string,
+ );
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
} finally {
- bulkUnlisten?.();
- bulkUnlisten = null;
bulkBusy = false;
}
}
+
+ function folderName(dir: string): string {
+ const parts = dir.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] ?? dir;
+ }
+
+ async function startInlineDownload(track: ScTrack) {
+ const codec = getLastCodec() ?? "mp3";
+ const dir = getLastDownloadDir();
+ if (!dir) {
+ downloadTrack = track;
+ return;
+ }
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: track.id,
+ title: track.title,
+ artist: track.user.username,
+ artwork:
+ soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url) ?? null,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: track.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ showToast("success", `Pronto — salvo na pasta ${folderName(dir)}`);
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function handleDownload(track: ScTrack, advanced: boolean) {
+ if (advanced || !getFirstDownloadDone() || !getLastDownloadDir()) {
+ downloadTrack = track;
+ return;
+ }
+ void startInlineDownload(track);
+ }
</script>
<section class="page">
@@ -137,7 +200,7 @@
<button type="button" class="bulk-btn" onclick={downloadAll} disabled={bulkBusy || tracks.length === 0}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
{bulkBusy
- ? $t('study.music.sc_download_bulk_progress', { current: bulkCurrent, total: bulkTotal })
+ ? "Baixando playlist…"
: $t('study.music.sc_download_all', { count: tracks.length })}
</button>
</div>
@@ -148,8 +211,19 @@
{#if loading}
<p class="muted">Carregando…</p>
{:else if error}
- <p class="error">{error}</p>
+ <SoundCloudError
+ {error}
+ trackUrl={playlist?.permalink_url}
+ onRetry={load}
+ />
{:else}
+ {#if playbackError}
+ <SoundCloudError
+ error={playbackError}
+ trackUrl={playbackTrack?.permalink_url}
+ onRetry={retryPlayback}
+ />
+ {/if}
<div class="track-list">
{#each tracks as track, i (track.id)}
<div class="track-row" role="button" tabindex="0" onclick={() => play(i)} onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); play(i); } }}>
@@ -164,9 +238,7 @@
<span class="a">{track.user.username}</span>
</div>
<span class="d">{fmtDuration(track.duration)}</span>
- <button type="button" class="dl" onclick={(e) => { e.stopPropagation(); downloadTrack = track; }} aria-label="Baixar">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton {track} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -208,8 +280,5 @@
.t { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.a { font-size: 12px; color: rgba(255,255,255,0.55); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.d { font-size: 13px; color: rgba(255,255,255,0.55); text-align: right; font-variant-numeric: tabular-nums; }
- .dl { width: 28px; height: 28px; padding: 0; background: transparent; border: 0; color: rgba(255,255,255,0.5); cursor: pointer; display: grid; place-items: center; border-radius: 4px; transition: background 200ms ease, color 200ms ease; }
- .dl:hover { background: rgba(255,255,255,0.1); color: #ff5500; }
.muted { color: rgba(255,255,255,0.5); font-size: 13px; }
- .error { color: #e22134; font-size: 13px; }
</style>
diff --git a/src/routes/study/music/soundcloud/search/+page.svelte b/src/routes/study/music/soundcloud/search/+page.svelte
index 13afafec..bb0c5b70 100644
--- a/src/routes/study/music/soundcloud/search/+page.svelte
+++ b/src/routes/study/music/soundcloud/search/+page.svelte
@@ -8,8 +8,16 @@
type ScTrack,
type ScUser,
} from "$lib/study-music/soundcloud-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import {
+ getFirstDownloadDone,
+ getLastCodec,
+ getLastDownloadDir,
+ } from "$lib/study-music/local-prefs";
import { colorFromString } from "$lib/study-music/format";
import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";
+ import SoundCloudDownloadButton from "$lib/study-music-components/SoundCloudDownloadButton.svelte";
+ import SoundCloudError from "$lib/study-music-components/SoundCloudError.svelte";
type Tab = "tracks" | "playlists" | "users";
@@ -21,6 +29,10 @@
let playlists = $state<ScPlaylist[]>([]);
let users = $state<ScUser[]>([]);
let loading = $state(false);
+ let searchError = $state<string | null>(null);
+ let playbackError = $state<string | null>(null);
+ let playbackTrack = $state<ScTrack | null>(null);
+ let playbackQueue = $state<ScTrack[] | null>(null);
let downloadTrack = $state<ScTrack | null>(null);
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -47,6 +59,7 @@
const q = query.trim();
if (!q) return;
loading = true;
+ searchError = null;
try {
const [t, p, u] = await Promise.allSettled([
soundcloudStore.search("tracks", q, 30),
@@ -56,27 +69,88 @@
tracks = (t.status === "fulfilled" ? (t.value as ScTrack[]) : []) ?? [];
playlists = (p.status === "fulfilled" ? (p.value as ScPlaylist[]) : []) ?? [];
users = (u.status === "fulfilled" ? (u.value as ScUser[]) : []) ?? [];
+ const firstReject = [t, p, u].find((r) => r.status === "rejected");
+ if (
+ firstReject &&
+ firstReject.status === "rejected" &&
+ tracks.length === 0 &&
+ playlists.length === 0 &&
+ users.length === 0
+ ) {
+ searchError =
+ firstReject.reason instanceof Error
+ ? firstReject.reason.message
+ : String(firstReject.reason);
+ }
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
+ searchError = e instanceof Error ? e.message : String(e);
} finally {
loading = false;
}
}
async function play(track: ScTrack, queueAll: ScTrack[]) {
+ playbackError = null;
+ playbackTrack = track;
+ playbackQueue = queueAll;
try {
await soundcloudStore.playTrack(track, queueAll);
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
+ playbackError = e instanceof Error ? e.message : String(e);
}
}
+ function retryPlayback() {
+ if (!playbackTrack) return;
+ void play(playbackTrack, playbackQueue ?? [playbackTrack]);
+ }
+
function fmtDuration(ms: number): string {
const total = Math.floor(ms / 1000);
const m = Math.floor(total / 60);
const s = total % 60;
return `${m}:${s.toString().padStart(2, "0")}`;
}
+
+ function folderName(dir: string): string {
+ const parts = dir.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] ?? dir;
+ }
+
+ async function startInlineDownload(track: ScTrack) {
+ const codec = getLastCodec() ?? "mp3";
+ const dir = getLastDownloadDir();
+ if (!dir) {
+ downloadTrack = track;
+ return;
+ }
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: track.id,
+ title: track.title,
+ artist: track.user.username,
+ artwork:
+ soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url) ?? null,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: track.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ showToast("success", `Pronto — salvo na pasta ${folderName(dir)}`);
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function handleDownload(track: ScTrack, advanced: boolean) {
+ if (advanced || !getFirstDownloadDone() || !getLastDownloadDir()) {
+ downloadTrack = track;
+ return;
+ }
+ void startInlineDownload(track);
+ }
</script>
<section class="page">
@@ -103,6 +177,17 @@
{#if loading}<span class="spinner"></span>{/if}
</div>
+ {#if searchError}
+ <SoundCloudError error={searchError} onRetry={doSearch} />
+ {/if}
+ {#if playbackError}
+ <SoundCloudError
+ error={playbackError}
+ trackUrl={playbackTrack?.permalink_url}
+ onRetry={retryPlayback}
+ />
+ {/if}
+
{#if tracks.length || playlists.length || users.length}
<div class="tabs" role="tablist">
<button type="button" class="tab" class:on={tab === "tracks"} onclick={() => (tab = "tracks")} role="tab" aria-selected={tab === "tracks"}>Faixas {tracks.length > 0 ? `(${tracks.length})` : ""}</button>
@@ -123,9 +208,7 @@
<span class="a">{t.user.username}</span>
</div>
<span class="d">{fmtDuration(t.duration)}</span>
- <button type="button" class="dl" onclick={(e) => { e.stopPropagation(); downloadTrack = t; }} aria-label="Baixar">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton track={t} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -184,8 +267,6 @@
.t { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.a { font-size: 12px; color: rgba(255,255,255,0.55); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.d { font-size: 13px; color: rgba(255,255,255,0.55); text-align: right; font-variant-numeric: tabular-nums; }
- .dl { width: 28px; height: 28px; padding: 0; background: transparent; border: 0; color: rgba(255,255,255,0.5); cursor: pointer; display: grid; place-items: center; border-radius: 4px; transition: background 200ms ease, color 200ms ease; }
- .dl:hover { background: rgba(255,255,255,0.1); color: #ff5500; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 24px; }
.card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: left; text-decoration: none; }
.card-cover, .card-circle { aspect-ratio: 1/1; border-radius: 12px; overflow: hidden; margin-bottom: 12px; background: rgba(40,40,40,0.8); }
diff --git a/src/routes/study/music/soundcloud/user/[id]/+page.svelte b/src/routes/study/music/soundcloud/user/[id]/+page.svelte
index 7450d5a2..fef57679 100644
--- a/src/routes/study/music/soundcloud/user/[id]/+page.svelte
+++ b/src/routes/study/music/soundcloud/user/[id]/+page.svelte
@@ -9,23 +9,36 @@
type ScTrack,
type ScUser,
} from "$lib/study-music/soundcloud-store.svelte";
+ import { downloadStore } from "$lib/study-music/download-store.svelte";
+ import {
+ getFirstDownloadDone,
+ getLastCodec,
+ getLastDownloadDir,
+ } from "$lib/study-music/local-prefs";
import { colorFromString } from "$lib/study-music/format";
import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";
+ import SoundCloudDownloadButton from "$lib/study-music-components/SoundCloudDownloadButton.svelte";
+ import SoundCloudError from "$lib/study-music-components/SoundCloudError.svelte";
let user = $state<ScUser | null>(null);
let tracks = $state<ScTrack[]>([]);
let playlists = $state<ScPlaylist[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
+ let playbackError = $state<string | null>(null);
+ let playbackTrack = $state<ScTrack | null>(null);
+ let playbackQueue = $state<ScTrack[] | null>(null);
let downloadTrack = $state<ScTrack | null>(null);
const userId = $derived(parseInt($page.params.id ?? "0", 10));
- onMount(async () => {
+ async function load() {
if (!userId) {
goto("/study/music/soundcloud");
return;
}
+ loading = true;
+ error = null;
try {
const [u, t, p] = await Promise.allSettled([
soundcloudStore.getUser(userId),
@@ -35,29 +48,90 @@
if (u.status === "fulfilled") user = u.value;
if (t.status === "fulfilled") tracks = t.value;
if (p.status === "fulfilled") playlists = p.value;
+ const firstReject = [u, t, p].find((r) => r.status === "rejected");
+ if (firstReject && firstReject.status === "rejected" && !user) {
+ error =
+ firstReject.reason instanceof Error
+ ? firstReject.reason.message
+ : String(firstReject.reason);
+ }
} catch (e) {
error = e instanceof Error ? e.message : String(e);
} finally {
loading = false;
}
- });
+ }
- async function play(idx: number) {
- if (tracks.length === 0) return;
- const reordered = [...tracks.slice(idx), ...tracks.slice(0, idx)];
+ onMount(load);
+
+ async function playQueue(track: ScTrack, queue: ScTrack[]) {
+ playbackError = null;
+ playbackTrack = track;
+ playbackQueue = queue;
try {
- await soundcloudStore.playTrack(reordered[0], reordered);
+ await soundcloudStore.playTrack(track, queue);
} catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
+ playbackError = e instanceof Error ? e.message : String(e);
}
}
+ async function play(idx: number) {
+ if (tracks.length === 0) return;
+ const reordered = [...tracks.slice(idx), ...tracks.slice(0, idx)];
+ await playQueue(reordered[0], reordered);
+ }
+
+ function retryPlayback() {
+ if (!playbackTrack) return;
+ void playQueue(playbackTrack, playbackQueue ?? [playbackTrack]);
+ }
+
function fmtDuration(ms: number): string {
const total = Math.floor(ms / 1000);
const m = Math.floor(total / 60);
const s = total % 60;
return `${m}:${s.toString().padStart(2, "0")}`;
}
+
+ function folderName(dir: string): string {
+ const parts = dir.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] ?? dir;
+ }
+
+ async function startInlineDownload(track: ScTrack) {
+ const codec = getLastCodec() ?? "mp3";
+ const dir = getLastDownloadDir();
+ if (!dir) {
+ downloadTrack = track;
+ return;
+ }
+ const optId = downloadStore.addOptimisticSingleJob({
+ trackId: track.id,
+ title: track.title,
+ artist: track.user.username,
+ artwork:
+ soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url) ?? null,
+ });
+ try {
+ await soundcloudStore.download({
+ trackId: track.id,
+ codec,
+ outputDir: dir,
+ quality: "progressive",
+ });
+ showToast("success", `Pronto — salvo na pasta ${folderName(dir)}`);
+ } catch (e) {
+ downloadStore.markJobError(optId, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function handleDownload(track: ScTrack, advanced: boolean) {
+ if (advanced || !getFirstDownloadDone() || !getLastDownloadDir()) {
+ downloadTrack = track;
+ return;
+ }
+ void startInlineDownload(track);
+ }
</script>
<section class="page">
@@ -100,8 +174,19 @@
{#if loading}
<p class="muted">Carregando…</p>
{:else if error}
- <p class="error">{error}</p>
+ <SoundCloudError
+ {error}
+ trackUrl={user?.permalink_url}
+ onRetry={load}
+ />
{:else}
+ {#if playbackError}
+ <SoundCloudError
+ error={playbackError}
+ trackUrl={playbackTrack?.permalink_url}
+ onRetry={retryPlayback}
+ />
+ {/if}
{#if tracks.length > 0}
<section class="block">
<header class="block-head"><h2>Faixas ({tracks.length})</h2></header>
@@ -119,9 +204,7 @@
{#if track.likes_count}<span class="a">♥ {track.likes_count.toLocaleString("pt-BR")}</span>{/if}
</div>
<span class="d">{fmtDuration(track.duration)}</span>
- <button type="button" class="dl" onclick={(e) => { e.stopPropagation(); downloadTrack = track; }} aria-label="Baixar">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
- </button>
+ <SoundCloudDownloadButton {track} onTrigger={handleDownload} />
</div>
{/each}
</div>
@@ -184,8 +267,6 @@
.t { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.a { font-size: 12px; color: rgba(255,255,255,0.55); }
.d { font-size: 13px; color: rgba(255,255,255,0.55); text-align: right; font-variant-numeric: tabular-nums; }
- .dl { width: 28px; height: 28px; padding: 0; background: transparent; border: 0; color: rgba(255,255,255,0.5); cursor: pointer; display: grid; place-items: center; border-radius: 4px; transition: background 200ms ease, color 200ms ease; }
- .dl:hover { background: rgba(255,255,255,0.1); color: #ff5500; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 24px; }
.card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: left; text-decoration: none; }
.card-cover { aspect-ratio: 1/1; border-radius: 12px; overflow: hidden; margin-bottom: 12px; background: rgba(40,40,40,0.8); }
@@ -195,5 +276,4 @@
.card-title { margin: 0; font-size: 14px; font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; }
.card-sub { margin: 4px 0 0; font-size: 12px; color: rgba(255,255,255,0.5); padding: 0 4px; }
.muted { color: rgba(255,255,255,0.5); font-size: 13px; }
- .error { color: #e22134; font-size: 13px; }
</style>
diff --git a/src/routes/study/music/spotify/+page.svelte b/src/routes/study/music/spotify/+page.svelte
index 09a7ffe6..93ff8c41 100644
--- a/src/routes/study/music/spotify/+page.svelte
+++ b/src/routes/study/music/spotify/+page.svelte
@@ -23,13 +23,13 @@
await spotifyStore.refreshStatus();
await spotifyStore.loadAll();
void spotifyStore.prewarmSdk();
- showToast("success", "Conectado ao Spotify");
+ showToast("success", $t("study.music.spotify_connected") as string);
});
unlistenError = await listen<{ error: string }>(
"study-spotify-auth-error",
(event) => {
spotifyStore.authInProgress = false;
- spotifyStore.error = event.payload.error ?? "Falha na autenticação";
+ spotifyStore.error = event.payload.error ?? ($t("study.music.spotify_auth_failed") as string);
showToast("error", spotifyStore.error);
},
);
@@ -48,7 +48,7 @@
async function refreshLibrary() {
await spotifyStore.loadAll();
- showToast("info", "Biblioteca atualizada");
+ showToast("info", $t("study.music.spotify_library_updated") as string);
}
onDestroy(() => {
@@ -61,7 +61,7 @@
await spotifyStore.login();
showToast(
"info",
- "Aguardando autorização no navegador. Volte aqui depois de aceitar.",
+ $t("study.music.spotify_auth_waiting") as string,
);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
@@ -75,14 +75,14 @@
async function doLogout() {
await spotifyStore.logout();
- showToast("info", "Desconectado do Spotify");
+ showToast("info", $t("study.music.spotify_disconnected") as string);
}
async function playTrack(track: SpotifyTrack, queue?: SpotifyTrack[]) {
try {
const mode = await spotifyStore.playTrack(track, queue);
if (mode === "youtube") {
- showToast("info", "Tocando via YouTube (modo Free)");
+ showToast("info", $t("study.music.spotify_play_via_yt") as string);
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
@@ -126,17 +126,17 @@
type="button"
class="ghost-btn"
onclick={() => goto("/study/music/spotify/search")}
- aria-label="Buscar no Spotify"
+ aria-label={$t("study.music.spotify_search_aria") as string}
>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="11" cy="11" r="8"/>
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
</svg>
- Buscar
+ {$t("study.music.spotify_search_label")}
</button>
{/if}
<button type="button" class="ghost-btn" onclick={refreshLibrary}>
- Atualizar
+ {$t("study.music.spotify_refresh_label")}
</button>
<span class="profile-pill">
{#if spotifyStore.profile.images?.[0]?.url}
@@ -255,10 +255,10 @@
<header class="block-head">
<h2>Suas playlists</h2>
<div class="scroll-arrows">
- <button type="button" class="arrow" onclick={() => scrollContainer("sp-playlists", -1)} aria-label="Anterior">
+ <button type="button" class="arrow" onclick={() => scrollContainer("sp-playlists", -1)} aria-label={$t("study.music.spotify_prev_aria") as string}>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
</button>
- <button type="button" class="arrow" onclick={() => scrollContainer("sp-playlists", 1)} aria-label="Próximo">
+ <button type="button" class="arrow" onclick={() => scrollContainer("sp-playlists", 1)} aria-label={$t("study.music.spotify_next_aria") as string}>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
@@ -294,10 +294,10 @@
<header class="block-head">
<h2>Seus artistas</h2>
<div class="scroll-arrows">
- <button type="button" class="arrow" onclick={() => scrollContainer("sp-artists", -1)} aria-label="Anterior">
+ <button type="button" class="arrow" onclick={() => scrollContainer("sp-artists", -1)} aria-label={$t("study.music.spotify_prev_aria") as string}>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
</button>
- <button type="button" class="arrow" onclick={() => scrollContainer("sp-artists", 1)} aria-label="Próximo">
+ <button type="button" class="arrow" onclick={() => scrollContainer("sp-artists", 1)} aria-label={$t("study.music.spotify_next_aria") as string}>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
diff --git a/src/routes/study/music/transcode/+page.svelte b/src/routes/study/music/transcode/+page.svelte
new file mode 100644
index 00000000..91f979bb
--- /dev/null
+++ b/src/routes/study/music/transcode/+page.svelte
@@ -0,0 +1,411 @@
+<script lang="ts">
+ import { onMount, onDestroy } from "svelte";
+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";
+ import { open } from "@tauri-apps/plugin-dialog";
+ import { pluginInvoke } from "$lib/plugin-invoke";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { t } from "$lib/i18n";
+
+ type TranscodeFormat = "m4a" | "opus" | "mp3";
+
+ let inputDir = $state<string>("");
+ let outputDir = $state<string>("");
+ let format = $state<TranscodeFormat>("m4a");
+ let quality = $state<string>("192k");
+ let starting = $state(false);
+ let jobId = $state<number | null>(null);
+ let total = $state(0);
+ let current = $state(0);
+ let currentFile = $state<string | null>(null);
+ let etaSecs = $state<number | null>(null);
+ let finished = $state(false);
+ let cancelled = $state(false);
+ const unlisteners: UnlistenFn[] = [];
+
+ function pct() {
+ if (total === 0) return 0;
+ return Math.round((current / total) * 100);
+ }
+
+ function fmtEta(secs: number | null) {
+ if (secs === null || secs <= 0 || !Number.isFinite(secs)) return "—";
+ if (secs < 60) return `${Math.round(secs)}s`;
+ const m = Math.floor(secs / 60);
+ const s = Math.round(secs % 60);
+ return `${m}m ${s}s`;
+ }
+
+ async function pickInput() {
+ const sel = (await open({
+ directory: true,
+ title: $t("study.music.transcode_pick_input") as string,
+ })) as string | null;
+ if (sel) inputDir = sel;
+ }
+
+ async function pickOutput() {
+ const sel = (await open({
+ directory: true,
+ title: $t("study.music.transcode_pick_output") as string,
+ })) as string | null;
+ if (sel) outputDir = sel;
+ }
+
+ async function startJob() {
+ if (!inputDir.trim()) {
+ showToast("error", $t("study.music.transcode_missing_input") as string);
+ return;
+ }
+ starting = true;
+ finished = false;
+ cancelled = false;
+ current = 0;
+ total = 0;
+ currentFile = null;
+ etaSecs = null;
+ try {
+ const res = await pluginInvoke<{ job_id: number; total: number }>(
+ "study",
+ "study:music:transcode:start",
+ {
+ inputDir,
+ outputFormat: format,
+ quality: quality.trim() || "192k",
+ outputDir: outputDir.trim() || undefined,
+ },
+ );
+ jobId = res.job_id;
+ total = res.total;
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ showToast("error", msg);
+ } finally {
+ starting = false;
+ }
+ }
+
+ async function cancelJob() {
+ if (jobId === null) return;
+ try {
+ await pluginInvoke("study", "study:music:transcode:cancel", { jobId });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ showToast("error", msg);
+ }
+ }
+
+ onMount(() => {
+ void (async () => {
+ const onStart = await listen<{ job_id: number; total: number }>(
+ "study:music:transcode:start",
+ (e) => {
+ if (jobId !== null && e.payload?.job_id !== jobId) return;
+ if (jobId === null) jobId = e.payload.job_id;
+ total = e.payload.total;
+ },
+ );
+ const onProgress = await listen<{
+ job_id: number;
+ current: number;
+ total: number;
+ current_file: string;
+ eta_secs: number | null;
+ ok: boolean;
+ error: string | null;
+ }>("study:music:transcode:progress", (e) => {
+ if (jobId !== null && e.payload?.job_id !== jobId) return;
+ current = e.payload.current;
+ total = e.payload.total;
+ currentFile = e.payload.current_file;
+ etaSecs = e.payload.eta_secs;
+ });
+ const onComplete = await listen<{
+ job_id: number;
+ cancelled: boolean;
+ current: number;
+ total: number;
+ }>("study:music:transcode:complete", (e) => {
+ if (jobId !== null && e.payload?.job_id !== jobId) return;
+ finished = true;
+ cancelled = e.payload.cancelled;
+ const msg = cancelled
+ ? ($t("study.music.transcode_cancelled") as string)
+ : ($t("study.music.transcode_done", {
+ current: e.payload.current,
+ total: e.payload.total,
+ }) as string);
+ showToast(cancelled ? "info" : "success", msg);
+ });
+ unlisteners.push(onStart, onProgress, onComplete);
+ })();
+ });
+
+ onDestroy(() => {
+ for (const u of unlisteners) u();
+ });
+</script>
+
+<section class="transcode-page">
+ <header class="hero">
+ <span class="eyebrow">{$t("study.music.transcode_eyebrow")}</span>
+ <h1>{$t("study.music.transcode_title")}</h1>
+ <p class="lead">{$t("study.music.transcode_lead")}</p>
+ </header>
+
+ <div class="card">
+ <div class="row">
+ <label class="field">
+ <span>{$t("study.music.transcode_input_label")}</span>
+ <div class="path-input">
+ <input
+ type="text"
+ bind:value={inputDir}
+ placeholder={$t("study.music.transcode_input_placeholder") as string}
+ disabled={starting || (jobId !== null && !finished)}
+ />
+ <button
+ type="button"
+ class="ghost"
+ onclick={pickInput}
+ disabled={starting || (jobId !== null && !finished)}
+ >
+ {$t("study.music.transcode_browse")}
+ </button>
+ </div>
+ </label>
+ </div>
+
+ <div class="row">
+ <label class="field">
+ <span>{$t("study.music.transcode_output_label")}</span>
+ <div class="path-input">
+ <input
+ type="text"
+ bind:value={outputDir}
+ placeholder={$t("study.music.transcode_output_placeholder") as string}
+ disabled={starting || (jobId !== null && !finished)}
+ />
+ <button
+ type="button"
+ class="ghost"
+ onclick={pickOutput}
+ disabled={starting || (jobId !== null && !finished)}
+ >
+ {$t("study.music.transcode_browse")}
+ </button>
+ </div>
+ </label>
+ </div>
+
+ <div class="row two">
+ <label class="field">
+ <span>{$t("study.music.transcode_format_label")}</span>
+ <select
+ bind:value={format}
+ disabled={starting || (jobId !== null && !finished)}
+ >
+ <option value="m4a">m4a (AAC)</option>
+ <option value="opus">opus</option>
+ <option value="mp3">mp3</option>
+ </select>
+ </label>
+ <label class="field">
+ <span>{$t("study.music.transcode_quality_label")}</span>
+ <input
+ type="text"
+ bind:value={quality}
+ placeholder="192k"
+ disabled={starting || (jobId !== null && !finished)}
+ />
+ </label>
+ </div>
+
+ <div class="actions">
+ {#if jobId === null || finished}
+ <button
+ type="button"
+ class="primary"
+ onclick={startJob}
+ disabled={starting || !inputDir.trim()}
+ >
+ {starting
+ ? $t("study.music.transcode_starting")
+ : $t("study.music.transcode_start")}
+ </button>
+ {:else}
+ <button type="button" class="danger" onclick={cancelJob}>
+ {$t("study.music.transcode_cancel")}
+ </button>
+ {/if}
+ </div>
+ </div>
+
+ {#if jobId !== null}
+ <div class="progress-card" role="status" aria-live="polite">
+ <div class="progress-header">
+ <span class="state">
+ {#if finished && cancelled}
+ {$t("study.music.transcode_state_cancelled")}
+ {:else if finished}
+ {$t("study.music.transcode_state_done")}
+ {:else}
+ {$t("study.music.transcode_state_running")}
+ {/if}
+ </span>
+ <span class="count">{current} / {total}</span>
+ </div>
+ <div class="progress-track">
+ <div class="progress-fill" style:width="{pct()}%"></div>
+ </div>
+ <div class="progress-meta">
+ {#if currentFile && !finished}
+ <span class="current-file" title={currentFile}>{currentFile}</span>
+ {/if}
+ {#if !finished}
+ <span class="eta">{$t("study.music.transcode_eta")}: {fmtEta(etaSecs)}</span>
+ {/if}
+ </div>
+ </div>
+ {/if}
+</section>
+
+<style>
+ .transcode-page {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ padding: 24px 4px;
+ max-width: 720px;
+ }
+ .hero { display: flex; flex-direction: column; gap: 6px; }
+ .eyebrow {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--tertiary);
+ }
+ .hero h1 {
+ margin: 0;
+ font-size: clamp(22px, 3vw, 32px);
+ font-weight: 800;
+ color: var(--secondary);
+ letter-spacing: -0.01em;
+ }
+ .hero .lead {
+ margin: 0;
+ color: var(--tertiary);
+ font-size: 13px;
+ max-width: 56ch;
+ }
+ .card {
+ background: color-mix(in oklab, var(--surface, var(--button-elevated)) 80%, transparent);
+ border: 1px solid var(--content-border);
+ border-radius: 12px;
+ padding: 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ }
+ .row.two { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+ .field { display: flex; flex-direction: column; gap: 6px; }
+ .field > span {
+ font-size: 12px;
+ color: var(--tertiary);
+ font-weight: 500;
+ }
+ .field input[type="text"],
+ .field select {
+ padding: 8px 10px;
+ background: var(--surface, var(--button-elevated));
+ border: 1px solid var(--content-border);
+ border-radius: 6px;
+ color: var(--secondary);
+ font-family: inherit;
+ font-size: 13px;
+ }
+ .field input:disabled,
+ .field select:disabled { opacity: 0.5; cursor: not-allowed; }
+ .path-input { display: grid; grid-template-columns: 1fr auto; gap: 6px; }
+ .ghost {
+ padding: 8px 14px;
+ background: transparent;
+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);
+ border-radius: 6px;
+ color: var(--secondary);
+ font-family: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ }
+ .ghost:disabled { opacity: 0.5; cursor: not-allowed; }
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
+ .primary {
+ padding: 9px 18px;
+ background: var(--accent);
+ color: var(--on-accent, white);
+ border: 0;
+ border-radius: 8px;
+ font-family: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .primary:disabled { opacity: 0.4; cursor: not-allowed; }
+ .danger {
+ padding: 9px 18px;
+ background: var(--error, #dc2626);
+ color: white;
+ border: 0;
+ border-radius: 8px;
+ font-family: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .progress-card {
+ background: color-mix(in oklab, var(--accent) 5%, transparent);
+ border: 1px solid color-mix(in oklab, var(--accent) 35%, transparent);
+ border-radius: 12px;
+ padding: 16px 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .progress-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ font-size: 13px;
+ }
+ .state { color: var(--secondary); font-weight: 600; }
+ .count { color: var(--tertiary); font-variant-numeric: tabular-nums; }
+ .progress-track {
+ height: 6px;
+ border-radius: 6px;
+ background: color-mix(in oklab, var(--content-border) 60%, transparent);
+ overflow: hidden;
+ }
+ .progress-fill {
+ height: 100%;
+ background: var(--accent);
+ transition: width 200ms ease;
+ }
+ .progress-meta {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ font-size: 12px;
+ color: var(--tertiary);
+ }
+ .current-file {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 1;
+ min-width: 0;
+ }
+ .eta { font-variant-numeric: tabular-nums; flex-shrink: 0; }
+ @media (prefers-reduced-motion: reduce) {
+ .progress-fill { transition: none; }
+ }
+</style>
diff --git a/src/routes/study/music/watch/[trackId]/+page.svelte b/src/routes/study/music/watch/[trackId]/+page.svelte
new file mode 100644
index 00000000..a279a885
--- /dev/null
+++ b/src/routes/study/music/watch/[trackId]/+page.svelte
@@ -0,0 +1,189 @@
+<script lang="ts">
+ import { onMount, onDestroy } from "svelte";
+ import { goto } from "$app/navigation";
+ import { page } from "$app/stores";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+ import { t } from "$lib/i18n";
+ import PlayerShell from "$lib/study-components/player/PlayerShell.svelte";
+ import { studySettingsGet } from "$lib/study-bridge";
+
+ const trackId = $derived.by(() => {
+ const raw = $page.params.trackId ?? "";
+ const v = Number.parseInt(raw, 10);
+ return Number.isFinite(v) ? v : null;
+ });
+
+ const track = $derived.by(() => {
+ if (trackId == null) return null;
+ if (musicPlayer.currentTrack?.id === trackId) return musicPlayer.currentTrack;
+ return musicPlayer.queue.find((q) => q.id === trackId) ?? null;
+ });
+
+ const videoUrl = $derived(musicPlayer.youtubeVideoUrl);
+ const chapters = $derived(musicPlayer.youtubeChapters);
+ const sponsorBlockSegments = $derived(musicPlayer.youtubeSponsorBlockSegments);
+
+ let snapshot = $state<{ currentTime: number; wasPlaying: boolean } | null>(null);
+ let videoEl: HTMLVideoElement | null = null;
+ let lastVideoTime = $state(0);
+ let lastVideoPaused = $state(true);
+ let sponsorBlockAutoSkip = $state(false);
+
+ onMount(() => {
+ const snap = musicPlayer.suspendAudioForWatch();
+ snapshot = snap;
+ lastVideoTime = snap.currentTime;
+ lastVideoPaused = !snap.wasPlaying;
+ void studySettingsGet()
+ .then((s) => {
+ const music = (s as unknown as { music?: { sponsorblock_auto_skip?: boolean } }).music;
+ sponsorBlockAutoSkip = Boolean(music?.sponsorblock_auto_skip ?? false);
+ })
+ .catch(() => {});
+ });
+
+ onDestroy(() => {
+ if (!snapshot) return;
+ const resumeAt = videoEl?.currentTime ?? lastVideoTime;
+ const shouldPlay = videoEl ? !videoEl.paused : snapshot.wasPlaying;
+ musicPlayer.resumeAudioFromWatch(resumeAt, shouldPlay);
+ });
+
+ function handleVideoEl(el: HTMLVideoElement | null) {
+ videoEl = el;
+ }
+
+ function handleLoadedMetadata() {
+ if (!videoEl) return;
+ if (snapshot?.wasPlaying) {
+ videoEl.play().catch(() => {});
+ }
+ }
+
+ function close() {
+ goto("/study/music");
+ }
+
+ function onTimeUpdate(cur: number, _dur: number) {
+ lastVideoTime = cur;
+ musicPlayer.currentTime = cur;
+ }
+ function onPlay() {
+ lastVideoPaused = false;
+ musicPlayer.paused = false;
+ }
+ function onPause() {
+ lastVideoPaused = true;
+ musicPlayer.paused = true;
+ }
+ function onSeek(_fromMs: number, toMs: number) {
+ const cur = toMs / 1000;
+ lastVideoTime = cur;
+ musicPlayer.currentTime = cur;
+ }
+ function onEnded() {
+ musicPlayer.next();
+ }
+</script>
+
+<section class="watch-overlay">
+ {#if !track}
+ <div class="watch-error">
+ <h2>{$t("study.music.watch_video_unavailable")}</h2>
+ <button type="button" class="back-btn" onclick={close}>
+ {$t("study.music.watch_back")}
+ </button>
+ </div>
+ {:else if !videoUrl}
+ <div class="watch-error">
+ <h2>{$t("study.music.watch_video_unavailable")}</h2>
+ <p class="muted">{track.title ?? track.path}</p>
+ <button type="button" class="back-btn" onclick={close}>
+ {$t("study.music.watch_back")}
+ </button>
+ </div>
+ {:else}
+ <div class="player-frame">
+ <PlayerShell
+ videoSrc={videoUrl}
+ title={track.title ?? track.path}
+ courseTitle={track.artist ?? ""}
+ backHref="/study/music"
+ durationMs={track.duration_ms ?? null}
+ initialSeconds={snapshot?.currentTime ?? 0}
+ initialPlaybackSpeed={1.0}
+ subtitles={[]}
+ audioTracks={[]}
+ skipGaps={null}
+ thumbnails={[]}
+ sponsorBlockSegments={sponsorBlockSegments}
+ {sponsorBlockAutoSkip}
+ {chapters}
+ settings={null}
+ selectedSubtitleLang={null}
+ selectedAudioLang={null}
+ theaterMode={false}
+ {onTimeUpdate}
+ {onSeek}
+ {onPlay}
+ {onPause}
+ {onEnded}
+ onLoadedMetadata={handleLoadedMetadata}
+ onSubtitleChange={() => {}}
+ onAudioChange={() => {}}
+ onSpeedChange={() => {}}
+ onSkipGap={() => {}}
+ onTheaterToggle={() => {}}
+ onClose={close}
+ onVideoEl={handleVideoEl}
+ />
+ </div>
+ {/if}
+</section>
+
+<style>
+ .watch-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 95;
+ background: #000;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ }
+ .player-frame {
+ width: min(100%, 1600px);
+ aspect-ratio: 16 / 9;
+ max-height: calc(100vh - 48px);
+ }
+ .watch-error {
+ color: rgba(255, 255, 255, 0.92);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 14px;
+ text-align: center;
+ }
+ .watch-error h2 {
+ margin: 0;
+ font-size: 22px;
+ font-weight: 700;
+ }
+ .muted {
+ margin: 0;
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 14px;
+ }
+ .back-btn {
+ margin-top: 8px;
+ padding: 10px 24px;
+ background: var(--accent, white);
+ color: var(--on-accent, black);
+ border: 0;
+ border-radius: 999px;
+ font-family: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+</style>
diff --git a/src/routes/study/music/youtube/+page.svelte b/src/routes/study/music/youtube/+page.svelte
index d80c49f3..3031f954 100644
--- a/src/routes/study/music/youtube/+page.svelte
+++ b/src/routes/study/music/youtube/+page.svelte
@@ -1,721 +1,552 @@
<script lang="ts">
import { onMount } from "svelte";
- import { goto } from "$app/navigation";
- import { pluginInvoke } from "$lib/plugin-invoke";
import { showToast } from "$lib/stores/toast-store.svelte";
- import { musicUI } from "$lib/study-music/ui-store.svelte";
- import {
- musicPlayer,
- type MusicTrack,
- } from "$lib/study-music/player-store.svelte";
- import { fmtDuration } from "$lib/study-music/format";
import { t } from "$lib/i18n";
+ import { colorFromString } from "$lib/study-music/format";
+ import { playYoutubeVideoId, playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+ import {
+ studyMusicQuickPicks,
+ studyMusicDailyDiscover,
+ studyMusicContinueListening,
+ studyYoutubeTrending,
+ studyYoutubeSubsFeed,
+ studyMusicLoopCookieStatus,
+ type MusicQuickPickEntry,
+ type MusicDiscoverEntry,
+ type MusicContinueEntry,
+ type YoutubeSearchVideoItem,
+ type LoopCookieStatus,
+ } from "$lib/study-bridge";
+ import NavigationTitle from "$lib/study-music-components/NavigationTitle.svelte";
+ import SpeedDialGridItem from "$lib/study-music-components/SpeedDialGridItem.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeConnectHero from "$lib/study-music-youtube-components/YoutubeConnectHero.svelte";
- type Playlist = {
- id: string;
- url: string;
- title: string | null;
- uploader: string | null;
- thumbnail: string | null;
- track_count: number;
- kind: string;
- added_at: number;
- refreshed_at: number;
- };
-
- type RemoteTrack = {
- video_id: string;
- title: string;
- artist: string;
- album: string | null;
- duration_ms: number | null;
- thumbnail: string | null;
- };
-
- let playlists = $state<Playlist[]>([]);
- let loading = $state(true);
- let busyId = $state<string | null>(null);
+ let authStatus = $state<LoopCookieStatus | null>(null);
+ let bootingAuth = $state(true);
+ let authDerived = $derived(
+ authStatus === null
+ ? "loading"
+ : authStatus.available && authStatus.has_youtube
+ ? "ready"
+ : authStatus.available
+ ? "no_youtube"
+ : "missing",
+ );
- let searchQuery = $state("");
- let searchResults = $state<RemoteTrack[]>([]);
- let searchLoading = $state(false);
- let searchError = $state<string | null>(null);
- let searchTimer: ReturnType<typeof setTimeout> | null = null;
+ let quickPicks = $state<MusicQuickPickEntry[]>([]);
+ let discover = $state<MusicDiscoverEntry[]>([]);
+ let discoverSeedTitle = $state<string | null>(null);
+ let continueWatching = $state<MusicContinueEntry[]>([]);
+ let trending = $state<YoutubeSearchVideoItem[]>([]);
+ let subsFeed = $state<YoutubeSearchVideoItem[]>([]);
- let recs = $state<RemoteTrack[]>([]);
- let recsSeedTitle = $state<string | null>(null);
- let downloadingId = $state<string | null>(null);
+ let loadingPicks = $state(true);
+ let loadingDiscover = $state(true);
+ let loadingContinue = $state(true);
+ let loadingTrending = $state(true);
+ let loadingSubs = $state(true);
- async function load() {
- loading = true;
+ async function loadAuth() {
+ bootingAuth = true;
try {
- const res = await pluginInvoke<{ playlists: Playlist[] }>(
- "study",
- "study:music:youtube:playlists_list",
- );
- playlists = res.playlists ?? [];
+ authStatus = await studyMusicLoopCookieStatus();
+ } catch {
+ authStatus = { available: false, file_path: "", has_youtube: false };
} finally {
- loading = false;
+ bootingAuth = false;
}
}
- async function loadRecommendations() {
+ async function loadQuickPicks() {
+ loadingPicks = true;
try {
- const recent = await pluginInvoke<{
- tracks: Array<{ video_id: string; title: string | null; artist: string | null }>;
- }>("study", "study:music:youtube:tracks_recent", { limit: 1 });
- const seed = recent.tracks?.[0];
- if (!seed) return;
- recsSeedTitle = seed.title ?? seed.video_id;
- const res = await pluginInvoke<{ tracks: RemoteTrack[] }>(
- "study",
- "study:music:youtube:recommendations",
- { video_id: seed.video_id, limit: 12 },
- );
- recs = res.tracks ?? [];
- } catch (e) {
- console.warn("[recommendations] failed", e);
+ const res = await studyMusicQuickPicks();
+ quickPicks = (res.entries ?? []).filter((e) => e.source === "youtube");
+ } catch {
+ quickPicks = [];
+ } finally {
+ loadingPicks = false;
}
}
- function handleSearchInput(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- searchQuery = value;
- if (searchTimer) clearTimeout(searchTimer);
- if (!value.trim()) {
- searchResults = [];
- searchError = null;
- return;
+ async function loadDiscover() {
+ loadingDiscover = true;
+ try {
+ const res = await studyMusicDailyDiscover();
+ discover = res.entries ?? [];
+ discoverSeedTitle = res.seed_title ?? null;
+ } catch {
+ discover = [];
+ } finally {
+ loadingDiscover = false;
}
- searchTimer = setTimeout(() => void runSearch(value.trim()), 300);
}
- async function runSearch(q: string) {
- if (!q) return;
- searchLoading = true;
- searchError = null;
+ async function loadContinueWatching() {
+ loadingContinue = true;
try {
- const res = await pluginInvoke<{ tracks: RemoteTrack[] }>(
- "study",
- "study:music:youtube:search",
- { query: q },
- );
- searchResults = res.tracks ?? [];
- } catch (e) {
- searchError = e instanceof Error ? e.message : String(e);
- searchResults = [];
+ const res = await studyMusicContinueListening({ limit: 16 });
+ continueWatching = (res.entries ?? [])
+ .filter((e) => e.source === "youtube")
+ .slice(0, 8);
+ } catch {
+ continueWatching = [];
} finally {
- searchLoading = false;
+ loadingContinue = false;
}
}
- function clearSearch() {
- searchQuery = "";
- searchResults = [];
- searchError = null;
+ async function loadTrending() {
+ loadingTrending = true;
+ try {
+ const res = await studyYoutubeTrending({ category: "now" });
+ const flat: YoutubeSearchVideoItem[] = [];
+ for (const it of res.items ?? []) {
+ if (it.kind === "shelf") {
+ for (const s of it.items) if (s.kind === "video") flat.push(s);
+ } else if (it.kind === "video") {
+ flat.push(it);
+ }
+ }
+ trending = flat.slice(0, 16);
+ } catch {
+ trending = [];
+ } finally {
+ loadingTrending = false;
+ }
}
- async function remoteToMusicTrack(rt: RemoteTrack): Promise<MusicTrack> {
- const ensured = await pluginInvoke<{ id: number }>(
- "study",
- "study:music:youtube:ensure_external_track",
- {
- video_id: rt.video_id,
- title: rt.title,
- artist: rt.artist,
- album: rt.album,
- duration_ms: rt.duration_ms,
- thumbnail: rt.thumbnail,
- },
- );
- return {
- id: ensured.id,
- path: `external://youtube/${rt.video_id}`,
- title: rt.title,
- artist: rt.artist,
- album: rt.album,
- duration_ms: rt.duration_ms,
- cover_path: rt.thumbnail,
- source: "youtube",
- youtube_url: `https://www.youtube.com/watch?v=${rt.video_id}`,
- youtube_video_id: rt.video_id,
- youtube_thumbnail: rt.thumbnail ?? undefined,
- };
+ async function loadSubs() {
+ loadingSubs = true;
+ try {
+ const res = await studyYoutubeSubsFeed();
+ const items: YoutubeSearchVideoItem[] = [];
+ for (const e of res.entries ?? []) {
+ for (const it of e.items.slice(0, 4)) {
+ if (it.kind === "video") items.push(it);
+ }
+ }
+ subsFeed = items.slice(0, 12);
+ } catch {
+ subsFeed = [];
+ } finally {
+ loadingSubs = false;
+ }
}
- async function playRemote(rt: RemoteTrack, queue: RemoteTrack[]) {
+ async function playQuickPick(entry: MusicQuickPickEntry) {
+ if (!entry.external_id) return;
try {
- const tracks = await Promise.all(queue.map((q) => remoteToMusicTrack(q)));
- const target = tracks.find((t) => t.youtube_video_id === rt.video_id);
- if (target) await musicPlayer.play(target, tracks);
- void loadRecommendations();
+ await playYoutubeVideoId(
+ entry.external_id,
+ entry.title,
+ entry.artist,
+ entry.cover_url,
+ );
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
}
}
- async function downloadRemote(rt: RemoteTrack) {
- if (downloadingId) return;
- downloadingId = rt.video_id;
+ async function playDiscover(entry: MusicDiscoverEntry) {
try {
- await pluginInvoke("study", "study:music:ytdlp:download_shortcut", {
- url: `https://www.youtube.com/watch?v=${rt.video_id}`,
- });
- showToast("success", $t("study.music.yt_download_started") as string);
+ await playYoutubeVideoId(
+ entry.external_id,
+ entry.title,
+ entry.artist,
+ entry.cover_url,
+ );
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
- } finally {
- downloadingId = null;
}
}
- async function refresh(p: Playlist) {
- if (busyId) return;
- busyId = p.id;
+ async function playContinue(entry: MusicContinueEntry) {
+ if (!entry.external_id) return;
try {
- const res = await pluginInvoke<{ imported: number }>(
- "study",
- "study:music:youtube:playlist_refresh",
- { id: p.id },
+ await playYoutubeVideoId(
+ entry.external_id,
+ entry.title,
+ entry.artist,
+ entry.cover_url,
);
- showToast(
- "success",
- $t("study.music.yt_refreshed", { count: res.imported }) as string,
- );
- await load();
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
- } finally {
- busyId = null;
}
}
- async function remove(p: Playlist) {
- if (busyId) return;
- if (!window.confirm($t("study.music.yt_remove_confirm") as string)) return;
- busyId = p.id;
+ async function playVideo(item: YoutubeSearchVideoItem, queue: YoutubeSearchVideoItem[]) {
try {
- await pluginInvoke("study", "study:music:youtube:playlist_remove", { id: p.id });
- await load();
+ await playYoutubeVideoItem(item, queue);
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
- } finally {
- busyId = null;
}
}
- function open(p: Playlist) {
- goto(`/study/music/youtube/playlist/${encodeURIComponent(p.id)}`);
- }
-
- onMount(() => {
- void load();
- void loadRecommendations();
+ onMount(async () => {
+ await loadAuth();
+ void loadTrending();
+ if (authDerived === "ready") {
+ void loadContinueWatching();
+ void loadQuickPicks();
+ void loadDiscover();
+ void loadSubs();
+ }
});
</script>
-<section class="page">
- <header class="head">
- <div>
- <h1>{$t("study.music.yt_title")}</h1>
- <p class="sub">{$t("study.music.yt_subtitle")}</p>
- </div>
- <button type="button" class="cta" onclick={() => musicUI.openYoutube()}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <line x1="12" y1="5" x2="12" y2="19"/>
- <line x1="5" y1="12" x2="19" y2="12"/>
- </svg>
- {$t("study.music.yt_add_playlist")}
- </button>
+<section class="yt-hub">
+ <header class="page-head">
+ <h1>{$t("study.music.youtube.hub_title")}</h1>
+ <p class="tagline">{$t("study.music.youtube.hub_tagline")}</p>
</header>
- <div class="search-block">
- <div class="search-input-wrap">
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class="search-ico">
- <circle cx="11" cy="11" r="8"/>
- <line x1="21" y1="21" x2="16.65" y2="16.65"/>
- </svg>
- <input
- type="search"
- class="search-input"
- placeholder={$t("study.music.yt_search_placeholder") as string}
- value={searchQuery}
- oninput={handleSearchInput}
- spellcheck="false"
- autocomplete="off"
- />
- {#if searchQuery}
- <button type="button" class="search-clear" onclick={clearSearch} aria-label="clear">×</button>
- {/if}
+ {#if authDerived === "loading"}
+ <div class="boot-skel">
+ <YoutubeSkeleton kind="card" count={3} />
</div>
- {#if searchLoading}
- <p class="muted small">{$t("study.common.loading")}</p>
- {/if}
- {#if searchError}
- <p class="error small">{searchError}</p>
+ {:else if authDerived !== "ready"}
+ <div class="speed-dial-row anon">
+ <SpeedDialGridItem label={$t("study.music.speed_dial_search") as string} href="/study/music/youtube/search">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.youtube.explore_title") as string} href="/study/music/youtube/explore">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ </div>
+
+ <YoutubeConnectHero status={authDerived as "missing" | "no_youtube"} filePath={authStatus?.file_path ?? ""} />
+ {:else}
+ <div class="speed-dial-row">
+ <SpeedDialGridItem label={$t("study.music.speed_dial_search") as string} href="/study/music/youtube/search">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.youtube.explore_title") as string} href="/study/music/youtube/explore">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_history") as string} href="/study/music/youtube/history">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.74 9.74 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.youtube.shelf_subscriptions") as string} href="/study/music/youtube/explore">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 19h16"/><path d="M6 15h12"/><rect x="3" y="3" width="18" height="9" rx="2"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.my_playlists_title") as string} href="/study/music/youtube/playlists">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15V6"/><path d="M3 18V9"/><path d="M3 18a3 3 0 1 0 6 0V9a3 3 0 1 0-6 0"/><path d="M15 6a3 3 0 1 0 6 0 3 3 0 1 0-6 0"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ <SpeedDialGridItem label={$t("study.music.speed_dial_trending") as string} href="/study/music/youtube/explore">
+ {#snippet icon()}
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m23 6-9.5 9.5-5-5L1 18"/><path d="M17 6h6v6"/></svg>
+ {/snippet}
+ </SpeedDialGridItem>
+ </div>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_continue_watching") as string} seeAllHref="/study/music/youtube/history" />
+ {#if loadingContinue}
+ <YoutubeSkeleton kind="row" count={4} />
+ {:else if continueWatching.length === 0}
+ <EmptyPlaceholder title={$t("study.music.youtube.shelf_continue_watching_empty") as string} compact />
+ {:else}
+ <div class="h-scroll">
+ {#each continueWatching as entry (entry.external_id ?? entry.title)}
+ <button
+ type="button"
+ class="continue-card"
+ onclick={() => playContinue(entry)}
+ >
+ <div class="cover">
+ {#if entry.cover_url}
+ <img src={entry.cover_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(entry.title)}></div>
+ {/if}
+ <div class="progress-track">
+ <div class="progress-fill" style:width={`${Math.round((entry.progress ?? 0) * 100)}%`}></div>
+ </div>
+ </div>
+ <h3 class="card-title">{entry.title}</h3>
+ {#if entry.artist}<p class="card-sub">{entry.artist}</p>{/if}
+ </button>
+ {/each}
+ </div>
{/if}
- {#if searchResults.length > 0}
- <ul class="track-list">
- {#each searchResults as rt (rt.video_id)}
- <li class="track-row">
- <button class="track-cover" onclick={() => playRemote(rt, searchResults)} aria-label="play">
- {#if rt.thumbnail}
- <img src={rt.thumbnail} alt="" loading="lazy" />
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_quick_picks") as string} />
+ {#if loadingPicks}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if quickPicks.length === 0}
+ <EmptyPlaceholder title={$t("study.music.youtube.shelf_quick_picks_empty") as string} compact />
+ {:else}
+ <div class="h-scroll">
+ {#each quickPicks as entry, idx (entry.external_id ?? entry.title + idx)}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playQuickPick(entry)}
+ >
+ <div class="cover">
+ {#if entry.cover_url}
+ <img src={entry.cover_url} alt="" loading="lazy" />
{:else}
- <div class="track-cover-fallback"></div>
+ <div class="cover-fallback" style:background={colorFromString(entry.title)}></div>
{/if}
- <span class="track-play-overlay">
- <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
- </span>
- </button>
- <div class="track-meta">
- <span class="track-title">{rt.title}</span>
- <span class="track-sub">{rt.artist}{rt.album ? ` • ${rt.album}` : ""}</span>
</div>
- <span class="track-dur">{rt.duration_ms ? fmtDuration(rt.duration_ms) : ""}</span>
- <button
- type="button"
- class="track-action"
- onclick={() => downloadRemote(rt)}
- disabled={downloadingId === rt.video_id}
- title={$t("study.music.yt_download") as string}
- aria-label={$t("study.music.yt_download") as string}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
- <polyline points="7 10 12 15 17 10"/>
- <line x1="12" y1="15" x2="12" y2="3"/>
- </svg>
- </button>
- </li>
+ <h3 class="card-title">{entry.title}</h3>
+ {#if entry.artist}<p class="card-sub">{entry.artist}</p>{/if}
+ </button>
{/each}
- </ul>
+ </div>
{/if}
- </div>
+ </section>
- {#if recs.length > 0 && !searchQuery}
- <div class="recs-block">
- <h2 class="shelf-title">
- {$t("study.music.yt_recs_for", { name: recsSeedTitle ?? "" })}
- </h2>
- <ul class="track-list">
- {#each recs as rt (rt.video_id)}
- <li class="track-row">
- <button class="track-cover" onclick={() => playRemote(rt, recs)} aria-label="play">
- {#if rt.thumbnail}
- <img src={rt.thumbnail} alt="" loading="lazy" />
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_daily_discover") as string} />
+ {#if discoverSeedTitle}
+ <p class="seed-hint">{discoverSeedTitle}</p>
+ {/if}
+ {#if loadingDiscover}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if discover.length === 0}
+ <EmptyPlaceholder title={$t("study.music.youtube.shelf_daily_discover_empty") as string} compact />
+ {:else}
+ <div class="h-scroll">
+ {#each discover as entry, idx (entry.external_id + idx)}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playDiscover(entry)}
+ >
+ <div class="cover">
+ {#if entry.cover_url}
+ <img src={entry.cover_url} alt="" loading="lazy" />
{:else}
- <div class="track-cover-fallback"></div>
+ <div class="cover-fallback" style:background={colorFromString(entry.title)}></div>
{/if}
- <span class="track-play-overlay">
- <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
- </span>
- </button>
- <div class="track-meta">
- <span class="track-title">{rt.title}</span>
- <span class="track-sub">{rt.artist}{rt.album ? ` • ${rt.album}` : ""}</span>
</div>
- <span class="track-dur">{rt.duration_ms ? fmtDuration(rt.duration_ms) : ""}</span>
- <button
- type="button"
- class="track-action"
- onclick={() => downloadRemote(rt)}
- disabled={downloadingId === rt.video_id}
- title={$t("study.music.yt_download") as string}
- aria-label={$t("study.music.yt_download") as string}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
- <polyline points="7 10 12 15 17 10"/>
- <line x1="12" y1="15" x2="12" y2="3"/>
- </svg>
- </button>
- </li>
+ <h3 class="card-title">{entry.title}</h3>
+ {#if entry.artist}<p class="card-sub">{entry.artist}</p>{/if}
+ </button>
{/each}
- </ul>
- </div>
- {/if}
+ </div>
+ {/if}
+ </section>
- {#if loading}
- <p class="muted">{$t("study.common.loading")}</p>
- {:else if playlists.length === 0}
- <div class="empty">
- <h2>{$t("study.music.yt_empty_title")}</h2>
- <p>{$t("study.music.yt_empty_body")}</p>
- <button type="button" class="cta-big" onclick={() => musicUI.openYoutube()}>
- {$t("study.music.yt_setup")}
- </button>
- </div>
- {:else}
- <ul class="grid">
- {#each playlists as p (p.id)}
- <li>
- <article class="card">
- <button type="button" class="card-cover" onclick={() => open(p)}>
- {#if p.thumbnail}
- <img src={p.thumbnail} alt="" loading="lazy" />
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_trending") as string} seeAllHref="/study/music/youtube/explore" />
+ {#if loadingTrending}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if trending.length === 0}
+ <EmptyPlaceholder title={$t("study.music.youtube.shelf_trending_error") as string} compact />
+ {:else}
+ <div class="h-scroll">
+ {#each trending as item (item.video_id)}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playVideo(item, trending)}
+ >
+ <div class="cover">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
{:else}
- <div class="fallback">
- <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/>
- <polygon points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02" fill="currentColor"/>
- </svg>
- </div>
+ <div class="cover-fallback" style:background={colorFromString(item.title)}></div>
{/if}
- <span class="play-overlay" aria-hidden="true">
- <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
- </span>
- </button>
- <div class="card-body">
- <h3>{p.title ?? p.id}</h3>
- {#if p.uploader}<span class="card-sub">{p.uploader}</span>{/if}
- <span class="card-meta">{p.track_count} faixas</span>
</div>
- <div class="card-actions">
- <button
- type="button"
- class="ico"
- onclick={() => refresh(p)}
- disabled={busyId === p.id}
- title={$t("study.music.yt_refresh") as string}
- aria-label={$t("study.music.yt_refresh") as string}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
- <polyline points="23 4 23 10 17 10"/>
- <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
- </svg>
- </button>
- <button
- type="button"
- class="ico danger"
- onclick={() => remove(p)}
- disabled={busyId === p.id}
- title={$t("study.music.yt_remove") as string}
- aria-label={$t("study.music.yt_remove") as string}
- >×</button>
+ <h3 class="card-title">{item.title}</h3>
+ {#if item.channel_title}<p class="card-sub">{item.channel_title}</p>{/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_subscriptions") as string} />
+ {#if loadingSubs}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if subsFeed.length === 0}
+ <EmptyPlaceholder title={$t("study.music.youtube.shelf_subscriptions_empty") as string} compact />
+ {:else}
+ <div class="h-scroll">
+ {#each subsFeed as item (item.video_id)}
+ <button
+ type="button"
+ class="discover-card"
+ onclick={() => playVideo(item, subsFeed)}
+ >
+ <div class="cover">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(item.title)}></div>
+ {/if}
</div>
- </article>
- </li>
- {/each}
- </ul>
+ <h3 class="card-title">{item.title}</h3>
+ {#if item.channel_title}<p class="card-sub">{item.channel_title}</p>{/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </section>
{/if}
</section>
<style>
- .page {
+ .yt-hub {
display: flex;
flex-direction: column;
- gap: 24px;
- padding-bottom: 60px;
- }
- .head {
- display: flex;
- align-items: flex-end;
- justify-content: space-between;
- gap: 16px;
- }
- .head h1 {
- margin: 0 0 4px;
- font-size: 28px;
- font-weight: 800;
- letter-spacing: -0.02em;
+ gap: 28px;
+ color: rgba(255, 255, 255, 0.95);
}
- .sub {
+ .page-head h1 {
margin: 0;
- color: rgba(255, 255, 255, 0.5);
- font-size: 13px;
- }
- .cta {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 8px 16px;
- border: 0;
- border-radius: 999px;
- background: var(--accent);
- color: var(--on-accent, white);
- font-family: inherit;
- font-size: 13px;
- font-weight: 700;
- cursor: pointer;
- flex-shrink: 0;
+ font-size: clamp(28px, 3.5vw, 40px);
+ font-weight: 900;
+ letter-spacing: -0.02em;
+ color: white;
}
- .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }
- .empty {
- padding: 80px 24px;
- text-align: center;
- color: rgba(255, 255, 255, 0.6);
- border: 1px dashed rgba(255, 255, 255, 0.08);
- border-radius: 12px;
+ .tagline {
+ margin: 4px 0 0;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 14px;
}
- .empty h2 {
- margin: 0 0 8px;
- font-size: 18px;
- color: rgba(255, 255, 255, 0.95);
+ .speed-dial-row {
+ display: grid;
+ grid-template-columns: repeat(6, 1fr);
+ gap: 10px;
}
- .empty p {
- margin: 0 0 16px;
- font-size: 14px;
- line-height: 1.5;
+ .speed-dial-row.anon {
+ grid-template-columns: repeat(2, 1fr);
+ max-width: 480px;
}
- .cta-big {
- padding: 10px 22px;
- border: 0;
- border-radius: 999px;
- background: var(--accent);
- color: var(--on-accent, white);
- font-family: inherit;
- font-size: 13px;
- font-weight: 700;
- cursor: pointer;
+ @media (max-width: 760px) {
+ .speed-dial-row {
+ grid-template-columns: repeat(3, 1fr);
+ }
+ .speed-dial-row.anon {
+ grid-template-columns: repeat(2, 1fr);
+ }
}
- .grid {
- list-style: none;
- margin: 0;
- padding: 0;
+ .boot-skel {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
- gap: 18px;
+ gap: 14px;
}
- .card {
+ .block {
display: flex;
flex-direction: column;
- gap: 8px;
- padding: 10px;
- background: rgba(255, 255, 255, 0.03);
- border: 1px solid rgba(255, 255, 255, 0.05);
- border-radius: 10px;
- position: relative;
- transition: background 120ms ease;
- }
- .card:hover {
- background: rgba(255, 255, 255, 0.06);
- }
- .card-cover {
- position: relative;
- width: 100%;
- aspect-ratio: 1 / 1;
- border: 0;
- padding: 0;
- background: rgba(0, 0, 0, 0.3);
- border-radius: 6px;
- overflow: hidden;
- cursor: pointer;
+ gap: 14px;
}
- .card-cover img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- }
- .fallback {
- display: grid;
- place-items: center;
- width: 100%;
- height: 100%;
- color: rgba(255, 255, 255, 0.3);
- }
- .play-overlay {
- position: absolute;
- inset: 0;
- display: grid;
- place-items: center;
- background: linear-gradient(to bottom, transparent 50%, rgba(0, 0, 0, 0.4));
- color: white;
- opacity: 0;
- transition: opacity 120ms ease;
- }
- .card-cover:hover .play-overlay { opacity: 1; }
- .card-body { display: flex; flex-direction: column; gap: 2px; padding: 0 4px; }
- .card-body h3 {
- margin: 0;
- font-size: 13px;
- font-weight: 700;
- color: rgba(255, 255, 255, 0.95);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .card-sub {
- font-size: 11px;
+ .seed-hint {
+ margin: -4px 0 0;
color: rgba(255, 255, 255, 0.55);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .card-meta {
- font-size: 10px;
- color: rgba(255, 255, 255, 0.4);
- margin-top: 2px;
+ font-size: 13px;
}
- .card-actions {
- position: absolute;
- top: 14px;
- right: 14px;
+ .h-scroll {
display: flex;
- gap: 4px;
- opacity: 0;
- transition: opacity 120ms ease;
- }
- .card:hover .card-actions { opacity: 1; }
- .ico {
- width: 28px;
- height: 28px;
- padding: 0;
- background: rgba(0, 0, 0, 0.6);
- border: 0;
- border-radius: 50%;
- color: white;
- font-size: 14px;
- cursor: pointer;
- display: grid;
- place-items: center;
+ gap: 18px;
+ overflow-x: auto;
+ overflow-y: visible;
+ padding: 4px 2px 16px;
+ scrollbar-width: none;
+ scroll-behavior: smooth;
}
- .ico:hover { background: rgba(0, 0, 0, 0.85); }
- .ico.danger:hover { background: rgb(220, 38, 38); }
+ .h-scroll::-webkit-scrollbar { display: none; }
- .search-block { display: flex; flex-direction: column; gap: 12px; }
- .search-input-wrap {
- position: relative;
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 999px;
- padding: 0 14px 0 40px;
- transition: border-color 120ms ease, background 120ms ease;
- }
- .search-input-wrap:focus-within {
- border-color: var(--accent);
- background: rgba(255, 255, 255, 0.07);
- }
- .search-ico {
- position: absolute;
- left: 14px;
- color: rgba(255, 255, 255, 0.5);
- pointer-events: none;
- }
- .search-input {
- flex: 1;
+ .continue-card,
+ .discover-card {
+ flex: 0 0 auto;
background: transparent;
border: 0;
- outline: 0;
- padding: 12px 0;
- color: white;
- font-family: inherit;
- font-size: 14px;
- }
- .search-clear {
- background: transparent;
- border: 0;
- color: rgba(255, 255, 255, 0.6);
- cursor: pointer;
- font-size: 18px;
- line-height: 1;
- padding: 4px 8px;
- }
- .small { font-size: 12px; }
- .error { color: rgb(248, 113, 113); }
- .recs-block { display: flex; flex-direction: column; gap: 12px; }
- .shelf-title {
- margin: 0;
- font-size: 18px;
- font-weight: 700;
- color: rgba(255, 255, 255, 0.92);
- }
- .track-list {
- list-style: none;
- margin: 0;
padding: 0;
- display: flex;
- flex-direction: column;
- gap: 4px;
- }
- .track-row {
- display: grid;
- grid-template-columns: 48px 1fr auto auto;
- gap: 12px;
- align-items: center;
- padding: 6px 8px;
- border-radius: 8px;
- transition: background 120ms ease;
+ text-align: left;
+ color: inherit;
+ cursor: pointer;
+ font: inherit;
}
- .track-row:hover { background: rgba(255, 255, 255, 0.04); }
- .track-cover {
+ .continue-card { width: 160px; }
+ .discover-card { width: 176px; }
+
+ .cover {
position: relative;
- width: 48px;
- height: 48px;
- border: 0;
- padding: 0;
- background: rgba(0, 0, 0, 0.3);
- border-radius: 6px;
+ aspect-ratio: 1 / 1;
+ border-radius: 12px;
overflow: hidden;
- cursor: pointer;
+ background: rgba(40, 40, 40, 0.6);
+ margin-bottom: 10px;
+ transition: transform 200ms ease;
+ }
+ .continue-card:hover .cover,
+ .discover-card:hover .cover {
+ transform: scale(1.02);
}
- .track-cover img {
+ .cover img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
- .track-cover-fallback {
+ .cover-fallback {
width: 100%;
height: 100%;
- background: rgba(255, 255, 255, 0.04);
}
- .track-play-overlay {
+ .progress-track {
position: absolute;
- inset: 0;
- display: grid;
- place-items: center;
+ left: 6px;
+ right: 6px;
+ bottom: 6px;
+ height: 3px;
background: rgba(0, 0, 0, 0.5);
- color: white;
- opacity: 0;
- transition: opacity 120ms ease;
- }
- .track-cover:hover .track-play-overlay { opacity: 1; }
- .track-meta {
- display: flex;
- flex-direction: column;
- gap: 2px;
+ border-radius: 2px;
overflow: hidden;
}
- .track-title {
+ .progress-fill {
+ height: 100%;
+ background: var(--accent);
+ border-radius: inherit;
+ }
+ .card-title {
+ margin: 0;
font-size: 13px;
- font-weight: 600;
- color: rgba(255, 255, 255, 0.95);
+ font-weight: 700;
+ color: white;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ padding: 0 2px;
}
- .track-sub {
+ .card-sub {
+ margin: 2px 0 0;
font-size: 11px;
+ font-weight: 600;
color: rgba(255, 255, 255, 0.55);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ padding: 0 2px;
}
- .track-dur {
- font-size: 11px;
- color: rgba(255, 255, 255, 0.5);
- font-variant-numeric: tabular-nums;
- }
- .track-action {
- width: 28px;
- height: 28px;
- padding: 0;
- background: transparent;
- border: 0;
- color: rgba(255, 255, 255, 0.6);
- border-radius: 6px;
- display: grid;
- place-items: center;
- cursor: pointer;
- transition: background 120ms ease, color 120ms ease;
- }
- .track-action:hover {
- background: rgba(255, 255, 255, 0.08);
- color: white;
+ @media (prefers-reduced-motion: reduce) {
+ .cover, .continue-card:hover .cover, .discover-card:hover .cover {
+ transition: none;
+ transform: none;
+ }
}
- .track-action:disabled { opacity: 0.4; cursor: not-allowed; }
</style>
diff --git a/src/routes/study/music/youtube/album/[id]/+page.svelte b/src/routes/study/music/youtube/album/[id]/+page.svelte
new file mode 100644
index 00000000..903b0255
--- /dev/null
+++ b/src/routes/study/music/youtube/album/[id]/+page.svelte
@@ -0,0 +1,230 @@
+<script lang="ts">
+ import { page } from "$app/stores";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyYoutubePlaylist,
+ type YoutubePlaylist,
+ type YoutubePlaylistVideo,
+ type YoutubeSearchVideoItem,
+ } from "$lib/study-bridge";
+ import MediaHero from "$lib/study-music-components/MediaHero.svelte";
+ import TrackListRow from "$lib/study-music-components/TrackListRow.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import StickyHeader from "$lib/study-music-components/StickyHeader.svelte";
+ import { playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+
+ let albumId = $derived($page.params.id ?? "");
+ let album = $state<YoutubePlaylist | null>(null);
+ let loading = $state(false);
+ let error = $state<string | null>(null);
+ let pendingShuffle = $state(false);
+
+ async function load() {
+ loading = true;
+ error = null;
+ try {
+ album = await studyYoutubePlaylist({ playlistId: albumId });
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function totalDurationText(videos: YoutubePlaylistVideo[]): string | null {
+ const totalSeconds = videos.reduce((acc, v) => acc + (v.duration_seconds ?? 0), 0);
+ if (totalSeconds <= 0) return null;
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ if (hours > 0) return `${hours}h ${minutes}min`;
+ return `${minutes}min`;
+ }
+
+ function asSearchVideo(v: YoutubePlaylistVideo, fallbackThumb: string | null): YoutubeSearchVideoItem {
+ return {
+ kind: "video",
+ video_id: v.video_id,
+ title: v.title,
+ channel_id: v.channel_id,
+ channel_title: v.channel_title,
+ thumbnail_url: v.thumbnail_url ?? fallbackThumb,
+ duration_text: v.duration_text,
+ published_time_text: null,
+ view_count_text: null,
+ short_description: null,
+ is_live: false,
+ };
+ }
+
+ async function playFromIndex(idx: number, shuffle = false) {
+ if (!album || album.videos.length === 0) return;
+ const fallbackThumb = album.info.thumbnail_url;
+ let queue = album.videos.map((v) => asSearchVideo(v, fallbackThumb));
+ let target = queue[idx];
+ if (shuffle) {
+ const rest = queue.slice();
+ for (let i = rest.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [rest[i], rest[j]] = [rest[j], rest[i]];
+ }
+ queue = rest;
+ target = queue[0];
+ }
+ try {
+ await playYoutubeVideoItem(target, queue);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function playAll() {
+ await playFromIndex(0, false);
+ }
+
+ async function shuffleAll() {
+ if (pendingShuffle) return;
+ pendingShuffle = true;
+ try {
+ await playFromIndex(0, true);
+ } finally {
+ pendingShuffle = false;
+ }
+ }
+
+ $effect(() => {
+ if (albumId) void load();
+ });
+</script>
+
+<section class="page">
+ <StickyHeader>
+ <div class="sticky-row">
+ <button class="back" type="button" onclick={() => history.back()}>← {$t("study.music.back")}</button>
+ {#if album}
+ <span class="sticky-title">{album.info.title || albumId}</span>
+ {/if}
+ </div>
+ </StickyHeader>
+
+ {#if loading && !album}
+ <div class="hero-skel">
+ <YoutubeSkeleton kind="card" count={1} />
+ </div>
+ <div class="list-skel">
+ <YoutubeSkeleton kind="row" count={6} />
+ </div>
+ {:else if error && !album}
+ <YoutubeError error={error} onRetry={() => { error = null; void load(); }} />
+ {:else if album}
+ {@const subtitle = album.info.owner_title}
+ {@const total = totalDurationText(album.videos)}
+ {@const trackCount = album.info.video_count ?? album.videos.length}
+ <MediaHero
+ coverUrl={album.info.thumbnail_url}
+ eyebrow={$t("study.music.eyebrow_album")}
+ title={album.info.title || albumId}
+ subtitle={subtitle}
+ stats={[
+ { label: "", value: trackCount === 1 ? $t("study.music.track_count_one") : $t("study.music.tracks_count_n", { count: trackCount }) },
+ { label: "", value: total },
+ { label: "", value: album.info.view_count_text },
+ ]}
+ actions={[
+ {
+ id: "play",
+ label: $t("study.music.play_all"),
+ primary: true,
+ onClick: () => void playAll(),
+ },
+ {
+ id: "shuffle",
+ label: $t("study.music.shuffle_play"),
+ busy: pendingShuffle,
+ onClick: () => void shuffleAll(),
+ },
+ ]}
+ />
+
+ {#if album.videos.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.album_empty")}
+ body={null}
+ />
+ {:else}
+ <div class="tracklist" role="list">
+ {#each album.videos as v, idx (v.video_id)}
+ <TrackListRow
+ index={idx}
+ coverUrl={null}
+ title={v.title}
+ subtitle={v.channel_title}
+ durationText={v.duration_text}
+ isPlaying={musicPlayer.currentTrack?.youtube_video_id === v.video_id}
+ onPlay={() => void playFromIndex(idx, false)}
+ />
+ {/each}
+ </div>
+ {/if}
+ {/if}
+</section>
+
+<style>
+ .page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 0 20px 32px;
+ }
+ .sticky-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-height: 32px;
+ }
+ .sticky-title {
+ font-size: 14px;
+ font-weight: 700;
+ color: rgba(255, 255, 255, 0.9);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0;
+ transition: opacity 200ms ease;
+ }
+ :global(.sticky-header.opaque) .sticky-title {
+ opacity: 1;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .sticky-title {
+ transition: none;
+ }
+ }
+ .back {
+ align-self: flex-start;
+ padding: 6px 10px;
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ cursor: pointer;
+ font-size: 13px;
+ }
+ .back:hover {
+ color: var(--secondary);
+ }
+ .tracklist {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 4px;
+ }
+ .hero-skel,
+ .list-skel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+</style>
diff --git a/src/routes/study/music/youtube/channel/[id]/+page.svelte b/src/routes/study/music/youtube/channel/[id]/+page.svelte
new file mode 100644
index 00000000..81fd4bc5
--- /dev/null
+++ b/src/routes/study/music/youtube/channel/[id]/+page.svelte
@@ -0,0 +1,358 @@
+<script lang="ts">
+ import { page } from "$app/stores";
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyYoutubeChannel,
+ studyYoutubeSubsAdd,
+ studyYoutubeSubsRemove,
+ studyYoutubeSubsIsSubscribed,
+ type YoutubeChannel,
+ type YoutubeChannelTab,
+ type YoutubeSearchItem,
+ type YoutubeSearchVideoItem,
+ } from "$lib/study-bridge";
+ import YoutubeItem from "$lib/study-music-youtube-components/YoutubeItem.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import HeroGradient from "$lib/study-music-components/HeroGradient.svelte";
+ import ChipsRow from "$lib/study-music-components/ChipsRow.svelte";
+ import ExpandableText from "$lib/study-music-components/ExpandableText.svelte";
+ import StickyHeader from "$lib/study-music-components/StickyHeader.svelte";
+ import { playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+
+ let channelId = $derived($page.params.id ?? "");
+ let activeTab = $state<YoutubeChannelTab>("videos");
+ let channel = $state<YoutubeChannel | null>(null);
+ let loading = $state(false);
+ let error = $state<string | null>(null);
+ let subscribed = $state(false);
+ let subBusy = $state(false);
+
+ const tabChips = $derived([
+ { id: "videos" as YoutubeChannelTab, label: $t("study.music.tab_songs") },
+ { id: "playlists" as YoutubeChannelTab, label: $t("study.music.tab_albums") },
+ { id: "shorts" as YoutubeChannelTab, label: $t("study.music.tab_videos") },
+ { id: "about" as YoutubeChannelTab, label: $t("study.music.tab_about") },
+ ]);
+
+ async function load(tab: YoutubeChannelTab) {
+ loading = true;
+ error = null;
+ try {
+ channel = await studyYoutubeChannel({ channelId, tab });
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function refreshSubscribed(id: string) {
+ try {
+ const res = await studyYoutubeSubsIsSubscribed({ channelId: id });
+ subscribed = res.subscribed;
+ } catch {
+ /* ignore */
+ }
+ }
+
+ async function toggleSub() {
+ if (!channel || subBusy) return;
+ subBusy = true;
+ try {
+ if (subscribed) {
+ await studyYoutubeSubsRemove({ channelId: channel.header.channel_id });
+ subscribed = false;
+ } else {
+ await studyYoutubeSubsAdd({
+ channelId: channel.header.channel_id,
+ title: channel.header.title,
+ thumbnailUrl: channel.header.avatar_url ?? undefined,
+ });
+ subscribed = true;
+ }
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ subBusy = false;
+ }
+ }
+
+ function videoItems(items: YoutubeSearchItem[]): YoutubeSearchVideoItem[] {
+ const out: YoutubeSearchVideoItem[] = [];
+ for (const it of items) {
+ if (it.kind === "video") out.push(it);
+ else if (it.kind === "shelf") {
+ for (const s of it.items) if (s.kind === "video") out.push(s);
+ }
+ }
+ return out;
+ }
+
+ async function play(videoId: string) {
+ if (!channel) return;
+ const queue = videoItems(channel.items);
+ const item = queue.find((v) => v.video_id === videoId);
+ if (!item) return;
+ try {
+ await playYoutubeVideoItem(item, queue);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function openPlaylist(playlistId: string) {
+ const route = playlistId.startsWith("OLAK") ? "album" : "playlist";
+ void goto(`/study/music/youtube/${route}/${encodeURIComponent(playlistId)}`);
+ }
+
+ async function shuffleRadio() {
+ if (!channel) return;
+ const queue = videoItems(channel.items);
+ if (queue.length === 0) {
+ showToast("info", $t("study.music.shelf_recent_empty"));
+ return;
+ }
+ const shuffled = queue.slice();
+ for (let i = shuffled.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
+ }
+ try {
+ await playYoutubeVideoItem(shuffled[0], shuffled);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function switchTab(tab: string) {
+ const target = tab as YoutubeChannelTab;
+ if (activeTab === target) return;
+ activeTab = target;
+ void load(target);
+ }
+
+ $effect(() => {
+ const id = channelId;
+ if (id) {
+ void refreshSubscribed(id);
+ void load(activeTab);
+ }
+ });
+</script>
+
+<section class="channel-page">
+ <StickyHeader>
+ <div class="sticky-row">
+ <button class="back" onclick={() => goto("/study/music/youtube")} type="button">
+ ← {$t("study.music.back")}
+ </button>
+ {#if channel}
+ <span class="sticky-title">{channel.header.title}</span>
+ {/if}
+ </div>
+ </StickyHeader>
+
+ {#if loading && !channel}
+ <div class="grid-skel">
+ <YoutubeSkeleton kind="card" count={6} />
+ </div>
+ {:else if error && !channel}
+ <YoutubeError error={error} onRetry={() => { error = null; void load(activeTab); }} />
+ {:else if channel}
+ <HeroGradient coverUrl={channel.header.avatar_url ?? channel.header.banner_url} minHeight={260}>
+ <div class="hero-inner">
+ {#if channel.header.banner_url}
+ <img class="banner" src={channel.header.banner_url} alt="" />
+ {/if}
+ <div class="hero-meta">
+ <div class="avatar">
+ {#if channel.header.avatar_url}
+ <img src={channel.header.avatar_url} alt="" />
+ {/if}
+ </div>
+ <div class="info">
+ <h1 class="title">{channel.header.title}</h1>
+ <p class="meta">
+ {#if channel.header.handle}
+ <span>{channel.header.handle}</span>
+ {/if}
+ {#if channel.header.subscribers_text}
+ <span class="sep" aria-hidden="true"> · </span>
+ <span>{channel.header.subscribers_text}</span>
+ {/if}
+ {#if channel.header.video_count_text}
+ <span class="sep" aria-hidden="true"> · </span>
+ <span>{channel.header.video_count_text}</span>
+ {/if}
+ </p>
+ <div class="hero-actions">
+ <button
+ class="action primary"
+ type="button"
+ onclick={shuffleRadio}
+ aria-label={$t("study.music.shuffle_radio")}
+ >
+ {$t("study.music.shuffle_radio")}
+ </button>
+ <button
+ class="action sub-btn"
+ class:is-subscribed={subscribed}
+ disabled={subBusy}
+ onclick={toggleSub}
+ type="button"
+ aria-label={subscribed ? $t("study.music.youtube.channel_unsubscribe_aria") : $t("study.music.youtube.channel_subscribe")}
+ >
+ <span class="default-label">{subscribed ? $t("study.music.youtube.channel_subscribed") : $t("study.music.youtube.channel_subscribe")}</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </HeroGradient>
+
+ <ChipsRow
+ chips={tabChips}
+ activeId={activeTab}
+ onSelect={switchTab}
+ ariaLabel={$t("study.music.tab_about")}
+ />
+
+ {#if activeTab === "about"}
+ <article class="about">
+ {#if channel.header.description}
+ <ExpandableText text={channel.header.description} maxLines={6} />
+ {:else}
+ <p class="muted">{$t("study.music.no_description")}</p>
+ {/if}
+ </article>
+ {:else if loading}
+ <div class="grid">
+ <YoutubeSkeleton kind="card" count={6} />
+ </div>
+ {:else if error}
+ <YoutubeError error={error} onRetry={() => { error = null; void load(activeTab); }} />
+ {:else if channel.items.length === 0}
+ <p class="muted">{$t("study.music.youtube.channel_no_items")}</p>
+ {:else}
+ <div class="grid">
+ {#each channel.items as item, idx (idx)}
+ <YoutubeItem item={item} onPlay={play} onPlaylistOpen={openPlaylist} />
+ {/each}
+ </div>
+ {/if}
+ {/if}
+</section>
+
+<style>
+ .channel-page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 0 20px 32px;
+ }
+ .sticky-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-height: 32px;
+ }
+ .sticky-title {
+ font-size: 14px;
+ font-weight: 700;
+ color: rgba(255, 255, 255, 0.9);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0;
+ transition: opacity 200ms ease;
+ }
+ :global(.sticky-header.opaque) .sticky-title {
+ opacity: 1;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .sticky-title {
+ transition: none;
+ }
+ }
+ .back {
+ align-self: flex-start;
+ padding: 6px 10px;
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ cursor: pointer;
+ font-size: 13px;
+ }
+ .back:hover { color: var(--secondary); }
+ .hero-inner {
+ position: relative;
+ min-height: 260px;
+ }
+ .banner {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ opacity: 0.35;
+ z-index: 0;
+ }
+ .hero-meta {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: 18px;
+ padding: 24px;
+ }
+ .avatar {
+ width: 96px;
+ height: 96px;
+ border-radius: 50%;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.08);
+ flex-shrink: 0;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
+ }
+ .avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }
+ .info { display: flex; flex-direction: column; gap: 6px; min-width: 0; color: #fff; }
+ .title { margin: 0; font-size: 28px; font-weight: 800; }
+ .meta { margin: 0; font-size: 13px; color: rgba(255, 255, 255, 0.7); }
+ .sep { color: rgba(255, 255, 255, 0.35); }
+ .hero-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
+ .action {
+ padding: 10px 18px;
+ border-radius: 999px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .action:hover:not(:disabled) { background: rgba(255, 255, 255, 0.14); }
+ .action.primary {
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ border-color: transparent;
+ }
+ .action.primary:hover:not(:disabled) { filter: brightness(1.08); }
+ .sub-btn { padding: 10px 18px; }
+ .sub-btn:disabled { opacity: 0.6; cursor: not-allowed; }
+ .about { padding: 8px 4px; color: rgba(255, 255, 255, 0.78); font-size: 14px; line-height: 1.5; }
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 18px 14px;
+ }
+ .muted { color: var(--tertiary); font-size: 13px; }
+ .grid-skel {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 18px 14px;
+ }
+</style>
diff --git a/src/routes/study/music/youtube/explore/+page.svelte b/src/routes/study/music/youtube/explore/+page.svelte
new file mode 100644
index 00000000..37f285c4
--- /dev/null
+++ b/src/routes/study/music/youtube/explore/+page.svelte
@@ -0,0 +1,472 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { colorFromString } from "$lib/study-music/format";
+ import { playYoutubeVideoId } from "$lib/study-music/youtube-play-helper";
+ import {
+ studyYoutubeTrending,
+ studyYoutubeNewReleases,
+ studyYoutubeMoodsAndGenres,
+ type YoutubeSearchItem,
+ type YoutubeNewReleaseAlbum,
+ type YoutubeMoodCategory,
+ type YoutubeMoodSection,
+ } from "$lib/study-bridge";
+ import NavigationTitle from "$lib/study-music-components/NavigationTitle.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+
+ let chartsItems = $state<YoutubeSearchItem[]>([]);
+ let chartsLoading = $state(true);
+ let chartsError = $state<string | null>(null);
+
+ let trendingItems = $state<YoutubeSearchItem[]>([]);
+ let trendingLoading = $state(true);
+ let trendingError = $state<string | null>(null);
+
+ let newReleases = $state<YoutubeNewReleaseAlbum[]>([]);
+ let newReleasesLoading = $state(true);
+ let newReleasesError = $state<string | null>(null);
+
+ let moodSections = $state<YoutubeMoodSection[]>([]);
+ let moodsLoading = $state(true);
+ let moodsError = $state<string | null>(null);
+
+ function flattenItems(items: YoutubeSearchItem[]): YoutubeSearchItem[] {
+ const out: YoutubeSearchItem[] = [];
+ for (const it of items) {
+ if (it.kind === "shelf") {
+ for (const s of it.items) out.push(s);
+ } else {
+ out.push(it);
+ }
+ }
+ return out;
+ }
+
+ async function loadAll() {
+ void loadCharts();
+ void loadTrending();
+ void loadNewReleases();
+ void loadMoods();
+ }
+
+ async function loadCharts() {
+ chartsLoading = true;
+ chartsError = null;
+ try {
+ const res = await studyYoutubeTrending({ category: "music" });
+ chartsItems = flattenItems(res.items ?? []).filter((i) => i.kind === "video").slice(0, 16);
+ } catch (e) {
+ chartsError = e instanceof Error ? e.message : String(e);
+ } finally {
+ chartsLoading = false;
+ }
+ }
+
+ async function loadTrending() {
+ trendingLoading = true;
+ trendingError = null;
+ try {
+ const res = await studyYoutubeTrending({ category: "now" });
+ trendingItems = flattenItems(res.items ?? []).filter((i) => i.kind === "video").slice(0, 16);
+ } catch (e) {
+ trendingError = e instanceof Error ? e.message : String(e);
+ } finally {
+ trendingLoading = false;
+ }
+ }
+
+ async function loadNewReleases() {
+ newReleasesLoading = true;
+ newReleasesError = null;
+ try {
+ const res = await studyYoutubeNewReleases();
+ newReleases = (res.albums ?? []).slice(0, 16);
+ } catch (e) {
+ newReleasesError = e instanceof Error ? e.message : String(e);
+ } finally {
+ newReleasesLoading = false;
+ }
+ }
+
+ async function loadMoods() {
+ moodsLoading = true;
+ moodsError = null;
+ try {
+ const res = await studyYoutubeMoodsAndGenres();
+ moodSections = res.sections ?? [];
+ } catch (e) {
+ moodsError = e instanceof Error ? e.message : String(e);
+ } finally {
+ moodsLoading = false;
+ }
+ }
+
+ async function playVideoItem(item: YoutubeSearchItem) {
+ if (item.kind !== "video") return;
+ try {
+ await playYoutubeVideoId(item.video_id, item.title, item.channel_title, item.thumbnail_url);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function openAlbum(album: YoutubeNewReleaseAlbum) {
+ void goto(`/study/music/youtube/album/${encodeURIComponent(album.browse_id)}`);
+ }
+
+ function openMood(mood: YoutubeMoodCategory) {
+ const params = mood.params ? `?params=${encodeURIComponent(mood.params)}` : "";
+ void goto(`/study/music/youtube/mood/${encodeURIComponent(mood.mood_id)}${params}`);
+ }
+
+ function moodSurface(color: string | null): string {
+ if (!color) return "rgba(255,255,255,0.06)";
+ return `linear-gradient(135deg, ${color}cc 0%, ${color}66 100%)`;
+ }
+
+ onMount(() => {
+ void loadAll();
+ });
+</script>
+
+<svelte:head>
+ <title>{$t("study.music.youtube.explore_title")}</title>
+</svelte:head>
+
+<main class="explore">
+ <header class="page-head">
+ <button class="back" type="button" onclick={() => goto("/study/music/youtube")}>
+ <span aria-hidden="true">←</span>
+ <span>{$t("study.music.back")}</span>
+ </button>
+ <div class="head-text">
+ <h1>{$t("study.music.youtube.explore_title")}</h1>
+ <p>{$t("study.music.youtube.explore_tagline")}</p>
+ </div>
+ </header>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_charts")} />
+ {#if chartsLoading}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if chartsError || chartsItems.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.shelf_charts_empty")}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each chartsItems as item, idx (idx)}
+ {#if item.kind === "video"}
+ <button type="button" class="card" onclick={() => playVideoItem(item)}>
+ <div class="cover">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(item.title)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{item.title}</h3>
+ {#if item.channel_title}<p class="card-sub">{item.channel_title}</p>{/if}
+ </button>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_new_releases")} />
+ {#if newReleasesLoading}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if newReleasesError || newReleases.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.shelf_new_releases_empty")}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each newReleases as album (album.browse_id)}
+ <button type="button" class="card" onclick={() => openAlbum(album)}>
+ <div class="cover">
+ {#if album.thumbnail_url}
+ <img src={album.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(album.title)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{album.title}</h3>
+ {#if album.artist}<p class="card-sub">{album.artist}</p>{/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_trending")} />
+ {#if trendingLoading}
+ <YoutubeSkeleton kind="card" count={6} />
+ {:else if trendingError || trendingItems.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.shelf_trending_error")}
+ compact
+ />
+ {:else}
+ <div class="h-scroll">
+ {#each trendingItems as item, idx (idx)}
+ {#if item.kind === "video"}
+ <button type="button" class="card" onclick={() => playVideoItem(item)}>
+ <div class="cover">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(item.title)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{item.title}</h3>
+ {#if item.channel_title}<p class="card-sub">{item.channel_title}</p>{/if}
+ </button>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ </section>
+
+ <section class="block">
+ <NavigationTitle title={$t("study.music.youtube.shelf_moods_and_genres")} />
+ {#if moodsLoading}
+ <div class="moods-skeleton">
+ {#each Array(8) as _, i (i)}
+ <div class="mood-card mood-skeleton"></div>
+ {/each}
+ </div>
+ {:else if moodsError || moodSections.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.moods_empty")}
+ compact
+ />
+ {:else}
+ <div class="moods-stack">
+ {#each moodSections as section, i (section.title + i)}
+ {#if section.title}
+ <h3 class="moods-section-title">{section.title}</h3>
+ {/if}
+ <div class="moods-grid">
+ {#each section.items as mood (mood.mood_id)}
+ <button
+ type="button"
+ class="mood-card"
+ style:background={moodSurface(mood.color)}
+ onclick={() => openMood(mood)}
+ >
+ <span class="mood-title">{mood.title}</span>
+ </button>
+ {/each}
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </section>
+</main>
+
+<style>
+ .explore {
+ padding: 24px 24px 96px;
+ max-width: 1200px;
+ margin: 0 auto;
+ display: grid;
+ gap: 28px;
+ }
+ .page-head {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .back {
+ align-self: start;
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.7);
+ cursor: pointer;
+ padding: 6px 10px;
+ border-radius: 8px;
+ font: inherit;
+ font-size: 13px;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .back:hover {
+ color: white;
+ background: rgba(255, 255, 255, 0.06);
+ }
+ .head-text h1 {
+ margin: 0;
+ font-size: 32px;
+ font-weight: 800;
+ letter-spacing: -0.02em;
+ color: white;
+ }
+ .head-text p {
+ margin: 4px 0 0;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 14px;
+ }
+ .block {
+ display: grid;
+ gap: 12px;
+ }
+ .h-scroll {
+ display: grid;
+ grid-auto-flow: column;
+ grid-auto-columns: minmax(160px, 180px);
+ gap: 12px;
+ overflow-x: auto;
+ padding-bottom: 6px;
+ scroll-snap-type: x mandatory;
+ -ms-overflow-style: none;
+ scrollbar-width: thin;
+ }
+ .h-scroll::-webkit-scrollbar {
+ height: 6px;
+ }
+ .h-scroll::-webkit-scrollbar-thumb {
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ }
+ .card {
+ scroll-snap-align: start;
+ background: transparent;
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: left;
+ color: inherit;
+ display: grid;
+ gap: 6px;
+ }
+ .cover {
+ aspect-ratio: 1 / 1;
+ border-radius: 12px;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.04);
+ }
+ .cover img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .cover-fallback {
+ width: 100%;
+ height: 100%;
+ }
+ .card-title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.92);
+ line-height: 1.3;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+ .card-sub {
+ margin: 0;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .moods-stack {
+ display: grid;
+ gap: 18px;
+ }
+ .moods-section-title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+ .moods-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 12px;
+ }
+ @media (min-width: 760px) {
+ .moods-grid {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ }
+ .mood-card {
+ min-height: 84px;
+ border-radius: 14px;
+ border: 0;
+ cursor: pointer;
+ padding: 14px;
+ display: flex;
+ align-items: flex-end;
+ text-align: left;
+ font: inherit;
+ color: white;
+ overflow: hidden;
+ position: relative;
+ transition: transform 200ms ease, filter 200ms ease;
+ }
+ .mood-card:hover {
+ transform: translateY(-2px);
+ filter: brightness(1.1);
+ }
+ .mood-title {
+ font-size: 14px;
+ font-weight: 700;
+ letter-spacing: -0.005em;
+ line-height: 1.3;
+ }
+ .moods-skeleton {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 12px;
+ }
+ @media (min-width: 760px) {
+ .moods-skeleton {
+ grid-template-columns: repeat(4, 1fr);
+ }
+ }
+ .mood-skeleton {
+ background: linear-gradient(
+ 90deg,
+ rgba(255, 255, 255, 0.04) 0%,
+ rgba(255, 255, 255, 0.08) 50%,
+ rgba(255, 255, 255, 0.04) 100%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.6s linear infinite;
+ }
+ @keyframes shimmer {
+ 0% {
+ background-position: 200% 0;
+ }
+ 100% {
+ background-position: -200% 0;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .mood-skeleton {
+ animation: none;
+ }
+ .mood-card {
+ transition: none;
+ }
+ }
+</style>
diff --git a/src/routes/study/music/youtube/history/+page.svelte b/src/routes/study/music/youtube/history/+page.svelte
new file mode 100644
index 00000000..68f530ed
--- /dev/null
+++ b/src/routes/study/music/youtube/history/+page.svelte
@@ -0,0 +1,219 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyMusicHistoryList,
+ studyMusicHistoryClear,
+ studyMusicHistoryRemove,
+ type MusicHistoryEntry,
+ } from "$lib/study-bridge";
+ import { playYoutubeVideoId } from "$lib/study-music/youtube-play-helper";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import { t } from "$lib/i18n";
+ import { goto } from "$app/navigation";
+
+ let entries = $state<MusicHistoryEntry[]>([]);
+ let loading = $state(true);
+ let error = $state<string | null>(null);
+
+ async function load() {
+ loading = true;
+ error = null;
+ try {
+ const res = await studyMusicHistoryList({
+ limit: 300,
+ source: "youtube",
+ });
+ entries = res.entries ?? [];
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function fmtAgo(tsMs: number): string {
+ const seconds = Math.floor((Date.now() - tsMs) / 1000);
+ if (seconds < 60) return $t("study.music.history_now") as string;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes} min`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours} h`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days} d`;
+ const months = Math.floor(days / 30);
+ if (months < 12) return `${months} m`;
+ const years = Math.floor(months / 12);
+ return `${years} a`;
+ }
+
+ async function play(entry: MusicHistoryEntry) {
+ try {
+ if (entry.external_id) {
+ await playYoutubeVideoId(
+ entry.external_id,
+ entry.title,
+ entry.artist,
+ entry.cover_url,
+ );
+ return;
+ }
+ showToast("info", $t("study.music.history_unplayable") as string);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function remove(id: number) {
+ try {
+ await studyMusicHistoryRemove({ id });
+ entries = entries.filter((e) => e.id !== id);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function clearAll() {
+ if (!window.confirm($t("study.music.history_clear_confirm_yt") as string)) return;
+ try {
+ const res = await studyMusicHistoryClear({ source: "youtube" });
+ showToast("success", `${res.removed} ${$t("study.music.history_entries_removed") as string}`);
+ entries = [];
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ onMount(() => {
+ void load();
+ });
+</script>
+
+<section class="history-page">
+ <header class="head">
+ <h1>{$t("study.music.history_title_yt")}</h1>
+ {#if entries.length > 0}
+ <button class="clear-btn" onclick={clearAll} type="button">{$t("study.music.history_clear")}</button>
+ {/if}
+ </header>
+
+ {#if loading}
+ <div class="skel-list">
+ <YoutubeSkeleton kind="row" count={6} />
+ </div>
+ {:else if error}
+ <YoutubeError error={error} onRetry={() => { error = null; void load(); }} />
+ {:else if entries.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.history_empty_title_yt") as string}
+ ctaLabel={$t("study.music.history_empty_cta_yt") as string}
+ onCta={() => goto("/study/music/youtube/search")}
+ />
+ {:else}
+ <ul class="list">
+ {#each entries as entry (entry.id)}
+ <li class="row">
+ <button class="thumb" onclick={() => play(entry)} type="button" aria-label={$t("study.music.play") as string}>
+ {#if entry.cover_url}
+ <img src={entry.cover_url} alt="" loading="lazy" />
+ {/if}
+ </button>
+ <div class="info">
+ <button class="title-btn" onclick={() => play(entry)} type="button">
+ {entry.title}
+ </button>
+ <p class="meta">
+ {#if entry.artist}
+ <span>{entry.artist}</span>
+ <span> · </span>
+ {/if}
+ <span>{fmtAgo(entry.played_at)}</span>
+ </p>
+ </div>
+ <button class="remove" onclick={() => remove(entry.id)} aria-label={$t("study.music.history_remove_aria") as string} type="button">×</button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+</section>
+
+<style>
+ .history-page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 16px 20px 32px;
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .head h1 { margin: 0; font-size: 22px; font-weight: 700; color: var(--primary); }
+ .clear-btn {
+ padding: 6px 14px;
+ background: transparent;
+ color: var(--tertiary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ border-radius: 999px;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .clear-btn:hover { color: #d33; border-color: #d33; }
+ .list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
+ .row {
+ display: grid;
+ grid-template-columns: 120px 1fr auto;
+ align-items: center;
+ gap: 14px;
+ padding: 8px;
+ border-radius: 10px;
+ }
+ .row:hover { background: color-mix(in oklab, var(--button) 30%, transparent); }
+ .thumb {
+ position: relative;
+ width: 120px;
+ aspect-ratio: 16 / 9;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ border: 0;
+ border-radius: 8px;
+ overflow: hidden;
+ cursor: pointer;
+ padding: 0;
+ }
+ .thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
+ .info { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
+ .title-btn {
+ padding: 0;
+ background: transparent;
+ border: 0;
+ color: var(--primary);
+ font-size: 14px;
+ font-weight: 600;
+ text-align: left;
+ cursor: pointer;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .title-btn:hover { color: var(--accent); }
+ .meta { margin: 0; font-size: 12px; color: var(--tertiary); }
+ .remove {
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: var(--tertiary);
+ font-size: 18px;
+ cursor: pointer;
+ }
+ .remove:hover { color: #d33; background: color-mix(in oklab, var(--button) 40%, transparent); }
+ .skel-list { display: flex; flex-direction: column; gap: 8px; }
+</style>
diff --git a/src/routes/study/music/youtube/mood/[id]/+page.svelte b/src/routes/study/music/youtube/mood/[id]/+page.svelte
new file mode 100644
index 00000000..14be7965
--- /dev/null
+++ b/src/routes/study/music/youtube/mood/[id]/+page.svelte
@@ -0,0 +1,240 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { page } from "$app/stores";
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import { colorFromString } from "$lib/study-music/format";
+ import {
+ studyYoutubeMoodDetail,
+ type YoutubeMoodPlaylistItem,
+ type YoutubeMoodShelf,
+ } from "$lib/study-bridge";
+ import NavigationTitle from "$lib/study-music-components/NavigationTitle.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+
+ let moodId = $derived($page.params.id ?? "");
+ let params = $derived($page.url.searchParams.get("params"));
+
+ let title = $state<string | null>(null);
+ let shelves = $state<YoutubeMoodShelf[]>([]);
+ let loading = $state(true);
+ let error = $state<string | null>(null);
+
+ async function load() {
+ if (!moodId) return;
+ loading = true;
+ error = null;
+ try {
+ const res = await studyYoutubeMoodDetail({ moodId, params });
+ title = res.title ?? null;
+ shelves = res.shelves ?? [];
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function openPlaylist(item: YoutubeMoodPlaylistItem) {
+ const id = item.playlist_id;
+ if (!id) return;
+ const route = id.startsWith("OLAK") ? "album" : "playlist";
+ void goto(`/study/music/youtube/${route}/${encodeURIComponent(id)}`);
+ }
+
+ $effect(() => {
+ if (moodId) void load();
+ });
+</script>
+
+<svelte:head>
+ <title>{title ?? $t("study.music.youtube.explore_title")}</title>
+</svelte:head>
+
+<main class="mood-page">
+ <header class="page-head">
+ <button class="back" type="button" onclick={() => goto("/study/music/youtube/explore")}>
+ <span aria-hidden="true">←</span>
+ <span>{$t("study.music.youtube.back_to_explore")}</span>
+ </button>
+ {#if title}
+ <h1>{title}</h1>
+ {:else if loading}
+ <div class="title-skeleton"></div>
+ {/if}
+ </header>
+
+ {#if loading}
+ <section class="block">
+ <YoutubeSkeleton kind="card" count={6} />
+ </section>
+ {:else if error}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.mood_loading_error")}
+ ctaLabel={$t("study.music.retry")}
+ onCta={() => load()}
+ />
+ {:else if shelves.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.youtube.mood_empty")}
+ ctaLabel={$t("study.music.youtube.back_to_explore")}
+ ctaHref="/study/music/youtube/explore"
+ />
+ {:else}
+ {#each shelves as shelf, idx (shelf.title + idx)}
+ <section class="block">
+ {#if shelf.title}<NavigationTitle title={shelf.title} />{/if}
+ <div class="h-scroll">
+ {#each shelf.items as item (item.playlist_id + idx)}
+ <button type="button" class="card" onclick={() => openPlaylist(item)}>
+ <div class="cover">
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {:else}
+ <div class="cover-fallback" style:background={colorFromString(item.title)}></div>
+ {/if}
+ </div>
+ <h3 class="card-title">{item.title}</h3>
+ {#if item.subtitle}<p class="card-sub">{item.subtitle}</p>{/if}
+ </button>
+ {/each}
+ </div>
+ </section>
+ {/each}
+ {/if}
+</main>
+
+<style>
+ .mood-page {
+ padding: 24px 24px 96px;
+ max-width: 1200px;
+ margin: 0 auto;
+ display: grid;
+ gap: 28px;
+ }
+ .page-head {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .back {
+ align-self: start;
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.7);
+ cursor: pointer;
+ padding: 6px 10px;
+ border-radius: 8px;
+ font: inherit;
+ font-size: 13px;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .back:hover {
+ color: white;
+ background: rgba(255, 255, 255, 0.06);
+ }
+ h1 {
+ margin: 0;
+ font-size: 32px;
+ font-weight: 800;
+ letter-spacing: -0.02em;
+ color: white;
+ }
+ .title-skeleton {
+ height: 36px;
+ width: 280px;
+ border-radius: 8px;
+ background: linear-gradient(
+ 90deg,
+ rgba(255, 255, 255, 0.04) 0%,
+ rgba(255, 255, 255, 0.08) 50%,
+ rgba(255, 255, 255, 0.04) 100%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.6s linear infinite;
+ }
+ @keyframes shimmer {
+ 0% {
+ background-position: 200% 0;
+ }
+ 100% {
+ background-position: -200% 0;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .title-skeleton {
+ animation: none;
+ }
+ }
+ .block {
+ display: grid;
+ gap: 12px;
+ }
+ .h-scroll {
+ display: grid;
+ grid-auto-flow: column;
+ grid-auto-columns: minmax(160px, 180px);
+ gap: 12px;
+ overflow-x: auto;
+ padding-bottom: 6px;
+ scroll-snap-type: x mandatory;
+ scrollbar-width: thin;
+ }
+ .h-scroll::-webkit-scrollbar {
+ height: 6px;
+ }
+ .h-scroll::-webkit-scrollbar-thumb {
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ }
+ .card {
+ scroll-snap-align: start;
+ background: transparent;
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: left;
+ color: inherit;
+ display: grid;
+ gap: 6px;
+ }
+ .cover {
+ aspect-ratio: 1 / 1;
+ border-radius: 12px;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.04);
+ }
+ .cover img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .cover-fallback {
+ width: 100%;
+ height: 100%;
+ }
+ .card-title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.92);
+ line-height: 1.3;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+ .card-sub {
+ margin: 0;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+</style>
diff --git a/src/routes/study/music/youtube/playlist/[id]/+page.svelte b/src/routes/study/music/youtube/playlist/[id]/+page.svelte
index ed93aa38..6eb17de7 100644
--- a/src/routes/study/music/youtube/playlist/[id]/+page.svelte
+++ b/src/routes/study/music/youtube/playlist/[id]/+page.svelte
@@ -1,80 +1,34 @@
<script lang="ts">
- import { onMount } from "svelte";
import { page } from "$app/stores";
- import { pluginInvoke } from "$lib/plugin-invoke";
+ import { t } from "$lib/i18n";
import { showToast } from "$lib/stores/toast-store.svelte";
- import { fmtDuration } from "$lib/study-music/format";
import {
- musicPlayer,
- type MusicTrack,
- } from "$lib/study-music/player-store.svelte";
- import { t } from "$lib/i18n";
-
- type YtTrack = {
- video_id: string;
- url: string;
- title: string | null;
- artist: string | null;
- uploader: string | null;
- duration_ms: number | null;
- thumbnail: string | null;
- last_played_at: number | null;
- play_count: number;
- favorite: boolean;
- };
+ studyYoutubePlaylist,
+ type YoutubePlaylist,
+ type YoutubePlaylistVideo,
+ type YoutubeSearchVideoItem,
+ } from "$lib/study-bridge";
+ import MediaHero from "$lib/study-music-components/MediaHero.svelte";
+ import TrackListRow from "$lib/study-music-components/TrackListRow.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import ExpandableText from "$lib/study-music-components/ExpandableText.svelte";
+ import StickyHeader from "$lib/study-music-components/StickyHeader.svelte";
+ import { playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
- type YtPlaylist = {
- id: string;
- url: string;
- title: string | null;
- uploader: string | null;
- thumbnail: string | null;
- track_count: number;
- kind: string;
- };
-
- let playlist = $state<YtPlaylist | null>(null);
- let tracks = $state<YtTrack[]>([]);
- let loading = $state(true);
+ let playlistId = $derived($page.params.id ?? "");
+ let playlist = $state<YoutubePlaylist | null>(null);
+ let loading = $state(false);
let error = $state<string | null>(null);
-
- const playlistId = $derived(decodeURIComponent($page.params.id ?? ""));
-
- function ytToMusicTrack(t: YtTrack): MusicTrack {
- const numericId =
- Math.abs(
- t.video_id
- .split("")
- .reduce((acc, c) => (acc * 31 + c.charCodeAt(0)) | 0, 0),
- ) || 1;
- return {
- id: numericId,
- path: t.url,
- title: t.title,
- artist: t.artist ?? t.uploader,
- album: playlist?.title ?? null,
- duration_ms: t.duration_ms,
- cover_path: null,
- favorite: t.favorite,
- play_count: t.play_count,
- last_played_at: t.last_played_at,
- source: "youtube",
- youtube_url: t.url,
- youtube_video_id: t.video_id,
- youtube_thumbnail: t.thumbnail ?? undefined,
- };
- }
+ let pendingShuffle = $state(false);
async function load() {
loading = true;
error = null;
try {
- const res = await pluginInvoke<{
- playlist: YtPlaylist;
- tracks: YtTrack[];
- }>("study", "study:music:youtube:playlist_get", { id: playlistId });
- playlist = res.playlist;
- tracks = res.tracks ?? [];
+ playlist = await studyYoutubePlaylist({ playlistId });
} catch (e) {
error = e instanceof Error ? e.message : String(e);
} finally {
@@ -82,104 +36,151 @@
}
}
- function playAll() {
- if (tracks.length === 0) return;
- const queue = tracks.map(ytToMusicTrack);
- void musicPlayer.play(queue[0], queue);
+ function totalDurationText(videos: YoutubePlaylistVideo[]): string | null {
+ const totalSeconds = videos.reduce((acc, v) => acc + (v.duration_seconds ?? 0), 0);
+ if (totalSeconds <= 0) return null;
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ if (hours > 0) return `${hours}h ${minutes}min`;
+ return `${minutes}min`;
+ }
+
+ function asSearchVideo(v: YoutubePlaylistVideo, fallbackThumb: string | null): YoutubeSearchVideoItem {
+ return {
+ kind: "video",
+ video_id: v.video_id,
+ title: v.title,
+ channel_id: v.channel_id,
+ channel_title: v.channel_title,
+ thumbnail_url: v.thumbnail_url ?? fallbackThumb,
+ duration_text: v.duration_text,
+ published_time_text: null,
+ view_count_text: null,
+ short_description: null,
+ is_live: false,
+ };
}
- function playOne(t: YtTrack) {
- const queue = tracks.map(ytToMusicTrack);
- const target = queue.find((q) => q.youtube_video_id === t.video_id);
- if (target) void musicPlayer.play(target, queue);
+ async function playFromIndex(idx: number, shuffle = false) {
+ if (!playlist || playlist.videos.length === 0) return;
+ const fallbackThumb = playlist.info.thumbnail_url;
+ let queue = playlist.videos.map((v) => asSearchVideo(v, fallbackThumb));
+ let target = queue[idx];
+ if (shuffle) {
+ const rest = queue.slice();
+ for (let i = rest.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [rest[i], rest[j]] = [rest[j], rest[i]];
+ }
+ queue = rest;
+ target = queue[0];
+ }
+ try {
+ await playYoutubeVideoItem(target, queue);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
}
- async function toggleFavorite(t: YtTrack) {
+ async function shareLink() {
+ if (!playlist) return;
+ const url = `https://www.youtube.com/playlist?list=${encodeURIComponent(playlist.info.playlist_id)}`;
try {
- const res = await pluginInvoke<{ favorite: boolean }>(
- "study",
- "study:music:youtube:track_toggle_favorite",
- { video_id: t.video_id },
- );
- tracks = tracks.map((x) =>
- x.video_id === t.video_id ? { ...x, favorite: res.favorite } : x,
- );
+ await navigator.clipboard.writeText(url);
+ showToast("success", $t("study.music.share_copied"));
} catch (e) {
showToast("error", e instanceof Error ? e.message : String(e));
}
}
+ async function shuffleAll() {
+ if (pendingShuffle) return;
+ pendingShuffle = true;
+ try {
+ await playFromIndex(0, true);
+ } finally {
+ pendingShuffle = false;
+ }
+ }
+
$effect(() => {
if (playlistId) void load();
});
-
- onMount(() => {
- void load();
- });
</script>
<section class="page">
- {#if loading}
- <p class="muted">{$t("study.common.loading")}</p>
- {:else if error}
- <p class="error">{error}</p>
+ <StickyHeader>
+ <div class="sticky-row">
+ <button class="back" type="button" onclick={() => history.back()}>← {$t("study.music.back")}</button>
+ {#if playlist}
+ <span class="sticky-title">{playlist.info.title || playlistId}</span>
+ {/if}
+ </div>
+ </StickyHeader>
+
+ {#if loading && !playlist}
+ <div class="hero-skel"><YoutubeSkeleton kind="card" count={1} /></div>
+ <div class="list-skel"><YoutubeSkeleton kind="row" count={6} /></div>
+ {:else if error && !playlist}
+ <YoutubeError error={error} onRetry={() => { error = null; void load(); }} />
{:else if playlist}
- <header class="hero">
- <div class="hero-cover">
- {#if playlist.thumbnail}
- <img src={playlist.thumbnail} alt="" />
- {:else}
- <div class="fallback"></div>
- {/if}
- </div>
- <div class="hero-meta">
- <span class="eyebrow">{$t("study.music.yt_eyebrow")}</span>
- <h1>{playlist.title ?? playlist.id}</h1>
- {#if playlist.uploader}
- <p class="hero-sub">{playlist.uploader}</p>
- {/if}
- <p class="hero-stats">{tracks.length} faixas</p>
- <div class="hero-actions">
- <button type="button" class="cta" onclick={playAll}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
- {$t("study.music.play")}
- </button>
- </div>
- </div>
- </header>
+ {@const total = totalDurationText(playlist.videos)}
+ {@const trackCount = playlist.info.video_count ?? playlist.videos.length}
+ {@const ownerLine = playlist.info.owner_title
+ ? $t("study.music.youtube.creator_by", { name: playlist.info.owner_title })
+ : null}
+ <MediaHero
+ coverUrl={playlist.info.thumbnail_url}
+ eyebrow={$t("study.music.eyebrow_playlist")}
+ title={playlist.info.title || playlistId}
+ subtitle={ownerLine}
+ stats={[
+ { label: "", value: trackCount === 1 ? $t("study.music.track_count_one") : $t("study.music.tracks_count_n", { count: trackCount }) },
+ { label: "", value: total },
+ { label: "", value: playlist.info.view_count_text },
+ ]}
+ actions={[
+ {
+ id: "play",
+ label: $t("study.music.play_all"),
+ primary: true,
+ onClick: () => void playFromIndex(0, false),
+ },
+ {
+ id: "shuffle",
+ label: $t("study.music.shuffle_play"),
+ busy: pendingShuffle,
+ onClick: () => void shuffleAll(),
+ },
+ {
+ id: "share",
+ label: $t("study.music.share"),
+ onClick: () => void shareLink(),
+ },
+ ]}
+ >
+ {#snippet description()}
+ <ExpandableText text={playlist?.info.description ?? null} maxLines={3} />
+ {/snippet}
+ </MediaHero>
- <ul class="track-list">
- {#each tracks as track, i (track.video_id)}
- <li class="row">
- <button type="button" class="row-btn" onclick={() => playOne(track)}>
- <span class="num">{i + 1}</span>
- <span class="thumb-wrap">
- {#if track.thumbnail}
- <img src={track.thumbnail} alt="" loading="lazy" />
- {/if}
- </span>
- <span class="info">
- <span class="title">{track.title ?? track.video_id}</span>
- {#if track.artist || track.uploader}
- <span class="artist">{track.artist ?? track.uploader}</span>
- {/if}
- </span>
- <span class="dur">{fmtDuration(track.duration_ms)}</span>
- </button>
- <button
- type="button"
- class="fav"
- class:on={track.favorite}
- onclick={(e) => { e.stopPropagation(); toggleFavorite(track); }}
- aria-label={$t("study.music.favorite") as string}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill={track.favorite ? "currentColor" : "none"} stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
- <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
- </svg>
- </button>
- </li>
- {/each}
- </ul>
+ {#if playlist.videos.length === 0}
+ <EmptyPlaceholder title={$t("study.music.playlist_empty")} />
+ {:else}
+ <div class="tracklist">
+ {#each playlist.videos as v, idx (v.video_id)}
+ <TrackListRow
+ index={idx}
+ coverUrl={v.thumbnail_url}
+ title={v.title}
+ subtitle={v.channel_title}
+ durationText={v.duration_text}
+ isPlaying={musicPlayer.currentTrack?.youtube_video_id === v.video_id}
+ onPlay={() => void playFromIndex(idx, false)}
+ />
+ {/each}
+ </div>
+ {/if}
{/if}
</section>
@@ -187,174 +188,49 @@
.page {
display: flex;
flex-direction: column;
- gap: 28px;
- padding-bottom: 40px;
- }
- .hero {
- display: flex;
- gap: 24px;
- align-items: flex-end;
- }
- .hero-cover {
- width: 200px;
- height: 200px;
- flex-shrink: 0;
- border-radius: 10px;
- overflow: hidden;
- box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);
- background: rgba(40, 40, 40, 0.6);
- }
- .hero-cover img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .hero-cover .fallback {
- width: 100%;
- height: 100%;
- background: linear-gradient(135deg, #ff0000, #8b0000);
+ gap: 16px;
+ padding: 0 20px 32px;
}
- .hero-meta {
- flex: 1;
+ .sticky-row {
display: flex;
- flex-direction: column;
- gap: 6px;
- }
- .eyebrow {
- font-size: 11px;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--accent);
- }
- .hero-meta h1 {
- margin: 0;
- font-size: 40px;
- font-weight: 800;
- letter-spacing: -0.02em;
+ align-items: center;
+ gap: 12px;
+ min-height: 32px;
}
- .hero-sub {
- margin: 0;
- color: rgba(255, 255, 255, 0.65);
+ .sticky-title {
font-size: 14px;
- }
- .hero-stats {
- margin: 0;
- color: rgba(255, 255, 255, 0.5);
- font-size: 12px;
- }
- .hero-actions {
- display: flex;
- gap: 8px;
- margin-top: 12px;
- }
- .cta {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 10px 22px;
- border: 0;
- border-radius: 999px;
- background: var(--accent);
- color: var(--on-accent, white);
- font-family: inherit;
- font-size: 13px;
font-weight: 700;
- cursor: pointer;
+ color: rgba(255, 255, 255, 0.9);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0;
+ transition: opacity 200ms ease;
}
- .track-list {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
+ :global(.sticky-header.opaque) .sticky-title {
+ opacity: 1;
}
- .row {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 4px 8px;
- border-radius: 6px;
+ @media (prefers-reduced-motion: reduce) {
+ .sticky-title {
+ transition: none;
+ }
}
- .row:hover { background: rgba(255, 255, 255, 0.04); }
- .row-btn {
- flex: 1;
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 6px 4px;
+ .back {
+ align-self: flex-start;
+ padding: 6px 10px;
background: transparent;
border: 0;
- color: rgba(255, 255, 255, 0.95);
- font-family: inherit;
- text-align: left;
+ color: var(--tertiary);
cursor: pointer;
- min-width: 0;
- }
- .num {
- flex-shrink: 0;
- width: 24px;
- text-align: center;
- color: rgba(255, 255, 255, 0.5);
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- }
- .thumb-wrap {
- flex-shrink: 0;
- width: 40px;
- height: 40px;
- background: rgba(40, 40, 40, 0.6);
- border-radius: 4px;
- overflow: hidden;
- }
- .thumb-wrap img {
- width: 100%;
- height: 100%;
- object-fit: cover;
+ font-size: 13px;
}
- .info {
- flex: 1;
+ .back:hover { color: var(--secondary); }
+ .tracklist {
display: flex;
flex-direction: column;
- min-width: 0;
gap: 2px;
+ padding: 4px;
}
- .title {
- font-size: 13px;
- font-weight: 600;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .artist {
- font-size: 11px;
- color: rgba(255, 255, 255, 0.5);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .dur {
- flex-shrink: 0;
- font-size: 12px;
- color: rgba(255, 255, 255, 0.5);
- font-variant-numeric: tabular-nums;
- min-width: 48px;
- text-align: right;
- }
- .fav {
- width: 28px;
- height: 28px;
- padding: 0;
- background: transparent;
- border: 0;
- border-radius: 50%;
- color: rgba(255, 255, 255, 0.5);
- cursor: pointer;
- display: grid;
- place-items: center;
- }
- .fav:hover { color: var(--accent); background: rgba(255, 255, 255, 0.08); }
- .fav.on { color: var(--accent); }
- .muted { color: rgba(255, 255, 255, 0.5); }
- .error { color: rgb(248, 113, 113); }
+ .hero-skel,
+ .list-skel { display: flex; flex-direction: column; gap: 8px; }
</style>
diff --git a/src/routes/study/music/youtube/playlists/+page.svelte b/src/routes/study/music/youtube/playlists/+page.svelte
new file mode 100644
index 00000000..7eed8797
--- /dev/null
+++ b/src/routes/study/music/youtube/playlists/+page.svelte
@@ -0,0 +1,282 @@
+<script lang="ts">
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyYoutubeUserPlaylistList,
+ studyYoutubeUserPlaylistCreate,
+ type YoutubeUserPlaylistSummary,
+ } from "$lib/study-bridge";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+
+ let playlists = $state<YoutubeUserPlaylistSummary[]>([]);
+ let loading = $state(false);
+ let error = $state<string | null>(null);
+ let creating = $state(false);
+ let newTitle = $state("");
+ let newDescription = $state("");
+ let formOpen = $state(false);
+
+ async function reload() {
+ loading = true;
+ error = null;
+ try {
+ const res = await studyYoutubeUserPlaylistList();
+ playlists = res.playlists;
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function submitCreate(event: Event) {
+ event.preventDefault();
+ const title = newTitle.trim();
+ if (!title || creating) return;
+ creating = true;
+ try {
+ const res = await studyYoutubeUserPlaylistCreate({
+ title,
+ description: newDescription.trim() || undefined,
+ });
+ newTitle = "";
+ newDescription = "";
+ formOpen = false;
+ void goto(`/study/music/youtube/playlists/${res.id}`);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ creating = false;
+ }
+ }
+
+ function cancelCreate() {
+ formOpen = false;
+ newTitle = "";
+ newDescription = "";
+ }
+
+ $effect(() => {
+ void reload();
+ });
+</script>
+
+<section class="page">
+ <header class="page-header">
+ <div>
+ <h1>{$t("study.music.my_playlists_title")}</h1>
+ <p class="subtitle">{$t("study.music.my_playlists_subtitle")}</p>
+ </div>
+ <button class="create-btn" type="button" onclick={() => (formOpen = true)}>
+ + {$t("study.music.my_playlists_create")}
+ </button>
+ </header>
+
+ {#if loading && playlists.length === 0}
+ <div class="grid-skel"><YoutubeSkeleton kind="card" count={4} /></div>
+ {:else if error && playlists.length === 0}
+ <YoutubeError error={error} onRetry={() => { error = null; void reload(); }} />
+ {:else if playlists.length === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.my_playlists_empty_title")}
+ body={$t("study.music.my_playlists_empty_body")}
+ ctaLabel={$t("study.music.my_playlists_create")}
+ onCta={() => (formOpen = true)}
+ />
+ {:else}
+ <ul class="grid">
+ {#each playlists as p (p.id)}
+ <li>
+ <a class="card" href={`/study/music/youtube/playlists/${p.id}`} aria-label={$t("study.music.my_playlists_open_aria")}>
+ <div class="thumb" aria-hidden="true">
+ <span class="initial">{p.title.slice(0, 1).toUpperCase()}</span>
+ </div>
+ <div class="meta">
+ <span class="card-title" title={p.title}>{p.title}</span>
+ <span class="card-count">{p.item_count === 1 ? $t("study.music.track_count_one") : $t("study.music.tracks_count_n", { count: p.item_count })}</span>
+ </div>
+ </a>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+</section>
+
+{#if formOpen}
+ <div class="modal-bg" role="dialog" aria-modal="true" aria-label={$t("study.music.my_playlists_create_title")}>
+ <form class="modal" onsubmit={submitCreate}>
+ <h2>{$t("study.music.my_playlists_create_title")}</h2>
+ <label>
+ <span>{$t("study.music.my_playlists_form_name")}</span>
+ <input
+ bind:value={newTitle}
+ type="text"
+ required
+ autofocus
+ maxlength="120"
+ placeholder={$t("study.music.my_playlists_form_name_placeholder")}
+ />
+ </label>
+ <label>
+ <span>{$t("study.music.my_playlists_form_description")}</span>
+ <textarea
+ bind:value={newDescription}
+ rows="3"
+ maxlength="500"
+ ></textarea>
+ </label>
+ <div class="modal-actions">
+ <button type="button" class="ghost" onclick={cancelCreate} disabled={creating}>
+ {$t("study.music.my_playlists_form_cancel")}
+ </button>
+ <button type="submit" class="primary" disabled={creating || newTitle.trim().length === 0}>
+ {$t("study.music.my_playlists_form_save")}
+ </button>
+ </div>
+ </form>
+ </div>
+{/if}
+
+<style>
+ .page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 16px 20px 32px;
+ }
+ .page-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ flex-wrap: wrap;
+ }
+ h1 { margin: 0; font-size: 24px; font-weight: 800; color: var(--primary); }
+ .subtitle { margin: 4px 0 0; color: var(--tertiary); font-size: 13px; }
+ .create-btn {
+ padding: 10px 18px;
+ border-radius: 999px;
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ border: 0;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .create-btn:hover { filter: brightness(1.08); }
+ .grid {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 14px;
+ }
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ text-decoration: none;
+ color: inherit;
+ padding: 12px;
+ background: color-mix(in oklab, var(--button) 30%, transparent);
+ border-radius: 12px;
+ transition: background 160ms ease;
+ }
+ .card:hover { background: color-mix(in oklab, var(--button) 50%, transparent); }
+ .thumb {
+ aspect-ratio: 1;
+ border-radius: 8px;
+ background: linear-gradient(135deg, color-mix(in oklab, var(--accent) 30%, transparent), color-mix(in oklab, var(--accent) 5%, transparent));
+ display: grid;
+ place-items: center;
+ }
+ .initial {
+ font-size: 44px;
+ font-weight: 800;
+ color: var(--accent);
+ }
+ .meta { display: flex; flex-direction: column; gap: 2px; }
+ .card-title {
+ font-size: 14px;
+ font-weight: 700;
+ color: var(--primary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .card-count { font-size: 12px; color: var(--tertiary); }
+ .grid-skel {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 14px;
+ }
+ .modal-bg {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.55);
+ display: grid;
+ place-items: center;
+ z-index: 100;
+ padding: 24px;
+ }
+ .modal {
+ background: var(--background);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 16px;
+ padding: 22px;
+ width: min(420px, 100%);
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.5);
+ }
+ .modal h2 { margin: 0; font-size: 18px; font-weight: 800; color: var(--primary); }
+ .modal label { display: flex; flex-direction: column; gap: 6px; font-size: 13px; color: var(--secondary); }
+ .modal input,
+ .modal textarea {
+ padding: 9px 12px;
+ border-radius: 8px;
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ background: color-mix(in oklab, var(--button) 30%, transparent);
+ color: var(--primary);
+ font: inherit;
+ font-size: 14px;
+ resize: vertical;
+ }
+ .modal-actions {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+ margin-top: 4px;
+ }
+ .modal-actions button {
+ padding: 9px 18px;
+ border-radius: 999px;
+ border: 0;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .ghost {
+ background: transparent;
+ color: var(--secondary);
+ }
+ .primary {
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ }
+ .primary:disabled,
+ .ghost:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .card { transition: none; }
+ }
+</style>
diff --git a/src/routes/study/music/youtube/playlists/[id]/+page.svelte b/src/routes/study/music/youtube/playlists/[id]/+page.svelte
new file mode 100644
index 00000000..3f4b9eed
--- /dev/null
+++ b/src/routes/study/music/youtube/playlists/[id]/+page.svelte
@@ -0,0 +1,619 @@
+<script lang="ts">
+ import { page } from "$app/stores";
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import {
+ studyYoutubeUserPlaylistGet,
+ studyYoutubeUserPlaylistRename,
+ studyYoutubeUserPlaylistDelete,
+ studyYoutubeUserPlaylistReorder,
+ studyYoutubeUserPlaylistRemoveItem,
+ studyYoutubeUserPlaylistAddItem,
+ studyYoutubeSearch,
+ type YoutubeUserPlaylistDetail,
+ type YoutubeUserPlaylistItem,
+ type YoutubeSearchVideoItem,
+ } from "$lib/study-bridge";
+ import MediaHero from "$lib/study-music-components/MediaHero.svelte";
+ import TrackListRow from "$lib/study-music-components/TrackListRow.svelte";
+ import DraggableList from "$lib/study-music-components/DraggableList.svelte";
+ import EmptyPlaceholder from "$lib/study-music-components/EmptyPlaceholder.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import { playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+ import { musicPlayer } from "$lib/study-music/player-store.svelte";
+
+ let playlistId = $derived(parseInt($page.params.id ?? "0", 10));
+ let detail = $state<YoutubeUserPlaylistDetail | null>(null);
+ let loading = $state(false);
+ let error = $state<string | null>(null);
+
+ let renaming = $state(false);
+ let renameValue = $state("");
+
+ let confirmingDelete = $state(false);
+ let pendingDelete = $state(false);
+
+ let addOpen = $state(false);
+ let addQuery = $state("");
+ let addResults = $state<YoutubeSearchVideoItem[]>([]);
+ let addLoading = $state(false);
+ let addTimer: ReturnType<typeof setTimeout> | null = null;
+
+ type RowItem = YoutubeUserPlaylistItem & { id: string };
+
+ const rowItems = $derived<RowItem[]>(
+ (detail?.items ?? []).map((it) => ({ ...it, id: it.video_id })),
+ );
+
+ async function reload() {
+ if (!playlistId) return;
+ loading = true;
+ error = null;
+ try {
+ detail = await studyYoutubeUserPlaylistGet({ playlistId });
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function asSearchVideo(it: YoutubeUserPlaylistItem): YoutubeSearchVideoItem {
+ return {
+ kind: "video",
+ video_id: it.video_id,
+ title: it.title ?? "",
+ channel_id: null,
+ channel_title: it.channel_title,
+ thumbnail_url: it.thumbnail_url,
+ duration_text: null,
+ published_time_text: null,
+ view_count_text: null,
+ short_description: null,
+ is_live: false,
+ };
+ }
+
+ async function playFromIndex(idx: number, shuffle = false) {
+ if (!detail || detail.items.length === 0) return;
+ let queue = detail.items.map(asSearchVideo);
+ let target = queue[idx];
+ if (shuffle) {
+ const rest = queue.slice();
+ for (let i = rest.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [rest[i], rest[j]] = [rest[j], rest[i]];
+ }
+ queue = rest;
+ target = queue[0];
+ }
+ try {
+ await playYoutubeVideoItem(target, queue);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function startRename() {
+ if (!detail) return;
+ renameValue = detail.summary.title;
+ renaming = true;
+ }
+
+ async function commitRename() {
+ if (!detail || !renaming) return;
+ const title = renameValue.trim();
+ if (title.length === 0 || title === detail.summary.title) {
+ renaming = false;
+ return;
+ }
+ try {
+ await studyYoutubeUserPlaylistRename({
+ playlistId: detail.summary.id,
+ title,
+ });
+ detail = { ...detail, summary: { ...detail.summary, title } };
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ renaming = false;
+ }
+ }
+
+ function cancelRename() {
+ renaming = false;
+ }
+
+ async function onReorder(orderedIds: Array<string | number>) {
+ if (!detail) return;
+ const videoIds = orderedIds.map(String);
+ const next = [...detail.items];
+ next.sort((a, b) => videoIds.indexOf(a.video_id) - videoIds.indexOf(b.video_id));
+ next.forEach((it, idx) => (it.position = idx));
+ detail = { ...detail, items: next };
+ try {
+ await studyYoutubeUserPlaylistReorder({
+ playlistId: detail.summary.id,
+ videoIds,
+ });
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ await reload();
+ }
+ }
+
+ async function removeItem(videoId: string) {
+ if (!detail) return;
+ try {
+ await studyYoutubeUserPlaylistRemoveItem({
+ playlistId: detail.summary.id,
+ videoId,
+ });
+ detail = {
+ ...detail,
+ items: detail.items.filter((it) => it.video_id !== videoId),
+ summary: { ...detail.summary, item_count: Math.max(0, detail.summary.item_count - 1) },
+ };
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function performDelete() {
+ if (!detail || pendingDelete) return;
+ pendingDelete = true;
+ try {
+ await studyYoutubeUserPlaylistDelete({ playlistId: detail.summary.id });
+ confirmingDelete = false;
+ void goto("/study/music/youtube/playlists");
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ pendingDelete = false;
+ }
+ }
+
+ function openAdd() {
+ addOpen = true;
+ addQuery = "";
+ addResults = [];
+ }
+
+ function closeAdd() {
+ addOpen = false;
+ if (addTimer) {
+ clearTimeout(addTimer);
+ addTimer = null;
+ }
+ }
+
+ function scheduleAddSearch() {
+ if (addTimer) clearTimeout(addTimer);
+ addTimer = setTimeout(() => {
+ void runAddSearch(addQuery);
+ }, 320);
+ }
+
+ async function runAddSearch(query: string) {
+ const q = query.trim();
+ if (q.length < 2) {
+ addResults = [];
+ return;
+ }
+ addLoading = true;
+ try {
+ const res = await studyYoutubeSearch({ query: q, filter: "videos" });
+ const flat: YoutubeSearchVideoItem[] = [];
+ for (const group of res.groups) {
+ for (const item of group.items) {
+ if (item.kind === "video") flat.push(item);
+ }
+ }
+ addResults = flat.slice(0, 25);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ addLoading = false;
+ }
+ }
+
+ async function addFromYoutube(item: YoutubeSearchVideoItem) {
+ if (!detail) return;
+ try {
+ const res = await studyYoutubeUserPlaylistAddItem({
+ playlistId: detail.summary.id,
+ item: {
+ video_id: item.video_id,
+ title: item.title,
+ channel_title: item.channel_title ?? undefined,
+ thumbnail_url: item.thumbnail_url ?? undefined,
+ },
+ });
+ detail = {
+ ...detail,
+ items: [
+ ...detail.items,
+ {
+ video_id: item.video_id,
+ position: res.position,
+ added_at: Math.floor(Date.now() / 1000),
+ title: item.title,
+ channel_title: item.channel_title,
+ thumbnail_url: item.thumbnail_url,
+ duration_ms: null,
+ },
+ ],
+ summary: { ...detail.summary, item_count: detail.summary.item_count + 1 },
+ };
+ showToast("success", $t("study.music.add_to_playlist_added"));
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ $effect(() => {
+ if (playlistId) void reload();
+ });
+</script>
+
+<section class="page">
+ <button class="back" type="button" onclick={() => goto("/study/music/youtube/playlists")}>
+ ← {$t("study.music.back")}
+ </button>
+
+ {#if loading && !detail}
+ <div class="hero-skel"><YoutubeSkeleton kind="card" count={1} /></div>
+ <div class="list-skel"><YoutubeSkeleton kind="row" count={6} /></div>
+ {:else if error && !detail}
+ <YoutubeError error={error} onRetry={() => { error = null; void reload(); }} />
+ {:else if detail}
+ {@const count = detail.summary.item_count}
+ <div class="hero-wrap">
+ <MediaHero
+ coverUrl={detail.items[0]?.thumbnail_url ?? null}
+ eyebrow={$t("study.music.eyebrow_playlist")}
+ title={renaming ? "" : detail.summary.title}
+ subtitle={detail.summary.description}
+ stats={[
+ { label: "", value: count === 1 ? $t("study.music.track_count_one") : $t("study.music.tracks_count_n", { count }) },
+ ]}
+ actions={count > 0
+ ? [
+ { id: "play", label: $t("study.music.play_all"), primary: true, onClick: () => void playFromIndex(0, false) },
+ { id: "shuffle", label: $t("study.music.shuffle_play"), onClick: () => void playFromIndex(0, true) },
+ { id: "add", label: $t("study.music.add_to_playlist"), onClick: openAdd },
+ { id: "delete", label: $t("study.music.my_playlists_delete_confirm_action"), onClick: () => (confirmingDelete = true) },
+ ]
+ : [
+ { id: "add", label: $t("study.music.add_to_playlist"), primary: true, onClick: openAdd },
+ { id: "delete", label: $t("study.music.my_playlists_delete_confirm_action"), onClick: () => (confirmingDelete = true) },
+ ]}
+ />
+ <div class="title-overlay">
+ {#if renaming}
+ <input
+ class="title-input"
+ type="text"
+ bind:value={renameValue}
+ placeholder={$t("study.music.rename_inline_placeholder")}
+ onblur={commitRename}
+ onkeydown={(e) => {
+ if (e.key === "Enter") { e.preventDefault(); void commitRename(); }
+ else if (e.key === "Escape") cancelRename();
+ }}
+ autofocus
+ maxlength="120"
+ aria-label={$t("study.music.my_playlists_rename_aria")}
+ />
+ {:else}
+ <button
+ type="button"
+ class="title-button"
+ onclick={startRename}
+ aria-label={$t("study.music.my_playlists_rename_aria")}
+ >
+ <span class="visually-hidden">{detail.summary.title}</span>
+ <span class="pen" aria-hidden="true">✎</span>
+ </button>
+ {/if}
+ </div>
+ </div>
+
+ {#if count === 0}
+ <EmptyPlaceholder
+ title={$t("study.music.playlist_empty")}
+ ctaLabel={$t("study.music.playlist_empty_cta")}
+ onCta={openAdd}
+ />
+ {:else}
+ <DraggableList
+ items={rowItems}
+ onReorder={onReorder}
+ item={(it, idx) => itemSnippet(it, idx)}
+ />
+ {/if}
+ {/if}
+</section>
+
+{#snippet itemSnippet(it: RowItem, idx: number)}
+ <TrackListRow
+ index={idx}
+ coverUrl={it.thumbnail_url}
+ title={it.title ?? it.video_id}
+ subtitle={it.channel_title}
+ durationText={null}
+ isPlaying={musicPlayer.currentTrack?.youtube_video_id === it.video_id}
+ onPlay={() => void playFromIndex(idx, false)}
+ >
+ {#snippet actions()}
+ <button
+ type="button"
+ class="row-remove"
+ title={$t("study.music.remove_from_playlist")}
+ aria-label={$t("study.music.remove_from_playlist_aria", { title: it.title ?? it.video_id })}
+ onclick={(e) => { e.stopPropagation(); void removeItem(it.video_id); }}
+ >×</button>
+ {/snippet}
+ </TrackListRow>
+{/snippet}
+
+{#if confirmingDelete && detail}
+ {@const count = detail.summary.item_count}
+ <div class="modal-bg" role="dialog" aria-modal="true">
+ <div class="modal">
+ <h2>{$t("study.music.my_playlists_delete_confirm_title")}</h2>
+ <p>
+ {count > 0
+ ? $t("study.music.my_playlists_delete_confirm_body", { count })
+ : $t("study.music.my_playlists_delete_confirm_empty")}
+ </p>
+ <div class="modal-actions">
+ <button type="button" class="ghost" onclick={() => (confirmingDelete = false)} disabled={pendingDelete}>
+ {$t("study.music.my_playlists_delete_confirm_cancel")}
+ </button>
+ <button type="button" class="danger" onclick={performDelete} disabled={pendingDelete}>
+ {$t("study.music.my_playlists_delete_confirm_action")}
+ </button>
+ </div>
+ </div>
+ </div>
+{/if}
+
+{#if addOpen}
+ <div class="modal-bg" role="dialog" aria-modal="true" aria-label={$t("study.music.add_to_playlist_modal_title")}>
+ <div class="modal modal-wide">
+ <header class="modal-head">
+ <h2>{$t("study.music.add_to_playlist_modal_title")}</h2>
+ <button type="button" class="close" onclick={closeAdd} aria-label={$t("study.music.add_to_playlist_close")}>×</button>
+ </header>
+ <input
+ type="text"
+ placeholder={$t("study.music.add_to_playlist_search_placeholder")}
+ bind:value={addQuery}
+ oninput={scheduleAddSearch}
+ autofocus
+ />
+ {#if addLoading}
+ <YoutubeSkeleton kind="row" count={4} />
+ {:else if addQuery.trim().length < 2}
+ <p class="hint">{$t("study.music.add_to_playlist_search_short")}</p>
+ {:else if addResults.length === 0}
+ <p class="hint">{$t("study.music.empty_search_no_results")}</p>
+ {:else}
+ <ul class="add-list">
+ {#each addResults as item (item.video_id)}
+ <li>
+ <button type="button" class="add-row" onclick={() => void addFromYoutube(item)}>
+ {#if item.thumbnail_url}
+ <img src={item.thumbnail_url} alt="" loading="lazy" />
+ {/if}
+ <div class="add-meta">
+ <span class="add-title">{item.title}</span>
+ <span class="add-channel">{item.channel_title ?? ""}</span>
+ </div>
+ <span class="add-cta" aria-hidden="true">+</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ </div>
+{/if}
+
+<style>
+ .page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: 16px 20px 32px;
+ }
+ .back {
+ align-self: flex-start;
+ padding: 6px 10px;
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ cursor: pointer;
+ font-size: 13px;
+ }
+ .back:hover { color: var(--secondary); }
+ .hero-wrap { position: relative; }
+ .title-overlay {
+ position: absolute;
+ top: 24px;
+ left: 240px;
+ right: 24px;
+ pointer-events: none;
+ }
+ .title-button {
+ pointer-events: auto;
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.85);
+ cursor: pointer;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 14px;
+ }
+ .title-button:hover { background: rgba(255, 255, 255, 0.1); }
+ .pen { font-size: 16px; }
+ .visually-hidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ }
+ .title-input {
+ pointer-events: auto;
+ width: 100%;
+ max-width: 480px;
+ padding: 8px 12px;
+ font-size: 32px;
+ font-weight: 800;
+ background: rgba(0, 0, 0, 0.35);
+ color: #fff;
+ border: 1px solid rgba(255, 255, 255, 0.25);
+ border-radius: 8px;
+ }
+ .hero-skel,
+ .list-skel { display: flex; flex-direction: column; gap: 8px; }
+ .row-remove {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ border: 0;
+ background: transparent;
+ color: rgba(255, 255, 255, 0.55);
+ cursor: pointer;
+ font-size: 18px;
+ line-height: 1;
+ }
+ .row-remove:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: #fff;
+ }
+ .modal-bg {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.55);
+ display: grid;
+ place-items: center;
+ z-index: 100;
+ padding: 24px;
+ }
+ .modal {
+ background: var(--background);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 16px;
+ padding: 22px;
+ width: min(420px, 100%);
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.5);
+ }
+ .modal-wide { width: min(560px, 100%); max-height: 80vh; }
+ .modal-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .modal h2 { margin: 0; font-size: 18px; font-weight: 800; color: var(--primary); }
+ .modal p { margin: 0; color: var(--secondary); font-size: 14px; line-height: 1.5; }
+ .modal input[type="text"] {
+ padding: 9px 12px;
+ border-radius: 8px;
+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);
+ background: color-mix(in oklab, var(--button) 30%, transparent);
+ color: var(--primary);
+ font: inherit;
+ font-size: 14px;
+ }
+ .close {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ cursor: pointer;
+ font-size: 20px;
+ line-height: 1;
+ }
+ .close:hover { color: var(--primary); }
+ .modal-actions {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+ margin-top: 4px;
+ }
+ .modal-actions button {
+ padding: 9px 18px;
+ border-radius: 999px;
+ border: 0;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+ }
+ .ghost { background: transparent; color: var(--secondary); }
+ .danger { background: #d33; color: #fff; }
+ .add-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ overflow-y: auto;
+ max-height: 48vh;
+ }
+ .add-row {
+ display: grid;
+ grid-template-columns: 88px 1fr auto;
+ gap: 10px;
+ align-items: center;
+ background: transparent;
+ border: 0;
+ padding: 4px;
+ text-align: left;
+ cursor: pointer;
+ border-radius: 8px;
+ width: 100%;
+ color: inherit;
+ }
+ .add-row:hover { background: rgba(255, 255, 255, 0.04); }
+ .add-row img {
+ width: 88px;
+ height: 50px;
+ object-fit: cover;
+ border-radius: 4px;
+ }
+ .add-meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+ .add-title {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--primary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .add-channel { font-size: 11px; color: var(--tertiary); }
+ .add-cta {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--on-accent, #000);
+ display: grid;
+ place-items: center;
+ font-size: 16px;
+ font-weight: 800;
+ }
+ .hint { color: var(--tertiary); font-size: 13px; }
+</style>
diff --git a/src/routes/study/music/youtube/search/+page.svelte b/src/routes/study/music/youtube/search/+page.svelte
new file mode 100644
index 00000000..1a9b6b64
--- /dev/null
+++ b/src/routes/study/music/youtube/search/+page.svelte
@@ -0,0 +1,515 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { goto } from "$app/navigation";
+ import { t } from "$lib/i18n";
+ import YoutubeShelf from "$lib/study-music-youtube-components/YoutubeShelf.svelte";
+ import YoutubeSkeleton from "$lib/study-music-youtube-components/YoutubeSkeleton.svelte";
+ import YoutubeError from "$lib/study-music-youtube-components/YoutubeError.svelte";
+ import ChipsRow from "$lib/study-music-components/ChipsRow.svelte";
+ import {
+ studyYoutubeSearch,
+ studyYoutubeTrending,
+ type YoutubeSearchItem,
+ type YoutubeSearchVideoItem,
+ type YoutubeSearchResultGroup,
+ type YoutubeSearchFilter,
+ } from "$lib/study-bridge";
+ import { playYoutubeVideoItem } from "$lib/study-music/youtube-play-helper";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+
+ let q = $state("");
+ let loading = $state(false);
+ let inputRef = $state<HTMLInputElement | null>(null);
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ let ytGroups = $state<YoutubeSearchResultGroup[]>([]);
+ let ytError = $state<string | null>(null);
+
+ let trending = $state<YoutubeSearchItem[]>([]);
+ let trendingLoading = $state(false);
+
+ type SortKey = "relevance" | "recent" | "views";
+ let activeFilter = $state<YoutubeSearchFilter>("all");
+ let activeSort = $state<SortKey>("relevance");
+ const HISTORY_KEY = "study.music.search.history.v1";
+ const HISTORY_MAX = 10;
+ let history = $state<string[]>([]);
+
+ function loadHistory() {
+ try {
+ const raw = localStorage.getItem(HISTORY_KEY);
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ if (Array.isArray(parsed)) {
+ history = parsed.filter((s) => typeof s === "string").slice(0, HISTORY_MAX);
+ }
+ }
+ } catch {
+ history = [];
+ }
+ }
+
+ function saveHistory() {
+ try {
+ localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
+ } catch {}
+ }
+
+ function pushHistory(query: string) {
+ const trimmed = query.trim();
+ if (!trimmed) return;
+ history = [trimmed, ...history.filter((h) => h !== trimmed)].slice(0, HISTORY_MAX);
+ saveHistory();
+ }
+
+ function removeFromHistory(query: string) {
+ history = history.filter((h) => h !== query);
+ saveHistory();
+ }
+
+ function clearHistory() {
+ history = [];
+ saveHistory();
+ }
+
+ function applyHistory(query: string) {
+ q = query;
+ if (timer) clearTimeout(timer);
+ void runSearch(q);
+ }
+
+ function applySort(items: YoutubeSearchItem[]): YoutubeSearchItem[] {
+ if (activeSort === "relevance") return items;
+ return [...items].sort((a, b) => {
+ if (a.kind !== "video" || b.kind !== "video") return 0;
+ if (activeSort === "views") {
+ const av = parseViewCount(a.view_count_text);
+ const bv = parseViewCount(b.view_count_text);
+ return bv - av;
+ }
+ if (activeSort === "recent") {
+ const ap = parsePublishedRank(a.published_time_text);
+ const bp = parsePublishedRank(b.published_time_text);
+ return ap - bp;
+ }
+ return 0;
+ });
+ }
+
+ function parseViewCount(text: string | null | undefined): number {
+ if (!text) return 0;
+ const cleaned = text.replace(/[^\d.,KMBkmb]/g, "").trim();
+ const m = cleaned.match(/^([\d.,]+)([KMBkmb])?/);
+ if (!m) return 0;
+ const n = parseFloat((m[1] ?? "0").replace(/,/g, ""));
+ const suffix = (m[2] ?? "").toLowerCase();
+ const mult = suffix === "k" ? 1e3 : suffix === "m" ? 1e6 : suffix === "b" ? 1e9 : 1;
+ return n * mult;
+ }
+
+ function parsePublishedRank(text: string | null | undefined): number {
+ if (!text) return Number.MAX_SAFE_INTEGER;
+ const m = text.match(/(\d+)\s*(second|minute|hour|day|week|month|year)/i);
+ if (!m) return Number.MAX_SAFE_INTEGER;
+ const n = parseInt(m[1] ?? "0", 10);
+ const unit = (m[2] ?? "").toLowerCase();
+ const mult =
+ unit === "second" ? 1 :
+ unit === "minute" ? 60 :
+ unit === "hour" ? 3600 :
+ unit === "day" ? 86400 :
+ unit === "week" ? 604800 :
+ unit === "month" ? 2629800 :
+ 31557600;
+ return n * mult;
+ }
+
+ async function loadTrending() {
+ trendingLoading = true;
+ try {
+ const res = await studyYoutubeTrending({ category: "now" });
+ const flat: YoutubeSearchItem[] = [];
+ for (const it of res.items ?? []) {
+ if (it.kind === "shelf") {
+ for (const s of it.items) flat.push(s);
+ } else {
+ flat.push(it);
+ }
+ }
+ trending = flat.slice(0, 24);
+ } catch (e) {
+ console.warn("[trending] failed", e);
+ } finally {
+ trendingLoading = false;
+ }
+ }
+
+ function flattenVideoItems(groups: YoutubeSearchResultGroup[]): YoutubeSearchVideoItem[] {
+ const out: YoutubeSearchVideoItem[] = [];
+ for (const g of groups) {
+ for (const item of g.items) {
+ if (item.kind === "video") out.push(item);
+ else if (item.kind === "shelf") {
+ for (const s of item.items) if (s.kind === "video") out.push(s);
+ }
+ }
+ }
+ return out;
+ }
+
+ function openYoutubePlaylist(playlistId: string) {
+ const route = playlistId.startsWith("OLAK") ? "album" : "playlist";
+ void goto(`/study/music/youtube/${route}/${encodeURIComponent(playlistId)}`);
+ }
+
+ async function playFromYouTube(videoId: string) {
+ const queue = flattenVideoItems(ytGroups);
+ const item = queue.find((v) => v.video_id === videoId);
+ if (!item) return;
+ try {
+ await playYoutubeVideoItem(item, queue);
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ async function runSearch(query: string) {
+ if (!query.trim()) {
+ ytGroups = [];
+ ytError = null;
+ loading = false;
+ return;
+ }
+ loading = true;
+ ytError = null;
+ try {
+ const ytRes = await studyYoutubeSearch({ query, filter: activeFilter });
+ const raw = ytRes.groups ?? [];
+ if (activeSort !== "relevance") {
+ ytGroups = raw.map((g) => ({ ...g, items: applySort(g.items) }));
+ } else {
+ ytGroups = raw;
+ }
+ } catch (e) {
+ ytError = e instanceof Error ? e.message : String(e);
+ ytGroups = [];
+ } finally {
+ loading = false;
+ }
+ }
+
+ function onInput(e: Event) {
+ q = (e.target as HTMLInputElement).value;
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => runSearch(q), 200);
+ }
+
+ function onSearchSubmit(e: Event) {
+ e.preventDefault();
+ const trimmed = q.trim();
+ if (!trimmed) return;
+ if (timer) clearTimeout(timer);
+ pushHistory(trimmed);
+ void runSearch(trimmed);
+ }
+
+ function setFilter(id: string) {
+ activeFilter = id as YoutubeSearchFilter;
+ if (activeFilter === "all" && activeSort !== "relevance") {
+ activeSort = "relevance";
+ }
+ if (q.trim()) void runSearch(q);
+ }
+
+ function setSort(key: SortKey) {
+ activeSort = key;
+ if (q.trim()) void runSearch(q);
+ }
+
+ onMount(() => {
+ inputRef?.focus();
+ void loadTrending();
+ loadHistory();
+ return () => {
+ if (timer) clearTimeout(timer);
+ };
+ });
+</script>
+
+<section class="search-page">
+ <header class="head">
+ <form class="search-box" onsubmit={onSearchSubmit}>
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="11" cy="11" r="7"/>
+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>
+ </svg>
+ <input
+ bind:this={inputRef}
+ type="search"
+ value={q}
+ oninput={onInput}
+ placeholder={$t("study.music.youtube.search_placeholder")}
+ autocomplete="off"
+ />
+ {#if q}
+ <button
+ type="button"
+ class="clear"
+ onclick={() => { q = ""; ytGroups = []; }}
+ aria-label={$t("study.common.clear") as string}
+ >×</button>
+ {/if}
+ </form>
+
+ <div class="filters">
+ <ChipsRow
+ ariaLabel={$t("study.music.youtube.search_filter_aria") as string}
+ chips={[
+ { id: "all", label: $t("study.music.youtube.search_filter_all") as string },
+ { id: "music", label: $t("study.music.youtube.search_filter_music") as string },
+ { id: "videos", label: $t("study.music.youtube.search_filter_videos") as string },
+ { id: "channels", label: $t("study.music.youtube.search_filter_channels") as string },
+ { id: "playlists", label: $t("study.music.youtube.search_filter_playlists") as string },
+ ]}
+ activeId={activeFilter}
+ onSelect={setFilter}
+ />
+ {#if activeFilter !== "all"}
+ <label class="sort-label">
+ <span class="sr-only">{$t("study.music.youtube.search_sort_aria")}</span>
+ <select class="sort-select" value={activeSort} onchange={(e) => setSort((e.currentTarget as HTMLSelectElement).value as SortKey)}>
+ <option value="relevance">{$t("study.music.youtube.search_sort_relevance")}</option>
+ <option value="recent">{$t("study.music.youtube.search_sort_recent")}</option>
+ <option value="views">{$t("study.music.youtube.search_sort_views")}</option>
+ </select>
+ </label>
+ {/if}
+ </div>
+
+ {#if history.length > 0 && !q.trim()}
+ <div class="history">
+ <div class="history-head">
+ <span class="history-label">{$t("study.music.youtube.search_history_label")}</span>
+ <button type="button" class="history-clear" onclick={clearHistory}>
+ {$t("study.music.youtube.search_history_clear")}
+ </button>
+ </div>
+ <ul class="history-list">
+ {#each history as item (item)}
+ <li class="history-pill">
+ <button type="button" class="history-text" onclick={() => applyHistory(item)}>
+ {item}
+ </button>
+ <button
+ type="button"
+ class="history-x"
+ aria-label={$t("study.music.youtube.search_history_remove_aria", { query: item }) as string}
+ onclick={() => removeFromHistory(item)}
+ >×</button>
+ </li>
+ {/each}
+ </ul>
+ </div>
+ {/if}
+ </header>
+
+ {#if !q.trim()}
+ {#if trendingLoading}
+ <section class="block">
+ <h3 class="block-title">{$t("study.music.youtube.shelf_trending")}</h3>
+ <div class="grid-skel">
+ <YoutubeSkeleton kind="card" count={3} />
+ </div>
+ </section>
+ {:else if trending.length > 0}
+ <YoutubeShelf
+ title={$t("study.music.youtube.shelf_trending")}
+ items={trending}
+ onPlay={playFromYouTube}
+ onPlaylistOpen={openYoutubePlaylist}
+ minCard={200}
+ />
+ {:else}
+ <div class="empty">
+ <p>{$t("study.music.youtube.search_hint")}</p>
+ </div>
+ {/if}
+ {:else if loading}
+ <section class="block">
+ <div class="grid-skel">
+ <YoutubeSkeleton kind="card" count={4} />
+ </div>
+ </section>
+ {:else if ytGroups.length === 0 && !ytError}
+ <div class="empty">
+ <p>{$t("study.music.empty_results")}</p>
+ </div>
+ {:else}
+ {#if ytError}
+ <YoutubeError
+ error={ytError}
+ onRetry={() => { ytError = null; void runSearch(q); }}
+ />
+ {:else if ytGroups.length > 0}
+ {#each ytGroups as group, gi (gi)}
+ <YoutubeShelf
+ title={group.title ?? ($t("study.music.youtube.shelf_group") as string)}
+ items={group.items}
+ onPlay={playFromYouTube}
+ onPlaylistOpen={openYoutubePlaylist}
+ minCard={210}
+ />
+ {/each}
+ {/if}
+ {/if}
+</section>
+
+<style>
+ .search-page { display: flex; flex-direction: column; gap: 20px; }
+ .search-box {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 14px;
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 999px;
+ width: min(100%, 480px);
+ }
+ .search-box:focus-within { border-color: var(--accent); }
+ .search-box svg { color: var(--tertiary); flex-shrink: 0; }
+ .search-box input {
+ flex: 1;
+ border: 0;
+ background: transparent;
+ color: var(--secondary);
+ font-family: inherit;
+ font-size: 14px;
+ outline: none;
+ min-width: 0;
+ }
+ .clear {
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-radius: 50%;
+ color: var(--tertiary);
+ font-size: 16px;
+ line-height: 1;
+ cursor: pointer;
+ }
+ .clear:hover { color: var(--secondary); }
+ .empty { padding: 48px 24px; text-align: center; color: var(--tertiary); font-size: 14px; }
+ .block { display: flex; flex-direction: column; gap: 10px; }
+ .block-title { margin: 0; font-size: 16px; font-weight: 700; color: var(--secondary); }
+ .grid-skel {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
+ gap: 18px 14px;
+ }
+ .head { display: flex; flex-direction: column; gap: 12px; }
+ .filters {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+ .sort-label {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--tertiary);
+ font-size: 12px;
+ }
+ .sort-select {
+ background: color-mix(in oklab, var(--button) 60%, transparent);
+ color: var(--secondary);
+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);
+ border-radius: 999px;
+ padding: 6px 10px;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .sort-select:hover { border-color: var(--accent); }
+ .sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+ }
+ .history {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .history-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .history-label {
+ color: var(--tertiary);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+ .history-clear {
+ background: transparent;
+ border: 0;
+ color: var(--tertiary);
+ font: inherit;
+ font-size: 11px;
+ padding: 0;
+ cursor: pointer;
+ text-decoration: underline;
+ }
+ .history-clear:hover { color: var(--secondary); }
+ .history-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .history-pill {
+ display: inline-flex;
+ align-items: center;
+ background: color-mix(in oklab, var(--button) 50%, transparent);
+ border: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);
+ border-radius: 999px;
+ overflow: hidden;
+ }
+ .history-pill:hover { border-color: var(--accent); }
+ .history-text {
+ background: transparent;
+ border: 0;
+ padding: 6px 4px 6px 12px;
+ color: var(--secondary);
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ }
+ .history-x {
+ background: transparent;
+ border: 0;
+ padding: 4px 10px 4px 4px;
+ color: var(--tertiary);
+ font: inherit;
+ font-size: 14px;
+ cursor: pointer;
+ line-height: 1;
+ }
+ .history-x:hover { color: var(--secondary); }
+</style>
diff --git a/src/routes/study/settings/+page.svelte b/src/routes/study/settings/+page.svelte
index 05091d1f..3f68b12d 100644
--- a/src/routes/study/settings/+page.svelte
+++ b/src/routes/study/settings/+page.svelte
@@ -15,6 +15,8 @@
import LibrarySettingsTab from "$lib/study-components/settings/LibrarySettingsTab.svelte";
import MaintenanceTab from "$lib/study-components/settings/MaintenanceTab.svelte";
import PetsSettingsTab from "$lib/study-components/settings/PetsSettingsTab.svelte";
+ import MusicSettingsTab from "$lib/study-components/settings/MusicSettingsTab.svelte";
+ import DiagnosticTab from "$lib/study-components/settings/DiagnosticTab.svelte";
import NotesSettingsTab from "$lib/study-components/notes/NotesSettingsTab.svelte";
type TabKey =
@@ -23,20 +25,24 @@
| "audio"
| "behavior"
| "library"
+ | "music"
+ | "diagnostic"
| "notes"
| "maintenance"
| "pets";
- const TABS: { key: TabKey; label: string }[] = [
+ const TABS = $derived<{ key: TabKey; label: string }[]>([
{ key: "player", label: "Player" },
{ key: "subtitles", label: "Legendas" },
{ key: "audio", label: "Áudio" },
{ key: "behavior", label: "Comportamento" },
{ key: "library", label: "Biblioteca" },
+ { key: "music", label: "Música" },
+ { key: "diagnostic", label: $t("study.settings.tab_diagnostic") as string },
{ key: "notes", label: "Notas" },
{ key: "maintenance", label: "Manutenção" },
{ key: "pets", label: "Pets" },
- ];
+ ]);
let activeTab = $state<TabKey>("player");
let settings = $state<StudySettings>({});
@@ -158,15 +164,15 @@
<div class="status">
{#if savingState === "saving"}
<span class="dot saving" aria-hidden="true"></span>
- <span>Salvando…</span>
+ <span>{$t("study.settings.saving")}</span>
{:else if savingState === "saved"}
<span class="dot saved" aria-hidden="true"></span>
- <span>Salvo</span>
+ <span>{$t("study.settings.saved")}</span>
{/if}
</div>
</header>
- <nav class="tabs" role="tablist" aria-label="Categorias">
+ <nav class="tabs" role="tablist" aria-label={$t("study.settings.categories_aria") as string}>
{#each TABS as tab (tab.key)}
<button
type="button"
@@ -196,6 +202,10 @@
<BehaviorSettingsTab {settings} onPatch={patchSettings} />
{:else if activeTab === "library"}
<LibrarySettingsTab {settings} onPatch={patchSettings} />
+ {:else if activeTab === "music"}
+ <MusicSettingsTab {settings} onPatch={patchSettings} />
+ {:else if activeTab === "diagnostic"}
+ <DiagnosticTab />
{:else if activeTab === "notes"}
<NotesSettingsTab onToast={showToast} />
{:else if activeTab === "maintenance"}