Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
Refactor layout styles for notes and journal pages; update height handling
Tonhof6368ea2cf05
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 13804b2a..c4079f8b 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -607,7 +607,7 @@ checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"dependencies = ["byteorder","fnv",- "uuid",+ "uuid 1.21.0",][[package]]@@ -1092,6 +1092,19 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "discord-rich-presence"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a75db747ecd252c01bfecaf709b07fcb4c634adf0edb5fed47bc9c3052e7076b"+dependencies = [+ "serde",+ "serde_derive",+ "serde_json",+ "serde_repr",+ "uuid 0.8.2",+]+[[package]]name = "dispatch"version = "0.2.0"@@ -2709,7 +2722,7 @@ dependencies = ["tracing","url","urlencoding",- "uuid",+ "uuid 1.21.0","walkdir",]@@ -3522,7 +3535,7 @@ dependencies = [[[package]]name = "omniget"-version = "0.5.2"+version = "0.6.0"dependencies = ["aes","anyhow",@@ -3531,6 +3544,7 @@ dependencies = ["cbc","chrono","dirs 6.0.0",+ "discord-rich-presence","filetime","futures","libloading 0.8.9",@@ -3538,6 +3552,7 @@ dependencies = ["m3u8-rs","omniget-core","omniget-plugin-sdk",+ "once_cell","open","rand 0.10.0","regex",@@ -3568,7 +3583,7 @@ dependencies = ["unicode-normalization","url","urlencoding",- "uuid",+ "uuid 1.21.0","webview2-com","which","windows",@@ -3606,7 +3621,7 @@ dependencies = ["unicode-normalization","url","urlencoding",- "uuid",+ "uuid 1.21.0","xz2","zip 2.4.2",]@@ -4808,7 +4823,7 @@ dependencies = ["serde","serde_json","url",- "uuid",+ "uuid 1.21.0",][[package]]@@ -5529,7 +5544,7 @@ dependencies = ["thiserror 2.0.18","time","url",- "uuid",+ "uuid 1.21.0","walkdir",]@@ -5869,7 +5884,7 @@ dependencies = ["toml 0.9.12+spec-1.1.0","url","urlpattern",- "uuid",+ "uuid 1.21.0","walkdir",]@@ -6534,6 +6549,15 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]+name = "uuid"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"+dependencies = [+ "getrandom 0.2.17",+]+[[package]]name = "uuid"version = "1.21.0"@@ -7737,7 +7761,7 @@ dependencies = ["serde_repr","tracing","uds_windows",- "uuid",+ "uuid 1.21.0","windows-sys 0.61.2","winnow 0.7.14","zbus_macros",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 568d1167..fcbf00e4 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -4,7 +4,7 @@ resolver = "2"[package]name = "omniget"-version = "0.5.2"+version = "0.6.0"description = "A Tauri App"authors = ["you"]edition = "2021"@@ -57,6 +57,8 @@ omniget-plugin-sdk = { path = "omniget-plugin-sdk" }libloading = "0.8"which = "7"librqbit = "8.1.1"+discord-rich-presence = "0.2"+once_cell = "1"[target.'cfg(windows)'.dependencies]webview2-com = "0.38"diff --git a/src-tauri/omniget-core/src/core/direct_downloader.rs b/src-tauri/omniget-core/src/core/direct_downloader.rsindex fc5fccb5..a13848e1 100644--- a/src-tauri/omniget-core/src/core/direct_downloader.rs+++ b/src-tauri/omniget-core/src/core/direct_downloader.rs@@ -1,6 +1,5 @@use std::collections::HashMap;use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, OnceLock};use std::time::Duration;@@ -10,6 +9,10 @@ use futures::StreamExt;use tokio::sync::{mpsc, Semaphore};use tokio_util::sync::CancellationToken;+use crate::core::http_fetcher::{+ get_global_max_concurrent_segments, HttpFetcher, HttpFetcherConfig,+};+const CHUNK_TIMEOUT: Duration = Duration::from_secs(45);const MAX_RETRIES: u32 = 3;const CHUNK_SIZE: u64 = 10 * 1024 * 1024;@@ -166,35 +169,29 @@ async fn download_attempt(probe.accept_ranges && probe.content_length.is_some_and(|s| s > CHUNK_THRESHOLD);if use_chunked {- let total = probe.content_length.unwrap();- let _ = std::fs::remove_file(&part_path);- if let Err(chunked_err) = download_chunked(- client,- url,- &part_path,- total,- progress_tx,- headers.clone(),- cancel,- )- .await- {- if is_fatal_error(&chunked_err) {- return Err(chunked_err);+ match run_http_fetcher(client, url, output, progress_tx, headers.clone(), cancel).await {+ Ok(size) => return Ok(size),+ Err(fetch_err) => {+ if is_fatal_error(&fetch_err) {+ return Err(fetch_err);+ }+ let _ = std::fs::remove_file(&part_path);+ tracing::warn!(+ "[direct] http_fetcher failed, falling back to single stream: {}",+ fetch_err+ );+ download_single_stream(+ client,+ url,+ &part_path,+ 0,+ probe.content_length,+ progress_tx,+ headers,+ cancel,+ )+ .await?;}- let _ = std::fs::remove_file(&part_path);- tracing::warn!("[direct] chunked failed, falling back: {}", chunked_err);- download_single_stream(- client,- url,- &part_path,- 0,- probe.content_length,- progress_tx,- headers,- cancel,- )- .await?;}} else {let existing = match std::fs::metadata(&part_path) {@@ -233,205 +230,34 @@ async fn download_attempt(Ok(size)}-async fn download_chunked(+async fn run_http_fetcher(client: &reqwest::Client,url: &str,- part_path: &Path,- total_size: u64,+ output: &Path,progress_tx: &mpsc::Sender<f64>,headers: Option<reqwest::header::HeaderMap>,cancel: Option<&CancellationToken>,-) -> anyhow::Result<()> {- let file = std::fs::File::create(part_path)?;- file.set_len(total_size)?;- drop(file);-- let num_chunks = total_size.div_ceil(CHUNK_SIZE);- let downloaded = Arc::new(AtomicU64::new(0));- let semaphore = Arc::new(Semaphore::new(MAX_PARALLEL));- let cancel_token = match cancel {- Some(ct) => ct.clone(),- None => CancellationToken::new(),+) -> anyhow::Result<u64> {+ let concurrent = get_global_max_concurrent_segments()+ .unwrap_or(MAX_PARALLEL)+ .clamp(1, 32);+ let cfg = HttpFetcherConfig {+ min_size_for_chunked: 0,+ concurrent_segments: concurrent,+ segment_size_hint: CHUNK_SIZE,+ ..Default::default()};- let mut join_set = tokio::task::JoinSet::new();- for i in 0..num_chunks {- let start = i * CHUNK_SIZE;- let end = ((i + 1) * CHUNK_SIZE).min(total_size) - 1;- let client = client.clone();- let url = url.to_string();- let path = part_path.to_owned();- let sem = semaphore.clone();- let dl = downloaded.clone();- let ptx = progress_tx.clone();- let ct = cancel_token.clone();- let hdrs = headers.clone();-- join_set.spawn(async move {- let _permit = sem.acquire().await.unwrap();- if ct.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }- download_chunk(- &client, &url, &path, start, end, &dl, total_size, &ptx, hdrs, &ct,- )- .await- });- }-- while let Some(result) = join_set.join_next().await {- if cancel_token.is_cancelled() {- join_set.abort_all();- return Err(anyhow!("Download cancelled"));- }- match result {- Ok(Ok(())) => {}- Ok(Err(e)) => {- join_set.abort_all();- return Err(e);- }- Err(e) => {- join_set.abort_all();- return Err(anyhow!("Chunk task failed: {:?}", e));- }- }- }-- Ok(())-}--#[allow(clippy::too_many_arguments)]-async fn download_chunk(- client: &reqwest::Client,- url: &str,- part_path: &Path,- start: u64,- end: u64,- downloaded: &AtomicU64,- total_size: u64,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: &CancellationToken,-) -> anyhow::Result<()> {- let mut last_err = None;-- for attempt in 0..3u32 {- if cancel.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }-- if attempt > 0 {- tokio::time::sleep(Duration::from_millis(1000 * (attempt as u64))).await;- }-- match download_chunk_attempt(- client,- url,- part_path,- start,- end,- downloaded,- total_size,- progress_tx,- headers.clone(),- cancel,- )- .await- {- Ok(()) => return Ok(()),- Err(e) => {- if is_fatal_error(&e) {- return Err(e);- }- let chunk_bytes = end - start + 1;- let current = downloaded.load(Ordering::Relaxed);- downloaded.fetch_sub(chunk_bytes.min(current), Ordering::Relaxed);- tracing::warn!(- "[direct] chunk {}-{} attempt {}/3 failed: {}",- start,- end,- attempt + 1,- e- );- last_err = Some(e);- }- }- }-- Err(last_err.unwrap_or_else(|| anyhow!("Chunk failed after 3 attempts")))-}--#[allow(clippy::too_many_arguments)]-async fn download_chunk_attempt(- client: &reqwest::Client,- url: &str,- part_path: &Path,- start: u64,- end: u64,- downloaded: &AtomicU64,- total_size: u64,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: &CancellationToken,-) -> anyhow::Result<()> {- let mut request = client.get(url);+ let mut fetcher = HttpFetcher::new(client.clone(), url.to_string(), output.to_path_buf())+ .with_config(cfg);if let Some(h) = headers {- request = request.headers(h);+ fetcher = fetcher.with_headers(h);}- request = request.header("Range", format!("bytes={}-{}", start, end));-- let response = tokio::time::timeout(Duration::from_secs(30), request.send())- .await- .map_err(|_| anyhow!("Timeout connecting to chunk"))??;-- let status = response.status();- if status != reqwest::StatusCode::PARTIAL_CONTENT {- if status.is_success() {- return Err(anyhow!("Server did not support Range request (HTTP 200)"));- }- return Err(anyhow!("HTTP {} downloading chunk", status));+ if let Some(c) = cancel {+ fetcher = fetcher.with_cancel(c.clone());}-- use std::io::{Seek, Write};- let mut file = std::fs::OpenOptions::new().write(true).open(part_path)?;- file.seek(std::io::SeekFrom::Start(start))?;-- let expected_size = end - start + 1;- let mut chunk_written: u64 = 0;- let mut stream = response.bytes_stream();-- loop {- if cancel.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }-- let chunk_result = tokio::time::timeout(CHUNK_TIMEOUT, stream.next()).await;- match chunk_result {- Ok(Some(Ok(data))) => {- file.write_all(&data)- .map_err(|e| anyhow!("Write error (disk full?): {}", e))?;- chunk_written += data.len() as u64;- let total_dl =- downloaded.fetch_add(data.len() as u64, Ordering::Relaxed) + data.len() as u64;- let percent = (total_dl as f64 / total_size as f64) * 100.0;- let _ = progress_tx.send(percent.min(99.9)).await;- }- Ok(Some(Err(e))) => return Err(anyhow!("Chunk stream error: {}", e)),- Ok(None) => break,- Err(_) => return Err(anyhow!("Chunk timeout — no data received for 30 seconds")),- }- }-- if chunk_written != expected_size {- return Err(anyhow!(- "Incomplete chunk: expected {} bytes, got {}",- expected_size,- chunk_written- ));- }-- file.flush()?;- Ok(())+ let result = fetcher.download(progress_tx.clone()).await?;+ Ok(result.bytes_written)}#[allow(clippy::too_many_arguments)]diff --git a/src-tauri/omniget-core/src/core/events.rs b/src-tauri/omniget-core/src/core/events.rsindex a3ad992a..55adec77 100644--- a/src-tauri/omniget-core/src/core/events.rs+++ b/src-tauri/omniget-core/src/core/events.rs@@ -24,6 +24,8 @@ pub struct QueueItemInfo {pub file_path: Option<String>,pub file_size_bytes: Option<u64>,pub file_count: Option<u32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,}#[derive(Clone, Serialize)]@@ -36,6 +38,8 @@ pub struct QueueItemProgress {pub downloaded_bytes: u64,pub total_bytes: Option<u64>,pub phase: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,}pub trait EventEmitter: Send + Sync + Clone + 'static {diff --git a/src-tauri/omniget-core/src/core/http_fetcher.rs b/src-tauri/omniget-core/src/core/http_fetcher.rsnew file mode 100644index 00000000..9816ec0e--- /dev/null+++ b/src-tauri/omniget-core/src/core/http_fetcher.rs@@ -0,0 +1,1245 @@+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::{Duration, SystemTime};++use anyhow::anyhow;+use futures::StreamExt;+use serde::{Deserialize, Serialize};+use tokio::io::{AsyncSeekExt, AsyncWriteExt};+use tokio::sync::{mpsc, Mutex};+use tokio_util::sync::CancellationToken;++const SEG_PENDING: u8 = 0;+const SEG_RUNNING: u8 = 1;+const SEG_DONE: u8 = 2;+const SEG_FAILED: u8 = 3;++const DEFAULT_MIN_SIZE_FOR_CHUNKED: u64 = 50 * 1024 * 1024;+const DEFAULT_SEGMENT_SIZE_HINT: u64 = 4 * 1024 * 1024;+const DEFAULT_CONCURRENT_SEGMENTS: usize = 8;+const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;+const DEFAULT_READ_TIMEOUT_SECS: u64 = 30;+const DEFAULT_MAX_RETRIES_PER_SEGMENT: u32 = 3;+const DEFAULT_STEAL_THRESHOLD_SECS: u64 = 3;+const DEFAULT_STEAL_MIN_CHUNK_SIZE: u64 = 512 * 1024;+const DEFAULT_RESUME_SAVE_INTERVAL_SECS: u64 = 2;++static GLOBAL_MAX_CONCURRENT_SEGMENTS: AtomicUsize = AtomicUsize::new(0);++pub fn set_global_max_concurrent_segments(n: usize) {+ GLOBAL_MAX_CONCURRENT_SEGMENTS.store(n, Ordering::Relaxed);+}++pub fn get_global_max_concurrent_segments() -> Option<usize> {+ let v = GLOBAL_MAX_CONCURRENT_SEGMENTS.load(Ordering::Relaxed);+ if v == 0 {+ None+ } else {+ Some(v)+ }+}++#[derive(Clone)]+pub struct HttpFetcherConfig {+ pub concurrent_segments: usize,+ pub segment_size_hint: u64,+ pub min_size_for_chunked: u64,+ pub connect_timeout: Duration,+ pub read_timeout: Duration,+ pub max_retries_per_segment: u32,+ pub steal_threshold: Duration,+ pub steal_min_chunk_size: u64,+ pub use_sidecar_resume: bool,+ pub resume_save_interval: Duration,+}++impl Default for HttpFetcherConfig {+ fn default() -> Self {+ Self {+ concurrent_segments: DEFAULT_CONCURRENT_SEGMENTS,+ segment_size_hint: DEFAULT_SEGMENT_SIZE_HINT,+ min_size_for_chunked: DEFAULT_MIN_SIZE_FOR_CHUNKED,+ connect_timeout: Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS),+ read_timeout: Duration::from_secs(DEFAULT_READ_TIMEOUT_SECS),+ max_retries_per_segment: DEFAULT_MAX_RETRIES_PER_SEGMENT,+ steal_threshold: Duration::from_secs(DEFAULT_STEAL_THRESHOLD_SECS),+ steal_min_chunk_size: DEFAULT_STEAL_MIN_CHUNK_SIZE,+ use_sidecar_resume: true,+ resume_save_interval: Duration::from_secs(DEFAULT_RESUME_SAVE_INTERVAL_SECS),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResumeSegment {+ pub begin: u64,+ pub end: u64,+ pub downloaded: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResumeState {+ pub r#type: String,+ pub url_hash: String,+ pub total_bytes: u64,+ pub segments: Vec<ResumeSegment>,+}++#[derive(Debug, Clone)]+pub struct HttpFetcherResult {+ pub bytes_written: u64,+}++#[derive(Debug)]+struct Segment {+ id: usize,+ begin: u64,+ end_ceiling: AtomicU64,+ downloaded: AtomicU64,+ state: AtomicU8,+ last_progress_unix_nanos: AtomicU64,+ speed_baseline_unix_nanos: AtomicU64,+ speed_baseline_downloaded: AtomicU64,+}++impl Segment {+ fn new(id: usize, begin: u64, end: u64, downloaded: u64) -> Self {+ Self {+ id,+ begin,+ end_ceiling: AtomicU64::new(end),+ downloaded: AtomicU64::new(downloaded),+ state: AtomicU8::new(SEG_PENDING),+ last_progress_unix_nanos: AtomicU64::new(now_unix_nanos()),+ speed_baseline_unix_nanos: AtomicU64::new(now_unix_nanos()),+ speed_baseline_downloaded: AtomicU64::new(downloaded),+ }+ }++ fn remaining(&self) -> u64 {+ let end = self.end_ceiling.load(Ordering::Relaxed);+ let dl = self.downloaded.load(Ordering::Relaxed);+ let total = end.saturating_sub(self.begin) + 1;+ total.saturating_sub(dl)+ }++ fn estimated_seconds_remaining(&self, fallback_large: bool) -> u64 {+ let now = now_unix_nanos();+ let baseline_t = self.speed_baseline_unix_nanos.load(Ordering::Relaxed);+ let baseline_d = self.speed_baseline_downloaded.load(Ordering::Relaxed);+ let cur_d = self.downloaded.load(Ordering::Relaxed);+ let elapsed_ns = now.saturating_sub(baseline_t);+ if elapsed_ns < 1_000_000_000 || cur_d <= baseline_d {+ if fallback_large {+ u64::MAX / 2+ } else {+ 0+ }+ } else {+ let bytes_per_sec = (cur_d - baseline_d) as u128 * 1_000_000_000u128 / elapsed_ns as u128;+ if bytes_per_sec == 0 {+ u64::MAX / 2+ } else {+ (self.remaining() as u128 / bytes_per_sec) as u64+ }+ }+ }+}++fn now_unix_nanos() -> u64 {+ SystemTime::now()+ .duration_since(SystemTime::UNIX_EPOCH)+ .map(|d| d.as_nanos() as u64)+ .unwrap_or(0)+}++pub struct HttpFetcher {+ client: reqwest::Client,+ url: String,+ output_path: PathBuf,+ headers: Option<reqwest::header::HeaderMap>,+ cancel: Option<CancellationToken>,+ config: HttpFetcherConfig,+}++impl HttpFetcher {+ pub fn new(client: reqwest::Client, url: String, output_path: PathBuf) -> Self {+ Self {+ client,+ url,+ output_path,+ headers: None,+ cancel: None,+ config: HttpFetcherConfig::default(),+ }+ }++ pub fn with_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {+ self.headers = Some(headers);+ self+ }++ pub fn with_cancel(mut self, cancel: CancellationToken) -> Self {+ self.cancel = Some(cancel);+ self+ }++ pub fn with_config(mut self, config: HttpFetcherConfig) -> Self {+ self.config = config;+ self+ }++ pub fn output_path(&self) -> &Path {+ &self.output_path+ }++ pub async fn download(+ &self,+ progress_tx: mpsc::Sender<f64>,+ ) -> anyhow::Result<HttpFetcherResult> {+ let probe = self.probe().await?;++ let part_path = part_path_for(&self.output_path);+ if let Some(parent) = self.output_path.parent() {+ tokio::fs::create_dir_all(parent).await.ok();+ }++ let total = match probe.content_length {+ Some(t) if t > 0 => t,+ _ => return self.download_streaming(&part_path, &progress_tx).await,+ };++ if !probe.accept_ranges || total < self.config.min_size_for_chunked {+ return self.download_streaming(&part_path, &progress_tx).await;+ }++ let resume_path = sidecar_path_for(&part_path);+ let url_hash = url_hash(&self.url);++ let initial_segments = if self.config.use_sidecar_resume {+ load_resume_state(&resume_path)+ .filter(|st| st.r#type == "http_segmented" && st.total_bytes == total && st.url_hash == url_hash)+ .map(|st| st.segments)+ } else {+ None+ };++ let segments = match initial_segments {+ Some(segs) if !segs.is_empty() => segs,+ _ => plan_segments(total, self.config.segment_size_hint, self.config.concurrent_segments),+ };++ ensure_part_file(&part_path, total).await?;++ let result = self+ .download_chunked(&part_path, total, segments, &resume_path, &url_hash, &progress_tx)+ .await;++ match result {+ Ok(()) => {+ tokio::fs::rename(&part_path, &self.output_path)+ .await+ .map_err(|e| anyhow!("rename .part to final failed: {}", e))?;+ if self.config.use_sidecar_resume {+ let _ = tokio::fs::remove_file(&resume_path).await;+ }+ let _ = progress_tx.send(100.0).await;+ let bytes = tokio::fs::metadata(&self.output_path)+ .await+ .map(|m| m.len())+ .unwrap_or(total);+ Ok(HttpFetcherResult { bytes_written: bytes })+ }+ Err(e) => Err(e),+ }+ }++ async fn probe(&self) -> anyhow::Result<ProbeResult> {+ let mut req = self.client.head(&self.url);+ if let Some(h) = &self.headers {+ req = req.headers(h.clone());+ }+ let resp = match tokio::time::timeout(self.config.connect_timeout * 2, req.send()).await {+ Ok(Ok(r)) => r,+ Ok(Err(e)) => return Err(anyhow!("HEAD probe failed: {}", e)),+ Err(_) => return Err(anyhow!("HEAD probe timed out")),+ };++ if !resp.status().is_success() {+ return Err(anyhow!("HEAD returned HTTP {}", resp.status()));+ }+ let content_length = resp.content_length();+ let accept_ranges = resp+ .headers()+ .get(reqwest::header::ACCEPT_RANGES)+ .and_then(|v| v.to_str().ok())+ .map(|v| v.contains("bytes"))+ .unwrap_or(false);+ Ok(ProbeResult {+ content_length,+ accept_ranges,+ })+ }++ async fn download_streaming(+ &self,+ part_path: &Path,+ progress_tx: &mpsc::Sender<f64>,+ ) -> anyhow::Result<HttpFetcherResult> {+ let _ = tokio::fs::remove_file(part_path).await;++ let mut req = self.client.get(&self.url);+ if let Some(h) = &self.headers {+ req = req.headers(h.clone());+ }+ let resp = req.send().await?;+ if !resp.status().is_success() {+ return Err(anyhow!("HTTP {} downloading {}", resp.status(), self.url));+ }+ let total = resp.content_length();++ let mut file = tokio::fs::File::create(part_path).await?;+ let mut downloaded: u64 = 0;+ let mut stream = resp.bytes_stream();++ loop {+ if let Some(token) = &self.cancel {+ if token.is_cancelled() {+ return Err(anyhow!("Download cancelled"));+ }+ }+ match tokio::time::timeout(self.config.read_timeout, stream.next()).await {+ Ok(Some(Ok(chunk))) => {+ file.write_all(&chunk).await?;+ downloaded += chunk.len() as u64;+ if let Some(t) = total.filter(|t| *t > 0) {+ let pct = (downloaded as f64 / t as f64) * 100.0;+ let _ = progress_tx.send(pct.min(99.9)).await;+ }+ }+ Ok(Some(Err(e))) => return Err(anyhow!("stream error: {}", e)),+ Ok(None) => break,+ Err(_) => return Err(anyhow!("read timed out after {:?}", self.config.read_timeout)),+ }+ }++ file.flush().await?;+ drop(file);+ tokio::fs::rename(part_path, &self.output_path).await?;+ let _ = progress_tx.send(100.0).await;+ Ok(HttpFetcherResult {+ bytes_written: downloaded,+ })+ }++ async fn download_chunked(+ &self,+ part_path: &Path,+ total: u64,+ seg_specs: Vec<ResumeSegment>,+ resume_path: &Path,+ url_hash: &str,+ progress_tx: &mpsc::Sender<f64>,+ ) -> anyhow::Result<()> {+ let segments: Arc<Mutex<Vec<Arc<Segment>>>> = Arc::new(Mutex::new(+ seg_specs+ .into_iter()+ .enumerate()+ .map(|(i, s)| Arc::new(Segment::new(i, s.begin, s.end, s.downloaded)))+ .collect(),+ ));++ let cancel = self.cancel.clone().unwrap_or_else(CancellationToken::new);+ let progress_done = Arc::new(AtomicU64::new(0));+ for seg in segments.lock().await.iter() {+ progress_done.fetch_add(seg.downloaded.load(Ordering::Relaxed), Ordering::Relaxed);+ }++ let progress_pump = {+ let segments = segments.clone();+ let progress_tx = progress_tx.clone();+ let cancel = cancel.clone();+ tokio::spawn(async move {+ let mut last_emit = std::time::Instant::now() - Duration::from_secs(1);+ loop {+ if cancel.is_cancelled() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ let dl: u64 = {+ let segs = segments.lock().await;+ segs.iter()+ .map(|s| s.downloaded.load(Ordering::Relaxed))+ .sum()+ };+ if last_emit.elapsed() >= Duration::from_millis(200) {+ let pct = (dl as f64 / total as f64) * 100.0;+ let _ = progress_tx.send(pct.min(99.9)).await;+ last_emit = std::time::Instant::now();+ }+ }+ })+ };++ let resume_pump = if self.config.use_sidecar_resume {+ let segments = segments.clone();+ let resume_path = resume_path.to_path_buf();+ let url_hash = url_hash.to_string();+ let cancel = cancel.clone();+ let interval = self.config.resume_save_interval;+ Some(tokio::spawn(async move {+ loop {+ if cancel.is_cancelled() {+ break;+ }+ tokio::time::sleep(interval).await;+ let snapshot: Vec<ResumeSegment> = {+ let segs = segments.lock().await;+ segs.iter()+ .map(|s| ResumeSegment {+ begin: s.begin,+ end: s.end_ceiling.load(Ordering::Relaxed),+ downloaded: s.downloaded.load(Ordering::Relaxed),+ })+ .collect()+ };+ let state = ResumeState {+ r#type: "http_segmented".to_string(),+ url_hash: url_hash.clone(),+ total_bytes: total,+ segments: snapshot,+ };+ if let Err(e) = save_resume_state(&resume_path, &state).await {+ tracing::trace!("[http_fetcher] resume save failed: {}", e);+ }+ }+ }))+ } else {+ None+ };++ let worker_count = self.config.concurrent_segments.max(1);+ let mut tasks = Vec::with_capacity(worker_count);+ let url = Arc::new(self.url.clone());+ let headers = self.headers.clone();+ let part_path_arc: Arc<PathBuf> = Arc::new(part_path.to_path_buf());+ for _ in 0..worker_count {+ let segments = segments.clone();+ let cancel = cancel.clone();+ let client = self.client.clone();+ let url = url.clone();+ let headers = headers.clone();+ let part_path = part_path_arc.clone();+ let cfg = self.config.clone();+ tasks.push(tokio::spawn(async move {+ worker_loop(client, url, headers, part_path, segments, cancel, cfg).await+ }));+ }++ let mut first_err: Option<anyhow::Error> = None;+ for t in tasks {+ match t.await {+ Ok(Ok(())) => {}+ Ok(Err(e)) => {+ if first_err.is_none() {+ first_err = Some(e);+ }+ cancel.cancel();+ }+ Err(e) => {+ if first_err.is_none() {+ first_err = Some(anyhow!("worker task panicked: {:?}", e));+ }+ cancel.cancel();+ }+ }+ }++ progress_pump.abort();+ if let Some(p) = resume_pump {+ p.abort();+ }+ let _ = progress_pump.await;++ if let Some(e) = first_err {+ return Err(e);+ }++ let segs = segments.lock().await;+ let all_done = segs+ .iter()+ .all(|s| s.state.load(Ordering::Relaxed) == SEG_DONE);+ if !all_done {+ return Err(anyhow!("not all segments completed"));+ }+ let actual = tokio::fs::metadata(part_path).await?.len();+ if actual != total {+ return Err(anyhow!(+ "size mismatch: expected {} bytes, got {}",+ total,+ actual+ ));+ }++ Ok(())+ }+}++struct ProbeResult {+ content_length: Option<u64>,+ accept_ranges: bool,+}++fn plan_segments(total: u64, hint: u64, max_segments: usize) -> Vec<ResumeSegment> {+ if total == 0 {+ return Vec::new();+ }+ let max = max_segments.max(1) as u64;+ let segment_size = hint.max(1);+ let count_by_size = total.div_ceil(segment_size).max(1);+ let count = count_by_size.min(max).max(1);+ let base = total / count;+ let mut remainder = total % count;+ let mut segments = Vec::with_capacity(count as usize);+ let mut cursor: u64 = 0;+ for _ in 0..count {+ let mut size = base;+ if remainder > 0 {+ size += 1;+ remainder -= 1;+ }+ let begin = cursor;+ let end = begin + size - 1;+ segments.push(ResumeSegment {+ begin,+ end,+ downloaded: 0,+ });+ cursor = end + 1;+ }+ segments+}++async fn worker_loop(+ client: reqwest::Client,+ url: Arc<String>,+ headers: Option<reqwest::header::HeaderMap>,+ part_path: Arc<PathBuf>,+ segments: Arc<Mutex<Vec<Arc<Segment>>>>,+ cancel: CancellationToken,+ cfg: HttpFetcherConfig,+) -> anyhow::Result<()> {+ loop {+ if cancel.is_cancelled() {+ return Ok(());+ }++ let claimed = claim_pending_or_steal(&segments, &cfg).await;+ let seg = match claimed {+ Some(s) => s,+ None => return Ok(()),+ };++ let mut attempt: u32 = 0;+ loop {+ if cancel.is_cancelled() {+ return Ok(());+ }+ match download_segment(&client, &url, headers.as_ref(), &part_path, &seg, &cancel, &cfg).await {+ Ok(()) => {+ seg.state.store(SEG_DONE, Ordering::Relaxed);+ break;+ }+ Err(e) => {+ if cancel.is_cancelled() {+ return Ok(());+ }+ if is_fatal(&e) {+ seg.state.store(SEG_FAILED, Ordering::Relaxed);+ return Err(e);+ }+ attempt += 1;+ if attempt >= cfg.max_retries_per_segment {+ seg.state.store(SEG_FAILED, Ordering::Relaxed);+ return Err(e);+ }+ let delay = Duration::from_secs((attempt as u64).min(5));+ tracing::warn!(+ "[http_fetcher] segment {}: attempt {}/{} failed: {}",+ seg.id,+ attempt,+ cfg.max_retries_per_segment,+ e+ );+ tokio::time::sleep(delay).await;+ }+ }+ }+ }+}++async fn claim_pending_or_steal(+ segments: &Arc<Mutex<Vec<Arc<Segment>>>>,+ cfg: &HttpFetcherConfig,+) -> Option<Arc<Segment>> {+ {+ let mut segs = segments.lock().await;+ for s in segs.iter() {+ if s.state.load(Ordering::Relaxed) == SEG_PENDING {+ s.state.store(SEG_RUNNING, Ordering::Relaxed);+ s.last_progress_unix_nanos+ .store(now_unix_nanos(), Ordering::Relaxed);+ s.speed_baseline_unix_nanos+ .store(now_unix_nanos(), Ordering::Relaxed);+ s.speed_baseline_downloaded+ .store(s.downloaded.load(Ordering::Relaxed), Ordering::Relaxed);+ return Some(s.clone());+ }+ }+ if let Some(stolen) = try_steal(&mut segs, cfg) {+ return Some(stolen);+ }+ }+ None+}++fn try_steal(+ segs: &mut Vec<Arc<Segment>>,+ cfg: &HttpFetcherConfig,+) -> Option<Arc<Segment>> {+ let mut victim: Option<Arc<Segment>> = None;+ let mut victim_score: u64 = 0;+ for s in segs.iter() {+ if s.state.load(Ordering::Relaxed) != SEG_RUNNING {+ continue;+ }+ let remain = s.remaining();+ if remain < cfg.steal_min_chunk_size {+ continue;+ }+ let est = s.estimated_seconds_remaining(true);+ if est <= cfg.steal_threshold.as_secs() {+ continue;+ }+ if est > victim_score {+ victim_score = est;+ victim = Some(s.clone());+ }+ }+ let victim = victim?;+ let remain = victim.remaining();+ if remain < cfg.steal_min_chunk_size {+ return None;+ }+ let half = remain / 2;+ if half < cfg.steal_min_chunk_size {+ return None;+ }+ let old_end = victim.end_ceiling.load(Ordering::Relaxed);+ let new_begin_for_helper = old_end - half + 1;+ let new_end_for_victim = new_begin_for_helper - 1;+ if new_begin_for_helper <= victim.begin + victim.downloaded.load(Ordering::Relaxed) {+ return None;+ }+ victim.end_ceiling.store(new_end_for_victim, Ordering::Relaxed);++ let next_id = segs.iter().map(|s| s.id).max().unwrap_or(0) + 1;+ let helper = Arc::new(Segment::new(next_id, new_begin_for_helper, old_end, 0));+ helper.state.store(SEG_RUNNING, Ordering::Relaxed);+ helper+ .last_progress_unix_nanos+ .store(now_unix_nanos(), Ordering::Relaxed);+ helper+ .speed_baseline_unix_nanos+ .store(now_unix_nanos(), Ordering::Relaxed);+ segs.push(helper.clone());+ tracing::debug!(+ "[http_fetcher] stole {} bytes from segment {} → helper segment {}",+ half,+ victim.id,+ helper.id+ );+ Some(helper)+}++async fn download_segment(+ client: &reqwest::Client,+ url: &str,+ headers: Option<&reqwest::header::HeaderMap>,+ part_path: &Path,+ seg: &Arc<Segment>,+ cancel: &CancellationToken,+ cfg: &HttpFetcherConfig,+) -> anyhow::Result<()> {+ let begin = seg.begin;+ let end = seg.end_ceiling.load(Ordering::Relaxed);+ let already = seg.downloaded.load(Ordering::Relaxed);+ if begin + already > end {+ return Ok(());+ }+ let range_start = begin + already;++ let mut req = client.get(url);+ if let Some(h) = headers {+ req = req.headers(h.clone());+ }+ req = req.header(+ reqwest::header::RANGE,+ format!("bytes={}-{}", range_start, end),+ );++ let resp = tokio::time::timeout(cfg.connect_timeout, req.send())+ .await+ .map_err(|_| anyhow!("connect timeout"))??;++ let status = resp.status();+ if status != reqwest::StatusCode::PARTIAL_CONTENT {+ if status.is_success() {+ return Err(anyhow!("server did not honor Range (HTTP 200)"));+ }+ return Err(anyhow!("HTTP {}", status));+ }++ if let Some(ct) = resp.headers().get(reqwest::header::CONTENT_TYPE) {+ if let Ok(s) = ct.to_str() {+ if s.contains("text/html") {+ return Err(anyhow!("server returned HTML instead of media"));+ }+ }+ }++ let mut file = tokio::fs::OpenOptions::new()+ .write(true)+ .open(part_path)+ .await?;+ file.seek(std::io::SeekFrom::Start(range_start)).await?;++ let mut stream = resp.bytes_stream();+ let mut written: u64 = 0;+ let target = (end - range_start) + 1;+ loop {+ if cancel.is_cancelled() {+ return Err(anyhow!("Download cancelled"));+ }+ let cur_end = seg.end_ceiling.load(Ordering::Relaxed);+ if cur_end < end {+ break;+ }+ let res = tokio::time::timeout(cfg.read_timeout, stream.next()).await;+ match res {+ Ok(Some(Ok(chunk))) => {+ if chunk.is_empty() {+ continue;+ }+ let mut take = chunk.len() as u64;+ let max_allowed = target.saturating_sub(written);+ if take > max_allowed {+ take = max_allowed;+ }+ let slice = &chunk[..take as usize];+ file.write_all(slice).await?;+ written += take;+ seg.downloaded.fetch_add(take, Ordering::Relaxed);+ seg.last_progress_unix_nanos+ .store(now_unix_nanos(), Ordering::Relaxed);+ if written >= target {+ break;+ }+ }+ Ok(Some(Err(e))) => return Err(anyhow!("stream error: {}", e)),+ Ok(None) => break,+ Err(_) => return Err(anyhow!("read timed out after {:?}", cfg.read_timeout)),+ }+ }+ file.flush().await?;+ let cur_end = seg.end_ceiling.load(Ordering::Relaxed);+ let cur_target = (cur_end - begin) + 1;+ let cur_dl = seg.downloaded.load(Ordering::Relaxed);+ if cur_dl < cur_target {+ return Err(anyhow!(+ "incomplete segment: {} of {} bytes",+ cur_dl,+ cur_target+ ));+ }+ Ok(())+}++fn is_fatal(err: &anyhow::Error) -> bool {+ let m = err.to_string();+ for code in &[+ "HTTP 400", "HTTP 401", "HTTP 403", "HTTP 404", "HTTP 405", "HTTP 410", "HTTP 451",+ ] {+ if m.contains(code) {+ return true;+ }+ }+ if m.contains("HTML instead of media") {+ return true;+ }+ if m.contains("cancelled") {+ return true;+ }+ false+}++async fn ensure_part_file(part_path: &Path, total: u64) -> anyhow::Result<()> {+ let needs_create = match tokio::fs::metadata(part_path).await {+ Ok(m) => m.len() != total,+ Err(_) => true,+ };+ if needs_create {+ let _ = tokio::fs::remove_file(part_path).await;+ let f = tokio::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(true)+ .open(part_path)+ .await?;+ f.set_len(total).await?;+ }+ Ok(())+}++pub fn part_path_for(output: &Path) -> PathBuf {+ let mut s = output.as_os_str().to_owned();+ s.push(".part");+ PathBuf::from(s)+}++fn sidecar_path_for(part_path: &Path) -> PathBuf {+ let mut s = part_path.as_os_str().to_owned();+ s.push(".resume.json");+ PathBuf::from(s)+}++fn url_hash(url: &str) -> String {+ use sha2::{Digest, Sha256};+ let mut h = Sha256::new();+ h.update(url.as_bytes());+ let out = h.finalize();+ let mut s = String::with_capacity(16);+ for b in &out[..8] {+ s.push_str(&format!("{:02x}", b));+ }+ s+}++fn load_resume_state(path: &Path) -> Option<ResumeState> {+ let bytes = std::fs::read(path).ok()?;+ serde_json::from_slice(&bytes).ok()+}++async fn save_resume_state(path: &Path, state: &ResumeState) -> anyhow::Result<()> {+ let mut tmp = path.as_os_str().to_owned();+ tmp.push(".tmp");+ let tmp_path = PathBuf::from(tmp);+ let json = serde_json::to_vec(state)?;+ tokio::fs::write(&tmp_path, json).await?;+ tokio::fs::rename(&tmp_path, path).await?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn plan_segments_uniform_division() {+ let segs = plan_segments(100, 10, 10);+ assert_eq!(segs.len(), 10);+ assert_eq!(segs.first().unwrap().begin, 0);+ assert_eq!(segs.last().unwrap().end, 99);+ for w in segs.windows(2) {+ assert_eq!(w[0].end + 1, w[1].begin);+ }+ }++ #[test]+ fn plan_segments_remainder_distributed() {+ let segs = plan_segments(101, 10, 10);+ assert_eq!(segs.len(), 10);+ assert_eq!(segs.last().unwrap().end, 100);+ let total: u64 = segs.iter().map(|s| s.end - s.begin + 1).sum();+ assert_eq!(total, 101);+ }++ #[test]+ fn plan_segments_capped_by_max() {+ let segs = plan_segments(1_000_000, 1024, 4);+ assert_eq!(segs.len(), 4);+ let total: u64 = segs.iter().map(|s| s.end - s.begin + 1).sum();+ assert_eq!(total, 1_000_000);+ }++ #[test]+ fn plan_segments_capped_by_size_hint() {+ let segs = plan_segments(100, 50, 16);+ assert_eq!(segs.len(), 2);+ }++ #[test]+ fn plan_segments_zero_total() {+ assert!(plan_segments(0, 1024, 4).is_empty());+ }++ #[test]+ fn plan_segments_smaller_than_hint() {+ let segs = plan_segments(500, 1024, 4);+ assert_eq!(segs.len(), 1);+ assert_eq!(segs[0].begin, 0);+ assert_eq!(segs[0].end, 499);+ }++ #[test]+ fn part_path_basic() {+ assert_eq!(+ part_path_for(Path::new("video.mp4")),+ PathBuf::from("video.mp4.part")+ );+ }++ #[test]+ fn sidecar_appends_resume_json() {+ let part = Path::new("video.mp4.part");+ assert_eq!(+ sidecar_path_for(part),+ PathBuf::from("video.mp4.part.resume.json")+ );+ }++ #[test]+ fn url_hash_stable_and_short() {+ let h1 = url_hash("https://example.com/foo");+ let h2 = url_hash("https://example.com/foo");+ let h3 = url_hash("https://example.com/bar");+ assert_eq!(h1, h2);+ assert_ne!(h1, h3);+ assert_eq!(h1.len(), 16);+ }++ #[test]+ fn segment_remaining_zero_when_done() {+ let seg = Segment::new(0, 0, 99, 100);+ assert_eq!(seg.remaining(), 0);+ }++ #[test]+ fn segment_remaining_partial() {+ let seg = Segment::new(0, 0, 99, 40);+ assert_eq!(seg.remaining(), 60);+ }++ #[test]+ fn fatal_classification_403() {+ assert!(is_fatal(&anyhow!("HTTP 403 Forbidden")));+ }++ #[test]+ fn fatal_classification_500_not_fatal() {+ assert!(!is_fatal(&anyhow!("HTTP 500 Internal Server Error")));+ }++ #[test]+ fn fatal_classification_html() {+ assert!(is_fatal(&anyhow!("HTML instead of media")));+ }++ #[test]+ fn fatal_classification_cancelled() {+ assert!(is_fatal(&anyhow!("Download cancelled")));+ }++ #[test]+ fn fatal_classification_network() {+ assert!(!is_fatal(&anyhow!("connection reset")));+ }++ #[test]+ fn global_concurrent_segments_setter() {+ set_global_max_concurrent_segments(0);+ assert_eq!(get_global_max_concurrent_segments(), None);+ set_global_max_concurrent_segments(7);+ assert_eq!(get_global_max_concurrent_segments(), Some(7));+ set_global_max_concurrent_segments(0);+ }++ #[tokio::test]+ async fn fetcher_downloads_small_file_streaming() {+ use std::io::Write;+ let temp_dir = std::env::temp_dir().join(format!(+ "omniget_http_fetcher_test_{}",+ now_unix_nanos()+ ));+ std::fs::create_dir_all(&temp_dir).unwrap();+ let payload: Vec<u8> = (0u8..=255).cycle().take(200_000).collect();++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let payload_for_server = payload.clone();+ tokio::spawn(async move {+ loop {+ let Ok((mut stream, _)) = listener.accept().await else { break };+ let body = payload_for_server.clone();+ tokio::spawn(async move {+ use tokio::io::AsyncReadExt;+ let mut buf = vec![0u8; 4096];+ let _ = stream.read(&mut buf).await;+ let header = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nAccept-Ranges: none\r\nContent-Type: application/octet-stream\r\n\r\n",+ body.len()+ );+ use tokio::io::AsyncWriteExt;+ let _ = stream.write_all(header.as_bytes()).await;+ let _ = stream.write_all(&body).await;+ });+ }+ });++ let client = reqwest::Client::builder().build().unwrap();+ let output = temp_dir.join("file.bin");+ let url = format!("http://{}/file.bin", addr);+ let fetcher = HttpFetcher::new(client, url, output.clone());++ let (tx, mut rx) = tokio::sync::mpsc::channel::<f64>(32);+ let progress_collector = tokio::spawn(async move {+ let mut last = 0.0;+ while let Some(p) = rx.recv().await {+ last = p;+ }+ last+ });++ let res = fetcher.download(tx).await;+ let last_pct = progress_collector.await.unwrap();++ assert!(res.is_ok(), "{:?}", res.err());+ let written = std::fs::read(&output).unwrap();+ assert_eq!(written.len(), payload.len());+ assert_eq!(written, payload);+ assert!((last_pct - 100.0).abs() < f64::EPSILON);++ let _ = std::fs::remove_dir_all(&temp_dir);+ let _ = writeln!(std::io::stderr(), "ok");+ }++ async fn serve_range_request(mut stream: tokio::net::TcpStream, body: Arc<Vec<u8>>) {+ use tokio::io::AsyncReadExt;+ use tokio::io::AsyncWriteExt;+ let mut buf = vec![0u8; 8192];+ let n = match stream.read(&mut buf).await {+ Ok(n) if n > 0 => n,+ _ => return,+ };+ let req = String::from_utf8_lossy(&buf[..n]).to_string();+ let mut lines = req.split("\r\n");+ let request_line = lines.next().unwrap_or("");+ let mut parts = request_line.split_whitespace();+ let method = parts.next().unwrap_or("").to_string();+ let mut range_header: Option<String> = None;+ for line in lines {+ if line.is_empty() {+ break;+ }+ if let Some(v) = line.strip_prefix("Range: ") {+ range_header = Some(v.trim().to_string());+ } else if let Some(v) = line.strip_prefix("range: ") {+ range_header = Some(v.trim().to_string());+ }+ }++ if method == "HEAD" {+ let head = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nAccept-Ranges: bytes\r\nContent-Type: application/octet-stream\r\n\r\n",+ body.len()+ );+ let _ = stream.write_all(head.as_bytes()).await;+ return;+ }++ if let Some(range) = range_header {+ if let Some(rest) = range.strip_prefix("bytes=") {+ let mut iter = rest.split('-');+ let start: u64 = iter.next().and_then(|s| s.parse().ok()).unwrap_or(0);+ let end: u64 = iter+ .next()+ .and_then(|s| s.parse().ok())+ .unwrap_or((body.len() as u64) - 1);+ let s = start as usize;+ let e = (end as usize).min(body.len() - 1);+ let slice = &body[s..=e];+ let head = format!(+ "HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {}-{}/{}\r\nContent-Type: application/octet-stream\r\n\r\n",+ slice.len(),+ s,+ e,+ body.len()+ );+ let _ = stream.write_all(head.as_bytes()).await;+ let _ = stream.write_all(slice).await;+ return;+ }+ }++ let head = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nAccept-Ranges: bytes\r\nContent-Type: application/octet-stream\r\n\r\n",+ body.len()+ );+ let _ = stream.write_all(head.as_bytes()).await;+ let _ = stream.write_all(&body).await;+ }++ #[tokio::test]+ async fn fetcher_downloads_multi_segment_with_range() {+ let temp_dir = std::env::temp_dir().join(format!(+ "omniget_http_fetcher_chunked_{}",+ now_unix_nanos()+ ));+ std::fs::create_dir_all(&temp_dir).unwrap();+ let payload: Vec<u8> = (0u8..=255).cycle().take(2 * 1024 * 1024).collect();++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let payload_for_server = Arc::new(payload.clone());+ tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ let body = payload_for_server.clone();+ tokio::spawn(async move {+ serve_range_request(stream, body).await;+ });+ }+ });++ let client = reqwest::Client::builder().build().unwrap();+ let output = temp_dir.join("file.bin");+ let url = format!("http://{}/file.bin", addr);+ let cfg = HttpFetcherConfig {+ min_size_for_chunked: 256 * 1024,+ segment_size_hint: 256 * 1024,+ concurrent_segments: 4,+ connect_timeout: Duration::from_secs(5),+ read_timeout: Duration::from_secs(15),+ use_sidecar_resume: false,+ ..Default::default()+ };+ let fetcher = HttpFetcher::new(client, url, output.clone()).with_config(cfg);++ let (tx, mut rx) = tokio::sync::mpsc::channel::<f64>(64);+ let progress_collector = tokio::spawn(async move {+ let mut last = 0.0;+ while let Some(p) = rx.recv().await {+ last = p;+ }+ last+ });++ let res = fetcher.download(tx).await;+ let last_pct = progress_collector.await.unwrap();++ assert!(res.is_ok(), "{:?}", res.err());+ let written = std::fs::read(&output).unwrap();+ assert_eq!(written.len(), payload.len());+ assert_eq!(written, payload);+ assert!((last_pct - 100.0).abs() < f64::EPSILON);++ let _ = std::fs::remove_dir_all(&temp_dir);+ }++ #[tokio::test]+ async fn fetcher_resumes_from_sidecar_state() {+ let temp_dir = std::env::temp_dir().join(format!(+ "omniget_http_fetcher_resume_load_{}",+ now_unix_nanos()+ ));+ std::fs::create_dir_all(&temp_dir).unwrap();+ let total: usize = 1024 * 1024;+ let payload: Vec<u8> = (0u8..=255).cycle().take(total).collect();++ let part = part_path_for(&temp_dir.join("file.bin"));+ let f = tokio::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(true)+ .open(&part)+ .await+ .unwrap();+ f.set_len(total as u64).await.unwrap();+ drop(f);++ let half = total / 2;+ let mut f = tokio::fs::OpenOptions::new()+ .write(true)+ .open(&part)+ .await+ .unwrap();+ f.write_all(&payload[..half]).await.unwrap();+ f.flush().await.unwrap();+ drop(f);++ let resume_path = sidecar_path_for(&part);+ let url_hash_v = url_hash("test://payload");+ let state = ResumeState {+ r#type: "http_segmented".to_string(),+ url_hash: url_hash_v.clone(),+ total_bytes: total as u64,+ segments: vec![+ ResumeSegment {+ begin: 0,+ end: (half - 1) as u64,+ downloaded: half as u64,+ },+ ResumeSegment {+ begin: half as u64,+ end: (total - 1) as u64,+ downloaded: 0,+ },+ ],+ };+ save_resume_state(&resume_path, &state).await.unwrap();++ let loaded = load_resume_state(&resume_path).unwrap();+ assert_eq!(loaded.url_hash, url_hash_v);+ assert_eq!(loaded.segments[0].downloaded, half as u64);+ assert_eq!(loaded.segments[1].downloaded, 0);+ assert_eq!(loaded.total_bytes, total as u64);++ let _ = std::fs::remove_dir_all(&temp_dir);+ }++ #[tokio::test]+ async fn fetcher_resume_sidecar_round_trip() {+ let temp_dir = std::env::temp_dir().join(format!(+ "omniget_http_fetcher_resume_{}",+ now_unix_nanos()+ ));+ std::fs::create_dir_all(&temp_dir).unwrap();+ let path = temp_dir.join("video.mp4.part.resume.json");+ let state = ResumeState {+ r#type: "http_segmented".to_string(),+ url_hash: "deadbeef".to_string(),+ total_bytes: 1024,+ segments: vec![+ ResumeSegment {+ begin: 0,+ end: 511,+ downloaded: 100,+ },+ ResumeSegment {+ begin: 512,+ end: 1023,+ downloaded: 0,+ },+ ],+ };+ save_resume_state(&path, &state).await.unwrap();+ let loaded = load_resume_state(&path).unwrap();+ assert_eq!(loaded.url_hash, "deadbeef");+ assert_eq!(loaded.segments.len(), 2);+ assert_eq!(loaded.segments[0].downloaded, 100);+ let _ = std::fs::remove_dir_all(&temp_dir);+ }+}diff --git a/src-tauri/omniget-core/src/core/mod.rs b/src-tauri/omniget-core/src/core/mod.rsindex e4004935..08a36f4e 100644--- a/src-tauri/omniget-core/src/core/mod.rs+++ b/src-tauri/omniget-core/src/core/mod.rs@@ -9,6 +9,7 @@ pub mod ffmpeg;pub mod filename;pub mod hls_downloader;pub mod http_client;+pub mod http_fetcher;pub mod hwaccel;pub mod log_hook;pub mod media_processor;diff --git a/src-tauri/omniget-core/src/core/process.rs b/src-tauri/omniget-core/src/core/process.rsindex 699adb59..32e1ffe0 100644--- a/src-tauri/omniget-core/src/core/process.rs+++ b/src-tauri/omniget-core/src/core/process.rs@@ -40,6 +40,7 @@ pub fn command<S: AsRef<std::ffi::OsStr>>(program: S) -> tokio::process::Commandcmd.env_remove("PYTHONPATH");cmd.env("PYTHONIOENCODING", "utf-8");cmd.env("PYTHONUTF8", "1");+ cmd.env("PYTHONLEGACYWINDOWSSTDIO", "0");cmd}@@ -57,5 +58,6 @@ pub fn std_command<S: AsRef<std::ffi::OsStr>>(program: S) -> std::process::Commacmd.env_remove("PYTHONPATH");cmd.env("PYTHONIOENCODING", "utf-8");cmd.env("PYTHONUTF8", "1");+ cmd.env("PYTHONLEGACYWINDOWSSTDIO", "0");cmd}diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rsindex d0b74517..a6fe1791 100644--- a/src-tauri/omniget-core/src/core/ytdlp.rs+++ b/src-tauri/omniget-core/src/core/ytdlp.rs@@ -106,6 +106,28 @@ fn ext_user_agent_for_url(url: &str) -> Option<String> {.and_then(|m| m.get(url).cloned())}+static ETA_BY_DOWNLOAD: OnceLock<Mutex<HashMap<u64, u64>>> = OnceLock::new();++fn eta_map() -> &'static Mutex<HashMap<u64, u64>> {+ ETA_BY_DOWNLOAD.get_or_init(|| Mutex::new(HashMap::new()))+}++pub fn record_eta(download_id: u64, eta_seconds: u64) {+ if let Ok(mut m) = eta_map().lock() {+ m.insert(download_id, eta_seconds);+ }+}++pub fn get_eta(download_id: u64) -> Option<u64> {+ eta_map().lock().ok().and_then(|m| m.get(&download_id).copied())+}++pub fn clear_eta(download_id: u64) {+ if let Ok(mut m) = eta_map().lock() {+ m.remove(&download_id);+ }+}+static EXT_HEADERS_MAP: OnceLock<Mutex<HashMap<String, HashMap<String, String>>>> = OnceLock::new();fn ext_headers_map() -> &'static Mutex<HashMap<String, HashMap<String, String>>> {@@ -964,7 +986,7 @@ pub async fn get_playlist_info("--extractor-retries".to_string(),"3".to_string(),"--retry-sleep".to_string(),- "exp=1:60".to_string(),+ "exp=1:15".to_string(),"--user-agent".to_string(),CHROME_UA.to_string(),];@@ -1297,7 +1319,7 @@ pub async fn download_video("--no-playlist".to_string(),"--newline".to_string(),"--progress-template".to_string(),- "download:%(progress._percent_str)s".to_string(),+ "download:%(progress._percent_str)s|eta:%(progress.eta)s".to_string(),"-o".to_string(),output_template,"--skip-unavailable-fragments".to_string(),@@ -1485,6 +1507,11 @@ pub async fn download_video(_timer_start.elapsed());}+ if let Some(id) = log_id {+ if let Some(eta) = parse_eta_line(&line) {+ record_eta(id, eta);+ }+ }if is_audio_only {if pct >= 99.0 || last_send.elapsed() >= throttle {let _ = progress_tx.send(pct).await;@@ -1819,6 +1846,16 @@ fn sanitize_log_line(line: &str) -> String {fn translate_ytdlp_error(stderr: &str) -> anyhow::Error {let lower = stderr.to_lowercase();+ if lower.contains("errno 22")+ && (lower.contains("textiowrapper")+ || lower.contains("encoding=")+ || lower.contains("exception ignored"))+ {+ return anyhow!(+ "Console encoding error (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run `chcp 65001` in a terminal and reopen the app."+ );+ }+if lower.contains("http error 429") {return anyhow!("Server returned error 429 (too many requests). Try again later.");}@@ -1831,6 +1868,14 @@ fn translate_ytdlp_error(stderr: &str) -> anyhow::Error {if lower.contains("nsig extraction failed") || lower.contains("nsig") {return anyhow!("Video extraction failed. Update yt-dlp or try again.");}+ if lower.contains("cannot parse data")+ || lower.contains("please report this issue")+ || (lower.contains("confirm you are on the latest version") && lower.contains("yt-dlp"))+ {+ return anyhow!(+ "yt-dlp extractor is broken for this site. Update yt-dlp in Settings → Dependencies, then retry."+ );+ }if lower.contains("requested format") && lower.contains("not available") {return anyhow!("Requested format is not available. The download will retry with a compatible format."@@ -1900,15 +1945,32 @@ pub fn get_rate_limit_stats() -> serde_json::Value {fn parse_progress_line(line: &str) -> Option<f64> {let line = line.trim();- let pct_str = if let Some(rest) = line.strip_prefix("download:") {- rest.trim().trim_end_matches('%')+ let body = if let Some(rest) = line.strip_prefix("download:") {+ rest} else if line.ends_with('%') {- line.trim_end_matches('%').split_whitespace().last()?+ line} else {return None;};- pct_str.trim().parse::<f64>().ok()+ let pct_part = body.split('|').next()?.trim().trim_end_matches('%');+ let pct_str = pct_part.split_whitespace().last()?;+ pct_str.parse::<f64>().ok()+}++fn parse_eta_line(line: &str) -> Option<u64> {+ let body = line.trim().strip_prefix("download:")?;+ for part in body.split('|') {+ let part = part.trim();+ if let Some(rest) = part.strip_prefix("eta:") {+ let rest = rest.trim();+ if rest.is_empty() || rest.eq_ignore_ascii_case("na") {+ return None;+ }+ return rest.parse::<u64>().ok();+ }+ }+ None}async fn find_downloaded_file(output_dir: &Path, url: &str) -> anyhow::Result<PathBuf> {@@ -2122,6 +2184,34 @@ mod tests {assert_eq!(parse_progress_line("download:100%"), Some(100.0));}+ #[test]+ fn parse_progress_with_eta_field() {+ assert_eq!(+ parse_progress_line("download: 45.2%|eta:30"),+ Some(45.2)+ );+ }++ #[test]+ fn parse_eta_extracts_seconds() {+ assert_eq!(parse_eta_line("download: 45.2%|eta:30"), Some(30));+ }++ #[test]+ fn parse_eta_na_returns_none() {+ assert_eq!(parse_eta_line("download: 45.2%|eta:NA"), None);+ }++ #[test]+ fn parse_eta_missing_returns_none() {+ assert_eq!(parse_eta_line("download: 45.2%"), None);+ }++ #[test]+ fn parse_eta_no_prefix_returns_none() {+ assert_eq!(parse_eta_line(" 45.2%|eta:30"), None);+ }+#[test]fn parse_progress_garbage_returns_none() {assert_eq!(parse_progress_line("[info] Writing video subtitles"), None);diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rsindex b07ed903..b9a9b259 100644--- a/src-tauri/omniget-core/src/models/settings.rs+++ b/src-tauri/omniget-core/src/models/settings.rs@@ -25,6 +25,40 @@ pub struct AppSettings {pub last_download_options: LastDownloadOptions,#[serde(default)]pub typography: TypographySettings,+ #[serde(default)]+ pub rpc: RpcSettings,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RpcSettings {+ #[serde(default = "default_rpc_enabled")]+ pub enabled: bool,+ #[serde(default = "default_rpc_app_id")]+ pub app_id: String,+ #[serde(default = "default_rpc_image_key")]+ pub large_image_key: String,+}++impl Default for RpcSettings {+ fn default() -> Self {+ Self {+ enabled: default_rpc_enabled(),+ app_id: default_rpc_app_id(),+ large_image_key: default_rpc_image_key(),+ }+ }+}++fn default_rpc_enabled() -> bool {+ true+}++fn default_rpc_app_id() -> String {+ "1502867748353478656".into()+}++fn default_rpc_image_key() -> String {+ "omniget_music".into()}#[derive(Debug, Clone, Serialize, Deserialize, Default)]@@ -74,6 +108,16 @@ pub struct DownloadSettings {#[serde(default = "default_hotkey_binding")]pub hotkey_binding: String,#[serde(default)]+ pub clip_hotkey_enabled: bool,+ #[serde(default = "default_clip_hotkey_binding")]+ pub clip_hotkey_binding: String,+ #[serde(default)]+ pub music_hotkey_enabled: bool,+ #[serde(default = "default_music_hotkey_binding")]+ pub music_hotkey_binding: String,+ #[serde(default = "default_music_audio_format")]+ pub music_audio_format: String,+ #[serde(default)]pub extra_ytdlp_flags: Vec<String>,#[serde(default = "default_true")]pub copy_to_clipboard_on_hotkey: bool,@@ -125,6 +169,18 @@ fn default_hotkey_binding() -> String {"CmdOrCtrl+Shift+D".into()}+fn default_clip_hotkey_binding() -> String {+ "CmdOrCtrl+Shift+B".into()+}++fn default_music_hotkey_binding() -> String {+ "CmdOrCtrl+Shift+M".into()+}++fn default_music_audio_format() -> String {+ "m4a".into()+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct TelegramSettings {pub concurrent_downloads: u32,@@ -240,6 +296,11 @@ impl Default for AppSettings {split_by_chapters: false,hotkey_enabled: false,hotkey_binding: default_hotkey_binding(),+ clip_hotkey_enabled: false,+ clip_hotkey_binding: default_clip_hotkey_binding(),+ music_hotkey_enabled: false,+ music_hotkey_binding: default_music_hotkey_binding(),+ music_audio_format: default_music_audio_format(),extra_ytdlp_flags: Vec::new(),copy_to_clipboard_on_hotkey: true,cookie_file: String::new(),@@ -262,6 +323,7 @@ impl Default for AppSettings {legal_acknowledged: false,last_download_options: LastDownloadOptions::default(),typography: TypographySettings::default(),+ rpc: RpcSettings::default(),}}}diff --git a/src-tauri/src/commands/browser_extension.rs b/src-tauri/src/commands/browser_extension.rsnew file mode 100644index 00000000..73a9443e--- /dev/null+++ b/src-tauri/src/commands/browser_extension.rs@@ -0,0 +1,149 @@+use std::path::{Path, PathBuf};++use serde::Serialize;+use tauri::{AppHandle, Manager};++#[derive(Debug, Clone, Serialize)]+pub struct BrowserExtensionStatus {+ pub browser: String,+ pub supported: bool,+ pub bundled_version: Option<String>,+ pub installable: bool,+ pub install_hint: String,+ pub store_url: Option<String>,+}++fn read_bundled_manifest_version(app: &AppHandle, browser: &str) -> Option<String> {+ let resource = format!("browser-extension/{}/manifest.json", browser);+ let path = app.path().resolve(resource, tauri::path::BaseDirectory::Resource).ok()?;+ let raw = std::fs::read_to_string(&path).ok()?;+ let v: serde_json::Value = serde_json::from_str(&raw).ok()?;+ v.get("version")?.as_str().map(|s| s.to_string())+}++fn extension_export_dir(app: &AppHandle, browser: &str) -> Option<PathBuf> {+ let base = app.path().app_data_dir().ok()?;+ Some(base.join("browser-extension").join(browser))+}++fn copy_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {+ if !src.exists() {+ return Ok(());+ }+ if src.is_file() {+ if let Some(parent) = dst.parent() {+ std::fs::create_dir_all(parent)?;+ }+ std::fs::copy(src, dst)?;+ return Ok(());+ }+ std::fs::create_dir_all(dst)?;+ for entry in std::fs::read_dir(src)? {+ let entry = entry?;+ let from = entry.path();+ let to = dst.join(entry.file_name());+ copy_recursive(&from, &to)?;+ }+ Ok(())+}++#[tauri::command]+pub async fn browser_extension_status(+ app: AppHandle,+) -> Result<Vec<BrowserExtensionStatus>, String> {+ let chrome_v = read_bundled_manifest_version(&app, "chrome");+ let firefox_v = read_bundled_manifest_version(&app, "firefox");+ Ok(vec![+ BrowserExtensionStatus {+ browser: "chrome".into(),+ supported: true,+ bundled_version: chrome_v,+ installable: true,+ install_hint: "chrome://extensions → Modo do desenvolvedor → \"Carregar sem compactação\" → selecionar a pasta extraída.".into(),+ store_url: None,+ },+ BrowserExtensionStatus {+ browser: "firefox".into(),+ supported: true,+ bundled_version: firefox_v,+ installable: true,+ install_hint: "about:debugging#/runtime/this-firefox → \"Carregar complemento temporário\" → selecionar manifest.json da pasta extraída. (Reinstalação necessária a cada reinício do Firefox enquanto não publicado na AMO.)".into(),+ store_url: None,+ },+ BrowserExtensionStatus {+ browser: "safari".into(),+ supported: false,+ bundled_version: None,+ installable: false,+ install_hint: "Safari só aceita extensões via Mac App Store desde Safari 14. Versão Safari da OmniGet ainda não publicada.".into(),+ store_url: None,+ },+ ])+}++#[derive(Debug, Clone, Serialize)]+pub struct ExtensionExportResult {+ pub path: String,+ pub version: Option<String>,+ pub browser: String,+}++#[tauri::command]+pub async fn browser_extension_export(+ app: AppHandle,+ browser: String,+) -> Result<ExtensionExportResult, String> {+ if browser != "chrome" && browser != "firefox" {+ return Err(format!("browser '{}' não suportado pra export", browser));+ }+ let resource = format!("../browser-extension/{}", browser);+ let src = app+ .path()+ .resolve(resource, tauri::path::BaseDirectory::Resource)+ .map_err(|e| format!("resolve resource: {}", e))?;+ let dst = extension_export_dir(&app, &browser)+ .ok_or_else(|| "could not derive extension dir".to_string())?;+ if dst.exists() {+ let _ = std::fs::remove_dir_all(&dst);+ }+ std::fs::create_dir_all(&dst).map_err(|e| format!("mkdir: {}", e))?;+ copy_recursive(&src, &dst).map_err(|e| format!("copy extension: {}", e))?;++ let version = read_bundled_manifest_version(&app, &browser);++ Ok(ExtensionExportResult {+ path: dst.to_string_lossy().into_owned(),+ version,+ browser,+ })+}++#[tauri::command]+pub async fn browser_extension_open_folder(path: String) -> Result<(), String> {+ let path = PathBuf::from(&path);+ if !path.exists() {+ return Err(format!("path not found: {}", path.display()));+ }+ #[cfg(target_os = "windows")]+ {+ std::process::Command::new("explorer")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("explorer: {}", e))?;+ }+ #[cfg(target_os = "macos")]+ {+ std::process::Command::new("open")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("open: {}", e))?;+ }+ #[cfg(all(unix, not(target_os = "macos")))]+ {+ std::process::Command::new("xdg-open")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("xdg-open: {}", e))?;+ }+ Ok(())+}diff --git a/src-tauri/src/commands/clip.rs b/src-tauri/src/commands/clip.rsnew file mode 100644index 00000000..a2b4e9fe--- /dev/null+++ b/src-tauri/src/commands/clip.rs@@ -0,0 +1,185 @@+use std::path::{Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};++use serde::{Deserialize, Serialize};+use tauri::AppHandle;++use omniget_core::core::ffmpeg;+use omniget_core::core::process;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ClipRequest {+ pub source_path: String,+ pub start_secs: f64,+ pub duration_secs: f64,+ pub dest_dir: Option<String>,+ pub label: Option<String>,+ pub reencode: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ClipResult {+ pub output_path: String,+ pub duration_secs: f64,+ pub size_bytes: u64,+ pub used_reencode: bool,+}++#[tauri::command]+pub async fn clip_video(_app: AppHandle, req: ClipRequest) -> Result<ClipResult, String> {+ if !ffmpeg::is_ffmpeg_available().await {+ return Err("ffmpeg not found".to_string());+ }++ let source = PathBuf::from(&req.source_path);+ if !source.is_file() {+ return Err(format!("source not found: {}", req.source_path));+ }++ let duration = req.duration_secs.max(0.5);+ let start = req.start_secs.max(0.0);++ let dest_dir = match req.dest_dir.as_deref() {+ Some(d) if !d.is_empty() => PathBuf::from(d),+ _ => default_dest_dir(&source),+ };+ std::fs::create_dir_all(&dest_dir).map_err(|e| format!("mkdir failed: {}", e))?;++ let stem = source+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or("clip");+ let ext = source.extension().and_then(|s| s.to_str()).unwrap_or("mp4");+ let label = sanitize(&req.label.clone().unwrap_or_else(|| "clip".to_string()));+ let ts = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0);+ let dest = dest_dir.join(format!("{}.{}.{}.{}", stem, label, ts, ext));++ let want_reencode = req.reencode.unwrap_or(false);++ if !want_reencode {+ let copy_result = run_copy_clip(&source, start, duration, &dest).await;+ if copy_result.is_ok() && dest.is_file() && file_size(&dest) > 1024 {+ return Ok(ClipResult {+ output_path: dest.to_string_lossy().into_owned(),+ duration_secs: duration,+ size_bytes: file_size(&dest),+ used_reencode: false,+ });+ }+ }++ run_reencode_clip(&source, start, duration, &dest).await?;+ if !dest.is_file() {+ return Err("clip output missing after reencode".to_string());+ }++ Ok(ClipResult {+ output_path: dest.to_string_lossy().into_owned(),+ duration_secs: duration,+ size_bytes: file_size(&dest),+ used_reencode: true,+ })+}++fn default_dest_dir(source: &Path) -> PathBuf {+ if let Some(parent) = source.parent() {+ return parent.join("clips");+ }+ PathBuf::from("clips")+}++fn sanitize(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ out.push(c);+ } else if c == ' ' {+ out.push('_');+ }+ }+ if out.is_empty() {+ return "clip".into();+ }+ out+}++fn file_size(p: &Path) -> u64 {+ std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)+}++async fn run_copy_clip(+ source: &Path,+ start: f64,+ duration: f64,+ dest: &Path,+) -> Result<(), String> {+ let status = process::command("ffmpeg")+ .args([+ "-y",+ "-ss",+ &format!("{:.3}", start),+ "-i",+ &source.to_string_lossy(),+ "-t",+ &format!("{:.3}", duration),+ "-c",+ "copy",+ "-avoid_negative_ts",+ "make_zero",+ "-movflags",+ "+faststart",+ &dest.to_string_lossy(),+ ])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .await+ .map_err(|e| format!("spawn ffmpeg failed: {}", e))?;+ if !status.success() {+ return Err(format!("ffmpeg copy clip failed (exit {})", status));+ }+ Ok(())+}++async fn run_reencode_clip(+ source: &Path,+ start: f64,+ duration: f64,+ dest: &Path,+) -> Result<(), String> {+ let status = process::command("ffmpeg")+ .args([+ "-y",+ "-ss",+ &format!("{:.3}", start),+ "-i",+ &source.to_string_lossy(),+ "-t",+ &format!("{:.3}", duration),+ "-c:v",+ "libx264",+ "-preset",+ "veryfast",+ "-crf",+ "20",+ "-c:a",+ "aac",+ "-b:a",+ "128k",+ "-movflags",+ "+faststart",+ &dest.to_string_lossy(),+ ])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .await+ .map_err(|e| format!("spawn ffmpeg failed: {}", e))?;+ if !status.success() {+ return Err(format!("ffmpeg reencode clip failed (exit {})", status));+ }+ Ok(())+}diff --git a/src-tauri/src/commands/diagnostics.rs b/src-tauri/src/commands/diagnostics.rsindex cc86ad02..25fd90f3 100644--- a/src-tauri/src/commands/diagnostics.rs+++ b/src-tauri/src/commands/diagnostics.rs@@ -2,3 +2,8 @@pub fn get_rate_limit_stats() -> serde_json::Value {crate::core::ytdlp::get_rate_limit_stats()}++#[tauri::command]+pub async fn get_hwaccel_info() -> omniget_core::core::hwaccel::HwAccelInfo {+ omniget_core::core::hwaccel::detect_hwaccel().await+}diff --git a/src-tauri/src/commands/downloads.rs b/src-tauri/src/commands/downloads.rsindex 053a2430..115067dd 100644--- a/src-tauri/src/commands/downloads.rs+++ b/src-tauri/src/commands/downloads.rs@@ -179,6 +179,7 @@ pub async fn download_from_url(let mut q = download_queue.lock().await;q.max_concurrent = settings.advanced.max_concurrent_downloads.max(1);q.stagger_delay_ms = settings.advanced.stagger_delay_ms;+ q.default_max_retries = settings.advanced.max_retries;if q.has_url(&url) {tracing::debug!("[perf] download_from_url took {:?}", _timer_start.elapsed());return Err("Download already in progress for this URL".to_string());@@ -438,6 +439,16 @@ pub fn get_recovery_items() -> Vec<crate::core::recovery::RecoveryItem> {crate::core::recovery::list()}+#[tauri::command]+pub fn get_download_history() -> Vec<crate::core::queue_history::HistoryEntry> {+ crate::core::queue_history::list()+}++#[tauri::command]+pub fn clear_download_history() {+ crate::core::queue_history::clear_all();+}+#[tauri::command]pub fn discard_recovery() {crate::core::recovery::clear_all();@@ -520,6 +531,70 @@ pub async fn update_max_concurrent(Ok(format!("Max concurrent set to {}", max))}+#[tauri::command]+pub async fn pause_all_downloads(+ app: tauri::AppHandle,+ state: tauri::State<'_, AppState>,+) -> Result<u32, String> {+ let (state_to_emit, count, paused_torrents) = {+ let mut q = state.download_queue.lock().await;+ let paused = q.pause_all();+ let n = paused.len() as u32;+ let torrents: Vec<usize> = paused.iter().filter_map(|(_, tid)| *tid).collect();+ (q.get_state(), n, torrents)+ };+ if let Some(session) = state.torrent_session.lock().await.as_ref() {+ for tid in paused_torrents {+ if let Some(handle) = session.get(librqbit::api::TorrentIdOrHash::Id(tid)) {+ let _ = session.pause(&handle).await;+ }+ }+ }+ emit_queue_state_from_state(&app, state_to_emit);+ Ok(count)+}++#[tauri::command]+pub async fn resume_all_downloads(+ app: tauri::AppHandle,+ state: tauri::State<'_, AppState>,+) -> Result<u32, String> {+ let (state_to_emit, count, resumed_torrents) = {+ let mut q = state.download_queue.lock().await;+ let resumed = q.resume_all();+ let n = resumed.len() as u32;+ let torrents: Vec<usize> = resumed.iter().filter_map(|(_, tid)| *tid).collect();+ (q.get_state(), n, torrents)+ };+ if let Some(session) = state.torrent_session.lock().await.as_ref() {+ for tid in resumed_torrents {+ if let Some(handle) = session.get(librqbit::api::TorrentIdOrHash::Id(tid)) {+ let _ = session.unpause(&handle).await;+ }+ }+ }+ emit_queue_state_from_state(&app, state_to_emit);+ queue::try_start_next(app, state.download_queue.clone()).await;+ Ok(count)+}++#[tauri::command]+pub async fn reorder_queue(+ app: tauri::AppHandle,+ state: tauri::State<'_, AppState>,+ ids: Vec<u64>,+) -> Result<bool, String> {+ let (changed, state_to_emit) = {+ let mut q = state.download_queue.lock().await;+ let ok = q.reorder(ids);+ (ok, q.get_state())+ };+ if changed {+ emit_queue_state_from_state(&app, state_to_emit);+ }+ Ok(changed)+}+#[tauri::command]pub async fn clear_finished_downloads(app: tauri::AppHandle,diff --git a/src-tauri/src/commands/extension_cookies.rs b/src-tauri/src/commands/extension_cookies.rsnew file mode 100644index 00000000..67f2df4e--- /dev/null+++ b/src-tauri/src/commands/extension_cookies.rs@@ -0,0 +1,212 @@+use std::collections::BTreeMap;++use serde::Serialize;++use crate::native_host::extension_cookie_file_path;++#[derive(Debug, Serialize)]+pub struct ExtensionCookiesStatus {+ pub file_exists: bool,+ pub file_path: String,+ pub last_modified_secs: Option<i64>,+ pub age_seconds: Option<i64>,+ pub total_cookies: i64,+ pub domains: Vec<String>,+}++#[tauri::command]+pub async fn extension_cookies_status() -> Result<ExtensionCookiesStatus, String> {+ let path = extension_cookie_file_path();+ let file_path = path.to_string_lossy().into_owned();+ if !path.exists() {+ return Ok(ExtensionCookiesStatus {+ file_exists: false,+ file_path,+ last_modified_secs: None,+ age_seconds: None,+ total_cookies: 0,+ domains: Vec::new(),+ });+ }+ let metadata = std::fs::metadata(&path).map_err(|e| e.to_string())?;+ let last_modified = metadata+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_secs() as i64);+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .ok()+ .map(|d| d.as_secs() as i64);+ let age = match (now, last_modified) {+ (Some(n), Some(m)) => Some(n - m),+ _ => None,+ };+ let content = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let mut total = 0i64;+ let mut domains: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();+ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() {+ continue;+ }+ let effective = if line.starts_with("#HttpOnly_") {+ &line["#HttpOnly_".len()..]+ } else if line.starts_with('#') {+ continue;+ } else {+ line+ };+ let parts: Vec<&str> = effective.split('\t').collect();+ if parts.len() < 7 {+ continue;+ }+ total += 1;+ let domain = parts[0].trim_start_matches('.').to_lowercase();+ domains.insert(domain);+ }+ Ok(ExtensionCookiesStatus {+ file_exists: true,+ file_path,+ last_modified_secs: last_modified,+ age_seconds: age,+ total_cookies: total,+ domains: domains.into_iter().collect(),+ })+}++#[derive(Debug, Clone, Serialize)]+pub struct ExtensionCookieEntry {+ pub name: String,+ pub value: String,+ pub domain: String,+ pub path: String,+ pub secure: bool,+ pub http_only: bool,+}++#[derive(Debug, Serialize)]+pub struct ExtensionCookieBundle {+ pub domain: String,+ pub cookies: Vec<ExtensionCookieEntry>,+ pub cookie_string: String,+ pub fetched_at: i64,+ pub source_path: String,+ pub well_known: BTreeMap<String, String>,+}++const WELL_KNOWN_NAMES: &[&str] = &[+ "__Secure-3PAPISID",+ "__Secure-1PAPISID",+ "__Secure-3PSID",+ "__Secure-1PSID",+ "SAPISID",+ "SID",+ "HSID",+ "SSID",+ "APISID",+ "LOGIN_INFO",+ "VISITOR_INFO1_LIVE",+ "PREF",+];++fn cookie_domain_matches(request_domain: &str, cookie_domain: &str, include_subdomains: bool) -> bool {+ if include_subdomains {+ request_domain == cookie_domain+ || request_domain.ends_with(&format!(".{}", cookie_domain))+ } else {+ request_domain == cookie_domain+ }+}++#[tauri::command]+pub async fn read_extension_cookies(+ domain: String,+) -> Result<Option<ExtensionCookieBundle>, String> {+ let path = extension_cookie_file_path();+ if !path.exists() {+ return Ok(None);+ }+ let content = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let request_domain = domain.trim_start_matches('.').to_lowercase();++ let mut cookies: Vec<ExtensionCookieEntry> = Vec::new();+ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() {+ continue;+ }+ let is_http_only_line = line.starts_with("#HttpOnly_");+ let effective = if is_http_only_line {+ &line["#HttpOnly_".len()..]+ } else if line.starts_with('#') {+ continue;+ } else {+ line+ };+ let parts: Vec<&str> = effective.split('\t').collect();+ if parts.len() < 7 {+ continue;+ }+ let raw_domain = parts[0];+ let include_subdomains = parts[1].eq_ignore_ascii_case("TRUE");+ let cookie_domain = raw_domain.trim_start_matches('.').to_lowercase();+ if !cookie_domain_matches(&request_domain, &cookie_domain, include_subdomains) {+ continue;+ }+ let path_field = parts[2].to_string();+ let secure = parts[3].eq_ignore_ascii_case("TRUE");+ let name = parts[5].to_string();+ let value = parts[6].to_string();+ cookies.push(ExtensionCookieEntry {+ name,+ value,+ domain: raw_domain.to_string(),+ path: path_field,+ secure,+ http_only: is_http_only_line,+ });+ }++ if cookies.is_empty() {+ return Ok(None);+ }++ let mut seen = std::collections::HashSet::new();+ let mut deduped: Vec<&ExtensionCookieEntry> = Vec::new();+ for c in cookies.iter().rev() {+ if seen.insert(c.name.clone()) {+ deduped.push(c);+ }+ }+ deduped.reverse();++ let cookie_string = deduped+ .iter()+ .map(|c| format!("{}={}", c.name, c.value))+ .collect::<Vec<_>>()+ .join("; ");++ let mut well_known = BTreeMap::new();+ for c in &deduped {+ if WELL_KNOWN_NAMES.iter().any(|w| *w == c.name) {+ well_known.insert(c.name.clone(), c.value.clone());+ }+ }++ let fetched_at = std::fs::metadata(&path)+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_secs() as i64)+ .unwrap_or(0);++ Ok(Some(ExtensionCookieBundle {+ domain: request_domain,+ cookies: deduped.into_iter().cloned().collect(),+ cookie_string,+ fetched_at,+ source_path: path.to_string_lossy().into_owned(),+ well_known,+ }))+}diff --git a/src-tauri/src/commands/host_queue.rs b/src-tauri/src/commands/host_queue.rsindex f1898bf2..69ed5284 100644--- a/src-tauri/src/commands/host_queue.rs+++ b/src-tauri/src/commands/host_queue.rs@@ -86,6 +86,12 @@ pub async fn enqueue_external_inner(kind: Some(kind),external: true,thumbnail_url_override: args.thumbnail_url,+ retry_count: 0,+ max_retries: 0,+ resume_state: None,+ concurrent_segments: None,+ segment_size_bytes: None,+ eta_seconds: None,};{@@ -197,8 +203,11 @@ pub async fn report_complete_inner(}it.status = QueueStatus::Complete { success: true };} else {+ let msg = args.error.clone().unwrap_or_else(|| "Unknown error".to_string());+ let retryable = crate::core::queue::is_retryable_error_message(&msg);it.status = QueueStatus::Error {- message: args.error.clone().unwrap_or_else(|| "Unknown error".to_string()),+ message: msg,+ retryable,};}Some(q.get_state())diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex f21cdf3c..91d8a693 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,12 +1,17 @@pub mod app_lifecycle;pub mod auth_webview;+pub mod browser_extension;+pub mod extension_cookies;pub mod autostart;+pub mod clip;pub mod diagnostics;pub mod downloads;pub mod host_queue;pub mod integration;pub mod p2p;pub mod plugins;+pub mod reencode;+pub mod rpc;pub mod settings;#[cfg(not(target_os = "android"))]diff --git a/src-tauri/src/commands/reencode.rs b/src-tauri/src/commands/reencode.rsnew file mode 100644index 00000000..e0c4ea7a--- /dev/null+++ b/src-tauri/src/commands/reencode.rs@@ -0,0 +1,217 @@+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use omniget_core::core::ffmpeg;+use omniget_core::core::hwaccel;+use omniget_core::core::process;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum ReencodeCodec {+ Av1,+ Hevc,+ H264,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReencodeRequest {+ pub input_path: String,+ pub output_path: Option<String>,+ pub codec: ReencodeCodec,+ pub cq: Option<u32>,+ pub replace_original: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReencodeResult {+ pub output_path: String,+ pub encoder_used: String,+ pub used_hwaccel: bool,+ pub original_size_bytes: u64,+ pub new_size_bytes: u64,+ pub savings_pct: f64,+ pub replaced_original: bool,+}++#[tauri::command]+pub async fn reencode_video(req: ReencodeRequest) -> Result<ReencodeResult, String> {+ if !ffmpeg::is_ffmpeg_available().await {+ return Err("ffmpeg not found".to_string());+ }++ let input = PathBuf::from(&req.input_path);+ if !input.is_file() {+ return Err(format!("source not found: {}", req.input_path));+ }+ let original_size = std::fs::metadata(&input)+ .map(|m| m.len())+ .unwrap_or(0);++ let output = req.output_path.clone().unwrap_or_else(|| {+ let stem = input.file_stem().and_then(|s| s.to_str()).unwrap_or("out");+ let parent = input+ .parent()+ .map(|p| p.to_path_buf())+ .unwrap_or_else(|| PathBuf::from("."));+ let ext = match req.codec {+ ReencodeCodec::Av1 | ReencodeCodec::Hevc => "mp4",+ ReencodeCodec::H264 => "mp4",+ };+ parent+ .join(format!("{}.reencoded.{}", stem, ext))+ .to_string_lossy()+ .into_owned()+ });+ let output_path = PathBuf::from(&output);+ if let Some(parent) = output_path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| format!("mkdir failed: {}", e))?;+ }++ let hw = hwaccel::detect_hwaccel().await;+ let (encoder, used_hw) = pick_encoder(&req.codec, &hw);++ let cq = req.cq.unwrap_or(match req.codec {+ ReencodeCodec::Av1 => 32,+ ReencodeCodec::Hevc => 28,+ ReencodeCodec::H264 => 22,+ });+ let cq_str = cq.to_string();+ let cq_label = if encoder.contains("nvenc")+ || encoder.contains("qsv")+ || encoder.contains("amf")+ || encoder.contains("videotoolbox")+ {+ "-cq"+ } else {+ "-crf"+ };++ let status = process::command("ffmpeg")+ .args([+ "-y",+ "-hwaccel",+ "auto",+ "-i",+ input.to_string_lossy().as_ref(),+ "-c:v",+ &encoder,+ cq_label,+ &cq_str,+ "-c:a",+ "copy",+ "-movflags",+ "+faststart",+ output_path.to_string_lossy().as_ref(),+ ])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .await+ .map_err(|e| format!("spawn ffmpeg failed: {}", e))?;++ if !status.success() {+ return Err(format!(+ "ffmpeg reencode failed (exit {}). encoder={}",+ status, encoder+ ));+ }+ if !output_path.is_file() {+ return Err("output file missing after ffmpeg".to_string());+ }++ let new_size = std::fs::metadata(&output_path)+ .map(|m| m.len())+ .unwrap_or(0);+ let savings_pct = if original_size > 0 {+ 100.0 * (original_size as f64 - new_size as f64) / original_size as f64+ } else {+ 0.0+ };++ let replace = req.replace_original.unwrap_or(false);+ let mut replaced = false;+ if replace && new_size > 0 && new_size < original_size {+ let backup = backup_path(&input);+ std::fs::rename(&input, &backup)+ .map_err(|e| format!("rename original→backup failed: {}", e))?;+ if let Err(e) = std::fs::rename(&output_path, &input) {+ let _ = std::fs::rename(&backup, &input);+ return Err(format!("rename new→original failed: {}", e));+ }+ let _ = std::fs::remove_file(&backup);+ replaced = true;+ }++ let final_path = if replaced {+ input.clone()+ } else {+ output_path.clone()+ };++ Ok(ReencodeResult {+ output_path: final_path.to_string_lossy().into_owned(),+ encoder_used: encoder,+ used_hwaccel: used_hw,+ original_size_bytes: original_size,+ new_size_bytes: new_size,+ savings_pct,+ replaced_original: replaced,+ })+}++fn pick_encoder(codec: &ReencodeCodec, hw: &hwaccel::HwAccelInfo) -> (String, bool) {+ let candidates: &[(&str, ReencodeCodec)] = match codec {+ ReencodeCodec::Av1 => &[+ ("av1_nvenc", ReencodeCodec::Av1),+ ("av1_qsv", ReencodeCodec::Av1),+ ("av1_amf", ReencodeCodec::Av1),+ ("libsvtav1", ReencodeCodec::Av1),+ ],+ ReencodeCodec::Hevc => &[+ ("hevc_nvenc", ReencodeCodec::Hevc),+ ("hevc_qsv", ReencodeCodec::Hevc),+ ("hevc_amf", ReencodeCodec::Hevc),+ ("hevc_videotoolbox", ReencodeCodec::Hevc),+ ("hevc_vaapi", ReencodeCodec::Hevc),+ ("libx265", ReencodeCodec::Hevc),+ ],+ ReencodeCodec::H264 => &[+ ("h264_nvenc", ReencodeCodec::H264),+ ("h264_qsv", ReencodeCodec::H264),+ ("h264_amf", ReencodeCodec::H264),+ ("h264_videotoolbox", ReencodeCodec::H264),+ ("h264_vaapi", ReencodeCodec::H264),+ ("libx264", ReencodeCodec::H264),+ ],+ };++ for (enc, _) in candidates {+ let is_hw = !enc.starts_with("lib");+ let available = if is_hw {+ hw.encoders.iter().any(|e| e == enc)+ } else {+ true+ };+ if available {+ return (enc.to_string(), is_hw);+ }+ }+ let fallback = match codec {+ ReencodeCodec::Av1 => "libsvtav1",+ ReencodeCodec::Hevc => "libx265",+ ReencodeCodec::H264 => "libx264",+ };+ (fallback.to_string(), false)+}++fn backup_path(p: &Path) -> PathBuf {+ let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or("file");+ let ext = p.extension().and_then(|s| s.to_str()).unwrap_or("");+ let parent = p.parent().unwrap_or_else(|| Path::new("."));+ if ext.is_empty() {+ parent.join(format!("{}.backup", stem))+ } else {+ parent.join(format!("{}.backup.{}", stem, ext))+ }+}diff --git a/src-tauri/src/commands/rpc.rs b/src-tauri/src/commands/rpc.rsnew file mode 100644index 00000000..eeb4cd1b--- /dev/null+++ b/src-tauri/src/commands/rpc.rs@@ -0,0 +1,54 @@+use serde_json::Value;++use crate::core::rpc;+use crate::storage::config;++#[tauri::command]+pub async fn rpc_test_connection(app: tauri::AppHandle) -> Result<Value, String> {+ let settings = config::load_settings(&app);+ rpc::test_connection(settings.rpc.clone()).await+}++#[tauri::command]+pub async fn rpc_set_source(+ app: tauri::AppHandle,+ source: String,+ details: String,+ state: String,+ duration: i64,+ position: i64,+ paused: bool,+ large_image_key: Option<String>,+) -> Result<Value, String> {+ let settings = config::load_settings(&app);+ rpc::set_presence_source(+ settings.rpc.clone(),+ source,+ details,+ state,+ duration,+ position,+ paused,+ large_image_key,+ )+ .await+}++#[tauri::command]+pub async fn rpc_clear_source(+ app: tauri::AppHandle,+ source: String,+) -> Result<Value, String> {+ let settings = config::load_settings(&app);+ rpc::clear_source(settings.rpc.clone(), source).await+}++#[tauri::command]+pub async fn rpc_set_idle_stats(+ app: tauri::AppHandle,+ downloads_count: u64,+ total_bytes: u64,+) -> Result<Value, String> {+ let settings = config::load_settings(&app);+ rpc::set_idle_stats(settings.rpc.clone(), downloads_count, total_bytes).await+}diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rsindex 81f8c6d7..6cc15adb 100644--- a/src-tauri/src/commands/settings.rs+++ b/src-tauri/src/commands/settings.rs@@ -12,7 +12,12 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettlet mut current = config::load_settings(&app);let old_hotkey_enabled = current.download.hotkey_enabled;let old_hotkey_binding = current.download.hotkey_binding.clone();+ let old_clip_hotkey_enabled = current.download.clip_hotkey_enabled;+ let old_clip_hotkey_binding = current.download.clip_hotkey_binding.clone();+ let old_music_hotkey_enabled = current.download.music_hotkey_enabled;+ let old_music_hotkey_binding = current.download.music_hotkey_binding.clone();let old_start_with_system = current.start_with_system;+ let old_rpc = current.rpc.clone();let patch: serde_json::Value =serde_json::from_str(&partial).map_err(|e| format!("Invalid JSON: {}", e))?;@@ -23,9 +28,16 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettconfig::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;crate::core::http_client::init_proxy(current.proxy.clone());+ crate::core::http_fetcher::set_global_max_concurrent_segments(+ current.advanced.max_concurrent_segments as usize,+ );if old_hotkey_enabled != current.download.hotkey_enabled|| old_hotkey_binding != current.download.hotkey_binding+ || old_clip_hotkey_enabled != current.download.clip_hotkey_enabled+ || old_clip_hotkey_binding != current.download.clip_hotkey_binding+ || old_music_hotkey_enabled != current.download.music_hotkey_enabled+ || old_music_hotkey_binding != current.download.music_hotkey_binding{hotkey::reregister(&app);}@@ -34,6 +46,17 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettcrate::commands::autostart::apply_autostart(&app, current.start_with_system)?;}+ if old_rpc.enabled != current.rpc.enabled+ || old_rpc.app_id != current.rpc.app_id+ || old_rpc.large_image_key != current.rpc.large_image_key+ {+ let new_rpc = current.rpc.clone();+ let prev_app_id = old_rpc.app_id.clone();+ tauri::async_runtime::spawn(async move {+ crate::core::rpc::handle_settings_changed(new_rpc, prev_app_id).await;+ });+ }+Ok(current)}diff --git a/src-tauri/src/core/host_limiter.rs b/src-tauri/src/core/host_limiter.rsnew file mode 100644index 00000000..8320ff3b--- /dev/null+++ b/src-tauri/src/core/host_limiter.rs@@ -0,0 +1,177 @@+use std::collections::HashMap;+use std::sync::{Arc, OnceLock};++use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};++const DEFAULT_PER_HOST_LIMIT: usize = 4;+const YOUTUBE_PER_HOST_LIMIT: usize = 2;+const INSTAGRAM_PER_HOST_LIMIT: usize = 2;+const TIKTOK_PER_HOST_LIMIT: usize = 2;+const TWITTER_PER_HOST_LIMIT: usize = 2;+const REDDIT_PER_HOST_LIMIT: usize = 3;++const DEFAULT_REQUEST_INTERVAL_MS: u64 = 0;+const YOUTUBE_REQUEST_INTERVAL_MS: u64 = 1500;+const INSTAGRAM_REQUEST_INTERVAL_MS: u64 = 2000;+const TIKTOK_REQUEST_INTERVAL_MS: u64 = 1500;+const TWITTER_REQUEST_INTERVAL_MS: u64 = 1500;+const REDDIT_REQUEST_INTERVAL_MS: u64 = 1000;++#[derive(Default)]+struct HostState {+ semaphores: HashMap<String, Arc<Semaphore>>,+ last_dispatch: HashMap<String, std::time::Instant>,+}++fn state() -> &'static Mutex<HostState> {+ static STATE: OnceLock<Mutex<HostState>> = OnceLock::new();+ STATE.get_or_init(|| Mutex::new(HostState::default()))+}++pub fn host_key_for_url(url: &str) -> String {+ let parsed = match url::Url::parse(url) {+ Ok(u) => u,+ Err(_) => return "unknown".to_string(),+ };+ let host = parsed.host_str().unwrap_or("unknown").to_lowercase();+ canonicalize_host(&host)+}++fn canonicalize_host(host: &str) -> String {+ let trimmed = host.trim_start_matches("www.");+ if trimmed.contains("youtube.com") || trimmed.contains("youtu.be") || trimmed.contains("googlevideo.com") {+ return "youtube".to_string();+ }+ if trimmed.contains("instagram.com") || trimmed.contains("cdninstagram.com") {+ return "instagram".to_string();+ }+ if trimmed.contains("tiktok.com") || trimmed.contains("tiktokcdn.com") {+ return "tiktok".to_string();+ }+ if trimmed.contains("twitter.com") || trimmed.contains("x.com") || trimmed.contains("twimg.com") {+ return "twitter".to_string();+ }+ if trimmed.contains("reddit.com") || trimmed.contains("redd.it") || trimmed.contains("redditmedia.com") {+ return "reddit".to_string();+ }+ if trimmed.contains("vimeo.com") || trimmed.contains("vimeocdn.com") {+ return "vimeo".to_string();+ }+ if trimmed.contains("twitch.tv") || trimmed.contains("ttvnw.net") {+ return "twitch".to_string();+ }+ if trimmed.contains("bilibili.com") || trimmed.contains("bilivideo.com") {+ return "bilibili".to_string();+ }+ if trimmed.contains("bsky.app") || trimmed.contains("bsky.social") {+ return "bluesky".to_string();+ }+ if trimmed.contains("pinterest") || trimmed.contains("pinimg.com") {+ return "pinterest".to_string();+ }+ if trimmed.contains("soundcloud.com") {+ return "soundcloud".to_string();+ }+ if trimmed.contains("facebook.com") || trimmed.contains("fbcdn.net") {+ return "facebook".to_string();+ }+ trimmed.to_string()+}++fn limit_for_host(key: &str) -> usize {+ match key {+ "youtube" => YOUTUBE_PER_HOST_LIMIT,+ "instagram" => INSTAGRAM_PER_HOST_LIMIT,+ "tiktok" => TIKTOK_PER_HOST_LIMIT,+ "twitter" => TWITTER_PER_HOST_LIMIT,+ "reddit" => REDDIT_PER_HOST_LIMIT,+ _ => DEFAULT_PER_HOST_LIMIT,+ }+}++fn interval_ms_for_host(key: &str) -> u64 {+ match key {+ "youtube" => YOUTUBE_REQUEST_INTERVAL_MS,+ "instagram" => INSTAGRAM_REQUEST_INTERVAL_MS,+ "tiktok" => TIKTOK_REQUEST_INTERVAL_MS,+ "twitter" => TWITTER_REQUEST_INTERVAL_MS,+ "reddit" => REDDIT_REQUEST_INTERVAL_MS,+ _ => DEFAULT_REQUEST_INTERVAL_MS,+ }+}++pub struct HostLease {+ _permit: OwnedSemaphorePermit,+}++pub async fn acquire(host_key: &str) -> HostLease {+ let semaphore = {+ let mut guard = state().lock().await;+ guard+ .semaphores+ .entry(host_key.to_string())+ .or_insert_with(|| Arc::new(Semaphore::new(limit_for_host(host_key))))+ .clone()+ };++ let permit = semaphore+ .acquire_owned()+ .await+ .expect("host semaphore closed unexpectedly");++ let interval_ms = interval_ms_for_host(host_key);+ if interval_ms > 0 {+ let wait = {+ let mut guard = state().lock().await;+ let now = std::time::Instant::now();+ let last = guard.last_dispatch.get(host_key).copied();+ let wait = match last {+ Some(t) => {+ let elapsed = now.duration_since(t).as_millis() as u64;+ interval_ms.saturating_sub(elapsed)+ }+ None => 0,+ };+ guard.last_dispatch.insert(+ host_key.to_string(),+ now + std::time::Duration::from_millis(wait),+ );+ wait+ };+ if wait > 0 {+ tokio::time::sleep(std::time::Duration::from_millis(wait)).await;+ }+ }++ HostLease { _permit: permit }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn youtube_variants_canonicalize() {+ assert_eq!(host_key_for_url("https://www.youtube.com/watch?v=abc"), "youtube");+ assert_eq!(host_key_for_url("https://youtu.be/abc"), "youtube");+ assert_eq!(host_key_for_url("https://r5---sn-foo.googlevideo.com/x"), "youtube");+ }++ #[test]+ fn x_and_twitter_share_bucket() {+ assert_eq!(host_key_for_url("https://x.com/jack/status/1"), "twitter");+ assert_eq!(host_key_for_url("https://twitter.com/jack/status/1"), "twitter");+ }++ #[test]+ fn unknown_host_returns_clean_string() {+ assert_eq!(host_key_for_url("https://example.org/foo"), "example.org");+ assert_eq!(host_key_for_url("not a url"), "unknown");+ }++ #[test]+ fn limits_have_sensible_defaults() {+ assert!(limit_for_host("youtube") <= DEFAULT_PER_HOST_LIMIT);+ assert!(limit_for_host("example.org") == DEFAULT_PER_HOST_LIMIT);+ }+}diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsindex 38c8543c..8d112953 100644--- a/src-tauri/src/core/mod.rs+++ b/src-tauri/src/core/mod.rs@@ -7,6 +7,7 @@ pub use omniget_core::core::ffmpeg;pub use omniget_core::core::filename;pub use omniget_core::core::hls_downloader;pub use omniget_core::core::http_client;+pub use omniget_core::core::http_fetcher;pub use omniget_core::core::hwaccel;pub use omniget_core::core::media_processor;pub use omniget_core::core::paths;@@ -18,7 +19,10 @@ pub use omniget_core::core::ytdlp;pub mod download_log;pub mod events;+pub mod host_limiter;pub mod path_limits;pub mod queue;+pub mod queue_history;pub mod recovery;+pub mod rpc;pub mod url_parser;diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rsindex 08969bdf..c84b54a2 100644--- a/src-tauri/src/core/queue.rs+++ b/src-tauri/src/core/queue.rs@@ -93,7 +93,16 @@ pub enum QueueStatus {Paused,Seeding,Complete { success: bool },- Error { message: String },+ Error { message: String, retryable: bool },+}++pub fn is_retryable_error_message(message: &str) -> bool {+ let lower = message.to_lowercase();+ if lower.contains("cancel") {+ return false;+ }+ let (category, _) = omniget_core::core::errors::classify_download_error(message);+ matches!(category, "unknown" | "rate_limited")}#[derive(Clone, Serialize)]@@ -115,6 +124,8 @@ pub struct QueueItemInfo {pub kind: Option<QueueKind>,#[serde(default)]pub external: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,}pub struct QueueItem {@@ -147,6 +158,12 @@ pub struct QueueItem {pub kind: Option<QueueKind>,pub external: bool,pub thumbnail_url_override: Option<String>,+ pub retry_count: u32,+ pub max_retries: u32,+ pub resume_state: Option<serde_json::Value>,+ pub concurrent_segments: Option<usize>,+ pub segment_size_bytes: Option<u64>,+ pub eta_seconds: Option<u64>,}impl QueueItem {@@ -170,6 +187,7 @@ impl QueueItem {.or_else(|| self.media_info.as_ref().and_then(|m| m.thumbnail_url.clone())),kind: self.kind,external: self.external,+ eta_seconds: self.eta_seconds,}}}@@ -178,6 +196,7 @@ pub struct DownloadQueue {pub items: Vec<QueueItem>,pub max_concurrent: u32,pub stagger_delay_ms: u64,+ pub default_max_retries: u32,}impl DownloadQueue {@@ -186,6 +205,7 @@ impl DownloadQueue {items: Vec::new(),max_concurrent,stagger_delay_ms: 150,+ default_max_retries: 3,}}@@ -242,6 +262,12 @@ impl DownloadQueue {kind: computed_kind,external: false,thumbnail_url_override: None,+ retry_count: 0,+ max_retries: self.default_max_retries,+ resume_state: None,+ concurrent_segments: None,+ segment_size_bytes: None,+ eta_seconds: None,};crate::core::recovery::persist(crate::core::recovery::RecoveryItem {id: item.id,@@ -257,6 +283,77 @@ impl DownloadQueue {self.items.push(item);}+ pub fn hydrate_from_history(&mut self) {+ let entries = crate::core::queue_history::list();+ if entries.is_empty() {+ return;+ }+ let placeholder: Arc<dyn PlatformDownloader> =+ Arc::new(crate::platforms::noop::NoopDownloader::new());+ for entry in entries.iter().rev() {+ if self.items.iter().any(|i| i.id == entry.id) {+ continue;+ }+ let status = if entry.success {+ QueueStatus::Complete { success: true }+ } else {+ let msg = entry.error.clone().unwrap_or_default();+ let retryable = is_retryable_error_message(&msg);+ QueueStatus::Error {+ message: msg,+ retryable,+ }+ };+ let percent = if entry.success { 100.0 } else { 0.0 };+ let item = QueueItem {+ id: entry.id,+ url: entry.url.clone(),+ platform: entry.platform.clone(),+ title: entry.title.clone(),+ status,+ cancel_token: CancellationToken::new(),+ output_dir: entry+ .file_path+ .as_ref()+ .and_then(|p| {+ std::path::Path::new(p)+ .parent()+ .map(|x| x.to_string_lossy().to_string())+ })+ .unwrap_or_default(),+ download_mode: None,+ quality: None,+ format_id: None,+ referer: None,+ extra_headers: None,+ page_url: None,+ user_agent: None,+ percent,+ speed_bytes_per_sec: 0.0,+ downloaded_bytes: entry.file_size_bytes.unwrap_or(0),+ total_bytes: entry.total_bytes,+ file_path: entry.file_path.clone(),+ file_size_bytes: entry.file_size_bytes,+ file_count: None,+ media_info: None,+ downloader: placeholder.clone(),+ ytdlp_path: None,+ from_hotkey: false,+ torrent_id: None,+ kind: entry.kind,+ external: false,+ thumbnail_url_override: entry.thumbnail_url.clone(),+ retry_count: 0,+ max_retries: 0,+ resume_state: None,+ concurrent_segments: None,+ segment_size_bytes: None,+ eta_seconds: None,+ };+ self.items.push(item);+ }+ }+pub fn active_count(&self) -> u32 {self.items.iter()@@ -290,18 +387,43 @@ impl DownloadQueue {file_size_bytes: Option<u64>,) {if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {+ let error_for_history = error.clone();if success {item.status = QueueStatus::Complete { success: true };item.percent = 100.0;} else {+ let msg = error.unwrap_or_default();+ let retryable = is_retryable_error_message(&msg);item.status = QueueStatus::Error {- message: error.unwrap_or_default(),+ message: msg,+ retryable,};}item.file_path = file_path;item.file_size_bytes = file_size_bytes;item.speed_bytes_per_sec = 0.0;crate::core::recovery::remove(id);++ if !item.external {+ let entry = crate::core::queue_history::HistoryEntry {+ id: item.id,+ url: item.url.clone(),+ platform: item.platform.clone(),+ title: item.title.clone(),+ file_path: item.file_path.clone(),+ file_size_bytes: item.file_size_bytes,+ total_bytes: item.total_bytes,+ success,+ error: if success { None } else { error_for_history },+ completed_at: crate::core::queue_history::now_unix_seconds(),+ thumbnail_url: item+ .thumbnail_url_override+ .clone()+ .or_else(|| item.media_info.as_ref().and_then(|m| m.thumbnail_url.clone())),+ kind: item.kind,+ };+ crate::core::queue_history::record(entry);+ }}}@@ -331,6 +453,7 @@ impl DownloadQueue {downloaded: u64,total: Option<u64>,torrent_id: Option<usize>,+ eta_seconds: Option<u64>,) {if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {item.percent = percent;@@ -342,6 +465,7 @@ impl DownloadQueue {if torrent_id.is_some() && item.torrent_id.is_none() {item.torrent_id = torrent_id;}+ item.eta_seconds = eta_seconds;}}@@ -374,6 +498,99 @@ impl DownloadQueue {false}+ pub fn pause_all(&mut self) -> Vec<(u64, Option<usize>)> {+ let mut paused = Vec::new();+ for item in self.items.iter_mut() {+ if item.status == QueueStatus::Active {+ if item.platform != "magnet" {+ item.cancel_token.cancel();+ }+ item.status = QueueStatus::Paused;+ item.speed_bytes_per_sec = 0.0;+ paused.push((item.id, item.torrent_id));+ }+ }+ paused+ }++ pub fn resume_all(&mut self) -> Vec<(u64, Option<usize>)> {+ let mut resumed = Vec::new();+ for item in self.items.iter_mut() {+ if item.status == QueueStatus::Paused {+ let tid = item.torrent_id;+ if item.platform == "magnet" {+ item.status = QueueStatus::Active;+ } else {+ item.status = QueueStatus::Queued;+ item.cancel_token = CancellationToken::new();+ }+ resumed.push((item.id, tid));+ }+ }+ resumed+ }++ pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {+ let mut slots: Vec<Option<QueueItem>> =+ self.items.drain(..).map(Some).collect();++ let queued_slot_indices: Vec<usize> = slots+ .iter()+ .enumerate()+ .filter_map(|(idx, slot)| {+ slot.as_ref()+ .filter(|i| i.status == QueueStatus::Queued)+ .map(|_| idx)+ })+ .collect();++ if queued_slot_indices.is_empty() {+ self.items = slots.into_iter().flatten().collect();+ return false;+ }++ let queued_id_to_slot: std::collections::HashMap<u64, usize> = queued_slot_indices+ .iter()+ .map(|idx| (slots[*idx].as_ref().unwrap().id, *idx))+ .collect();++ let mut new_queued_order: Vec<QueueItem> =+ Vec::with_capacity(queued_slot_indices.len());+ let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();++ for id in &ids_in_order {+ if seen.contains(id) {+ continue;+ }+ if let Some(slot_idx) = queued_id_to_slot.get(id) {+ if let Some(item) = slots[*slot_idx].take() {+ new_queued_order.push(item);+ seen.insert(*id);+ }+ }+ }+ for idx in &queued_slot_indices {+ if let Some(item) = slots[*idx].take() {+ new_queued_order.push(item);+ }+ }++ let mut iter = new_queued_order.into_iter();+ let mut rebuilt: Vec<QueueItem> = Vec::with_capacity(slots.len());+ for (idx, slot) in slots.into_iter().enumerate() {+ if queued_slot_indices.contains(&idx) {+ if let Some(item) = iter.next() {+ rebuilt.push(item);+ }+ } else if let Some(item) = slot {+ rebuilt.push(item);+ }+ }+ rebuilt.extend(iter);+ self.items = rebuilt;+ true+ }+/// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {let result = self.cancel_inner(id);@@ -390,6 +607,7 @@ impl DownloadQueue {item.cancel_token.cancel();item.status = QueueStatus::Error {message: "Cancelled".to_string(),+ retryable: false,};item.speed_bytes_per_sec = 0.0;return (true, None);@@ -398,6 +616,7 @@ impl DownloadQueue {let tid = item.torrent_id;item.status = QueueStatus::Error {message: "Cancelled".to_string(),+ retryable: false,};item.speed_bytes_per_sec = 0.0;return (true, tid);@@ -414,6 +633,7 @@ impl DownloadQueue {};item.status = QueueStatus::Error {message: "Cancelled".to_string(),+ retryable: false,};item.speed_bytes_per_sec = 0.0;return (true, tid);@@ -421,6 +641,7 @@ impl DownloadQueue {QueueStatus::Queued => {item.status = QueueStatus::Error {message: "Cancelled".to_string(),+ retryable: false,};return (true, None);}@@ -440,6 +661,7 @@ impl DownloadQueue {item.downloaded_bytes = 0;item.file_path = None;item.file_size_bytes = None;+ item.retry_count = 0;return true;}}@@ -451,6 +673,7 @@ impl DownloadQueue {let result = self.remove_inner(id);if result.is_some() {crate::core::recovery::remove(id);+ crate::core::queue_history::remove(id);}result}@@ -487,6 +710,7 @@ impl DownloadQueue {.collect();for id in &to_remove {crate::core::recovery::remove(*id);+ crate::core::queue_history::remove(*id);}self.items.retain(|i| {!matches!(@@ -548,6 +772,8 @@ pub struct QueueItemProgress {pub downloaded_bytes: u64,pub total_bytes: Option<u64>,pub phase: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub eta_seconds: Option<u64>,}pub fn emit_queue_state_from_state(app: &tauri::AppHandle, state: Vec<QueueItemInfo>) {@@ -696,9 +922,22 @@ async fn spawn_download_inner(downloaded_bytes: 0,total_bytes: None,phase: "preparing".to_string(),+ eta_seconds: None,},);+ let host_key = {+ let q = queue.lock().await;+ q.items+ .iter()+ .find(|i| i.id == item_id)+ .map(|i| crate::core::host_limiter::host_key_for_url(&i.url))+ };+ let _host_lease = match host_key {+ Some(key) => Some(crate::core::host_limiter::acquire(&key).await),+ None => None,+ };+let (url,output_dir,@@ -766,6 +1005,7 @@ async fn spawn_download_inner(downloaded_bytes: 0,total_bytes: None,phase: "fetching_info".to_string(),+ eta_seconds: None,},);@@ -849,6 +1089,7 @@ async fn spawn_download_inner(downloaded_bytes: 0,total_bytes: info.file_size_bytes,phase: "starting".to_string(),+ eta_seconds: None,},);@@ -921,10 +1162,25 @@ async fn spawn_download_inner(let phase = match percent {p if p < -1.5 => "connecting",p if p < -0.5 => "starting",+ p if p > 99.5 => "finalizing",p if p > 0.0 => "downloading",_ => "starting",};+ let eta_seconds = omniget_core::core::ytdlp::get_eta(item_id).or_else(|| {+ if current_speed > 0.0 {+ total_bytes.and_then(|total| {+ if downloaded_bytes >= total {+ None+ } else {+ Some(((total - downloaded_bytes) as f64 / current_speed) as u64)+ }+ })+ } else {+ None+ }+ });+{let mut q = queue_progress.lock().await;let tid = { *torrent_id_slot_progress.lock().await };@@ -935,6 +1191,7 @@ async fn spawn_download_inner(downloaded_bytes,total_bytes,tid,+ eta_seconds,);}@@ -949,9 +1206,11 @@ async fn spawn_download_inner(downloaded_bytes,total_bytes,phase: phase.to_string(),+ eta_seconds,},);}+ omniget_core::core::ytdlp::clear_eta(item_id);});if let Some(ua) = opts.user_agent.clone() {@@ -1081,6 +1340,58 @@ async fn spawn_download_inner(category,raw_err);++ let retry_decision = {+ let mut q = queue.lock().await;+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {+ if item.downloaded_bytes > 5 * 1024 * 1024 {+ item.retry_count = 0;+ }+ let retryable = is_retryable_category(category);+ let attempt = item.retry_count;+ let max = item.max_retries;+ if retryable && attempt < max {+ item.retry_count = attempt + 1;+ Some((attempt + 1, max))+ } else {+ None+ }+ } else {+ None+ }+ };++ if let Some((next_attempt, max)) = retry_decision {+ let delay_secs = (1u64 << (next_attempt - 1).min(5)).min(30);+ tracing::warn!(+ "[queue] retry {}/{} for {} in {}s (category={})",+ next_attempt,+ max,+ item_id,+ delay_secs,+ category+ );+ let state = {+ let mut q = queue.lock().await;+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {+ item.status = QueueStatus::Queued;+ item.cancel_token = CancellationToken::new();+ item.percent = 0.0;+ item.speed_bytes_per_sec = 0.0;+ item.downloaded_bytes = 0;+ }+ q.get_state()+ };+ emit_queue_state_from_state(&app, state);+ let app_for_retry = app.clone();+ let queue_for_retry = queue.clone();+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;+ try_start_next(app_for_retry, queue_for_retry).await;+ });+ return;+ }+let state = {let mut q = queue.lock().await;q.mark_complete(item_id, false, Some(user_msg), None, None);@@ -1093,6 +1404,10 @@ async fn spawn_download_inner(try_start_next(app, queue).await;}+fn is_retryable_category(category: &str) -> bool {+ matches!(category, "unknown" | "rate_limited")+}+async fn fetch_and_cache_info(url: &str,downloader: &dyn PlatformDownloader,@@ -1245,6 +1560,7 @@ pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutexdownloaded_bytes: 0,total_bytes: None,phase: "queued_starting".to_string(),+ eta_seconds: None,},);diff --git a/src-tauri/src/core/queue_history.rs b/src-tauri/src/core/queue_history.rsnew file mode 100644index 00000000..53fe25a2--- /dev/null+++ b/src-tauri/src/core/queue_history.rs@@ -0,0 +1,140 @@+use std::collections::VecDeque;+use std::io::Write;+use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};++use serde::{Deserialize, Serialize};++use crate::core::queue::QueueKind;++const HISTORY_FILE: &str = "download-history.json";+const MAX_HISTORY_ENTRIES: usize = 200;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct HistoryEntry {+ pub id: u64,+ pub url: String,+ pub platform: String,+ pub title: String,+ #[serde(default)]+ pub file_path: Option<String>,+ #[serde(default)]+ pub file_size_bytes: Option<u64>,+ #[serde(default)]+ pub total_bytes: Option<u64>,+ pub success: bool,+ #[serde(default)]+ pub error: Option<String>,+ pub completed_at: i64,+ #[serde(default)]+ pub thumbnail_url: Option<String>,+ #[serde(default)]+ pub kind: Option<QueueKind>,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+struct HistoryFile {+ #[serde(default)]+ entries: Vec<HistoryEntry>,+}++fn store() -> &'static Mutex<VecDeque<HistoryEntry>> {+ static STORE: OnceLock<Mutex<VecDeque<HistoryEntry>>> = OnceLock::new();+ STORE.get_or_init(|| Mutex::new(VecDeque::new()))+}++fn file_path() -> Option<PathBuf> {+ crate::core::paths::app_data_dir().map(|d| d.join(HISTORY_FILE))+}++fn write_to_disk(entries: &VecDeque<HistoryEntry>) {+ let Some(path) = file_path() else { return };+ let Some(parent) = path.parent() else { return };+ if let Err(e) = std::fs::create_dir_all(parent) {+ tracing::warn!("[history] create_dir_all failed: {}", e);+ return;+ }+ let file_data = HistoryFile {+ entries: entries.iter().cloned().collect(),+ };+ let serialized = match serde_json::to_string_pretty(&file_data) {+ Ok(s) => s,+ Err(e) => {+ tracing::warn!("[history] serialize failed: {}", e);+ return;+ }+ };+ let tmp = path.with_extension("json.tmp");+ let write_result = (|| -> std::io::Result<()> {+ let mut f = std::fs::File::create(&tmp)?;+ f.write_all(serialized.as_bytes())?;+ f.sync_all()?;+ Ok(())+ })();+ if let Err(e) = write_result {+ tracing::warn!("[history] write tmp failed: {}", e);+ let _ = std::fs::remove_file(&tmp);+ return;+ }+ if let Err(e) = std::fs::rename(&tmp, &path) {+ tracing::warn!("[history] rename failed: {}", e);+ let _ = std::fs::remove_file(&tmp);+ }+}++pub fn init_from_disk() {+ let Some(path) = file_path() else { return };+ let content = match std::fs::read_to_string(&path) {+ Ok(c) => c,+ Err(_) => return,+ };+ let parsed: HistoryFile = match serde_json::from_str(&content) {+ Ok(v) => v,+ Err(e) => {+ tracing::warn!("[history] parse failed: {}", e);+ return;+ }+ };+ let mut guard = store().lock().unwrap();+ guard.clear();+ for entry in parsed.entries.into_iter().take(MAX_HISTORY_ENTRIES) {+ guard.push_back(entry);+ }+}++pub fn record(entry: HistoryEntry) {+ let mut guard = store().lock().unwrap();+ guard.retain(|e| e.id != entry.id);+ guard.push_back(entry);+ while guard.len() > MAX_HISTORY_ENTRIES {+ guard.pop_front();+ }+ write_to_disk(&guard);+}++pub fn list() -> Vec<HistoryEntry> {+ let guard = store().lock().unwrap();+ guard.iter().rev().cloned().collect()+}++pub fn remove(id: u64) {+ let mut guard = store().lock().unwrap();+ let before = guard.len();+ guard.retain(|e| e.id != id);+ if guard.len() != before {+ write_to_disk(&guard);+ }+}++pub fn clear_all() {+ let mut guard = store().lock().unwrap();+ guard.clear();+ write_to_disk(&guard);+}++pub fn now_unix_seconds() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs() as i64)+ .unwrap_or(0)+}diff --git a/src-tauri/src/core/rpc.rs b/src-tauri/src/core/rpc.rsnew file mode 100644index 00000000..1d1d8e5f--- /dev/null+++ b/src-tauri/src/core/rpc.rs@@ -0,0 +1,522 @@+use std::collections::HashMap;+use std::sync::Mutex;++use discord_rich_presence::activity::{Activity, Assets, Button, Timestamps};+use discord_rich_presence::{DiscordIpc, DiscordIpcClient};+use once_cell::sync::Lazy;+use serde_json::{json, Value};++pub use omniget_core::models::settings::RpcSettings;++const GITHUB_BUTTON_LABEL: &str = "View on GitHub";+const GITHUB_BUTTON_URL: &str = "https://github.com/tonhowtf/omniget";+const APP_LARGE_TEXT: &str = "omniget";++const SOURCE_PRIORITIES: &[&str] = &["focus", "music", "video", "course", "reading"];++fn priority_of(source: &str) -> usize {+ SOURCE_PRIORITIES+ .iter()+ .position(|s| *s == source)+ .unwrap_or(SOURCE_PRIORITIES.len())+}++#[derive(Debug, Clone)]+struct SourceActivity {+ source: String,+ details: String,+ state: String,+ duration_secs: i64,+ position_secs: i64,+ paused: bool,+ large_image_key: Option<String>,+ timestamp: i64,+}++#[derive(Debug, Clone, Copy, Default)]+struct IdleStats {+ downloads_count: u64,+ total_bytes: u64,+}++struct RpcState {+ client: Option<DiscordIpcClient>,+ connected: bool,+ connected_app_id: String,+ session_start_ts: i64,+ activities: HashMap<String, SourceActivity>,+ idle_stats: IdleStats,+ last_displayed_source: Option<String>,+}++static RPC: Lazy<Mutex<RpcState>> = Lazy::new(|| {+ Mutex::new(RpcState {+ client: None,+ connected: false,+ connected_app_id: String::new(),+ session_start_ts: 0,+ activities: HashMap::new(),+ idle_stats: IdleStats::default(),+ last_displayed_source: None,+ })+});++fn disconnect_locked(state: &mut RpcState) {+ if let Some(client) = state.client.as_mut() {+ let _ = client.clear_activity();+ let _ = client.close();+ }+ state.client = None;+ state.connected = false;+ state.connected_app_id.clear();+ state.last_displayed_source = None;+}++fn ensure_connected_with(app_id: &str) -> bool {+ let mut state = match RPC.lock() {+ Ok(g) => g,+ Err(_) => return false,+ };+ if state.connected && state.connected_app_id == app_id {+ return true;+ }+ if state.connected_app_id != app_id {+ disconnect_locked(&mut state);+ }+ if state.client.is_none() {+ match DiscordIpcClient::new(app_id) {+ Ok(c) => state.client = Some(c),+ Err(_) => return false,+ }+ }+ if let Some(client) = state.client.as_mut() {+ if client.connect().is_ok() {+ state.connected = true;+ state.connected_app_id = app_id.to_string();+ if state.session_start_ts == 0 {+ state.session_start_ts = chrono::Utc::now().timestamp();+ }+ return true;+ }+ }+ false+}++fn truncate_for_discord(s: &str, max: usize) -> String {+ if s.chars().count() <= max {+ return s.to_string();+ }+ let truncated: String = s.chars().take(max - 1).collect();+ format!("{}…", truncated)+}++fn format_position_duration(position: i64, duration: i64) -> Option<String> {+ if duration <= 0 {+ return None;+ }+ let p = position.max(0);+ let fmt = |sec: i64| -> String {+ let m = sec / 60;+ let s = sec % 60;+ format!("{}:{:02}", m, s)+ };+ Some(format!("{} / {}", fmt(p), fmt(duration)))+}++fn format_bytes_short(bytes: u64) -> String {+ let units = ["B", "KB", "MB", "GB", "TB"];+ let mut value = bytes as f64;+ let mut idx = 0;+ while value >= 1024.0 && idx < units.len() - 1 {+ value /= 1024.0;+ idx += 1;+ }+ if idx == 0 {+ format!("{} {}", bytes, units[idx])+ } else if value >= 100.0 {+ format!("{:.0} {}", value, units[idx])+ } else {+ format!("{:.1} {}", value, units[idx])+ }+}++fn format_count_short(count: u64) -> String {+ if count < 1_000 {+ count.to_string()+ } else if count < 1_000_000 {+ let v = count as f64 / 1_000.0;+ if v >= 100.0 {+ format!("{:.0}k", v)+ } else {+ format!("{:.1}k", v)+ }+ } else {+ let v = count as f64 / 1_000_000.0;+ format!("{:.1}M", v)+ }+}++fn redact(settings: &RpcSettings) -> Value {+ let connected = match RPC.lock() {+ Ok(g) => g.connected && !settings.app_id.is_empty() && g.connected_app_id == settings.app_id,+ Err(_) => false,+ };+ json!({+ "enabled": settings.enabled,+ "app_id": settings.app_id,+ "large_image_key": settings.large_image_key,+ "connected": connected,+ })+}++pub fn settings_view(settings: &RpcSettings) -> Value {+ redact(settings)+}++fn select_top_activity(state: &RpcState) -> Option<SourceActivity> {+ state+ .activities+ .values()+ .min_by_key(|a| (priority_of(&a.source), -a.timestamp))+ .cloned()+}++fn idle_state_text(stats: IdleStats) -> String {+ if stats.downloads_count == 0 {+ return "Ready".to_string();+ }+ if stats.total_bytes == 0 {+ return format!("{} downloads", format_count_short(stats.downloads_count));+ }+ format!(+ "{} downloads · {}",+ format_count_short(stats.downloads_count),+ format_bytes_short(stats.total_bytes)+ )+}++fn apply_top_activity(default_image: &str) -> bool {+ let mut state = match RPC.lock() {+ Ok(g) => g,+ Err(_) => return false,+ };+ let session_start = state.session_start_ts;+ let idle_stats = state.idle_stats;+ let top = select_top_activity(&state);+ let client = match state.client.as_mut() {+ Some(c) => c,+ None => return false,+ };++ let (details_str, state_str, source_tag, img_key_owned) = match top {+ Some(a) => {+ let mut details = if a.details.is_empty() {+ "—".to_string()+ } else {+ truncate_for_discord(&a.details, 64)+ };+ if details.chars().count() < 2 {+ details.push(' ');+ details.push(' ');+ }+ let scrub = if !a.paused {+ format_position_duration(a.position_secs, a.duration_secs)+ } else {+ None+ };+ let mut state_text = if a.state.is_empty() {+ String::new()+ } else {+ truncate_for_discord(&a.state, 64)+ };+ if let Some(s) = scrub {+ if state_text.is_empty() {+ state_text = s;+ } else {+ state_text = format!("{} · {}", state_text, s);+ }+ }+ if state_text.is_empty() {+ state_text = "—".into();+ }+ let img = a+ .large_image_key+ .clone()+ .unwrap_or_else(|| default_image.to_string());+ (details, state_text, a.source.clone(), img)+ }+ None => {+ let details = "omniget".to_string();+ let state_text = idle_state_text(idle_stats);+ (details, state_text, "idle".to_string(), default_image.to_string())+ }+ };++ let assets = Assets::new().large_image(&img_key_owned).large_text(APP_LARGE_TEXT);+ let buttons = vec![Button::new(GITHUB_BUTTON_LABEL, GITHUB_BUTTON_URL)];++ let start = if session_start > 0 {+ session_start+ } else {+ chrono::Utc::now().timestamp()+ };+ let timestamps = Timestamps::new().start(start);++ let activity = Activity::new()+ .details(&details_str)+ .state(&state_str)+ .assets(assets)+ .buttons(buttons)+ .timestamps(timestamps);++ let result = client.set_activity(activity).is_ok();+ if !result {+ state.connected = false;+ state.last_displayed_source = None;+ return false;+ }+ state.last_displayed_source = Some(source_tag);+ true+}++pub async fn test_connection(settings: RpcSettings) -> Result<Value, String> {+ if settings.app_id.is_empty() {+ return Ok(json!({ "ok": false, "reason": "missing_app_id" }));+ }+ let app_id = settings.app_id.clone();+ let img = settings.large_image_key.clone();+ let ok = tokio::task::spawn_blocking(move || -> bool {+ if !ensure_connected_with(&app_id) {+ return false;+ }+ let mut state = match RPC.lock() {+ Ok(g) => g,+ Err(_) => return false,+ };+ let session_start = if state.session_start_ts > 0 {+ state.session_start_ts+ } else {+ chrono::Utc::now().timestamp()+ };+ let client = match state.client.as_mut() {+ Some(c) => c,+ None => return false,+ };+ let assets = Assets::new().large_image(&img).large_text(APP_LARGE_TEXT);+ let buttons = vec![Button::new(GITHUB_BUTTON_LABEL, GITHUB_BUTTON_URL)];+ let activity = Activity::new()+ .details("omniget")+ .state("Testing connection")+ .assets(assets)+ .buttons(buttons)+ .timestamps(Timestamps::new().start(session_start));+ let res = client.set_activity(activity).is_ok();+ state.last_displayed_source = Some("__test__".into());+ res+ })+ .await+ .map_err(|e| e.to_string())?;+ Ok(json!({ "ok": ok }))+}++pub async fn set_presence_source(+ settings: RpcSettings,+ source: String,+ details: String,+ state_text: String,+ duration_secs: i64,+ position_secs: i64,+ paused: bool,+ large_image_key: Option<String>,+) -> Result<Value, String> {+ if !settings.enabled || settings.app_id.is_empty() {+ let _ = tokio::task::spawn_blocking(|| {+ if let Ok(mut s) = RPC.lock() {+ if s.connected {+ disconnect_locked(&mut s);+ }+ s.activities.clear();+ }+ })+ .await;+ return Ok(json!({ "ok": false, "reason": "disabled" }));+ }++ let source_owned = if source.trim().is_empty() {+ "music".to_string()+ } else {+ source.trim().to_string()+ };+ let app_id = settings.app_id.clone();+ let default_img = settings.large_image_key.clone();+ let activity_record = SourceActivity {+ source: source_owned.clone(),+ details,+ state: state_text,+ duration_secs,+ position_secs,+ paused,+ large_image_key,+ timestamp: chrono::Utc::now().timestamp_millis(),+ };++ let outcome = tokio::task::spawn_blocking(move || -> bool {+ if !ensure_connected_with(&app_id) {+ return false;+ }+ if let Ok(mut state) = RPC.lock() {+ state.activities.insert(source_owned.clone(), activity_record);+ }+ apply_top_activity(&default_img)+ })+ .await+ .map_err(|e| e.to_string())?;++ Ok(json!({ "ok": outcome }))+}++pub async fn clear_source(settings: RpcSettings, source: String) -> Result<Value, String> {+ let default_img = settings.large_image_key.clone();+ let app_id = settings.app_id.clone();+ let enabled = settings.enabled;+ let source_owned = if source.trim().is_empty() {+ "music".to_string()+ } else {+ source.trim().to_string()+ };+ let _ = tokio::task::spawn_blocking(move || {+ if let Ok(mut state) = RPC.lock() {+ state.activities.remove(&source_owned);+ }+ if !enabled || app_id.is_empty() {+ return;+ }+ if !ensure_connected_with(&app_id) {+ return;+ }+ let _ = apply_top_activity(&default_img);+ })+ .await;+ Ok(json!({ "ok": true }))+}++pub async fn set_idle_stats(+ settings: RpcSettings,+ downloads_count: u64,+ total_bytes: u64,+) -> Result<Value, String> {+ if !settings.enabled || settings.app_id.is_empty() {+ return Ok(json!({ "ok": false, "reason": "disabled" }));+ }+ let app_id = settings.app_id.clone();+ let default_img = settings.large_image_key.clone();+ let outcome = tokio::task::spawn_blocking(move || -> bool {+ if let Ok(mut state) = RPC.lock() {+ state.idle_stats = IdleStats {+ downloads_count,+ total_bytes,+ };+ }+ if !ensure_connected_with(&app_id) {+ return false;+ }+ apply_top_activity(&default_img)+ })+ .await+ .map_err(|e| e.to_string())?;+ Ok(json!({ "ok": outcome }))+}++pub async fn handle_settings_changed(new_settings: RpcSettings, previous_app_id: String) {+ let id_changed = previous_app_id != new_settings.app_id;+ let disabled = !new_settings.enabled || new_settings.app_id.is_empty();+ if id_changed || disabled {+ let _ = tokio::task::spawn_blocking(|| {+ if let Ok(mut state) = RPC.lock() {+ disconnect_locked(&mut state);+ state.session_start_ts = 0;+ }+ })+ .await;+ }+ if !disabled {+ let app_id = new_settings.app_id.clone();+ let default_img = new_settings.large_image_key.clone();+ let _ = tokio::task::spawn_blocking(move || {+ if !ensure_connected_with(&app_id) {+ return;+ }+ let _ = apply_top_activity(&default_img);+ })+ .await;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn priority_order_focus_first() {+ assert!(priority_of("focus") < priority_of("music"));+ assert!(priority_of("music") < priority_of("video"));+ assert!(priority_of("video") < priority_of("course"));+ assert!(priority_of("course") < priority_of("reading"));+ }++ #[test]+ fn unknown_source_lowest_priority() {+ let unknown = priority_of("xyz");+ let known = priority_of("music");+ assert!(unknown > known);+ }++ #[test]+ fn format_position_duration_basic() {+ assert_eq!(format_position_duration(83, 245), Some("1:23 / 4:05".into()));+ }++ #[test]+ fn format_position_zero_duration_none() {+ assert_eq!(format_position_duration(50, 0), None);+ }++ #[test]+ fn count_short_thousands() {+ assert_eq!(format_count_short(999), "999");+ assert_eq!(format_count_short(1_200), "1.2k");+ assert_eq!(format_count_short(150_000), "150k");+ assert_eq!(format_count_short(1_500_000), "1.5M");+ }++ #[test]+ fn bytes_short_units() {+ assert_eq!(format_bytes_short(0), "0 B");+ assert_eq!(format_bytes_short(1500), "1.5 KB");+ assert_eq!(format_bytes_short(1_500_000_000), "1.4 GB");+ }++ #[test]+ fn idle_text_empty() {+ let stats = IdleStats::default();+ assert_eq!(idle_state_text(stats), "Ready");+ }++ #[test]+ fn idle_text_with_count_only() {+ let stats = IdleStats {+ downloads_count: 12,+ total_bytes: 0,+ };+ assert_eq!(idle_state_text(stats), "12 downloads");+ }++ #[test]+ fn idle_text_with_count_and_bytes() {+ let stats = IdleStats {+ downloads_count: 1234,+ total_bytes: 1_500_000_000,+ };+ assert_eq!(idle_state_text(stats), "1.2k downloads · 1.4 GB");+ }+}diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 4df885d3..878181ab 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -13,15 +13,23 @@ pub fn reregister(app: &tauri::AppHandle) {pub fn register_from_settings(app: &tauri::AppHandle) {let settings = config::load_settings(app);- if !settings.download.hotkey_enabled {- return;++ if settings.download.hotkey_enabled {+ register_one(app, &settings.download.hotkey_binding, "download");+ }+ if settings.download.clip_hotkey_enabled {+ register_one(app, &settings.download.clip_hotkey_binding, "clip");+ }+ if settings.download.music_hotkey_enabled {+ register_one(app, &settings.download.music_hotkey_binding, "music");}+}- let binding = &settings.download.hotkey_binding;+fn register_one(app: &tauri::AppHandle, binding: &str, label: &str) {match binding.parse::<Shortcut>() {Ok(shortcut) => {if let Err(e) = app.global_shortcut().register(shortcut) {- tracing::warn!("Failed to register hotkey '{}': {}", binding, e);+ tracing::warn!("[hotkey] register {} '{}' failed: {}", label, binding, e);#[cfg(target_os = "macos")]{tracing::warn!(@@ -39,16 +47,42 @@ pub fn register_from_settings(app: &tauri::AppHandle) {);}} else {- tracing::info!("[hotkey] registered: {}", binding);+ tracing::info!("[hotkey] registered {}: {}", label, binding);}}Err(e) => {- tracing::warn!("Invalid hotkey binding '{}': {:?}", binding, e);+ tracing::warn!("[hotkey] invalid {} binding '{}': {:?}", label, binding, e);}}}-pub fn on_hotkey_pressed(app: &tauri::AppHandle) {+pub fn on_hotkey_pressed(app: &tauri::AppHandle, shortcut: &Shortcut) {+ let settings = config::load_settings(app);++ let download_match = matches_binding(shortcut, &settings.download.hotkey_binding);+ let clip_match = matches_binding(shortcut, &settings.download.clip_hotkey_binding);+ let music_match = matches_binding(shortcut, &settings.download.music_hotkey_binding);++ if settings.download.clip_hotkey_enabled && clip_match {+ let _ = app.emit("clip-hotkey-pressed", serde_json::json!({}));+ return;+ }++ if settings.download.music_hotkey_enabled && music_match {+ handle_music_clipboard(app);+ return;+ }++ if settings.download.hotkey_enabled && download_match {+ handle_download_clipboard(app);+ }+}++fn matches_binding(pressed: &Shortcut, binding: &str) -> bool {+ binding.parse::<Shortcut>().map(|s| s == *pressed).unwrap_or(false)+}++fn handle_download_clipboard(app: &tauri::AppHandle) {let text = match app.clipboard().read_text() {Ok(t) => t,Err(_) => return,@@ -77,3 +111,18 @@ async fn enqueue_from_clipboard(app: &tauri::AppHandle, url: String) {let _ = app.emit("hotkey-download-queued", serde_json::json!({ "url": url }));}}++fn handle_music_clipboard(app: &tauri::AppHandle) {+ let text = match app.clipboard().read_text() {+ Ok(t) => t,+ Err(_) => return,+ };+ let text = text.trim().to_string();+ if text.is_empty() || (!text.starts_with("http://") && !text.starts_with("https://")) {+ return;+ }+ if url::Url::parse(&text).is_err() {+ return;+ }+ let _ = app.emit("music-hotkey-pressed", serde_json::json!({ "url": text }));+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex cbc0482e..43bc36e0 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -110,9 +110,9 @@ pub fn run() {.plugin(tauri_plugin_process::init()).plugin(tauri_plugin_global_shortcut::Builder::new()- .with_handler(|app, _shortcut, event| {+ .with_handler(|app, shortcut, event| {if event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed {- hotkey::on_hotkey_pressed(app);+ hotkey::on_hotkey_pressed(app, shortcut);}}).build(),@@ -127,6 +127,9 @@ pub fn run() {commands::host_queue::register_event_listeners(app.handle());let settings = storage::config::load_settings(app.handle());core::http_client::init_proxy(settings.proxy.clone());+ core::http_fetcher::set_global_max_concurrent_segments(+ settings.advanced.max_concurrent_segments as usize,+ );core::ytdlp::set_ext_cookie_path_fn(|| native_host::extension_cookie_file_path());core::ytdlp::set_global_cookie_file_fn(|| {let s = storage::config::load_settings_standalone();@@ -189,6 +192,21 @@ pub fn run() {));}core::recovery::init_from_disk();+ core::queue_history::init_from_disk();+ {+ let app_handle = app.handle().clone();+ tauri::async_runtime::spawn(async move {+ let state = app_handle.state::<AppState>();+ let snapshot = {+ let mut q = state.download_queue.lock().await;+ q.hydrate_from_history();+ q.get_state()+ };+ if !snapshot.is_empty() {+ core::queue::emit_queue_state_from_state(&app_handle, snapshot);+ }+ });+ }{let pending = core::recovery::list();if !pending.is_empty() {@@ -305,7 +323,15 @@ pub fn run() {}).invoke_handler(tauri::generate_handler![commands::auth_webview::open_auth_webview,+ commands::browser_extension::browser_extension_status,+ commands::browser_extension::browser_extension_export,+ commands::browser_extension::browser_extension_open_folder,+ commands::extension_cookies::read_extension_cookies,+ commands::extension_cookies::extension_cookies_status,+ commands::clip::clip_video,+ commands::reencode::reencode_video,commands::diagnostics::get_rate_limit_stats,+ commands::diagnostics::get_hwaccel_info,commands::downloads::detect_platform,commands::downloads::check_cookie_error,commands::downloads::validate_output_path,@@ -315,6 +341,9 @@ pub fn run() {commands::downloads::cancel_generic_download,commands::downloads::pause_download,commands::downloads::resume_download,+ commands::downloads::pause_all_downloads,+ commands::downloads::resume_all_downloads,+ commands::downloads::reorder_queue,commands::downloads::retry_download,commands::downloads::remove_download,commands::downloads::get_queue_state,@@ -326,6 +355,8 @@ pub fn run() {commands::downloads::get_recovery_items,commands::downloads::discard_recovery,commands::downloads::restore_recovery,+ commands::downloads::get_download_history,+ commands::downloads::clear_download_history,commands::downloads::reveal_file,commands::downloads::open_path_default,commands::host_queue::host_queue_enqueue_external,@@ -337,6 +368,10 @@ pub fn run() {commands::settings::reset_settings,commands::settings::mark_onboarding_complete,commands::settings::mark_legal_acknowledged,+ commands::rpc::rpc_test_connection,+ commands::rpc::rpc_set_source,+ commands::rpc::rpc_clear_source,+ commands::rpc::rpc_set_idle_stats,commands::autostart::set_autostart,commands::autostart::get_autostart_status,commands::dependencies::check_dependencies,diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 0b5ee088..2862bdc1 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -25,6 +25,7 @@ fn setup_environment() {std::env::set_var("PYTHONIOENCODING", "utf-8");std::env::set_var("PYTHONUTF8", "1");+ std::env::set_var("PYTHONLEGACYWINDOWSSTDIO", "0");#[cfg(target_os = "linux")]if std::env::var("WEBKIT_DISABLE_DMABUF_RENDERER").is_err() {diff --git a/src-tauri/src/native_host.rs b/src-tauri/src/native_host.rsindex 36280f35..8293c8ed 100644--- a/src-tauri/src/native_host.rs+++ b/src-tauri/src/native_host.rs@@ -25,6 +25,7 @@ const HOST_MANIFEST_NAME: &str = "wtf.tonho.omniget.json";struct NativeHostRequest {#[serde(rename = "type")]kind: String,+ #[serde(default)]url: String,#[serde(default, rename = "protocolVersion")]protocol_version: Option<u32>,@@ -499,6 +500,48 @@ fn sanitize_cookie_field(s: &str) -> String {.collect()}+fn root_domain_of(host: &str) -> String {+ let h = host.trim_start_matches('.').to_lowercase();+ let parts: Vec<&str> = h.split('.').collect();+ if parts.len() >= 2 {+ parts[parts.len() - 2..].join(".")+ } else {+ h+ }+}++fn format_cookie_line(c: &NativeCookie, session_ttl: u64) -> String {+ let raw_domain = sanitize_cookie_field(&c.domain);+ let path_field = sanitize_cookie_field(&c.path);+ let name = sanitize_cookie_field(&c.name);+ let value = sanitize_cookie_field(&c.value);+ let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };+ let is_host_only = c+ .host_only+ .unwrap_or_else(|| !raw_domain.starts_with('.'));+ let (domain, include_subdomains) = if is_host_only {+ let stripped = raw_domain+ .strip_prefix('.')+ .unwrap_or(&raw_domain)+ .to_string();+ (stripped, "FALSE")+ } else if raw_domain.starts_with('.') {+ (raw_domain.clone(), "TRUE")+ } else {+ (format!(".{}", raw_domain), "TRUE")+ };+ let secure = if c.secure { "TRUE" } else { "FALSE" };+ let expires = if c.expires == 0 {+ session_ttl+ } else {+ c.expires as u64+ };+ format!(+ "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",+ http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,+ )+}+fn write_extension_cookies(cookies: &[NativeCookie]) -> anyhow::Result<()> {let path = extension_cookie_file_path();if let Some(parent) = path.parent() {@@ -514,37 +557,47 @@ fn write_extension_cookies(cookies: &[NativeCookie]) -> anyhow::Result<()> {.as_secs();let session_ttl = now + 86400; // 24 h, same approach as Cookie-Editor+ // Merge with existing file: keep cookies whose root domain is NOT in the+ // incoming batch. Each platform capture only ships its own domains, so+ // overwriting the file would wipe other platforms' auth.+ let incoming_roots: std::collections::HashSet<String> = cookies+ .iter()+ .map(|c| root_domain_of(&c.domain))+ .collect();++ let mut preserved: Vec<String> = Vec::new();+ if let Ok(existing) = fs::read_to_string(&path) {+ for line in existing.lines() {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ let effective = if let Some(rest) = trimmed.strip_prefix("#HttpOnly_") {+ rest+ } else if trimmed.starts_with('#') {+ continue; // header / comment+ } else {+ trimmed+ };+ let parts: Vec<&str> = effective.split('\t').collect();+ if parts.len() < 7 {+ continue;+ }+ let domain = parts[0];+ let root = root_domain_of(domain);+ if !incoming_roots.contains(&root) {+ preserved.push(line.to_string());+ }+ }+ }+let mut content = String::from("# Netscape HTTP Cookie File\n");+ for line in &preserved {+ content.push_str(line);+ content.push('\n');+ }for c in cookies {- let raw_domain = sanitize_cookie_field(&c.domain);- let path_field = sanitize_cookie_field(&c.path);- let name = sanitize_cookie_field(&c.name);- let value = sanitize_cookie_field(&c.value);- let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };- let is_host_only = c- .host_only- .unwrap_or_else(|| !raw_domain.starts_with('.'));- let (domain, include_subdomains) = if is_host_only {- let stripped = raw_domain- .strip_prefix('.')- .unwrap_or(&raw_domain)- .to_string();- (stripped, "FALSE")- } else if raw_domain.starts_with('.') {- (raw_domain.clone(), "TRUE")- } else {- (format!(".{}", raw_domain), "TRUE")- };- let secure = if c.secure { "TRUE" } else { "FALSE" };- let expires = if c.expires == 0 {- session_ttl- } else {- c.expires as u64- };- content.push_str(&format!(- "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",- http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,- ));+ content.push_str(&format_cookie_line(c, session_ttl));}fs::write(&path, content)?;@@ -746,6 +799,35 @@ fn handle_request(request: NativeHostRequest) -> NativeHostResponse {}}+ if request.kind == "cookies:export" {+ if let Some(ref cookies) = request.cookies {+ if cookies.len() > MAX_COOKIES_PER_REQUEST {+ return NativeHostResponse {+ ok: false,+ code: Some("TOO_MANY_COOKIES"),+ message: Some(format!(+ "cookies:export contains {} cookies; max is {MAX_COOKIES_PER_REQUEST}",+ cookies.len()+ )),+ };+ }+ if !cookies.is_empty() {+ if let Err(e) = write_extension_cookies(cookies) {+ return NativeHostResponse {+ ok: false,+ code: Some("WRITE_FAILED"),+ message: Some(format!("write extension cookies: {}", e)),+ };+ }+ }+ }+ return NativeHostResponse {+ ok: true,+ code: None,+ message: None,+ };+ }+if request.kind != "enqueue" {return NativeHostResponse {ok: false,diff --git a/src-tauri/src/platforms/generic_ytdlp/mod.rs b/src-tauri/src/platforms/generic_ytdlp/mod.rsindex ddea932e..42e4b1d4 100644--- a/src-tauri/src/platforms/generic_ytdlp/mod.rs+++ b/src-tauri/src/platforms/generic_ytdlp/mod.rs@@ -266,7 +266,23 @@ impl PlatformDownloader for GenericYtdlpDownloader {.first().ok_or_else(|| anyhow!("No quality available"))?;- let selected = if let Some(ref wanted) = opts.quality {+ let requested_height = opts+ .quality+ .as_deref()+ .and_then(Self::extract_quality_height);++ let selected = if let Some(h) = requested_height {+ info.available_qualities+ .iter()+ .filter(|q| q.height > 0 && q.height <= h)+ .max_by_key(|q| q.height)+ .or_else(|| {+ opts.quality+ .as_deref()+ .and_then(|w| info.available_qualities.iter().find(|q| q.label == *w))+ })+ .unwrap_or(first)+ } else if let Some(ref wanted) = opts.quality {info.available_qualities.iter().find(|q| q.label == *wanted)@@ -417,7 +433,7 @@ impl PlatformDownloader for GenericYtdlpDownloader {ytdlp::ensure_ytdlp().await?};- let quality_height = Self::extract_quality_height(&selected.label);+ let quality_height = requested_height.or_else(|| Self::extract_quality_height(&selected.label));let video_url = &selected.url;let referer = opts@@ -425,23 +441,59 @@ impl PlatformDownloader for GenericYtdlpDownloader {.as_deref().or_else(|| platform_referer(video_url));- ytdlp::download_video(- &ytdlp_path,- video_url,- &opts.output_dir,- quality_height,- progress,- opts.download_mode.as_deref(),- opts.format_id.as_deref(),- opts.filename_template.as_deref(),- referer,- opts.cancel_token.clone(),- None,- opts.concurrent_fragments,- opts.download_subtitles,- &[],- )- .await+ let format_fallbacks: &[Option<&str>] = if opts.format_id.is_some() {+ &[None]+ } else {+ &[None, Some("b"), Some("worst")]+ };++ let mut last_err: Option<anyhow::Error> = None;+ for (idx, override_format) in format_fallbacks.iter().enumerate() {+ let effective_format = override_format.or(opts.format_id.as_deref());+ let attempt_progress = progress.clone();+ let result = ytdlp::download_video(+ &ytdlp_path,+ video_url,+ &opts.output_dir,+ quality_height,+ attempt_progress,+ opts.download_mode.as_deref(),+ effective_format,+ opts.filename_template.as_deref(),+ referer,+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ opts.download_subtitles,+ &[],+ )+ .await;++ match result {+ Ok(r) => return Ok(r),+ Err(e) => {+ let msg = e.to_string().to_lowercase();+ let is_format_error = msg.contains("requested format")+ || msg.contains("format is not available")+ || msg.contains("no video formats")+ || msg.contains("no suitable format");+ let has_more = idx + 1 < format_fallbacks.len();+ if is_format_error && has_more && !opts.cancel_token.is_cancelled() {+ tracing::warn!(+ "[generic_ytdlp] format fallback {}/{} after error: {}",+ idx + 1,+ format_fallbacks.len() - 1,+ e+ );+ last_err = Some(e);+ continue;+ }+ return Err(e);+ }+ }+ }++ Err(last_err.unwrap_or_else(|| anyhow!("download failed without specific error")))}}diff --git a/src-tauri/src/platforms/instagram/mod.rs b/src-tauri/src/platforms/instagram/mod.rsindex 9ad93dd7..523c85f8 100644--- a/src-tauri/src/platforms/instagram/mod.rs+++ b/src-tauri/src/platforms/instagram/mod.rs@@ -780,7 +780,7 @@ impl PlatformDownloader for InstagramDownloader {&output,progress.clone(),headers,- None,+ Some(&opts.cancel_token),).await{@@ -830,7 +830,7 @@ impl PlatformDownloader for InstagramDownloader {&output,tx,headers,- None,+ Some(&opts.cancel_token),).await{diff --git a/src-tauri/src/platforms/pinterest/mod.rs b/src-tauri/src/platforms/pinterest/mod.rsindex 5b9b193a..90739397 100644--- a/src-tauri/src/platforms/pinterest/mod.rs+++ b/src-tauri/src/platforms/pinterest/mod.rs@@ -240,7 +240,7 @@ impl PlatformDownloader for PinterestDownloader {&quality.url,&output_path,progress,- None,+ Some(&opts.cancel_token),).await?;diff --git a/src-tauri/src/platforms/reddit/mod.rs b/src-tauri/src/platforms/reddit/mod.rsindex db75a66f..66b44ec2 100644--- a/src-tauri/src/platforms/reddit/mod.rs+++ b/src-tauri/src/platforms/reddit/mod.rs@@ -206,17 +206,23 @@ impl RedditDownloader {video_url: &str,output: &std::path::Path,progress_tx: mpsc::Sender<f64>,+ cancel: Option<&tokio_util::sync::CancellationToken>,) -> anyhow::Result<u64> {let variants = Self::get_resolution_variants(video_url);let mut last_err = anyhow!("No resolution available");for variant in &variants {+ if let Some(token) = cancel {+ if token.is_cancelled() {+ return Err(anyhow!("Download cancelled"));+ }+ }match direct_downloader::download_direct(&self.client,variant,output,progress_tx.clone(),- None,+ cancel,).await{@@ -569,7 +575,12 @@ impl RedditDownloader {});let video_bytes = self- .download_video_with_fallback(&video_quality.url, &video_tmp, vtx)+ .download_video_with_fallback(+ &video_quality.url,+ &video_tmp,+ vtx,+ Some(&opts.cancel_token),+ ).await?;let _ = progress.send(60.0).await;@@ -589,7 +600,7 @@ impl RedditDownloader {audio_url,&audio_tmp,atx,- None,+ Some(&opts.cancel_token),).await.is_ok();@@ -641,7 +652,12 @@ impl RedditDownloader {.output_dir.join(format!("{}.mp4", sanitize_filename::sanitize(&info.title)));let bytes = self- .download_video_with_fallback(&video_quality.url, &output, progress)+ .download_video_with_fallback(+ &video_quality.url,+ &output,+ progress,+ Some(&opts.cancel_token),+ ).await?;Ok(DownloadResult {@@ -661,9 +677,14 @@ impl RedditDownloader {let output = opts.output_dir.join(format!("{}.gif", sanitize_filename::sanitize(&info.title)));- let bytes =- direct_downloader::download_direct(&self.client, url, &output, progress, None)- .await?;+ let bytes = direct_downloader::download_direct(+ &self.client,+ url,+ &output,+ progress,+ Some(&opts.cancel_token),+ )+ .await?;Ok(DownloadResult {file_path: output,@@ -688,7 +709,7 @@ impl RedditDownloader {&quality.url,&output,progress,- None,+ Some(&opts.cancel_token),).await?;@@ -719,7 +740,7 @@ impl RedditDownloader {&quality.url,&output,tx,- None,+ Some(&opts.cancel_token),).await?;diff --git a/src-tauri/src/platforms/tiktok/mod.rs b/src-tauri/src/platforms/tiktok/mod.rsindex c8f221e8..ea5ac7eb 100644--- a/src-tauri/src/platforms/tiktok/mod.rs+++ b/src-tauri/src/platforms/tiktok/mod.rs@@ -619,7 +619,7 @@ impl PlatformDownloader for TikTokDownloader {&output,tx,Some(headers.clone()),- None,+ Some(&opts.cancel_token),).await?;@@ -652,7 +652,7 @@ impl PlatformDownloader for TikTokDownloader {&output,progress,Some(headers),- None,+ Some(&opts.cancel_token),).await?;diff --git a/src-tauri/src/platforms/twitch/mod.rs b/src-tauri/src/platforms/twitch/mod.rsindex 077f4821..11289bdd 100644--- a/src-tauri/src/platforms/twitch/mod.rs+++ b/src-tauri/src/platforms/twitch/mod.rs@@ -345,7 +345,7 @@ impl PlatformDownloader for TwitchClipsDownloader {&selected.url,&output_path,progress,- None,+ Some(&opts.cancel_token),).await?;diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rsindex df480b85..c1f3858f 100644--- a/src-tauri/src/platforms/twitter/mod.rs+++ b/src-tauri/src/platforms/twitter/mod.rs@@ -501,7 +501,7 @@ impl PlatformDownloader for TwitterDownloader {&quality.url,&output,progress,- None,+ Some(&opts.cancel_token),).await?;@@ -526,9 +526,14 @@ impl PlatformDownloader for TwitterDownloader {let output = opts.output_dir.join(&filename);let (tx, _rx) = mpsc::channel(8);- let bytes =- direct_downloader::download_direct(&self.client, &quality.url, &output, tx, None)- .await?;+ let bytes = direct_downloader::download_direct(+ &self.client,+ &quality.url,+ &output,+ tx,+ Some(&opts.cancel_token),+ )+ .await?;total_bytes += bytes;last_path = output;diff --git a/src-tauri/src/platforms/youtube/mod.rs b/src-tauri/src/platforms/youtube/mod.rsindex 9fa77087..3dcfcdb2 100644--- a/src-tauri/src/platforms/youtube/mod.rs+++ b/src-tauri/src/platforms/youtube/mod.rs@@ -290,9 +290,14 @@ impl PlatformDownloader for YouTubeDownloader {ytdlp::ensure_ytdlp().await?};+ let quality_height = opts+ .quality+ .as_deref()+ .and_then(Self::extract_quality_height);+if info.media_type == MediaType::Playlist {return self- .download_playlist(info, opts, progress, &ytdlp_path)+ .download_playlist(info, opts, progress, &ytdlp_path, quality_height).await;}@@ -301,27 +306,14 @@ impl PlatformDownloader for YouTubeDownloader {.first().ok_or_else(|| anyhow!("No quality available"))?;- let quality_height = if let Some(ref wanted) = opts.quality {- if wanted == "best" {- None- } else {- Self::extract_quality_height(wanted)- }- } else {- None- };-- let selected = if let Some(ref wanted) = opts.quality {- if wanted == "best" {- first- } else {- info.available_qualities- .iter()- .find(|q| q.label == *wanted)- .unwrap_or(first)- }- } else {- first+ let selected = match quality_height {+ Some(h) => info+ .available_qualities+ .iter()+ .filter(|q| q.height > 0 && q.height <= h)+ .max_by_key(|q| q.height)+ .unwrap_or(first),+ None => first,};let video_url = &selected.url;@@ -352,6 +344,7 @@ impl YouTubeDownloader {opts: &DownloadOptions,progress: mpsc::Sender<f64>,ytdlp_path: &std::path::Path,+ quality_height: Option<u32>,) -> anyhow::Result<DownloadResult> {let playlist_dir = opts.output_dir@@ -385,7 +378,7 @@ impl YouTubeDownloader {ytdlp_path,&entry.url,&playlist_dir,- None,+ quality_height,video_tx,opts.download_mode.as_deref(),None,diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rsindex 77db5285..7fcf019a 100644--- a/src-tauri/src/plugin_loader.rs+++ b/src-tauri/src/plugin_loader.rs@@ -179,12 +179,14 @@ fn load_single_plugin(PluginLoadError::simple("manifest_parse", format!("Invalid plugin.json: {e}"))})?;- let lib_path = find_native_lib(plugin_dir).ok_or_else(|| {- PluginLoadError::simple(- "no_native_lib",- format!("No native library found in {}", plugin_dir.display()),- )- })?;+ let lib_path = find_native_lib(plugin_dir, manifest.rust_crate.as_deref()).ok_or_else(+ || {+ PluginLoadError::simple(+ "no_native_lib",+ format!("No native library found in {}", plugin_dir.display()),+ )+ },+ )?;let lib = unsafe { libloading::Library::new(&lib_path) }.map_err(|e| {PluginLoadError::simple(@@ -236,7 +238,7 @@ fn load_single_plugin(})}-fn find_native_lib(dir: &Path) -> Option<PathBuf> {+fn find_native_lib(dir: &Path, rust_crate: Option<&str>) -> Option<PathBuf> {let extensions = if cfg!(target_os = "windows") {&["dll"][..]} else if cfg!(target_os = "macos") {@@ -245,6 +247,21 @@ fn find_native_lib(dir: &Path) -> Option<PathBuf> {&["so"][..]};+ if let Some(crate_name) = rust_crate {+ for ext in extensions {+ let candidate = dir.join(format!("{}.{}", crate_name, ext));+ if candidate.is_file() {+ return Some(candidate);+ }+ if !cfg!(target_os = "windows") {+ let unix_candidate = dir.join(format!("lib{}.{}", crate_name, ext));+ if unix_candidate.is_file() {+ return Some(unix_candidate);+ }+ }+ }+ }+for entry in fs::read_dir(dir).ok()? {let path = entry.ok()?.path();if let Some(ext) = path.extension() {diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex e27d7a38..b2ee370d 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,10 +1,10 @@{"$schema": "https://schema.tauri.app/config/2","productName": "omniget",- "version": "0.5.2",+ "version": "0.6.0","identifier": "wtf.tonho.omniget","build": {- "beforeDevCommand": "pnpm plugins:deploy && pnpm dev",+ "beforeDevCommand": "pnpm dev","devUrl": "http://localhost:1420","beforeBuildCommand": "pnpm build","frontendDist": "../build"@@ -47,6 +47,10 @@"active": true,"targets": "all","createUpdaterArtifacts": true,+ "resources": {+ "../browser-extension/chrome/": "browser-extension/chrome/",+ "../browser-extension/firefox/": "browser-extension/firefox/"+ },"icon": ["icons/32x32.png","icons/128x128.png",diff --git a/src/components/dialog/DialogContainer.svelte b/src/components/dialog/DialogContainer.svelteindex 8d15dd45..4806f76b 100644--- a/src/components/dialog/DialogContainer.svelte+++ b/src/components/dialog/DialogContainer.svelte@@ -18,9 +18,18 @@let closing = $state(false);$effect(() => {- if (isOpen && dialogEl && !dialogEl.open) {+ if (!dialogEl) return;+ if (isOpen && !dialogEl.open) {previousFocusEl = document.activeElement as HTMLElement;dialogEl.showModal();+ } else if (!isOpen && dialogEl.open && !closing) {+ closing = true;+ setTimeout(() => {+ closing = false;+ dialogEl?.close();+ previousFocusEl?.focus();+ previousFocusEl = null;+ }, 150);}});diff --git a/src/components/onboarding/OnboardingWizard.svelte b/src/components/onboarding/OnboardingWizard.svelteindex 55e15565..db4ae034 100644--- a/src/components/onboarding/OnboardingWizard.svelte+++ b/src/components/onboarding/OnboardingWizard.svelte@@ -13,7 +13,7 @@version: string | null;};- const TOTAL_STEPS = 6;+ const TOTAL_STEPS = 7;const SUGGESTED_PLUGINS = [{ id: "courses", name: "Course Downloader", desc: "Hotmart, Udemy, Kiwify, Teachable, Kajabi, MasterClass and 30+ more" },@@ -28,6 +28,13 @@let settings = $derived(getSettings());let selectedPlugins = $state<Set<string>>(new Set(["courses"]));let hotkeyEnabled = $state(false);+ let rpcEnabled = $state(true);++ $effect(() => {+ if (settings) {+ rpcEnabled = settings.rpc?.enabled ?? true;+ }+ });$effect(() => {if (dialogEl && !dialogEl.open) {@@ -98,6 +105,11 @@if (hotkeyEnabled) {await updateSettings({ download: { hotkey_enabled: true } });}+ await updateSettings({ rpc: { enabled: rpcEnabled } });+ if (rpcEnabled) {+ const { rpcSyncIdleStats } = await import("$lib/rpc");+ void rpcSyncIdleStats();+ }await completeOnboarding();}@@ -143,6 +155,7 @@<option value="ja">日本語</option><option value="it">Italiano</option><option value="fr">Français</option>+ <option value="es">Español</option><option value="el">Ελληνικά</option></select></div>@@ -281,6 +294,26 @@</div>{:else if step === 6}+ <div class="step step-rpc">+ <div class="step-icon">+ <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="9" />+ <path d="M8 10c1.5 0 2.5 1 2.5 2s-1 2-2.5 2M16 10c-1.5 0-2.5 1-2.5 2s1 2 2.5 2" />+ </svg>+ </div>+ <h2>{$t("onboarding.rpc_title")}</h2>+ <p class="step-desc">{$t("onboarding.rpc_desc")}</p>+ <button+ class="hotkey-toggle"+ class:on={rpcEnabled}+ onclick={() => { rpcEnabled = !rpcEnabled; }}+ >+ <span class="hotkey-toggle-label">{rpcEnabled ? $t("onboarding.rpc_on") : $t("onboarding.rpc_off")}</span>+ </button>+ <p class="step-desc step-rpc-note">{$t("onboarding.rpc_privacy_note")}</p>+ </div>++ {:else if step === 7}<div class="step step-done"><Mascot emotion="idle" /><h2>{$t("onboarding.done_title")}</h2>@@ -749,6 +782,12 @@color: var(--on-cta);}+ .step-rpc-note {+ margin-top: calc(var(--padding) / 2);+ font-size: 12.5px;+ opacity: 0.8;+ }+.theme-row {display: flex;align-items: center;diff --git a/src/components/settings/RichPresencePanel.svelte b/src/components/settings/RichPresencePanel.sveltenew file mode 100644index 00000000..32a53bce--- /dev/null+++ b/src/components/settings/RichPresencePanel.svelte@@ -0,0 +1,178 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { getSettings, updateSettings } from "$lib/stores/settings-store.svelte";+ import { rpcTestConnection, rpcSyncIdleStats } from "$lib/rpc";+ import { showToast } from "$lib/stores/toast-store.svelte";++ let settings = $derived(getSettings());+ let busy = $state(false);+ let testResult = $state<"ok" | "fail" | null>(null);+ let appIdInput = $state("");+ let imageKeyInput = $state("");++ $effect(() => {+ if (settings) {+ appIdInput = settings.rpc?.app_id ?? "";+ imageKeyInput = settings.rpc?.large_image_key ?? "";+ }+ });++ async function toggleEnabled() {+ if (!settings || busy) return;+ busy = true;+ try {+ await updateSettings({ rpc: { enabled: !settings.rpc.enabled } });+ if (!settings.rpc.enabled) {+ testResult = null;+ } else {+ void rpcSyncIdleStats();+ }+ } finally {+ busy = false;+ }+ }++ async function saveAdvanced() {+ if (!settings || busy) return;+ busy = true;+ try {+ await updateSettings({+ rpc: {+ app_id: appIdInput.trim(),+ large_image_key: imageKeyInput.trim(),+ },+ });+ void rpcSyncIdleStats();+ showToast("success", $t("settings.rpc.saved") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function testConnection() {+ if (busy) return;+ busy = true;+ testResult = null;+ try {+ const res = await rpcTestConnection();+ testResult = res.ok ? "ok" : "fail";+ if (!res.ok) {+ showToast("error", $t("settings.rpc.test_fail") as string);+ } else {+ showToast("success", $t("settings.rpc.test_ok") as string);+ }+ } catch (e) {+ testResult = "fail";+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }+</script>++{#if settings}+ <section class="section">+ <h5 class="section-title">{$t("settings.rpc.title")}</h5>+ <p class="setting-path" style="margin: 0 0 8px 4px">{$t("settings.rpc.desc")}</p>+ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("settings.rpc.enable")}</span>+ <span class="setting-path">{$t("settings.rpc.privacy_note")}</span>+ </div>+ <button+ class="toggle"+ class:on={settings.rpc.enabled}+ onclick={toggleEnabled}+ disabled={busy}+ role="switch"+ aria-checked={settings.rpc.enabled}+ aria-label={$t("settings.rpc.enable") as string}+ ><span class="toggle-knob"></span></button>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("settings.rpc.test")}</span>+ <span class="setting-path">{$t("settings.rpc.test_desc")}</span>+ </div>+ <div class="rpc-test-row">+ <button+ class="button"+ onclick={testConnection}+ disabled={busy || !settings.rpc.enabled}+ type="button"+ >{$t("settings.rpc.test_button")}</button>+ {#if testResult === "ok"}+ <span class="badge ok">✓</span>+ {:else if testResult === "fail"}+ <span class="badge fail">✗</span>+ {/if}+ </div>+ </div>+ </div>+ </section>++ <details class="section">+ <summary class="section-title">{$t("settings.rpc.advanced")}</summary>+ <div class="card">+ <div class="setting-row stack">+ <div class="setting-col">+ <span class="setting-label">{$t("settings.rpc.app_id")}</span>+ <span class="setting-path">{$t("settings.rpc.app_id_hint")}</span>+ </div>+ <input type="text" class="rpc-input" bind:value={appIdInput} spellcheck="false" />+ </div>+ <div class="divider"></div>+ <div class="setting-row stack">+ <div class="setting-col">+ <span class="setting-label">{$t("settings.rpc.large_image")}</span>+ <span class="setting-path">{$t("settings.rpc.large_image_hint")}</span>+ </div>+ <input type="text" class="rpc-input" bind:value={imageKeyInput} spellcheck="false" />+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <span class="setting-label"></span>+ <button class="button" onclick={saveAdvanced} disabled={busy} type="button">+ {$t("settings.rpc.save")}+ </button>+ </div>+ </div>+ </details>+{/if}++<style>+ .rpc-test-row {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .badge {+ font-size: 14px;+ font-weight: 700;+ }+ .badge.ok { color: var(--green, #4ade80); }+ .badge.fail { color: var(--red, #f87171); }+ .rpc-input {+ width: 100%;+ padding: 8px 10px;+ background: var(--button-elevated);+ border: 1px solid var(--input-border, var(--border));+ border-radius: calc(var(--border-radius) / 2);+ color: var(--text);+ font-family: ui-monospace, monospace;+ font-size: 12.5px;+ outline: none;+ }+ .rpc-input:focus {+ border-color: var(--accent);+ }+ .setting-row.stack {+ flex-direction: column;+ align-items: stretch;+ gap: 8px;+ }+</style>diff --git a/src/components/settings/SettingsAppearance.svelte b/src/components/settings/SettingsAppearance.svelteindex 559f81e9..1fd2aedf 100644--- a/src/components/settings/SettingsAppearance.svelte+++ b/src/components/settings/SettingsAppearance.svelte@@ -1,6 +1,7 @@<script lang="ts">import { t } from "$lib/i18n";import { showToast } from "$lib/stores/toast-store.svelte";+ import RichPresencePanel from "./RichPresencePanel.svelte";import {getSettings,updateSettings,@@ -114,6 +115,7 @@<option value="ja">{$t('settings.appearance.lang_ja')}</option><option value="it">{$t('settings.appearance.lang_it')}</option><option value="fr">{$t('settings.appearance.lang_fr')}</option>+ <option value="es">{$t('settings.appearance.lang_es')}</option><option value="el">{$t('settings.appearance.lang_el')}</option></select></div>@@ -138,4 +140,6 @@</div></div></section>++ <RichPresencePanel />{/if}diff --git a/src/components/settings/SettingsDownloads.svelte b/src/components/settings/SettingsDownloads.svelteindex 7e9c45ed..4e6aa2f7 100644--- a/src/components/settings/SettingsDownloads.svelte+++ b/src/components/settings/SettingsDownloads.svelte@@ -9,8 +9,16 @@toggleBool,changeQuality,} from "./settings-helpers";+ import { YTDLP_PRESETS, matchActivePreset, type YtdlpPresetId } from "$lib/ytdlp-presets";let settings = $derived(getSettings());+ let activePreset = $derived<YtdlpPresetId | null>(matchActivePreset(settings));++ async function applyPreset(id: YtdlpPresetId) {+ const preset = YTDLP_PRESETS.find((p) => p.id === id);+ if (!preset) return;+ await updateSettings({ download: preset.download });+ }let templateInput = $state("");let templateTimer: ReturnType<typeof setTimeout> | null = null;@@ -18,11 +26,16 @@let hotkeyTimer: ReturnType<typeof setTimeout> | null = null;let hotkeyMode = $state<"record" | "type">("record");let hotkeyRecording = $state(false);+ let musicHotkeyInput = $state("");+ let musicHotkeyTimer: ReturnType<typeof setTimeout> | null = null;+ let musicHotkeyMode = $state<"record" | "type">("record");+ let musicHotkeyRecording = $state(false);$effect(() => {if (settings) {templateInput = settings.download.filename_template;hotkeyInput = settings.download.hotkey_binding;+ musicHotkeyInput = settings.download.music_hotkey_binding;}});@@ -89,6 +102,39 @@hotkeyRecording = false;updateSettings({ download: { hotkey_binding: value } });}++ function handleMusicHotkeyInput(e: Event) {+ const value = (e.target as HTMLInputElement).value;+ musicHotkeyInput = value;+ if (musicHotkeyTimer) clearTimeout(musicHotkeyTimer);+ musicHotkeyTimer = setTimeout(async () => {+ if (value.trim()) {+ await updateSettings({ download: { music_hotkey_binding: value } });+ }+ }, 800);+ }++ function handleMusicHotkeyKeyDown(e: KeyboardEvent) {+ e.preventDefault();+ e.stopPropagation();+ if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;+ const keyName = mapKeyName(e.key);+ if (!keyName) return;+ const parts: string[] = [];+ if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");+ if (e.shiftKey) parts.push("Shift");+ if (e.altKey) parts.push("Alt");+ parts.push(keyName);+ const value = parts.join("+");+ musicHotkeyInput = value;+ musicHotkeyRecording = false;+ updateSettings({ download: { music_hotkey_binding: value } });+ }++ function changeMusicAudioFormat(e: Event) {+ const value = (e.target as HTMLSelectElement).value;+ updateSettings({ download: { music_audio_format: value } });+ }</script>{#if settings}@@ -132,6 +178,52 @@</div></section>+<section class="section">+ <h5 class="section-title">{$t('settings.download.music_hotkey_enabled')}</h5>+ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t('settings.download.music_hotkey_enabled')}</span>+ <span class="setting-path">{$t('settings.download.music_hotkey_enabled_desc')}</span>+ </div>+ <button class="toggle" class:on={settings.download.music_hotkey_enabled} onclick={() => toggleBool("download", "music_hotkey_enabled", settings.download.music_hotkey_enabled)} role="switch" aria-checked={settings.download.music_hotkey_enabled} aria-label={$t('settings.download.music_hotkey_enabled') as string}><span class="toggle-knob"></span></button>+ </div>+ {#if settings.download.music_hotkey_enabled}+ <div class="divider"></div>+ <div class="setting-row hotkey-row">+ <span class="setting-label">{$t('settings.download.music_hotkey_binding')}</span>+ <div class="hotkey-controls">+ <div class="hotkey-mode-switch">+ <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'record'} onclick={() => { musicHotkeyMode = 'record'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_record')}</button>+ <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'type'} onclick={() => { musicHotkeyMode = 'type'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_type')}</button>+ </div>+ {#if musicHotkeyMode === 'type'}+ <input type="text" class="input-hotkey" value={musicHotkeyInput} oninput={handleMusicHotkeyInput} spellcheck="false" />+ {:else}+ <button class="input-hotkey hotkey-record-btn" class:recording={musicHotkeyRecording} onclick={() => { musicHotkeyRecording = true; }} onkeydown={musicHotkeyRecording ? handleMusicHotkeyKeyDown : undefined} onblur={() => { musicHotkeyRecording = false; }}>+ {musicHotkeyRecording ? $t('settings.download.hotkey_press') : (musicHotkeyInput || $t('settings.download.hotkey_press'))}+ </button>+ {/if}+ </div>+ </div>+ {/if}+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t('settings.download.music_audio_format')}</span>+ <span class="setting-path">{$t('settings.download.music_audio_format_desc')}</span>+ </div>+ <select class="select" value={settings.download.music_audio_format} onchange={changeMusicAudioFormat}>+ <option value="m4a">M4A (AAC)</option>+ <option value="mp3">MP3</option>+ <option value="flac">FLAC (lossless)</option>+ <option value="opus">Opus</option>+ <option value="wav">WAV</option>+ </select>+ </div>+ </div>+</section>+<section class="section"><div class="card"><div class="setting-row">@@ -168,6 +260,24 @@</div></section>+<section class="section">+ <h5 class="section-title">{$t('settings.download.presets')}</h5>+ <p class="setting-path" style="margin: 0 0 8px 4px">{$t('settings.download.presets_desc')}</p>+ <div class="preset-grid">+ {#each YTDLP_PRESETS as preset (preset.id)}+ <button+ class="preset-card"+ class:active={activePreset === preset.id}+ onclick={() => applyPreset(preset.id)}+ type="button"+ >+ <span class="preset-label">{$t(preset.labelKey)}</span>+ <span class="preset-desc">{$t(preset.descKey)}</span>+ </button>+ {/each}+ </div>+</section>+<details class="section"><summary class="section-title">{$t('settings.download.organize_by_platform')}</summary><div class="card">@@ -295,3 +405,41 @@</div></details>{/if}++<style>+ .preset-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));+ gap: 8px;+ }+ .preset-card {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 4px;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: var(--border-radius, 6px);+ background: var(--surface);+ color: var(--text);+ cursor: pointer;+ text-align: left;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .preset-card:hover {+ border-color: var(--accent);+ }+ .preset-card.active {+ border-color: var(--accent);+ background: color-mix(in srgb, var(--accent) 12%, var(--surface));+ }+ .preset-label {+ font-weight: 600;+ font-size: 0.9rem;+ }+ .preset-desc {+ font-size: 0.78rem;+ color: var(--text-muted, var(--text));+ opacity: 0.75;+ }+</style>diff --git a/src/components/settings/SettingsPlugins.svelte b/src/components/settings/SettingsPlugins.svelteindex 306fca69..1c62230d 100644--- a/src/components/settings/SettingsPlugins.svelte+++ b/src/components/settings/SettingsPlugins.svelte@@ -1,6 +1,9 @@<script lang="ts">+ import { onMount } from "svelte";+ import { invoke } from "@tauri-apps/api/core";import { t } from "$lib/i18n";import { getSettings, toggleBool, changeNumber, type DependencyStatus } from "./settings-helpers";+ import { showToast } from "$lib/stores/toast-store.svelte";import DependencyRow from "./DependencyRow.svelte";let { deps = [], installingDep = null, onInstallDep, onRefresh }: {@@ -11,6 +14,67 @@} = $props();let settings = $derived(getSettings());++ type BrowserExtStatus = {+ browser: string;+ supported: boolean;+ bundled_version: string | null;+ installable: boolean;+ install_hint: string;+ store_url: string | null;+ };++ let extStatuses = $state<BrowserExtStatus[]>([]);+ let busyBrowser = $state<string | null>(null);+ let installModal = $state<{ browser: string; path: string; hint: string } | null>(null);++ onMount(async () => {+ try {+ extStatuses = await invoke<BrowserExtStatus[]>("browser_extension_status");+ } catch (e) {+ console.warn("[ext] status failed", e);+ }+ });++ async function exportExtension(browser: string) {+ if (busyBrowser) return;+ busyBrowser = browser;+ try {+ const res = await invoke<{ path: string; version: string | null; browser: string }>(+ "browser_extension_export",+ { browser },+ );+ const status = extStatuses.find((s) => s.browser === browser);+ installModal = {+ browser,+ path: res.path,+ hint: status?.install_hint ?? "",+ };+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busyBrowser = null;+ }+ }++ async function openFolder(path: string) {+ try {+ await invoke("browser_extension_open_folder", { path });+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ function closeInstall() {+ installModal = null;+ }++ function browserLabel(b: string): string {+ if (b === "chrome") return "Chrome / Edge / Brave";+ if (b === "firefox") return "Firefox";+ if (b === "safari") return "Safari";+ return b;+ }</script>{#if settings}@@ -51,6 +115,41 @@</div></section>+ <section class="section">+ <h5 class="section-title">Extensão de navegador</h5>+ <p class="muted">A extensão envia cookies e URLs do seu navegador para o OmniGet. Auto-update direto pelo app só funciona via lojas oficiais — enquanto não publicamos, use os botões abaixo para extrair a versão atual e (re)instalar manualmente.</p>+ <div class="card">+ {#each extStatuses as ext, i (ext.browser)}+ {#if i > 0}<div class="divider"></div>{/if}+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{browserLabel(ext.browser)}</span>+ <span class="setting-path">+ {#if ext.bundled_version}+ Versão empacotada: v{ext.bundled_version}+ {:else}+ {ext.install_hint}+ {/if}+ </span>+ </div>+ {#if ext.installable}+ <button+ class="button"+ disabled={busyBrowser === ext.browser}+ onclick={() => exportExtension(ext.browser)}+ >+ {busyBrowser === ext.browser ? "Extraindo..." : "Atualizar / Instalar"}+ </button>+ {:else if ext.store_url}+ <a class="button" href={ext.store_url} target="_blank" rel="noreferrer">Abrir loja</a>+ {:else}+ <span class="muted small">Indisponível</span>+ {/if}+ </div>+ {/each}+ </div>+ </section>+{#if deps.length > 0}<section class="section"><h5 class="section-title">{$t('settings.dependencies.title')}</h5>@@ -70,3 +169,66 @@</section>{/if}{/if}++{#if installModal}+ <div class="overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) closeInstall(); }}>+ <div class="dialog" role="dialog" aria-modal="true">+ <header class="head">+ <h3>Instalar / Atualizar extensão — {browserLabel(installModal.browser)}</h3>+ <button class="close" onclick={closeInstall} aria-label="fechar">×</button>+ </header>+ <div class="body">+ <p>A extensão foi extraída para:</p>+ <code class="path">{installModal.path}</code>+ <button class="button" onclick={() => openFolder(installModal!.path)}>Abrir pasta</button>+ <h4>Como instalar / atualizar</h4>+ <p class="hint">{installModal.hint}</p>+ <p class="hint small">+ Se a extensão já está instalada, clique em "Recarregar" no <code>{installModal.browser === 'firefox' ? 'about:debugging' : 'chrome://extensions'}</code> apontando pra essa pasta — ou remova a antiga e adicione a nova.+ </p>+ </div>+ <footer class="foot">+ <button class="button" onclick={closeInstall}>Fechar</button>+ </footer>+ </div>+ </div>+{/if}++<style>+ .muted { color: rgba(255, 255, 255, 0.6); font-size: 12px; line-height: 1.4; margin: 0 0 8px; }+ .small { font-size: 11px; }+ .overlay {+ position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6);+ display: grid; place-items: center; z-index: 999;+ }+ .dialog {+ background: var(--bg-card, #1a1a1a);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 12px;+ width: min(560px, 90vw);+ max-height: 80vh; overflow: auto;+ display: flex; flex-direction: column;+ }+ .head {+ display: flex; justify-content: space-between; align-items: center;+ padding: 16px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.05);+ }+ .head h3 { margin: 0; font-size: 16px; }+ .close {+ background: transparent; border: 0; color: rgba(255, 255, 255, 0.6);+ font-size: 22px; line-height: 1; cursor: pointer;+ }+ .body { padding: 16px 20px; display: flex; flex-direction: column; gap: 12px; }+ .body h4 { margin: 8px 0 0; font-size: 13px; font-weight: 600; }+ .body p { margin: 0; font-size: 13px; line-height: 1.5; }+ .body .hint { color: rgba(255, 255, 255, 0.7); }+ .path {+ display: block; padding: 8px 10px; background: rgba(0, 0, 0, 0.4);+ border-radius: 6px; font-family: var(--font-mono, monospace); font-size: 11px;+ word-break: break-all;+ }+ .foot {+ padding: 12px 20px; border-top: 1px solid rgba(255, 255, 255, 0.05);+ display: flex; justify-content: flex-end;+ }+</style>diff --git a/src/lib/error-translate.ts b/src/lib/error-translate.tsindex d1c2a909..bb7fd564 100644--- a/src/lib/error-translate.ts+++ b/src/lib/error-translate.ts@@ -31,6 +31,10 @@ const BACKEND_ERROR_MAP: Record<string, string> = {"Download timeout — no data received for 30 seconds":"errors.download_timeout","Write error (disk full?)": "errors.disk_full",+ "Console encoding error (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run `chcp 65001` in a terminal and reopen the app.":+ "errors.console_encoding",+ "yt-dlp extractor is broken for this site. Update yt-dlp in Settings → Dependencies, then retry.":+ "errors.extractor_broken",};/**diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.jsonindex 8c37ef0c..5479b90b 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "Δείξε {{count}} περισσότερα","open_folder": "Εμφάνιση στο φάκελο",+ "open_in_study": "Watch in Study","stop": "Διακοπή","confirm_remove": "Αφαίρεση αυτής της λήψης;","stats_line": "{{count}} λήψεις · {{size}} αποθηκευμένα",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "Κόψτε χορηγούμενα τμήματα, intro και outro από τα βίντεο YouTube (δεδομένα κοινότητας· μπορεί να χάσει ή να κόψει υπερβολικά)","split_by_chapters": "Διαίρεση βίντεο ανά κεφάλαια","split_by_chapters_desc": "Όταν το βίντεο έχει δείκτες κεφαλαίων, αποθηκεύεται κάθε κεφάλαιο σε ξεχωριστό αρχείο",+ "presets": "Γρήγορες προεπιλογές",+ "presets_desc": "Ρύθμιση με ένα κλικ. Πατήστε μια κάρτα για εφαρμογή.",+ "preset_fast": "Γρήγορα",+ "preset_fast_desc": "480p · χωρίς μεταδεδομένα · χωρίς υπότιτλους",+ "preset_quality": "Ποιότητα",+ "preset_quality_desc": "Καλύτερο βίντεο · μεταδεδομένα · μικρογραφία",+ "preset_compact": "Συμπαγές",+ "preset_compact_desc": "720p · μεταδεδομένα · χωρίς μικρογραφία",+ "preset_music_only": "Μόνο μουσική",+ "preset_music_only_desc": "Ήχος · ετικέτες ID3 · εξώφυλλο","hotkey_enabled": "Καθολικό πλήκτρο πρόσβασης","hotkey_enabled_desc": "Λήψη διεύθυνσης URL προχείρου με συντόμευση πληκτρολογίου","hotkey_binding": "Συντόμευση πλήκτρου πρόσβασης","hotkey_record": "Εγγραφή","hotkey_type": "Πληκτρολόγηση","hotkey_press": "Πατήστε πλήκτρα...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "Αντιγράψτε το αρχείο στο πρόχειρο μετά τη λήψη του πλήκτρου πρόσβασης","copy_to_clipboard_on_hotkey_desc": "Αντιγράψτε αυτόματα το ληφθέν αρχείο στο πρόχειρο για εύκολη επικόλληση","filename_template": "Πρότυπο ονόματος αρχείου",@@ -326,7 +343,25 @@"cat_downloads": "Ληψεις","cat_network": "Δικτυο","cat_advanced": "Προχωρημενα",- "search_placeholder": "Αναζήτηση ρυθμίσεων..."+ "search_placeholder": "Αναζήτηση ρυθμίσεων...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Εμφανιστε τη δραστηριοτητα σας στο προφιλ Discord. Το χρονομετρο δεν μηδενιζεται αλλαζοντας δραστηριοτητα.",+ "enable": "Εμφανιση δραστηριοτητας στο Discord",+ "privacy_note": "Εμφανιζει τι ακουτε, βλεπετε ή διαβαζετε. Οι λήψεις σας παραμένουν ιδιωτικές.",+ "test": "Δοκιμη συνδεσης",+ "test_desc": "Στελνει δοκιμαστικη δραστηριοτητα για να επιβεβαιωθει οτι το Discord ειναι ενεργο.",+ "test_button": "Αποστολη δοκιμης",+ "test_ok": "Συνδεθηκε στο Discord",+ "test_fail": "Αδυνατη η συνδεση στο Discord. Βεβαιωθειτε οτι ειναι ενεργο.",+ "saved": "Αποθηκευτηκε",+ "save": "Αποθηκευση",+ "advanced": "Προχωρημενα",+ "app_id": "ID εφαρμογης",+ "app_id_hint": "ID εφαρμογης Discord. Αλλαξτε μονο αν ξερετε τι κανετε.",+ "large_image": "Κλειδι μεγαλης εικονας",+ "large_image_hint": "Ονομα ενεργειου που μεταφορτωθηκε στην εφαρμογη Discord."+ }},"omnibox": {"placeholder": "Επικόλληση διεύθυνσης URL ή αναζήτηση",@@ -554,6 +589,11 @@"hotkey_desc": "Αντιγραψτε ενα URL, πατηστε τη συντομευση και η ληψη ξεκινα αμεσα — ακομα και ελαχιστοποιημενο.","hotkey_on": "Ενεργο","hotkey_off": "Ανενεργο",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Εμφανιστε στο προφιλ σας στο Discord οτι χρησιμοποιειτε το OmniGet — μαζι με τι ακουτε, βλεπετε ή διαβαζετε.",+ "rpc_on": "Ενεργο",+ "rpc_off": "Ανενεργο",+ "rpc_privacy_note": "Εμφανιζει τι ακουτε, βλεπετε ή διαβαζετε. Οι λήψεις σας παραμένουν ιδιωτικές.","theme_label": "Θεμα","theme_system": "Συστημα","theme_light": "Φωτεινο",@@ -602,7 +642,9 @@"download_timeout": "Η λήψη έληξε. Ελέγξτε τη σύνδεσή σας στο διαδίκτυο.","size_mismatch": "Το μέγεθος του αρχείου που λήφθηκε δεν ταιριάζει. Δοκιμάστε ξανά.","disk_full": "Σφάλμα εγγραφής — ο δίσκος σας μπορεί να είναι γεμάτος.",- "path_too_long": "Η διαδρομή του φακέλου λήψης είναι πολύ μεγάλη ({{current}}/{{limit}} χαρακτήρες). Επιλέξτε συντομότερο φάκελο."+ "path_too_long": "Η διαδρομή του φακέλου λήψης είναι πολύ μεγάλη ({{current}}/{{limit}} χαρακτήρες). Επιλέξτε συντομότερο φάκελο.",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "Αρχείο καταγραφής",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "Μελέτη","subtitle": "Μετατρέψτε τα μαθήματα που έχετε κατεβάσει σε έναν κύκλο συνειδητής εξάσκησης.","library": "Βιβλιοθήκη",+ "music": "Music","focus": "Συγκέντρωση","progress": "Πρόοδος","achievements": "Επιτεύγματα",@@ -839,8 +892,437 @@"action_vacuum_label": "Συμπιεση βασης (vacuum)","action_vacuum_hint": "Συντηρηση SQLite"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "Λουλακί",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "Βιβλιοθήκη",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "Λειτουργία προβολής",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "Δεν έχει γίνει ακόμα ευρετηρίαση μαθημάτων. Εκτελέστε σάρωση από τις Ρυθμίσεις.","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "Σε εξέλιξη","status_not_started": "Δεν ξεκίνησαν","status_completed": "Ολοκληρωμένα",- "view_mode_aria": "Λειτουργία προβολής","status_aria": "Κατάσταση","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "Συνέχεια από εκεί που σταμάτησες",+ "home_continue_eyebrow": "Πρόσφατα",+ "home_continue_empty": "Δεν υπάρχουν μαθήματα σε εξέλιξη. Ξεκίνα ένα μάθημα για να εμφανιστεί εδώ.",+ "home_continue_next": "Επόμενο: {{title}}",+ "home_continue_current": "Σε εξέλιξη: {{title}}",+ "home_news_title": "Με ενημερώσεις",+ "home_news_eyebrow": "Νέα μαθήματα",+ "home_news_count_one": "{{count}} νέο μάθημα",+ "home_news_count_other": "{{count}} νέα μαθήματα",+ "home_recently_title": "Πρόσφατα προστέθηκαν",+ "home_recently_eyebrow": "Νέα",+ "home_platform_eyebrow": "Πλατφόρμα",+ "home_subject_eyebrow": "Μάθημα",+ "home_empty_title": "Η βιβλιοθήκη σου είναι άδεια",+ "home_empty_desc": "Πρόσθεσε έναν φάκελο με μαθήματα για να ξεκινήσεις.",+ "home_empty_cta": "Προσθήκη φακέλου μαθημάτων",+ "home_load_error": "Αποτυχία φόρτωσης βιβλιοθήκης: {{error}}",+ "view_home": "Αρχική",+ "view_catalog": "Κατάλογος",+ "platform_generic": "Άλλες πλατφόρμες"},"player": {"title": "Αναπαραγωγή",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "Απόσπασμα 60 δευτ.",+ "clip_loading": "Δημιουργία…",+ "clip_done": "Το απόσπασμα αποθηκεύτηκε",+ "clip_failed": "Αποτυχία απόσπασης",+ "clip_no_video": "Το βίντεο δεν έχει φορτωθεί",+ "clip_aria": "Αποθήκευση των τελευταίων 60 δευτερολέπτων ως απόσπασμα"},"notes": {"title": "Σημειώσεις",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "χάλκινο",+ "tier_silver": "ασημένιο",+ "tier_gold": "χρυσό",+ "unlocked_prefix": "ξεκλειδώθηκε",+ "reset_done": "Έγινε επαναφορά",+ "reset_confirm_label": "Επαναφορά",+ "filter_aria": "Φίλτρα κατηγορίας",+ "tree_link": "Δέντρο",+ "charts_link": "Γραφήματα",+ "label_xp_100": "Πρώτοι 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Χίλιοι XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "Πρώτο μάθημα",+ "label_lessons_10": "10 μαθήματα",+ "label_lessons_50": "50 μαθήματα",+ "label_lessons_100": "100 μαθήματα",+ "label_focus_60": "1ω εστιασμένος",+ "label_focus_600": "10ω εστιασμένος",+ "label_focus_6000": "100ω εστιασμένος",+ "label_streak_3": "3 μέρες στη σειρά",+ "label_streak_7": "Σερί 1 εβδομάδας",+ "label_streak_30": "Σερί 30 ημερών",+ "label_streak_100": "Σερί 100 ημερών",+ "desc_xp_100": "Συγκέντρωσε 100 XP μελετώντας",+ "desc_xp_500": "Συγκέντρωσε 500 XP",+ "desc_xp_1000": "Ορόσημο των 1000 XP",+ "desc_xp_5000": "Πέντε χιλιάδες XP συγκεντρωμένοι",+ "desc_xp_10000": "Δέκα χιλιάδες XP — είσαι αφοσιωμένος",+ "desc_lessons_1": "Ολοκλήρωσε το πρώτο σου μάθημα",+ "desc_lessons_10": "Ολοκλήρωσε 10 μαθήματα",+ "desc_lessons_50": "Μισός αιώνας μαθημάτων",+ "desc_lessons_100": "Εκατό μαθήματα ολοκληρωμένα",+ "desc_focus_60": "60 λεπτά εστίασης συγκεντρωμένα",+ "desc_focus_600": "600 λεπτά εστίασης συγκεντρωμένα",+ "desc_focus_6000": "6000 λεπτά εστίασης — σπάνια πειθαρχία",+ "desc_streak_3": "Διατήρησε σερί για 3 μέρες",+ "desc_streak_7": "7 συνεχόμενες μέρες μελέτης",+ "desc_streak_30": "Έναν ολόκληρο μήνα συνέπειας",+ "desc_streak_100": "Συνήθεια από ατσάλι"},"focus": {"title": "Συγκέντρωση","placeholder": "Συνεδρίες Pomodoro και βαθιάς εργασίας εδώ.",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "Pomodoro (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "αποθήκευση…",+ "settings_saved": "αποθηκεύτηκε ✓",+ "acc_cycles_title": "Κύκλοι",+ "acc_cycles_summary": "{{focus}}λεπτά εστίαση · {{break}}λεπτά διάλειμμα · {{cycles}}× μέχρι μεγάλο διάλειμμα",+ "acc_cycles_focus": "Εστίαση (λεπτά)",+ "acc_cycles_short": "Σύντομο διάλειμμα (λεπτά)",+ "acc_cycles_long": "Μεγάλο διάλειμμα (λεπτά)",+ "acc_cycles_count": "Κύκλοι πριν το μεγάλο διάλειμμα",+ "acc_breaks_title": "Διαλείμματα & αυτόματη εκκίνηση",+ "acc_breaks_auto_yes": "αυτόματη παύση",+ "acc_breaks_auto_no": "χειροκίνητο",+ "acc_breaks_focus_yes": "αυτόματη επανέναρξη",+ "acc_breaks_focus_no": "χειροκίνητο",+ "acc_breaks_player_yes": "παύει την αναπαραγωγή",+ "acc_breaks_player_no": "αγνοεί την αναπαραγωγή",+ "acc_breaks_check_breaks": "Αυτόματη έναρξη διαλειμμάτων μετά την εστίαση",+ "acc_breaks_check_focus": "Αυτόματη επανέναρξη εστίασης μετά το διάλειμμα",+ "acc_breaks_check_player": "Παύση βίντεο κατά τη διάρκεια διαλείμματος εστίασης",+ "acc_sounds_title": "Ήχοι & ειδοποίηση",+ "acc_sounds_notify_on": "ειδοποίηση ON",+ "acc_sounds_notify_off": "σιωπηλό",+ "acc_sounds_sound_on": "ήχος {{n}}%",+ "acc_sounds_sound_off": "χωρίς ήχο",+ "acc_sounds_check_notify": "Ειδοποίηση στο τέλος του κύκλου",+ "acc_sounds_check_sound": "Αναπαραγωγή ήχου στο τέλος",+ "acc_sounds_volume": "Ένταση ({{n}}%)",+ "unlimited_aria": "ελεύθερο"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "Χρόνος ανά μάθημα",+ "chart_time_per_course_empty": "Δεν καταγράφηκε χρόνος σε αυτή την περίοδο.",+ "chart_time_period_days": "τελευταίες {{n}} ημέρες",+ "chart_activity_by_hour": "Δραστηριότητα ανά ώρα",+ "chart_activity_hint": "άθροισμα εστίασης · 24ώρου",+ "chart_activity_empty": "Καμία δραστηριότητα τις τελευταίες {{n}} ημέρες.",+ "chart_subject": "Ανά μάθημα",+ "chart_subject_unit": "λεπτά εστίασης",+ "chart_subject_empty": "Δημιούργησε μαθήματα και ανάθεσε συνεδρίες για να δεις την ανάλυση.",+ "chart_subject_unassigned": "Χωρίς μάθημα",+ "retention_title": "Διατήρηση (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "Η πραγματική διατήρηση θα προέλθει από το cross-DB ερώτημα του Anki. Για τώρα, άνοιξε",+ "retention_link": "Στατιστικά Anki →",+ "retention_stub_after": "για να δεις διατήρηση, κατανομή διαστημάτων και ιστορικό επαναλήψεων.",+ "recent_achievements": "Πρόσφατα επιτεύγματα",+ "view_all": "Προβολή όλων →",+ "time_today": "σήμερα",+ "time_yesterday": "χθες",+ "time_days_ago": "πριν {{n}} ημέρες",+ "time_months_ago": "πριν {{n}} μήνες",+ "time_years_ago": "πριν {{n}} χρόνια",+ "ach_label_xp_100": "100 XP συγκεντρωμένοι",+ "ach_label_xp_500": "500 XP συγκεντρωμένοι",+ "ach_label_xp_1000": "1.000 XP συγκεντρωμένοι",+ "ach_label_xp_5000": "5.000 XP συγκεντρωμένοι",+ "ach_label_xp_10000": "10.000 XP συγκεντρωμένοι",+ "ach_label_lessons_1": "Πρώτο μάθημα",+ "ach_label_lessons_10": "10 μαθήματα ολοκληρωμένα",+ "ach_label_lessons_50": "50 μαθήματα ολοκληρωμένα",+ "ach_label_lessons_100": "100 μαθήματα ολοκληρωμένα",+ "ach_label_focus_60": "1 ώρα εστίασης",+ "ach_label_focus_600": "10 ώρες εστίασης",+ "ach_label_focus_6000": "100 ώρες εστίασης",+ "ach_label_streak_3": "Σερί 3 ημερών",+ "ach_label_streak_7": "Σερί 1 εβδομάδας",+ "ach_label_streak_30": "Σερί 30 ημερών",+ "ach_label_streak_100": "Σερί 100 ημερών"},"settings": {"title": "Ρυθμίσεις",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "Αναζήτηση σημειώσεων",+ "downloads_btn": "Λήψεις",+ "enrich_no_results": "Κανένα αποτέλεσμα. Δοκίμασε να επεξεργαστείς πρώτα τον τίτλο του βιβλίου.",+ "enrich_done": "✓ Τα μεταδεδομένα ενημερώθηκαν",+ "enrich_field_title": "Τίτλος:",+ "enrich_field_author": "Συγγραφέας:",+ "enrich_field_publisher": "Εκδότης:",+ "enrich_field_cover": "Εξώφυλλο (λήψη)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex e71e9958..3da085a6 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "Show {{count}} more","open_folder": "Show in folder",+ "open_in_study": "Watch in Study","stop": "Stop","confirm_remove": "Remove this download?","stats_line": "{{count}} downloads · {{size}} saved",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "Cut sponsored, intro and outro segments from YouTube videos (community-sourced data; may miss or over-cut)","split_by_chapters": "Split video by chapters","split_by_chapters_desc": "When the source has chapter markers, save each chapter as a separate file",+ "presets": "Quick presets",+ "presets_desc": "One-click setup for common workflows. Tap a card to apply.",+ "preset_fast": "Fast",+ "preset_fast_desc": "480p · no metadata · no subtitles",+ "preset_quality": "Quality",+ "preset_quality_desc": "Best video · metadata · thumbnail",+ "preset_compact": "Compact",+ "preset_compact_desc": "720p · metadata · no thumbnail",+ "preset_music_only": "Music only",+ "preset_music_only_desc": "Audio · ID3 tags · cover art","hotkey_enabled": "Global hotkey","hotkey_enabled_desc": "Download clipboard URL with a keyboard shortcut","hotkey_binding": "Hotkey shortcut","hotkey_record": "Record","hotkey_type": "Type","hotkey_press": "Press keys...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "Copy file to clipboard after hotkey download","copy_to_clipboard_on_hotkey_desc": "Automatically copy the downloaded file to clipboard for easy pasting","filename_template": "Filename template",@@ -326,7 +343,25 @@"cat_downloads": "Downloads","cat_network": "Network","cat_advanced": "Advanced",- "search_placeholder": "Search settings..."+ "search_placeholder": "Search settings...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Show your activity on your Discord profile. The timer keeps going across activities, never resets.",+ "enable": "Show activity on Discord",+ "privacy_note": "Shows what you're listening to, watching or reading. Downloads stay private.",+ "test": "Test connection",+ "test_desc": "Send a test activity to verify Discord is running and connected.",+ "test_button": "Send test",+ "test_ok": "Connected to Discord",+ "test_fail": "Could not reach Discord. Make sure it is running.",+ "saved": "Saved",+ "save": "Save",+ "advanced": "Advanced",+ "app_id": "Application ID",+ "app_id_hint": "Discord application ID. Change only if you know what you're doing.",+ "large_image": "Large image key",+ "large_image_hint": "Asset name uploaded to your Discord application."+ }},"omnibox": {"placeholder": "Paste a URL, magnet link, .torrent, or search",@@ -554,6 +589,11 @@"hotkey_desc": "Copy any video URL, press the hotkey, and OmniGet starts downloading instantly — even when minimized.","hotkey_on": "Enabled","hotkey_off": "Disabled",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Show on your Discord profile that you're using OmniGet — including what you're listening to, watching or reading.",+ "rpc_on": "Enabled",+ "rpc_off": "Disabled",+ "rpc_privacy_note": "Shows what you're listening to, watching or reading. Downloads stay private.","theme_label": "Theme","theme_system": "System","theme_light": "Light",@@ -602,7 +642,9 @@"download_timeout": "Download timed out. Check your internet connection.","size_mismatch": "Downloaded file size doesn't match. Try again.","disk_full": "Write error — your disk may be full.",- "path_too_long": "Download folder path is too long ({{current}}/{{limit}} chars). Choose a shorter folder."+ "path_too_long": "Download folder path is too long ({{current}}/{{limit}} chars). Choose a shorter folder.",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "Activity Log",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "Study","subtitle": "Turn your downloaded courses into a deliberate practice loop.","library": "Library",+ "music": "Music","focus": "Focus","progress": "Progress","achievements": "Achievements",@@ -839,8 +892,484 @@"action_vacuum_label": "Compact database (vacuum)","action_vacuum_hint": "SQLite maintenance"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "Indigo",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "sc_title": "SoundCloud",+ "sc_signin_heading": "Connect to SoundCloud",+ "sc_signin_body": "Sign in to SoundCloud in your browser — the OmniGet extension grabs the cookies automatically. Then come back and refresh.",+ "sc_open_in_browser": "Open SoundCloud in browser",+ "sc_already_signed_in": "I'm signed in, refresh",+ "sc_search": "Search",+ "sc_refresh": "Refresh",+ "sc_logout": "Sign out",+ "sc_loading": "Loading…",+ "sc_status_client_id": "client_id",+ "sc_status_oauth": "oauth",+ "sc_import_url": "Import by URL",+ "sc_import_url_title": "Import from a SoundCloud URL",+ "sc_import_url_desc": "Paste any link to a track, playlist or artist — we'll figure out the rest.",+ "sc_import_url_placeholder": "https://soundcloud.com/…",+ "sc_import_action": "Import",+ "sc_import_invalid": "That doesn't look like a SoundCloud URL.",+ "sc_import_failed": "Could not resolve that URL: {{error}}",+ "sc_import_success": "Imported \"{{title}}\"",+ "sc_section_continue": "Pick up where you left off",+ "sc_section_stream": "From people you follow",+ "sc_section_recommended": "Because you liked {{name}}",+ "sc_section_likes": "Your likes ({{count}})",+ "sc_section_playlists": "Your playlists",+ "sc_section_following": "Following",+ "sc_followers_count": "{{count}} followers",+ "sc_track_count": "{{count}} tracks",+ "sc_download_track": "Download track",+ "sc_download_all": "Download all ({{count}})",+ "sc_download_started": "Download queued",+ "sc_download_bulk_progress": "Downloading {{current}} of {{total}}",+ "sc_download_bulk_done": "Finished — {{success}} downloaded, {{failed}} failed",+ "sc_go_plus_badge": "Go+",+ "sc_go_plus_unavailable_hint": "Higher quality streams require a SoundCloud Go+ account. Standard MP3 still works without it.",+ "sc_empty_likes_title": "No likes yet",+ "sc_empty_likes_body": "Hearts you give on SoundCloud show up here.",+ "sc_empty_likes_action": "Search music",+ "sc_empty_playlists_title": "No playlists yet",+ "sc_empty_playlists_body": "Create or import a playlist on soundcloud.com — it'll show here on next refresh.",+ "sc_empty_following_title": "Not following anyone yet",+ "sc_empty_state_logged_out_action": "Take me to SoundCloud",+ "sc_load_more": "Load more",+ "sc_show_count": "Showing {{shown}} of {{total}}",+ "sc_skeleton_loading": "Pulling your library…",+ "sc_offline_for_focus": "Save offline so it plays even with no internet",+ "sc_recommended_seed_fallback": "your taste",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "top_tracks": "Top tracks",+ "discography": "Discography",+ "queue_title": "Queue",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "Library",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "View mode",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "No courses indexed yet. Run a scan from Settings.","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -909,13 +1438,9 @@"progress_pct": "{{pct}}% complete","favorite_on": "Unfavorite","favorite_off": "Favorite",- "filters": "Filters","platform": "Platform","status": "Status","status_new": "New",- "status_not_started": "Not started",- "status_in_progress": "In progress",- "status_completed": "Completed","status_empty": "Empty","has_gaps": "Has gaps","has_notes": "Has notes",@@ -934,8 +1459,8 @@"recent": "Recent","history": "History","history_empty": "No recent activity",- "mode_browse": "Folders",- "mode_courses": "Courses",+ "mode_browse": "Folders & files",+ "mode_courses": "My courses","browse_empty": "Empty folder.","videos": "videos","roots": "Library roots",@@ -946,7 +1471,7 @@"kind_media_badge": "Video","favorite": "Favorite","resume": "Resume",- "roots_button": "Folders",+ "roots_button": "Where to look","roots_add_btn": "Add folder","roots_remove": "Remove","roots_remove_tooltip": "Remove this folder",@@ -966,7 +1491,7 @@"watch_back": "Back to library","watch_not_found": "No video selected.","watch_file_missing": "File not found.",- "mode_telegram": "Telegram",+ "mode_telegram": "Import from Telegram","telegram": {"plugin_missing_title": "Telegram plugin not found","plugin_missing_body": "Install the Telegram plugin from the marketplace to access your chats here.",@@ -1127,7 +1652,6 @@"copy_to": "Copy to…","upload_files": "Upload","upload_hint": "Send files to this chat",- "keymap_title": "Keyboard shortcuts","kbd_help": "Open this help","kbd_esc": "Close player / clear selection","kbd_click": "Open player",@@ -1156,7 +1680,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "Continue where you left off",+ "home_continue_eyebrow": "Recent",+ "home_continue_empty": "No courses in progress yet. Start a lesson to see it here.",+ "home_continue_next": "Next: {{title}}",+ "home_continue_current": "On: {{title}}",+ "home_news_title": "With updates",+ "home_news_eyebrow": "New lessons",+ "home_news_count_one": "{{count}} new lesson",+ "home_news_count_other": "{{count}} new lessons",+ "home_recently_title": "Recently added",+ "home_recently_eyebrow": "New",+ "home_platform_eyebrow": "Platform",+ "home_subject_eyebrow": "Subject",+ "home_empty_title": "Your library is empty",+ "home_empty_desc": "Add a folder with courses to begin.",+ "home_empty_cta": "Add courses folder",+ "home_load_error": "Failed to load library: {{error}}",+ "view_home": "Home",+ "view_catalog": "Catalog",+ "platform_generic": "Other platforms"},"player": {"title": "Player",@@ -1196,7 +1740,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "Clip last 60s",+ "clip_loading": "Clipping…",+ "clip_done": "Clip saved",+ "clip_failed": "Clip failed",+ "clip_no_video": "Video not loaded yet",+ "clip_aria": "Save last 60 seconds as clip"},"notes": {"title": "Notes",@@ -1276,11 +1826,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "bronze",+ "tier_silver": "silver",+ "tier_gold": "gold",+ "unlocked_prefix": "unlocked",+ "reset_done": "Reset done",+ "reset_confirm_label": "Reset",+ "filter_aria": "Category filters",+ "tree_link": "Tree",+ "charts_link": "Charts",+ "label_xp_100": "First 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Thousand XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "First lesson",+ "label_lessons_10": "10 lessons",+ "label_lessons_50": "50 lessons",+ "label_lessons_100": "100 lessons",+ "label_focus_60": "1h focused",+ "label_focus_600": "10h focused",+ "label_focus_6000": "100h focused",+ "label_streak_3": "3 days in a row",+ "label_streak_7": "1-week streak",+ "label_streak_30": "30-day streak",+ "label_streak_100": "100-day streak",+ "desc_xp_100": "Earn 100 XP studying",+ "desc_xp_500": "Earn 500 XP",+ "desc_xp_1000": "1000 XP milestone",+ "desc_xp_5000": "Five thousand XP collected",+ "desc_xp_10000": "Ten thousand XP — you're dedicated",+ "desc_lessons_1": "Complete your first lesson",+ "desc_lessons_10": "Complete 10 lessons",+ "desc_lessons_50": "Half-century of lessons",+ "desc_lessons_100": "A hundred lessons completed",+ "desc_focus_60": "60 minutes of focus collected",+ "desc_focus_600": "600 minutes of focus collected",+ "desc_focus_6000": "6000 minutes of focus — rare discipline",+ "desc_streak_3": "Maintain streak for 3 days",+ "desc_streak_7": "7 consecutive days studying",+ "desc_streak_30": "A whole month of consistency",+ "desc_streak_100": "Habit of steel"},"focus": {"title": "Focus","placeholder": "Pomodoro and deep-work sessions live here.",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "Pomodoro","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1352,7 +1949,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "saving…",+ "settings_saved": "saved ✓",+ "acc_cycles_title": "Cycles",+ "acc_cycles_summary": "{{focus}}min focus · {{break}}min break · {{cycles}}× until long break",+ "acc_cycles_focus": "Focus (min)",+ "acc_cycles_short": "Short break (min)",+ "acc_cycles_long": "Long break (min)",+ "acc_cycles_count": "Cycles before long break",+ "acc_breaks_title": "Breaks & auto-start",+ "acc_breaks_auto_yes": "auto-pause",+ "acc_breaks_auto_no": "manual",+ "acc_breaks_focus_yes": "auto-resume",+ "acc_breaks_focus_no": "manual",+ "acc_breaks_player_yes": "pauses player",+ "acc_breaks_player_no": "ignores player",+ "acc_breaks_check_breaks": "Auto-start breaks after focus",+ "acc_breaks_check_focus": "Auto-resume focus after break",+ "acc_breaks_check_player": "Pause video during focus break",+ "acc_sounds_title": "Sounds & notification",+ "acc_sounds_notify_on": "notification ON",+ "acc_sounds_notify_off": "silent",+ "acc_sounds_sound_on": "sound {{n}}%",+ "acc_sounds_sound_off": "no sound",+ "acc_sounds_check_notify": "Notify on cycle end",+ "acc_sounds_check_sound": "Play sound on end",+ "acc_sounds_volume": "Volume ({{n}}%)",+ "unlimited_aria": "unlimited"},"subjects": {"title": "Subjects",@@ -1444,7 +2068,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "Time per course",+ "chart_time_per_course_empty": "No time logged in this period.",+ "chart_time_period_days": "last {{n}} days",+ "chart_activity_by_hour": "Activity by hour",+ "chart_activity_hint": "sum of focus · 24h",+ "chart_activity_empty": "No activity in the last {{n}} days.",+ "chart_subject": "By subject",+ "chart_subject_unit": "focus minutes",+ "chart_subject_empty": "Create subjects and assign sessions to see the breakdown.",+ "chart_subject_unassigned": "No subject",+ "retention_title": "Retention (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "Real retention will come from the Anki cross-DB query. For now, open",+ "retention_link": "Anki Stats →",+ "retention_stub_after": "to see retention, interval distribution, and review history.",+ "recent_achievements": "Recent achievements",+ "view_all": "View all →",+ "time_today": "today",+ "time_yesterday": "yesterday",+ "time_days_ago": "{{n}} days ago",+ "time_months_ago": "{{n}} months ago",+ "time_years_ago": "{{n}} years ago",+ "ach_label_xp_100": "100 XP collected",+ "ach_label_xp_500": "500 XP collected",+ "ach_label_xp_1000": "1,000 XP collected",+ "ach_label_xp_5000": "5,000 XP collected",+ "ach_label_xp_10000": "10,000 XP collected",+ "ach_label_lessons_1": "First lesson",+ "ach_label_lessons_10": "10 lessons completed",+ "ach_label_lessons_50": "50 lessons completed",+ "ach_label_lessons_100": "100 lessons completed",+ "ach_label_focus_60": "1 hour of focus",+ "ach_label_focus_600": "10 hours of focus",+ "ach_label_focus_6000": "100 hours of focus",+ "ach_label_streak_3": "3-day streak",+ "ach_label_streak_7": "1-week streak",+ "ach_label_streak_30": "30-day streak",+ "ach_label_streak_100": "100-day streak"},"settings": {"title": "Settings",@@ -1723,7 +2385,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "Search notes",+ "downloads_btn": "Downloads",+ "enrich_no_results": "No results. Try editing the book title first.",+ "enrich_done": "✓ Metadata updated",+ "enrich_field_title": "Title:",+ "enrich_field_author": "Author:",+ "enrich_field_publisher": "Publisher:",+ "enrich_field_cover": "Cover (download)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonnew file mode 100644index 00000000..74da4acf--- /dev/null+++ b/src/lib/i18n/es.json@@ -0,0 +1,2462 @@+{+ "confirm_close": {+ "title": "Descargas en curso",+ "message": "Tienes {{count}} descarga(s) activa(s). Si cierras ahora se cancelarán.",+ "cancel": "Seguir ejecutando",+ "confirm": "Cerrar de todos modos"+ },+ "legal": {+ "title": "Usa OmniGet con responsabilidad",+ "body_paragraph_1": "OmniGet es una herramienta para descargar contenido al que tienes derecho de acceso. Eres responsable de respetar los derechos de autor y los términos de servicio de cada plataforma de la que descargas.",+ "body_paragraph_2": "Al continuar reconoces lo siguiente:",+ "rule_copyright": "Solo descargaré contenido que poseo, sobre el que tengo licencia, o que es explícitamente libre de reutilizar.",+ "rule_tos": "Respetaré los términos de servicio de la plataforma de origen.",+ "rule_personal_use": "Entiendo que esta herramienta se proporciona tal cual y los desarrolladores no son responsables del uso indebido.",+ "acknowledge": "Entendido"+ },+ "recovery": {+ "title": "Descargas sin terminar",+ "message": "OmniGet encontró {{count}} descarga(s) que no terminaron la sesión anterior. ¿Quieres reanudarlas?",+ "more": "y {{count}} más...",+ "restore": "Reanudar descargas",+ "discard": "Descartar",+ "restored": "{{count}} descarga(s) reanudada(s)"+ },+ "shortcuts": {+ "title": "Atajos de teclado",+ "section_application": "Aplicación",+ "section_downloads": "Descargas",+ "section_navigation": "Navegación",+ "paste_url": "Pegar URL y descargar",+ "show_shortcuts": "Mostrar este diálogo",+ "open_settings": "Abrir configuración",+ "search_settings": "Buscar en configuración",+ "start_download": "Iniciar descarga",+ "cancel_dialog": "Cerrar diálogo o cancelar",+ "nav_home": "Ir a Inicio",+ "nav_downloads": "Ir a Descargas"+ },+ "nav": {+ "home": "Inicio",+ "downloads": "Descargas",+ "marketplace": "Marketplace",+ "settings": "Configuración",+ "about": "Acerca de"+ },+ "downloads": {+ "title": "Descargas",+ "empty": "Sin descargas en curso",+ "status": {+ "queued": "En cola",+ "downloading": "Descargando",+ "paused": "Pausada",+ "complete": "Completa",+ "error": "Error",+ "seeding": "Compartiendo"+ },+ "section_queued": "En cola",+ "section_finished": "Terminadas",+ "pause": "Pausar",+ "resume": "Reanudar",+ "retry": "Reintentar",+ "page_progress": "Página {{current}}/{{total}}",+ "module_progress": "Módulo {{current}}/{{total}}",+ "phase_fetching_info": "Obteniendo información del vídeo...",+ "phase_starting": "Iniciando motor de descarga...",+ "phase_connecting": "Conectando al servidor...",+ "phase_preparing": "Preparando descarga...",+ "cancel": "Cancelar",+ "clear_finished": "Limpiar terminadas",+ "clear_confirm": "¿Limpiar todas las descargas terminadas?",+ "show_more": "Mostrar {{count}} más",+ "open_folder": "Mostrar en carpeta",+ "open_in_study": "Ver en Estudio",+ "stop": "Detener",+ "confirm_remove": "¿Quitar esta descarga?",+ "stats_line": "{{count}} descargas · {{size}} guardados",+ "filter_label": "Filtrar descargas por estado",+ "filter": {+ "all": "Todas",+ "active": "Activas",+ "queued": "En cola",+ "completed": "Completadas",+ "failed": "Fallidas"+ },+ "log": {+ "show": "Ver registro",+ "hide": "Ocultar registro",+ "copy": "Copiar",+ "copied": "Registro copiado al portapapeles",+ "copy_failed": "No se pudo copiar el registro",+ "empty": "Aún no hay líneas en el registro"+ }+ },+ "toast": {+ "download_preparing": "Preparando descarga...",+ "download_started": "Iniciando: {{name}}",+ "download_complete": "¡Listo! {{name}} está en tu carpeta",+ "download_error": "No se pudo descargar {{name}}. ¿Reintentar?",+ "clipboard_url_detected": "¡Enlace detectado! Pega para descargar",+ "external_url_ready": "URL recibida y lista para descargar",+ "external_url_queued": "Descarga añadida desde la extensión de Chrome",+ "file_copied_to_clipboard": "Archivo copiado al portapapeles",+ "drm_skipped": "{{count}} vídeo(s) omitidos — protegidos por DRM (FairPlay/SAMPLE-AES)",+ "generic_download_complete": "{{name}} — ¡descarga completa!"+ },+ "telegram": {+ "title": "Telegram",+ "checking_session": "Comprobando sesión...",+ "login": "Iniciar sesión",+ "logout": "Cerrar sesión",+ "logged_as": "Sesión iniciada como {{phone}}",+ "phone_label": "Número de teléfono",+ "phone_placeholder": "+34 600 000 000",+ "phone_hint": "Incluye el código de país",+ "send_code": "Enviar código",+ "sending_code": "Enviando...",+ "code_label": "Código de verificación",+ "code_placeholder": "00000",+ "code_hint": "Enviamos un código a tu app de Telegram",+ "verify": "Verificar",+ "verifying": "Verificando...",+ "invalid_code": "Código no válido. Inténtalo de nuevo.",+ "password_label": "Contraseña de dos factores",+ "password_placeholder": "Tu contraseña 2FA",+ "password_hint": "Pista: {{hint}}",+ "password_submit": "Confirmar",+ "password_verifying": "Verificando...",+ "invalid_password": "Contraseña no válida. Inténtalo de nuevo.",+ "chats_title": "Tus chats",+ "loading_chats": "Cargando chats...",+ "chats_error": "Error al cargar chats",+ "no_chats": "No hay chats.",+ "chat_count": "{{count}} chats",+ "chat_count_one": "{{count}} chat",+ "chat_type_private": "Privado",+ "chat_type_group": "Grupo",+ "chat_type_channel": "Canal",+ "media_title": "Multimedia",+ "loading_media": "Cargando multimedia...",+ "no_media": "No se encontró multimedia en este chat.",+ "media_error": "Error al cargar multimedia",+ "filter_all": "Todo",+ "filter_photo": "Fotos",+ "filter_video": "Vídeos",+ "filter_document": "Archivos",+ "filter_audio": "Audio",+ "search_files": "Buscar archivos...",+ "searching": "Buscando...",+ "back_to_chats": "Volver a chats",+ "download_btn": "Descargar",+ "downloading": "Descargando...",+ "downloaded": "Descargado",+ "choose_folder": "Elegir carpeta de descarga",+ "unknown_error": "Error desconocido",+ "download_all": "Descargar todo",+ "batch_progress": "{{done}} de {{total}} archivos",+ "batch_cancelled": "Descarga en lote cancelada",+ "batch_complete": "Todos los archivos descargados",+ "load_more": "Cargar más",+ "status_waiting": "Esperando",+ "status_skipped": "Omitido",+ "status_error": "Error",+ "file_count": "{{count}} elementos",+ "cancel_batch": "Cancelar",+ "qr_title": "Escanea para iniciar sesión",+ "qr_instruction": "Abre Telegram en tu teléfono y ve a Ajustes > Dispositivos > Vincular dispositivo de escritorio",+ "qr_loading": "Generando código QR...",+ "qr_error": "Error al generar código QR",+ "or_separator": "o",+ "use_phone": "Usar número de teléfono",+ "back_to_qr": "Volver al código QR"+ },+ "settings": {+ "title": "Configuración",+ "general": {+ "title": "General",+ "start_with_system": "Iniciar con el sistema",+ "start_with_system_desc": "Abre OmniGet automáticamente al encender el ordenador",+ "start_minimized": "Iniciar solo en la bandeja",+ "start_minimized_desc": "Abre OmniGet en la bandeja del sistema sin mostrar la ventana. Haz clic en el icono para abrir.",+ "reset_hints": "Restablecer sugerencias",+ "reset_hints_desc": "Volver a mostrar todas las sugerencias descartadas",+ "restore": "Restablecer",+ "hints_restored": "Sugerencias restablecidas"+ },+ "appearance": {+ "title": "Apariencia",+ "theme": "Tema",+ "theme_system": "Sistema",+ "more_themes": "Más temas",+ "language": "Idioma",+ "lang_pt": "Português",+ "lang_en": "English",+ "lang_zh": "中文",+ "lang_ja": "日本語",+ "lang_it": "Italiano",+ "lang_fr": "Français",+ "lang_es": "Español",+ "lang_el": "Ελληνικά"+ },+ "download": {+ "default_output_dir": "Carpeta por defecto",+ "choose_folder": "Elegir",+ "always_ask_path": "Preguntar siempre dónde guardar",+ "video_quality": "Calidad de vídeo",+ "skip_existing": "Saltar archivos existentes",+ "download_attachments": "Descargar adjuntos",+ "download_descriptions": "Guardar descripciones",+ "embed_metadata": "Incrustar metadatos",+ "embed_metadata_desc": "Escribe título y artista dentro de los archivos descargados",+ "embed_thumbnail": "Incrustar miniatura como carátula",+ "embed_thumbnail_desc": "Incrusta la carátula en los archivos de audio",+ "clipboard_detection": "Detección del portapapeles",+ "clipboard_detection_desc": "Detecta automáticamente las URLs copiadas",+ "organize_by_platform": "Organizar por plataforma",+ "organize_by_platform_desc": "Guarda los archivos en subcarpetas con el nombre de la plataforma",+ "download_subtitles": "Descargar subtítulos",+ "download_subtitles_desc": "Descarga los subtítulos disponibles junto con los vídeos (YouTube)",+ "what_to_also_save": "Qué guardar también",+ "youtube_specific": "Específico de YouTube",+ "telegram_plugin_section": "Telegram (plugin)",+ "include_auto_subtitles": "Incluir subtítulos generados automáticamente",+ "include_auto_subtitles_desc": "También obtiene los subtítulos auto-generados por YouTube cuando no hay manuales (calidad variable)",+ "translate_metadata": "Traducir título y descripción al idioma de la app",+ "translate_metadata_desc": "Pide a YouTube que localice los títulos y capítulos al idioma de la app (solo YouTube)",+ "youtube_sponsorblock": "Eliminar segmentos de SponsorBlock",+ "youtube_sponsorblock_desc": "Corta segmentos patrocinados, intros y outros de vídeos de YouTube (datos comunitarios; puede fallar o cortar de más)",+ "split_by_chapters": "Dividir vídeo por capítulos",+ "split_by_chapters_desc": "Cuando el origen tiene marcadores de capítulo, guarda cada capítulo como un archivo aparte",+ "presets": "Presets rápidos",+ "presets_desc": "Configuración en un clic para flujos comunes. Toca una tarjeta para aplicar.",+ "preset_fast": "Rápido",+ "preset_fast_desc": "480p · sin metadatos · sin subtítulos",+ "preset_quality": "Calidad",+ "preset_quality_desc": "Mejor vídeo · metadatos · miniatura",+ "preset_compact": "Compacto",+ "preset_compact_desc": "720p · metadatos · sin miniatura",+ "preset_music_only": "Solo música",+ "preset_music_only_desc": "Audio · etiquetas ID3 · carátula",+ "hotkey_enabled": "Atajo global",+ "hotkey_enabled_desc": "Descarga la URL del portapapeles con un atajo de teclado",+ "hotkey_binding": "Combinación del atajo",+ "hotkey_record": "Grabar",+ "hotkey_type": "Escribir",+ "hotkey_press": "Pulsa las teclas...",+ "music_hotkey_enabled": "Atajo para descargar música",+ "music_hotkey_enabled_desc": "Descarga la URL del portapapeles como audio con un atajo (usa el formato de música de abajo)",+ "music_hotkey_binding": "Combinación del atajo de música",+ "music_audio_format": "Formato de descarga de música",+ "music_audio_format_desc": "Formato usado por el atajo de música y por el descargador del plugin Music",+ "copy_to_clipboard_on_hotkey": "Copiar archivo al portapapeles tras descarga por atajo",+ "copy_to_clipboard_on_hotkey_desc": "Copia automáticamente el archivo descargado al portapapeles para pegarlo fácilmente",+ "filename_template": "Plantilla de nombre de archivo",+ "filename_template_desc": "Plantilla de salida yt-dlp para los archivos descargados",+ "filename_template_preview": "Vista previa: {{preview}}"+ },+ "update_available": "OmniGet {{version}} está disponible",+ "update_button": "actualizar ahora",+ "update_downloading": "descargando actualización...",+ "telegram": {+ "concurrent_downloads": "Descargas simultáneas",+ "concurrent_downloads_desc": "Máximo de descargas de archivos a la vez",+ "fix_file_extensions": "Corregir extensiones de archivo",+ "fix_file_extensions_desc": "Añade la extensión correcta según el tipo de archivo"+ },+ "dependencies": {+ "title": "Dependencias",+ "not_found": "no encontrado",+ "install": "Instalar",+ "update": "Actualizar",+ "variant_aria": "Variante",+ "more_options": "Más opciones",+ "pick_custom_file": "Elegir archivo del disco…",+ "show_folder": "Mostrar carpeta",+ "pick_dialog_title": "Selecciona el archivo de {{name}}",+ "filter_pdfium": "Biblioteca PDFium",+ "filter_all_files": "Todos los archivos",+ "set_file_failed": "No se pudo establecer el archivo: {{msg}}",+ "open_folder_failed": "No se pudo abrir la carpeta: {{msg}}",+ "system_font_suffix": "sistema"+ },+ "typography": {+ "section_title": "Tipografía",+ "presets_title": "Presets",+ "presets_desc": "Combinaciones probadas. Un clic aplica fuentes + interlineado + espaciado.",+ "modified_indicator": "(modificado manualmente)",+ "fonts_title": "Fuentes",+ "fonts_desc": "Elige por familia. La lista muestra fuentes incluidas en la app (las del sistema aún no se admiten).",+ "reset": "Restablecer",+ "display_label": "Display",+ "body_label": "Cuerpo",+ "mono_label": "Mono",+ "body_sample": "El veloz murciélago hindú",+ "line_height_label": "Interlineado",+ "line_height_desc": "Espacio vertical entre líneas. Mayor = más aireado, más fácil de leer en sesiones largas.",+ "spacing_label": "Espaciado global",+ "spacing_desc": "Multiplica los tokens de espacio (padding, gap, margin). 1.0× = predeterminado. 0.85× compacta toda la interfaz; 1.25× la hace más aireada.",+ "preview_title": "Vista previa",+ "preview_desc": "En tiempo real. Respeta el tema activo.",+ "preset_omniget_default_name": "Omniget por defecto",+ "preset_omniget_default_desc": "Bricolage para display, Inter para cuerpo, Plex Mono. Estándar de la casa.",+ "preset_notion_like_name": "Estilo Notion",+ "preset_notion_like_desc": "Inter para display + cuerpo. Jerarquía por tamaño+peso, sin cambiar familia.",+ "preset_compact_name": "Compacto",+ "preset_compact_desc": "DM Sans + Inter, 90% de espaciado. Más texto en pantalla.",+ "preset_reading_name": "Modo lectura",+ "preset_reading_desc": "Bricolage + DM Sans, interlineado 1.7, 110% de espaciado. Sesiones largas.",+ "preset_tech_minimal_name": "Tech minimal",+ "preset_tech_minimal_desc": "Plex Mono en todo. Divisivo. Para devs a quienes les gusta."+ },+ "proxy": {+ "title": "Proxy",+ "enabled": "Activar proxy",+ "type": "Tipo",+ "host": "Host",+ "port": "Puerto",+ "username": "Usuario",+ "password": "Contraseña"+ },+ "ytdlp_flags": {+ "title": "Flags de yt-dlp"+ },+ "advanced": {+ "title": "Avanzado",+ "max_concurrent_downloads": "Descargas simultáneas",+ "max_concurrent_downloads_desc": "Máximo de descargas a la vez",+ "max_concurrent_segments": "Trozos descargados en paralelo en streams HLS (avanzado)",+ "concurrent_fragments": "Trozos descargados en paralelo (avanzado)",+ "concurrent_fragments_desc": "Cuántos trozos del archivo descarga yt-dlp a la vez por vídeo",+ "max_retries": "Reintentos por segmento",+ "stagger_delay": "Pausa entre descargas (ms)",+ "stagger_delay_desc": "Retardo antes de iniciar la próxima descarga simultánea",+ "reset": "Restablecer valores por defecto",+ "reset_confirm": "¿Estás seguro? Toda la configuración se restablecerá.",+ "torrent_listen_port": "Puerto de escucha de torrent",+ "torrent_listen_port_desc": "Puerto TCP para conexiones BitTorrent entrantes",+ "cookies_from_browser": "Leer cookies directamente desde un perfil del navegador (avanzado)",+ "cookies_from_browser_desc": "Solo actívalo si la extensión del navegador no funciona. La mayoría no necesita tocar esto."+ },+ "cat_appearance": "Apariencia",+ "cat_typography": "Tipografía",+ "cat_plugins": "Plugins",+ "cat_downloads": "Descargas",+ "cat_network": "Red",+ "cat_advanced": "Avanzado",+ "search_placeholder": "Buscar en configuración...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Muestra tu actividad en tu perfil de Discord. El cronómetro sigue corriendo entre actividades, nunca se reinicia.",+ "enable": "Mostrar actividad en Discord",+ "privacy_note": "Muestra qué estás escuchando, viendo o leyendo. Tus descargas se mantienen privadas.",+ "test": "Probar conexión",+ "test_desc": "Envía una actividad de prueba para verificar que Discord está abierto y conectado.",+ "test_button": "Enviar prueba",+ "test_ok": "Conectado a Discord",+ "test_fail": "No se pudo conectar con Discord. Asegúrate de que esté abierto.",+ "saved": "Guardado",+ "save": "Guardar",+ "advanced": "Avanzado",+ "app_id": "Application ID",+ "app_id_hint": "ID de la aplicación de Discord. Cámbialo solo si sabes lo que haces.",+ "large_image": "Clave de imagen grande",+ "large_image_hint": "Nombre del recurso subido a tu aplicación de Discord."+ }+ },+ "omnibox": {+ "placeholder": "Pega una URL, enlace magnet, .torrent o busca",+ "searching": "Buscando...",+ "search_empty": "Sin resultados",+ "unsupported": "Plataforma aún no admitida",+ "go_to_hotmart": "Ir a Hotmart",+ "download": "Descargar",+ "options": "Opciones",+ "advanced": "Avanzado",+ "preparing": "Preparando descarga...",+ "error": "La descarga falló",+ "retry": "Reintentar",+ "batch_detected": "{{count}} URLs detectadas",+ "batch_download_all": "Descargar todo",+ "batch_queued": "{{count}} descargas añadidas a la cola",+ "batch_file_open": "Cargar desde archivo",+ "batch_file_title": "Selecciona un archivo .txt con URLs",+ "batch_file_empty": "No se encontraron URLs válidas en el archivo",+ "mode_auto": "Auto",+ "mode_audio": "Solo audio (MP3)",+ "mode_mute": "Sin sonido",+ "quality": "Calidad",+ "quality_best": "Mejor calidad",+ "quality_1080p": "Full HD (1080p)",+ "quality_720p": "HD (720p) — más ligero",+ "quality_480p": "Media (480p) — rápida",+ "quality_360p": "Baja (360p) — muy ligera",+ "view_formats": "Ver formatos",+ "hide_formats": "Ocultar formatos",+ "no_formats": "No hay formatos disponibles para este vídeo",+ "formats_error": "Error al cargar formatos",+ "preset_best": "Mejor",+ "preset_music": "Música",+ "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.",+ "referer_label": "Referer (opcional)",+ "referer_placeholder": "https://example.com",+ "external_url_ready": "URL recibida desde la extensión de Chrome",+ "content_type": {+ "video": "Vídeo",+ "audio": "Audio",+ "image": "Imagen",+ "post": "Publicación",+ "reel": "Reel",+ "clip": "Clip",+ "short": "Short",+ "playlist": "Playlist",+ "course": "Curso",+ "unknown": "Multimedia"+ },+ "fmt_type": "Tipo",+ "fmt_quality": "Calidad",+ "fmt_streams": "A/V",+ "fmt_video": "Vídeo",+ "fmt_audio": "Audio",+ "fmt_size": "Tamaño",+ "fmt_speed": "Velocidad"+ },+ "about": {+ "tab": {+ "terms": "términos",+ "project": "proyecto",+ "roadmap": "roadmap",+ "changelog": "changelog",+ "debug": "info de depuración"+ },+ "debug": {+ "title": "Info de depuración",+ "description": "Detalles del entorno para pegar en un reporte de bug. No incluye ningún secreto.",+ "copy_button": "Copiar al portapapeles",+ "copied_short": "Copiado",+ "copied": "Info de depuración copiada al portapapeles",+ "copy_failed": "No se pudo copiar al portapapeles"+ },+ "debug_disabled_redirect": "La página de depuración está oculta. Actívala en Configuración → Avanzado → Diagnóstico.",+ "description": "tu descargador de medios. open source y gratis.",+ "terms_title": "términos de uso",+ "terms_text": "OmniGet se proporciona tal cual y no garantizamos nada. la app facilita descargar contenido que ya está públicamente disponible en internet, pero no asumimos ninguna responsabilidad por lo que descargas ni por lo que haces con ello. al usar OmniGet aceptas esto.",+ "legal_title": "base legal",+ "legal_text": "el uso personal de OmniGet está respaldado por el artículo 184, §4 del Código Penal Brasileño, que indica que copiar una obra para uso privado, en una única copia y sin ánimo de lucro, no es delito. eso no significa que puedas distribuirla, revenderla o usarla comercialmente. los derechos de autor siguen aplicando en materia civil.",+ "responsibility_title": "responsabilidad del usuario",+ "responsibility_text": "tú (el usuario) eres responsable de lo que haces con OmniGet y del contenido que obtienes a través de él. respeta los derechos de autor y los términos de servicio de cada plataforma. da siempre crédito a los creadores originales. no lo uses para nada ilegal o comercial que viole derechos ajenos. si usas el contenido con fines educativos, cita tus fuentes.",+ "mascot_title": "Loop",+ "mascot_text": "Loop es la mascota de OmniGet, una pequeña criatura expresiva que reacciona a tus descargas en tiempo real. queremos mantener a Loop a salvo, así que algunas reglas: puedes hacer fan art de Loop libremente, pero no puedes usar su diseño u obras comercialmente, en tus propios proyectos, ni modificar y redistribuir las obras originales del proyecto.",+ "license_title": "licencia",+ "license_text": "OmniGet es open source y está bajo licencia GPL-3.0. el código fuente está en GitHub. el nombre \"OmniGet\", el logo y Loop son marcas del proyecto y no están cubiertos por la licencia del código.",+ "star_button": "darle estrella en GitHub",+ "star_description": "¡si te gusta el proyecto, dale una estrella!",+ "version": "versión",+ "features_title": "lo que hemos construido hasta ahora",+ "feature_platforms": "descargas desde más de 10 plataformas y más de 1000 vía yt-dlp: YouTube, Instagram, TikTok, Twitter/X, Reddit, Twitch, Pinterest, Vimeo, Bluesky, Telegram",+ "feature_hotmart": "descarga de cursos de Hotmart con login (vídeos, adjuntos, descripciones)",+ "feature_progress": "progreso de descarga en tiempo real con ETA y velocidad",+ "feature_mascot": "Loop, la mascota que reacciona a tus descargas",+ "feature_themes": "11 temas: Oscuro, Claro, Catppuccin (4 variantes), One Dark Pro, Dracula, NyxVamp (3 variantes)",+ "feature_i18n": "disponible en inglés, portugués, chino, japonés, italiano y francés",+ "feature_tech": "construido con Tauri + Rust. rápido y ligero",+ "roadmap_intro": "lo que está planeado para las próximas versiones de OmniGet.",+ "roadmap_platforms_title": "integraciones",+ "roadmap_features_title": "funciones",+ "roadmap_feature_telegram_multi_account": "varias cuentas de Telegram",+ "roadmap_community_title": "¿tienes una idea?",+ "roadmap_community_text": "¡estamos abiertos a ideas y sugerencias! es una buena forma de pedir una nueva plataforma o función.",+ "roadmap_community_discord": "habla con nosotros en discord:",+ "roadmap_community_issue": "o abre un issue en el repositorio:",+ "tagline": "Descarga lo que sea, desde donde sea.",+ "credit": "Hecho con cariño por tonho.wtf"+ },+ "marketplace": {+ "title": "Marketplace",+ "installed": "Instalados",+ "browse": "Explorar",+ "no_plugins": "Sin plugins instalados",+ "enable": "Activar",+ "disable": "Desactivar",+ "enabled": "Activado",+ "disabled": "Desactivado",+ "version": "v{{version}}",+ "by_author": "por {{author}}",+ "uninstall": "Desinstalar",+ "restart_required": "Reinicia OmniGet para aplicar los cambios",+ "browse_loading": "Cargando plugins...",+ "browse_error": "No se pudieron cargar los plugins",+ "browse_empty": "Aún no hay plugins disponibles",+ "official_badge": "Oficial",+ "community_badge": "Comunidad",+ "installed_badge": "Instalado",+ "capabilities": "Permisos",+ "cap_events": "Enviar eventos a la app",+ "cap_toast": "Mostrar notificaciones",+ "cap_settings": "Leer y guardar configuración",+ "cap_filesystem": "Acceso a carpetas de descarga",+ "cap_proxy": "Usar configuración de proxy",+ "cap_tools": "Usar herramientas administradas (yt-dlp, FFmpeg)",+ "cap_download_queue": "Enviar descargas a la cola",+ "install": "Instalar",+ "update_available": "Actualizar",+ "update_hint": "v{{version}} disponible",+ "plugin_not_installed": "Plugin no instalado",+ "plugin_install_hint": "Instala este plugin desde el Marketplace para usarlo.",+ "go_to_marketplace": "Ir al Marketplace",+ "plugin_restart_hint": "Reinicia OmniGet para cargar este plugin.",+ "plugin_incompatible_title": "Plugin incompatible con esta versión",+ "plugin_incompatible_hint": "Este plugin fue compilado para una versión anterior de OmniGet y no puede cargarse. Reinstálalo desde el Marketplace para obtener una versión compatible — reiniciar no soluciona esto.",+ "plugin_load_failed_title": "Error al cargar el plugin",+ "plugin_load_failed_hint": "OmniGet no pudo cargar este plugin. Intenta reinstalarlo desde el Marketplace.",+ "plugin_load_error_details": "Detalles: {{error}}",+ "reinstall": "Reinstalar"+ },+ "services": {+ "title": "Soporta YouTube, Instagram y más de 1000 sitios",+ "title_show": "ver servicios admitidos",+ "title_hide": "ocultar servicios admitidos",+ "disclaimer": "la disponibilidad depende de cada plataforma y puede variar",+ "and_more": "+1000 más"+ },+ "terms_note": {+ "agreement": "al continuar aceptas los",+ "link": "términos y ética de uso"+ },+ "convert": {+ "title": "Convertir",+ "select_files": "Seleccionar archivos",+ "select_folder": "Seleccionar carpeta",+ "empty": "No hay archivos seleccionados. Añade archivos para convertir.",+ "file_list": "Archivos",+ "options_title": "Opciones",+ "output_format": "Formato de salida",+ "video_codec": "Códec de vídeo",+ "audio_codec": "Códec de audio",+ "resolution": "Resolución",+ "preset": "Preset",+ "video_bitrate": "Bitrate de vídeo",+ "audio_bitrate": "Bitrate de audio",+ "trim_start": "Recortar inicio",+ "trim_end": "Recortar fin",+ "convert_btn": "Convertir",+ "converting": "Convirtiendo...",+ "cancel": "Cancelar",+ "remove": "Quitar",+ "clear_all": "Limpiar todo",+ "status_idle": "Pendiente",+ "status_probing": "Analizando...",+ "status_ready": "Listo",+ "status_converting": "Convirtiendo",+ "status_complete": "Completo",+ "status_error": "Error",+ "original": "Original",+ "auto": "Auto",+ "hwaccel_detected": "Aceleración GPU: {{encoder}}",+ "hwaccel_none": "Sin aceleración GPU detectada",+ "probe_failed": "Análisis fallido",+ "conversion_failed": "Conversión fallida",+ "toast_complete": "Conversión completa",+ "toast_error": "Conversión fallida",+ "no_ffmpeg": "FFmpeg no encontrado. Instala FFmpeg para usar la conversión."+ },+ "changelog": {+ "title": "Novedades",+ "empty": "No hay notas de versión disponibles."+ },+ "onboarding": {+ "welcome_title": "¡Bienvenido a OmniGet!",+ "welcome_desc": "Te ayudaré a descargar cualquier vídeo o curso de internet. Simple, rápido y gratis.",+ "next": "Siguiente",+ "skip": "Saltar",+ "back": "Atrás",+ "finish": "Empezar",+ "step_of": "Paso {{current}} de {{total}}",+ "folder_title": "¿Dónde guardar tus descargas?",+ "folder_desc": "Elige la carpeta donde se guardarán tus vídeos y cursos.",+ "folder_current": "Carpeta actual:",+ "folder_change": "Cambiar carpeta",+ "deps_title": "Herramientas necesarias",+ "deps_desc": "Necesito un par de herramientas para funcionar bien. ¡Puedo instalarlas automáticamente!",+ "deps_install_all": "Instalar todas",+ "language_label": "Idioma",+ "done_title": "¡Todo listo!",+ "done_desc": "Pega una URL en la barra de búsqueda y mira la magia.",+ "plugins_title": "Potencia tu OmniGet",+ "plugins_desc": "Elige qué funciones instalar. Siempre puedes añadirlas o quitarlas desde el Marketplace.",+ "hotkey_title": "Atajo global",+ "hotkey_desc": "Copia cualquier URL de vídeo, pulsa el atajo y OmniGet empieza a descargar al instante — incluso minimizado.",+ "hotkey_on": "Activado",+ "hotkey_off": "Desactivado",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Muestra en tu perfil de Discord que estás usando OmniGet — incluyendo qué escuchas, ves o lees.",+ "rpc_on": "Activado",+ "rpc_off": "Desactivado",+ "rpc_privacy_note": "Muestra qué estás escuchando, viendo o leyendo. Tus descargas se mantienen privadas.",+ "theme_label": "Tema",+ "theme_system": "Sistema",+ "theme_light": "Claro",+ "theme_dark": "Oscuro"+ },+ "hints": {+ "omnibox": "Pega aquí la URL del vídeo o el medio que quieres descargar.",+ "telegram": "Conecta tu cuenta de Telegram para descargar multimedia de canales y grupos.",+ "hotkey": "Atajo global: descarga automáticamente la URL del portapapeles.",+ "clipboard": "Detecta URLs automáticamente cuando copias un enlace y rellena el omnibox.",+ "downloads_empty": "Tus descargas aparecerán aquí. Ve a la página de inicio para empezar.",+ "convert": "Convierte archivos multimedia entre formatos usando FFmpeg."+ },+ "common": {+ "cancel": "Cancelar",+ "clear": "Limpiar",+ "retry": "Reintentar",+ "close": "Cerrar",+ "hint": "Pista",+ "error": "Error",+ "unknown_error": "Error desconocido",+ "ytdlp_missing": "yt-dlp no está instalado. Instálalo en Configuración para activar las descargas.",+ "go_to_settings": "Ir a Configuración",+ "cookie_error_message": "La detección automática de cookies solo funciona con Firefox. Chrome, Edge y otros navegadores basados en Chromium bloquean el acceso a cookies. Para usar cookies: instala Firefox e inicia sesión en tus cuentas allí, o exporta un archivo cookies.txt desde tu navegador y configúralo en Configuración > Descargas > Archivo de cookies.",+ "cookie_file_label": "Archivo de cookies (cookies.txt)",+ "cookie_file_choose": "Elegir archivo",+ "cookie_file_hint": "Exporta las cookies de tu navegador con una extensión como 'Get cookies.txt LOCALLY' y selecciona el archivo aquí. Es necesario para usuarios de Chrome/Edge que necesitan descargas autenticadas."+ },+ "errors": {+ "login_required": "Se requiere inicio de sesión — usa las cookies del navegador o prueba otra URL",+ "rate_limited": "Demasiadas solicitudes (429) — vuelve a intentarlo más tarde",+ "access_denied": "Acceso denegado (403) — el vídeo puede ser privado o estar restringido por región",+ "extraction_failed": "Extracción fallida — actualiza yt-dlp o reintenta",+ "format_unavailable": "Formato solicitado no disponible",+ "video_unavailable": "Vídeo no disponible o eliminado",+ "video_private": "Este vídeo es privado",+ "copyright_blocked": "Bloqueado por derechos de autor",+ "geo_restricted": "No disponible en tu región",+ "connection_timeout": "Tiempo de conexión agotado — revisa tu internet",+ "ffmpeg_missing": "FFmpeg no encontrado — instálalo en Configuración",+ "unsupported_url": "URL no admitida — revisa el enlace",+ "page_access_failed": "No se pudo acceder a la página — revisa el enlace y la conexión",+ "no_formats": "No se encontraron formatos de vídeo para este enlace",+ "cookie_database": "Acceso a cookies del navegador fallido. La descarga seguirá sin autenticación.",+ "tiktok_blocked": "TikTok está bloqueando temporalmente las solicitudes. Vuelve a intentar en unos minutos.",+ "download_timeout": "Tiempo de descarga agotado. Revisa tu conexión a internet.",+ "size_mismatch": "El tamaño del archivo descargado no coincide. Reintenta.",+ "disk_full": "Error de escritura — puede que tu disco esté lleno.",+ "path_too_long": "La ruta de la carpeta de descargas es demasiado larga ({{current}}/{{limit}} caracteres). Elige una más corta.",+ "console_encoding": "Problema de codificación de consola (locale no UTF-8). Actualiza yt-dlp en Configuración → Dependencias, o ejecuta \"chcp 65001\" en una terminal y reabre la app.",+ "extractor_broken": "El extractor del sitio está roto. Actualiza yt-dlp en Configuración → Dependencias y reintenta."+ },+ "debug": {+ "title": "Registro de actividad",+ "enable": "Registro de actividad",+ "enable_desc": "Mira lo que hace OmniGet entre bastidores",+ "filter_all": "Todo",+ "filter_downloads": "Descargas",+ "filter_network": "Red",+ "filter_auth": "Autenticación",+ "filter_system": "Sistema",+ "filter_convert": "Conversión",+ "filter_errors": "Solo errores",+ "copy_report": "Copiar informe",+ "report_copied": "Informe de diagnóstico copiado al portapapeles",+ "clear": "Limpiar",+ "no_entries": "Aún no hay actividad. Empieza una descarga para ver eventos aquí.",+ "open_panel": "Abrir registro de actividad"+ },+ "p2p": {+ "send_file": "Enviar archivo",+ "send_title": "Enviar archivo por P2P",+ "send_description": "Envía cualquier archivo a otro usuario de OmniGet. Se generará un código — el receptor lo pega en el omnibox para descargar.",+ "select_file": "Seleccionar archivo",+ "share_code": "Código de envío",+ "click_to_copy": "Clic para copiar",+ "share_hint": "Comparte este código con el receptor",+ "code_copied": "Código copiado al portapapeles",+ "waiting_for_receiver": "Esperando al receptor...",+ "transferring": "Transfiriendo...",+ "transfer_complete": "Transferencia completa",+ "send_failed": "Envío fallido",+ "try_again": "Reintentar",+ "pause": "Pausar",+ "resume": "Reanudar",+ "paused": "Pausado",+ "receive_title": "Transferencia P2P entrante",+ "receive_description": "Alguien quiere enviarte un archivo. Acepta para empezar a descargar.",+ "accept_transfer": "Aceptar y descargar",+ "reject_transfer": "Rechazar",+ "searching_hint": "Conectando al servidor de relevo..."+ },+ "mascot": {+ "idle": "¡Pega un enlace o busca para empezar!|¿Qué vamos a descargar hoy?|¡Listo cuando quieras!",+ "detecting": "A ver, déjame mirar esto...|Analizando el enlace...|Un segundo...",+ "detected": "¡Lo tengo! ¡Listo cuando quieras!|¡Encontrado! ¿Vamos?|¡Todo listo!",+ "preparing": "Preparando todo...|Casi listo...|Preparando tu descarga...",+ "search": "¡Mira lo que encontré!|¡Échale un vistazo!|¡Aquí tienes!",+ "error": "Ups, algo salió mal. ¿Reintentar?|No funcionó. ¿Probamos otra vez?|Hmm, algo se rompió...",+ "complete": "¡Listo!|¡Descarga completa!|¡Lo tengo para ti!",+ "amazed": "¡Wow, tu primera descarga! 🎉|¡Ahí está — la primera!|¡Guardada! ¡Bienvenido a bordo!",+ "downloading": "Descargando ahora...|¡A trabajar!|Trayendo tus archivos...",+ "stalled": "Hmm, esto está tardando...|Aguanta, sigo trabajando...|La conexión va lenta...",+ "queue": "Esperando en la cola...|Paciencia, ya casi...|¡Tu turno se acerca!"+ },+ "courses": {+ "title": "Cursos",+ "search_placeholder": "Buscar plataformas...",+ "not_connected": "No conectado",+ "connection_failed": "Conexión fallida",+ "connected_as": "Conectado como {{email}}",+ "back": "Volver a Cursos",+ "coming_soon": "Próximamente",+ "update_plugin_hint": "Actualiza el plugin Cursos para la mejor experiencia.",+ "update_plugin_for_platform": "Esta plataforma necesita el plugin Cursos actualizado. Mira el Marketplace.",+ "search_btn": "Buscar",+ "login_with_browser": "Iniciar sesión con el navegador",+ "browser": "Navegador",+ "browser_hint": "Se abrirá una ventana del navegador para que inicies sesión. Tras hacerlo, tu sesión se detectará automáticamente.",+ "otp_check_email": "Revisa tu correo para el código de verificación.",+ "otp_code_label": "Código de verificación",+ "verify_code": "Verificar código"+ },+ "hotmart": {+ "title": "Hotmart",+ "login": "Iniciar sesión",+ "logout": "Cerrar sesión",+ "checking_session": "Comprobando sesión...",+ "logged_as": "Sesión iniciada como {{email}}",+ "email_label": "Correo",+ "email_placeholder": "[email protected]",+ "password_label": "Contraseña",+ "password_placeholder": "Tu contraseña",+ "authenticating": "Autenticando...",+ "courses_title": "Tus cursos",+ "loading_courses": "Cargando cursos...",+ "courses_error": "Error al cargar cursos",+ "no_courses": "No hay cursos en esta cuenta.",+ "course_count": "{{count}} cursos",+ "course_count_one": "{{count}} curso",+ "page_of": "Página {{current}} de {{total}}",+ "free": "Gratis",+ "download_btn": "Descargar",+ "downloading": "Descargando...",+ "downloaded": "Descargado",+ "download_retry": "Error — Reintentar",+ "cancel_download": "Cancelar",+ "unavailable": "No disponible",+ "external_platform": "Plataforma externa",+ "choose_folder": "Elegir carpeta de descarga",+ "refresh": "Actualizar",+ "unknown_error": "Error desconocido",+ "captcha_detected": "Captcha detectado — resuélvelo en la ventana de inicio de sesión."+ },+ "torrent": {+ "open_file": "Abrir .torrent"+ },+ "udemy": {+ "title": "Udemy",+ "login": "Iniciar sesión",+ "logout": "Cerrar sesión",+ "checking_session": "Comprobando sesión...",+ "logged_as": "Sesión iniciada como {{email}}",+ "email_label": "Correo",+ "email_placeholder": "[email protected]",+ "authenticating": "Iniciando sesión...",+ "waiting_code": "Se envió un código de 6 dígitos a tu correo. Introdúcelo en la ventana de inicio de sesión.",+ "waiting_code_title": "Revisa tu correo",+ "courses_title": "Tus cursos",+ "loading_courses": "Cargando cursos...",+ "courses_error": "Error al cargar cursos",+ "no_courses": "No hay cursos en esta cuenta.",+ "course_count": "{{count}} cursos",+ "course_count_one": "{{count}} curso",+ "page_of": "Página {{current}} de {{total}}",+ "download_btn": "Descargar",+ "downloading": "Descargando...",+ "downloaded": "Descargado",+ "download_retry": "Error — Reintentar",+ "choose_folder": "Elegir carpeta de descarga",+ "refresh": "Actualizar",+ "unknown_error": "Error desconocido",+ "lectures": "{{count}} clases",+ "login_email_tab": "Correo (Udemy.com)",+ "login_cookies_tab": "Cookies (Empresa)",+ "cookies_instructions": "Para cuentas Udemy Business/Enterprise (ej. empresa.udemy.com), exporta tus cookies del navegador usando una extensión como \"Get cookies.txt locally\" en formato JSON, luego pégalas o carga el archivo aquí.",+ "cookies_placeholder": "Pega el JSON de cookies aquí...",+ "cookies_load_file": "Cargar archivo JSON",+ "cookies_login": "Iniciar sesión con cookies",+ "logged_as_enterprise": "Sesión iniciada como {{email}} ({{portal}}.udemy.com)",+ "upload_file": "Subir archivo"+ },+ "study": {+ "common": {+ "loading": "Cargando...",+ "error": "Error",+ "save": "Guardar",+ "saving": "Guardando...",+ "cancel": "Cancelar",+ "create": "Crear",+ "clear": "Limpiar",+ "delete": "Eliminar",+ "edit": "Editar",+ "close": "Cerrar",+ "copy": "Copiar",+ "copied": "¡Copiado!",+ "retry": "Reintentar",+ "refresh": "Actualizar",+ "search": "Buscar",+ "all": "Todo",+ "empty": "Aún no hay nada aquí",+ "confirm": "¿Estás seguro?",+ "dismiss": "Descartar",+ "go_home": "Volver"+ },+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source en GitHub",+ "long_pitch": "Estudiar no es solo PDFs. Son libros, podcasts, clases, anotaciones entre medias. omniget agrupa todo — sin perder el ritmo cambiando de ventana.",+ "cta_github": "Ver en GitHub"+ },+ "hub": {+ "title": "Estudio",+ "subtitle": "Convierte tus cursos descargados en un bucle de práctica deliberada.",+ "library": "Biblioteca",+ "music": "Música",+ "focus": "Concentración",+ "progress": "Progreso",+ "achievements": "Logros",+ "anki": "Anki",+ "notes": "Notas",+ "read": "Leer",+ "settings": "Configuración",+ "visited_recent": "Visitado recientemente",+ "recently_added": "Añadido recientemente",+ "new": "nuevo",+ "now": "Ahora",+ "continue_title": "Continuar curso",+ "continue_cta": "Reanudar",+ "review_title": "Repasar tarjetas",+ "review_count": "{{n}} tarjetas pendientes",+ "review_cta": "Repasar",+ "review_empty": "Nada pendiente hoy",+ "focus_title": "Sesión de concentración",+ "focus_hint": "25 min · concentración profunda",+ "focus_cta": "Empezar",+ "explore": "Explorar",+ "streak_label": "días",+ "streak_none": "Sin racha",+ "goal_met": "Meta diaria alcanzada",+ "greeting_morning": "Buenos días",+ "greeting_afternoon": "Buenas tardes",+ "greeting_evening": "Buenas noches",+ "secondary_review": "{{n}} tarjetas por repasar",+ "secondary_continue": "Reanudar {{title}}",+ "secondary_resume_book": "Seguir leyendo {{title}}",+ "secondary_focus": "Empezar una sesión de concentración",+ "secondary_explore": "Explorar biblioteca",+ "review_subtitle": "tarjetas pendientes hoy",+ "focus_hint_default": "25 min · concentración profunda",+ "made_by": "Hecho por:"+ },+ "search": {+ "placeholder": "Busca cursos, clases, notas, tarjetas...",+ "courses": "Cursos",+ "lessons": "Clases",+ "notes": "Notas",+ "no_results": "Sin resultados para \"{{term}}\"",+ "hint": "Pulsa Ctrl+K para abrir · Esc para cerrar"+ },+ "palette": {+ "aria_modes": "Modos de paleta",+ "tab_search": "Buscar",+ "tab_jump": "Saltar a",+ "tab_action": "Acciones",+ "heading_shortcuts": "Atajos",+ "heading_recent_pages": "Páginas recientes",+ "heading_actions": "Acciones",+ "empty_pages": "Aún no hay páginas.",+ "shortcut_daily": "Diario de hoy",+ "shortcut_journal_history": "Historial del diario",+ "shortcut_graph": "Grafo",+ "shortcut_templates": "Plantillas",+ "aria_xp_progress": "{{pct}}% al nivel {{level}}",+ "action_create_page_label": "Crear página",+ "action_create_page_hint": "Nueva página en blanco",+ "action_open_daily_label": "Abrir diario de hoy",+ "action_open_templates_label": "Abrir plantillas",+ "action_open_graph_label": "Abrir grafo",+ "action_open_graph_hint": "Visualización del grafo",+ "action_rebuild_fts_label": "Reconstruir búsqueda (FTS)",+ "action_rebuild_fts_hint": "Reconstruye el índice de texto completo",+ "action_export_graph_label": "Exportar grafo (JSON)",+ "action_export_graph_hint": "Descargar notes-graph.json",+ "action_open_settings_label": "Abrir configuración",+ "action_vacuum_label": "Compactar base de datos (vacuum)",+ "action_vacuum_hint": "Mantenimiento de SQLite"+ },+ "music": {+ "title": "Música",+ "subtitle": "Tus pistas, álbumes y playlists.",+ "library_title": "Biblioteca",+ "favorites_title": "Favoritos",+ "favorites_subtitle": "Pistas marcadas con ❤",+ "favorites_empty": "Aún no hay favoritos. Marca una pista para empezar.",+ "add_root": "Añadir carpeta",+ "add_root_cta": "Añadir carpeta de música",+ "clear_covers": "Restablecer carátulas",+ "clear_covers_hint": "Borra la caché de carátulas y fuerza re-extracción en el próximo escaneo",+ "clear_covers_confirm": "¿Borrar todas las carátulas en caché? El próximo escaneo las volverá a extraer.",+ "clear_covers_done": "{{files}} archivos eliminados · {{tracks}} pistas restablecidas",+ "diagnostics": "Diagnóstico",+ "diagnostics_hint": "Muestra el estado actual de carátulas (rutas, tamaños, conteos) — útil cuando no aparecen las miniaturas",+ "diagnostics_title": "Diagnóstico de carátulas",+ "scan_now": "Escanear",+ "scanning": "Escaneando…",+ "scan_done": "{{added}} añadidas · {{updated}} actualizadas · {{removed}} eliminadas",+ "root_added": "Carpeta añadida: {{path}}",+ "empty_no_roots_title": "Tu biblioteca de música está vacía",+ "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.",+ "empty_results": "Sin resultados.",+ "empty_album": "Este álbum está vacío.",+ "shelf_continue": "Seguir escuchando",+ "shelf_albums": "Álbumes",+ "shelf_added": "Añadidos recientemente",+ "shelf_most_played": "Más reproducidos",+ "see_all": "Ver todo",+ "tracks_count": "{{count}} pistas",+ "eyebrow_album": "Álbum",+ "play": "Reproducir",+ "pause": "Pausar",+ "prev": "Anterior",+ "next": "Siguiente",+ "shuffle": "Aleatorio",+ "repeat": "Repetir",+ "favorite": "Favorito",+ "unfavorite": "Quitar favorito",+ "player_aria": "Reproductor de música",+ "tab_tracks": "Pistas",+ "tab_albums": "Álbumes",+ "tab_artists": "Artistas",+ "search_placeholder": "Buscar título, artista, álbum…",+ "nav_home": "Inicio",+ "nav_library": "Biblioteca",+ "nav_favorites": "Favoritos",+ "nav_genres": "Géneros",+ "nav_activity": "Actividad",+ "queue_clear": "Limpiar",+ "eq_title": "Ecualizador",+ "eq_enable": "Activar ecualizador",+ "eq_preset": "Preset",+ "eq_reset": "Restablecer",+ "eq_preset_flat": "Plano",+ "eq_preset_bass": "Bajos",+ "eq_preset_vocal": "Voces",+ "eq_preset_treble": "Agudos",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Clásico",+ "eq_preset_electronic": "Electrónica",+ "eq_preset_custom": "Personalizado",+ "genres_title": "Géneros",+ "genres_subtitle": "Explora por género detectado en tus archivos.",+ "no_genres": "No se encontraron géneros. Las pistas necesitan etiqueta de género.",+ "eyebrow_genre": "Género",+ "albums_count": "{{count}} álbumes",+ "artists_count": "{{count}} artistas",+ "activity_title": "Tu actividad",+ "activity_subtitle": "Qué escuchaste, cuándo, cuánto.",+ "no_activity": "Sin actividad en este periodo. Reproduce algo para empezar a ver estadísticas.",+ "period_7d": "7 días",+ "period_30d": "30 días",+ "period_90d": "90 días",+ "period_1y": "1 año",+ "period_all": "Siempre",+ "total_plays": "Reproducciones",+ "total_listened": "Tiempo escuchado",+ "unique_tracks": "Pistas únicas",+ "top_tracks": "Top pistas",+ "top_artists": "Top artistas",+ "top_albums": "Top álbumes",+ "top_genres": "Top géneros",+ "empty": "Vacío",+ "lyrics_title": "Letras",+ "lyrics_loading": "Buscando letras…",+ "lyrics_not_found": "No se encontraron letras",+ "lyrics_lrclib_hint": "Letras de lrclib.net (base comunitaria de letras sincronizadas). Puede no existir para pistas oscuras.",+ "lyrics_no_track": "No hay pista en reproducción",+ "lyrics_refresh": "Buscar de nuevo",+ "lyrics_source": "Fuente: {{source}}",+ "n_selected": "{{count}} seleccionada(s)",+ "selection_aria": "Acciones de selección",+ "queued_count": "{{count}} en cola",+ "favorited_count": "{{count}} favorita(s)",+ "add_to_queue": "Añadir a la cola",+ "ctx_show_in_folder": "Abrir carpeta",+ "ctx_show_failed": "No se pudo abrir la carpeta",+ "nav_download": "Descargar",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Descargar audio",+ "ytdlp_subtitle": "Pega una URL (YouTube, SoundCloud, Bandcamp, cualquiera que admita yt-dlp). Se convertirá a audio en tu biblioteca.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Guardar en",+ "ytdlp_format": "Formato",+ "ytdlp_no_roots": "Añade primero una carpeta de música",+ "ytdlp_start": "Descargar",+ "ytdlp_downloading": "Descargando…",+ "ytdlp_done": "Descarga completa. Biblioteca actualizada.",+ "ytdlp_log": "Registro",+ "ytdlp_missing_title": "yt-dlp no encontrado",+ "ytdlp_missing_body": "Instala yt-dlp y asegúrate de que esté en el PATH del sistema (https://github.com/yt-dlp/yt-dlp). En Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Cola",+ "tab_lyrics": "Letras",+ "tab_info": "Info",+ "info_no_track": "Reproduce una pista para ver detalles",+ "field_album": "Álbum",+ "field_year": "Año",+ "field_genre": "Género",+ "field_duration": "Duración",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Reproducciones",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Conecta tu cuenta de Last.fm para scrobblear lo que reproduces. Necesitas crear una API app gratuita.",+ "lastfm_step1_title": "Crea una API app",+ "lastfm_step1_desc": "Ve a Last.fm y crea una aplicación. Obtendrás una API key y un shared secret.",+ "lastfm_step2_title": "Pega las credenciales",+ "lastfm_step2_desc": "Pega la API key y el shared secret de la app que creaste.",+ "lastfm_save_keys": "Guardar credenciales",+ "lastfm_keys_saved": "Credenciales guardadas",+ "lastfm_step3_title": "Autorizar acceso",+ "lastfm_step3_desc": "Abre Last.fm en tu navegador para aprobar. Luego vuelve y pulsa Finalizar.",+ "lastfm_authorize": "Autorizar con Last.fm",+ "lastfm_authorize_pending": "Aprueba el acceso en la página de Last.fm que se abrió y pulsa Finalizar:",+ "lastfm_open_auth": "Abrir página de aprobación",+ "lastfm_finalize": "Finalizar conexión",+ "lastfm_connected": "Conectado como {{username}}",+ "lastfm_connected_as": "Conectado como {{username}}",+ "lastfm_connected_hint": "Las pistas que escuchas más de 30s se scrobblean en tu cuenta. El \"reproduciendo\" se actualiza en tiempo real.",+ "lastfm_enable_scrobble": "Scrobble automático",+ "lastfm_disconnect": "Desconectar",+ "lastfm_disconnect_confirm": "¿Borrar credenciales y desconectar?",+ "lastfm_disconnected": "Desconectado",+ "dl_hero_title": "Pega una URL o busca",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, cualquiera que admita yt-dlp. Se convierte en audio en tu biblioteca.",+ "dl_quality": "Calidad",+ "dl_quality_best": "Mejor disponible",+ "dl_idle_hint": "Pega la URL de una pista o álbum, o busca por título. Ctrl+V auto-detecta.",+ "dl_detecting": "Detectando…",+ "dl_searching": "Buscando…",+ "dl_search_empty": "Sin resultados.",+ "dl_unsupported": "Sitio no reconocido. Prueba con la URL directa de la pista.",+ "dl_preparing": "Iniciando descarga…",+ "dl_download_audio": "Descargar audio",+ "dl_started": "Descarga iniciada",+ "dl_recent": "Descargas recientes",+ "batch_done": "{{ok}} iniciadas, {{fail}} fallidas",+ "music_theme_title": "Tema de música",+ "music_theme_subtitle": "Personaliza los colores de la sección Música. Se guarda aparte del tema global de la app.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Color de acento",+ "music_theme_save": "Guardar tema",+ "music_theme_reset": "Restaurar por defecto",+ "music_theme_preset_default": "Por defecto",+ "music_theme_preset_indigo": "Índigo",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Violeta",+ "music_theme_preset_amber": "Ámbar",+ "music_theme_preset_custom": "Personalizado",+ "music_theme_use_dominant": "Usar el color de la carátula actual",+ "music_theme_dominant_off": "Color fijo",+ "music_theme_dominant_on": "Auto (color de carátula)",+ "rpc_title": "Discord Rich Presence",+ "rpc_intro": "Muestra qué estás escuchando en tu perfil de Discord. Necesita Discord abierto en el equipo.",+ "rpc_connected": "Conectado",+ "rpc_disconnected": "Desconectado",+ "rpc_enable": "Mostrar actividad en Discord",+ "rpc_advanced": "Configuración avanzada",+ "rpc_appid_hint": "Application ID de tu app en el Discord Developer Portal. El predeterminado es el app \"Loop\" de omniget.",+ "rpc_large_image": "Clave de imagen grande",+ "rpc_image_hint": "Nombre del recurso (Rich Presence Assets) subido en el Discord Dev Portal. Sin él, la actividad se muestra sin icono.",+ "rpc_save": "Guardar",+ "rpc_saved": "Configuración guardada",+ "rpc_test": "Probar conexión",+ "rpc_test_ok": "¡Conectado!",+ "rpc_test_fail": "Falló (Discord no abierto o app ID no válido)",+ "rpc_discord_running": "Discord debe estar abierto en el equipo (cliente de escritorio, no navegador).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Importa playlists de YouTube y YouTube Music. Reproduce bajo demanda — sin descarga.",+ "yt_intro": "Pega cualquier enlace de playlist de YouTube o YouTube Music. Para playlists privadas (incluido \"Me gusta\"), apunta al navegador donde tienes sesión.",+ "yt_step1_title": "¿De qué navegador sacar las cookies?",+ "yt_step1_desc": "Para playlists privadas y tu Biblioteca, omniget necesita cookies del navegador donde tienes sesión. Sin cookies, solo funcionan las playlists públicas.",+ "yt_browser_micro": "yt-dlp lee las cookies directamente desde tu navegador. Nada sale de tu equipo — todo es local.",+ "yt_browser_saved": "Cookies de {{browser}} configuradas",+ "yt_step2_title": "Importar una playlist",+ "yt_step2_desc": "Pega el enlace, omniget importa la lista de pistas. La reproducción es bajo demanda — no se descarga nada.",+ "yt_import": "Importar",+ "yt_imported": "{{title}}: {{count}} pistas importadas",+ "yt_lm_label": "Me gusta (Liked Music)",+ "yt_playlist_label": "Playlist de YouTube Music",+ "yt_yt_playlist_label": "Playlist de vídeos de YouTube",+ "yt_add_playlist": "Añadir playlist",+ "yt_empty_title": "Aún no hay playlists",+ "yt_empty_body": "Conecta una playlist de YouTube o YouTube Music para ver tus pistas aquí junto a las locales.",+ "yt_setup": "Configurar YouTube",+ "yt_refresh": "Re-importar",+ "yt_refreshed": "Actualizado: {{count}} pistas",+ "yt_remove": "Quitar",+ "yt_remove_confirm": "¿Quitar esta playlist de tu biblioteca? (La playlist en YouTube se queda intacta.)",+ "yt_search_placeholder": "Buscar en YouTube Music — canciones, artistas, álbumes…",+ "yt_recs_for": "Porque escuchaste: {{name}}",+ "yt_download": "Descargar",+ "yt_download_started": "Descarga iniciada",+ "sc_title": "SoundCloud",+ "sc_signin_heading": "Conectar a SoundCloud",+ "sc_signin_body": "Inicia sesión en SoundCloud en tu navegador — la extensión de OmniGet captura las cookies automáticamente. Luego vuelve y actualiza.",+ "sc_open_in_browser": "Abrir SoundCloud en el navegador",+ "sc_already_signed_in": "Ya tengo sesión, actualizar",+ "sc_search": "Buscar",+ "sc_refresh": "Actualizar",+ "sc_logout": "Cerrar sesión",+ "sc_loading": "Cargando…",+ "sc_status_client_id": "client_id",+ "sc_status_oauth": "oauth",+ "sc_import_url": "Importar por URL",+ "sc_import_url_title": "Importar desde una URL de SoundCloud",+ "sc_import_url_desc": "Pega cualquier enlace a una pista, playlist o artista — descubrimos el resto.",+ "sc_import_url_placeholder": "https://soundcloud.com/…",+ "sc_import_action": "Importar",+ "sc_import_invalid": "Eso no parece una URL de SoundCloud.",+ "sc_import_failed": "No se pudo resolver esa URL: {{error}}",+ "sc_import_success": "Importado \"{{title}}\"",+ "sc_section_continue": "Sigue donde lo dejaste",+ "sc_section_stream": "De gente que sigues",+ "sc_section_recommended": "Porque te gustó {{name}}",+ "sc_section_likes": "Tus me gusta ({{count}})",+ "sc_section_playlists": "Tus playlists",+ "sc_section_following": "Siguiendo",+ "sc_followers_count": "{{count}} seguidores",+ "sc_track_count": "{{count}} pistas",+ "sc_download_track": "Descargar pista",+ "sc_download_all": "Descargar todo ({{count}})",+ "sc_download_started": "Descarga en cola",+ "sc_download_bulk_progress": "Descargando {{current}} de {{total}}",+ "sc_download_bulk_done": "Terminado — {{success}} descargadas, {{failed}} fallidas",+ "sc_go_plus_badge": "Go+",+ "sc_go_plus_unavailable_hint": "Las pistas de alta calidad requieren cuenta SoundCloud Go+. El MP3 estándar funciona sin ella.",+ "sc_empty_likes_title": "Aún no hay me gusta",+ "sc_empty_likes_body": "Los corazones que des en SoundCloud aparecen aquí.",+ "sc_empty_likes_action": "Buscar música",+ "sc_empty_playlists_title": "Aún no hay playlists",+ "sc_empty_playlists_body": "Crea o importa una playlist en soundcloud.com — aparecerá aquí al actualizar.",+ "sc_empty_following_title": "Aún no sigues a nadie",+ "sc_empty_state_logged_out_action": "Llévame a SoundCloud",+ "sc_load_more": "Cargar más",+ "sc_show_count": "Mostrando {{shown}} de {{total}}",+ "sc_skeleton_loading": "Trayendo tu biblioteca…",+ "sc_offline_for_focus": "Guarda offline para que suene sin internet",+ "sc_recommended_seed_fallback": "tu gusto",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Conectado",+ "yt_state_anon": "No conectado",+ "yt_auth_title": "Conecta tu cuenta",+ "yt_auth_desc": "Para traer tu biblioteca privada (Me gusta, tus playlists), pega 2 cookies del navegador donde tienes sesión en YouTube Music.",+ "yt_auth_how": "Cómo obtener las cookies",+ "yt_auth_step1": "Abre music.youtube.com en Chrome/Edge/Firefox donde tienes sesión.",+ "yt_auth_step2": "F12 → Aplicación/Almacenamiento → Cookies → music.youtube.com",+ "yt_auth_step3": "Copia el valor de __Secure-3PAPISID y pégalo en el primer campo.",+ "yt_auth_step4": "En la pestaña Red, pulsa cualquier petición, copia toda la cabecera Cookie: y pégala en el segundo campo.",+ "yt_cookie_full": "Cabecera completa de cookie",+ "yt_cookie_hint": "Pega toda la cabecera Cookie: de cualquier petición a music.youtube.com.",+ "yt_save_auth": "Guardar credenciales",+ "yt_auth_saved": "Credenciales guardadas",+ "yt_disconnect": "Desconectar",+ "yt_disconnect_confirm": "¿Borrar credenciales guardadas?",+ "yt_disconnected": "Desconectado",+ "yt_visitor_ok": "Datos de visitante actualizados",+ "yt_sync_title": "Sincronizar mi biblioteca",+ "yt_sync_desc": "Importa Me gusta + todas tus playlists en una sola tanda. Corre en segundo plano. Las pistas aparecen en Biblioteca / Álbumes / Artistas junto a las locales.",+ "yt_sync_now": "Sincronizar ahora",+ "yt_syncing": "Sincronizando…",+ "yt_sync_starting": "Iniciando…",+ "yt_sync_liked": "Trayendo Me gusta…",+ "yt_sync_playlists": "Trayendo {{total}} playlists…",+ "yt_sync_done": "Sincronizado: {{playlists}} playlists, {{tracks}} pistas",+ "yt_ext_import": "Importar desde extensión",+ "yt_ext_hint": "Toma las cookies de YouTube directamente desde la extensión del navegador de omniget. Sin F12, sin copiar y pegar.",+ "yt_ext_imported": "{{count}} cookies importadas desde la extensión",+ "yt_ext_empty": "Aún no hay cookies capturadas. Abre music.youtube.com en tu navegador con la extensión de omniget activa y vuelve a intentarlo.",+ "yt_ext_no_sapisid": "Cookies encontradas pero sin __Secure-3PAPISID. Inicia sesión en YouTube Music y reintenta.",+ "yt_ext_no_file": "El archivo de cookies no existe. La extensión nunca envió nada — revisa: (1) host de omniget en ejecución, (2) extensión activa, (3) Native Messaging registrado. Esperado en: {{path}}",+ "yt_ext_no_youtube": "El archivo existe ({{age}}) pero solo tiene cookies de: {{domains}}. Abre music.youtube.com en el navegador, espera 3s y reintenta.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies importadas ({{age}}) pero ninguna es __Secure-3PAPISID. Inicia sesión en YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies importadas ({{age}})",+ "yt_or_manual": "o manualmente",+ "quality_title": "Calidad de audio",+ "quality_short": "Calidad",+ "quality_intro": "Elige cómo se codifica la música descargada. Puedes cambiarlo cuando quieras — solo afecta a descargas nuevas.",+ "quality_current": "Actual: {{label}}",+ "quality_saved": "Calidad ajustada a {{label}}",+ "quality_group_recommended": "Recomendado",+ "quality_group_compact": "Ahorrar espacio",+ "quality_group_high": "Alta calidad",+ "quality_group_lossless": "Sin pérdida (audiófilo)",+ "quality_hint_mp3_128": "Archivos más pequeños · ~3 MB por canción · calidad básica",+ "quality_hint_mp3_192": "Equilibrado · ~5 MB por canción · suena en cualquier lado",+ "quality_hint_mp3_320": "MP3 al máximo · ~7 MB por canción · compatibilidad total",+ "quality_hint_aac_192": "Suena genial, archivos pequeños, suena en todos lados · ~5 MB por canción",+ "quality_hint_aac_256": "Lossy premium · ~6 MB por canción · calidad transparente",+ "quality_hint_opus_160": "El más eficiente · ~4 MB por canción · puede no sonar en equipos viejos",+ "quality_hint_flac": "Sin pérdida · mantiene el tamaño del archivo origen",+ "quality_hint_flac_cd": "Calidad CD sin pérdida · ~30 MB por canción",+ "quality_hint_flac_hires": "Calidad estudio · 24-bit/96 kHz · ~80 MB por canción",+ "quality_hint_wav": "PCM sin comprimir · ~50 MB por canción · los archivos más grandes",+ "sources_title": "Fuentes de música",+ "sources_short": "Fuentes",+ "sources_subtitle": "Dónde buscar pistas",+ "sources_intro": "Cuando le pides a omniget que busque una canción por nombre, intenta estas fuentes en orden. Reordena con las flechas.",+ "source_status_connected": "Conectado",+ "source_status_not_connected": "No conectado",+ "source_status_unavailable": "Próximamente",+ "source_connect": "Conectar",+ "source_inactive_header": "Fuera de rotación",+ "source_reset_default": "Restaurar orden por defecto",+ "source_move_up": "Subir",+ "source_move_down": "Bajar",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Conectado",+ "qobuz_state_disconnected": "No conectado",+ "qobuz_intro": "Conecta tu cuenta Qobuz para obtener pistas sin pérdida (FLAC hasta 24-bit/192 kHz). Requiere suscripción activa de Qobuz.",+ "qobuz_email_label": "Correo de Qobuz",+ "qobuz_password_label": "Contraseña",+ "qobuz_pwd_show": "Mostrar contraseña",+ "qobuz_pwd_hide": "Ocultar contraseña",+ "qobuz_privacy": "Se guarda localmente solo en tu dispositivo. Nunca se envía a servidores de omniget.",+ "qobuz_connect": "Conectar",+ "qobuz_connecting": "Conectando…",+ "qobuz_connected": "Conectado a Qobuz",+ "qobuz_disconnected": "Desconectado de Qobuz",+ "qobuz_disconnect": "Desconectar",+ "qobuz_disconnect_confirm": "¿Eliminar credenciales guardadas de Qobuz?",+ "qobuz_signed_in_as": "Sesión iniciada como",+ "qobuz_connected_hint": "Qobuz ya está en el pool de fuentes. Usa el panel de Fuentes para controlar su prioridad.",+ "qobuz_test_again": "Probar conexión",+ "qobuz_testing": "Probando…",+ "qobuz_test_ok": "El login de Qobuz funciona",+ "qobuz_test_failed": "Prueba de Qobuz fallida: {{error}}",+ "nav_aria": "Navegación de música",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "La música sigue sonando mientras navegas entre Cursos, Notas y otras secciones.",+ "nav_search": "Buscar",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "Aún no tienes playlists",+ "playlists_empty_body": "Crea una playlist para agrupar tus pistas favoritas y escucharlas en orden.",+ "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.",+ "playlist_deleted": "Playlist eliminada",+ "click_to_rename": "Clic para renombrar",+ "delete_playlist": "Eliminar playlist",+ "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",+ "queue_empty": "La cola está vacía.",+ "queue_toggle": "Alternar cola",+ "search_hint": "Escribe el título de una pista, artista o álbum.",+ "exit": "Salir",+ "featured_album": "Álbum destacado",+ "by": "De",+ "start_listening": "Empezar a escuchar",+ "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.",+ "sort_added": "Añadido",+ "sort_name": "Nombre A→Z",+ "sort_year": "Año",+ "sort_track_count": "Más pistas",+ "manage_folders": "Gestionar carpetas",+ "roots_title": "Carpetas de música",+ "roots_hint": "Carpetas que escaneamos en busca de audio. Desactiva una para ignorarla sin borrar nada. Quitar aquí no elimina archivos.",+ "roots_empty": "Aún no has añadido ninguna carpeta de música.",+ "root_missing": "falta",+ "root_remove": "Quitar",+ "root_removed": "Carpeta quitada: {{path}}",+ "nav_albums": "Álbumes",+ "nav_artists": "Artistas",+ "nav_playlists": "Playlists"+ },+ "library": {+ "title": "Biblioteca",+ "subtitle": "Tus cursos, vídeos y PDFs en un solo sitio.",+ "empty_browse_title": "Tu biblioteca aún está vacía",+ "empty_browse_description": "Apunta a tus carpetas de cursos o importa vídeos de Telegram. Nada se copia ni se mueve.",+ "empty_add_folder_title": "Añadir carpeta de vídeos",+ "empty_add_folder_desc": "Apunta a donde ya están tus cursos. Sin copia, sin movimiento.",+ "empty_add_folder_cta": "Elegir carpeta",+ "empty_telegram_title": "Importar desde Telegram",+ "empty_telegram_desc": "Descarga vídeos directamente desde canales en los que estés.",+ "empty_telegram_cta": "Conectar",+ "pinned_strip_aria": "Carpetas fijadas",+ "pin_action": "Fijar",+ "pin_action_active": "Fijada",+ "pin_action_title": "Fijar esta carpeta",+ "unpin_action": "Quitar de fijadas",+ "unpin_action_title": "Quitar de fijadas",+ "pin_failed": "Fijar falló: {{msg}}",+ "unpin_failed": "Quitar de fijadas falló: {{msg}}",+ "siblings_aria": "Carpetas hermanas",+ "siblings_empty": "Sin carpetas hermanas",+ "view_mode_aria": "Modo de vista",+ "view_mode_grid": "Cuadrícula",+ "view_mode_list": "Lista",+ "back_toast": "Volver a {{folder}}",+ "address_bar_placeholder": "Pega o escribe una ruta…",+ "address_bar_open": "Editar ruta",+ "new_folder": "Nueva carpeta",+ "new_folder_placeholder": "Nombre de la carpeta",+ "ctx_open": "Abrir",+ "ctx_rename": "Renombrar",+ "ctx_delete": "Eliminar (Papelera)",+ "ctx_show_in_explorer": "Mostrar en el gestor de archivos",+ "delete_confirm_title": "¿Mover a la Papelera?",+ "delete_confirm_msg_folder": "La carpeta \"{{name}}\" y todo lo que contiene se moverá a la Papelera del sistema.",+ "delete_confirm_msg_file": "\"{{name}}\" se moverá a la Papelera del sistema.",+ "delete_confirm_btn": "Mover a la Papelera",+ "delete_toast_done": "\"{{name}}\" movido a la Papelera",+ "last_watched_label": "Visto por última vez",+ "roots_button_hint": "Carpetas que la biblioteca escanea en busca de cursos y vídeos",+ "empty_with_roots_one": "Detectada 1 carpeta configurada pero aún no hay cursos indexados.",+ "empty_with_roots_other": "Detectadas {{count}} carpetas configuradas pero aún no hay cursos indexados.",+ "empty_with_roots_cta": "Volver a escanear",+ "pin_added_toast": "\"{{name}}\" fijada",+ "pin_removed_toast": "Quitada de fijadas",+ "root_missing_label": "falta",+ "root_missing_hint": "¿Disco desconectado? ¿Carpeta eliminada? Reconecta o quita aquí.",+ "mode_telegram_disconnected_suffix": "(no conectado)",+ "browse_sort_label": "Orden",+ "browse_sort_name_asc": "Nombre A→Z",+ "browse_sort_name_desc": "Nombre Z→A",+ "browse_sort_size_desc": "Tamaño",+ "browse_sort_recent": "Modificado",+ "selection_count_one": "1 seleccionado",+ "selection_count_other": "{{count}} seleccionados",+ "selection_clear": "Limpiar selección",+ "selection_delete": "Eliminar seleccionados",+ "selection_delete_confirm_title": "¿Eliminar {{count}} elemento(s)?",+ "selection_delete_confirm_msg": "Los elementos se moverán a la Papelera del sistema. Puedes restaurarlos desde allí si cambias de idea.",+ "selection_delete_done": "{{count}} elemento(s) movido(s) a la Papelera",+ "selection_delete_partial": "{{ok}} OK · {{fail}} fallidos",+ "open_in_new_tab": "Abrir en pestaña nueva",+ "tab_close": "Cerrar pestaña",+ "tab_new": "Nueva pestaña",+ "empty": "Aún no hay cursos indexados. Ejecuta un escaneo desde Configuración.",+ "error_loading_notes": "No se pudieron cargar tus notas. Recarga o contacta con soporte si persiste.",+ "health_title": "Salud de la biblioteca",+ "health_ok": "Todo donde debe estar.",+ "health_banner_one": "1 archivo necesita atención",+ "health_banner_many": "{{count}} archivos necesitan atención",+ "health_banner_part_empty": "{{count}} vacíos",+ "health_banner_part_missing": "{{count}} ausentes",+ "health_banner_part_orphan": "{{count}} huérfanos",+ "health_banner_cta": "Revisar",+ "health_banner_aria": "Abrir informe de salud de la biblioteca",+ "health_zero_byte": "Vídeos vacíos",+ "health_zero_byte_hint": "No terminaron de descargar. Vuelve a descargar el curso, o elimina el archivo vacío y vuelve a escanear.",+ "health_missing": "Vídeos ausentes",+ "health_missing_hint": "Registrados en la base de datos pero no en el disco — normalmente movidos o eliminados fuera de la app. La limpieza solo quita entradas cuando la carpeta del curso sigue ahí, así que los discos desmontados están a salvo.",+ "health_orphan_desc": "description.html huérfanas",+ "health_orphan_hint": "Carpetas con texto de descripción pero sin vídeo. A menudo una \"vista previa gratuita\" no descargada, o una clase de solo texto que el escáner saltó.",+ "health_checking": "Comprobando…",+ "health_recheck": "Volver a comprobar",+ "cleanup_busy": "Limpiando…",+ "filters": "Filtros",+ "filter_status": "Estado",+ "filter_playlist": "Playlist",+ "filter_tags": "Etiquetas",+ "all_courses": "Todos los cursos",+ "manage_playlists": "Gestionar playlists →",+ "clear_filters": "limpiar",+ "tags_hint": "Clic → incluir · Shift+Clic → excluir",+ "loading_more": "Cargando más cursos…",+ "status_all": "Todos",+ "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",+ "cleanup_confirm_title": "Limpiar entradas con vídeo ausente",+ "cleanup_confirm_message": "Eliminará {{count}} clase(s) cuyo archivo de vídeo ya no existe en disco. Los cursos cuya carpeta entera no existe se conservan (probablemente un disco desmontado). Los cursos que se queden sin clases también se eliminan. No se borra nada del disco.",+ "cleanup_done": "{{lessons}} clase(s) eliminadas · {{courses}} curso(s) eliminado(s) · {{kept}} conservados (disco desmontado)",+ "cleanup_force_btn": "Forzar (incluir cursos con carpetas ausentes)",+ "cleanup_force_hint": "Usa esto si renombraste/borraste carpetas a propósito. AVISO: los discos externos desconectados también se borrarán.",+ "cleanup_force_confirm_title": "Forzar limpieza total",+ "cleanup_force_confirm_message": "Eliminará TODAS las {{count}} entradas, INCLUIDOS los cursos cuya carpeta entera ya no existe en disco. Úsalo solo si estás seguro de que las carpetas fueron renombradas/eliminadas y no es un disco externo desconectado. Los cursos huérfanos también se eliminan. No se borra nada del disco.",+ "notes_pages_section": "Páginas",+ "notes_page_not_found": "no encontrada",+ "notes_no_references": "Aún no hay referencias.",+ "notes_no_pages": "Aún no hay páginas.",+ "notes_new_page": "Nueva página",+ "notes_rename_page": "Renombrar página",+ "notes_filter_pages": "Filtrar páginas…",+ "notes_page_name_placeholder": "Nombre de la página",+ "notes_journal_history": "Historial del diario",+ "notes_history_recent": "Historial reciente",+ "notes_no_open_page": "No hay página abierta. Crea o selecciona una en la barra lateral.",+ "search_placeholder": "Buscar cursos...",+ "sort_label": "Orden",+ "sort_title": "Nombre",+ "sort_recent": "Añadido recientemente",+ "sort_progress": "Progreso",+ "sort_name": "Nombre",+ "sort_added": "Añadido",+ "sort_last_watched": "Visto por última vez",+ "favorites_only": "Solo favoritos",+ "lessons_count": "{{count}} clase(s)",+ "progress_pct": "{{pct}}% completado",+ "favorite_on": "Quitar favorito",+ "favorite_off": "Favorito",+ "platform": "Plataforma",+ "status": "Estado",+ "status_new": "Nuevo",+ "status_empty": "Vacío",+ "has_gaps": "Tiene huecos",+ "has_notes": "Tiene notas",+ "has_cards": "Tiene tarjetas",+ "no_platforms": "Pon una plataforma a un curso para filtrar aquí.",+ "more_filters": "Más filtros",+ "tag": "Etiqueta",+ "tags": "Etiquetas",+ "tag_add": "Añadir etiqueta…",+ "reset": "Restablecer",+ "view_grid": "Cuadrícula",+ "view_list": "Lista",+ "lessons": "clases",+ "notes": "notas",+ "gap": "hueco",+ "recent": "Reciente",+ "history": "Historial",+ "history_empty": "Sin actividad reciente",+ "mode_browse": "Carpetas y archivos",+ "mode_courses": "Mis cursos",+ "browse_empty": "Carpeta vacía.",+ "videos": "vídeos",+ "roots": "Raíces de la biblioteca",+ "loose_lessons": "Clases sueltas",+ "kind_all": "Todo",+ "kind_course": "Cursos",+ "kind_media": "Vídeos",+ "kind_media_badge": "Vídeo",+ "favorite": "Favorito",+ "resume": "Reanudar",+ "roots_button": "Dónde buscar",+ "roots_add_btn": "Añadir carpeta",+ "roots_remove": "Quitar",+ "roots_remove_tooltip": "Quitar esta carpeta",+ "roots_default": "Por defecto",+ "roots_empty": "No hay carpetas configuradas.",+ "roots_hint": "Activa o desactiva carpetas para incluirlas en los escaneos.",+ "rescan_now": "Volver a escanear",+ "rescanning": "Escaneando...",+ "rescan_ok": "{{courses}} curso(s), {{lessons}} clase(s)",+ "browse_empty_roots": "Añade una carpeta para empezar.",+ "browse_breadcrumb_root": "Raíces",+ "videos_count": "{{count}} vídeo(s)",+ "video": "Vídeo",+ "folder": "Carpeta",+ "back": "Atrás",+ "watch_title": "Viendo",+ "watch_back": "Volver a la biblioteca",+ "watch_not_found": "No hay vídeo seleccionado.",+ "watch_file_missing": "Archivo no encontrado.",+ "mode_telegram": "Importar desde Telegram",+ "telegram": {+ "plugin_missing_title": "Plugin de Telegram no encontrado",+ "plugin_missing_body": "Instala el plugin de Telegram desde el marketplace para acceder a tus chats aquí.",+ "connected_as": "Conectado como {{phone}}",+ "coming_soon": "Navegador de Telegram próximamente — la autenticación ya está lista.",+ "auth": {+ "title": "Conectar Telegram",+ "subtitle": "Inicia sesión para navegar tus chats y multimedia.",+ "tab_qr": "Código QR",+ "tab_phone": "Teléfono",+ "qr_hint_scan": "Abre Telegram › Ajustes › Dispositivos › Vincular dispositivo de escritorio",+ "qr_expires_in": "Se actualiza en {{sec}}s",+ "phone_input": "Número de teléfono (E.164)",+ "code_input": "Código",+ "send_code": "Enviar código",+ "code_resend": "Reenviar",+ "password_title": "Verificación en dos pasos",+ "password_hint": "Pista: {{hint}}"+ },+ "chats_title": "Tus chats de Telegram",+ "chats_subtitle": "Abre un chat para navegar su multimedia.",+ "chats_empty": "Aún no hay chats.",+ "chat_empty": "No hay multimedia de este tipo en este chat.",+ "chat_type_private": "Privado",+ "chat_type_group": "Grupo",+ "chat_type_channel": "Canal",+ "crumb_root": "Telegram",+ "filter_all": "Todo",+ "filter_photo": "Fotos",+ "filter_video": "Vídeos",+ "filter_document": "Documentos",+ "filter_audio": "Audio",+ "filter_gif": "GIFs",+ "filter_round_video": "Vídeos circulares",+ "filter_round_voice": "Voz",+ "filter_photo_video": "Fotos+Vídeos",+ "filter_chat_photos": "Fotos del chat",+ "downloads_view_panel": "Abrir panel de descargas",+ "album_title": "Álbum",+ "album_prev": "Anterior",+ "album_next": "Siguiente",+ "album_indicator": "Álbum ({{n}} elementos)",+ "folder_autoscan": "Escanear chats en busca de carpetas tipo drive",+ "folder_autoscan_desc": "Encuentra canales marcados con [og] en el título o [telegram-drive-folder] en la descripción.",+ "folder_autoscan_running": "Escaneando chats…",+ "folder_autoscan_result": "{{n}} canales detectados como carpetas de drive",+ "folder_autoscan_none": "No se detectaron carpetas de drive.",+ "keymap_title": "Atajos de teclado",+ "keymap_search": "Enfocar búsqueda",+ "keymap_clear": "Limpiar / descartar",+ "keymap_nav": "Navegar",+ "keymap_open": "Abrir",+ "keymap_open_player": "Abrir en reproductor",+ "keymap_select_all": "Seleccionar todo lo visible",+ "keymap_delete": "Eliminar selección",+ "keymap_play_pause": "Reproducir / pausar",+ "keymap_help": "Mostrar esta ayuda",+ "keymap_next_prev": "Siguiente / anterior",+ "keymap_fullscreen": "Pantalla completa",+ "keymap_close": "Cerrar reproductor",+ "keymap_volume": "Subir / bajar volumen",+ "keymap_mute": "Silenciar / activar sonido",+ "keymap_seek": "Atrás / adelante 10s",+ "output_dir_pick": "Elegir carpeta…",+ "output_dir_reset": "Usar por defecto",+ "crumb_clear_search": "Limpiar búsqueda",+ "delete_done_local": "{{n}} elemento(s) eliminado(s) localmente",+ "delete_done_revoke": "{{n}} elemento(s) eliminado(s) para todos (irreversible)",+ "smart_yt-courses": "Cursos de YouTube",+ "load_more": "Cargar más",+ "downloads": {+ "title": "Descargas",+ "empty": "Aún no hay descargas.",+ "download": "Descargar",+ "no_output_dir": "Carpeta de salida no configurada.",+ "clear_finished": "Limpiar terminadas",+ "toggle": "Alternar panel de descargas",+ "status_queued": "En cola",+ "status_downloading": "Descargando",+ "status_done": "Listo",+ "status_error": "Error",+ "status_cancelled": "Cancelado",+ "open_in_reader": "Abrir en lector"+ },+ "search_chats": "Filtrar chats por título…",+ "search_chats_empty": "Ningún chat coincide.",+ "search_media": "Filtrar por nombre de archivo…",+ "search_media_empty": "Ningún elemento coincide con el filtro.",+ "search_server": "Buscar en el servidor",+ "clear_server_search": "Limpiar búsqueda del servidor",+ "favorites": "Favoritos",+ "favorites_empty": "Aún no hay favoritos. Marca elementos dentro de un chat para fijarlos aquí.",+ "favorites_count_suffix": "elementos",+ "bookmark": "Añadir a favoritos",+ "unbookmark": "Quitar de favoritos",+ "selected": "{{n}} seleccionados",+ "select_all_visible": "Seleccionar todo",+ "bulk_download": "Descargar",+ "bulk_bookmark": "Favorito",+ "clear_selection": "Limpiar selección",+ "smart_pdfs": "PDFs",+ "smart_videos": "Vídeos",+ "smart_audios": "Audios",+ "smart_images": "Imágenes",+ "smart_untagged": "Sin etiqueta",+ "smart_empty": "Ningún favorito coincide con esta carpeta. Marca elementos para llenarla.",+ "tag_add": "Añadir etiqueta",+ "tag_add_short": "etiqueta",+ "tag_remove": "Quitar etiqueta",+ "tag_placeholder": "etiqueta…",+ "status_connected": "Conectado",+ "status_checking": "Comprobando…",+ "status_disconnected": "Desconectado",+ "settings_title": "Configuración de Telegram",+ "settings_output_dir": "Carpeta de descargas",+ "settings_prune_cache": "Limpiar caché de miniaturas",+ "settings_logout": "Desconectar",+ "saved_messages": "Mensajes guardados",+ "saved_messages_hint": "Tu archivo personal",+ "verified": "Verificado",+ "muted": "Silenciado",+ "pinned": "Fijado",+ "ctx_open": "Abrir chat",+ "ctx_mark_read": "Marcar como leído",+ "ctx_pin": "Fijar arriba",+ "ctx_unpin": "Desfijar",+ "ctx_mute": "Silenciar notificaciones",+ "ctx_unmute": "Reactivar notificaciones",+ "tabs_label": "Filtros de chat",+ "tab_all": "Todos",+ "tab_unread": "Sin leer",+ "tab_private": "Personales",+ "tab_group": "Grupos",+ "tab_channel": "Canales",+ "tab_folder": "Drives",+ "online": "En línea",+ "player_pip": "Picture-in-picture",+ "flood_wait_hint": "Telegram nos pidió esperar antes de más solicitudes",+ "list_trimmed_hint": "Mostrando los primeros {{shown}} de {{total}} chats. Usa la búsqueda para encontrar uno concreto.",+ "auto_resume_downloads": "Reanudar descargas automáticamente",+ "auto_resume_downloads_hint": "Al iniciar la app, reanuda las descargas que estaban en curso.",+ "thumb_cache_limit": "Límite de caché de miniaturas",+ "bulk_confirm_threshold": "Confirmar acciones masivas por encima de",+ "bulk_confirm_threshold_unit": "elementos",+ "player_not_playable": "Este tipo de multimedia no se puede reproducir en línea.",+ "player_kbd_hint": "Esc cerrar · J/↓ siguiente · K/↑ anterior",+ "filter_webpage": "Enlaces",+ "webpage_open_external": "Abrir en navegador",+ "allow_remote_delete": "Permitir eliminación remota",+ "allow_remote_delete_hint": "Permite al botón de eliminar masivo borrar mensajes de Telegram. Desactivado por defecto.",+ "bulk_delete": "Eliminar",+ "bulk_copy": "Copiar",+ "bulk_move": "Mover",+ "move_needs_delete_perm": "Activa \"Permitir eliminación remota\" en configuración para mover (mover = copiar + eliminar original).",+ "delete_confirm_title": "¿Eliminar mensajes remotos?",+ "delete_confirm_body": "{{n}} mensajes se eliminarán de Telegram. No se puede deshacer.",+ "move_to": "Mover a…",+ "copy_to": "Copiar a…",+ "upload_files": "Subir",+ "upload_hint": "Envía archivos a este chat",+ "kbd_help": "Abrir esta ayuda",+ "kbd_esc": "Cerrar reproductor / limpiar selección",+ "kbd_click": "Abrir reproductor",+ "kbd_ctrl_click": "Alternar selección",+ "kbd_shift_click": "Selección de rango",+ "kbd_ctrl_a": "Seleccionar todo lo visible",+ "kbd_next": "Siguiente elemento (reproductor)",+ "kbd_prev": "Elemento anterior (reproductor)",+ "kbd_space": "Reproducir/pausar control nativo",+ "title_edit_hint": "Doble clic para editar el pie",+ "player_book_hint": "PDF/EPUB — descarga para leer en el lector integrado.",+ "load_more_chats": "Cargar más chats",+ "refreshing_in_background": "Actualizando lista…",+ "create_folder": "Nueva carpeta",+ "create_folder_title": "Crear nueva carpeta",+ "create_folder_hint": "Crea un canal privado de Telegram marcado como carpeta de curso.",+ "create_folder_placeholder": "Nombre de la carpeta (ej. Álgebra Lineal)",+ "chats_empty_hint": "Crea tu primera carpeta para empezar a hospedar cursos en Telegram.",+ "folder_rename": "Renombrar",+ "folder_delete": "Eliminar",+ "folder_rename_title": "Renombrar carpeta",+ "folder_delete_title": "¿Eliminar carpeta?",+ "folder_delete_body": "El canal de Telegram se eliminará permanentemente junto con todos los archivos subidos. No se puede deshacer.",+ "drop_to_upload_title": "Suelta para subir",+ "drop_to_upload_hint": "Los archivos se enviarán a {{chat}}",+ "watched": "Visto",+ "resume_at": "Reanudar en {{time}}",+ "player_speed": "Velocidad de reproducción"+ },+ "home_continue_title": "Continúa donde lo dejaste",+ "home_continue_eyebrow": "Reciente",+ "home_continue_empty": "Aún no hay cursos en curso. Empieza una clase para verla aquí.",+ "home_continue_next": "Siguiente: {{title}}",+ "home_continue_current": "En: {{title}}",+ "home_news_title": "Con novedades",+ "home_news_eyebrow": "Clases nuevas",+ "home_news_count_one": "{{count}} clase nueva",+ "home_news_count_other": "{{count}} clases nuevas",+ "home_recently_title": "Añadidos recientemente",+ "home_recently_eyebrow": "Nuevo",+ "home_platform_eyebrow": "Plataforma",+ "home_subject_eyebrow": "Materia",+ "home_empty_title": "Tu biblioteca está vacía",+ "home_empty_desc": "Añade una carpeta con cursos para empezar.",+ "home_empty_cta": "Añadir carpeta de cursos",+ "home_load_error": "Error al cargar la biblioteca: {{error}}",+ "view_home": "Inicio",+ "view_catalog": "Catálogo",+ "platform_generic": "Otras plataformas"+ },+ "player": {+ "title": "Reproductor",+ "placeholder": "Selecciona una clase de la biblioteca para empezar."+ },+ "course": {+ "back": "Volver a la biblioteca",+ "continue": "Seguir viendo",+ "start": "Empezar curso",+ "lessons_total": "{{count}} clases",+ "progress": "{{completed}} de {{total}} completadas ({{pct}}%)",+ "no_lessons": "No hay clases para este curso.",+ "loose_lessons": "Clases",+ "mark_complete": "Marcar como completada",+ "mark_incomplete": "Marcar como no vista",+ "search_placeholder": "Buscar clases...",+ "resume_label": "Reanudar desde aquí"+ },+ "attachments": {+ "title": "Adjuntos ({{count}})"+ },+ "lesson": {+ "progress_label": "Progreso de la clase",+ "back_to_course": "Volver al curso",+ "next": "Siguiente clase",+ "prev": "Clase anterior",+ "mark_complete": "Marcar como completada",+ "completed": "Completada",+ "loading": "Cargando vídeo...",+ "no_video": "Archivo de vídeo no encontrado en el disco.",+ "autoplay_title": "A continuación",+ "autoplay_in": "Reproduciendo a continuación en {{seconds}}s...",+ "autoplay_play_now": "Reproducir ahora",+ "autoplay_cancel": "Cancelar reproducción automática",+ "autoplay_last": "Terminaste la última clase.",+ "speed": "Velocidad",+ "theater_on": "Salir del modo cine",+ "theater_off": "Modo cine",+ "theater_hint": "Oculta barra lateral y paneles (T)",+ "description_title": "Descripción",+ "clip": "Cortar últimos 60s",+ "clip_loading": "Cortando…",+ "clip_done": "Clip guardado",+ "clip_failed": "Falló el clip",+ "clip_no_video": "Vídeo aún no cargado",+ "clip_aria": "Guardar últimos 60 segundos como clip"+ },+ "notes": {+ "title": "Notas",+ "placeholder": "Las notas que tomes estudiando aparecerán aquí.",+ "empty": "Aún no hay notas. Toma una mientras ves una clase.",+ "add_placeholder": "Escribe una nota... (markdown soportado)",+ "quick_placeholder": "Nota rápida en {{time}} — pulsa Enter para guardar",+ "add": "Añadir nota",+ "save": "Guardar",+ "cancel": "Cancelar",+ "edit": "Editar",+ "delete": "Eliminar",+ "confirm_delete": "¿Eliminar esta nota?",+ "jump_to": "Saltar a {{time}}",+ "panel_title": "Notas de esta clase",+ "at_time": "en {{time}}",+ "no_timestamp": "Sin marca de tiempo",+ "quick_note_hint": "Pulsa N mientras ves para capturar una nota en el momento actual.",+ "recent": "Notas recientes",+ "loading": "Cargando notas...",+ "course_col": "Curso",+ "lesson_col": "Clase",+ "body_col": "Nota",+ "search_placeholder": "Busca en tus notas...",+ "tab_recent": "Recientes",+ "tab_daily": "Revisión diaria",+ "cal_today": "Hoy",+ "cal_selected": "{{date}} — {{count}} nota(s)",+ "empty_day": "No hay notas este día.",+ "new": "Nueva nota",+ "preview": "Vista previa",+ "convert": "Convertir a tarjeta",+ "export_md": "Exportar .md",+ "export_pdf": "Exportar PDF",+ "to_flashcard": "→ Tarjeta",+ "pick_deck": "Mazo...",+ "empty_front": "(sin título)",+ "editor_placeholder": "Escribe en Markdown + LaTeX (usa $...$ y $$...$$)",+ "select_or_new": "Selecciona una nota o crea una nueva.",+ "filter": {+ "all": "Todas",+ "notes": "Notas",+ "bookmarks": "Marcadores"+ },+ "read_mode": "Lectura",+ "edit_mode": "Edición",+ "open_menu": "Más opciones",+ "menu_label": "Opciones de la nota",+ "delete_title": "¿Eliminar nota?",+ "delete_body": "La nota se eliminará permanentemente. No se puede deshacer.",+ "toggle_preview": "Vista previa",+ "export_menu": "Exportar…",+ "untitled": "(sin título)",+ "scope_global": "Sin vínculo",+ "scope_course": "Curso",+ "scope_module": "Módulo",+ "scope_lesson": "Clase"+ },+ "achievements": {+ "title": "Logros",+ "subtitle": "XP local — sin clasificación, sin comparación social",+ "loading": "Cargando…",+ "level_tag": "Nivel",+ "to_next": "al nivel {{next}}",+ "level_progress": "{{pct}}% al siguiente nivel",+ "history_title": "Historial reciente de XP",+ "history_empty": "Aún no hay nada aquí. Estudia algo para empezar a ganar XP.",+ "reset_title": "Restablecer gamificación",+ "reset_desc": "Borra XP, logros y contadores. No afecta al progreso de los cursos.",+ "reset_confirm_title": "Restablecer gamificación",+ "reset_confirm_message": "Se borrarán XP, nivel, logros y contadores. Esta acción no se puede deshacer.",+ "minutes_ago": "hace {{n}} min",+ "hours_ago": "hace {{n}} h",+ "day_ago": "hace {{n}} día",+ "days_ago": "hace {{n}} días",+ "filter_all": "Todo",+ "filter_xp": "XP",+ "filter_lessons": "Clases",+ "filter_focus": "Concentración",+ "filter_streak": "Racha",+ "tier_bronze": "bronce",+ "tier_silver": "plata",+ "tier_gold": "oro",+ "unlocked_prefix": "desbloqueado",+ "reset_done": "Restablecido",+ "reset_confirm_label": "Restablecer",+ "filter_aria": "Filtros de categoría",+ "tree_link": "Árbol",+ "charts_link": "Gráficos",+ "label_xp_100": "Primeros 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Mil XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "Primera clase",+ "label_lessons_10": "10 clases",+ "label_lessons_50": "50 clases",+ "label_lessons_100": "100 clases",+ "label_focus_60": "1h concentrado",+ "label_focus_600": "10h concentrado",+ "label_focus_6000": "100h concentrado",+ "label_streak_3": "3 días seguidos",+ "label_streak_7": "Racha de 1 semana",+ "label_streak_30": "Racha de 30 días",+ "label_streak_100": "Racha de 100 días",+ "desc_xp_100": "Gana 100 XP estudiando",+ "desc_xp_500": "Gana 500 XP",+ "desc_xp_1000": "Hito de 1000 XP",+ "desc_xp_5000": "Cinco mil XP acumulados",+ "desc_xp_10000": "Diez mil XP — estás dedicado",+ "desc_lessons_1": "Completa tu primera clase",+ "desc_lessons_10": "Completa 10 clases",+ "desc_lessons_50": "Medio centenar de clases",+ "desc_lessons_100": "Cien clases completadas",+ "desc_focus_60": "60 minutos de concentración acumulados",+ "desc_focus_600": "600 minutos de concentración acumulados",+ "desc_focus_6000": "6000 minutos de concentración — disciplina rara",+ "desc_streak_3": "Mantén una racha de 3 días",+ "desc_streak_7": "7 días seguidos estudiando",+ "desc_streak_30": "Un mes entero de constancia",+ "desc_streak_100": "Hábito de acero"+ },+ "focus": {+ "title": "Concentración",+ "placeholder": "Aquí viven las sesiones de Pomodoro y deep work.",+ "intent_label": "¿Para qué es esta sesión?",+ "intent_prefix": "Estudiando",+ "intent_placeholder": "tesis, examen de cálculo, certificación de ventas...",+ "intent_hint": "Aparece en tu Discord si tienes el RPC activo. Déjalo vacío si prefieres.",+ "intent_for": "estudiando",+ "rpc_default": "Sesión de concentración",+ "preset_pomodoro": "Pomodoro",+ "preset_short_break": "Pausa corta",+ "preset_long_break": "Pausa larga",+ "preset_deep": "Deep work",+ "preset_long": "Deep work (50/10)",+ "preset_custom": "Cronómetro",+ "start": "Empezar",+ "stop": "Detener",+ "running": "Activa",+ "no_session": "No hay sesión activa. Elige un preset para empezar.",+ "elapsed": "{{minutes}} min",+ "today": "Hoy",+ "this_week": "Esta semana",+ "history": "Historial de sesiones",+ "history_empty": "Aún no hay sesiones. Empieza una para construir la racha.",+ "no_history": "Aún no hay sesiones.",+ "minutes_unit": "min",+ "min": "min",+ "break_toast": "¡Hora de descanso! Toma 5.",+ "done_toast": "Sesión terminada: {{minutes}} min",+ "pomodoro": "Pomodoro (min)",+ "short_break": "Pausa corta (min)",+ "long_break": "Pausa larga (min)",+ "cycles": "Ciclos hasta pausa larga",+ "deep": "Deep work",+ "notify_end": "Notificar al terminar",+ "notify_sound": "Alerta sonora",+ "auto_pause_player": "Pausar reproductor automáticamente",+ "daily_target": "Meta diaria (min)",+ "weekly_target": "Días por semana",+ "today_progress": "Hoy",+ "interrupt": "Interrumpir",+ "start_now": "Empezar ahora",+ "interrupted": "interrumpida",+ "cycles_today": "Ciclos hoy: {{count}}",+ "settings_title": "Preferencias del temporizador",+ "min_per_week": " min/sem",+ "auto_start": {+ "breaks": "Iniciar pausas automáticamente",+ "focus": "Iniciar concentración automáticamente",+ "cycles_until_long_break": "Ciclos hasta pausa larga"+ },+ "notifications": {+ "title": "Notificaciones",+ "enable": "Notificación del navegador",+ "sound": "Sonido al terminar el ciclo",+ "sound_volume": "Volumen",+ "permission_denied": "Permiso denegado en el navegador",+ "unsupported": "Notificaciones no soportadas en este navegador"+ },+ "cycle_end": {+ "focus_done": "Concentración hecha",+ "break_done": "Pausa hecha",+ "long_break_done": "Pausa larga hecha",+ "body": "Vuelve cuando estés listo"+ },+ "hero_title": "Empezar",+ "hero_subtitle": "Elige una materia y un preset para empezar.",+ "page_subtitle": "Sesiones enfocadas con Pomodoro o deep work",+ "stats_subjects": "Materias activas",+ "stats_today": "Hoy",+ "stats_week": "Esta semana",+ "today_session": "{{n}} sesión · {{min}} min",+ "today_sessions": "{{n}} sesiones · {{min}} min",+ "config_cycles": "Ciclos y pausas",+ "config_sounds": "Sonidos y notificaciones",+ "config_autostart": "Inicio automático",+ "stop_title": "¿Interrumpir sesión?",+ "stop_body": "La sesión se marcará como interrumpida y no contará para las estadísticas.",+ "stop_confirm": "Interrumpir",+ "active_preset_label": "Concentrado",+ "session_ended": "Sesión terminada",+ "settings_saving": "guardando…",+ "settings_saved": "guardado ✓",+ "acc_cycles_title": "Ciclos",+ "acc_cycles_summary": "{{focus}}min concentración · {{break}}min pausa · {{cycles}}× hasta pausa larga",+ "acc_cycles_focus": "Concentración (min)",+ "acc_cycles_short": "Pausa corta (min)",+ "acc_cycles_long": "Pausa larga (min)",+ "acc_cycles_count": "Ciclos antes de pausa larga",+ "acc_breaks_title": "Pausas e inicio automático",+ "acc_breaks_auto_yes": "pausa automática",+ "acc_breaks_auto_no": "manual",+ "acc_breaks_focus_yes": "reanudar automáticamente",+ "acc_breaks_focus_no": "manual",+ "acc_breaks_player_yes": "pausa el reproductor",+ "acc_breaks_player_no": "ignora el reproductor",+ "acc_breaks_check_breaks": "Iniciar pausas automáticamente tras la concentración",+ "acc_breaks_check_focus": "Reanudar concentración tras la pausa",+ "acc_breaks_check_player": "Pausar vídeo durante la pausa de concentración",+ "acc_sounds_title": "Sonidos y notificación",+ "acc_sounds_notify_on": "notificación activa",+ "acc_sounds_notify_off": "silencio",+ "acc_sounds_sound_on": "sonido {{n}}%",+ "acc_sounds_sound_off": "sin sonido",+ "acc_sounds_check_notify": "Notificar al terminar el ciclo",+ "acc_sounds_check_sound": "Reproducir sonido al terminar",+ "acc_sounds_volume": "Volumen ({{n}}%)",+ "unlimited_aria": "ilimitado"+ },+ "subjects": {+ "title": "Materias",+ "new": "Nueva",+ "name": "Nombre",+ "color": "Color",+ "weekly_minutes": "Meta semanal (min)",+ "edit": "Editar materia",+ "empty": "Aún no hay materias",+ "archive": "Archivar",+ "unarchive": "Desarchivar",+ "archived_label": "Archivada",+ "active": "Materia activa",+ "none": "Ninguna",+ "confirm_delete": "¿Eliminar esta materia?",+ "progress_today": "Materias hoy",+ "field": {+ "name": "Nombre",+ "color": "Color",+ "weekly_target": "Meta semanal (min)",+ "daily_targets": "Metas diarias (min)",+ "daily_sum": "Suma semanal",+ "distribute_equally": "Distribuir equitativamente"+ },+ "day": {+ "mon": "Lun",+ "tue": "Mar",+ "wed": "Mié",+ "thu": "Jue",+ "fri": "Vie",+ "sat": "Sáb",+ "sun": "Dom"+ },+ "progress": {+ "status_not_started": "Sin empezar",+ "status_in_progress": "En curso",+ "status_reached": "Meta alcanzada",+ "status_exceeded": "Meta superada"+ }+ },+ "progress": {+ "title": "Progreso",+ "placeholder": "Racha, actividad diaria e hitos.",+ "no_data": "Aún no hay progreso — mira una clase para empezar.",+ "streak": "Racha",+ "streak_unit": "día",+ "streak_unit_plural": "días",+ "today_lessons": "Clases hoy",+ "today_minutes": "Minutos de concentración hoy",+ "lessons_done": "Clases completadas",+ "courses_done": "Cursos completados",+ "courses_completed": "Cursos completados",+ "lessons_completed_total": "Total de clases completadas",+ "heatmap_title": "Últimos 90 días",+ "heatmap_empty": "Aún sin actividad. Completa una clase para encenderlo.",+ "goal_daily": "Meta diaria",+ "goal_lessons": "{{current}} / {{target}} clases",+ "goal_minutes": "{{current}} / {{target}} minutos de concentración",+ "goal_hit": "¡Meta cumplida!",+ "goal_missed": "Sigue adelante",+ "legend_less": "Menos",+ "legend_more": "Más",+ "read_title": "Lectura",+ "read_streak": "Racha de lectura",+ "read_today": "Hoy",+ "read_week": "Esta semana",+ "read_total": "Siempre",+ "read_active": "Leyendo ahora",+ "minutes_per_week": "Minutos por semana",+ "cards_per_day": "Clases por día",+ "time_by_subject": "Tiempo por materia",+ "retention": "Pool de tarjetas",+ "new": "Nuevas",+ "learning": "Aprendiendo",+ "review": "Repaso",+ "no_subjects": "Sin materias definidas",+ "page_subtitle": "Tu ritmo de estudio y metas",+ "period_today": "Hoy",+ "period_7d": "7d",+ "period_30d": "30d",+ "period_90d": "90d",+ "hero_today": "Hoy",+ "daily_goal_pct": "de la meta diaria",+ "stat_lessons": "Clases",+ "stat_cards": "Tarjetas",+ "stat_minutes": "Concentración (min)",+ "stat_streak": "Racha",+ "heatmap_hint": "Últimos {{n}} días · clic para notas diarias",+ "chart_explore_library": "Explorar biblioteca",+ "chart_review_weak": "Repasar tarjetas débiles",+ "chart_adjust_goals": "Ajustar metas",+ "streak_best": "mejor: {{n}}",+ "chart_time_per_course": "Tiempo por curso",+ "chart_time_per_course_empty": "Sin tiempo registrado en este periodo.",+ "chart_time_period_days": "últimos {{n}} días",+ "chart_activity_by_hour": "Actividad por hora",+ "chart_activity_hint": "suma de concentración · 24h",+ "chart_activity_empty": "Sin actividad en los últimos {{n}} días.",+ "chart_subject": "Por materia",+ "chart_subject_unit": "minutos de concentración",+ "chart_subject_empty": "Crea materias y asigna sesiones para ver el desglose.",+ "chart_subject_unassigned": "Sin materia",+ "retention_title": "Retención (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "La retención real vendrá de la consulta cruzada con la base de Anki. Por ahora, abre",+ "retention_link": "Stats de Anki →",+ "retention_stub_after": "para ver retención, distribución de intervalos e historial de repasos.",+ "recent_achievements": "Logros recientes",+ "view_all": "Ver todos →",+ "time_today": "hoy",+ "time_yesterday": "ayer",+ "time_days_ago": "hace {{n}} días",+ "time_months_ago": "hace {{n}} meses",+ "time_years_ago": "hace {{n}} años",+ "ach_label_xp_100": "100 XP acumulados",+ "ach_label_xp_500": "500 XP acumulados",+ "ach_label_xp_1000": "1.000 XP acumulados",+ "ach_label_xp_5000": "5.000 XP acumulados",+ "ach_label_xp_10000": "10.000 XP acumulados",+ "ach_label_lessons_1": "Primera clase",+ "ach_label_lessons_10": "10 clases completadas",+ "ach_label_lessons_50": "50 clases completadas",+ "ach_label_lessons_100": "100 clases completadas",+ "ach_label_focus_60": "1 hora de concentración",+ "ach_label_focus_600": "10 horas de concentración",+ "ach_label_focus_6000": "100 horas de concentración",+ "ach_label_streak_3": "Racha de 3 días",+ "ach_label_streak_7": "Racha de 1 semana",+ "ach_label_streak_30": "Racha de 30 días",+ "ach_label_streak_100": "Racha de 100 días"+ },+ "settings": {+ "title": "Configuración",+ "placeholder": "Preferencias del plugin y reescaneo de biblioteca.",+ "library_section": "Biblioteca",+ "rescan": "Volver a escanear biblioteca",+ "rescan_desc": "Recorre la carpeta de descargas otra vez y refresca cursos, módulos y clases.",+ "rescan_running": "Escaneando...",+ "rescan_done": "Encontrados {{courses}} curso(s) y {{lessons}} clase(s) en {{ms}} ms.",+ "rescan_error": "Reescaneo fallido: {{message}}",+ "stats_section": "Estadísticas de la biblioteca",+ "stat_courses": "Cursos",+ "stat_lessons": "Clases",+ "stat_completed": "Completadas",+ "stat_notes": "Notas",+ "stat_decks": "Mazos",+ "stat_flashcards": "Tarjetas",+ "stat_focus": "Sesiones de concentración",+ "backup_section": "Copia y restauración",+ "export": "Exportar datos",+ "export_desc": "Descarga un snapshot JSON con cursos, notas, tarjetas, progreso e historial de concentración.",+ "export_button": "Exportar JSON",+ "exporting": "Exportando...",+ "import": "Importar datos",+ "import_desc": "Restaura desde un archivo JSON exportado previamente. Las filas existentes con IDs coincidentes se sobrescriben.",+ "import_button": "Elegir archivo...",+ "importing": "Importando...",+ "import_replace": "Borrar datos actuales antes de importar (destructivo)",+ "import_done": "Importados {{courses}} cursos, {{lessons}} clases, {{notes}} notas, {{flashcards}} tarjetas."+ },+ "read": {+ "title": "Leer",+ "subtitle": "Biblioteca de libros, PDFs y documentos.",+ "empty": "Aún no hay libros. Añade carpetas y pulsa Reescanear.",+ "scan_now": "Volver a escanear",+ "scanning": "Escaneando...",+ "scan_done": "{{added}} añadidos · {{updated}} actualizados · {{found}} encontrados",+ "open": "Abrir",+ "back_to_library": "Volver a la biblioteca",+ "no_book": "Ningún libro seleccionado.",+ "loading_page": "Cargando página...",+ "file_missing": "Archivo no encontrado en el disco.",+ "format_pdf": "PDF",+ "format_epub": "EPUB",+ "format_djvu": "DJVU",+ "format_mobi": "MOBI",+ "format_azw3": "AZW3",+ "format_fb2": "FB2",+ "format_cbz": "CBZ",+ "format_cbr": "CBR",+ "format_txt": "TXT",+ "format_rtf": "RTF",+ "format_html": "HTML",+ "format_unknown": "Archivo",+ "filter_all": "Todos",+ "filter_reading": "Leyendo",+ "filter_finished": "Terminados",+ "filter_favorites": "Favoritos",+ "search_placeholder": "Buscar libros...",+ "sort_last_opened": "Último abierto",+ "sort_added": "Añadido",+ "sort_title": "Título",+ "sort_author": "Autor",+ "page_count": "{{count}} páginas",+ "progress_pct": "{{pct}}% leído",+ "not_started": "Sin empezar",+ "in_progress": "Leyendo",+ "finished": "Terminado",+ "collections_title": "Colecciones",+ "collection_new": "Nueva colección",+ "collection_name": "Nombre de la colección",+ "no_collections": "Sin colecciones.",+ "soon": "Lector en construcción. Por ahora, los archivos se abren en la app por defecto.",+ "open_external": "Abrir en la app por defecto",+ "loading_book": "Cargando libro…",+ "txt_load_more": "Cargar más",+ "page_of": "{{current}} de {{total}}",+ "prev_page": "Página anterior",+ "next_page": "Página siguiente",+ "go_to": "Ir a la página",+ "zoom_in": "Acercar",+ "zoom_out": "Alejar",+ "fit_width": "Ajustar al ancho",+ "manga_rtl": "Modo manga (derecha a izquierda)",+ "outline_title": "Índice",+ "outline_empty": "No hay índice para este libro.",+ "pdfium_missing": "pdfium.dll no encontrado. Ejecuta scripts/fetch-pdfium.ps1.",+ "unsupported_format": "El formato {{format}} aún no es compatible con el lector interno. Usa 'Abrir en la app por defecto'.",+ "search_title": "Buscar",+ "search_input": "Buscar en el libro…",+ "search_no_hits": "Sin resultados.",+ "search_hits_count": "{{n}} resultado(s)",+ "bookmarks_title": "Marcadores",+ "bookmarks_empty": "Sin marcadores. Pulsa B para marcar la página actual.",+ "add_bookmark": "Marcar página",+ "remove_bookmark": "Quitar marcador",+ "panel_outline": "Índice",+ "panel_bookmarks": "Marcadores",+ "panel_search": "Buscar",+ "highlight_save": "Resaltar",+ "highlight_delete": "Quitar resaltado",+ "color_yellow": "Amarillo",+ "color_green": "Verde",+ "color_pink": "Rosa",+ "color_blue": "Azul",+ "panel_highlights": "Resaltados",+ "highlights_empty": "Selecciona texto en la página y elige un color.",+ "menu": "Más opciones",+ "export_md": "Exportar anotaciones (.md)",+ "export_md_v2": "Exportar markdown enriquecido (v2)",+ "export_json": "Exportar anotaciones (.json)",+ "export_pdf_burn_in": "Exportar PDF anotado",+ "export_pdf_ok": "PDF anotado · {{highlights}} resaltados · {{bookmarks}} marcadores · {{notes}} notas · {{inks}} trazos",+ "export_pdf_only": "Solo formato PDF",+ "export_ok": "Exportado a {{path}}",+ "export_failed": "Exportación fallida: {{err}}",+ "import_json": "Importar anotaciones (.json)",+ "import_ok": "{{imported}} importados · {{skipped}} duplicados · {{errors}} errores",+ "import_failed": "Importación fallida: {{err}}",+ "bulk_export_btn": "Exportar todo (.md)",+ "bulk_export_hint": "Exporta markdown v2 de cada libro en una carpeta",+ "bulk_export_done": "{{written}} libros exportados · {{skipped}} omitidos · {{kb}} KB",+ "ink_toggle": "Modo lápiz",+ "ink_undo": "Deshacer último trazo",+ "ink_color_black": "Negro",+ "ink_color_red": "Rojo",+ "ink_color_blue": "Azul",+ "chapter": "Capítulo",+ "chapter_of": "Cap {{current}} de {{total}}",+ "prev_chapter": "Capítulo anterior",+ "next_chapter": "Capítulo siguiente",+ "no_outline": "No hay índice disponible.",+ "theme_label": "Tema",+ "theme_default": "Por defecto",+ "theme_day": "E-ink día",+ "theme_night": "E-ink noche",+ "theme_sepia": "Sepia",+ "effects_label": "Efectos",+ "effect_paper": "Filtro papel",+ "effect_cursor": "Línea de lectura",+ "reading_style": "Estilo de lectura",+ "focus_mode": "Modo concentración (F)",+ "format_all": "Todos los formatos",+ "roots_btn": "Carpetas ({{count}})",+ "roots_title": "Carpetas de libros",+ "roots_hint": "Elige dónde buscar libros. El escáner recorre estas carpetas recursivamente y ignora dotfolders.",+ "roots_empty": "Aún no hay carpetas. Añade una abajo.",+ "roots_add_btn": "Añadir carpeta",+ "roots_rescan": "Escanear ahora",+ "empty_no_roots_title": "Sin carpetas configuradas",+ "empty_no_roots_hint": "Añade una carpeta con libros para empezar a escanear. Cursos y libros usan raíces separadas.",+ "empty_no_roots_cta": "Elegir carpetas",+ "folder_label": "Carpeta",+ "folder_all": "Todas las carpetas",+ "scan_removed": "eliminados {{n}} ausentes",+ "view_scroll": "Scroll continuo",+ "view_paged": "Vista por páginas",+ "tags_edit": "Editar etiquetas",+ "enrich_metadata": "Enriquecer metadatos",+ "enrich_search_btn": "Buscar en OpenLibrary",+ "enrich_search_hint": "Busca por título + autor actuales. Toma la mejor coincidencia de OpenLibrary.",+ "enrich_apply_hint": "Elige qué campos sobrescribir:",+ "enrich_apply_btn": "Aplicar",+ "tags_empty": "Aún sin etiquetas.",+ "tags_input_placeholder": "escribe etiqueta y pulsa Enter",+ "tags_add_btn": "Añadir etiqueta",+ "collections_btn": "Colecciones ({{count}})",+ "collections_hint": "Agrupa libros entre carpetas. Abre una colección desde el desplegable para añadir o quitar libros.",+ "collections_empty": "Aún sin colecciones.",+ "collection_create": "Nueva colección",+ "collection_create_prompt": "¿Nombre de la colección?",+ "collection_rename": "Renombrar",+ "collection_delete_confirm": "¿Eliminar la colección \"{{name}}\"? Los libros se quedan; solo se quita la agrupación.",+ "collection_label": "Colección",+ "collection_all": "Todos los libros",+ "collection_add_book": "Añadir a la colección activa",+ "collection_remove_book": "Quitar de la colección activa",+ "typo_title": "Tipografía",+ "typo_font": "Fuente",+ "typo_size": "Tamaño",+ "typo_line": "Interlineado",+ "typo_justify": "Alineación",+ "typo_justify_left": "Izquierda",+ "typo_justify_full": "Justificada",+ "typo_reset": "Restablecer valores por defecto",+ "manga_nav_btn": "Manga",+ "manga_title": "Manga",+ "manga_subtitle": "Manga, manhwa, manhua, webtoons y otros cómics seriados de estilo japonés.",+ "series_empty_title": "Sin manga detectado",+ "series_empty_hint": "Añade carpetas con archivos CBZ/CBR o carpetas de capítulos desempaquetadas, luego escanea.",+ "series_scan_done": "{{found}} títulos · {{added}} nuevos",+ "series_count_chapters": "{{current}}/{{total}} cap",+ "series_chapters": "Capítulos",+ "series_start_reading": "Empezar a leer",+ "series_continue_reading": "Seguir leyendo",+ "back_to_manga": "Volver a manga",+ "back_to_manga_detail": "Volver al listado de capítulos",+ "clean_orphans_btn": "Limpiar huérfanos",+ "clean_orphans_hint": "Elimina filas de la BD que apuntan a archivos inexistentes o que se volvieron capítulos de serie.",+ "orphans_cleared": "Eliminados {{missing}} ausentes · {{member}} ahora en manga · {{junk}} basura (LICENSE/README/diminutos)",+ "manga_clean_orphans_btn": "Limpiar carpetas ausentes",+ "manga_clean_orphans_hint": "Elimina series locales cuya carpeta ya no existe.",+ "manga_orphans_cleared": "Eliminadas {{n}} carpeta(s) ausentes",+ "manga_clear_remote_btn": "Limpiar tracked",+ "manga_clear_remote_confirm": "¿Eliminar todo el manga rastreado desde MangaDex? Las series locales se quedan.",+ "manga_remote_cleared": "Eliminado {{n}} manga rastreado",+ "manga_clear_all_btn": "Limpiar TODO",+ "manga_clear_all_confirm": "¿Eliminar todo el manga de la biblioteca, incluido el local? No se puede deshacer.",+ "manga_all_cleared": "Eliminados {{n}} manga",+ "mark_read": "Marcar como leído",+ "mark_unread": "Marcar como no leído",+ "spread_toggle": "Doble página",+ "entry_empty": "No se encontraron páginas en este capítulo.",+ "kind_comic": "Cómic",+ "kind_manga": "Manga",+ "kind_manhwa": "Manhwa",+ "kind_manhua": "Manhua",+ "kind_webcomic": "Webcómic",+ "kind_light_novel": "Light Novel",+ "discover_nav": "Descubrir",+ "discover_title": "Descubrir series",+ "discover_subtitle": "Busca en MangaDex y añade a tu biblioteca.",+ "discover_source": "Fuente",+ "discover_search_placeholder": "Buscar por título…",+ "discover_empty": "Sin resultados. Prueba con otra búsqueda.",+ "track_btn": "+ Seguir",+ "tracking": "Añadiendo…",+ "tracked_ok": "Siguiendo. {{count}} capítulos nuevos ({{total}} en total)",+ "discover_source_all": "★ Todas las fuentes activas (global)",+ "discover_global_summary": "{{alive}}/{{total}} fuentes respondieron · {{items}} elementos totales",+ "discover_global_failed": "{{n}} fuente(s) fallaron",+ "book_discover_nav": "Libros online",+ "book_discover_title": "Descubrir libros",+ "book_discover_subtitle": "Busca en bibliotecas de dominio público y descarga ebooks gratis directo a tu biblioteca.",+ "book_search_placeholder": "Buscar por título, autor…",+ "book_download_btn": "+ Descargar",+ "book_downloading": "Descargando…",+ "book_download_ok": "Descargado ({{format}}). Añadido a la biblioteca.",+ "book_already_in_library": "Ya está en tu biblioteca.",+ "book_results_count": "{{n}} resultados",+ "book_page_label": "Página {{current}}",+ "book_metadata_only": "Solo metadatos",+ "book_borrow_only": "Prestar en archive.org",+ "book_borrow_only_hint": "Este libro está bajo Préstamo Digital Controlado. La descarga gratuita no está disponible; el préstamo requiere cuenta en archive.org.",+ "annas_manage_link": "Fuentes avanzadas (Alt Library)",+ "annas_title": "Alt Library — fuente avanzada",+ "annas_subtitle": "Metabúsqueda de shadow libraries. Desactivada por defecto. Depende de la jurisdicción.",+ "annas_warning_title": "Aviso legal y de seguridad",+ "annas_warning_body1": "Alt Library agrega mirrors de LibGen, Z-Library, Sci-Hub y otras shadow libraries. El material allí puede tener copyright.",+ "annas_warning_body2": "La legalidad de acceder, descargar o distribuir ese contenido varía por país. En algunas jurisdicciones (Palau, por ejemplo) el uso personal está permitido; en otras no. Eres el único responsable de comprobar tus leyes.",+ "annas_warning_body3": "omniget-study solo proporciona un cliente HTTP programable. Activar esta fuente descarga contenido que TÚ elegiste pedir. Mantén tu propio cumplimiento.",+ "annas_status": "Estado de la fuente",+ "annas_acked_at": "Aviso aceptado el {{date}}",+ "annas_not_acked": "Aviso aún no aceptado — activarla requiere confirmación.",+ "annas_on": "Activa",+ "annas_enable_btn": "Activar fuente",+ "annas_disable_btn": "Desactivar",+ "annas_enabled": "Alt Library activada.",+ "annas_disabled": "Alt Library desactivada.",+ "annas_log_title": "Registro de mirrors intentados",+ "annas_log_hint": "Registro local opcional de qué dominios/mirrors usó cada descarga. Guardado solo localmente.",+ "annas_domains_title": "Dominios de mirror",+ "annas_domains_hint": "Uno por línea. Se prueban en orden en cada solicitud. Restablece para volver a los valores por defecto.",+ "annas_domains_save": "Guardar dominios",+ "annas_domains_revert": "Revertir",+ "annas_domains_saved": "Dominios guardados.",+ "annas_reset_title": "Restablecer todo",+ "annas_reset_hint": "Borra la aceptación, desactiva la fuente, restaura los dominios por defecto. NO elimina archivos ya descargados.",+ "annas_reset_btn": "Restablecer configuración de Alt Library",+ "annas_reset_confirm": "¿Restablecer toda la configuración de Alt Library? La fuente se desactivará y requerirá nueva aceptación.",+ "annas_reset_done": "Configuración restablecida.",+ "annas_warning_modal_title": "Antes de activar Alt Library",+ "annas_warning_modal_line1": "Esta fuente rastrea shadow libraries.",+ "annas_warning_modal_line2": "La mayoría del contenido allí tiene copyright. Descargarlo puede ser legal en tu jurisdicción, zona gris, o totalmente ilegal — verifica con tus leyes locales.",+ "annas_warning_modal_line3": "omniget-study no hospeda contenido. Todas las descargas pasan por mirrors que TÚ configuras y TÚ activas.",+ "annas_warning_modal_line4": "Marca la casilla de abajo si entiendes y aceptas la responsabilidad personal de tu uso.",+ "annas_warning_ack_label": "Entiendo. Asumo plena responsabilidad de mi uso en mi jurisdicción.",+ "annas_warning_cancel": "Cancelar",+ "annas_warning_confirm": "Activar Alt Library",+ "search_notes_btn": "Buscar en notas",+ "downloads_btn": "Descargas",+ "enrich_no_results": "Sin resultados. Intenta editar primero el título del libro.",+ "enrich_done": "✓ Metadatos actualizados",+ "enrich_field_title": "Título:",+ "enrich_field_author": "Autor:",+ "enrich_field_publisher": "Editorial:",+ "enrich_field_cover": "Portada (descargar)"+ },+ "bulk": {+ "select_all": "Seleccionar todo",+ "selected": "seleccionado",+ "mark_completed": "Marcar completadas",+ "mark_uncompleted": "Desmarcar",+ "mark_module_completed": "Módulo completado",+ "mark_module_uncompleted": "Desmarcar módulo",+ "mark_course_completed": "Curso completado",+ "mark_course_uncompleted": "Desmarcar curso",+ "marked_completed": "{{count}} clase(s) marcadas como completadas",+ "marked_uncompleted": "{{count}} clase(s) desmarcadas",+ "undo": "Deshacer"+ },+ "goals": {+ "title": "Metas",+ "weekly": "Semanal",+ "monthly": "Mensual",+ "metric": {+ "minutes": "Minutos",+ "lessons": "Clases",+ "cards": "Tarjetas"+ }+ },+ "export": {+ "all_md": "Exportar .md",+ "all_hint": "Exporta todas las notas filtradas como .md",+ "ok": "{{count}} nota(s) exportadas"+ },+ "bookmark": {+ "add": "Marcar",+ "add_hint": "Añadir marcador en el momento actual (B)",+ "seek_hint": "Saltar a este punto",+ "default_label": "{{time}}"+ },+ "stats": {+ "chart": {+ "time_per_course": "Tiempo por curso (últimos 30 días)",+ "empty": "Sin datos para el periodo"+ }+ },+ "empty": {+ "library_hint": "Descarga un curso vía plugin de Cursos o configura la carpeta en Configuración.",+ "notes_hint": "Crea una nota durante la reproducción o con Ctrl+Shift+N.",+ "subjects_hint": "Añade materias para distribuir las metas semanales."+ },+ "maintenance": {+ "title": "{{feature}} en mantenimiento",+ "lead": "Estamos puliendo esta sección. El resto de Estudio funciona normalmente — esta parte vuelve pronto.",+ "eta_label": "ETA",+ "back_to_study": "Volver a Estudio",+ "open_library": "Abrir Biblioteca",+ "feature_notes": "Notas",+ "feature_anki": "Anki",+ "detail_notes": "El editor por bloques (Tiptap), backlinks, vista de grafo y plantillas aún se están puliendo.",+ "detail_anki": "El cliente interno de Anki (FSRS-5, sync, .apkg) está siendo finalizado."+ },+ "library_health": {+ "removed_toast": "Eliminado: {{name}}",+ "remove_failed_toast": "Error al eliminar: {{msg}}",+ "no_issues_toast": "La biblioteca no tiene problemas",+ "issues_found_toast": "{{count}} problema(s) encontrados",+ "verify_failed_toast": "Error al verificar la biblioteca: {{msg}}"+ }+ }+}diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex b792777a..83f7aa6a 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "Afficher {{count}} de plus","open_folder": "Afficher dans le dossier",+ "open_in_study": "Watch in Study","stop": "Arrêter","confirm_remove": "Supprimer ce téléchargement ?","stats_line": "{{count}} téléchargements · {{size}} enregistrés",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "Couper les segments sponsorisés, intros et outros des vidéos YouTube (données communautaires ; peut manquer ou trop couper)","split_by_chapters": "Diviser la vidéo par chapitres","split_by_chapters_desc": "Lorsque la vidéo contient des marqueurs de chapitre, enregistrer chaque chapitre dans un fichier séparé",+ "presets": "Préréglages rapides",+ "presets_desc": "Configuration en un clic. Appuyez sur une carte pour appliquer.",+ "preset_fast": "Rapide",+ "preset_fast_desc": "480p · sans métadonnées · sans sous-titres",+ "preset_quality": "Qualité",+ "preset_quality_desc": "Meilleure vidéo · métadonnées · vignette",+ "preset_compact": "Compact",+ "preset_compact_desc": "720p · métadonnées · sans vignette",+ "preset_music_only": "Musique uniquement",+ "preset_music_only_desc": "Audio · tags ID3 · pochette","hotkey_enabled": "Raccourci global","hotkey_enabled_desc": "Télécharger l'URL du presse-papiers avec un raccourci clavier","hotkey_binding": "Raccourci clavier","hotkey_record": "Enregistrer","hotkey_type": "Saisir","hotkey_press": "Appuyez sur les touches...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "Copier le fichier dans le presse-papiers après téléchargement par raccourci","copy_to_clipboard_on_hotkey_desc": "Copier automatiquement le fichier téléchargé dans le presse-papiers pour un collage facile","filename_template": "Modèle de nom de fichier",@@ -326,7 +343,25 @@"cat_downloads": "Telechargements","cat_network": "Reseau","cat_advanced": "Avance",- "search_placeholder": "Rechercher des paramètres..."+ "search_placeholder": "Rechercher des paramètres...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Affiche votre activite sur votre profil Discord. Le chronometre continue d'une activite a l'autre.",+ "enable": "Afficher l'activite sur Discord",+ "privacy_note": "Affiche ce que vous ecoutez, regardez ou lisez. Vos telechargements restent prives.",+ "test": "Tester la connexion",+ "test_desc": "Envoie une activite test pour verifier que Discord est lance.",+ "test_button": "Envoyer test",+ "test_ok": "Connecte a Discord",+ "test_fail": "Impossible de se connecter a Discord. Verifiez qu'il est lance.",+ "saved": "Sauvegarde",+ "save": "Enregistrer",+ "advanced": "Avance",+ "app_id": "ID d'application",+ "app_id_hint": "ID de l'application Discord. Ne changez que si vous savez ce que vous faites.",+ "large_image": "Cle de la grande image",+ "large_image_hint": "Nom de l'asset televerse vers votre application Discord."+ }},"omnibox": {"placeholder": "Collez une URL ou recherchez",@@ -554,6 +589,11 @@"hotkey_desc": "Copiez une URL, appuyez sur le raccourci et OmniGet telecharge instantanement — meme minimise.","hotkey_on": "Active","hotkey_off": "Desactive",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Affichez sur votre profil Discord que vous utilisez OmniGet — y compris ce que vous ecoutez, regardez ou lisez.",+ "rpc_on": "Active",+ "rpc_off": "Desactive",+ "rpc_privacy_note": "Affiche ce que vous ecoutez, regardez ou lisez. Vos telechargements restent prives.","theme_label": "Theme","theme_system": "Systeme","theme_light": "Clair",@@ -602,7 +642,9 @@"download_timeout": "Le téléchargement a expiré. Vérifiez votre connexion Internet.","size_mismatch": "La taille du fichier téléchargé ne correspond pas. Réessayez.","disk_full": "Erreur d'écriture — votre disque est peut-être plein.",- "path_too_long": "Le chemin du dossier est trop long ({{current}}/{{limit}} caractères). Choisissez un dossier plus court."+ "path_too_long": "Le chemin du dossier est trop long ({{current}}/{{limit}} caractères). Choisissez un dossier plus court.",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "Journal d'activité",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "Étude","subtitle": "Transformez vos cours téléchargés en une boucle de pratique délibérée.","library": "Bibliothèque",+ "music": "Music","focus": "Concentration","progress": "Progression","achievements": "Succès",@@ -839,8 +892,437 @@"action_vacuum_label": "Compacter la base (vacuum)","action_vacuum_hint": "Maintenance SQLite"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "Indigo",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "Bibliothèque",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "Mode d'affichage",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "Aucun cours indexé. Lancez une analyse depuis les paramètres.","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "En cours","status_not_started": "Non commencés","status_completed": "Terminés",- "view_mode_aria": "Mode d'affichage","status_aria": "Statut","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "Continuer là où vous en étiez",+ "home_continue_eyebrow": "Récent",+ "home_continue_empty": "Aucun cours en cours. Commencez une leçon pour la voir ici.",+ "home_continue_next": "Prochaine : {{title}}",+ "home_continue_current": "En cours : {{title}}",+ "home_news_title": "Avec nouveautés",+ "home_news_eyebrow": "Nouvelles leçons",+ "home_news_count_one": "{{count}} nouvelle leçon",+ "home_news_count_other": "{{count}} nouvelles leçons",+ "home_recently_title": "Récemment ajoutés",+ "home_recently_eyebrow": "Nouveau",+ "home_platform_eyebrow": "Plateforme",+ "home_subject_eyebrow": "Matière",+ "home_empty_title": "Votre bibliothèque est vide",+ "home_empty_desc": "Ajoutez un dossier de cours pour commencer.",+ "home_empty_cta": "Ajouter un dossier de cours",+ "home_load_error": "Échec du chargement de la bibliothèque : {{error}}",+ "view_home": "Accueil",+ "view_catalog": "Catalogue",+ "platform_generic": "Autres plateformes"},"player": {"title": "Lecteur",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "Clip 60 dernières s",+ "clip_loading": "Création du clip…",+ "clip_done": "Clip enregistré",+ "clip_failed": "Clip échoué",+ "clip_no_video": "Vidéo pas encore chargée",+ "clip_aria": "Enregistrer les 60 dernières secondes comme clip"},"notes": {"title": "Notes",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "bronze",+ "tier_silver": "argent",+ "tier_gold": "or",+ "unlocked_prefix": "débloqué",+ "reset_done": "Reset effectué",+ "reset_confirm_label": "Reset",+ "filter_aria": "Filtres de catégorie",+ "tree_link": "Arbre",+ "charts_link": "Graphiques",+ "label_xp_100": "Premiers 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Mille XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "Première leçon",+ "label_lessons_10": "10 leçons",+ "label_lessons_50": "50 leçons",+ "label_lessons_100": "100 leçons",+ "label_focus_60": "1h de focus",+ "label_focus_600": "10h de focus",+ "label_focus_6000": "100h de focus",+ "label_streak_3": "3 jours d'affilée",+ "label_streak_7": "Série d'1 semaine",+ "label_streak_30": "Série de 30 jours",+ "label_streak_100": "Série de 100 jours",+ "desc_xp_100": "Cumulez 100 XP en étudiant",+ "desc_xp_500": "Cumulez 500 XP",+ "desc_xp_1000": "Cap des 1000 XP",+ "desc_xp_5000": "Cinq mille XP cumulés",+ "desc_xp_10000": "Dix mille XP — vous êtes dévoué",+ "desc_lessons_1": "Terminez votre première leçon",+ "desc_lessons_10": "Terminez 10 leçons",+ "desc_lessons_50": "Demi-siècle de leçons",+ "desc_lessons_100": "Cent leçons terminées",+ "desc_focus_60": "60 minutes de focus cumulées",+ "desc_focus_600": "600 minutes de focus cumulées",+ "desc_focus_6000": "6000 minutes de focus — discipline rare",+ "desc_streak_3": "Maintenez la série pendant 3 jours",+ "desc_streak_7": "7 jours consécutifs d'étude",+ "desc_streak_30": "Un mois entier de constance",+ "desc_streak_100": "Habitude d'acier"},"focus": {"title": "Concentration","placeholder": "Sessions Pomodoro et de travail en profondeur.",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "Pomodoro (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "enregistrement…",+ "settings_saved": "enregistré ✓",+ "acc_cycles_title": "Cycles",+ "acc_cycles_summary": "{{focus}}min focus · {{break}}min pause · {{cycles}}× jusqu'à la pause longue",+ "acc_cycles_focus": "Focus (min)",+ "acc_cycles_short": "Pause courte (min)",+ "acc_cycles_long": "Pause longue (min)",+ "acc_cycles_count": "Cycles avant la pause longue",+ "acc_breaks_title": "Pauses & démarrage auto",+ "acc_breaks_auto_yes": "auto-pause",+ "acc_breaks_auto_no": "manuel",+ "acc_breaks_focus_yes": "auto-reprise",+ "acc_breaks_focus_no": "manuel",+ "acc_breaks_player_yes": "met le lecteur en pause",+ "acc_breaks_player_no": "ignore le lecteur",+ "acc_breaks_check_breaks": "Démarrer les pauses automatiquement après le focus",+ "acc_breaks_check_focus": "Reprendre le focus automatiquement après la pause",+ "acc_breaks_check_player": "Mettre la vidéo en pause pendant la pause focus",+ "acc_sounds_title": "Sons & notification",+ "acc_sounds_notify_on": "notification ON",+ "acc_sounds_notify_off": "silencieux",+ "acc_sounds_sound_on": "son {{n}}%",+ "acc_sounds_sound_off": "sans son",+ "acc_sounds_check_notify": "Notification à la fin du cycle",+ "acc_sounds_check_sound": "Jouer un son à la fin",+ "acc_sounds_volume": "Volume ({{n}}%)",+ "unlimited_aria": "libre"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "Temps par cours",+ "chart_time_per_course_empty": "Aucun temps enregistré sur cette période.",+ "chart_time_period_days": "{{n}} derniers jours",+ "chart_activity_by_hour": "Activité par heure",+ "chart_activity_hint": "somme des focus · 24h",+ "chart_activity_empty": "Aucune activité sur les {{n}} derniers jours.",+ "chart_subject": "Par matière",+ "chart_subject_unit": "minutes de focus",+ "chart_subject_empty": "Créez des matières et assignez des sessions pour voir la répartition.",+ "chart_subject_unassigned": "Sans matière",+ "retention_title": "Rétention (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "La rétention réelle viendra de la requête cross-DB d'Anki. Pour l'instant, ouvrez",+ "retention_link": "Statistiques Anki →",+ "retention_stub_after": "pour voir la rétention, la distribution des intervalles et l'historique des révisions.",+ "recent_achievements": "Réussites récentes",+ "view_all": "Voir tout →",+ "time_today": "aujourd'hui",+ "time_yesterday": "hier",+ "time_days_ago": "il y a {{n}} jours",+ "time_months_ago": "il y a {{n}} mois",+ "time_years_ago": "il y a {{n}} ans",+ "ach_label_xp_100": "100 XP cumulés",+ "ach_label_xp_500": "500 XP cumulés",+ "ach_label_xp_1000": "1 000 XP cumulés",+ "ach_label_xp_5000": "5 000 XP cumulés",+ "ach_label_xp_10000": "10 000 XP cumulés",+ "ach_label_lessons_1": "Première leçon",+ "ach_label_lessons_10": "10 leçons terminées",+ "ach_label_lessons_50": "50 leçons terminées",+ "ach_label_lessons_100": "100 leçons terminées",+ "ach_label_focus_60": "1 heure de focus",+ "ach_label_focus_600": "10 heures de focus",+ "ach_label_focus_6000": "100 heures de focus",+ "ach_label_streak_3": "Série de 3 jours",+ "ach_label_streak_7": "Série d'1 semaine",+ "ach_label_streak_30": "Série de 30 jours",+ "ach_label_streak_100": "Série de 100 jours"},"settings": {"title": "Paramètres",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "Rechercher les notes",+ "downloads_btn": "Téléchargements",+ "enrich_no_results": "Aucun résultat. Essayez d'abord de modifier le titre du livre.",+ "enrich_done": "✓ Métadonnées mises à jour",+ "enrich_field_title": "Titre :",+ "enrich_field_author": "Auteur :",+ "enrich_field_publisher": "Éditeur :",+ "enrich_field_cover": "Couverture (téléchargement)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/index.ts b/src/lib/i18n/index.tsindex 652a21de..d7672e33 100644--- a/src/lib/i18n/index.ts+++ b/src/lib/i18n/index.ts@@ -44,6 +44,11 @@ const config = {key: "",loader: async () => (await import("./fr.json")).default,},+ {+ locale: "es",+ key: "",+ loader: async () => (await import("./es.json")).default,+ },],};diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex 9224917d..59e4ce9b 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "Mostra altri {{count}}","open_folder": "Mostra nella cartella",+ "open_in_study": "Watch in Study","stop": "Ferma","confirm_remove": "Rimuovere questo download?","stats_line": "{{count}} download · {{size}} salvati",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "Taglia sponsor, intro e outro dai video YouTube (dati della community; può mancare o tagliare troppo)","split_by_chapters": "Dividi video per capitoli","split_by_chapters_desc": "Quando il video ha marcatori di capitolo, salva ciascun capitolo come file separato",+ "presets": "Preset rapidi",+ "presets_desc": "Configurazione con un clic. Tocca una scheda per applicare.",+ "preset_fast": "Veloce",+ "preset_fast_desc": "480p · senza metadati · senza sottotitoli",+ "preset_quality": "Qualità",+ "preset_quality_desc": "Video migliore · metadati · miniatura",+ "preset_compact": "Compatto",+ "preset_compact_desc": "720p · metadati · senza miniatura",+ "preset_music_only": "Solo musica",+ "preset_music_only_desc": "Audio · tag ID3 · copertina","hotkey_enabled": "Scorciatoia globale","hotkey_enabled_desc": "Scarica l'URL negli appunti con una scorciatoia da tastiera","hotkey_binding": "Tasto scorciatoia","hotkey_record": "Registra","hotkey_type": "Digita","hotkey_press": "Premi i tasti...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "Copia file negli appunti dopo download da scorciatoia","copy_to_clipboard_on_hotkey_desc": "Copia automaticamente il file scaricato negli appunti per incollare facilmente","filename_template": "Modello nome file",@@ -326,7 +343,25 @@"cat_downloads": "Download","cat_network": "Rete","cat_advanced": "Avanzato",- "search_placeholder": "Cerca impostazioni..."+ "search_placeholder": "Cerca impostazioni...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Mostra la tua attività sul profilo Discord. Il timer non si resetta passando da un'attività all'altra.",+ "enable": "Mostra attività su Discord",+ "privacy_note": "Mostra ciò che stai ascoltando, guardando o leggendo. I tuoi download restano privati.",+ "test": "Testa connessione",+ "test_desc": "Invia un'attività di test per verificare che Discord sia in esecuzione.",+ "test_button": "Invia test",+ "test_ok": "Connesso a Discord",+ "test_fail": "Impossibile connettersi a Discord. Verifica che sia in esecuzione.",+ "saved": "Salvato",+ "save": "Salva",+ "advanced": "Avanzato",+ "app_id": "ID applicazione",+ "app_id_hint": "ID applicazione Discord. Modifica solo se sai cosa stai facendo.",+ "large_image": "Chiave immagine grande",+ "large_image_hint": "Nome dell'asset caricato nella tua applicazione Discord."+ }},"omnibox": {"placeholder": "Incolla un URL o cerca",@@ -554,6 +589,11 @@"hotkey_desc": "Copia un URL, premi la scorciatoia e OmniGet scarica subito — anche da minimizzato.","hotkey_on": "Attivato","hotkey_off": "Disattivato",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Mostra sul tuo profilo Discord che stai usando OmniGet — incluso ciò che ascolti, guardi o leggi.",+ "rpc_on": "Attivato",+ "rpc_off": "Disattivato",+ "rpc_privacy_note": "Mostra ciò che stai ascoltando, guardando o leggendo. I tuoi download restano privati.","theme_label": "Tema","theme_system": "Sistema","theme_light": "Chiaro",@@ -602,7 +642,9 @@"download_timeout": "Download scaduto. Controlla la tua connessione internet.","size_mismatch": "La dimensione del file scaricato non corrisponde. Riprova.","disk_full": "Errore di scrittura — il disco potrebbe essere pieno.",- "path_too_long": "Il percorso della cartella è troppo lungo ({{current}}/{{limit}} caratteri). Scegli una cartella più corta."+ "path_too_long": "Il percorso della cartella è troppo lungo ({{current}}/{{limit}} caratteri). Scegli una cartella più corta.",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "Registro attività",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "Studio","subtitle": "Trasforma i corsi scaricati in un ciclo di pratica deliberata.","library": "Libreria",+ "music": "Music","focus": "Focus","progress": "Progressi","achievements": "Obiettivi",@@ -839,8 +892,437 @@"action_vacuum_label": "Compatta database (vacuum)","action_vacuum_hint": "Manutenzione SQLite"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "Indaco",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "Libreria",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "Modalità di visualizzazione",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "Nessun corso indicizzato. Avvia una scansione dalle impostazioni.","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "In corso","status_not_started": "Non iniziati","status_completed": "Completati",- "view_mode_aria": "Modalità di visualizzazione","status_aria": "Stato","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "Continua da dove hai lasciato",+ "home_continue_eyebrow": "Recente",+ "home_continue_empty": "Nessun corso in corso. Inizia una lezione per vederla qui.",+ "home_continue_next": "Prossima: {{title}}",+ "home_continue_current": "In corso: {{title}}",+ "home_news_title": "Con novità",+ "home_news_eyebrow": "Nuove lezioni",+ "home_news_count_one": "{{count}} nuova lezione",+ "home_news_count_other": "{{count}} nuove lezioni",+ "home_recently_title": "Aggiunti di recente",+ "home_recently_eyebrow": "Nuovi",+ "home_platform_eyebrow": "Piattaforma",+ "home_subject_eyebrow": "Materia",+ "home_empty_title": "La tua libreria è vuota",+ "home_empty_desc": "Aggiungi una cartella con corsi per iniziare.",+ "home_empty_cta": "Aggiungi cartella corsi",+ "home_load_error": "Caricamento libreria fallito: {{error}}",+ "view_home": "Home",+ "view_catalog": "Catalogo",+ "platform_generic": "Altre piattaforme"},"player": {"title": "Player",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "Clip ultimi 60s",+ "clip_loading": "Creazione clip…",+ "clip_done": "Clip salvata",+ "clip_failed": "Clip fallita",+ "clip_no_video": "Video non ancora caricato",+ "clip_aria": "Salva gli ultimi 60 secondi come clip"},"notes": {"title": "Note",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "bronzo",+ "tier_silver": "argento",+ "tier_gold": "oro",+ "unlocked_prefix": "sbloccato",+ "reset_done": "Reset effettuato",+ "reset_confirm_label": "Reset",+ "filter_aria": "Filtri di categoria",+ "tree_link": "Albero",+ "charts_link": "Grafici",+ "label_xp_100": "Primi 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Mille XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "Prima lezione",+ "label_lessons_10": "10 lezioni",+ "label_lessons_50": "50 lezioni",+ "label_lessons_100": "100 lezioni",+ "label_focus_60": "1h focalizzato",+ "label_focus_600": "10h focalizzato",+ "label_focus_6000": "100h focalizzato",+ "label_streak_3": "3 giorni di fila",+ "label_streak_7": "Streak di 1 settimana",+ "label_streak_30": "Streak di 30 giorni",+ "label_streak_100": "Streak di 100 giorni",+ "desc_xp_100": "Accumula 100 XP studiando",+ "desc_xp_500": "Accumula 500 XP",+ "desc_xp_1000": "Traguardo dei 1000 XP",+ "desc_xp_5000": "Cinquemila XP accumulati",+ "desc_xp_10000": "Diecimila XP — sei dedicato",+ "desc_lessons_1": "Completa la tua prima lezione",+ "desc_lessons_10": "Completa 10 lezioni",+ "desc_lessons_50": "Mezzo secolo di lezioni",+ "desc_lessons_100": "Cento lezioni completate",+ "desc_focus_60": "60 minuti di focus accumulati",+ "desc_focus_600": "600 minuti di focus accumulati",+ "desc_focus_6000": "6000 minuti di focus — disciplina rara",+ "desc_streak_3": "Mantieni la streak per 3 giorni",+ "desc_streak_7": "7 giorni consecutivi di studio",+ "desc_streak_30": "Un mese intero di costanza",+ "desc_streak_100": "Abitudine d'acciaio"},"focus": {"title": "Focus","placeholder": "Sessioni Pomodoro e deep work qui.",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "Pomodoro (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "salvataggio…",+ "settings_saved": "salvato ✓",+ "acc_cycles_title": "Cicli",+ "acc_cycles_summary": "{{focus}}min focus · {{break}}min pausa · {{cycles}}× fino alla pausa lunga",+ "acc_cycles_focus": "Focus (min)",+ "acc_cycles_short": "Pausa breve (min)",+ "acc_cycles_long": "Pausa lunga (min)",+ "acc_cycles_count": "Cicli prima della pausa lunga",+ "acc_breaks_title": "Pause & avvio automatico",+ "acc_breaks_auto_yes": "auto-pausa",+ "acc_breaks_auto_no": "manuale",+ "acc_breaks_focus_yes": "auto-ripresa",+ "acc_breaks_focus_no": "manuale",+ "acc_breaks_player_yes": "mette in pausa il player",+ "acc_breaks_player_no": "ignora il player",+ "acc_breaks_check_breaks": "Avvia pause automaticamente dopo il focus",+ "acc_breaks_check_focus": "Riprendi focus automaticamente dopo la pausa",+ "acc_breaks_check_player": "Metti in pausa il video durante la pausa focus",+ "acc_sounds_title": "Suoni & notifica",+ "acc_sounds_notify_on": "notifica ON",+ "acc_sounds_notify_off": "silenzioso",+ "acc_sounds_sound_on": "suono {{n}}%",+ "acc_sounds_sound_off": "senza suono",+ "acc_sounds_check_notify": "Notifica alla fine del ciclo",+ "acc_sounds_check_sound": "Riproduci suono alla fine",+ "acc_sounds_volume": "Volume ({{n}}%)",+ "unlimited_aria": "libero"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "Tempo per corso",+ "chart_time_per_course_empty": "Nessun tempo registrato in questo periodo.",+ "chart_time_period_days": "ultimi {{n}} giorni",+ "chart_activity_by_hour": "Attività per ora",+ "chart_activity_hint": "somma dei focus · 24h",+ "chart_activity_empty": "Nessuna attività negli ultimi {{n}} giorni.",+ "chart_subject": "Per materia",+ "chart_subject_unit": "minuti focalizzati",+ "chart_subject_empty": "Crea materie e assegna sessioni per vedere la suddivisione.",+ "chart_subject_unassigned": "Senza materia",+ "retention_title": "Ritenzione (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "La ritenzione reale arriverà dalla query cross-DB di Anki. Per ora, apri",+ "retention_link": "Statistiche Anki →",+ "retention_stub_after": "per vedere ritenzione, distribuzione degli intervalli e storico delle revisioni.",+ "recent_achievements": "Risultati recenti",+ "view_all": "Vedi tutti →",+ "time_today": "oggi",+ "time_yesterday": "ieri",+ "time_days_ago": "{{n}} giorni fa",+ "time_months_ago": "{{n}} mesi fa",+ "time_years_ago": "{{n}} anni fa",+ "ach_label_xp_100": "100 XP accumulati",+ "ach_label_xp_500": "500 XP accumulati",+ "ach_label_xp_1000": "1.000 XP accumulati",+ "ach_label_xp_5000": "5.000 XP accumulati",+ "ach_label_xp_10000": "10.000 XP accumulati",+ "ach_label_lessons_1": "Prima lezione",+ "ach_label_lessons_10": "10 lezioni completate",+ "ach_label_lessons_50": "50 lezioni completate",+ "ach_label_lessons_100": "100 lezioni completate",+ "ach_label_focus_60": "1 ora di focus",+ "ach_label_focus_600": "10 ore di focus",+ "ach_label_focus_6000": "100 ore di focus",+ "ach_label_streak_3": "Streak di 3 giorni",+ "ach_label_streak_7": "Streak di 1 settimana",+ "ach_label_streak_30": "Streak di 30 giorni",+ "ach_label_streak_100": "Streak di 100 giorni"},"settings": {"title": "Impostazioni",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "Cerca note",+ "downloads_btn": "Download",+ "enrich_no_results": "Nessun risultato. Prova prima a modificare il titolo del libro.",+ "enrich_done": "✓ Metadati aggiornati",+ "enrich_field_title": "Titolo:",+ "enrich_field_author": "Autore:",+ "enrich_field_publisher": "Editore:",+ "enrich_field_cover": "Copertina (scarica)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex 3a522f08..9b023e23 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "さらに {{count}} 件を表示","open_folder": "フォルダーで表示",+ "open_in_study": "Watch in Study","stop": "停止","confirm_remove": "このダウンロードを削除しますか?","stats_line": "{{count}} 件のダウンロード · {{size}} 保存済み",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "YouTube動画からスポンサー、イントロ、アウトロのセグメントをカット(コミュニティデータ。漏れや過剰カットの可能性あり)","split_by_chapters": "チャプターごとに動画を分割","split_by_chapters_desc": "動画にチャプターマーカーがある場合、各チャプターを別ファイルとして保存します",+ "presets": "クイックプリセット",+ "presets_desc": "よく使う設定をワンクリックで適用。カードをタップしてください。",+ "preset_fast": "高速",+ "preset_fast_desc": "480p · メタデータなし · 字幕なし",+ "preset_quality": "高画質",+ "preset_quality_desc": "最高画質 · メタデータ · サムネイル",+ "preset_compact": "コンパクト",+ "preset_compact_desc": "720p · メタデータ · サムネイルなし",+ "preset_music_only": "音楽のみ",+ "preset_music_only_desc": "音声 · ID3タグ · カバー画像","hotkey_enabled": "グローバルホットキー","hotkey_enabled_desc": "キーボードショートカットでクリップボードのURLをダウンロードします","hotkey_binding": "ホットキーの割り当て","hotkey_record": "録音","hotkey_type": "入力","hotkey_press": "キーを押してください...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "ホットキーダウンロード後にファイルをクリップボードにコピー","copy_to_clipboard_on_hotkey_desc": "ダウンロードしたファイルを自動的にクリップボードにコピーして貼り付けやすくします","filename_template": "ファイル名テンプレート",@@ -326,7 +343,25 @@"cat_downloads": "ダウンロード","cat_network": "ネットワーク","cat_advanced": "詳細",- "search_placeholder": "設定を検索..."+ "search_placeholder": "設定を検索...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Discord プロフィールにアクティビティを表示します。アクティビティを切り替えてもタイマーはリセットされません。",+ "enable": "Discord にアクティビティを表示",+ "privacy_note": "聴いている、見ている、読んでいる内容を表示します。ダウンロードは表示されません。",+ "test": "接続をテスト",+ "test_desc": "Discord が実行中で接続されているか確認するためのテストアクティビティを送信します。",+ "test_button": "テスト送信",+ "test_ok": "Discord に接続しました",+ "test_fail": "Discord に接続できませんでした。Discord が起動しているか確認してください。",+ "saved": "保存しました",+ "save": "保存",+ "advanced": "詳細設定",+ "app_id": "アプリケーション ID",+ "app_id_hint": "Discord アプリケーション ID。意図がない限り変更しないでください。",+ "large_image": "ラージイメージキー",+ "large_image_hint": "Discord アプリにアップロードされたアセット名。"+ }},"omnibox": {"placeholder": "URLを貼り付けるか検索",@@ -554,6 +589,11 @@"hotkey_desc": "動画のURLをコピーしてホットキーを押すと、最小化中でもすぐにダウンロードが始まります。","hotkey_on": "有効","hotkey_off": "無効",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Discord プロフィールに OmniGet を使用していることを表示します — 聴いている、見ている、読んでいる内容も含めて。",+ "rpc_on": "有効",+ "rpc_off": "無効",+ "rpc_privacy_note": "聴いている、見ている、読んでいる内容を表示します。ダウンロードは表示されません。","theme_label": "テーマ","theme_system": "システム","theme_light": "ライト",@@ -602,7 +642,9 @@"download_timeout": "ダウンロードがタイムアウトしました。インターネット接続を確認してください。","size_mismatch": "ダウンロードしたファイルのサイズが一致しません。もう一度お試しください。","disk_full": "書き込みエラー — ディスクが満杯の可能性があります。",- "path_too_long": "ダウンロードフォルダのパスが長すぎます ({{current}}/{{limit}} 文字)。より短いフォルダを選択してください。"+ "path_too_long": "ダウンロードフォルダのパスが長すぎます ({{current}}/{{limit}} 文字)。より短いフォルダを選択してください。",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "アクティビティログ",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "学習","subtitle": "ダウンロードしたコースを意図的な練習ループに変えましょう。","library": "ライブラリ",+ "music": "Music","focus": "集中","progress": "進捗","achievements": "達成",@@ -839,8 +892,437 @@"action_vacuum_label": "DB を圧縮 (vacuum)","action_vacuum_hint": "SQLite メンテナンス"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "インディゴ",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "ライブラリ",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "表示モード",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "まだコースがインデックス化されていません。設定からスキャンを実行してください。","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "進行中","status_not_started": "未開始","status_completed": "完了",- "view_mode_aria": "表示モード","status_aria": "ステータス","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "中断したところから続ける",+ "home_continue_eyebrow": "最近",+ "home_continue_empty": "進行中のコースはありません。レッスンを開始するとここに表示されます。",+ "home_continue_next": "次:{{title}}",+ "home_continue_current": "受講中:{{title}}",+ "home_news_title": "更新あり",+ "home_news_eyebrow": "新着レッスン",+ "home_news_count_one": "新着 {{count}} レッスン",+ "home_news_count_other": "新着 {{count}} レッスン",+ "home_recently_title": "最近追加",+ "home_recently_eyebrow": "新着",+ "home_platform_eyebrow": "プラットフォーム",+ "home_subject_eyebrow": "科目",+ "home_empty_title": "ライブラリは空です",+ "home_empty_desc": "コースのあるフォルダを追加して始めましょう。",+ "home_empty_cta": "コースフォルダを追加",+ "home_load_error": "ライブラリの読み込みに失敗:{{error}}",+ "view_home": "ホーム",+ "view_catalog": "カタログ",+ "platform_generic": "その他のプラットフォーム"},"player": {"title": "プレーヤー",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "直近60秒をクリップ",+ "clip_loading": "クリップ中…",+ "clip_done": "クリップを保存",+ "clip_failed": "クリップ失敗",+ "clip_no_video": "動画がまだ読み込まれていません",+ "clip_aria": "直近60秒をクリップとして保存"},"notes": {"title": "ノート",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "ブロンズ",+ "tier_silver": "シルバー",+ "tier_gold": "ゴールド",+ "unlocked_prefix": "解除済み",+ "reset_done": "リセット完了",+ "reset_confirm_label": "リセット",+ "filter_aria": "カテゴリーフィルター",+ "tree_link": "ツリー",+ "charts_link": "チャート",+ "label_xp_100": "最初の 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "千 XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "最初のレッスン",+ "label_lessons_10": "10 レッスン",+ "label_lessons_50": "50 レッスン",+ "label_lessons_100": "100 レッスン",+ "label_focus_60": "1時間集中",+ "label_focus_600": "10時間集中",+ "label_focus_6000": "100時間集中",+ "label_streak_3": "3日連続",+ "label_streak_7": "1週間連続",+ "label_streak_30": "30日連続",+ "label_streak_100": "100日連続",+ "desc_xp_100": "学習して 100 XP を獲得",+ "desc_xp_500": "500 XP を獲得",+ "desc_xp_1000": "1000 XP のマイルストーン",+ "desc_xp_5000": "五千 XP 獲得",+ "desc_xp_10000": "一万 XP — 献身的です",+ "desc_lessons_1": "最初のレッスンを完了",+ "desc_lessons_10": "10 レッスン完了",+ "desc_lessons_50": "半世紀のレッスン",+ "desc_lessons_100": "百レッスン完了",+ "desc_focus_60": "60分の集中を獲得",+ "desc_focus_600": "600分の集中を獲得",+ "desc_focus_6000": "6000分の集中 — 稀有な自律",+ "desc_streak_3": "3日間ストリークを維持",+ "desc_streak_7": "7日連続で学習",+ "desc_streak_30": "一ヶ月の継続",+ "desc_streak_100": "鋼の習慣"},"focus": {"title": "集中","placeholder": "ポモドーロと深い作業のセッションはここから。",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "ポモドーロ (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "保存中…",+ "settings_saved": "保存済み ✓",+ "acc_cycles_title": "サイクル",+ "acc_cycles_summary": "{{focus}}分集中 · {{break}}分休憩 · 長休憩まで {{cycles}}×",+ "acc_cycles_focus": "集中(分)",+ "acc_cycles_short": "短い休憩(分)",+ "acc_cycles_long": "長い休憩(分)",+ "acc_cycles_count": "長い休憩までのサイクル数",+ "acc_breaks_title": "休憩 & 自動開始",+ "acc_breaks_auto_yes": "自動一時停止",+ "acc_breaks_auto_no": "手動",+ "acc_breaks_focus_yes": "自動再開",+ "acc_breaks_focus_no": "手動",+ "acc_breaks_player_yes": "プレーヤーを一時停止",+ "acc_breaks_player_no": "プレーヤーを無視",+ "acc_breaks_check_breaks": "集中後に休憩を自動開始",+ "acc_breaks_check_focus": "休憩後に集中を自動再開",+ "acc_breaks_check_player": "集中休憩中に動画を一時停止",+ "acc_sounds_title": "サウンド & 通知",+ "acc_sounds_notify_on": "通知 ON",+ "acc_sounds_notify_off": "無音",+ "acc_sounds_sound_on": "音 {{n}}%",+ "acc_sounds_sound_off": "音なし",+ "acc_sounds_check_notify": "サイクル終了時に通知",+ "acc_sounds_check_sound": "終了時にサウンドを再生",+ "acc_sounds_volume": "音量 ({{n}}%)",+ "unlimited_aria": "無制限"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "コースごとの時間",+ "chart_time_per_course_empty": "この期間に記録された時間はありません。",+ "chart_time_period_days": "直近 {{n}} 日",+ "chart_activity_by_hour": "時間帯別のアクティビティ",+ "chart_activity_hint": "集中の合計 · 24時間",+ "chart_activity_empty": "直近 {{n}} 日のアクティビティはありません。",+ "chart_subject": "科目別",+ "chart_subject_unit": "集中分数",+ "chart_subject_empty": "科目を作成しセッションを割り当てると内訳が表示されます。",+ "chart_subject_unassigned": "科目なし",+ "retention_title": "保持率 (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "実際の保持率は Anki クロスDB クエリから取得されます。今のところは",+ "retention_link": "Anki 統計 →",+ "retention_stub_after": "を開いて保持率・間隔分布・復習履歴を確認してください。",+ "recent_achievements": "最近の実績",+ "view_all": "すべて表示 →",+ "time_today": "今日",+ "time_yesterday": "昨日",+ "time_days_ago": "{{n}} 日前",+ "time_months_ago": "{{n}} ヶ月前",+ "time_years_ago": "{{n}} 年前",+ "ach_label_xp_100": "100 XP 獲得",+ "ach_label_xp_500": "500 XP 獲得",+ "ach_label_xp_1000": "1,000 XP 獲得",+ "ach_label_xp_5000": "5,000 XP 獲得",+ "ach_label_xp_10000": "10,000 XP 獲得",+ "ach_label_lessons_1": "最初のレッスン",+ "ach_label_lessons_10": "10 レッスン完了",+ "ach_label_lessons_50": "50 レッスン完了",+ "ach_label_lessons_100": "100 レッスン完了",+ "ach_label_focus_60": "1 時間集中",+ "ach_label_focus_600": "10 時間集中",+ "ach_label_focus_6000": "100 時間集中",+ "ach_label_streak_3": "3 日連続",+ "ach_label_streak_7": "1 週間連続",+ "ach_label_streak_30": "30 日連続",+ "ach_label_streak_100": "100 日連続"},"settings": {"title": "設定",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "ノート検索",+ "downloads_btn": "ダウンロード",+ "enrich_no_results": "結果なし。先に本のタイトルを編集してみてください。",+ "enrich_done": "✓ メタデータを更新しました",+ "enrich_field_title": "タイトル:",+ "enrich_field_author": "著者:",+ "enrich_field_publisher": "出版社:",+ "enrich_field_cover": "カバー(ダウンロード)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex b2a8bdb2..ec9ac6c4 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -174,6 +174,7 @@ export type TranslationKeys =| 'downloads.log.show'| 'downloads.module_progress'| 'downloads.open_folder'+ | 'downloads.open_in_study'| 'downloads.page_progress'| 'downloads.pause'| 'downloads.phase_connecting'@@ -197,11 +198,13 @@ export type TranslationKeys =| 'errors.access_denied'| 'errors.connection_timeout'+ | 'errors.console_encoding'| 'errors.cookie_database'| 'errors.copyright_blocked'| 'errors.disk_full'| 'errors.download_timeout'| 'errors.extraction_failed'+ | 'errors.extractor_broken'| 'errors.ffmpeg_missing'| 'errors.format_unavailable'| 'errors.geo_restricted'@@ -394,6 +397,11 @@ export type TranslationKeys =| 'onboarding.next'| 'onboarding.plugins_desc'| 'onboarding.plugins_title'+ | 'onboarding.rpc_desc'+ | 'onboarding.rpc_off'+ | 'onboarding.rpc_on'+ | 'onboarding.rpc_privacy_note'+ | 'onboarding.rpc_title'| 'onboarding.skip'| 'onboarding.step_of'| 'onboarding.theme_dark'@@ -455,6 +463,7 @@ export type TranslationKeys =| 'settings.advanced.torrent_listen_port_desc'| 'settings.appearance.lang_el'| 'settings.appearance.lang_en'+ | 'settings.appearance.lang_es'| 'settings.appearance.lang_fr'| 'settings.appearance.lang_it'| 'settings.appearance.lang_ja'@@ -511,8 +520,23 @@ export type TranslationKeys =| 'settings.download.hotkey_type'| 'settings.download.include_auto_subtitles'| 'settings.download.include_auto_subtitles_desc'+ | 'settings.download.music_audio_format'+ | 'settings.download.music_audio_format_desc'+ | 'settings.download.music_hotkey_binding'+ | 'settings.download.music_hotkey_enabled'+ | 'settings.download.music_hotkey_enabled_desc'| 'settings.download.organize_by_platform'| 'settings.download.organize_by_platform_desc'+ | 'settings.download.preset_compact'+ | 'settings.download.preset_compact_desc'+ | 'settings.download.preset_fast'+ | 'settings.download.preset_fast_desc'+ | 'settings.download.preset_music_only'+ | 'settings.download.preset_music_only_desc'+ | 'settings.download.preset_quality'+ | 'settings.download.preset_quality_desc'+ | 'settings.download.presets'+ | 'settings.download.presets_desc'| 'settings.download.skip_existing'| 'settings.download.split_by_chapters'| 'settings.download.split_by_chapters_desc'@@ -540,6 +564,22 @@ export type TranslationKeys =| 'settings.proxy.title'| 'settings.proxy.type'| 'settings.proxy.username'+ | 'settings.rpc.advanced'+ | 'settings.rpc.app_id'+ | 'settings.rpc.app_id_hint'+ | 'settings.rpc.desc'+ | 'settings.rpc.enable'+ | 'settings.rpc.large_image'+ | 'settings.rpc.large_image_hint'+ | 'settings.rpc.privacy_note'+ | 'settings.rpc.save'+ | 'settings.rpc.saved'+ | 'settings.rpc.test'+ | 'settings.rpc.test_button'+ | 'settings.rpc.test_desc'+ | 'settings.rpc.test_fail'+ | 'settings.rpc.test_ok'+ | 'settings.rpc.title'| 'settings.search_placeholder'| 'settings.telegram.concurrent_downloads'| 'settings.telegram.concurrent_downloads_desc'@@ -591,9 +631,31 @@ export type TranslationKeys =| 'shortcuts.start_download'| 'shortcuts.title'+ | 'study.about.cta_github'+ | 'study.about.eyebrow'+ | 'study.about.long_pitch'+ | 'study.about.short_pitch'+ | 'study.achievements.charts_link'| 'study.achievements.day_ago'| 'study.achievements.days_ago'+ | 'study.achievements.desc_focus_60'+ | 'study.achievements.desc_focus_600'+ | 'study.achievements.desc_focus_6000'+ | 'study.achievements.desc_lessons_1'+ | 'study.achievements.desc_lessons_10'+ | 'study.achievements.desc_lessons_100'+ | 'study.achievements.desc_lessons_50'+ | 'study.achievements.desc_streak_100'+ | 'study.achievements.desc_streak_3'+ | 'study.achievements.desc_streak_30'+ | 'study.achievements.desc_streak_7'+ | 'study.achievements.desc_xp_100'+ | 'study.achievements.desc_xp_1000'+ | 'study.achievements.desc_xp_10000'+ | 'study.achievements.desc_xp_500'+ | 'study.achievements.desc_xp_5000'| 'study.achievements.filter_all'+ | 'study.achievements.filter_aria'| 'study.achievements.filter_focus'| 'study.achievements.filter_lessons'| 'study.achievements.filter_streak'@@ -601,17 +663,40 @@ export type TranslationKeys =| 'study.achievements.history_empty'| 'study.achievements.history_title'| 'study.achievements.hours_ago'+ | 'study.achievements.label_focus_60'+ | 'study.achievements.label_focus_600'+ | 'study.achievements.label_focus_6000'+ | 'study.achievements.label_lessons_1'+ | 'study.achievements.label_lessons_10'+ | 'study.achievements.label_lessons_100'+ | 'study.achievements.label_lessons_50'+ | 'study.achievements.label_streak_100'+ | 'study.achievements.label_streak_3'+ | 'study.achievements.label_streak_30'+ | 'study.achievements.label_streak_7'+ | 'study.achievements.label_xp_100'+ | 'study.achievements.label_xp_1000'+ | 'study.achievements.label_xp_10000'+ | 'study.achievements.label_xp_500'+ | 'study.achievements.label_xp_5000'| 'study.achievements.level_progress'| 'study.achievements.level_tag'| 'study.achievements.loading'| 'study.achievements.minutes_ago'+ | 'study.achievements.reset_confirm_label'| 'study.achievements.reset_confirm_message'| 'study.achievements.reset_confirm_title'| 'study.achievements.reset_desc'+ | 'study.achievements.reset_done'| 'study.achievements.reset_title'| 'study.achievements.subtitle'+ | 'study.achievements.tier_bronze'+ | 'study.achievements.tier_gold'+ | 'study.achievements.tier_silver'| 'study.achievements.title'| 'study.achievements.to_next'+ | 'study.achievements.tree_link'+ | 'study.achievements.unlocked_prefix'| 'study.attachments.title'| 'study.bookmark.add'| 'study.bookmark.add_hint'@@ -630,8 +715,12 @@ export type TranslationKeys =| 'study.bulk.undo'| 'study.common.all'| 'study.common.cancel'+ | 'study.common.clear'| 'study.common.close'| 'study.common.confirm'+ | 'study.common.copied'+ | 'study.common.copy'+ | 'study.common.create'| 'study.common.delete'| 'study.common.dismiss'| 'study.common.edit'@@ -661,6 +750,30 @@ export type TranslationKeys =| 'study.export.all_hint'| 'study.export.all_md'| 'study.export.ok'+ | 'study.focus.acc_breaks_auto_no'+ | 'study.focus.acc_breaks_auto_yes'+ | 'study.focus.acc_breaks_check_breaks'+ | 'study.focus.acc_breaks_check_focus'+ | 'study.focus.acc_breaks_check_player'+ | 'study.focus.acc_breaks_focus_no'+ | 'study.focus.acc_breaks_focus_yes'+ | 'study.focus.acc_breaks_player_no'+ | 'study.focus.acc_breaks_player_yes'+ | 'study.focus.acc_breaks_title'+ | 'study.focus.acc_cycles_count'+ | 'study.focus.acc_cycles_focus'+ | 'study.focus.acc_cycles_long'+ | 'study.focus.acc_cycles_short'+ | 'study.focus.acc_cycles_summary'+ | 'study.focus.acc_cycles_title'+ | 'study.focus.acc_sounds_check_notify'+ | 'study.focus.acc_sounds_check_sound'+ | 'study.focus.acc_sounds_notify_off'+ | 'study.focus.acc_sounds_notify_on'+ | 'study.focus.acc_sounds_sound_off'+ | 'study.focus.acc_sounds_sound_on'+ | 'study.focus.acc_sounds_title'+ | 'study.focus.acc_sounds_volume'| 'study.focus.active_preset_label'| 'study.focus.auto_pause_player'| 'study.focus.auto_start.breaks'@@ -684,6 +797,11 @@ export type TranslationKeys =| 'study.focus.hero_title'| 'study.focus.history'| 'study.focus.history_empty'+ | 'study.focus.intent_for'+ | 'study.focus.intent_hint'+ | 'study.focus.intent_label'+ | 'study.focus.intent_placeholder'+ | 'study.focus.intent_prefix'| 'study.focus.interrupt'| 'study.focus.interrupted'| 'study.focus.long_break'@@ -709,8 +827,11 @@ export type TranslationKeys =| 'study.focus.preset_long_break'| 'study.focus.preset_pomodoro'| 'study.focus.preset_short_break'+ | 'study.focus.rpc_default'| 'study.focus.running'| 'study.focus.session_ended'+ | 'study.focus.settings_saved'+ | 'study.focus.settings_saving'| 'study.focus.settings_title'| 'study.focus.short_break'| 'study.focus.start'@@ -728,6 +849,7 @@ export type TranslationKeys =| 'study.focus.today_progress'| 'study.focus.today_session'| 'study.focus.today_sessions'+ | 'study.focus.unlimited_aria'| 'study.focus.weekly_target'| 'study.goals.metric.cards'| 'study.goals.metric.lessons'@@ -751,6 +873,7 @@ export type TranslationKeys =| 'study.hub.greeting_morning'| 'study.hub.library'| 'study.hub.made_by'+ | 'study.hub.music'| 'study.hub.new'| 'study.hub.notes'| 'study.hub.now'@@ -779,6 +902,12 @@ export type TranslationKeys =| 'study.lesson.autoplay_play_now'| 'study.lesson.autoplay_title'| 'study.lesson.back_to_course'+ | 'study.lesson.clip'+ | 'study.lesson.clip_aria'+ | 'study.lesson.clip_done'+ | 'study.lesson.clip_failed'+ | 'study.lesson.clip_loading'+ | 'study.lesson.clip_no_video'| 'study.lesson.completed'| 'study.lesson.description_title'| 'study.lesson.loading'@@ -791,11 +920,19 @@ export type TranslationKeys =| 'study.lesson.theater_hint'| 'study.lesson.theater_off'| 'study.lesson.theater_on'+ | 'study.library.address_bar_open'+ | 'study.library.address_bar_placeholder'| 'study.library.all_courses'| 'study.library.back'+ | 'study.library.back_toast'| 'study.library.browse_breadcrumb_root'| 'study.library.browse_empty'| 'study.library.browse_empty_roots'+ | 'study.library.browse_sort_label'+ | 'study.library.browse_sort_name_asc'+ | 'study.library.browse_sort_name_desc'+ | 'study.library.browse_sort_recent'+ | 'study.library.browse_sort_size_desc'| 'study.library.cleanup_btn'| 'study.library.cleanup_busy'| 'study.library.cleanup_confirm_message'@@ -807,7 +944,27 @@ export type TranslationKeys =| 'study.library.cleanup_force_hint'| 'study.library.cleanup_orphan_delete'| 'study.library.clear_filters'+ | 'study.library.ctx_delete'+ | 'study.library.ctx_open'+ | 'study.library.ctx_rename'+ | 'study.library.ctx_show_in_explorer'+ | 'study.library.delete_confirm_btn'+ | 'study.library.delete_confirm_msg_file'+ | 'study.library.delete_confirm_msg_folder'+ | 'study.library.delete_confirm_title'+ | 'study.library.delete_toast_done'| 'study.library.empty'+ | 'study.library.empty_add_folder_cta'+ | 'study.library.empty_add_folder_desc'+ | 'study.library.empty_add_folder_title'+ | 'study.library.empty_browse_description'+ | 'study.library.empty_browse_title'+ | 'study.library.empty_telegram_cta'+ | 'study.library.empty_telegram_desc'+ | 'study.library.empty_telegram_title'+ | 'study.library.empty_with_roots_cta'+ | 'study.library.empty_with_roots_one'+ | 'study.library.empty_with_roots_other'| 'study.library.error_loading_notes'| 'study.library.favorite'| 'study.library.favorite_off'@@ -841,10 +998,28 @@ export type TranslationKeys =| 'study.library.health_zero_byte_hint'| 'study.library.history'| 'study.library.history_empty'+ | 'study.library.home_continue_current'+ | 'study.library.home_continue_empty'+ | 'study.library.home_continue_eyebrow'+ | 'study.library.home_continue_next'+ | 'study.library.home_continue_title'+ | 'study.library.home_empty_cta'+ | 'study.library.home_empty_desc'+ | 'study.library.home_empty_title'+ | 'study.library.home_load_error'+ | 'study.library.home_news_count_one'+ | 'study.library.home_news_count_other'+ | 'study.library.home_news_eyebrow'+ | 'study.library.home_news_title'+ | 'study.library.home_platform_eyebrow'+ | 'study.library.home_recently_eyebrow'+ | 'study.library.home_recently_title'+ | 'study.library.home_subject_eyebrow'| 'study.library.kind_all'| 'study.library.kind_course'| 'study.library.kind_media'| 'study.library.kind_media_badge'+ | 'study.library.last_watched_label'| 'study.library.lessons'| 'study.library.lessons_count'| 'study.library.loading_more'@@ -853,7 +1028,10 @@ export type TranslationKeys =| 'study.library.mode_browse'| 'study.library.mode_courses'| 'study.library.mode_telegram'+ | 'study.library.mode_telegram_disconnected_suffix'| 'study.library.more_filters'+ | 'study.library.new_folder'+ | 'study.library.new_folder_placeholder'| 'study.library.no_platforms'| 'study.library.notes'| 'study.library.notes_filter_pages'@@ -867,7 +1045,16 @@ export type TranslationKeys =| 'study.library.notes_page_not_found'| 'study.library.notes_pages_section'| 'study.library.notes_rename_page'+ | 'study.library.open_in_new_tab'+ | 'study.library.pin_action'+ | 'study.library.pin_action_active'+ | 'study.library.pin_action_title'+ | 'study.library.pin_added_toast'+ | 'study.library.pin_failed'+ | 'study.library.pin_removed_toast'+ | 'study.library.pinned_strip_aria'| 'study.library.platform'+ | 'study.library.platform_generic'| 'study.library.progress_pct'| 'study.library.recent'| 'study.library.rescan_now'@@ -875,15 +1062,28 @@ export type TranslationKeys =| 'study.library.rescanning'| 'study.library.reset'| 'study.library.resume'+ | 'study.library.root_missing_hint'+ | 'study.library.root_missing_label'| 'study.library.roots'| 'study.library.roots_add_btn'| 'study.library.roots_button'+ | 'study.library.roots_button_hint'| 'study.library.roots_default'| 'study.library.roots_empty'| 'study.library.roots_hint'| 'study.library.roots_remove'| 'study.library.roots_remove_tooltip'| 'study.library.search_placeholder'+ | 'study.library.selection_clear'+ | 'study.library.selection_count_one'+ | 'study.library.selection_count_other'+ | 'study.library.selection_delete'+ | 'study.library.selection_delete_confirm_msg'+ | 'study.library.selection_delete_confirm_title'+ | 'study.library.selection_delete_done'+ | 'study.library.selection_delete_partial'+ | 'study.library.siblings_aria'+ | 'study.library.siblings_empty'| 'study.library.sort_added'| 'study.library.sort_label'| 'study.library.sort_last_watched'@@ -899,6 +1099,9 @@ export type TranslationKeys =| 'study.library.status_in_progress'| 'study.library.status_new'| 'study.library.status_not_started'+ | 'study.library.subtitle'+ | 'study.library.tab_close'+ | 'study.library.tab_new'| 'study.library.tag'| 'study.library.tag_add'| 'study.library.tags'@@ -1087,12 +1290,19 @@ export type TranslationKeys =| 'study.library.telegram.watched'| 'study.library.telegram.webpage_open_external'| 'study.library.title'+ | 'study.library.unpin_action'+ | 'study.library.unpin_action_title'+ | 'study.library.unpin_failed'| 'study.library.video'| 'study.library.videos'| 'study.library.videos_count'+ | 'study.library.view_catalog'| 'study.library.view_grid'+ | 'study.library.view_home'| 'study.library.view_list'| 'study.library.view_mode_aria'+ | 'study.library.view_mode_grid'+ | 'study.library.view_mode_list'| 'study.library.watch_back'| 'study.library.watch_file_missing'| 'study.library.watch_not_found'@@ -1111,6 +1321,417 @@ export type TranslationKeys =| 'study.maintenance.lead'| 'study.maintenance.open_library'| 'study.maintenance.title'+ | 'study.music.activity_subtitle'+ | 'study.music.activity_title'+ | 'study.music.add_root'+ | 'study.music.add_root_cta'+ | 'study.music.add_to_playlist'+ | 'study.music.add_to_queue'+ | 'study.music.added_to_playlist'+ | 'study.music.albums_count'+ | 'study.music.albums_empty'+ | 'study.music.artists_count'+ | 'study.music.artists_empty'+ | 'study.music.batch_done'+ | 'study.music.by'+ | 'study.music.clear_covers'+ | 'study.music.clear_covers_confirm'+ | 'study.music.clear_covers_done'+ | 'study.music.clear_covers_hint'+ | 'study.music.click_to_rename'+ | 'study.music.created_playlist_with_track'+ | 'study.music.ctx_show_failed'+ | 'study.music.ctx_show_in_folder'+ | 'study.music.delete_confirm'+ | 'study.music.delete_confirm_msg'+ | 'study.music.delete_confirm_title'+ | 'study.music.delete_playlist'+ | 'study.music.diagnostics'+ | 'study.music.diagnostics_hint'+ | 'study.music.diagnostics_title'+ | 'study.music.discography'+ | 'study.music.dl_detecting'+ | 'study.music.dl_download_audio'+ | 'study.music.dl_hero_sub'+ | 'study.music.dl_hero_title'+ | 'study.music.dl_idle_hint'+ | 'study.music.dl_preparing'+ | 'study.music.dl_quality'+ | 'study.music.dl_quality_best'+ | 'study.music.dl_recent'+ | 'study.music.dl_search_empty'+ | 'study.music.dl_searching'+ | 'study.music.dl_started'+ | 'study.music.dl_unsupported'+ | 'study.music.empty'+ | 'study.music.empty_album'+ | 'study.music.empty_no_roots_body'+ | 'study.music.empty_no_roots_title'+ | 'study.music.empty_no_tracks_body'+ | 'study.music.empty_no_tracks_title'+ | 'study.music.empty_results'+ | 'study.music.eq_enable'+ | 'study.music.eq_preset'+ | 'study.music.eq_preset_bass'+ | 'study.music.eq_preset_classical'+ | 'study.music.eq_preset_custom'+ | 'study.music.eq_preset_electronic'+ | 'study.music.eq_preset_flat'+ | 'study.music.eq_preset_pop'+ | 'study.music.eq_preset_rock'+ | 'study.music.eq_preset_treble'+ | 'study.music.eq_preset_vocal'+ | 'study.music.eq_reset'+ | 'study.music.eq_title'+ | 'study.music.exit'+ | 'study.music.eyebrow_album'+ | 'study.music.eyebrow_artist'+ | 'study.music.eyebrow_genre'+ | 'study.music.eyebrow_playlist'+ | 'study.music.favorite'+ | 'study.music.favorited_count'+ | 'study.music.favorites_empty'+ | 'study.music.favorites_subtitle'+ | 'study.music.favorites_title'+ | 'study.music.featured_album'+ | 'study.music.field_album'+ | 'study.music.field_bitrate'+ | 'study.music.field_duration'+ | 'study.music.field_genre'+ | 'study.music.field_plays'+ | 'study.music.field_samplerate'+ | 'study.music.field_year'+ | 'study.music.genres_subtitle'+ | 'study.music.genres_title'+ | 'study.music.info_no_track'+ | 'study.music.jump_back_in'+ | 'study.music.lastfm_authorize'+ | 'study.music.lastfm_authorize_pending'+ | 'study.music.lastfm_connected'+ | 'study.music.lastfm_connected_as'+ | 'study.music.lastfm_connected_hint'+ | 'study.music.lastfm_disconnect'+ | 'study.music.lastfm_disconnect_confirm'+ | 'study.music.lastfm_disconnected'+ | 'study.music.lastfm_enable_scrobble'+ | 'study.music.lastfm_finalize'+ | 'study.music.lastfm_intro'+ | 'study.music.lastfm_keys_saved'+ | 'study.music.lastfm_open_auth'+ | 'study.music.lastfm_save_keys'+ | 'study.music.lastfm_step1_desc'+ | 'study.music.lastfm_step1_title'+ | 'study.music.lastfm_step2_desc'+ | 'study.music.lastfm_step2_title'+ | 'study.music.lastfm_step3_desc'+ | 'study.music.lastfm_step3_title'+ | 'study.music.lastfm_title'+ | 'study.music.library_title'+ | 'study.music.lyrics_loading'+ | 'study.music.lyrics_lrclib_hint'+ | 'study.music.lyrics_no_track'+ | 'study.music.lyrics_not_found'+ | 'study.music.lyrics_refresh'+ | 'study.music.lyrics_source'+ | 'study.music.lyrics_title'+ | 'study.music.manage_folders'+ | 'study.music.music_theme_accent'+ | 'study.music.music_theme_dominant_off'+ | 'study.music.music_theme_dominant_on'+ | 'study.music.music_theme_preset'+ | 'study.music.music_theme_preset_amber'+ | 'study.music.music_theme_preset_custom'+ | 'study.music.music_theme_preset_default'+ | 'study.music.music_theme_preset_indigo'+ | 'study.music.music_theme_preset_purple'+ | 'study.music.music_theme_preset_spotify'+ | '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.n_selected'+ | 'study.music.nav_activity'+ | 'study.music.nav_albums'+ | 'study.music.nav_aria'+ | 'study.music.nav_artists'+ | 'study.music.nav_download'+ | 'study.music.nav_favorites'+ | 'study.music.nav_genres'+ | '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_youtube'+ | 'study.music.new_playlist'+ | 'study.music.next'+ | 'study.music.no_activity'+ | 'study.music.no_genres'+ | 'study.music.no_playlists_yet'+ | 'study.music.open_album'+ | 'study.music.pause'+ | 'study.music.period_1y'+ | 'study.music.period_30d'+ | 'study.music.period_7d'+ | 'study.music.period_90d'+ | 'study.music.period_all'+ | 'study.music.play'+ | 'study.music.player_aria'+ | 'study.music.playlist_deleted'+ | 'study.music.playlist_duplicate'+ | 'study.music.playlist_empty_body'+ | 'study.music.playlist_empty_title'+ | 'study.music.playlist_name_placeholder'+ | 'study.music.playlist_not_found'+ | 'study.music.playlists_empty_body'+ | 'study.music.playlists_empty_title'+ | 'study.music.playlists_section'+ | 'study.music.playlists_title'+ | 'study.music.prev'+ | 'study.music.qobuz_connect'+ | 'study.music.qobuz_connected'+ | 'study.music.qobuz_connected_hint'+ | 'study.music.qobuz_connecting'+ | 'study.music.qobuz_disconnect'+ | 'study.music.qobuz_disconnect_confirm'+ | 'study.music.qobuz_disconnected'+ | 'study.music.qobuz_email_label'+ | 'study.music.qobuz_intro'+ | 'study.music.qobuz_password_label'+ | 'study.music.qobuz_privacy'+ | 'study.music.qobuz_pwd_hide'+ | 'study.music.qobuz_pwd_show'+ | 'study.music.qobuz_signed_in_as'+ | 'study.music.qobuz_state_connected'+ | 'study.music.qobuz_state_disconnected'+ | 'study.music.qobuz_test_again'+ | 'study.music.qobuz_test_failed'+ | 'study.music.qobuz_test_ok'+ | 'study.music.qobuz_testing'+ | 'study.music.qobuz_title'+ | 'study.music.quality_current'+ | 'study.music.quality_group_compact'+ | 'study.music.quality_group_high'+ | 'study.music.quality_group_lossless'+ | 'study.music.quality_group_recommended'+ | 'study.music.quality_hint_aac_192'+ | 'study.music.quality_hint_aac_256'+ | 'study.music.quality_hint_flac'+ | 'study.music.quality_hint_flac_cd'+ | 'study.music.quality_hint_flac_hires'+ | 'study.music.quality_hint_mp3_128'+ | 'study.music.quality_hint_mp3_192'+ | 'study.music.quality_hint_mp3_320'+ | 'study.music.quality_hint_opus_160'+ | 'study.music.quality_hint_wav'+ | 'study.music.quality_intro'+ | 'study.music.quality_saved'+ | 'study.music.quality_short'+ | 'study.music.quality_title'+ | 'study.music.queue_aria'+ | 'study.music.queue_clear'+ | 'study.music.queue_empty'+ | 'study.music.queue_title'+ | 'study.music.queue_toggle'+ | 'study.music.queued_count'+ | 'study.music.remove_from_playlist'+ | 'study.music.repeat'+ | 'study.music.root_added'+ | 'study.music.root_missing'+ | 'study.music.root_remove'+ | 'study.music.root_removed'+ | 'study.music.roots_empty'+ | 'study.music.roots_hint'+ | 'study.music.roots_title'+ | 'study.music.rpc_advanced'+ | 'study.music.rpc_appid_hint'+ | 'study.music.rpc_connected'+ | 'study.music.rpc_disconnected'+ | 'study.music.rpc_discord_running'+ | 'study.music.rpc_enable'+ | 'study.music.rpc_image_hint'+ | 'study.music.rpc_intro'+ | 'study.music.rpc_large_image'+ | 'study.music.rpc_save'+ | 'study.music.rpc_saved'+ | 'study.music.rpc_test'+ | 'study.music.rpc_test_fail'+ | 'study.music.rpc_test_ok'+ | 'study.music.rpc_title'+ | 'study.music.sc_already_signed_in'+ | 'study.music.sc_download_all'+ | 'study.music.sc_download_bulk_done'+ | 'study.music.sc_download_bulk_progress'+ | 'study.music.sc_download_started'+ | 'study.music.sc_download_track'+ | 'study.music.sc_empty_following_title'+ | 'study.music.sc_empty_likes_action'+ | 'study.music.sc_empty_likes_body'+ | 'study.music.sc_empty_likes_title'+ | 'study.music.sc_empty_playlists_body'+ | 'study.music.sc_empty_playlists_title'+ | 'study.music.sc_empty_state_logged_out_action'+ | 'study.music.sc_followers_count'+ | 'study.music.sc_go_plus_badge'+ | 'study.music.sc_go_plus_unavailable_hint'+ | 'study.music.sc_import_action'+ | 'study.music.sc_import_failed'+ | 'study.music.sc_import_invalid'+ | 'study.music.sc_import_success'+ | 'study.music.sc_import_url'+ | 'study.music.sc_import_url_desc'+ | 'study.music.sc_import_url_placeholder'+ | 'study.music.sc_import_url_title'+ | 'study.music.sc_load_more'+ | 'study.music.sc_loading'+ | 'study.music.sc_logout'+ | 'study.music.sc_offline_for_focus'+ | 'study.music.sc_open_in_browser'+ | 'study.music.sc_recommended_seed_fallback'+ | 'study.music.sc_refresh'+ | 'study.music.sc_search'+ | 'study.music.sc_section_continue'+ | 'study.music.sc_section_following'+ | 'study.music.sc_section_likes'+ | 'study.music.sc_section_playlists'+ | 'study.music.sc_section_recommended'+ | 'study.music.sc_section_stream'+ | 'study.music.sc_show_count'+ | 'study.music.sc_signin_body'+ | 'study.music.sc_signin_heading'+ | 'study.music.sc_skeleton_loading'+ | 'study.music.sc_status_client_id'+ | 'study.music.sc_status_oauth'+ | 'study.music.sc_title'+ | 'study.music.sc_track_count'+ | 'study.music.scan_done'+ | 'study.music.scan_now'+ | 'study.music.scanning'+ | 'study.music.search_hint'+ | 'study.music.search_placeholder'+ | 'study.music.see_all'+ | 'study.music.selection_aria'+ | 'study.music.shelf_added'+ | 'study.music.shelf_albums'+ | 'study.music.shelf_continue'+ | 'study.music.shelf_listen_now'+ | 'study.music.shelf_most_played'+ | 'study.music.shelf_new_releases'+ | 'study.music.shelf_top_artists'+ | 'study.music.shuffle'+ | 'study.music.sidebar_hint_body'+ | 'study.music.sidebar_hint_title'+ | 'study.music.sort_added'+ | 'study.music.sort_name'+ | 'study.music.sort_track_count'+ | 'study.music.sort_year'+ | 'study.music.source_connect'+ | 'study.music.source_inactive_header'+ | 'study.music.source_move_down'+ | 'study.music.source_move_up'+ | 'study.music.source_reset_default'+ | 'study.music.source_status_connected'+ | 'study.music.source_status_not_connected'+ | 'study.music.source_status_unavailable'+ | 'study.music.sources_intro'+ | 'study.music.sources_short'+ | 'study.music.sources_subtitle'+ | 'study.music.sources_title'+ | 'study.music.start_listening'+ | 'study.music.subtitle'+ | 'study.music.tab_albums'+ | 'study.music.tab_artists'+ | 'study.music.tab_info'+ | 'study.music.tab_lyrics'+ | 'study.music.tab_queue'+ | 'study.music.tab_tracks'+ | 'study.music.title'+ | 'study.music.top_albums'+ | 'study.music.top_artists'+ | 'study.music.top_genres'+ | 'study.music.top_tracks'+ | 'study.music.total_listened'+ | 'study.music.total_plays'+ | 'study.music.tracks_count'+ | 'study.music.unfavorite'+ | 'study.music.unique_tracks'+ | 'study.music.yt_add_playlist'+ | 'study.music.yt_auth_desc'+ | 'study.music.yt_auth_how'+ | 'study.music.yt_auth_saved'+ | 'study.music.yt_auth_step1'+ | 'study.music.yt_auth_step2'+ | 'study.music.yt_auth_step3'+ | 'study.music.yt_auth_step4'+ | 'study.music.yt_auth_title'+ | 'study.music.yt_browser_micro'+ | 'study.music.yt_browser_saved'+ | 'study.music.yt_cookie_full'+ | 'study.music.yt_cookie_hint'+ | 'study.music.yt_disconnect'+ | 'study.music.yt_disconnect_confirm'+ | 'study.music.yt_disconnected'+ | 'study.music.yt_download'+ | 'study.music.yt_download_started'+ | 'study.music.yt_empty_body'+ | 'study.music.yt_empty_title'+ | 'study.music.yt_ext_empty'+ | 'study.music.yt_ext_hint'+ | 'study.music.yt_ext_import'+ | 'study.music.yt_ext_imported'+ | 'study.music.yt_ext_imported_detail'+ | 'study.music.yt_ext_no_file'+ | 'study.music.yt_ext_no_sapisid'+ | 'study.music.yt_ext_no_sapisid_detail'+ | 'study.music.yt_ext_no_youtube'+ | 'study.music.yt_eyebrow'+ | 'study.music.yt_import'+ | 'study.music.yt_imported'+ | 'study.music.yt_intro'+ | 'study.music.yt_lm_label'+ | 'study.music.yt_or_manual'+ | 'study.music.yt_playlist_label'+ | 'study.music.yt_recs_for'+ | 'study.music.yt_refresh'+ | 'study.music.yt_refreshed'+ | 'study.music.yt_remove'+ | 'study.music.yt_remove_confirm'+ | 'study.music.yt_save_auth'+ | 'study.music.yt_search_placeholder'+ | 'study.music.yt_setup'+ | 'study.music.yt_state_anon'+ | 'study.music.yt_state_authed'+ | 'study.music.yt_step1_desc'+ | 'study.music.yt_step1_title'+ | 'study.music.yt_step2_desc'+ | 'study.music.yt_step2_title'+ | 'study.music.yt_subtitle'+ | 'study.music.yt_sync_desc'+ | 'study.music.yt_sync_done'+ | 'study.music.yt_sync_liked'+ | 'study.music.yt_sync_now'+ | 'study.music.yt_sync_playlists'+ | 'study.music.yt_sync_starting'+ | 'study.music.yt_sync_title'+ | 'study.music.yt_syncing'+ | 'study.music.yt_title'+ | 'study.music.yt_visitor_ok'+ | 'study.music.yt_yt_playlist_label'+ | 'study.music.ytdlp_bin'+ | 'study.music.ytdlp_done'+ | 'study.music.ytdlp_downloading'+ | 'study.music.ytdlp_format'+ | 'study.music.ytdlp_log'+ | 'study.music.ytdlp_missing_body'+ | 'study.music.ytdlp_missing_title'+ | 'study.music.ytdlp_no_roots'+ | 'study.music.ytdlp_start'+ | 'study.music.ytdlp_subtitle'+ | 'study.music.ytdlp_target'+ | 'study.music.ytdlp_title'+ | 'study.music.ytdlp_url'| 'study.notes.add'| 'study.notes.add_placeholder'| 'study.notes.at_time'@@ -1192,10 +1813,36 @@ export type TranslationKeys =| 'study.palette.tab_search'| 'study.player.placeholder'| 'study.player.title'+ | 'study.progress.ach_label_focus_60'+ | 'study.progress.ach_label_focus_600'+ | 'study.progress.ach_label_focus_6000'+ | 'study.progress.ach_label_lessons_1'+ | 'study.progress.ach_label_lessons_10'+ | 'study.progress.ach_label_lessons_100'+ | 'study.progress.ach_label_lessons_50'+ | 'study.progress.ach_label_streak_100'+ | 'study.progress.ach_label_streak_3'+ | 'study.progress.ach_label_streak_30'+ | 'study.progress.ach_label_streak_7'+ | 'study.progress.ach_label_xp_100'+ | 'study.progress.ach_label_xp_1000'+ | 'study.progress.ach_label_xp_10000'+ | 'study.progress.ach_label_xp_500'+ | 'study.progress.ach_label_xp_5000'| 'study.progress.cards_per_day'+ | 'study.progress.chart_activity_by_hour'+ | 'study.progress.chart_activity_empty'+ | 'study.progress.chart_activity_hint'| 'study.progress.chart_adjust_goals'| 'study.progress.chart_explore_library'| 'study.progress.chart_review_weak'+ | 'study.progress.chart_subject'+ | 'study.progress.chart_subject_empty'+ | 'study.progress.chart_subject_unassigned'+ | 'study.progress.chart_subject_unit'+ | 'study.progress.chart_time_per_course'+ | 'study.progress.chart_time_per_course_empty'+ | 'study.progress.chart_time_period_days'| 'study.progress.courses_completed'| 'study.progress.courses_done'| 'study.progress.daily_goal_pct'@@ -1229,7 +1876,13 @@ export type TranslationKeys =| 'study.progress.read_today'| 'study.progress.read_total'| 'study.progress.read_week'+ | 'study.progress.recent_achievements'| 'study.progress.retention'+ | 'study.progress.retention_link'+ | 'study.progress.retention_method'+ | 'study.progress.retention_stub_after'+ | 'study.progress.retention_stub_before'+ | 'study.progress.retention_title'| 'study.progress.review'| 'study.progress.stat_cards'| 'study.progress.stat_lessons'@@ -1240,9 +1893,15 @@ export type TranslationKeys =| 'study.progress.streak_unit'| 'study.progress.streak_unit_plural'| 'study.progress.time_by_subject'+ | 'study.progress.time_days_ago'+ | 'study.progress.time_months_ago'+ | 'study.progress.time_today'+ | 'study.progress.time_years_ago'+ | 'study.progress.time_yesterday'| 'study.progress.title'| 'study.progress.today_lessons'| 'study.progress.today_minutes'+ | 'study.progress.view_all'| 'study.read.add_bookmark'| 'study.read.annas_acked_at'| 'study.read.annas_disable_btn'@@ -1331,6 +1990,7 @@ export type TranslationKeys =| 'study.read.discover_source_all'| 'study.read.discover_subtitle'| 'study.read.discover_title'+ | 'study.read.downloads_btn'| 'study.read.effect_cursor'| 'study.read.effect_paper'| 'study.read.effects_label'@@ -1340,7 +2000,13 @@ export type TranslationKeys =| 'study.read.empty_no_roots_title'| 'study.read.enrich_apply_btn'| 'study.read.enrich_apply_hint'+ | 'study.read.enrich_done'+ | 'study.read.enrich_field_author'+ | 'study.read.enrich_field_cover'+ | 'study.read.enrich_field_publisher'+ | 'study.read.enrich_field_title'| 'study.read.enrich_metadata'+ | 'study.read.enrich_no_results'| 'study.read.enrich_search_btn'| 'study.read.enrich_search_hint'| 'study.read.entry_empty'@@ -1448,6 +2114,7 @@ export type TranslationKeys =| 'study.read.search_hits_count'| 'study.read.search_input'| 'study.read.search_no_hits'+ | 'study.read.search_notes_btn'| 'study.read.search_placeholder'| 'study.read.search_title'| 'study.read.series_chapters'diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex a0cfa085..dc089748 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -70,6 +70,7 @@"clear_confirm": "Limpar todos os downloads finalizados?","show_more": "Mostrar mais {{count}}","open_folder": "Abrir pasta",+ "open_in_study": "Assistir no Study","stop": "Parar","confirm_remove": "Remover este download?","stats_line": "{{count}} downloads · {{size}} salvos",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "Cortar trechos patrocinados, intros e outros de vídeos do YouTube (dados da comunidade; pode falhar ou cortar demais)","split_by_chapters": "Dividir vídeo por capítulos","split_by_chapters_desc": "Quando o vídeo tem marcadores de capítulo, salvar cada capítulo como arquivo separado",+ "presets": "Predefinições rápidas",+ "presets_desc": "Configuração com um clique. Toque num cartão para aplicar.",+ "preset_fast": "Rápido",+ "preset_fast_desc": "480p · sem metadados · sem legendas",+ "preset_quality": "Qualidade",+ "preset_quality_desc": "Melhor vídeo · metadados · miniatura",+ "preset_compact": "Compacto",+ "preset_compact_desc": "720p · metadados · sem miniatura",+ "preset_music_only": "Só música",+ "preset_music_only_desc": "Áudio · tags ID3 · capa","hotkey_enabled": "Atalho global","hotkey_enabled_desc": "Baixar URL do clipboard com um atalho de teclado","hotkey_binding": "Tecla de atalho","hotkey_record": "Gravar","hotkey_type": "Digitar","hotkey_press": "Pressione teclas...",+ "music_hotkey_enabled": "Atalho de download de música",+ "music_hotkey_enabled_desc": "Baixar URL do clipboard como áudio com um atalho de teclado (usa o Formato de Música abaixo)",+ "music_hotkey_binding": "Tecla do atalho de música",+ "music_audio_format": "Formato de música",+ "music_audio_format_desc": "Formato de áudio usado pelo atalho de música e pelo downloader do plugin Music","copy_to_clipboard_on_hotkey": "Copiar arquivo para clipboard após download via hotkey","copy_to_clipboard_on_hotkey_desc": "Copiar automaticamente o arquivo baixado para o clipboard para fácil colagem","filename_template": "Template de nome",@@ -326,7 +343,25 @@"cat_downloads": "Downloads","cat_network": "Rede","cat_advanced": "Avancado",- "search_placeholder": "Buscar configurações..."+ "search_placeholder": "Buscar configurações...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "Mostra sua atividade no perfil do Discord. O timer não reseta ao trocar de atividade.",+ "enable": "Mostrar atividade no Discord",+ "privacy_note": "Mostra o que você está ouvindo, assistindo ou lendo. Seus downloads ficam privados.",+ "test": "Testar conexão",+ "test_desc": "Envia uma atividade de teste pra verificar se o Discord está rodando.",+ "test_button": "Enviar teste",+ "test_ok": "Conectado ao Discord",+ "test_fail": "Não foi possível conectar ao Discord. Verifique se ele está aberto.",+ "saved": "Salvo",+ "save": "Salvar",+ "advanced": "Avançado",+ "app_id": "Application ID",+ "app_id_hint": "ID da aplicação Discord. Mude apenas se souber o que está fazendo.",+ "large_image": "Chave da imagem grande",+ "large_image_hint": "Nome do asset enviado para sua aplicação Discord."+ }},"omnibox": {"placeholder": "Cole uma URL, magnet link, .torrent ou pesquise",@@ -554,6 +589,11 @@"hotkey_desc": "Copie qualquer URL de video, pressione o atalho e o OmniGet comeca a baixar na hora — mesmo minimizado.","hotkey_on": "Ativado","hotkey_off": "Desativado",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "Mostre no seu perfil do Discord que você está usando o OmniGet — incluindo o que está ouvindo, assistindo ou lendo.",+ "rpc_on": "Ativado",+ "rpc_off": "Desativado",+ "rpc_privacy_note": "Mostra o que você está ouvindo, assistindo ou lendo. Seus downloads ficam privados.","theme_label": "Tema","theme_system": "Sistema","theme_light": "Claro",@@ -602,7 +642,9 @@"download_timeout": "Download expirou. Verifique sua conexão.","size_mismatch": "Tamanho do arquivo não confere. Tente novamente.","disk_full": "Erro de escrita — seu disco pode estar cheio.",- "path_too_long": "Caminho da pasta é muito longo ({{current}}/{{limit}} caracteres). Escolha uma pasta mais curta."+ "path_too_long": "Caminho da pasta é muito longo ({{current}}/{{limit}} caracteres). Escolha uma pasta mais curta.",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "Registro de Atividade",@@ -751,9 +793,13 @@"save": "Salvar","saving": "Salvando...","cancel": "Cancelar",+ "create": "Criar",+ "clear": "Limpar","delete": "Excluir","edit": "Editar","close": "Fechar",+ "copy": "Copiar",+ "copied": "Copiado!","retry": "Tentar novamente","refresh": "Atualizar","search": "Buscar",@@ -763,10 +809,17 @@"dismiss": "Fechar","go_home": "Voltar"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source no GitHub",+ "long_pitch": "Estudar não é só PDF. É livro, podcast, aula, anotação no meio. omniget junta tudo num lugar — sem perder o ritmo trocando de janela.",+ "cta_github": "Ver no GitHub"+ },"hub": {"title": "Estudo","subtitle": "Transforme os cursos baixados em um ciclo de prática deliberada.","library": "Biblioteca",+ "music": "Música","focus": "Foco","progress": "Progresso","achievements": "Conquistas",@@ -839,8 +892,483 @@"action_vacuum_label": "Compactar banco (vacuum)","action_vacuum_hint": "Manutenção do SQLite"},+ "music": {+ "title": "Música",+ "subtitle": "Suas faixas, álbuns e playlists.",+ "library_title": "Biblioteca",+ "favorites_title": "Favoritos",+ "favorites_subtitle": "As músicas que você marcou com ❤",+ "favorites_empty": "Nada favoritado ainda. Marque uma faixa pra começar.",+ "add_root": "Adicionar pasta",+ "add_root_cta": "Adicionar pasta de música",+ "clear_covers": "Resetar capas",+ "clear_covers_hint": "Apaga o cache de capas e força re-extração no próximo scan",+ "clear_covers_confirm": "Apagar todas as capas em cache? O próximo scan vai re-extrair tudo.",+ "clear_covers_done": "{{files}} arquivos apagados · {{tracks}} faixas resetadas",+ "diagnostics": "Diagnóstico",+ "diagnostics_hint": "Mostra estado atual das capas (paths, tamanhos, contagens) — útil quando thumb não aparece",+ "diagnostics_title": "Diagnóstico de capas",+ "scan_now": "Escanear",+ "scanning": "Escaneando…",+ "scan_done": "{{added}} adicionadas · {{updated}} atualizadas · {{removed}} removidas",+ "root_added": "Pasta adicionada: {{path}}",+ "empty_no_roots_title": "Sua biblioteca de música está vazia",+ "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.",+ "empty_album": "Este álbum está vazio.",+ "shelf_continue": "Continue ouvindo",+ "shelf_albums": "Álbuns",+ "shelf_added": "Recém adicionados",+ "shelf_most_played": "Mais tocadas",+ "see_all": "Ver todos",+ "tracks_count": "{{count}} faixas",+ "eyebrow_album": "Álbum",+ "play": "Tocar",+ "pause": "Pausar",+ "prev": "Anterior",+ "next": "Próxima",+ "shuffle": "Aleatório",+ "repeat": "Repetir",+ "favorite": "Favoritar",+ "unfavorite": "Desfavoritar",+ "player_aria": "Player de música",+ "tab_tracks": "Faixas",+ "tab_albums": "Álbuns",+ "tab_artists": "Artistas",+ "search_placeholder": "Buscar título, artista, álbum…",+ "nav_home": "Início",+ "nav_library": "Biblioteca",+ "nav_favorites": "Favoritos",+ "nav_genres": "Gêneros",+ "nav_activity": "Atividade",+ "queue_clear": "Limpar",+ "eq_title": "Equalizador",+ "eq_enable": "Ativar equalizador",+ "eq_preset": "Predefinição",+ "eq_reset": "Zerar",+ "eq_preset_flat": "Plano",+ "eq_preset_bass": "Grave",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Agudo",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Clássico",+ "eq_preset_electronic": "Eletrônica",+ "eq_preset_custom": "Custom",+ "genres_title": "Gêneros",+ "genres_subtitle": "Navegue por gênero musical detectado nos seus arquivos.",+ "no_genres": "Nenhum gênero encontrado. Faixas precisam ter tag de gênero.",+ "eyebrow_genre": "Gênero",+ "albums_count": "{{count}} álbuns",+ "artists_count": "{{count}} artistas",+ "activity_title": "Sua atividade",+ "activity_subtitle": "O que você ouviu, quando, quanto.",+ "no_activity": "Sem atividade ainda nesse período. Toque algumas faixas pra começar a ver suas estatísticas.",+ "period_7d": "7 dias",+ "period_30d": "30 dias",+ "period_90d": "90 dias",+ "period_1y": "1 ano",+ "period_all": "Tudo",+ "total_plays": "Reproduções",+ "total_listened": "Tempo ouvindo",+ "unique_tracks": "Faixas únicas",+ "top_tracks": "Mais tocadas",+ "top_artists": "Artistas mais ouvidos",+ "top_albums": "Álbuns mais tocados",+ "top_genres": "Gêneros favoritos",+ "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_no_track": "Nenhuma faixa tocando",+ "lyrics_refresh": "Buscar de novo",+ "lyrics_source": "Fonte: {{source}}",+ "n_selected": "{{count}} selecionadas",+ "selection_aria": "Ações em seleção",+ "queued_count": "{{count}} adicionadas à fila",+ "favorited_count": "{{count}} marcadas como favorito",+ "add_to_queue": "Adicionar à fila",+ "ctx_show_in_folder": "Abrir pasta",+ "ctx_show_failed": "Não foi possível abrir a pasta",+ "nav_download": "Baixar",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Baixar áudio",+ "ytdlp_subtitle": "Cole uma URL (YouTube, SoundCloud, Bandcamp e qualquer site suportado pelo yt-dlp). Vai converter pra áudio na sua biblioteca.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Salvar em",+ "ytdlp_format": "Formato",+ "ytdlp_no_roots": "Adicione uma pasta de música primeiro",+ "ytdlp_start": "Baixar",+ "ytdlp_downloading": "Baixando…",+ "ytdlp_done": "Download concluído. Biblioteca atualizada.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp não encontrado",+ "ytdlp_missing_body": "Instale yt-dlp e garanta que está no PATH do sistema (https://github.com/yt-dlp/yt-dlp). No Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Fila",+ "tab_lyrics": "Letras",+ "tab_info": "Info",+ "info_no_track": "Toque uma faixa pra ver detalhes",+ "field_album": "Álbum",+ "field_year": "Ano",+ "field_genre": "Gênero",+ "field_duration": "Duração",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Reproduções",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Conecte sua conta Last.fm pra fazer scrobble do que você ouve. Precisa de um app na API deles (gratuito).",+ "lastfm_step1_title": "Crie um app na API",+ "lastfm_step1_desc": "Vá no site da Last.fm e crie uma aplicação. Você vai receber uma API key e um shared secret.",+ "lastfm_step2_title": "Cole as credenciais",+ "lastfm_step2_desc": "Cole aqui a API key e o shared secret do app que você criou.",+ "lastfm_save_keys": "Salvar credenciais",+ "lastfm_keys_saved": "Credenciais salvas",+ "lastfm_step3_title": "Autorize o acesso",+ "lastfm_step3_desc": "Abre o navegador na Last.fm pra você aprovar. Depois volte e clique em Finalizar.",+ "lastfm_authorize": "Autorizar com Last.fm",+ "lastfm_authorize_pending": "Aprove o acesso na página da Last.fm que abriu, depois clique em Finalizar:",+ "lastfm_open_auth": "Abrir página de aprovação",+ "lastfm_finalize": "Finalizar conexão",+ "lastfm_connected": "Conectado como {{username}}",+ "lastfm_connected_as": "Conectado como {{username}}",+ "lastfm_connected_hint": "Faixas tocadas por mais de 30s vão pra sua conta. Now playing atualiza em tempo real.",+ "lastfm_enable_scrobble": "Scrobble automático",+ "lastfm_disconnect": "Desconectar",+ "lastfm_disconnect_confirm": "Apagar credenciais e desconectar?",+ "lastfm_disconnected": "Desconectado",+ "dl_hero_title": "Cole uma URL ou pesquise",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, qualquer site suportado pelo yt-dlp. Vai virar áudio na sua biblioteca.",+ "dl_quality": "Qualidade",+ "dl_quality_best": "Melhor disponível",+ "dl_idle_hint": "Cole o link da faixa, do álbum ou pesquise por título. Ctrl+V cola e detecta automático.",+ "dl_detecting": "Detectando…",+ "dl_searching": "Buscando…",+ "dl_search_empty": "Nenhum resultado encontrado.",+ "dl_unsupported": "Site não reconhecido. Tente colar a URL direta da faixa.",+ "dl_preparing": "Iniciando download…",+ "dl_download_audio": "Baixar áudio",+ "dl_started": "Download iniciado",+ "dl_recent": "Downloads recentes",+ "batch_done": "{{ok}} iniciados, {{fail}} falharam",+ "music_theme_title": "Tema da Música",+ "music_theme_subtitle": "Personalize as cores da seção de música. Salvo separado do tema global do app.",+ "music_theme_preset": "Predefinição",+ "music_theme_accent": "Cor de destaque",+ "music_theme_save": "Salvar tema",+ "music_theme_reset": "Restaurar padrão",+ "music_theme_preset_default": "Padrão",+ "music_theme_preset_indigo": "Índigo",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Roxo",+ "music_theme_preset_amber": "Âmbar",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Usar cor da capa atual",+ "music_theme_dominant_off": "Cor fixa",+ "music_theme_dominant_on": "Auto (cor da capa)",+ "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",+ "rpc_disconnected": "Desconectado",+ "rpc_enable": "Mostrar atividade no Discord",+ "rpc_advanced": "Configurações avançadas",+ "rpc_appid_hint": "Application ID da sua app no Discord Developer Portal. O default é a app \"Loop\" do omniget.",+ "rpc_large_image": "Chave da imagem grande",+ "rpc_image_hint": "Nome do asset (Rich Presence Assets) que você fez upload no Discord Dev Portal. Sem o asset, a atividade aparece sem ícone.",+ "rpc_save": "Salvar",+ "rpc_saved": "Configurações salvas",+ "rpc_test": "Testar conexão",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Importe playlists do YouTube e YouTube Music. Toca direto via stream — não baixa.",+ "yt_intro": "Cole o link de qualquer playlist do YouTube ou YouTube Music. Pra playlists privadas (incluindo \"Likes\"), aponte o navegador onde você tá logado.",+ "yt_step1_title": "De qual navegador puxar os cookies?",+ "yt_step1_desc": "Pra playlists privadas e o seu Library, omniget precisa dos cookies do navegador onde você tá logado. Sem cookies, só pega playlists públicas.",+ "yt_browser_micro": "yt-dlp lê os cookies direto do navegador. Nada é enviado pra fora — fica tudo local.",+ "yt_browser_saved": "Cookies de {{browser}} configurados",+ "yt_step2_title": "Importar playlist",+ "yt_step2_desc": "Cole o link e o omniget importa a lista de faixas. Tocar é via stream sob demanda — sem baixar nada.",+ "yt_import": "Importar",+ "yt_imported": "{{title}}: {{count}} faixas importadas",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "Playlist do YouTube Music",+ "yt_yt_playlist_label": "Playlist de vídeos do YouTube",+ "yt_add_playlist": "Adicionar playlist",+ "yt_empty_title": "Nenhuma playlist ainda",+ "yt_empty_body": "Conecte uma playlist do YouTube ou YouTube Music pra ver suas faixas aqui junto com seus arquivos locais.",+ "yt_setup": "Configurar YouTube",+ "yt_refresh": "Re-importar",+ "yt_refreshed": "Atualizada: {{count}} faixas",+ "yt_remove": "Remover",+ "yt_remove_confirm": "Remover essa playlist da biblioteca? (A playlist no YouTube continua intacta.)",+ "yt_search_placeholder": "Pesquisar no YouTube Music — músicas, artistas, álbuns…",+ "yt_recs_for": "Porque você ouviu: {{name}}",+ "yt_download": "Baixar",+ "yt_download_started": "Download iniciado",+ "sc_title": "SoundCloud",+ "sc_signin_heading": "Conectar ao SoundCloud",+ "sc_signin_body": "Faça login no SoundCloud pelo navegador — a extensão do OmniGet captura os cookies automaticamente. Depois volte aqui e clique em atualizar.",+ "sc_open_in_browser": "Abrir SoundCloud no navegador",+ "sc_already_signed_in": "Já fiz login, atualizar",+ "sc_search": "Buscar",+ "sc_refresh": "Atualizar",+ "sc_logout": "Sair",+ "sc_loading": "Carregando…",+ "sc_status_client_id": "client_id",+ "sc_status_oauth": "oauth",+ "sc_import_url": "Importar por URL",+ "sc_import_url_title": "Importar de uma URL do SoundCloud",+ "sc_import_url_desc": "Cole qualquer link de faixa, playlist ou artista — a gente identifica.",+ "sc_import_url_placeholder": "https://soundcloud.com/…",+ "sc_import_action": "Importar",+ "sc_import_invalid": "Isso não parece uma URL do SoundCloud.",+ "sc_import_failed": "Não consegui resolver essa URL: {{error}}",+ "sc_import_success": "\"{{title}}\" importado",+ "sc_section_continue": "Continuar de onde parou",+ "sc_section_stream": "De quem você segue",+ "sc_section_recommended": "Porque você curtiu {{name}}",+ "sc_section_likes": "Suas curtidas ({{count}})",+ "sc_section_playlists": "Suas playlists",+ "sc_section_following": "Seguindo",+ "sc_followers_count": "{{count}} seguidores",+ "sc_track_count": "{{count}} faixas",+ "sc_download_track": "Baixar faixa",+ "sc_download_all": "Baixar tudo ({{count}})",+ "sc_download_started": "Download na fila",+ "sc_download_bulk_progress": "Baixando {{current}} de {{total}}",+ "sc_download_bulk_done": "Concluído — {{success}} baixadas, {{failed}} falharam",+ "sc_go_plus_badge": "Go+",+ "sc_go_plus_unavailable_hint": "Streams em alta qualidade exigem conta SoundCloud Go+. MP3 padrão funciona normal.",+ "sc_empty_likes_title": "Sem curtidas ainda",+ "sc_empty_likes_body": "Os corações que você dá no SoundCloud aparecem aqui.",+ "sc_empty_likes_action": "Buscar música",+ "sc_empty_playlists_title": "Nenhuma playlist",+ "sc_empty_playlists_body": "Crie ou importe uma playlist no soundcloud.com — aparece aqui na próxima atualização.",+ "sc_empty_following_title": "Você ainda não segue ninguém",+ "sc_empty_state_logged_out_action": "Ir pro SoundCloud",+ "sc_load_more": "Carregar mais",+ "sc_show_count": "Mostrando {{shown}} de {{total}}",+ "sc_skeleton_loading": "Carregando sua biblioteca…",+ "sc_offline_for_focus": "Salve offline pra tocar mesmo sem internet",+ "sc_recommended_seed_fallback": "seu gosto",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Conectado",+ "yt_state_anon": "Não conectado",+ "yt_auth_title": "Conectar à sua conta",+ "yt_auth_desc": "Pra puxar sua biblioteca privada (Likes, suas playlists), cole 2 cookies do navegador onde você tá logado no YouTube Music.",+ "yt_auth_how": "Como pegar os cookies",+ "yt_auth_step1": "Abra music.youtube.com no Chrome/Edge/Firefox logado.",+ "yt_auth_step2": "F12 → aba Application/Storage → Cookies → music.youtube.com",+ "yt_auth_step3": "Copie o valor de __Secure-3PAPISID e cole no primeiro campo.",+ "yt_auth_step4": "Na aba Network, clique em qualquer request, copie o header inteiro Cookie: e cole no segundo campo.",+ "yt_cookie_full": "Cookie completo (header)",+ "yt_cookie_hint": "Cole o header Cookie: inteiro de qualquer request pra music.youtube.com.",+ "yt_save_auth": "Salvar credenciais",+ "yt_auth_saved": "Credenciais salvas",+ "yt_disconnect": "Desconectar",+ "yt_disconnect_confirm": "Apagar credenciais salvas?",+ "yt_disconnected": "Desconectado",+ "yt_visitor_ok": "Visitor data atualizado",+ "yt_sync_title": "Sincronizar minha biblioteca",+ "yt_sync_desc": "Importa Liked Music + todas as suas playlists em batch. Roda em segundo plano. Tracks aparecem na Library / Albums / Artists junto com seus arquivos locais.",+ "yt_sync_now": "Sincronizar agora",+ "yt_syncing": "Sincronizando…",+ "yt_sync_starting": "Iniciando…",+ "yt_sync_liked": "Buscando Liked Music…",+ "yt_sync_playlists": "Buscando {{total}} playlists…",+ "yt_sync_done": "Sincronizado: {{playlists}} playlists, {{tracks}} faixas",+ "yt_ext_import": "Importar da extensão",+ "yt_ext_hint": "Pega os cookies do YouTube direto da extensão omniget instalada no seu navegador. Sem F12, sem copy-paste.",+ "yt_ext_imported": "{{count}} cookies importados da extensão",+ "yt_ext_empty": "Nenhum cookie capturado ainda. Abra music.youtube.com no navegador com a extensão omniget ativa, depois tente de novo.",+ "yt_ext_no_sapisid": "Cookies encontrados mas sem __Secure-3PAPISID. Faça login no YouTube Music e tente de novo.",+ "yt_ext_no_file": "Arquivo de cookies não existe. A extensão nunca enviou nada — verifique: (1) host omniget rodando, (2) extensão ativa, (3) Native Messaging registrado. Esperado em: {{path}}",+ "yt_ext_no_youtube": "Arquivo existe ({{age}}) mas só tem cookies de: {{domains}}. Abra music.youtube.com no navegador, aguarde 3s, tente de novo.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies importados ({{age}}) mas nenhum é __Secure-3PAPISID. Faça login no YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies importados ({{age}})",+ "yt_or_manual": "ou manualmente",+ "quality_title": "Qualidade de áudio",+ "quality_short": "Qualidade",+ "quality_intro": "Escolha como suas músicas serão baixadas. Pode trocar a qualquer momento — só afeta downloads novos.",+ "quality_current": "Atual: {{label}}",+ "quality_saved": "Qualidade ajustada para {{label}}",+ "quality_group_recommended": "Recomendado",+ "quality_group_compact": "Economizar espaço",+ "quality_group_high": "Alta qualidade",+ "quality_group_lossless": "Lossless (audiófilo)",+ "quality_hint_mp3_128": "Arquivos pequenos · ~3 MB por música · qualidade básica",+ "quality_hint_mp3_192": "Equilibrado · ~5 MB por música · toca em qualquer lugar",+ "quality_hint_mp3_320": "MP3 no máximo · ~7 MB por música · compatibilidade máxima",+ "quality_hint_aac_192": "Boa qualidade, arquivo pequeno, toca em tudo · ~5 MB por música",+ "quality_hint_aac_256": "Lossy premium · ~6 MB por música · qualidade transparente",+ "quality_hint_opus_160": "Mais eficiente · ~4 MB por música · pode não tocar em aparelhos antigos",+ "quality_hint_flac": "Sem perda · mantém o tamanho original",+ "quality_hint_flac_cd": "Lossless qualidade CD · ~30 MB por música",+ "quality_hint_flac_hires": "Qualidade de estúdio · 24-bit/96 kHz · ~80 MB por música",+ "quality_hint_wav": "PCM sem compressão · ~50 MB por música · arquivos grandes",+ "sources_title": "Fontes de música",+ "sources_short": "Fontes",+ "sources_subtitle": "Onde buscar as músicas",+ "sources_intro": "Quando você pede para o omniget buscar uma música pelo nome, ele tenta nessas fontes em ordem. Use as setas para reordenar.",+ "source_status_connected": "Conectado",+ "source_status_not_connected": "Não conectado",+ "source_status_unavailable": "Em breve",+ "source_connect": "Conectar",+ "source_inactive_header": "Fora de rotação",+ "source_reset_default": "Restaurar ordem padrão",+ "source_move_up": "Mover para cima",+ "source_move_down": "Mover para baixo",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Conectado",+ "qobuz_state_disconnected": "Não conectado",+ "qobuz_intro": "Conecte sua conta Qobuz para baixar em lossless (FLAC até 24-bit/192 kHz). Precisa de uma assinatura Qobuz ativa.",+ "qobuz_email_label": "Email do Qobuz",+ "qobuz_password_label": "Senha",+ "qobuz_pwd_show": "Mostrar senha",+ "qobuz_pwd_hide": "Ocultar senha",+ "qobuz_privacy": "Salvo só no seu computador. Nunca enviamos para servidores do omniget.",+ "qobuz_connect": "Conectar",+ "qobuz_connecting": "Conectando…",+ "qobuz_connected": "Conectado ao Qobuz",+ "qobuz_disconnected": "Desconectado do Qobuz",+ "qobuz_disconnect": "Desconectar",+ "qobuz_disconnect_confirm": "Remover credenciais salvas do Qobuz?",+ "qobuz_signed_in_as": "Logado como",+ "qobuz_connected_hint": "Qobuz já está no pool de fontes. Use o painel de Fontes para ajustar a prioridade.",+ "qobuz_test_again": "Testar conexão",+ "qobuz_testing": "Testando…",+ "qobuz_test_ok": "Login no Qobuz funcionando",+ "qobuz_test_failed": "Falha no teste: {{error}}",+ "nav_aria": "Navegação de música",+ "sidebar_hint_title": "Dica",+ "sidebar_hint_body": "A música continua tocando enquanto você navega entre Cursos, Notas e outras seções.",+ "nav_search": "Buscar",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "Você não tem playlists ainda",+ "playlists_empty_body": "Crie uma playlist pra agrupar suas faixas favoritas e ouvir em sequência.",+ "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.",+ "playlist_deleted": "Playlist apagada",+ "click_to_rename": "Clique pra renomear",+ "delete_playlist": "Apagar playlist",+ "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",+ "eyebrow_artist": "Artista",+ "discography": "Discografia",+ "queue_title": "Fila",+ "queue_aria": "Fila de reprodução",+ "queue_empty": "A fila está vazia.",+ "queue_toggle": "Alternar fila",+ "search_hint": "Digite o título de uma faixa, artista ou álbum.",+ "exit": "Sair",+ "featured_album": "Álbum em destaque",+ "by": "Por",+ "start_listening": "Começar a ouvir",+ "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.",+ "sort_added": "Adicionado",+ "sort_name": "Nome A→Z",+ "sort_year": "Ano",+ "sort_track_count": "Mais faixas",+ "manage_folders": "Gerenciar pastas",+ "roots_title": "Pastas de música",+ "roots_hint": "Pastas que escaneamos em busca de áudio. Desabilite uma pra ignorar sem apagar do disco. Remover daqui não apaga arquivo nenhum.",+ "roots_empty": "Você ainda não adicionou nenhuma pasta de música.",+ "root_missing": "sumiu",+ "root_remove": "Remover",+ "root_removed": "Pasta removida: {{path}}",+ "nav_albums": "Álbuns",+ "nav_artists": "Artistas",+ "nav_playlists": "Playlists"+ },"library": {"title": "Biblioteca",+ "subtitle": "Seus cursos, vídeos e PDFs em um só lugar.",+ "empty_browse_title": "Sua biblioteca ainda está vazia",+ "empty_browse_description": "Aponte pra suas pastas de cursos ou importe vídeos do Telegram. Nada é copiado, nada é movido.",+ "empty_add_folder_title": "Adicionar pasta de vídeos",+ "empty_add_folder_desc": "Aponte pra onde seus cursos já estão. Não copia, não move.",+ "empty_add_folder_cta": "Escolher pasta",+ "empty_telegram_title": "Importar do Telegram",+ "empty_telegram_desc": "Baixe vídeos direto de canais que você participa.",+ "empty_telegram_cta": "Conectar",+ "pinned_strip_aria": "Pastas fixadas",+ "pin_action": "Fixar",+ "pin_action_active": "Fixada",+ "pin_action_title": "Fixar esta pasta",+ "unpin_action": "Despinhar",+ "unpin_action_title": "Despinhar esta pasta",+ "pin_failed": "Falha ao fixar: {{msg}}",+ "unpin_failed": "Falha ao despinhar: {{msg}}",+ "siblings_aria": "Pastas-irmãs",+ "siblings_empty": "Sem pastas-irmãs",+ "view_mode_aria": "Modo de visualização",+ "view_mode_grid": "Grade",+ "view_mode_list": "Lista",+ "back_toast": "De volta a {{folder}}",+ "address_bar_placeholder": "Cole ou digite um caminho…",+ "address_bar_open": "Editar caminho",+ "new_folder": "Nova pasta",+ "new_folder_placeholder": "Nome da pasta",+ "ctx_open": "Abrir",+ "ctx_rename": "Renomear",+ "ctx_delete": "Apagar (Lixeira)",+ "ctx_show_in_explorer": "Mostrar no Explorer",+ "delete_confirm_title": "Mover pra Lixeira?",+ "delete_confirm_msg_folder": "A pasta \"{{name}}\" e tudo dentro dela vão pra Lixeira do sistema.",+ "delete_confirm_msg_file": "\"{{name}}\" vai pra Lixeira do sistema.",+ "delete_confirm_btn": "Mover pra Lixeira",+ "delete_toast_done": "\"{{name}}\" foi pra Lixeira",+ "last_watched_label": "Último visto",+ "roots_button_hint": "Pastas que a Biblioteca varre em busca de cursos e vídeos",+ "empty_with_roots_one": "Detectamos 1 pasta configurada mas nenhum curso indexado ainda.",+ "empty_with_roots_other": "Detectamos {{count}} pastas configuradas mas nenhum curso indexado ainda.",+ "empty_with_roots_cta": "Rescanear agora",+ "pin_added_toast": "\"{{name}}\" fixada",+ "pin_removed_toast": "Pin removido",+ "root_missing_label": "sumiu",+ "root_missing_hint": "Drive desplugado? Pasta apagada? Reconecte ou remova daqui.",+ "mode_telegram_disconnected_suffix": "(não conectado)",+ "browse_sort_label": "Ordenar",+ "browse_sort_name_asc": "Nome A→Z",+ "browse_sort_name_desc": "Nome Z→A",+ "browse_sort_size_desc": "Tamanho",+ "browse_sort_recent": "Modificado",+ "selection_count_one": "1 selecionado",+ "selection_count_other": "{{count}} selecionados",+ "selection_clear": "Limpar seleção",+ "selection_delete": "Apagar selecionados",+ "selection_delete_confirm_title": "Apagar {{count}} item(s)?",+ "selection_delete_confirm_msg": "Os itens vão pra Lixeira do sistema. Você pode restaurar de lá se mudar de ideia.",+ "selection_delete_done": "{{count}} item(s) movidos pra Lixeira",+ "selection_delete_partial": "{{ok}} OK · {{fail}} falharam",+ "open_in_new_tab": "Abrir em nova aba",+ "tab_close": "Fechar aba",+ "tab_new": "Nova aba","empty": "Nenhum curso indexado. Rode uma varredura em Configurações.","error_loading_notes": "Não foi possível carregar suas notas. Tente recarregar ou entre em contato com o suporte.","health_title": "Saúde da biblioteca",@@ -874,7 +1402,6 @@"status_in_progress": "Em progresso","status_not_started": "Não iniciados","status_completed": "Concluídos",- "view_mode_aria": "Modo de visualização","status_aria": "Status","cleanup_btn": "Limpar entradas órfãs","cleanup_orphan_delete": "Apagar arquivo",@@ -930,8 +1457,8 @@"recent": "Recentes","history": "Histórico","history_empty": "Sem atividade recente",- "mode_browse": "Pastas",- "mode_courses": "Cursos",+ "mode_browse": "Pastas e arquivos",+ "mode_courses": "Meus cursos","browse_empty": "Pasta vazia.","videos": "vídeos","roots": "Raízes da biblioteca",@@ -942,7 +1469,7 @@"kind_media_badge": "Vídeo","favorite": "Favorito","resume": "Retomar",- "roots_button": "Pastas",+ "roots_button": "Onde buscar","roots_add_btn": "Adicionar pasta","roots_remove": "Remover","roots_remove_tooltip": "Remover esta pasta",@@ -962,7 +1489,7 @@"watch_back": "Voltar para biblioteca","watch_not_found": "Nenhum vídeo selecionado.","watch_file_missing": "Arquivo não encontrado.",- "mode_telegram": "Telegram",+ "mode_telegram": "Importar do Telegram","telegram": {"plugin_missing_title": "Plugin Telegram não encontrado","plugin_missing_body": "Instale o plugin Telegram pelo marketplace pra acessar seus chats aqui.",@@ -1151,7 +1678,27 @@"watched": "Assistido","resume_at": "Retomar em {{time}}","player_speed": "Velocidade"- }+ },+ "home_continue_title": "Continue de onde parou",+ "home_continue_eyebrow": "Recente",+ "home_continue_empty": "Nenhum curso em progresso ainda. Comece uma aula para aparecer aqui.",+ "home_continue_next": "Próxima: {{title}}",+ "home_continue_current": "Em: {{title}}",+ "home_news_title": "Com novidades",+ "home_news_eyebrow": "Aulas novas",+ "home_news_count_one": "{{count}} aula nova",+ "home_news_count_other": "{{count}} aulas novas",+ "home_recently_title": "Recém-adicionados",+ "home_recently_eyebrow": "Novos",+ "home_platform_eyebrow": "Plataforma",+ "home_subject_eyebrow": "Matéria",+ "home_empty_title": "Sua biblioteca está vazia",+ "home_empty_desc": "Adicione uma pasta com cursos para começar.",+ "home_empty_cta": "Adicionar pasta com cursos",+ "home_load_error": "Falha ao carregar biblioteca: {{error}}",+ "view_home": "Início",+ "view_catalog": "Catálogo",+ "platform_generic": "Outras plataformas"},"player": {"title": "Player",@@ -1191,7 +1738,13 @@"theater_on": "Sair do modo cinema","theater_off": "Modo cinema","theater_hint": "Esconde sidebar e painéis (T)",- "description_title": "Descrição"+ "description_title": "Descrição",+ "clip": "Clipar últimos 60s",+ "clip_loading": "Clipando…",+ "clip_done": "Clip salvo",+ "clip_failed": "Falha ao clipar",+ "clip_no_video": "Vídeo ainda não carregou",+ "clip_aria": "Salvar últimos 60 segundos como clip"},"notes": {"title": "Notas",@@ -1271,11 +1824,58 @@"filter_xp": "XP","filter_lessons": "Aulas","filter_focus": "Foco",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "bronze",+ "tier_silver": "prata",+ "tier_gold": "ouro",+ "unlocked_prefix": "desbloqueado",+ "reset_done": "Reset feito",+ "reset_confirm_label": "Reset",+ "filter_aria": "Filtros de categoria",+ "tree_link": "Árvore",+ "charts_link": "Gráficos",+ "label_xp_100": "Primeiros 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "Mil XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "Primeira aula",+ "label_lessons_10": "10 aulas",+ "label_lessons_50": "50 aulas",+ "label_lessons_100": "100 aulas",+ "label_focus_60": "1h focado",+ "label_focus_600": "10h focado",+ "label_focus_6000": "100h focado",+ "label_streak_3": "3 dias seguidos",+ "label_streak_7": "1 semana de streak",+ "label_streak_30": "30 dias de streak",+ "label_streak_100": "100 dias de streak",+ "desc_xp_100": "Acumule 100 XP estudando",+ "desc_xp_500": "Acumule 500 XP",+ "desc_xp_1000": "Marca dos 1000 XP",+ "desc_xp_5000": "Cinco mil XP acumulados",+ "desc_xp_10000": "Dez mil XP — você é dedicado",+ "desc_lessons_1": "Complete sua primeira aula",+ "desc_lessons_10": "Complete 10 aulas",+ "desc_lessons_50": "Meio centenário de aulas",+ "desc_lessons_100": "Cem aulas concluídas",+ "desc_focus_60": "60 minutos de foco acumulados",+ "desc_focus_600": "600 minutos de foco acumulados",+ "desc_focus_6000": "6000 minutos de foco — disciplina rara",+ "desc_streak_3": "Mantenha streak por 3 dias",+ "desc_streak_7": "7 dias consecutivos estudando",+ "desc_streak_30": "Um mês inteiro de consistência",+ "desc_streak_100": "Hábito de aço"},"focus": {"title": "Foco","placeholder": "Sessões Pomodoro e de deep work ficam aqui.",+ "intent_label": "Pra que essa sessão?",+ "intent_prefix": "Estudando",+ "intent_placeholder": "tese, certificação, livro de filosofia...",+ "intent_hint": "Aparece no seu Discord se RPC estiver ligado. Pode deixar vazio.",+ "intent_for": "estudando",+ "rpc_default": "Sessão de foco","preset_pomodoro": "Pomodoro","preset_short_break": "Pausa curta","preset_long_break": "Pausa longa",@@ -1347,7 +1947,34 @@"stop_body": "A sessão será marcada como interrompida e não contará nas estatísticas.","stop_confirm": "Interromper","active_preset_label": "Em foco",- "session_ended": "Sessão concluída"+ "session_ended": "Sessão concluída",+ "settings_saving": "salvando…",+ "settings_saved": "salvo ✓",+ "acc_cycles_title": "Ciclos",+ "acc_cycles_summary": "{{focus}}min foco · {{break}}min pausa · {{cycles}}× até pausa longa",+ "acc_cycles_focus": "Foco (min)",+ "acc_cycles_short": "Pausa curta (min)",+ "acc_cycles_long": "Pausa longa (min)",+ "acc_cycles_count": "Ciclos antes da pausa longa",+ "acc_breaks_title": "Pausas & auto-start",+ "acc_breaks_auto_yes": "auto-pausa",+ "acc_breaks_auto_no": "manual",+ "acc_breaks_focus_yes": "auto-retomada",+ "acc_breaks_focus_no": "manual",+ "acc_breaks_player_yes": "pausa player",+ "acc_breaks_player_no": "ignora player",+ "acc_breaks_check_breaks": "Iniciar pausas automaticamente após o foco",+ "acc_breaks_check_focus": "Retomar foco automaticamente após pausa",+ "acc_breaks_check_player": "Pausar vídeo durante pausa de foco",+ "acc_sounds_title": "Sons & notificação",+ "acc_sounds_notify_on": "notificação ON",+ "acc_sounds_notify_off": "silencioso",+ "acc_sounds_sound_on": "som {{n}}%",+ "acc_sounds_sound_off": "sem som",+ "acc_sounds_check_notify": "Notificação ao terminar ciclo",+ "acc_sounds_check_sound": "Tocar som ao terminar",+ "acc_sounds_volume": "Volume ({{n}}%)",+ "unlimited_aria": "livre"},"subjects": {"title": "Disciplinas",@@ -1439,7 +2066,45 @@"chart_explore_library": "Explorar biblioteca","chart_review_weak": "Revisar cards fracos","chart_adjust_goals": "Ajustar metas",- "streak_best": "melhor: {{n}}"+ "streak_best": "melhor: {{n}}",+ "chart_time_per_course": "Tempo por curso",+ "chart_time_per_course_empty": "Sem tempo registrado nesse período.",+ "chart_time_period_days": "últimos {{n}} dias",+ "chart_activity_by_hour": "Atividade por hora",+ "chart_activity_hint": "soma de focos · 24h",+ "chart_activity_empty": "Sem atividade nas últimas {{n}} dias.",+ "chart_subject": "Por disciplina",+ "chart_subject_unit": "minutos focados",+ "chart_subject_empty": "Crie disciplinas e atribua sessões para ver breakdown.",+ "chart_subject_unassigned": "Sem disciplina",+ "retention_title": "Retenção (Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "Retenção real virá da query cross-DB do Anki. Por ora, abra",+ "retention_link": "Estatísticas Anki →",+ "retention_stub_after": "para ver retenção, distribuição de intervalos e histórico de revisões.",+ "recent_achievements": "Conquistas recentes",+ "view_all": "Ver todas →",+ "time_today": "hoje",+ "time_yesterday": "ontem",+ "time_days_ago": "{{n}} dias atrás",+ "time_months_ago": "{{n}} meses atrás",+ "time_years_ago": "{{n}} anos atrás",+ "ach_label_xp_100": "100 XP acumulados",+ "ach_label_xp_500": "500 XP acumulados",+ "ach_label_xp_1000": "1.000 XP acumulados",+ "ach_label_xp_5000": "5.000 XP acumulados",+ "ach_label_xp_10000": "10.000 XP acumulados",+ "ach_label_lessons_1": "Primeira aula",+ "ach_label_lessons_10": "10 aulas concluídas",+ "ach_label_lessons_50": "50 aulas concluídas",+ "ach_label_lessons_100": "100 aulas concluídas",+ "ach_label_focus_60": "1 hora de foco",+ "ach_label_focus_600": "10 horas de foco",+ "ach_label_focus_6000": "100 horas de foco",+ "ach_label_streak_3": "Streak de 3 dias",+ "ach_label_streak_7": "Streak de 1 semana",+ "ach_label_streak_30": "Streak de 30 dias",+ "ach_label_streak_100": "Streak de 100 dias"},"settings": {"title": "Configurações",@@ -1718,7 +2383,15 @@"annas_warning_modal_line4": "Marque a caixa abaixo se você entende e aceita responsabilidade pessoal pelo seu uso.","annas_warning_ack_label": "Entendo. Assumo total responsabilidade pelo meu uso na minha jurisdição.","annas_warning_cancel": "Cancelar",- "annas_warning_confirm": "Ativar Alt Library"+ "annas_warning_confirm": "Ativar Alt Library",+ "search_notes_btn": "Buscar anotações",+ "downloads_btn": "Downloads",+ "enrich_no_results": "Nenhum resultado. Tente editar o título do livro antes.",+ "enrich_done": "✓ Metadados atualizados",+ "enrich_field_title": "Título:",+ "enrich_field_author": "Autor:",+ "enrich_field_publisher": "Editora:",+ "enrich_field_cover": "Capa (baixar)"},"bulk": {"select_all": "Selecionar tudo",diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex 64610698..911cabd0 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "顯示另外 {{count}} 項","open_folder": "在資料夾中顯示",+ "open_in_study": "Watch in Study","stop": "停止","confirm_remove": "移除此下载?","stats_line": "{{count}} 次下载 · 已保存 {{size}}",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "從 YouTube 影片中剪除贊助、片頭、片尾片段(社群資料;可能遺漏或過度剪除)","split_by_chapters": "依章節分割影片","split_by_chapters_desc": "當影片含有章節標記時,將每個章節儲存為獨立檔案",+ "presets": "快速預設",+ "presets_desc": "一鍵套用常用設定。點擊卡片即可套用。",+ "preset_fast": "快速",+ "preset_fast_desc": "480p · 無中繼資料 · 無字幕",+ "preset_quality": "高品質",+ "preset_quality_desc": "最佳影片 · 中繼資料 · 縮圖",+ "preset_compact": "精簡",+ "preset_compact_desc": "720p · 中繼資料 · 無縮圖",+ "preset_music_only": "僅音樂",+ "preset_music_only_desc": "音訊 · ID3 標籤 · 封面","hotkey_enabled": "全域快捷鍵","hotkey_enabled_desc": "使用鍵盤快捷鍵下載剪貼簿中的 URL","hotkey_binding": "快捷鍵","hotkey_record": "錄製","hotkey_type": "類型","hotkey_press": "請按下按鍵...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "使用快捷鍵下載後複製檔案到剪貼簿","copy_to_clipboard_on_hotkey_desc": "下載完成後自動將檔案複製到剪貼簿,方便貼上","filename_template": "檔名範本",@@ -326,7 +343,25 @@"cat_downloads": "下载","cat_network": "网络","cat_advanced": "高级",- "search_placeholder": "搜尋設定..."+ "search_placeholder": "搜尋設定...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "在 Discord 個人資料上顯示您的活動。切換活動時計時器不會重置。",+ "enable": "在 Discord 上顯示活動",+ "privacy_note": "顯示您正在聆聽、觀看或閱讀的內容。下載內容保持私密。",+ "test": "測試連線",+ "test_desc": "傳送測試活動以驗證 Discord 是否執行中。",+ "test_button": "傳送測試",+ "test_ok": "已連線到 Discord",+ "test_fail": "無法連線到 Discord。請確認 Discord 已執行。",+ "saved": "已儲存",+ "save": "儲存",+ "advanced": "進階",+ "app_id": "應用程式 ID",+ "app_id_hint": "Discord 應用程式 ID。除非您知道在做什麼,否則請勿變更。",+ "large_image": "大圖鍵",+ "large_image_hint": "上傳至 Discord 應用程式的資源名稱。"+ }},"omnibox": {"placeholder": "貼上 URL、磁力連結、.torrent,或搜尋",@@ -554,6 +589,11 @@"hotkey_desc": "复制任何视频链接,按下快捷键,OmniGet 立即开始下载——即使最小化。","hotkey_on": "已启用","hotkey_off": "已停用",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "在 Discord 個人資料中顯示您正在使用 OmniGet — 包括您正在聆聽、觀看或閱讀的內容。",+ "rpc_on": "已啟用",+ "rpc_off": "已停用",+ "rpc_privacy_note": "顯示您正在聆聽、觀看或閱讀的內容。下載內容保持私密。","theme_label": "主题","theme_system": "跟随系统","theme_light": "浅色",@@ -602,7 +642,9 @@"download_timeout": "下载超时。请检查您的互联网连接。","size_mismatch": "下载的文件大小不匹配。请重试。","disk_full": "写入错误 — 您的磁盘可能已满。",- "path_too_long": "下載資料夾路徑過長 ({{current}}/{{limit}} 字元)。請選擇更短的資料夾。"+ "path_too_long": "下載資料夾路徑過長 ({{current}}/{{limit}} 字元)。請選擇更短的資料夾。",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "活動記錄",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "學習","subtitle": "把下載的課程變成刻意練習的循環。","library": "課程庫",+ "music": "Music","focus": "專注","progress": "進度","achievements": "成就",@@ -839,8 +892,437 @@"action_vacuum_label": "壓縮資料庫 (vacuum)","action_vacuum_hint": "SQLite 維護"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "靛藍",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "課程庫",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "檢視模式",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "尚未索引任何課程。請從設定中執行掃描。","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "進行中","status_not_started": "未開始","status_completed": "已完成",- "view_mode_aria": "檢視模式","status_aria": "狀態","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "從上次離開的地方繼續",+ "home_continue_eyebrow": "最近",+ "home_continue_empty": "還沒有進行中的課程。開始一節課就會出現在這裡。",+ "home_continue_next": "下一節:{{title}}",+ "home_continue_current": "正在學:{{title}}",+ "home_news_title": "有更新",+ "home_news_eyebrow": "新課程",+ "home_news_count_one": "{{count}} 節新課",+ "home_news_count_other": "{{count}} 節新課",+ "home_recently_title": "最近新增",+ "home_recently_eyebrow": "新增",+ "home_platform_eyebrow": "平台",+ "home_subject_eyebrow": "學科",+ "home_empty_title": "你的資料庫是空的",+ "home_empty_desc": "新增一個包含課程的資料夾開始。",+ "home_empty_cta": "新增課程資料夾",+ "home_load_error": "載入資料庫失敗:{{error}}",+ "view_home": "主頁",+ "view_catalog": "目錄",+ "platform_generic": "其他平台"},"player": {"title": "播放器",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "剪輯最後60秒",+ "clip_loading": "剪輯中…",+ "clip_done": "剪輯已儲存",+ "clip_failed": "剪輯失敗",+ "clip_no_video": "影片尚未載入",+ "clip_aria": "將最後60秒儲存為剪輯"},"notes": {"title": "筆記",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "銅",+ "tier_silver": "銀",+ "tier_gold": "金",+ "unlocked_prefix": "已解鎖",+ "reset_done": "重置完成",+ "reset_confirm_label": "重置",+ "filter_aria": "類別篩選",+ "tree_link": "樹",+ "charts_link": "圖表",+ "label_xp_100": "首個 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "千 XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "第一節課",+ "label_lessons_10": "10 節課",+ "label_lessons_50": "50 節課",+ "label_lessons_100": "100 節課",+ "label_focus_60": "1 小時專注",+ "label_focus_600": "10 小時專注",+ "label_focus_6000": "100 小時專注",+ "label_streak_3": "連續 3 天",+ "label_streak_7": "1 週連續",+ "label_streak_30": "30 天連續",+ "label_streak_100": "100 天連續",+ "desc_xp_100": "透過學習獲得 100 XP",+ "desc_xp_500": "獲得 500 XP",+ "desc_xp_1000": "1000 XP 里程碑",+ "desc_xp_5000": "累積五千 XP",+ "desc_xp_10000": "累積一萬 XP — 你很專注",+ "desc_lessons_1": "完成你的第一節課",+ "desc_lessons_10": "完成 10 節課",+ "desc_lessons_50": "半個世紀的課程",+ "desc_lessons_100": "完成一百節課",+ "desc_focus_60": "累積 60 分鐘專注",+ "desc_focus_600": "累積 600 分鐘專注",+ "desc_focus_6000": "累積 6000 分鐘專注 — 罕見的自律",+ "desc_streak_3": "保持 3 天連續",+ "desc_streak_7": "連續學習 7 天",+ "desc_streak_30": "整整一個月的堅持",+ "desc_streak_100": "鋼鐵般的習慣"},"focus": {"title": "專注","placeholder": "番茄鐘和深度工作工作階段在此進行。",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "番茄鐘 (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "儲存中…",+ "settings_saved": "已儲存 ✓",+ "acc_cycles_title": "循環",+ "acc_cycles_summary": "{{focus}}分鐘專注 · {{break}}分鐘休息 · {{cycles}}× 直到長休息",+ "acc_cycles_focus": "專注(分鐘)",+ "acc_cycles_short": "短休息(分鐘)",+ "acc_cycles_long": "長休息(分鐘)",+ "acc_cycles_count": "長休息前的循環數",+ "acc_breaks_title": "休息與自動開始",+ "acc_breaks_auto_yes": "自動暫停",+ "acc_breaks_auto_no": "手動",+ "acc_breaks_focus_yes": "自動恢復",+ "acc_breaks_focus_no": "手動",+ "acc_breaks_player_yes": "暫停播放器",+ "acc_breaks_player_no": "忽略播放器",+ "acc_breaks_check_breaks": "專注後自動開始休息",+ "acc_breaks_check_focus": "休息後自動恢復專注",+ "acc_breaks_check_player": "專注休息時暫停影片",+ "acc_sounds_title": "聲音與通知",+ "acc_sounds_notify_on": "通知開啟",+ "acc_sounds_notify_off": "靜音",+ "acc_sounds_sound_on": "聲音 {{n}}%",+ "acc_sounds_sound_off": "無聲音",+ "acc_sounds_check_notify": "循環結束時通知",+ "acc_sounds_check_sound": "結束時播放聲音",+ "acc_sounds_volume": "音量 ({{n}}%)",+ "unlimited_aria": "無限"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "每門課程的時間",+ "chart_time_per_course_empty": "本週期內沒有時間紀錄。",+ "chart_time_period_days": "最近 {{n}} 天",+ "chart_activity_by_hour": "依小時活動",+ "chart_activity_hint": "專注總和 · 24小時",+ "chart_activity_empty": "最近 {{n}} 天沒有活動。",+ "chart_subject": "依學科",+ "chart_subject_unit": "專注分鐘",+ "chart_subject_empty": "建立學科並分配工作階段以檢視細分。",+ "chart_subject_unassigned": "無學科",+ "retention_title": "記憶保留(Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "真實的保留率將來自 Anki 跨資料庫查詢。目前請開啟",+ "retention_link": "Anki 統計 →",+ "retention_stub_after": "查看保留率、間隔分佈和複習歷史。",+ "recent_achievements": "最近的成就",+ "view_all": "檢視全部 →",+ "time_today": "今天",+ "time_yesterday": "昨天",+ "time_days_ago": "{{n}} 天前",+ "time_months_ago": "{{n}} 個月前",+ "time_years_ago": "{{n}} 年前",+ "ach_label_xp_100": "已累積 100 XP",+ "ach_label_xp_500": "已累積 500 XP",+ "ach_label_xp_1000": "已累積 1,000 XP",+ "ach_label_xp_5000": "已累積 5,000 XP",+ "ach_label_xp_10000": "已累積 10,000 XP",+ "ach_label_lessons_1": "第一節課",+ "ach_label_lessons_10": "完成 10 節課",+ "ach_label_lessons_50": "完成 50 節課",+ "ach_label_lessons_100": "完成 100 節課",+ "ach_label_focus_60": "1 小時專注",+ "ach_label_focus_600": "10 小時專注",+ "ach_label_focus_6000": "100 小時專注",+ "ach_label_streak_3": "3 天連續",+ "ach_label_streak_7": "1 週連續",+ "ach_label_streak_30": "30 天連續",+ "ach_label_streak_100": "100 天連續"},"settings": {"title": "設定",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "搜尋筆記",+ "downloads_btn": "下載",+ "enrich_no_results": "無結果。請先嘗試編輯書籍標題。",+ "enrich_done": "✓ 元資料已更新",+ "enrich_field_title": "標題:",+ "enrich_field_author": "作者:",+ "enrich_field_publisher": "出版社:",+ "enrich_field_cover": "封面(下載)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex 1d7ad84f..c5f3a2a9 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -70,6 +70,7 @@"clear_confirm": "Clear all finished downloads?","show_more": "显示更多 {{count}} 项","open_folder": "在文件夹中显示",+ "open_in_study": "Watch in Study","stop": "停止","confirm_remove": "移除此下载?","stats_line": "{{count}} 次下载 · 已保存 {{size}}",@@ -194,6 +195,7 @@"lang_ja": "日本語","lang_it": "Italiano","lang_fr": "Français",+ "lang_es": "Español","lang_el": "Ελληνικά"},"download": {@@ -225,12 +227,27 @@"youtube_sponsorblock_desc": "从 YouTube 视频中剪除广告、片头、片尾等赞助片段(社区数据;可能遗漏或误剪)","split_by_chapters": "按章节分割视频","split_by_chapters_desc": "当视频包含章节标记时,将每个章节保存为单独的文件",+ "presets": "快速预设",+ "presets_desc": "一键应用常用配置。点击卡片即可应用。",+ "preset_fast": "快速",+ "preset_fast_desc": "480p · 无元数据 · 无字幕",+ "preset_quality": "高质量",+ "preset_quality_desc": "最佳视频 · 元数据 · 缩略图",+ "preset_compact": "紧凑",+ "preset_compact_desc": "720p · 元数据 · 无缩略图",+ "preset_music_only": "仅音乐",+ "preset_music_only_desc": "音频 · ID3 标签 · 封面","hotkey_enabled": "全局快捷键","hotkey_enabled_desc": "通过键盘快捷键下载剪贴板中的链接","hotkey_binding": "快捷键","hotkey_record": "录制","hotkey_type": "输入","hotkey_press": "按下快捷键...",+ "music_hotkey_enabled": "Music download hotkey",+ "music_hotkey_enabled_desc": "Download clipboard URL as audio with a keyboard shortcut (uses Music Format below)",+ "music_hotkey_binding": "Music hotkey shortcut",+ "music_audio_format": "Music download format",+ "music_audio_format_desc": "Audio format used by the music hotkey and the Music plugin downloader","copy_to_clipboard_on_hotkey": "快捷键下载后复制文件到剪贴板","copy_to_clipboard_on_hotkey_desc": "自动将下载的文件复制到剪贴板以便粘贴","filename_template": "文件名模板",@@ -326,7 +343,25 @@"cat_downloads": "下载","cat_network": "网络","cat_advanced": "高级",- "search_placeholder": "搜索设置..."+ "search_placeholder": "搜索设置...",+ "rpc": {+ "title": "Discord Rich Presence",+ "desc": "在 Discord 个人资料上显示您的活动。切换活动时计时器不会重置。",+ "enable": "在 Discord 上显示活动",+ "privacy_note": "显示您正在听、看或读的内容。下载内容保持私密。",+ "test": "测试连接",+ "test_desc": "发送测试活动以验证 Discord 正在运行。",+ "test_button": "发送测试",+ "test_ok": "已连接到 Discord",+ "test_fail": "无法连接到 Discord。请确保 Discord 正在运行。",+ "saved": "已保存",+ "save": "保存",+ "advanced": "高级",+ "app_id": "应用 ID",+ "app_id_hint": "Discord 应用 ID。如不确定请勿更改。",+ "large_image": "大图键",+ "large_image_hint": "上传到 Discord 应用的资源名称。"+ }},"omnibox": {"placeholder": "粘贴链接或搜索",@@ -554,6 +589,11 @@"hotkey_desc": "复制任何视频链接,按下快捷键,OmniGet 立即开始下载——即使最小化。","hotkey_on": "已启用","hotkey_off": "已停用",+ "rpc_title": "Discord Rich Presence",+ "rpc_desc": "在 Discord 个人资料中显示您正在使用 OmniGet — 包括您正在听、看或读的内容。",+ "rpc_on": "已启用",+ "rpc_off": "已停用",+ "rpc_privacy_note": "显示您正在听、看或读的内容。下载内容保持私密。","theme_label": "主题","theme_system": "跟随系统","theme_light": "浅色",@@ -602,7 +642,9 @@"download_timeout": "下载超时。请检查您的互联网连接。","size_mismatch": "下载的文件大小不匹配。请重试。","disk_full": "写入错误 — 您的磁盘可能已满。",- "path_too_long": "下载文件夹路径过长 ({{current}}/{{limit}} 字符)。请选择更短的文件夹。"+ "path_too_long": "下载文件夹路径过长 ({{current}}/{{limit}} 字符)。请选择更短的文件夹。",+ "console_encoding": "Console encoding issue (non-UTF-8 locale). Update yt-dlp in Settings → Dependencies, or run \"chcp 65001\" in a terminal and reopen the app.",+ "extractor_broken": "The site extractor is broken. Update yt-dlp in Settings → Dependencies, then retry."},"debug": {"title": "活动日志",@@ -751,9 +793,13 @@"save": "Save","saving": "Saving...","cancel": "Cancel",+ "create": "Create",+ "clear": "Clear","delete": "Delete","edit": "Edit","close": "Close",+ "copy": "Copy",+ "copied": "Copied!","retry": "Retry","refresh": "Refresh","search": "Search",@@ -763,10 +809,17 @@"dismiss": "Dismiss","go_home": "Back"},+ "about": {+ "eyebrow": "omniget · open-source",+ "short_pitch": "Open-source on GitHub",+ "long_pitch": "Studying isn't just PDFs. It's books, podcasts, lessons, scribbled notes in between. omniget bundles all of it — without losing your flow switching windows.",+ "cta_github": "See on GitHub"+ },"hub": {"title": "学习","subtitle": "把下载的课程变成刻意练习的循环。","library": "课程库",+ "music": "Music","focus": "专注","progress": "进度","achievements": "成就",@@ -839,8 +892,437 @@"action_vacuum_label": "压缩数据库 (vacuum)","action_vacuum_hint": "SQLite 维护"},+ "music": {+ "title": "Music",+ "subtitle": "Your tracks, albums and playlists.",+ "library_title": "Library",+ "favorites_title": "Favorites",+ "favorites_subtitle": "Tracks you marked with ❤",+ "favorites_empty": "Nothing favorited yet. Mark a track to start.",+ "add_root": "Add folder",+ "add_root_cta": "Add music folder",+ "clear_covers": "Reset covers",+ "clear_covers_hint": "Wipes the cover cache and forces re-extraction on next scan",+ "clear_covers_confirm": "Delete all cached covers? Next scan will re-extract them.",+ "clear_covers_done": "{{files}} files deleted · {{tracks}} tracks reset",+ "diagnostics": "Diagnostics",+ "diagnostics_hint": "Shows current cover state (paths, sizes, counts) — useful when thumbs don't show",+ "diagnostics_title": "Cover diagnostics",+ "scan_now": "Scan",+ "scanning": "Scanning…",+ "scan_done": "{{added}} added · {{updated}} updated · {{removed}} removed",+ "root_added": "Folder added: {{path}}",+ "empty_no_roots_title": "Your music library is empty",+ "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.",+ "empty_album": "This album is empty.",+ "shelf_continue": "Continue listening",+ "shelf_albums": "Albums",+ "shelf_added": "Recently added",+ "shelf_most_played": "Most played",+ "see_all": "See all",+ "tracks_count": "{{count}} tracks",+ "eyebrow_album": "Album",+ "play": "Play",+ "pause": "Pause",+ "prev": "Previous",+ "next": "Next",+ "shuffle": "Shuffle",+ "repeat": "Repeat",+ "favorite": "Favorite",+ "unfavorite": "Unfavorite",+ "player_aria": "Music player",+ "tab_tracks": "Tracks",+ "tab_albums": "Albums",+ "tab_artists": "Artists",+ "search_placeholder": "Search title, artist, album…",+ "nav_home": "Home",+ "nav_library": "Library",+ "nav_favorites": "Favorites",+ "nav_genres": "Genres",+ "nav_activity": "Activity",+ "queue_clear": "Clear",+ "eq_title": "Equalizer",+ "eq_enable": "Enable equalizer",+ "eq_preset": "Preset",+ "eq_reset": "Reset",+ "eq_preset_flat": "Flat",+ "eq_preset_bass": "Bass",+ "eq_preset_vocal": "Vocal",+ "eq_preset_treble": "Treble",+ "eq_preset_rock": "Rock",+ "eq_preset_pop": "Pop",+ "eq_preset_classical": "Classical",+ "eq_preset_electronic": "Electronic",+ "eq_preset_custom": "Custom",+ "genres_title": "Genres",+ "genres_subtitle": "Browse by music genre detected in your files.",+ "no_genres": "No genres found. Tracks need a genre tag.",+ "eyebrow_genre": "Genre",+ "albums_count": "{{count}} albums",+ "artists_count": "{{count}} artists",+ "activity_title": "Your activity",+ "activity_subtitle": "What you listened, when, how much.",+ "no_activity": "No activity in this period yet. Play some tracks to start seeing stats.",+ "period_7d": "7 days",+ "period_30d": "30 days",+ "period_90d": "90 days",+ "period_1y": "1 year",+ "period_all": "All time",+ "total_plays": "Plays",+ "total_listened": "Time listened",+ "unique_tracks": "Unique tracks",+ "top_tracks": "Top tracks",+ "top_artists": "Top artists",+ "top_albums": "Top albums",+ "top_genres": "Top genres",+ "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_no_track": "No track playing",+ "lyrics_refresh": "Fetch again",+ "lyrics_source": "Source: {{source}}",+ "n_selected": "{{count}} selected",+ "selection_aria": "Selection actions",+ "queued_count": "{{count}} queued",+ "favorited_count": "{{count}} favorited",+ "add_to_queue": "Add to queue",+ "ctx_show_in_folder": "Open folder",+ "ctx_show_failed": "Could not open folder",+ "nav_download": "Download",+ "nav_spotify": "Spotify",+ "nav_soundcloud": "SoundCloud",+ "ytdlp_title": "Download audio",+ "ytdlp_subtitle": "Paste a URL (YouTube, SoundCloud, Bandcamp, anything yt-dlp supports). Will convert to audio in your library.",+ "ytdlp_url": "URL",+ "ytdlp_target": "Save to",+ "ytdlp_format": "Format",+ "ytdlp_no_roots": "Add a music folder first",+ "ytdlp_start": "Download",+ "ytdlp_downloading": "Downloading…",+ "ytdlp_done": "Download complete. Library refreshed.",+ "ytdlp_log": "Log",+ "ytdlp_missing_title": "yt-dlp not found",+ "ytdlp_missing_body": "Install yt-dlp and make sure it's on your system PATH (https://github.com/yt-dlp/yt-dlp). On Windows: winget install yt-dlp.yt-dlp.",+ "ytdlp_bin": "yt-dlp: {{path}}",+ "tab_queue": "Queue",+ "tab_lyrics": "Lyrics",+ "tab_info": "Info",+ "info_no_track": "Play a track to see details",+ "field_album": "Album",+ "field_year": "Year",+ "field_genre": "Genre",+ "field_duration": "Duration",+ "field_bitrate": "Bitrate",+ "field_samplerate": "Sample rate",+ "field_plays": "Plays",+ "lastfm_title": "Last.fm",+ "lastfm_intro": "Connect your Last.fm account to scrobble what you play. You'll need to create a free API app.",+ "lastfm_step1_title": "Create an API app",+ "lastfm_step1_desc": "Go to Last.fm and create an application. You'll get an API key and a shared secret.",+ "lastfm_step2_title": "Paste credentials",+ "lastfm_step2_desc": "Paste the API key and shared secret from the app you created.",+ "lastfm_save_keys": "Save credentials",+ "lastfm_keys_saved": "Credentials saved",+ "lastfm_step3_title": "Authorize access",+ "lastfm_step3_desc": "Opens Last.fm in your browser to approve. Then come back and click Finalize.",+ "lastfm_authorize": "Authorize with Last.fm",+ "lastfm_authorize_pending": "Approve access on the Last.fm page that opened, then click Finalize:",+ "lastfm_open_auth": "Open approval page",+ "lastfm_finalize": "Finalize connection",+ "lastfm_connected": "Connected as {{username}}",+ "lastfm_connected_as": "Connected as {{username}}",+ "lastfm_connected_hint": "Tracks played for over 30s scrobble to your account. Now playing updates in real time.",+ "lastfm_enable_scrobble": "Auto-scrobble",+ "lastfm_disconnect": "Disconnect",+ "lastfm_disconnect_confirm": "Delete credentials and disconnect?",+ "lastfm_disconnected": "Disconnected",+ "dl_hero_title": "Paste a URL or search",+ "dl_hero_sub": "YouTube, SoundCloud, Bandcamp, anything yt-dlp supports. Becomes audio in your library.",+ "dl_quality": "Quality",+ "dl_quality_best": "Best available",+ "dl_idle_hint": "Paste a track or album URL, or search by title. Ctrl+V auto-detects.",+ "dl_detecting": "Detecting…",+ "dl_searching": "Searching…",+ "dl_search_empty": "No results found.",+ "dl_unsupported": "Site not recognized. Try pasting the direct track URL.",+ "dl_preparing": "Starting download…",+ "dl_download_audio": "Download audio",+ "dl_started": "Download started",+ "dl_recent": "Recent downloads",+ "batch_done": "{{ok}} started, {{fail}} failed",+ "music_theme_title": "Music theme",+ "music_theme_subtitle": "Customize music section colors. Saved separately from the global app theme.",+ "music_theme_preset": "Preset",+ "music_theme_accent": "Accent color",+ "music_theme_save": "Save theme",+ "music_theme_reset": "Restore default",+ "music_theme_preset_default": "Default",+ "music_theme_preset_indigo": "靛蓝",+ "music_theme_preset_spotify": "Spotify",+ "music_theme_preset_purple": "Purple",+ "music_theme_preset_amber": "Amber",+ "music_theme_preset_custom": "Custom",+ "music_theme_use_dominant": "Use current cover color",+ "music_theme_dominant_off": "Fixed color",+ "music_theme_dominant_on": "Auto (cover color)",+ "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",+ "rpc_disconnected": "Disconnected",+ "rpc_enable": "Show activity on Discord",+ "rpc_advanced": "Advanced settings",+ "rpc_appid_hint": "Application ID from your Discord Developer Portal app. Default is the omniget \"Loop\" app.",+ "rpc_large_image": "Large image key",+ "rpc_image_hint": "Asset name (Rich Presence Assets) uploaded on Discord Dev Portal. Without it, activity shows without icon.",+ "rpc_save": "Save",+ "rpc_saved": "Settings saved",+ "rpc_test": "Test connection",+ "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).",+ "nav_youtube": "YouTube",+ "yt_title": "YouTube Music",+ "yt_subtitle": "Import playlists from YouTube and YouTube Music. Streams on demand — no download.",+ "yt_intro": "Paste any YouTube or YouTube Music playlist link. For private playlists (including \"Likes\"), point to the browser you're logged into.",+ "yt_step1_title": "Which browser to pull cookies from?",+ "yt_step1_desc": "For private playlists and your Library, omniget needs cookies from the browser you're signed into. Without cookies, only public playlists work.",+ "yt_browser_micro": "yt-dlp reads cookies straight from your browser. Nothing leaves your machine — it's all local.",+ "yt_browser_saved": "{{browser}} cookies configured",+ "yt_step2_title": "Import a playlist",+ "yt_step2_desc": "Paste the link, omniget imports the track list. Playback streams on demand — nothing is downloaded.",+ "yt_import": "Import",+ "yt_imported": "{{title}}: {{count}} tracks imported",+ "yt_lm_label": "Likes (Liked Music)",+ "yt_playlist_label": "YouTube Music playlist",+ "yt_yt_playlist_label": "YouTube video playlist",+ "yt_add_playlist": "Add playlist",+ "yt_empty_title": "No playlists yet",+ "yt_empty_body": "Hook up a YouTube or YouTube Music playlist to see your tracks here alongside your local files.",+ "yt_setup": "Set up YouTube",+ "yt_refresh": "Re-import",+ "yt_refreshed": "Refreshed: {{count}} tracks",+ "yt_remove": "Remove",+ "yt_remove_confirm": "Remove this playlist from your library? (The YouTube playlist stays intact.)",+ "yt_search_placeholder": "Search YouTube Music — songs, artists, albums…",+ "yt_recs_for": "Because you played: {{name}}",+ "yt_download": "Download",+ "yt_download_started": "Download started",+ "yt_eyebrow": "YouTube Music",+ "yt_state_authed": "Connected",+ "yt_state_anon": "Not connected",+ "yt_auth_title": "Connect to your account",+ "yt_auth_desc": "To pull your private library (Likes, your playlists), paste 2 cookies from the browser where you're logged into YouTube Music.",+ "yt_auth_how": "How to get the cookies",+ "yt_auth_step1": "Open music.youtube.com in Chrome/Edge/Firefox where you're logged in.",+ "yt_auth_step2": "F12 → Application/Storage tab → Cookies → music.youtube.com",+ "yt_auth_step3": "Copy the value of __Secure-3PAPISID and paste in the first field.",+ "yt_auth_step4": "In Network tab, click any request, copy the whole Cookie: header and paste in the second field.",+ "yt_cookie_full": "Full cookie header",+ "yt_cookie_hint": "Paste the entire Cookie: header from any request to music.youtube.com.",+ "yt_save_auth": "Save credentials",+ "yt_auth_saved": "Credentials saved",+ "yt_disconnect": "Disconnect",+ "yt_disconnect_confirm": "Delete saved credentials?",+ "yt_disconnected": "Disconnected",+ "yt_visitor_ok": "Visitor data refreshed",+ "yt_sync_title": "Sync my library",+ "yt_sync_desc": "Imports Liked Music + all your playlists in one batch. Runs in the background. Tracks show up in Library / Albums / Artists alongside your local files.",+ "yt_sync_now": "Sync now",+ "yt_syncing": "Syncing…",+ "yt_sync_starting": "Starting…",+ "yt_sync_liked": "Fetching Liked Music…",+ "yt_sync_playlists": "Fetching {{total}} playlists…",+ "yt_sync_done": "Synced: {{playlists}} playlists, {{tracks}} tracks",+ "yt_ext_import": "Import from extension",+ "yt_ext_hint": "Pulls YouTube cookies straight from the omniget browser extension. No F12, no copy-paste.",+ "yt_ext_imported": "{{count}} cookies imported from extension",+ "yt_ext_empty": "No cookies captured yet. Open music.youtube.com in your browser with the omniget extension active, then try again.",+ "yt_ext_no_sapisid": "Cookies found but no __Secure-3PAPISID. Sign in to YouTube Music and try again.",+ "yt_ext_no_file": "Cookie file doesn't exist. Extension never sent anything — check: (1) omniget host running, (2) extension active, (3) Native Messaging registered. Expected at: {{path}}",+ "yt_ext_no_youtube": "File exists ({{age}}) but only has cookies for: {{domains}}. Open music.youtube.com in browser, wait 3s, try again.",+ "yt_ext_no_sapisid_detail": "{{count}} cookies imported ({{age}}) but none is __Secure-3PAPISID. Sign in to YouTube Music.",+ "yt_ext_imported_detail": "{{count}} cookies imported ({{age}})",+ "yt_or_manual": "or manually",+ "quality_title": "Audio quality",+ "quality_short": "Quality",+ "quality_intro": "Pick how downloaded music is encoded. You can change anytime — this only affects new downloads.",+ "quality_current": "Current: {{label}}",+ "quality_saved": "Quality set to {{label}}",+ "quality_group_recommended": "Recommended",+ "quality_group_compact": "Save space",+ "quality_group_high": "High quality",+ "quality_group_lossless": "Lossless (audiophile)",+ "quality_hint_mp3_128": "Smallest files · ~3 MB per song · basic quality",+ "quality_hint_mp3_192": "Balanced · ~5 MB per song · plays everywhere",+ "quality_hint_mp3_320": "MP3 at max · ~7 MB per song · maximum compatibility",+ "quality_hint_aac_192": "Sounds great, small files, plays everywhere · ~5 MB per song",+ "quality_hint_aac_256": "Premium lossy · ~6 MB per song · transparent quality",+ "quality_hint_opus_160": "Most efficient · ~4 MB per song · may not play on older devices",+ "quality_hint_flac": "Lossless · keeps source file size",+ "quality_hint_flac_cd": "Lossless CD quality · ~30 MB per song",+ "quality_hint_flac_hires": "Studio quality · 24-bit/96 kHz · ~80 MB per song",+ "quality_hint_wav": "Uncompressed PCM · ~50 MB per song · largest files",+ "sources_title": "Music sources",+ "sources_short": "Sources",+ "sources_subtitle": "Where to look for tracks",+ "sources_intro": "When you ask omniget to fetch a song by name, it tries these sources in order. Drag with arrows to reorder.",+ "source_status_connected": "Connected",+ "source_status_not_connected": "Not connected",+ "source_status_unavailable": "Coming soon",+ "source_connect": "Connect",+ "source_inactive_header": "Not in rotation",+ "source_reset_default": "Restore default order",+ "source_move_up": "Move up",+ "source_move_down": "Move down",+ "qobuz_title": "Qobuz",+ "qobuz_state_connected": "Connected",+ "qobuz_state_disconnected": "Not connected",+ "qobuz_intro": "Connect your Qobuz account to get lossless tracks (FLAC up to 24-bit/192 kHz). Requires an active Qobuz subscription.",+ "qobuz_email_label": "Qobuz email",+ "qobuz_password_label": "Password",+ "qobuz_pwd_show": "Show password",+ "qobuz_pwd_hide": "Hide password",+ "qobuz_privacy": "Stored locally on your device only. Never sent to omniget servers.",+ "qobuz_connect": "Connect",+ "qobuz_connecting": "Connecting…",+ "qobuz_connected": "Connected to Qobuz",+ "qobuz_disconnected": "Disconnected from Qobuz",+ "qobuz_disconnect": "Disconnect",+ "qobuz_disconnect_confirm": "Remove saved Qobuz credentials?",+ "qobuz_signed_in_as": "Signed in as",+ "qobuz_connected_hint": "Qobuz is now in the source pool. Use the Sources panel to control its priority.",+ "qobuz_test_again": "Test connection",+ "qobuz_testing": "Testing…",+ "qobuz_test_ok": "Qobuz login works",+ "qobuz_test_failed": "Qobuz test failed: {{error}}",+ "nav_aria": "Music navigation",+ "sidebar_hint_title": "Tip",+ "sidebar_hint_body": "Music keeps playing while you navigate between Courses, Notes and other sections.",+ "nav_search": "Search",+ "playlists_section": "Playlists",+ "playlists_title": "Playlists",+ "playlists_empty_title": "You have no playlists yet",+ "playlists_empty_body": "Create a playlist to group your favorite tracks and listen in sequence.",+ "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.",+ "playlist_deleted": "Playlist deleted",+ "click_to_rename": "Click to rename",+ "delete_playlist": "Delete playlist",+ "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",+ "queue_aria": "Playback queue",+ "queue_empty": "Queue is empty.",+ "queue_toggle": "Toggle queue",+ "search_hint": "Type a track title, artist or album.",+ "exit": "Exit",+ "featured_album": "Featured album",+ "by": "By",+ "start_listening": "Start listening",+ "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.",+ "sort_added": "Added",+ "sort_name": "Name A→Z",+ "sort_year": "Year",+ "sort_track_count": "Most tracks",+ "manage_folders": "Manage folders",+ "roots_title": "Music folders",+ "roots_hint": "Folders we scan for audio. Disable one to ignore without deleting from disk. Removing here does not delete any file.",+ "roots_empty": "You haven't added any music folder yet.",+ "root_missing": "missing",+ "root_remove": "Remove",+ "root_removed": "Folder removed: {{path}}",+ "nav_albums": "Albums",+ "nav_artists": "Artists",+ "nav_playlists": "Playlists"+ },"library": {"title": "课程库",+ "subtitle": "Your courses, videos and PDFs in one place.",+ "empty_browse_title": "Your library is still empty",+ "empty_browse_description": "Point to your course folders or import videos from Telegram. Nothing is copied or moved.",+ "empty_add_folder_title": "Add a video folder",+ "empty_add_folder_desc": "Point to where your courses already are. No copy, no move.",+ "empty_add_folder_cta": "Choose folder",+ "empty_telegram_title": "Import from Telegram",+ "empty_telegram_desc": "Download videos straight from channels you've joined.",+ "empty_telegram_cta": "Connect",+ "pinned_strip_aria": "Pinned folders",+ "pin_action": "Pin",+ "pin_action_active": "Pinned",+ "pin_action_title": "Pin this folder",+ "unpin_action": "Unpin",+ "unpin_action_title": "Unpin this folder",+ "pin_failed": "Pin failed: {{msg}}",+ "unpin_failed": "Unpin failed: {{msg}}",+ "siblings_aria": "Sibling folders",+ "siblings_empty": "No sibling folders",+ "view_mode_aria": "视图模式",+ "view_mode_grid": "Grid",+ "view_mode_list": "List",+ "back_toast": "Back to {{folder}}",+ "address_bar_placeholder": "Paste or type a path…",+ "address_bar_open": "Edit path",+ "new_folder": "New folder",+ "new_folder_placeholder": "Folder name",+ "ctx_open": "Open",+ "ctx_rename": "Rename",+ "ctx_delete": "Delete (Trash)",+ "ctx_show_in_explorer": "Show in file manager",+ "delete_confirm_title": "Move to Trash?",+ "delete_confirm_msg_folder": "The folder \"{{name}}\" and everything inside will be moved to the system Trash.",+ "delete_confirm_msg_file": "\"{{name}}\" will be moved to the system Trash.",+ "delete_confirm_btn": "Move to Trash",+ "delete_toast_done": "\"{{name}}\" moved to Trash",+ "last_watched_label": "Last watched",+ "roots_button_hint": "Folders the library scans for courses and videos",+ "empty_with_roots_one": "Detected 1 configured folder but no courses indexed yet.",+ "empty_with_roots_other": "Detected {{count}} configured folders but no courses indexed yet.",+ "empty_with_roots_cta": "Rescan now",+ "pin_added_toast": "\"{{name}}\" pinned",+ "pin_removed_toast": "Pin removed",+ "root_missing_label": "missing",+ "root_missing_hint": "Drive unplugged? Folder deleted? Reconnect or remove here.",+ "mode_telegram_disconnected_suffix": "(not connected)",+ "browse_sort_label": "Sort",+ "browse_sort_name_asc": "Name A→Z",+ "browse_sort_name_desc": "Name Z→A",+ "browse_sort_size_desc": "Size",+ "browse_sort_recent": "Modified",+ "selection_count_one": "1 selected",+ "selection_count_other": "{{count}} selected",+ "selection_clear": "Clear selection",+ "selection_delete": "Delete selected",+ "selection_delete_confirm_title": "Delete {{count}} item(s)?",+ "selection_delete_confirm_msg": "Items will be moved to the system Trash. You can restore from there if you change your mind.",+ "selection_delete_done": "{{count}} item(s) moved to Trash",+ "selection_delete_partial": "{{ok}} OK · {{fail}} failed",+ "open_in_new_tab": "Open in new tab",+ "tab_close": "Close tab",+ "tab_new": "New tab","empty": "尚未索引任何课程。请从设置中运行扫描。","error_loading_notes": "Couldn't load your notes. Try reloading or contact support if it persists.","health_title": "Library health",@@ -874,7 +1356,6 @@"status_in_progress": "进行中","status_not_started": "未开始","status_completed": "已完成",- "view_mode_aria": "视图模式","status_aria": "状态","cleanup_btn": "Clean orphan entries","cleanup_orphan_delete": "Delete file",@@ -1151,7 +1632,27 @@"watched": "Watched","resume_at": "Resume at {{time}}","player_speed": "Playback speed"- }+ },+ "home_continue_title": "从上次离开的地方继续",+ "home_continue_eyebrow": "最近",+ "home_continue_empty": "还没有进行中的课程。开始一节课就会出现在这里。",+ "home_continue_next": "下一节:{{title}}",+ "home_continue_current": "正在学:{{title}}",+ "home_news_title": "有更新",+ "home_news_eyebrow": "新课程",+ "home_news_count_one": "{{count}} 节新课",+ "home_news_count_other": "{{count}} 节新课",+ "home_recently_title": "最近添加",+ "home_recently_eyebrow": "新增",+ "home_platform_eyebrow": "平台",+ "home_subject_eyebrow": "学科",+ "home_empty_title": "你的资料库是空的",+ "home_empty_desc": "添加一个包含课程的文件夹开始。",+ "home_empty_cta": "添加课程文件夹",+ "home_load_error": "加载资料库失败:{{error}}",+ "view_home": "主页",+ "view_catalog": "目录",+ "platform_generic": "其他平台"},"player": {"title": "播放器",@@ -1191,7 +1692,13 @@"theater_on": "Exit theater mode","theater_off": "Theater mode","theater_hint": "Hide sidebar and panels (T)",- "description_title": "Description"+ "description_title": "Description",+ "clip": "剪辑最后60秒",+ "clip_loading": "剪辑中…",+ "clip_done": "剪辑已保存",+ "clip_failed": "剪辑失败",+ "clip_no_video": "视频尚未加载",+ "clip_aria": "将最后60秒保存为剪辑"},"notes": {"title": "笔记",@@ -1271,11 +1778,58 @@"filter_xp": "XP","filter_lessons": "Lessons","filter_focus": "Focus",- "filter_streak": "Streak"+ "filter_streak": "Streak",+ "tier_bronze": "铜",+ "tier_silver": "银",+ "tier_gold": "金",+ "unlocked_prefix": "已解锁",+ "reset_done": "重置完成",+ "reset_confirm_label": "重置",+ "filter_aria": "类别筛选",+ "tree_link": "树",+ "charts_link": "图表",+ "label_xp_100": "首个 100 XP",+ "label_xp_500": "500 XP",+ "label_xp_1000": "千 XP",+ "label_xp_5000": "5k XP",+ "label_xp_10000": "10k XP",+ "label_lessons_1": "第一节课",+ "label_lessons_10": "10 节课",+ "label_lessons_50": "50 节课",+ "label_lessons_100": "100 节课",+ "label_focus_60": "1 小时专注",+ "label_focus_600": "10 小时专注",+ "label_focus_6000": "100 小时专注",+ "label_streak_3": "连续 3 天",+ "label_streak_7": "1 周连续",+ "label_streak_30": "30 天连续",+ "label_streak_100": "100 天连续",+ "desc_xp_100": "通过学习获得 100 XP",+ "desc_xp_500": "获得 500 XP",+ "desc_xp_1000": "1000 XP 里程碑",+ "desc_xp_5000": "累积五千 XP",+ "desc_xp_10000": "累积一万 XP — 你很专注",+ "desc_lessons_1": "完成你的第一节课",+ "desc_lessons_10": "完成 10 节课",+ "desc_lessons_50": "半个世纪的课程",+ "desc_lessons_100": "完成一百节课",+ "desc_focus_60": "累积 60 分钟专注",+ "desc_focus_600": "累积 600 分钟专注",+ "desc_focus_6000": "累积 6000 分钟专注 — 罕见的自律",+ "desc_streak_3": "保持 3 天连续",+ "desc_streak_7": "连续学习 7 天",+ "desc_streak_30": "整整一个月的坚持",+ "desc_streak_100": "钢铁般的习惯"},"focus": {"title": "专注","placeholder": "番茄钟和深度工作会话在此进行。",+ "intent_label": "What's this session for?",+ "intent_prefix": "Studying",+ "intent_placeholder": "thesis, calculus exam, sales certification...",+ "intent_hint": "Shows up on your Discord if RPC is on. Leave empty if you'd rather not.",+ "intent_for": "studying",+ "rpc_default": "Focus session","preset_pomodoro": "番茄钟 (25/5)","preset_short_break": "Short break","preset_long_break": "Long break",@@ -1347,7 +1901,34 @@"stop_body": "The session will be marked as interrupted and won't count towards stats.","stop_confirm": "Interrupt","active_preset_label": "In focus",- "session_ended": "Session ended"+ "session_ended": "Session ended",+ "settings_saving": "保存中…",+ "settings_saved": "已保存 ✓",+ "acc_cycles_title": "循环",+ "acc_cycles_summary": "{{focus}}分钟专注 · {{break}}分钟休息 · {{cycles}}× 直到长休息",+ "acc_cycles_focus": "专注(分钟)",+ "acc_cycles_short": "短休息(分钟)",+ "acc_cycles_long": "长休息(分钟)",+ "acc_cycles_count": "长休息前的循环数",+ "acc_breaks_title": "休息与自动开始",+ "acc_breaks_auto_yes": "自动暂停",+ "acc_breaks_auto_no": "手动",+ "acc_breaks_focus_yes": "自动恢复",+ "acc_breaks_focus_no": "手动",+ "acc_breaks_player_yes": "暂停播放器",+ "acc_breaks_player_no": "忽略播放器",+ "acc_breaks_check_breaks": "专注后自动开始休息",+ "acc_breaks_check_focus": "休息后自动恢复专注",+ "acc_breaks_check_player": "专注休息时暂停视频",+ "acc_sounds_title": "声音与通知",+ "acc_sounds_notify_on": "通知开启",+ "acc_sounds_notify_off": "静音",+ "acc_sounds_sound_on": "声音 {{n}}%",+ "acc_sounds_sound_off": "无声音",+ "acc_sounds_check_notify": "循环结束时通知",+ "acc_sounds_check_sound": "结束时播放声音",+ "acc_sounds_volume": "音量 ({{n}}%)",+ "unlimited_aria": "无限"},"subjects": {"title": "Subjects",@@ -1439,7 +2020,45 @@"chart_explore_library": "Browse library","chart_review_weak": "Review weak cards","chart_adjust_goals": "Adjust goals",- "streak_best": "best: {{n}}"+ "streak_best": "best: {{n}}",+ "chart_time_per_course": "每门课程的时间",+ "chart_time_per_course_empty": "本周期内没有时间记录。",+ "chart_time_period_days": "最近 {{n}} 天",+ "chart_activity_by_hour": "按小时活动",+ "chart_activity_hint": "专注总和 · 24小时",+ "chart_activity_empty": "最近 {{n}} 天没有活动。",+ "chart_subject": "按学科",+ "chart_subject_unit": "专注分钟",+ "chart_subject_empty": "创建学科并分配会话以查看细分。",+ "chart_subject_unassigned": "无学科",+ "retention_title": "记忆保留(Anki)",+ "retention_method": "FSRS-5",+ "retention_stub_before": "真实的保留率将来自 Anki 跨数据库查询。目前请打开",+ "retention_link": "Anki 统计 →",+ "retention_stub_after": "查看保留率、间隔分布和复习历史。",+ "recent_achievements": "最近的成就",+ "view_all": "查看全部 →",+ "time_today": "今天",+ "time_yesterday": "昨天",+ "time_days_ago": "{{n}} 天前",+ "time_months_ago": "{{n}} 个月前",+ "time_years_ago": "{{n}} 年前",+ "ach_label_xp_100": "已累积 100 XP",+ "ach_label_xp_500": "已累积 500 XP",+ "ach_label_xp_1000": "已累积 1,000 XP",+ "ach_label_xp_5000": "已累积 5,000 XP",+ "ach_label_xp_10000": "已累积 10,000 XP",+ "ach_label_lessons_1": "第一节课",+ "ach_label_lessons_10": "完成 10 节课",+ "ach_label_lessons_50": "完成 50 节课",+ "ach_label_lessons_100": "完成 100 节课",+ "ach_label_focus_60": "1 小时专注",+ "ach_label_focus_600": "10 小时专注",+ "ach_label_focus_6000": "100 小时专注",+ "ach_label_streak_3": "3 天连续",+ "ach_label_streak_7": "1 周连续",+ "ach_label_streak_30": "30 天连续",+ "ach_label_streak_100": "100 天连续"},"settings": {"title": "设置",@@ -1718,7 +2337,15 @@"annas_warning_modal_line4": "Tick the box below if you understand and accept personal responsibility for your usage.","annas_warning_ack_label": "I understand. I take full responsibility for my use in my jurisdiction.","annas_warning_cancel": "Cancel",- "annas_warning_confirm": "Enable Alt Library"+ "annas_warning_confirm": "Enable Alt Library",+ "search_notes_btn": "搜索笔记",+ "downloads_btn": "下载",+ "enrich_no_results": "无结果。请先尝试编辑书籍标题。",+ "enrich_done": "✓ 元数据已更新",+ "enrich_field_title": "标题:",+ "enrich_field_author": "作者:",+ "enrich_field_publisher": "出版社:",+ "enrich_field_cover": "封面(下载)"},"bulk": {"select_all": "Select all",diff --git a/src/lib/notes-bridge.ts b/src/lib/notes-bridge.tsindex 739bf25d..65c7e64b 100644--- a/src/lib/notes-bridge.ts+++ b/src/lib/notes-bridge.ts@@ -18,6 +18,7 @@ export type PageSummary = {journal_day: number | null;block_count: number;updated_at: number;+ notebook_id: number;};export type BlockKind =@@ -34,7 +35,12 @@ export type BlockKind =| "divider"| "image"| "embed"- | "video";+ | "video"+ | "mermaid"+ | "flowchart"+ | "mindmap"+ | "abc"+ | "plantuml";export type NoteBlock = {id: number;@@ -261,23 +267,39 @@ export async function notesPagesCreate(args: {name: string;title?: string;journalDay?: number;-}): Promise<{ id: number }> {- return pluginInvoke<{ id: number }>(NS, "study:notes:pages:create", args);+ notebookId?: number;+}): Promise<{ id: number; notebook_id: number }> {+ return pluginInvoke<{ id: number; notebook_id: number }>(+ NS,+ "study:notes:pages:create",+ args,+ );}export async function notesPagesEnsure(args: {name: string;title?: string;-}): Promise<{ id: number }> {- return pluginInvoke<{ id: number }>(NS, "study:notes:pages:ensure", args);+ notebookId?: number;+}): Promise<{ id: number; notebook_id: number }> {+ return pluginInvoke<{ id: number; notebook_id: number }>(+ NS,+ "study:notes:pages:ensure",+ args,+ );}export async function notesPagesGet(id: number): Promise<NotePage> {return pluginInvoke<NotePage>(NS, "study:notes:pages:get", { id });}-export async function notesPagesGetByName(name: string): Promise<NotePage | null> {- return pluginInvoke<NotePage | null>(NS, "study:notes:pages:get_by_name", { name });+export async function notesPagesGetByName(+ name: string,+ notebookId?: number,+): Promise<NotePage | null> {+ return pluginInvoke<NotePage | null>(NS, "study:notes:pages:get_by_name", {+ name,+ notebookId,+ });}export async function notesPagesRename(args: {@@ -997,3 +1019,378 @@ export async function notesCardsExportToAnki(args: {}// #endregion++// #region tabs + wnds (Z2)++export type TabViewKind =+ | "editor"+ | "graph"+ | "search"+ | "templates"+ | "settings"+ | "journal";++export type TabSummary = {+ id: number;+ wnd_id: number;+ page_id: number | null;+ page_name: string | null;+ page_title: string | null;+ view_kind: TabViewKind;+ pinned: boolean;+ sort_idx: number;+ created_at: number;+ last_focused_at: number | null;+};++export type WndNode = {+ id: number;+ split_dir: "horizontal" | "vertical" | null;+ ratio: number;+ children: WndNode[];+};++export type TabCloseReport = {+ closed: boolean;+ fallback_tab_id: number | null;+};++export type WndCloseReport = {+ closed: boolean;+ collapsed_to_parent: boolean;+ new_root_id: number | null;+};++export async function notesTabsListForWnd(wndId: number): Promise<TabSummary[]> {+ return pluginInvoke<TabSummary[]>(NS, "study:notes:tabs:list_for_wnd", { wndId });+}++export async function notesTabsOpen(args: {+ wndId: number;+ pageId?: number | null;+ viewKind?: TabViewKind;+}): Promise<{ tab_id: number }> {+ return pluginInvoke<{ tab_id: number }>(NS, "study:notes:tabs:open", args);+}++export async function notesTabsClose(tabId: number): Promise<TabCloseReport> {+ return pluginInvoke<TabCloseReport>(NS, "study:notes:tabs:close", { tabId });+}++export async function notesTabsReorder(args: {+ tabId: number;+ newSortIdx: number;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:tabs:reorder", args);+}++export async function notesTabsMoveToWnd(args: {+ tabId: number;+ targetWndId: number;+ sortIdx?: number;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:tabs:move_to_wnd", args);+}++export async function notesTabsPin(args: {+ tabId: number;+ pinned: boolean;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:tabs:pin", args);+}++export async function notesTabsTouchFocus(tabId: number): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:tabs:touch_focus", { tabId });+}++export async function notesWndsTree(): Promise<WndNode> {+ return pluginInvoke<WndNode>(NS, "study:notes:wnds:tree", {});+}++export async function notesWndsSplit(args: {+ parentWndId: number;+ direction: "horizontal" | "vertical";+}): Promise<{ new_wnd_id: number }> {+ return pluginInvoke<{ new_wnd_id: number }>(NS, "study:notes:wnds:split", args);+}++export async function notesWndsClose(wndId: number): Promise<WndCloseReport> {+ return pluginInvoke<WndCloseReport>(NS, "study:notes:wnds:close", { wndId });+}++export async function notesWndsSetRatio(args: {+ wndId: number;+ ratio: number;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:wnds:set_ratio", args);+}++// #endregion++// #region active state (Z2)++export type ActiveStateEntry = {+ key: string;+ value: NoteSettingValue;+ updated_at: number;+};++export async function notesActiveStateGet(+ key: string,+): Promise<{ value: NoteSettingValue }> {+ return pluginInvoke<{ value: NoteSettingValue }>(+ NS,+ "study:notes:active_state:get",+ { key },+ );+}++export async function notesActiveStateSet(args: {+ key: string;+ value: NoteSettingValue;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:active_state:set", args);+}++export async function notesActiveStateList(): Promise<ActiveStateEntry[]> {+ return pluginInvoke<ActiveStateEntry[]>(NS, "study:notes:active_state:list", {});+}++// #endregion++// #region docks (Z3)++export type DockId =+ | "files"+ | "outline"+ | "backlink"+ | "bookmark"+ | "tag"+ | "inbox"+ | "graph"+ | (string & {});++export type DockPosition = "left" | "right" | "bottom";++export type DockState = {+ dock_id: DockId;+ position: DockPosition;+ visible: boolean;+ expanded: boolean;+ sort_idx: number;+ width_px: number | null;+};++export type DockStatePatch = {+ position?: DockPosition;+ visible?: boolean;+ expanded?: boolean;+ sort_idx?: number;+ width_px?: number | null;+};++export type OutlineEntry = {+ block_id: number;+ level: number;+ content: string;+ order_idx: number;+};++export async function notesDocksState(): Promise<DockState[]> {+ return pluginInvoke<DockState[]>(NS, "study:notes:docks:state", {});+}++export async function notesDocksSetState(args: {+ dockId: DockId;+ patch: DockStatePatch;+}): Promise<{ ok: true; state: DockState }> {+ return pluginInvoke<{ ok: true; state: DockState }>(+ NS,+ "study:notes:docks:set_state",+ args,+ );+}++export async function notesDocksToggleVisible(+ dockId: DockId,+): Promise<{ visible: boolean }> {+ return pluginInvoke<{ visible: boolean }>(+ NS,+ "study:notes:docks:toggle_visible",+ { dockId },+ );+}++export async function notesPagesOutline(pageId: number): Promise<OutlineEntry[]> {+ return pluginInvoke<OutlineEntry[]>(NS, "study:notes:pages:outline", { pageId });+}++export async function notesBookmarksList(): Promise<PageSummary[]> {+ return pluginInvoke<PageSummary[]>(NS, "study:notes:bookmarks:list", {});+}++export async function notesInboxList(): Promise<PageSummary[]> {+ return pluginInvoke<PageSummary[]>(NS, "study:notes:inbox:list", {});+}++// #endregion++// #region notebooks (Z4)++export type Notebook = {+ id: number;+ name: string;+ sort_idx: number;+ closed: boolean;+ color: string | null;+ icon_lucide: string | null;+ cover_asset_id: number | null;+ created_at: number;+ updated_at: number;+ page_count: number;+};++export type NotebookDeleteReport = {+ deleted: boolean;+ page_count: number;+};++export type NotebookMoveReport = {+ ok: boolean;+ new_full_name: string;+ notebook_id: number;+};++export async function notesNotebooksList(+ args: { includeClosed?: boolean } = {},+): Promise<Notebook[]> {+ return pluginInvoke<Notebook[]>(NS, "study:notes:notebooks:list", args);+}++export async function notesNotebooksGet(notebookId: number): Promise<Notebook | null> {+ return pluginInvoke<Notebook | null>(NS, "study:notes:notebooks:get", {+ notebookId,+ });+}++export async function notesNotebooksCreate(args: {+ name: string;+ color?: string | null;+ iconLucide?: string | null;+}): Promise<{ notebook_id: number }> {+ return pluginInvoke<{ notebook_id: number }>(+ NS,+ "study:notes:notebooks:create",+ args,+ );+}++export async function notesNotebooksRename(args: {+ notebookId: number;+ newName: string;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:notebooks:rename", args);+}++export async function notesNotebooksClose(+ notebookId: number,+): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:notebooks:close", {+ notebookId,+ });+}++export async function notesNotebooksReopen(+ notebookId: number,+): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(NS, "study:notes:notebooks:reopen", {+ notebookId,+ });+}++export async function notesNotebooksDelete(args: {+ notebookId: number;+ force?: boolean;+}): Promise<NotebookDeleteReport> {+ return pluginInvoke<NotebookDeleteReport>(+ NS,+ "study:notes:notebooks:delete",+ args,+ );+}++export async function notesNotebooksMovePage(args: {+ pageId: number;+ targetNotebookId: number;+ targetName?: string;+}): Promise<NotebookMoveReport> {+ return pluginInvoke<NotebookMoveReport>(+ NS,+ "study:notes:notebooks:move_page",+ args,+ );+}++export async function notesNotebooksSetCover(args: {+ notebookId: number;+ assetId?: number | null;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(+ NS,+ "study:notes:notebooks:set_cover",+ args,+ );+}++export async function notesNotebooksSetColor(args: {+ notebookId: number;+ color?: string | null;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(+ NS,+ "study:notes:notebooks:set_color",+ args,+ );+}++export async function notesNotebooksSetIcon(args: {+ notebookId: number;+ iconLucide?: string | null;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(+ NS,+ "study:notes:notebooks:set_icon",+ args,+ );+}++export async function notesNotebooksReorder(args: {+ notebookId: number;+ newSortIdx: number;+}): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(+ NS,+ "study:notes:notebooks:reorder",+ args,+ );+}++export async function notesNotebooksActiveGet(): Promise<{ notebook_id: number }> {+ return pluginInvoke<{ notebook_id: number }>(+ NS,+ "study:notes:notebooks:active_get",+ {},+ );+}++export async function notesNotebooksActiveSet(+ notebookId: number,+): Promise<{ ok: true }> {+ return pluginInvoke<{ ok: true }>(+ NS,+ "study:notes:notebooks:active_set",+ { notebookId },+ );+}++// #endregiondiff --git a/src/lib/rpc.ts b/src/lib/rpc.tsnew file mode 100644index 00000000..e67872b1--- /dev/null+++ b/src/lib/rpc.ts@@ -0,0 +1,48 @@+import { invoke } from "@tauri-apps/api/core";+import { getDownloadStats } from "$lib/stores/download-stats.svelte";++export type RpcSource = "focus" | "music" | "video" | "course" | "reading";++export type RpcSetSourceArgs = {+ source: RpcSource;+ details: string;+ state: string;+ duration?: number;+ position?: number;+ paused?: boolean;+ largeImageKey?: string | null;+};++export async function rpcSetSource(args: RpcSetSourceArgs): Promise<void> {+ try {+ await invoke("rpc_set_source", {+ source: args.source,+ details: args.details,+ state: args.state,+ duration: args.duration ?? 0,+ position: args.position ?? 0,+ paused: args.paused ?? false,+ largeImageKey: args.largeImageKey ?? null,+ });+ } catch {}+}++export async function rpcClearSource(source: RpcSource): Promise<void> {+ try {+ await invoke("rpc_clear_source", { source });+ } catch {}+}++export async function rpcSyncIdleStats(): Promise<void> {+ const stats = getDownloadStats();+ try {+ await invoke("rpc_set_idle_stats", {+ downloadsCount: stats.totalDownloads,+ totalBytes: stats.totalBytes,+ });+ } catch {}+}++export async function rpcTestConnection(): Promise<{ ok: boolean; reason?: string }> {+ return await invoke("rpc_test_connection");+}diff --git a/src/lib/stores/changelog-store.svelte.ts b/src/lib/stores/changelog-store.svelte.tsindex c88a38bc..f2932f7c 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.5.2";+ currentVersion = "0.6.0";}const lastSeen = localStorage.getItem(STORAGE_KEY);diff --git a/src/lib/stores/download-listener.ts b/src/lib/stores/download-listener.tsindex 09dc3553..ae8ee31e 100644--- a/src/lib/stores/download-listener.ts+++ b/src/lib/stores/download-listener.ts@@ -17,6 +17,7 @@ import {import { setMediaPreview } from "./media-preview-store.svelte";import { addLog } from "./debug-store.svelte";import { recordDownloadComplete } from "./download-stats.svelte";+import { rpcSyncIdleStats } from "$lib/rpc";type ProgressPayload = {course_id: number;@@ -51,6 +52,7 @@ type QueueItemInfo = {file_size_bytes: number | null;file_count: number | null;thumbnail_url: string | null;+ eta_seconds?: number | null;};export type BatchFileStatusPayload = {@@ -77,6 +79,7 @@ type QueueItemProgressPayload = {downloaded_bytes: number;total_bytes: number | null;phase: string;+ eta_seconds?: number | null;};type ConvertProgressPayload = {@@ -172,6 +175,7 @@ export async function initDownloadListener(): Promise<() => void> {showToast("success", tr("toast.download_complete", { name: d.course_name }));addLog("info", "download", `Course download complete: ${d.course_name}`);recordDownloadComplete(0);+ void rpcSyncIdleStats();} else {let msg = tr("toast.download_error", { name: d.course_name });if (d.error) msg += ` — ${d.error}`;@@ -217,6 +221,7 @@ export async function initDownloadListener(): Promise<() => void> {showToast("success", tr("toast.download_complete", { name: d.course_name }));addLog("info", "download", `Udemy download complete: ${d.course_name}`);recordDownloadComplete(0);+ void rpcSyncIdleStats();if (d.drm_skipped > 0) {showToast("info", tr("toast.drm_skipped", { count: String(d.drm_skipped) }));addLog("warn", "download", `${d.drm_skipped} DRM-protected video(s) skipped`, d.course_name);@@ -247,6 +252,7 @@ export async function initDownloadListener(): Promise<() => void> {const tr = get(t);showToast("success", tr("toast.generic_download_complete", { name: item.title }));recordDownloadComplete(item.file_size_bytes ?? 0);+ void rpcSyncIdleStats();}}throttledSyncQueueState(payload);@@ -270,6 +276,7 @@ export async function initDownloadListener(): Promise<() => void> {d.downloaded_bytes,d.total_bytes,d.phase,+ d.eta_seconds ?? null,);},);diff --git a/src/lib/stores/download-store.svelte.ts b/src/lib/stores/download-store.svelte.tsindex 85e2bff1..4fc2edcc 100644--- a/src/lib/stores/download-store.svelte.ts+++ b/src/lib/stores/download-store.svelte.ts@@ -42,6 +42,7 @@ export type GenericDownloadItem = BaseItem & {downloadedBytes: number;totalBytes: number | null;phase: string;+ etaSeconds?: number | null;filePath?: string;fileCount?: number;thumbnail_url?: string | null;@@ -240,6 +241,7 @@ type QueueItemInfo = {thumbnail_url: string | null;kind?: QueueKind;external?: boolean;+ eta_seconds?: number | null;};function queueStatusToDownloadStatus(status: { type: string; data?: unknown }): DownloadStatus {@@ -296,6 +298,7 @@ export function syncQueueState(items: QueueItemInfo[]) {downloadedBytes: qi.downloaded_bytes,totalBytes: qi.total_bytes,phase: (existing?.kind === "generic" ? existing.phase : undefined) ?? "queued",+ etaSeconds: qi.eta_seconds ?? null,status: dlStatus,error: extractError(qi.status),startedAt: existing?.startedAt ?? now,@@ -353,6 +356,7 @@ export function upsertGenericProgress(downloadedBytes: number,totalBytes: number | null,phase: string,+ etaSeconds?: number | null,) {const now = Date.now();const existing = downloads.get(id);@@ -380,6 +384,7 @@ export function upsertGenericProgress(downloadedBytes,totalBytes,phase,+ etaSeconds: etaSeconds ?? null,status: resolvedStatus,startedAt: existing?.startedAt ?? now,lastUpdateAt: now,@@ -405,3 +410,16 @@ export function formatSpeed(bytesPerSec: number): string {return `${(bytesPerSec / (1024 * 1024)).toFixed(1)} MB/s`;}+export function formatEta(seconds: number | null | undefined): string {+ if (seconds == null || seconds <= 0 || !Number.isFinite(seconds)) return "";+ if (seconds < 60) return `${Math.round(seconds)}s`;+ if (seconds < 3600) {+ const m = Math.floor(seconds / 60);+ const s = Math.round(seconds % 60);+ return s > 0 ? `${m}m ${s}s` : `${m}m`;+ }+ const h = Math.floor(seconds / 3600);+ const m = Math.round((seconds % 3600) / 60);+ return m > 0 ? `${h}h ${m}m` : `${h}h`;+}+diff --git a/src/lib/stores/settings-store.svelte.ts b/src/lib/stores/settings-store.svelte.tsindex 60666a2f..d49122ed 100644--- a/src/lib/stores/settings-store.svelte.ts+++ b/src/lib/stores/settings-store.svelte.ts@@ -25,6 +25,11 @@ export type AppSettings = {split_by_chapters: boolean;hotkey_enabled: boolean;hotkey_binding: string;+ clip_hotkey_enabled?: boolean;+ clip_hotkey_binding?: string;+ music_hotkey_enabled: boolean;+ music_hotkey_binding: string;+ music_audio_format: string;copy_to_clipboard_on_hotkey: boolean;extra_ytdlp_flags?: string[];cookie_file: string;@@ -50,6 +55,11 @@ export type AppSettings = {concurrent_downloads: number;fix_file_extensions: boolean;};+ rpc: {+ enabled: boolean;+ app_id: string;+ large_image_key: string;+ };onboarding_completed: boolean;start_with_system: boolean;start_minimized: boolean;diff --git a/src/lib/study-components/notes/AbcView.svelte b/src/lib/study-components/notes/AbcView.sveltenew file mode 100644index 00000000..97e356bd--- /dev/null+++ b/src/lib/study-components/notes/AbcView.svelte@@ -0,0 +1,279 @@+<script lang="ts">+ import { onDestroy } from "svelte";++ type Props = {+ source: string;+ blockId: string;+ onSourceChange?: (next: string) => void;+ };++ let { source, blockId, onSourceChange }: Props = $props();++ type RenderState =+ | { kind: "idle" }+ | { kind: "loading" }+ | { kind: "rendered" }+ | { kind: "error"; message: string };++ let renderState = $state<RenderState>({ kind: "idle" });+ let mode = $state<"render" | "source">("render");+ let renderToken = 0;+ let host: HTMLDivElement | null = $state(null);++ type AbcjsModule = {+ renderAbc: (+ element: HTMLElement | string,+ src: string,+ options?: Record<string, unknown>,+ ) => unknown;+ };++ let cachedAbcjs: AbcjsModule | null = null;++ async function loadLib(): Promise<AbcjsModule> {+ if (cachedAbcjs) return cachedAbcjs;+ const mod = (await import("abcjs")) as { default?: AbcjsModule } & AbcjsModule;+ const resolved = (mod.default ?? mod) as AbcjsModule;+ cachedAbcjs = resolved;+ return resolved;+ }++ function readThemeOptions(): Record<string, unknown> {+ if (typeof window === "undefined") return {};+ const cs = window.getComputedStyle(document.documentElement);+ const fg = cs.getPropertyValue("--text").trim() || "#222";+ return {+ responsive: "resize",+ staffwidth: 740,+ foregroundColor: fg,+ wrap: {+ minSpacing: 1.8,+ maxSpacing: 2.7,+ preferredMeasuresPerLine: 4,+ },+ };+ }++ async function render(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) {+ renderState = { kind: "idle" };+ return;+ }+ renderState = { kind: "loading" };+ try {+ const abcjs = await loadLib();+ if (token !== renderToken) return;+ renderState = { kind: "rendered" };+ await Promise.resolve();+ if (token !== renderToken) return;+ if (!host) {+ renderState = { kind: "error", message: "container ausente" };+ return;+ }+ host.innerHTML = "";+ abcjs.renderAbc(host, trimmed, readThemeOptions());+ const _id = `abc-${blockId}-${token}`;+ void _id;+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message };+ }+ }++ let editingValue = $state(source);++ $effect(() => {+ editingValue = source;+ if (mode === "render") {+ void render(source);+ }+ });++ function toggleMode() {+ if (mode === "render") {+ editingValue = source;+ mode = "source";+ } else {+ mode = "render";+ onSourceChange?.(editingValue);+ void render(editingValue);+ }+ }++ function onSourceInput(event: Event) {+ const target = event.target as HTMLTextAreaElement;+ editingValue = target.value;+ }++ function onSourceBlur() {+ if (editingValue !== source) {+ onSourceChange?.(editingValue);+ }+ }++ onDestroy(() => {+ renderToken++;+ if (host) {+ try {+ host.innerHTML = "";+ } catch {}+ }+ });+</script>++<div class="abc-block" data-abc data-mode={mode}>+ <header class="abc-head" contenteditable="false">+ <span class="abc-icon" aria-hidden="true">♪</span>+ <span class="abc-label">abc</span>+ <button+ type="button"+ class="abc-toggle"+ onclick={toggleMode}+ title={mode === "render" ? "Editar source" : "Voltar pra partitura"}+ >+ {mode === "render" ? "‹/›" : "▶"}+ </button>+ </header>++ {#if mode === "source"}+ <textarea+ class="abc-source"+ value={editingValue}+ oninput={onSourceInput}+ onblur={onSourceBlur}+ spellcheck="false"+ rows={Math.max(6, editingValue.split("\n").length)}+ aria-label="Source da partitura (notação ABC)"+ ></textarea>+ {:else if renderState.kind === "idle"}+ <p class="abc-state">Sem source. Clique em ‹/› para editar.</p>+ {:else if renderState.kind === "loading"}+ <p class="abc-state">renderizando…</p>+ {:else if renderState.kind === "error"}+ <div class="abc-error">+ <p class="abc-error-msg">erro: {renderState.message}</p>+ <button type="button" class="abc-edit-btn" onclick={toggleMode}+ >Editar source</button>+ </div>+ {/if}++ <div+ class="abc-host"+ bind:this={host}+ style:display={mode === "render" && renderState.kind === "rendered"+ ? "block"+ : "none"}+ ></div>+</div>++<style>+ .abc-block {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--input-border) 12%, transparent);+ border-left: 3px solid var(--accent);+ border-radius: 0 var(--border-radius) var(--border-radius) 0;+ font-size: 12px;+ }+ .abc-head {+ display: flex;+ align-items: center;+ gap: 6px;+ user-select: none;+ }+ .abc-icon {+ color: var(--accent);+ font-size: 13px;+ }+ .abc-label {+ flex: 1 1 auto;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--secondary);+ }+ .abc-toggle {+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .abc-toggle:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .abc-source {+ width: 100%;+ box-sizing: border-box;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ line-height: 1.5;+ background: var(--surface);+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ padding: 8px 10px;+ color: var(--text);+ resize: vertical;+ min-height: 120px;+ }+ .abc-source:focus {+ outline: 2px solid var(--accent);+ outline-offset: -1px;+ }+ .abc-state {+ margin: 0;+ color: var(--tertiary);+ font-size: 11px;+ }+ .abc-host {+ width: 100%;+ background: var(--surface);+ border-radius: var(--border-radius);+ padding: 12px;+ box-sizing: border-box;+ overflow-x: auto;+ }+ .abc-host :global(svg) {+ max-width: 100%;+ height: auto;+ }+ .abc-error {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 6px 8px;+ background: color-mix(in oklab, var(--error, #e74c3c) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--error, #e74c3c) 30%, transparent);+ border-radius: var(--border-radius);+ color: var(--error, #e74c3c);+ }+ .abc-error-msg {+ margin: 0;+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ word-break: break-word;+ }+ .abc-edit-btn {+ align-self: flex-start;+ border: 0;+ background: transparent;+ color: var(--accent);+ font: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .abc-edit-btn:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/Editor.svelte b/src/lib/study-components/notes/Editor.svelteindex e2b4a3dc..8db48b63 100644--- a/src/lib/study-components/notes/Editor.svelte+++ b/src/lib/study-components/notes/Editor.svelte@@ -21,6 +21,11 @@import { Callout } from "./callout-node";import { QueryBlock } from "./query-node";import { EmbedBlock } from "./embed-node";+ import { MermaidBlock } from "./mermaid-node";+ import { FlowchartBlock } from "./flowchart-node";+ import { MindmapBlock } from "./mindmap-node";+ import { AbcBlock } from "./abc-node";+ import { PlantumlBlock } from "./plantuml-node";import { createSlashExtension, type SlashSuggestionState } from "./slash-extension";import { NotesKeyboardShortcuts } from "./keyboard-shortcuts";import {@@ -51,9 +56,30 @@initialMarkdown: string;onSaved?: (markdown: string, blockId: number) => void;onError?: (message: string) => void;+ onStats?: (stats: { words: number; chars: number }) => void;+ onSavingChange?: (saving: boolean) => void;};- let { pageId, aggregateBlockId, initialMarkdown, onSaved, onError }: Props = $props();+ let {+ pageId,+ aggregateBlockId,+ initialMarkdown,+ onSaved,+ onError,+ onStats,+ onSavingChange,+ }: Props = $props();++ function computeStats(markdown: string): { words: number; chars: number } {+ const trimmed = markdown.trim();+ const chars = markdown.length;+ if (!trimmed) return { words: 0, chars };+ const words = trimmed+ .replace(/[`*_>#~\-\[\]\(\)\{\}!]+/g, " ")+ .split(/\s+/)+ .filter((w) => w.length > 0).length;+ return { words, chars };+ }let element = $state<HTMLDivElement | undefined>(undefined);let bubbleElement = $state<HTMLDivElement | undefined>(undefined);@@ -108,6 +134,8 @@function scheduleSave(markdown: string) {pendingMarkdown = markdown;+ onStats?.(computeStats(markdown));+ onSavingChange?.(true);if (saveTimer) clearTimeout(saveTimer);saveTimer = setTimeout(() => {void flush();@@ -119,8 +147,12 @@clearTimeout(saveTimer);saveTimer = null;}- if (pendingMarkdown === initialMarkdown && lastSavedAt === null) return;+ if (pendingMarkdown === initialMarkdown && lastSavedAt === null) {+ onSavingChange?.(false);+ return;+ }isSaving = true;+ onSavingChange?.(true);try {const id = await ensureBlockId();await notesBlocksUpdate({ id, content: pendingMarkdown });@@ -131,6 +163,7 @@onError?.(msg);} finally {isSaving = false;+ onSavingChange?.(false);}}@@ -173,6 +206,11 @@Callout,QueryBlock,EmbedBlock,+ MermaidBlock,+ FlowchartBlock,+ MindmapBlock,+ AbcBlock,+ PlantumlBlock,NotesKeyboardShortcuts,Mention.extend({ name: "pageMention" }).configure({HTMLAttributes: { class: "tiptap-page-mention", "data-mention-kind": "page" },diff --git a/src/lib/study-components/notes/FlowchartView.svelte b/src/lib/study-components/notes/FlowchartView.sveltenew file mode 100644index 00000000..cebf4388--- /dev/null+++ b/src/lib/study-components/notes/FlowchartView.svelte@@ -0,0 +1,300 @@+<script lang="ts">+ import { onDestroy } from "svelte";++ type Props = {+ source: string;+ blockId: string;+ onSourceChange?: (next: string) => void;+ };++ let { source, blockId, onSourceChange }: Props = $props();++ type RenderState =+ | { kind: "idle" }+ | { kind: "loading" }+ | { kind: "rendered" }+ | { kind: "error"; message: string };++ let renderState = $state<RenderState>({ kind: "idle" });+ let mode = $state<"render" | "source">("render");+ let renderToken = 0;+ let svgHost: HTMLDivElement | null = $state(null);++ type FlowchartInstance = {+ clean: () => void;+ drawSVG: (+ container: HTMLElement | string,+ options?: Record<string, unknown>,+ ) => void;+ };++ type FlowchartApi = {+ parse: (code: string) => FlowchartInstance;+ };++ let cachedFlowchart: FlowchartApi | null = null;+ let lastInstance: FlowchartInstance | null = null;++ async function loadFlowchart(): Promise<FlowchartApi> {+ if (cachedFlowchart) return cachedFlowchart;+ const mod = (await import("flowchart.js")) as {+ default: FlowchartApi;+ } & FlowchartApi;+ const api = (mod.default ?? mod) as FlowchartApi;+ cachedFlowchart = api;+ return api;+ }++ function readThemeOptions(): Record<string, unknown> {+ if (typeof window === "undefined") {+ return {};+ }+ const cs = window.getComputedStyle(document.documentElement);+ const accent = cs.getPropertyValue("--accent").trim() || "#4a90e2";+ const text = cs.getPropertyValue("--text").trim() || "#222";+ const surface = cs.getPropertyValue("--surface").trim() || "#fff";+ return {+ "line-color": accent,+ "font-color": text,+ "element-color": text,+ fill: surface,+ "line-width": 2,+ "font-size": 14,+ "yes-text": "sim",+ "no-text": "não",+ };+ }++ async function render(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) {+ renderState = { kind: "idle" };+ return;+ }+ renderState = { kind: "loading" };+ try {+ const api = await loadFlowchart();+ if (token !== renderToken) return;+ const instance = api.parse(trimmed);+ if (lastInstance) {+ try {+ lastInstance.clean();+ } catch {}+ lastInstance = null;+ }+ if (svgHost) {+ svgHost.innerHTML = "";+ }+ renderState = { kind: "rendered" };+ await Promise.resolve();+ if (token !== renderToken) return;+ if (!svgHost) {+ renderState = { kind: "error", message: "container ausente" };+ return;+ }+ instance.drawSVG(svgHost, readThemeOptions());+ lastInstance = instance;+ const _id = `fc-${blockId}-${token}`;+ void _id;+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message };+ }+ }++ let editingValue = $state(source);++ $effect(() => {+ editingValue = source;+ if (mode === "render") {+ void render(source);+ }+ });++ function toggleMode() {+ if (mode === "render") {+ editingValue = source;+ mode = "source";+ } else {+ mode = "render";+ onSourceChange?.(editingValue);+ void render(editingValue);+ }+ }++ function onSourceInput(event: Event) {+ const target = event.target as HTMLTextAreaElement;+ editingValue = target.value;+ }++ function onSourceBlur() {+ if (editingValue !== source) {+ onSourceChange?.(editingValue);+ }+ }++ onDestroy(() => {+ renderToken++;+ if (lastInstance) {+ try {+ lastInstance.clean();+ } catch {}+ lastInstance = null;+ }+ });+</script>++<div class="flowchart-block" data-flowchart data-mode={mode}>+ <header class="flowchart-head" contenteditable="false">+ <span class="flowchart-icon" aria-hidden="true">⇄</span>+ <span class="flowchart-label">flowchart</span>+ <button+ type="button"+ class="flowchart-toggle"+ onclick={toggleMode}+ title={mode === "render" ? "Editar source" : "Voltar pro diagrama"}+ >+ {mode === "render" ? "‹/›" : "▶"}+ </button>+ </header>++ {#if mode === "source"}+ <textarea+ class="flowchart-source"+ value={editingValue}+ oninput={onSourceInput}+ onblur={onSourceBlur}+ spellcheck="false"+ rows={Math.max(4, editingValue.split("\n").length)}+ aria-label="Source do diagrama flowchart"+ ></textarea>+ {:else if renderState.kind === "idle"}+ <p class="flowchart-state">Sem source. Clique em ‹/› para editar.</p>+ {:else if renderState.kind === "loading"}+ <p class="flowchart-state">renderizando…</p>+ {:else if renderState.kind === "error"}+ <div class="flowchart-error">+ <p class="flowchart-error-msg">erro: {renderState.message}</p>+ <button type="button" class="flowchart-edit-btn" onclick={toggleMode}+ >Editar source</button>+ </div>+ {/if}++ <div+ class="flowchart-svg"+ bind:this={svgHost}+ style:display={mode === "render" && renderState.kind === "rendered"+ ? "flex"+ : "none"}+ ></div>+</div>++<style>+ .flowchart-block {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--input-border) 12%, transparent);+ border-left: 3px solid var(--accent);+ border-radius: 0 var(--border-radius) var(--border-radius) 0;+ font-size: 12px;+ }+ .flowchart-head {+ display: flex;+ align-items: center;+ gap: 6px;+ user-select: none;+ }+ .flowchart-icon {+ color: var(--accent);+ font-size: 13px;+ }+ .flowchart-label {+ flex: 1 1 auto;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--secondary);+ }+ .flowchart-toggle {+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .flowchart-toggle:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .flowchart-source {+ width: 100%;+ box-sizing: border-box;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ line-height: 1.5;+ background: var(--surface);+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ padding: 8px 10px;+ color: var(--text);+ resize: vertical;+ min-height: 100px;+ }+ .flowchart-source:focus {+ outline: 2px solid var(--accent);+ outline-offset: -1px;+ }+ .flowchart-state {+ margin: 0;+ color: var(--tertiary);+ font-size: 11px;+ }+ .flowchart-svg {+ justify-content: center;+ overflow-x: auto;+ background: var(--surface);+ border-radius: var(--border-radius);+ padding: 8px;+ }+ .flowchart-svg :global(svg) {+ max-width: 100%;+ height: auto;+ }+ .flowchart-error {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 6px 8px;+ background: color-mix(in oklab, var(--error, #e74c3c) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--error, #e74c3c) 30%, transparent);+ border-radius: var(--border-radius);+ color: var(--error, #e74c3c);+ }+ .flowchart-error-msg {+ margin: 0;+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ word-break: break-word;+ }+ .flowchart-edit-btn {+ align-self: flex-start;+ border: 0;+ background: transparent;+ color: var(--accent);+ font: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .flowchart-edit-btn:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/MermaidView.svelte b/src/lib/study-components/notes/MermaidView.sveltenew file mode 100644index 00000000..41495911--- /dev/null+++ b/src/lib/study-components/notes/MermaidView.svelte@@ -0,0 +1,273 @@+<script lang="ts">+ import { onDestroy } from "svelte";++ type Props = {+ source: string;+ blockId: string;+ onSourceChange?: (next: string) => void;+ };++ let { source, blockId, onSourceChange }: Props = $props();++ type RenderState =+ | { kind: "idle" }+ | { kind: "loading" }+ | { kind: "rendered"; svg: string }+ | { kind: "error"; message: string };++ let renderState = $state<RenderState>({ kind: "idle" });+ let mode = $state<"render" | "source">("render");+ let renderToken = 0;++ type MermaidApi = {+ initialize: (config: Record<string, unknown>) => void;+ render: (id: string, src: string) => Promise<{ svg: string }>;+ };++ let cachedMermaid: MermaidApi | null = null;+ let cachedTheme: "dark" | "default" | null = null;++ function detectTheme(): "dark" | "default" {+ if (typeof window === "undefined") return "default";+ const isDark =+ window.matchMedia &&+ window.matchMedia("(prefers-color-scheme: dark)").matches;+ return isDark ? "dark" : "default";+ }++ async function loadMermaid(): Promise<MermaidApi> {+ if (cachedMermaid) return cachedMermaid;+ const mod = (await import("mermaid")) as { default: MermaidApi };+ const api = mod.default;+ const theme = detectTheme();+ api.initialize({+ startOnLoad: false,+ theme,+ securityLevel: "strict",+ fontFamily: "inherit",+ });+ cachedMermaid = api;+ cachedTheme = theme;+ return api;+ }++ function ensureThemeFresh(api: MermaidApi) {+ const current = detectTheme();+ if (current !== cachedTheme) {+ api.initialize({+ startOnLoad: false,+ theme: current,+ securityLevel: "strict",+ fontFamily: "inherit",+ });+ cachedTheme = current;+ }+ }++ async function render(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) {+ renderState = { kind: "idle" };+ return;+ }+ renderState = { kind: "loading" };+ try {+ const api = await loadMermaid();+ ensureThemeFresh(api);+ const id = `mmd-${blockId}-${token}`;+ const { svg } = await api.render(id, trimmed);+ if (token !== renderToken) return;+ renderState = { kind: "rendered", svg };+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message };+ }+ }++ let editingValue = $state(source);++ $effect(() => {+ editingValue = source;+ if (mode === "render") {+ void render(source);+ }+ });++ function toggleMode() {+ if (mode === "render") {+ editingValue = source;+ mode = "source";+ } else {+ mode = "render";+ onSourceChange?.(editingValue);+ void render(editingValue);+ }+ }++ function onSourceInput(event: Event) {+ const target = event.target as HTMLTextAreaElement;+ editingValue = target.value;+ }++ function onSourceBlur() {+ if (editingValue !== source) {+ onSourceChange?.(editingValue);+ }+ }++ onDestroy(() => {+ renderToken++;+ });+</script>++<div class="mermaid-block" data-mermaid data-mode={mode}>+ <header class="mermaid-head" contenteditable="false">+ <span class="mermaid-icon" aria-hidden="true">▦</span>+ <span class="mermaid-label">mermaid</span>+ <button+ type="button"+ class="mermaid-toggle"+ onclick={toggleMode}+ title={mode === "render" ? "Editar source" : "Voltar pro diagrama"}+ >+ {mode === "render" ? "‹/›" : "▶"}+ </button>+ </header>++ {#if mode === "source"}+ <textarea+ class="mermaid-source"+ value={editingValue}+ oninput={onSourceInput}+ onblur={onSourceBlur}+ spellcheck="false"+ rows={Math.max(3, editingValue.split("\n").length)}+ aria-label="Source do diagrama mermaid"+ ></textarea>+ {:else if renderState.kind === "idle"}+ <p class="mermaid-state">Sem source. Clique em ‹/› para editar.</p>+ {:else if renderState.kind === "loading"}+ <p class="mermaid-state">renderizando…</p>+ {:else if renderState.kind === "rendered"}+ <div class="mermaid-svg">+ {@html renderState.svg}+ </div>+ {:else if renderState.kind === "error"}+ <div class="mermaid-error">+ <p class="mermaid-error-msg">erro: {renderState.message}</p>+ <button type="button" class="mermaid-edit-btn" onclick={toggleMode}+ >Editar source</button>+ </div>+ {/if}+</div>++<style>+ .mermaid-block {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--input-border) 12%, transparent);+ border-left: 3px solid var(--accent);+ border-radius: 0 var(--border-radius) var(--border-radius) 0;+ font-size: 12px;+ }+ .mermaid-head {+ display: flex;+ align-items: center;+ gap: 6px;+ user-select: none;+ }+ .mermaid-icon {+ color: var(--accent);+ font-size: 13px;+ }+ .mermaid-label {+ flex: 1 1 auto;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--secondary);+ }+ .mermaid-toggle {+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .mermaid-toggle:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .mermaid-source {+ width: 100%;+ box-sizing: border-box;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ line-height: 1.5;+ background: var(--surface);+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ padding: 8px 10px;+ color: var(--text);+ resize: vertical;+ min-height: 80px;+ }+ .mermaid-source:focus {+ outline: 2px solid var(--accent);+ outline-offset: -1px;+ }+ .mermaid-state {+ margin: 0;+ color: var(--tertiary);+ font-size: 11px;+ }+ .mermaid-svg {+ display: flex;+ justify-content: center;+ overflow-x: auto;+ background: var(--surface);+ border-radius: var(--border-radius);+ padding: 8px;+ }+ .mermaid-svg :global(svg) {+ max-width: 100%;+ height: auto;+ }+ .mermaid-error {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 6px 8px;+ background: color-mix(in oklab, var(--error, #e74c3c) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--error, #e74c3c) 30%, transparent);+ border-radius: var(--border-radius);+ color: var(--error, #e74c3c);+ }+ .mermaid-error-msg {+ margin: 0;+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ word-break: break-word;+ }+ .mermaid-edit-btn {+ align-self: flex-start;+ border: 0;+ background: transparent;+ color: var(--accent);+ font: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .mermaid-edit-btn:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/MindmapView.svelte b/src/lib/study-components/notes/MindmapView.sveltenew file mode 100644index 00000000..f65a2348--- /dev/null+++ b/src/lib/study-components/notes/MindmapView.svelte@@ -0,0 +1,307 @@+<script lang="ts">+ import { onDestroy } from "svelte";++ type Props = {+ source: string;+ blockId: string;+ onSourceChange?: (next: string) => void;+ };++ let { source, blockId, onSourceChange }: Props = $props();++ type RenderState =+ | { kind: "idle" }+ | { kind: "loading" }+ | { kind: "rendered" }+ | { kind: "error"; message: string };++ let renderState = $state<RenderState>({ kind: "idle" });+ let mode = $state<"render" | "source">("render");+ let renderToken = 0;+ let svgHost: SVGSVGElement | null = $state(null);++ type PureNode = { content: string; children?: PureNode[]; payload?: unknown };++ type TransformResult = { root: PureNode };++ type TransformerCtor = new () => {+ transform: (src: string) => TransformResult;+ };++ type MarkmapInstance = {+ setData: (root: PureNode) => Promise<void>;+ fit: () => Promise<void>;+ destroy: () => void;+ };++ type MarkmapStatic = {+ create: (+ svg: SVGSVGElement,+ opts?: Record<string, unknown>,+ data?: PureNode | null,+ ) => MarkmapInstance;+ };++ let cachedTransformerCtor: TransformerCtor | null = null;+ let cachedMarkmap: MarkmapStatic | null = null;+ let lastInstance: MarkmapInstance | null = null;++ async function loadLibs(): Promise<{+ Transformer: TransformerCtor;+ Markmap: MarkmapStatic;+ }> {+ if (!cachedTransformerCtor) {+ const mod = (await import("markmap-lib")) as {+ Transformer: TransformerCtor;+ };+ cachedTransformerCtor = mod.Transformer;+ }+ if (!cachedMarkmap) {+ const mod = (await import("markmap-view")) as { Markmap: MarkmapStatic };+ cachedMarkmap = mod.Markmap;+ }+ return { Transformer: cachedTransformerCtor, Markmap: cachedMarkmap };+ }++ function readThemeOptions(): Record<string, unknown> {+ if (typeof window === "undefined") return {};+ const cs = window.getComputedStyle(document.documentElement);+ const accent = cs.getPropertyValue("--accent").trim() || "#4a90e2";+ return {+ color: () => accent,+ duration: 200,+ paddingX: 16,+ autoFit: true,+ };+ }++ async function render(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) {+ renderState = { kind: "idle" };+ return;+ }+ renderState = { kind: "loading" };+ try {+ const { Transformer, Markmap } = await loadLibs();+ if (token !== renderToken) return;+ const transformer = new Transformer();+ const { root } = transformer.transform(trimmed);+ if (lastInstance) {+ try {+ lastInstance.destroy();+ } catch {}+ lastInstance = null;+ }+ renderState = { kind: "rendered" };+ await Promise.resolve();+ if (token !== renderToken) return;+ if (!svgHost) {+ renderState = { kind: "error", message: "container ausente" };+ return;+ }+ svgHost.innerHTML = "";+ const instance = Markmap.create(svgHost, readThemeOptions(), root);+ lastInstance = instance;+ await instance.fit();+ const _id = `mm-${blockId}-${token}`;+ void _id;+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message };+ }+ }++ let editingValue = $state(source);++ $effect(() => {+ editingValue = source;+ if (mode === "render") {+ void render(source);+ }+ });++ function toggleMode() {+ if (mode === "render") {+ editingValue = source;+ mode = "source";+ } else {+ mode = "render";+ onSourceChange?.(editingValue);+ void render(editingValue);+ }+ }++ function onSourceInput(event: Event) {+ const target = event.target as HTMLTextAreaElement;+ editingValue = target.value;+ }++ function onSourceBlur() {+ if (editingValue !== source) {+ onSourceChange?.(editingValue);+ }+ }++ onDestroy(() => {+ renderToken++;+ if (lastInstance) {+ try {+ lastInstance.destroy();+ } catch {}+ lastInstance = null;+ }+ });+</script>++<div class="mindmap-block" data-mindmap data-mode={mode}>+ <header class="mindmap-head" contenteditable="false">+ <span class="mindmap-icon" aria-hidden="true">⌘</span>+ <span class="mindmap-label">mindmap</span>+ <button+ type="button"+ class="mindmap-toggle"+ onclick={toggleMode}+ title={mode === "render" ? "Editar source" : "Voltar pro mapa"}+ >+ {mode === "render" ? "‹/›" : "▶"}+ </button>+ </header>++ {#if mode === "source"}+ <textarea+ class="mindmap-source"+ value={editingValue}+ oninput={onSourceInput}+ onblur={onSourceBlur}+ spellcheck="false"+ rows={Math.max(4, editingValue.split("\n").length)}+ aria-label="Source do mindmap (markdown indentado)"+ ></textarea>+ {:else if renderState.kind === "idle"}+ <p class="mindmap-state">Sem source. Clique em ‹/› para editar.</p>+ {:else if renderState.kind === "loading"}+ <p class="mindmap-state">renderizando…</p>+ {:else if renderState.kind === "error"}+ <div class="mindmap-error">+ <p class="mindmap-error-msg">erro: {renderState.message}</p>+ <button type="button" class="mindmap-edit-btn" onclick={toggleMode}+ >Editar source</button>+ </div>+ {/if}++ <svg+ class="mindmap-svg"+ bind:this={svgHost}+ style:display={mode === "render" && renderState.kind === "rendered"+ ? "block"+ : "none"}+ ></svg>+</div>++<style>+ .mindmap-block {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--input-border) 12%, transparent);+ border-left: 3px solid var(--accent);+ border-radius: 0 var(--border-radius) var(--border-radius) 0;+ font-size: 12px;+ }+ .mindmap-head {+ display: flex;+ align-items: center;+ gap: 6px;+ user-select: none;+ }+ .mindmap-icon {+ color: var(--accent);+ font-size: 13px;+ }+ .mindmap-label {+ flex: 1 1 auto;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--secondary);+ }+ .mindmap-toggle {+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .mindmap-toggle:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .mindmap-source {+ width: 100%;+ box-sizing: border-box;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ line-height: 1.5;+ background: var(--surface);+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ padding: 8px 10px;+ color: var(--text);+ resize: vertical;+ min-height: 100px;+ }+ .mindmap-source:focus {+ outline: 2px solid var(--accent);+ outline-offset: -1px;+ }+ .mindmap-state {+ margin: 0;+ color: var(--tertiary);+ font-size: 11px;+ }+ .mindmap-svg {+ width: 100%;+ height: 360px;+ background: var(--surface);+ border-radius: var(--border-radius);+ padding: 8px;+ box-sizing: border-box;+ }+ .mindmap-error {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 6px 8px;+ background: color-mix(in oklab, var(--error, #e74c3c) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--error, #e74c3c) 30%, transparent);+ border-radius: var(--border-radius);+ color: var(--error, #e74c3c);+ }+ .mindmap-error-msg {+ margin: 0;+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ word-break: break-word;+ }+ .mindmap-edit-btn {+ align-self: flex-start;+ border: 0;+ background: transparent;+ color: var(--accent);+ font: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .mindmap-edit-btn:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/PlantumlView.svelte b/src/lib/study-components/notes/PlantumlView.sveltenew file mode 100644index 00000000..a77015c1--- /dev/null+++ b/src/lib/study-components/notes/PlantumlView.svelte@@ -0,0 +1,387 @@+<script lang="ts">+ import { onDestroy } from "svelte";++ type Props = {+ source: string;+ blockId: string;+ onSourceChange?: (next: string) => void;+ };++ let { source, blockId, onSourceChange }: Props = $props();++ type RenderState =+ | { kind: "idle" }+ | { kind: "loading" }+ | { kind: "rendered" }+ | { kind: "error"; message: string }+ | { kind: "remote-rendering" }+ | { kind: "remote-rendered" };++ let renderState = $state<RenderState>({ kind: "idle" });+ let mode = $state<"render" | "source">("render");+ let renderToken = 0;+ let host: HTMLDivElement | null = $state(null);++ type GraphvizLike = {+ layout: (dot: string, format: string, engine: string) => string;+ };+ type PlantumlLittleModule = {+ convert: (puml: string) => string;+ setup: (opts: { graphviz: GraphvizLike }) => () => void;+ hasGraphvizBridge: () => boolean;+ };++ type Loaded = { convert: (puml: string) => string };++ let loadPromise: Promise<Loaded> | null = null;++ async function loadLib(): Promise<Loaded> {+ if (loadPromise) return loadPromise;+ loadPromise = (async () => {+ const [pumlMod, gvMod] = await Promise.all([+ import("@kookyleo/plantuml-little-web") as unknown as Promise<PlantumlLittleModule>,+ import("@kookyleo/graphviz-anywhere-web") as unknown as Promise<{+ Graphviz: { load: () => Promise<GraphvizLike> };+ }>,+ ]);+ const graphviz = await gvMod.Graphviz.load();+ pumlMod.setup({ graphviz });+ return { convert: (puml: string) => pumlMod.convert(puml) };+ })();+ try {+ return await loadPromise;+ } catch (err) {+ loadPromise = null;+ throw err;+ }+ }++ function readAccentColor(): string {+ if (typeof window === "undefined") return "currentColor";+ const cs = window.getComputedStyle(document.documentElement);+ return cs.getPropertyValue("--text").trim() || "currentColor";+ }++ async function render(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) {+ renderState = { kind: "idle" };+ return;+ }+ renderState = { kind: "loading" };+ try {+ const lib = await loadLib();+ if (token !== renderToken) return;+ const svg = lib.convert(trimmed);+ if (token !== renderToken) return;+ if (!host) {+ renderState = { kind: "error", message: "container ausente" };+ return;+ }+ host.innerHTML = svg;+ const _id = `plantuml-${blockId}-${token}`;+ void _id;+ renderState = { kind: "rendered" };+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message };+ }+ }++ function deflateBase64(bytes: Uint8Array): string {+ const PLANT_ALPHABET =+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";+ let result = "";+ for (let i = 0; i < bytes.length; i += 3) {+ const b1 = bytes[i] ?? 0;+ const b2 = bytes[i + 1] ?? 0;+ const b3 = bytes[i + 2] ?? 0;+ const c1 = b1 >> 2;+ const c2 = ((b1 & 0x3) << 4) | (b2 >> 4);+ const c3 = ((b2 & 0xf) << 2) | (b3 >> 6);+ const c4 = b3 & 0x3f;+ result +=+ PLANT_ALPHABET[c1 & 0x3f] ++ PLANT_ALPHABET[c2 & 0x3f] ++ PLANT_ALPHABET[c3 & 0x3f] ++ PLANT_ALPHABET[c4 & 0x3f];+ }+ return result;+ }++ async function compressForUrl(text: string): Promise<string> {+ const G = globalThis as unknown as {+ CompressionStream?: new (format: string) => GenericTransformStream;+ };+ if (!G.CompressionStream) {+ throw new Error("CompressionStream indisponível neste runtime");+ }+ const ds = new G.CompressionStream("deflate-raw");+ const stream = new Blob([text]).stream().pipeThrough(ds);+ const compressed = await new Response(stream).arrayBuffer();+ return deflateBase64(new Uint8Array(compressed));+ }++ async function renderRemote(src: string) {+ const token = ++renderToken;+ const trimmed = src.trim();+ if (!trimmed) return;+ renderState = { kind: "remote-rendering" };+ try {+ const encoded = await compressForUrl(trimmed);+ if (token !== renderToken) return;+ const url = `https://www.plantuml.com/plantuml/svg/~1${encoded}`;+ const resp = await fetch(url);+ if (!resp.ok) {+ renderState = {+ kind: "error",+ message: `plantuml.com respondeu ${resp.status}`,+ };+ return;+ }+ const svg = await resp.text();+ if (token !== renderToken) return;+ if (!host) {+ renderState = { kind: "error", message: "container ausente" };+ return;+ }+ host.innerHTML = svg;+ renderState = { kind: "remote-rendered" };+ } catch (err) {+ if (token !== renderToken) return;+ const message = err instanceof Error ? err.message : String(err);+ renderState = { kind: "error", message: `fallback: ${message}` };+ }+ }++ let editingValue = $state(source);++ $effect(() => {+ editingValue = source;+ if (mode === "render") {+ void render(source);+ }+ });++ function toggleMode() {+ if (mode === "render") {+ editingValue = source;+ mode = "source";+ } else {+ mode = "render";+ onSourceChange?.(editingValue);+ void render(editingValue);+ }+ }++ function onSourceInput(event: Event) {+ const target = event.target as HTMLTextAreaElement;+ editingValue = target.value;+ }++ function onSourceBlur() {+ if (editingValue !== source) {+ onSourceChange?.(editingValue);+ }+ }++ onDestroy(() => {+ renderToken++;+ if (host) {+ try {+ host.innerHTML = "";+ } catch {}+ }+ });++ void readAccentColor;+</script>++<div class="puml-block" data-plantuml data-mode={mode}>+ <header class="puml-head" contenteditable="false">+ <span class="puml-icon" aria-hidden="true">⚙</span>+ <span class="puml-label">plantuml</span>+ {#if renderState.kind === "remote-rendered"}+ <span class="puml-remote-badge" title="renderizado via plantuml.com">via plantuml.com</span>+ {/if}+ <button+ type="button"+ class="puml-toggle"+ onclick={toggleMode}+ title={mode === "render" ? "Editar source" : "Voltar pro diagrama"}+ >+ {mode === "render" ? "‹/›" : "▶"}+ </button>+ </header>++ {#if mode === "source"}+ <textarea+ class="puml-source"+ value={editingValue}+ oninput={onSourceInput}+ onblur={onSourceBlur}+ spellcheck="false"+ rows={Math.max(6, editingValue.split("\n").length)}+ aria-label="Source do diagrama PlantUML"+ ></textarea>+ {:else if renderState.kind === "idle"}+ <p class="puml-state">Sem source. Clique em ‹/› para editar.</p>+ {:else if renderState.kind === "loading"}+ <p class="puml-state">renderizando…</p>+ {:else if renderState.kind === "remote-rendering"}+ <p class="puml-state">enviando a plantuml.com…</p>+ {:else if renderState.kind === "error"}+ <div class="puml-error">+ <p class="puml-error-msg">erro local: {renderState.message}</p>+ <div class="puml-error-actions">+ <button+ type="button"+ class="puml-edit-btn"+ onclick={toggleMode}>Editar source</button>+ <button+ type="button"+ class="puml-remote-btn"+ onclick={() => void renderRemote(source)}+ title="Envia o diagrama pra plantuml.com (terceiro pode logar)"+ >Render via plantuml.com</button>+ </div>+ </div>+ {/if}++ <div+ class="puml-host"+ bind:this={host}+ style:display={mode === "render" &&+ (renderState.kind === "rendered" || renderState.kind === "remote-rendered")+ ? "block"+ : "none"}+ ></div>+</div>++<style>+ .puml-block {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: color-mix(in oklab, var(--input-border) 12%, transparent);+ border-left: 3px solid var(--accent);+ border-radius: 0 var(--border-radius) var(--border-radius) 0;+ font-size: 12px;+ }+ .puml-head {+ display: flex;+ align-items: center;+ gap: 6px;+ user-select: none;+ }+ .puml-icon {+ color: var(--accent);+ font-size: 13px;+ }+ .puml-label {+ flex: 1 1 auto;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--secondary);+ }+ .puml-remote-badge {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 10px;+ padding: 1px 6px;+ border-radius: 3px;+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .puml-toggle {+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .puml-toggle:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }+ .puml-source {+ width: 100%;+ box-sizing: border-box;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ line-height: 1.5;+ background: var(--surface);+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ padding: 8px 10px;+ color: var(--text);+ resize: vertical;+ min-height: 120px;+ }+ .puml-source:focus {+ outline: 2px solid var(--accent);+ outline-offset: -1px;+ }+ .puml-state {+ margin: 0;+ color: var(--tertiary);+ font-size: 11px;+ }+ .puml-host {+ width: 100%;+ background: var(--surface);+ border-radius: var(--border-radius);+ padding: 12px;+ box-sizing: border-box;+ overflow-x: auto;+ }+ .puml-host :global(svg) {+ max-width: 100%;+ height: auto;+ }+ .puml-error {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 6px 8px;+ background: color-mix(in oklab, var(--error, #e74c3c) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--error, #e74c3c) 30%, transparent);+ border-radius: var(--border-radius);+ color: var(--error, #e74c3c);+ }+ .puml-error-msg {+ margin: 0;+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ word-break: break-word;+ }+ .puml-error-actions {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ }+ .puml-edit-btn,+ .puml-remote-btn {+ border: 0;+ background: transparent;+ color: var(--accent);+ font: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 3px;+ }+ .puml-edit-btn:hover,+ .puml-remote-btn:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+ .puml-remote-btn {+ border: 1px dashed color-mix(in oklab, var(--accent) 40%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/abc-node.ts b/src/lib/study-components/notes/abc-node.tsnew file mode 100644index 00000000..486d5a69--- /dev/null+++ b/src/lib/study-components/notes/abc-node.ts@@ -0,0 +1,238 @@+import { Node, mergeAttributes } from "@tiptap/core";+import { mount, unmount, type Component } from "svelte";+import AbcView from "./AbcView.svelte";++declare module "@tiptap/core" {+ interface Commands<ReturnType> {+ abcBlock: {+ setAbc: (source?: string) => ReturnType;+ };+ }+}++type MarkdownItToken = {+ type: string;+ tag?: string;+ info?: string;+ content?: string;+ markup?: string;+ block?: boolean;+ level?: number;+ meta?: unknown;+ attrs?: Array<[string, string]> | null;+ attrSet?: (name: string, value: string) => void;+ hidden?: boolean;+};++type MarkdownItState = {+ src: string;+ bMarks: number[];+ eMarks: number[];+ tShift: number[];+ sCount: number[];+ line: number;+ push: (type: string, tag: string, nesting: number) => MarkdownItToken;+};++type MarkdownItRule = (+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+) => boolean;++type MarkdownItBlockRuler = {+ before: (+ name: string,+ ruleName: string,+ rule: MarkdownItRule,+ options?: { alt?: string[] },+ ) => void;+};++type MarkdownItInstance = {+ block: { ruler: MarkdownItBlockRuler };+};++const FENCE_OPEN = /^```abc\s*$/;+const FENCE_CLOSE = /^```\s*$/;++function abcFenceRule(+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+): boolean {+ const startPos = state.bMarks[startLine] + state.tShift[startLine];+ const max = state.eMarks[startLine];+ if (state.sCount[startLine] - state.tShift[startLine] >= 4) return false;+ const opening = state.src.slice(startPos, max);+ if (!FENCE_OPEN.test(opening)) return false;+ if (silent) return true;++ let nextLine = startLine + 1;+ let closed = false;+ while (nextLine < endLine) {+ const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];+ const lineEnd = state.eMarks[nextLine];+ const text = state.src.slice(lineStart, lineEnd);+ if (FENCE_CLOSE.test(text)) {+ closed = true;+ break;+ }+ nextLine++;+ }++ const lines: string[] = [];+ for (let i = startLine + 1; i < nextLine; i++) {+ const ls = state.bMarks[i] + state.tShift[i];+ const le = state.eMarks[i];+ lines.push(state.src.slice(ls, le));+ }+ const source = lines.join("\n");++ const token = state.push("abc", "div", 0);+ token.block = true;+ token.markup = "```";+ token.info = "abc";+ token.content = source;+ if (token.attrSet) {+ token.attrSet("source", source);+ } else {+ token.attrs = [["source", source]];+ }++ state.line = closed ? nextLine + 1 : nextLine;+ return true;+}++export const AbcBlock = Node.create({+ name: "abc",+ group: "block",+ atom: false,+ selectable: true,+ draggable: true,+ defining: true,++ addAttributes() {+ return {+ source: {+ default: "",+ parseHTML: (el) => el.getAttribute("data-abc-source") ?? "",+ renderHTML: (attrs) => ({+ "data-abc-source": String(attrs.source ?? ""),+ }),+ },+ };+ },++ parseHTML() {+ return [{ tag: "div[data-abc]" }];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ class: "tiptap-abc-block",+ "data-abc": "",+ }),+ "",+ ];+ },++ addCommands() {+ return {+ setAbc:+ (+ source = "X:1\nT:Scale\nM:4/4\nL:1/4\nK:C\nC D E F | G A B c |",+ ) =>+ ({ commands }) =>+ commands.insertContent({+ type: this.name,+ attrs: { source },+ }),+ };+ },++ addNodeView() {+ return ({ node, editor, getPos }) => {+ const dom = document.createElement("div");+ dom.className = "tiptap-abc-block";+ dom.setAttribute("data-abc", "");+ dom.setAttribute("contenteditable", "false");++ let lastSource = String(node.attrs.source ?? "");+ const blockId = Math.random().toString(36).slice(2, 10);++ const view = mount(AbcView as unknown as Component, {+ target: dom,+ props: {+ source: lastSource,+ blockId,+ onSourceChange: (next: string) => {+ const pos = typeof getPos === "function" ? getPos() : null;+ if (pos == null) return;+ lastSource = next;+ editor+ .chain()+ .command(({ tr }) => {+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ source: next,+ });+ return true;+ })+ .run();+ },+ },+ });++ return {+ dom,+ update: (updatedNode) => {+ if (updatedNode.type.name !== node.type.name) return false;+ const next = String(updatedNode.attrs.source ?? "");+ if (next !== lastSource) {+ lastSource = next;+ (view as unknown as { source?: string }).source = next;+ }+ return true;+ },+ destroy: () => {+ try {+ unmount(view);+ } catch {}+ },+ };+ };+ },++ addStorage() {+ return {+ markdown: {+ serialize(+ state: { write: (s: string) => void; closeBlock: (n: unknown) => void },+ node: { attrs: { source?: string } },+ ) {+ const src = String(node.attrs.source ?? "").replace(/\s+$/g, "");+ state.write("```abc\n");+ if (src.length > 0) {+ state.write(src);+ state.write("\n");+ }+ state.write("```");+ state.closeBlock(node);+ },+ parse: {+ setup(md: MarkdownItInstance) {+ md.block.ruler.before("fence", "abc_fence", abcFenceRule, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ return undefined;+ },+ },+ },+ };+ },+});diff --git a/src/lib/study-components/notes/flowchart-node.ts b/src/lib/study-components/notes/flowchart-node.tsnew file mode 100644index 00000000..9e3e44de--- /dev/null+++ b/src/lib/study-components/notes/flowchart-node.ts@@ -0,0 +1,236 @@+import { Node, mergeAttributes } from "@tiptap/core";+import { mount, unmount, type Component } from "svelte";+import FlowchartView from "./FlowchartView.svelte";++declare module "@tiptap/core" {+ interface Commands<ReturnType> {+ flowchartBlock: {+ setFlowchart: (source?: string) => ReturnType;+ };+ }+}++type MarkdownItToken = {+ type: string;+ tag?: string;+ info?: string;+ content?: string;+ markup?: string;+ block?: boolean;+ level?: number;+ meta?: unknown;+ attrs?: Array<[string, string]> | null;+ attrSet?: (name: string, value: string) => void;+ hidden?: boolean;+};++type MarkdownItState = {+ src: string;+ bMarks: number[];+ eMarks: number[];+ tShift: number[];+ sCount: number[];+ line: number;+ push: (type: string, tag: string, nesting: number) => MarkdownItToken;+};++type MarkdownItRule = (+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+) => boolean;++type MarkdownItBlockRuler = {+ before: (+ name: string,+ ruleName: string,+ rule: MarkdownItRule,+ options?: { alt?: string[] },+ ) => void;+};++type MarkdownItInstance = {+ block: { ruler: MarkdownItBlockRuler };+};++const FENCE_OPEN = /^```flowchart\s*$/;+const FENCE_CLOSE = /^```\s*$/;++function flowchartFenceRule(+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+): boolean {+ const startPos = state.bMarks[startLine] + state.tShift[startLine];+ const max = state.eMarks[startLine];+ if (state.sCount[startLine] - state.tShift[startLine] >= 4) return false;+ const opening = state.src.slice(startPos, max);+ if (!FENCE_OPEN.test(opening)) return false;+ if (silent) return true;++ let nextLine = startLine + 1;+ let closed = false;+ while (nextLine < endLine) {+ const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];+ const lineEnd = state.eMarks[nextLine];+ const text = state.src.slice(lineStart, lineEnd);+ if (FENCE_CLOSE.test(text)) {+ closed = true;+ break;+ }+ nextLine++;+ }++ const lines: string[] = [];+ for (let i = startLine + 1; i < nextLine; i++) {+ const ls = state.bMarks[i] + state.tShift[i];+ const le = state.eMarks[i];+ lines.push(state.src.slice(ls, le));+ }+ const source = lines.join("\n");++ const token = state.push("flowchart", "div", 0);+ token.block = true;+ token.markup = "```";+ token.info = "flowchart";+ token.content = source;+ if (token.attrSet) {+ token.attrSet("source", source);+ } else {+ token.attrs = [["source", source]];+ }++ state.line = closed ? nextLine + 1 : nextLine;+ return true;+}++export const FlowchartBlock = Node.create({+ name: "flowchart",+ group: "block",+ atom: false,+ selectable: true,+ draggable: true,+ defining: true,++ addAttributes() {+ return {+ source: {+ default: "",+ parseHTML: (el) => el.getAttribute("data-flowchart-source") ?? "",+ renderHTML: (attrs) => ({+ "data-flowchart-source": String(attrs.source ?? ""),+ }),+ },+ };+ },++ parseHTML() {+ return [{ tag: "div[data-flowchart]" }];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ class: "tiptap-flowchart-block",+ "data-flowchart": "",+ }),+ "",+ ];+ },++ addCommands() {+ return {+ setFlowchart:+ (source = "st=>start: Start\nop=>operation: Step\ne=>end: End\nst->op->e") =>+ ({ commands }) =>+ commands.insertContent({+ type: this.name,+ attrs: { source },+ }),+ };+ },++ addNodeView() {+ return ({ node, editor, getPos }) => {+ const dom = document.createElement("div");+ dom.className = "tiptap-flowchart-block";+ dom.setAttribute("data-flowchart", "");+ dom.setAttribute("contenteditable", "false");++ let lastSource = String(node.attrs.source ?? "");+ const blockId = Math.random().toString(36).slice(2, 10);++ const view = mount(FlowchartView as unknown as Component, {+ target: dom,+ props: {+ source: lastSource,+ blockId,+ onSourceChange: (next: string) => {+ const pos = typeof getPos === "function" ? getPos() : null;+ if (pos == null) return;+ lastSource = next;+ editor+ .chain()+ .command(({ tr }) => {+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ source: next,+ });+ return true;+ })+ .run();+ },+ },+ });++ return {+ dom,+ update: (updatedNode) => {+ if (updatedNode.type.name !== node.type.name) return false;+ const next = String(updatedNode.attrs.source ?? "");+ if (next !== lastSource) {+ lastSource = next;+ (view as unknown as { source?: string }).source = next;+ }+ return true;+ },+ destroy: () => {+ try {+ unmount(view);+ } catch {}+ },+ };+ };+ },++ addStorage() {+ return {+ markdown: {+ serialize(+ state: { write: (s: string) => void; closeBlock: (n: unknown) => void },+ node: { attrs: { source?: string } },+ ) {+ const src = String(node.attrs.source ?? "").replace(/\s+$/g, "");+ state.write("```flowchart\n");+ if (src.length > 0) {+ state.write(src);+ state.write("\n");+ }+ state.write("```");+ state.closeBlock(node);+ },+ parse: {+ setup(md: MarkdownItInstance) {+ md.block.ruler.before("fence", "flowchart_fence", flowchartFenceRule, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ return undefined;+ },+ },+ },+ };+ },+});diff --git a/src/lib/study-components/notes/mermaid-node.ts b/src/lib/study-components/notes/mermaid-node.tsnew file mode 100644index 00000000..a6ef4bad--- /dev/null+++ b/src/lib/study-components/notes/mermaid-node.ts@@ -0,0 +1,236 @@+import { Node, mergeAttributes } from "@tiptap/core";+import { mount, unmount, type Component } from "svelte";+import MermaidView from "./MermaidView.svelte";++declare module "@tiptap/core" {+ interface Commands<ReturnType> {+ mermaidBlock: {+ setMermaid: (source?: string) => ReturnType;+ };+ }+}++type MarkdownItToken = {+ type: string;+ tag?: string;+ info?: string;+ content?: string;+ markup?: string;+ block?: boolean;+ level?: number;+ meta?: unknown;+ attrs?: Array<[string, string]> | null;+ attrSet?: (name: string, value: string) => void;+ hidden?: boolean;+};++type MarkdownItState = {+ src: string;+ bMarks: number[];+ eMarks: number[];+ tShift: number[];+ sCount: number[];+ line: number;+ push: (type: string, tag: string, nesting: number) => MarkdownItToken;+};++type MarkdownItRule = (+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+) => boolean;++type MarkdownItBlockRuler = {+ before: (+ name: string,+ ruleName: string,+ rule: MarkdownItRule,+ options?: { alt?: string[] },+ ) => void;+};++type MarkdownItInstance = {+ block: { ruler: MarkdownItBlockRuler };+};++const FENCE_OPEN = /^```mermaid\s*$/;+const FENCE_CLOSE = /^```\s*$/;++function mermaidFenceRule(+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+): boolean {+ const startPos = state.bMarks[startLine] + state.tShift[startLine];+ const max = state.eMarks[startLine];+ if (state.sCount[startLine] - state.tShift[startLine] >= 4) return false;+ const opening = state.src.slice(startPos, max);+ if (!FENCE_OPEN.test(opening)) return false;+ if (silent) return true;++ let nextLine = startLine + 1;+ let closed = false;+ while (nextLine < endLine) {+ const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];+ const lineEnd = state.eMarks[nextLine];+ const text = state.src.slice(lineStart, lineEnd);+ if (FENCE_CLOSE.test(text)) {+ closed = true;+ break;+ }+ nextLine++;+ }++ const lines: string[] = [];+ for (let i = startLine + 1; i < nextLine; i++) {+ const ls = state.bMarks[i] + state.tShift[i];+ const le = state.eMarks[i];+ lines.push(state.src.slice(ls, le));+ }+ const source = lines.join("\n");++ const token = state.push("mermaid", "div", 0);+ token.block = true;+ token.markup = "```";+ token.info = "mermaid";+ token.content = source;+ if (token.attrSet) {+ token.attrSet("source", source);+ } else {+ token.attrs = [["source", source]];+ }++ state.line = closed ? nextLine + 1 : nextLine;+ return true;+}++export const MermaidBlock = Node.create({+ name: "mermaid",+ group: "block",+ atom: false,+ selectable: true,+ draggable: true,+ defining: true,++ addAttributes() {+ return {+ source: {+ default: "",+ parseHTML: (el) => el.getAttribute("data-mermaid-source") ?? "",+ renderHTML: (attrs) => ({+ "data-mermaid-source": String(attrs.source ?? ""),+ }),+ },+ };+ },++ parseHTML() {+ return [{ tag: "div[data-mermaid]" }];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ class: "tiptap-mermaid-block",+ "data-mermaid": "",+ }),+ "",+ ];+ },++ addCommands() {+ return {+ setMermaid:+ (source = "graph LR;\n A-->B") =>+ ({ commands }) =>+ commands.insertContent({+ type: this.name,+ attrs: { source },+ }),+ };+ },++ addNodeView() {+ return ({ node, editor, getPos }) => {+ const dom = document.createElement("div");+ dom.className = "tiptap-mermaid-block";+ dom.setAttribute("data-mermaid", "");+ dom.setAttribute("contenteditable", "false");++ let lastSource = String(node.attrs.source ?? "");+ const blockId = Math.random().toString(36).slice(2, 10);++ const view = mount(MermaidView as unknown as Component, {+ target: dom,+ props: {+ source: lastSource,+ blockId,+ onSourceChange: (next: string) => {+ const pos = typeof getPos === "function" ? getPos() : null;+ if (pos == null) return;+ lastSource = next;+ editor+ .chain()+ .command(({ tr }) => {+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ source: next,+ });+ return true;+ })+ .run();+ },+ },+ });++ return {+ dom,+ update: (updatedNode) => {+ if (updatedNode.type.name !== node.type.name) return false;+ const next = String(updatedNode.attrs.source ?? "");+ if (next !== lastSource) {+ lastSource = next;+ (view as unknown as { source?: string }).source = next;+ }+ return true;+ },+ destroy: () => {+ try {+ unmount(view);+ } catch {}+ },+ };+ };+ },++ addStorage() {+ return {+ markdown: {+ serialize(+ state: { write: (s: string) => void; closeBlock: (n: unknown) => void },+ node: { attrs: { source?: string } },+ ) {+ const src = String(node.attrs.source ?? "").replace(/\s+$/g, "");+ state.write("```mermaid\n");+ if (src.length > 0) {+ state.write(src);+ state.write("\n");+ }+ state.write("```");+ state.closeBlock(node);+ },+ parse: {+ setup(md: MarkdownItInstance) {+ md.block.ruler.before("fence", "mermaid_fence", mermaidFenceRule, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ return undefined;+ },+ },+ },+ };+ },+});diff --git a/src/lib/study-components/notes/mindmap-node.ts b/src/lib/study-components/notes/mindmap-node.tsnew file mode 100644index 00000000..9494a66c--- /dev/null+++ b/src/lib/study-components/notes/mindmap-node.ts@@ -0,0 +1,236 @@+import { Node, mergeAttributes } from "@tiptap/core";+import { mount, unmount, type Component } from "svelte";+import MindmapView from "./MindmapView.svelte";++declare module "@tiptap/core" {+ interface Commands<ReturnType> {+ mindmapBlock: {+ setMindmap: (source?: string) => ReturnType;+ };+ }+}++type MarkdownItToken = {+ type: string;+ tag?: string;+ info?: string;+ content?: string;+ markup?: string;+ block?: boolean;+ level?: number;+ meta?: unknown;+ attrs?: Array<[string, string]> | null;+ attrSet?: (name: string, value: string) => void;+ hidden?: boolean;+};++type MarkdownItState = {+ src: string;+ bMarks: number[];+ eMarks: number[];+ tShift: number[];+ sCount: number[];+ line: number;+ push: (type: string, tag: string, nesting: number) => MarkdownItToken;+};++type MarkdownItRule = (+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+) => boolean;++type MarkdownItBlockRuler = {+ before: (+ name: string,+ ruleName: string,+ rule: MarkdownItRule,+ options?: { alt?: string[] },+ ) => void;+};++type MarkdownItInstance = {+ block: { ruler: MarkdownItBlockRuler };+};++const FENCE_OPEN = /^```mindmap\s*$/;+const FENCE_CLOSE = /^```\s*$/;++function mindmapFenceRule(+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+): boolean {+ const startPos = state.bMarks[startLine] + state.tShift[startLine];+ const max = state.eMarks[startLine];+ if (state.sCount[startLine] - state.tShift[startLine] >= 4) return false;+ const opening = state.src.slice(startPos, max);+ if (!FENCE_OPEN.test(opening)) return false;+ if (silent) return true;++ let nextLine = startLine + 1;+ let closed = false;+ while (nextLine < endLine) {+ const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];+ const lineEnd = state.eMarks[nextLine];+ const text = state.src.slice(lineStart, lineEnd);+ if (FENCE_CLOSE.test(text)) {+ closed = true;+ break;+ }+ nextLine++;+ }++ const lines: string[] = [];+ for (let i = startLine + 1; i < nextLine; i++) {+ const ls = state.bMarks[i] + state.tShift[i];+ const le = state.eMarks[i];+ lines.push(state.src.slice(ls, le));+ }+ const source = lines.join("\n");++ const token = state.push("mindmap", "div", 0);+ token.block = true;+ token.markup = "```";+ token.info = "mindmap";+ token.content = source;+ if (token.attrSet) {+ token.attrSet("source", source);+ } else {+ token.attrs = [["source", source]];+ }++ state.line = closed ? nextLine + 1 : nextLine;+ return true;+}++export const MindmapBlock = Node.create({+ name: "mindmap",+ group: "block",+ atom: false,+ selectable: true,+ draggable: true,+ defining: true,++ addAttributes() {+ return {+ source: {+ default: "",+ parseHTML: (el) => el.getAttribute("data-mindmap-source") ?? "",+ renderHTML: (attrs) => ({+ "data-mindmap-source": String(attrs.source ?? ""),+ }),+ },+ };+ },++ parseHTML() {+ return [{ tag: "div[data-mindmap]" }];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ class: "tiptap-mindmap-block",+ "data-mindmap": "",+ }),+ "",+ ];+ },++ addCommands() {+ return {+ setMindmap:+ (source = "# Root\n## Branch A\n### Leaf 1\n### Leaf 2\n## Branch B") =>+ ({ commands }) =>+ commands.insertContent({+ type: this.name,+ attrs: { source },+ }),+ };+ },++ addNodeView() {+ return ({ node, editor, getPos }) => {+ const dom = document.createElement("div");+ dom.className = "tiptap-mindmap-block";+ dom.setAttribute("data-mindmap", "");+ dom.setAttribute("contenteditable", "false");++ let lastSource = String(node.attrs.source ?? "");+ const blockId = Math.random().toString(36).slice(2, 10);++ const view = mount(MindmapView as unknown as Component, {+ target: dom,+ props: {+ source: lastSource,+ blockId,+ onSourceChange: (next: string) => {+ const pos = typeof getPos === "function" ? getPos() : null;+ if (pos == null) return;+ lastSource = next;+ editor+ .chain()+ .command(({ tr }) => {+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ source: next,+ });+ return true;+ })+ .run();+ },+ },+ });++ return {+ dom,+ update: (updatedNode) => {+ if (updatedNode.type.name !== node.type.name) return false;+ const next = String(updatedNode.attrs.source ?? "");+ if (next !== lastSource) {+ lastSource = next;+ (view as unknown as { source?: string }).source = next;+ }+ return true;+ },+ destroy: () => {+ try {+ unmount(view);+ } catch {}+ },+ };+ };+ },++ addStorage() {+ return {+ markdown: {+ serialize(+ state: { write: (s: string) => void; closeBlock: (n: unknown) => void },+ node: { attrs: { source?: string } },+ ) {+ const src = String(node.attrs.source ?? "").replace(/\s+$/g, "");+ state.write("```mindmap\n");+ if (src.length > 0) {+ state.write(src);+ state.write("\n");+ }+ state.write("```");+ state.closeBlock(node);+ },+ parse: {+ setup(md: MarkdownItInstance) {+ md.block.ruler.before("fence", "mindmap_fence", mindmapFenceRule, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ return undefined;+ },+ },+ },+ };+ },+});diff --git a/src/lib/study-components/notes/plantuml-node.ts b/src/lib/study-components/notes/plantuml-node.tsnew file mode 100644index 00000000..d42101ec--- /dev/null+++ b/src/lib/study-components/notes/plantuml-node.ts@@ -0,0 +1,238 @@+import { Node, mergeAttributes } from "@tiptap/core";+import { mount, unmount, type Component } from "svelte";+import PlantumlView from "./PlantumlView.svelte";++declare module "@tiptap/core" {+ interface Commands<ReturnType> {+ plantumlBlock: {+ setPlantuml: (source?: string) => ReturnType;+ };+ }+}++type MarkdownItToken = {+ type: string;+ tag?: string;+ info?: string;+ content?: string;+ markup?: string;+ block?: boolean;+ level?: number;+ meta?: unknown;+ attrs?: Array<[string, string]> | null;+ attrSet?: (name: string, value: string) => void;+ hidden?: boolean;+};++type MarkdownItState = {+ src: string;+ bMarks: number[];+ eMarks: number[];+ tShift: number[];+ sCount: number[];+ line: number;+ push: (type: string, tag: string, nesting: number) => MarkdownItToken;+};++type MarkdownItRule = (+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+) => boolean;++type MarkdownItBlockRuler = {+ before: (+ name: string,+ ruleName: string,+ rule: MarkdownItRule,+ options?: { alt?: string[] },+ ) => void;+};++type MarkdownItInstance = {+ block: { ruler: MarkdownItBlockRuler };+};++const FENCE_OPEN = /^```plantuml\s*$/;+const FENCE_CLOSE = /^```\s*$/;++function plantumlFenceRule(+ state: MarkdownItState,+ startLine: number,+ endLine: number,+ silent: boolean,+): boolean {+ const startPos = state.bMarks[startLine] + state.tShift[startLine];+ const max = state.eMarks[startLine];+ if (state.sCount[startLine] - state.tShift[startLine] >= 4) return false;+ const opening = state.src.slice(startPos, max);+ if (!FENCE_OPEN.test(opening)) return false;+ if (silent) return true;++ let nextLine = startLine + 1;+ let closed = false;+ while (nextLine < endLine) {+ const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];+ const lineEnd = state.eMarks[nextLine];+ const text = state.src.slice(lineStart, lineEnd);+ if (FENCE_CLOSE.test(text)) {+ closed = true;+ break;+ }+ nextLine++;+ }++ const lines: string[] = [];+ for (let i = startLine + 1; i < nextLine; i++) {+ const ls = state.bMarks[i] + state.tShift[i];+ const le = state.eMarks[i];+ lines.push(state.src.slice(ls, le));+ }+ const source = lines.join("\n");++ const token = state.push("plantuml", "div", 0);+ token.block = true;+ token.markup = "```";+ token.info = "plantuml";+ token.content = source;+ if (token.attrSet) {+ token.attrSet("source", source);+ } else {+ token.attrs = [["source", source]];+ }++ state.line = closed ? nextLine + 1 : nextLine;+ return true;+}++export const PlantumlBlock = Node.create({+ name: "plantuml",+ group: "block",+ atom: false,+ selectable: true,+ draggable: true,+ defining: true,++ addAttributes() {+ return {+ source: {+ default: "",+ parseHTML: (el) => el.getAttribute("data-plantuml-source") ?? "",+ renderHTML: (attrs) => ({+ "data-plantuml-source": String(attrs.source ?? ""),+ }),+ },+ };+ },++ parseHTML() {+ return [{ tag: "div[data-plantuml]" }];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ class: "tiptap-plantuml-block",+ "data-plantuml": "",+ }),+ "",+ ];+ },++ addCommands() {+ return {+ setPlantuml:+ (+ source = "@startuml\nAlice -> Bob: hello\nBob --> Alice: hi\n@enduml",+ ) =>+ ({ commands }) =>+ commands.insertContent({+ type: this.name,+ attrs: { source },+ }),+ };+ },++ addNodeView() {+ return ({ node, editor, getPos }) => {+ const dom = document.createElement("div");+ dom.className = "tiptap-plantuml-block";+ dom.setAttribute("data-plantuml", "");+ dom.setAttribute("contenteditable", "false");++ let lastSource = String(node.attrs.source ?? "");+ const blockId = Math.random().toString(36).slice(2, 10);++ const view = mount(PlantumlView as unknown as Component, {+ target: dom,+ props: {+ source: lastSource,+ blockId,+ onSourceChange: (next: string) => {+ const pos = typeof getPos === "function" ? getPos() : null;+ if (pos == null) return;+ lastSource = next;+ editor+ .chain()+ .command(({ tr }) => {+ tr.setNodeMarkup(pos, undefined, {+ ...node.attrs,+ source: next,+ });+ return true;+ })+ .run();+ },+ },+ });++ return {+ dom,+ update: (updatedNode) => {+ if (updatedNode.type.name !== node.type.name) return false;+ const next = String(updatedNode.attrs.source ?? "");+ if (next !== lastSource) {+ lastSource = next;+ (view as unknown as { source?: string }).source = next;+ }+ return true;+ },+ destroy: () => {+ try {+ unmount(view);+ } catch {}+ },+ };+ };+ },++ addStorage() {+ return {+ markdown: {+ serialize(+ state: { write: (s: string) => void; closeBlock: (n: unknown) => void },+ node: { attrs: { source?: string } },+ ) {+ const src = String(node.attrs.source ?? "").replace(/\s+$/g, "");+ state.write("```plantuml\n");+ if (src.length > 0) {+ state.write(src);+ state.write("\n");+ }+ state.write("```");+ state.closeBlock(node);+ },+ parse: {+ setup(md: MarkdownItInstance) {+ md.block.ruler.before("fence", "plantuml_fence", plantumlFenceRule, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ return undefined;+ },+ },+ },+ };+ },+});diff --git a/src/lib/study-components/notes/shell/NbActiveNotebookBadge.svelte b/src/lib/study-components/notes/shell/NbActiveNotebookBadge.sveltenew file mode 100644index 00000000..90892cf7--- /dev/null+++ b/src/lib/study-components/notes/shell/NbActiveNotebookBadge.svelte@@ -0,0 +1,175 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { notebooksStore } from "$lib/study-notes/notebooks-store.svelte";++ let open = $state(false);+ let rootRef = $state<HTMLDivElement | null>(null);++ const active = $derived(notebooksStore.active);+ const visible = $derived(notebooksStore.visible);++ onMount(() => {+ if (!notebooksStore.hydrated) {+ void notebooksStore.hydrate();+ }+ function onWinClick(e: MouseEvent) {+ if (!open) return;+ const target = e.target as Node | null;+ if (rootRef && target && rootRef.contains(target)) return;+ open = false;+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape" && open) {+ open = false;+ }+ }+ window.addEventListener("mousedown", onWinClick);+ window.addEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("mousedown", onWinClick);+ window.removeEventListener("keydown", onKey);+ };+ });++ function pick(id: number) {+ void notebooksStore.setActive(id);+ open = false;+ }+</script>++<div class="badge-wrap" bind:this={rootRef}>+ <button+ type="button"+ class="badge"+ aria-haspopup="menu"+ aria-expanded={open}+ onclick={() => (open = !open)}+ title="Notebook ativo (Ctrl+Alt+1..9 alterna)"+ >+ {#if active?.color}+ <span class="dot" style:background={active.color}></span>+ {:else}+ <span class="dot dim"></span>+ {/if}+ <span class="name">{active?.name ?? "Pessoal"}</span>+ <svg viewBox="0 0 24 24" width="10" height="10" 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>+ </button>++ {#if open}+ <div class="menu" role="menu">+ {#each visible as nb, i (nb.id)}+ <button+ type="button"+ role="menuitem"+ class="menu-item"+ class:active={nb.id === active?.id}+ onclick={() => pick(nb.id)}+ >+ {#if nb.color}+ <span class="dot" style:background={nb.color}></span>+ {:else}+ <span class="dot dim"></span>+ {/if}+ <span class="menu-name">{nb.name}</span>+ <span class="menu-count">{nb.page_count}</span>+ <span class="menu-shortcut">⌘⌥{i + 1}</span>+ </button>+ {/each}+ </div>+ {/if}+</div>++<style>+ .badge-wrap {+ position: relative;+ display: inline-flex;+ }+ .badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 2px 8px;+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ border-radius: 999px;+ color: var(--text);+ font: inherit;+ font-size: 11px;+ font-weight: 500;+ cursor: pointer;+ transition: background 120ms, border-color 120ms;+ }+ .badge:hover {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ border-color: var(--accent);+ }+ .dot {+ width: 8px;+ height: 8px;+ border-radius: 999px;+ background: var(--accent);+ flex-shrink: 0;+ }+ .dot.dim {+ background: color-mix(in oklab, var(--text) 25%, transparent);+ }+ .name {+ max-width: 120px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .menu {+ position: absolute;+ bottom: calc(100% + 6px);+ left: 0;+ z-index: 120;+ min-width: 220px;+ background: var(--bg);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 10px;+ padding: 4px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.32);+ }+ .menu-item {+ display: grid;+ grid-template-columns: auto 1fr auto auto;+ gap: 8px;+ align-items: center;+ padding: 6px 8px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ text-align: left;+ transition: background 120ms;+ }+ .menu-item:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .menu-item.active {+ background: color-mix(in oklab, var(--accent) 15%, transparent);+ }+ .menu-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .menu-count {+ color: var(--tertiary);+ font-size: 10px;+ }+ .menu-shortcut {+ color: var(--tertiary);+ font-family: ui-monospace, monospace;+ font-size: 10px;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockBacklink.svelte b/src/lib/study-components/notes/shell/NbDockBacklink.sveltenew file mode 100644index 00000000..53fa4f5c--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockBacklink.svelte@@ -0,0 +1,285 @@+<script lang="ts">+ import { onMount, untrack } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import {+ notesPagesLinkedRefs,+ notesPagesUnlinkedRefs,+ notesBlocksPropertyListKeys,+ type LinkedRef,+ type PropertyKeyStat,+ } from "$lib/notes-bridge";++ type Tab = "linked" | "unlinked" | "props";+ let tab = $state<Tab>("linked");++ let linked = $state<LinkedRef[]>([]);+ let unlinked = $state<LinkedRef[]>([]);+ let props = $state<PropertyKeyStat[]>([]);+ let loading = $state(false);+ let lastPageId = $state<number | null>(null);++ const pageId = $derived(tabsStore.activeTab?.page_id ?? null);++ async function reload(id: number) {+ loading = true;+ try {+ const [l, u, p] = await Promise.all([+ notesPagesLinkedRefs(id),+ notesPagesUnlinkedRefs(id),+ notesBlocksPropertyListKeys({ pageId: id }),+ ]);+ linked = l;+ unlinked = u;+ props = p;+ } catch {+ linked = [];+ unlinked = [];+ props = [];+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const id = pageId;+ if (id === lastPageId) return;+ untrack(() => {+ lastPageId = id;+ if (id == null) {+ linked = [];+ unlinked = [];+ props = [];+ return;+ }+ void reload(id);+ });+ });++ async function openByPageId(pid: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({ wndId: wnd, pageId: pid, viewKind: "editor", activate: true });+ }++ onMount(() => {+ if (pageId != null) void reload(pageId);+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Backlinks</span>+ </header>+ <nav class="tabs" role="tablist">+ <button+ type="button"+ class="tab"+ class:active={tab === "linked"}+ role="tab"+ aria-selected={tab === "linked"}+ onclick={() => (tab = "linked")}+ >+ Linked <span class="count">{linked.length}</span>+ </button>+ <button+ type="button"+ class="tab"+ class:active={tab === "unlinked"}+ role="tab"+ aria-selected={tab === "unlinked"}+ onclick={() => (tab = "unlinked")}+ >+ Unlinked <span class="count">{unlinked.length}</span>+ </button>+ <button+ type="button"+ class="tab"+ class:active={tab === "props"}+ role="tab"+ aria-selected={tab === "props"}+ onclick={() => (tab = "props")}+ >+ Props <span class="count">{props.length}</span>+ </button>+ </nav>+ <div class="body">+ {#if pageId == null}+ <p class="empty">Sem página ativa.</p>+ {:else if loading}+ <p class="empty">Carregando…</p>+ {:else if tab === "linked"}+ {#if linked.length === 0}+ <p class="empty">Nenhuma referência direta.</p>+ {:else}+ <ul class="refs">+ {#each linked as r (r.block_id)}+ <li class="ref">+ <button+ type="button"+ class="ref-page"+ onclick={() => openByPageId(r.page_id)}+ title={r.page_name}+ >+ {r.page_name}+ </button>+ <p class="snippet">{r.snippet}</p>+ </li>+ {/each}+ </ul>+ {/if}+ {:else if tab === "unlinked"}+ {#if unlinked.length === 0}+ <p class="empty">Nenhuma menção sem link.</p>+ {:else}+ <ul class="refs">+ {#each unlinked as r (r.block_id)}+ <li class="ref">+ <button+ type="button"+ class="ref-page"+ onclick={() => openByPageId(r.page_id)}+ title={r.page_name}+ >+ {r.page_name}+ </button>+ <p class="snippet">{r.snippet}</p>+ </li>+ {/each}+ </ul>+ {/if}+ {:else if tab === "props"}+ {#if props.length === 0}+ <p class="empty">Nenhuma propriedade nesta página.</p>+ {:else}+ <ul class="props">+ {#each props as p (p.key)}+ <li class="prop">+ <span class="key">{p.key}</span>+ <span class="meta">{p.block_count} blocos · {p.distinct_values} valores</span>+ </li>+ {/each}+ </ul>+ {/if}+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .tabs {+ display: flex;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 25%, transparent);+ }+ .tab {+ flex: 1;+ background: transparent;+ border: 0;+ border-bottom: 2px solid transparent;+ padding: 6px 4px;+ font: inherit;+ font-size: 11px;+ color: var(--tertiary, var(--muted-fg));+ cursor: pointer;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }+ .tab:hover {+ color: var(--secondary, var(--text));+ }+ .tab.active {+ color: var(--accent);+ border-bottom-color: var(--accent);+ }+ .count {+ font-size: 9px;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ border-radius: 999px;+ padding: 1px 5px;+ margin-left: 4px;+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .refs {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .ref {+ padding: 6px 10px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 18%, transparent);+ }+ .ref-page {+ background: transparent;+ border: 0;+ color: var(--accent);+ font: inherit;+ font-size: 11.5px;+ font-weight: 600;+ padding: 0;+ cursor: pointer;+ text-align: left;+ }+ .ref-page:hover {+ text-decoration: underline;+ }+ .snippet {+ margin: 3px 0 0;+ font-size: 11px;+ line-height: 1.4;+ color: var(--secondary, var(--text));+ opacity: 0.8;+ overflow: hidden;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ -webkit-box-orient: vertical;+ }+ .props {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .prop {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ padding: 6px 10px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 18%, transparent);+ gap: 8px;+ }+ .key {+ font-size: 12px;+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .meta {+ font-size: 10px;+ color: var(--tertiary, var(--muted-fg));+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockBookmark.svelte b/src/lib/study-components/notes/shell/NbDockBookmark.sveltenew file mode 100644index 00000000..f619eaf9--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockBookmark.svelte@@ -0,0 +1,148 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { notesBookmarksList, type PageSummary } from "$lib/notes-bridge";++ let pages = $state<PageSummary[]>([]);+ let loading = $state(false);++ async function reload() {+ loading = true;+ try {+ pages = await notesBookmarksList();+ } catch {+ pages = [];+ } finally {+ loading = false;+ }+ }++ async function open(pageId: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({ wndId: wnd, pageId, viewKind: "editor", activate: true });+ }++ onMount(() => {+ void reload();+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Favoritos</span>+ <button class="refresh" type="button" onclick={() => void reload()} title="Recarregar" aria-label="Recarregar">+ ↻+ </button>+ </header>+ <div class="body">+ {#if loading && pages.length === 0}+ <p class="empty">Carregando…</p>+ {:else if pages.length === 0}+ <p class="empty">Nenhuma página marcada com <code>bookmark::true</code>.</p>+ {:else}+ <ul class="entries">+ {#each pages as p (p.id)}+ <li>+ <button type="button" class="entry-btn" onclick={() => open(p.id)} title={p.name}>+ <span class="title">{p.title || p.name}</span>+ {#if p.title && p.name !== p.title}+ <span class="sub">{p.name}</span>+ {/if}+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .refresh {+ background: transparent;+ border: 0;+ color: inherit;+ cursor: pointer;+ font-size: 13px;+ padding: 0 4px;+ border-radius: 4px;+ }+ .refresh:hover {+ color: var(--accent);+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .entries {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .entry-btn {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 12px;+ line-height: 1.35;+ padding: 5px 10px;+ cursor: pointer;+ border-radius: 4px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .entry-btn:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }+ .title {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ font-size: 10px;+ opacity: 0.65;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ code {+ font-size: 10.5px;+ background: color-mix(in oklab, var(--content-border) 40%, transparent);+ padding: 0 4px;+ border-radius: 3px;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockFiles.svelte b/src/lib/study-components/notes/shell/NbDockFiles.sveltenew file mode 100644index 00000000..a6dfa549--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockFiles.svelte@@ -0,0 +1,845 @@+<script lang="ts">+ import { onMount } from "svelte";+ import CreatePageDialog from "../CreatePageDialog.svelte";+ import NbNotebookCreateDialog from "./NbNotebookCreateDialog.svelte";+ import NbNotebookCoverDialog from "./NbNotebookCoverDialog.svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { notebooksStore } from "$lib/study-notes/notebooks-store.svelte";+ import {+ notesPagesList,+ notesPagesCreate,+ notesJournalToday,+ type PageSummary,+ } from "$lib/notes-bridge";++ let pages = $state<PageSummary[]>([]);+ let search = $state("");+ let createPageOpen = $state(false);+ let createPageInNotebookId = $state<number | null>(null);+ let createNotebookOpen = $state(false);+ let coverNotebookId = $state<number | null>(null);+ let coverDialogOpen = $state(false);+ let expandedClosed = $state(false);+ let expandedNotebooks = $state<Record<number, boolean>>({});+ let menuFor = $state<number | null>(null);+ let menuPos = $state({ x: 0, y: 0 });+ let renameTarget = $state<number | null>(null);+ let renameDraft = $state("");++ const selectedId = $derived(tabsStore.activeTab?.page_id ?? null);+ const query = $derived(search.trim().toLowerCase());++ function matchesSearch(p: PageSummary): boolean {+ if (!query) return true;+ return (+ p.name.toLowerCase().includes(query) ||+ (p.title ?? "").toLowerCase().includes(query)+ );+ }++ function pagesIn(notebookId: number): PageSummary[] {+ return pages+ .filter((p) => p.notebook_id === notebookId && matchesSearch(p))+ .sort((a, b) =>+ (a.title ?? a.name).localeCompare(b.title ?? b.name, "pt-BR", {+ sensitivity: "base",+ }),+ );+ }++ async function reloadPages() {+ try {+ pages = await notesPagesList();+ } catch {+ pages = [];+ }+ }++ async function reloadAll() {+ await Promise.all([reloadPages(), notebooksStore.refresh()]);+ }++ async function openPage(pageId: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({+ wndId: wnd,+ pageId,+ viewKind: "editor",+ activate: true,+ });+ }++ function startCreatePage(notebookId: number) {+ createPageInNotebookId = notebookId;+ createPageOpen = true;+ }++ async function confirmCreatePage(name: string) {+ const nbId = createPageInNotebookId ?? notebooksStore.activeId;+ try {+ const r = await notesPagesCreate({ name, notebookId: nbId });+ createPageOpen = false;+ createPageInNotebookId = null;+ await reloadAll();+ await openPage(r.id);+ } catch {+ /* ignore */+ }+ }++ async function openJournalToday() {+ try {+ const r = await notesJournalToday();+ await reloadAll();+ await openPage(r.page_id);+ } catch {+ /* ignore */+ }+ }++ async function confirmCreateNotebook(args: {+ name: string;+ color: string | null;+ iconLucide: string | null;+ }) {+ const id = await notebooksStore.create(args);+ createNotebookOpen = false;+ if (id != null) {+ expandedNotebooks = { ...expandedNotebooks, [id]: true };+ await notebooksStore.setActive(id);+ }+ }++ function toggleNotebook(id: number) {+ expandedNotebooks = {+ ...expandedNotebooks,+ [id]: !(expandedNotebooks[id] ?? true),+ };+ }++ function isExpanded(id: number): boolean {+ return expandedNotebooks[id] ?? true;+ }++ function openContext(e: MouseEvent, notebookId: number) {+ e.preventDefault();+ e.stopPropagation();+ menuFor = notebookId;+ menuPos = { x: e.clientX, y: e.clientY };+ }++ function closeContext() {+ menuFor = null;+ }++ function startRename(notebookId: number) {+ const nb = notebooksStore.byId(notebookId);+ if (!nb) return;+ renameTarget = notebookId;+ renameDraft = nb.name;+ menuFor = null;+ }++ async function commitRename() {+ if (renameTarget == null) return;+ const trimmed = renameDraft.trim();+ if (trimmed.length > 0) {+ await notebooksStore.rename(renameTarget, trimmed);+ }+ renameTarget = null;+ renameDraft = "";+ }++ async function doClose(notebookId: number) {+ await notebooksStore.close(notebookId);+ closeContext();+ }++ async function doReopen(notebookId: number) {+ await notebooksStore.reopen(notebookId);+ closeContext();+ }++ async function doDelete(notebookId: number) {+ closeContext();+ const nb = notebooksStore.byId(notebookId);+ if (!nb) return;+ if (nb.id === 1) {+ window.alert("Notebook 'Pessoal' não pode ser excluído.");+ return;+ }+ if (nb.page_count > 0) {+ const ok = window.confirm(+ `Excluir "${nb.name}" remove ${nb.page_count} página${nb.page_count === 1 ? "" : "s"} para sempre. Continuar?`,+ );+ if (!ok) return;+ const r = await notebooksStore.delete(notebookId, true);+ if (!r.deleted) {+ window.alert("Falha ao excluir notebook.");+ } else {+ await reloadPages();+ }+ } else {+ await notebooksStore.delete(notebookId, false);+ }+ }++ function openCover(notebookId: number) {+ coverNotebookId = notebookId;+ coverDialogOpen = true;+ closeContext();+ }++ async function pickColor(notebookId: number) {+ closeContext();+ const swatch = window.prompt(+ "Cor (hex ou var, ex: #f97316). Vazio = sem cor.",+ notebooksStore.byId(notebookId)?.color ?? "",+ );+ if (swatch == null) return;+ await notebooksStore.setColor(+ notebookId,+ swatch.trim().length > 0 ? swatch.trim() : null,+ );+ }++ async function pickIcon(notebookId: number) {+ closeContext();+ const icon = window.prompt(+ "Ícone (lucide name, ex: book, briefcase). Vazio = sem ícone.",+ notebooksStore.byId(notebookId)?.icon_lucide ?? "",+ );+ if (icon == null) return;+ await notebooksStore.setIcon(+ notebookId,+ icon.trim().length > 0 ? icon.trim() : null,+ );+ }++ async function activate(notebookId: number) {+ await notebooksStore.setActive(notebookId);+ }++ function fmtDay(secs: number): string {+ if (!secs) return "—";+ const d = new Date(secs * 1000);+ const today = new Date();+ const same =+ d.getFullYear() === today.getFullYear() &&+ d.getMonth() === today.getMonth() &&+ d.getDate() === today.getDate();+ if (same) return "hoje";+ return d.toLocaleDateString();+ }++ onMount(() => {+ if (!notebooksStore.hydrated) void notebooksStore.hydrate();+ void reloadPages();+ const handler = () => void reloadAll();+ const newNotebookHandler = () => (createNotebookOpen = true);+ window.addEventListener("study:notes:dirty", handler);+ window.addEventListener("study:notes:notebook-new", newNotebookHandler);+ const close = () => closeContext();+ window.addEventListener("mousedown", close);+ return () => {+ window.removeEventListener("study:notes:dirty", handler);+ window.removeEventListener("study:notes:notebook-new", newNotebookHandler);+ window.removeEventListener("mousedown", close);+ };+ });++ const visibleNotebooks = $derived(notebooksStore.visible);+ const closedNotebooks = $derived(notebooksStore.closed);+</script>++<div class="nb-dock-files">+ <header class="dock-head">+ <h2>Notebooks</h2>+ <button+ class="head-btn"+ type="button"+ onclick={() => void openJournalToday()}+ title="Journal de hoje"+ aria-label="Journal de hoje"+ >+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="3" y="4" width="18" height="18" rx="2" />+ <path d="M3 10h18 M8 2v4 M16 2v4" />+ </svg>+ </button>+ </header>++ <input+ class="search"+ placeholder="Filtrar páginas…"+ bind:value={search}+ />++ <div class="scroll">+ {#each visibleNotebooks as nb (nb.id)}+ {@const expanded = isExpanded(nb.id)}+ {@const items = pagesIn(nb.id)}+ <section class="notebook" class:active={nb.id === notebooksStore.activeId}>+ <button+ class="nb-row"+ type="button"+ onclick={() => toggleNotebook(nb.id)}+ oncontextmenu={(e) => openContext(e, nb.id)}+ ondblclick={() => void activate(nb.id)}+ >+ <span+ class="chevron"+ class:open={expanded}+ aria-hidden="true"+ >▸</span>+ {#if nb.color}+ <span class="dot" style:background={nb.color}></span>+ {:else}+ <span class="dot dim"></span>+ {/if}+ <span class="nb-name" title={nb.icon_lucide ?? ""}>+ {nb.name}+ </span>+ <span class="count">{nb.page_count}</span>+ </button>++ {#if expanded}+ <ul class="page-list">+ {#each items as p (p.id)}+ <li>+ <button+ type="button"+ class="page-row"+ class:active={selectedId === p.id}+ onclick={() => void openPage(p.id)}+ title={p.name}+ >+ <span class="page-name">{p.title ?? p.name}</span>+ <span class="page-meta">+ {p.block_count} · {fmtDay(p.updated_at)}+ </span>+ </button>+ </li>+ {:else}+ <li class="empty">— vazio —</li>+ {/each}+ <li>+ <button+ type="button"+ class="page-row add-page"+ onclick={() => startCreatePage(nb.id)}+ title="Nova página neste notebook"+ >+ <span class="page-name">+ Nova página</span>+ </button>+ </li>+ </ul>+ {/if}+ </section>+ {/each}++ {#if closedNotebooks.length > 0}+ <section class="closed-section">+ <button+ type="button"+ class="closed-toggle"+ onclick={() => (expandedClosed = !expandedClosed)}+ >+ <span class="chevron" class:open={expandedClosed} aria-hidden="true">▸</span>+ <span>Closed notebooks ({closedNotebooks.length})</span>+ </button>+ {#if expandedClosed}+ <ul class="closed-list">+ {#each closedNotebooks as nb (nb.id)}+ <li>+ <button+ type="button"+ class="closed-row"+ oncontextmenu={(e) => openContext(e, nb.id)}+ onclick={() => void doReopen(nb.id)}+ title="Reabrir notebook"+ >+ {#if nb.color}+ <span class="dot" style:background={nb.color}></span>+ {:else}+ <span class="dot dim"></span>+ {/if}+ <span>{nb.name}</span>+ <span class="count">{nb.page_count}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </section>+ {/if}+ </div>++ <footer class="dock-foot">+ <button+ type="button"+ class="new-nb"+ onclick={() => (createNotebookOpen = true)}+ title="Novo notebook (Ctrl+Shift+N)"+ >+ <span aria-hidden="true">+</span>+ <span>Novo notebook</span>+ </button>+ </footer>+</div>++{#if menuFor != null}+ {@const nb = notebooksStore.byId(menuFor)}+ {#if nb}+ <div+ class="ctx-menu"+ role="menu"+ tabindex="-1"+ data-modal="true"+ style:left={`${menuPos.x}px`}+ style:top={`${menuPos.y}px`}+ onmousedown={(e) => e.stopPropagation()}+ >+ <button class="ctx-item" onclick={() => void activate(nb.id)}>+ Tornar ativo+ </button>+ <button class="ctx-item" onclick={() => startRename(nb.id)}>+ Renomear+ </button>+ <button class="ctx-item" onclick={() => openCover(nb.id)}>+ Capa…+ </button>+ <button class="ctx-item" onclick={() => void pickColor(nb.id)}>+ Cor…+ </button>+ <button class="ctx-item" onclick={() => void pickIcon(nb.id)}>+ Ícone…+ </button>+ <hr />+ {#if nb.closed}+ <button class="ctx-item" onclick={() => void doReopen(nb.id)}>+ Reabrir+ </button>+ {:else}+ <button class="ctx-item" onclick={() => void doClose(nb.id)}>+ Fechar+ </button>+ {/if}+ <button class="ctx-item danger" onclick={() => void doDelete(nb.id)}>+ Excluir…+ </button>+ </div>+ {/if}+{/if}++{#if renameTarget != null}+ <div+ class="rename-overlay"+ role="presentation"+ data-modal="true"+ onmousedown={(e) => {+ if (e.target === e.currentTarget) {+ renameTarget = null;+ }+ }}+ >+ <div class="rename-card">+ <label>+ <span>Renomear notebook</span>+ <input+ type="text"+ bind:value={renameDraft}+ onkeydown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void commitRename();+ } else if (e.key === "Escape") {+ e.preventDefault();+ renameTarget = null;+ }+ }}+ />+ </label>+ <div class="rename-actions">+ <button type="button" class="btn ghost" onclick={() => (renameTarget = null)}>+ Cancelar+ </button>+ <button type="button" class="btn primary" onclick={() => void commitRename()}>+ Salvar+ </button>+ </div>+ </div>+ </div>+{/if}++<CreatePageDialog+ open={createPageOpen}+ onConfirm={(name) => void confirmCreatePage(name)}+ onClose={() => {+ createPageOpen = false;+ createPageInNotebookId = null;+ }}+/>++<NbNotebookCreateDialog+ open={createNotebookOpen}+ onConfirm={(args) => void confirmCreateNotebook(args)}+ onClose={() => (createNotebookOpen = false)}+/>++<NbNotebookCoverDialog+ open={coverDialogOpen}+ notebookId={coverNotebookId}+ onClose={() => {+ coverDialogOpen = false;+ coverNotebookId = null;+ }}+/>++<style>+ .nb-dock-files {+ height: 100%;+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 10px 8px 8px;+ overflow: hidden;+ }+ .dock-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 6px;+ padding: 0 4px;+ }+ .dock-head h2 {+ margin: 0;+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--tertiary);+ }+ .head-btn {+ background: transparent;+ border: 0;+ padding: 4px;+ color: var(--tertiary);+ cursor: pointer;+ border-radius: 4px;+ }+ .head-btn:hover {+ color: var(--text);+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .search {+ padding: 6px 9px;+ border: 1px solid var(--input-border);+ border-radius: 6px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ font-size: 12px;+ }+ .search:focus {+ outline: none;+ border-color: var(--accent);+ }+ .scroll {+ flex: 1;+ overflow-y: auto;+ overflow-x: hidden;+ padding-right: 2px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .notebook {+ display: flex;+ flex-direction: column;+ }+ .notebook.active > .nb-row {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .nb-row {+ display: grid;+ grid-template-columns: 14px auto 1fr auto;+ align-items: center;+ gap: 6px;+ padding: 4px 6px;+ border: 0;+ border-radius: 5px;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 500;+ text-align: left;+ cursor: pointer;+ transition: background 120ms;+ }+ .nb-row:hover {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .chevron {+ display: inline-block;+ color: var(--tertiary);+ transition: transform 120ms;+ font-size: 9px;+ line-height: 1;+ text-align: center;+ }+ .chevron.open {+ transform: rotate(90deg);+ }+ .dot {+ width: 8px;+ height: 8px;+ border-radius: 999px;+ background: var(--accent);+ flex-shrink: 0;+ }+ .dot.dim {+ background: color-mix(in oklab, var(--text) 22%, transparent);+ }+ .nb-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .count {+ color: var(--tertiary);+ font-size: 10.5px;+ font-weight: 500;+ }+ .page-list {+ list-style: none;+ margin: 0 0 4px 0;+ padding: 0 0 0 18px;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .page-row {+ display: flex;+ flex-direction: column;+ gap: 1px;+ width: 100%;+ padding: 4px 6px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition: background 100ms;+ }+ .page-row:hover {+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .page-row.active {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ }+ .page-name {+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .page-meta {+ font-size: 10px;+ color: var(--tertiary);+ }+ .add-page {+ color: var(--tertiary);+ font-style: italic;+ }+ .add-page:hover {+ color: var(--accent);+ }+ .empty {+ color: var(--tertiary);+ font-size: 11px;+ padding: 4px 6px;+ list-style: none;+ }+ .closed-section {+ margin-top: 8px;+ border-top: 1px dashed color-mix(in oklab, var(--content-border) 40%, transparent);+ padding-top: 6px;+ }+ .closed-toggle {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 6px;+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ cursor: pointer;+ width: 100%;+ text-align: left;+ }+ .closed-toggle:hover {+ color: var(--text);+ }+ .closed-list {+ list-style: none;+ margin: 4px 0 0 0;+ padding: 0 0 0 18px;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .closed-row {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ padding: 4px 6px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--secondary);+ font: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ transition: background 100ms;+ }+ .closed-row:hover {+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ color: var(--text);+ }+ .dock-foot {+ border-top: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);+ padding-top: 6px;+ }+ .new-nb {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ padding: 6px 8px;+ border: 1px dashed color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 6px;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ transition: background 120ms, color 120ms, border-color 120ms;+ }+ .new-nb:hover {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .ctx-menu {+ position: fixed;+ z-index: 220;+ min-width: 180px;+ background: var(--bg);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 8px;+ padding: 4px;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.34);+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .ctx-menu hr {+ border: 0;+ border-top: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ margin: 3px 0;+ }+ .ctx-item {+ text-align: left;+ padding: 6px 10px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .ctx-item:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .ctx-item.danger {+ color: #ef4444;+ }+ .rename-overlay {+ position: fixed;+ inset: 0;+ z-index: 220;+ display: grid;+ place-items: center;+ background: color-mix(in oklab, black 35%, transparent);+ }+ .rename-card {+ background: var(--bg);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 10px;+ padding: 14px;+ width: min(360px, 90vw);+ display: flex;+ flex-direction: column;+ gap: 10px;+ }+ .rename-card label {+ display: flex;+ flex-direction: column;+ gap: 6px;+ font-size: 11px;+ color: var(--tertiary);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ }+ .rename-card input {+ padding: 7px 9px;+ border: 1px solid var(--input-border);+ border-radius: 6px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ font-size: 13px;+ }+ .rename-card input:focus {+ outline: none;+ border-color: var(--accent);+ }+ .rename-actions {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ }+ .btn {+ padding: 6px 12px;+ border-radius: 6px;+ border: 1px solid transparent;+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ transition: background 120ms;+ }+ .btn.ghost {+ background: transparent;+ border-color: var(--input-border);+ color: var(--text);+ }+ .btn.ghost:hover {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .btn.primary {+ background: var(--accent);+ color: #fff;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockGraph.svelte b/src/lib/study-components/notes/shell/NbDockGraph.sveltenew file mode 100644index 00000000..d70c6916--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockGraph.svelte@@ -0,0 +1,219 @@+<script lang="ts">+ import { onMount, untrack } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { notesGraph, type Graph, type GraphNode } from "$lib/notes-bridge";++ let graph = $state<Graph | null>(null);+ let loading = $state(false);+ let lastPageId = $state<number | null>(null);++ const pageId = $derived(tabsStore.activeTab?.page_id ?? null);++ type Neighbor = { node: GraphNode; weight: number };++ const neighbors = $derived.by<Neighbor[]>(() => {+ if (!graph || pageId == null) return [];+ const nodeById = new Map(graph.nodes.map((n) => [n.id, n]));+ const out: Neighbor[] = [];+ for (const e of graph.edges) {+ if (e.from === pageId && e.to !== pageId) {+ const n = nodeById.get(e.to);+ if (n) out.push({ node: n, weight: e.weight });+ } else if (e.to === pageId && e.from !== pageId) {+ const n = nodeById.get(e.from);+ if (n) out.push({ node: n, weight: e.weight });+ }+ }+ out.sort((a, b) => b.weight - a.weight);+ return out;+ });++ const center = $derived.by<GraphNode | null>(() => {+ if (!graph || pageId == null) return null;+ return graph.nodes.find((n) => n.id === pageId) ?? null;+ });++ async function reload() {+ loading = true;+ try {+ graph = await notesGraph();+ } catch {+ graph = null;+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const id = pageId;+ if (id === lastPageId) return;+ untrack(() => {+ lastPageId = id;+ if (!graph) void reload();+ });+ });++ async function open(pid: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({ wndId: wnd, pageId: pid, viewKind: "editor", activate: true });+ }++ onMount(() => {+ void reload();+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Graph</span>+ <button class="refresh" type="button" onclick={() => void reload()} title="Recarregar" aria-label="Recarregar">+ ↻+ </button>+ </header>+ <div class="body">+ {#if loading && !graph}+ <p class="empty">Construindo graph…</p>+ {:else if pageId == null}+ <p class="empty">Sem página ativa.</p>+ {:else if !center}+ <p class="empty">Página não está no grafo.</p>+ {:else}+ <div class="center">+ <span class="dot" aria-hidden="true"></span>+ <span class="label">{center.name}</span>+ <span class="meta">{center.ref_count} refs</span>+ </div>+ {#if neighbors.length === 0}+ <p class="empty">Sem links 1-hop.</p>+ {:else}+ <ul class="neighbors">+ {#each neighbors as n (n.node.id)}+ <li>+ <button type="button" class="entry-btn" onclick={() => open(n.node.id)}>+ <span class="weight" aria-hidden="true" style:--w={Math.min(n.weight, 5)}>·</span>+ <span class="name">{n.node.name}</span>+ <span class="w">×{n.weight}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .refresh {+ background: transparent;+ border: 0;+ color: inherit;+ cursor: pointer;+ font-size: 13px;+ padding: 0 4px;+ border-radius: 4px;+ }+ .refresh:hover {+ color: var(--accent);+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .center {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 12px;+ margin: 4px;+ border-radius: 6px;+ background: color-mix(in oklab, var(--accent) 15%, transparent);+ border: 1px solid color-mix(in oklab, var(--accent) 35%, transparent);+ font-size: 12px;+ }+ .dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--accent);+ }+ .label {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-weight: 600;+ color: var(--text);+ }+ .meta {+ font-size: 10px;+ color: var(--tertiary, var(--muted-fg));+ }+ .neighbors {+ list-style: none;+ margin: 0;+ padding: 4px 0;+ }+ .entry-btn {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 12px;+ padding: 4px 10px;+ cursor: pointer;+ border-radius: 4px;+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .entry-btn:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }+ .weight {+ color: color-mix(in oklab, var(--accent) calc(40% + var(--w) * 12%), transparent);+ font-size: 16px;+ line-height: 0.5;+ }+ .name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .w {+ font-size: 10px;+ opacity: 0.6;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockInbox.svelte b/src/lib/study-components/notes/shell/NbDockInbox.sveltenew file mode 100644index 00000000..c16ee93c--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockInbox.svelte@@ -0,0 +1,137 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { notesInboxList, type PageSummary } from "$lib/notes-bridge";++ let pages = $state<PageSummary[]>([]);+ let loading = $state(false);++ async function reload() {+ loading = true;+ try {+ pages = await notesInboxList();+ } catch {+ pages = [];+ } finally {+ loading = false;+ }+ }++ async function open(pageId: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({ wndId: wnd, pageId, viewKind: "editor", activate: true });+ }++ onMount(() => {+ void reload();+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Inbox</span>+ <button class="refresh" type="button" onclick={() => void reload()} title="Recarregar" aria-label="Recarregar">+ ↻+ </button>+ </header>+ <div class="body">+ {#if loading && pages.length === 0}+ <p class="empty">Carregando…</p>+ {:else if pages.length === 0}+ <p class="empty">Nada para triar — caixa vazia.</p>+ {:else}+ <ul class="entries">+ {#each pages as p (p.id)}+ <li>+ <button type="button" class="entry-btn" onclick={() => open(p.id)} title={p.name}>+ <span class="title">{p.title || p.name}</span>+ <span class="sub">{p.block_count} {p.block_count === 1 ? "bloco" : "blocos"}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .refresh {+ background: transparent;+ border: 0;+ color: inherit;+ cursor: pointer;+ font-size: 13px;+ padding: 0 4px;+ border-radius: 4px;+ }+ .refresh:hover {+ color: var(--accent);+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .entries {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .entry-btn {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 12px;+ line-height: 1.35;+ padding: 5px 10px;+ cursor: pointer;+ border-radius: 4px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .entry-btn:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }+ .title {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ font-size: 10px;+ opacity: 0.6;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockLeft.svelte b/src/lib/study-components/notes/shell/NbDockLeft.sveltenew file mode 100644index 00000000..a8f5bd4f--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockLeft.svelte@@ -0,0 +1,75 @@+<script lang="ts">+ import { docksStore } from "$lib/study-notes/docks-store.svelte";+ import NbResizeHandle from "./NbResizeHandle.svelte";+ import NbDockFiles from "./NbDockFiles.svelte";+ import NbDockOutline from "./NbDockOutline.svelte";++ const visible = $derived(docksStore.visibleByPosition("left"));+</script>++{#if visible.length > 0}+ <aside class="nb-dock nb-dock-left" data-count={visible.length}>+ <div class="stack" class:multi={visible.length > 1}>+ {#each visible as dock (dock.dock_id)}+ <section class="slot" data-id={dock.dock_id}>+ {#if dock.dock_id === "files"}+ <NbDockFiles />+ {:else if dock.dock_id === "outline"}+ <NbDockOutline />+ {:else}+ <div class="placeholder">+ <p class="hint">{dock.dock_id}</p>+ <p class="sub">Dock sem renderer dedicado.</p>+ </div>+ {/if}+ </section>+ {/each}+ </div>+ <NbResizeHandle side="left" />+ </aside>+{/if}++<style>+ .nb-dock {+ position: relative;+ height: 100%;+ display: flex;+ flex-direction: column;+ background: color-mix(in oklab, var(--surface-bg, var(--primary)) 70%, transparent);+ overflow: hidden;+ }+ .stack {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .stack.multi .slot:not(:last-child) {+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ }+ .stack.multi .slot {+ flex: 1 1 0;+ min-height: 0;+ overflow: hidden;+ }+ .stack:not(.multi) .slot {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ }+ .placeholder {+ padding: 20px 16px;+ color: var(--tertiary, var(--muted-fg));+ }+ .hint {+ margin: 0 0 4px;+ font-size: 13px;+ color: var(--secondary, var(--text));+ }+ .sub {+ margin: 0;+ font-size: 11px;+ opacity: 0.75;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockOutline.svelte b/src/lib/study-components/notes/shell/NbDockOutline.sveltenew file mode 100644index 00000000..d5cb9f35--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockOutline.svelte@@ -0,0 +1,153 @@+<script lang="ts">+ import { onMount, untrack } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { notesPagesOutline, type OutlineEntry } from "$lib/notes-bridge";++ let entries = $state<OutlineEntry[]>([]);+ let loading = $state(false);+ let lastPageId = $state<number | null>(null);++ const pageId = $derived(tabsStore.activeTab?.page_id ?? null);++ async function reload(id: number) {+ loading = true;+ try {+ entries = await notesPagesOutline(id);+ } catch {+ entries = [];+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const id = pageId;+ if (id === lastPageId) return;+ untrack(() => {+ lastPageId = id;+ if (id == null) {+ entries = [];+ return;+ }+ void reload(id);+ });+ });++ function jumpTo(blockId: number) {+ const el = document.querySelector<HTMLElement>(`[data-block-id="${blockId}"]`);+ if (el) {+ el.scrollIntoView({ behavior: "smooth", block: "start" });+ el.classList.add("nb-flash");+ setTimeout(() => el.classList.remove("nb-flash"), 800);+ }+ }++ onMount(() => {+ if (pageId != null) void reload(pageId);+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Outline</span>+ </header>+ <div class="body">+ {#if pageId == null}+ <p class="empty">Sem página ativa.</p>+ {:else if loading}+ <p class="empty">Carregando…</p>+ {:else if entries.length === 0}+ <p class="empty">Sem cabeçalhos nesta página.</p>+ {:else}+ <ul class="entries">+ {#each entries as entry (entry.block_id)}+ <li class="entry" style:--lvl={entry.level}>+ <button+ type="button"+ class="entry-btn"+ onclick={() => jumpTo(entry.block_id)}+ title={entry.content}+ >+ <span class="content">{entry.content || "(vazio)"}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .entries {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .entry {+ --lvl: 1;+ }+ .entry-btn {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 12px;+ line-height: 1.4;+ padding: 4px 8px 4px calc(8px + (var(--lvl) - 1) * 14px);+ cursor: pointer;+ border-radius: 4px;+ display: block;+ }+ .entry-btn:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }+ .content {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ display: block;+ }+ :global(.nb-flash) {+ animation: nb-flash 800ms ease-out;+ }+ @keyframes nb-flash {+ 0% {+ background: color-mix(in oklab, var(--accent) 30%, transparent);+ }+ 100% {+ background: transparent;+ }+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockRight.svelte b/src/lib/study-components/notes/shell/NbDockRight.sveltenew file mode 100644index 00000000..2184a010--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockRight.svelte@@ -0,0 +1,84 @@+<script lang="ts">+ import { docksStore } from "$lib/study-notes/docks-store.svelte";+ import NbResizeHandle from "./NbResizeHandle.svelte";+ import NbDockBacklink from "./NbDockBacklink.svelte";+ import NbDockBookmark from "./NbDockBookmark.svelte";+ import NbDockTag from "./NbDockTag.svelte";+ import NbDockInbox from "./NbDockInbox.svelte";+ import NbDockGraph from "./NbDockGraph.svelte";++ const visible = $derived(docksStore.visibleByPosition("right"));+</script>++{#if visible.length > 0}+ <aside class="nb-dock nb-dock-right" data-count={visible.length}>+ <NbResizeHandle side="right" />+ <div class="stack" class:multi={visible.length > 1}>+ {#each visible as dock (dock.dock_id)}+ <section class="slot" data-id={dock.dock_id}>+ {#if dock.dock_id === "backlink"}+ <NbDockBacklink />+ {:else if dock.dock_id === "bookmark"}+ <NbDockBookmark />+ {:else if dock.dock_id === "tag"}+ <NbDockTag />+ {:else if dock.dock_id === "inbox"}+ <NbDockInbox />+ {:else if dock.dock_id === "graph"}+ <NbDockGraph />+ {:else}+ <div class="placeholder">+ <p class="hint">{dock.dock_id}</p>+ <p class="sub">Dock sem renderer dedicado.</p>+ </div>+ {/if}+ </section>+ {/each}+ </div>+ </aside>+{/if}++<style>+ .nb-dock {+ position: relative;+ height: 100%;+ display: flex;+ flex-direction: column;+ background: color-mix(in oklab, var(--surface-bg, var(--primary)) 70%, transparent);+ overflow: hidden;+ }+ .stack {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .stack.multi .slot:not(:last-child) {+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ }+ .stack.multi .slot {+ flex: 1 1 0;+ min-height: 0;+ overflow: hidden;+ }+ .stack:not(.multi) .slot {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ }+ .placeholder {+ padding: 20px 16px;+ color: var(--tertiary, var(--muted-fg));+ }+ .hint {+ margin: 0 0 4px;+ font-size: 13px;+ color: var(--secondary, var(--text));+ }+ .sub {+ margin: 0;+ font-size: 11px;+ opacity: 0.75;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockSidebar.svelte b/src/lib/study-components/notes/shell/NbDockSidebar.sveltenew file mode 100644index 00000000..2fb93a9d--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockSidebar.svelte@@ -0,0 +1,112 @@+<script lang="ts">+ import { docksStore, DOCK_META, type DockIconKey } from "$lib/study-notes/docks-store.svelte";+ import type { DockPosition } from "$lib/notes-bridge";++ type Props = { side: "left" | "right" };+ let { side }: Props = $props();++ const sideAsPos = $derived<DockPosition>(side);++ const items = $derived(+ DOCK_META.filter((m) => {+ const cur = docksStore.states[m.id];+ const pos = cur?.position ?? m.defaultPosition;+ return pos === sideAsPos;+ }),+ );++ function isVisible(id: string): boolean {+ return docksStore.states[id]?.visible ?? false;+ }++ function toggle(id: string) {+ void docksStore.toggle(id);+ }++ function iconPath(key: DockIconKey): string {+ switch (key) {+ case "files":+ return "M3 7l1.7-3.4A2 2 0 0 1 6.5 2.5h11A2 2 0 0 1 19.3 3.6L21 7M3 7v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V7M3 7h18M8 11h8";+ case "list-tree":+ return "M21 12h-8M21 6h-8M21 18h-8M3 6v12M3 6l4 4M3 12l4-4M3 18l4-4";+ case "link":+ return "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71";+ case "bookmark":+ return "M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z";+ case "tags":+ return "M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82zM7 7h.01";+ case "inbox":+ return "M22 12h-6l-2 3h-4l-2-3H2M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z";+ case "share-2":+ return "M18 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 22a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM8.59 13.51l6.83 3.98M15.41 6.51l-6.82 3.98";+ }+ }+</script>++<aside class="nb-dock-sidebar" data-side={side} aria-label="Toggle docks {side}">+ {#each items as item (item.id)}+ <button+ type="button"+ class="icon-btn"+ class:active={isVisible(item.id)}+ onclick={() => toggle(item.id)}+ title="{item.label} ({isVisible(item.id) ? 'visível' : 'oculto'})"+ aria-pressed={isVisible(item.id)}+ aria-label={item.label}+ >+ <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"+ >+ <path d={iconPath(item.iconKey)} />+ </svg>+ </button>+ {/each}+</aside>++<style>+ .nb-dock-sidebar {+ width: 32px;+ height: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 4px 0;+ gap: 2px;+ background: color-mix(in oklab, var(--surface-bg, var(--primary)) 60%, transparent);+ }+ .nb-dock-sidebar[data-side="left"] {+ border-right: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ }+ .nb-dock-sidebar[data-side="right"] {+ border-left: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ }+ .icon-btn {+ width: 26px;+ height: 26px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: 0;+ border-radius: 5px;+ cursor: pointer;+ color: var(--tertiary, var(--muted-fg));+ transition: background 120ms ease, color 120ms ease;+ }+ .icon-btn:hover {+ color: var(--secondary, var(--text));+ background: color-mix(in oklab, var(--content-border) 30%, transparent);+ }+ .icon-btn.active {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 16%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbDockTag.svelte b/src/lib/study-components/notes/shell/NbDockTag.sveltenew file mode 100644index 00000000..cd7a78c7--- /dev/null+++ b/src/lib/study-components/notes/shell/NbDockTag.svelte@@ -0,0 +1,236 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import {+ notesTagsList,+ notesPagesListByTag,+ type TagSummary,+ type PageSummary,+ } from "$lib/notes-bridge";++ let tags = $state<TagSummary[]>([]);+ let loading = $state(false);+ let activeTag = $state<string | null>(null);+ let activeTagPages = $state<PageSummary[]>([]);+ let activeLoading = $state(false);++ async function reload() {+ loading = true;+ try {+ tags = await notesTagsList(80);+ } catch {+ tags = [];+ } finally {+ loading = false;+ }+ }++ async function pickTag(name: string) {+ if (activeTag === name) {+ activeTag = null;+ activeTagPages = [];+ return;+ }+ activeTag = name;+ activeLoading = true;+ try {+ activeTagPages = await notesPagesListByTag(name);+ } catch {+ activeTagPages = [];+ } finally {+ activeLoading = false;+ }+ }++ async function openPage(pageId: number) {+ const wnd = tabsStore.activeWndId ?? tabsStore.leafIds[0];+ if (wnd == null) return;+ await tabsStore.openTab({ wndId: wnd, pageId, viewKind: "editor", activate: true });+ }++ onMount(() => {+ void reload();+ });+</script>++<aside class="nb-dock">+ <header class="dock-head">+ <span class="dock-title">Tags</span>+ <button class="refresh" type="button" onclick={() => void reload()} title="Recarregar" aria-label="Recarregar">+ ↻+ </button>+ </header>+ <div class="body">+ {#if loading && tags.length === 0}+ <p class="empty">Carregando…</p>+ {:else if tags.length === 0}+ <p class="empty">Nenhuma tag.</p>+ {:else}+ <ul class="tag-list">+ {#each tags as tag (tag.name)}+ <li>+ <button+ type="button"+ class="tag"+ class:active={activeTag === tag.name}+ onclick={() => pickTag(tag.name)}+ >+ <span class="hash">#</span>+ <span class="name">{tag.name}</span>+ <span class="count">{tag.ref_count}</span>+ </button>+ </li>+ {/each}+ </ul>++ {#if activeTag}+ <div class="tag-pages">+ <header class="sub-head">+ Páginas com #{activeTag}+ {#if activeLoading}<span class="loading">…</span>{/if}+ </header>+ {#if activeTagPages.length === 0 && !activeLoading}+ <p class="empty">Nenhuma página.</p>+ {:else}+ <ul class="entries">+ {#each activeTagPages as p (p.id)}+ <li>+ <button type="button" class="entry-btn" onclick={() => openPage(p.id)}>+ {p.title || p.name}+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+ {/if}+ {/if}+ </div>+</aside>++<style>+ .nb-dock {+ height: 100%;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .dock-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary, var(--muted-fg));+ }+ .dock-title {+ font-weight: 600;+ color: var(--secondary, var(--text));+ }+ .refresh {+ background: transparent;+ border: 0;+ color: inherit;+ cursor: pointer;+ font-size: 13px;+ padding: 0 4px;+ border-radius: 4px;+ }+ .refresh:hover {+ color: var(--accent);+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 6px 4px;+ }+ .empty {+ padding: 14px;+ margin: 0;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+ .tag-list {+ list-style: none;+ margin: 0;+ padding: 4px;+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ }+ .tag {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ background: color-mix(in oklab, var(--content-border) 25%, transparent);+ border: 1px solid transparent;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 11px;+ padding: 3px 8px;+ border-radius: 999px;+ cursor: pointer;+ }+ .tag:hover {+ color: var(--accent);+ border-color: color-mix(in oklab, var(--accent) 35%, transparent);+ }+ .tag.active {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 18%, transparent);+ border-color: color-mix(in oklab, var(--accent) 50%, transparent);+ }+ .hash {+ opacity: 0.55;+ }+ .count {+ font-size: 9.5px;+ opacity: 0.7;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ padding: 0 5px;+ border-radius: 999px;+ }+ .tag-pages {+ margin-top: 6px;+ border-top: 1px solid color-mix(in oklab, var(--content-border) 25%, transparent);+ padding-top: 6px;+ }+ .sub-head {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ padding: 6px 10px 2px;+ color: var(--tertiary, var(--muted-fg));+ }+ .loading {+ font-style: italic;+ margin-left: 4px;+ }+ .entries {+ list-style: none;+ margin: 0;+ padding: 0;+ }+ .entry-btn {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: var(--secondary, var(--text));+ font: inherit;+ font-size: 12px;+ padding: 4px 10px;+ cursor: pointer;+ border-radius: 4px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .entry-btn:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbNewSplitMenu.svelte b/src/lib/study-components/notes/shell/NbNewSplitMenu.sveltenew file mode 100644index 00000000..8985336e--- /dev/null+++ b/src/lib/study-components/notes/shell/NbNewSplitMenu.svelte@@ -0,0 +1,137 @@+<script lang="ts">+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";++ type Props = { wndId: number };++ let { wndId }: Props = $props();++ let open = $state(false);+ let buttonEl: HTMLButtonElement | null = null;++ function toggle() {+ open = !open;+ }++ async function doSplit(direction: "horizontal" | "vertical") {+ open = false;+ await tabsStore.splitWnd(wndId, direction);+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ open = false;+ buttonEl?.focus();+ }+ }++ function onWindowMouseDown(e: MouseEvent) {+ if (!open) return;+ const target = e.target as Node | null;+ if (buttonEl && target && !buttonEl.contains(target)) {+ open = false;+ }+ }+</script>++<svelte:window onmousedown={onWindowMouseDown} onkeydown={onKey} />++<div class="nb-new-split-menu">+ <button+ type="button"+ class="trigger"+ class:active={open}+ onclick={toggle}+ bind:this={buttonEl}+ aria-haspopup="menu"+ aria-expanded={open}+ title="Novo split"+ >+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">+ <rect x="1" y="1" width="14" height="14" rx="1" />+ <line x1="8" y1="1" x2="8" y2="15" />+ </svg>+ </button>+ {#if open}+ <div class="menu" role="menu">+ <button class="item" role="menuitem" onclick={() => doSplit("vertical")}>+ <span class="icon">⇨</span>+ Split à direita+ <span class="shortcut">Ctrl+\</span>+ </button>+ <button class="item" role="menuitem" onclick={() => doSplit("horizontal")}>+ <span class="icon">⇩</span>+ Split abaixo+ <span class="shortcut">Ctrl+Shift+\</span>+ </button>+ </div>+ {/if}+</div>++<style>+ .nb-new-split-menu {+ position: relative;+ display: inline-flex;+ align-items: center;+ height: 100%;+ }+ .trigger {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 100%;+ background: transparent;+ border: 0;+ color: var(--tertiary, var(--muted-fg));+ cursor: pointer;+ transition: color 120ms ease, background 120ms ease;+ }+ .trigger:hover,+ .trigger.active {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .menu {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ z-index: 50;+ min-width: 180px;+ background: var(--secondary-bg, var(--page-bg));+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 6px;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);+ padding: 4px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 10px;+ background: transparent;+ border: 0;+ color: var(--text);+ text-align: left;+ font-size: 12px;+ cursor: pointer;+ border-radius: 4px;+ transition: background 80ms ease;+ }+ .item:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+ .icon {+ width: 16px;+ text-align: center;+ color: var(--tertiary, var(--muted-fg));+ }+ .shortcut {+ margin-left: auto;+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: var(--tertiary, var(--muted-fg));+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbNotebookCoverDialog.svelte b/src/lib/study-components/notes/shell/NbNotebookCoverDialog.sveltenew file mode 100644index 00000000..d962c673--- /dev/null+++ b/src/lib/study-components/notes/shell/NbNotebookCoverDialog.svelte@@ -0,0 +1,256 @@+<script lang="ts">+ import { notebooksStore } from "$lib/study-notes/notebooks-store.svelte";++ type Props = {+ open: boolean;+ notebookId: number | null;+ onClose: () => void;+ };++ let { open, notebookId, onClose }: Props = $props();++ let assetIdDraft = $state<string>("");+ let busy = $state(false);+ let error = $state<string>("");++ const current = $derived(+ notebookId == null ? null : notebooksStore.byId(notebookId),+ );++ $effect(() => {+ if (open) {+ assetIdDraft = current?.cover_asset_id?.toString() ?? "";+ error = "";+ }+ });++ async function apply() {+ if (notebookId == null) return;+ const trimmed = assetIdDraft.trim();+ let asset: number | null = null;+ if (trimmed.length > 0) {+ const n = Number.parseInt(trimmed, 10);+ if (!Number.isFinite(n) || n <= 0) {+ error = "ID precisa ser inteiro positivo";+ return;+ }+ asset = n;+ }+ busy = true;+ error = "";+ try {+ await notebooksStore.setCover(notebookId, asset);+ onClose();+ } catch (e) {+ error = String(e ?? "falha ao aplicar capa");+ } finally {+ busy = false;+ }+ }++ async function clear() {+ if (notebookId == null) return;+ busy = true;+ try {+ await notebooksStore.setCover(notebookId, null);+ onClose();+ } finally {+ busy = false;+ }+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ onClose();+ } else if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void apply();+ }+ }+</script>++{#if open && notebookId != null}+ <div+ class="backdrop"+ role="presentation"+ onclick={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ onkeydown={onKey}+ >+ <div+ class="dialog"+ role="dialog"+ aria-modal="true"+ aria-label="Capa do notebook"+ data-modal="true"+ >+ <header>+ <h3>Capa de {current?.name ?? "notebook"}</h3>+ <button type="button" class="x" onclick={onClose} aria-label="Fechar">×</button>+ </header>++ <p class="hint">+ Use o ID de um asset já registrado em <code>note_assets</code>.+ Para fazer upload de uma nova imagem, use o gerenciador de capas+ de uma página primeiro e depois aponte o ID aqui.+ </p>++ <label class="field">+ <span>Asset ID</span>+ <input+ type="text"+ inputmode="numeric"+ placeholder="ex: 42"+ bind:value={assetIdDraft}+ />+ </label>++ {#if error}+ <p class="error">{error}</p>+ {/if}++ <footer>+ <button+ type="button"+ class="btn ghost"+ onclick={clear}+ disabled={busy || current?.cover_asset_id == null}+ >+ Remover capa+ </button>+ <span class="spacer"></span>+ <button type="button" class="btn ghost" onclick={onClose} disabled={busy}>+ Cancelar+ </button>+ <button type="button" class="btn primary" onclick={apply} disabled={busy}>+ Aplicar+ </button>+ </footer>+ </div>+ </div>+{/if}++<style>+ .backdrop {+ position: fixed;+ inset: 0;+ z-index: 200;+ display: grid;+ place-items: center;+ background: color-mix(in oklab, black 40%, transparent);+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ }+ .dialog {+ width: min(440px, 92vw);+ background: var(--bg);+ color: var(--text);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 14px;+ padding: 18px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.4);+ }+ header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }+ header h3 {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+ }+ .x {+ background: transparent;+ border: 0;+ color: var(--tertiary);+ font-size: 18px;+ cursor: pointer;+ padding: 0 4px;+ }+ .hint {+ margin: 0;+ color: var(--tertiary);+ font-size: 12px;+ line-height: 1.45;+ }+ .hint code {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ padding: 1px 5px;+ border-radius: 4px;+ font-family: ui-monospace, monospace;+ font-size: 11px;+ }+ .field {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .field > span {+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary);+ }+ input[type="text"] {+ padding: 8px 10px;+ border: 1px solid var(--input-border);+ border-radius: 8px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ font-size: 13px;+ }+ input[type="text"]:focus {+ outline: none;+ border-color: var(--accent);+ }+ .error {+ margin: 0;+ color: #ef4444;+ font-size: 12px;+ }+ footer {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .spacer {+ flex: 1;+ }+ .btn {+ padding: 7px 14px;+ border-radius: 8px;+ border: 1px solid transparent;+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 150ms, border-color 150ms;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .btn.ghost {+ background: transparent;+ border-color: var(--input-border);+ color: var(--text);+ }+ .btn.ghost:hover:not(:disabled) {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .btn.primary {+ background: var(--accent);+ color: #fff;+ }+ .btn.primary:hover:not(:disabled) {+ filter: brightness(1.08);+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbNotebookCreateDialog.svelte b/src/lib/study-components/notes/shell/NbNotebookCreateDialog.sveltenew file mode 100644index 00000000..7dc80ffa--- /dev/null+++ b/src/lib/study-components/notes/shell/NbNotebookCreateDialog.svelte@@ -0,0 +1,336 @@+<script lang="ts">+ import { untrack } from "svelte";+ import {+ NOTEBOOK_LUCIDE_OPTIONS,+ NOTEBOOK_COLOR_SWATCHES,+ } from "$lib/study-notes/notebooks-store.svelte";++ type Props = {+ open: boolean;+ initialName?: string;+ initialColor?: string | null;+ initialIcon?: string | null;+ title?: string;+ confirmLabel?: string;+ onConfirm: (args: {+ name: string;+ color: string | null;+ iconLucide: string | null;+ }) => void;+ onClose: () => void;+ };++ // svelte-ignore state_referenced_locally+ let {+ open,+ initialName = "",+ initialColor = null,+ initialIcon = "book",+ title = "Novo notebook",+ confirmLabel = "Criar",+ onConfirm,+ onClose,+ }: Props = $props();++ let name = $state(initialName);+ let icon = $state<string | null>(initialIcon);+ let color = $state<string | null>(initialColor);+ let inputRef = $state<HTMLInputElement | null>(null);++ function snapshotProps() {+ return {+ name: initialName,+ icon: initialIcon,+ color: initialColor,+ };+ }++ $effect(() => {+ if (open) {+ const snap = untrack(snapshotProps);+ name = snap.name;+ icon = snap.icon;+ color = snap.color;+ queueMicrotask(() => inputRef?.focus());+ }+ });++ function submit() {+ const trimmed = name.trim();+ if (!trimmed) return;+ onConfirm({ name: trimmed, color, iconLucide: icon });+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ onClose();+ } else if (e.key === "Enter" && !e.shiftKey && !e.altKey) {+ e.preventDefault();+ submit();+ }+ }+</script>++{#if open}+ <div+ class="backdrop"+ role="presentation"+ onclick={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ onkeydown={onKey}+ >+ <div+ class="dialog"+ role="dialog"+ aria-modal="true"+ aria-label={title}+ data-modal="true"+ >+ <header>+ <h3>{title}</h3>+ <button+ type="button"+ class="x"+ onclick={onClose}+ aria-label="Fechar"+ >×</button>+ </header>++ <label class="field">+ <span>Nome</span>+ <input+ bind:this={inputRef}+ bind:value={name}+ type="text"+ maxlength="60"+ placeholder="Pessoal, Trabalho, Estudos…"+ />+ </label>++ <div class="field">+ <span>Ícone</span>+ <div class="grid icons">+ {#each NOTEBOOK_LUCIDE_OPTIONS as opt (opt)}+ <button+ type="button"+ class="icon-btn"+ class:active={icon === opt}+ title={opt}+ aria-pressed={icon === opt}+ onclick={() => (icon = opt)}+ >+ <span class="icon-name">{opt}</span>+ </button>+ {/each}+ </div>+ </div>++ <div class="field">+ <span>Cor</span>+ <div class="grid swatches">+ <button+ type="button"+ class="swatch none"+ class:active={color === null}+ aria-pressed={color === null}+ title="Sem cor"+ onclick={() => (color = null)}+ >∅</button>+ {#each NOTEBOOK_COLOR_SWATCHES as sw (sw)}+ <button+ type="button"+ class="swatch"+ class:active={color === sw}+ aria-pressed={color === sw}+ style:background={sw}+ title={sw}+ onclick={() => (color = sw)}+ ></button>+ {/each}+ </div>+ </div>++ <footer>+ <button type="button" class="btn ghost" onclick={onClose}>+ Cancelar+ </button>+ <button+ type="button"+ class="btn primary"+ disabled={!name.trim()}+ onclick={submit}+ >+ {confirmLabel}+ </button>+ </footer>+ </div>+ </div>+{/if}++<style>+ .backdrop {+ position: fixed;+ inset: 0;+ z-index: 200;+ display: grid;+ place-items: center;+ background: color-mix(in oklab, black 40%, transparent);+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ }+ .dialog {+ width: min(440px, 92vw);+ background: var(--bg, var(--page-bg));+ color: var(--text);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 14px;+ padding: 18px 18px 14px;+ display: flex;+ flex-direction: column;+ gap: 14px;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.4);+ }+ header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }+ header h3 {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+ }+ .x {+ background: transparent;+ border: 0;+ color: var(--tertiary);+ font-size: 18px;+ cursor: pointer;+ padding: 0 4px;+ }+ .x:hover {+ color: var(--text);+ }+ .field {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .field > span {+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--tertiary);+ }+ input[type="text"] {+ padding: 8px 10px;+ border: 1px solid var(--input-border);+ border-radius: 8px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ font-size: 13px;+ }+ input[type="text"]:focus {+ outline: none;+ border-color: var(--accent);+ }+ .grid {+ display: grid;+ gap: 6px;+ }+ .grid.icons {+ grid-template-columns: repeat(6, 1fr);+ }+ .grid.swatches {+ grid-template-columns: repeat(9, 1fr);+ }+ .icon-btn {+ border: 1px solid var(--input-border);+ border-radius: 8px;+ background: transparent;+ color: var(--secondary);+ font: inherit;+ font-size: 9.5px;+ padding: 6px 4px;+ cursor: pointer;+ transition: background 120ms, border-color 120ms;+ min-height: 40px;+ display: grid;+ place-items: center;+ }+ .icon-btn:hover {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .icon-btn.active {+ background: color-mix(in oklab, var(--accent) 15%, transparent);+ border-color: var(--accent);+ color: var(--text);+ }+ .icon-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ width: 100%;+ text-align: center;+ }+ .swatch {+ aspect-ratio: 1 / 1;+ border-radius: 999px;+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ background: transparent;+ cursor: pointer;+ transition: transform 120ms, border-color 120ms;+ }+ .swatch:hover {+ transform: scale(1.08);+ }+ .swatch.active {+ border-color: var(--text);+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--text) 30%, transparent);+ }+ .swatch.none {+ color: var(--tertiary);+ font-size: 14px;+ display: grid;+ place-items: center;+ }+ footer {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 4px;+ }+ .btn {+ padding: 7px 14px;+ border-radius: 8px;+ border: 1px solid transparent;+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 150ms, border-color 150ms;+ }+ .btn.ghost {+ background: transparent;+ border-color: var(--input-border);+ color: var(--text);+ }+ .btn.ghost:hover {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .btn.primary {+ background: var(--accent);+ color: #fff;+ }+ .btn.primary:hover:not(:disabled) {+ filter: brightness(1.08);+ }+ .btn.primary:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbResizeHandle.svelte b/src/lib/study-components/notes/shell/NbResizeHandle.sveltenew file mode 100644index 00000000..d22a076d--- /dev/null+++ b/src/lib/study-components/notes/shell/NbResizeHandle.svelte@@ -0,0 +1,99 @@+<script lang="ts">+ import {+ notesShell,+ NOTES_SHELL_DOCK_MIN,+ NOTES_SHELL_DOCK_MAX,+ } from "$lib/study-notes/shell-store.svelte";++ type Props = { side: "left" | "right" };+ let { side }: Props = $props();++ let dragging = $state(false);+ let startX = 0;+ let startWidth = 0;++ function onPointerDown(e: PointerEvent) {+ if (e.button !== 0) return;+ e.preventDefault();+ dragging = true;+ startX = e.clientX;+ startWidth =+ side === "left" ? notesShell.dockLeftWidth : notesShell.dockRightWidth;+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ }++ function onPointerMove(e: PointerEvent) {+ if (!dragging) return;+ const delta = e.clientX - startX;+ if (side === "left") {+ notesShell.setDockLeftWidth(startWidth + delta);+ } else {+ notesShell.setDockRightWidth(startWidth - delta);+ }+ }++ function onPointerUp(e: PointerEvent) {+ if (!dragging) return;+ dragging = false;+ try {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ } catch {+ /* ignore */+ }+ void notesShell.persistBackend();+ }++ function onDoubleClick() {+ if (side === "left") {+ notesShell.setDockLeftWidth(240);+ } else {+ notesShell.setDockRightWidth(280);+ }+ void notesShell.persistBackend();+ }+</script>++<div+ class="handle"+ class:left={side === "left"}+ class:right={side === "right"}+ class:dragging+ role="separator"+ aria-orientation="vertical"+ aria-label={side === "left" ? "Redimensionar dock esquerdo" : "Redimensionar dock direito"}+ aria-valuemin={NOTES_SHELL_DOCK_MIN}+ aria-valuemax={NOTES_SHELL_DOCK_MAX}+ aria-valuenow={side === "left" ? notesShell.dockLeftWidth : notesShell.dockRightWidth}+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ onpointercancel={onPointerUp}+ ondblclick={onDoubleClick}+></div>++<style>+ .handle {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 4px;+ cursor: col-resize;+ background: transparent;+ transition: background 120ms ease;+ z-index: 3;+ }+ .handle.left {+ right: -2px;+ }+ .handle.right {+ left: -2px;+ }+ .handle:hover,+ .handle.dragging {+ background: color-mix(in oklab, var(--accent) 50%, transparent);+ }+ .handle:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: -2px;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbShell.svelte b/src/lib/study-components/notes/shell/NbShell.sveltenew file mode 100644index 00000000..48d49a75--- /dev/null+++ b/src/lib/study-components/notes/shell/NbShell.svelte@@ -0,0 +1,354 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { notesShell } from "$lib/study-notes/shell-store.svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { docksStore } from "$lib/study-notes/docks-store.svelte";+ import { notebooksStore } from "$lib/study-notes/notebooks-store.svelte";+ import NbStatusBar from "./NbStatusBar.svelte";+ import NbDockLeft from "./NbDockLeft.svelte";+ import NbDockRight from "./NbDockRight.svelte";+ import NbDockSidebar from "./NbDockSidebar.svelte";+ import NbWndTree from "./NbWndTree.svelte";++ let { children } = $props();++ function exitFullscreen() {+ const target = notesShell.consumeReturnUrl();+ void goto(target);+ }++ function shouldIgnoreEsc(target: HTMLElement | null): boolean {+ if (!target) return false;+ const tag = target.tagName;+ if (tag === "INPUT" || tag === "TEXTAREA") return true;+ if (target.isContentEditable) return true;+ if (target.closest('[data-modal="true"]')) return true;+ if (target.closest('[role="dialog"]')) return true;+ return false;+ }++ function shouldIgnoreShortcut(target: HTMLElement | null): boolean {+ if (!target) return false;+ if (target.isContentEditable) return true;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";+ }++ async function reopenLastClosed() {+ const popped = tabsStore.popRecentlyClosed();+ if (!popped) return;+ const exists = tabsStore.leafIds.includes(popped.wndId);+ const wndId = exists ? popped.wndId : (tabsStore.activeWndId ?? tabsStore.leafIds[0] ?? 1);+ if (popped.viewKind === "editor" && popped.pageId == null) return;+ await tabsStore.openTab({+ wndId,+ pageId: popped.pageId,+ viewKind: popped.viewKind,+ activate: true,+ });+ }++ function dispatchNewNotebook() {+ window.dispatchEvent(new CustomEvent("study:notes:notebook-new"));+ }++ async function handleShortcut(e: KeyboardEvent) {+ const ctrl = e.ctrlKey || e.metaKey;+ if (!ctrl) return;+ if (shouldIgnoreShortcut(e.target as HTMLElement | null)) return;+ const wndId = tabsStore.activeWndId;++ if (e.shiftKey && (e.key === "n" || e.key === "N") && !e.altKey) {+ e.preventDefault();+ dispatchNewNotebook();+ return;+ }+ if (e.altKey && /^[1-9]$/.test(e.key) && !e.shiftKey) {+ e.preventDefault();+ const ok = notebooksStore.switchToIndex(parseInt(e.key, 10) - 1);+ if (!ok) {+ /* no-op when index out of range */+ }+ return;+ }++ if (e.key === "t" && !e.shiftKey && !e.altKey) {+ e.preventDefault();+ const trigger = document.querySelector<HTMLButtonElement>(+ `[data-wnd-id="${wndId}"] .add`,+ );+ trigger?.click();+ return;+ }+ if (e.key === "w" && !e.shiftKey && !e.altKey) {+ e.preventDefault();+ const tabId = tabsStore.activeTabId;+ if (tabId != null) await tabsStore.closeTab(tabId);+ return;+ }+ if (e.key === "T" && e.shiftKey) {+ e.preventDefault();+ await reopenLastClosed();+ return;+ }+ if (e.key === "Tab") {+ e.preventDefault();+ tabsStore.cycleActiveTab(e.shiftKey ? -1 : 1);+ return;+ }+ if (e.key === "\\" && !e.shiftKey && wndId != null) {+ e.preventDefault();+ await tabsStore.splitWnd(wndId, "vertical");+ return;+ }+ if (e.key === "|" && wndId != null) {+ e.preventDefault();+ await tabsStore.splitWnd(wndId, "horizontal");+ return;+ }+ if (/^[1-9]$/.test(e.key) && !e.shiftKey && !e.altKey) {+ e.preventDefault();+ tabsStore.activateTabIndex(parseInt(e.key, 10) - 1);+ return;+ }+ if (e.altKey && wndId != null) {+ let dir: "left" | "right" | "up" | "down" | null = null;+ if (e.key === "ArrowLeft") dir = "left";+ else if (e.key === "ArrowRight") dir = "right";+ else if (e.key === "ArrowUp") dir = "up";+ else if (e.key === "ArrowDown") dir = "down";+ if (dir) {+ e.preventDefault();+ tabsStore.focusNeighborWnd(dir);+ }+ }+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape" && !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) {+ if (!shouldIgnoreEsc(e.target as HTMLElement | null)) {+ e.preventDefault();+ exitFullscreen();+ return;+ }+ }+ void handleShortcut(e);+ }++ onMount(() => {+ notesShell.loadLocal();+ void notesShell.hydrateFromBackend();+ void tabsStore.hydrate();+ void docksStore.hydrate();+ void notebooksStore.hydrate();++ if (typeof window !== "undefined") {+ try {+ const referrer = document.referrer;+ if (referrer && !referrer.includes("/study/notes")) {+ const url = new URL(referrer, window.location.origin);+ if (url.origin === window.location.origin) {+ notesShell.rememberReturnUrl(url.pathname + url.search);+ }+ }+ } catch {+ /* ignore */+ }+ }++ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });++ const leftHasVisible = $derived(docksStore.visibleByPosition("left").length > 0);+ const rightHasVisible = $derived(docksStore.visibleByPosition("right").length > 0);+ const dockLeftPx = $derived(+ notesShell.dockLeftVisible && leftHasVisible ? `${notesShell.dockLeftWidth}px` : "0px",+ );+ const dockRightPx = $derived(+ notesShell.dockRightVisible && rightHasVisible ? `${notesShell.dockRightWidth}px` : "0px",+ );+ const tree = $derived(tabsStore.tree);+ const hasSplits = $derived(!!tree && tree.split_dir !== null && tree.split_dir !== undefined);+</script>++<div+ class="nb-shell"+ style:--nb-dock-left={dockLeftPx}+ style:--nb-dock-right={dockRightPx}+>+ <div class="nb-rail nb-rail-left">+ <NbDockSidebar side="left" />+ </div>++ <div class="nb-dock-left">+ <NbDockLeft />+ </div>++ <main class="nb-main">+ <button+ type="button"+ class="exit-btn"+ onclick={exitFullscreen}+ aria-label="Sair do modo fullscreen"+ title="Sair (Esc)"+ >+ <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>++ {#snippet activeContentSnippet()}+ <div class="nb-route-host">+ {@render children?.()}+ </div>+ {/snippet}+ {#if tree}+ <div class="nb-tree" class:has-splits={hasSplits}>+ <NbWndTree node={tree} activeContent={activeContentSnippet} />+ </div>+ {:else}+ <div class="nb-route-host">+ {@render children?.()}+ </div>+ {/if}+ </main>++ <div class="nb-dock-right">+ <NbDockRight />+ </div>++ <div class="nb-rail nb-rail-right">+ <NbDockSidebar side="right" />+ </div>++ <div class="nb-status">+ <NbStatusBar />+ </div>+</div>++<style>+ .nb-shell {+ position: fixed;+ inset: 0;+ z-index: 90;+ display: grid;+ grid-template-columns: 32px var(--nb-dock-left, 240px) 1fr var(--nb-dock-right, 280px) 32px;+ grid-template-rows: 1fr 24px;+ grid-template-areas:+ "rail-left dock-left main dock-right rail-right"+ "statusbar statusbar statusbar statusbar statusbar";+ background:+ radial-gradient(ellipse at 30% 0%, color-mix(in oklab, var(--accent) 18%, transparent) 0%, transparent 60%),+ radial-gradient(ellipse at 80% 100%, color-mix(in oklab, var(--accent) 8%, transparent) 0%, transparent 70%),+ var(--primary, var(--page-bg));+ color: var(--secondary, var(--text));+ transition: background 600ms ease;+ }++ .nb-rail {+ overflow: hidden;+ }+ .nb-rail-left {+ grid-area: rail-left;+ }+ .nb-rail-right {+ grid-area: rail-right;+ }++ .nb-dock-left {+ grid-area: dock-left;+ border-right: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);+ overflow: hidden;+ min-width: 0;+ }++ .nb-dock-right {+ grid-area: dock-right;+ border-left: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);+ overflow: hidden;+ min-width: 0;+ }++ .nb-main {+ grid-area: main;+ position: relative;+ overflow: hidden;+ min-width: 0;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }+ .nb-tree {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ padding: 0;+ }+ .nb-tree.has-splits {+ padding: 4px;+ }+ .nb-route-host {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ }++ .nb-status {+ grid-area: statusbar;+ border-top: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);+ }++ .exit-btn {+ position: absolute;+ top: 10px;+ right: 16px;+ z-index: 5;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: color-mix(in oklab, var(--button) 60%, transparent);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 999px;+ color: var(--tertiary, var(--muted-fg));+ font-family: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .exit-btn:hover {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, var(--button));+ }+ .esc-hint {+ font-family: ui-monospace, monospace;+ font-size: 10px;+ padding: 1px 5px;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ border-radius: 4px;+ color: var(--secondary, var(--text));+ letter-spacing: 0.04em;+ }++ @media (max-width: 760px) {+ .nb-shell {+ grid-template-columns: 1fr;+ grid-template-areas:+ "main"+ "statusbar";+ }+ .nb-dock-left,+ .nb-dock-right,+ .nb-rail {+ display: none;+ }+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbSplitHandle.svelte b/src/lib/study-components/notes/shell/NbSplitHandle.sveltenew file mode 100644index 00000000..f59bc678--- /dev/null+++ b/src/lib/study-components/notes/shell/NbSplitHandle.svelte@@ -0,0 +1,99 @@+<script lang="ts">+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";++ type Props = {+ wndId: number;+ direction: "horizontal" | "vertical";+ ratio: number;+ };++ let { wndId, direction, ratio }: Props = $props();++ let dragging = $state(false);+ let containerEl: HTMLElement | null = null;++ function onPointerDown(e: PointerEvent) {+ e.preventDefault();+ const handle = e.currentTarget as HTMLElement;+ containerEl = handle.parentElement;+ if (!containerEl) return;+ dragging = true;+ handle.setPointerCapture(e.pointerId);+ }++ function onPointerMove(e: PointerEvent) {+ if (!dragging || !containerEl) return;+ const rect = containerEl.getBoundingClientRect();+ let next: number;+ if (direction === "vertical") {+ next = (e.clientX - rect.left) / rect.width;+ } else {+ next = (e.clientY - rect.top) / rect.height;+ }+ next = Math.max(0.05, Math.min(0.95, next));+ void tabsStore.setRatio(wndId, next);+ }++ function onPointerUp(e: PointerEvent) {+ if (!dragging) return;+ dragging = false;+ const handle = e.currentTarget as HTMLElement;+ try {+ handle.releasePointerCapture(e.pointerId);+ } catch {+ /* ignore */+ }+ }++ function onDoubleClick() {+ void tabsStore.setRatio(wndId, 0.5);+ }+</script>++<div+ class="nb-split-handle"+ class:vertical={direction === "vertical"}+ class:horizontal={direction === "horizontal"}+ class:dragging+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ ondblclick={onDoubleClick}+ role="separator"+ aria-orientation={direction === "vertical" ? "vertical" : "horizontal"}+ aria-valuenow={Math.round(ratio * 100)}+ aria-valuemin={5}+ aria-valuemax={95}+ tabindex="-1"+></div>++<style>+ .nb-split-handle {+ position: absolute;+ background: transparent;+ z-index: 5;+ transition: background 120ms ease;+ user-select: none;+ touch-action: none;+ }+ .nb-split-handle.vertical {+ width: 4px;+ height: 100%;+ top: 0;+ cursor: col-resize;+ transform: translateX(-2px);+ }+ .nb-split-handle.horizontal {+ height: 4px;+ width: 100%;+ left: 0;+ cursor: row-resize;+ transform: translateY(-2px);+ }+ .nb-split-handle:hover {+ background: color-mix(in oklab, var(--accent) 60%, transparent);+ }+ .nb-split-handle.dragging {+ background: var(--accent);+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbStatusBar.svelte b/src/lib/study-components/notes/shell/NbStatusBar.sveltenew file mode 100644index 00000000..7de28b06--- /dev/null+++ b/src/lib/study-components/notes/shell/NbStatusBar.svelte@@ -0,0 +1,134 @@+<script lang="ts">+ import { onMount, onDestroy } from "svelte";+ import { notesShell } from "$lib/study-notes/shell-store.svelte";+ import NbActiveNotebookBadge from "./NbActiveNotebookBadge.svelte";++ let now = $state(new Date());+ let timer: ReturnType<typeof setInterval> | null = null;++ onMount(() => {+ timer = setInterval(() => {+ now = new Date();+ }, 30_000);+ });++ onDestroy(() => {+ if (timer) clearInterval(timer);+ });++ const clockText = $derived(+ `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`,+ );++ const modeLabel = $derived(+ notesShell.mode === "edit"+ ? "edit"+ : notesShell.mode === "source"+ ? "source"+ : "preview",+ );++ const pageLabel = $derived(notesShell.currentPageTitle ?? notesShell.currentPageName ?? "—");++ const wordsLabel = $derived(`${notesShell.wordCount.toLocaleString("pt-BR")} palavras`);+ const charsLabel = $derived(`${notesShell.charCount.toLocaleString("pt-BR")} chars`);+</script>++<div class="nb-status-bar" role="status" aria-live="polite">+ <span class="seg counts">+ <span class="metric">{charsLabel}</span>+ <span class="dot">·</span>+ <span class="metric">{wordsLabel}</span>+ </span>+ <span class="seg">+ <span class="ic" aria-hidden="true">✏</span>+ <span class="value">{modeLabel}</span>+ </span>+ <span class="seg notebook">+ <NbActiveNotebookBadge />+ </span>+ <span class="seg page">+ <span class="ic" aria-hidden="true">📄</span>+ <span class="value">{pageLabel}</span>+ </span>+ <span class="seg saving" class:on={notesShell.saving}>+ <span class="dot-mark" aria-hidden="true"></span>+ <span class="value">{notesShell.saving ? "Salvando…" : "Salvo"}</span>+ </span>+ <span class="spacer"></span>+ <span class="seg clock">+ <span class="value">{clockText}</span>+ </span>+</div>++<style>+ .nb-status-bar {+ height: 100%;+ display: flex;+ align-items: center;+ gap: 16px;+ padding: 0 14px;+ font-size: 11px;+ font-family: var(--font-body, inherit);+ color: var(--tertiary, var(--muted-fg));+ background: color-mix(in oklab, var(--surface-bg, var(--primary)) 70%, transparent);+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ overflow: hidden;+ white-space: nowrap;+ }+ .seg {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ line-height: 1;+ }+ .seg.counts .metric {+ font-variant-numeric: tabular-nums;+ }+ .dot {+ opacity: 0.5;+ }+ .ic {+ font-size: 11px;+ line-height: 1;+ opacity: 0.7;+ }+ .value {+ color: var(--secondary, var(--text));+ }+ .seg.page .value {+ max-width: 240px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .seg.saving .dot-mark {+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: color-mix(in oklab, var(--success, #4caf50) 80%, transparent);+ transition: background 200ms ease;+ }+ .seg.saving.on .dot-mark {+ background: var(--accent);+ animation: nb-pulse 1.2s ease-in-out infinite;+ }+ .spacer {+ flex: 1;+ }+ .seg.clock .value {+ font-variant-numeric: tabular-nums;+ }+ @keyframes nb-pulse {+ 0%, 100% { opacity: 0.55; }+ 50% { opacity: 1; }+ }+ @media (max-width: 760px) {+ .seg.notebook,+ .seg.page,+ .seg.clock {+ display: none;+ }+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbTabContextMenu.svelte b/src/lib/study-components/notes/shell/NbTabContextMenu.sveltenew file mode 100644index 00000000..f864b028--- /dev/null+++ b/src/lib/study-components/notes/shell/NbTabContextMenu.svelte@@ -0,0 +1,116 @@+<script lang="ts">+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import type { TabSummary } from "$lib/notes-bridge";++ type Props = {+ tab: TabSummary;+ x: number;+ y: number;+ onClose: () => void;+ };++ let { tab, x, y, onClose }: Props = $props();++ async function close() {+ onClose();+ await tabsStore.closeTab(tab.id);+ }+ async function closeOthers() {+ onClose();+ await tabsStore.closeOtherTabsInWnd(tab.wnd_id, tab.id);+ }+ async function closeRight() {+ onClose();+ await tabsStore.closeTabsToRight(tab.wnd_id, tab.id);+ }+ async function togglePin() {+ onClose();+ await tabsStore.pinTab(tab.id, !tab.pinned);+ }+ async function moveNewSplitRight() {+ onClose();+ const newWnd = await tabsStore.splitWnd(tab.wnd_id, "vertical");+ await tabsStore.moveTabToWnd(tab.id, newWnd);+ }+ async function moveNewSplitDown() {+ onClose();+ const newWnd = await tabsStore.splitWnd(tab.wnd_id, "horizontal");+ await tabsStore.moveTabToWnd(tab.id, newWnd);+ }++ function onWindowMouseDown(e: MouseEvent) {+ const target = e.target as HTMLElement | null;+ if (target?.closest('[data-nb-context-menu="true"]')) return;+ onClose();+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") onClose();+ }+</script>++<svelte:window onmousedown={onWindowMouseDown} onkeydown={onKey} />++<div+ class="nb-tab-context-menu"+ data-nb-context-menu="true"+ style="left: {x}px; top: {y}px;"+ role="menu"+>+ <button class="item" role="menuitem" onclick={close}>+ Fechar+ <span class="shortcut">Ctrl+W</span>+ </button>+ <button class="item" role="menuitem" onclick={closeOthers}>Fechar outras</button>+ <button class="item" role="menuitem" onclick={closeRight}>Fechar à direita</button>+ <div class="sep"></div>+ <button class="item" role="menuitem" onclick={togglePin}>+ {tab.pinned ? "Desafixar" : "Fixar"}+ </button>+ <div class="sep"></div>+ <button class="item" role="menuitem" onclick={moveNewSplitRight}>Mover pra novo split à direita</button>+ <button class="item" role="menuitem" onclick={moveNewSplitDown}>Mover pra novo split abaixo</button>+</div>++<style>+ .nb-tab-context-menu {+ position: fixed;+ z-index: 200;+ min-width: 220px;+ background: var(--secondary-bg, var(--page-bg));+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 6px;+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.32);+ padding: 4px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ background: transparent;+ border: 0;+ color: var(--text);+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ border-radius: 4px;+ transition: background 80ms ease;+ }+ .item:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+ .shortcut {+ margin-left: auto;+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: var(--tertiary, var(--muted-fg));+ }+ .sep {+ height: 1px;+ margin: 4px 0;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbTabStrip.svelte b/src/lib/study-components/notes/shell/NbTabStrip.sveltenew file mode 100644index 00000000..1cb99e99--- /dev/null+++ b/src/lib/study-components/notes/shell/NbTabStrip.svelte@@ -0,0 +1,484 @@+<script lang="ts">+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import {+ notesPagesList,+ notesPagesEnsure,+ type PageSummary,+ type TabSummary,+ type TabViewKind,+ } from "$lib/notes-bridge";+ import NbNewSplitMenu from "./NbNewSplitMenu.svelte";+ import NbTabContextMenu from "./NbTabContextMenu.svelte";++ type Props = { wndId: number };+ let { wndId }: Props = $props();++ const tabs = $derived(tabsStore.sortedTabsForWnd(wndId));+ const activeTabId = $derived(tabsStore.activeTabIdByWnd[wndId] ?? null);+ const isActiveWnd = $derived(tabsStore.activeWndId === wndId);++ let pickerOpen = $state(false);+ let pickerQuery = $state("");+ let pickerPages = $state<PageSummary[]>([]);+ let pickerLoading = $state(false);+ let pickerInputEl = $state<HTMLInputElement | null>(null);++ let context = $state<{ tab: TabSummary; x: number; y: number } | null>(null);++ let dragTabId = $state<number | null>(null);+ let dragOverTabId = $state<number | null>(null);++ async function openPicker() {+ pickerOpen = true;+ pickerQuery = "";+ pickerLoading = true;+ try {+ pickerPages = await notesPagesList();+ } finally {+ pickerLoading = false;+ }+ queueMicrotask(() => pickerInputEl?.focus());+ }++ function closePicker() {+ pickerOpen = false;+ pickerQuery = "";+ }++ const filteredPages = $derived.by(() => {+ const q = pickerQuery.trim().toLowerCase();+ if (!q) return pickerPages.slice(0, 30);+ return pickerPages+ .filter(+ (p) =>+ p.name.toLowerCase().includes(q) ||+ (p.title && p.title.toLowerCase().includes(q)),+ )+ .slice(0, 30);+ });++ async function pickPage(page: PageSummary) {+ closePicker();+ await tabsStore.openTab({+ wndId,+ pageId: page.id,+ viewKind: "editor",+ activate: true,+ });+ }++ async function createNewPage() {+ const name = pickerQuery.trim();+ if (!name) return;+ closePicker();+ const res = await notesPagesEnsure({ name });+ await tabsStore.openTab({+ wndId,+ pageId: res.id,+ viewKind: "editor",+ activate: true,+ });+ }++ function onPickerKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ closePicker();+ } else if (e.key === "Enter") {+ e.preventDefault();+ if (filteredPages.length > 0) {+ void pickPage(filteredPages[0]);+ } else if (pickerQuery.trim()) {+ void createNewPage();+ }+ }+ }++ function activate(tab: TabSummary) {+ tabsStore.setActiveWnd(wndId);+ tabsStore.setActiveTab(wndId, tab.id);+ }++ async function closeTab(e: MouseEvent, tabId: number) {+ e.stopPropagation();+ await tabsStore.closeTab(tabId);+ }++ function showContext(e: MouseEvent, tab: TabSummary) {+ e.preventDefault();+ e.stopPropagation();+ context = { tab, x: e.clientX, y: e.clientY };+ }++ function viewKindIconPath(kind: TabViewKind): string {+ switch (kind) {+ case "graph":+ return "M9 5a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z M19 19a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z M5 19a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z M9 5l8 11 M5 16l4 -11";+ case "search":+ return "M11 4a7 7 0 1 1 0 14 7 7 0 0 1 0-14Z M16 16l5 5";+ case "journal":+ return "M3 4h12a3 3 0 0 1 3 3v14H6a3 3 0 0 1-3-3Z M9 4v18 M14 9h2 M14 13h2";+ case "templates":+ return "M3 3h7v7H3z M14 3h7v4H14z M14 11h7v10H14z M3 14h7v7H3z";+ case "settings":+ return "M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.5-2.4.9a7 7 0 0 0-2-1.2l-.4-2.5h-4l-.4 2.5a7 7 0 0 0-2 1.2l-2.4-.9-2 3.5 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.5 2.4-.9c.6.5 1.3.9 2 1.2l.4 2.5h4l.4-2.5a7 7 0 0 0 2-1.2l2.4.9 2-3.5-2-1.5c.1-.4.1-.8.1-1.2Z";+ default:+ return "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8";+ }+ }++ function tabLabel(tab: TabSummary): string {+ if (tab.view_kind === "editor") {+ return tab.page_title || tab.page_name || "Sem nome";+ }+ switch (tab.view_kind) {+ case "graph": return "Graph";+ case "search": return "Buscar";+ case "journal": return "Journal";+ case "templates": return "Templates";+ case "settings": return "Settings";+ }+ }++ function onDragStart(e: DragEvent, tabId: number) {+ if (!e.dataTransfer) return;+ dragTabId = tabId;+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData("text/plain", String(tabId));+ }++ function onDragOver(e: DragEvent, overId: number) {+ if (dragTabId == null) return;+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = "move";+ dragOverTabId = overId;+ }++ function onDragLeave() {+ dragOverTabId = null;+ }++ async function onDrop(e: DragEvent, dropOnId: number) {+ e.preventDefault();+ const draggedId = dragTabId;+ dragTabId = null;+ dragOverTabId = null;+ if (draggedId == null || draggedId === dropOnId) return;+ const ordered = tabs.map((t) => t.id);+ const fromIdx = ordered.indexOf(draggedId);+ const toIdx = ordered.indexOf(dropOnId);+ if (fromIdx === -1 || toIdx === -1) return;+ ordered.splice(fromIdx, 1);+ ordered.splice(toIdx, 0, draggedId);+ await tabsStore.reorderTabs(wndId, ordered);+ }++ function onDragEnd() {+ dragTabId = null;+ dragOverTabId = null;+ }+</script>++<div+ class="nb-tab-strip"+ class:active-wnd={isActiveWnd}+ role="tablist"+ data-wnd-id={wndId}+>+ {#each tabs as tab (tab.id)}+ {@const isActive = tab.id === activeTabId}+ <div+ class="tab"+ class:active={isActive}+ class:pinned={tab.pinned}+ class:drag-over={dragOverTabId === tab.id}+ role="tab"+ tabindex={isActive ? 0 : -1}+ aria-selected={isActive}+ draggable={!tab.pinned}+ onclick={() => activate(tab)}+ onkeydown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ activate(tab);+ }+ }}+ oncontextmenu={(e) => showContext(e, tab)}+ ondragstart={(e) => onDragStart(e, tab.id)}+ ondragover={(e) => onDragOver(e, tab.id)}+ ondragleave={onDragLeave}+ ondrop={(e) => onDrop(e, tab.id)}+ ondragend={onDragEnd}+ title={tab.page_name ?? tab.view_kind}+ >+ <svg+ viewBox="0 0 24 24"+ width="13"+ height="13"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d={viewKindIconPath(tab.view_kind)} />+ </svg>+ <span class="label">{tabLabel(tab)}</span>+ {#if tab.pinned}+ <span class="pin-dot" aria-label="Tab fixada">●</span>+ {:else}+ <button+ type="button"+ class="close"+ aria-label="Fechar tab"+ onclick={(e) => closeTab(e, tab.id)}+ >+ ×+ </button>+ {/if}+ </div>+ {/each}++ <button+ class="add"+ type="button"+ onclick={openPicker}+ aria-label="Nova tab"+ title="Nova tab (Ctrl+T)"+ >+ ++ </button>++ <NbNewSplitMenu {wndId} />++ <div class="filler"></div>+</div>++{#if pickerOpen}+ <div+ class="picker-backdrop"+ onmousedown={(e) => {+ if (e.target === e.currentTarget) closePicker();+ }}+ role="presentation"+ >+ <div class="picker" role="dialog" aria-label="Abrir página em nova tab">+ <input+ bind:this={pickerInputEl}+ bind:value={pickerQuery}+ onkeydown={onPickerKey}+ type="text"+ placeholder="Buscar ou criar página…"+ class="picker-input"+ />+ <div class="picker-list">+ {#if pickerLoading}+ <div class="picker-empty">Carregando…</div>+ {:else if filteredPages.length === 0}+ <button+ class="picker-item create"+ type="button"+ onclick={createNewPage}+ disabled={!pickerQuery.trim()}+ >+ <span class="prefix">+ Criar:</span>+ <span class="value">{pickerQuery || "(digite um nome)"}</span>+ </button>+ {:else}+ {#each filteredPages as p (p.id)}+ <button+ class="picker-item"+ type="button"+ onclick={() => pickPage(p)}+ >+ <span class="value">{p.title || p.name}</span>+ <span class="hint">{p.name}</span>+ </button>+ {/each}+ {#if pickerQuery.trim() && !filteredPages.some((p) => p.name === pickerQuery.trim() || p.title === pickerQuery.trim())}+ <button+ class="picker-item create"+ type="button"+ onclick={createNewPage}+ >+ <span class="prefix">+ Criar:</span>+ <span class="value">{pickerQuery}</span>+ </button>+ {/if}+ {/if}+ </div>+ </div>+ </div>+{/if}++{#if context}+ <NbTabContextMenu+ tab={context.tab}+ x={context.x}+ y={context.y}+ onClose={() => (context = null)}+ />+{/if}++<style>+ .nb-tab-strip {+ height: 100%;+ display: flex;+ align-items: stretch;+ gap: 0;+ padding: 0 4px 0 8px;+ overflow-x: auto;+ overflow-y: hidden;+ user-select: none;+ background: color-mix(in oklab, var(--primary, var(--page-bg)) 70%, transparent);+ scrollbar-width: thin;+ }+ .nb-tab-strip.active-wnd {+ background: color-mix(in oklab, var(--accent) 4%, var(--primary, var(--page-bg)));+ }+ .tab {+ position: relative;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 0 6px 0 10px;+ height: 100%;+ border-right: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ font-size: 12px;+ color: var(--secondary, var(--text));+ cursor: pointer;+ max-width: 220px;+ min-width: 80px;+ transition: background 100ms ease, color 100ms ease;+ }+ .tab:hover {+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .tab.active {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--text);+ box-shadow: inset 0 -2px 0 0 var(--accent);+ }+ .tab.pinned {+ background: color-mix(in oklab, var(--accent) 4%, transparent);+ }+ .tab.drag-over {+ background: color-mix(in oklab, var(--accent) 18%, transparent);+ }+ .label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex: 1;+ }+ .close,+ .add {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: 0;+ color: var(--tertiary, var(--muted-fg));+ cursor: pointer;+ transition: color 120ms ease, background 120ms ease;+ }+ .close {+ width: 16px;+ height: 16px;+ border-radius: 3px;+ font-size: 14px;+ line-height: 1;+ margin-left: 4px;+ }+ .close:hover {+ background: color-mix(in oklab, var(--accent) 20%, transparent);+ color: var(--text);+ }+ .add {+ width: 28px;+ height: 100%;+ font-size: 16px;+ }+ .add:hover {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .pin-dot {+ color: var(--accent);+ font-size: 10px;+ margin-left: 4px;+ }+ .filler {+ flex: 1;+ }+ .picker-backdrop {+ position: fixed;+ inset: 0;+ z-index: 150;+ background: rgba(0, 0, 0, 0.45);+ display: flex;+ align-items: flex-start;+ justify-content: center;+ padding-top: 14vh;+ }+ .picker {+ width: min(520px, 92vw);+ max-height: 60vh;+ background: var(--secondary-bg, var(--page-bg));+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 8px;+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.4);+ display: flex;+ flex-direction: column;+ }+ .picker-input {+ background: transparent;+ border: 0;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ padding: 12px 16px;+ color: var(--text);+ font-size: 14px;+ outline: none;+ }+ .picker-list {+ overflow-y: auto;+ padding: 4px;+ }+ .picker-item {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 12px;+ background: transparent;+ border: 0;+ color: var(--text);+ font-size: 13px;+ text-align: left;+ cursor: pointer;+ border-radius: 4px;+ }+ .picker-item:hover {+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+ .picker-item .hint {+ margin-left: auto;+ color: var(--tertiary, var(--muted-fg));+ font-size: 11px;+ font-family: ui-monospace, monospace;+ }+ .picker-item.create .prefix {+ color: var(--accent);+ font-weight: 600;+ }+ .picker-item:disabled {+ cursor: not-allowed;+ opacity: 0.5;+ }+ .picker-empty {+ padding: 12px 16px;+ color: var(--tertiary, var(--muted-fg));+ font-size: 12px;+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbWndTree.svelte b/src/lib/study-components/notes/shell/NbWndTree.sveltenew file mode 100644index 00000000..1b824e07--- /dev/null+++ b/src/lib/study-components/notes/shell/NbWndTree.svelte@@ -0,0 +1,111 @@+<script lang="ts">+ import type { WndNode } from "$lib/notes-bridge";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import NbTabStrip from "./NbTabStrip.svelte";+ import NbSplitHandle from "./NbSplitHandle.svelte";+ import NbWorkspace from "./NbWorkspace.svelte";+ import Self from "./NbWndTree.svelte";+ import { type Snippet } from "svelte";++ type Props = {+ node: WndNode;+ activeContent?: Snippet<[]>;+ };++ let { node, activeContent }: Props = $props();++ const activeWndId = $derived(tabsStore.activeWndId);+</script>++{#if node.split_dir === null || node.split_dir === undefined}+ <div+ class="nb-wnd-leaf"+ class:active={activeWndId === node.id}+ role="region"+ onpointerdown={() => tabsStore.setActiveWnd(node.id)}+ >+ <div class="leaf-tabs">+ <NbTabStrip wndId={node.id} />+ </div>+ <div class="leaf-body">+ <NbWorkspace wndId={node.id} {activeContent} />+ </div>+ </div>+{:else if node.children.length === 2}+ {@const dir = node.split_dir}+ {@const r = Math.max(0.05, Math.min(0.95, node.ratio))}+ {@const r1 = Math.round(r * 1000) / 10}+ {@const r2 = Math.round((1 - r) * 1000) / 10}+ <div class="nb-wnd-split" class:vertical={dir === "vertical"} class:horizontal={dir === "horizontal"}>+ <div+ class="split-pane"+ style:flex-basis="{r1}%"+ >+ <Self node={node.children[0]} {activeContent} />+ </div>+ <NbSplitHandle wndId={node.id} direction={dir} ratio={node.ratio} />+ <div+ class="split-pane"+ style:flex-basis="{r2}%"+ >+ <Self node={node.children[1]} {activeContent} />+ </div>+ </div>+{:else}+ <div class="nb-wnd-empty">Layout inválido</div>+{/if}++<style>+ .nb-wnd-leaf {+ display: flex;+ flex-direction: column;+ height: 100%;+ width: 100%;+ overflow: hidden;+ border: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ border-radius: 4px;+ background: var(--primary, var(--page-bg));+ transition: border-color 120ms ease;+ }+ .nb-wnd-leaf.active {+ border-color: color-mix(in oklab, var(--accent) 70%, var(--content-border));+ }+ .leaf-tabs {+ height: 32px;+ flex-shrink: 0;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 30%, transparent);+ overflow: hidden;+ }+ .leaf-body {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ }+ .nb-wnd-split {+ position: relative;+ display: flex;+ width: 100%;+ height: 100%;+ }+ .nb-wnd-split.vertical {+ flex-direction: row;+ }+ .nb-wnd-split.horizontal {+ flex-direction: column;+ }+ .split-pane {+ flex-grow: 1;+ flex-shrink: 1;+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ padding: 2px;+ }+ .nb-wnd-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ height: 100%;+ color: var(--tertiary, var(--muted-fg));+ }+</style>diff --git a/src/lib/study-components/notes/shell/NbWorkspace.svelte b/src/lib/study-components/notes/shell/NbWorkspace.sveltenew file mode 100644index 00000000..69a3eb38--- /dev/null+++ b/src/lib/study-components/notes/shell/NbWorkspace.svelte@@ -0,0 +1,87 @@+<script lang="ts">+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";+ import { type Snippet } from "svelte";++ type Props = {+ wndId: number;+ activeContent?: Snippet<[]>;+ };++ let { wndId, activeContent }: Props = $props();++ const isActiveWnd = $derived(tabsStore.activeWndId === wndId);+ const tabs = $derived(tabsStore.sortedTabsForWnd(wndId));+ const activeTabId = $derived(tabsStore.activeTabIdByWnd[wndId] ?? null);+ const activeTab = $derived(tabs.find((t) => t.id === activeTabId) ?? null);++ function focusThisWnd() {+ tabsStore.setActiveWnd(wndId);+ }+</script>++<div class="nb-workspace" class:active={isActiveWnd}>+ {#if isActiveWnd && activeContent}+ {@render activeContent()}+ {:else if activeTab}+ <div class="placeholder">+ <div class="ph-title">{activeTab.page_title || activeTab.page_name || activeTab.view_kind}</div>+ <div class="ph-hint">+ {#if activeTab.view_kind === "editor"}+ Conteúdo da page é renderizado no leaf ativo. Clique aqui para focar.+ {:else}+ Esta visualização é renderizada no leaf ativo.+ {/if}+ </div>+ <button class="focus-btn" type="button" onclick={focusThisWnd}>+ Focar este split+ </button>+ </div>+ {:else}+ <div class="placeholder">+ <div class="ph-title">Sem tabs abertas</div>+ <div class="ph-hint">Use o botão + acima ou Ctrl+T para abrir uma página.</div>+ </div>+ {/if}+</div>++<style>+ .nb-workspace {+ height: 100%;+ overflow: hidden;+ display: flex;+ flex-direction: column;+ }+ .placeholder {+ margin: auto;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 12px;+ padding: 32px;+ text-align: center;+ }+ .ph-title {+ font-size: 16px;+ font-weight: 600;+ color: var(--text);+ }+ .ph-hint {+ font-size: 12px;+ color: var(--tertiary, var(--muted-fg));+ max-width: 320px;+ line-height: 1.5;+ }+ .focus-btn {+ padding: 6px 14px;+ background: color-mix(in oklab, var(--accent) 15%, transparent);+ border: 1px solid color-mix(in oklab, var(--accent) 40%, transparent);+ border-radius: 4px;+ color: var(--accent);+ font-size: 12px;+ cursor: pointer;+ transition: background 120ms ease;+ }+ .focus-btn:hover {+ background: color-mix(in oklab, var(--accent) 25%, transparent);+ }+</style>diff --git a/src/lib/study-components/notes/slash-commands.ts b/src/lib/study-components/notes/slash-commands.tsindex 3753d388..409150fe 100644--- a/src/lib/study-components/notes/slash-commands.ts+++ b/src/lib/study-components/notes/slash-commands.ts@@ -4,6 +4,7 @@ export type SlashCommandGroup =| "estrutura"| "blocos"| "callout"+ | "renderers"| "refs"| "datas"| "utilidades";@@ -22,6 +23,7 @@ const GROUP_ORDER: SlashCommandGroup[] = ["estrutura","blocos","callout",+ "renderers","refs","datas","utilidades",@@ -31,6 +33,7 @@ const GROUP_LABEL: Record<SlashCommandGroup, string> = {estrutura: "Estrutura",blocos: "Blocos",callout: "Callouts",+ renderers: "Renderers",refs: "Refs",datas: "Datas",utilidades: "Utilidades",@@ -329,6 +332,105 @@ export const SLASH_COMMANDS: SlashCommand[] = [run: (editor, range) =>editor.chain().focus().deleteRange(range).setCallout("caution").run(),},+ {+ id: "mermaid",+ label: "Diagrama (mermaid)",+ hint: "Flowcharts, sequência, gantt — sintaxe mermaid",+ aliases: ["mermaid", "diagram", "diagrama", "flow", "fluxo"],+ indicator: "▦",+ group: "renderers",+ run: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent({+ type: "mermaid",+ attrs: { source: "graph LR;\n A-->B" },+ })+ .run(),+ },+ {+ id: "flowchart",+ label: "Fluxograma (flowchart.js)",+ hint: "Sintaxe flowchart.js: símbolos start/end/operation/condition",+ aliases: ["flowchart", "fluxograma", "fluxo", "fc"],+ indicator: "⇄",+ group: "renderers",+ run: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent({+ type: "flowchart",+ attrs: {+ source:+ "st=>start: Start\nop=>operation: Step\ne=>end: End\nst->op->e",+ },+ })+ .run(),+ },+ {+ id: "mindmap",+ label: "Mapa mental (markmap)",+ hint: "Markdown indentado: # raiz, ## ramo, ### folha",+ aliases: ["mindmap", "markmap", "mapa", "mental", "brain"],+ indicator: "⌘",+ group: "renderers",+ run: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent({+ type: "mindmap",+ attrs: {+ source: "# Root\n## Branch A\n### Leaf 1\n### Leaf 2\n## Branch B",+ },+ })+ .run(),+ },+ {+ id: "abc",+ label: "Partitura (notação ABC)",+ hint: "Notação musical ABC — escala, melodia, harmonia",+ aliases: ["abc", "musica", "music", "score", "partitura", "notation"],+ indicator: "♪",+ group: "renderers",+ run: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent({+ type: "abc",+ attrs: {+ source: "X:1\nT:Scale\nM:4/4\nL:1/4\nK:C\nC D E F | G A B c |",+ },+ })+ .run(),+ },+ {+ id: "plantuml",+ label: "Diagrama UML (PlantUML)",+ hint: "Sequência, classe, casos de uso — sintaxe PlantUML",+ aliases: ["plantuml", "puml", "uml", "diagrama", "sequence", "class"],+ indicator: "⚙",+ group: "renderers",+ run: (editor, range) =>+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent({+ type: "plantuml",+ attrs: {+ source: "@startuml\nAlice -> Bob: hello\nBob --> Alice: hi\n@enduml",+ },+ })+ .run(),+ },{id: "link",label: "Link",diff --git a/src/lib/study-components/shelves/CourseCard.svelte b/src/lib/study-components/shelves/CourseCard.svelteindex b40945fc..64989d0c 100644--- a/src/lib/study-components/shelves/CourseCard.svelte+++ b/src/lib/study-components/shelves/CourseCard.svelte@@ -1,5 +1,6 @@<script lang="ts">import { convertFileSrc } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";import NotificationBadge from "./NotificationBadge.svelte";type Props = {@@ -26,6 +27,78 @@tags = [],}: Props = $props();+ type SpriteInfo = {+ sprite_url: string;+ cols: number;+ rows: number;+ total_frames: number;+ };+ let sprite = $state<SpriteInfo | null>(null);+ let spriteLoading = false;+ let spriteFailed = false;+ let scrubFrame = $state(0);+ let scrubbing = $state(false);++ async function ensureSprite() {+ if (sprite || spriteLoading || spriteFailed) return;+ spriteLoading = true;+ try {+ const res = await pluginInvoke<{+ sprite_path: string;+ cols: number;+ rows: number;+ total_frames: number;+ }>("study", "study:courses:generate_sprite", { courseId });+ let url = res.sprite_path;+ try {+ url = convertFileSrc(res.sprite_path);+ } catch {+ // keep raw path+ }+ sprite = {+ sprite_url: url,+ cols: res.cols,+ rows: res.rows,+ total_frames: res.total_frames,+ };+ } catch (e) {+ spriteFailed = true;+ if (import.meta.env.DEV) {+ console.warn(`[CourseCard] sprite gen failed for ${courseId}:`, e);+ }+ } finally {+ spriteLoading = false;+ }+ }++ function onPointerEnter() {+ void ensureSprite();+ }+ function onPointerMove(e: PointerEvent) {+ if (!sprite) return;+ const target = e.currentTarget as HTMLElement | null;+ if (!target) return;+ const rect = target.getBoundingClientRect();+ if (rect.width <= 0) return;+ const x = Math.min(rect.width, Math.max(0, e.clientX - rect.left));+ const ratio = x / rect.width;+ scrubFrame = Math.min(+ sprite.total_frames - 1,+ Math.floor(ratio * sprite.total_frames),+ );+ scrubbing = true;+ }+ function onPointerLeave() {+ scrubbing = false;+ }++ const scrubStyle = $derived.by(() => {+ if (!sprite || !scrubbing) return "";+ const col = scrubFrame % sprite.cols;+ const row = Math.floor(scrubFrame / sprite.cols);+ return `background-image: url('${sprite.sprite_url}'); background-position: ${-col * 100}% ${-row * 100}%; background-size: ${sprite.cols * 100}% ${sprite.rows * 100}%;`;+ });+const visibleTags = $derived(tags.slice(0, 2));const extraTags = $derived(Math.max(0, tags.length - 2));@@ -34,7 +107,13 @@if (!thumbnail) return null;try {return convertFileSrc(thumbnail);- } catch {+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn(+ `[CourseCard] convertFileSrc failed for course ${courseId}: ${thumbnail}`,+ e,+ );+ }return thumbnail;}});@@ -47,11 +126,18 @@});</script>-<a class="card" href={link} aria-label="Abrir {title}">- <div class="thumb">- {#if thumbSrc}+<a+ class="card"+ href={link}+ aria-label="Abrir {title}"+ onpointerenter={onPointerEnter}+ onpointermove={onPointerMove}+ onpointerleave={onPointerLeave}+>+ <div class="thumb" style={scrubStyle}>+ {#if thumbSrc && !scrubbing}<img src={thumbSrc} alt="" loading="lazy" />- {:else}+ {:else if !thumbSrc && !scrubbing}<div class="thumb-fallback" aria-hidden="true"><svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="18" height="12" rx="2" />diff --git a/src/lib/study-components/shelves/LibraryHomeShelves.svelte b/src/lib/study-components/shelves/LibraryHomeShelves.svelteindex 8ca84125..3ca217ad 100644--- a/src/lib/study-components/shelves/LibraryHomeShelves.svelte+++ b/src/lib/study-components/shelves/LibraryHomeShelves.svelte@@ -9,6 +9,8 @@type RecentlyAddedCourse,type NotificationFull,} from "$lib/study-bridge";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";import CourseCard from "./CourseCard.svelte";import Shelf from "./Shelf.svelte";@@ -101,6 +103,73 @@withNewsItems = [...grouped.values()].slice(0, 8);}newsLoading = false;++ void extractMissingThumbnails();+ }++ const tried = new Set<number>();+ async function extractMissingThumbnails() {+ const missing: number[] = [];+ for (const it of cwItems) {+ if (!it.course_thumbnail && !tried.has(it.course_id)) missing.push(it.course_id);+ }+ for (const it of recentItems) {+ if (!it.thumbnail_path && !tried.has(it.id)) missing.push(it.id);+ }+ for (const g of platformGroups) {+ for (const it of g.items) {+ if (!it.thumbnail_path && !tried.has(it.id)) missing.push(it.id);+ }+ }+ for (const g of subjectGroups) {+ for (const it of g.items) {+ if (!it.thumbnail_path && !tried.has(it.id)) missing.push(it.id);+ }+ }+ for (const it of withNewsItems) {+ if (!it.thumbnail && !tried.has(it.course_id)) missing.push(it.course_id);+ }++ const unique = [...new Set(missing)];+ for (const courseId of unique) {+ tried.add(courseId);+ try {+ const res = await pluginInvoke<{ course_id: number; thumbnail_path: string }>(+ "study",+ "study:courses:extract_thumbnail",+ { courseId },+ );+ applyThumbnail(res.course_id, res.thumbnail_path);+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn(`[shelves] thumbnail extract failed for course ${courseId}:`, e);+ }+ }+ }+ }++ function applyThumbnail(courseId: number, path: string) {+ cwItems = cwItems.map((it) =>+ it.course_id === courseId ? { ...it, course_thumbnail: path } : it,+ );+ recentItems = recentItems.map((it) =>+ it.id === courseId ? { ...it, thumbnail_path: path } : it,+ );+ platformGroups = platformGroups.map((g) => ({+ ...g,+ items: g.items.map((it) =>+ it.id === courseId ? { ...it, thumbnail_path: path } : it,+ ),+ }));+ subjectGroups = subjectGroups.map((g) => ({+ ...g,+ items: g.items.map((it) =>+ it.id === courseId ? { ...it, thumbnail_path: path } : it,+ ),+ }));+ withNewsItems = withNewsItems.map((it) =>+ it.course_id === courseId ? { ...it, thumbnail: path } : it,+ );}$effect(() => {@@ -148,7 +217,7 @@</script>{#if error && cwItems.length === 0 && !cwLoading}- <p class="error" role="alert">Falha ao carregar biblioteca: {error}</p>+ <p class="error" role="alert">{$t("study.library.home_load_error", { error })}</p>{/if}{#if allEmpty}@@ -157,20 +226,20 @@<rect x="10" y="14" width="44" height="36" rx="4" /><path d="M22 26h20M22 32h20M22 38h12" /></svg>- <h3>Sua biblioteca está vazia</h3>- <p>Adicione uma pasta com cursos para começar.</p>- <a href="/study/library?mode=browse" class="cta">Adicionar pasta com cursos</a>+ <h3>{$t("study.library.home_empty_title")}</h3>+ <p>{$t("study.library.home_empty_desc")}</p>+ <a href="/study/library?mode=browse" class="cta">{$t("study.library.home_empty_cta")}</a></div>{:else}<div class="shelves"><Shelf- title="Continue de onde parou"- eyebrow="Recente"+ title={$t("study.library.home_continue_title") as string}+ eyebrow={$t("study.library.home_continue_eyebrow") as string}isLoading={cwLoading}isEmpty={cwEmpty}>{#snippet empty()}- <div class="hint">Nenhum curso em progresso ainda. Comece uma aula para aparecer aqui.</div>+ <div class="hint">{$t("study.library.home_continue_empty")}</div>{/snippet}{#each cwItems as item (item.course_id)}{@const href =@@ -178,9 +247,9 @@? `/study/course/${item.course_id}/lesson/${item.last_lesson_id}`: `/study/course/${item.course_id}`}{@const eyebrowText = item.next_lesson_title- ? `Próxima: ${item.next_lesson_title}`+ ? ($t("study.library.home_continue_next", { title: item.next_lesson_title }) as string): item.last_lesson_title- ? `Em: ${item.last_lesson_title}`+ ? ($t("study.library.home_continue_current", { title: item.last_lesson_title }) as string): item.course_title}<CourseCardcourseId={item.course_id}@@ -195,21 +264,34 @@</Shelf>{#if withNewsItems.length > 0}- <Shelf title="Com novidades" eyebrow="Aulas novas" isLoading={newsLoading}>+ <Shelf+ title={$t("study.library.home_news_title") as string}+ eyebrow={$t("study.library.home_news_eyebrow") as string}+ isLoading={newsLoading}+ >{#each withNewsItems as item (item.course_id)}<CourseCardcourseId={item.course_id}title={item.course_title}thumbnail={item.thumbnail}notificationCount={item.count}- eyebrow={`${item.count} ${item.count === 1 ? "aula nova" : "aulas novas"}`}+ eyebrow={$t(+ item.count === 1+ ? "study.library.home_news_count_one"+ : "study.library.home_news_count_other",+ { count: item.count },+ ) as string}/>{/each}</Shelf>{/if}{#if recentItems.length > 0}- <Shelf title="Recém-adicionados" eyebrow="Novos" isLoading={recentLoading}>+ <Shelf+ title={$t("study.library.home_recently_title") as string}+ eyebrow={$t("study.library.home_recently_eyebrow") as string}+ isLoading={recentLoading}+ >{#each recentItems as item (item.id)}<CourseCardcourseId={item.id}@@ -225,9 +307,13 @@{#if showPlatform}{#each platformGroups as group (group.key)}+ {@const platformLabel =+ group.key.toLowerCase() === "generic"+ ? ($t("study.library.platform_generic") as string)+ : prettyPlatform(group.label)}<Shelf- title={prettyPlatform(group.label)}- eyebrow="Plataforma"+ title={platformLabel}+ eyebrow={$t("study.library.home_platform_eyebrow") as string}isLoading={platformLoading}isEmpty={group.items.length === 0}seeMoreHref={`/study/library?mode=courses&platform=${encodeURIComponent(group.key)}`}@@ -237,7 +323,7 @@courseId={course.id}title={course.title}thumbnail={course.thumbnail_path}- eyebrow={prettyPlatform(group.label)}+ eyebrow={platformLabel}/>{/each}</Shelf>@@ -248,7 +334,7 @@{#each subjectGroups as group (group.key)}<Shelftitle={group.label}- eyebrow="Matéria"+ eyebrow={$t("study.library.home_subject_eyebrow") as string}isLoading={subjectLoading}isEmpty={group.items.length === 0}seeMoreHref={`/study/library?mode=courses&subject=${group.subject_id ?? group.key}`}@@ -279,7 +365,6 @@greatcourses: "The Great Courses",thinkific: "Thinkific",rocketseat: "Rocketseat",- generic: "Outras plataformas",};function prettyPlatform(key: string): string {diff --git a/src/lib/study-feature-flags.ts b/src/lib/study-feature-flags.tsindex ba67ccac..df064a96 100644--- a/src/lib/study-feature-flags.ts+++ b/src/lib/study-feature-flags.ts@@ -1,2 +1,2 @@-export const STUDY_NOTES_ENABLED = false;+export const STUDY_NOTES_ENABLED = true;export const STUDY_ANKI_ENABLED = false;diff --git a/src/lib/study-music-components/AboutLink.svelte b/src/lib/study-music-components/AboutLink.sveltenew file mode 100644index 00000000..78afb0f1--- /dev/null+++ b/src/lib/study-music-components/AboutLink.svelte@@ -0,0 +1,137 @@+<script lang="ts">+ import { t } from "$lib/i18n";++ type Props = {+ variant?: "footer" | "inline" | "card";+ text?: string;+ };++ let { variant = "inline", text }: Props = $props();++ const url = "https://github.com/tonhowtf/omniget";++ async function open() {+ try {+ const { openUrl } = await import("@tauri-apps/plugin-opener");+ await openUrl(url);+ } catch {+ try {+ window.open(url, "_blank");+ } catch {+ /* ignore */+ }+ }+ }++ const label = $derived(text ?? ($t("study.about.short_pitch") as string));+</script>++{#if variant === "card"}+ <button type="button" class="about-card" onclick={open}>+ <span class="about-eyebrow">{$t("study.about.eyebrow")}</span>+ <span class="about-headline">{$t("study.about.long_pitch")}</span>+ <span class="about-cta">+ {$t("study.about.cta_github")}+ <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="7" y1="17" x2="17" y2="7"/>+ <polyline points="7 7 17 7 17 17"/>+ </svg>+ </span>+ </button>+{:else if variant === "footer"}+ <button type="button" class="about-footer" onclick={open} title={url}>+ <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor" aria-hidden="true">+ <path d="M12 2C6.48 2 2 6.58 2 12.25c0 4.51 2.87 8.34 6.84 9.69.5.1.68-.22.68-.49 0-.24-.01-.88-.01-1.73-2.78.62-3.37-1.36-3.37-1.36-.45-1.18-1.11-1.49-1.11-1.49-.91-.64.07-.62.07-.62 1 .07 1.53 1.05 1.53 1.05.89 1.56 2.34 1.11 2.91.85.09-.66.35-1.11.63-1.37-2.22-.26-4.55-1.14-4.55-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.31.1-2.72 0 0 .84-.27 2.75 1.05A9.4 9.4 0 0 1 12 7.07c.85.01 1.71.12 2.51.34 1.91-1.32 2.75-1.05 2.75-1.05.55 1.41.2 2.46.1 2.72.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9 0 1.37-.01 2.48-.01 2.81 0 .27.18.6.69.49A10.04 10.04 0 0 0 22 12.25C22 6.58 17.52 2 12 2z"/>+ </svg>+ <span>{label}</span>+ </button>+{:else}+ <button type="button" class="about-inline" onclick={open}>+ <span>{label}</span>+ <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <line x1="7" y1="17" x2="17" y2="7"/>+ <polyline points="7 7 17 7 17 17"/>+ </svg>+ </button>+{/if}++<style>+ .about-card {+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: 100%;+ padding: 18px 20px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 12px;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ transition: border-color 120ms ease, background 120ms ease;+ }+ .about-card:hover {+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 6%, rgba(255, 255, 255, 0.03));+ }+ .about-eyebrow {+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--accent);+ }+ .about-headline {+ font-size: 14px;+ font-weight: 600;+ line-height: 1.5;+ color: rgba(255, 255, 255, 0.9);+ }+ .about-cta {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ font-weight: 600;+ color: var(--accent);+ }+ .about-footer {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 8px 14px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.45);+ font-family: inherit;+ font-size: 11px;+ font-weight: 500;+ text-align: left;+ cursor: pointer;+ transition: color 120ms ease, background 120ms ease;+ }+ .about-footer:hover {+ color: rgba(255, 255, 255, 0.95);+ background: color-mix(in oklab, white 6%, transparent);+ }+ .about-inline {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.5);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ padding: 2px 4px;+ }+ .about-inline:hover {+ color: var(--accent);+ text-decoration: underline;+ text-underline-offset: 2px;+ }+</style>diff --git a/src/lib/study-music-components/AddToPlaylistDialog.svelte b/src/lib/study-music-components/AddToPlaylistDialog.sveltenew file mode 100644index 00000000..e204593c--- /dev/null+++ b/src/lib/study-music-components/AddToPlaylistDialog.svelte@@ -0,0 +1,280 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { playlistsStore } from "$lib/study-music/playlists-store.svelte";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ type Props = {+ open: boolean;+ trackId: number | null;+ trackName?: string | null;+ onClose: () => void;+ };++ let { open = $bindable(), trackId, trackName, onClose }: Props = $props();++ let creatingNew = $state(false);+ let newName = $state("");+ let newRef = $state<HTMLInputElement | null>(null);+ let busy = $state(false);++ $effect(() => {+ if (open) {+ void playlistsStore.load();+ creatingNew = false;+ newName = "";+ }+ });++ async function addToExisting(playlistId: number) {+ if (busy || trackId == null) return;+ busy = true;+ try {+ const res = await playlistsStore.addTrack(playlistId, trackId);+ const pl = playlistsStore.list.find((p) => p.id === playlistId);+ if (res.duplicate) {+ showToast("info", $t("study.music.playlist_duplicate", { name: pl?.name ?? "" }) as string);+ } else {+ showToast(+ "success",+ $t("study.music.added_to_playlist", { name: pl?.name ?? "" }) as string,+ );+ }+ onClose();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function createAndAdd() {+ const trimmed = newName.trim();+ if (!trimmed || trackId == null || busy) return;+ busy = true;+ try {+ const id = await playlistsStore.create(trimmed);+ if (id) {+ await playlistsStore.addTrack(id, trackId);+ showToast(+ "success",+ $t("study.music.created_playlist_with_track", { name: trimmed }) as string,+ );+ }+ onClose();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ newName = "";+ creatingNew = false;+ }+ }++ function startNew() {+ creatingNew = true;+ queueMicrotask(() => newRef?.focus());+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ onClose();+ }+ }+</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.add_to_playlist")}</h3>+ {#if trackName}+ <p class="track-name">{trackName}</p>+ {/if}+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close")}>×</button>+ </header>+ <div class="content">+ <button type="button" class="new-btn" onclick={startNew} disabled={creatingNew}>+ + {$t("study.music.new_playlist")}+ </button>+ {#if creatingNew}+ <div class="new-row">+ <input+ type="text"+ bind:this={newRef}+ bind:value={newName}+ placeholder={$t("study.music.playlist_name_placeholder")}+ onkeydown={(e) => {+ if (e.key === "Enter") createAndAdd();+ else if (e.key === "Escape") {+ e.stopPropagation();+ creatingNew = false;+ newName = "";+ }+ }}+ />+ <button type="button" class="confirm" onclick={createAndAdd} disabled={!newName.trim() || busy}>+ {$t("study.common.create")}+ </button>+ </div>+ {/if}+ {#if playlistsStore.list.length === 0}+ <p class="muted">{$t("study.music.no_playlists_yet")}</p>+ {:else}+ <ul class="list">+ {#each playlistsStore.list as p (p.id)}+ <li>+ <button+ type="button"+ class="row"+ onclick={() => addToExisting(p.id)}+ disabled={busy}+ >+ <span class="row-name">{p.name}</span>+ <span class="row-count">{p.track_count}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+ </div>+ </div>+{/if}++<style>+ .overlay {+ position: fixed;+ inset: 0;+ background: color-mix(in oklab, black 50%, transparent);+ z-index: 300;+ display: grid;+ place-items: center;+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ }+ .dialog {+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 12px;+ width: min(440px, 92vw);+ max-height: 80vh;+ box-shadow: 0 16px 48px color-mix(in oklab, black 40%, transparent);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head {+ position: relative;+ padding: 16px 18px 12px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ }+ .head h3 {+ margin: 0;+ font-size: 15px;+ font-weight: 700;+ color: var(--secondary);+ }+ .track-name {+ margin: 4px 0 0;+ font-size: 12px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .close {+ position: absolute;+ top: 10px;+ right: 12px;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: var(--tertiary);+ font-size: 18px;+ cursor: pointer;+ }+ .close:hover { color: var(--secondary); background: color-mix(in oklab, var(--accent) 8%, transparent); }+ .content {+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ overflow-y: auto;+ }+ .new-btn {+ align-self: flex-start;+ padding: 6px 14px;+ border: 1px dashed color-mix(in oklab, var(--accent) 50%, transparent);+ border-radius: 999px;+ background: transparent;+ color: var(--accent);+ font-family: inherit;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ }+ .new-btn:disabled { opacity: 0.5; cursor: default; }+ .new-row {+ display: flex;+ gap: 8px;+ }+ .new-row input {+ flex: 1;+ padding: 8px 12px;+ border: 1px solid var(--accent);+ border-radius: 8px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: inherit;+ font-size: 13px;+ outline: none;+ }+ .confirm {+ padding: 8px 14px;+ border: 0;+ border-radius: 8px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ }+ .confirm:disabled { opacity: 0.5; cursor: default; }+ .list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }+ .row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ width: 100%;+ padding: 10px 12px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 13px;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease;+ }+ .row:hover { background: color-mix(in oklab, var(--accent) 8%, transparent); }+ .row:disabled { opacity: 0.5; cursor: default; }+ .row-count {+ font-size: 11px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ }+ .muted { color: var(--tertiary); font-size: 12px; padding: 8px 4px; }+</style>diff --git a/src/lib/study-music-components/AlbumCard.svelte b/src/lib/study-music-components/AlbumCard.sveltenew file mode 100644index 00000000..9c369aa2--- /dev/null+++ b/src/lib/study-music-components/AlbumCard.svelte@@ -0,0 +1,129 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import CoverImage from "./CoverImage.svelte";++ type Album = {+ name: string;+ artist?: string | null;+ cover_path?: string | null;+ track_count?: number;+ year?: number | null;+ first_id?: number | null;+ };++ type Props = {+ album: Album;+ href?: string;+ };++ let { album, href }: Props = $props();++ function open() {+ if (href) {+ goto(href);+ return;+ }+ const params = new URLSearchParams({ name: album.name });+ if (album.artist) params.set("artist", album.artist);+ goto(`/study/music/album/by-name?${params.toString()}`);+ }+</script>++<button type="button" class="album-card" onclick={open}>+ <div class="cover-wrap">+ <CoverImage+ src={album.cover_path}+ alt={album.name}+ fallbackSeed={album.name + (album.artist ?? "")}+ rounded="lg"+ trackId={album.first_id ?? null}+ />+ <span class="play-overlay" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>+ </span>+ </div>+ <div class="meta">+ <span class="title">{album.name}</span>+ {#if album.artist}+ <span class="sub">{album.artist}</span>+ {/if}+ </div>+</button>++<style>+ .album-card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 12px;+ background: color-mix(in oklab, var(--button) 50%, transparent);+ border: 0;+ border-radius: 10px;+ color: inherit;+ text-align: left;+ cursor: pointer;+ transition: background 150ms ease, transform 150ms ease;+ }+ .album-card:hover {+ background: color-mix(in oklab, var(--accent) 8%, var(--button));+ }+ .album-card:hover .play-overlay {+ opacity: 1;+ transform: translateY(0);+ }+ .cover-wrap {+ position: relative;+ aspect-ratio: 1 / 1;+ width: 100%;+ box-shadow: 0 4px 14px color-mix(in oklab, black 28%, transparent);+ border-radius: 10px;+ overflow: hidden;+ }+ .play-overlay {+ position: absolute;+ bottom: 8px;+ right: 8px;+ width: 40px;+ height: 40px;+ border-radius: 50%;+ background: var(--accent);+ color: var(--on-accent, white);+ display: grid;+ place-items: center;+ box-shadow: 0 4px 12px color-mix(in oklab, var(--accent) 40%, transparent);+ opacity: 0;+ transform: translateY(8px);+ transition: opacity 150ms ease, transform 150ms ease;+ }+ .meta {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 0 2px;+ min-width: 0;+ }+ .title {+ font-size: 14px;+ font-weight: 600;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ font-size: 12px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ @media (prefers-reduced-motion: reduce) {+ .album-card,+ .play-overlay {+ transition: none;+ }+ .album-card:hover .play-overlay {+ transform: none;+ }+ }+</style>diff --git a/src/lib/study-music-components/AlbumHero.svelte b/src/lib/study-music-components/AlbumHero.sveltenew file mode 100644index 00000000..e08bd00a--- /dev/null+++ b/src/lib/study-music-components/AlbumHero.svelte@@ -0,0 +1,199 @@+<script lang="ts">+ import { fmtDurationLong } from "$lib/study-music/format";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { t } from "$lib/i18n";+ import CoverImage from "./CoverImage.svelte";++ type Album = {+ name: string;+ artist?: string | null;+ track_count?: number;+ total_duration_ms?: number;+ year?: number | null;+ cover_path?: string | null;+ first_id?: number | null;+ };++ type Props = {+ album: Album;+ tracks: MusicTrack[];+ eyebrow?: string;+ };++ let { album, tracks, eyebrow }: Props = $props();++ function playAll() {+ if (tracks.length === 0) return;+ void musicPlayer.play(tracks[0], tracks);+ }++ function playShuffled() {+ if (tracks.length === 0) return;+ musicPlayer.shuffle = true;+ const idx = Math.floor(Math.random() * tracks.length);+ void musicPlayer.play(tracks[idx], tracks);+ }+</script>++<header class="album-hero">+ <div class="cover-block">+ <CoverImage+ src={album.cover_path}+ alt={album.name}+ fallbackSeed={album.name + (album.artist ?? "")}+ rounded="lg"+ trackId={album.first_id ?? (tracks[0]?.id ?? null)}+ />+ </div>+ <div class="meta">+ <span class="eyebrow">{eyebrow ?? $t("study.music.eyebrow_album")}</span>+ <h1 class="title">{album.name}</h1>+ <div class="info">+ {#if album.artist}+ <span class="artist">{album.artist}</span>+ <span class="dot" aria-hidden="true">·</span>+ {/if}+ {#if album.year}+ <span>{album.year}</span>+ <span class="dot" aria-hidden="true">·</span>+ {/if}+ <span>{$t("study.music.tracks_count", { count: album.track_count ?? tracks.length })}</span>+ {#if album.total_duration_ms}+ <span class="dot" aria-hidden="true">·</span>+ <span>{fmtDurationLong(album.total_duration_ms)}</span>+ {/if}+ </div>+ <div class="actions">+ <button type="button" class="play-big" onclick={playAll}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ <span>{$t("study.music.play")}</span>+ </button>+ <button+ type="button"+ class="ghost-big"+ onclick={playShuffled}+ title={$t("study.music.shuffle") as string}+ aria-label={$t("study.music.shuffle") as string}+ >+ <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">+ <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>+ </div>+ </div>+</header>++<style>+ .album-hero {+ display: flex;+ align-items: flex-end;+ gap: 28px;+ padding: 24px 4px 28px;+ }+ .cover-block {+ flex-shrink: 0;+ width: clamp(160px, 22vw, 240px);+ aspect-ratio: 1 / 1;+ box-shadow: 0 12px 40px color-mix(in oklab, black 35%, transparent);+ border-radius: 10px;+ overflow: hidden;+ }+ .meta {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .eyebrow {+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--tertiary);+ }+ .title {+ margin: 0;+ font-size: clamp(28px, 4.5vw, 56px);+ line-height: 1.05;+ font-weight: 800;+ letter-spacing: -0.02em;+ color: var(--secondary);+ overflow-wrap: anywhere;+ }+ .info {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ color: var(--tertiary);+ font-size: 13px;+ }+ .info .artist {+ color: var(--secondary);+ font-weight: 600;+ }+ .info .dot {+ opacity: 0.6;+ }+ .actions {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-top: 6px;+ }+ .play-big {+ 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: 14px;+ font-weight: 700;+ cursor: pointer;+ box-shadow: 0 4px 14px color-mix(in oklab, var(--accent) 35%, transparent);+ transition: transform 120ms ease, background 120ms ease;+ }+ .play-big:hover {+ transform: scale(1.04);+ }+ .play-big:active {+ transform: scale(0.98);+ }+ .ghost-big {+ width: 40px;+ height: 40px;+ padding: 0;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 50%;+ background: transparent;+ color: var(--tertiary);+ cursor: pointer;+ display: grid;+ place-items: center;+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .ghost-big:hover {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ @media (max-width: 720px) {+ .album-hero {+ flex-direction: column;+ align-items: flex-start;+ }+ }+ @media (prefers-reduced-motion: reduce) {+ .play-big, .ghost-big { transition: none; }+ .play-big:hover { transform: none; }+ }+</style>diff --git a/src/lib/study-music-components/AlbumPill.svelte b/src/lib/study-music-components/AlbumPill.sveltenew file mode 100644index 00000000..f260b882--- /dev/null+++ b/src/lib/study-music-components/AlbumPill.svelte@@ -0,0 +1,201 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import CoverImage from "./CoverImage.svelte";++ type Album = {+ name: string;+ artist?: string | null;+ cover_path?: string | null;+ year?: number | null;+ first_id?: number | null;+ };++ type Props = {+ album: Album;+ href?: string;+ };++ let { album, href }: Props = $props();+ let busy = $state(false);++ function open() {+ if (href) {+ goto(href);+ return;+ }+ const params = new URLSearchParams({ name: album.name });+ if (album.artist) params.set("artist", album.artist);+ goto(`/study/music/album/by-name?${params.toString()}`);+ }++ async function playAlbum(e: MouseEvent) {+ e.stopPropagation();+ if (busy) return;+ busy = true;+ try {+ const args: { name: string; artist?: string } = { name: album.name };+ if (album.artist) args.artist = album.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);+ }+ } catch {+ /* ignore */+ } finally {+ busy = false;+ }+ }+</script>++<div+ class="album-pill"+ role="button"+ tabindex="0"+ onclick={open}+ onkeydown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ open();+ }+ }}+>+ <div class="cover">+ <CoverImage+ src={album.cover_path}+ alt={album.name}+ fallbackSeed={album.name + (album.artist ?? "")}+ rounded="sm"+ trackId={album.first_id ?? null}+ />+ <div class="cover-overlay" aria-hidden="true"></div>+ </div>+ <div class="meta">+ <h3 class="title">{album.name}</h3>+ {#if album.artist}+ <p class="sub">{album.artist}</p>+ {/if}+ </div>+ <div class="play-wrap">+ <button+ type="button"+ class="play-btn"+ onclick={playAlbum}+ aria-label="Tocar"+ disabled={busy}+ >+ <svg viewBox="0 0 24 24" width="11" height="11" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ </button>+ </div>+</div>++<style>+ .album-pill {+ display: flex;+ align-items: center;+ gap: 0;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.05);+ border-radius: 16px;+ cursor: pointer;+ overflow: hidden;+ padding-right: 16px;+ transition: background 300ms ease, border-color 300ms ease;+ }+ .album-pill:hover {+ background: rgba(255, 255, 255, 0.1);+ }+ .album-pill:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .cover {+ position: relative;+ flex-shrink: 0;+ width: 80px;+ height: 80px;+ background: rgba(40, 40, 40, 0.5);+ overflow: hidden;+ }+ .cover :global(.cover) {+ border-radius: 0;+ }+ .cover :global(img) {+ transition: transform 500ms ease;+ }+ .album-pill:hover .cover :global(img) {+ transform: scale(1.05);+ }+ .cover-overlay {+ position: absolute;+ inset: 0;+ background: rgba(0, 0, 0, 0);+ transition: background 300ms ease;+ }+ .album-pill:hover .cover-overlay {+ background: rgba(0, 0, 0, 0.2);+ }+ .meta {+ flex: 1;+ min-width: 0;+ padding: 16px;+ display: flex;+ flex-direction: column;+ justify-content: center;+ }+ .title {+ margin: 0;+ color: rgba(255, 255, 255, 0.95);+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.5);+ font-weight: 600;+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .play-wrap {+ opacity: 0;+ transition: opacity 300ms ease;+ }+ .album-pill:hover .play-wrap {+ opacity: 1;+ }+ .play-btn {+ width: 32px;+ height: 32px;+ padding: 0;+ background: rgba(255, 255, 255, 0.1);+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.85);+ cursor: pointer;+ display: grid;+ place-items: center;+ transition: background 200ms ease;+ }+ .play-btn:hover {+ background: rgba(255, 255, 255, 0.2);+ }+ @media (max-width: 640px) {+ .cover { width: 64px; height: 64px; }+ .meta { padding: 12px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .album-pill, .cover :global(img), .cover-overlay, .play-wrap, .play-btn {+ transition: none;+ }+ }+</style>diff --git a/src/lib/study-music-components/ArtistCircle.svelte b/src/lib/study-music-components/ArtistCircle.sveltenew file mode 100644index 00000000..d1353577--- /dev/null+++ b/src/lib/study-music-components/ArtistCircle.svelte@@ -0,0 +1,101 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { colorFromString } from "$lib/study-music/format";++ type Props = {+ name: string;+ coverPath?: string | null;+ trackCount?: number;+ };++ let { name, coverPath, trackCount }: Props = $props();++ const cover = $derived.by(() => {+ if (!coverPath) return null;+ try {+ return convertFileSrc(coverPath);+ } catch {+ return coverPath;+ }+ });++ const fallbackColor = $derived(colorFromString(name));+ const initial = $derived(name.slice(0, 1).toUpperCase());++ function open() {+ goto(`/study/music/artist/by-name?name=${encodeURIComponent(name)}`);+ }+</script>++<button type="button" class="artist-circle" onclick={open}>+ <span class="circle">+ {#if cover}+ <img src={cover} alt="" loading="lazy" />+ {:else}+ <span class="circle-fallback" style:background={fallbackColor}>{initial}</span>+ {/if}+ </span>+ <span class="name">{name}</span>+ {#if trackCount != null}+ <span class="sub">{trackCount} faixa(s)</span>+ {/if}+</button>++<style>+ .artist-circle {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ background: transparent;+ border: 0;+ color: inherit;+ font-family: inherit;+ cursor: pointer;+ padding: 0;+ width: 100%;+ text-align: center;+ }+ .circle {+ width: 100%;+ aspect-ratio: 1 / 1;+ border-radius: 50%;+ overflow: hidden;+ box-shadow: 0 4px 14px color-mix(in oklab, black 24%, transparent);+ transition: transform 120ms ease, box-shadow 120ms ease;+ background: var(--button);+ }+ .artist-circle:hover .circle {+ transform: scale(1.04);+ box-shadow: 0 6px 18px color-mix(in oklab, var(--accent) 40%, transparent);+ }+ .circle img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .circle-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ font-size: clamp(28px, 4vw, 48px);+ font-weight: 800;+ }+ .name {+ font-size: 13px;+ font-weight: 600;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ max-width: 100%;+ }+ .sub {+ font-size: 11px;+ color: var(--tertiary);+ }+</style>diff --git a/src/lib/study-music-components/ContextMenu.svelte b/src/lib/study-music-components/ContextMenu.sveltenew file mode 100644index 00000000..30e28be3--- /dev/null+++ b/src/lib/study-music-components/ContextMenu.svelte@@ -0,0 +1,177 @@+<script lang="ts">+ export type ContextMenuItem = {+ id: string;+ label: string;+ icon?: string;+ shortcut?: string;+ danger?: boolean;+ separator?: boolean;+ disabled?: boolean;+ };++ type Props = {+ open: boolean;+ x: number;+ y: number;+ items: ContextMenuItem[];+ onAction: (id: string) => void;+ onClose: () => void;+ };++ let { open, x, y, items, onAction, onClose }: Props = $props();++ let menuEl = $state<HTMLDivElement | null>(null);++ const adjustedPos = $derived.by(() => {+ if (!open || typeof window === "undefined") return { left: x, top: y };+ const rect = menuEl?.getBoundingClientRect();+ const w = rect?.width ?? 220;+ const h = rect?.height ?? 200;+ let left = x;+ let top = y;+ if (left + w > window.innerWidth - 8) left = window.innerWidth - w - 8;+ if (top + h > window.innerHeight - 8) top = window.innerHeight - h - 8;+ if (left < 8) left = 8;+ if (top < 8) top = 8;+ return { left, top };+ });++ $effect(() => {+ if (!open || typeof document === "undefined") return;+ function handleClick(e: MouseEvent) {+ if (menuEl && !menuEl.contains(e.target as Node)) {+ onClose();+ }+ }+ function handleKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }+ document.addEventListener("mousedown", handleClick);+ document.addEventListener("keydown", handleKey);+ return () => {+ document.removeEventListener("mousedown", handleClick);+ document.removeEventListener("keydown", handleKey);+ };+ });+</script>++{#if open}+ <div+ bind:this={menuEl}+ class="ctx-menu"+ style="left: {adjustedPos.left}px; top: {adjustedPos.top}px;"+ role="menu"+ tabindex="-1"+ >+ {#each items as item (item.id)}+ {#if item.separator}+ <div class="separator" role="separator"></div>+ {:else}+ <button+ type="button"+ class="item"+ class:danger={item.danger}+ disabled={item.disabled}+ role="menuitem"+ onclick={() => {+ if (!item.disabled) {+ onAction(item.id);+ onClose();+ }+ }}+ >+ {#if item.icon}+ <span class="icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">+ <path d={item.icon}></path>+ </svg>+ </span>+ {/if}+ <span class="label">{item.label}</span>+ {#if item.shortcut}+ <span class="shortcut">{item.shortcut}</span>+ {/if}+ </button>+ {/if}+ {/each}+ </div>+{/if}++<style>+ .ctx-menu {+ position: fixed;+ z-index: 350;+ min-width: 220px;+ padding: 4px;+ background: rgb(28, 28, 30);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 8px;+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(0, 0, 0, 0.4);+ display: flex;+ flex-direction: column;+ gap: 1px;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ }+ .item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 7px 10px;+ background: transparent;+ border: 0;+ border-radius: 5px;+ color: inherit;+ font-family: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ width: 100%;+ }+ .item:hover:not(:disabled) {+ background: var(--accent);+ color: var(--on-accent, white);+ }+ .item:disabled {+ opacity: 0.4;+ cursor: default;+ }+ .item.danger {+ color: rgb(248, 113, 113);+ }+ .item.danger:hover:not(:disabled) {+ background: rgba(220, 38, 38, 0.85);+ color: white;+ }+ .icon {+ flex-shrink: 0;+ width: 14px;+ height: 14px;+ display: grid;+ place-items: center;+ color: inherit;+ opacity: 0.7;+ }+ .item:hover .icon { opacity: 1; }+ .label {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .shortcut {+ font-size: 10px;+ color: rgba(255, 255, 255, 0.4);+ font-family: ui-monospace, monospace;+ }+ .item:hover .shortcut { color: rgba(255, 255, 255, 0.8); }+ .separator {+ height: 1px;+ margin: 4px 6px;+ background: rgba(255, 255, 255, 0.08);+ }+</style>diff --git a/src/lib/study-music-components/CoverImage.svelte b/src/lib/study-music-components/CoverImage.sveltenew file mode 100644index 00000000..10f8b8bc--- /dev/null+++ b/src/lib/study-music-components/CoverImage.svelte@@ -0,0 +1,116 @@+<script lang="ts">+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";++ type Props = {+ src: string | null | undefined;+ alt?: string;+ size?: number | "fluid";+ fallbackSeed?: string | null;+ rounded?: "sm" | "md" | "lg" | "xl";+ trackId?: number | null;+ };++ let {+ src,+ alt = "",+ size = "fluid",+ fallbackSeed = null,+ rounded = "md",+ trackId = null,+ }: Props = $props();++ let assetSrc = $state<string | null>(null);+ let dataUrl = $state<string | null>(null);+ let assetFailed = $state(false);++ $effect(() => {+ assetFailed = false;+ dataUrl = null;+ if (!src) {+ assetSrc = null;+ return;+ }+ // URLs HTTP/HTTPS/data passam direto. convertFileSrc é só pra paths locais.+ if (+ src.startsWith("http://") ||+ src.startsWith("https://") ||+ src.startsWith("data:") ||+ src.startsWith("blob:")+ ) {+ assetSrc = src;+ return;+ }+ try {+ assetSrc = convertFileSrc(src);+ } catch {+ assetSrc = src;+ }+ });++ async function onAssetError() {+ if (assetFailed) return;+ assetFailed = true;+ if (!trackId) return;+ try {+ const res = await pluginInvoke<{ data_url: string | null }>(+ "study",+ "study:music:cover:data-url",+ { id: trackId },+ );+ if (res.data_url) dataUrl = res.data_url;+ } catch {+ /* ignore */+ }+ }++ const sizeStyle = $derived(+ size === "fluid"+ ? "width: 100%; height: 100%;"+ : `width: ${size}px; height: ${size}px;`,+ );++ const radiusClass = $derived(`r-${rounded}`);+ const finalSrc = $derived(dataUrl ?? assetSrc);+</script>++<div class="cover {radiusClass}" style={sizeStyle}>+ {#if finalSrc}+ <img src={finalSrc} {alt} loading="lazy" onerror={onAssetError} />+ {:else}+ <div class="fallback">+ <svg viewBox="0 0 24 24" width="40%" height="40%" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M9 18V5l12-2v13"/>+ <circle cx="6" cy="18" r="3"/>+ <circle cx="18" cy="16" r="3"/>+ </svg>+ </div>+ {/if}+</div>++<style>+ .cover {+ position: relative;+ overflow: hidden;+ flex-shrink: 0;+ background: rgba(40, 40, 40, 0.6);+ }+ .r-sm { border-radius: 4px; }+ .r-md { border-radius: 6px; }+ .r-lg { border-radius: 10px; }+ .r-xl { border-radius: 14px; }+ img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: rgba(255, 255, 255, 0.25);+ background: rgba(40, 40, 40, 0.6);+ }+</style>diff --git a/src/lib/study-music-components/DiscordRpcPanel.svelte b/src/lib/study-music-components/DiscordRpcPanel.sveltenew file mode 100644index 00000000..f1b0f0b9--- /dev/null+++ b/src/lib/study-music-components/DiscordRpcPanel.svelte@@ -0,0 +1,390 @@+<script lang="ts">+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";+ import AboutLink from "./AboutLink.svelte";++ type Status = {+ enabled: boolean;+ app_id: string;+ large_image_key: string;+ connected: boolean;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ let status = $state<Status | null>(null);+ let appIdInput = $state("");+ let imageKeyInput = $state("");+ let busy = $state(false);+ let testResult = $state<"ok" | "fail" | null>(null);++ async function load() {+ try {+ status = await pluginInvoke<Status>("study", "study:music:rpc:get_settings");+ appIdInput = status.app_id;+ imageKeyInput = status.large_image_key;+ } catch {+ status = null;+ }+ }++ $effect(() => {+ if (open) {+ testResult = null;+ void load();+ }+ });++ async function toggleEnabled() {+ if (!status || busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<Status>(+ "study",+ "study:music:rpc:set_settings",+ { enabled: !status.enabled },+ );+ status = res;+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function saveFields() {+ if (!status || busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<Status>(+ "study",+ "study:music:rpc:set_settings",+ {+ app_id: appIdInput.trim(),+ large_image_key: imageKeyInput.trim(),+ },+ );+ status = res;+ appIdInput = res.app_id;+ imageKeyInput = res.large_image_key;+ showToast("success", $t("study.music.rpc_saved") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function testConnection() {+ if (busy) return;+ busy = true;+ testResult = null;+ try {+ const res = await pluginInvoke<{ ok: boolean }>(+ "study",+ "study:music:rpc:test",+ );+ testResult = res.ok ? "ok" : "fail";+ if (!res.ok) {+ showToast("error", $t("study.music.rpc_test_fail") as string);+ } else {+ showToast("success", $t("study.music.rpc_test_ok") as string);+ }+ await load();+ } catch (e) {+ testResult = "fail";+ 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();+ }+ }+</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">+ <div class="head-text">+ <h3>{$t("study.music.rpc_title")}</h3>+ {#if status}+ <span class="state" class:on={status.connected} class:off={!status.connected}>+ {status.connected+ ? $t("study.music.rpc_connected")+ : $t("study.music.rpc_disconnected")}+ </span>+ {/if}+ </div>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.rpc_intro")}</p>++ {#if status === null}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else}+ <label class="toggle">+ <input+ type="checkbox"+ checked={status.enabled}+ onchange={toggleEnabled}+ disabled={busy}+ />+ <span>{$t("study.music.rpc_enable")}</span>+ </label>++ <details class="advanced">+ <summary>{$t("study.music.rpc_advanced")}</summary>+ <div class="adv-body">+ <label class="field">+ <span>Application ID</span>+ <input+ type="text"+ bind:value={appIdInput}+ placeholder="1502867748353478656"+ autocomplete="off"+ />+ <small>{$t("study.music.rpc_appid_hint")}</small>+ </label>+ <label class="field">+ <span>{$t("study.music.rpc_large_image")}</span>+ <input+ type="text"+ bind:value={imageKeyInput}+ placeholder="omniget_music"+ autocomplete="off"+ />+ <small>{$t("study.music.rpc_image_hint")}</small>+ </label>+ <button+ type="button"+ class="cta-secondary"+ onclick={saveFields}+ disabled={busy}+ >{$t("study.music.rpc_save")}</button>+ </div>+ </details>++ <div class="actions">+ <button type="button" class="cta" onclick={testConnection} disabled={busy || !status.enabled}>+ {$t("study.music.rpc_test")}+ </button>+ {#if testResult === "ok"}+ <span class="ok-badge">✓ {$t("study.music.rpc_test_ok")}</span>+ {:else if testResult === "fail"}+ <span class="fail-badge">✗ {$t("study.music.rpc_test_fail")}</span>+ {/if}+ </div>++ <p class="footnote">{$t("study.music.rpc_discord_running")}</p>+ <AboutLink variant="card" />+ {/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 {+ position: relative;+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px;+ padding: 18px 20px 8px;+ }+ .head-text { display: flex; flex-direction: column; gap: 4px; }+ .head h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ }+ .state {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 2px 10px;+ border-radius: 999px;+ font-size: 11px;+ font-weight: 600;+ width: fit-content;+ }+ .state::before {+ content: "";+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: currentColor;+ }+ .state.on { background: rgba(34, 197, 94, 0.15); color: rgb(74, 222, 128); }+ .state.off { background: rgba(255, 255, 255, 0.06); color: rgba(255, 255, 255, 0.45); }+ .close {+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ flex-shrink: 0;+ }+ .body {+ padding: 8px 20px 20px;+ display: flex;+ flex-direction: column;+ gap: 16px;+ }+ .hint {+ margin: 0;+ color: rgba(255, 255, 255, 0.65);+ font-size: 13px;+ line-height: 1.5;+ }+ .muted { color: rgba(255, 255, 255, 0.5); }+ .toggle {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ cursor: pointer;+ font-size: 13px;+ color: rgba(255, 255, 255, 0.85);+ padding: 10px 14px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 10px;+ }+ .toggle input { width: 14px; height: 14px; accent-color: var(--accent); }+ .advanced {+ background: rgba(0, 0, 0, 0.2);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 10px;+ padding: 10px 14px;+ }+ .advanced summary {+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ color: rgba(255, 255, 255, 0.7);+ user-select: none;+ }+ .adv-body {+ margin-top: 12px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .field span {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.5);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ }+ .field small {+ color: rgba(255, 255, 255, 0.4);+ font-size: 11px;+ line-height: 1.4;+ }+ .field input {+ padding: 8px 10px;+ 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;+ }+ .field input:focus { border-color: var(--accent); }+ .cta-secondary {+ align-self: flex-start;+ padding: 7px 14px;+ border: 1px solid rgba(255, 255, 255, 0.15);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .cta-secondary:hover { border-color: var(--accent); color: var(--accent); }+ .actions {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .cta {+ padding: 8px 18px;+ border: 0;+ border-radius: 999px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 13px;+ font-weight: 700;+ cursor: pointer;+ }+ .cta:disabled { opacity: 0.5; cursor: default; }+ .ok-badge {+ color: rgb(74, 222, 128);+ font-size: 12px;+ font-weight: 600;+ }+ .fail-badge {+ color: rgb(248, 113, 113);+ font-size: 12px;+ font-weight: 600;+ }+ .footnote {+ margin: 8px 0 0;+ color: rgba(255, 255, 255, 0.4);+ font-size: 11px;+ font-style: italic;+ }+</style>diff --git a/src/lib/study-music-components/EqualizerPanel.svelte b/src/lib/study-music-components/EqualizerPanel.sveltenew file mode 100644index 00000000..57ef295a--- /dev/null+++ b/src/lib/study-music-components/EqualizerPanel.svelte@@ -0,0 +1,291 @@+<script lang="ts">+ import {+ musicPlayer,+ EQ_BAND_FREQUENCIES,+ EQ_PRESETS,+ type EqPreset,+ } from "$lib/study-music/player-store.svelte";+ import { t } from "$lib/i18n";++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ const PRESETS: EqPreset[] = [+ "flat",+ "bass",+ "vocal",+ "treble",+ "rock",+ "pop",+ "classical",+ "electronic",+ "custom",+ ];++ function fmtFreq(hz: number) {+ return hz >= 1000 ? `${hz / 1000}k` : `${hz}`;+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }+</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.eq_title")}</h3>+ <button+ type="button"+ class="close"+ onclick={onClose}+ aria-label={$t("study.common.close") as string}+ >×</button>+ </header>++ <div class="enable-row">+ <label class="toggle">+ <input+ type="checkbox"+ checked={musicPlayer.eqEnabled}+ onchange={(e) =>+ musicPlayer.setEqEnabled((e.currentTarget as HTMLInputElement).checked)}+ />+ <span>{$t("study.music.eq_enable")}</span>+ </label>+ </div>++ <div class="presets">+ <span class="presets-label">{$t("study.music.eq_preset")}</span>+ <div class="preset-row">+ {#each PRESETS as p (p)}+ <button+ type="button"+ class="preset-btn"+ class:active={musicPlayer.eqPreset === p}+ onclick={() => musicPlayer.setEqPreset(p)}+ >{$t(`study.music.eq_preset_${p}`)}</button>+ {/each}+ </div>+ </div>++ <div class="bands">+ {#each EQ_BAND_FREQUENCIES as freq, i (freq)}+ {@const value = musicPlayer.eqGains[i] ?? 0}+ <div class="band">+ <span class="gain">{value > 0 ? "+" : ""}{value.toFixed(1)} dB</span>+ <input+ type="range"+ orient="vertical"+ min="-12"+ max="12"+ step="0.5"+ value={value}+ disabled={!musicPlayer.eqEnabled}+ oninput={(e) =>+ musicPlayer.setEqGain(i, Number((e.currentTarget as HTMLInputElement).value))}+ />+ <span class="freq">{fmtFreq(freq)} Hz</span>+ </div>+ {/each}+ </div>++ <footer class="foot">+ <button+ type="button"+ class="reset-btn"+ onclick={() => musicPlayer.setEqPreset("flat")}+ >{$t("study.music.eq_reset")}</button>+ <button+ type="button"+ class="done-btn"+ onclick={onClose}+ >{$t("study.common.close")}</button>+ </footer>+ </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 {+ position: relative;+ padding: 18px 20px 8px;+ }+ .head h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ }+ .close {+ position: absolute;+ top: 12px;+ right: 14px;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ }+ .close:hover { color: white; background: rgba(255, 255, 255, 0.08); }+ .enable-row {+ padding: 8px 20px 0;+ }+ .toggle {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ cursor: pointer;+ font-size: 13px;+ color: rgba(255, 255, 255, 0.85);+ }+ .toggle input {+ width: 14px;+ height: 14px;+ accent-color: var(--accent);+ }+ .presets {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 12px 20px 4px;+ }+ .presets-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: rgba(255, 255, 255, 0.5);+ }+ .preset-row {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ }+ .preset-btn {+ padding: 5px 12px;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.65);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ text-transform: capitalize;+ }+ .preset-btn:hover {+ color: rgba(255, 255, 255, 0.95);+ border-color: rgba(255, 255, 255, 0.25);+ }+ .preset-btn.active {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent, white);+ }+ .bands {+ display: flex;+ align-items: stretch;+ justify-content: space-around;+ padding: 18px 20px;+ gap: 8px;+ }+ .band {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ flex: 1;+ }+ .gain {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.65);+ font-variant-numeric: tabular-nums;+ min-height: 16px;+ }+ .band input[type="range"] {+ writing-mode: vertical-lr;+ direction: rtl;+ appearance: slider-vertical;+ -webkit-appearance: slider-vertical;+ width: 18px;+ height: 160px;+ accent-color: var(--accent);+ }+ .freq {+ font-size: 10px;+ color: rgba(255, 255, 255, 0.45);+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }+ .foot {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ padding: 14px 20px;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ background: rgba(255, 255, 255, 0.02);+ }+ .reset-btn {+ padding: 8px 14px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.65);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .reset-btn:hover {+ color: rgba(255, 255, 255, 0.95);+ border-color: rgba(255, 255, 255, 0.25);+ }+ .done-btn {+ 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;+ }+</style>diff --git a/src/lib/study-music-components/FeaturedAlbumHero.svelte b/src/lib/study-music-components/FeaturedAlbumHero.sveltenew file mode 100644index 00000000..9e8ba05b--- /dev/null+++ b/src/lib/study-music-components/FeaturedAlbumHero.svelte@@ -0,0 +1,213 @@+<script lang="ts">+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { musicPlayer } from "$lib/study-music/player-store.svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import type { MusicTrack } from "$lib/study-music/player-store.svelte";++ type Album = {+ name: string;+ artist: string | null;+ cover_path: string | null;+ track_count: number;+ year: number | null;+ };++ type Props = {+ album: Album | null;+ };++ let { album }: Props = $props();++ const coverUrl = $derived.by(() => {+ if (!album?.cover_path) return null;+ try {+ return convertFileSrc(album.cover_path);+ } catch {+ return album.cover_path;+ }+ });++ let busy = $state(false);++ async function startListening() {+ if (!album || busy) return;+ busy = true;+ try {+ const args: { name: string; artist?: string } = { name: album.name };+ if (album.artist) args.artist = album.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);+ }+ } catch {+ /* ignore */+ } finally {+ busy = false;+ }+ }++ function openAlbum() {+ if (!album) return;+ const params = new URLSearchParams({ name: album.name });+ if (album.artist) params.set("artist", album.artist);+ goto(`/study/music/album/by-name?${params.toString()}`);+ }+</script>++{#if album}+ <section+ class="hero"+ style:background-image={coverUrl ? `url('${coverUrl}')` : "none"}+ >+ <div class="overlay">+ <div class="content">+ <span class="eyebrow">+ <svg viewBox="0 0 24 24" width="11" height="11" fill="currentColor" aria-hidden="true">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>+ </svg>+ {$t("study.music.featured_album")}+ </span>+ <h1 class="title">{album.name}</h1>+ {#if album.artist}+ <p class="artist">{$t("study.music.by")} {album.artist}</p>+ {/if}+ <div class="actions">+ <button+ type="button"+ class="play-cta"+ onclick={startListening}+ disabled={busy}+ >+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ <span>{$t("study.music.start_listening")}</span>+ </button>+ <button+ type="button"+ class="open-cta"+ onclick={openAlbum}+ aria-label={$t("study.music.open_album") as string}+ title={$t("study.music.open_album") 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" aria-hidden="true">+ <line x1="5" y1="12" x2="19" y2="12"/>+ <polyline points="12 5 19 12 12 19"/>+ </svg>+ </button>+ </div>+ </div>+ </div>+ </section>+{/if}++<style>+ .hero {+ position: relative;+ width: 100%;+ aspect-ratio: 21 / 9;+ max-height: 380px;+ border-radius: 12px;+ overflow: hidden;+ background-size: cover;+ background-position: center 30%;+ background-color: color-mix(in oklab, var(--accent) 8%, var(--button));+ box-shadow: 0 8px 24px color-mix(in oklab, black 28%, transparent);+ }+ .overlay {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: flex-end;+ background: linear-gradient(+ 90deg,+ color-mix(in oklab, black 70%, transparent) 0%,+ color-mix(in oklab, black 35%, transparent) 50%,+ transparent 80%+ );+ padding: 32px 36px;+ }+ .content {+ display: flex;+ flex-direction: column;+ gap: 10px;+ max-width: 60%;+ color: white;+ }+ .eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.12em;+ color: rgba(255, 255, 255, 0.85);+ text-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);+ }+ .title {+ margin: 0;+ font-size: clamp(36px, 6vw, 80px);+ line-height: 0.95;+ font-weight: 900;+ letter-spacing: -0.02em;+ color: white;+ text-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);+ overflow-wrap: anywhere;+ }+ .artist {+ margin: 0;+ font-size: 14px;+ color: rgba(255, 255, 255, 0.85);+ text-shadow: 0 1px 6px rgba(0, 0, 0, 0.4);+ }+ .actions {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-top: 10px;+ }+ .play-cta {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 10px 22px;+ background: var(--accent);+ color: var(--on-accent, white);+ border: 0;+ border-radius: 999px;+ font-family: inherit;+ font-size: 13px;+ font-weight: 700;+ cursor: pointer;+ box-shadow: 0 4px 14px color-mix(in oklab, var(--accent) 40%, transparent);+ transition: transform 120ms ease;+ }+ .play-cta:hover { transform: scale(1.04); }+ .play-cta:disabled { opacity: 0.6; cursor: default; }+ .open-cta {+ width: 38px;+ height: 38px;+ padding: 0;+ background: rgba(255, 255, 255, 0.12);+ border: 1px solid rgba(255, 255, 255, 0.2);+ border-radius: 50%;+ color: white;+ cursor: pointer;+ display: grid;+ place-items: center;+ backdrop-filter: blur(4px);+ transition: background 120ms ease;+ }+ .open-cta:hover {+ background: rgba(255, 255, 255, 0.22);+ }+ @media (max-width: 800px) {+ .overlay { padding: 18px; }+ .content { max-width: 100%; }+ }+</style>diff --git a/src/lib/study-music-components/LastFmPanel.svelte b/src/lib/study-music-components/LastFmPanel.sveltenew file mode 100644index 00000000..5a94dad5--- /dev/null+++ b/src/lib/study-music-components/LastFmPanel.svelte@@ -0,0 +1,466 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ type Status = {+ username: string;+ api_key_set: boolean;+ api_secret_set: boolean;+ session_key_set: boolean;+ enabled: boolean;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ let status = $state<Status | null>(null);+ let apiKey = $state("");+ let apiSecret = $state("");+ let busy = $state(false);+ let pendingToken = $state<string | null>(null);+ let pendingAuthUrl = $state<string | null>(null);++ async function load() {+ try {+ status = await pluginInvoke<Status>(+ "study",+ "study:music:lastfm:get_settings",+ );+ } catch {+ status = null;+ }+ }++ $effect(() => {+ if (open) void load();+ });++ async function saveKeys() {+ if (busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<Status>("study", "study:music:lastfm:set_settings", {+ api_key: apiKey,+ api_secret: apiSecret,+ });+ status = res;+ apiKey = "";+ apiSecret = "";+ showToast("success", $t("study.music.lastfm_keys_saved") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function startAuth() {+ if (busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<{ token: string; auth_url: string }>(+ "study",+ "study:music:lastfm:auth_token",+ );+ pendingToken = res.token;+ pendingAuthUrl = res.auth_url;+ try {+ const { openUrl } = await import("@tauri-apps/plugin-opener");+ await openUrl(res.auth_url);+ } catch {+ /* user can click link */+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function finalizeAuth() {+ if (!pendingToken || busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<Status>(+ "study",+ "study:music:lastfm:auth_finalize",+ { token: pendingToken },+ );+ status = res;+ pendingToken = null;+ pendingAuthUrl = null;+ showToast(+ "success",+ $t("study.music.lastfm_connected", { username: res.username }) as string,+ );+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function toggleEnabled() {+ if (!status || busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<Status>("study", "study:music:lastfm:set_settings", {+ enabled: !status.enabled,+ });+ status = res;+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function disconnect() {+ if (busy || typeof window === "undefined") return;+ if (!window.confirm($t("study.music.lastfm_disconnect_confirm") as string)) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:lastfm:clear");+ await load();+ showToast("success", $t("study.music.lastfm_disconnected") as string);+ } 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();+ }+ }+</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.lastfm_title")}</h3>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.lastfm_intro")}</p>++ {#if status === null}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if !status.session_key_set}+ <section class="step">+ <span class="step-num">1</span>+ <div class="step-body">+ <h4>{$t("study.music.lastfm_step1_title")}</h4>+ <p class="step-desc">{$t("study.music.lastfm_step1_desc")}</p>+ <a+ class="ext-link"+ href="https://www.last.fm/api/account/create"+ target="_blank"+ rel="noopener"+ >www.last.fm/api/account/create →</a>+ </div>+ </section>++ <section class="step">+ <span class="step-num">2</span>+ <div class="step-body">+ <h4>{$t("study.music.lastfm_step2_title")}</h4>+ <p class="step-desc">{$t("study.music.lastfm_step2_desc")}</p>+ <label class="field">+ <span>API key</span>+ <input+ type="text"+ bind:value={apiKey}+ placeholder={status.api_key_set ? "•••••••• (already set)" : ""}+ autocomplete="off"+ />+ </label>+ <label class="field">+ <span>Shared secret</span>+ <input+ type="password"+ bind:value={apiSecret}+ placeholder={status.api_secret_set ? "•••••••• (already set)" : ""}+ autocomplete="off"+ />+ </label>+ <button+ type="button"+ class="cta-secondary"+ onclick={saveKeys}+ disabled={busy || (!apiKey.trim() && !apiSecret.trim())}+ >{$t("study.music.lastfm_save_keys")}</button>+ </div>+ </section>++ {#if status.api_key_set && status.api_secret_set}+ <section class="step">+ <span class="step-num">3</span>+ <div class="step-body">+ <h4>{$t("study.music.lastfm_step3_title")}</h4>+ <p class="step-desc">{$t("study.music.lastfm_step3_desc")}</p>+ {#if !pendingToken}+ <button+ type="button"+ class="cta"+ onclick={startAuth}+ disabled={busy}+ >{$t("study.music.lastfm_authorize")}</button>+ {:else}+ <div class="pending">+ <p>{$t("study.music.lastfm_authorize_pending")}</p>+ {#if pendingAuthUrl}+ <a class="ext-link" href={pendingAuthUrl} target="_blank" rel="noopener">+ {$t("study.music.lastfm_open_auth")} →+ </a>+ {/if}+ <button+ type="button"+ class="cta"+ onclick={finalizeAuth}+ disabled={busy}+ >{$t("study.music.lastfm_finalize")}</button>+ </div>+ {/if}+ </div>+ </section>+ {/if}+ {:else}+ <section class="connected">+ <div class="badge-ok">✓</div>+ <div>+ <h4>{$t("study.music.lastfm_connected_as", { username: status.username })}</h4>+ <p class="step-desc">{$t("study.music.lastfm_connected_hint")}</p>+ </div>+ </section>+ <label class="toggle">+ <input+ type="checkbox"+ checked={status.enabled}+ onchange={toggleEnabled}+ disabled={busy}+ />+ <span>{$t("study.music.lastfm_enable_scrobble")}</span>+ </label>+ <button+ type="button"+ class="link danger"+ onclick={disconnect}+ disabled={busy}+ >{$t("study.music.lastfm_disconnect")}</button>+ {/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(560px, 92vw);+ max-height: 86vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head {+ position: relative;+ padding: 18px 20px 8px;+ }+ .head h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ }+ .close {+ position: absolute;+ top: 12px;+ right: 14px;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ }+ .body {+ flex: 1;+ overflow-y: auto;+ padding: 8px 20px 20px;+ display: flex;+ flex-direction: column;+ gap: 18px;+ }+ .hint {+ margin: 0;+ color: rgba(255, 255, 255, 0.65);+ font-size: 13px;+ line-height: 1.5;+ }+ .muted { color: rgba(255, 255, 255, 0.5); }+ .step {+ display: flex;+ gap: 12px;+ padding: 14px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 10px;+ }+ .step-num {+ flex-shrink: 0;+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ background: var(--accent);+ color: var(--on-accent, white);+ border-radius: 50%;+ font-size: 12px;+ font-weight: 700;+ }+ .step-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px; }+ .step-body h4 {+ margin: 0;+ font-size: 13px;+ font-weight: 700;+ }+ .step-desc {+ margin: 0;+ color: rgba(255, 255, 255, 0.6);+ font-size: 12px;+ line-height: 1.5;+ }+ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin: 4px 0;+ }+ .field span {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.5);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ }+ .field input {+ padding: 8px 10px;+ 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;+ }+ .field input:focus { border-color: var(--accent); }+ .ext-link {+ color: var(--accent);+ font-size: 12px;+ text-decoration: none;+ }+ .ext-link:hover { text-decoration: underline; }+ .cta {+ align-self: flex-start;+ padding: 8px 18px;+ border: 0;+ border-radius: 999px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 12px;+ font-weight: 700;+ cursor: pointer;+ }+ .cta:disabled { opacity: 0.5; cursor: default; }+ .cta-secondary {+ align-self: flex-start;+ padding: 7px 14px;+ border: 1px solid rgba(255, 255, 255, 0.15);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .cta-secondary:hover { border-color: var(--accent); color: var(--accent); }+ .pending {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }+ .connected {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 14px;+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ border: 1px solid color-mix(in oklab, var(--accent) 30%, transparent);+ border-radius: 10px;+ }+ .badge-ok {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ background: var(--accent);+ color: var(--on-accent, white);+ border-radius: 50%;+ font-size: 16px;+ font-weight: 700;+ }+ .connected h4 { margin: 0; font-size: 13px; font-weight: 700; }+ .toggle {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ cursor: pointer;+ font-size: 13px;+ color: rgba(255, 255, 255, 0.85);+ }+ .toggle input { width: 14px; height: 14px; accent-color: var(--accent); }+ .link {+ align-self: flex-start;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.5);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ padding: 0;+ }+ .link.danger:hover { color: rgb(248, 113, 113); }+</style>diff --git a/src/lib/study-music-components/LyricsPanel.svelte b/src/lib/study-music-components/LyricsPanel.sveltenew file mode 100644index 00000000..653e9b8e--- /dev/null+++ b/src/lib/study-music-components/LyricsPanel.svelte@@ -0,0 +1,260 @@+<script lang="ts">+ import { onMount, tick } from "svelte";+ import { musicPlayer } from "$lib/study-music/player-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { lyricsStore } from "$lib/study-music/lyrics-store.svelte";+ import { t } from "$lib/i18n";++ let containerEl = $state<HTMLDivElement | null>(null);+ let lineRefs: HTMLLIElement[] = [];++ const trackId = $derived(musicPlayer.currentTrack?.id ?? null);+ const activeIdx = $derived(+ lyricsStore.lines.length > 0+ ? lyricsStore.activeIndex(musicPlayer.currentTime)+ : -1,+ );++ $effect(() => {+ if (!musicUI.lyricsOpen) return;+ if (trackId === null) {+ lyricsStore.reset();+ return;+ }+ void lyricsStore.loadFor(trackId);+ });++ $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" });+ }+ });+ });++ function close() {+ musicUI.closeLyrics();+ }++ function refresh() {+ if (trackId !== null) {+ void lyricsStore.loadFor(trackId, true);+ }+ }++ onMount(() => {+ if (typeof document === "undefined") return;+ const handler = (e: KeyboardEvent) => {+ if (!musicUI.lyricsOpen) return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.isContentEditable)+ )+ return;+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ close();+ }+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ });+</script>++{#if musicUI.lyricsOpen}+ <aside class="lyrics-panel" role="complementary">+ <header class="head">+ <h3>{$t("study.music.lyrics_title")}</h3>+ <div class="actions">+ <button+ type="button"+ class="ico"+ onclick={refresh}+ title={$t("study.music.lyrics_refresh") as string}+ aria-label={$t("study.music.lyrics_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"+ onclick={close}+ aria-label={$t("study.common.close") as string}+ >×</button>+ </div>+ </header>++ {#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>+ </div>+ {:else if lyricsStore.notFound}+ <div class="empty">+ <p>{$t("study.music.lyrics_not_found")}</p>+ <p class="muted">{$t("study.music.lyrics_lrclib_hint")}</p>+ </div>+ {:else if lyricsStore.lines.length > 0}+ <div bind:this={containerEl} class="scroll synced">+ <ul class="lines">+ {#each lyricsStore.lines as line, i (i)}+ <li+ bind:this={lineRefs[i]}+ class="line"+ class:active={i === activeIdx}+ class:past={i < activeIdx}+ >+ {line.text || "♪"}+ </li>+ {/each}+ </ul>+ </div>+ {:else if lyricsStore.plain}+ <div class="scroll plain">+ {#each lyricsStore.plain.split(/\r?\n/) as line, i (i)}+ <p class="plain-line">{line || " "}</p>+ {/each}+ </div>+ {/if}++ {#if lyricsStore.source}+ <footer class="foot">+ <span>{$t("study.music.lyrics_source", { source: lyricsStore.source })}</span>+ </footer>+ {/if}+ </aside>+{/if}++<style>+ .lyrics-panel {+ position: fixed;+ top: 14px;+ right: 14px;+ bottom: 96px;+ width: min(420px, 92vw);+ z-index: 95;+ background: rgb(20, 20, 20);+ color: rgba(255, 255, 255, 0.95);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 14px;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 14px 16px;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }+ .head h3 {+ margin: 0;+ font-size: 13px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: rgba(255, 255, 255, 0.85);+ }+ .actions { display: inline-flex; gap: 4px; }+ .ico {+ width: 28px;+ height: 28px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 16px;+ line-height: 1;+ cursor: pointer;+ }+ .ico:hover { color: white; background: rgba(255, 255, 255, 0.08); }+ .scroll {+ flex: 1;+ overflow-y: auto;+ padding: 16px 22px 32px;+ scrollbar-width: thin;+ }+ .lines {+ list-style: none;+ margin: 0;+ padding: 30vh 0;+ display: flex;+ flex-direction: column;+ gap: 18px;+ }+ .line {+ 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;+ transform-origin: left;+ }+ .line.past {+ color: rgba(255, 255, 255, 0.25);+ }+ .line.active {+ color: white;+ font-weight: 700;+ font-size: 22px;+ transform: scale(1.02);+ }+ .plain-line {+ margin: 0 0 10px;+ font-size: 14px;+ line-height: 1.6;+ color: rgba(255, 255, 255, 0.85);+ }+ .empty,+ .loading {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 8px;+ align-items: center;+ justify-content: center;+ padding: 24px;+ color: rgba(255, 255, 255, 0.5);+ 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;+ }+ @keyframes spin {+ to { transform: rotate(360deg); }+ }+ .foot {+ padding: 8px 14px;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ color: rgba(255, 255, 255, 0.35);+ font-size: 10px;+ text-align: right;+ }+</style>diff --git a/src/lib/study-music-components/MusicSidebar.svelte b/src/lib/study-music-components/MusicSidebar.sveltenew file mode 100644index 00000000..f57e62b0--- /dev/null+++ b/src/lib/study-music-components/MusicSidebar.svelte@@ -0,0 +1,434 @@+<script lang="ts">+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { playlistsStore } from "$lib/study-music/playlists-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import AboutLink from "./AboutLink.svelte";++ type NavItem = {+ href: string;+ labelKey: string;+ icon: string;+ match: "exact" | "prefix";+ };++ const ITEMS: NavItem[] = [+ {+ href: "/study/music",+ labelKey: "study.music.nav_home",+ icon: "M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M9 22V12h6v10",+ match: "exact",+ },+ {+ href: "/study/music/search",+ labelKey: "study.music.nav_search",+ icon: "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.35-4.35",+ match: "prefix",+ },+ {+ href: "/study/music/library",+ labelKey: "study.music.nav_library",+ icon: "M4 19.5A2.5 2.5 0 0 1 6.5 17H20 M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z",+ match: "prefix",+ },+ {+ href: "/study/music/albums",+ labelKey: "study.music.nav_albums",+ icon: "M9 18V5l12-2v13 M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M18 19a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",+ match: "prefix",+ },+ {+ href: "/study/music/artists",+ labelKey: "study.music.nav_artists",+ icon: "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2 M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0z",+ match: "prefix",+ },+ {+ href: "/study/music/playlists",+ labelKey: "study.music.nav_playlists",+ icon: "M3 6h18 M3 12h18 M3 18h12",+ match: "prefix",+ },+ {+ href: "/study/music/genres",+ labelKey: "study.music.nav_genres",+ icon: "M4 4h16v16H4z M4 9h16 M4 15h16 M9 4v16 M15 4v16",+ match: "prefix",+ },+ {+ href: "/study/music/favorites",+ labelKey: "study.music.nav_favorites",+ icon: "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",+ match: "prefix",+ },+ {+ href: "/study/music/activity",+ labelKey: "study.music.nav_activity",+ icon: "M3 12h4l3-9 4 18 3-9h4",+ 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/youtube",+ labelKey: "study.music.nav_youtube",+ icon: "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 M9.75 15.02l5.75-3.27-5.75-3.27v6.54z",+ match: "prefix",+ },+ {+ href: "/study/music/spotify",+ labelKey: "study.music.nav_spotify",+ icon: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M7.5 14.5c2.5-1.5 6.5-1.8 9.5-.5 M7 11c3-1.8 8-2 11.5-.5 M6.5 7.5c4-2 9.5-2 13 0",+ match: "prefix",+ },+ {+ href: "/study/music/soundcloud",+ labelKey: "study.music.nav_soundcloud",+ icon: "M2 16h2 M5 14h2 M8 13h2 M11 13h2 M14 13c0-2 2-4 5-4s4 2 4 4-1 4-4 4h-9",+ match: "prefix",+ },+ ];++ function isActive(href: string, match: "exact" | "prefix", url: URL): boolean {+ if (match === "exact") return url.pathname === href;+ return url.pathname === href || url.pathname.startsWith(href + "/");+ }++ let creatingPlaylist = $state(false);+ let newPlaylistName = $state("");+ let newPlaylistRef = $state<HTMLInputElement | null>(null);+ let busy = $state(false);++ function startCreate() {+ creatingPlaylist = true;+ newPlaylistName = "";+ queueMicrotask(() => newPlaylistRef?.focus());+ }++ async function confirmCreate() {+ const trimmed = newPlaylistName.trim();+ if (!trimmed || busy) return;+ busy = true;+ try {+ const id = await playlistsStore.create(trimmed);+ creatingPlaylist = false;+ newPlaylistName = "";+ if (id) goto(`/study/music/playlists/${id}`);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ function cancelCreate() {+ creatingPlaylist = false;+ newPlaylistName = "";+ }+</script>++<aside class="music-sidebar">+ <header class="brand">+ <span class="brand-text">{$t("study.music.title")}</span>+ </header>++ <nav class="nav" aria-label={$t("study.music.nav_aria") as string}>+ {#each ITEMS as item (item.href)}+ {@const active = isActive(item.href, item.match, $page.url)}+ <a+ href={item.href}+ class="nav-item"+ class:active+ aria-current={active ? "page" : undefined}+ >+ <span class="indicator" aria-hidden="true"></span>+ <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={item.icon}></path>+ </svg>+ <span class="label">{$t(item.labelKey)}</span>+ </a>+ {/each}+ </nav>++ <div class="divider" aria-hidden="true"></div>++ <div class="playlists-section">+ <header class="ps-head">+ <span class="ps-title">{$t("study.music.playlists_section")}</span>+ <button+ type="button"+ class="ps-add"+ onclick={startCreate}+ disabled={creatingPlaylist}+ aria-label={$t("study.music.new_playlist") as string}+ title={$t("study.music.new_playlist") as string}+ >+</button>+ </header>+ {#if creatingPlaylist}+ <div class="new-row">+ <input+ type="text"+ bind:this={newPlaylistRef}+ bind:value={newPlaylistName}+ placeholder={$t("study.music.playlist_name_placeholder")}+ onkeydown={(e) => {+ if (e.key === "Enter") confirmCreate();+ else if (e.key === "Escape") {+ e.stopPropagation();+ cancelCreate();+ }+ }}+ onblur={() => {+ if (newPlaylistName.trim()) confirmCreate();+ else cancelCreate();+ }}+ />+ </div>+ {/if}+ {#if playlistsStore.list.length === 0 && !creatingPlaylist}+ <p class="ps-empty">{$t("study.music.no_playlists_yet")}</p>+ {:else}+ <ul class="playlist-list">+ {#each playlistsStore.list as p (p.id)}+ {@const href = `/study/music/playlists/${p.id}`}+ {@const active = $page.url.pathname === href}+ <li>+ <a class="playlist-item" class:active {href}>+ <span class="playlist-name">{p.name}</span>+ <span class="playlist-count">{p.track_count}</span>+ </a>+ </li>+ {/each}+ </ul>+ {/if}+ </div>++ <div class="footer-nav">+ <button+ type="button"+ class="footer-item"+ onclick={() => musicUI.openRoots()}+ title={$t("study.music.manage_folders") as string}+ >+ <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="M3 7v13h18V9h-9l-2-2H3z"/>+ <line x1="12" y1="13" x2="12" y2="17"/>+ <line x1="10" y1="15" x2="14" y2="15"/>+ </svg>+ <span>{$t("study.music.manage_folders")}</span>+ </button>+ <AboutLink variant="footer" />+ </div>+</aside>++<style>+ .music-sidebar {+ display: grid;+ grid-template-rows: auto auto auto 1fr auto;+ gap: 12px;+ padding: 16px 12px;+ height: 100%;+ overflow: hidden;+ background: color-mix(in oklab, var(--primary) 96%, black);+ border-right: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent);+ scrollbar-width: thin;+ }+ .brand {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 4px 12px 8px;+ }+ .brand-text {+ font-size: 13px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.16em;+ color: var(--tertiary);+ }+ .nav {+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .nav-item {+ position: relative;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 9px 14px 9px 16px;+ color: var(--tertiary);+ font-size: 13px;+ font-weight: 500;+ text-decoration: none;+ border-radius: 6px;+ transition: color 120ms ease, background 120ms ease;+ }+ .nav-item:hover {+ color: var(--secondary);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .nav-item.active {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ }+ .indicator {+ position: absolute;+ left: 0;+ top: 8px;+ bottom: 8px;+ width: 3px;+ border-radius: 0 3px 3px 0;+ background: transparent;+ transition: background 120ms ease;+ }+ .nav-item.active .indicator {+ background: var(--accent);+ }+ .label {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .divider {+ height: 1px;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ margin: 4px 8px;+ }+ .playlists-section {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ }+ .ps-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 4px 12px;+ }+ .ps-title {+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--tertiary);+ }+ .ps-add {+ width: 22px;+ height: 22px;+ padding: 0;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 50%;+ color: var(--tertiary);+ font-size: 14px;+ line-height: 1;+ cursor: pointer;+ transition: color 120ms ease, border-color 120ms ease;+ }+ .ps-add:hover:not(:disabled) {+ color: var(--accent);+ border-color: var(--accent);+ }+ .ps-add:disabled { opacity: 0.5; cursor: default; }+ .ps-empty {+ margin: 4px 12px 8px;+ color: var(--tertiary);+ font-size: 11px;+ line-height: 1.4;+ }+ .new-row {+ padding: 4px 12px;+ }+ .new-row input {+ width: 100%;+ padding: 6px 10px;+ border: 1px solid var(--accent);+ border-radius: 6px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ outline: none;+ }+ .playlist-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .playlist-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 6px 14px;+ color: var(--tertiary);+ font-size: 12px;+ text-decoration: none;+ border-radius: 4px;+ transition: color 120ms ease, background 120ms ease;+ }+ .playlist-item:hover {+ color: var(--secondary);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .playlist-item.active {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .playlist-name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .playlist-count {+ font-size: 10px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ }+ .footer-nav {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding-top: 12px;+ padding-bottom: 4px;+ border-top: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ background: color-mix(in oklab, var(--primary) 96%, black);+ }+ .footer-item {+ display: flex;+ align-items: center;+ gap: 12px;+ width: 100%;+ padding: 8px 14px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: var(--tertiary);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ text-align: left;+ cursor: pointer;+ transition: color 120ms ease, background 120ms ease;+ }+ .footer-item:hover {+ color: var(--secondary);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+</style>diff --git a/src/lib/study-music-components/MusicThemePanel.svelte b/src/lib/study-music-components/MusicThemePanel.sveltenew file mode 100644index 00000000..30a27deb--- /dev/null+++ b/src/lib/study-music-components/MusicThemePanel.svelte@@ -0,0 +1,308 @@+<script lang="ts">+ import { musicTheme, PRESET_ACCENTS, type MusicThemePreset } from "$lib/study-music/theme-store.svelte";+ import { t } from "$lib/i18n";++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ const PRESETS: MusicThemePreset[] = [+ "default",+ "indigo",+ "spotify",+ "purple",+ "amber",+ "custom",+ ];++ function previewColor(preset: MusicThemePreset): string {+ if (preset === "custom") return musicTheme.accent || "#888";+ if (preset === "default") return "var(--accent)";+ return PRESET_ACCENTS[preset as Exclude<MusicThemePreset, "custom">];+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }+</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.music_theme_title")}</h3>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.music_theme_subtitle")}</p>++ <section class="row">+ <span class="label">{$t("study.music.music_theme_preset")}</span>+ <div class="presets">+ {#each PRESETS as p (p)}+ <button+ type="button"+ class="preset"+ class:active={musicTheme.preset === p}+ onclick={() => musicTheme.setPreset(p)}+ >+ <span class="swatch" style:background={previewColor(p)}></span>+ <span class="preset-name">{$t(`study.music.music_theme_preset_${p}`)}</span>+ </button>+ {/each}+ </div>+ </section>++ {#if musicTheme.preset === "custom" || musicTheme.preset !== "default"}+ <section class="row">+ <span class="label">{$t("study.music.music_theme_accent")}</span>+ <div class="color-row">+ <input+ type="color"+ class="picker"+ value={musicTheme.accent || PRESET_ACCENTS.indigo}+ oninput={(e) => musicTheme.setAccent((e.currentTarget as HTMLInputElement).value)}+ />+ <input+ type="text"+ class="hex"+ value={musicTheme.accent}+ oninput={(e) => {+ const v = (e.currentTarget as HTMLInputElement).value;+ if (/^#[0-9a-f]{6}$/i.test(v)) musicTheme.setAccent(v);+ }}+ placeholder="#6366f1"+ />+ </div>+ </section>+ {/if}++ <section class="row">+ <span class="label">{$t("study.music.music_theme_use_dominant")}</span>+ <div class="dom-toggle">+ <button+ type="button"+ class="seg"+ class:active={!musicTheme.useDominant}+ onclick={() => { if (musicTheme.useDominant) musicTheme.toggleUseDominant(); }}+ >{$t("study.music.music_theme_dominant_off")}</button>+ <button+ type="button"+ class="seg"+ class:active={musicTheme.useDominant}+ onclick={() => { if (!musicTheme.useDominant) musicTheme.toggleUseDominant(); }}+ >{$t("study.music.music_theme_dominant_on")}</button>+ </div>+ </section>++ <div class="actions">+ <button type="button" class="reset" onclick={() => musicTheme.reset()}>+ {$t("study.music.music_theme_reset")}+ </button>+ <button type="button" class="done" onclick={onClose}>+ {$t("study.common.close")}+ </button>+ </div>+ </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(560px, 92vw);+ max-height: 86vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head {+ position: relative;+ padding: 18px 20px 8px;+ }+ .head h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ }+ .close {+ position: absolute;+ top: 12px;+ right: 14px;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ }+ .body {+ padding: 8px 20px 20px;+ display: flex;+ flex-direction: column;+ gap: 22px;+ }+ .hint {+ margin: 0;+ color: rgba(255, 255, 255, 0.55);+ font-size: 13px;+ line-height: 1.5;+ }+ .row {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }+ .label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: rgba(255, 255, 255, 0.5);+ }+ .presets {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));+ gap: 6px;+ }+ .preset {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 10px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 8px;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ text-align: left;+ transition: border-color 120ms ease, background 120ms ease;+ }+ .preset:hover { background: rgba(255, 255, 255, 0.08); }+ .preset.active {+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ }+ .swatch {+ flex-shrink: 0;+ width: 16px;+ height: 16px;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.4);+ }+ .preset-name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .color-row {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .picker {+ width: 48px;+ height: 36px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ background: transparent;+ cursor: pointer;+ }+ .hex {+ flex: 1;+ padding: 8px 10px;+ 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;+ }+ .hex:focus { border-color: var(--accent); }+ .dom-toggle {+ display: inline-flex;+ background: rgba(0, 0, 0, 0.3);+ border-radius: 999px;+ padding: 3px;+ align-self: flex-start;+ }+ .seg {+ padding: 6px 14px;+ border: 0;+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.6);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .seg.active {+ background: var(--accent);+ color: var(--on-accent, white);+ }+ .actions {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ padding-top: 8px;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ }+ .reset {+ padding: 8px 14px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.65);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .reset:hover {+ color: rgba(255, 255, 255, 0.95);+ border-color: rgba(255, 255, 255, 0.25);+ }+ .done {+ padding: 8px 18px;+ border: 0;+ border-radius: 999px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 13px;+ font-weight: 700;+ cursor: pointer;+ }+</style>diff --git a/src/lib/study-music-components/PlayerBar.svelte b/src/lib/study-music-components/PlayerBar.sveltenew file mode 100644index 00000000..694929e0--- /dev/null+++ b/src/lib/study-music-components/PlayerBar.svelte@@ -0,0 +1,366 @@+<script lang="ts">+ 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";++ const t_ = $derived(musicPlayer.currentTrack);++ function favoriteToggle() {+ if (!t_) return;+ void musicPlayer.toggleFavorite(t_.id);+ }+</script>++{#if t_}+ <div class="player-bar" role="region" aria-label={$t("study.music.player_aria")}>+ <div class="left">+ <div class="cover-mini">+ <CoverImage+ src={t_.cover_path}+ alt={t_.title ?? t_.path}+ fallbackSeed={t_.album ?? t_.title}+ rounded="md"+ trackId={t_.id}+ />+ </div>+ <div class="info">+ <span class="title">{t_.title ?? t_.path}</span>+ {#if t_.artist}+ <span class="artist">{t_.artist}</span>+ {/if}+ </div>+ <button+ type="button"+ class="fav"+ class:on={t_.favorite}+ onclick={favoriteToggle}+ aria-label={t_.favorite+ ? ($t("study.music.unfavorite") as string)+ : ($t("study.music.favorite") as string)}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill={t_.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>+ </div>++ <div class="center">+ <div class="controls">+ <button+ type="button"+ class="ctrl-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="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <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="ctrl-btn"+ onclick={() => musicPlayer.prev()}+ aria-label={$t("study.music.prev") as string}+ title={$t("study.music.prev") as string}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M19 20L9 12l10-8v16zM5 4h2v16H5z"/></svg>+ </button>+ <button+ type="button"+ class="play-btn"+ onclick={() => musicPlayer.togglePlay()}+ aria-label={musicPlayer.paused+ ? ($t("study.music.play") as string)+ : ($t("study.music.pause") as string)}+ >+ {#if musicPlayer.loading}+ <span class="spinner" aria-hidden="true"></span>+ {:else if musicPlayer.paused}+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>+ {:else}+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><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="ctrl-btn"+ onclick={() => musicPlayer.next()}+ aria-label={$t("study.music.next") as string}+ title={$t("study.music.next") as string}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M5 4l10 8-10 8V4zm12 0h2v16h-2z"/></svg>+ </button>+ <button+ type="button"+ class="ctrl-btn"+ class:active={musicPlayer.repeat !== "off"}+ onclick={() => musicPlayer.cycleRepeat()}+ aria-label={$t("study.music.repeat") as string}+ title={$t("study.music.repeat") as string}+ >+ {#if musicPlayer.repeat === "one"}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <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"/>+ <text x="11" y="14" font-size="9" font-weight="bold" fill="currentColor" stroke="none">1</text>+ </svg>+ {:else}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <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"/>+ </svg>+ {/if}+ </button>+ </div>+ <ProgressBar+ current={musicPlayer.currentTime}+ duration={musicPlayer.duration}+ onSeek={(s) => musicPlayer.seek(s)}+ />+ </div>++ <div class="right">+ <button+ type="button"+ class="ctrl-btn"+ class:active={musicUI.rightbarTab === "info"}+ onclick={() => musicUI.toggleInfo()}+ aria-label={$t("study.music.tab_info") as string}+ title={$t("study.music.tab_info") 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">+ <circle cx="12" cy="12" r="9"/>+ <line x1="12" y1="8" x2="12" y2="12"/>+ <line x1="12" y1="16" x2="12.01" y2="16"/>+ </svg>+ </button>+ <button+ type="button"+ class="ctrl-btn"+ class:active={musicUI.lyricsOpen}+ onclick={() => musicUI.toggleLyrics()}+ aria-label={$t("study.music.lyrics_title") as string}+ title={$t("study.music.lyrics_title") 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">+ <path d="M9 18V5l12-2v13"/>+ <circle cx="6" cy="18" r="3"/>+ <circle cx="18" cy="16" r="3"/>+ <line x1="3" y1="9" x2="9" y2="9"/>+ <line x1="3" y1="13" x2="7" y2="13"/>+ </svg>+ </button>+ <button+ type="button"+ class="ctrl-btn"+ class:active={musicPlayer.eqEnabled}+ onclick={() => musicUI.toggleEqualizer()}+ aria-label={$t("study.music.eq_title") as string}+ title={$t("study.music.eq_title") 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" aria-hidden="true">+ <line x1="4" y1="21" x2="4" y2="14"/>+ <line x1="4" y1="10" x2="4" y2="3"/>+ <line x1="12" y1="21" x2="12" y2="12"/>+ <line x1="12" y1="8" x2="12" y2="3"/>+ <line x1="20" y1="21" x2="20" y2="16"/>+ <line x1="20" y1="12" x2="20" y2="3"/>+ <line x1="1" y1="14" x2="7" y2="14"/>+ <line x1="9" y1="8" x2="15" y2="8"/>+ <line x1="17" y1="16" x2="23" y2="16"/>+ </svg>+ </button>+ <button+ type="button"+ class="ctrl-btn"+ class:active={musicUI.queueOpen}+ onclick={() => musicUI.toggleQueue()}+ aria-label={$t("study.music.queue_toggle") as string}+ title={$t("study.music.queue_toggle") 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" 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>+ <VolumeControl />+ </div>+ </div>+{/if}++<style>+ .player-bar {+ display: grid;+ grid-template-columns: minmax(0, 28%) minmax(0, 44%) minmax(0, 28%);+ align-items: center;+ gap: 16px;+ width: 100%;+ height: 80px;+ padding: 0 18px;+ background: color-mix(in oklab, var(--primary) 90%, var(--button-elevated));+ border-top: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ backdrop-filter: blur(6px);+ -webkit-backdrop-filter: blur(6px);+ }+ .left {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ }+ .cover-mini {+ flex-shrink: 0;+ width: 56px;+ height: 56px;+ box-shadow: 0 2px 8px color-mix(in oklab, black 20%, transparent);+ border-radius: 6px;+ overflow: hidden;+ }+ .info {+ display: flex;+ flex-direction: column;+ min-width: 0;+ overflow: hidden;+ flex: 1;+ }+ .title {+ font-size: 13px;+ font-weight: 600;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .artist {+ font-size: 11px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .fav {+ flex-shrink: 0;+ width: 28px;+ height: 28px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: var(--tertiary);+ cursor: pointer;+ display: grid;+ place-items: center;+ transition: color 120ms ease, background 120ms ease;+ }+ .fav:hover { color: var(--secondary); background: color-mix(in oklab, var(--accent) 8%, transparent); }+ .fav.on { color: var(--accent); }++ .center {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }+ .controls {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 14px;+ }+ .ctrl-btn {+ width: 28px;+ height: 28px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 4px;+ color: var(--tertiary);+ cursor: pointer;+ display: grid;+ place-items: center;+ transition: color 120ms ease, background 120ms ease, transform 100ms ease;+ }+ .ctrl-btn:hover {+ color: var(--secondary);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .ctrl-btn.active {+ color: var(--accent);+ }+ .ctrl-btn:active {+ transform: scale(0.92);+ }+ .play-btn {+ width: 36px;+ height: 36px;+ padding: 0;+ border: 0;+ border-radius: 50%;+ background: var(--secondary);+ color: var(--primary);+ cursor: pointer;+ display: grid;+ place-items: center;+ box-shadow: 0 2px 8px color-mix(in oklab, var(--secondary) 20%, transparent);+ transition: transform 100ms ease, background 120ms ease;+ }+ .play-btn:hover {+ transform: scale(1.05);+ background: var(--accent);+ color: var(--on-accent, white);+ }+ .play-btn:active {+ transform: scale(0.96);+ }+ .spinner {+ display: block;+ width: 16px;+ height: 16px;+ border: 2px solid color-mix(in oklab, currentColor 30%, transparent);+ border-top-color: currentColor;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }+ @keyframes spin {+ to { transform: rotate(360deg); }+ }++ .right {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 12px;+ }++ @media (max-width: 760px) {+ .player-bar {+ grid-template-columns: 1fr auto;+ height: auto;+ padding: 8px 12px;+ }+ .right { display: none; }+ }+ @media (prefers-reduced-motion: reduce) {+ .play-btn, .ctrl-btn, .fav, .spinner {+ transition: none;+ animation: none;+ }+ }+</style>diff --git a/src/lib/study-music-components/ProgressBar.svelte b/src/lib/study-music-components/ProgressBar.sveltenew file mode 100644index 00000000..239f35b2--- /dev/null+++ b/src/lib/study-music-components/ProgressBar.svelte@@ -0,0 +1,142 @@+<script lang="ts">+ import { fmtSecondsToTime } from "$lib/study-music/format";++ type Props = {+ current: number;+ duration: number;+ onSeek: (seconds: number) => void;+ showTime?: boolean;+ };++ let { current, duration, onSeek, showTime = true }: Props = $props();++ let dragging = $state(false);+ let dragValue = $state(0);+ let trackEl = $state<HTMLDivElement | null>(null);++ const ratio = $derived.by(() => {+ if (dragging) return dragValue;+ if (!duration || duration <= 0 || !Number.isFinite(duration)) return 0;+ return Math.max(0, Math.min(1, current / duration));+ });++ const displayTime = $derived(dragging ? dragValue * duration : current);++ function ratioFromEvent(e: PointerEvent): number {+ if (!trackEl) return 0;+ const rect = trackEl.getBoundingClientRect();+ const x = e.clientX - rect.left;+ return Math.max(0, Math.min(1, x / rect.width));+ }++ function onPointerDown(e: PointerEvent) {+ if (!duration || duration <= 0) return;+ e.preventDefault();+ dragging = true;+ dragValue = ratioFromEvent(e);+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);+ }++ function onPointerMove(e: PointerEvent) {+ if (!dragging) return;+ dragValue = ratioFromEvent(e);+ }++ function onPointerUp(e: PointerEvent) {+ if (!dragging) return;+ dragging = false;+ onSeek(dragValue * duration);+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);+ }+</script>++<div class="progress-row">+ {#if showTime}+ <span class="t left">{fmtSecondsToTime(displayTime)}</span>+ {/if}+ <div+ class="track"+ bind:this={trackEl}+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ role="slider"+ aria-valuemin="0"+ aria-valuemax={duration || 0}+ aria-valuenow={current}+ tabindex="0"+ >+ <div class="bar"></div>+ <div class="filled" style:width="{ratio * 100}%"></div>+ <div class="thumb" style:left="{ratio * 100}%"></div>+ </div>+ {#if showTime}+ <span class="t right">{fmtSecondsToTime(duration)}</span>+ {/if}+</div>++<style>+ .progress-row {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ }+ .t {+ font-size: 11px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ min-width: 36px;+ text-align: center;+ }+ .track {+ position: relative;+ flex: 1;+ height: 14px;+ cursor: pointer;+ display: flex;+ align-items: center;+ }+ .track:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ border-radius: 4px;+ }+ .bar {+ position: absolute;+ inset: 50% 0 auto;+ transform: translateY(-50%);+ height: 4px;+ width: 100%;+ background: color-mix(in oklab, currentColor 20%, transparent);+ border-radius: 2px;+ }+ .filled {+ position: absolute;+ inset: 50% auto auto 0;+ transform: translateY(-50%);+ height: 4px;+ background: var(--secondary);+ border-radius: 2px;+ pointer-events: none;+ }+ .track:hover .filled {+ background: var(--accent);+ }+ .thumb {+ position: absolute;+ top: 50%;+ width: 12px;+ height: 12px;+ margin-left: -6px;+ margin-top: -6px;+ background: var(--secondary);+ border-radius: 50%;+ pointer-events: none;+ opacity: 0;+ transition: opacity 120ms ease;+ }+ .track:hover .thumb {+ opacity: 1;+ }+</style>diff --git a/src/lib/study-music-components/QobuzPanel.svelte b/src/lib/study-music-components/QobuzPanel.sveltenew file mode 100644index 00000000..73aacd16--- /dev/null+++ b/src/lib/study-music-components/QobuzPanel.svelte@@ -0,0 +1,305 @@+<script lang="ts">+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ type QobuzSettings = {+ email: string;+ format_id: number;+ configured: boolean;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ let settings = $state<QobuzSettings | null>(null);+ let email = $state("");+ let password = $state("");+ let showPassword = $state(false);+ let busy = $state(false);+ let testing = $state(false);++ async function load() {+ try {+ settings = await pluginInvoke<QobuzSettings>("study", "study:music:qobuz:get_settings");+ } catch {+ settings = null;+ }+ }++ $effect(() => {+ if (open) {+ void load();+ email = "";+ password = "";+ showPassword = false;+ }+ });++ async function connect() {+ const trimmedEmail = email.trim();+ const pwd = password;+ if (!trimmedEmail || !pwd || busy) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:qobuz:set_credentials", {+ email: trimmedEmail,+ password: pwd,+ });+ testing = true;+ try {+ await pluginInvoke<{ ok: boolean }>("study", "study:music:qobuz:test");+ showToast("success", $t("study.music.qobuz_connected") as string);+ password = "";+ await load();+ } catch (e) {+ showToast(+ "error",+ $t("study.music.qobuz_test_failed", {+ error: e instanceof Error ? e.message : String(e),+ }) as string,+ );+ await load();+ } finally {+ testing = false;+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function disconnect() {+ if (busy) return;+ if (!window.confirm($t("study.music.qobuz_disconnect_confirm") as string)) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:qobuz:clear");+ showToast("success", $t("study.music.qobuz_disconnected") as string);+ await load();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function retest() {+ if (busy || testing) return;+ testing = true;+ try {+ await pluginInvoke<{ ok: boolean }>("study", "study:music:qobuz:test");+ showToast("success", $t("study.music.qobuz_test_ok") as string);+ } catch (e) {+ showToast(+ "error",+ $t("study.music.qobuz_test_failed", {+ error: e instanceof Error ? e.message : String(e),+ }) as string,+ );+ } finally {+ testing = false;+ }+ }++ function maskedEmail(addr: string): string {+ if (!addr) return "";+ const at = addr.indexOf("@");+ if (at < 1) return addr;+ const user = addr.slice(0, at);+ const domain = addr.slice(at);+ if (user.length <= 2) return user[0] + "•" + domain;+ return user[0] + "•".repeat(Math.min(user.length - 2, 6)) + user[user.length - 1] + domain;+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }++ const isConfigured = $derived(settings?.configured ?? false);+</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">+ <div class="head-text">+ <h3>{$t("study.music.qobuz_title")}</h3>+ {#if isConfigured}+ <span class="state on">✓ {$t("study.music.qobuz_state_connected")}</span>+ {:else}+ <span class="state off">{$t("study.music.qobuz_state_disconnected")}</span>+ {/if}+ </div>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ {#if isConfigured}+ <div class="connected-block">+ <div class="connected-line">+ <span class="connected-label">{$t("study.music.qobuz_signed_in_as")}</span>+ <span class="connected-email">{maskedEmail(settings?.email ?? "")}</span>+ </div>+ <p class="hint">{$t("study.music.qobuz_connected_hint")}</p>+ <div class="row-actions">+ <button type="button" class="cta-secondary" onclick={retest} disabled={busy || testing}>+ {testing ? $t("study.music.qobuz_testing") : $t("study.music.qobuz_test_again")}+ </button>+ <button type="button" class="link danger" onclick={disconnect} disabled={busy}>+ {$t("study.music.qobuz_disconnect")}+ </button>+ </div>+ </div>+ {:else}+ <p class="hint">{$t("study.music.qobuz_intro")}</p>++ <label class="field">+ <span>{$t("study.music.qobuz_email_label")}</span>+ <input+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ autocomplete="email"+ disabled={busy}+ onkeydown={(e) => { if (e.key === "Enter") connect(); }}+ />+ </label>++ <label class="field">+ <span>{$t("study.music.qobuz_password_label")}</span>+ <div class="pwd-wrap">+ {#if showPassword}+ <input+ type="text"+ bind:value={password}+ autocomplete="current-password"+ disabled={busy}+ onkeydown={(e) => { if (e.key === "Enter") connect(); }}+ />+ {:else}+ <input+ type="password"+ bind:value={password}+ autocomplete="current-password"+ disabled={busy}+ onkeydown={(e) => { if (e.key === "Enter") connect(); }}+ />+ {/if}+ <button+ type="button"+ class="pwd-toggle"+ onclick={() => (showPassword = !showPassword)}+ aria-label={$t(showPassword ? "study.music.qobuz_pwd_hide" : "study.music.qobuz_pwd_show") as string}+ tabindex={-1}+ >+ {showPassword ? "🙈" : "👁"}+ </button>+ </div>+ </label>++ <p class="privacy">{$t("study.music.qobuz_privacy")}</p>++ <div class="row-actions">+ <button+ type="button"+ class="cta"+ onclick={connect}+ disabled={busy || !email.trim() || !password}+ >+ {busy ? $t("study.music.qobuz_connecting") : $t("study.music.qobuz_connect")}+ </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(520px, 92vw);+ max-height: 88vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 18px 20px 8px; }+ .head-text { display: flex; flex-direction: column; gap: 4px; }+ .head h3 { margin: 0; font-size: 16px; font-weight: 800; }+ .state { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; font-size: 11px; font-weight: 600; width: fit-content; }+ .state.on { background: rgba(34, 197, 94, 0.15); color: rgb(74, 222, 128); }+ .state.off { background: rgba(255, 255, 255, 0.06); color: rgba(255, 255, 255, 0.45); }+ .close { width: 28px; height: 28px; background: transparent; border: 0; border-radius: 50%; color: rgba(255, 255, 255, 0.5); font-size: 18px; cursor: pointer; flex-shrink: 0; }+ .close:hover { color: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.06); }+ .body { padding: 8px 20px 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }+ .hint { margin: 0; color: rgba(255, 255, 255, 0.65); font-size: 13px; line-height: 1.5; }++ .connected-block { display: flex; flex-direction: column; gap: 10px; }+ .connected-line { display: flex; align-items: baseline; gap: 8px; padding: 10px 12px; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 8px; }+ .connected-label { font-size: 11px; color: rgba(255, 255, 255, 0.5); text-transform: uppercase; letter-spacing: 0.06em; }+ .connected-email { font-size: 13px; font-weight: 600; font-family: ui-monospace, monospace; }++ .field { display: flex; flex-direction: column; gap: 4px; }+ .field span { font-size: 11px; color: rgba(255, 255, 255, 0.55); text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600; }+ .field input { padding: 10px 12px; 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: inherit; font-size: 13px; outline: none; }+ .field input:focus { border-color: var(--accent); }+ .field input:disabled { opacity: 0.5; }++ .pwd-wrap { position: relative; }+ .pwd-wrap input { width: 100%; padding-right: 40px; box-sizing: border-box; }+ .pwd-toggle {+ position: absolute;+ right: 6px; top: 50%;+ transform: translateY(-50%);+ width: 28px; height: 28px;+ background: transparent; border: 0;+ color: rgba(255, 255, 255, 0.55);+ cursor: pointer;+ border-radius: 4px;+ font-size: 14px;+ display: grid; place-items: center;+ }+ .pwd-toggle:hover { background: rgba(255, 255, 255, 0.08); color: rgba(255, 255, 255, 0.95); }++ .privacy { margin: 0; font-size: 11px; color: rgba(255, 255, 255, 0.5); line-height: 1.5; }++ .row-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }+ .cta { padding: 9px 18px; border: 0; border-radius: 999px; background: var(--accent); color: var(--on-accent, white); font-family: inherit; font-size: 13px; font-weight: 700; cursor: pointer; }+ .cta:disabled { opacity: 0.5; cursor: default; }+ .cta-secondary { padding: 7px 14px; border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 999px; background: transparent; color: rgba(255, 255, 255, 0.95); font-family: inherit; font-size: 12px; cursor: pointer; }+ .cta-secondary:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }+ .cta-secondary:disabled { opacity: 0.4; cursor: default; }+ .link { background: transparent; border: 0; color: rgba(255, 255, 255, 0.5); font-family: inherit; font-size: 11px; cursor: pointer; padding: 0; font-weight: 600; }+ .link.danger:hover { color: rgb(248, 113, 113); }+ .link:disabled { opacity: 0.4; cursor: default; }+</style>diff --git a/src/lib/study-music-components/QualityPresetPanel.svelte b/src/lib/study-music-components/QualityPresetPanel.sveltenew file mode 100644index 00000000..1412fadb--- /dev/null+++ b/src/lib/study-music-components/QualityPresetPanel.svelte@@ -0,0 +1,219 @@+<script lang="ts">+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ type PresetEntry = {+ id: string;+ label: string;+ preset: unknown;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ let presets = $state<PresetEntry[]>([]);+ let currentId = $state<string | null>(null);+ let loading = $state(false);+ let saving = $state(false);++ const GROUPS: { headerKey: string; ids: string[] }[] = [+ { headerKey: "study.music.quality_group_recommended", ids: ["aac-192"] },+ { headerKey: "study.music.quality_group_compact", ids: ["mp3-128", "opus-160", "mp3-192"] },+ { headerKey: "study.music.quality_group_high", ids: ["aac-256", "mp3-320"] },+ { headerKey: "study.music.quality_group_lossless", ids: ["flac-cd", "flac-hires", "flac", "wav"] },+ ];++ const HINT_KEYS: Record<string, string> = {+ "mp3-128": "study.music.quality_hint_mp3_128",+ "mp3-192": "study.music.quality_hint_mp3_192",+ "mp3-320": "study.music.quality_hint_mp3_320",+ "aac-192": "study.music.quality_hint_aac_192",+ "aac-256": "study.music.quality_hint_aac_256",+ "opus-160": "study.music.quality_hint_opus_160",+ "flac": "study.music.quality_hint_flac",+ "flac-cd": "study.music.quality_hint_flac_cd",+ "flac-hires": "study.music.quality_hint_flac_hires",+ "wav": "study.music.quality_hint_wav",+ };++ async function load() {+ loading = true;+ try {+ const [listRes, getRes] = await Promise.all([+ pluginInvoke<{ presets: PresetEntry[] }>("study", "study:music:quality:list"),+ pluginInvoke<{ preset: unknown; label: string }>("study", "study:music:quality:get"),+ ]);+ presets = listRes.presets ?? [];+ const getJson = JSON.stringify(getRes.preset);+ const match = presets.find((p) => JSON.stringify(p.preset) === getJson);+ currentId = match?.id ?? null;+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ if (open) void load();+ });++ async function pick(entry: PresetEntry) {+ if (saving || entry.id === currentId) return;+ const previous = currentId;+ currentId = entry.id;+ saving = true;+ try {+ await pluginInvoke("study", "study:music:quality:set", { preset: entry.preset });+ showToast("success", $t("study.music.quality_saved", { label: entry.label }) as string);+ } catch (e) {+ currentId = previous;+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ saving = false;+ }+ }++ function findPreset(id: string): PresetEntry | undefined {+ return presets.find((p) => p.id === id);+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }++ const currentLabel = $derived(+ presets.find((p) => p.id === currentId)?.label ?? "—",+ );+</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">+ <div class="head-text">+ <h3>{$t("study.music.quality_title")}</h3>+ <span class="state on">{$t("study.music.quality_current", { label: currentLabel })}</span>+ </div>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.quality_intro")}</p>++ {#if loading}+ <div class="loading">{$t("study.common.loading")}</div>+ {:else}+ {#each GROUPS as group}+ <section class="group">+ <h4 class="group-title">{$t(group.headerKey)}</h4>+ <div class="cards">+ {#each group.ids as id}+ {@const entry = findPreset(id)}+ {#if entry}+ {@const isCurrent = currentId === id}+ <button+ type="button"+ class="card"+ class:selected={isCurrent}+ disabled={saving}+ onclick={() => pick(entry)}+ >+ <span class="card-title">+ <span>{entry.label}</span>+ {#if isCurrent}+ <svg class="check" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <polyline points="3 9 6.5 12.5 13 4" />+ </svg>+ {/if}+ </span>+ <span class="card-hint">{$t(HINT_KEYS[id])}</span>+ </button>+ {/if}+ {/each}+ </div>+ </section>+ {/each}+ {/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(620px, 92vw);+ max-height: 88vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 18px 20px 8px; }+ .head-text { display: flex; flex-direction: column; gap: 4px; }+ .head h3 { margin: 0; font-size: 16px; font-weight: 800; }+ .state { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; font-size: 11px; font-weight: 600; width: fit-content; }+ .state.on { background: rgba(34, 197, 94, 0.15); color: rgb(74, 222, 128); }+ .close { width: 28px; height: 28px; background: transparent; border: 0; border-radius: 50%; color: rgba(255, 255, 255, 0.5); font-size: 18px; cursor: pointer; flex-shrink: 0; }+ .close:hover { color: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.06); }+ .body { padding: 8px 20px 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 18px; }+ .hint { margin: 0; color: rgba(255, 255, 255, 0.65); font-size: 13px; line-height: 1.5; }+ .loading { padding: 24px; text-align: center; color: rgba(255, 255, 255, 0.5); font-size: 12px; }+ .group { display: flex; flex-direction: column; gap: 8px; }+ .group-title { margin: 0; font-size: 11px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: rgba(255, 255, 255, 0.45); }+ .cards { display: flex; flex-direction: column; gap: 6px; }+ .card {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 12px 14px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 10px;+ color: inherit;+ text-align: left;+ cursor: pointer;+ font-family: inherit;+ transition: border-color 80ms ease, background 80ms ease;+ }+ .card:hover:not(:disabled) {+ border-color: rgba(255, 255, 255, 0.18);+ background: rgba(255, 255, 255, 0.05);+ }+ .card:disabled { opacity: 0.5; cursor: default; }+ .card.selected {+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 10%, rgba(255, 255, 255, 0.03));+ }+ .card-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 13px; font-weight: 700; }+ .check { color: var(--accent); flex-shrink: 0; }+ .card-hint { font-size: 11px; color: rgba(255, 255, 255, 0.55); line-height: 1.4; }+</style>diff --git a/src/lib/study-music-components/QueuePanel.svelte b/src/lib/study-music-components/QueuePanel.sveltenew file mode 100644index 00000000..fe432d68--- /dev/null+++ b/src/lib/study-music-components/QueuePanel.svelte@@ -0,0 +1,202 @@+<script lang="ts">+ import { musicPlayer } from "$lib/study-music/player-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { fmtDuration } from "$lib/study-music/format";+ import { t } from "$lib/i18n";+ import CoverImage from "./CoverImage.svelte";++ function jumpTo(idx: number) {+ if (idx < 0 || idx >= musicPlayer.queue.length) return;+ musicPlayer.queueIndex = idx;+ void musicPlayer.play(musicPlayer.queue[idx], musicPlayer.queue);+ }++ function close() {+ musicUI.closeQueue();+ }++ $effect(() => {+ if (!musicUI.queueOpen || typeof document === "undefined") return;+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ close();+ }+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });+</script>++{#if musicUI.queueOpen}+ <div class="queue-panel" role="dialog" aria-label={$t("study.music.queue_aria") as string} aria-modal="false" tabindex="-1">+ <header class="head">+ <h3>{$t("study.music.queue_title")}</h3>+ <span class="count">{musicPlayer.queue.length}</span>+ {#if musicPlayer.queue.length > 0}+ <button+ type="button"+ class="clear"+ onclick={() => musicPlayer.clearQueue()}+ title={$t("study.music.queue_clear") as string}+ >{$t("study.music.queue_clear")}</button>+ {/if}+ <button type="button" class="close" onclick={close} aria-label={$t("study.common.close")}>×</button>+ </header>+ {#if musicPlayer.queue.length === 0}+ <p class="muted">{$t("study.music.queue_empty")}</p>+ {:else}+ <ol class="list">+ {#each musicPlayer.queue as track, i (i + ":" + track.id)}+ {@const current = i === musicPlayer.queueIndex}+ <li class="row" class:current>+ <button type="button" class="play-cell" onclick={() => jumpTo(i)}>+ <CoverImage+ src={track.cover_path}+ alt={track.title ?? track.path}+ size={32}+ fallbackSeed={track.album ?? track.title}+ rounded="sm"+ trackId={track.id}+ />+ <span class="info">+ <span class="title">{track.title ?? track.path}</span>+ {#if track.artist}+ <span class="artist">{track.artist}</span>+ {/if}+ </span>+ <span class="dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ </li>+ {/each}+ </ol>+ {/if}+ </div>+{/if}++<style>+ .queue-panel {+ position: fixed;+ right: 12px;+ bottom: 92px;+ width: 360px;+ max-height: 60vh;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 12px;+ box-shadow: 0 16px 48px color-mix(in oklab, black 38%, transparent);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ z-index: 100;+ }+ .head {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 12px 14px;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ }+ .head h3 {+ margin: 0;+ flex: 1;+ font-size: 13px;+ font-weight: 700;+ color: var(--secondary);+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }+ .count {+ font-size: 11px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ }+ .clear {+ padding: 4px 10px;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 999px;+ color: var(--tertiary);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ }+ .clear:hover {+ color: var(--secondary);+ border-color: var(--secondary);+ }+ .close {+ width: 24px;+ height: 24px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: var(--tertiary);+ font-size: 18px;+ line-height: 1;+ cursor: pointer;+ }+ .close:hover { color: var(--secondary); background: color-mix(in oklab, var(--accent) 8%, transparent); }+ .list {+ list-style: none;+ margin: 0;+ padding: 6px;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .row { padding: 0; }+ .row.current .play-cell { background: color-mix(in oklab, var(--accent) 14%, transparent); }+ .row.current .title { color: var(--accent); }+ .play-cell {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 6px 10px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: var(--secondary);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease;+ }+ .play-cell:hover { background: color-mix(in oklab, var(--accent) 6%, transparent); }+ .info {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-width: 0;+ overflow: hidden;+ }+ .title {+ font-size: 12px;+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .artist {+ font-size: 10px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .dur {+ font-size: 10px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ }+ .muted {+ color: var(--tertiary);+ font-size: 12px;+ padding: 14px;+ margin: 0;+ text-align: center;+ }+</style>diff --git a/src/lib/study-music-components/RightBar.svelte b/src/lib/study-music-components/RightBar.sveltenew file mode 100644index 00000000..2b019d21--- /dev/null+++ b/src/lib/study-music-components/RightBar.svelte@@ -0,0 +1,543 @@+<script lang="ts">+ import { tick } from "svelte";+ import { musicUI, type RightBarTab } from "$lib/study-music/ui-store.svelte";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { lyricsStore } from "$lib/study-music/lyrics-store.svelte";+ import { fmtDuration, fmtDurationLong, trackDisplayTitle } from "$lib/study-music/format";+ import { t } from "$lib/i18n";+ import CoverImage from "./CoverImage.svelte";++ let lyricsContainer = $state<HTMLDivElement | null>(null);+ let lineRefs: HTMLLIElement[] = [];++ const currentTrack = $derived(musicPlayer.currentTrack);+ const activeIdx = $derived(+ lyricsStore.lines.length > 0+ ? lyricsStore.activeIndex(musicPlayer.currentTime)+ : -1,+ );++ $effect(() => {+ if (musicUI.rightbarTab !== "lyrics") return;+ const id = currentTrack?.id ?? null;+ if (id === null) {+ lyricsStore.reset();+ return;+ }+ void lyricsStore.loadFor(id);+ });++ $effect(() => {+ if (musicUI.rightbarTab !== "lyrics") return;+ void activeIdx;+ void tick().then(() => {+ const el = lineRefs[activeIdx];+ if (el && lyricsContainer) {+ const rect = el.getBoundingClientRect();+ const cRect = lyricsContainer.getBoundingClientRect();+ const offset =+ el.offsetTop - lyricsContainer.offsetTop - cRect.height / 2 + rect.height / 2;+ lyricsContainer.scrollTo({ top: offset, behavior: "smooth" });+ }+ });+ });++ function jumpTo(idx: number) {+ if (idx < 0 || idx >= musicPlayer.queue.length) return;+ musicPlayer.queueIndex = idx;+ void musicPlayer.play(musicPlayer.queue[idx], musicPlayer.queue);+ }++ function setTab(tab: RightBarTab) {+ musicUI.rightbarTab = tab;+ }++ function close() {+ musicUI.rightbarTab = null;+ }++ function refreshLyrics() {+ if (currentTrack) void lyricsStore.loadFor(currentTrack.id, true);+ }++ $effect(() => {+ if (typeof document === "undefined") return;+ function onKey(e: KeyboardEvent) {+ if (musicUI.rightbarTab === null) return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.isContentEditable)+ ) {+ return;+ }+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ close();+ }+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });+</script>++{#if musicUI.rightbarTab !== null}+ <aside class="right-bar" role="complementary">+ <header class="head">+ <nav class="tabs" role="tablist">+ <button+ type="button"+ role="tab"+ class="tab"+ class:active={musicUI.rightbarTab === "queue"}+ aria-selected={musicUI.rightbarTab === "queue"}+ onclick={() => setTab("queue")}+ >+ <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">+ <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>+ <span>{$t("study.music.tab_queue")}</span>+ {#if musicPlayer.queue.length > 0}+ <span class="badge">{musicPlayer.queue.length}</span>+ {/if}+ </button>+ <button+ type="button"+ role="tab"+ class="tab"+ class:active={musicUI.rightbarTab === "lyrics"}+ aria-selected={musicUI.rightbarTab === "lyrics"}+ onclick={() => setTab("lyrics")}+ >+ <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="M9 18V5l12-2v13"/>+ <line x1="3" y1="9" x2="9" y2="9"/>+ <line x1="3" y1="13" x2="7" y2="13"/>+ </svg>+ <span>{$t("study.music.tab_lyrics")}</span>+ </button>+ <button+ type="button"+ role="tab"+ class="tab"+ class:active={musicUI.rightbarTab === "info"}+ aria-selected={musicUI.rightbarTab === "info"}+ onclick={() => setTab("info")}+ >+ <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">+ <circle cx="12" cy="12" r="9"/>+ <line x1="12" y1="8" x2="12" y2="12"/>+ <line x1="12" y1="16" x2="12.01" y2="16"/>+ </svg>+ <span>{$t("study.music.tab_info")}</span>+ </button>+ </nav>+ <button type="button" class="close" onclick={close} aria-label={$t("study.common.close") as string}>×</button>+ </header>++ <div class="body">+ {#if musicUI.rightbarTab === "queue"}+ {#if musicPlayer.queue.length === 0}+ <p class="empty">{$t("study.music.queue_empty")}</p>+ {:else}+ <div class="queue-bar">+ <span class="muted">{$t("study.music.tracks_count", { count: musicPlayer.queue.length })}</span>+ <button type="button" class="link" onclick={() => musicPlayer.clearQueue()}>+ {$t("study.music.queue_clear")}+ </button>+ </div>+ <ol class="queue-list">+ {#each musicPlayer.queue as track, i (i + ":" + track.id)}+ {@const current = i === musicPlayer.queueIndex}+ <li class="q-row" class:current>+ <button type="button" class="q-btn" onclick={() => jumpTo(i)}>+ <CoverImage+ src={track.cover_path}+ alt={track.title ?? track.path}+ size={32}+ fallbackSeed={track.album ?? track.title}+ rounded="sm"+ trackId={track.id}+ />+ <span class="q-info">+ <span class="q-title">{trackDisplayTitle(track)}</span>+ {#if track.artist}<span class="q-artist">{track.artist}</span>{/if}+ </span>+ <span class="q-dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ </li>+ {/each}+ </ol>+ {/if}+ {:else if musicUI.rightbarTab === "lyrics"}+ {#if !currentTrack}+ <p class="empty">{$t("study.music.lyrics_no_track")}</p>+ {:else if lyricsStore.loading}+ <div class="loading"><span class="spinner"></span><p>{$t("study.music.lyrics_loading")}</p></div>+ {:else if lyricsStore.notFound}+ <div class="empty">+ <p>{$t("study.music.lyrics_not_found")}</p>+ <p class="muted small">{$t("study.music.lyrics_lrclib_hint")}</p>+ <button type="button" class="link" onclick={refreshLyrics}>+ {$t("study.music.lyrics_refresh")}+ </button>+ </div>+ {:else if lyricsStore.lines.length > 0}+ <div bind:this={lyricsContainer} class="lyrics synced">+ <ul class="lines">+ {#each lyricsStore.lines as line, i (i)}+ <li+ bind:this={lineRefs[i]}+ class="line"+ class:active={i === activeIdx}+ class:past={i < activeIdx}+ >{line.text || "♪"}</li>+ {/each}+ </ul>+ </div>+ {:else if lyricsStore.plain}+ <div class="lyrics plain">+ {#each lyricsStore.plain.split(/\r?\n/) as line, i (i)}+ <p class="plain-line">{line || " "}</p>+ {/each}+ </div>+ {/if}+ {:else if musicUI.rightbarTab === "info"}+ {#if !currentTrack}+ <p class="empty">{$t("study.music.info_no_track")}</p>+ {:else}+ <div class="info-block">+ <div class="info-cover">+ <CoverImage+ src={currentTrack.cover_path}+ alt={currentTrack.title ?? ""}+ fallbackSeed={currentTrack.album ?? currentTrack.title}+ rounded="lg"+ trackId={currentTrack.id}+ />+ </div>+ <h2 class="info-title">{trackDisplayTitle(currentTrack)}</h2>+ {#if currentTrack.artist}+ <p class="info-artist">{currentTrack.artist}</p>+ {/if}+ <dl class="info-meta">+ {#if currentTrack.album}+ <dt>{$t("study.music.field_album")}</dt>+ <dd>{currentTrack.album}</dd>+ {/if}+ {#if currentTrack.year}+ <dt>{$t("study.music.field_year")}</dt>+ <dd>{currentTrack.year}</dd>+ {/if}+ {#if currentTrack.genre}+ <dt>{$t("study.music.field_genre")}</dt>+ <dd>{currentTrack.genre}</dd>+ {/if}+ {#if currentTrack.duration_ms}+ <dt>{$t("study.music.field_duration")}</dt>+ <dd>{fmtDurationLong(currentTrack.duration_ms)}</dd>+ {/if}+ {#if currentTrack.bitrate}+ <dt>{$t("study.music.field_bitrate")}</dt>+ <dd>{currentTrack.bitrate} kbps</dd>+ {/if}+ {#if currentTrack.sample_rate}+ <dt>{$t("study.music.field_samplerate")}</dt>+ <dd>{Math.round(currentTrack.sample_rate / 1000)} kHz</dd>+ {/if}+ {#if currentTrack.play_count !== undefined && currentTrack.play_count > 0}+ <dt>{$t("study.music.field_plays")}</dt>+ <dd>{currentTrack.play_count}</dd>+ {/if}+ </dl>+ <p class="info-path" title={currentTrack.path}>{currentTrack.path}</p>+ </div>+ {/if}+ {/if}+ </div>+ </aside>+{/if}++<style>+ .right-bar {+ position: fixed;+ top: 14px;+ right: 14px;+ bottom: 96px;+ width: min(380px, 92vw);+ z-index: 95;+ background: rgba(20, 20, 20, 0.96);+ color: rgba(255, 255, 255, 0.95);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 14px;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ backdrop-filter: blur(8px);+ }+ .head {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 10px 10px 10px 12px;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }+ .tabs {+ display: flex;+ gap: 2px;+ flex: 1;+ overflow-x: auto;+ scrollbar-width: none;+ }+ .tab {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 11px;+ border: 0;+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.55);+ font-family: inherit;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ flex-shrink: 0;+ }+ .tab:hover { color: rgba(255, 255, 255, 0.95); }+ .tab.active {+ background: rgba(255, 255, 255, 0.08);+ color: white;+ }+ .badge {+ padding: 0 6px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.9);+ font-size: 10px;+ font-weight: 700;+ font-variant-numeric: tabular-nums;+ }+ .close {+ width: 28px;+ height: 28px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ flex-shrink: 0;+ }+ .close:hover { color: white; background: rgba(255, 255, 255, 0.08); }+ .body {+ flex: 1;+ overflow: hidden;+ display: flex;+ flex-direction: column;+ }+ .queue-bar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 14px;+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 11px; }+ .small { font-size: 11px; }+ .link {+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.65);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ padding: 4px 0;+ }+ .link:hover { color: white; text-decoration: underline; }+ .queue-list {+ flex: 1;+ overflow-y: auto;+ list-style: none;+ margin: 0;+ padding: 6px 6px 24px;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .q-row.current .q-title { color: var(--accent); }+ .q-btn {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 6px 10px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ }+ .q-btn:hover { background: rgba(255, 255, 255, 0.05); }+ .q-row.current .q-btn { background: color-mix(in oklab, var(--accent) 14%, transparent); }+ .q-info {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ .q-title {+ font-size: 12px;+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .q-artist {+ font-size: 10px;+ color: rgba(255, 255, 255, 0.5);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .q-dur {+ flex-shrink: 0;+ font-size: 11px;+ color: rgba(255, 255, 255, 0.5);+ font-variant-numeric: tabular-nums;+ }+ .empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 32px 16px;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ text-align: center;+ }+ .loading {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 12px;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .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;+ }+ @keyframes spin { to { transform: rotate(360deg); } }+ .lyrics {+ flex: 1;+ overflow-y: auto;+ padding: 16px 22px 32px;+ scrollbar-width: thin;+ }+ .lyrics .lines {+ list-style: none;+ margin: 0;+ padding: 30vh 0;+ display: flex;+ flex-direction: column;+ gap: 16px;+ }+ .line {+ font-size: 16px;+ line-height: 1.4;+ color: rgba(255, 255, 255, 0.4);+ transition: color 220ms ease, transform 220ms ease, font-size 220ms ease;+ }+ .line.past { color: rgba(255, 255, 255, 0.25); }+ .line.active {+ color: white;+ font-weight: 700;+ font-size: 19px;+ transform: scale(1.02);+ transform-origin: left;+ }+ .plain-line {+ margin: 0 0 10px;+ font-size: 13px;+ line-height: 1.6;+ color: rgba(255, 255, 255, 0.85);+ }+ .info-block {+ flex: 1;+ overflow-y: auto;+ padding: 18px 18px 24px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ }+ .info-cover {+ width: 100%;+ aspect-ratio: 1 / 1;+ margin-bottom: 4px;+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+ border-radius: 10px;+ overflow: hidden;+ }+ .info-title {+ margin: 8px 0 0;+ font-size: 18px;+ font-weight: 800;+ letter-spacing: -0.01em;+ line-height: 1.2;+ }+ .info-artist {+ margin: 0;+ color: rgba(255, 255, 255, 0.65);+ font-size: 13px;+ }+ .info-meta {+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 4px 12px;+ margin: 12px 0 0;+ padding-top: 12px;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ font-size: 12px;+ }+ .info-meta dt {+ color: rgba(255, 255, 255, 0.5);+ text-transform: uppercase;+ font-size: 10px;+ letter-spacing: 0.06em;+ align-self: center;+ }+ .info-meta dd {+ margin: 0;+ color: rgba(255, 255, 255, 0.95);+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .info-path {+ margin: 16px 0 0;+ padding: 8px;+ background: rgba(0, 0, 0, 0.3);+ border-radius: 6px;+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: rgba(255, 255, 255, 0.45);+ word-break: break-all;+ }+</style>diff --git a/src/lib/study-music-components/RootsManager.svelte b/src/lib/study-music-components/RootsManager.sveltenew file mode 100644index 00000000..f7a12cb0--- /dev/null+++ b/src/lib/study-music-components/RootsManager.svelte@@ -0,0 +1,592 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { t } from "$lib/i18n";++ type RootEntry = {+ path: string;+ enabled: boolean;+ added_at: number;+ exists: boolean;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ onChanged?: () => void;+ };++ let { open = $bindable(), onClose, onChanged }: Props = $props();++ let roots = $state<RootEntry[]>([]);+ let loading = $state(false);+ let busy = $state(false);+ let diagnosticsOpen = $state(false);+ let diagnostics = $state<unknown>(null);++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{ roots: RootEntry[] }>(+ "study",+ "study:music:roots:list",+ );+ roots = res.roots ?? [];+ } finally {+ loading = false;+ }+ }++ async function addRoot() {+ if (busy) return;+ busy = true;+ 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 load();+ onChanged?.();+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ async function toggleRoot(r: RootEntry) {+ try {+ await pluginInvoke("study", "study:music:roots:toggle", {+ path: r.path,+ enabled: !r.enabled,+ });+ await load();+ onChanged?.();+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ async function clearCovers() {+ if (busy) return;+ if (+ typeof window !== "undefined" &&+ !window.confirm($t("study.music.clear_covers_confirm") as string)+ ) {+ return;+ }+ busy = true;+ try {+ const res = await pluginInvoke<{ files_removed: number; tracks_cleared: number }>(+ "study",+ "study:music:covers:clear",+ );+ showToast(+ "success",+ $t("study.music.clear_covers_done", {+ files: res.files_removed,+ tracks: res.tracks_cleared,+ }) as string,+ );+ const scanRes = await pluginInvoke<{+ added: number;+ updated: number;+ removed: number;+ }>("study", "study:music:scan");+ showToast(+ "success",+ $t("study.music.scan_done", {+ added: scanRes.added,+ updated: scanRes.updated,+ removed: scanRes.removed,+ }) as string,+ );+ onChanged?.();+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ async function runDiagnostics() {+ if (busy) return;+ busy = true;+ try {+ const res = await pluginInvoke(+ "study",+ "study:music:debug:cover-status",+ );+ diagnostics = res;+ diagnosticsOpen = true;+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ async function copyDiagnostics() {+ if (!diagnostics) return;+ try {+ await navigator.clipboard.writeText(JSON.stringify(diagnostics, null, 2));+ showToast("success", $t("study.common.copied") as string);+ } catch {+ /* ignore */+ }+ }++ async function removeRoot(r: RootEntry) {+ if (busy) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:roots:remove", { path: r.path });+ showToast(+ "success",+ $t("study.music.root_removed", { path: r.path }) as string,+ );+ await load();+ onChanged?.();+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ function compactPath(path: string, max = 60): string {+ if (path.length <= max) return path;+ return `…${path.slice(path.length - max + 1)}`;+ }++ $effect(() => {+ if (open) void load();+ });++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }+</script>++{#if diagnosticsOpen && diagnostics}+ <div+ class="overlay diag-overlay"+ role="presentation"+ onclick={(e) => {+ if (e.target === e.currentTarget) diagnosticsOpen = false;+ }}+ >+ <div class="dialog diag-dialog" role="dialog" aria-modal="true" tabindex="-1">+ <header class="head">+ <h3>{$t("study.music.diagnostics_title")}</h3>+ <button+ type="button"+ class="close"+ onclick={() => (diagnosticsOpen = false)}+ aria-label={$t("study.common.close") as string}+ >×</button>+ </header>+ <div class="diag-body">+ <pre>{JSON.stringify(diagnostics, null, 2)}</pre>+ </div>+ <footer class="foot">+ <button+ type="button"+ class="reset-btn"+ onclick={copyDiagnostics}+ >{$t("study.common.copy")}</button>+ <button+ type="button"+ class="done-btn"+ onclick={() => (diagnosticsOpen = false)}+ >{$t("study.common.close")}</button>+ </footer>+ </div>+ </div>+{/if}++{#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.roots_title")}</h3>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <p class="hint">{$t("study.music.roots_hint")}</p>++ <div class="content">+ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if roots.length === 0}+ <div class="empty">+ <p>{$t("study.music.roots_empty")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each roots as r (r.path)}+ <li class="row" class:disabled={!r.enabled} class:missing={!r.exists}>+ <label class="toggle">+ <input+ type="checkbox"+ checked={r.enabled}+ onchange={() => toggleRoot(r)}+ />+ </label>+ <div class="info">+ <span class="path" title={r.path}>{compactPath(r.path)}</span>+ {#if !r.exists}+ <span class="badge missing-badge">{$t("study.music.root_missing")}</span>+ {/if}+ </div>+ <button+ type="button"+ class="remove"+ onclick={() => removeRoot(r)}+ disabled={busy}+ aria-label={$t("study.music.root_remove") as string}+ title={$t("study.music.root_remove") as string}+ >×</button>+ </li>+ {/each}+ </ul>+ {/if}+ </div>++ <footer class="foot">+ <button+ type="button"+ class="add-btn"+ onclick={addRoot}+ disabled={busy}+ >+ {$t("study.music.add_root")}</button>+ <div class="tools-grid">+ <button+ type="button"+ class="reset-btn"+ onclick={clearCovers}+ disabled={busy}+ title={$t("study.music.clear_covers_hint") as string}+ >{$t("study.music.clear_covers")}</button>+ <button+ type="button"+ class="reset-btn"+ onclick={runDiagnostics}+ disabled={busy}+ title={$t("study.music.diagnostics_hint") as string}+ >{$t("study.music.diagnostics")}</button>+ <button+ type="button"+ class="reset-btn"+ onclick={() => {+ onClose();+ musicUI.openLastFm();+ }}+ disabled={busy}+ title={$t("study.music.lastfm_title") as string}+ >Last.fm</button>+ <button+ type="button"+ class="reset-btn"+ onclick={() => {+ onClose();+ musicUI.openTheme();+ }}+ disabled={busy}+ title={$t("study.music.music_theme_title") as string}+ >{$t("study.music.music_theme_title")}</button>+ <button+ type="button"+ class="reset-btn"+ onclick={() => {+ onClose();+ musicUI.openQuality();+ }}+ disabled={busy}+ title={$t("study.music.quality_title") as string}+ >{$t("study.music.quality_short")}</button>+ <button+ type="button"+ class="reset-btn"+ onclick={() => {+ onClose();+ musicUI.openSources();+ }}+ disabled={busy}+ title={$t("study.music.sources_title") as string}+ >{$t("study.music.sources_short")}</button>+ <button+ type="button"+ class="reset-btn"+ onclick={() => {+ onClose();+ musicUI.openQobuz();+ }}+ disabled={busy}+ title={$t("study.music.qobuz_title") as string}+ >Qobuz</button>+ <button type="button" class="done-btn" onclick={onClose}>+ {$t("study.common.close")}+ </button>+ </div>+ </footer>+ </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);+ -webkit-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: 80vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head {+ position: relative;+ padding: 18px 20px 8px;+ }+ .head h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 800;+ letter-spacing: -0.01em;+ }+ .close {+ position: absolute;+ top: 12px;+ right: 14px;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 0;+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 18px;+ cursor: pointer;+ }+ .close:hover { color: white; background: rgba(255, 255, 255, 0.08); }+ .hint {+ margin: 0;+ padding: 0 20px 12px;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ line-height: 1.5;+ }+ .content {+ flex: 1;+ overflow-y: auto;+ padding: 4px 12px 12px;+ }+ .empty {+ padding: 32px 12px;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; padding: 8px; }+ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 12px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.05);+ border-radius: 8px;+ }+ .row.missing {+ background: rgba(217, 119, 6, 0.08);+ border-color: rgba(217, 119, 6, 0.25);+ }+ .row.disabled .path {+ opacity: 0.5;+ text-decoration: line-through;+ text-decoration-color: rgba(255, 255, 255, 0.25);+ }+ .toggle input {+ width: 16px;+ height: 16px;+ cursor: pointer;+ accent-color: var(--accent);+ }+ .info {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .path {+ font-family: ui-monospace, monospace;+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: rgba(255, 255, 255, 0.95);+ }+ .badge {+ font-size: 10px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ padding: 2px 6px;+ border-radius: 4px;+ align-self: flex-start;+ }+ .missing-badge {+ background: rgba(217, 119, 6, 0.18);+ color: rgb(251, 191, 36);+ }+ .remove {+ width: 26px;+ height: 26px;+ padding: 0;+ background: transparent;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 50%;+ color: rgba(255, 255, 255, 0.5);+ font-size: 16px;+ line-height: 1;+ cursor: pointer;+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .remove:hover:not(:disabled) {+ color: rgb(248, 113, 113);+ border-color: rgb(248, 113, 113);+ background: rgba(248, 113, 113, 0.1);+ }+ .remove:disabled { opacity: 0.5; cursor: default; }+ .foot {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 14px 20px 16px;+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ background: rgba(255, 255, 255, 0.02);+ }+ .add-btn {+ width: 100%;+ padding: 10px 16px;+ border: 1px dashed rgba(255, 255, 255, 0.25);+ border-radius: 10px;+ background: transparent;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: border-color 120ms ease, color 120ms ease, background 120ms ease;+ }+ .add-btn:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .add-btn:disabled { opacity: 0.5; cursor: default; }+ .tools-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));+ gap: 6px;+ }+ .reset-btn {+ padding: 8px 12px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ background: transparent;+ color: rgba(255, 255, 255, 0.7);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ text-align: center;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .reset-btn:hover:not(:disabled) {+ color: rgba(255, 255, 255, 0.95);+ border-color: rgba(255, 255, 255, 0.3);+ background: rgba(255, 255, 255, 0.05);+ }+ .reset-btn:disabled { opacity: 0.4; cursor: default; }+ .diag-overlay { z-index: 340; }+ .diag-dialog {+ width: min(720px, 94vw);+ max-height: 86vh;+ }+ .diag-body {+ flex: 1;+ overflow: auto;+ padding: 0 20px 16px;+ }+ .diag-body pre {+ margin: 0;+ padding: 12px;+ background: rgba(0, 0, 0, 0.35);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 8px;+ font-family: ui-monospace, monospace;+ font-size: 11px;+ line-height: 1.5;+ color: rgba(255, 255, 255, 0.85);+ white-space: pre-wrap;+ word-break: break-all;+ }+ .done-btn {+ padding: 8px 12px;+ border: 0;+ border-radius: 8px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 12px;+ font-weight: 700;+ cursor: pointer;+ text-align: center;+ }+ .done-btn:hover {+ filter: brightness(1.1);+ }+</style>diff --git a/src/lib/study-music-components/SelectionBar.svelte b/src/lib/study-music-components/SelectionBar.sveltenew file mode 100644index 00000000..ff4f2b59--- /dev/null+++ b/src/lib/study-music-components/SelectionBar.svelte@@ -0,0 +1,187 @@+<script lang="ts">+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ function getSelectedTracks(): MusicTrack[] {+ const ids = musicUI.selectedIds;+ if (ids.size === 0 || !musicUI.selectionAnchor) return [];+ return musicUI.selectionAnchor.queue.filter((tr) => ids.has(tr.id));+ }++ async function playSelection() {+ const tracks = getSelectedTracks();+ if (tracks.length === 0) return;+ await musicPlayer.play(tracks[0], tracks);+ musicUI.clearSelection();+ }++ function queueSelection() {+ const tracks = getSelectedTracks();+ if (tracks.length === 0) return;+ musicPlayer.queue = [...musicPlayer.queue, ...tracks];+ showToast(+ "success",+ $t("study.music.queued_count", { count: tracks.length }) as string,+ );+ }++ async function favoriteSelection() {+ const tracks = getSelectedTracks();+ for (const tr of tracks) {+ if (!tr.favorite) {+ await musicPlayer.toggleFavorite(tr.id);+ }+ }+ showToast(+ "success",+ $t("study.music.favorited_count", { count: tracks.length }) as string,+ );+ musicUI.clearSelection();+ }++ function addToPlaylist() {+ const tracks = getSelectedTracks();+ if (tracks.length === 0) return;+ musicUI.openAddToPlaylist(tracks[0]);+ }++ $effect(() => {+ if (typeof document === "undefined") return;+ function onKey(e: KeyboardEvent) {+ if (musicUI.selectedCount() === 0) return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.isContentEditable)+ ) {+ return;+ }+ if (e.key === "Escape") {+ e.preventDefault();+ musicUI.clearSelection();+ }+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "a") {+ const queue = musicUI.selectionAnchor?.queue;+ if (queue && queue.length > 0) {+ e.preventDefault();+ const all = new Set(queue.map((t) => t.id));+ musicUI.selectedIds = all;+ }+ }+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });+</script>++{#if musicUI.selectedCount() > 0}+ <div class="selection-bar" role="toolbar" aria-label={$t("study.music.selection_aria") as string}>+ <span class="count">+ {$t("study.music.n_selected", { count: musicUI.selectedCount() })}+ </span>+ <div class="actions">+ <button type="button" class="action play" onclick={playSelection} title={$t("study.music.play") as string}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>+ <span>{$t("study.music.play")}</span>+ </button>+ <button type="button" class="action" onclick={queueSelection} title={$t("study.music.add_to_queue") 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"><line x1="3" y1="6" x2="16" y2="6"/><line x1="3" y1="12" x2="16" y2="12"/><line x1="3" y1="18" x2="11" y2="18"/><line x1="20" y1="14" x2="20" y2="20"/><line x1="17" y1="17" x2="23" y2="17"/></svg>+ <span>{$t("study.music.add_to_queue")}</span>+ </button>+ <button type="button" class="action" onclick={addToPlaylist} title={$t("study.music.add_to_playlist") 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"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>+ <span>{$t("study.music.add_to_playlist")}</span>+ </button>+ <button type="button" class="action" onclick={favoriteSelection} title={$t("study.music.favorite") 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"><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>+ <span>{$t("study.music.favorite")}</span>+ </button>+ </div>+ <button type="button" class="dismiss" onclick={() => musicUI.clearSelection()} aria-label={$t("study.common.close") as string}>×</button>+ </div>+{/if}++<style>+ .selection-bar {+ position: fixed;+ bottom: 96px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 110;+ display: flex;+ align-items: center;+ gap: 16px;+ padding: 8px 12px 8px 16px;+ background: rgb(28, 28, 30);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 999px;+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ animation: slideUp 180ms ease;+ }+ @keyframes slideUp {+ from { opacity: 0; transform: translateX(-50%) translateY(8px); }+ to { opacity: 1; transform: translateX(-50%) translateY(0); }+ }+ .count {+ font-size: 12px;+ font-weight: 600;+ color: rgba(255, 255, 255, 0.85);+ padding-right: 4px;+ border-right: 1px solid rgba(255, 255, 255, 0.1);+ margin-right: 4px;+ }+ .actions {+ display: flex;+ align-items: center;+ gap: 4px;+ }+ .action {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 12px;+ background: transparent;+ border: 0;+ border-radius: 999px;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 120ms ease, color 120ms ease;+ }+ .action:hover {+ background: rgba(255, 255, 255, 0.08);+ color: white;+ }+ .action.play {+ background: var(--accent);+ color: var(--on-accent, white);+ font-weight: 700;+ }+ .action.play:hover {+ filter: brightness(1.1);+ }+ .dismiss {+ 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;+ }+ .dismiss:hover {+ color: white;+ background: rgba(255, 255, 255, 0.08);+ }+</style>diff --git a/src/lib/study-music-components/SoundCloudDownloadDialog.svelte b/src/lib/study-music-components/SoundCloudDownloadDialog.sveltenew file mode 100644index 00000000..a95efef7--- /dev/null+++ b/src/lib/study-music-components/SoundCloudDownloadDialog.svelte@@ -0,0 +1,253 @@+<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";++ type Props = {+ track: ScTrack;+ onClose: () => void;+ };++ let { track, onClose }: Props = $props();++ let qualities = $state<ScQuality[]>([]);+ let selectedQuality = $state<string>("");+ let codec = $state<string>("mp3");+ 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;++ const codecs = [+ { id: "mp3", label: "MP3 192k" },+ { id: "opus", label: "Opus 96k" },+ { id: "vorbis", label: "Vorbis q3" },+ { id: "aac", label: "AAC 192k" },+ { id: "flac", label: "FLAC" },+ { 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");+ const picked = await dialog.open({ directory: true, multiple: false });+ if (typeof picked === "string" && picked) {+ outputDir = picked;+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ async function startDownload() {+ if (!outputDir) {+ showToast("error", "Escolha uma pasta de destino");+ return;+ }+ downloading = true;+ progressMs = 0;+ stage = "starting";+ try {+ const res = await soundcloudStore.download({+ trackId: track.id,+ codec,+ outputDir,+ quality: selectedQuality,+ });+ showToast("success", `Salvo em: ${res.path}`);+ onClose();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ downloading = false;+ }+ }++ 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">+ <header class="head">+ <div class="info">+ {#if track.artwork_url}+ <img src={soundcloudStore.pickArtwork(track.artwork_url)} alt="" />+ {/if}+ <div class="meta">+ <span class="title">{track.title}</span>+ <span class="artist">{track.user.username}</span>+ </div>+ </div>+ <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+ </button>+ <button+ type="button"+ class="cta"+ onclick={startDownload}+ disabled={downloading || !outputDir || !selectedQuality}+ >+ {downloading ? "Baixando…" : "Baixar"}+ </button>+ </footer>+ {/if}+ </div>+</div>++<style>+ .backdrop {+ position: fixed; inset: 0; background: rgba(0, 0, 0, 0.7); z-index: 1000;+ display: grid; place-items: center; padding: 16px;+ }+ .dialog {+ width: min(560px, 100%); max-height: 90vh; overflow-y: auto;+ background: #111; border: 1px solid rgba(255,255,255,0.08); border-radius: 12px;+ color: white; padding: 20px; display: flex; flex-direction: column; gap: 16px;+ }+ .head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }+ .info { display: flex; gap: 12px; align-items: center; min-width: 0; }+ .info img { width: 56px; height: 56px; border-radius: 6px; object-fit: cover; }+ .meta { display: flex; flex-direction: column; min-width: 0; }+ .title { font-size: 15px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .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 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; }+ .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; }+ .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); }+ .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/SourceOrderPanel.svelte b/src/lib/study-music-components/SourceOrderPanel.sveltenew file mode 100644index 00000000..63125b8c--- /dev/null+++ b/src/lib/study-music-components/SourceOrderPanel.svelte@@ -0,0 +1,305 @@+<script lang="ts">+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { t } from "$lib/i18n";++ type SourceEntry = { slug: string; available: boolean };++ type Props = {+ open: boolean;+ onClose: () => void;+ };++ let { open, onClose }: Props = $props();++ let activeOrder = $state<SourceEntry[]>([]);+ let allSources = $state<SourceEntry[]>([]);+ let loading = $state(false);+ let saving = $state(false);++ const DEFAULT_ORDER = ["youtube_music", "soundcloud"];++ const SOURCE_LABEL: Record<string, string> = {+ "youtube_music": "YouTube Music",+ "soundcloud": "SoundCloud",+ "qobuz": "Qobuz",+ "tidal": "Tidal",+ "deezer": "Deezer",+ };++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{+ active_order: SourceEntry[];+ all: SourceEntry[];+ }>("study", "study:music:resolver:list_sources");+ activeOrder = res.active_order ?? [];+ allSources = res.all ?? [];+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ if (open) void load();+ });++ async function commit(newOrder: SourceEntry[]) {+ if (saving) return;+ const previous = activeOrder;+ activeOrder = newOrder;+ saving = true;+ try {+ await pluginInvoke("study", "study:music:resolver:set_order", {+ order: newOrder.map((s) => s.slug),+ });+ } catch (e) {+ activeOrder = previous;+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ saving = false;+ }+ }++ function moveUp(idx: number) {+ if (idx <= 0) return;+ const next = activeOrder.slice();+ [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];+ void commit(next);+ }++ function moveDown(idx: number) {+ if (idx >= activeOrder.length - 1) return;+ const next = activeOrder.slice();+ [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];+ void commit(next);+ }++ function resetDefault() {+ if (saving) return;+ const lookup = new Map(allSources.map((s) => [s.slug, s]));+ const next: SourceEntry[] = [];+ for (const slug of DEFAULT_ORDER) {+ const entry = lookup.get(slug);+ if (entry) next.push(entry);+ }+ void commit(next);+ }++ function statusLabel(slug: string, available: boolean): string {+ if (available) return $t("study.music.source_status_connected") as string;+ if (slug === "qobuz") return $t("study.music.source_status_not_connected") as string;+ return $t("study.music.source_status_unavailable") as string;+ }++ function openAuth(slug: string) {+ if (slug === "qobuz") {+ onClose();+ musicUI.openQobuz();+ } else if (slug === "youtube_music") {+ onClose();+ musicUI.openYoutube();+ }+ }++ function canConnect(slug: string): boolean {+ return slug === "qobuz" || slug === "youtube_music";+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }++ const inactiveSources = $derived(+ allSources.filter((s) => !activeOrder.some((a) => a.slug === s.slug)),+ );+</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">+ <div class="head-text">+ <h3>{$t("study.music.sources_title")}</h3>+ <span class="state">{$t("study.music.sources_subtitle")}</span>+ </div>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.sources_intro")}</p>++ {#if loading}+ <div class="loading">{$t("study.common.loading")}</div>+ {:else}+ <ol class="list">+ {#each activeOrder as src, idx (src.slug)}+ <li class="row" class:dim={!src.available}>+ <span class="rank">{idx + 1}</span>+ <span class="name">{SOURCE_LABEL[src.slug] ?? src.slug}</span>+ <span class="status" class:on={src.available} class:off={!src.available}>+ {statusLabel(src.slug, src.available)}+ </span>+ {#if !src.available && canConnect(src.slug)}+ <button type="button" class="link" onclick={() => openAuth(src.slug)}>+ {$t("study.music.source_connect")} →+ </button>+ {/if}+ <span class="arrows">+ <button+ type="button"+ class="arrow"+ disabled={saving || idx === 0}+ aria-label={$t("study.music.source_move_up") as string}+ onclick={() => moveUp(idx)}+ >▲</button>+ <button+ type="button"+ class="arrow"+ disabled={saving || idx === activeOrder.length - 1}+ aria-label={$t("study.music.source_move_down") as string}+ onclick={() => moveDown(idx)}+ >▼</button>+ </span>+ </li>+ {/each}+ </ol>++ {#if inactiveSources.length > 0}+ <section class="inactive">+ <h4 class="group-title">{$t("study.music.source_inactive_header")}</h4>+ <ul class="inactive-list">+ {#each inactiveSources as src (src.slug)}+ <li class="row dim">+ <span class="name">{SOURCE_LABEL[src.slug] ?? src.slug}</span>+ <span class="status off">+ {statusLabel(src.slug, src.available)}+ </span>+ {#if canConnect(src.slug)}+ <button type="button" class="link" onclick={() => openAuth(src.slug)}>+ {$t("study.music.source_connect")} →+ </button>+ {/if}+ </li>+ {/each}+ </ul>+ </section>+ {/if}++ <div class="footer">+ <button type="button" class="link reset" onclick={resetDefault} disabled={saving}>+ {$t("study.music.source_reset_default")}+ </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(620px, 92vw);+ max-height: 88vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 18px 20px 8px; }+ .head-text { display: flex; flex-direction: column; gap: 4px; }+ .head h3 { margin: 0; font-size: 16px; font-weight: 800; }+ .state { font-size: 12px; color: rgba(255, 255, 255, 0.55); }+ .close { width: 28px; height: 28px; background: transparent; border: 0; border-radius: 50%; color: rgba(255, 255, 255, 0.5); font-size: 18px; cursor: pointer; flex-shrink: 0; }+ .close:hover { color: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.06); }+ .body { padding: 8px 20px 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }+ .hint { margin: 0; color: rgba(255, 255, 255, 0.65); font-size: 13px; line-height: 1.5; }+ .loading { padding: 24px; text-align: center; color: rgba(255, 255, 255, 0.5); font-size: 12px; }++ .list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; counter-reset: src; }+ .row {+ display: grid;+ grid-template-columns: auto 1fr auto auto auto;+ align-items: center;+ gap: 10px;+ padding: 10px 12px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 10px;+ }+ .row.dim { opacity: 0.7; }+ .rank {+ width: 22px; height: 22px;+ display: grid; place-items: center;+ background: rgba(255, 255, 255, 0.06);+ border-radius: 50%;+ font-size: 11px; font-weight: 700;+ color: rgba(255, 255, 255, 0.7);+ }+ .name { font-size: 13px; font-weight: 600; }+ .status { font-size: 11px; padding: 2px 8px; border-radius: 999px; font-weight: 600; }+ .status.on { background: rgba(34, 197, 94, 0.15); color: rgb(74, 222, 128); }+ .status.off { background: rgba(255, 255, 255, 0.06); color: rgba(255, 255, 255, 0.45); }+ .link {+ background: transparent;+ border: 0;+ color: var(--accent);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ padding: 0;+ font-weight: 600;+ }+ .link:hover:not(:disabled) { text-decoration: underline; }+ .link:disabled { opacity: 0.4; cursor: default; }+ .link.reset { color: rgba(255, 255, 255, 0.5); }+ .link.reset:hover { color: rgba(255, 255, 255, 0.85); }+ .arrows { display: flex; flex-direction: column; gap: 2px; }+ .arrow {+ width: 22px;+ height: 16px;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 9px;+ cursor: pointer;+ border-radius: 3px;+ padding: 0;+ }+ .arrow:hover:not(:disabled) { background: rgba(255, 255, 255, 0.08); color: rgba(255, 255, 255, 0.9); }+ .arrow:disabled { opacity: 0.2; cursor: default; }++ .inactive { display: flex; flex-direction: column; gap: 6px; margin-top: 4px; }+ .group-title { margin: 0; font-size: 11px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: rgba(255, 255, 255, 0.45); }+ .inactive-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }+ .inactive-list .row { grid-template-columns: 1fr auto auto; }++ .footer { display: flex; justify-content: flex-end; padding-top: 6px; }+</style>diff --git a/src/lib/study-music-components/TrackRow.svelte b/src/lib/study-music-components/TrackRow.sveltenew file mode 100644index 00000000..2f13c20d--- /dev/null+++ b/src/lib/study-music-components/TrackRow.svelte@@ -0,0 +1,349 @@+<script lang="ts">+ import { fmtDuration, trackDisplayTitle } from "$lib/study-music/format";+ import { musicPlayer, type MusicTrack } 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";++ type Props = {+ track: MusicTrack;+ queue?: MusicTrack[];+ index?: number;+ showCover?: boolean;+ showAlbum?: boolean;+ showNumber?: boolean;+ showRemove?: boolean;+ onRemove?: (track: MusicTrack) => void;+ onContextMenu?: (e: MouseEvent, track: MusicTrack) => void;+ };++ let {+ track,+ queue,+ index = 0,+ showCover = true,+ showAlbum = false,+ showNumber = false,+ showRemove = false,+ onRemove,+ onContextMenu,+ }: Props = $props();++ const isCurrent = $derived(musicPlayer.currentTrack?.id === track.id);+ const isPlaying = $derived(isCurrent && !musicPlayer.paused);+ const isSelected = $derived(musicUI.isSelected(track.id));+ const hasSelection = $derived(musicUI.selectedCount() > 0);++ function handleClick(e: MouseEvent) {+ if (e.shiftKey && queue) {+ e.preventDefault();+ musicUI.selectRange(track.id, queue);+ return;+ }+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ musicUI.toggleSelected(track.id, queue);+ return;+ }+ if (hasSelection) {+ musicUI.clearSelection();+ }+ void musicPlayer.play(track, queue);+ }++ function handleContextMenu(e: MouseEvent) {+ e.preventDefault();+ if (onContextMenu) {+ onContextMenu(e, track);+ return;+ }+ if (!isSelected && hasSelection) {+ musicUI.selectOnly(track.id, queue);+ } else if (!hasSelection && queue) {+ musicUI.selectionAnchor = { trackId: track.id, queue };+ }+ musicUI.openContextMenu(track, e.clientX, e.clientY);+ }++ async function favoriteToggle(e: MouseEvent) {+ e.stopPropagation();+ await musicPlayer.toggleFavorite(track.id);+ track.favorite = !track.favorite;+ }+</script>++<div+ class="track-row"+ class:current={isCurrent}+ class:selected={isSelected}+ role="button"+ tabindex="0"+ onclick={handleClick}+ onkeydown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ void musicPlayer.play(track, queue);+ }+ }}+ oncontextmenu={handleContextMenu}+>+ {#if showNumber}+ <span class="track-num">+ {#if isPlaying}+ <span class="playing-dots" aria-hidden="true">+ <i></i><i></i><i></i>+ </span>+ {:else}+ <span class="num">{index + 1}</span>+ <span class="play-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>+ </span>+ {/if}+ </span>+ {/if}+ {#if showCover}+ <CoverImage+ src={track.cover_path}+ alt={track.title ?? track.path}+ size={36}+ fallbackSeed={track.album ?? track.title}+ rounded="sm"+ trackId={track.id}+ />+ {/if}+ <span class="track-info">+ <span class="track-title">{trackDisplayTitle(track)}</span>+ {#if track.artist}+ <span class="track-artist">{track.artist}</span>+ {/if}+ </span>+ {#if showAlbum && track.album}+ <span class="track-album">{track.album}</span>+ {/if}+ <button+ type="button"+ class="fav-btn"+ 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="14" height="14" 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="more-btn"+ onclick={(e) => {+ e.stopPropagation();+ musicUI.openAddToPlaylist(track);+ }}+ aria-label={$t("study.music.add_to_playlist") as string}+ title={$t("study.music.add_to_playlist") 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" aria-hidden="true">+ <line x1="12" y1="5" x2="12" y2="19"/>+ <line x1="5" y1="12" x2="19" y2="12"/>+ </svg>+ </button>+ {#if showRemove}+ <button+ type="button"+ class="remove-btn"+ onclick={(e) => {+ e.stopPropagation();+ onRemove?.(track);+ }}+ aria-label={$t("study.music.remove_from_playlist") as string}+ title={$t("study.music.remove_from_playlist") 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" aria-hidden="true">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ {/if}+ <span class="track-dur">{fmtDuration(track.duration_ms)}</span>+</div>++<style>+ .track-row {+ display: flex;+ align-items: center;+ gap: 12px;+ width: 100%;+ padding: 6px 12px;+ background: transparent;+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease;+ user-select: none;+ min-height: 48px;+ }+ .track-row:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 1px;+ }+ .track-row:hover {+ background: rgba(255, 255, 255, 0.05);+ }+ .track-row.current {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ }+ .track-row.current .track-title {+ color: var(--accent);+ }+ .track-row.selected {+ background: color-mix(in oklab, var(--accent) 22%, transparent);+ outline: 1px solid color-mix(in oklab, var(--accent) 50%, transparent);+ }+ .track-num {+ position: relative;+ flex-shrink: 0;+ width: 28px;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ }+ .track-num .play-icon {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ color: rgba(255, 255, 255, 0.95);+ opacity: 0;+ transition: opacity 120ms ease;+ }+ .track-row:hover .track-num .num {+ opacity: 0;+ }+ .track-row:hover .track-num .play-icon {+ opacity: 1;+ }+ .track-row :global(.cover) {+ flex-shrink: 0;+ }+ .track-info {+ flex: 1 1 auto;+ display: flex;+ flex-direction: column;+ min-width: 0;+ overflow: hidden;+ gap: 2px;+ }+ .track-title {+ font-size: 13px;+ font-weight: 600;+ color: rgba(255, 255, 255, 0.95);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ line-height: 1.3;+ }+ .track-artist {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.5);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ line-height: 1.3;+ }+ .track-album {+ flex: 0 1 auto;+ width: clamp(120px, 24vw, 240px);+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .fav-btn {+ flex-shrink: 0;+ 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;+ opacity: 0;+ transition: color 120ms ease, background 120ms ease, opacity 120ms ease;+ }+ .track-row:hover .fav-btn {+ opacity: 1;+ }+ .fav-btn.on {+ color: var(--accent);+ opacity: 1;+ }+ .fav-btn:hover {+ background: rgba(255, 255, 255, 0.1);+ color: var(--accent);+ }+ .more-btn,+ .remove-btn {+ flex-shrink: 0;+ 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;+ opacity: 0;+ transition: color 120ms ease, background 120ms ease, opacity 120ms ease;+ }+ .track-row:hover .more-btn,+ .track-row:hover .remove-btn {+ opacity: 1;+ }+ .more-btn:hover {+ color: var(--accent);+ background: rgba(255, 255, 255, 0.1);+ }+ .remove-btn:hover {+ color: var(--error, #dc2626);+ background: color-mix(in oklab, var(--error, #dc2626) 12%, transparent);+ }+ .track-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;+ }+ .playing-dots {+ display: inline-flex;+ align-items: flex-end;+ gap: 2px;+ height: 14px;+ }+ .playing-dots i {+ display: block;+ width: 3px;+ height: 100%;+ background: var(--accent);+ border-radius: 1px;+ animation: bars 0.9s ease-in-out infinite;+ }+ .playing-dots i:nth-child(2) { animation-delay: 0.15s; }+ .playing-dots i:nth-child(3) { animation-delay: 0.3s; }+ @keyframes bars {+ 0%, 100% { transform: scaleY(0.35); }+ 50% { transform: scaleY(1); }+ }+ @media (prefers-reduced-motion: reduce) {+ .playing-dots i { animation: none; transform: scaleY(0.7); }+ }+</style>diff --git a/src/lib/study-music-components/VolumeControl.svelte b/src/lib/study-music-components/VolumeControl.sveltenew file mode 100644index 00000000..c98795b0--- /dev/null+++ b/src/lib/study-music-components/VolumeControl.svelte@@ -0,0 +1,144 @@+<script lang="ts">+ import { musicPlayer } from "$lib/study-music/player-store.svelte";++ let trackEl = $state<HTMLDivElement | null>(null);+ let dragging = $state(false);++ const ratio = $derived(musicPlayer.muted ? 0 : musicPlayer.volume);++ function ratioFromEvent(e: PointerEvent): number {+ if (!trackEl) return 0;+ const rect = trackEl.getBoundingClientRect();+ const x = e.clientX - rect.left;+ return Math.max(0, Math.min(1, x / rect.width));+ }++ function onPointerDown(e: PointerEvent) {+ e.preventDefault();+ dragging = true;+ musicPlayer.setVolume(ratioFromEvent(e));+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);+ }++ function onPointerMove(e: PointerEvent) {+ if (!dragging) return;+ musicPlayer.setVolume(ratioFromEvent(e));+ }++ function onPointerUp(e: PointerEvent) {+ if (!dragging) return;+ dragging = false;+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);+ }+</script>++<div class="volume">+ <button+ type="button"+ class="mute-btn"+ onclick={() => musicPlayer.toggleMute()}+ aria-label={musicPlayer.muted ? "Tirar mudo" : "Mudo"}+ >+ {#if musicPlayer.muted || musicPlayer.volume === 0}+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>+ <line x1="23" y1="9" x2="17" y2="15"/>+ <line x1="17" y1="9" x2="23" y2="15"/>+ </svg>+ {:else if ratio < 0.4}+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>+ <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>+ </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">+ <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>+ <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>+ <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>+ </svg>+ {/if}+ </button>+ <div+ class="track"+ bind:this={trackEl}+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ role="slider"+ aria-valuemin="0"+ aria-valuemax="1"+ aria-valuenow={ratio}+ tabindex="0"+ >+ <div class="bar"></div>+ <div class="filled" style:width="{ratio * 100}%"></div>+ <div class="thumb" style:left="{ratio * 100}%"></div>+ </div>+</div>++<style>+ .volume {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }+ .mute-btn {+ background: transparent;+ border: 0;+ padding: 6px;+ color: var(--tertiary);+ cursor: pointer;+ display: grid;+ place-items: center;+ border-radius: 4px;+ transition: color 120ms ease, background 120ms ease;+ }+ .mute-btn:hover {+ color: var(--secondary);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .track {+ position: relative;+ width: 90px;+ height: 14px;+ cursor: pointer;+ display: flex;+ align-items: center;+ }+ .bar {+ position: absolute;+ inset: 50% 0 auto;+ transform: translateY(-50%);+ height: 4px;+ background: color-mix(in oklab, currentColor 20%, transparent);+ border-radius: 2px;+ }+ .filled {+ position: absolute;+ inset: 50% auto auto 0;+ transform: translateY(-50%);+ height: 4px;+ background: var(--secondary);+ border-radius: 2px;+ pointer-events: none;+ }+ .track:hover .filled {+ background: var(--accent);+ }+ .thumb {+ position: absolute;+ top: 50%;+ width: 10px;+ height: 10px;+ margin-left: -5px;+ margin-top: -5px;+ background: var(--secondary);+ border-radius: 50%;+ opacity: 0;+ pointer-events: none;+ transition: opacity 120ms ease;+ }+ .track:hover .thumb {+ opacity: 1;+ }+</style>diff --git a/src/lib/study-music-components/YoutubePanel.svelte b/src/lib/study-music-components/YoutubePanel.sveltenew file mode 100644index 00000000..c576904a--- /dev/null+++ b/src/lib/study-music-components/YoutubePanel.svelte@@ -0,0 +1,481 @@+<script lang="ts">+ import { onMount, onDestroy } from "svelte";+ import { invoke } from "@tauri-apps/api/core";+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";++ type Settings = {+ browser: string;+ audio_format_preference: string;+ sapisid_set: boolean;+ cookie_set: boolean;+ visitor_data_set: boolean;+ };++ type Props = {+ open: boolean;+ onClose: () => void;+ onImported?: () => void;+ };++ let { open, onClose, onImported }: Props = $props();++ let settings = $state<Settings | null>(null);+ let importUrl = $state("");+ let busy = $state(false);+ let sapisidInput = $state("");+ let cookieInput = $state("");+ let syncProgress = $state<{ stage: string; current?: number; total?: number; name?: string } | null>(null);+ let unlistenFns: UnlistenFn[] = [];++ async function load() {+ try {+ settings = await pluginInvoke<Settings>("study", "study:music:youtube:get_settings");+ } catch {+ settings = null;+ }+ }++ $effect(() => {+ if (open) void load();+ });++ type Status = {+ file_exists: boolean;+ file_path: string;+ last_modified_secs: number | null;+ age_seconds: number | null;+ total_cookies: number;+ domains: string[];+ };++ function fmtAge(secs: number | null | undefined): string {+ if (secs == null) return "—";+ if (secs < 60) return `${secs}s atrás`;+ if (secs < 3600) return `${Math.floor(secs / 60)} min atrás`;+ if (secs < 86400) return `${Math.floor(secs / 3600)} h atrás`;+ return `${Math.floor(secs / 86400)} dias atrás`;+ }++ async function importFromExtension() {+ if (busy) return;+ busy = true;+ try {+ const status = await invoke<Status>("extension_cookies_status");++ if (!status.file_exists) {+ showToast(+ "error",+ $t("study.music.yt_ext_no_file", {+ path: status.file_path,+ }) as string,+ );+ return;+ }++ const ageMin = status.age_seconds != null+ ? Math.floor(status.age_seconds / 60)+ : null;+ const hasYoutube = status.domains.some(+ (d) => d.endsWith("youtube.com") || d.endsWith("google.com"),+ );++ if (!hasYoutube) {+ showToast(+ "error",+ $t("study.music.yt_ext_no_youtube", {+ domains: status.domains.slice(0, 3).join(", ") || "(nenhum)",+ age: fmtAge(status.age_seconds),+ }) as string,+ );+ return;+ }++ type Bundle = {+ domain: string;+ cookie_string: string;+ well_known: Record<string, string>;+ cookies: Array<{ name: string; value: string }>;+ fetched_at: number;+ };+ const bundle = await invoke<Bundle | null>("read_extension_cookies", {+ domain: "youtube.com",+ });+ if (!bundle) {+ showToast("error", $t("study.music.yt_ext_empty") as string);+ return;+ }+ const sapisid = bundle.well_known["__Secure-3PAPISID"]+ ?? bundle.well_known["SAPISID"]+ ?? "";+ if (!sapisid) {+ showToast(+ "error",+ $t("study.music.yt_ext_no_sapisid_detail", {+ count: bundle.cookies.length,+ age: fmtAge(status.age_seconds),+ }) as string,+ );+ return;+ }+ const res = await pluginInvoke<Settings>(+ "study",+ "study:music:youtube:set_settings",+ {+ sapisid,+ cookie_string: bundle.cookie_string,+ },+ );+ settings = res;+ showToast(+ "success",+ $t("study.music.yt_ext_imported_detail", {+ count: bundle.cookies.length,+ age: fmtAge(status.age_seconds),+ }) as string,+ );+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function saveAuth() {+ if (busy) return;+ busy = true;+ try {+ const args: Record<string, string> = {};+ if (sapisidInput.trim()) args.sapisid = sapisidInput.trim();+ if (cookieInput.trim()) args.cookie_string = cookieInput.trim();+ const res = await pluginInvoke<Settings>(+ "study",+ "study:music:youtube:set_settings",+ args,+ );+ settings = res;+ sapisidInput = "";+ cookieInput = "";+ showToast("success", $t("study.music.yt_auth_saved") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function autoVisitorData() {+ if (busy) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:youtube:auto_visitor_data");+ await load();+ showToast("success", $t("study.music.yt_visitor_ok") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function disconnect() {+ if (busy || !window.confirm($t("study.music.yt_disconnect_confirm") as string)) return;+ busy = true;+ try {+ await pluginInvoke("study", "study:music:youtube:set_settings", {+ sapisid: "",+ cookie_string: "",+ visitor_data: "",+ });+ await load();+ showToast("success", $t("study.music.yt_disconnected") as string);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function importPlaylist() {+ if (!importUrl.trim() || busy) return;+ busy = true;+ try {+ const res = await pluginInvoke<{ title: string; imported: number }>(+ "study",+ "study:music:youtube:import_playlist",+ { url: importUrl.trim() },+ );+ showToast(+ "success",+ $t("study.music.yt_imported", {+ title: res.title || "playlist",+ count: res.imported,+ }) as string,+ );+ importUrl = "";+ onImported?.();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ }+ }++ async function syncLibrary() {+ if (busy) return;+ busy = true;+ syncProgress = { stage: "starting" };+ try {+ const res = await pluginInvoke<{ playlists: number; tracks: number }>(+ "study",+ "study:music:youtube:sync_library",+ );+ showToast(+ "success",+ $t("study.music.yt_sync_done", {+ playlists: res.playlists,+ tracks: res.tracks,+ }) as string,+ );+ onImported?.();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ busy = false;+ setTimeout(() => (syncProgress = null), 2000);+ }+ }++ onMount(async () => {+ try {+ unlistenFns.push(+ await listen<{ stage: string; current?: number; total?: number; name?: string }>(+ "study:music:youtube:sync_progress",+ (e) => {+ syncProgress = e.payload;+ },+ ),+ );+ } catch {+ /* ignore */+ }+ });++ onDestroy(() => {+ for (const fn of unlistenFns) fn();+ });++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ }++ const isAuthed = $derived((settings?.sapisid_set ?? false) || (settings?.cookie_set ?? false));+</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">+ <div class="head-text">+ <h3>{$t("study.music.yt_title")}</h3>+ {#if isAuthed}+ <span class="state on">✓ {$t("study.music.yt_state_authed")}</span>+ {:else}+ <span class="state off">{$t("study.music.yt_state_anon")}</span>+ {/if}+ </div>+ <button type="button" class="close" onclick={onClose} aria-label={$t("study.common.close") as string}>×</button>+ </header>+ <div class="body">+ <p class="hint">{$t("study.music.yt_intro")}</p>++ <section class="step">+ <span class="step-num">1</span>+ <div class="step-body">+ <h4>{$t("study.music.yt_auth_title")}</h4>+ <p class="step-desc">{$t("study.music.yt_auth_desc")}</p>+ <div class="ext-shortcut">+ <button type="button" class="cta-secondary" onclick={importFromExtension} disabled={busy}>+ <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <polyline points="20 6 9 17 4 12"/>+ </svg>+ {$t("study.music.yt_ext_import")}+ </button>+ <span class="ext-hint">{$t("study.music.yt_ext_hint")}</span>+ </div>+ <div class="manual-divider"><span>{$t("study.music.yt_or_manual")}</span></div>+ <details class="howto">+ <summary>{$t("study.music.yt_auth_how")}</summary>+ <ol>+ <li>{$t("study.music.yt_auth_step1")}</li>+ <li>{$t("study.music.yt_auth_step2")}</li>+ <li>{$t("study.music.yt_auth_step3")}</li>+ <li>{$t("study.music.yt_auth_step4")}</li>+ </ol>+ </details>+ <label class="field">+ <span>__Secure-3PAPISID</span>+ <input+ type="password"+ bind:value={sapisidInput}+ placeholder={settings?.sapisid_set ? "•••••• (já configurado)" : "AbcDef123..."}+ autocomplete="off"+ />+ </label>+ <label class="field">+ <span>{$t("study.music.yt_cookie_full")}</span>+ <textarea+ bind:value={cookieInput}+ placeholder={settings?.cookie_set ? "(já configurado)" : "VISITOR_INFO1_LIVE=...; SID=...; HSID=...; ..."}+ rows="2"+ ></textarea>+ <small>{$t("study.music.yt_cookie_hint")}</small>+ </label>+ <div class="row-actions">+ <button type="button" class="cta-secondary" onclick={saveAuth} disabled={busy || (!sapisidInput.trim() && !cookieInput.trim())}>+ {$t("study.music.yt_save_auth")}+ </button>+ {#if isAuthed}+ <button type="button" class="link danger" onclick={disconnect} disabled={busy}>+ {$t("study.music.yt_disconnect")}+ </button>+ {/if}+ </div>+ </div>+ </section>++ <section class="step">+ <span class="step-num">2</span>+ <div class="step-body">+ <h4>{$t("study.music.yt_step2_title")}</h4>+ <p class="step-desc">{$t("study.music.yt_step2_desc")}</p>+ <div class="import-row">+ <input+ type="text"+ bind:value={importUrl}+ placeholder="https://music.youtube.com/playlist?list=..."+ onkeydown={(e) => { if (e.key === "Enter") importPlaylist(); }}+ disabled={busy}+ />+ <button type="button" class="cta" onclick={importPlaylist} disabled={busy || !importUrl.trim()}>+ {$t("study.music.yt_import")}+ </button>+ </div>+ <ul class="example-list">+ <li><code>music.youtube.com/playlist?list=LM</code> — <span>{$t("study.music.yt_lm_label")}</span></li>+ <li><code>music.youtube.com/playlist?list=PLxxxx</code> — <span>{$t("study.music.yt_playlist_label")}</span></li>+ </ul>+ </div>+ </section>++ {#if isAuthed}+ <section class="step accent">+ <span class="step-num">3</span>+ <div class="step-body">+ <h4>{$t("study.music.yt_sync_title")}</h4>+ <p class="step-desc">{$t("study.music.yt_sync_desc")}</p>+ <button type="button" class="cta wide" onclick={syncLibrary} disabled={busy}>+ {busy ? $t("study.music.yt_syncing") : $t("study.music.yt_sync_now")}+ </button>+ {#if syncProgress}+ <div class="progress-line">+ {#if syncProgress.stage === "starting"}+ {$t("study.music.yt_sync_starting")}+ {:else if syncProgress.stage === "liked"}+ {$t("study.music.yt_sync_liked")}+ {:else if syncProgress.stage === "playlists"}+ {$t("study.music.yt_sync_playlists", { total: syncProgress.total ?? 0 })}+ {:else if syncProgress.stage === "playlist_fetch"}+ {syncProgress.current}/{syncProgress.total}: {syncProgress.name}+ {/if}+ </div>+ {/if}+ </div>+ </section>+ {/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(620px, 92vw);+ max-height: 88vh;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 18px 20px 8px; }+ .head-text { display: flex; flex-direction: column; gap: 4px; }+ .head h3 { margin: 0; font-size: 16px; font-weight: 800; }+ .state { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; font-size: 11px; font-weight: 600; width: fit-content; }+ .state.on { background: rgba(34, 197, 94, 0.15); color: rgb(74, 222, 128); }+ .state.off { background: rgba(255, 255, 255, 0.06); color: rgba(255, 255, 255, 0.45); }+ .close { width: 28px; height: 28px; background: transparent; border: 0; border-radius: 50%; color: rgba(255, 255, 255, 0.5); font-size: 18px; cursor: pointer; flex-shrink: 0; }+ .body { padding: 8px 20px 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; }+ .hint { margin: 0; color: rgba(255, 255, 255, 0.65); font-size: 13px; line-height: 1.5; }+ .step { display: flex; gap: 12px; padding: 14px; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 10px; }+ .step.accent { background: color-mix(in oklab, var(--accent) 10%, rgba(255,255,255,0.03)); border-color: color-mix(in oklab, var(--accent) 30%, transparent); }+ .step-num { flex-shrink: 0; width: 24px; height: 24px; display: grid; place-items: center; background: var(--accent); color: var(--on-accent, white); border-radius: 50%; font-size: 12px; font-weight: 700; }+ .step-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px; }+ .step-body h4 { margin: 0; font-size: 13px; font-weight: 700; }+ .step-desc { margin: 0; color: rgba(255, 255, 255, 0.6); font-size: 12px; line-height: 1.5; }+ .howto summary { cursor: pointer; font-size: 11px; color: rgba(255, 255, 255, 0.55); margin-bottom: 4px; }+ .howto ol { margin: 4px 0 8px 16px; padding: 0; font-size: 11px; color: rgba(255, 255, 255, 0.7); line-height: 1.5; }+ .howto li { margin-bottom: 2px; }+ .field { display: flex; flex-direction: column; gap: 4px; margin: 4px 0; }+ .field span { font-size: 11px; color: rgba(255, 255, 255, 0.5); text-transform: uppercase; letter-spacing: 0.06em; }+ .field input, .field textarea { padding: 8px 10px; 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: 11px; outline: none; resize: vertical; }+ .field input:focus, .field textarea:focus { border-color: var(--accent); }+ .field small { font-size: 11px; color: rgba(255, 255, 255, 0.4); }+ .row-actions { display: flex; align-items: center; gap: 8px; }+ .cta-secondary { padding: 7px 14px; border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 999px; background: transparent; color: rgba(255, 255, 255, 0.95); font-family: inherit; font-size: 12px; cursor: pointer; }+ .cta-secondary:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }+ .cta-secondary:disabled { opacity: 0.4; cursor: default; }+ .cta { padding: 8px 18px; border: 0; border-radius: 999px; background: var(--accent); color: var(--on-accent, white); font-family: inherit; font-size: 13px; font-weight: 700; cursor: pointer; }+ .cta.wide { width: 100%; padding: 10px 18px; }+ .cta:disabled { opacity: 0.5; cursor: default; }+ .link { background: transparent; border: 0; color: rgba(255, 255, 255, 0.5); font-family: inherit; font-size: 11px; cursor: pointer; padding: 0; }+ .link.danger:hover { color: rgb(248, 113, 113); }+ .import-row { display: flex; gap: 8px; }+ .import-row input { flex: 1; padding: 9px 12px; background: rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 8px; color: rgba(255, 255, 255, 0.95); font-family: ui-monospace, monospace; font-size: 12px; outline: none; }+ .import-row input:focus { border-color: var(--accent); }+ .example-list { list-style: none; margin: 4px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 11px; }+ .example-list code { background: rgba(0, 0, 0, 0.4); padding: 1px 6px; border-radius: 4px; color: rgba(255, 255, 255, 0.75); font-size: 10px; margin-right: 6px; }+ .example-list span { color: rgba(255, 255, 255, 0.55); }+ .progress-line { margin-top: 4px; padding: 6px 10px; background: rgba(0, 0, 0, 0.3); border-radius: 6px; font-size: 11px; color: rgba(255, 255, 255, 0.7); font-family: ui-monospace, monospace; }+ .ext-shortcut { display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: color-mix(in oklab, var(--accent) 8%, transparent); border: 1px solid color-mix(in oklab, var(--accent) 30%, transparent); border-radius: 8px; }+ .ext-shortcut .cta-secondary { display: inline-flex; align-items: center; gap: 6px; }+ .ext-hint { font-size: 11px; color: rgba(255, 255, 255, 0.65); flex: 1; }+ .manual-divider { display: flex; align-items: center; margin: 4px 0; color: rgba(255, 255, 255, 0.35); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; }+ .manual-divider::before, .manual-divider::after { content: ""; flex: 1; height: 1px; background: rgba(255, 255, 255, 0.08); }+ .manual-divider span { padding: 0 10px; }+</style>diff --git a/src/lib/study-music/dominant-color.ts b/src/lib/study-music/dominant-color.tsnew file mode 100644index 00000000..73de368a--- /dev/null+++ b/src/lib/study-music/dominant-color.ts@@ -0,0 +1,148 @@+import { convertFileSrc } from "@tauri-apps/api/core";++export type RGB = { r: number; g: number; b: number };++const cache = new Map<string, RGB>();+const inFlight = new Map<string, Promise<RGB | null>>();++const FALLBACK: RGB = { r: 35, g: 35, b: 38 };++function clampByte(n: number): number {+ return Math.max(0, Math.min(255, Math.round(n)));+}++function rgbToHsl(r: number, g: number, b: number): [number, number, number] {+ r /= 255;+ g /= 255;+ b /= 255;+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ if (max === min) return [0, 0, l];+ const d = max - min;+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);+ let h = 0;+ if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;+ else if (max === g) h = ((b - r) / d + 2) / 6;+ else h = ((r - g) / d + 4) / 6;+ return [h, s, l];+}++function hslToRgb(h: number, s: number, l: number): RGB {+ if (s === 0) {+ const v = clampByte(l * 255);+ return { r: v, g: v, b: v };+ }+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;+ const p = 2 * l - q;+ const hue = (t: number) => {+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ if (t < 1 / 6) return p + (q - p) * 6 * t;+ if (t < 1 / 2) return q;+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;+ return p;+ };+ return {+ r: clampByte(hue(h + 1 / 3) * 255),+ g: clampByte(hue(h) * 255),+ b: clampByte(hue(h - 1 / 3) * 255),+ };+}++function vibrantize(rgb: RGB): RGB {+ const [h, s, l] = rgbToHsl(rgb.r, rgb.g, rgb.b);+ const boostedS = Math.min(1, s * 1.4);+ const adjustedL = Math.max(0.18, Math.min(0.42, l));+ return hslToRgb(h, boostedS, adjustedL);+}++async function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.crossOrigin = "anonymous";+ img.onload = () => resolve(img);+ img.onerror = (e) => reject(e);+ img.src = src;+ });+}++function sampleAverage(img: HTMLImageElement): RGB {+ const W = 32;+ const H = 32;+ const canvas = document.createElement("canvas");+ canvas.width = W;+ canvas.height = H;+ const ctx = canvas.getContext("2d");+ if (!ctx) return FALLBACK;+ ctx.drawImage(img, 0, 0, W, H);+ let data: ImageData;+ try {+ data = ctx.getImageData(0, 0, W, H);+ } catch {+ return FALLBACK;+ }+ const buf = data.data;+ let r = 0;+ let g = 0;+ let b = 0;+ let count = 0;+ 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 luma = (rr * 0.299 + gg * 0.587 + bb * 0.114) | 0;+ if (luma < 18 || luma > 245) continue;+ r += rr;+ g += gg;+ b += bb;+ count++;+ }+ if (count === 0) return FALLBACK;+ return {+ r: (r / count) | 0,+ g: (g / count) | 0,+ b: (b / count) | 0,+ };+}++export async function dominantColorFromPath(path: string | null | undefined): Promise<RGB | null> {+ if (!path) return null;+ if (cache.has(path)) return cache.get(path)!;+ const existing = inFlight.get(path);+ if (existing) return existing;+ const promise = (async () => {+ try {+ const url = (() => {+ try {+ return convertFileSrc(path);+ } catch {+ return path;+ }+ })();+ const img = await loadImage(url);+ const avg = sampleAverage(img);+ const tinted = vibrantize(avg);+ cache.set(path, tinted);+ return tinted;+ } catch {+ return null;+ } finally {+ inFlight.delete(path);+ }+ })();+ inFlight.set(path, 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})`;+}++export function rgbToCssAlpha(rgb: RGB | null, alpha: number): string {+ if (!rgb) return `rgba(35,35,38,${alpha})`;+ return `rgba(${rgb.r},${rgb.g},${rgb.b},${alpha})`;+}diff --git a/src/lib/study-music/format.ts b/src/lib/study-music/format.tsnew file mode 100644index 00000000..ea75fce5--- /dev/null+++ b/src/lib/study-music/format.ts@@ -0,0 +1,62 @@+export function fmtDuration(ms: number | null | undefined): string {+ if (ms == null || ms <= 0 || !Number.isFinite(ms)) return "—";+ const total = Math.floor(ms / 1000);+ const h = Math.floor(total / 3600);+ const m = Math.floor((total % 3600) / 60);+ const s = total % 60;+ if (h > 0) {+ return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;+ }+ return `${m}:${String(s).padStart(2, "0")}`;+}++export function fmtDurationLong(ms: number | null | undefined): string {+ if (ms == null || ms <= 0 || !Number.isFinite(ms)) return "—";+ const total = Math.floor(ms / 1000);+ const h = Math.floor(total / 3600);+ const m = Math.floor((total % 3600) / 60);+ if (h > 0) return `${h}h ${m}min`;+ return `${m}min`;+}++export function fmtBitrate(kbps: number | null | undefined): string {+ if (!kbps || kbps <= 0) return "";+ return `${Math.round(kbps)} kbps`;+}++export function fmtSampleRate(hz: number | null | undefined): string {+ if (!hz || hz <= 0) return "";+ return `${(hz / 1000).toFixed(1)} kHz`;+}++export function colorFromString(s: string | null | undefined): string {+ if (!s) return "oklch(0.4 0.05 250)";+ let hash = 0;+ for (let i = 0; i < s.length; i++) {+ hash = (hash * 31 + s.charCodeAt(i)) | 0;+ }+ const hue = Math.abs(hash) % 360;+ return `oklch(0.45 0.12 ${hue})`;+}++export function fmtSecondsToTime(seconds: number): string {+ if (!Number.isFinite(seconds) || seconds < 0) return "0:00";+ const total = Math.floor(seconds);+ const m = Math.floor(total / 60);+ const s = total % 60;+ return `${m}:${String(s).padStart(2, "0")}`;+}++export function trackDisplayTitle(track: { title?: string | null; path: string }): string {+ if (track.title && track.title.trim().length > 0) return track.title;+ const norm = track.path.replace(/\\/g, "/");+ const seg = norm.split("/").filter(Boolean).pop() ?? track.path;+ return seg.replace(/\.[^.]+$/, "");+}++export function fileNameOf(path: string): string {+ if (!path) return "";+ const norm = path.replace(/\\/g, "/");+ const seg = norm.split("/").filter(Boolean).pop() ?? path;+ return seg;+}diff --git a/src/lib/study-music/hls-loader.svelte.ts b/src/lib/study-music/hls-loader.svelte.tsnew file mode 100644index 00000000..caf636f1--- /dev/null+++ b/src/lib/study-music/hls-loader.svelte.ts@@ -0,0 +1,78 @@+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;+}++export type HlsHandle = {+ destroy: () => void;+};++export async function attachHls(audio: HTMLAudioElement, m3u8Url: string): Promise<HlsHandle> {+ if (audio.canPlayType("application/vnd.apple.mpegurl") !== "") {+ audio.src = m3u8Url;+ return {+ destroy: () => {+ try {+ audio.src = "";+ } catch {+ /* ignore */+ }+ },+ };+ }++ await ensureHlsLoaded();+ if (!window.Hls || !window.Hls.isSupported()) {+ throw new Error("HLS não é suportado neste navegador");+ }++ const hls = new window.Hls({+ enableWorker: false,+ lowLatencyMode: false,+ });+ hls.loadSource(m3u8Url);+ hls.attachMedia(audio);++ return {+ destroy: () => {+ try {+ hls.destroy();+ } catch {+ /* ignore */+ }+ },+ };+}diff --git a/src/lib/study-music/lyrics-store.svelte.ts b/src/lib/study-music/lyrics-store.svelte.tsnew file mode 100644index 00000000..92e5bfde--- /dev/null+++ b/src/lib/study-music/lyrics-store.svelte.ts@@ -0,0 +1,133 @@+import { pluginInvoke } from "$lib/plugin-invoke";++export type LyricsLine = { time: number; text: string };++type FetchResult = {+ track_id: number;+ found: boolean;+ synced: string | null;+ plain: string | null;+ source: string | null;+ cached?: boolean;+};++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;+}++class LyricsStore {+ trackId = $state<number | null>(null);+ lines = $state<LyricsLine[]>([]);+ plain = $state<string | null>(null);+ loading = $state(false);+ notFound = $state(false);+ source = $state<string | null>(null);++ async loadFor(trackId: number, force = false) {+ if (this.trackId === trackId && !force && (this.lines.length > 0 || this.plain || this.notFound)) {+ return;+ }+ this.trackId = trackId;+ this.lines = [];+ this.plain = null;+ this.notFound = false;+ this.source = null;+ this.loading = true;+ try {+ const res = await pluginInvoke<FetchResult>(+ "study",+ "study:music:lyrics:fetch",+ { 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;+ }+ } catch {+ this.notFound = true;+ } finally {+ if (this.trackId === trackId) {+ this.loading = false;+ }+ }+ }++ async clear(trackId: number) {+ try {+ await pluginInvoke("study", "study:music:lyrics:clear", { id: trackId });+ } catch {+ /* ignore */+ }+ if (this.trackId === trackId) {+ this.lines = [];+ this.plain = null;+ this.notFound = false;+ this.source = null;+ }+ }++ reset() {+ this.trackId = null;+ this.lines = [];+ this.plain = null;+ this.notFound = false;+ this.source = null;+ this.loading = false;+ }++ activeIndex(currentTime: number): number {+ if (this.lines.length === 0) return -1;+ let lo = 0;+ let hi = this.lines.length - 1;+ let result = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (this.lines[mid].time <= currentTime) {+ result = mid;+ lo = mid + 1;+ } else {+ hi = mid - 1;+ }+ }+ return result;+ }+}++export const lyricsStore = new LyricsStore();diff --git a/src/lib/study-music/player-store.svelte.ts b/src/lib/study-music/player-store.svelte.tsnew file mode 100644index 00000000..6474fa23--- /dev/null+++ b/src/lib/study-music/player-store.svelte.ts@@ -0,0 +1,912 @@+import { convertFileSrc } from "@tauri-apps/api/core";+import { pluginInvoke } from "$lib/plugin-invoke";+import { dominantColorFromPath, type RGB } from "./dominant-color";+import { spotifySdk, type SpotifySdkState } from "./spotify-sdk.svelte";+import { attachHls, type HlsHandle } from "./hls-loader.svelte";++export type TrackSource = "local" | "spotify" | "youtube" | "soundcloud";++export type MusicTrack = {+ id: number;+ path: string;+ title: string | null;+ artist: string | null;+ album: string | null;+ album_artist?: string | null;+ track_number?: number | null;+ disc_number?: number | null;+ year?: number | null;+ genre?: string | null;+ duration_ms: number | null;+ cover_path: string | null;+ file_size?: number;+ sample_rate?: number | null;+ bitrate?: number | null;+ added_at?: number;+ last_played_at?: number | null;+ play_count?: number;+ favorite?: boolean;+ source?: TrackSource;+ spotify_uri?: string;+ spotify_cover_url?: string;+ youtube_url?: string;+ youtube_video_id?: string;+ youtube_thumbnail?: string;+ isrc?: string;+ soundcloud_id?: number;+ soundcloud_artwork_url?: string;+};++export type RepeatMode = "off" | "all" | "one";++export type EqPreset =+ | "flat"+ | "bass"+ | "vocal"+ | "treble"+ | "rock"+ | "pop"+ | "classical"+ | "electronic"+ | "custom";++export const EQ_BAND_FREQUENCIES = [60, 250, 1000, 4000, 12000] as const;++export const EQ_PRESETS: Record<EqPreset, number[]> = {+ flat: [0, 0, 0, 0, 0],+ bass: [6, 4, 0, -2, -3],+ vocal: [-2, -1, 4, 3, 0],+ treble: [-3, -2, 0, 4, 6],+ rock: [4, 2, -2, 3, 5],+ pop: [-1, 2, 4, 2, -1],+ classical: [3, 2, 0, 2, 4],+ electronic: [5, 3, -1, 2, 4],+ custom: [0, 0, 0, 0, 0],+};++const PERSIST_KEY = "study.music.player.v1";+const QUEUE_KEY = "study.music.queue.v1";++class MusicPlayerStore {+ private audio: HTMLAudioElement | null = null;+ private playStartedAt = 0;+ private accumulatedPlayedMs = 0;+ private lastReportTrackId: number | null = null;+ private queueSaveTimer: ReturnType<typeof setTimeout> | null = null;+ private eqContext: AudioContext | null = null;+ private eqSource: MediaElementAudioSourceNode | null = null;+ private eqFilters: BiquadFilterNode[] = [];+ private eqGainNode: GainNode | null = null;++ currentTrack = $state<MusicTrack | null>(null);+ queue = $state<MusicTrack[]>([]);+ queueIndex = $state(0);+ paused = $state(true);+ currentTime = $state(0);+ duration = $state(0);+ volume = $state(1);+ muted = $state(false);+ shuffle = $state(false);+ repeat = $state<RepeatMode>("off");+ ready = $state(false);+ loading = $state(false);+ error = $state<string | null>(null);+ eqEnabled = $state(false);+ eqGains = $state<number[]>([0, 0, 0, 0, 0]);+ eqPreset = $state<EqPreset>("flat");+ dominantColor = $state<RGB | null>(null);+ private mediaSessionInstalled = false;++ init() {+ if (this.audio || typeof window === "undefined") return;+ const audio = new Audio();+ audio.preload = "metadata";+ audio.crossOrigin = "anonymous";++ audio.addEventListener("play", () => {+ this.paused = false;+ this.playStartedAt = Date.now();+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) {+ navigator.mediaSession.playbackState = "playing";+ }+ });+ audio.addEventListener("pause", () => {+ this.paused = true;+ if (this.playStartedAt > 0) {+ this.accumulatedPlayedMs += Date.now() - this.playStartedAt;+ this.playStartedAt = 0;+ }+ this.scheduleQueueSave();+ if (typeof navigator !== "undefined" && "mediaSession" in navigator) {+ navigator.mediaSession.playbackState = "paused";+ }+ });+ audio.addEventListener("timeupdate", () => {+ this.currentTime = audio.currentTime;+ this.scheduleQueueSave();+ this.updateMediaSessionPosition();+ });+ audio.addEventListener("loadedmetadata", () => {+ this.duration = audio.duration || 0;+ this.ready = true;+ this.loading = false;+ this.updateMediaSessionPosition();+ });+ audio.addEventListener("loadstart", () => {+ this.loading = true;+ this.ready = false;+ });+ audio.addEventListener("canplay", () => {+ this.loading = false;+ });+ audio.addEventListener("ended", () => {+ this.handleEnded();+ });+ audio.addEventListener("error", () => {+ const err = audio.error;+ let msg = "Erro ao carregar áudio";+ if (err) {+ const codeMap: Record<number, string> = {+ 1: "abortado",+ 2: "rede falhou",+ 3: "decodificação falhou",+ 4: "formato não suportado",+ };+ const reason = codeMap[err.code] ?? `code ${err.code}`;+ msg = `Erro de áudio: ${reason}${err.message ? ` (${err.message})` : ""}`;+ console.error(+ "[player] audio error",+ { code: err.code, message: err.message, src: audio.src.slice(0, 200) },+ );+ }+ this.error = msg;+ this.loading = false;+ });+ audio.addEventListener("volumechange", () => {+ this.volume = audio.volume;+ this.muted = audio.muted;+ });++ try {+ const raw = localStorage.getItem(PERSIST_KEY);+ if (raw) {+ const data = JSON.parse(raw) as {+ volume?: number;+ shuffle?: boolean;+ repeat?: RepeatMode;+ muted?: boolean;+ eqEnabled?: boolean;+ eqGains?: number[];+ eqPreset?: EqPreset;+ };+ if (typeof data.volume === "number") {+ audio.volume = Math.min(1, Math.max(0, data.volume));+ }+ if (typeof data.shuffle === "boolean") this.shuffle = data.shuffle;+ if (data.repeat === "off" || data.repeat === "all" || data.repeat === "one") {+ this.repeat = data.repeat;+ }+ if (typeof data.muted === "boolean") audio.muted = data.muted;+ if (typeof data.eqEnabled === "boolean") this.eqEnabled = data.eqEnabled;+ if (Array.isArray(data.eqGains) && data.eqGains.length === 5) {+ this.eqGains = data.eqGains.map((g) =>+ Math.max(-12, Math.min(12, Number(g) || 0)),+ );+ }+ if (data.eqPreset && data.eqPreset in EQ_PRESETS) {+ this.eqPreset = data.eqPreset;+ }+ }+ } catch {+ /* ignore */+ }++ this.audio = audio;+ this.volume = audio.volume;+ this.muted = audio.muted;+ this.installMediaSession();+ this.restoreQueue();+ this.installSpotifySync();+ }++ private spotifyUnsub: (() => void) | null = null;+ private installSpotifySync() {+ if (this.spotifyUnsub) return;+ this.spotifyUnsub = spotifySdk.onState((state) => this.applySpotifyState(state));+ }++ private applySpotifyState(state: SpotifySdkState | null) {+ if (this.currentTrack?.source !== "spotify") return;+ if (!state) return;+ this.paused = state.paused;+ this.currentTime = state.position / 1000;+ this.duration = (state.duration || this.currentTrack.duration_ms || 0) / 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+ ) {+ const inQueue = this.queue.find((t) => t.spotify_uri === sdkUri);+ if (inQueue) {+ this.currentTrack = inQueue;+ this.queueIndex = this.queue.indexOf(inQueue);+ this.updateMediaSessionMetadata(inQueue);+ }+ }+ }++ private isSpotify(): boolean {+ return this.currentTrack?.source === "spotify";+ }++ private installMediaSession() {+ if (+ this.mediaSessionInstalled ||+ typeof navigator === "undefined" ||+ !("mediaSession" in navigator)+ ) {+ return;+ }+ try {+ navigator.mediaSession.setActionHandler("play", () => this.resume());+ navigator.mediaSession.setActionHandler("pause", () => this.pause());+ navigator.mediaSession.setActionHandler("previoustrack", () => this.prev());+ navigator.mediaSession.setActionHandler("nexttrack", () => this.next());+ navigator.mediaSession.setActionHandler("seekbackward", (e) => {+ const off = e.seekOffset ?? 10;+ this.seek(Math.max(0, this.currentTime - off));+ });+ navigator.mediaSession.setActionHandler("seekforward", (e) => {+ const off = e.seekOffset ?? 10;+ this.seek(this.currentTime + off);+ });+ navigator.mediaSession.setActionHandler("seekto", (e) => {+ if (typeof e.seekTime === "number") this.seek(e.seekTime);+ });+ navigator.mediaSession.setActionHandler("stop", () => this.pause());+ this.mediaSessionInstalled = true;+ } catch {+ /* not all UAs support every action */+ }+ }++ private updateMediaSessionMetadata(track: MusicTrack | null) {+ if (typeof navigator === "undefined" || !("mediaSession" in navigator)) return;+ if (!track) {+ navigator.mediaSession.metadata = null;+ return;+ }+ let artwork: MediaImage[] = [];+ if (track.cover_path) {+ try {+ const url = convertFileSrc(track.cover_path);+ artwork = [+ { src: url, sizes: "512x512", type: "image/jpeg" },+ ];+ } catch {+ /* ignore */+ }+ }+ try {+ navigator.mediaSession.metadata = new MediaMetadata({+ title: track.title ?? track.path,+ artist: track.artist ?? "",+ album: track.album ?? "",+ artwork,+ });+ } catch {+ /* ignore */+ }+ }++ private updateMediaSessionPosition() {+ if (+ typeof navigator === "undefined" ||+ !("mediaSession" in navigator) ||+ !("setPositionState" in navigator.mediaSession)+ ) {+ return;+ }+ if (!this.duration || !Number.isFinite(this.duration)) return;+ try {+ navigator.mediaSession.setPositionState({+ duration: this.duration,+ position: Math.min(this.currentTime, this.duration),+ playbackRate: 1,+ });+ } catch {+ /* ignore */+ }+ }++ private async refreshDominantColor(track: MusicTrack | null) {+ if (!track || !track.cover_path) {+ this.dominantColor = null;+ return;+ }+ const c = await dominantColorFromPath(track.cover_path);+ if (this.currentTrack?.id === track.id) {+ this.dominantColor = c;+ }+ }++ private restoreQueue() {+ if (!this.audio) return;+ try {+ const raw = localStorage.getItem(QUEUE_KEY);+ if (!raw) return;+ const data = JSON.parse(raw) as {+ queue?: MusicTrack[];+ queueIndex?: number;+ currentTime?: number;+ };+ if (!Array.isArray(data.queue) || data.queue.length === 0) return;+ const idx = Math.max(+ 0,+ Math.min((data.queueIndex ?? 0) | 0, data.queue.length - 1),+ );+ const track = data.queue[idx];+ if (!track || typeof track.path !== "string") return;+ this.queue = data.queue;+ this.queueIndex = idx;+ this.currentTrack = track;+ this.duration = (track.duration_ms ?? 0) / 1000;+ this.audio.src = convertFileSrc(track.path);+ this.updateMediaSessionMetadata(track);+ void this.refreshDominantColor(track);+ const t = Number(data.currentTime);+ if (Number.isFinite(t) && t > 0) {+ const onLoaded = () => {+ if (this.audio) this.audio.currentTime = t;+ this.audio?.removeEventListener("loadedmetadata", onLoaded);+ };+ this.audio.addEventListener("loadedmetadata", onLoaded);+ }+ } catch {+ /* ignore */+ }+ }++ private persist() {+ try {+ localStorage.setItem(+ PERSIST_KEY,+ JSON.stringify({+ volume: this.volume,+ shuffle: this.shuffle,+ repeat: this.repeat,+ muted: this.muted,+ eqEnabled: this.eqEnabled,+ eqGains: this.eqGains,+ eqPreset: this.eqPreset,+ }),+ );+ } catch {+ /* ignore */+ }+ }++ private scheduleQueueSave() {+ if (this.queueSaveTimer) return;+ this.queueSaveTimer = setTimeout(() => {+ this.queueSaveTimer = null;+ this.saveQueueNow();+ }, 1500);+ }++ private saveQueueNow() {+ if (typeof localStorage === "undefined") return;+ try {+ if (this.queue.length === 0 || !this.currentTrack) {+ localStorage.removeItem(QUEUE_KEY);+ return;+ }+ localStorage.setItem(+ QUEUE_KEY,+ JSON.stringify({+ queue: this.queue,+ queueIndex: this.queueIndex,+ currentTime: this.currentTime,+ }),+ );+ } catch {+ /* ignore */+ }+ }++ private ensureEqGraph() {+ if (!this.audio || this.eqContext) return;+ if (typeof window === "undefined" || !window.AudioContext) return;+ try {+ const ctx = new AudioContext();+ const source = ctx.createMediaElementSource(this.audio);+ const filters = EQ_BAND_FREQUENCIES.map((freq) => {+ const f = ctx.createBiquadFilter();+ f.type = "peaking";+ f.frequency.value = freq;+ f.Q.value = 1;+ f.gain.value = 0;+ return f;+ });+ const out = ctx.createGain();+ out.gain.value = 1;+ let node: AudioNode = source;+ for (const f of filters) {+ node.connect(f);+ node = f;+ }+ node.connect(out);+ out.connect(ctx.destination);+ this.eqContext = ctx;+ this.eqSource = source;+ this.eqFilters = filters;+ this.eqGainNode = out;+ this.applyEq();+ } catch {+ /* ignore — EQ optional */+ }+ }++ private applyEq() {+ if (this.eqFilters.length !== 5) return;+ const gains = this.eqEnabled ? this.eqGains : [0, 0, 0, 0, 0];+ for (let i = 0; i < 5; i++) {+ this.eqFilters[i].gain.value = gains[i] ?? 0;+ }+ }++ setEqEnabled(enabled: boolean) {+ this.eqEnabled = enabled;+ this.ensureEqGraph();+ this.applyEq();+ this.persist();+ }++ setEqGain(band: number, gainDb: number) {+ if (band < 0 || band >= 5) return;+ const next = [...this.eqGains];+ next[band] = Math.max(-12, Math.min(12, gainDb));+ this.eqGains = next;+ this.eqPreset = "custom";+ this.applyEq();+ this.persist();+ }++ setEqPreset(preset: EqPreset) {+ if (!(preset in EQ_PRESETS)) return;+ this.eqPreset = preset;+ if (preset !== "custom") {+ this.eqGains = [...EQ_PRESETS[preset]];+ }+ this.applyEq();+ this.persist();+ }++ async play(track: MusicTrack, queue?: MusicTrack[]) {+ this.init();++ void this.flushPlayReport();++ if (queue && queue.length > 0) {+ this.queue = queue;+ const idx = queue.findIndex(+ (t) =>+ t.id === track.id &&+ (t.source ?? "local") === (track.source ?? "local"),+ );+ this.queueIndex = idx >= 0 ? idx : 0;+ } else {+ const existingIdx = this.queue.findIndex(+ (t) =>+ t.id === track.id &&+ (t.source ?? "local") === (track.source ?? "local"),+ );+ if (existingIdx < 0) {+ this.queue = [track];+ this.queueIndex = 0;+ } else {+ this.queueIndex = existingIdx;+ }+ }++ this.currentTrack = track;+ this.error = null;+ this.ready = false;+ this.currentTime = 0;+ this.duration = (track.duration_ms ?? 0) / 1000;+ this.accumulatedPlayedMs = 0;+ this.playStartedAt = 0;+ this.lastReportTrackId = track.source === "spotify" ? null : track.id;++ if (track.source === "spotify") {+ await this.playSpotify(track);+ } else if (track.source === "youtube") {+ await this.playYoutube(track);+ } else if (track.source === "soundcloud") {+ await this.playSoundcloud(track);+ } else {+ await this.playLocal(track);+ }+ }++ soundcloudResolver:+ | ((track: MusicTrack) => Promise<{ url: string; is_hls: boolean }>)+ | 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;+ try {+ try {+ await spotifySdk.pause();+ } catch {+ /* ignore */+ }+ if (this.hlsHandle) {+ try {+ this.hlsHandle.destroy();+ } catch {+ /* ignore */+ }+ this.hlsHandle = null;+ }+ const { url, is_hls } = await this.soundcloudResolver(track);+ if (is_hls || url.includes(".m3u8")) {+ this.hlsHandle = await attachHls(this.audio, url);+ } else {+ this.audio.src = url;+ }+ await this.audio.play();+ this.ensureEqGraph();+ this.saveQueueNow();+ this.updateMediaSessionMetadata(track);+ } catch (e) {+ this.error = e instanceof Error ? e.message : "Erro ao tocar SoundCloud";+ this.loading = false;+ throw e;+ }+ }++ private async playYoutube(track: MusicTrack) {+ if (!this.audio) return;+ const videoId = track.youtube_video_id;+ if (!videoId) {+ this.error = "Video ID ausente";+ this.loading = false;+ return;+ }+ this.loading = true;+ 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;+ await this.audio.play();+ this.ensureEqGraph();+ this.saveQueueNow();+ this.updateMediaSessionMetadata(track);+ void this.refreshDominantColor(track);+ void pluginInvoke("study", "study:music:youtube:track_record_play", {+ video_id: videoId,+ }).catch(() => {});+ } catch (e) {+ this.error = e instanceof Error ? e.message : "Erro ao tocar (YouTube)";+ this.loading = false;+ }+ }++ private async playLocal(track: MusicTrack) {+ if (!this.audio) return;+ try {+ try {+ await spotifySdk.pause();+ } catch {+ /* ignore */+ }+ const isHttpUrl =+ track.path.startsWith("http://") || track.path.startsWith("https://");+ this.audio.src = isHttpUrl ? track.path : convertFileSrc(track.path);+ await this.audio.play();+ this.ensureEqGraph();+ this.saveQueueNow();+ this.updateMediaSessionMetadata(track);+ void this.refreshDominantColor(track);+ } catch (e) {+ this.error = e instanceof Error ? e.message : "Erro ao tocar";+ this.loading = false;+ }+ }++ spotifyFreeFallback: ((track: MusicTrack) => Promise<string>) | null = null;++ private async playSpotify(track: MusicTrack) {+ if (!track.spotify_uri) {+ this.error = "Faixa Spotify sem URI";+ return;+ }+ if (this.audio && !this.audio.paused) {+ try {+ this.audio.pause();+ } catch {+ /* ignore */+ }+ }+ this.loading = true;+ let sdkErr: unknown = null;+ try {+ await spotifySdk.ensureLoaded();+ const queueUris = this.queue+ .filter((t) => t.source === "spotify" && t.spotify_uri)+ .map((t) => t.spotify_uri as string);+ const startUri = track.spotify_uri;+ const orderedUris = (() => {+ const idx = queueUris.indexOf(startUri);+ if (idx < 0) return [startUri];+ return [...queueUris.slice(idx), ...queueUris.slice(0, idx)];+ })();+ await spotifySdk.play({ uris: orderedUris });+ this.saveQueueNow();+ this.updateMediaSessionMetadata(track);+ if (track.spotify_cover_url) {+ void this.refreshDominantColorFromUrl(track.spotify_cover_url);+ }+ return;+ } catch (e) {+ sdkErr = e;+ console.warn("[player] Spotify SDK failed, trying YouTube fallback:", e);+ }++ 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));+ }++ try {+ const url = await this.spotifyFreeFallback(track);+ track.youtube_url = url;+ this.audio.src = url;+ await this.audio.play();+ this.ensureEqGraph();+ 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;+ throw e;+ }+ }++ private async refreshDominantColorFromUrl(_url: string) {+ this.dominantColor = null;+ }++ togglePlay() {+ this.init();+ if (!this.currentTrack) return;+ if (this.isSpotify()) {+ void spotifySdk.togglePlay();+ return;+ }+ if (!this.audio) return;+ if (this.paused) {+ this.audio.play().catch((e) => {+ this.error = e instanceof Error ? e.message : String(e);+ });+ this.ensureEqGraph();+ } else {+ this.audio.pause();+ }+ }++ pause() {+ if (this.isSpotify()) {+ void spotifySdk.pause();+ return;+ }+ if (this.audio && !this.paused) this.audio.pause();+ }++ resume() {+ if (this.isSpotify()) {+ void spotifySdk.resume();+ return;+ }+ if (this.audio && this.paused && this.currentTrack) {+ this.audio.play().catch(() => {});+ this.ensureEqGraph();+ }+ }++ next() {+ if (this.isSpotify()) {+ void spotifySdk.next();+ return;+ }+ if (this.queue.length === 0) return;+ let nextIdx: number;+ if (this.shuffle && this.queue.length > 1) {+ do {+ nextIdx = Math.floor(Math.random() * this.queue.length);+ } while (nextIdx === this.queueIndex);+ } else {+ nextIdx = this.queueIndex + 1;+ if (nextIdx >= this.queue.length) {+ if (this.repeat === "all") {+ nextIdx = 0;+ } else {+ this.audio?.pause();+ return;+ }+ }+ }+ this.queueIndex = nextIdx;+ void this.play(this.queue[nextIdx], this.queue);+ }++ prev() {+ if (this.isSpotify()) {+ void spotifySdk.prev();+ return;+ }+ if (this.queue.length === 0) return;+ if (this.audio && this.audio.currentTime > 3) {+ this.audio.currentTime = 0;+ return;+ }+ let prevIdx = this.queueIndex - 1;+ if (prevIdx < 0) {+ prevIdx = this.repeat === "all" ? this.queue.length - 1 : 0;+ }+ this.queueIndex = prevIdx;+ void this.play(this.queue[prevIdx], this.queue);+ }++ seek(seconds: number) {+ if (this.isSpotify()) {+ const ms = Math.max(0, seconds * 1000);+ void spotifySdk.seek(ms);+ 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));+ }++ seekRatio(ratio: number) {+ const dur = this.duration;+ if (!Number.isFinite(dur) || dur <= 0) return;+ this.seek(dur * Math.max(0, Math.min(1, ratio)));+ }++ setVolume(v: number) {+ const clamped = Math.max(0, Math.min(1, v));+ if (this.isSpotify()) {+ void spotifySdk.setVolume(clamped);+ this.volume = clamped;+ this.persist();+ return;+ }+ if (!this.audio) return;+ this.audio.volume = clamped;+ if (clamped > 0 && this.audio.muted) this.audio.muted = false;+ this.persist();+ }++ toggleMute() {+ if (this.isSpotify()) {+ const next = !this.muted;+ void spotifySdk.setVolume(next ? 0 : this.volume);+ this.muted = next;+ this.persist();+ return;+ }+ if (!this.audio) return;+ this.audio.muted = !this.audio.muted;+ this.persist();+ }++ toggleShuffle() {+ this.shuffle = !this.shuffle;+ this.persist();+ }++ cycleRepeat() {+ const order: RepeatMode[] = ["off", "all", "one"];+ const cur = order.indexOf(this.repeat);+ this.repeat = order[(cur + 1) % order.length];+ this.persist();+ }++ clearQueue() {+ this.audio?.pause();+ this.queue = [];+ this.queueIndex = 0;+ this.currentTrack = null;+ this.currentTime = 0;+ this.duration = 0;+ this.saveQueueNow();+ }++ private handleEnded() {+ void this.flushPlayReport();+ if (this.repeat === "one" && this.audio) {+ this.audio.currentTime = 0;+ this.audio.play().catch(() => {});+ return;+ }+ this.next();+ }++ private async flushPlayReport() {+ const track_id = this.lastReportTrackId;+ if (!track_id) return;+ if (this.playStartedAt > 0) {+ this.accumulatedPlayedMs += Date.now() - this.playStartedAt;+ this.playStartedAt = 0;+ }+ const positionMs = Math.floor((this.currentTime || 0) * 1000);+ const durationPlayedMs = this.accumulatedPlayedMs;+ this.accumulatedPlayedMs = 0;+ this.lastReportTrackId = null;+ if (durationPlayedMs <= 0) return;+ try {+ await pluginInvoke("study", "study:music:play:record", {+ trackId: track_id,+ positionMs,+ durationPlayedMs,+ });+ } catch {+ /* ignore */+ }+ }++ async toggleFavorite(trackId: number): Promise<boolean | null> {+ try {+ const res = await pluginInvoke<{ favorite: boolean }>(+ "study",+ "study:music:favorite:toggle",+ { trackId },+ );+ if (this.currentTrack && this.currentTrack.id === trackId) {+ this.currentTrack = { ...this.currentTrack, favorite: res.favorite };+ }+ return res.favorite;+ } catch {+ return null;+ }+ }++ reportNow() {+ void this.flushPlayReport();+ this.saveQueueNow();+ }+}++export const musicPlayer = new MusicPlayerStore();++if (typeof window !== "undefined") {+ window.addEventListener("beforeunload", () => {+ musicPlayer.reportNow();+ });+}diff --git a/src/lib/study-music/playlists-store.svelte.ts b/src/lib/study-music/playlists-store.svelte.tsnew file mode 100644index 00000000..3f8f667f--- /dev/null+++ b/src/lib/study-music/playlists-store.svelte.ts@@ -0,0 +1,92 @@+import { pluginInvoke } from "$lib/plugin-invoke";++export type Playlist = {+ id: number;+ name: string;+ description: string | null;+ cover_path: string | null;+ created_at: number;+ updated_at: number;+ track_count: number;+ resolved_cover: string | null;+};++class PlaylistsStore {+ list = $state<Playlist[]>([]);+ loaded = $state(false);+ loading = $state(false);++ async load(force = false) {+ if (this.loaded && !force) return;+ this.loading = true;+ try {+ const res = await pluginInvoke<{ playlists: Playlist[] }>(+ "study",+ "study:music:playlists:list",+ );+ this.list = res.playlists ?? [];+ this.loaded = true;+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn("[music] playlists load failed", e);+ }+ } finally {+ this.loading = false;+ }+ }++ async create(name: string, description?: string): Promise<number | null> {+ try {+ const res = await pluginInvoke<{ id: number }>(+ "study",+ "study:music:playlists:create",+ { name, description: description ?? null },+ );+ await this.load(true);+ return res.id;+ } catch (e) {+ throw e;+ }+ }++ async deleteOne(id: number) {+ await pluginInvoke("study", "study:music:playlists:delete", { id });+ await this.load(true);+ }++ async addTrack(playlistId: number, trackId: number): Promise<{ duplicate: boolean }> {+ const res = await pluginInvoke<{ duplicate?: boolean }>(+ "study",+ "study:music:playlists:add_track",+ { playlistId, trackId },+ );+ await this.load(true);+ return { duplicate: !!res.duplicate };+ }++ async removeTrack(playlistId: number, trackId: number) {+ await pluginInvoke("study", "study:music:playlists:remove_track", {+ playlistId,+ trackId,+ });+ await this.load(true);+ }++ async reorder(playlistId: number, trackIds: number[]) {+ await pluginInvoke("study", "study:music:playlists:reorder", {+ playlistId,+ trackIds,+ });+ await this.load(true);+ }++ async update(playlistId: number, name?: string, description?: string | null) {+ const args: Record<string, unknown> = { id: playlistId };+ if (name !== undefined) args.name = name;+ if (description !== undefined) args.description = description;+ await pluginInvoke("study", "study:music:playlists:update", args);+ await this.load(true);+ }+}++export const playlistsStore = new PlaylistsStore();diff --git a/src/lib/study-music/soundcloud-store.svelte.ts b/src/lib/study-music/soundcloud-store.svelte.tsnew file mode 100644index 00000000..7f0f1aeb--- /dev/null+++ b/src/lib/study-music/soundcloud-store.svelte.ts@@ -0,0 +1,401 @@+import { pluginInvoke } from "$lib/plugin-invoke";+import { musicPlayer, type MusicTrack } from "./player-store.svelte";++export type ScUser = {+ id: number;+ username: string;+ permalink: string;+ permalink_url: string;+ avatar_url: string | null;+ followers_count?: number;+ followings_count?: number;+ description?: string | null;+ city?: string | null;+ country_code?: string | null;+};++export type ScTrack = {+ id: number;+ title: string;+ duration: number;+ artwork_url: string | null;+ permalink_url: string;+ streamable: boolean;+ downloadable: boolean;+ user: ScUser;+ display_date?: string;+ genre?: string | null;+ description?: string | null;+ tag_list?: string;+ likes_count?: number;+ playback_count?: number;+};++export type ScPlaylist = {+ id: number;+ title: string;+ permalink_url: string;+ artwork_url: string | null;+ track_count: number;+ duration: number;+ is_album: boolean;+ user: ScUser;+ tracks?: ScTrack[];+ description?: string | null;+};++export type ScQuality = {+ id: string;+ label: string;+ protocol: string;+ quality: string;+ preset?: string;+ mime_type?: string;+ is_premium: boolean;+};++type AuthStatus = {+ has_client_id: boolean;+ has_oauth: boolean;+ user_id: number | null;+};++function bigArtwork(url: string | null | undefined): string | null {+ if (!url) return null;+ return url.replace(/-(large|t300x300|t120x120|t67x67|small|tiny|mini)\./, "-t500x500.");+}++function mapUser(u: any): ScUser | null {+ if (!u || typeof u.id !== "number") return null;+ return {+ id: u.id,+ username: u.username ?? "",+ permalink: u.permalink ?? "",+ permalink_url: u.permalink_url ?? "",+ avatar_url: u.avatar_url ?? null,+ followers_count: u.followers_count,+ followings_count: u.followings_count,+ description: u.description ?? null,+ city: u.city ?? null,+ country_code: u.country_code ?? null,+ };+}++export function mapTrack(t: any): ScTrack | null {+ if (!t || typeof t.id !== "number") return null;+ const user = mapUser(t.user);+ if (!user) return null;+ return {+ id: t.id,+ title: t.title ?? "",+ duration: t.duration ?? 0,+ artwork_url: t.artwork_url ?? null,+ permalink_url: t.permalink_url ?? "",+ streamable: !!t.streamable,+ downloadable: !!t.downloadable,+ user,+ display_date: t.display_date,+ genre: t.genre ?? null,+ description: t.description ?? null,+ tag_list: t.tag_list,+ likes_count: t.likes_count,+ playback_count: t.playback_count,+ };+}++export function mapPlaylist(p: any): ScPlaylist | null {+ if (!p || typeof p.id !== "number") return null;+ const user = mapUser(p.user);+ if (!user) return null;+ const tracks: ScTrack[] = Array.isArray(p.tracks)+ ? (p.tracks as any[]).map(mapTrack).filter((t): t is ScTrack => !!t)+ : [];+ return {+ id: p.id,+ title: p.title ?? "",+ permalink_url: p.permalink_url ?? "",+ artwork_url: p.artwork_url ?? null,+ track_count: p.track_count ?? tracks.length,+ duration: p.duration ?? 0,+ is_album: !!p.is_album,+ user,+ tracks,+ description: p.description ?? null,+ };+}++export function scTrackToMusicTrack(t: ScTrack): MusicTrack {+ return {+ id: -(t.id + 1_000_000_000),+ path: `soundcloud:track:${t.id}`,+ title: t.title,+ artist: t.user.username,+ album: null,+ duration_ms: t.duration,+ cover_path: null,+ source: "soundcloud" as any,+ soundcloud_id: t.id,+ soundcloud_artwork_url: bigArtwork(t.artwork_url) ?? bigArtwork(t.user.avatar_url) ?? undefined,+ } as MusicTrack & { soundcloud_id: number; soundcloud_artwork_url?: string };+}++class SoundCloudStore {+ status = $state<AuthStatus>({+ has_client_id: false,+ has_oauth: false,+ user_id: null,+ });+ profile = $state<ScUser | null>(null);+ likedTracks = $state<ScTrack[]>([]);+ playlists = $state<ScPlaylist[]>([]);+ followings = $state<ScUser[]>([]);+ streamFeed = $state<ScTrack[]>([]);+ loading = $state(false);+ error = $state<string | null>(null);++ pickArtwork = bigArtwork;++ get isLoggedIn(): boolean {+ return this.status.has_oauth && !!this.status.user_id;+ }++ get hasOauth(): boolean {+ return this.status.has_oauth;+ }++ async refreshStatus() {+ try {+ const s = await pluginInvoke<AuthStatus>("study", "study:soundcloud:auth:refresh");+ this.status = s;+ if (s.has_oauth && s.user_id == null) {+ try {+ const me = await pluginInvoke<any>("study", "study:soundcloud:me");+ this.profile = mapUser(me);+ if (this.profile) this.status = { ...this.status, user_id: this.profile.id };+ } catch (e) {+ console.warn("[soundcloud] me failed:", e);+ }+ } else if (s.user_id) {+ try {+ const me = await pluginInvoke<any>("study", "study:soundcloud:me");+ this.profile = mapUser(me);+ } catch {+ /* ignore */+ }+ }+ } catch (e) {+ this.error = e instanceof Error ? e.message : String(e);+ }+ }++ async logout() {+ try {+ await pluginInvoke("study", "study:soundcloud:auth:logout");+ } finally {+ this.profile = null;+ this.likedTracks = [];+ this.playlists = [];+ this.followings = [];+ this.streamFeed = [];+ await this.refreshStatus();+ }+ }++ async loadAll() {+ if (!this.isLoggedIn) return;+ this.loading = true;+ try {+ const [likedRes, playlistsRes, followingsRes, streamRes] = await Promise.allSettled([+ pluginInvoke<{ collection?: any[] }>("study", "study:soundcloud:liked_tracks", {+ limit: 50,+ offset: 0,+ }),+ pluginInvoke<{ collection?: any[] }>("study", "study:soundcloud:user_playlists", {+ limit: 50,+ offset: 0,+ }),+ pluginInvoke<{ collection?: any[] }>("study", "study:soundcloud:followings", {+ limit: 50,+ offset: 0,+ }),+ pluginInvoke<{ collection?: any[] }>("study", "study:soundcloud:stream_feed", {+ limit: 50,+ offset: 0,+ }),+ ]);++ if (likedRes.status === "fulfilled") {+ const items = likedRes.value.collection ?? [];+ this.likedTracks = items+ .map((it: any) => mapTrack(it.track ?? it))+ .filter((t): t is ScTrack => !!t);+ }+ if (playlistsRes.status === "fulfilled") {+ const items = playlistsRes.value.collection ?? [];+ this.playlists = items.map(mapPlaylist).filter((p): p is ScPlaylist => !!p);+ }+ if (followingsRes.status === "fulfilled") {+ const items = followingsRes.value.collection ?? [];+ this.followings = items.map(mapUser).filter((u): u is ScUser => !!u);+ }+ if (streamRes.status === "fulfilled") {+ const items = streamRes.value.collection ?? [];+ const tracks: ScTrack[] = [];+ const seen = new Set<number>();+ for (const it of items) {+ const t = mapTrack(it.track ?? it.origin?.track ?? it.origin ?? it);+ if (t && !seen.has(t.id)) {+ tracks.push(t);+ seen.add(t.id);+ }+ }+ this.streamFeed = tracks;+ }+ } finally {+ this.loading = false;+ }+ }++ async getPlaylist(playlistId: number): Promise<ScPlaylist | null> {+ const v = await pluginInvoke<any>("study", "study:soundcloud:playlist:get", {+ playlistId,+ });+ return mapPlaylist(v);+ }++ async getUser(userId: number): Promise<ScUser | null> {+ const v = await pluginInvoke<any>("study", "study:soundcloud:user:get", { userId });+ return mapUser(v);+ }++ async getUserTracks(userId: number, limit = 50): Promise<ScTrack[]> {+ const res = await pluginInvoke<{ collection?: any[] }>(+ "study",+ "study:soundcloud:user:tracks",+ { userId, limit, offset: 0 },+ );+ return (res.collection ?? []).map(mapTrack).filter((t): t is ScTrack => !!t);+ }++ async getUserPlaylists(userId: number, limit = 50): Promise<ScPlaylist[]> {+ const res = await pluginInvoke<{ collection?: any[] }>(+ "study",+ "study:soundcloud:user:playlists",+ { userId, limit, offset: 0 },+ );+ return (res.collection ?? []).map(mapPlaylist).filter((p): p is ScPlaylist => !!p);+ }++ async search(+ kind: "tracks" | "users" | "albums" | "playlists",+ q: string,+ limit = 20,+ ) {+ const res = await pluginInvoke<{ collection?: any[] }>(+ "study",+ "study:soundcloud:search",+ { kind, q, limit },+ );+ const items = res.collection ?? [];+ if (kind === "users") return items.map(mapUser).filter((u): u is ScUser => !!u);+ if (kind === "playlists" || kind === "albums")+ return items.map(mapPlaylist).filter((p): p is ScPlaylist => !!p);+ return items.map(mapTrack).filter((t): t is ScTrack => !!t);+ }++ async listQualities(trackId: number): Promise<ScQuality[]> {+ const res = await pluginInvoke<{ qualities: ScQuality[] }>(+ "study",+ "study:soundcloud:list_qualities",+ { trackId },+ );+ return res.qualities ?? [];+ }++ async resolveStream(trackId: number, quality = "progressive"): Promise<{+ url: string;+ is_hls: boolean;+ mime_type: string;+ quality: string;+ }> {+ return pluginInvoke("study", "study:soundcloud:stream:resolve", {+ trackId,+ quality,+ });+ }++ async download(opts: {+ trackId: number;+ codec: string;+ outputDir: string;+ quality: string;+ }): Promise<{ path: string; codec: string; quality: string }> {+ return pluginInvoke("study", "study:soundcloud:download", opts);+ }++ async downloadPlaylist(opts: {+ playlistId: number;+ codec: string;+ outputDir: string;+ quality: string;+ }): Promise<{ total: number; success: number; failed: number; files: string[] }> {+ return pluginInvoke("study", "study:soundcloud:download:playlist", opts);+ }++ async resolveAnyUrl(url: string): Promise<{ kind: string; id: number; title: string; data: any }> {+ return pluginInvoke("study", "study:soundcloud:resolve_url", { url });+ }++ async relatedTracks(trackId: number, limit = 12): Promise<ScTrack[]> {+ const res = await pluginInvoke<{ collection?: any[] }>(+ "study",+ "study:soundcloud:track:related",+ { trackId, limit },+ );+ return (res.collection ?? []).map(mapTrack).filter((t): t is ScTrack => !!t);+ }++ async toggleLike(trackId: number, currentlyLiked: boolean): Promise<boolean> {+ if (currentlyLiked) {+ await pluginInvoke("study", "study:soundcloud:like:remove", { trackId });+ this.likedTracks = this.likedTracks.filter((t) => t.id !== trackId);+ return false;+ }+ await pluginInvoke("study", "study:soundcloud:like:add", { trackId });+ return true;+ }++ async playTrack(track: ScTrack, queue?: ScTrack[]): Promise<void> {+ const local = scTrackToMusicTrack(track);+ const localQueue = (queue && queue.length > 0 ? queue : [track]).map(scTrackToMusicTrack);+ await musicPlayer.play(local, localQueue);+ }+}++export const soundcloudStore = new SoundCloudStore();++async function resolveSoundcloudStream(+ track: MusicTrack,+): Promise<{ url: string; is_hls: boolean }> {+ const scId = (track as any).soundcloud_id as number | undefined;+ if (!scId) throw new Error("Track sem soundcloud_id");+ const res = await pluginInvoke<{ url: string; is_hls: boolean }>(+ "study",+ "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;+ }+ return res;+}++if (typeof window !== "undefined") {+ (musicPlayer as any).soundcloudResolver = resolveSoundcloudStream;+}diff --git a/src/lib/study-music/spotify-sdk.svelte.ts b/src/lib/study-music/spotify-sdk.svelte.tsnew file mode 100644index 00000000..c1971b8c--- /dev/null+++ b/src/lib/study-music/spotify-sdk.svelte.ts@@ -0,0 +1,291 @@+import { pluginInvoke } from "$lib/plugin-invoke";++declare global {+ interface Window {+ onSpotifyWebPlaybackSDKReady?: () => void;+ Spotify?: {+ Player: new (opts: SpotifyPlayerOptions) => SpotifyPlayer;+ };+ }+}++type SpotifyPlayerOptions = {+ name: string;+ getOAuthToken: (cb: (token: string) => void) => void;+ volume?: number;+};++type SpotifyPlayerEvent =+ | "ready"+ | "not_ready"+ | "initialization_error"+ | "authentication_error"+ | "account_error"+ | "playback_error"+ | "player_state_changed";++type SpotifyPlayer = {+ connect(): Promise<boolean>;+ disconnect(): void;+ addListener(event: SpotifyPlayerEvent, cb: (data: any) => void): void;+ removeListener(event: SpotifyPlayerEvent): void;+ pause(): Promise<void>;+ resume(): Promise<void>;+ togglePlay(): Promise<void>;+ seek(positionMs: number): Promise<void>;+ nextTrack(): Promise<void>;+ previousTrack(): Promise<void>;+ setVolume(volume: number): Promise<void>;+ getVolume(): Promise<number>;+ getCurrentState(): Promise<SpotifySdkState | null>;+ setName(name: string): Promise<void>;+};++export type SpotifySdkState = {+ paused: boolean;+ position: number;+ duration: number;+ shuffle: boolean;+ repeat_mode: number;+ track_window: {+ current_track: {+ id: string;+ uri: string;+ name: string;+ duration_ms: number;+ artists: { name: string; uri: string }[];+ album: { name: string; uri: string; images: { url: string }[] };+ };+ };+};++const SDK_SCRIPT = "https://sdk.scdn.co/spotify-player.js";+const DEVICE_NAME = "OmniGet";++class SpotifySdkController {+ ready = $state(false);+ deviceId = $state<string | null>(null);+ unavailableReason = $state<string | null>(null);+ loading = $state(false);+ state = $state<SpotifySdkState | null>(null);++ private player: SpotifyPlayer | null = null;+ private loadingPromise: Promise<void> | null = null;+ private stateListeners = new Set<(state: SpotifySdkState | null) => void>();++ onState(cb: (state: SpotifySdkState | null) => void): () => void {+ this.stateListeners.add(cb);+ return () => this.stateListeners.delete(cb);+ }++ private emitState(state: SpotifySdkState | null) {+ this.state = state;+ for (const cb of this.stateListeners) {+ try {+ cb(state);+ } catch {+ /* ignore listener errors */+ }+ }+ }++ async checkWidevine(): Promise<boolean> {+ if (typeof navigator === "undefined" || !navigator.requestMediaKeySystemAccess) {+ return false;+ }+ try {+ const config: MediaKeySystemConfiguration[] = [+ {+ initDataTypes: ["cenc"],+ audioCapabilities: [+ { contentType: 'audio/mp4;codecs="mp4a.40.2"' },+ ],+ },+ ];+ await navigator.requestMediaKeySystemAccess("com.widevine.alpha", config);+ return true;+ } catch {+ return false;+ }+ }++ async ensureLoaded(): Promise<void> {+ if (this.player && this.ready) return;+ if (this.loadingPromise) return this.loadingPromise;++ this.loading = true;+ this.unavailableReason = null;++ this.loadingPromise = new Promise<void>((resolve, reject) => {+ void (async () => {+ const widevine = await this.checkWidevine();+ if (!widevine) {+ this.unavailableReason =+ "Widevine DRM não está disponível neste sistema. Spotify playback nativo não vai funcionar — use a Fase 1 (transfer pra outro device).";+ this.loading = false;+ reject(new Error(this.unavailableReason));+ return;+ }++ const onSdkReady = () => {+ if (!window.Spotify) {+ this.unavailableReason = "SDK do Spotify carregou mas Spotify global não foi exposto";+ this.loading = false;+ reject(new Error(this.unavailableReason));+ return;+ }++ const player = new window.Spotify.Player({+ name: DEVICE_NAME,+ getOAuthToken: async (cb) => {+ try {+ const res = await pluginInvoke<{ access_token: string }>(+ "study",+ "study:spotify:auth:access_token",+ );+ cb(res.access_token);+ } catch (e) {+ console.error("[spotify-sdk] failed to get access_token:", e);+ }+ },+ volume: 1.0,+ });++ player.addListener("ready", ({ device_id }: { device_id: string }) => {+ this.deviceId = device_id;+ this.ready = true;+ this.loading = false;+ resolve();+ });+ player.addListener("not_ready", () => {+ this.ready = false;+ });+ player.addListener(+ "initialization_error",+ ({ message }: { message: string }) => {+ this.unavailableReason = `init: ${message}`;+ this.loading = false;+ reject(new Error(message));+ },+ );+ player.addListener(+ "authentication_error",+ ({ message }: { message: string }) => {+ this.unavailableReason = `auth: ${message}`;+ },+ );+ player.addListener(+ "account_error",+ ({ message }: { message: string }) => {+ this.unavailableReason = `Spotify Premium é obrigatório (${message})`;+ },+ );+ player.addListener(+ "playback_error",+ ({ message }: { message: string }) => {+ console.warn("[spotify-sdk] playback error:", message);+ },+ );+ player.addListener(+ "player_state_changed",+ (state: SpotifySdkState | null) => {+ this.emitState(state);+ },+ );++ this.player = player;+ void player.connect().catch((e) => {+ this.unavailableReason = `connect: ${String(e)}`;+ this.loading = false;+ reject(e);+ });+ };++ if (window.Spotify) {+ onSdkReady();+ return;+ }+ const existing = document.querySelector(+ `script[src="${SDK_SCRIPT}"]`,+ ) as HTMLScriptElement | null;+ window.onSpotifyWebPlaybackSDKReady = onSdkReady;+ if (!existing) {+ const script = document.createElement("script");+ script.src = SDK_SCRIPT;+ script.async = true;+ script.onerror = () => {+ this.unavailableReason = "Falha ao carregar SDK do Spotify (offline?)";+ this.loading = false;+ reject(new Error(this.unavailableReason));+ };+ document.head.appendChild(script);+ }+ })();+ }).catch((e) => {+ this.loadingPromise = null;+ throw e;+ });++ return this.loadingPromise;+ }++ async play(opts: {+ uris?: string[];+ contextUri?: string;+ positionMs?: number;+ }): Promise<void> {+ await this.ensureLoaded();+ if (!this.deviceId) throw new Error("Spotify SDK device not ready");+ await pluginInvoke("study", "study:spotify:playback:play", {+ deviceId: this.deviceId,+ uris: opts.uris ?? [],+ contextUri: opts.contextUri,+ positionMs: opts.positionMs,+ });+ }++ async pause(): Promise<void> {+ if (this.player) await this.player.pause();+ }++ async resume(): Promise<void> {+ if (this.player) await this.player.resume();+ }++ async togglePlay(): Promise<void> {+ if (this.player) await this.player.togglePlay();+ }++ async seek(positionMs: number): Promise<void> {+ if (this.player) await this.player.seek(positionMs);+ }++ async next(): Promise<void> {+ if (this.player) await this.player.nextTrack();+ }++ async prev(): Promise<void> {+ if (this.player) await this.player.previousTrack();+ }++ async setVolume(volume: number): Promise<void> {+ if (this.player) await this.player.setVolume(Math.max(0, Math.min(1, volume)));+ }++ disconnect(): void {+ if (this.player) {+ try {+ this.player.disconnect();+ } catch {+ /* ignore */+ }+ this.player = null;+ }+ this.ready = false;+ this.deviceId = null;+ this.state = null;+ this.loadingPromise = null;+ }+}++export const spotifySdk = new SpotifySdkController();diff --git a/src/lib/study-music/spotify-store.svelte.ts b/src/lib/study-music/spotify-store.svelte.tsnew file mode 100644index 00000000..c66f09eb--- /dev/null+++ b/src/lib/study-music/spotify-store.svelte.ts@@ -0,0 +1,779 @@+import { pluginInvoke } from "$lib/plugin-invoke";+import { musicPlayer, type MusicTrack } from "./player-store.svelte";+import { spotifySdk } from "./spotify-sdk.svelte";++export type SpotifyImage = { url: string; height?: number | null; width?: number | null };++export type SpotifyArtistRef = { id: string; name: string; uri: string };++export type SpotifyAlbumRef = {+ id: string;+ name: string;+ uri: string;+ images: SpotifyImage[];+ release_date?: string;+};++export type SpotifyTrack = {+ id: string;+ name: string;+ uri: string;+ duration_ms: number;+ explicit: boolean;+ is_playable?: boolean;+ preview_url: string | null;+ isrc?: string;+ artists: SpotifyArtistRef[];+ album: SpotifyAlbumRef;+ added_at?: string;+ played_at?: string;+};++export type SpotifyPlaylist = {+ id: string;+ name: string;+ description: string | null;+ uri: string;+ images: SpotifyImage[];+ tracks_total: number;+ owner_name: string | null;+ owner_id: string | null;+ collaborative: boolean;+ public: boolean;+};++export type SpotifyArtist = {+ id: string;+ name: string;+ uri: string;+ images: SpotifyImage[];+ genres: string[];+ followers?: number;+ popularity?: number;+};++export type SpotifySavedAlbum = {+ id: string;+ name: string;+ uri: string;+ images: SpotifyImage[];+ artists: SpotifyArtistRef[];+ release_date: string | null;+ total_tracks: number;+ added_at?: string;+};++export type SpotifyDevice = {+ id: string | null;+ name: string;+ type: string;+ is_active: boolean;+ is_private_session: boolean;+ is_restricted: boolean;+ volume_percent: number | null;+};++export type SpotifyProfile = {+ id: string;+ display_name: string | null;+ email: string | null;+ product: string | null;+ country: string | null;+ images: SpotifyImage[];+};++type AuthStatus = {+ logged_in: boolean;+ expires_in_secs: number;+ scope: string;+ has_client_id: boolean;+ redirect_uri: string;+};++function pickImage(images: SpotifyImage[] | undefined | null, target = 300): string | null {+ if (!images || images.length === 0) return null;+ const sorted = [...images].sort((a, b) => (a.width ?? 0) - (b.width ?? 0));+ const found = sorted.find((i) => (i.width ?? 0) >= target);+ return (found ?? sorted[sorted.length - 1])?.url ?? null;+}++function hashStringToInt(s: string): number {+ let h = 0;+ for (let i = 0; i < s.length; i++) {+ h = (h << 5) - h + s.charCodeAt(i);+ h |= 0;+ }+ return -Math.abs(h || 1);+}++export function spotifyTrackToMusicTrack(track: SpotifyTrack): MusicTrack {+ const cover = pickImage(track.album.images, 300);+ return {+ id: hashStringToInt(track.uri),+ path: track.uri,+ title: track.name,+ artist: track.artists.map((a) => a.name).join(", "),+ album: track.album.name,+ duration_ms: track.duration_ms,+ cover_path: null,+ source: "spotify",+ spotify_uri: track.uri,+ spotify_cover_url: cover ?? undefined,+ isrc: track.isrc,+ };+}++async function resolveSpotifyToYoutube(track: MusicTrack): Promise<string> {+ if (!track.title || !track.artist) {+ throw new Error("Track sem metadata pra resolver no YouTube");+ }+ console.log("[spotify-yt] resolving:", {+ title: track.title,+ artist: track.artist,+ isrc: track.isrc,+ duration_ms: track.duration_ms,+ });+ const res = await pluginInvoke<{+ youtube_url: string;+ video_id: string;+ video_title: string;+ channel: string;+ score: number;+ }>("study", "study:spotify:resolve_youtube", {+ title: track.title,+ artist: track.artist,+ durationMs: track.duration_ms ?? 0,+ isrc: track.isrc,+ });+ console.log("[spotify-yt] resolved:", {+ video_id: res.video_id,+ video_title: res.video_title,+ channel: res.channel,+ score: res.score,+ url_preview: res.youtube_url?.slice(0, 100),+ });+ if (!res.youtube_url) throw new Error("YouTube não retornou URL");+ return res.youtube_url;+}++if (typeof window !== "undefined") {+ musicPlayer.spotifyFreeFallback = resolveSpotifyToYoutube;+}++function mapTrack(item: any, addedAt?: string, playedAt?: string): SpotifyTrack | null {+ const t = item?.track ?? item;+ if (!t || !t.id) return null;+ return {+ id: t.id,+ name: t.name ?? "",+ uri: t.uri ?? `spotify:track:${t.id}`,+ duration_ms: t.duration_ms ?? 0,+ explicit: !!t.explicit,+ is_playable: t.is_playable,+ preview_url: t.preview_url ?? null,+ isrc: t.external_ids?.isrc,+ artists: (t.artists ?? []).map((a: any) => ({+ id: a.id,+ name: a.name,+ uri: a.uri ?? `spotify:artist:${a.id}`,+ })),+ album: {+ id: t.album?.id ?? "",+ name: t.album?.name ?? "",+ uri: t.album?.uri ?? "",+ images: t.album?.images ?? [],+ release_date: t.album?.release_date,+ },+ added_at: addedAt ?? item?.added_at,+ played_at: playedAt ?? item?.played_at,+ };+}++function mapPlaylist(p: any, _owner?: any): SpotifyPlaylist | null {+ if (!p || !p.id) return null;+ return {+ id: p.id,+ name: p.name ?? "",+ description: p.description ?? null,+ uri: p.uri ?? `spotify:playlist:${p.id}`,+ images: p.images ?? [],+ tracks_total: p.tracks?.total ?? 0,+ owner_name: p.owner?.display_name ?? p.owner?.id ?? null,+ owner_id: p.owner?.id ?? null,+ collaborative: !!p.collaborative,+ public: !!p.public,+ };+}++function mapArtist(a: any): SpotifyArtist | null {+ if (!a || !a.id) return null;+ return {+ id: a.id,+ name: a.name ?? "",+ uri: a.uri ?? `spotify:artist:${a.id}`,+ images: a.images ?? [],+ genres: a.genres ?? [],+ followers: a.followers?.total,+ popularity: a.popularity,+ };+}++class SpotifyStore {+ status = $state<AuthStatus>({+ logged_in: false,+ expires_in_secs: 0,+ scope: "",+ has_client_id: false,+ redirect_uri: "http://127.0.0.1:8888/callback",+ });+ profile = $state<SpotifyProfile | null>(null);+ savedTracks = $state<SpotifyTrack[]>([]);+ playlists = $state<SpotifyPlaylist[]>([]);+ recentlyPlayed = $state<SpotifyTrack[]>([]);+ topArtists = $state<SpotifyArtist[]>([]);+ topTracks = $state<SpotifyTrack[]>([]);+ savedAlbums = $state<SpotifySavedAlbum[]>([]);+ followedArtists = $state<SpotifyArtist[]>([]);+ devices = $state<SpotifyDevice[]>([]);+ loading = $state(false);+ loadingLibrary = $state(false);+ error = $state<string | null>(null);+ authInProgress = $state(false);++ widevineSupported = $state<boolean | null>(null);+ sdkPrewarmed = $state(false);+ localMatches = $state<Map<string, number>>(new Map());++ pickImage = pickImage;++ get isPremium(): boolean {+ return this.profile?.product === "premium";+ }++ get playbackMode(): "sdk" | "connect" | "unknown" {+ if (this.isPremium && this.widevineSupported && !spotifySdk.unavailableReason) {+ return "sdk";+ }+ if (this.profile) {+ return "connect";+ }+ return "unknown";+ }++ async detectCapabilities() {+ this.widevineSupported = await spotifySdk.checkWidevine();+ }++ async prewarmSdk() {+ if (this.sdkPrewarmed) return;+ if (!this.isPremium || !this.widevineSupported) return;+ try {+ await spotifySdk.ensureLoaded();+ this.sdkPrewarmed = true;+ } catch {+ /* ignore — fallback to Connect */+ }+ }++ get allArtists(): SpotifyArtist[] {+ const map = new Map<string, SpotifyArtist>();+ for (const a of this.topArtists) map.set(a.id, a);+ for (const a of this.followedArtists) {+ if (!map.has(a.id)) map.set(a.id, a);+ }+ const seen = new Set<string>(map.keys());+ const inferFromTracks = (tracks: SpotifyTrack[]) => {+ for (const t of tracks) {+ for (const a of t.artists) {+ if (a.id && !seen.has(a.id)) {+ seen.add(a.id);+ map.set(a.id, {+ id: a.id,+ name: a.name,+ uri: a.uri,+ images: [],+ genres: [],+ });+ }+ }+ }+ };+ inferFromTracks(this.savedTracks);+ inferFromTracks(this.recentlyPlayed);+ inferFromTracks(this.topTracks);+ for (const al of this.savedAlbums) {+ for (const a of al.artists) {+ if (a.id && !seen.has(a.id)) {+ seen.add(a.id);+ map.set(a.id, {+ id: a.id,+ name: a.name,+ uri: a.uri,+ images: [],+ genres: [],+ });+ }+ }+ }+ return [...map.values()].sort((a, b) => a.name.localeCompare(b.name));+ }++ isPlaylistOwned(p: SpotifyPlaylist): boolean {+ return !!this.profile?.id && p.owner_id === this.profile.id;+ }++ searchLocal(query: string): {+ tracks: SpotifyTrack[];+ artists: SpotifyArtist[];+ playlists: SpotifyPlaylist[];+ } {+ const q = query.trim().toLowerCase();+ if (!q) return { tracks: [], artists: [], playlists: [] };++ const allTracks = new Map<string, SpotifyTrack>();+ for (const t of this.savedTracks) allTracks.set(t.id, t);+ for (const t of this.recentlyPlayed) if (!allTracks.has(t.id)) allTracks.set(t.id, t);+ for (const t of this.topTracks) if (!allTracks.has(t.id)) allTracks.set(t.id, t);++ const matchesText = (s: string | null | undefined) =>+ !!s && s.toLowerCase().includes(q);++ const tracks = [...allTracks.values()].filter(+ (t) =>+ matchesText(t.name) ||+ t.artists.some((a) => matchesText(a.name)) ||+ matchesText(t.album.name),+ );++ const artists = this.allArtists.filter((a) => matchesText(a.name));++ const playlists = this.playlists.filter(+ (p) => matchesText(p.name) || matchesText(p.description),+ );++ return { tracks, artists, playlists };+ }++ async refreshLocalMatches() {+ if (this.savedTracks.length === 0) return;+ const items = this.savedTracks.map((t) => ({+ title: t.name,+ artist: t.artists[0]?.name ?? "",+ duration_ms: t.duration_ms,+ }));+ try {+ const res = await pluginInvoke<{ matches: { index: number; local_id: number }[] }>(+ "study",+ "study:spotify:match:local",+ { items },+ );+ const next = new Map<string, number>();+ for (const m of res.matches) {+ const t = this.savedTracks[m.index];+ if (t) next.set(t.id, m.local_id);+ }+ this.localMatches = next;+ } catch {+ /* ignore */+ }+ }++ async refreshStatus() {+ try {+ const res = await pluginInvoke<AuthStatus>("study", "study:spotify:auth:status");+ this.status = res;+ if (res.logged_in && !this.profile) {+ await this.loadProfile().catch(() => {});+ }+ if (!res.logged_in) {+ this.profile = null;+ }+ } catch (e) {+ this.error = e instanceof Error ? e.message : String(e);+ }+ }++ async setClientId(id: string): Promise<void> {+ await pluginInvoke("study", "study:spotify:config:set_client_id", { clientId: id });+ await this.refreshStatus();+ }++ async login(): Promise<{ auth_url: string }> {+ this.error = null;+ this.authInProgress = true;+ try {+ const res = await pluginInvoke<{ auth_url: string }>(+ "study",+ "study:spotify:auth:start",+ );+ const { open } = await import("@tauri-apps/plugin-shell");+ await open(res.auth_url).catch(() => {+ try {+ window.open(res.auth_url, "_blank");+ } catch {+ /* ignore */+ }+ });+ return res;+ } catch (e) {+ this.authInProgress = false;+ this.error = e instanceof Error ? e.message : String(e);+ throw e;+ }+ }++ async cancelAuth(): Promise<void> {+ try {+ await pluginInvoke("study", "study:spotify:auth:cancel");+ } catch {+ /* ignore */+ }+ this.authInProgress = false;+ }++ async logout(): Promise<void> {+ try {+ await pluginInvoke("study", "study:spotify:auth:logout");+ } finally {+ this.profile = null;+ this.savedTracks = [];+ this.playlists = [];+ this.recentlyPlayed = [];+ this.topArtists = [];+ this.topTracks = [];+ this.devices = [];+ await this.refreshStatus();+ }+ }++ async loadProfile() {+ const me = await pluginInvoke<SpotifyProfile & { images?: SpotifyImage[] }>(+ "study",+ "study:spotify:me",+ );+ this.profile = {+ id: me.id,+ display_name: me.display_name ?? null,+ email: me.email ?? null,+ product: me.product ?? null,+ country: me.country ?? null,+ images: me.images ?? [],+ };+ }++ async loadAll() {+ if (!this.status.logged_in) return;+ this.loadingLibrary = true;+ try {+ const [savedRes, playlistsRes, recentRes, topArtistsRes, topTracksRes, savedAlbumsRes] =+ await Promise.allSettled([+ pluginInvoke<{ items: any[] }>("study", "study:spotify:library:saved_tracks", {+ limit: 50,+ offset: 0,+ }),+ pluginInvoke<{ items: any[] }>("study", "study:spotify:library:playlists", {+ limit: 50,+ offset: 0,+ }),+ pluginInvoke<{ items: any[] }>(+ "study",+ "study:spotify:library:recently_played",+ { limit: 50 },+ ),+ pluginInvoke<{ items: any[] }>("study", "study:spotify:library:top_artists", {+ timeRange: "medium_term",+ limit: 20,+ }),+ pluginInvoke<{ items: any[] }>("study", "study:spotify:library:top_tracks", {+ timeRange: "medium_term",+ limit: 20,+ }),+ pluginInvoke<{ items: any[] }>("study", "study:spotify:library:saved_albums", {+ limit: 50,+ offset: 0,+ }),+ ]);++ if (savedRes.status === "fulfilled") {+ this.savedTracks = (savedRes.value.items ?? [])+ .map((it) => mapTrack(it.track, it.added_at))+ .filter((t): t is SpotifyTrack => !!t);+ void this.refreshLocalMatches();+ }+ if (playlistsRes.status === "fulfilled") {+ this.playlists = (playlistsRes.value.items ?? [])+ .map((p) => mapPlaylist(p, p?.owner))+ .filter((p): p is SpotifyPlaylist => !!p)+ .filter((p) => p.owner_id !== "spotify");+ }+ if (recentRes.status === "fulfilled") {+ const seen = new Set<string>();+ this.recentlyPlayed = (recentRes.value.items ?? [])+ .map((it) => mapTrack(it.track, undefined, it.played_at))+ .filter((t): t is SpotifyTrack => {+ if (!t || seen.has(t.id)) return false;+ seen.add(t.id);+ return true;+ });+ }+ if (topArtistsRes.status === "fulfilled") {+ this.topArtists = (topArtistsRes.value.items ?? [])+ .map(mapArtist)+ .filter((a): a is SpotifyArtist => !!a);+ }+ if (topTracksRes.status === "fulfilled") {+ this.topTracks = (topTracksRes.value.items ?? [])+ .map((t) => mapTrack(t))+ .filter((t): t is SpotifyTrack => !!t);+ }+ void this.getFollowedArtists()+ .then((arr) => {+ this.followedArtists = arr;+ })+ .catch(() => {});++ if (savedAlbumsRes.status === "fulfilled") {+ const out: SpotifySavedAlbum[] = [];+ for (const it of savedAlbumsRes.value.items ?? []) {+ const a = it?.album;+ if (!a || !a.id) continue;+ out.push({+ id: a.id,+ name: a.name ?? "",+ uri: a.uri ?? `spotify:album:${a.id}`,+ images: a.images ?? [],+ artists: (a.artists ?? []).map((ar: any) => ({+ id: ar.id,+ name: ar.name,+ uri: ar.uri ?? `spotify:artist:${ar.id}`,+ })),+ release_date: a.release_date ?? null,+ total_tracks: a.total_tracks ?? 0,+ added_at: it?.added_at,+ });+ }+ this.savedAlbums = out;+ }+ } finally {+ this.loadingLibrary = false;+ }+ }++ async loadPlaylistTracks(playlistId: string): Promise<SpotifyTrack[]> {+ const out: SpotifyTrack[] = [];+ let offset = 0;+ const pageSize = 100;+ for (let page = 0; page < 20; page++) {+ const res = await pluginInvoke<{ items: any[]; next: string | null }>(+ "study",+ "study:spotify:library:playlist_tracks",+ { playlistId, limit: pageSize, offset },+ );+ const items = res.items ?? [];+ for (const it of items) {+ const t = mapTrack(it.track, it.added_at);+ if (t) out.push(t);+ }+ if (items.length < pageSize) break;+ offset += pageSize;+ }+ return out;+ }++ async loadDevices() {+ const res = await pluginInvoke<{ devices: SpotifyDevice[] }>(+ "study",+ "study:spotify:playback:devices",+ );+ this.devices = res.devices ?? [];+ return this.devices;+ }++ async transferPlayback(deviceId: string, play = true) {+ await pluginInvoke("study", "study:spotify:playback:transfer", { deviceId, play });+ }++ async playUris(opts: {+ deviceId?: string;+ uris?: string[];+ contextUri?: string;+ positionMs?: number;+ }) {+ await pluginInvoke("study", "study:spotify:playback:play", {+ deviceId: opts.deviceId,+ uris: opts.uris ?? [],+ contextUri: opts.contextUri,+ positionMs: opts.positionMs,+ });+ }++ async toggleSaveTrack(trackId: string): Promise<boolean> {+ const contains = await pluginInvoke<boolean[]>(+ "study",+ "study:spotify:tracks:contains",+ { ids: [trackId] },+ );+ const isSaved = contains?.[0] === true;+ if (isSaved) {+ await pluginInvoke("study", "study:spotify:tracks:unsave", {+ ids: [trackId],+ });+ this.savedTracks = this.savedTracks.filter((t) => t.id !== trackId);+ return false;+ }+ await pluginInvoke("study", "study:spotify:tracks:save", {+ ids: [trackId],+ });+ return true;+ }++ async toggleSaveAlbum(albumId: string): Promise<boolean> {+ const contains = await pluginInvoke<boolean[]>(+ "study",+ "study:spotify:albums:contains",+ { ids: [albumId] },+ );+ const isSaved = contains?.[0] === true;+ if (isSaved) {+ await pluginInvoke("study", "study:spotify:albums:unsave", {+ ids: [albumId],+ });+ this.savedAlbums = this.savedAlbums.filter((a) => a.id !== albumId);+ return false;+ }+ await pluginInvoke("study", "study:spotify:albums:save", {+ ids: [albumId],+ });+ return true;+ }++ async addToQueue(trackUri: string, deviceId?: string): Promise<void> {+ await pluginInvoke("study", "study:spotify:playback:add_to_queue", {+ uri: trackUri,+ deviceId,+ });+ }++ async getAlbum(albumId: string): Promise<any> {+ return pluginInvoke("study", "study:spotify:albums:get", { albumId });+ }++ async getAlbumTracks(albumId: string): Promise<SpotifyTrack[]> {+ const out: SpotifyTrack[] = [];+ let offset = 0;+ for (let page = 0; page < 10; page++) {+ const res = await pluginInvoke<{ items: any[]; next: string | null }>(+ "study",+ "study:spotify:albums:tracks",+ { albumId, limit: 50, offset },+ );+ const items = res.items ?? [];+ for (const it of items) {+ const t = mapTrack(it);+ if (t) out.push(t);+ }+ if (items.length < 50) break;+ offset += 50;+ }+ return out;+ }++ async getArtist(artistId: string): Promise<any> {+ return pluginInvoke("study", "study:spotify:artists:get", { artistId });+ }++ async getArtistAlbums(artistId: string): Promise<SpotifySavedAlbum[]> {+ const res = await pluginInvoke<{ items: any[] }>(+ "study",+ "study:spotify:artists:albums",+ { artistId, limit: 50 },+ );+ const out: SpotifySavedAlbum[] = [];+ for (const a of res.items ?? []) {+ if (!a?.id) continue;+ out.push({+ id: a.id,+ name: a.name ?? "",+ uri: a.uri ?? `spotify:album:${a.id}`,+ images: a.images ?? [],+ artists: (a.artists ?? []).map((ar: any) => ({+ id: ar.id,+ name: ar.name,+ uri: ar.uri ?? `spotify:artist:${ar.id}`,+ })),+ release_date: a.release_date ?? null,+ total_tracks: a.total_tracks ?? 0,+ });+ }+ return out;+ }++ async getArtistTopTracks(artistId: string, market = "US"): Promise<SpotifyTrack[]> {+ const res = await pluginInvoke<{ tracks: any[] }>(+ "study",+ "study:spotify:artists:top_tracks",+ { artistId, market },+ );+ const out: SpotifyTrack[] = [];+ for (const t of res.tracks ?? []) {+ const mapped = mapTrack(t);+ if (mapped) out.push(mapped);+ }+ return out;+ }++ async getFollowedArtists(): Promise<SpotifyArtist[]> {+ const res = await pluginInvoke<{ artists: { items: any[] } }>(+ "study",+ "study:spotify:artists:followed",+ { limit: 50 },+ );+ const out: SpotifyArtist[] = [];+ for (const a of res.artists?.items ?? []) {+ const m = mapArtist(a);+ if (m) out.push(m);+ }+ return out;+ }++ async checkFollowArtists(ids: string[]): Promise<boolean[]> {+ if (ids.length === 0) return [];+ return pluginInvoke<boolean[]>("study", "study:spotify:artists:check_follow", {+ ids,+ });+ }++ async toggleFollowArtist(artistId: string): Promise<boolean> {+ const res = await this.checkFollowArtists([artistId]);+ const isFollowing = res[0] === true;+ if (isFollowing) {+ await pluginInvoke("study", "study:spotify:artists:unfollow", {+ ids: [artistId],+ });+ return false;+ }+ await pluginInvoke("study", "study:spotify:artists:follow", {+ ids: [artistId],+ });+ return true;+ }++ async playTrack(track: SpotifyTrack, queue?: SpotifyTrack[]): Promise<"sdk" | "youtube"> {+ const local = spotifyTrackToMusicTrack(track);+ const localQueue = (queue && queue.length > 0 ? queue : [track]).map(+ spotifyTrackToMusicTrack,+ );+ await musicPlayer.play(local, localQueue);+ return this.isPremium && spotifySdk.ready ? "sdk" : "youtube";+ }++ async playPlaylistContext(+ _playlistUri: string,+ firstTrack: SpotifyTrack,+ tracks: SpotifyTrack[],+ ): Promise<"sdk" | "youtube"> {+ return this.playTrack(firstTrack, tracks);+ }+}++export const spotifyStore = new SpotifyStore();diff --git a/src/lib/study-music/theme-store.svelte.ts b/src/lib/study-music/theme-store.svelte.tsnew file mode 100644index 00000000..cd65c4f3--- /dev/null+++ b/src/lib/study-music/theme-store.svelte.ts@@ -0,0 +1,111 @@+export type MusicThemePreset =+ | "default"+ | "indigo"+ | "spotify"+ | "purple"+ | "amber"+ | "custom";++export type MusicTheme = {+ preset: MusicThemePreset;+ accent: string;+ useDominant: boolean;+};++const STORAGE_KEY = "study.music.theme.v1";++export const PRESET_ACCENTS: Record<Exclude<MusicThemePreset, "custom">, string> = {+ default: "",+ indigo: "#6366f1",+ spotify: "#1db954",+ purple: "#a855f7",+ amber: "#f59e0b",+};++const DEFAULT_THEME: MusicTheme = {+ preset: "default",+ accent: "",+ useDominant: true,+};++function isHexColor(value: string): boolean {+ return /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value);+}++class MusicThemeStore {+ preset = $state<MusicThemePreset>("default");+ accent = $state("");+ useDominant = $state(true);++ load() {+ if (typeof localStorage === "undefined") return;+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return;+ const data = JSON.parse(raw) as Partial<MusicTheme>;+ if (data.preset && data.preset in PRESET_ACCENTS) {+ this.preset = data.preset as MusicThemePreset;+ } else if (data.preset === "custom") {+ this.preset = "custom";+ }+ if (typeof data.accent === "string" && (isHexColor(data.accent) || data.accent === "")) {+ this.accent = data.accent;+ }+ if (typeof data.useDominant === "boolean") {+ this.useDominant = data.useDominant;+ }+ } catch {+ /* ignore */+ }+ }++ persist() {+ if (typeof localStorage === "undefined") return;+ try {+ localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({+ preset: this.preset,+ accent: this.accent,+ useDominant: this.useDominant,+ }),+ );+ } catch {+ /* ignore */+ }+ }++ setPreset(preset: MusicThemePreset) {+ this.preset = preset;+ if (preset !== "custom") {+ this.accent = PRESET_ACCENTS[preset];+ }+ this.persist();+ }++ setAccent(value: string) {+ if (!isHexColor(value)) return;+ this.accent = value;+ this.preset = "custom";+ this.persist();+ }++ toggleUseDominant() {+ this.useDominant = !this.useDominant;+ this.persist();+ }++ reset() {+ this.preset = DEFAULT_THEME.preset;+ this.accent = DEFAULT_THEME.accent;+ this.useDominant = DEFAULT_THEME.useDominant;+ this.persist();+ }++ get effectiveAccent(): string | null {+ if (this.preset === "default" || !this.accent) return null;+ return this.accent;+ }+}++export const musicTheme = new MusicThemeStore();diff --git a/src/lib/study-music/ui-store.svelte.ts b/src/lib/study-music/ui-store.svelte.tsnew file mode 100644index 00000000..70c8dbd5--- /dev/null+++ b/src/lib/study-music/ui-store.svelte.ts@@ -0,0 +1,165 @@+import type { MusicTrack } from "./player-store.svelte";++export type ContextMenuState = {+ open: boolean;+ x: number;+ y: number;+ track: MusicTrack | null;+};++export type RightBarTab = "queue" | "lyrics" | "info";++class MusicUI {+ addToPlaylistTrack = $state<MusicTrack | null>(null);+ rootsOpen = $state(false);+ equalizerOpen = $state(false);+ lastfmOpen = $state(false);+ rightbarTab = $state<RightBarTab | null>(null);+ 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 });++ get queueOpen(): boolean {+ return this.rightbarTab === "queue";+ }+ get lyricsOpen(): boolean {+ return this.rightbarTab === "lyrics";+ }++ openAddToPlaylist(track: MusicTrack) {+ this.addToPlaylistTrack = track;+ }+ closeAddToPlaylist() {+ this.addToPlaylistTrack = null;+ }+ toggleQueue() {+ this.rightbarTab = this.rightbarTab === "queue" ? null : "queue";+ }+ closeQueue() {+ if (this.rightbarTab === "queue") this.rightbarTab = null;+ }+ toggleLyrics() {+ this.rightbarTab = this.rightbarTab === "lyrics" ? null : "lyrics";+ }+ closeLyrics() {+ if (this.rightbarTab === "lyrics") this.rightbarTab = null;+ }+ toggleInfo() {+ this.rightbarTab = this.rightbarTab === "info" ? null : "info";+ }+ closeRightBar() {+ this.rightbarTab = null;+ }+ openRoots() {+ this.rootsOpen = true;+ }+ closeRoots() {+ this.rootsOpen = false;+ }+ toggleEqualizer() {+ this.equalizerOpen = !this.equalizerOpen;+ }+ closeEqualizer() {+ this.equalizerOpen = false;+ }+ openLastFm() {+ this.lastfmOpen = true;+ }+ closeLastFm() {+ this.lastfmOpen = false;+ }+ themeOpen = $state(false);+ openTheme() {+ this.themeOpen = true;+ }+ closeTheme() {+ this.themeOpen = false;+ }+ discordOpen = $state(false);+ openDiscord() {+ this.discordOpen = true;+ }+ closeDiscord() {+ this.discordOpen = false;+ }+ youtubeOpen = $state(false);+ openYoutube() {+ this.youtubeOpen = true;+ }+ closeYoutube() {+ this.youtubeOpen = false;+ }+ qualityOpen = $state(false);+ openQuality() {+ this.qualityOpen = true;+ }+ closeQuality() {+ this.qualityOpen = false;+ }+ sourcesOpen = $state(false);+ openSources() {+ this.sourcesOpen = true;+ }+ closeSources() {+ this.sourcesOpen = false;+ }+ qobuzOpen = $state(false);+ openQobuz() {+ this.qobuzOpen = true;+ }+ closeQobuz() {+ this.qobuzOpen = false;+ }+ openContextMenu(track: MusicTrack, x: number, y: number) {+ this.contextMenu = { open: true, x, y, track };+ }+ closeContextMenu() {+ this.contextMenu = { open: false, x: 0, y: 0, track: null };+ }+ isSelected(trackId: number): boolean {+ return this.selectedIds.has(trackId);+ }+ toggleSelected(trackId: number, queue?: MusicTrack[]) {+ const next = new Set(this.selectedIds);+ if (next.has(trackId)) {+ next.delete(trackId);+ } else {+ next.add(trackId);+ }+ this.selectedIds = next;+ if (next.size > 0 && queue) {+ this.selectionAnchor = { trackId, queue };+ }+ if (next.size === 0) {+ this.selectionAnchor = null;+ }+ }+ selectRange(trackId: number, queue: MusicTrack[]) {+ if (!this.selectionAnchor || this.selectionAnchor.queue !== queue) {+ this.selectedIds = new Set([trackId]);+ this.selectionAnchor = { trackId, queue };+ return;+ }+ const startIdx = queue.findIndex((t) => t.id === this.selectionAnchor!.trackId);+ const endIdx = queue.findIndex((t) => t.id === trackId);+ if (startIdx < 0 || endIdx < 0) return;+ const lo = Math.min(startIdx, endIdx);+ const hi = Math.max(startIdx, endIdx);+ const next = new Set<number>(this.selectedIds);+ for (let i = lo; i <= hi; i++) next.add(queue[i].id);+ this.selectedIds = next;+ }+ selectOnly(trackId: number, queue?: MusicTrack[]) {+ this.selectedIds = new Set([trackId]);+ if (queue) this.selectionAnchor = { trackId, queue };+ }+ clearSelection() {+ this.selectedIds = new Set();+ this.selectionAnchor = null;+ }+ selectedCount(): number {+ return this.selectedIds.size;+ }+}++export const musicUI = new MusicUI();diff --git a/src/lib/study-notes/docks-store.svelte.ts b/src/lib/study-notes/docks-store.svelte.tsnew file mode 100644index 00000000..12dd2b1c--- /dev/null+++ b/src/lib/study-notes/docks-store.svelte.ts@@ -0,0 +1,110 @@+import {+ notesDocksState,+ notesDocksSetState,+ notesDocksToggleVisible,+ type DockId,+ type DockPosition,+ type DockState,+ type DockStatePatch,+} from "$lib/notes-bridge";++export type DockMeta = {+ id: DockId;+ label: string;+ iconKey: DockIconKey;+ defaultPosition: DockPosition;+};++export type DockIconKey =+ | "files"+ | "list-tree"+ | "link"+ | "bookmark"+ | "tags"+ | "inbox"+ | "share-2";++export const DOCK_META: DockMeta[] = [+ { id: "files", label: "Arquivos", iconKey: "files", defaultPosition: "left" },+ { id: "outline", label: "Outline", iconKey: "list-tree", defaultPosition: "left" },+ { id: "backlink", label: "Backlinks", iconKey: "link", defaultPosition: "right" },+ { id: "bookmark", label: "Favoritos", iconKey: "bookmark", defaultPosition: "right" },+ { id: "tag", label: "Tags", iconKey: "tags", defaultPosition: "right" },+ { id: "inbox", label: "Inbox", iconKey: "inbox", defaultPosition: "right" },+ { id: "graph", label: "Graph", iconKey: "share-2", defaultPosition: "right" },+];++class DocksStore {+ states = $state<Record<string, DockState>>({});+ hydrated = $state(false);++ async hydrate() {+ try {+ const rows = await notesDocksState();+ const map: Record<string, DockState> = {};+ for (const row of rows) map[row.dock_id] = row;+ this.states = map;+ } catch {+ /* ignore — UI falls back to defaults */+ }+ this.hydrated = true;+ }++ byPosition(position: DockPosition): DockState[] {+ return Object.values(this.states)+ .filter((d) => d.position === position)+ .sort((a, b) => a.sort_idx - b.sort_idx);+ }++ visibleByPosition(position: DockPosition): DockState[] {+ return this.byPosition(position).filter((d) => d.visible);+ }++ isVisible(id: DockId): boolean {+ return this.states[id]?.visible ?? false;+ }++ positionOf(id: DockId): DockPosition {+ return this.states[id]?.position ?? "left";+ }++ widthOf(id: DockId): number | null {+ return this.states[id]?.width_px ?? null;+ }++ async toggle(id: DockId) {+ const prev = this.states[id]?.visible ?? false;+ if (this.states[id]) {+ this.states = { ...this.states, [id]: { ...this.states[id], visible: !prev } };+ }+ try {+ const r = await notesDocksToggleVisible(id);+ if (this.states[id]) {+ this.states = { ...this.states, [id]: { ...this.states[id], visible: r.visible } };+ }+ } catch {+ if (this.states[id]) {+ this.states = { ...this.states, [id]: { ...this.states[id], visible: prev } };+ }+ }+ }++ async setState(id: DockId, patch: DockStatePatch) {+ const prev = this.states[id];+ if (prev) {+ this.states = { ...this.states, [id]: { ...prev, ...patch } as DockState };+ }+ try {+ const r = await notesDocksSetState({ dockId: id, patch });+ this.states = { ...this.states, [id]: r.state };+ } catch {+ if (prev) this.states = { ...this.states, [id]: prev };+ }+ }++ async setWidth(id: DockId, widthPx: number) {+ await this.setState(id, { width_px: widthPx });+ }+}++export const docksStore = new DocksStore();diff --git a/src/lib/study-notes/notebooks-store.svelte.ts b/src/lib/study-notes/notebooks-store.svelte.tsnew file mode 100644index 00000000..2aafb5cb--- /dev/null+++ b/src/lib/study-notes/notebooks-store.svelte.ts@@ -0,0 +1,218 @@+import {+ notesNotebooksList,+ notesNotebooksActiveGet,+ notesNotebooksActiveSet,+ notesNotebooksCreate,+ notesNotebooksRename,+ notesNotebooksClose,+ notesNotebooksReopen,+ notesNotebooksDelete,+ notesNotebooksMovePage,+ notesNotebooksSetCover,+ notesNotebooksSetColor,+ notesNotebooksSetIcon,+ notesNotebooksReorder,+ type Notebook,+ type NotebookDeleteReport,+ type NotebookMoveReport,+} from "$lib/notes-bridge";++export const NOTEBOOK_LUCIDE_OPTIONS = [+ "book",+ "book-open",+ "graduation-cap",+ "briefcase",+ "lightbulb",+ "flask-conical",+ "code",+ "music",+ "feather",+ "compass",+ "sparkles",+ "folder",+] as const;++export const NOTEBOOK_COLOR_SWATCHES = [+ "var(--accent)",+ "#ef4444",+ "#f97316",+ "#eab308",+ "#22c55e",+ "#14b8a6",+ "#3b82f6",+ "#a855f7",+] as const;++class NotebooksStore {+ list = $state<Notebook[]>([]);+ activeId = $state<number>(1);+ hydrated = $state(false);+ loading = $state(false);++ visible = $derived(this.list.filter((n) => !n.closed));+ closed = $derived(this.list.filter((n) => n.closed));+ active = $derived(this.list.find((n) => n.id === this.activeId) ?? null);++ async hydrate() {+ if (this.loading) return;+ this.loading = true;+ try {+ const [rows, active] = await Promise.all([+ notesNotebooksList({ includeClosed: true }),+ notesNotebooksActiveGet(),+ ]);+ this.list = rows;+ this.activeId = active.notebook_id;+ } catch (e) {+ console.warn("notebooksStore.hydrate failed", e);+ } finally {+ this.hydrated = true;+ this.loading = false;+ }+ }++ async refresh() {+ try {+ this.list = await notesNotebooksList({ includeClosed: true });+ } catch (e) {+ console.warn("notebooksStore.refresh failed", e);+ }+ }++ pageCountOf(id: number): number {+ return this.list.find((n) => n.id === id)?.page_count ?? 0;+ }++ byId(id: number): Notebook | null {+ return this.list.find((n) => n.id === id) ?? null;+ }++ async setActive(notebookId: number) {+ if (this.activeId === notebookId) return;+ this.activeId = notebookId;+ try {+ await notesNotebooksActiveSet(notebookId);+ } catch (e) {+ console.warn("setActive failed", e);+ }+ }++ async create(args: {+ name: string;+ color?: string | null;+ iconLucide?: string | null;+ }): Promise<number | null> {+ try {+ const r = await notesNotebooksCreate(args);+ await this.refresh();+ return r.notebook_id;+ } catch (e) {+ console.warn("create notebook failed", e);+ return null;+ }+ }++ async rename(notebookId: number, newName: string) {+ try {+ await notesNotebooksRename({ notebookId, newName });+ await this.refresh();+ } catch (e) {+ console.warn("rename failed", e);+ }+ }++ async close(notebookId: number) {+ try {+ await notesNotebooksClose(notebookId);+ if (this.activeId === notebookId) {+ await this.setActive(1);+ }+ await this.refresh();+ } catch (e) {+ console.warn("close failed", e);+ }+ }++ async reopen(notebookId: number) {+ try {+ await notesNotebooksReopen(notebookId);+ await this.refresh();+ } catch (e) {+ console.warn("reopen failed", e);+ }+ }++ async delete(notebookId: number, force = false): Promise<NotebookDeleteReport> {+ try {+ const r = await notesNotebooksDelete({ notebookId, force });+ if (r.deleted && this.activeId === notebookId) {+ await this.setActive(1);+ }+ await this.refresh();+ return r;+ } catch (e) {+ console.warn("delete failed", e);+ return { deleted: false, page_count: 0 };+ }+ }++ async movePage(args: {+ pageId: number;+ targetNotebookId: number;+ targetName?: string;+ }): Promise<NotebookMoveReport | null> {+ try {+ const r = await notesNotebooksMovePage(args);+ await this.refresh();+ return r;+ } catch (e) {+ console.warn("movePage failed", e);+ return null;+ }+ }++ async setCover(notebookId: number, assetId: number | null) {+ try {+ await notesNotebooksSetCover({ notebookId, assetId });+ await this.refresh();+ } catch (e) {+ console.warn("setCover failed", e);+ }+ }++ async setColor(notebookId: number, color: string | null) {+ try {+ await notesNotebooksSetColor({ notebookId, color });+ await this.refresh();+ } catch (e) {+ console.warn("setColor failed", e);+ }+ }++ async setIcon(notebookId: number, iconLucide: string | null) {+ try {+ await notesNotebooksSetIcon({ notebookId, iconLucide });+ await this.refresh();+ } catch (e) {+ console.warn("setIcon failed", e);+ }+ }++ async reorder(notebookId: number, newSortIdx: number) {+ try {+ await notesNotebooksReorder({ notebookId, newSortIdx });+ await this.refresh();+ } catch (e) {+ console.warn("reorder failed", e);+ }+ }++ switchToIndex(zeroBased: number): boolean {+ const target = this.visible[zeroBased];+ if (!target) return false;+ void this.setActive(target.id);+ return true;+ }+}++export const notebooksStore = new NotebooksStore();diff --git a/src/lib/study-notes/shell-store.svelte.ts b/src/lib/study-notes/shell-store.svelte.tsnew file mode 100644index 00000000..7e46154f--- /dev/null+++ b/src/lib/study-notes/shell-store.svelte.ts@@ -0,0 +1,183 @@+import { notesSettingsGet, notesSettingsSet } from "$lib/notes-bridge";++export type NotesEditorMode = "edit" | "source" | "preview";++const STORAGE_KEY = "study.notes.shell.v1";+const RETURN_URL_KEY = "study.notes.return_url";++const DEFAULT_DOCK_LEFT = 240;+const DEFAULT_DOCK_RIGHT = 280;+const DOCK_MIN = 180;+const DOCK_MAX = 480;++type PersistedShape = {+ dockLeftWidth: number;+ dockRightWidth: number;+ dockLeftVisible: boolean;+ dockRightVisible: boolean;+};++class NotesShellStore {+ dockLeftWidth = $state(DEFAULT_DOCK_LEFT);+ dockRightWidth = $state(DEFAULT_DOCK_RIGHT);+ dockLeftVisible = $state(true);+ dockRightVisible = $state(true);++ currentPageName = $state<string | null>(null);+ currentPageTitle = $state<string | null>(null);+ notebookName = $state<string>("Pessoal");+ wordCount = $state(0);+ charCount = $state(0);+ mode = $state<NotesEditorMode>("edit");+ saving = $state(false);+ hydrated = $state(false);++ loadLocal() {+ if (typeof localStorage === "undefined") return;+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return;+ const data = JSON.parse(raw) as Partial<PersistedShape>;+ if (typeof data.dockLeftWidth === "number") {+ this.dockLeftWidth = clampDock(data.dockLeftWidth);+ }+ if (typeof data.dockRightWidth === "number") {+ this.dockRightWidth = clampDock(data.dockRightWidth);+ }+ if (typeof data.dockLeftVisible === "boolean") {+ this.dockLeftVisible = data.dockLeftVisible;+ }+ if (typeof data.dockRightVisible === "boolean") {+ this.dockRightVisible = data.dockRightVisible;+ }+ } catch {+ /* ignore */+ }+ }++ async hydrateFromBackend() {+ try {+ const r = await notesSettingsGet("layout_snapshot");+ const v = r?.value;+ if (v && typeof v === "object" && !Array.isArray(v)) {+ const obj = v as Record<string, unknown>;+ if (typeof obj.dockLeftWidth === "number") {+ this.dockLeftWidth = clampDock(obj.dockLeftWidth);+ }+ if (typeof obj.dockRightWidth === "number") {+ this.dockRightWidth = clampDock(obj.dockRightWidth);+ }+ if (typeof obj.dockLeftVisible === "boolean") {+ this.dockLeftVisible = obj.dockLeftVisible;+ }+ if (typeof obj.dockRightVisible === "boolean") {+ this.dockRightVisible = obj.dockRightVisible;+ }+ }+ } catch {+ /* ignore */+ }+ this.hydrated = true;+ }++ persistLocal() {+ if (typeof localStorage === "undefined") return;+ try {+ const payload: PersistedShape = {+ dockLeftWidth: this.dockLeftWidth,+ dockRightWidth: this.dockRightWidth,+ dockLeftVisible: this.dockLeftVisible,+ dockRightVisible: this.dockRightVisible,+ };+ localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));+ } catch {+ /* ignore */+ }+ }++ async persistBackend() {+ try {+ await notesSettingsSet({+ key: "layout_snapshot",+ value: {+ dockLeftWidth: this.dockLeftWidth,+ dockRightWidth: this.dockRightWidth,+ dockLeftVisible: this.dockLeftVisible,+ dockRightVisible: this.dockRightVisible,+ },+ });+ } catch {+ /* ignore */+ }+ }++ setDockLeftWidth(px: number) {+ this.dockLeftWidth = clampDock(px);+ this.persistLocal();+ }++ setDockRightWidth(px: number) {+ this.dockRightWidth = clampDock(px);+ this.persistLocal();+ }++ toggleDockLeft() {+ this.dockLeftVisible = !this.dockLeftVisible;+ this.persistLocal();+ void this.persistBackend();+ }++ toggleDockRight() {+ this.dockRightVisible = !this.dockRightVisible;+ this.persistLocal();+ void this.persistBackend();+ }++ rememberReturnUrl(url: string) {+ if (typeof sessionStorage === "undefined") return;+ if (url.startsWith("/study/notes")) return;+ try {+ sessionStorage.setItem(RETURN_URL_KEY, url);+ } catch {+ /* ignore */+ }+ }++ consumeReturnUrl(): string {+ if (typeof sessionStorage === "undefined") return "/study/library";+ try {+ const stored = sessionStorage.getItem(RETURN_URL_KEY);+ if (stored && !stored.startsWith("/study/notes")) return stored;+ } catch {+ /* ignore */+ }+ return "/study/library";+ }++ setActivePage(name: string | null, title: string | null) {+ this.currentPageName = name;+ this.currentPageTitle = title;+ }++ setCounts(words: number, chars: number) {+ this.wordCount = words;+ this.charCount = chars;+ }++ setMode(mode: NotesEditorMode) {+ this.mode = mode;+ }++ setSaving(saving: boolean) {+ this.saving = saving;+ }+}++function clampDock(px: number): number {+ if (!Number.isFinite(px)) return DEFAULT_DOCK_LEFT;+ return Math.min(DOCK_MAX, Math.max(DOCK_MIN, Math.round(px)));+}++export const notesShell = new NotesShellStore();+export const NOTES_SHELL_DOCK_MIN = DOCK_MIN;+export const NOTES_SHELL_DOCK_MAX = DOCK_MAX;diff --git a/src/lib/study-notes/tabs-store.svelte.ts b/src/lib/study-notes/tabs-store.svelte.tsnew file mode 100644index 00000000..9b10b2f1--- /dev/null+++ b/src/lib/study-notes/tabs-store.svelte.ts@@ -0,0 +1,424 @@+import {+ notesActiveStateGet,+ notesActiveStateSet,+ notesTabsListForWnd,+ notesTabsOpen,+ notesTabsClose,+ notesTabsReorder,+ notesTabsMoveToWnd,+ notesTabsPin,+ notesTabsTouchFocus,+ notesWndsTree,+ notesWndsSplit,+ notesWndsClose,+ notesWndsSetRatio,+ type TabSummary,+ type TabViewKind,+ type WndNode,+} from "$lib/notes-bridge";++const ACTIVE_WND_KEY = "active_wnd_id";+const ACTIVE_TABS_KEY = "active_tab_id_per_wnd";+const RECENTLY_CLOSED_LIMIT = 12;++type RecentlyClosedTab = {+ wndId: number;+ pageId: number | null;+ viewKind: TabViewKind;+};++class TabsStore {+ tree = $state<WndNode | null>(null);+ tabsByWnd = $state<Record<number, TabSummary[]>>({});+ activeWndId = $state<number | null>(null);+ activeTabIdByWnd = $state<Record<number, number | null>>({});+ recentlyClosed = $state<RecentlyClosedTab[]>([]);+ hydrated = $state(false);+ loadingTree = $state(false);++ collectLeafIds(node: WndNode | null, acc: number[] = []): number[] {+ if (!node) return acc;+ if (!node.split_dir) {+ acc.push(node.id);+ return acc;+ }+ for (const child of node.children) this.collectLeafIds(child, acc);+ return acc;+ }++ get leafIds(): number[] {+ return this.collectLeafIds(this.tree);+ }++ get activeTabId(): number | null {+ if (this.activeWndId == null) return null;+ return this.activeTabIdByWnd[this.activeWndId] ?? null;+ }++ get activeTab(): TabSummary | null {+ if (this.activeWndId == null) return null;+ const tabs = this.tabsByWnd[this.activeWndId] ?? [];+ const id = this.activeTabIdByWnd[this.activeWndId];+ return tabs.find((t) => t.id === id) ?? tabs[0] ?? null;+ }++ async hydrate() {+ if (this.hydrated || this.loadingTree) return;+ this.loadingTree = true;+ try {+ const tree = await notesWndsTree();+ this.tree = tree;+ const leafIds = this.collectLeafIds(tree);+ const tabsLists = await Promise.all(+ leafIds.map(async (id) => [id, await notesTabsListForWnd(id)] as const),+ );+ const next: Record<number, TabSummary[]> = {};+ for (const [id, list] of tabsLists) next[id] = list;+ this.tabsByWnd = next;++ const activeWndRes = await notesActiveStateGet(ACTIVE_WND_KEY);+ const activeWnd =+ typeof activeWndRes.value === "number" ? activeWndRes.value : null;+ this.activeWndId =+ activeWnd != null && leafIds.includes(activeWnd)+ ? activeWnd+ : (leafIds[0] ?? null);++ const activeTabsRes = await notesActiveStateGet(ACTIVE_TABS_KEY);+ const stored =+ activeTabsRes.value && typeof activeTabsRes.value === "object"+ ? (activeTabsRes.value as Record<string, number | null>)+ : {};+ const sanitized: Record<number, number | null> = {};+ for (const id of leafIds) {+ const raw = stored[String(id)];+ const tabs = next[id] ?? [];+ const exists =+ typeof raw === "number" && tabs.some((t) => t.id === raw);+ sanitized[id] = exists ? (raw as number) : (tabs[0]?.id ?? null);+ }+ this.activeTabIdByWnd = sanitized;+ this.hydrated = true;+ } finally {+ this.loadingTree = false;+ }+ }++ async refreshWnd(wndId: number) {+ const list = await notesTabsListForWnd(wndId);+ this.tabsByWnd = { ...this.tabsByWnd, [wndId]: list };+ const current = this.activeTabIdByWnd[wndId];+ if (current == null || !list.some((t) => t.id === current)) {+ this.setActiveTab(wndId, list[0]?.id ?? null);+ }+ }++ async refreshTree() {+ const tree = await notesWndsTree();+ this.tree = tree;+ const leafIds = this.collectLeafIds(tree);+ const next: Record<number, TabSummary[]> = {};+ for (const id of leafIds) {+ const existing = this.tabsByWnd[id];+ next[id] = existing ?? (await notesTabsListForWnd(id));+ }+ this.tabsByWnd = next;+ if (this.activeWndId == null || !leafIds.includes(this.activeWndId)) {+ this.activeWndId = leafIds[0] ?? null;+ void this.persistActiveWnd();+ }+ const sanitized: Record<number, number | null> = {};+ for (const id of leafIds) {+ const list = next[id];+ const cur = this.activeTabIdByWnd[id];+ sanitized[id] =+ cur != null && list.some((t) => t.id === cur)+ ? cur+ : (list[0]?.id ?? null);+ }+ this.activeTabIdByWnd = sanitized;+ void this.persistActiveTabs();+ }++ setActiveWnd(wndId: number) {+ if (!this.leafIds.includes(wndId)) return;+ this.activeWndId = wndId;+ void this.persistActiveWnd();+ }++ setActiveTab(wndId: number, tabId: number | null) {+ this.activeTabIdByWnd = { ...this.activeTabIdByWnd, [wndId]: tabId };+ void this.persistActiveTabs();+ if (tabId != null) void notesTabsTouchFocus(tabId).catch(() => {});+ }++ async persistActiveWnd() {+ try {+ await notesActiveStateSet({ key: ACTIVE_WND_KEY, value: this.activeWndId });+ } catch {+ /* ignore */+ }+ }++ async persistActiveTabs() {+ try {+ await notesActiveStateSet({+ key: ACTIVE_TABS_KEY,+ value: this.activeTabIdByWnd as unknown as object,+ });+ } catch {+ /* ignore */+ }+ }++ pushRecentlyClosed(entry: RecentlyClosedTab) {+ const next = [entry, ...this.recentlyClosed].slice(0, RECENTLY_CLOSED_LIMIT);+ this.recentlyClosed = next;+ }++ popRecentlyClosed(): RecentlyClosedTab | null {+ if (this.recentlyClosed.length === 0) return null;+ const [head, ...rest] = this.recentlyClosed;+ this.recentlyClosed = rest;+ return head;+ }++ async openTab(args: {+ wndId: number;+ pageId?: number | null;+ viewKind?: TabViewKind;+ activate?: boolean;+ }): Promise<number> {+ const res = await notesTabsOpen({+ wndId: args.wndId,+ pageId: args.pageId,+ viewKind: args.viewKind,+ });+ await this.refreshWnd(args.wndId);+ if (args.activate !== false) {+ this.setActiveWnd(args.wndId);+ this.setActiveTab(args.wndId, res.tab_id);+ }+ return res.tab_id;+ }++ async closeTab(tabId: number) {+ const wndId = this.findWndOfTab(tabId);+ const tab = wndId != null ? this.findTab(wndId, tabId) : null;+ if (tab) {+ this.pushRecentlyClosed({+ wndId: tab.wnd_id,+ pageId: tab.page_id,+ viewKind: tab.view_kind,+ });+ }+ const report = await notesTabsClose(tabId);+ if (wndId != null) {+ await this.refreshWnd(wndId);+ if (report.fallback_tab_id != null) {+ this.setActiveTab(wndId, report.fallback_tab_id);+ }+ }+ }++ async closeOtherTabsInWnd(wndId: number, keepTabId: number) {+ const tabs = this.tabsByWnd[wndId] ?? [];+ for (const t of tabs) {+ if (t.id !== keepTabId && !t.pinned) {+ await notesTabsClose(t.id);+ }+ }+ await this.refreshWnd(wndId);+ this.setActiveTab(wndId, keepTabId);+ }++ async closeTabsToRight(wndId: number, anchorTabId: number) {+ const tabs = (this.tabsByWnd[wndId] ?? []).slice().sort((a, b) => {+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;+ return a.sort_idx - b.sort_idx;+ });+ const idx = tabs.findIndex((t) => t.id === anchorTabId);+ if (idx === -1) return;+ for (let i = idx + 1; i < tabs.length; i++) {+ const t = tabs[i];+ if (!t.pinned) await notesTabsClose(t.id);+ }+ await this.refreshWnd(wndId);+ }++ async pinTab(tabId: number, pinned: boolean) {+ await notesTabsPin({ tabId, pinned });+ const wndId = this.findWndOfTab(tabId);+ if (wndId != null) await this.refreshWnd(wndId);+ }++ async reorderTabs(wndId: number, orderedIds: number[]) {+ for (let i = 0; i < orderedIds.length; i++) {+ await notesTabsReorder({ tabId: orderedIds[i], newSortIdx: i });+ }+ await this.refreshWnd(wndId);+ }++ async moveTabToWnd(tabId: number, targetWndId: number) {+ await notesTabsMoveToWnd({ tabId, targetWndId });+ const sourceWnd = this.findWndOfTab(tabId);+ if (sourceWnd != null && sourceWnd !== targetWndId) {+ await this.refreshWnd(sourceWnd);+ }+ await this.refreshWnd(targetWndId);+ this.setActiveWnd(targetWndId);+ this.setActiveTab(targetWndId, tabId);+ }++ async splitWnd(parentWndId: number, direction: "horizontal" | "vertical") {+ const res = await notesWndsSplit({ parentWndId, direction });+ await this.refreshTree();+ this.setActiveWnd(res.new_wnd_id);+ return res.new_wnd_id;+ }++ async closeWnd(wndId: number) {+ if (this.leafIds.length <= 1) return;+ await notesWndsClose(wndId);+ await this.refreshTree();+ }++ async setRatio(internalWndId: number, ratio: number) {+ await notesWndsSetRatio({ wndId: internalWndId, ratio });+ if (this.tree) {+ this.tree = updateRatio(this.tree, internalWndId, ratio);+ }+ }++ findTab(wndId: number, tabId: number): TabSummary | undefined {+ return (this.tabsByWnd[wndId] ?? []).find((t) => t.id === tabId);+ }++ findWndOfTab(tabId: number): number | null {+ for (const [wnd, tabs] of Object.entries(this.tabsByWnd)) {+ if (tabs.some((t) => t.id === tabId)) return Number(wnd);+ }+ return null;+ }++ cycleActiveTab(direction: 1 | -1) {+ if (this.activeWndId == null) return;+ const tabs = this.sortedTabsForWnd(this.activeWndId);+ if (tabs.length === 0) return;+ const cur = this.activeTabIdByWnd[this.activeWndId];+ const idx = tabs.findIndex((t) => t.id === cur);+ const nextIdx =+ idx === -1 ? 0 : (idx + direction + tabs.length) % tabs.length;+ this.setActiveTab(this.activeWndId, tabs[nextIdx].id);+ }++ activateTabIndex(index: number) {+ if (this.activeWndId == null) return;+ const tabs = this.sortedTabsForWnd(this.activeWndId);+ if (index < 0 || index >= tabs.length) return;+ this.setActiveTab(this.activeWndId, tabs[index].id);+ }++ sortedTabsForWnd(wndId: number): TabSummary[] {+ const tabs = (this.tabsByWnd[wndId] ?? []).slice();+ tabs.sort((a, b) => {+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;+ return a.sort_idx - b.sort_idx;+ });+ return tabs;+ }++ focusNeighborWnd(direction: "left" | "right" | "up" | "down") {+ if (this.activeWndId == null || this.tree == null) return;+ const target = neighborLeaf(this.tree, this.activeWndId, direction);+ if (target != null) this.setActiveWnd(target);+ }+}++function updateRatio(node: WndNode, id: number, ratio: number): WndNode {+ if (node.id === id) {+ return { ...node, ratio };+ }+ if (!node.split_dir) return node;+ return {+ ...node,+ children: node.children.map((c) => updateRatio(c, id, ratio)),+ };+}++type Rect = { x: number; y: number; w: number; h: number };++function computeRects(node: WndNode, rect: Rect, acc: Map<number, Rect>) {+ if (!node.split_dir) {+ acc.set(node.id, rect);+ return;+ }+ if (node.children.length !== 2) {+ for (const c of node.children) computeRects(c, rect, acc);+ return;+ }+ const ratio = node.ratio;+ if (node.split_dir === "vertical") {+ const w1 = rect.w * ratio;+ computeRects(node.children[0], { ...rect, w: w1 }, acc);+ computeRects(+ node.children[1],+ { x: rect.x + w1, y: rect.y, w: rect.w - w1, h: rect.h },+ acc,+ );+ } else {+ const h1 = rect.h * ratio;+ computeRects(node.children[0], { ...rect, h: h1 }, acc);+ computeRects(+ node.children[1],+ { x: rect.x, y: rect.y + h1, w: rect.w, h: rect.h - h1 },+ acc,+ );+ }+}++function neighborLeaf(+ tree: WndNode,+ fromId: number,+ direction: "left" | "right" | "up" | "down",+): number | null {+ const rects = new Map<number, Rect>();+ computeRects(tree, { x: 0, y: 0, w: 1, h: 1 }, rects);+ const from = rects.get(fromId);+ if (!from) return null;+ let best: { id: number; dist: number } | null = null;+ for (const [id, r] of rects) {+ if (id === fromId) continue;+ let aligned = false;+ let dist = Infinity;+ const cy1 = from.y + from.h / 2;+ const cy2 = r.y + r.h / 2;+ const cx1 = from.x + from.w / 2;+ const cx2 = r.x + r.w / 2;+ if (direction === "left" && r.x + r.w <= from.x + 1e-6) {+ aligned = !(cy2 + r.h / 2 < from.y || cy2 - r.h / 2 > from.y + from.h);+ dist = from.x - (r.x + r.w);+ } else if (direction === "right" && r.x >= from.x + from.w - 1e-6) {+ aligned = !(cy2 + r.h / 2 < from.y || cy2 - r.h / 2 > from.y + from.h);+ dist = r.x - (from.x + from.w);+ } else if (direction === "up" && r.y + r.h <= from.y + 1e-6) {+ aligned = !(cx2 + r.w / 2 < from.x || cx2 - r.w / 2 > from.x + from.w);+ dist = from.y - (r.y + r.h);+ } else if (direction === "down" && r.y >= from.y + from.h - 1e-6) {+ aligned = !(cx2 + r.w / 2 < from.x || cx2 - r.w / 2 > from.x + from.w);+ dist = r.y - (from.y + from.h);+ }+ if (!aligned) continue;+ const tieBreak =+ direction === "left" || direction === "right"+ ? Math.abs(cy1 - cy2)+ : Math.abs(cx1 - cx2);+ const score = dist + tieBreak * 0.001;+ if (best === null || score < best.dist) {+ best = { id, dist: score };+ }+ }+ return best?.id ?? null;+}++export const tabsStore = new TabsStore();diff --git a/src/lib/ytdlp-presets.ts b/src/lib/ytdlp-presets.tsnew file mode 100644index 00000000..c0a2fb11--- /dev/null+++ b/src/lib/ytdlp-presets.ts@@ -0,0 +1,79 @@+import type { AppSettings } from "$lib/stores/settings-store.svelte";++export type YtdlpPresetId = "fast" | "quality" | "compact" | "music_only";++export type YtdlpPreset = {+ id: YtdlpPresetId;+ labelKey: string;+ descKey: string;+ download: {+ video_quality: string;+ embed_metadata: boolean;+ embed_thumbnail: boolean;+ download_subtitles: boolean;+ };+};++export const YTDLP_PRESETS: YtdlpPreset[] = [+ {+ id: "fast",+ labelKey: "settings.download.preset_fast",+ descKey: "settings.download.preset_fast_desc",+ download: {+ video_quality: "480p",+ embed_metadata: false,+ embed_thumbnail: false,+ download_subtitles: false,+ },+ },+ {+ id: "quality",+ labelKey: "settings.download.preset_quality",+ descKey: "settings.download.preset_quality_desc",+ download: {+ video_quality: "best",+ embed_metadata: true,+ embed_thumbnail: true,+ download_subtitles: false,+ },+ },+ {+ id: "compact",+ labelKey: "settings.download.preset_compact",+ descKey: "settings.download.preset_compact_desc",+ download: {+ video_quality: "720p",+ embed_metadata: true,+ embed_thumbnail: false,+ download_subtitles: false,+ },+ },+ {+ id: "music_only",+ labelKey: "settings.download.preset_music_only",+ descKey: "settings.download.preset_music_only_desc",+ download: {+ video_quality: "audio",+ embed_metadata: true,+ embed_thumbnail: true,+ download_subtitles: false,+ },+ },+];++export function matchActivePreset(settings: AppSettings | null): YtdlpPresetId | null {+ if (!settings) return null;+ const d = settings.download;+ for (const preset of YTDLP_PRESETS) {+ const p = preset.download;+ if (+ d.video_quality === p.video_quality+ && d.embed_metadata === p.embed_metadata+ && d.embed_thumbnail === p.embed_thumbnail+ && d.download_subtitles === p.download_subtitles+ ) {+ return preset.id;+ }+ }+ return null;+}diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelteindex 29ae2bcd..b8581f02 100644--- a/src/routes/+layout.svelte+++ b/src/routes/+layout.svelte@@ -103,8 +103,21 @@onMount(() => {let cleanup: (() => void) | undefined;let unlistenExternal: (() => void) | undefined;+ let unlistenMusicHotkey: (() => void) | undefined;initDownloadListener().then((fn) => (cleanup = fn));setTimeout(() => void checkAutoVacuum(), 5000);+ import("$lib/rpc").then(({ rpcSyncIdleStats }) => rpcSyncIdleStats());++ listen<{ url: string }>("music-hotkey-pressed", async (event) => {+ const url = event.payload?.url;+ if (!url) return;+ try {+ const { pluginInvoke } = await import("$lib/plugin-invoke");+ await pluginInvoke("study", "study:music:ytdlp:download_shortcut", { url });+ } catch (e) {+ console.warn("[music-hotkey] download failed", e);+ }+ }).then((fn) => (unlistenMusicHotkey = fn));invoke<{ id: string; enabled: boolean; nav: { route: string; label: Record<string, string>; icon_svg: string | null; group: string; order: number }[] }[]>("list_plugins").then((plugins) => {@@ -154,6 +167,7 @@return () => {cleanup?.();unlistenExternal?.();+ unlistenMusicHotkey?.();mediaQuery.removeEventListener("change", handleChange);};});diff --git a/src/routes/about/project/+page.svelte b/src/routes/about/project/+page.svelteindex 7da624bd..3d030017 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.5.2";+ const APP_VERSION = "0.6.0";async function openGitHub() {await open(GITHUB_URL);diff --git a/src/routes/downloads/+page.svelte b/src/routes/downloads/+page.svelteindex 13791a36..eaaebc9d 100644--- a/src/routes/downloads/+page.svelte+++ b/src/routes/downloads/+page.svelte@@ -1,4 +1,6 @@<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";import { invoke } from "@tauri-apps/api/core";import { pluginInvoke } from "$lib/plugin-invoke";import { t } from "$lib/i18n";@@ -8,6 +10,7 @@getDownloads,formatBytes,formatSpeed,+ formatEta,getFinishedCount,getSpeedHistory,type CourseDownloadItem,@@ -21,6 +24,39 @@import DownloadSpeedGraph from "$components/download/DownloadSpeedGraph.svelte";import DownloadLog from "$components/download/DownloadLog.svelte";+ let studyAvailable = $state(false);++ onMount(async () => {+ try {+ const plugins = await invoke<{+ id: string;+ enabled: boolean;+ loaded: boolean;+ }[]>("list_plugins");+ studyAvailable = plugins.some(+ (p) => p.id === "study" && p.enabled && p.loaded,+ );+ } catch {+ studyAvailable = false;+ }+ });++ function canOpenInStudy(item: GenericDownloadItem): boolean {+ return (+ studyAvailable &&+ item.status === "complete" &&+ !!item.filePath &&+ (item.queueKind === "video" || item.queueKind === "audio")+ );+ }++ function openInStudy(filePath: string) {+ const parts = filePath.replace(/\\/g, "/").split("/");+ const name = parts[parts.length - 1] ?? "";+ const url = `/study/watch?path=${encodeURIComponent(filePath)}&name=${encodeURIComponent(name)}`;+ goto(url);+ }+let downloads = $derived(getDownloads());let courseList = $derived([...downloads.values()].filter((d): d is CourseDownloadItem => d.kind === "course")@@ -367,6 +403,19 @@{/if}</button>{:else if item.status === "complete" && item.filePath}+ {#if canOpenInStudy(item)}+ <button+ class="action-icon-btn"+ onclick={() => openInStudy(item.filePath!)}+ aria-label={$t('downloads.open_in_study')}+ title={$t('downloads.open_in_study')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10" />+ <polygon points="10 8 16 12 10 16 10 8" fill="currentColor" stroke="none" />+ </svg>+ </button>+ {/if}<buttonclass="action-icon-btn"onclick={() => revealFile(item.filePath!)}@@ -449,6 +498,10 @@{/if}{#if item.speed > 0}<span>{formatSpeed(item.speed)}</span>+ {#if formatEta(item.etaSeconds)}+ <span class="stats-sep">·</span>+ <span>ETA {formatEta(item.etaSeconds)}</span>+ {/if}<DownloadSpeedGraph points={getSpeedHistory(item.id)} />{/if}</div>diff --git a/src/routes/misc/+page.svelte b/src/routes/misc/+page.sveltenew file mode 100644index 00000000..41ea91bf--- /dev/null+++ b/src/routes/misc/+page.svelte@@ -0,0 +1,181 @@+<script lang="ts">+ type Card = {+ href: string;+ title: string;+ desc: string;+ iconPath: string;+ badge?: string;+ };++ const cards: Card[] = [+ {+ href: "/misc/studio",+ title: "Studio",+ desc: "Record screen + system audio. Replay buffer to clip what just happened.",+ iconPath: "M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2z M12 8a4 4 0 1 1-4 4 4 4 0 0 1 4-4z",+ badge: "BETA",+ },+ {+ href: "/misc/file-clip",+ title: "File clip",+ desc: "Pick a video on disk and extract a portion of it. Output goes to your downloads queue.",+ iconPath: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H9H8",+ },+ {+ href: "/misc/models",+ title: "Models",+ desc: "Download AI models for transcription, translation, and chat. All run locally — nothing uploaded.",+ 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",+ },+ {+ href: "/misc/library",+ title: "Library",+ desc: "All media you've imported, recorded, or transcribed. Search across titles, transcripts, and notes.",+ 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",+ },+ ];+</script>++<section class="misc-hub">+ <header class="head">+ <h1>Misc</h1>+ <p class="subtitle">Utilities and side tools.</p>+ </header>++ <div class="grid">+ {#each cards as c (c.href)}+ <a class="card" href={c.href} aria-label={c.title}>+ <div class="icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">+ <path d={c.iconPath} />+ </svg>+ </div>+ <div class="meta">+ <div class="title-row">+ <span class="title">{c.title}</span>+ {#if c.badge}+ <span class="badge">{c.badge}</span>+ {/if}+ </div>+ <span class="desc">{c.desc}</span>+ </div>+ </a>+ {/each}+ </div>+</section>++<style>+ .misc-hub {+ display: flex;+ flex-direction: column;+ gap: calc(var(--padding) * 2);+ width: 100%;+ max-width: 980px;+ margin-inline: auto;+ padding: 16px 20px 80px;+ }++ .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);+ }++ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));+ gap: 12px;+ }++ .card {+ display: flex;+ align-items: flex-start;+ gap: 14px;+ padding: 16px 18px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ text-decoration: none;+ color: inherit;+ transition: border-color 150ms ease, transform 100ms ease, background 150ms ease;+ }++ .card:hover,+ .card:focus-visible {+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 5%, var(--surface));+ transform: translateY(-1px);+ outline: none;+ }++ .card:focus-visible {+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--accent) 40%, transparent);+ }++ .icon {+ flex-shrink: 0;+ width: 44px;+ height: 44px;+ display: grid;+ place-items: center;+ border-radius: 10px;+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--accent);+ }++ .meta {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }++ .title-row {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .title {+ font-size: 14px;+ font-weight: 500;+ color: var(--secondary);+ }++ .badge {+ font-size: 9px;+ font-weight: 600;+ letter-spacing: 0.5px;+ padding: 2px 6px;+ border-radius: 4px;+ background: color-mix(in oklab, var(--accent) 18%, transparent);+ color: var(--accent);+ text-transform: uppercase;+ }++ .desc {+ font-size: 12px;+ color: var(--tertiary);+ line-height: 1.4;+ }++ @media (prefers-reduced-motion: reduce) {+ .card {+ transition: none;+ }+ .card:hover,+ .card:focus-visible {+ transform: none;+ }+ }+</style>diff --git a/src/routes/misc/file-clip/+page.svelte b/src/routes/misc/file-clip/+page.sveltenew file mode 100644index 00000000..36252e61--- /dev/null+++ b/src/routes/misc/file-clip/+page.svelte@@ -0,0 +1,480 @@+<script lang="ts">+ import { invoke, convertFileSrc } from "@tauri-apps/api/core";+ import { open as openDialog } from "@tauri-apps/plugin-dialog";+ import { emit } from "@tauri-apps/api/event";++ type ClipResult = {+ output_path: string;+ duration_secs: number;+ size_bytes: number;+ used_reencode: boolean;+ };++ let sourcePath = $state<string | null>(null);+ let sourceLabel = $state<string>("");+ let videoSrc = $state<string>("");+ let videoEl = $state<HTMLVideoElement | null>(null);+ let videoDuration = $state<number>(0);+ let videoCurrent = $state<number>(0);+ let startSecs = $state<number>(0);+ let endSecs = $state<number>(30);+ let durationSecs = $derived(Math.max(0.5, endSecs - startSecs));+ let busy = $state(false);+ let lastError = $state<string | null>(null);+ let lastResult = $state<ClipResult | null>(null);++ async function pickFile() {+ try {+ const picked = await openDialog({+ multiple: false,+ directory: false,+ filters: [+ {+ name: "Video",+ extensions: ["mp4", "mkv", "webm", "mov", "m4v", "avi"],+ },+ ],+ });+ if (typeof picked === "string" && picked) {+ sourcePath = picked;+ const parts = picked.replace(/\\/g, "/").split("/");+ sourceLabel = parts[parts.length - 1] ?? picked;+ try {+ videoSrc = convertFileSrc(picked);+ } catch {+ videoSrc = "";+ }+ lastResult = null;+ lastError = null;+ }+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ }+ }++ function onVideoLoaded() {+ if (!videoEl) return;+ videoDuration = videoEl.duration || 0;+ if (endSecs <= 0 || endSecs > videoDuration) {+ endSecs = Math.min(30, videoDuration);+ }+ }++ function onVideoTimeUpdate() {+ if (!videoEl) return;+ videoCurrent = videoEl.currentTime;+ }++ function setStartHere() {+ startSecs = Math.floor(videoCurrent);+ if (endSecs <= startSecs) endSecs = Math.min(startSecs + 30, videoDuration);+ }++ function setEndHere() {+ endSecs = Math.ceil(videoCurrent);+ if (startSecs >= endSecs) startSecs = Math.max(0, endSecs - 30);+ }++ function jumpToStart() {+ if (videoEl) videoEl.currentTime = startSecs;+ }++ function jumpToEnd() {+ if (videoEl) videoEl.currentTime = endSecs;+ }++ async function doClip() {+ if (!sourcePath || busy) return;+ busy = true;+ lastError = null;+ lastResult = null;+ try {+ const result = await invoke<ClipResult>("clip_video", {+ req: {+ source_path: sourcePath,+ start_secs: Number(startSecs),+ duration_secs: Number(durationSecs),+ dest_dir: null,+ label: "fileclip",+ reencode: null,+ },+ });+ lastResult = result;++ const queueId = Date.now() * 1000;+ const filename =+ result.output_path.replace(/\\/g, "/").split("/").pop() ??+ "clip.mp4";+ await emit("host:queue:external:enqueue", {+ queue_id: queueId,+ platform: "studio",+ title: filename,+ output_path: result.output_path,+ total_bytes: result.size_bytes,+ kind: "video",+ });+ await emit("host:queue:external:complete", {+ queue_id: queueId,+ success: true,+ file_path: result.output_path,+ file_size_bytes: result.size_bytes,+ });+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ busy = false;+ }+ }++ async function revealResult() {+ if (!lastResult) return;+ try {+ await invoke("reveal_file", { path: lastResult.output_path });+ } catch (e) {+ console.warn("[file-clip] reveal failed:", e);+ }+ }++ function fmtTime(secs: number): string {+ const m = Math.floor(secs / 60);+ const s = Math.floor(secs % 60);+ return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;+ }++ function fmtSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+ }+</script>++<section class="clip-page">+ <header class="head">+ <h1>File clip</h1>+ <p class="subtitle">+ Pick a video file and extract a portion. Uses fast stream copy when possible (no quality loss).+ </p>+ </header>++ <section class="picker-card">+ <div class="picker-row">+ <button type="button" class="pick-btn" onclick={pickFile} disabled={busy}>+ {sourcePath ? "Change file" : "Pick video file"}+ </button>+ {#if sourceLabel}+ <span class="filename mono" title={sourcePath ?? ""}>{sourceLabel}</span>+ {:else}+ <span class="filename muted">No file selected</span>+ {/if}+ </div>++ {#if sourcePath && videoSrc}+ <div class="player-wrap">+ <video+ bind:this={videoEl}+ src={videoSrc}+ controls+ onloadedmetadata={onVideoLoaded}+ ontimeupdate={onVideoTimeUpdate}+ class="player"+ ></video>+ <div class="player-time mono">+ <span>Now: {fmtTime(videoCurrent)}</span>+ {#if videoDuration > 0}+ <span class="muted"> / {fmtTime(videoDuration)}</span>+ {/if}+ </div>+ </div>++ <div class="markers">+ <div class="marker">+ <span class="marker-label">In</span>+ <span class="marker-value mono">{fmtTime(startSecs)}</span>+ <button type="button" class="marker-btn" onclick={setStartHere} disabled={busy}>+ Set here+ </button>+ <button type="button" class="marker-btn" onclick={jumpToStart} disabled={busy}>+ ↩ Jump+ </button>+ </div>+ <div class="marker">+ <span class="marker-label">Out</span>+ <span class="marker-value mono">{fmtTime(endSecs)}</span>+ <button type="button" class="marker-btn" onclick={setEndHere} disabled={busy}>+ Set here+ </button>+ <button type="button" class="marker-btn" onclick={jumpToEnd} disabled={busy}>+ ↩ Jump+ </button>+ </div>+ <div class="marker dur">+ <span class="marker-label">Duration</span>+ <span class="marker-value mono">{fmtTime(durationSecs)}</span>+ </div>+ </div>++ <button type="button" class="clip-btn" onclick={doClip} disabled={busy || durationSecs < 0.5}>+ {busy ? "Clipping…" : `✂ Clip ${fmtTime(durationSecs)} (${fmtTime(startSecs)} → ${fmtTime(endSecs)})`}+ </button>+ {/if}+ </section>++ {#if lastError}+ <div class="error" role="alert"><strong>Error:</strong> {lastError}</div>+ {/if}++ {#if lastResult}+ <section class="result-card">+ <h2>Clip ready</h2>+ <div class="result-stats">+ <div class="stat">+ <span class="stat-label">Duration</span>+ <span class="stat-value mono">{fmtTime(lastResult.duration_secs)}</span>+ </div>+ <div class="stat">+ <span class="stat-label">Size</span>+ <span class="stat-value mono">{fmtSize(lastResult.size_bytes)}</span>+ </div>+ <div class="stat">+ <span class="stat-label">Method</span>+ <span class="stat-value mono">+ {lastResult.used_reencode ? "Re-encoded" : "Stream copy"}+ </span>+ </div>+ </div>+ <div class="result-path mono" title={lastResult.output_path}>+ {lastResult.output_path}+ </div>+ <div class="result-actions">+ <a href="/downloads" class="btn-link">View in queue</a>+ <button type="button" class="btn-reveal" onclick={revealResult}>Open folder</button>+ </div>+ </section>+ {/if}++ <p class="hint">+ Tip: stream copy is instant but starts at the nearest keyframe (might begin 1-2s before/after the+ requested start). For precise cuts, the system falls back to re-encoding automatically.+ </p>+</section>++<style>+ .clip-page {+ display: flex;+ flex-direction: column;+ gap: calc(var(--padding) * 2);+ width: 100%;+ max-width: 760px;+ margin-inline: auto;+ padding: 16px 20px 80px;+ }+ .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);+ }+ .picker-card {+ display: flex;+ flex-direction: column;+ gap: 14px;+ padding: 20px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }+ .picker-row {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .pick-btn {+ padding: 10px 18px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--bg);+ color: var(--secondary);+ font-size: 13px;+ font-family: inherit;+ cursor: pointer;+ }+ .pick-btn:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ }+ .filename {+ font-size: 12px;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .muted {+ color: var(--tertiary);+ }+ .player-wrap {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .player {+ width: 100%;+ max-height: 480px;+ background: black;+ border-radius: var(--border-radius);+ }+ .player-time {+ font-size: 12px;+ color: var(--secondary);+ text-align: right;+ }+ .markers {+ display: grid;+ grid-template-columns: 1fr 1fr 1fr;+ gap: 10px;+ }+ .marker {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--bg);+ }+ .marker.dur {+ border-style: dashed;+ background: color-mix(in oklab, var(--accent) 4%, var(--bg));+ }+ .marker-label {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ color: var(--tertiary);+ }+ .marker-value {+ font-size: 16px;+ color: var(--secondary);+ }+ .marker-btn {+ padding: 4px 10px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: transparent;+ color: var(--secondary);+ font-size: 11px;+ font-family: inherit;+ cursor: pointer;+ }+ .marker-btn:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ }+ .marker-btn:disabled {+ opacity: 0.5;+ }+ .clip-btn {+ padding: 12px 18px;+ border: 1px solid var(--accent);+ border-radius: var(--border-radius);+ background: color-mix(in oklab, var(--accent) 14%, var(--bg));+ color: var(--accent);+ font-size: 14px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ }+ .clip-btn:hover:not(:disabled) {+ background: color-mix(in oklab, var(--accent) 22%, var(--bg));+ }+ .clip-btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }+ .error {+ padding: 10px 14px;+ border-radius: var(--border-radius);+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ font-size: 13px;+ }+ .result-card {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 16px 20px;+ border: 1px solid color-mix(in oklab, oklch(70% 0.18 145) 60%, var(--input-border));+ border-radius: var(--border-radius);+ background: color-mix(in oklab, oklch(70% 0.18 145) 4%, var(--surface));+ }+ .result-card h2 {+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ color: var(--secondary);+ }+ .result-stats {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 10px;+ }+ .stat {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .stat-label {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.4px;+ color: var(--tertiary);+ }+ .stat-value {+ font-size: 13px;+ color: var(--secondary);+ }+ .mono {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-variant-numeric: tabular-nums;+ }+ .result-path {+ font-size: 11px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .result-actions {+ display: flex;+ gap: 10px;+ }+ .btn-link,+ .btn-reveal {+ padding: 6px 14px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: transparent;+ color: var(--secondary);+ font-size: 12px;+ font-family: inherit;+ cursor: pointer;+ text-decoration: none;+ }+ .btn-link:hover,+ .btn-reveal:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .hint {+ margin: 0;+ font-size: 11px;+ color: var(--tertiary);+ line-height: 1.5;+ }+</style>diff --git a/src/routes/misc/library/+page.svelte b/src/routes/misc/library/+page.sveltenew file mode 100644index 00000000..0a0b640c--- /dev/null+++ b/src/routes/misc/library/+page.svelte@@ -0,0 +1,671 @@+<script lang="ts">+ import { onDestroy, onMount } from "svelte";+ import { invoke } from "@tauri-apps/api/core";+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";+ import { pluginInvoke } from "$lib/plugin-invoke";++ type MediaKind = "video" | "audio" | "pdf" | "clip";++ type MediaItem = {+ id: number;+ kind: MediaKind;+ title: string;+ file_path: string;+ file_size_bytes: number | null;+ duration_secs: number | null;+ page_count: number | null;+ thumbnail_path: string | null;+ added_at: number;+ last_opened_at: number | null;+ progress_pct: number;+ source_url: string | null;+ metadata_json: string | null;+ };++ type SearchHit = {+ media_item_id: number;+ kind: string;+ title: string;+ file_path: string;+ score: number;+ };++ let items = $state<MediaItem[]>([]);+ let searchHits = $state<SearchHit[]>([]);+ let isSearching = $state(false);+ let totalCount = $state(0);+ let kindFilter = $state<MediaKind | "all">("all");+ let query = $state("");+ let lastError = $state<string | null>(null);+ let loading = $state(true);+ let searchDebounce: number | null = null;++ type TranscribeState = "idle" | "running" | "done" | "error";+ let transcribeStates = $state<Record<number, TranscribeState>>({});+ let transcribeMessages = $state<Record<number, string>>({});+ let transcribeProgress = $state<Record<number, number>>({});+ let transcribeQueueIds = $state<Record<number, number>>({});++ let unlistenStarted: UnlistenFn | null = null;+ let unlistenProgress: UnlistenFn | null = null;+ let unlistenDone: UnlistenFn | null = null;++ function findItemByPath(path: string): MediaItem | undefined {+ const norm = (p: string) => p.replace(/\\/g, "/").toLowerCase();+ return items.find((it) => norm(it.file_path) === norm(path));+ }++ onMount(() => {+ void refresh();+ void initListeners();+ });++ onDestroy(() => {+ unlistenStarted?.();+ unlistenProgress?.();+ unlistenDone?.();+ });++ async function initListeners() {+ unlistenStarted = await listen("misc:transcribe:started", (e) => {+ const p = e.payload as { queue_id: number; input_path: string };+ const item = findItemByPath(p.input_path);+ if (item) {+ transcribeQueueIds = { ...transcribeQueueIds, [p.queue_id]: item.id };+ transcribeStates = { ...transcribeStates, [item.id]: "running" };+ transcribeMessages = {+ ...transcribeMessages,+ [item.id]: "Extracting audio…",+ };+ transcribeProgress = { ...transcribeProgress, [item.id]: 0 };+ }+ });+ unlistenProgress = await listen("misc:transcribe:progress", (e) => {+ const p = e.payload as { queue_id: number; percent: number };+ const itemId = transcribeQueueIds[p.queue_id];+ if (itemId != null) {+ transcribeProgress = { ...transcribeProgress, [itemId]: p.percent };+ transcribeMessages = {+ ...transcribeMessages,+ [itemId]: `Transcribing… ${p.percent}%`,+ };+ }+ });+ unlistenDone = await listen("misc:transcribe:done", (e) => {+ const p = e.payload as {+ queue_id: number;+ srt_path: string;+ elapsed_s: number;+ segment_count: number;+ language: string;+ };+ const itemId = transcribeQueueIds[p.queue_id];+ if (itemId != null) {+ transcribeStates = { ...transcribeStates, [itemId]: "done" };+ transcribeMessages = {+ ...transcribeMessages,+ [itemId]: `${p.segment_count} segmentos · ${p.elapsed_s.toFixed(1)}s · ${p.language} → ${p.srt_path}`,+ };+ transcribeProgress = { ...transcribeProgress, [itemId]: 100 };+ }+ });+ }++ async function refresh() {+ loading = true;+ lastError = null;+ try {+ const args: Record<string, unknown> = { limit: 200 };+ if (kindFilter !== "all") args.kind = kindFilter;+ items = await pluginInvoke<MediaItem[]>("misc", "misc:library:list", args);+ const c = await pluginInvoke<{ count: number }>("misc", "misc:library:count", {});+ totalCount = c.count;+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ }++ async function runSearch() {+ if (!query.trim()) {+ isSearching = false;+ searchHits = [];+ return;+ }+ isSearching = true;+ try {+ searchHits = await pluginInvoke<SearchHit[]>("misc", "misc:library:search", {+ query: query.trim(),+ limit: 50,+ });+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ }+ }++ function onQueryInput() {+ if (searchDebounce != null) clearTimeout(searchDebounce);+ searchDebounce = window.setTimeout(() => void runSearch(), 250);+ }++ $effect(() => {+ void kindFilter;+ void refresh();+ });++ async function removeItem(id: number) {+ try {+ await pluginInvoke("misc", "misc:library:remove", { id });+ await refresh();+ if (isSearching) await runSearch();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ }+ }++ async function revealFile(path: string) {+ try {+ await invoke("reveal_file", { path });+ } catch (e) {+ console.warn("[library] reveal_file failed:", e);+ }+ }++ async function transcribeItem(item: MediaItem) {+ if (item.kind !== "video" && item.kind !== "audio" && item.kind !== "clip") {+ return;+ }+ if (transcribeStates[item.id] === "running") return;+ transcribeStates = { ...transcribeStates, [item.id]: "running" };+ transcribeMessages = { ...transcribeMessages, [item.id]: "Starting…" };+ transcribeProgress = { ...transcribeProgress, [item.id]: 0 };+ try {+ await pluginInvoke<{+ srt_path: string;+ elapsed_s: number;+ duration_s: number;+ segment_count: number;+ }>("misc", "misc:transcribe:run", {+ path: item.file_path,+ wordTimestamps: true,+ });+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ transcribeStates = { ...transcribeStates, [item.id]: "error" };+ transcribeMessages = { ...transcribeMessages, [item.id]: msg };+ if (msg.includes("no whisper model installed")) {+ lastError = "No whisper model installed. Go to /misc/models and install at least 'Whisper Tiny' (~75 MB).";+ } else if (msg.includes("Error code: -6")) {+ lastError =+ "Whisper falhou no encode (-6). Tenta clip mais longo (>2s) ou um modelo maior. Whisper-tiny pode falhar em audio muito curto.";+ } else {+ lastError = msg;+ }+ }+ }++ function canTranscribe(kind: MediaKind): boolean {+ return kind === "video" || kind === "audio" || kind === "clip";+ }++ function fmtSize(bytes: number | null): string {+ if (!bytes) return "—";+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(0)} MB`;+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;+ }++ function fmtDuration(secs: number | null): string {+ if (!secs) return "—";+ const total = Math.floor(secs);+ const m = Math.floor(total / 60);+ const s = total % 60;+ if (m >= 60) {+ const h = Math.floor(m / 60);+ const mm = m % 60;+ return `${h}h${String(mm).padStart(2, "0")}`;+ }+ return `${m}:${String(s).padStart(2, "0")}`;+ }++ function fmtRel(unixSecs: number): string {+ const diff = Date.now() / 1000 - unixSecs;+ if (diff < 60) return "just now";+ if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;+ if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;+ return new Date(unixSecs * 1000).toLocaleDateString();+ }++ function kindBadge(kind: MediaKind | string): string {+ switch (kind) {+ case "video": return "🎬";+ case "audio": return "🎵";+ case "pdf": return "📄";+ case "clip": return "✂️";+ default: return "•";+ }+ }+</script>++<section class="library-page">+ <header class="head">+ <h1>Library</h1>+ <p class="subtitle">+ All media you've imported, recorded, or transcribed. {totalCount} item{totalCount === 1 ? "" : "s"}.+ </p>+ </header>++ <div class="controls">+ <input+ type="search"+ class="search-input"+ placeholder="Search title, transcript, notes…"+ bind:value={query}+ oninput={onQueryInput}+ />+ <div class="kind-chips" role="group" aria-label="Filter by kind">+ {#each (["all", "video", "audio", "pdf", "clip"] as const) as k}+ <button+ type="button"+ class="chip"+ class:active={kindFilter === k}+ onclick={() => (kindFilter = k)}+ >+ {k === "all" ? "All" : `${kindBadge(k)} ${k}`}+ </button>+ {/each}+ </div>+ </div>++ {#if lastError}+ <div class="error" role="alert"><strong>Error:</strong> {lastError}</div>+ {/if}++ {#if loading}+ <p class="empty">Loading…</p>+ {:else if isSearching}+ <h2 class="section-title">{searchHits.length} result{searchHits.length === 1 ? "" : "s"} for "{query}"</h2>+ {#if searchHits.length === 0}+ <p class="empty">No matches. Try simpler terms or different keywords.</p>+ {:else}+ <ul class="hit-list">+ {#each searchHits as hit (hit.media_item_id)}+ <li class="hit-row">+ <span class="hit-kind">{kindBadge(hit.kind)}</span>+ <div class="hit-meta">+ <span class="hit-title">{hit.title}</span>+ <span class="hit-path mono">{hit.file_path}</span>+ </div>+ <span class="hit-score mono">{hit.score.toFixed(2)}</span>+ <button type="button" class="btn-secondary" onclick={() => revealFile(hit.file_path)}>+ Open+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ {:else if items.length === 0}+ <p class="empty">+ {#if kindFilter !== "all"}+ No {kindFilter} items in library.+ {:else}+ Library empty. Record something in Studio or import a file.+ {/if}+ </p>+ {:else}+ <div class="grid">+ {#each items as item (item.id)}+ <article class="card">+ <div class="card-head">+ <span class="card-kind">{kindBadge(item.kind)}</span>+ <span class="card-title" title={item.title}>{item.title}</span>+ </div>+ <div class="card-meta mono">+ {#if item.kind === "pdf"}+ {item.page_count ?? "?"} pages+ {:else}+ {fmtDuration(item.duration_secs)}+ {/if}+ · {fmtSize(item.file_size_bytes)}+ </div>+ <div class="card-path mono" title={item.file_path}>{item.file_path}</div>+ {#if item.progress_pct > 0}+ <div class="progress" aria-label="Progress">+ <div class="progress-fill" style="width: {(item.progress_pct * 100).toFixed(0)}%"></div>+ </div>+ {/if}+ <div class="card-foot">+ <span class="when">{fmtRel(item.added_at)}</span>+ <div class="actions">+ {#if canTranscribe(item.kind)}+ <button+ type="button"+ class="btn-secondary"+ onclick={() => transcribeItem(item)}+ disabled={transcribeStates[item.id] === "running"}+ >+ {#if transcribeStates[item.id] === "running"}+ Transcribing…+ {:else if transcribeStates[item.id] === "done"}+ ✓ Transcribed+ {:else}+ Transcribe+ {/if}+ </button>+ {/if}+ <button type="button" class="btn-secondary" onclick={() => revealFile(item.file_path)}>+ Open+ </button>+ <button type="button" class="btn-danger" onclick={() => removeItem(item.id)}>+ Remove+ </button>+ </div>+ </div>+ {#if transcribeMessages[item.id]}+ <div class="transcribe-msg" class:error={transcribeStates[item.id] === "error"}>+ {#if transcribeStates[item.id] === "running"}+ <div class="progress-line">+ <div class="progress-bar-mini">+ <div+ class="progress-fill-mini"+ style="width: {transcribeProgress[item.id] ?? 0}%"+ ></div>+ </div>+ <span class="progress-pct">{transcribeProgress[item.id] ?? 0}%</span>+ </div>+ {/if}+ {transcribeMessages[item.id]}+ </div>+ {/if}+ </article>+ {/each}+ </div>+ {/if}+</section>++<style>+ .library-page {+ display: flex;+ flex-direction: column;+ gap: calc(var(--padding) * 2);+ width: 100%;+ max-width: 1100px;+ margin-inline: auto;+ padding: 16px 20px 80px;+ }+ .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);+ }+ .controls {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }+ .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;+ text-transform: capitalize;+ 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, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ font-size: 13px;+ }++ .empty {+ color: var(--tertiary);+ font-size: 13px;+ margin: 0;+ padding: 20px 0;+ }++ .section-title {+ margin: 0 0 8px;+ font-size: 13px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--tertiary);+ }++ .hit-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .hit-row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 14px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }+ .hit-kind {+ font-size: 16px;+ flex-shrink: 0;+ }+ .hit-meta {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .hit-title {+ font-size: 13px;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .hit-path {+ font-size: 11px;+ color: var(--tertiary);+ opacity: 0.7;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .hit-score {+ font-size: 11px;+ color: var(--tertiary);+ flex-shrink: 0;+ }++ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));+ gap: 12px;+ }+ .card {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 14px 16px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }+ .card-head {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .card-kind {+ font-size: 16px;+ flex-shrink: 0;+ }+ .card-title {+ font-size: 14px;+ font-weight: 500;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex: 1;+ min-width: 0;+ }+ .card-meta {+ font-size: 11px;+ color: var(--tertiary);+ }+ .card-path {+ font-size: 10px;+ color: var(--tertiary);+ opacity: 0.65;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .progress {+ height: 3px;+ border-radius: 2px;+ background: color-mix(in oklab, var(--input-border) 60%, transparent);+ overflow: hidden;+ }+ .progress-fill {+ height: 100%;+ background: var(--accent);+ }+ .card-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ margin-top: 4px;+ }+ .when {+ font-size: 10px;+ color: var(--tertiary);+ }+ .actions {+ display: flex;+ gap: 6px;+ }+ .btn-secondary,+ .btn-danger {+ padding: 5px 10px;+ border-radius: var(--border-radius);+ background: transparent;+ font-size: 11px;+ font-family: inherit;+ cursor: pointer;+ }+ .btn-secondary {+ border: 1px solid var(--input-border);+ color: var(--secondary);+ }+ .btn-secondary:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .btn-danger {+ border: 1px solid color-mix(in oklab, oklch(60% 0.22 25) 40%, var(--input-border));+ color: oklch(70% 0.22 25);+ }+ .btn-danger:hover {+ border-color: oklch(60% 0.22 25);+ background: color-mix(in oklab, oklch(60% 0.22 25) 10%, transparent);+ }+ .btn-secondary:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .transcribe-msg {+ margin-top: 8px;+ padding: 6px 10px;+ border-radius: var(--border-radius);+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--secondary);+ font-size: 11px;+ line-height: 1.4;+ }+ .transcribe-msg.error {+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ }+ .progress-line {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 4px;+ }+ .progress-bar-mini {+ flex: 1;+ height: 4px;+ background: color-mix(in oklab, var(--input-border) 50%, transparent);+ border-radius: 2px;+ overflow: hidden;+ }+ .progress-fill-mini {+ height: 100%;+ background: var(--accent);+ transition: width 200ms ease;+ }+ .progress-pct {+ font-size: 10px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ min-width: 32px;+ text-align: right;+ }++ .mono {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-variant-numeric: tabular-nums;+ }+</style>diff --git a/src/routes/misc/models/+page.svelte b/src/routes/misc/models/+page.sveltenew file mode 100644index 00000000..cc801a48--- /dev/null+++ b/src/routes/misc/models/+page.svelte@@ -0,0 +1,439 @@+<script lang="ts">+ import { onDestroy, onMount } from "svelte";+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";+ import { pluginInvoke } from "$lib/plugin-invoke";++ type ModelKind = "whisper" | "translation" | "llm";++ type ModelSpec = {+ id: string;+ kind: ModelKind;+ display_name: string;+ description: string;+ repo: string;+ filename: string;+ revision: string | null;+ size_bytes_estimate: number;+ license: string;+ };++ type InstalledModel = {+ id: string;+ kind: ModelKind;+ display_name: string;+ local_path: string;+ size_bytes: number;+ };++ type ProgressPayload = {+ id: string;+ bytes_completed: number;+ total_bytes: number;+ percent: number;+ stage: "started" | "progress" | "complete";+ };++ let registry = $state<ModelSpec[]>([]);+ let installed = $state<Record<string, InstalledModel>>({});+ let progress = $state<Record<string, ProgressPayload>>({});+ let busy = $state<Record<string, boolean>>({});+ let lastError = $state<string | null>(null);++ let unlistenProgress: UnlistenFn | null = null;+ let unlistenInstalled: UnlistenFn | null = null;++ onMount(() => {+ void initListeners();+ void refresh();+ });++ onDestroy(() => {+ unlistenProgress?.();+ unlistenInstalled?.();+ });++ async function initListeners() {+ unlistenProgress = await listen("misc:models:progress", (e) => {+ const p = e.payload as ProgressPayload;+ progress = { ...progress, [p.id]: p };+ });+ unlistenInstalled = await listen("misc:models:installed", () => {+ void refreshInstalled();+ });+ }++ async function refresh() {+ try {+ registry = await pluginInvoke<ModelSpec[]>("misc", "misc:models:registry", {});+ await refreshInstalled();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ }+ }++ async function refreshInstalled() {+ try {+ const list = await pluginInvoke<InstalledModel[]>("misc", "misc:models:list", {});+ const next: Record<string, InstalledModel> = {};+ for (const m of list) next[m.id] = m;+ installed = next;+ } catch (e) {+ console.warn("[models] list failed:", e);+ }+ }++ async function install(spec: ModelSpec) {+ if (busy[spec.id]) return;+ busy = { ...busy, [spec.id]: true };+ lastError = null;+ progress = {+ ...progress,+ [spec.id]: {+ id: spec.id,+ bytes_completed: 0,+ total_bytes: spec.size_bytes_estimate,+ percent: 0,+ stage: "started",+ },+ };+ try {+ await pluginInvoke("misc", "misc:models:install", { id: spec.id });+ await refreshInstalled();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ busy = { ...busy, [spec.id]: false };+ const next = { ...progress };+ delete next[spec.id];+ progress = next;+ }+ }++ async function remove(spec: ModelSpec) {+ if (busy[spec.id]) return;+ busy = { ...busy, [spec.id]: true };+ lastError = null;+ try {+ await pluginInvoke("misc", "misc:models:remove", { id: spec.id });+ await refreshInstalled();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ busy = { ...busy, [spec.id]: false };+ }+ }++ function fmtSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(0)} MB`;+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;+ }++ function kindLabel(kind: ModelKind): string {+ switch (kind) {+ case "whisper":+ return "Transcription";+ case "translation":+ return "Translation";+ case "llm":+ return "Chat / Q&A";+ }+ }++ const grouped = $derived.by(() => {+ const out: Record<ModelKind, ModelSpec[]> = {+ whisper: [],+ translation: [],+ llm: [],+ };+ for (const s of registry) out[s.kind].push(s);+ return out;+ });+</script>++<section class="models-page">+ <header class="head">+ <h1>Models</h1>+ <p class="subtitle">+ Download AI models locally. Used for transcription, translation, and chat. All run+ on your machine — nothing is uploaded.+ </p>+ </header>++ {#if lastError}+ <div class="error" role="alert"><strong>Error:</strong> {lastError}</div>+ {/if}++ {#if registry.length === 0}+ <p class="empty">Loading registry…</p>+ {:else}+ {#each Object.keys(grouped) as kind (kind)}+ {#if grouped[kind as ModelKind].length > 0}+ <section class="kind-section">+ <h2>{kindLabel(kind as ModelKind)}</h2>+ <div class="cards">+ {#each grouped[kind as ModelKind] as spec (spec.id)}+ {@const isInstalled = !!installed[spec.id]}+ {@const isBusy = !!busy[spec.id]}+ {@const prog = progress[spec.id]}+ <div class="card" class:installed={isInstalled}>+ <div class="card-head">+ <div class="card-title">{spec.display_name}</div>+ <div class="card-tags">+ <span class="tag">{spec.license}</span>+ <span class="tag size">{fmtSize(spec.size_bytes_estimate)}</span>+ {#if isInstalled}+ <span class="tag tag-ok">Installed</span>+ {/if}+ </div>+ </div>+ <p class="card-desc">{spec.description}</p>+ <div class="repo-row mono">+ {spec.repo} · {spec.filename}+ </div>++ {#if prog && isBusy}+ <div class="progress-row">+ <div class="progress-bar">+ <div+ class="progress-fill"+ style="width: {Math.min(100, prog.percent).toFixed(1)}%"+ ></div>+ </div>+ <div class="progress-label mono">+ {fmtSize(prog.bytes_completed)} / {fmtSize(prog.total_bytes)}+ ({prog.percent.toFixed(1)}%)+ </div>+ </div>+ {/if}++ <div class="card-actions">+ {#if isInstalled}+ <button+ type="button"+ class="btn-secondary"+ onclick={() => remove(spec)}+ disabled={isBusy}+ >+ {isBusy ? "Removing…" : "Remove"}+ </button>+ {:else}+ <button+ type="button"+ class="btn-primary"+ onclick={() => install(spec)}+ disabled={isBusy}+ >+ {isBusy ? "Downloading…" : "Install"}+ </button>+ {/if}+ </div>+ </div>+ {/each}+ </div>+ </section>+ {/if}+ {/each}+ {/if}+</section>++<style>+ .models-page {+ display: flex;+ flex-direction: column;+ gap: calc(var(--padding) * 2);+ width: 100%;+ max-width: 980px;+ margin-inline: auto;+ padding: 16px 20px 80px;+ }+ .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);+ max-width: 640px;+ line-height: 1.5;+ }++ .empty {+ color: var(--tertiary);+ font-size: 13px;+ margin: 0;+ }++ .error {+ padding: 10px 14px;+ border-radius: var(--border-radius);+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ font-size: 13px;+ }++ .kind-section h2 {+ margin: 0 0 12px;+ font-size: 13px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--tertiary);+ }++ .cards {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));+ gap: 12px;+ }++ .card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 16px 18px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }++ .card.installed {+ border-color: color-mix(in oklab, var(--accent) 50%, var(--input-border));+ background: color-mix(in oklab, var(--accent) 4%, var(--surface));+ }++ .card-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 10px;+ }++ .card-title {+ font-size: 14px;+ font-weight: 500;+ color: var(--secondary);+ }++ .card-tags {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ flex-shrink: 0;+ }++ .tag {+ font-size: 10px;+ font-weight: 500;+ padding: 2px 7px;+ border-radius: 4px;+ background: color-mix(in oklab, var(--input-border) 30%, transparent);+ color: var(--tertiary);+ }++ .tag.size {+ background: color-mix(in oklab, var(--input-border) 60%, transparent);+ color: var(--secondary);+ }++ .tag-ok {+ background: color-mix(in oklab, var(--accent) 18%, transparent);+ color: var(--accent);+ }++ .card-desc {+ margin: 0;+ font-size: 12px;+ color: var(--tertiary);+ line-height: 1.5;+ }++ .repo-row {+ font-size: 11px;+ color: var(--tertiary);+ opacity: 0.75;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .mono {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-variant-numeric: tabular-nums;+ }++ .progress-row {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }++ .progress-bar {+ height: 6px;+ border-radius: 3px;+ background: color-mix(in oklab, var(--input-border) 60%, transparent);+ overflow: hidden;+ }++ .progress-fill {+ height: 100%;+ background: var(--accent);+ transition: width 200ms ease;+ }++ .progress-label {+ font-size: 11px;+ color: var(--tertiary);+ }++ .card-actions {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 4px;+ }++ .btn-primary {+ padding: 7px 16px;+ border: 1px solid var(--accent);+ border-radius: var(--border-radius);+ background: color-mix(in oklab, var(--accent) 14%, var(--bg));+ color: var(--accent);+ font-size: 12px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ transition: background 120ms ease;+ }++ .btn-primary:hover:not(:disabled) {+ background: color-mix(in oklab, var(--accent) 22%, var(--bg));+ }++ .btn-secondary {+ padding: 7px 16px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: transparent;+ color: var(--secondary);+ font-size: 12px;+ font-family: inherit;+ cursor: pointer;+ }++ .btn-secondary:hover:not(:disabled) {+ border-color: oklch(60% 0.22 25);+ color: oklch(70% 0.22 25);+ }++ .btn-primary:disabled,+ .btn-secondary:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+</style>diff --git a/src/routes/misc/studio/+page.svelte b/src/routes/misc/studio/+page.sveltenew file mode 100644index 00000000..3b2f39ba--- /dev/null+++ b/src/routes/misc/studio/+page.svelte@@ -0,0 +1,936 @@+<script lang="ts">+ import { onDestroy, onMount } from "svelte";+ import { invoke } from "@tauri-apps/api/core";+ import { listen, type UnlistenFn } from "@tauri-apps/api/event";+ import { pluginInvoke } from "$lib/plugin-invoke";++ type RecordingState = "idle" | "recording" | "stopping";++ type SessionStats = {+ video_frames: number;+ video_packets: number;+ audio_chunks: number;+ audio_samples: number;+ audio_packets: number;+ duration_secs: number;+ file_size_bytes: number;+ output_path: string;+ };++ type ClipResult = {+ queue_id: number;+ title: string;+ output_path: string;+ stats: SessionStats;+ saved_at: number;+ };++ type ReplayStatus = {+ running: boolean;+ buffer_secs: number;+ packet_count: number;+ bytes_used: number;+ max_secs: number;+ };++ let recState = $state<RecordingState>("idle");+ let elapsedSecs = $state(0);+ let outputPath = $state<string | null>(null);+ let lastError = $state<string | null>(null);+ let recentClips = $state<ClipResult[]>([]);++ let replayStatus = $state<ReplayStatus>({+ running: false,+ buffer_secs: 0,+ packet_count: 0,+ bytes_used: 0,+ max_secs: 30,+ });+ let replayBusy = $state(false);++ let timer: number | null = null;+ let replayPoller: number | null = null;+ let unlistenSaved: UnlistenFn | null = null;+ let unlistenStarted: UnlistenFn | null = null;+ let unlistenTranscribe: UnlistenFn | null = null;+ let unlistenTranscribeProgress: UnlistenFn | null = null;+ let startedAt = 0;++ type TranscribeState = "idle" | "running" | "done" | "error";+ let transcribeStates = $state<Record<number, TranscribeState>>({});+ let transcribeMessages = $state<Record<number, string>>({});+ let transcribeSrtPaths = $state<Record<number, string>>({});+ let transcribeProgress = $state<Record<number, number>>({});++ type TranslateState = "idle" | "running" | "done" | "error";+ let translateStates = $state<Record<number, TranslateState>>({});+ let translateMessages = $state<Record<number, string>>({});+ let translateTarget = $state<Record<number, string>>({});+ let translateSource = $state<Record<number, string>>({});+ let detectedLanguage = $state<Record<number, string>>({});++ onMount(() => {+ void initListeners();+ void refreshStatus();+ void refreshReplayStatus();+ replayPoller = window.setInterval(() => void refreshReplayStatus(), 1000);+ });++ onDestroy(() => {+ stopTimer();+ if (replayPoller != null) clearInterval(replayPoller);+ unlistenSaved?.();+ unlistenStarted?.();+ unlistenTranscribe?.();+ unlistenTranscribeProgress?.();+ });++ async function initListeners() {+ unlistenStarted = await listen("misc:studio:recording-started", (e) => {+ const payload = e.payload as { output_path: string };+ outputPath = payload.output_path;+ });+ unlistenSaved = await listen("misc:studio:clip-saved", (e) => {+ const payload = e.payload as Omit<ClipResult, "saved_at">;+ const clip: ClipResult = { ...payload, saved_at: Date.now() };+ recentClips = [clip, ...recentClips].slice(0, 8);+ });+ unlistenTranscribeProgress = await listen("misc:transcribe:progress", (e) => {+ const p = e.payload as { queue_id: number; percent: number };+ transcribeProgress = { ...transcribeProgress, [p.queue_id]: p.percent };+ });+ unlistenTranscribe = await listen("misc:transcribe:done", (e) => {+ const p = e.payload as {+ queue_id: number;+ srt_path: string;+ elapsed_s: number;+ duration_s: number;+ segment_count: number;+ language: string;+ };+ transcribeStates = { ...transcribeStates, [p.queue_id]: "done" };+ transcribeSrtPaths = { ...transcribeSrtPaths, [p.queue_id]: p.srt_path };+ detectedLanguage = { ...detectedLanguage, [p.queue_id]: p.language };+ translateSource = { ...translateSource, [p.queue_id]: p.language };+ transcribeMessages = {+ ...transcribeMessages,+ [p.queue_id]: `${p.segment_count} segmentos · ${p.elapsed_s.toFixed(1)}s · idioma: ${p.language} → ${p.srt_path}`,+ };+ });+ }++ async function translateClip(clip: ClipResult, target: string, source: string) {+ const srtPath = transcribeSrtPaths[clip.queue_id];+ if (!srtPath) {+ lastError = "Transcribe first to generate the SRT file.";+ return;+ }+ if (translateStates[clip.queue_id] === "running") return;+ if (source === target) {+ lastError = `Source and target are both '${source}'. Pick a different target.`;+ return;+ }+ translateStates = { ...translateStates, [clip.queue_id]: "running" };+ translateMessages = {+ ...translateMessages,+ [clip.queue_id]: `Translating ${source} → ${target}…`,+ };+ try {+ const res = await pluginInvoke<{ output_path: string; elapsed_s: number; block_count: number }>(+ "misc",+ "misc:translate:srt",+ {+ srtPath,+ targetLanguage: target,+ sourceLanguage: source,+ },+ );+ translateStates = { ...translateStates, [clip.queue_id]: "done" };+ translateMessages = {+ ...translateMessages,+ [clip.queue_id]: `${res.block_count} blocos em ${res.elapsed_s.toFixed(1)}s → ${res.output_path}`,+ };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ translateStates = { ...translateStates, [clip.queue_id]: "error" };+ translateMessages = { ...translateMessages, [clip.queue_id]: msg };+ if (msg.includes("model not installed")) {+ lastError = "Translation model not installed. Go to /misc/models and install 'M2M-100 418M (ONNX)' (~870 MB).";+ } else if (msg.includes("not found as token")) {+ lastError = `Language code '${source}' not supported by M2M-100. Use ISO codes like en, pt, es, fr, de, it, ja, zh, ko, ru, ar, hi.`;+ } else {+ lastError = msg;+ }+ }+ }++ const languageOptions = [+ { value: "en", label: "English (en)" },+ { value: "pt", label: "Portuguese (pt)" },+ { value: "es", label: "Spanish (es)" },+ { value: "fr", label: "French (fr)" },+ { value: "de", label: "German (de)" },+ { value: "it", label: "Italian (it)" },+ { value: "ja", label: "Japanese (ja)" },+ { value: "zh", label: "Chinese (zh)" },+ { value: "ko", label: "Korean (ko)" },+ { value: "ru", label: "Russian (ru)" },+ { value: "ar", label: "Arabic (ar)" },+ { value: "hi", label: "Hindi (hi)" },+ ];++ async function transcribeClip(clip: ClipResult) {+ if (transcribeStates[clip.queue_id] === "running") return;+ transcribeStates = { ...transcribeStates, [clip.queue_id]: "running" };+ transcribeMessages = {+ ...transcribeMessages,+ [clip.queue_id]: "Extracting audio…",+ };+ transcribeProgress = { ...transcribeProgress, [clip.queue_id]: 0 };+ try {+ await pluginInvoke("misc", "misc:transcribe:run", {+ path: clip.output_path,+ wordTimestamps: true,+ });+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ transcribeStates = { ...transcribeStates, [clip.queue_id]: "error" };+ transcribeMessages = { ...transcribeMessages, [clip.queue_id]: msg };+ if (msg.includes("model not installed")) {+ lastError = `Whisper model not installed. Go to /misc/models and install 'Whisper Tiny' (~75 MB) or 'Large v3 Turbo' (~800 MB).`;+ } else if (msg.includes("aborted")) {+ transcribeMessages = { ...transcribeMessages, [clip.queue_id]: "Cancelled" };+ } else {+ lastError = msg;+ }+ }+ }++ async function cancelTranscribe(clip: ClipResult) {+ try {+ await pluginInvoke("misc", "misc:transcribe:cancel", {});+ } catch (e) {+ console.warn("[studio] cancel failed:", e);+ }+ }++ async function refreshStatus() {+ try {+ const res = await pluginInvoke<{+ recording: boolean;+ elapsed_secs: number;+ output_path: string | null;+ }>("misc", "misc:studio:status", {});+ if (res.recording) {+ recState = "recording";+ elapsedSecs = res.elapsed_secs;+ outputPath = res.output_path;+ startedAt = Date.now() - res.elapsed_secs * 1000;+ startTimer();+ }+ } catch (e) {+ console.warn("[studio] status refresh failed:", e);+ }+ }++ async function refreshReplayStatus() {+ try {+ replayStatus = await pluginInvoke<ReplayStatus>(+ "misc",+ "misc:studio:replay_buffer:status",+ {},+ );+ } catch (e) {+ console.warn("[studio] replay status failed:", e);+ }+ }++ function startTimer() {+ stopTimer();+ timer = window.setInterval(() => {+ elapsedSecs = (Date.now() - startedAt) / 1000;+ }, 200);+ }++ function stopTimer() {+ if (timer != null) {+ clearInterval(timer);+ timer = null;+ }+ }++ async function startRecording() {+ if (recState !== "idle") return;+ lastError = null;+ recState = "recording";+ elapsedSecs = 0;+ startedAt = Date.now();+ try {+ const res = await pluginInvoke<{ ok: boolean; output_path: string }>(+ "misc",+ "misc:studio:start_recording",+ {},+ );+ outputPath = res.output_path;+ startTimer();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ recState = "idle";+ stopTimer();+ }+ }++ async function stopRecording() {+ if (recState !== "recording") return;+ recState = "stopping";+ stopTimer();+ try {+ await pluginInvoke("misc", "misc:studio:stop_recording", {});+ recState = "idle";+ elapsedSecs = 0;+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ recState = "idle";+ }+ }++ async function toggleReplayBuffer() {+ if (replayBusy) return;+ replayBusy = true;+ lastError = null;+ try {+ if (replayStatus.running) {+ await pluginInvoke("misc", "misc:studio:replay_buffer:stop", {});+ } else {+ await pluginInvoke("misc", "misc:studio:replay_buffer:start", {+ maxSecs: 35,+ maxMb: 120,+ });+ }+ await refreshReplayStatus();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ replayBusy = false;+ }+ }++ async function saveReplay() {+ if (replayBusy || !replayStatus.running) return;+ replayBusy = true;+ lastError = null;+ try {+ await pluginInvoke("misc", "misc:studio:replay_buffer:save", {});+ await refreshReplayStatus();+ } catch (e) {+ lastError = e instanceof Error ? e.message : String(e);+ } finally {+ replayBusy = false;+ }+ }++ async function revealFile(path: string) {+ try {+ await invoke("reveal_file", { path });+ } catch (e) {+ console.warn("[studio] reveal_file failed:", e);+ }+ }++ function fmtTime(secs: number): string {+ const total = Math.floor(secs);+ const m = Math.floor(total / 60);+ const s = total % 60;+ return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;+ }++ function fmtSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+ }++ function fmtRel(ts: number): string {+ const diff = Math.max(0, Date.now() - ts);+ if (diff < 60_000) return `${Math.floor(diff / 1000)}s ago`;+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;+ return new Date(ts).toLocaleTimeString();+ }+</script>++<section class="studio-page">+ <header class="head">+ <h1>Studio</h1>+ <p class="subtitle">+ Record screen + system audio (what you hear). Replay buffer keeps the last 30s in RAM.+ </p>+ </header>++ <section class="mode-card replay-card" class:armed={replayStatus.running}>+ <div class="mode-head">+ <div class="mode-title">+ <span class="dot" class:on={replayStatus.running}></span>+ Replay buffer+ </div>+ <button+ type="button"+ class="toggle-btn"+ class:active={replayStatus.running}+ onclick={toggleReplayBuffer}+ disabled={replayBusy}+ >+ {replayStatus.running ? "Turn off" : "Turn on"}+ </button>+ </div>+ <p class="mode-desc">+ Always recording in background. Press "Save last 30s" any time to clip what just happened — like ShadowPlay.+ </p>+ <div class="replay-stats">+ <div class="stat">+ <span class="stat-label">Buffered</span>+ <span class="stat-value mono">+ {fmtTime(replayStatus.buffer_secs)} / {fmtTime(replayStatus.max_secs)}+ </span>+ </div>+ <div class="stat">+ <span class="stat-label">RAM</span>+ <span class="stat-value mono">{fmtSize(replayStatus.bytes_used)}</span>+ </div>+ <div class="stat">+ <span class="stat-label">Packets</span>+ <span class="stat-value mono">{replayStatus.packet_count}</span>+ </div>+ </div>+ <button+ type="button"+ class="save-btn"+ class:disabled={!replayStatus.running || replayBusy}+ onclick={saveReplay}+ disabled={!replayStatus.running || replayBusy}+ >+ ✂ Save last {Math.floor(replayStatus.buffer_secs)}s+ </button>+ </section>++ <section class="mode-card">+ <div class="mode-head">+ <div class="mode-title">Manual recording</div>+ </div>+ <p class="mode-desc">+ Start/stop recording. Use this when you know in advance what you want to capture.+ </p>+ <div class="rec-stage">+ <button+ type="button"+ class="rec-btn"+ class:active={recState === "recording"}+ onclick={recState === "recording" ? stopRecording : startRecording}+ disabled={recState === "stopping"}+ >+ <span class="rec-dot"></span>+ <span class="rec-label">+ {#if recState === "idle"}+ Start recording+ {:else if recState === "recording"}+ Stop recording+ {:else}+ Finalizing…+ {/if}+ </span>+ </button>+ <div class="elapsed">+ {#if recState === "recording" || recState === "stopping"}+ <span class="elapsed-time mono">{fmtTime(elapsedSecs)}</span>+ {:else}+ <span class="elapsed-idle">Ready</span>+ {/if}+ </div>+ </div>+ </section>++ {#if lastError}+ <div class="error" role="alert"><strong>Error:</strong> {lastError}</div>+ {/if}++ <section class="recent">+ <h2>Recent clips</h2>+ {#if recentClips.length === 0}+ <p class="empty">No clips yet. Turn on the replay buffer or start a manual recording.</p>+ {:else}+ <ul class="clip-list">+ {#each recentClips as clip (clip.queue_id)}+ <li class="clip-row">+ <div class="clip-meta">+ <span class="clip-title">{clip.title}</span>+ <span class="clip-stats">+ {fmtTime(clip.stats.duration_secs)} · {fmtSize(clip.stats.file_size_bytes)}+ {#if clip.stats.video_frames > 0}+ · {clip.stats.video_frames} frames+ {/if}+ </span>+ <span class="clip-path mono" title={clip.output_path}>{clip.output_path}</span>+ </div>+ <div class="clip-actions">+ <span class="clip-when">{fmtRel(clip.saved_at)}</span>+ {#if transcribeStates[clip.queue_id] === "running"}+ <button+ type="button"+ class="btn-reveal"+ onclick={() => cancelTranscribe(clip)}+ title="Cancel running transcription"+ >+ Cancel+ </button>+ {:else}+ <button+ type="button"+ class="btn-reveal"+ onclick={() => transcribeClip(clip)}+ title="Generate SRT + VTT next to the clip"+ >+ {#if transcribeStates[clip.queue_id] === "done"}+ ✓ Transcribed+ {:else}+ Transcribe+ {/if}+ </button>+ {/if}+ <button type="button" class="btn-reveal" onclick={() => revealFile(clip.output_path)}>+ Open folder+ </button>+ </div>+ {#if transcribeMessages[clip.queue_id]}+ <div class="transcribe-msg" class:error={transcribeStates[clip.queue_id] === "error"}>+ {#if transcribeStates[clip.queue_id] === "running"}+ <div class="progress-line">+ <div class="progress-bar-mini">+ <div+ class="progress-fill-mini"+ style="width: {transcribeProgress[clip.queue_id] ?? 0}%"+ ></div>+ </div>+ <span class="progress-pct">{transcribeProgress[clip.queue_id] ?? 0}%</span>+ </div>+ {/if}+ {transcribeMessages[clip.queue_id]}+ </div>+ {/if}+ {#if transcribeStates[clip.queue_id] === "done"}+ <div class="translate-row">+ {#if detectedLanguage[clip.queue_id]}+ <span class="detected-lang">+ Detected: <strong>{detectedLanguage[clip.queue_id]}</strong>+ </span>+ {/if}+ <select+ class="translate-select"+ bind:value={translateSource[clip.queue_id]}+ title="Source language (override detected)"+ >+ {#each languageOptions as opt (opt.value)}+ <option value={opt.value}>{opt.label}</option>+ {/each}+ </select>+ <span class="arrow">→</span>+ <select+ class="translate-select"+ bind:value={translateTarget[clip.queue_id]}+ title="Target language"+ >+ {#each languageOptions as opt (opt.value)}+ <option value={opt.value}>{opt.label}</option>+ {/each}+ </select>+ <button+ type="button"+ class="btn-reveal"+ onclick={() =>+ translateClip(+ clip,+ translateTarget[clip.queue_id] || "pt",+ translateSource[clip.queue_id] || detectedLanguage[clip.queue_id] || "en",+ )}+ disabled={translateStates[clip.queue_id] === "running"}+ >+ {#if translateStates[clip.queue_id] === "running"}+ Translating…+ {:else if translateStates[clip.queue_id] === "done"}+ ✓ Translated+ {:else}+ Translate+ {/if}+ </button>+ </div>+ {/if}+ {#if translateMessages[clip.queue_id]}+ <div class="transcribe-msg" class:error={translateStates[clip.queue_id] === "error"}>+ {translateMessages[clip.queue_id]}+ </div>+ {/if}+ </li>+ {/each}+ </ul>+ {/if}+ </section>+</section>++<style>+ .studio-page {+ display: flex;+ flex-direction: column;+ gap: calc(var(--padding) * 2);+ width: 100%;+ max-width: 880px;+ margin-inline: auto;+ padding: 16px 20px 80px;+ }+ .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);+ }+ .mode-card {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 18px 20px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }+ .replay-card.armed {+ border-color: oklch(60% 0.22 25);+ background: color-mix(in oklab, oklch(60% 0.22 25) 5%, var(--surface));+ }+ .mode-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ }+ .mode-title {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ font-size: 15px;+ font-weight: 500;+ color: var(--secondary);+ }+ .dot {+ display: inline-block;+ width: 10px;+ height: 10px;+ border-radius: 50%;+ background: color-mix(in oklab, var(--input-border) 60%, transparent);+ }+ .dot.on {+ background: oklch(60% 0.22 25);+ animation: pulse 1.4s ease-in-out infinite;+ box-shadow: 0 0 6px oklch(60% 0.22 25 / 0.6);+ }+ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }+ .mode-desc {+ margin: 0;+ font-size: 12px;+ color: var(--tertiary);+ line-height: 1.4;+ }+ .toggle-btn {+ padding: 6px 14px;+ border-radius: 999px;+ border: 1px solid var(--input-border);+ background: var(--bg);+ color: var(--secondary);+ font-size: 12px;+ font-family: inherit;+ cursor: pointer;+ transition: border-color 120ms ease, color 120ms ease;+ }+ .toggle-btn:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ }+ .toggle-btn.active {+ border-color: oklch(60% 0.22 25);+ color: oklch(70% 0.22 25);+ }+ .toggle-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .replay-stats {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 10px;+ padding: 10px 12px;+ border: 1px solid color-mix(in oklab, var(--input-border) 60%, transparent);+ border-radius: var(--border-radius);+ background: var(--bg);+ }+ .stat {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .stat-label {+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.4px;+ color: var(--tertiary);+ }+ .stat-value {+ font-size: 14px;+ font-weight: 500;+ color: var(--secondary);+ }+ .mono {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-variant-numeric: tabular-nums;+ }+ .save-btn {+ padding: 12px 18px;+ border: 1px solid oklch(60% 0.22 25);+ border-radius: var(--border-radius);+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, var(--bg));+ color: oklch(70% 0.22 25);+ font-size: 14px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ transition: background 150ms ease;+ }+ .save-btn:hover:not(.disabled) {+ background: color-mix(in oklab, oklch(60% 0.22 25) 22%, var(--bg));+ }+ .save-btn.disabled {+ opacity: 0.4;+ cursor: not-allowed;+ }+ .rec-stage {+ display: flex;+ align-items: center;+ gap: 16px;+ padding: 8px 0;+ }+ .rec-btn {+ display: inline-flex;+ align-items: center;+ gap: 12px;+ padding: 12px 24px;+ border: 1px solid var(--input-border);+ border-radius: 999px;+ background: var(--bg);+ color: var(--secondary);+ font-size: 14px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ }+ .rec-btn:hover:not(:disabled) {+ border-color: var(--accent);+ }+ .rec-btn.active {+ border-color: oklch(60% 0.22 25);+ color: oklch(70% 0.22 25);+ background: color-mix(in oklab, oklch(60% 0.22 25) 8%, var(--bg));+ }+ .rec-btn:disabled {+ opacity: 0.6;+ }+ .rec-dot {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ background: oklch(60% 0.22 25);+ }+ .elapsed-time {+ font-size: 18px;+ color: var(--secondary);+ }+ .elapsed-idle {+ font-size: 11px;+ text-transform: uppercase;+ color: var(--tertiary);+ letter-spacing: 0.5px;+ }+ .error {+ padding: 10px 14px;+ border-radius: var(--border-radius);+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ font-size: 13px;+ }+ .recent h2 {+ margin: 0 0 12px;+ font-size: 13px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--tertiary);+ }+ .empty {+ color: var(--tertiary);+ font-size: 13px;+ margin: 0;+ }+ .clip-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .clip-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 14px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--bg);+ }+ .clip-meta {+ display: flex;+ flex-direction: column;+ gap: 3px;+ flex: 1;+ min-width: 0;+ }+ .clip-title {+ font-size: 13px;+ color: var(--secondary);+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .clip-stats {+ font-size: 11px;+ color: var(--tertiary);+ }+ .clip-path {+ font-size: 10px;+ color: var(--tertiary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ opacity: 0.7;+ }+ .clip-actions {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-shrink: 0;+ }+ .clip-when {+ font-size: 11px;+ color: var(--tertiary);+ }+ .btn-reveal {+ padding: 6px 12px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: transparent;+ color: var(--secondary);+ font-size: 12px;+ font-family: inherit;+ cursor: pointer;+ }+ .btn-reveal:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ }+ .btn-reveal:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .transcribe-msg {+ flex-basis: 100%;+ margin-top: 6px;+ padding: 6px 10px;+ border-radius: var(--border-radius);+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ color: var(--secondary);+ font-size: 11px;+ line-height: 1.4;+ }+ .transcribe-msg.error {+ background: color-mix(in oklab, oklch(60% 0.22 25) 14%, transparent);+ color: oklch(70% 0.22 25);+ }+ .translate-row {+ flex-basis: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 6px;+ flex-wrap: wrap;+ }+ .translate-select {+ padding: 4px 10px;+ border: 1px solid var(--input-border);+ border-radius: var(--border-radius);+ background: var(--surface);+ color: var(--secondary);+ font-size: 11px;+ font-family: inherit;+ }+ .translate-select:focus {+ outline: none;+ border-color: var(--accent);+ }+ .detected-lang {+ font-size: 11px;+ color: var(--tertiary);+ }+ .detected-lang strong {+ color: var(--secondary);+ font-weight: 600;+ }+ .arrow {+ font-size: 12px;+ color: var(--tertiary);+ }+ .progress-line {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 4px;+ }+ .progress-bar-mini {+ flex: 1;+ height: 4px;+ background: color-mix(in oklab, var(--input-border) 50%, transparent);+ border-radius: 2px;+ overflow: hidden;+ }+ .progress-fill-mini {+ height: 100%;+ background: var(--accent);+ transition: width 200ms ease;+ }+ .progress-pct {+ font-size: 10px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ min-width: 32px;+ text-align: right;+ }+ @media (prefers-reduced-motion: reduce) {+ .dot.on {+ animation: none;+ }+ }+</style>diff --git a/src/routes/study/+layout.svelte b/src/routes/study/+layout.svelteindex 3fae6c0a..746c12b5 100644--- a/src/routes/study/+layout.svelte+++ b/src/routes/study/+layout.svelte@@ -4,6 +4,7 @@import { goto } from "$app/navigation";import { page } from "$app/stores";import { pluginInvoke } from "$lib/plugin-invoke";+ import { rpcSetSource, rpcClearSource } from "$lib/rpc";import { t } from "$lib/i18n";import {onGamificationToast,@@ -11,6 +12,25 @@} from "$lib/study-gamification";import { emitFocusBreakStart } from "$lib/study-focus-bridge";import { STUDY_NOTES_ENABLED, STUDY_ANKI_ENABLED } from "$lib/study-feature-flags";+ import { beforeNavigate } from "$app/navigation";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { musicUI } from "$lib/study-music/ui-store.svelte";+ import { musicTheme } from "$lib/study-music/theme-store.svelte";+ import { playlistsStore } from "$lib/study-music/playlists-store.svelte";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import PlayerBar from "$lib/study-music-components/PlayerBar.svelte";+ import RightBar from "$lib/study-music-components/RightBar.svelte";+ import AddToPlaylistDialog from "$lib/study-music-components/AddToPlaylistDialog.svelte";+ import RootsManager from "$lib/study-music-components/RootsManager.svelte";+ 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 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 SelectionBar from "$lib/study-music-components/SelectionBar.svelte";+ import ContextMenu, { type ContextMenuItem } from "$lib/study-music-components/ContextMenu.svelte";const SUBNAV_FULL: { href: string; labelKey: string; icon: string; match: string }[] = [{ href: "/study", labelKey: "study.hub.title", icon: "M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M9 22V12h6v10", match: "exact" },@@ -21,6 +41,7 @@{ href: "/study/achievements", labelKey: "study.hub.achievements", icon: "M8 21h8 M12 17v4 M7 4h10v6a5 5 0 0 1-10 0V4z M3 5v3a4 4 0 0 0 4 4 M21 5v3a4 4 0 0 1-4 4", match: "prefix" },{ href: "/study/notes", labelKey: "study.hub.notes", icon: "M4 4h12l4 4v12H4z M14 4v5h5", match: "prefix" },{ href: "/study/read", labelKey: "study.hub.read", icon: "M4 4h6a3 3 0 0 1 3 3v13a2 2 0 0 0-2-2H4z M20 4h-6a3 3 0 0 0-3 3v13a2 2 0 0 1 2-2h7z", match: "prefix" },+ { href: "/study/music", labelKey: "study.hub.music", icon: "M9 18V5l12-2v13 M6 18 a3 3 0 1 0 0 0.01z M18 16 a3 3 0 1 0 0 0.01z", match: "prefix" },{ href: "/study/settings", labelKey: "study.hub.settings", icon: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M19 12a7 7 0 1 1-14 0 7 7 0 0 1 14 0z", match: "prefix" },];@@ -108,9 +129,56 @@} catch {}}+ function presetLabelStudy(presetId: string): string {+ const labels: Record<string, string> = {+ "pomodoro-25": "Pomodoro 25",+ "deep-50": "Deep Work 50",+ "stopwatch": "Cronômetro",+ };+ return labels[presetId] ?? presetId;+ }++ function loadFocusCustomText(): string {+ if (typeof localStorage === "undefined") return "";+ try {+ return localStorage.getItem("study.focus.rpc_text.v1") ?? "";+ } catch {+ return "";+ }+ }++ function pushFocusRpc(cur: FocusCurrent | null) {+ if (!cur) {+ void rpcClearSource("focus");+ return;+ }+ const customText = loadFocusCustomText().trim();+ const target = PRESET_MINUTES[cur.preset] ?? 0;+ 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 details = customText || $t("study.focus.rpc_default") as string;+ const stateText = customText+ ? (target > 0+ ? `${presetText} · ${Math.floor(elapsedSec / 60)}/${target} min`+ : `${presetText} · ${Math.floor(elapsedSec / 60)} min`)+ : (target > 0+ ? `${presetText} · ${Math.floor(elapsedSec / 60)}/${target} min`+ : `${presetText}`);+ void rpcSetSource({+ source: "focus",+ details,+ state: stateText,+ duration: target > 0 ? target * 60 : 0,+ position: elapsedSec,+ paused: false,+ });+ }+async function pollFocusForBreak() {try {const cur = await pluginInvoke<FocusCurrent>("study", "study:focus:current");+ pushFocusRpc(cur);if (!cur) return;const target = PRESET_MINUTES[cur.preset] ?? 0;if (target <= 0) return;@@ -465,6 +533,122 @@}}+ const ctxItems: ContextMenuItem[] = [+ { id: "play", label: $t("study.music.play") as string, icon: "M8 5v14l11-7z" },+ { id: "queue", label: $t("study.music.add_to_queue") as string, icon: "M3 6h13 M3 12h13 M3 18h9 M17 14v6 M14 17h6" },+ { id: "playlist", label: $t("study.music.add_to_playlist") as string, icon: "M12 5v14 M5 12h14" },+ { id: "favorite", label: $t("study.music.favorite") as string, icon: "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" },+ { id: "sep1", label: "", separator: true },+ { id: "show", label: $t("study.music.ctx_show_in_folder") as string, icon: "M3 7v13h18V9h-9l-2-2H3z" },+ { id: "lyrics", label: $t("study.music.lyrics_title") as string, icon: "M9 18V5l12-2v13" },+ ];++ function handleCtxAction(id: string) {+ const tr = musicUI.contextMenu.track;+ if (!tr) return;+ if (id === "play") {+ void musicPlayer.play(tr, [tr]);+ } else if (id === "queue") {+ const sel = musicUI.selectedIds.has(tr.id) && musicUI.selectionAnchor+ ? musicUI.selectionAnchor.queue.filter((t) => musicUI.selectedIds.has(t.id))+ : [tr];+ musicPlayer.queue = [...musicPlayer.queue, ...sel];+ showToast("success", $t("study.music.queued_count", { count: sel.length }) as string);+ } else if (id === "playlist") {+ musicUI.openAddToPlaylist(tr);+ } else if (id === "favorite") {+ void musicPlayer.toggleFavorite(tr.id);+ } else if (id === "show") {+ void (async () => {+ try {+ const { revealItemInDir } = await import("@tauri-apps/plugin-opener");+ await revealItemInDir(tr.path);+ } catch {+ showToast("error", $t("study.music.ctx_show_failed") as string);+ }+ })();+ } else if (id === "lyrics") {+ if (musicPlayer.currentTrack?.id !== tr.id) {+ void musicPlayer.play(tr, [tr]);+ }+ musicUI.rightbarTab = "lyrics";+ }+ }++ let lastRpcKey = "";+ let rpcInterval: ReturnType<typeof setInterval> | null = null;+ let lastScrobbleTrackId: number | null = null;+ let lastNowPlayingKey = "";+ let scrobbleTimer: ReturnType<typeof setTimeout> | null = null;++ function pushPresence(track: MusicTrack | null, paused: boolean) {+ if (!track) {+ void rpcClearSource("music");+ lastRpcKey = "";+ return;+ }+ const position = Math.floor(musicPlayer.currentTime);+ const duration = Math.floor((track.duration_ms ?? 0) / 1000);+ const details = track.title ?? track.path;+ const stateParts: string[] = [];+ if (track.artist) stateParts.push(track.artist);+ if (track.album) stateParts.push(track.album);+ const stateStr = stateParts.length > 0 ? stateParts.join(" · ") : "—";+ const sourceTag = track.source === "spotify" ? "Spotify" : "omniget";+ void rpcSetSource({+ source: "music",+ details,+ state: `${stateStr} · ${sourceTag}`,+ duration,+ position,+ paused,+ });+ }++ $effect(() => {+ const tr = musicPlayer.currentTrack;+ const paused = musicPlayer.paused;+ const key = `${tr?.id ?? "none"}:${paused ? "p" : "play"}`;+ if (key !== lastRpcKey) {+ lastRpcKey = key;+ pushPresence(tr, paused);+ }+ });++ $effect(() => {+ const tr = musicPlayer.currentTrack;+ if (!tr || musicPlayer.paused) return;+ if (tr.source === "spotify") return;+ const key = `${tr.id}:np`;+ if (key === lastNowPlayingKey) return;+ lastNowPlayingKey = key;+ void pluginInvoke("study", "study:music:lastfm:now_playing", {+ title: tr.title ?? "",+ artist: tr.artist ?? "",+ album: tr.album ?? "",+ duration: Math.floor((tr.duration_ms ?? 0) / 1000),+ }).catch(() => {});++ if (scrobbleTimer) {+ clearTimeout(scrobbleTimer);+ scrobbleTimer = null;+ }+ if (lastScrobbleTrackId === tr.id) return;+ const minPlay = Math.max(30, Math.min(240, Math.floor((tr.duration_ms ?? 0) / 1000 / 2)));+ scrobbleTimer = setTimeout(() => {+ const cur = musicPlayer.currentTrack;+ if (cur && cur.id === tr.id && !musicPlayer.paused) {+ lastScrobbleTrackId = cur.id;+ void pluginInvoke("study", "study:music:lastfm:scrobble", {+ title: cur.title ?? "",+ artist: cur.artist ?? "",+ album: cur.album ?? "",+ duration: Math.floor((cur.duration_ms ?? 0) / 1000),+ }).catch(() => {});+ }+ }, minPlay * 1000);+ });+onMount(() => {const events = ["download-complete",@@ -485,6 +669,14 @@focusPoll = window.setInterval(() => {void pollFocusForBreak();}, 10_000);+ void playlistsStore.load();+ musicTheme.load();+ rpcInterval = setInterval(() => {+ const tr = musicPlayer.currentTrack;+ if (tr && !musicPlayer.paused) {+ pushPresence(tr, false);+ }+ }, 30_000);return () => {for (const fn of unlisteners) fn();unlisteners = [];@@ -494,12 +686,38 @@clearInterval(focusPoll);focusPoll = null;}+ if (rpcInterval) clearInterval(rpcInterval);+ if (scrobbleTimer) clearTimeout(scrobbleTimer);+ void rpcClearSource("music");+ void rpcClearSource("focus");};});onDestroy(() => {if (searchTimer != null) clearTimeout(searchTimer);});++ beforeNavigate(({ to, from }) => {+ if (!to) return;+ const path = to.url.pathname;+ if (+ path.startsWith("/study/watch") ||+ path.startsWith("/study/course/") ||+ path.startsWith("/study/anki/study")+ ) {+ musicPlayer.pause();+ }+ if (path.startsWith("/study/music") && from && !from.url.pathname.startsWith("/study/music")) {+ try {+ sessionStorage.setItem(+ "study.music.return_url",+ `${from.url.pathname}${from.url.search}`,+ );+ } catch {+ /* ignore */+ }+ }+ });</script><nav class="subnav" aria-label="study sections">@@ -521,6 +739,72 @@{@render children()}+{#if musicPlayer.currentTrack && !$page.url.pathname.startsWith("/study/watch") && !$page.url.pathname.startsWith("/study/course/") && !$page.url.pathname.startsWith("/study/anki/study") && !$page.url.pathname.startsWith("/study/music")}+ <div class="global-player-bar">+ <PlayerBar />+ </div>+{/if}++<AddToPlaylistDialog+ open={musicUI.addToPlaylistTrack !== null}+ trackId={musicUI.addToPlaylistTrack?.id ?? null}+ trackName={musicUI.addToPlaylistTrack?.title ?? musicUI.addToPlaylistTrack?.path ?? null}+ onClose={() => musicUI.closeAddToPlaylist()}+/>++<RootsManager+ open={musicUI.rootsOpen}+ onClose={() => musicUI.closeRoots()}+/>++<EqualizerPanel+ open={musicUI.equalizerOpen}+ onClose={() => musicUI.closeEqualizer()}+/>++<LastFmPanel+ open={musicUI.lastfmOpen}+ onClose={() => musicUI.closeLastFm()}+/>++<MusicThemePanel+ open={musicUI.themeOpen}+ onClose={() => musicUI.closeTheme()}+/>++<YoutubePanel+ open={musicUI.youtubeOpen}+ onClose={() => musicUI.closeYoutube()}+/>++<QualityPresetPanel+ open={musicUI.qualityOpen}+ onClose={() => musicUI.closeQuality()}+/>++<SourceOrderPanel+ open={musicUI.sourcesOpen}+ onClose={() => musicUI.closeSources()}+/>++<QobuzPanel+ open={musicUI.qobuzOpen}+ onClose={() => musicUI.closeQobuz()}+/>++<RightBar />++<SelectionBar />++<ContextMenu+ open={musicUI.contextMenu.open}+ x={musicUI.contextMenu.x}+ y={musicUI.contextMenu.y}+ items={ctxItems}+ onAction={handleCtxAction}+ onClose={() => musicUI.closeContextMenu()}+/>+{#if gamificationToasts.length > 0}<div class="gamif-stack" role="status" aria-live="polite">{#each gamificationToasts as item (item.id)}@@ -1016,4 +1300,15 @@animation: none;}}++ .global-player-bar {+ position: fixed;+ bottom: 0;+ left: var(--sidebar-width, 0px);+ right: 0;+ z-index: 80;+ }+ :global(body:has(.global-player-bar)) {+ padding-bottom: 80px;+ }</style>diff --git a/src/routes/study/achievements/+page.svelte b/src/routes/study/achievements/+page.svelteindex 09c8fd8f..0c9f38e7 100644--- a/src/routes/study/achievements/+page.svelte+++ b/src/routes/study/achievements/+page.svelte@@ -30,8 +30,8 @@type CatalogEntry = {code: string;family: string;- label: string;- description: string;+ labelKey: string;+ descKey: string;icon: string;threshold: number;tier: "bronze" | "silver" | "gold";@@ -39,160 +39,25 @@};const CATALOG: CatalogEntry[] = [- {- code: "xp:100",- family: "xp",- label: "Primeiros 100 XP",- description: "Acumule 100 XP estudando",- icon: "✨",- threshold: 100,- tier: "bronze",- },- {- code: "xp:500",- family: "xp",- label: "500 XP",- description: "Acumule 500 XP",- icon: "⭐",- threshold: 500,- tier: "bronze",- },- {- code: "xp:1000",- family: "xp",- label: "Mil XP",- description: "Marca dos 1000 XP",- icon: "🌟",- threshold: 1000,- tier: "silver",- },- {- code: "xp:5000",- family: "xp",- label: "5k XP",- description: "Cinco mil XP acumulados",- icon: "💫",- threshold: 5000,- tier: "silver",- },- {- code: "xp:10000",- family: "xp",- label: "10k XP",- description: "Dez mil XP — você é dedicado",- icon: "🏆",- threshold: 10000,- tier: "gold",- },-- {- code: "lessons:1",- family: "lessons",- label: "Primeira aula",- description: "Complete sua primeira aula",- icon: "🎓",- threshold: 1,- tier: "bronze",- counterKey: "lessons_completed",- },- {- code: "lessons:10",- family: "lessons",- label: "10 aulas",- description: "Complete 10 aulas",- icon: "📚",- threshold: 10,- tier: "bronze",- counterKey: "lessons_completed",- },- {- code: "lessons:50",- family: "lessons",- label: "50 aulas",- description: "Meio centenário de aulas",- icon: "📖",- threshold: 50,- tier: "silver",- counterKey: "lessons_completed",- },- {- code: "lessons:100",- family: "lessons",- label: "100 aulas",- description: "Cem aulas concluídas",- icon: "🥇",- threshold: 100,- tier: "gold",- counterKey: "lessons_completed",- },-- {- code: "focus:60",- family: "focus",- label: "1h focado",- description: "60 minutos de foco acumulados",- icon: "🧘",- threshold: 60,- tier: "bronze",- counterKey: "focus_minutes",- },- {- code: "focus:600",- family: "focus",- label: "10h focado",- description: "600 minutos de foco acumulados",- icon: "🎯",- threshold: 600,- tier: "silver",- counterKey: "focus_minutes",- },- {- code: "focus:6000",- family: "focus",- label: "100h focado",- description: "6000 minutos de foco — disciplina rara",- icon: "🔥",- threshold: 6000,- tier: "gold",- counterKey: "focus_minutes",- },-- {- code: "streak:3",- family: "streak",- label: "3 dias seguidos",- description: "Mantenha streak por 3 dias",- icon: "🔥",- threshold: 3,- tier: "bronze",- },- {- code: "streak:7",- family: "streak",- label: "1 semana de streak",- description: "7 dias consecutivos estudando",- icon: "🔥🔥",- threshold: 7,- tier: "bronze",- },- {- code: "streak:30",- family: "streak",- label: "30 dias de streak",- description: "Um mês inteiro de consistência",- icon: "🔥🔥🔥",- threshold: 30,- tier: "silver",- },- {- code: "streak:100",- family: "streak",- label: "100 dias de streak",- description: "Hábito de aço",- icon: "🏅",- threshold: 100,- tier: "gold",- },+ { code: "xp:100", family: "xp", labelKey: "study.achievements.label_xp_100", descKey: "study.achievements.desc_xp_100", icon: "✨", threshold: 100, tier: "bronze" },+ { code: "xp:500", family: "xp", labelKey: "study.achievements.label_xp_500", descKey: "study.achievements.desc_xp_500", icon: "⭐", threshold: 500, tier: "bronze" },+ { code: "xp:1000", family: "xp", labelKey: "study.achievements.label_xp_1000", descKey: "study.achievements.desc_xp_1000", icon: "🌟", threshold: 1000, tier: "silver" },+ { code: "xp:5000", family: "xp", labelKey: "study.achievements.label_xp_5000", descKey: "study.achievements.desc_xp_5000", icon: "💫", threshold: 5000, tier: "silver" },+ { code: "xp:10000", family: "xp", labelKey: "study.achievements.label_xp_10000", descKey: "study.achievements.desc_xp_10000", icon: "🏆", threshold: 10000, tier: "gold" },++ { code: "lessons:1", family: "lessons", labelKey: "study.achievements.label_lessons_1", descKey: "study.achievements.desc_lessons_1", icon: "🎓", threshold: 1, tier: "bronze", counterKey: "lessons_completed" },+ { code: "lessons:10", family: "lessons", labelKey: "study.achievements.label_lessons_10", descKey: "study.achievements.desc_lessons_10", icon: "📚", threshold: 10, tier: "bronze", counterKey: "lessons_completed" },+ { code: "lessons:50", family: "lessons", labelKey: "study.achievements.label_lessons_50", descKey: "study.achievements.desc_lessons_50", icon: "📖", threshold: 50, tier: "silver", counterKey: "lessons_completed" },+ { code: "lessons:100", family: "lessons", labelKey: "study.achievements.label_lessons_100", descKey: "study.achievements.desc_lessons_100", icon: "🥇", threshold: 100, tier: "gold", counterKey: "lessons_completed" },++ { code: "focus:60", family: "focus", labelKey: "study.achievements.label_focus_60", descKey: "study.achievements.desc_focus_60", icon: "🧘", threshold: 60, tier: "bronze", counterKey: "focus_minutes" },+ { code: "focus:600", family: "focus", labelKey: "study.achievements.label_focus_600", descKey: "study.achievements.desc_focus_600", icon: "🎯", threshold: 600, tier: "silver", counterKey: "focus_minutes" },+ { code: "focus:6000", family: "focus", labelKey: "study.achievements.label_focus_6000", descKey: "study.achievements.desc_focus_6000", icon: "🔥", threshold: 6000, tier: "gold", counterKey: "focus_minutes" },++ { code: "streak:3", family: "streak", labelKey: "study.achievements.label_streak_3", descKey: "study.achievements.desc_streak_3", icon: "🔥", threshold: 3, tier: "bronze" },+ { code: "streak:7", family: "streak", labelKey: "study.achievements.label_streak_7", descKey: "study.achievements.desc_streak_7", icon: "🔥🔥", threshold: 7, tier: "bronze" },+ { code: "streak:30", family: "streak", labelKey: "study.achievements.label_streak_30", descKey: "study.achievements.desc_streak_30", icon: "🔥🔥🔥", threshold: 30, tier: "silver" },+ { code: "streak:100", family: "streak", labelKey: "study.achievements.label_streak_100", descKey: "study.achievements.desc_streak_100", icon: "🏅", threshold: 100, tier: "gold" },];let xpState = $state<GamificationState | null>(null);@@ -250,7 +115,7 @@await pluginInvoke("study", "study:gamification:reset");confirmResetOpen = false;await load();- showToast("ok", "Reset feito");+ showToast("ok", $t("study.achievements.reset_done") as string);} catch (e) {showToast("err", e instanceof Error ? e.message : String(e));}@@ -368,14 +233,14 @@<span>/{counts.total}</span></div><div class="sum-tiers">- <span class="t-pill bronze">{tierStats.bronze} bronze</span>- <span class="t-pill silver">{tierStats.silver} prata</span>- <span class="t-pill gold">{tierStats.gold} ouro</span>+ <span class="t-pill bronze">{tierStats.bronze} {$t("study.achievements.tier_bronze")}</span>+ <span class="t-pill silver">{tierStats.silver} {$t("study.achievements.tier_silver")}</span>+ <span class="t-pill gold">{tierStats.gold} {$t("study.achievements.tier_gold")}</span></div></div></section>- <nav class="filters" aria-label="Filtros de categoria">+ <nav class="filters" aria-label={$t("study.achievements.filter_aria") as string}>{#each families as f (f.v)}<buttonclass="filter-btn"@@ -388,11 +253,11 @@{/each}<a class="filter-btn link" href="/study/achievements/tree"><span class="f-icon">🌳</span>- <span>Tree</span>+ <span>{$t("study.achievements.tree_link")}</span></a><a class="filter-btn link" href="/study/achievements/charts"><span class="f-icon">📈</span>- <span>Charts</span>+ <span>{$t("study.achievements.charts_link")}</span></a></nav>@@ -404,12 +269,12 @@<article class="card" class:unlocked={isUnlocked} data-tier={c.tier}><div class="icon">{c.icon}</div><div class="card-body">- <h3>{c.label}</h3>- <p>{c.description}</p>+ <h3>{$t(c.labelKey)}</h3>+ <p>{$t(c.descKey)}</p>{#if isUnlocked}<div class="unlocked-meta">- <span class="tier-pill" data-tier={c.tier}>{c.tier}</span>- <span class="when">desbloqueado {fmtRel(u.unlocked_at)}</span>+ <span class="tier-pill" data-tier={c.tier}>{$t(`study.achievements.tier_${c.tier}`)}</span>+ <span class="when">{$t("study.achievements.unlocked_prefix")} {fmtRel(u.unlocked_at)}</span></div>{:else}<div class="prog">@@ -463,7 +328,7 @@bind:open={confirmResetOpen}title={$t("study.achievements.reset_confirm_title") as string}message={$t("study.achievements.reset_confirm_message") as string}- confirmLabel="Reset"+ confirmLabel={$t("study.achievements.reset_confirm_label") as string}variant="danger"onConfirm={resetAll}/>diff --git a/src/routes/study/course/[id]/lesson/[lid]/+page.svelte b/src/routes/study/course/[id]/lesson/[lid]/+page.svelteindex 4bf01a01..979c463b 100644--- a/src/routes/study/course/[id]/lesson/[lid]/+page.svelte+++ b/src/routes/study/course/[id]/lesson/[lid]/+page.svelte@@ -2,8 +2,9 @@import { onDestroy, onMount, tick } from "svelte";import { page } from "$app/stores";import { goto } from "$app/navigation";- import { convertFileSrc } from "@tauri-apps/api/core";+ import { convertFileSrc, invoke } from "@tauri-apps/api/core";import { pluginInvoke } from "$lib/plugin-invoke";+ import { rpcSetSource, rpcClearSource } from "$lib/rpc";import { awardXp, bumpCounter } from "$lib/study-gamification";import { onFocusBreakStart } from "$lib/study-focus-bridge";import { renderMarkdownSync } from "$lib/study-markdown";@@ -437,6 +438,8 @@let unsubBreak: (() => void) | null = null;+ let unlistenClipHotkey: (() => void) | null = null;+onMount(() => {loadLesson(lessonId);window.addEventListener("keydown", onKeyDown);@@ -446,6 +449,16 @@void persistProgress(videoRef.currentTime, false);}});+ (async () => {+ try {+ const { listen } = await import("@tauri-apps/api/event");+ unlistenClipHotkey = await listen("clip-hotkey-pressed", () => {+ void clipLast60s();+ });+ } catch {+ // event listener optional+ }+ })();});$effect(() => {@@ -679,6 +692,25 @@window.removeEventListener("keydown", onKeyDown);unsubBreak?.();unsubBreak = null;+ unlistenClipHotkey?.();+ unlistenClipHotkey = null;+ void rpcClearSource("video");+ });++ $effect(() => {+ if (!lesson) return;+ const courseTitle = detail?.course?.title ?? "";+ const durationMs = lesson.duration_ms ?? 0;+ const positionSec = Math.floor(videoRef?.currentTime ?? 0);+ const isPaused = videoRef ? videoRef.paused : true;+ void rpcSetSource({+ source: "video",+ details: lesson.title ?? "Aula",+ state: courseTitle || "—",+ duration: Math.floor(durationMs / 1000),+ position: positionSec,+ paused: isPaused,+ });});async function markCompleteNow() {@@ -710,6 +742,102 @@}let screenshotToast = $state("");+ let clipping = $state(false);+ let clipToast = $state("");+ let replaySaving = $state(false);++ type ClipResult = {+ output_path: string;+ duration_secs: number;+ size_bytes: number;+ used_reencode: boolean;+ };++ async function clipLast60s() {+ if (!videoRef || !lesson) return;+ if (!videoRef.videoWidth || !videoRef.videoHeight) {+ clipToast = $t("study.lesson.clip_no_video") as string;+ setTimeout(() => (clipToast = ""), 2400);+ return;+ }+ if (clipping) return;+ clipping = true;+ clipToast = $t("study.lesson.clip_loading") as string;+ try {+ const cur = videoRef.currentTime;+ const duration = 60;+ const start = Math.max(0, cur - duration);+ const actual = Math.min(duration, cur);+ const ts = fmtTimestamp(cur);+ const res = await invoke<ClipResult>("clip_video", {+ req: {+ source_path: lesson.video_path,+ start_secs: start,+ duration_secs: actual,+ dest_dir: null,+ label: `${safeForFilename(lesson.title || "aula")}-${ts}`,+ reencode: null,+ },+ });+ const kb = Math.round(res.size_bytes / 1024);+ clipToast = `${$t("study.lesson.clip_done")} (${kb} KB)`;+ setTimeout(() => (clipToast = ""), 3500);+ void awardXp("clip_saved", 2, {+ lesson_id: lesson.id,+ timestamp: Math.floor(cur),+ used_reencode: res.used_reencode,+ });+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ clipToast = `${$t("study.lesson.clip_failed")}: ${msg}`;+ setTimeout(() => (clipToast = ""), 4500);+ } finally {+ clipping = false;+ }+ }++ async function saveReplayFromBuffer() {+ if (replaySaving) return;+ replaySaving = true;+ clipToast = "Saving replay…";+ try {+ const status = await pluginInvoke<{ running: boolean; buffer_secs: number }>(+ "misc",+ "misc:studio:replay_buffer:status",+ {},+ );+ if (!status.running) {+ clipToast = "Replay buffer is off — turn it on in Misc → Studio first";+ setTimeout(() => (clipToast = ""), 5000);+ return;+ }+ const ts = fmtTimestamp(videoRef?.currentTime ?? 0);+ const filename = `replay-${safeForFilename(lesson?.title || "aula")}-${ts}.mp4`;+ const res = await pluginInvoke<{+ ok: boolean;+ stats: {+ buffer_span_secs: number;+ file_size_bytes: number;+ };+ }>("misc", "misc:studio:replay_buffer:save", { filename });+ const sec = Math.floor(res.stats.buffer_span_secs);+ const kb = Math.round(res.stats.file_size_bytes / 1024);+ clipToast = `Replay saved: last ${sec}s (${kb} KB)`;+ setTimeout(() => (clipToast = ""), 4000);+ if (lesson) {+ void awardXp("replay_saved", 3, {+ lesson_id: lesson.id,+ buffer_secs: sec,+ });+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ clipToast = `Replay save failed: ${msg}`;+ setTimeout(() => (clipToast = ""), 5000);+ } finally {+ replaySaving = false;+ }+ }function fmtTimestamp(secs: number): string {const total = Math.floor(secs);@@ -1081,25 +1209,69 @@</button><buttontype="button"- class="btn screenshot"+ class="btn icon-btn"onclick={captureScreenshot}title="Capturar frame atual como PNG"aria-label="Screenshot do frame atual">- 📸+ <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="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />+ <circle cx="12" cy="13" r="4" />+ </svg></button><buttontype="button"- class="btn"+ class="btn icon-btn"+ onclick={clipLast60s}+ disabled={clipping}+ title={$t("study.lesson.clip") as string}+ aria-label={$t("study.lesson.clip_aria") as string}+ >+ <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">+ <circle cx="6" cy="6" r="3" />+ <circle cx="6" cy="18" r="3" />+ <line x1="20" y1="4" x2="8.12" y2="15.88" />+ <line x1="14.47" y1="14.48" x2="20" y2="20" />+ <line x1="8.12" y1="8.12" x2="12" y2="12" />+ </svg>+ </button>+ <button+ type="button"+ class="btn icon-btn"+ onclick={saveReplayFromBuffer}+ disabled={replaySaving}+ title="Save replay buffer (last 30s of what you hear)"+ aria-label="Save replay buffer"+ >+ <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">+ <rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18" />+ <line x1="7" y1="2" x2="7" y2="22" />+ <line x1="17" y1="2" x2="17" y2="22" />+ <line x1="2" y1="12" x2="22" y2="12" />+ <line x1="2" y1="7" x2="7" y2="7" />+ <line x1="2" y1="17" x2="7" y2="17" />+ <line x1="17" y1="17" x2="22" y2="17" />+ <line x1="17" y1="7" x2="22" y2="7" />+ </svg>+ </button>+ <button+ type="button"+ class="btn icon-btn"onclick={() => (annotateOpen = !annotateOpen)}title="Anotar este momento da aula"aria-label="Anotar momento">- ✎+ <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="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />+ </svg></button>{#if screenshotToast}<span class="screenshot-toast">{screenshotToast}</span>{/if}+ {#if clipToast}+ <span class="screenshot-toast">{clipToast}</span>+ {/if}<buttontype="button"class="btn complete"diff --git a/src/routes/study/focus/+page.svelte b/src/routes/study/focus/+page.svelteindex 57a6bcb8..e6eb6b19 100644--- a/src/routes/study/focus/+page.svelte+++ b/src/routes/study/focus/+page.svelte@@ -5,6 +5,7 @@import { emitFocusBreakStart } from "$lib/study-focus-bridge";import { t } from "$lib/i18n";import PageHero from "$lib/study-components/PageHero.svelte";+ import AboutLink from "$lib/study-music-components/AboutLink.svelte";type Current = {id: number;@@ -196,6 +197,7 @@onMount(() => {refresh();loadSettings();+ loadRpcText();poll = window.setInterval(() => {tick += 1;}, 1000);@@ -208,6 +210,33 @@}});+ const RPC_TEXT_KEY = "study.focus.rpc_text.v1";++ let rpcCustomText = $state("");++ function loadRpcText() {+ if (typeof localStorage === "undefined") return;+ try {+ rpcCustomText = localStorage.getItem(RPC_TEXT_KEY) ?? "";+ } 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 {+ /* ignore */+ }+ }+function formatDate(iso: string): string {try {return new Date(iso.replace(" ", "T") + "Z").toLocaleString();@@ -248,6 +277,19 @@<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"+ />+ </div>+ {/if}<div class="session-actions"><button type="button" class="btn-stop" onclick={stop}>{$t("study.focus.stop")}@@ -261,6 +303,35 @@{:else}<div class="card-hero-start"><span class="hero-eyebrow">{$t("study.focus.start_now")}</span>++ <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>+ <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>+ </div>+<div class="presets-row">{#each PRESETS as p (p.id)}<button type="button" class="preset" onclick={() => start(p.id)}>@@ -269,7 +340,7 @@<span class="preset-num">{p.minutes}</span><span class="preset-unit">min</span>{:else}- <span class="preset-free" aria-label="livre">∞</span>+ <span class="preset-free" aria-label={$t("study.focus.unlimited_aria") as string}>∞</span>{/if}</span><span class="preset-label">{$t(p.labelKey)}</span>@@ -286,19 +357,27 @@<div class="settings-accordions"><span class="settings-status" class:saving={savingState === "saving"} class:saved={savingState === "saved"}>- {savingState === "saving" ? "salvando…" : savingState === "saved" ? "salvo ✓" : ""}+ {savingState === "saving"+ ? $t("study.focus.settings_saving")+ : savingState === "saved"+ ? $t("study.focus.settings_saved")+ : ""}</span><details class="acc"><summary>- <span class="acc-title">Ciclos</span>+ <span class="acc-title">{$t("study.focus.acc_cycles_title")}</span><span class="acc-summary">- {settings.pomodoro_minutes}min foco · {settings.short_break_minutes}min pausa · {settings.cycles_before_long_break}× até pausa longa+ {$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>Foco (min)</span>+ <span>{$t("study.focus.acc_cycles_focus")}</span><inputtype="number"min="1"@@ -308,7 +387,7 @@/></label><label class="field">- <span>Pausa curta (min)</span>+ <span>{$t("study.focus.acc_cycles_short")}</span><inputtype="number"min="1"@@ -318,7 +397,7 @@/></label><label class="field">- <span>Pausa longa (min)</span>+ <span>{$t("study.focus.acc_cycles_long")}</span><inputtype="number"min="1"@@ -328,7 +407,7 @@/></label><label class="field">- <span>Ciclos antes da pausa longa</span>+ <span>{$t("study.focus.acc_cycles_count")}</span><inputtype="number"min="2"@@ -342,11 +421,17 @@<details class="acc"><summary>- <span class="acc-title">Pausas & auto-start</span>+ <span class="acc-title">{$t("study.focus.acc_breaks_title")}</span><span class="acc-summary">- {settings.auto_start_breaks ? "auto-pausa" : "manual"} ·- {settings.auto_start_focus ? "auto-retomada" : "manual"} ·- {settings.auto_pause_player ? "pausa player" : "ignora player"}+ {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">@@ -356,7 +441,7 @@bind:checked={settings.auto_start_breaks}onchange={saveSettings}/>- <span>Iniciar pausas automaticamente após o foco</span>+ <span>{$t("study.focus.acc_breaks_check_breaks")}</span></label><label class="check"><input@@ -364,7 +449,7 @@bind:checked={settings.auto_start_focus}onchange={saveSettings}/>- <span>Retomar foco automaticamente após pausa</span>+ <span>{$t("study.focus.acc_breaks_check_focus")}</span></label><label class="check"><input@@ -372,17 +457,21 @@bind:checked={settings.auto_pause_player}onchange={saveSettings}/>- <span>Pausar vídeo durante pausa de foco</span>+ <span>{$t("study.focus.acc_breaks_check_player")}</span></label></div></details><details class="acc"><summary>- <span class="acc-title">Sons & notificação</span>+ <span class="acc-title">{$t("study.focus.acc_sounds_title")}</span><span class="acc-summary">- {settings.notify_end ? "notificação ON" : "silencioso"} ·- {settings.notify_sound ? `som ${settings.sound_volume}%` : "sem som"}+ {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">@@ -392,7 +481,7 @@bind:checked={settings.notify_end}onchange={saveSettings}/>- <span>Notificação ao terminar ciclo</span>+ <span>{$t("study.focus.acc_sounds_check_notify")}</span></label><label class="check"><input@@ -400,10 +489,10 @@bind:checked={settings.notify_sound}onchange={saveSettings}/>- <span>Tocar som ao terminar</span>+ <span>{$t("study.focus.acc_sounds_check_sound")}</span></label><label class="field">- <span>Volume ({settings.sound_volume}%)</span>+ <span>{$t("study.focus.acc_sounds_volume", { n: settings.sound_volume })}</span><inputtype="range"min="0"@@ -435,6 +524,10 @@</details>{/if}{/if}++ <footer class="study-footer">+ <AboutLink variant="inline" />+ </footer></section><style>@@ -446,6 +539,13 @@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);+ }.study-page[data-mode="active"] {min-height: 60vh;@@ -479,6 +579,130 @@text-transform: uppercase;color: var(--text-muted);}+ .intent-row {+ display: flex;+ flex-direction: column;+ gap: 6px;+ position: relative;+ }+ .intent-label-block {+ font-size: 12px;+ color: var(--text-muted);+ font-weight: 500;+ }+ .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;+ }+ .intent-input-wrap:focus-within {+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 4%, var(--surface));+ }+ .intent-prefix {+ color: var(--text-muted);+ font-size: 14px;+ font-weight: 500;+ padding-right: 6px;+ flex-shrink: 0;+ }+ .intent-input {+ flex: 1;+ border: 0;+ background: transparent;+ color: var(--text);+ font-family: inherit;+ font-size: 14px;+ padding: 8px 0;+ outline: none;+ }+ .intent-input::placeholder {+ color: color-mix(in oklab, var(--text-muted) 70%, transparent);+ }+ .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;+ }+ .intent-clear:hover {+ background: color-mix(in oklab, var(--text-muted) 12%, transparent);+ color: var(--text);+ }+ .intent-suggestions {+ 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;+ }+ .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;+ }+ .suggestion:hover {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .intent-hint {+ margin: 2px 4px 0;+ font-size: 11px;+ color: var(--text-muted);+ line-height: 1.4;+ }+ .session-intent {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-top: 8px;+ color: var(--text-muted);+ font-size: 13px;+ }+ .intent-label {+ text-transform: lowercase;+ }+ .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;+ }+ .intent-input.intent-inline:focus {+ border-bottom-color: var(--accent);+ }.presets-row {display: grid;grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));diff --git a/src/routes/study/library/+page.svelte b/src/routes/study/library/+page.svelteindex 4c05fdae..1731b35c 100644--- a/src/routes/study/library/+page.svelte+++ b/src/routes/study/library/+page.svelte@@ -1,12 +1,11 @@<script lang="ts">import { onMount, untrack } from "svelte";- import { goto } from "$app/navigation";+ import { goto, beforeNavigate, replaceState } from "$app/navigation";import { invoke, convertFileSrc } from "@tauri-apps/api/core";import { pluginInvoke } from "$lib/plugin-invoke";import { showToast } from "$lib/stores/toast-store.svelte";import { t } from "$lib/i18n";import { page } from "$app/stores";- import { replaceState } from "$app/navigation";import SegmentedControl from "$lib/study-components/SegmentedControl.svelte";import ConfirmDialog from "$lib/study-components/ConfirmDialog.svelte";import LibraryHomeShelves from "$lib/study-components/shelves/LibraryHomeShelves.svelte";@@ -43,15 +42,23 @@enabled: boolean;added_at: number;is_default: boolean;+ exists?: boolean;};- type BrowseFolder = { path: string; name: string; video_count: number };+ type BrowseFolder = {+ path: string;+ name: string;+ video_count: number;+ preview_videos?: string[];+ latest_mtime?: number | null;+ };type BrowseVideo = {path: string;name: string;stem: string;size: number;subtitle_path: string | null;+ thumbnail_path: string | null;};type BrowseDocument = {path: string;@@ -140,49 +147,125 @@let mode = $state<ViewMode>("courses");- function syncCoursesUrl() {+ function buildLibraryUrlSearch(): string {const params = new URLSearchParams();+ if (mode !== "courses") params.set("mode", mode);if (mode === "courses" && coursesView !== "home") {params.set("view", coursesView);}+ if (mode === "browse" && browsePath.length > 0) params.set("bp", browsePath);if (sortKey !== "last_watched" || sortDirection !== "desc") {params.set("sort", sortKey);if (sortDirection !== "desc") params.set("dir", sortDirection);}- if (search.trim().length > 0) {- params.set("q", search.trim());- }- const queryString = params.toString();- const next = queryString.length > 0 ? `?${queryString}` : "";- if (typeof window !== "undefined" && window.location.search !== next) {- try {- replaceState(`${window.location.pathname}${next}`, {});- } catch {- window.history.replaceState(null, "", `${window.location.pathname}${next}`);- }+ if (search.trim().length > 0) params.set("q", search.trim());+ if (statusFilter !== "all") params.set("status", statusFilter);+ if (playlistFilter != null) params.set("pl", String(playlistFilter));+ if (includeTags.size > 0) params.set("inc", [...includeTags].join(","));+ if (excludeTags.size > 0) params.set("exc", [...excludeTags].join(","));+ if (favoritesOnly) params.set("fav", "1");+ const qs = params.toString();+ return qs.length > 0 ? `?${qs}` : "";+ }++ function buildCurrentLibraryUrl(): string {+ if (typeof window === "undefined") return "/study/library";+ return `${window.location.pathname}${buildLibraryUrlSearch()}`;+ }++ function syncLibraryUrl() {+ if (typeof window === "undefined") return;+ const next = buildLibraryUrlSearch();+ if (window.location.search === next) return;+ try {+ replaceState(`${window.location.pathname}${next}`, {});+ } catch {+ window.history.replaceState(null, "", `${window.location.pathname}${next}`);}}function readUrlParams() {if (typeof window === "undefined") return;const params = new URLSearchParams(window.location.search);+ if (import.meta.env.DEV) {+ console.log("[lib] readUrlParams from", window.location.search);+ }+ let bpFromUrl = params.get("bp");+ if (!params.get("mode") && !bpFromUrl) {+ try {+ const raw = sessionStorage.getItem("study.library.return_state");+ if (raw) {+ const fallback = JSON.parse(raw) as {+ mode?: string;+ browsePath?: string;+ search?: string;+ };+ if (+ fallback.mode === "browse" ||+ fallback.mode === "courses" ||+ fallback.mode === "telegram"+ ) {+ params.set("mode", fallback.mode);+ }+ if (fallback.browsePath) {+ params.set("bp", fallback.browsePath);+ bpFromUrl = fallback.browsePath;+ }+ if (fallback.search) params.set("q", fallback.search);+ if (import.meta.env.DEV) {+ console.log("[lib] used return_state fallback", fallback);+ }+ }+ } catch {+ /* malformed; ignore */+ }+ }+ const m = params.get("mode");+ if (m === "courses" || m === "browse" || m === "telegram") mode = m;const v = params.get("view");if (v === "catalog" || v === "home") coursesView = v;+ const bp = params.get("bp");+ if (bp) browsePath = bp;const s = params.get("sort");if (s) sortKey = s as SortKey;const d = params.get("dir");if (d === "asc" || d === "desc") sortDirection = d;const q = params.get("q");if (q) search = q;+ const st = params.get("status");+ if (+ st === "all" ||+ st === "not_started" ||+ st === "in_progress" ||+ st === "completed"+ ) {+ statusFilter = st;+ }+ const pl = params.get("pl");+ if (pl) {+ const n = Number(pl);+ if (Number.isFinite(n)) playlistFilter = n;+ }+ const inc = params.get("inc");+ if (inc) includeTags = new Set(inc.split(",").filter(Boolean));+ const exc = params.get("exc");+ if (exc) excludeTags = new Set(exc.split(",").filter(Boolean));+ if (params.get("fav") === "1") favoritesOnly = true;}$effect(() => {void mode;void coursesView;+ void browsePath;void sortKey;void sortDirection;void search;- syncCoursesUrl();+ void statusFilter;+ void playlistFilter;+ void includeTags;+ void excludeTags;+ void favoritesOnly;+ syncLibraryUrl();});function onSortChange(s: CatalogSort, d: CatalogSortDirection) {@@ -202,17 +285,609 @@let rescanning = $state(false);let rescanMsg = $state("");- const modeOptions = $derived([- { value: "courses", label: $t("study.library.mode_courses") },- { value: "browse", label: $t("study.library.mode_browse") },- { value: "telegram", label: $t("study.library.mode_telegram") },- ]);+ type PinnedPath = {+ id: number;+ path: string;+ label: string | null;+ color: string | null;+ position: number;+ added_at: number;+ };+ let pins = $state<PinnedPath[]>([]);++ let openCrumbIndex = $state<number | null>(null);+ let crumbSiblingsCache = $state<Map<string, BrowseFolder[]>>(new Map());+ let crumbSiblingsLoading = $state<string | null>(null);++ let browseViewMode = $state<"grid" | "list">("grid");+ let lastWatchedInFolder = $state<string | null>(null);++ type BrowseSort = "name_asc" | "name_desc" | "size_desc";+ let browseSort = $state<BrowseSort>("name_asc");+ let sortMenuOpen = $state(false);++ let selectedPaths = $state<Set<string>>(new Set());+ let lastSelectionAnchor = $state<string | null>(null);+ let bulkDeleteOpen = $state(false);++ type Tab = { path: string };+ let tabs = $state<Tab[]>([]);+ let activeTabIndex = $state(0);++ function tabLabel(path: string): string {+ if (!path) return "Raízes";+ const norm = path.replace(/\\/g, "/").replace(/\/+$/, "");+ const seg = norm.split("/").pop();+ return seg && seg.length > 0 ? seg : path;+ }++ function saveTabs() {+ if (typeof window === "undefined") return;+ try {+ sessionStorage.setItem(+ "study.library.tabs.v1",+ JSON.stringify({ tabs, activeTabIndex }),+ );+ } catch {+ /* ignore */+ }+ }++ function loadTabsFromStorage(): { tabs: Tab[]; activeTabIndex: number } | null {+ if (typeof window === "undefined") return null;+ try {+ const raw = sessionStorage.getItem("study.library.tabs.v1");+ if (!raw) return null;+ const parsed = JSON.parse(raw) as { tabs?: Tab[]; activeTabIndex?: number };+ if (!Array.isArray(parsed.tabs) || parsed.tabs.length === 0) return null;+ const idx = Math.max(0, Math.min(parsed.tabs.length - 1, parsed.activeTabIndex ?? 0));+ return { tabs: parsed.tabs, activeTabIndex: idx };+ } catch {+ return null;+ }+ }++ function switchTab(idx: number) {+ if (idx < 0 || idx >= tabs.length) return;+ activeTabIndex = idx;+ const target = tabs[idx].path;+ saveTabs();+ if (target !== browsePath) {+ void loadBrowse(target);+ }+ }++ function openInNewTab(path: string) {+ tabs = [...tabs, { path }];+ activeTabIndex = tabs.length - 1;+ saveTabs();+ if (mode !== "browse") mode = "browse";+ void loadBrowse(path);+ }++ function closeTab(idx: number) {+ if (tabs.length <= 1) {+ tabs = [];+ activeTabIndex = 0;+ saveTabs();+ return;+ }+ const wasActive = idx === activeTabIndex;+ const next = tabs.filter((_, i) => i !== idx);+ let nextActive = activeTabIndex;+ if (wasActive) {+ nextActive = Math.max(0, idx - 1);+ } else if (idx < activeTabIndex) {+ nextActive = activeTabIndex - 1;+ }+ tabs = next;+ activeTabIndex = nextActive;+ saveTabs();+ if (wasActive && tabs[nextActive]) {+ void loadBrowse(tabs[nextActive].path);+ }+ }++ function selectionAllPaths(): string[] {+ if (!visibleBrowse) return [];+ return [+ ...visibleBrowse.folders.map((f) => f.path),+ ...visibleBrowse.videos.map((v) => v.path),+ ...(visibleBrowse.documents ?? []).map((d) => d.path),+ ];+ }++ function clearSelection() {+ selectedPaths = new Set();+ lastSelectionAnchor = null;+ }++ function toggleSelection(path: string) {+ const next = new Set(selectedPaths);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ selectedPaths = next;+ lastSelectionAnchor = path;+ }++ function selectRange(toPath: string) {+ if (!lastSelectionAnchor || !visibleBrowse) {+ toggleSelection(toPath);+ return;+ }+ const all = selectionAllPaths();+ const a = all.indexOf(lastSelectionAnchor);+ const b = all.indexOf(toPath);+ if (a < 0 || b < 0) {+ toggleSelection(toPath);+ return;+ }+ const [from, to] = a <= b ? [a, b] : [b, a];+ const next = new Set(selectedPaths);+ for (let i = from; i <= to; i++) next.add(all[i]);+ selectedPaths = next;+ }++ function selectAllVisible() {+ selectedPaths = new Set(selectionAllPaths());+ lastSelectionAnchor = null;+ }++ function handleFolderClick(e: MouseEvent, f: BrowseFolder) {+ if (renamingPath === f.path) return;+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ toggleSelection(f.path);+ return;+ }+ if (e.shiftKey) {+ e.preventDefault();+ selectRange(f.path);+ return;+ }+ clearSelection();+ void loadBrowse(f.path);+ }++ function handleVideoClick(e: MouseEvent, v: BrowseVideo) {+ if (renamingPath === v.path) return;+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ toggleSelection(v.path);+ return;+ }+ if (e.shiftKey) {+ e.preventDefault();+ selectRange(v.path);+ return;+ }+ clearSelection();+ openBrowseVideo(v);+ }++ function handleDocClick(e: MouseEvent, d: BrowseDocument) {+ if (renamingPath === d.path) return;+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ toggleSelection(d.path);+ return;+ }+ if (e.shiftKey) {+ e.preventDefault();+ selectRange(d.path);+ return;+ }+ clearSelection();+ void openBrowseDocument(d);+ }++ async function performBulkDelete() {+ const targets = [...selectedPaths];+ if (targets.length === 0) {+ bulkDeleteOpen = false;+ return;+ }+ let ok = 0;+ let fail = 0;+ for (const path of targets) {+ try {+ await pluginInvoke("study", "study:browse:delete", { path });+ ok += 1;+ } catch (e) {+ fail += 1;+ if (import.meta.env.DEV) {+ console.warn("[library] bulk delete failed for", path, e);+ }+ }+ }+ bulkDeleteOpen = false;+ clearSelection();+ await loadBrowse(browsePath);+ if (fail === 0) {+ showToast(+ "success",+ $t("study.library.selection_delete_done", { count: ok }) as string,+ );+ } else {+ showToast(+ "info",+ $t("study.library.selection_delete_partial", { ok, fail }) as string,+ );+ }+ }++ function setBrowseSort(s: BrowseSort) {+ browseSort = s;+ sortMenuOpen = false;+ }++ $effect(() => {+ if (!sortMenuOpen) return;+ function onDoc(e: MouseEvent) {+ const t = e.target as HTMLElement | null;+ if (t && t.closest(".sort-menu, .sort-btn")) return;+ sortMenuOpen = false;+ }+ document.addEventListener("mousedown", onDoc);+ return () => document.removeEventListener("mousedown", onDoc);+ });++ let addressBarOpen = $state(false);+ let addressBarValue = $state("");+ let addressBarRef = $state<HTMLInputElement | null>(null);++ let creatingFolder = $state(false);+ let newFolderName = $state("");+ let newFolderRef = $state<HTMLInputElement | null>(null);++ let renamingPath = $state<string | null>(null);+ let renameValue = $state("");++ type CtxMenuTarget =+ | { kind: "folder"; path: string; name: string }+ | { kind: "video"; path: string; name: string }+ | { kind: "doc"; path: string; name: string };++ let contextMenu = $state<{+ x: number;+ y: number;+ target: CtxMenuTarget;+ } | null>(null);++ let confirmDeleteOpen = $state(false);+ let pendingDelete = $state<CtxMenuTarget | null>(null);++ function openContextMenu(event: MouseEvent, target: CtxMenuTarget) {+ event.preventDefault();+ contextMenu = { x: event.clientX, y: event.clientY, target };+ }++ function closeContextMenu() {+ contextMenu = null;+ }++ $effect(() => {+ if (!contextMenu) return;+ function onDoc(e: MouseEvent) {+ const t = e.target as HTMLElement | null;+ if (t && t.closest(".ctx-menu")) return;+ closeContextMenu();+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") closeContextMenu();+ }+ document.addEventListener("mousedown", onDoc);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", onDoc);+ document.removeEventListener("keydown", onKey);+ };+ });++ async function showInExplorer(path: string) {+ try {+ await pluginInvoke("study", "study:shell:show_in_folder", { path });+ } catch (e) {+ console.error("show_in_folder failed", e);+ }+ closeContextMenu();+ }++ function startRename(target: CtxMenuTarget) {+ renamingPath = target.path;+ renameValue = target.name;+ closeContextMenu();+ }++ async function confirmRename(targetPath: string) {+ const trimmed = renameValue.trim();+ if (!trimmed) {+ cancelRename();+ return;+ }+ try {+ await pluginInvoke("study", "study:browse:rename", {+ path: targetPath,+ newName: trimmed,+ });+ renamingPath = null;+ renameValue = "";+ await loadBrowse(browsePath);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ function cancelRename() {+ renamingPath = null;+ renameValue = "";+ }++ function startDelete(target: CtxMenuTarget) {+ pendingDelete = target;+ confirmDeleteOpen = true;+ closeContextMenu();+ }++ async function performDelete() {+ if (!pendingDelete) return;+ const target = pendingDelete;+ try {+ await pluginInvoke("study", "study:browse:delete", { path: target.path });+ await loadBrowse(browsePath);+ showToast(+ "success",+ $t("study.library.delete_toast_done", { name: target.name }) as string,+ );+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ pendingDelete = null;+ confirmDeleteOpen = false;+ }+ }++ function startCreateFolder() {+ creatingFolder = true;+ newFolderName = "";+ queueMicrotask(() => newFolderRef?.focus());+ }++ async function confirmCreateFolder() {+ const trimmed = newFolderName.trim();+ if (!trimmed) {+ cancelCreateFolder();+ return;+ }+ try {+ await pluginInvoke("study", "study:browse:create_folder", {+ parent: browsePath,+ name: trimmed,+ });+ creatingFolder = false;+ newFolderName = "";+ await loadBrowse(browsePath);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ function cancelCreateFolder() {+ creatingFolder = false;+ newFolderName = "";+ }++ function openAddressBar() {+ addressBarValue = browsePath;+ addressBarOpen = true;+ queueMicrotask(() => {+ addressBarRef?.focus();+ addressBarRef?.select();+ });+ }++ function submitAddressBar() {+ const v = addressBarValue.trim();+ addressBarOpen = false;+ if (v && v !== browsePath) {+ void loadBrowse(v);+ }+ }++ function closeAddressBar() {+ addressBarOpen = false;+ addressBarValue = "";+ }++ function autofocusOnRender(node: HTMLInputElement) {+ node.focus();+ if (node.value.length > 0) {+ node.select();+ }+ }++ function isTypingTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ const tag = target.tagName;+ return (+ tag === "INPUT" ||+ tag === "TEXTAREA" ||+ tag === "SELECT" ||+ target.isContentEditable+ );+ }++ $effect(() => {+ if (mode !== "browse") return;+ function onKey(e: KeyboardEvent) {+ const isAddressBarShortcut =+ (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "l";+ if (isAddressBarShortcut) {+ e.preventDefault();+ openAddressBar();+ return;+ }+ if (isTypingTarget(e.target)) return;+ if (openCrumbIndex !== null) return;+ if (contextMenu) return;+ if (renamingPath !== null) return;+ if (e.key === "Escape" && selectedPaths.size > 0) {+ e.preventDefault();+ clearSelection();+ return;+ }+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "a") {+ if (visibleBrowse) {+ e.preventDefault();+ selectAllVisible();+ }+ return;+ }+ const isBack =+ e.key === "Backspace" ||+ (e.altKey && e.key === "ArrowLeft") ||+ (e.metaKey && e.key === "ArrowLeft") ||+ (e.metaKey && e.key === "ArrowUp") ||+ (e.altKey && e.key === "ArrowUp");+ if (!isBack) return;+ const parent = browseData?.parent ?? null;+ if (!parent) return;+ e.preventDefault();+ void loadBrowse(parent);+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });++ async function toggleSiblings(idx: number, parentPath: string) {+ if (openCrumbIndex === idx) {+ openCrumbIndex = null;+ return;+ }+ if (!crumbSiblingsCache.has(parentPath)) {+ crumbSiblingsLoading = parentPath;+ try {+ const data = await pluginInvoke<BrowseData>(+ "study",+ "study:browse:list",+ { path: parentPath },+ );+ const next = new Map(crumbSiblingsCache);+ next.set(parentPath, data.folders ?? []);+ crumbSiblingsCache = next;+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn("[library] siblings fetch failed", e);+ }+ const next = new Map(crumbSiblingsCache);+ next.set(parentPath, []);+ crumbSiblingsCache = next;+ } finally {+ crumbSiblingsLoading = null;+ }+ }+ openCrumbIndex = idx;+ }++ function closeSiblings() {+ openCrumbIndex = null;+ }++ $effect(() => {+ if (openCrumbIndex == null) return;+ function onDocPointer(e: MouseEvent) {+ const target = e.target as HTMLElement | null;+ if (target && target.closest(".crumb-chevron-wrap")) return;+ closeSiblings();+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") closeSiblings();+ }+ document.addEventListener("mousedown", onDocPointer);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", onDocPointer);+ document.removeEventListener("keydown", onKey);+ };+ });++ $effect(() => {+ void browsePath;+ crumbSiblingsCache = new Map();+ openCrumbIndex = null;+ });++ async function loadPins() {+ try {+ const res = await pluginInvoke<{ pins: PinnedPath[] }>(+ "study",+ "study:library:pins:list",+ );+ pins = res.pins ?? [];+ } catch (e) {+ if (import.meta.env.DEV) console.warn("[library] pins:list failed", e);+ }+ }++ async function togglePin(path: string, suggestedLabel?: string) {+ const isPinned = pins.some((p) => p.path === path);+ try {+ if (isPinned) {+ await pluginInvoke("study", "study:library:pins:remove", { path });+ } else {+ await pluginInvoke("study", "study:library:pins:add", {+ path,+ label: suggestedLabel ?? null,+ });+ }+ await loadPins();+ showToast(+ "success",+ $t(+ isPinned+ ? "study.library.pin_removed_toast"+ : "study.library.pin_added_toast",+ { name: suggestedLabel ?? path },+ ) as string,+ );+ } catch (e) {+ console.error("toggle pin failed", e);+ const msg = e instanceof Error ? e.message : String(e);+ showToast(+ "error",+ $t(+ isPinned+ ? "study.library.unpin_failed"+ : "study.library.pin_failed",+ { msg },+ ) as string,+ );+ }+ }++ function openPinnedPath(path: string) {+ if (mode !== "browse") {+ mode = "browse";+ }+ void loadBrowse(path);+ }+let tgSession = $state<TelegramSessionState>({ kind: "unauthenticated" });let tgChecking = $state(false);let tgOutputDir = $state("");let downloadsActive = $state(0);+ let tgConnected = $derived(tgSession.kind === "authenticated");+ let telegramLabel = $derived(+ tgConnected+ ? ($t("study.library.mode_telegram") as string)+ : `${$t("study.library.mode_telegram") as string} ${$t("study.library.mode_telegram_disconnected_suffix") as string}`,+ );+async function checkTelegramSession() {tgChecking = true;try {@@ -385,14 +1060,29 @@const visibleBrowse = $derived.by<BrowseData | null>(() => {if (!browseData) return null;const term = search.trim().toLowerCase();- if (!term) return browseData;+ let folders = browseData.folders;+ let videos = browseData.videos;+ let documents = browseData.documents ?? [];+ if (term) {+ folders = folders.filter((f) => f.name.toLowerCase().includes(term));+ videos = videos.filter((v) => v.name.toLowerCase().includes(term));+ documents = documents.filter((d) => d.name.toLowerCase().includes(term));+ }+ const dir = browseSort === "name_desc" ? -1 : 1;+ const cmpName = (a: { name: string }, b: { name: string }) =>+ dir * a.name.localeCompare(b.name, undefined, { numeric: true });+ const cmpSize = (a: { size?: number; name: string }, b: { size?: number; name: string }) => {+ const aS = a.size ?? 0;+ const bS = b.size ?? 0;+ if (aS === bS) return a.name.localeCompare(b.name, undefined, { numeric: true });+ return bS - aS;+ };+ const sortFn = browseSort === "size_desc" ? cmpSize : cmpName;return {...browseData,- folders: browseData.folders.filter((f) => f.name.toLowerCase().includes(term)),- videos: browseData.videos.filter((v) => v.name.toLowerCase().includes(term)),- documents: (browseData.documents ?? []).filter((d) =>- d.name.toLowerCase().includes(term),- ),+ folders: [...folders].sort(cmpName),+ videos: [...videos].sort(sortFn),+ documents: [...documents].sort(sortFn),};});@@ -417,30 +1107,189 @@}}- async function loadBrowse(path: string) {- browseLoading = true;+ function captureScrollRatio(): number {+ if (typeof window === "undefined") return 0;+ const max = Math.max(+ 1,+ document.documentElement.scrollHeight - window.innerHeight,+ );+ return Math.min(1, Math.max(0, window.scrollY / max));+ }++ async function saveBrowseStateFor(+ path: string,+ lastVideoPath: string | null = null,+ ) {+ if (!path || typeof window === "undefined") return;+ const ratio = captureScrollRatio();try {- browseData = await pluginInvoke<BrowseData>("study", "study:browse:list", {- path,+ const args: {+ path: string;+ scrollRatio: number;+ viewMode: string;+ lastVideoPath?: string;+ } = { path, scrollRatio: ratio, viewMode: browseViewMode };+ if (lastVideoPath) args.lastVideoPath = lastVideoPath;+ await pluginInvoke("study", "study:library:browse_state:set", args);+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn("[library] save browse state failed", e);+ }+ }+ }++ async function restoreScrollFor(path: string) {+ if (!path || typeof window === "undefined") return;+ try {+ const state = await pluginInvoke<{+ scroll_ratio: number;+ view_mode: string;+ last_video_path: string | null;+ }>("study", "study:library:browse_state:get", { path });+ const restoredView = state?.view_mode;+ if (restoredView === "list" || restoredView === "grid") {+ browseViewMode = restoredView;+ }+ lastWatchedInFolder = state?.last_video_path ?? null;+ const ratio = state?.scroll_ratio ?? 0;+ if (ratio <= 0) return;+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ const max = Math.max(+ 0,+ document.documentElement.scrollHeight - window.innerHeight,+ );+ window.scrollTo({ top: max * ratio, behavior: "auto" });+ });});- browsePath = browseData.path;} catch (e) {- console.error("browse failed", e);- browseData = null;- } finally {- browseLoading = false;+ if (import.meta.env.DEV) {+ console.warn("[library] restore browse scroll failed", e);+ }}}- type HealthReport = {- zero_byte_videos: { lesson_id: number; course_id: number; lesson_title: string; course_title: string; video_path: string }[];- missing_videos: { lesson_id: number; course_id: number; lesson_title: string; course_title: string; video_path: string }[];- orphan_descriptions: { dir: string; description_path: string }[];- total_issues: number;- };+ async function setBrowseViewMode(next: "grid" | "list") {+ if (browseViewMode === next) return;+ browseViewMode = next;+ if (!browsePath) return;+ try {+ await pluginInvoke("study", "study:library:browse_state:set", {+ path: browsePath,+ viewMode: next,+ scrollRatio: captureScrollRatio(),+ });+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn("[library] save view_mode failed", e);+ }+ }+ }- let healthReport = $state<HealthReport | null>(null);- let healthOpen = $state(false);+ const triedBrowseThumbs = new Set<string>();+ let videoThumbCache = $state<Map<string, string>>(new Map());++ function seedThumbCacheFromData() {+ if (!browseData) return;+ const next = new Map(videoThumbCache);+ for (const v of browseData.videos) {+ if (v.thumbnail_path) next.set(v.path, v.thumbnail_path);+ }+ videoThumbCache = next;+ }++ function applyBrowseThumb(videoPath: string, thumbPath: string) {+ const next = new Map(videoThumbCache);+ next.set(videoPath, thumbPath);+ videoThumbCache = next;+ if (!browseData) return;+ browseData = {+ ...browseData,+ videos: browseData.videos.map((v) =>+ v.path === videoPath ? { ...v, thumbnail_path: thumbPath } : v,+ ),+ };+ }++ function collectThumbExtractTargets(): string[] {+ if (!browseData) return [];+ const targets = new Set<string>();+ for (const v of browseData.videos) {+ if (!videoThumbCache.has(v.path) && !triedBrowseThumbs.has(v.path)) {+ targets.add(v.path);+ }+ }+ for (const f of browseData.folders) {+ const previews = f.preview_videos ?? [];+ for (const vp of previews) {+ if (!videoThumbCache.has(vp) && !triedBrowseThumbs.has(vp)) {+ targets.add(vp);+ }+ }+ }+ return [...targets];+ }++ async function extractMissingBrowseThumbs() {+ const targets = collectThumbExtractTargets();+ for (const path of targets) {+ triedBrowseThumbs.add(path);+ try {+ const res = await pluginInvoke<{+ video_path: string;+ thumbnail_path: string;+ }>("study", "study:browse:extract_thumbnail", { path });+ applyBrowseThumb(res.video_path, res.thumbnail_path);+ } catch (e) {+ if (import.meta.env.DEV) {+ console.warn("[library] thumb extract failed for", path, e);+ }+ }+ }+ }++ async function loadBrowse(path: string) {+ const previous = browsePath;+ if (previous && previous !== path) {+ void saveBrowseStateFor(previous);+ }+ browseLoading = true;+ try {+ browseData = await pluginInvoke<BrowseData>("study", "study:browse:list", {+ path,+ });+ browsePath = browseData.path;+ if (tabs.length === 0) {+ tabs = [{ path: browsePath }];+ activeTabIndex = 0;+ saveTabs();+ } else if (activeTabIndex < tabs.length && tabs[activeTabIndex].path !== browsePath) {+ const next = [...tabs];+ next[activeTabIndex] = { path: browsePath };+ tabs = next;+ saveTabs();+ }+ clearSelection();+ seedThumbCacheFromData();+ void restoreScrollFor(browsePath);+ void extractMissingBrowseThumbs();+ } catch (e) {+ console.error("browse failed", e);+ browseData = null;+ } finally {+ browseLoading = false;+ }+ }++ type HealthReport = {+ zero_byte_videos: { lesson_id: number; course_id: number; lesson_title: string; course_title: string; video_path: string }[];+ missing_videos: { lesson_id: number; course_id: number; lesson_title: string; course_title: string; video_path: string }[];+ orphan_descriptions: { dir: string; description_path: string }[];+ total_issues: number;+ };++ let healthReport = $state<HealthReport | null>(null);+ let healthOpen = $state(false);let healthLoading = $state(false);let cleanupBusy = $state(false);let cleanupMsg = $state("");@@ -530,17 +1379,46 @@}}+ function consumeReturnToast() {+ if (typeof window === "undefined") return;+ try {+ const raw = sessionStorage.getItem("study.library.return_toast");+ if (!raw) return;+ sessionStorage.removeItem("study.library.return_toast");+ const data = JSON.parse(raw) as { folderName?: string };+ if (data.folderName) {+ showToast(+ "info",+ $t("study.library.back_toast", { folder: data.folderName }) as string,+ );+ }+ } catch {+ /* malformed or sessionStorage unavailable */+ }+ }+onMount(async () => {readUrlParams();- await Promise.all([loadCourses(), loadRoots()]);+ consumeReturnToast();+ const savedTabs = loadTabsFromStorage();+ if (savedTabs && savedTabs.tabs.length > 0) {+ tabs = savedTabs.tabs;+ activeTabIndex = savedTabs.activeTabIndex;+ if (mode === "browse") {+ const target = tabs[activeTabIndex]?.path ?? "";+ if (target !== browsePath) browsePath = target;+ }+ }+ await Promise.all([loadCourses(), loadRoots(), loadPins()]);loadHealth();+ void checkTelegramSession();loading = false;});$effect(() => {const m = mode;if (m === "browse" && untrack(() => !browseData)) {- loadBrowse("");+ loadBrowse(untrack(() => browsePath));}if (m === "telegram" && untrack(() => !tgChecking && tgSession.kind !== "authenticated")) {void checkTelegramSession();@@ -660,11 +1538,35 @@}function openBrowseVideo(v: BrowseVideo) {+ if (typeof window !== "undefined") {+ const returnUrl = buildCurrentLibraryUrl();+ try {+ sessionStorage.setItem("study.library.return_url", returnUrl);+ sessionStorage.setItem(+ "study.library.return_state",+ JSON.stringify({ mode, browsePath, search }),+ );+ } catch {+ /* sessionStorage may be unavailable; back-button falls back to history */+ }+ if (import.meta.env.DEV) {+ console.log("[lib] saving return_url", returnUrl, "browsePath", browsePath);+ }+ }+ if (browsePath) {+ void saveBrowseStateFor(browsePath, v.path);+ }const params = new URLSearchParams({ path: v.path, name: v.name });if (v.subtitle_path) params.set("subtitle", v.subtitle_path);goto(`/study/watch?${params.toString()}`);}+ beforeNavigate(() => {+ if (mode === "browse" && browsePath) {+ void saveBrowseStateFor(browsePath);+ }+ });+async function openBrowseDocument(d: BrowseDocument) {await openPath(d.path);}@@ -673,13 +1575,17 @@<section class="study-page"><header class="head"><div class="row-primary">- <h1 class="page-title">{$t("study.library.title")}</h1>+ <div class="title-block">+ <h1 class="page-title">{$t("study.library.title")}</h1>+ <p class="page-subtitle">{$t("study.library.subtitle")}</p>+ </div><div class="right"><buttontype="button"class="ghost-btn"onclick={() => (rootsOpen = true)}aria-label={$t("study.library.roots_button")}+ title={$t("study.library.roots_button_hint") 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" aria-hidden="true"><path d="M3 7v13h18V9h-9l-2-2H3z"></path>@@ -693,7 +1599,33 @@</div><div class="row-secondary">- <SegmentedControl bind:value={mode} options={modeOptions} ariaLabel="mode" />+ {#snippet iconCourses()}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M22 10L12 5 2 10l10 5 10-5z"/>+ <path d="M6 12v5c0 1 3 3 6 3s6-2 6-3v-5"/>+ </svg>+ {/snippet}+ {#snippet iconBrowse()}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M3 7v13h18V9h-9l-2-2H3z"/>+ </svg>+ {/snippet}+ {#snippet iconTelegram()}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" 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>+ {/snippet}+ <SegmentedControl+ bind:value={mode}+ options={[+ { value: "courses", label: $t("study.library.mode_courses") as string, icon: iconCourses },+ { value: "browse", label: $t("study.library.mode_browse") as string, icon: iconBrowse },+ { value: "telegram", label: telegramLabel, icon: iconTelegram },+ ]}+ ariaLabel="mode"+ />{#if mode !== "courses"}<inputtype="search"@@ -716,7 +1648,7 @@aria-selected={coursesView === "home"}onclick={() => (coursesView = "home")}>- Início+ {$t("study.library.view_home")}</button><buttontype="button"@@ -726,7 +1658,7 @@aria-selected={coursesView === "catalog"}onclick={() => (coursesView = "catalog")}>- Catálogo+ {$t("study.library.view_catalog")}</button></div>{#if coursesView === "catalog"}@@ -777,6 +1709,33 @@</button>{/if}+ {#if pins.length > 0}+ <nav class="pinned-strip" aria-label={$t("study.library.pinned_strip_aria")}>+ {#each pins as pin (pin.id)}+ <div class="pin-chip-wrap">+ <button+ type="button"+ class="pin-chip"+ onclick={() => openPinnedPath(pin.path)}+ title={pin.path}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor" aria-hidden="true">+ <path d="M14 2l-1.5 1.5L14 5l-2 2v3l-3 3 1.5 1.5L13 11l3 3 1.5-1.5L14 9l2-2 1.5 1.5L19 7z M9 16l-5 5"/>+ </svg>+ <span class="pin-label">{pin.label ?? pin.path}</span>+ </button>+ <button+ type="button"+ class="pin-remove"+ onclick={() => togglePin(pin.path)}+ aria-label={$t("study.library.unpin_action")}+ title={$t("study.library.unpin_action") as string}+ >×</button>+ </div>+ {/each}+ </nav>+ {/if}+{#if mode === "courses" && coursesView === "home"}<section class="home-shelves"><LibraryHomeShelves />@@ -919,7 +1878,31 @@{:else if error}<p class="error">{error}</p>{:else if visibleCourses.length === 0}- <p class="muted">{$t("study.library.empty")}</p>+ {@const enabledRoots = roots.filter((r) => r.enabled).length}+ {#if courses.length === 0 && enabledRoots > 0}+ <div class="empty-with-roots">+ <p>+ {$t(+ enabledRoots === 1+ ? "study.library.empty_with_roots_one"+ : "study.library.empty_with_roots_other",+ { count: enabledRoots },+ )}+ </p>+ <button+ type="button"+ class="empty-card-cta"+ onclick={rescan}+ disabled={rescanning}+ >+ {rescanning+ ? $t("study.library.rescanning")+ : $t("study.library.empty_with_roots_cta")}+ </button>+ </div>+ {:else}+ <p class="muted">{$t("study.library.empty")}</p>+ {/if}{:else}<p class="result-count">{visibleCourses.length} de {courses.length} cursos@@ -977,43 +1960,374 @@</div></div>{:else if mode === "browse"}+ {#snippet emptyBrowse()}+ <div class="empty-browse">+ <div class="empty-browse-head">+ <h2>{$t("study.library.empty_browse_title")}</h2>+ <p>{$t("study.library.empty_browse_description")}</p>+ </div>+ <div class="empty-cards">+ <div class="empty-card">+ <span class="empty-card-icon">+ <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">+ <path d="M3 7v13h18V9h-9l-2-2H3z"/>+ <line x1="12" y1="13" x2="12" y2="17"/>+ <line x1="10" y1="15" x2="14" y2="15"/>+ </svg>+ </span>+ <h3>{$t("study.library.empty_add_folder_title")}</h3>+ <p>{$t("study.library.empty_add_folder_desc")}</p>+ <button type="button" class="empty-card-cta" onclick={addRoot}>+ {$t("study.library.empty_add_folder_cta")} →+ </button>+ </div>+ <div class="empty-card">+ <span class="empty-card-icon">+ <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">+ <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>+ </span>+ <h3>{$t("study.library.empty_telegram_title")}</h3>+ <p>{$t("study.library.empty_telegram_desc")}</p>+ <button type="button" class="empty-card-cta" onclick={() => (mode = "telegram")}>+ {$t("study.library.empty_telegram_cta")} →+ </button>+ </div>+ </div>+ </div>+ {/snippet}+ {#if tabs.length >= 2}+ <nav class="tab-bar" aria-label="Browse tabs">+ {#each tabs as tab, i (i + ":" + tab.path)}+ <div class="tab-wrap" class:active={i === activeTabIndex}>+ <button+ type="button"+ class="tab"+ onclick={() => switchTab(i)}+ title={tab.path || "Raízes"}+ >+ <svg viewBox="0 0 24 24" width="11" height="11" fill="currentColor" aria-hidden="true">+ <path d="M3 7v13h18V9h-9l-2-2H3z" opacity="0.85"/>+ </svg>+ <span class="tab-label">{tabLabel(tab.path)}</span>+ </button>+ <button+ type="button"+ class="tab-close"+ onclick={(e) => { e.stopPropagation(); closeTab(i); }}+ aria-label={$t("study.library.tab_close")}+ title={$t("study.library.tab_close") as string}+ >×</button>+ </div>+ {/each}+ </nav>+ {/if}{#if browseLoading && !browseData}<p class="muted">{$t("study.common.loading")}</p>{:else if !browseData}- <p class="muted">{$t("study.library.browse_empty_roots")}</p>+ {@render emptyBrowse()}{:else}{#if browseData.breadcrumb.length > 0 || !browseData.is_root_list}- <nav class="crumbs" aria-label="breadcrumb">- <button type="button" class="crumb" onclick={() => loadBrowse("")}>- {$t("study.library.browse_breadcrumb_root")}- </button>- {#each browseData.breadcrumb as cr, i (cr.path)}- <span class="crumb-sep" aria-hidden="true">›</span>- {#if i < browseData.breadcrumb.length - 1}- <button type="button" class="crumb" onclick={() => loadBrowse(cr.path)}>- {cr.name}- </button>- {:else}- <span class="crumb-current">{cr.name}</span>+ {@const segments = [+ { path: "", name: $t("study.library.browse_breadcrumb_root") as string },+ ...browseData.breadcrumb,+ ]}+ <div class="crumbs-row">+ {#if addressBarOpen}+ <input+ bind:this={addressBarRef}+ bind:value={addressBarValue}+ class="address-bar"+ type="text"+ spellcheck="false"+ autocomplete="off"+ placeholder={$t("study.library.address_bar_placeholder")}+ onkeydown={(e) => {+ if (e.key === "Enter") submitAddressBar();+ else if (e.key === "Escape") closeAddressBar();+ }}+ onblur={() => closeAddressBar()}+ />+ {:else}+ <button+ type="button"+ class="address-bar-toggle"+ onclick={openAddressBar}+ aria-label={$t("study.library.address_bar_open")}+ title={$t("study.library.address_bar_open") 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" aria-hidden="true">+ <polyline points="16 18 22 12 16 6"/>+ <polyline points="8 6 2 12 8 18"/>+ </svg>+ </button>+ {/if}+ <nav class="crumbs" aria-label="breadcrumb" class:hidden={addressBarOpen}>+ {#each segments as seg, i (i + ":" + seg.path)}+ {@const isLast = i === segments.length - 1}+ {@const parentPath =+ i >= 2 ? browseData.breadcrumb[i - 2].path : ""}+ {@const cached = crumbSiblingsCache.get(parentPath) ?? []}+ {#if isLast}+ <span class="crumb-current">{seg.name}</span>+ {:else if i === 0}+ <button+ type="button"+ class="crumb"+ onclick={() => loadBrowse("")}+ >{seg.name}</button>+ {:else}+ <button+ type="button"+ class="crumb"+ onclick={() => loadBrowse(seg.path)}+ >{seg.name}</button>+ {/if}+ <span class="crumb-chevron-wrap">+ <button+ type="button"+ class="crumb-chevron"+ class:open={openCrumbIndex === i}+ onclick={() => toggleSiblings(i, parentPath)}+ aria-haspopup="menu"+ aria-expanded={openCrumbIndex === i}+ aria-label={$t("study.library.siblings_aria")}+ >+ <svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <polyline points="6 9 12 15 18 9"/>+ </svg>+ </button>+ {#if openCrumbIndex === i}+ <div class="crumb-popover" role="menu">+ {#if crumbSiblingsLoading === parentPath}+ <span class="crumb-popover-empty">…</span>+ {:else if cached.length === 0}+ <span class="crumb-popover-empty">{$t("study.library.siblings_empty")}</span>+ {:else}+ {#each cached as sib (sib.path)}+ {@const isCurrent = sib.path === seg.path}+ <button+ type="button"+ class="crumb-popover-item"+ class:current={isCurrent}+ role="menuitem"+ onclick={() => {+ closeSiblings();+ loadBrowse(sib.path);+ }}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor" aria-hidden="true">+ <path d="M3 7v13h18V9h-9l-2-2H3z" opacity="0.85"/>+ </svg>+ <span class="crumb-popover-name">{sib.name}</span>+ {#if sib.video_count > 0}+ <span class="crumb-popover-count">{sib.video_count}</span>+ {/if}+ </button>+ {/each}+ {/if}+ </div>+ {/if}+ </span>+ {#if !isLast}+ <span class="crumb-sep" aria-hidden="true">›</span>+ {/if}+ {/each}+ </nav>+ {#if !browseData.is_root_list && browsePath.length > 0}+ {@const currentName = browseData.breadcrumb.at(-1)?.name ?? ""}+ {@const isPinned = pins.some((p) => p.path === browsePath)}+ <button+ type="button"+ class="ghost-btn-mini"+ onclick={startCreateFolder}+ disabled={creatingFolder}+ title={$t("study.library.new_folder") as string}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M3 7v13h18V9h-9l-2-2H3z"/>+ <line x1="12" y1="13" x2="12" y2="17"/>+ <line x1="10" y1="15" x2="14" y2="15"/>+ </svg>+ <span>{$t("study.library.new_folder")}</span>+ </button>+ <button+ type="button"+ class="pin-current"+ class:active={isPinned}+ onclick={() => togglePin(browsePath, currentName)}+ title={(isPinned+ ? $t("study.library.unpin_action_title")+ : $t("study.library.pin_action_title")) as string}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill={isPinned ? "currentColor" : "none"} stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M14 2l-1.5 1.5L14 5l-2 2v3l-3 3 1.5 1.5L13 11l3 3 1.5-1.5L14 9l2-2 1.5 1.5L19 7z M9 16l-5 5"/>+ </svg>+ <span>{$t(isPinned ? "study.library.pin_action_active" : "study.library.pin_action")}</span>+ </button>+ {/if}+ <div class="sort-wrap">+ <button+ type="button"+ class="ghost-btn-mini sort-btn"+ onclick={() => (sortMenuOpen = !sortMenuOpen)}+ aria-haspopup="menu"+ aria-expanded={sortMenuOpen}+ title={$t("study.library.browse_sort_label") as string}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M3 6h18M6 12h12M10 18h4"/>+ </svg>+ <span>+ {browseSort === "name_asc"+ ? $t("study.library.browse_sort_name_asc")+ : browseSort === "name_desc"+ ? $t("study.library.browse_sort_name_desc")+ : $t("study.library.browse_sort_size_desc")}+ </span>+ </button>+ {#if sortMenuOpen}+ <div class="sort-menu" role="menu">+ <button+ type="button"+ class="ctx-item"+ class:current={browseSort === "name_asc"}+ role="menuitem"+ onclick={() => setBrowseSort("name_asc")}+ >{$t("study.library.browse_sort_name_asc")}</button>+ <button+ type="button"+ class="ctx-item"+ class:current={browseSort === "name_desc"}+ role="menuitem"+ onclick={() => setBrowseSort("name_desc")}+ >{$t("study.library.browse_sort_name_desc")}</button>+ <button+ type="button"+ class="ctx-item"+ class:current={browseSort === "size_desc"}+ role="menuitem"+ onclick={() => setBrowseSort("size_desc")}+ >{$t("study.library.browse_sort_size_desc")}</button>+ </div>{/if}- {/each}- </nav>+ </div>+ <div class="view-mode-toggle" role="tablist" aria-label={$t("study.library.view_mode_aria")}>+ <button+ type="button"+ class="vm-btn"+ class:active={browseViewMode === "grid"}+ role="tab"+ aria-selected={browseViewMode === "grid"}+ onclick={() => setBrowseViewMode("grid")}+ title={$t("study.library.view_mode_grid") 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" aria-hidden="true">+ <rect x="3" y="3" width="7" height="7"/>+ <rect x="14" y="3" width="7" height="7"/>+ <rect x="3" y="14" width="7" height="7"/>+ <rect x="14" y="14" width="7" height="7"/>+ </svg>+ </button>+ <button+ type="button"+ class="vm-btn"+ class:active={browseViewMode === "list"}+ role="tab"+ aria-selected={browseViewMode === "list"}+ onclick={() => setBrowseViewMode("list")}+ title={$t("study.library.view_mode_list") 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" aria-hidden="true">+ <line x1="3" y1="6" x2="21" y2="6"/>+ <line x1="3" y1="12" x2="21" y2="12"/>+ <line x1="3" y1="18" x2="21" y2="18"/>+ </svg>+ </button>+ </div>+ </div>{/if}- {#if visibleBrowse && (visibleBrowse.folders.length > 0 || visibleBrowse.videos.length > 0 || (visibleBrowse.documents?.length ?? 0) > 0)}- <div class="grid">- {#each visibleBrowse.folders as f (f.path)}- <button type="button" class="card folder-card" onclick={() => loadBrowse(f.path)}>+ {#if visibleBrowse && (visibleBrowse.folders.length > 0 || visibleBrowse.videos.length > 0 || (visibleBrowse.documents?.length ?? 0) > 0) || creatingFolder}+ <div class="grid" class:browse-list={browseViewMode === "list" && mode === "browse"}>+ {#if creatingFolder}+ <div class="card folder-card folder-card-creating"><div class="thumb folder-thumb">- <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">- <path d="M6 14a4 4 0 0 1 4-4h14l6 6h24a4 4 0 0 1 4 4v30a4 4 0 0 1-4 4H10a4 4 0 0 1-4-4V14z" opacity="0.9"/>- <path d="M6 22h52v2H6z" opacity="0.3"/>+ <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true" opacity="0.4">+ <path d="M6 14a4 4 0 0 1 4-4h14l6 6h24a4 4 0 0 1 4 4v30a4 4 0 0 1-4 4H10a4 4 0 0 1-4-4V14z"/></svg><span class="kind-badge">{$t("study.library.folder")}</span></div>+ <div class="meta">+ <input+ bind:this={newFolderRef}+ bind:value={newFolderName}+ class="rename-input"+ type="text"+ placeholder={$t("study.library.new_folder_placeholder")}+ onkeydown={(e) => {+ if (e.key === "Enter") confirmCreateFolder();+ else if (e.key === "Escape") cancelCreateFolder();+ }}+ onblur={() => confirmCreateFolder()}+ />+ </div>+ </div>+ {/if}+ {#each visibleBrowse?.folders ?? [] as f (f.path)}+ {@const previews = (f.preview_videos ?? []).slice(0, 4)}+ {@const isRenaming = renamingPath === f.path}+ {@const isSelected = selectedPaths.has(f.path)}+ <button+ type="button"+ class="card folder-card"+ class:renaming={isRenaming}+ class:selected={isSelected}+ onclick={(e) => handleFolderClick(e, f)}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "folder", path: f.path, name: f.name })}+ >+ <div class="thumb folder-thumb">+ {#if previews.length > 0}+ <div class="folder-mosaic" data-tiles={previews.length}>+ {#each previews as vp (vp)}+ {@const tp = videoThumbCache.get(vp)}+ <span class="folder-mosaic-tile">+ {#if tp}+ <img src={convertFileSrc(tp)} alt="" loading="lazy" />+ {/if}+ </span>+ {/each}+ </div>+ {:else}+ <svg viewBox="0 0 64 64" width="56" height="56" fill="currentColor" aria-hidden="true">+ <path d="M6 14a4 4 0 0 1 4-4h14l6 6h24a4 4 0 0 1 4 4v30a4 4 0 0 1-4 4H10a4 4 0 0 1-4-4V14z" opacity="0.9"/>+ <path d="M6 22h52v2H6z" opacity="0.3"/>+ </svg>+ {/if}+ <span class="kind-badge">{$t("study.library.folder")}</span>+ </div><div class="meta"><div class="title-row">- <span class="title">{f.name}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(f.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(f.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="title">{f.name}</span>+ {/if}</div><div class="sub"><span>{$t("study.library.videos_count", { count: f.video_count })}</span>@@ -1021,19 +2335,59 @@</div></button>{/each}- {#each visibleBrowse.videos as v (v.path)}- <button type="button" class="card video-card" onclick={() => openBrowseVideo(v)}>+ {#each visibleBrowse?.videos ?? [] as v (v.path)}+ {@const isRenaming = renamingPath === v.path}+ {@const isLastWatched = v.path === lastWatchedInFolder}+ {@const isSelected = selectedPaths.has(v.path)}+ <button+ type="button"+ class="card video-card"+ class:renaming={isRenaming}+ class:last-watched={isLastWatched}+ class:selected={isSelected}+ onclick={(e) => handleVideoClick(e, v)}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "video", path: v.path, name: v.name })}+ ><div class="thumb video-thumb">- <svg viewBox="0 0 64 64" width="56" height="56" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">- <rect x="6" y="12" width="52" height="40" rx="4" fill="currentColor" opacity="0.12"/>- <rect x="6" y="12" width="52" height="40" rx="4"/>- <path d="M27 24l14 8-14 8z" fill="currentColor"/>- </svg>+ {#if isLastWatched}+ <span class="last-watched-badge">{$t("study.library.last_watched_label")}</span>+ {/if}+ {#if v.thumbnail_path}+ <img+ class="video-thumb-img"+ src={convertFileSrc(v.thumbnail_path)}+ alt=""+ loading="lazy"+ />+ {:else}+ <svg viewBox="0 0 64 64" width="56" height="56" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="6" y="12" width="52" height="40" rx="4" fill="currentColor" opacity="0.12"/>+ <rect x="6" y="12" width="52" height="40" rx="4"/>+ <path d="M27 24l14 8-14 8z" fill="currentColor"/>+ </svg>+ {/if}<span class="kind-badge">{$t("study.library.video")}</span></div><div class="meta"><div class="title-row">- <span class="title">{v.name}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(v.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(v.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="title">{v.name}</span>+ {/if}</div><div class="sub">{#if v.size}<span>{fmtBytes(v.size)}</span>{/if}@@ -1042,8 +2396,19 @@</div></button>{/each}- {#each (visibleBrowse.documents ?? []) as d (d.path)}- <button type="button" class="card doc-card" data-ext={d.ext} onclick={() => openBrowseDocument(d)}>+ {#each (visibleBrowse?.documents ?? []) as d (d.path)}+ {@const isRenaming = renamingPath === d.path}+ {@const isSelected = selectedPaths.has(d.path)}+ <button+ type="button"+ class="card doc-card"+ class:renaming={isRenaming}+ class:selected={isSelected}+ data-ext={d.ext}+ onclick={(e) => handleDocClick(e, d)}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "doc", path: d.path, name: d.name })}+ ><div class="thumb doc-thumb"><svg viewBox="0 0 64 64" width="52" height="64" fill="none" aria-hidden="true"><path d="M14 4h28l10 10v42a4 4 0 0 1-4 4H14a4 4 0 0 1-4-4V8a4 4 0 0 1 4-4z" fill="currentColor" opacity="0.08"/>@@ -1054,7 +2419,23 @@</div><div class="meta"><div class="title-row">- <span class="title">{d.name}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(d.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(d.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="title">{d.name}</span>+ {/if}</div><div class="sub">{#if d.size}<span>{fmtBytes(d.size)}</span>{/if}@@ -1063,12 +2444,10 @@</button>{/each}</div>+ {:else if browseData.is_root_list}+ {@render emptyBrowse()}{:else}- <p class="muted">- {browseData.is_root_list- ? $t("study.library.browse_empty_roots")- : $t("study.library.browse_empty")}- </p>+ <p class="muted">{$t("study.library.browse_empty")}</p>{/if}{/if}{:else if mode === "telegram"}@@ -1252,6 +2631,126 @@onConfirm={runCleanupForce}/>+<ConfirmDialog+ bind:open={confirmDeleteOpen}+ title={$t("study.library.delete_confirm_title")}+ message={pendingDelete+ ? ($t(+ pendingDelete.kind === "folder"+ ? "study.library.delete_confirm_msg_folder"+ : "study.library.delete_confirm_msg_file",+ { name: pendingDelete.name },+ ) as string)+ : ""}+ confirmLabel={$t("study.library.delete_confirm_btn")}+ variant="danger"+ onConfirm={performDelete}+/>++{#if mode === "browse" && selectedPaths.size > 0}+ <div class="bulk-action-bar" role="region" aria-label="Bulk actions">+ <span class="bulk-count">+ {$t(+ selectedPaths.size === 1+ ? "study.library.selection_count_one"+ : "study.library.selection_count_other",+ { count: selectedPaths.size },+ )}+ </span>+ <button+ type="button"+ class="bulk-btn"+ onclick={clearSelection}+ >{$t("study.library.selection_clear")}</button>+ <button+ type="button"+ class="bulk-btn danger"+ onclick={() => (bulkDeleteOpen = true)}+ >{$t("study.library.selection_delete")}</button>+ </div>+{/if}++<ConfirmDialog+ bind:open={bulkDeleteOpen}+ title={$t("study.library.selection_delete_confirm_title", { count: selectedPaths.size })}+ message={$t("study.library.selection_delete_confirm_msg")}+ confirmLabel={$t("study.library.selection_delete")}+ variant="danger"+ onConfirm={performBulkDelete}+/>++{#if contextMenu}+ <div+ class="ctx-menu"+ role="menu"+ style:left="{contextMenu.x}px"+ style:top="{contextMenu.y}px"+ >+ {#if contextMenu.target.kind === "folder"}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => {+ if (contextMenu) {+ const t = contextMenu.target;+ closeContextMenu();+ void loadBrowse(t.path);+ }+ }}+ >{$t("study.library.ctx_open")}</button>+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => {+ if (contextMenu) {+ const t = contextMenu.target;+ closeContextMenu();+ openInNewTab(t.path);+ }+ }}+ >{$t("study.library.open_in_new_tab")}</button>+ {:else}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => {+ if (contextMenu) {+ const t = contextMenu.target;+ closeContextMenu();+ if (t.kind === "video") {+ const fake = visibleBrowse?.videos.find((vv) => vv.path === t.path);+ if (fake) openBrowseVideo(fake);+ } else if (t.kind === "doc") {+ void openPath(t.path);+ }+ }+ }}+ >{$t("study.library.ctx_open")}</button>+ {/if}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => contextMenu && showInExplorer(contextMenu.target.path)}+ >{$t("study.library.ctx_show_in_explorer")}</button>+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => contextMenu && startRename(contextMenu.target)}+ >{$t("study.library.ctx_rename")}</button>+ <button+ type="button"+ class="ctx-item danger"+ role="menuitem"+ onclick={() => contextMenu && startDelete(contextMenu.target)}+ >{$t("study.library.ctx_delete")}</button>+ </div>+{/if}+{#if rootsOpen}<divclass="drawer-overlay"@@ -1280,7 +2779,7 @@{:else}<ul class="roots-list">{#each roots as r (r.path)}- <li class="root-row" class:disabled={!r.enabled}>+ <li class="root-row" class:disabled={!r.enabled} class:missing={r.exists === false}><label class="root-toggle"><inputtype="checkbox"@@ -1293,6 +2792,11 @@{#if r.is_default}<span class="root-tag">{$t("study.library.roots_default")}</span>{/if}+ {#if r.exists === false}+ <span class="root-tag missing-tag" title={$t("study.library.root_missing_hint") as string}>+ {$t("study.library.root_missing_label")}+ </span>+ {/if}</div>{#if !r.is_default}<button@@ -1794,6 +3298,7 @@color: var(--accent);}.video-thumb {+ overflow: hidden;background:radial-gradient(circle at 50% 50%,@@ -1802,6 +3307,12 @@);color: var(--accent);}+ .video-thumb-img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }.doc-thumb {position: relative;background:@@ -2337,4 +3848,808 @@font-weight: 600;color: var(--secondary);}++ .title-block {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }+ .page-subtitle {+ margin: 0;+ font-size: 13px;+ color: var(--tertiary);+ line-height: 1.4;+ max-width: 60ch;+ }++ .empty-browse {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 28px;+ padding: 56px 24px 24px;+ text-align: center;+ }+ .empty-browse-head {+ display: flex;+ flex-direction: column;+ gap: 8px;+ max-width: 50ch;+ }+ .empty-browse-head h2 {+ margin: 0;+ font-size: 22px;+ font-weight: 600;+ letter-spacing: -0.3px;+ color: var(--secondary);+ }+ .empty-browse-head p {+ margin: 0;+ font-size: 14px;+ color: var(--tertiary);+ line-height: 1.5;+ }+ .empty-cards {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 16px;+ width: 100%;+ max-width: 600px;+ }+ .empty-card {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 10px;+ padding: 22px 20px;+ border-radius: 12px;+ border: 1px solid var(--content-border);+ background: var(--surface);+ text-align: left;+ transition: border-color 150ms ease, transform 150ms ease;+ }+ .empty-card:hover {+ border-color: color-mix(in oklab, var(--accent) 60%, var(--content-border));+ transform: translateY(-2px);+ }+ .empty-card-icon {+ width: 40px;+ height: 40px;+ border-radius: 10px;+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ display: grid;+ place-items: center;+ }+ .empty-card h3 {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+ color: var(--secondary);+ }+ .empty-card > p {+ margin: 0;+ font-size: 13px;+ color: var(--tertiary);+ line-height: 1.45;+ flex: 1;+ }+ .empty-card-cta {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-top: 4px;+ 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;+ transition: background 150ms ease;+ }+ .empty-card-cta:hover {+ background: color-mix(in oklab, var(--accent) 88%, black);+ }+ .empty-card-cta:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ @media (prefers-reduced-motion: reduce) {+ .empty-card,+ .empty-card-cta {+ transition: none;+ }+ .empty-card:hover {+ transform: none;+ }+ }++ .pinned-strip {+ display: flex;+ flex-wrap: nowrap;+ overflow-x: auto;+ gap: 6px;+ padding: 4px 2px;+ scrollbar-width: thin;+ }+ .pin-chip-wrap {+ display: inline-flex;+ align-items: stretch;+ flex-shrink: 0;+ border-radius: 999px;+ border: 1px solid color-mix(in oklab, var(--accent) 30%, transparent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ transition: background 150ms ease, border-color 150ms ease;+ }+ .pin-chip-wrap:hover {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ border-color: color-mix(in oklab, var(--accent) 50%, transparent);+ }+ .pin-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 10px 5px 9px;+ border: 0;+ background: transparent;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ border-radius: 999px 0 0 999px;+ max-width: 240px;+ }+ .pin-chip svg {+ color: var(--accent);+ flex-shrink: 0;+ }+ .pin-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .pin-remove {+ border: 0;+ background: transparent;+ color: color-mix(in oklab, currentColor 50%, transparent);+ font-family: inherit;+ font-size: 14px;+ line-height: 1;+ padding: 0 9px;+ cursor: pointer;+ border-radius: 0 999px 999px 0;+ border-left: 1px solid color-mix(in oklab, var(--accent) 18%, transparent);+ transition: color 150ms ease, background 150ms ease;+ }+ .pin-remove:hover {+ color: var(--error, #dc2626);+ background: color-mix(in oklab, var(--error, #dc2626) 12%, transparent);+ }++ .crumbs-row {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+ }+ .crumbs-row .crumbs {+ flex: 1 1 auto;+ min-width: 0;+ }+ .pin-current {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 4px 10px;+ border-radius: 999px;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ background: transparent;+ color: var(--tertiary);+ font-family: inherit;+ font-size: 11px;+ font-weight: 500;+ cursor: pointer;+ flex-shrink: 0;+ transition: border-color 150ms ease, color 150ms ease, background 150ms ease;+ }+ .pin-current:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .pin-current.active {+ border-color: color-mix(in oklab, var(--accent) 60%, transparent);+ background: color-mix(in oklab, var(--accent) 12%, transparent);+ color: var(--accent);+ }++ .crumb-chevron-wrap {+ position: relative;+ display: inline-flex;+ align-items: center;+ }+ .crumb-chevron {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 18px;+ height: 18px;+ margin-left: 1px;+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 4px;+ color: color-mix(in oklab, currentColor 45%, transparent);+ cursor: pointer;+ transition: color 120ms ease, background 120ms ease, transform 150ms ease;+ }+ .crumb-chevron:hover {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .crumb-chevron.open {+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ transform: rotate(180deg);+ }+ .crumb-popover {+ position: absolute;+ top: calc(100% + 4px);+ left: 0;+ z-index: 50;+ min-width: 200px;+ max-width: 320px;+ max-height: 300px;+ overflow-y: auto;+ padding: 4px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 8px;+ box-shadow: 0 8px 24px color-mix(in oklab, black 18%, transparent);+ display: flex;+ flex-direction: column;+ gap: 1px;+ scrollbar-width: thin;+ }+ .crumb-popover-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ background: transparent;+ border: 0;+ border-radius: 5px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease;+ }+ .crumb-popover-item:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .crumb-popover-item.current {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ color: var(--accent);+ font-weight: 600;+ }+ .crumb-popover-item svg {+ color: color-mix(in oklab, var(--accent) 70%, currentColor);+ flex-shrink: 0;+ }+ .crumb-popover-name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .crumb-popover-count {+ font-family: var(--font-mono, "IBM Plex Mono", monospace);+ font-size: 10px;+ color: var(--tertiary);+ font-variant-numeric: tabular-nums;+ }+ .crumb-popover-empty {+ padding: 8px 10px;+ color: var(--tertiary);+ font-size: 12px;+ }+ @media (prefers-reduced-motion: reduce) {+ .crumb-chevron,+ .crumb-chevron.open {+ transition: none;+ transform: none;+ }+ }++ .view-mode-toggle {+ display: inline-flex;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 7px;+ padding: 1px;+ background: color-mix(in oklab, var(--content-bg) 80%, transparent);+ flex-shrink: 0;+ }+ .vm-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 26px;+ background: transparent;+ border: 0;+ border-radius: 5px;+ color: color-mix(in oklab, currentColor 55%, transparent);+ cursor: pointer;+ transition: background 120ms ease, color 120ms ease;+ }+ .vm-btn:hover:not(.active) {+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ color: var(--secondary);+ }+ .vm-btn.active {+ background: var(--accent);+ color: var(--on-accent, white);+ }++ .grid.browse-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .grid.browse-list .card {+ flex-direction: row;+ align-items: center;+ width: 100%;+ padding: 6px;+ border-radius: 8px;+ transition: background 150ms ease;+ }+ .grid.browse-list .card:hover {+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .grid.browse-list .thumb {+ width: 160px;+ flex-shrink: 0;+ border-radius: 6px;+ }+ .grid.browse-list .meta {+ flex: 1;+ min-width: 0;+ padding: 0 12px;+ }+ .grid.browse-list .video-thumb,+ .grid.browse-list .folder-thumb,+ .grid.browse-list .doc-thumb {+ aspect-ratio: 16 / 9;+ }+ .grid.browse-list .kind-badge {+ top: 4px;+ left: 4px;+ font-size: 9px;+ padding: 0.1rem 0.4rem;+ }++ .folder-thumb {+ overflow: hidden;+ }+ .folder-mosaic {+ width: 100%;+ height: 100%;+ display: grid;+ gap: 1px;+ background: color-mix(in oklab, var(--accent) 8%, var(--input-bg));+ }+ .folder-mosaic[data-tiles="1"] {+ grid-template-columns: 1fr;+ grid-template-rows: 1fr;+ }+ .folder-mosaic[data-tiles="2"] {+ grid-template-columns: 1fr 1fr;+ grid-template-rows: 1fr;+ }+ .folder-mosaic[data-tiles="3"] {+ grid-template-columns: 1fr 1fr;+ grid-template-rows: 1fr 1fr;+ }+ .folder-mosaic[data-tiles="3"] .folder-mosaic-tile:first-child {+ grid-row: span 2;+ }+ .folder-mosaic[data-tiles="4"] {+ grid-template-columns: 1fr 1fr;+ grid-template-rows: 1fr 1fr;+ }+ .folder-mosaic-tile {+ position: relative;+ overflow: hidden;+ background: color-mix(in oklab, var(--accent) 12%, var(--input-bg));+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .folder-mosaic-tile img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }++ .address-bar {+ flex: 1 1 auto;+ min-width: 0;+ padding: 5px 10px;+ border: 1px solid color-mix(in oklab, var(--accent) 60%, transparent);+ border-radius: 7px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: ui-monospace, "IBM Plex Mono", monospace;+ font-size: 12px;+ outline: none;+ }+ .address-bar:focus {+ border-color: var(--accent);+ box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent);+ }+ .address-bar-toggle {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 26px;+ height: 26px;+ padding: 0;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 6px;+ color: color-mix(in oklab, currentColor 55%, transparent);+ cursor: pointer;+ flex-shrink: 0;+ transition: border-color 120ms ease, color 120ms ease;+ }+ .address-bar-toggle:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .crumbs.hidden {+ display: none;+ }++ .ghost-btn-mini {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 4px 10px;+ border-radius: 999px;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ background: transparent;+ color: var(--tertiary);+ font-family: inherit;+ font-size: 11px;+ font-weight: 500;+ cursor: pointer;+ flex-shrink: 0;+ transition: border-color 150ms ease, color 150ms ease, background 150ms ease;+ }+ .ghost-btn-mini:hover:not(:disabled) {+ border-color: var(--accent);+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .ghost-btn-mini:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .rename-input {+ width: 100%;+ padding: 2px 4px;+ border: 1px solid var(--accent);+ border-radius: 4px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: inherit;+ font-size: inherit;+ outline: none;+ box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent);+ }++ .card.renaming {+ cursor: default;+ }+ .card.renaming:hover {+ transform: none;+ }++ .folder-card-creating {+ border: 1px dashed color-mix(in oklab, var(--accent) 50%, transparent);+ border-radius: 10px;+ padding: 4px;+ }++ .ctx-menu {+ position: fixed;+ z-index: 200;+ min-width: 180px;+ max-width: 280px;+ padding: 4px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 8px;+ box-shadow: 0 8px 28px color-mix(in oklab, black 22%, transparent);+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .ctx-item {+ display: flex;+ align-items: center;+ padding: 7px 10px;+ background: transparent;+ border: 0;+ border-radius: 5px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease, color 120ms ease;+ }+ .ctx-item:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .ctx-item.danger {+ color: var(--error, #dc2626);+ }+ .ctx-item.danger:hover {+ background: color-mix(in oklab, var(--error, #dc2626) 12%, transparent);+ }++ .video-card.last-watched .video-thumb {+ box-shadow: 0 0 0 2px var(--accent), 0 0 0 4px color-mix(in oklab, var(--accent) 30%, transparent);+ }+ .last-watched-badge {+ position: absolute;+ top: 8px;+ right: 8px;+ z-index: 2;+ padding: 2px 8px;+ border-radius: 999px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.02em;+ box-shadow: 0 2px 6px color-mix(in oklab, black 25%, transparent);+ }++ .doc-card[data-ext="pdf"] .doc-thumb {+ background: linear-gradient(+ 135deg,+ color-mix(in oklab, oklch(0.6 0.2 30) 14%, var(--input-bg)),+ color-mix(in oklab, oklch(0.5 0.18 25) 6%, var(--input-bg))+ );+ color: oklch(0.7 0.18 28);+ }+ .doc-card[data-ext="epub"] .doc-thumb {+ background: linear-gradient(+ 135deg,+ color-mix(in oklab, oklch(0.65 0.18 145) 14%, var(--input-bg)),+ color-mix(in oklab, oklch(0.55 0.16 150) 6%, var(--input-bg))+ );+ color: oklch(0.7 0.16 145);+ }+ .doc-card[data-ext="cbz"] .doc-thumb,+ .doc-card[data-ext="cbr"] .doc-thumb {+ background: linear-gradient(+ 135deg,+ color-mix(in oklab, oklch(0.6 0.2 300) 14%, var(--input-bg)),+ color-mix(in oklab, oklch(0.5 0.18 305) 6%, var(--input-bg))+ );+ color: oklch(0.7 0.18 300);+ }+ .doc-card[data-ext="mobi"] .doc-thumb,+ .doc-card[data-ext="azw3"] .doc-thumb {+ background: linear-gradient(+ 135deg,+ color-mix(in oklab, oklch(0.7 0.16 75) 14%, var(--input-bg)),+ color-mix(in oklab, oklch(0.6 0.14 80) 6%, var(--input-bg))+ );+ color: oklch(0.72 0.16 75);+ }+ .doc-card[data-ext="djvu"] .doc-thumb {+ background: linear-gradient(+ 135deg,+ color-mix(in oklab, oklch(0.6 0.16 240) 14%, var(--input-bg)),+ color-mix(in oklab, oklch(0.5 0.14 245) 6%, var(--input-bg))+ );+ color: oklch(0.7 0.16 240);+ }++ .empty-with-roots {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 16px;+ padding: 48px 24px 24px;+ text-align: center;+ max-width: 50ch;+ margin: 0 auto;+ }+ .empty-with-roots p {+ margin: 0;+ color: var(--secondary);+ font-size: 14px;+ line-height: 1.5;+ }++ .root-row.missing {+ background: color-mix(in oklab, var(--warning, #d97706) 8%, transparent);+ border-radius: 6px;+ }+ .root-row.missing .root-path {+ color: color-mix(in oklab, var(--warning, #d97706) 80%, currentColor);+ text-decoration: line-through;+ text-decoration-color: color-mix(in oklab, currentColor 40%, transparent);+ }+ .missing-tag {+ background: color-mix(in oklab, var(--warning, #d97706) 18%, transparent) !important;+ color: var(--warning, #d97706) !important;+ border-color: color-mix(in oklab, var(--warning, #d97706) 40%, transparent) !important;+ cursor: help;+ }++ .sort-wrap {+ position: relative;+ display: inline-flex;+ flex-shrink: 0;+ }+ .sort-menu {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ z-index: 60;+ min-width: 160px;+ padding: 4px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 8px;+ box-shadow: 0 8px 24px color-mix(in oklab, black 22%, transparent);+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .ctx-item.current {+ background: color-mix(in oklab, var(--accent) 14%, transparent);+ color: var(--accent);+ font-weight: 600;+ }++ .card.selected {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .card.selected.last-watched .video-thumb {+ box-shadow: 0 0 0 2px var(--accent);+ }++ .tab-bar {+ display: flex;+ flex-wrap: nowrap;+ overflow-x: auto;+ gap: 2px;+ padding: 0;+ margin: 0;+ border-bottom: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ scrollbar-width: thin;+ }+ .tab-wrap {+ display: inline-flex;+ align-items: stretch;+ flex-shrink: 0;+ border: 1px solid transparent;+ border-bottom: 0;+ border-radius: 7px 7px 0 0;+ background: transparent;+ transition: background 120ms ease, border-color 120ms ease;+ }+ .tab-wrap:hover:not(.active) {+ background: color-mix(in oklab, var(--accent) 5%, transparent);+ }+ .tab-wrap.active {+ background: var(--surface, var(--button-elevated));+ border-color: color-mix(in oklab, var(--content-border) 60%, transparent);+ }+ .tab {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 4px 6px 10px;+ background: transparent;+ border: 0;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ max-width: 200px;+ }+ .tab svg {+ color: var(--accent);+ flex-shrink: 0;+ }+ .tab-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .tab-wrap.active .tab {+ color: var(--text, var(--secondary));+ font-weight: 500;+ }+ .tab-close {+ background: transparent;+ border: 0;+ color: color-mix(in oklab, currentColor 50%, transparent);+ font-family: inherit;+ font-size: 14px;+ line-height: 1;+ padding: 0 8px;+ cursor: pointer;+ border-radius: 4px;+ transition: color 120ms ease, background 120ms ease;+ }+ .tab-close:hover {+ color: var(--error, #dc2626);+ background: color-mix(in oklab, var(--error, #dc2626) 12%, transparent);+ }++ .bulk-action-bar {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 90;+ display: inline-flex;+ align-items: center;+ gap: 12px;+ padding: 10px 18px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 999px;+ box-shadow: 0 8px 28px color-mix(in oklab, black 30%, transparent);+ }+ .bulk-count {+ font-size: 13px;+ font-weight: 600;+ color: var(--secondary);+ }+ .bulk-btn {+ padding: 6px 14px;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 999px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: border-color 120ms ease, color 120ms ease, background 120ms ease;+ }+ .bulk-btn:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .bulk-btn.danger {+ background: var(--error, #dc2626);+ border-color: var(--error, #dc2626);+ color: white;+ }+ .bulk-btn.danger:hover {+ background: color-mix(in oklab, var(--error, #dc2626) 88%, black);+ color: white;+ }</style>diff --git a/src/routes/study/music/+layout.svelte b/src/routes/study/music/+layout.sveltenew file mode 100644index 00000000..c7befff1--- /dev/null+++ b/src/routes/study/music/+layout.svelte@@ -0,0 +1,193 @@+<script lang="ts">+ 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 MusicSidebar from "$lib/study-music-components/MusicSidebar.svelte";+ import PlayerBar from "$lib/study-music-components/PlayerBar.svelte";++ let { children } = $props();++ const accentBg = $derived.by(() => {+ if (!musicTheme.useDominant) return null;+ const c = musicPlayer.dominantColor;+ if (!c) return null;+ 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)`,+ };+ });++ const themeAccentOverride = $derived(musicTheme.effectiveAccent);++ function exitFullscreen() {+ if (typeof window === "undefined") {+ goto("/study/library");+ return;+ }+ let target = "/study/library";+ try {+ const stored = sessionStorage.getItem("study.music.return_url");+ if (stored && !stored.startsWith("/study/music")) {+ target = stored;+ }+ } catch {+ /* ignore */+ }+ goto(target);+ }++ $effect(() => {+ if (typeof document === "undefined") return;+ function onKey(e: KeyboardEvent) {+ if (e.key !== "Escape") return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.isContentEditable)+ ) {+ return;+ }+ if (musicUI.addToPlaylistTrack !== null) return;+ if (musicUI.rightbarTab !== null) return;+ if (musicUI.rootsOpen) return;+ if (musicUI.equalizerOpen) return;+ if (musicUI.lastfmOpen) return;+ if (musicUI.themeOpen) return;+ if (musicUI.discordOpen) return;+ if (musicUI.youtubeOpen) return;+ 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 !== "/study/music") {+ goto("/study/music");+ } else {+ exitFullscreen();+ }+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });+</script>++<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'}+ 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">+ {@render children()}+ </div>+ </main>+ <div class="music-player">+ <PlayerBar />+ </div>+</div>++<style>+ .music-shell {+ position: fixed;+ inset: 0;+ z-index: 90;+ display: grid;+ grid-template-columns: 240px 1fr;+ grid-template-rows: 1fr 80px;+ grid-template-areas:+ "side main"+ "player player";+ background:+ radial-gradient(ellipse at 30% 0%, var(--music-accent-mid, transparent) 0%, transparent 60%),+ radial-gradient(ellipse at 80% 100%, var(--music-accent-soft, transparent) 0%, transparent 70%),+ var(--primary);+ color: var(--secondary);+ transition: background 600ms ease;+ }+ .music-shell > :global(aside.music-sidebar) {+ grid-area: side;+ }+ .music-main {+ grid-area: main;+ position: relative;+ overflow-y: auto;+ overflow-x: hidden;+ scrollbar-width: thin;+ }+ .music-content {+ padding: 24px 32px 32px;+ max-width: 1600px;+ margin-inline: auto;+ }+ .music-player {+ grid-area: player;+ border-top: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ }+ .exit-btn {+ position: absolute;+ top: 14px;+ right: 18px;+ z-index: 5;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 6px 10px;+ background: color-mix(in oklab, var(--button) 60%, transparent);+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 999px;+ color: var(--tertiary);+ font-family: inherit;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .exit-btn:hover {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, var(--button));+ }+ .esc-hint {+ font-family: ui-monospace, monospace;+ font-size: 10px;+ padding: 2px 6px;+ background: color-mix(in oklab, var(--content-border) 50%, transparent);+ border-radius: 4px;+ color: var(--secondary);+ }+ @media (max-width: 760px) {+ .music-shell {+ grid-template-columns: 1fr;+ grid-template-areas:+ "main"+ "player";+ }+ .music-shell > :global(aside.music-sidebar) {+ display: none;+ }+ }+</style>diff --git a/src/routes/study/music/+page.svelte b/src/routes/study/music/+page.sveltenew file mode 100644index 00000000..8eb5b82a--- /dev/null+++ b/src/routes/study/music/+page.svelte@@ -0,0 +1,1112 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { playlistsStore, type Playlist } from "$lib/study-music/playlists-store.svelte";+ import {+ spotifyStore,+ type SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import {+ soundcloudStore,+ 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";++ type RootEntry = { path: string; enabled: boolean; exists: boolean };+ type Album = {+ name: string;+ artist: string | null;+ track_count: number;+ total_duration_ms: number;+ year: number | null;+ cover_path: string | null;+ };+ type Artist = { name: string; album_count: number; track_count: number };++ let roots = $state<RootEntry[]>([]);+ let allAlbums = $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;+ }+ }++ 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);+ }+ }++ async function runScan() {+ if (scanning) return;+ scanning = true;+ scanMsg = "";+ 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);+ }+ }++ async function playHero() {+ if (!heroAlbum) return;+ 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);+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ 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) {+ const params = new URLSearchParams({ name: album.name });+ if (album.artist) params.set("artist", album.artist);+ goto(`/study/music/album/by-name?${params.toString()}`);+ }++ function openArtist(name: string) {+ goto(`/study/music/artist/by-name?name=${encodeURIComponent(name)}`);+ }++ 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;+ }+ }++ onMount(async () => {+ void loadAll();+ 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();+ }+ });++ 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);+ }+ }++ 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)");+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ 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 ||+ spotifyStore.playlists.length > 0 ||+ spotifyStore.recentlyPlayed.length > 0 ||+ spotifyStore.topArtists.length > 0),+ );+ const hasSoundcloudContent = $derived(+ soundcloudStore.isLoggedIn &&+ (soundcloudStore.likedTracks.length > 0 ||+ 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>++<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>+ </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}++ {#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>+ <h3 class="artist-name">{a.name}</h3>+ </div>+ {/each}+ </div>+ </section>+ {/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>+ {/if}+ </div>+ {/each}+ </div>+ </section>+ {/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>+ </div>+ {/each}+ </div>+ </section>+ {/if}+ {/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}++ {#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}+</section>++<style>+ .music-home {+ display: flex;+ flex-direction: column;+ gap: 32px;+ color: rgba(255, 255, 255, 0.95);+ }+ .page-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+ }+ .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 {+ 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);+ }+ .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;+ display: grid;+ place-items: center;+ transition: background 200ms ease;+ }+ .hero-fav:hover {+ background: rgba(255, 255, 255, 0.2);+ }+ .hero-fav.on {+ color: var(--accent);+ }++ .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;+ }+ .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;+ overflow-x: auto;+ overflow-y: visible;+ padding: 8px 4px 24px;+ scroll-behavior: smooth;+ scrollbar-width: none;+ }+ .h-scroll::-webkit-scrollbar { display: none; }++ .artist-card {+ flex: 0 0 144px;+ cursor: pointer;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 0;+ text-align: center;+ }+ .artist-circle {+ aspect-ratio: 1 / 1;+ border-radius: 50%;+ background: rgba(40, 40, 40, 0.8);+ overflow: hidden;+ margin: 0 auto 16px;+ transition: transform 700ms ease;+ position: relative;+ }+ .artist-card:hover .artist-circle {+ transform: scale(1.04);+ }+ .artist-circle 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 {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ font-size: 48px;+ font-weight: 800;+ }+ .artist-name {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ 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;+ }+ .album-card-cover {+ position: relative;+ aspect-ratio: 1 / 1;+ border-radius: 16px;+ background: rgba(40, 40, 40, 0.8);+ 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);+ }+ .album-card-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ }+ .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);+ }+ .album-card-title {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .album-card-sub {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }++ .muted {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }++ @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 {+ 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;+ }+ }+</style>diff --git a/src/routes/study/music/activity/+page.svelte b/src/routes/study/music/activity/+page.sveltenew file mode 100644index 00000000..279cc870--- /dev/null+++ b/src/routes/study/music/activity/+page.svelte@@ -0,0 +1,378 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { fmtDuration, fmtDurationLong } from "$lib/study-music/format";+ import {+ musicPlayer,+ type MusicTrack,+ } from "$lib/study-music/player-store.svelte";+ import CoverImage from "$lib/study-music-components/CoverImage.svelte";++ type Period = "7d" | "30d" | "90d" | "1y" | "all";++ type Summary = {+ period: string;+ total_plays: number;+ total_ms: number;+ unique_tracks: number;+ };++ type TopTrack = {+ id: number;+ title: string | null;+ artist: string | null;+ album: string | null;+ cover_path: string | null;+ duration_ms: number | null;+ plays: number;+ played_ms: number;+ };++ type TopArtist = {+ name: string;+ plays: number;+ played_ms: number;+ track_count: number;+ };++ type TopAlbum = {+ name: string;+ artist: string | null;+ plays: number;+ played_ms: number;+ cover_path: string | null;+ };++ type TopGenre = {+ name: string;+ plays: number;+ played_ms: number;+ };++ let period = $state<Period>("30d");+ let loading = $state(true);+ let summary = $state<Summary | null>(null);+ let tracks = $state<TopTrack[]>([]);+ let artists = $state<TopArtist[]>([]);+ let albums = $state<TopAlbum[]>([]);+ let genres = $state<TopGenre[]>([]);++ const PERIODS: { id: Period; labelKey: string }[] = [+ { id: "7d", labelKey: "study.music.period_7d" },+ { id: "30d", labelKey: "study.music.period_30d" },+ { id: "90d", labelKey: "study.music.period_90d" },+ { id: "1y", labelKey: "study.music.period_1y" },+ { id: "all", labelKey: "study.music.period_all" },+ ];++ async function load() {+ loading = true;+ try {+ const [s, tr, ar, al, ge] = await Promise.all([+ pluginInvoke<Summary>("study", "study:music:activity:summary", { period }),+ pluginInvoke<{ tracks: TopTrack[] }>("study", "study:music:activity:top_tracks", { period, limit: 10 }),+ pluginInvoke<{ artists: TopArtist[] }>("study", "study:music:activity:top_artists", { period, limit: 10 }),+ pluginInvoke<{ albums: TopAlbum[] }>("study", "study:music:activity:top_albums", { period, limit: 10 }),+ pluginInvoke<{ genres: TopGenre[] }>("study", "study:music:activity:top_genres", { period, limit: 10 }),+ ]);+ summary = s;+ tracks = tr.tracks ?? [];+ artists = ar.artists ?? [];+ albums = al.albums ?? [];+ genres = ge.genres ?? [];+ } finally {+ loading = false;+ }+ }++ async function playTrack(t: TopTrack) {+ try {+ const res = await pluginInvoke<{ track: MusicTrack }>(+ "study",+ "study:music:tracks:get",+ { id: t.id },+ );+ if (res.track) {+ await musicPlayer.play(res.track, [res.track]);+ }+ } catch {+ /* ignore */+ }+ }++ $effect(() => {+ void period;+ void load();+ });++ onMount(() => {+ void load();+ });+</script>++<section class="page">+ <header class="head">+ <h1>{$t("study.music.activity_title")}</h1>+ <p class="sub">{$t("study.music.activity_subtitle")}</p>+ </header>++ <div class="period-tabs" role="tablist">+ {#each PERIODS as p (p.id)}+ <button+ type="button"+ role="tab"+ class="period-tab"+ class:active={period === p.id}+ aria-selected={period === p.id}+ onclick={() => (period = p.id)}+ >{$t(p.labelKey)}</button>+ {/each}+ </div>++ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if summary && summary.total_plays === 0}+ <div class="empty">+ <p>{$t("study.music.no_activity")}</p>+ </div>+ {:else if summary}+ <div class="stats">+ <div class="stat">+ <span class="stat-label">{$t("study.music.total_plays")}</span>+ <span class="stat-value">{summary.total_plays}</span>+ </div>+ <div class="stat">+ <span class="stat-label">{$t("study.music.total_listened")}</span>+ <span class="stat-value">{fmtDurationLong(summary.total_ms)}</span>+ </div>+ <div class="stat">+ <span class="stat-label">{$t("study.music.unique_tracks")}</span>+ <span class="stat-value">{summary.unique_tracks}</span>+ </div>+ </div>++ <section class="block">+ <h2>{$t("study.music.top_tracks")}</h2>+ {#if tracks.length === 0}+ <p class="muted">{$t("study.music.empty")}</p>+ {:else}+ <ol class="track-rank">+ {#each tracks as tr, i (tr.id)}+ <li>+ <button type="button" class="rank-row" onclick={() => playTrack(tr)}>+ <span class="rank">{i + 1}</span>+ <CoverImage src={tr.cover_path} alt={tr.title ?? ""} size={36} rounded="sm" trackId={tr.id} />+ <span class="info">+ <span class="title">{tr.title ?? "—"}</span>+ {#if tr.artist}<span class="artist">{tr.artist}</span>{/if}+ </span>+ <span class="metric">{tr.plays} · {fmtDuration(tr.played_ms)}</span>+ </button>+ </li>+ {/each}+ </ol>+ {/if}+ </section>++ <section class="block">+ <h2>{$t("study.music.top_artists")}</h2>+ {#if artists.length === 0}+ <p class="muted">{$t("study.music.empty")}</p>+ {:else}+ <ol class="rank-list">+ {#each artists as a, i (a.name + ":" + i)}+ <li class="rank-row plain">+ <span class="rank">{i + 1}</span>+ <span class="info">+ <span class="title">{a.name}</span>+ <span class="artist">{$t("study.music.tracks_count", { count: a.track_count })}</span>+ </span>+ <span class="metric">{a.plays} · {fmtDuration(a.played_ms)}</span>+ </li>+ {/each}+ </ol>+ {/if}+ </section>++ <section class="block">+ <h2>{$t("study.music.top_albums")}</h2>+ {#if albums.length === 0}+ <p class="muted">{$t("study.music.empty")}</p>+ {:else}+ <ol class="rank-list">+ {#each albums as a, i (a.name + ":" + i)}+ <li class="rank-row plain">+ <span class="rank">{i + 1}</span>+ <CoverImage src={a.cover_path} alt={a.name} size={36} rounded="sm" />+ <span class="info">+ <span class="title">{a.name}</span>+ {#if a.artist}<span class="artist">{a.artist}</span>{/if}+ </span>+ <span class="metric">{a.plays} · {fmtDuration(a.played_ms)}</span>+ </li>+ {/each}+ </ol>+ {/if}+ </section>++ <section class="block">+ <h2>{$t("study.music.top_genres")}</h2>+ {#if genres.length === 0}+ <p class="muted">{$t("study.music.empty")}</p>+ {:else}+ <ol class="rank-list">+ {#each genres as g, i (g.name + ":" + i)}+ <li class="rank-row plain">+ <span class="rank">{i + 1}</span>+ <span class="info">+ <span class="title">{g.name}</span>+ </span>+ <span class="metric">{g.plays} · {fmtDuration(g.played_ms)}</span>+ </li>+ {/each}+ </ol>+ {/if}+ </section>+ {/if}+</section>++<style>+ .page {+ display: flex;+ flex-direction: column;+ gap: 28px;+ padding-bottom: 40px;+ }+ .head h1 {+ margin: 0 0 4px;+ font-size: 28px;+ font-weight: 800;+ letter-spacing: -0.02em;+ }+ .sub {+ margin: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .period-tabs {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+ }+ .period-tab {+ padding: 6px 14px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.65);+ font-family: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ }+ .period-tab:hover {+ color: rgba(255, 255, 255, 0.95);+ border-color: rgba(255, 255, 255, 0.25);+ }+ .period-tab.active {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent, white);+ }+ .stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));+ gap: 12px;+ }+ .stat {+ padding: 16px 18px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.05);+ border-radius: 10px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .stat-label {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.5);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ }+ .stat-value {+ font-size: 22px;+ font-weight: 700;+ color: rgba(255, 255, 255, 0.95);+ }+ .block h2 {+ margin: 0 0 12px;+ font-size: 16px;+ font-weight: 700;+ }+ .rank-list,+ .track-rank {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .rank-row {+ display: flex;+ align-items: center;+ gap: 12px;+ width: 100%;+ padding: 8px 12px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.95);+ text-align: left;+ cursor: pointer;+ font-family: inherit;+ }+ .rank-row.plain { cursor: default; }+ .rank-row:hover:not(.plain) {+ background: rgba(255, 255, 255, 0.05);+ }+ .rank {+ flex-shrink: 0;+ width: 28px;+ text-align: center;+ color: rgba(255, 255, 255, 0.4);+ font-size: 14px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ }+ .info {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ .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;+ }+ .metric {+ flex-shrink: 0;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ font-variant-numeric: tabular-nums;+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }+ .empty { padding: 80px 0; text-align: center; color: rgba(255, 255, 255, 0.5); }+</style>diff --git a/src/routes/study/music/album/by-name/+page.svelte b/src/routes/study/music/album/by-name/+page.sveltenew file mode 100644index 00000000..5fe018df--- /dev/null+++ b/src/routes/study/music/album/by-name/+page.svelte@@ -0,0 +1,87 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import AlbumHero from "$lib/study-music-components/AlbumHero.svelte";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";+ import type { MusicTrack } from "$lib/study-music/player-store.svelte";++ type Album = {+ name: string;+ artist: string | null;+ track_count: number;+ total_duration_ms: number;+ cover_path: string | null;+ year: number | null;+ };++ const albumName = $derived($page.url.searchParams.get("name") ?? "");+ const artistName = $derived($page.url.searchParams.get("artist") ?? "");++ let album = $state<Album | null>(null);+ let tracks = $state<MusicTrack[]>([]);+ let loading = $state(true);+ let error = $state<string | null>(null);++ async function load() {+ if (!albumName) {+ error = "Álbum não especificado.";+ loading = false;+ return;+ }+ loading = true;+ error = null;+ try {+ const args: { name: string; artist?: string } = { name: albumName };+ if (artistName) args.artist = artistName;+ const res = await pluginInvoke<{ album: Album; tracks: MusicTrack[] }>(+ "study",+ "study:music:albums:get",+ args,+ );+ album = res.album;+ tracks = res.tracks ?? [];+ } catch (e) {+ error = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ void load();+ });++ $effect(() => {+ void albumName;+ void artistName;+ void load();+ });+</script>++<section class="album-page">+ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if error || !album}+ <p class="error">{error ?? "Álbum não encontrado."}</p>+ {:else}+ <AlbumHero {album} {tracks} />+ {#if tracks.length === 0}+ <p class="muted">{$t("study.music.empty_album")}</p>+ {:else}+ <ul class="track-list">+ {#each tracks as track, i (track.id)}+ <TrackRow {track} queue={tracks} index={i} showNumber showCover />+ {/each}+ </ul>+ {/if}+ {/if}+</section>++<style>+ .album-page { display: flex; flex-direction: column; gap: 12px; }+ .track-list { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }+ .muted { color: var(--tertiary); font-size: 13px; }+ .error { color: var(--error, #dc2626); font-size: 13px; }+</style>diff --git a/src/routes/study/music/albums/+page.svelte b/src/routes/study/music/albums/+page.sveltenew file mode 100644index 00000000..9c037b7e--- /dev/null+++ b/src/routes/study/music/albums/+page.svelte@@ -0,0 +1,387 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { colorFromString } from "$lib/study-music/format";+ import { spotifyStore } from "$lib/study-music/spotify-store.svelte";++ type Album = {+ name: string;+ artist: string | null;+ track_count: number;+ total_duration_ms: number;+ year: number | null;+ cover_path: string | null;+ };++ type SortKey = "added" | "name" | "year" | "track_count";++ let albums = $state<Album[]>([]);+ let loading = $state(true);+ let q = $state("");+ let sortKey = $state<SortKey>("added");++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{ albums: Album[] }>(+ "study",+ "study:music:albums:list",+ { limit: 500 },+ );+ albums = res.albums ?? [];+ } finally {+ loading = false;+ }+ }++ function coverUrl(path: string | null | undefined): string | null {+ if (!path) return null;+ try {+ return convertFileSrc(path);+ } catch {+ return path;+ }+ }++ 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()}`);+ }++ onMount(async () => {+ void load();+ if (+ spotifyStore.status.logged_in &&+ spotifyStore.savedAlbums.length === 0+ ) {+ try {+ await spotifyStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ });++ function spotifyCoverFor(images: { url: string; width?: number | null }[]): string | null {+ return spotifyStore.pickImage(images, 300);+ }++ function openSpotifyAlbum(id: string) {+ goto(`/study/music/spotify/album/${id}`);+ }++ const filteredSpotifyAlbums = $derived.by(() => {+ const term = q.trim().toLowerCase();+ if (!term) return spotifyStore.savedAlbums;+ return spotifyStore.savedAlbums.filter(+ (a) =>+ a.name.toLowerCase().includes(term) ||+ a.artists.some((ar) => ar.name.toLowerCase().includes(term)),+ );+ });++ const filtered = $derived.by(() => {+ const term = q.trim().toLowerCase();+ let list = albums;+ if (term) {+ list = list.filter(+ (a) =>+ a.name.toLowerCase().includes(term) ||+ (a.artist?.toLowerCase() ?? "").includes(term),+ );+ }+ const cmp = (a: Album, b: Album) => {+ switch (sortKey) {+ case "name":+ return a.name.localeCompare(b.name, undefined, { numeric: true });+ case "year":+ return (b.year ?? 0) - (a.year ?? 0);+ case "track_count":+ return b.track_count - a.track_count;+ default:+ return 0;+ }+ };+ return sortKey === "added" ? list : [...list].sort(cmp);+ });+</script>++<section class="albums-page">+ <header class="page-head">+ <h1>{$t("study.music.nav_albums")}</h1>+ <div class="head-actions">+ <input+ type="search"+ class="search"+ placeholder={$t("study.music.search_placeholder")}+ bind:value={q}+ />+ <select class="sort" bind:value={sortKey}>+ <option value="added">{$t("study.music.sort_added")}</option>+ <option value="name">{$t("study.music.sort_name")}</option>+ <option value="year">{$t("study.music.sort_year")}</option>+ <option value="track_count">{$t("study.music.sort_track_count")}</option>+ </select>+ </div>+ </header>++ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if filtered.length === 0}+ <div class="empty">+ <p>{$t("study.music.albums_empty")}</p>+ </div>+ {:else}+ <p class="result-count">{filtered.length} álbum(ns)</p>+ <div class="album-grid">+ {#each filtered 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="36%" height="36%" 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="Abrir álbum"+ >+ <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>+ {/if}+ <p class="album-card-meta">+ {album.track_count} faixa(s){album.year ? ` · ${album.year}` : ""}+ </p>+ </div>+ {/each}+ </div>+ {/if}++ {#if filteredSpotifyAlbums.length > 0}+ <section class="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 álbuns Spotify+ </h2>+ </header>+ <div class="album-grid">+ {#each filteredSpotifyAlbums as album (album.id)}+ <button+ type="button"+ class="album-card"+ onclick={() => openSpotifyAlbum(album.id)}+ >+ <div class="album-card-cover">+ {#if spotifyCoverFor(album.images)}+ <img src={spotifyCoverFor(album.images)} alt="" loading="lazy" />+ {:else}+ <div class="album-card-fallback" style:background={colorFromString(album.name + (album.artists[0]?.name ?? ""))}>+ <svg viewBox="0 0 24 24" width="36%" height="36%" 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>+ </div>+ <h3 class="album-card-title">{album.name}</h3>+ {#if album.artists.length > 0}+ <p class="album-card-sub">{album.artists.map((a) => a.name).join(", ")}</p>+ {/if}+ <p class="album-card-meta">+ {album.total_tracks} faixa(s){album.release_date ? ` · ${album.release_date.slice(0, 4)}` : ""}+ </p>+ </button>+ {/each}+ </div>+ </section>+ {/if}+</section>++<style>+ .albums-page {+ display: flex;+ flex-direction: column;+ gap: 20px;+ color: rgba(255, 255, 255, 0.95);+ }+ .spotify-block { display: flex; flex-direction: column; gap: 16px; margin-top: 24px; padding-top: 24px; border-top: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent); }+ .block-head { display: flex; align-items: center; gap: 12px; }+ .block-head h2 { margin: 0; font-size: 18px; font-weight: 800; color: var(--secondary); display: inline-flex; align-items: center; gap: 10px; }+ .spotify-mark { display: inline-flex; align-items: center; }+ .spotify-block .album-card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: left; }+ .page-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+ }+ .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;+ }+ .search {+ padding: 8px 14px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.05);+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 13px;+ min-width: 240px;+ outline: none;+ }+ .search:focus { border-color: var(--accent); }+ .sort {+ padding: 8px 14px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.05);+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ outline: none;+ }+ .sort:hover { background: rgba(255, 255, 255, 0.1); }+ .result-count {+ margin: 0;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ }+ .empty {+ padding: 64px 24px;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ }+ .album-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: 24px;+ }+ .album-card {+ cursor: pointer;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 0;+ text-align: left;+ }+ .album-card-cover {+ position: relative;+ aspect-ratio: 1 / 1;+ border-radius: 16px;+ background: rgba(40, 40, 40, 0.8);+ overflow: hidden;+ margin-bottom: 14px;+ }+ .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);+ }+ .album-card-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ }+ .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);+ }+ .album-card-title {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .album-card-sub {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .album-card-meta {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.35);+ font-size: 11px;+ padding: 0 4px;+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }+ @media (prefers-reduced-motion: reduce) {+ .album-card-cover img, .album-card-overlay, .album-card-play { transition: none; }+ .album-card:hover .album-card-cover img { transform: none; }+ }+</style>diff --git a/src/routes/study/music/artist/by-name/+page.svelte b/src/routes/study/music/artist/by-name/+page.sveltenew file mode 100644index 00000000..2e6a09c4--- /dev/null+++ b/src/routes/study/music/artist/by-name/+page.svelte@@ -0,0 +1,176 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { fmtDurationLong, colorFromString } from "$lib/study-music/format";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import AlbumCard from "$lib/study-music-components/AlbumCard.svelte";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";++ type Album = {+ name: string;+ artist: string | null;+ cover_path: string | null;+ track_count: number;+ total_duration_ms: number;+ year: number | null;+ };++ const artistName = $derived($page.url.searchParams.get("name") ?? "");++ let albums = $state<Album[]>([]);+ let topTracks = $state<MusicTrack[]>([]);+ let loading = $state(true);++ async function load() {+ if (!artistName) {+ loading = false;+ return;+ }+ loading = true;+ try {+ const [albumsRes, tracksRes] = await Promise.allSettled([+ pluginInvoke<{ albums: Album[] }>("study", "study:music:albums:list", {+ artist: artistName,+ limit: 50,+ }),+ pluginInvoke<{ tracks: MusicTrack[] }>("study", "study:music:tracks:list", {+ artist: artistName,+ sort: "most_played",+ limit: 8,+ }),+ ]);+ if (albumsRes.status === "fulfilled") albums = albumsRes.value.albums ?? [];+ if (tracksRes.status === "fulfilled") topTracks = tracksRes.value.tracks ?? [];+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ void load();+ });++ $effect(() => {+ void artistName;+ void load();+ });++ function playAll() {+ const all: MusicTrack[] = [...topTracks];+ if (all.length > 0) musicPlayer.play(all[0], all);+ }++ const heroColor = $derived(colorFromString(artistName));+ const totalTracks = $derived(albums.reduce((sum, a) => sum + a.track_count, 0));+</script>++<section class="artist-page">+ {#if !artistName}+ <p class="muted">Artista não especificado.</p>+ {:else if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else}+ <header class="hero" style:--hero-color={heroColor}>+ <div class="initial">{artistName.slice(0, 1).toUpperCase()}</div>+ <div class="meta">+ <span class="eyebrow">{$t("study.music.eyebrow_artist")}</span>+ <h1>{artistName}</h1>+ <div class="info">+ <span>{albums.length} álbum(ns)</span>+ <span class="dot" aria-hidden="true">·</span>+ <span>{totalTracks} faixa(s)</span>+ </div>+ {#if topTracks.length > 0}+ <button type="button" class="play-big" onclick={playAll}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ <span>{$t("study.music.play")}</span>+ </button>+ {/if}+ </div>+ </header>++ {#if topTracks.length > 0}+ <section class="block">+ <h2>{$t("study.music.top_tracks")}</h2>+ <ul class="track-list">+ {#each topTracks as track, i (track.id)}+ <TrackRow {track} queue={topTracks} index={i} showNumber showCover showAlbum />+ {/each}+ </ul>+ </section>+ {/if}++ {#if albums.length > 0}+ <section class="block">+ <h2>{$t("study.music.discography")}</h2>+ <div class="album-grid">+ {#each albums as album (album.name + (album.artist ?? ""))}+ <AlbumCard {album} href={`/study/music/album/by-name?name=${encodeURIComponent(album.name)}&artist=${encodeURIComponent(artistName)}`} />+ {/each}+ </div>+ </section>+ {/if}+ {/if}+</section>++<style>+ .artist-page { display: flex; flex-direction: column; gap: 24px; }+ .hero {+ display: flex;+ align-items: flex-end;+ gap: 24px;+ padding: 32px 4px 20px;+ border-radius: 12px;+ background: linear-gradient(180deg, var(--hero-color) 0%, transparent 90%);+ }+ .initial {+ width: clamp(120px, 18vw, 200px);+ height: clamp(120px, 18vw, 200px);+ border-radius: 50%;+ background: color-mix(in oklab, var(--hero-color, var(--accent)) 60%, var(--button));+ color: white;+ font-size: clamp(48px, 7vw, 88px);+ font-weight: 800;+ display: grid;+ place-items: center;+ box-shadow: 0 12px 32px color-mix(in oklab, black 30%, transparent);+ flex-shrink: 0;+ }+ .meta { display: flex; flex-direction: column; gap: 12px; min-width: 0; flex: 1; }+ .eyebrow { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; color: var(--secondary); }+ .meta h1 { margin: 0; font-size: clamp(28px, 4.5vw, 56px); font-weight: 800; letter-spacing: -0.02em; color: var(--secondary); }+ .info { display: flex; gap: 6px; align-items: center; color: var(--tertiary); font-size: 13px; }+ .info .dot { opacity: 0.6; }+ .play-big {+ align-self: flex-start;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 10px 22px;+ 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) 35%, transparent);+ }+ .play-big:hover { transform: scale(1.04); }+ .play-big:active { transform: scale(0.98); }+ .block { display: flex; flex-direction: column; gap: 10px; }+ .block h2 { margin: 0; font-size: 18px; font-weight: 700; color: var(--secondary); }+ .track-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }+ .album-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));+ gap: 16px;+ }+ .muted { color: var(--tertiary); font-size: 13px; }+ @media (max-width: 720px) {+ .hero { flex-direction: column; align-items: flex-start; }+ }+</style>diff --git a/src/routes/study/music/artists/+page.svelte b/src/routes/study/music/artists/+page.sveltenew file mode 100644index 00000000..ad0a7889--- /dev/null+++ b/src/routes/study/music/artists/+page.svelte@@ -0,0 +1,366 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { convertFileSrc } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { colorFromString } from "$lib/study-music/format";+ import { spotifyStore } from "$lib/study-music/spotify-store.svelte";+ import { soundcloudStore } from "$lib/study-music/soundcloud-store.svelte";++ type Artist = { name: string; album_count: number; track_count: number };+ type Album = { artist: string | null; cover_path: string | null };++ let artists = $state<Artist[]>([]);+ let covers = $state<Map<string, string>>(new Map());+ let loading = $state(true);+ let q = $state("");++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{ artists: Artist[] }>(+ "study",+ "study:music:artists:list",+ { limit: 1000 },+ );+ artists = res.artists ?? [];+ void resolveCovers();+ } finally {+ loading = false;+ }+ }++ async function resolveCovers() {+ const next = new Map(covers);+ for (const a of artists.slice(0, 60)) {+ if (next.has(a.name)) continue;+ 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 */+ }+ }+ covers = next;+ void resolveMusicBrainz();+ }++ async function resolveMusicBrainz() {+ const next = new Map(covers);+ for (const a of artists.slice(0, 30)) {+ if (next.has(a.name)) continue;+ try {+ const res = await pluginInvoke<{ found: boolean; image_path: string | null }>(+ "study",+ "study:music:musicbrainz:artist",+ { name: a.name },+ );+ if (res.found && res.image_path) {+ next.set(a.name, res.image_path);+ }+ } catch {+ /* ignore */+ }+ }+ covers = next;+ }++ function coverUrl(path: string | null | undefined): string | null {+ if (!path) return null;+ try {+ return convertFileSrc(path);+ } catch {+ return path;+ }+ }++ function openArtist(name: string) {+ goto(`/study/music/artist/by-name?name=${encodeURIComponent(name)}`);+ }++ onMount(async () => {+ void load();+ if (+ spotifyStore.status.logged_in &&+ spotifyStore.topArtists.length === 0+ ) {+ try {+ await spotifyStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ if (+ soundcloudStore.isLoggedIn &&+ soundcloudStore.followings.length === 0+ ) {+ try {+ await soundcloudStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ });++ const filteredScArtists = $derived.by(() => {+ const term = q.trim().toLowerCase();+ const all = soundcloudStore.followings;+ if (!term) return all;+ return all.filter((u) => u.username.toLowerCase().includes(term));+ });++ function openSpotifyArtist(id: string) {+ goto(`/study/music/spotify/artist/${id}`);+ }++ function spotifyCover(images: { url: string; width?: number | null }[]): string | null {+ return spotifyStore.pickImage(images, 300);+ }++ const filtered = $derived.by(() => {+ const term = q.trim().toLowerCase();+ if (!term) return artists;+ return artists.filter((a) => a.name.toLowerCase().includes(term));+ });++ const filteredSpotifyArtists = $derived.by(() => {+ const term = q.trim().toLowerCase();+ const all = spotifyStore.allArtists;+ if (!term) return all;+ return all.filter((a) => a.name.toLowerCase().includes(term));+ });+</script>++<section class="artists-page">+ <header class="page-head">+ <h1>{$t("study.music.nav_artists")}</h1>+ <div class="head-actions">+ <input+ type="search"+ class="search"+ placeholder={$t("study.music.search_placeholder")}+ bind:value={q}+ />+ </div>+ </header>++ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if filtered.length === 0}+ <div class="empty">+ <p>{$t("study.music.artists_empty")}</p>+ </div>+ {:else}+ <p class="result-count">{filtered.length} artista(s)</p>+ <div class="artist-grid">+ {#each filtered 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 covers.get(a.name)}+ <img src={coverUrl(covers.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>+ <h3 class="artist-name">{a.name}</h3>+ <p class="artist-meta">+ {a.album_count} álbum(ns) · {a.track_count} faixa(s)+ </p>+ </div>+ {/each}+ </div>+ {/if}++ {#if filteredScArtists.length > 0}+ <section class="spotify-block">+ <header class="block-head">+ <h2><span style="color: #ff5500">●</span> Seguindo no SoundCloud ({filteredScArtists.length})</h2>+ </header>+ <div class="artist-grid">+ {#each filteredScArtists as u (u.id)}+ <a class="artist-card" href={`/study/music/soundcloud/user/${u.id}`}>+ <div class="artist-circle">+ {#if u.avatar_url}+ <img src={soundcloudStore.pickArtwork(u.avatar_url)} alt="" loading="lazy" />+ {:else}+ <div class="artist-fallback" style:background={colorFromString(u.username)}>{u.username.slice(0,1).toUpperCase()}</div>+ {/if}+ </div>+ <h3 class="artist-name">{u.username}</h3>+ {#if u.followers_count}<p class="artist-meta">{u.followers_count.toLocaleString("pt-BR")} seguidores</p>{/if}+ </a>+ {/each}+ </div>+ </section>+ {/if}++ {#if filteredSpotifyArtists.length > 0}+ <section class="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>+ Artistas do Spotify ({filteredSpotifyArtists.length})+ </h2>+ </header>+ <div class="artist-grid">+ {#each filteredSpotifyArtists as a (a.id)}+ <button+ type="button"+ class="artist-card"+ onclick={() => openSpotifyArtist(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>+ {#if a.genres.length > 0}+ <p class="artist-meta">{a.genres.slice(0, 2).join(", ")}</p>+ {/if}+ </button>+ {/each}+ </div>+ </section>+ {/if}+</section>++<style>+ .artists-page {+ display: flex;+ flex-direction: column;+ gap: 20px;+ color: rgba(255, 255, 255, 0.95);+ }+ .spotify-block { display: flex; flex-direction: column; gap: 16px; margin-top: 24px; padding-top: 24px; border-top: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent); }+ .block-head { display: flex; align-items: center; gap: 12px; }+ .block-head h2 { margin: 0; font-size: 18px; font-weight: 800; color: var(--secondary); display: inline-flex; align-items: center; gap: 10px; }+ .spotify-mark { display: inline-flex; align-items: center; }+ .spotify-block .artist-card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: center; }+ .page-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+ }+ .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;+ }+ .search {+ padding: 8px 14px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.05);+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 13px;+ min-width: 240px;+ outline: none;+ }+ .search:focus { border-color: var(--accent); }+ .result-count {+ margin: 0;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ }+ .empty {+ padding: 64px 24px;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ }+ .artist-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 24px;+ }+ .artist-card {+ cursor: pointer;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 0;+ text-align: center;+ }+ .artist-circle {+ aspect-ratio: 1 / 1;+ border-radius: 50%;+ background: rgba(40, 40, 40, 0.8);+ overflow: hidden;+ margin: 0 auto 14px;+ position: relative;+ transition: transform 300ms ease;+ }+ .artist-card:hover .artist-circle {+ transform: scale(1.04);+ }+ .artist-circle 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 {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ font-size: clamp(28px, 4vw, 56px);+ font-weight: 800;+ }+ .artist-name {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .artist-meta {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.35);+ font-size: 11px;+ padding: 0 4px;+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }+ @media (prefers-reduced-motion: reduce) {+ .artist-circle, .artist-circle img { transition: none; }+ .artist-card:hover .artist-circle, .artist-card:hover .artist-circle img { transform: none; }+ }+</style>diff --git a/src/routes/study/music/download/+page.svelte b/src/routes/study/music/download/+page.sveltenew file mode 100644index 00000000..482a9a1e--- /dev/null+++ b/src/routes/study/music/download/+page.svelte@@ -0,0 +1,527 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { invoke } from "@tauri-apps/api/core";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { onClipboardUrl } from "$lib/stores/clipboard-monitor";+ import { getDownloads, type DownloadItem } from "$lib/stores/download-store.svelte";+ import { translateBackendError } from "$lib/error-translate";+ import { t } from "$lib/i18n";+ import OmniboxInput from "$components/omnibox/OmniboxInput.svelte";+ import MediaPreview from "$components/omnibox/MediaPreview.svelte";+ import BatchDownload from "$components/omnibox/BatchDownload.svelte";+ import SearchResults from "$components/omnibox/SearchResults.svelte";+ import { getMediaPreview, clearMediaPreview } from "$lib/stores/media-preview-store.svelte";++ type PlatformInfo = {+ platform: string;+ supported: boolean;+ content_id: string | null;+ content_type: string | null;+ };++ type SearchResult = {+ id: string;+ title: string;+ author: string;+ duration: number | null;+ thumbnail_url: string | null;+ url: string;+ platform: string;+ };++ type DownloadStarted = { id: number; title: string };++ type Root = {+ path: string;+ enabled: boolean;+ exists: boolean;+ };++ type OmniState =+ | { kind: "idle" }+ | { kind: "detecting" }+ | { kind: "detected"; info: PlatformInfo }+ | { kind: "unsupported" }+ | { kind: "preparing"; platform: string }+ | { kind: "batch"; urls: string[] }+ | { kind: "searching" }+ | { kind: "search-results"; results: SearchResult[] }+ | { kind: "search-empty" }+ | { kind: "error"; message: string; originalUrl: string };++ let url = $state("");+ let omniState = $state<OmniState>({ kind: "idle" });+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;+ let quality = $state<"best" | "320" | "256" | "192" | "128">("best");+ let roots = $state<Root[]>([]);+ let targetRoot = $state("");+ let imageLoading = $state(true);+ const mediaPreview = $derived(getMediaPreview());+ const downloads = $derived(getDownloads());++ $effect(() => {+ if (mediaPreview) imageLoading = true;+ });++ const recentDownloads = $derived.by((): DownloadItem[] => {+ const arr = Array.from(downloads.values()) as DownloadItem[];+ return arr+ .filter((d) => d.kind === "generic")+ .sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))+ .slice(0, 6);+ });++ let lastCompleteCount = $state(0);+ $effect(() => {+ const completed = recentDownloads.filter((d) => d.status === "complete").length;+ if (completed > lastCompleteCount) {+ lastCompleteCount = completed;+ void pluginInvoke("study", "study:music:scan").catch(() => {});+ } else {+ lastCompleteCount = completed;+ }+ });++ async function loadRoots() {+ try {+ const r = await pluginInvoke<{ roots: Root[] }>(+ "study",+ "study:music:roots:list",+ );+ roots = (r.roots ?? []).filter((x) => x.enabled && x.exists);+ if (roots.length > 0 && !targetRoot) {+ targetRoot = roots[0].path;+ }+ } catch {+ /* ignore */+ }+ }++ function isUrl(value: string): boolean {+ return (+ value.startsWith("http://") ||+ value.startsWith("https://") ||+ value.startsWith("magnet:") ||+ value.endsWith(".torrent")+ );+ }++ function handleInput() {+ if (debounceTimer) clearTimeout(debounceTimer);+ clearMediaPreview();++ const trimmed = url.trim();+ if (!trimmed) {+ omniState = { kind: "idle" };+ return;+ }++ const urls = trimmed.split(/[\s\n]+/).filter(isUrl);+ if (urls.length > 1) {+ omniState = { kind: "batch", urls };+ return;+ }++ if (isUrl(trimmed)) {+ omniState = { kind: "detecting" };+ debounceTimer = setTimeout(() => detectPlatform(trimmed), 400);+ return;+ }++ if (trimmed.length >= 2) {+ omniState = { kind: "searching" };+ debounceTimer = setTimeout(() => performSearch(trimmed), 600);+ } else {+ omniState = { kind: "idle" };+ }+ }++ async function detectPlatform(value: string) {+ try {+ const result = await invoke<PlatformInfo>("detect_platform", { url: value });+ if (result.supported) {+ omniState = { kind: "detected", info: result };+ invoke("prefetch_media_info", { url: value }).catch(() => {});+ } else {+ omniState = { kind: "unsupported" };+ }+ } catch {+ omniState = { kind: "unsupported" };+ }+ }++ async function performSearch(query: string) {+ try {+ const results = await invoke<SearchResult[]>("search_videos", {+ query,+ platform: "youtube",+ maxResults: 8,+ });+ if (url.trim() !== query) return;+ omniState = results.length > 0+ ? { kind: "search-results", results }+ : { kind: "search-empty" };+ } catch {+ if (url.trim() === query) omniState = { kind: "search-empty" };+ }+ }++ function selectSearchResult(result: SearchResult) {+ url = result.url;+ omniState = { kind: "detecting" };+ void detectPlatform(result.url);+ }++ async function handleDownload() {+ if (omniState.kind !== "detected") return;+ if (!targetRoot) {+ showToast("error", $t("study.music.ytdlp_no_roots") as string);+ return;+ }+ const info = omniState.info;+ const currentUrl = url.trim();+ omniState = { kind: "preparing", platform: info.platform };+ url = "";+ try {+ await invoke<DownloadStarted>("download_from_url", {+ url: currentUrl,+ outputDir: targetRoot,+ downloadMode: "audio",+ quality,+ formatId: null,+ referer: null,+ });+ omniState = { kind: "idle" };+ showToast(+ "success",+ $t("study.music.dl_started", { title: info.platform }) as string,+ );+ } catch (e) {+ const msg = typeof e === "string" ? e : (e as Error).message ?? "";+ omniState = {+ kind: "error",+ message: msg ? translateBackendError(msg, $t) : ($t("omnibox.error") as string),+ originalUrl: currentUrl,+ };+ }+ }++ async function handleBatch() {+ if (omniState.kind !== "batch" || !targetRoot) return;+ const batchUrls = omniState.urls;+ omniState = { kind: "idle" };+ url = "";+ const results = await Promise.allSettled(+ batchUrls.map((u) =>+ invoke<DownloadStarted>("download_from_url", {+ url: u,+ outputDir: targetRoot,+ downloadMode: "audio",+ quality,+ formatId: null,+ referer: null,+ }),+ ),+ );+ const ok = results.filter((r) => r.status === "fulfilled").length;+ const fail = results.length - ok;+ showToast(+ ok > 0 ? "success" : "error",+ $t("study.music.batch_done", { ok, fail }) as string,+ );+ }++ function fmtPct(item: DownloadItem): string {+ if (item.kind === "generic" && item.totalBytes && item.totalBytes > 0) {+ return `${Math.round(((item.downloadedBytes ?? 0) / item.totalBytes) * 100)}%`;+ }+ if (typeof item.percent === "number") {+ return `${Math.round(item.percent)}%`;+ }+ return item.status === "complete" ? "100%" : "—";+ }++ onMount(() => {+ void loadRoots();+ onClipboardUrl((detected) => {+ if (omniState.kind === "preparing") return;+ url = detected;+ handleInput();+ showToast("info", $t("toast.clipboard_url_detected") as string);+ });+ return () => {+ onClipboardUrl(null);+ if (debounceTimer) clearTimeout(debounceTimer);+ };+ });+</script>++<section class="page">+ <header class="hero">+ <h1>{$t("study.music.dl_hero_title")}</h1>+ <p>{$t("study.music.dl_hero_sub")}</p>+ </header>++ <div class="omnibar-card">+ <OmniboxInput bind:url onInput={handleInput} />++ <div class="opts">+ <div class="opt">+ <label for="root-select">{$t("study.music.ytdlp_target")}</label>+ <select id="root-select" bind:value={targetRoot}>+ {#if roots.length === 0}+ <option value="">{$t("study.music.ytdlp_no_roots")}</option>+ {:else}+ {#each roots as r (r.path)}+ <option value={r.path}>{r.path}</option>+ {/each}+ {/if}+ </select>+ </div>+ <div class="opt">+ <label for="quality-select">{$t("study.music.dl_quality")}</label>+ <select id="quality-select" bind:value={quality}>+ <option value="best">{$t("study.music.dl_quality_best")}</option>+ <option value="320">320 kbps</option>+ <option value="256">256 kbps</option>+ <option value="192">192 kbps</option>+ <option value="128">128 kbps</option>+ </select>+ </div>+ </div>++ <div class="state-area">+ {#if omniState.kind === "idle"}+ <p class="hint">{$t("study.music.dl_idle_hint")}</p>+ {:else if omniState.kind === "detecting"}+ <p class="hint pulse">{$t("study.music.dl_detecting")}</p>+ {:else if omniState.kind === "detected"}+ <MediaPreview+ {mediaPreview}+ bind:imageLoading+ />+ <button+ type="button"+ class="cta"+ onclick={handleDownload}+ disabled={!targetRoot}+ >+ <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 M7 10l5 5 5-5 M12 15V3"/>+ </svg>+ {$t("study.music.dl_download_audio")}+ </button>+ {:else if omniState.kind === "unsupported"}+ <p class="warn">{$t("study.music.dl_unsupported")}</p>+ {:else if omniState.kind === "batch"}+ <BatchDownload count={omniState.urls.length} onDownload={handleBatch} />+ {:else if omniState.kind === "searching"}+ <p class="hint pulse">{$t("study.music.dl_searching")}</p>+ {:else if omniState.kind === "search-results"}+ <SearchResults results={omniState.results} onSelect={selectSearchResult} />+ {:else if omniState.kind === "search-empty"}+ <p class="hint">{$t("study.music.dl_search_empty")}</p>+ {:else if omniState.kind === "preparing"}+ <p class="hint pulse">{$t("study.music.dl_preparing")}</p>+ {:else if omniState.kind === "error"}+ <p class="warn">{omniState.message}</p>+ {/if}+ </div>+ </div>++ {#if recentDownloads.length > 0}+ <section class="downloads">+ <h2>{$t("study.music.dl_recent")}</h2>+ <ul class="dl-list">+ {#each recentDownloads as item (item.id)}+ <li class="dl-row" class:done={item.status === "complete"} class:fail={item.status === "error"}>+ <span class="dl-icon" aria-hidden="true">+ {#if item.status === "complete"}✓+ {:else if item.status === "error"}!+ {:else if item.status === "downloading"}+ <span class="spinner-tiny"></span>+ {:else}…+ {/if}+ </span>+ <span class="dl-title">{item.name}</span>+ <span class="dl-pct">{fmtPct(item)}</span>+ </li>+ {/each}+ </ul>+ </section>+ {/if}+</section>++<style>+ .page {+ display: flex;+ flex-direction: column;+ gap: 28px;+ padding-bottom: 60px;+ max-width: 760px;+ margin-inline: auto;+ }+ .hero {+ text-align: center;+ padding: 32px 16px 8px;+ }+ .hero h1 {+ margin: 0 0 6px;+ font-size: 32px;+ font-weight: 800;+ letter-spacing: -0.02em;+ color: rgba(255, 255, 255, 0.95);+ }+ .hero p {+ margin: 0;+ color: rgba(255, 255, 255, 0.55);+ font-size: 14px;+ }+ .omnibar-card {+ display: flex;+ flex-direction: column;+ gap: 14px;+ padding: 22px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 14px;+ }+ .opts {+ display: flex;+ gap: 14px;+ flex-wrap: wrap;+ }+ .opt {+ display: flex;+ flex-direction: column;+ gap: 4px;+ flex: 1;+ min-width: 200px;+ }+ .opt label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: rgba(255, 255, 255, 0.45);+ }+ .opt select {+ padding: 8px 12px;+ background: rgba(0, 0, 0, 0.25);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 8px;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 13px;+ outline: none;+ }+ .opt select:focus { border-color: var(--accent); }+ .state-area {+ display: flex;+ flex-direction: column;+ gap: 14px;+ align-items: stretch;+ min-height: 56px;+ justify-content: center;+ }+ .hint {+ margin: 0;+ color: rgba(255, 255, 255, 0.55);+ font-size: 13px;+ text-align: center;+ }+ .hint.pulse {+ animation: pulse 1.4s ease-in-out infinite;+ }+ @keyframes pulse {+ 0%, 100% { opacity: 0.55; }+ 50% { opacity: 1; }+ }+ .warn {+ margin: 0;+ padding: 10px 14px;+ color: rgb(251, 191, 36);+ background: rgba(217, 119, 6, 0.1);+ border: 1px solid rgba(217, 119, 6, 0.25);+ border-radius: 8px;+ font-size: 13px;+ }+ .cta {+ align-self: center;+ 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;+ transition: filter 120ms ease;+ }+ .cta:hover:not(:disabled) { filter: brightness(1.08); }+ .cta:disabled { opacity: 0.4; cursor: not-allowed; }+ .downloads h2 {+ margin: 0 0 12px;+ font-size: 14px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: rgba(255, 255, 255, 0.65);+ }+ .dl-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .dl-row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px 14px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.05);+ border-radius: 8px;+ color: rgba(255, 255, 255, 0.85);+ font-size: 12px;+ }+ .dl-row.done .dl-icon { color: rgb(74, 222, 128); }+ .dl-row.fail { background: rgba(220, 38, 38, 0.06); border-color: rgba(220, 38, 38, 0.2); }+ .dl-row.fail .dl-icon { color: rgb(248, 113, 113); }+ .dl-icon {+ flex-shrink: 0;+ width: 18px;+ height: 18px;+ display: grid;+ place-items: center;+ color: rgba(255, 255, 255, 0.4);+ font-size: 12px;+ font-weight: 700;+ }+ .dl-title {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .dl-pct {+ flex-shrink: 0;+ font-variant-numeric: tabular-nums;+ color: rgba(255, 255, 255, 0.5);+ }+ .spinner-tiny {+ width: 10px;+ height: 10px;+ border: 1.5px solid rgba(255, 255, 255, 0.2);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ }+ @keyframes spin { to { transform: rotate(360deg); } }+</style>diff --git a/src/routes/study/music/favorites/+page.svelte b/src/routes/study/music/favorites/+page.sveltenew file mode 100644index 00000000..d3b015bb--- /dev/null+++ b/src/routes/study/music/favorites/+page.svelte@@ -0,0 +1,91 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";+ import type { MusicTrack } from "$lib/study-music/player-store.svelte";+ import {+ spotifyStore,+ spotifyTrackToMusicTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import {+ soundcloudStore,+ scTrackToMusicTrack,+ } from "$lib/study-music/soundcloud-store.svelte";++ let tracks = $state<MusicTrack[]>([]);+ let loading = $state(true);++ async function load() {+ loading = true;+ try {+ const [localRes] = await Promise.allSettled([+ pluginInvoke<{ tracks: MusicTrack[] }>(+ "study",+ "study:music:favorites:list",+ { limit: 500 },+ ),+ spotifyStore.status.logged_in && spotifyStore.savedTracks.length === 0+ ? spotifyStore.loadAll()+ : Promise.resolve(),+ soundcloudStore.isLoggedIn && soundcloudStore.likedTracks.length === 0+ ? soundcloudStore.loadAll()+ : Promise.resolve(),+ ]);++ const local: MusicTrack[] =+ localRes.status === "fulfilled"+ ? (localRes.value.tracks ?? []).map((t) => ({ ...t, favorite: true }))+ : [];++ const spotifyTracks: MusicTrack[] = spotifyStore.savedTracks+ .filter((sp) => !spotifyStore.localMatches.has(sp.id))+ .map((t) => ({+ ...spotifyTrackToMusicTrack(t),+ favorite: true,+ }));++ const scTracks: MusicTrack[] = soundcloudStore.likedTracks.map((t) => ({+ ...scTrackToMusicTrack(t),+ favorite: true,+ }));++ tracks = [...local, ...spotifyTracks, ...scTracks];+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ void load();+ });+</script>++<section class="favorites-page">+ <header class="head">+ <h1>{$t("study.music.favorites_title")}</h1>+ <p class="sub">{$t("study.music.favorites_subtitle")}</p>+ </header>+ {#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>+ {:else}+ <ul class="track-list">+ {#each tracks as track (track.id)}+ <TrackRow {track} queue={tracks} showCover showAlbum />+ {/each}+ </ul>+ {/if}+</section>++<style>+ .favorites-page { display: flex; flex-direction: column; gap: 14px; }+ .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/genres/+page.svelte b/src/routes/study/music/genres/+page.sveltenew file mode 100644index 00000000..374b59ad--- /dev/null+++ b/src/routes/study/music/genres/+page.svelte@@ -0,0 +1,157 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { fmtDurationLong } from "$lib/study-music/format";++ type Genre = {+ name: string;+ track_count: number;+ album_count: number;+ artist_count: number;+ total_duration_ms: number;+ cover_path: string | null;+ };++ let genres = $state<Genre[]>([]);+ let loading = $state(true);++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{ genres: Genre[] }>(+ "study",+ "study:music:genres:list",+ );+ genres = res.genres ?? [];+ } finally {+ loading = false;+ }+ }++ function open(g: Genre) {+ goto(`/study/music/genres/${encodeURIComponent(g.name)}`);+ }++ function genreColor(name: string): string {+ let hash = 0;+ for (let i = 0; i < name.length; i++) {+ hash = (hash * 31 + name.charCodeAt(i)) >>> 0;+ }+ const hue = hash % 360;+ return `oklch(0.45 0.18 ${hue})`;+ }++ onMount(() => {+ void load();+ });+</script>++<section class="page">+ <header class="head">+ <h1>{$t("study.music.genres_title")}</h1>+ <p class="sub">{$t("study.music.genres_subtitle")}</p>+ </header>++ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if genres.length === 0}+ <div class="empty">+ <p>{$t("study.music.no_genres")}</p>+ </div>+ {:else}+ <ul class="grid">+ {#each genres as g (g.name)}+ <li>+ <button+ type="button"+ class="card"+ style="--seed: {genreColor(g.name)};"+ onclick={() => open(g)}+ >+ <span class="title">{g.name}</span>+ <span class="meta">+ {$t("study.music.tracks_count", { count: g.track_count })} ·+ {fmtDurationLong(g.total_duration_ms)}+ </span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}+</section>++<style>+ .page {+ display: flex;+ flex-direction: column;+ gap: 24px;+ padding-bottom: 40px;+ }+ .head h1 {+ margin: 0 0 4px;+ font-size: 28px;+ font-weight: 800;+ letter-spacing: -0.02em;+ }+ .sub {+ margin: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .muted {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .empty {+ padding: 80px 0;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ }+ .grid {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: 16px;+ }+ .card {+ width: 100%;+ aspect-ratio: 16 / 11;+ padding: 18px 16px;+ border: 0;+ border-radius: 12px;+ background: linear-gradient(135deg, var(--seed), color-mix(in oklab, var(--seed) 60%, black));+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ gap: 8px;+ transition: transform 120ms ease, filter 120ms ease;+ overflow: hidden;+ position: relative;+ }+ .card:hover {+ transform: translateY(-2px);+ filter: brightness(1.1);+ }+ .title {+ font-size: 18px;+ font-weight: 700;+ text-transform: capitalize;+ overflow: hidden;+ text-overflow: ellipsis;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ }+ .meta {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.75);+ }+</style>diff --git a/src/routes/study/music/genres/[name]/+page.svelte b/src/routes/study/music/genres/[name]/+page.sveltenew file mode 100644index 00000000..c7948faf--- /dev/null+++ b/src/routes/study/music/genres/[name]/+page.svelte@@ -0,0 +1,179 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import { fmtDurationLong } from "$lib/study-music/format";+ import {+ musicPlayer,+ type MusicTrack,+ } from "$lib/study-music/player-store.svelte";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";++ type GenreSummary = {+ name: string;+ track_count: number;+ album_count: number;+ artist_count: number;+ total_duration_ms: number;+ };++ let genre = $state<GenreSummary | null>(null);+ let tracks = $state<MusicTrack[]>([]);+ let loading = $state(true);+ let error = $state<string | null>(null);++ const name = $derived(decodeURIComponent($page.params.name ?? ""));++ async function load() {+ loading = true;+ error = null;+ try {+ const res = await pluginInvoke<{+ genre: GenreSummary;+ tracks: MusicTrack[];+ }>("study", "study:music:genres:get", { name, limit: 500 });+ genre = res.genre;+ tracks = res.tracks ?? [];+ } catch (e) {+ error = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ }++ function playAll() {+ if (tracks.length === 0) return;+ void musicPlayer.play(tracks[0], tracks);+ }++ function playShuffled() {+ if (tracks.length === 0) return;+ musicPlayer.shuffle = true;+ const idx = Math.floor(Math.random() * tracks.length);+ void musicPlayer.play(tracks[idx], tracks);+ }++ $effect(() => {+ if (name) 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>+ {:else if genre}+ <header class="hero">+ <span class="eyebrow">{$t("study.music.eyebrow_genre")}</span>+ <h1>{genre.name}</h1>+ <p class="meta">+ {$t("study.music.tracks_count", { count: genre.track_count })} ·+ {$t("study.music.albums_count", { count: genre.album_count })} ·+ {$t("study.music.artists_count", { count: genre.artist_count })} ·+ {fmtDurationLong(genre.total_duration_ms)}+ </p>+ <div class="actions">+ <button type="button" class="play-btn" 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>+ <button type="button" class="ghost-btn" onclick={playShuffled}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 3h5v5 M4 20l17-17 M21 16v5h-5 M4 4l5 5 M15 15l6 6"/></svg>+ {$t("study.music.shuffle")}+ </button>+ </div>+ </header>++ <ul class="track-list">+ {#each tracks as tr, idx (tr.id)}+ <TrackRow track={tr} queue={tracks} index={idx} showNumber showAlbum />+ {/each}+ </ul>+ {/if}+</section>++<style>+ .page {+ display: flex;+ flex-direction: column;+ gap: 24px;+ padding-bottom: 40px;+ }+ .hero {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px 0 4px;+ }+ .eyebrow {+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--accent);+ }+ .hero h1 {+ margin: 0;+ font-size: 40px;+ font-weight: 800;+ letter-spacing: -0.02em;+ text-transform: capitalize;+ }+ .hero .meta {+ margin: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .actions {+ display: flex;+ gap: 8px;+ margin-top: 8px;+ }+ .play-btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 8px 18px;+ border: 0;+ border-radius: 999px;+ background: var(--accent);+ color: var(--on-accent, white);+ font-family: inherit;+ font-size: 13px;+ font-weight: 700;+ cursor: pointer;+ }+ .ghost-btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 8px 16px;+ border: 1px solid rgba(255, 255, 255, 0.15);+ border-radius: 999px;+ background: transparent;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 13px;+ cursor: pointer;+ }+ .ghost-btn:hover {+ color: var(--accent);+ border-color: var(--accent);+ }+ .track-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .muted { color: rgba(255, 255, 255, 0.5); }+ .error { color: rgb(248, 113, 113); }+</style>diff --git a/src/routes/study/music/library/+page.svelte b/src/routes/study/music/library/+page.sveltenew file mode 100644index 00000000..e9a49783--- /dev/null+++ b/src/routes/study/music/library/+page.svelte@@ -0,0 +1,250 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";+ import type { MusicTrack } from "$lib/study-music/player-store.svelte";+ import {+ spotifyStore,+ spotifyTrackToMusicTrack,+ type SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import {+ soundcloudStore,+ scTrackToMusicTrack,+ type ScTrack,+ } from "$lib/study-music/soundcloud-store.svelte";++ let tracks = $state<MusicTrack[]>([]);+ let total = $state(0);+ let loading = $state(true);+ let q = $state("");+ let timer: ReturnType<typeof setTimeout> | null = null;++ function buildSpotifyPool(): SpotifyTrack[] {+ const pool = new Map<string, SpotifyTrack>();+ for (const t of spotifyStore.savedTracks) pool.set(t.id, t);+ for (const t of spotifyStore.recentlyPlayed) if (!pool.has(t.id)) pool.set(t.id, t);+ for (const t of spotifyStore.topTracks) if (!pool.has(t.id)) pool.set(t.id, t);+ return [...pool.values()].filter((sp) => !spotifyStore.localMatches.has(sp.id));+ }++ function spotifyToMusic(pool: SpotifyTrack[]): MusicTrack[] {+ return pool.map(spotifyTrackToMusicTrack);+ }++ type UnifiedTrackRow = {+ source: "local" | "youtube";+ id: number;+ path: string;+ title: string | null;+ artist: string | null;+ album: string | null;+ duration_ms: number | null;+ cover_path: string | null;+ youtube_thumbnail?: string | null;+ video_id?: string;+ play_count: number;+ favorite: boolean;+ };++ function unifiedToTrack(u: UnifiedTrackRow): MusicTrack {+ return {+ id: u.id,+ path: u.path,+ title: u.title,+ artist: u.artist,+ album: u.album,+ duration_ms: u.duration_ms,+ cover_path: u.cover_path ?? u.youtube_thumbnail ?? null,+ play_count: u.play_count,+ favorite: u.favorite,+ source: u.source,+ youtube_video_id: u.source === "youtube" ? u.video_id : undefined,+ youtube_thumbnail: u.youtube_thumbnail ?? undefined,+ youtube_url: u.source === "youtube" ? u.path : undefined,+ };+ }++ async function load() {+ loading = true;+ try {+ if (+ spotifyStore.status.logged_in &&+ spotifyStore.savedTracks.length === 0 &&+ spotifyStore.recentlyPlayed.length === 0+ ) {+ try {+ await spotifyStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ if (+ soundcloudStore.isLoggedIn &&+ soundcloudStore.likedTracks.length === 0+ ) {+ try {+ await soundcloudStore.loadAll();+ } catch {+ /* ignore */+ }+ }++ const trimmed = q.trim();+ const sortKey = trimmed ? "title" : "added";+ const res = await pluginInvoke<{ tracks: UnifiedTrackRow[]; total: number }>(+ "study",+ "study:music:unified:tracks",+ { limit: 500, sort: sortKey },+ );+ let unified = (res.tracks ?? []).map(unifiedToTrack);++ if (trimmed) {+ const term = trimmed.toLowerCase();+ unified = unified.filter(+ (t) =>+ (t.title ?? "").toLowerCase().includes(term) ||+ (t.artist ?? "").toLowerCase().includes(term) ||+ (t.album ?? "").toLowerCase().includes(term),+ );+ }++ const spotifyPool = buildSpotifyPool();+ const matchesText = (s: string | null | undefined) =>+ !!s && s.toLowerCase().includes(trimmed.toLowerCase());+ const filteredSpotify =+ trimmed.length > 0+ ? spotifyPool.filter(+ (t) =>+ matchesText(t.name) ||+ t.artists.some((a) => matchesText(a.name)) ||+ matchesText(t.album.name),+ )+ : spotifyPool;+ const spotifyTracks = spotifyToMusic(filteredSpotify);++ const scPool: ScTrack[] = soundcloudStore.likedTracks;+ const scFiltered =+ trimmed.length > 0+ ? scPool.filter(+ (t) =>+ matchesText(t.title) ||+ matchesText(t.user.username),+ )+ : scPool;+ const scTracks = scFiltered.map(scTrackToMusicTrack);++ tracks = [...unified, ...spotifyTracks, ...scTracks];+ total = tracks.length;+ } finally {+ loading = false;+ }+ }++ function onInput(e: Event) {+ q = (e.target as HTMLInputElement).value;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => load(), 200);+ }++ onMount(() => {+ void load();+ return () => {+ if (timer) clearTimeout(timer);+ };+ });+</script>++<section class="library-page">+ <header class="page-head">+ <h1>{$t("study.music.library_title")}</h1>+ </header>++ <div class="search-box">+ <svg viewBox="0 0 24 24" width="14" height="14" 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+ type="search"+ value={q}+ oninput={onInput}+ placeholder={$t("study.music.search_placeholder")}+ autocomplete="off"+ />+ </div>++ {#if loading && tracks.length === 0}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if tracks.length === 0}+ <div class="empty">+ <p>{$t("study.music.empty_results")}</p>+ </div>+ {:else}+ <p class="result-count">{tracks.length} de {total} faixa(s)</p>+ <ul class="track-list">+ {#each tracks as track (track.id)}+ <TrackRow {track} queue={tracks} showCover showAlbum />+ {/each}+ </ul>+ {/if}+</section>++<style>+ .library-page {+ display: flex;+ flex-direction: column;+ gap: 18px;+ color: rgba(255, 255, 255, 0.95);+ }+ .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);+ }+ .search-box {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 14px;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.05);+ border-radius: 999px;+ width: min(100%, 480px);+ transition: border-color 200ms ease;+ }+ .search-box:focus-within { border-color: var(--accent); }+ .search-box svg { color: rgba(255, 255, 255, 0.5); flex-shrink: 0; }+ .search-box input {+ flex: 1;+ border: 0;+ background: transparent;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ font-size: 13px;+ outline: none;+ min-width: 0;+ }+ .result-count {+ margin: 0;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ }+ .track-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .empty {+ padding: 64px 24px;+ text-align: center;+ color: rgba(255, 255, 255, 0.5);+ }+ .muted { color: rgba(255, 255, 255, 0.5); font-size: 13px; }+</style>diff --git a/src/routes/study/music/playlists/+page.svelte b/src/routes/study/music/playlists/+page.sveltenew file mode 100644index 00000000..26687816--- /dev/null+++ b/src/routes/study/music/playlists/+page.svelte@@ -0,0 +1,343 @@+<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 { playlistsStore, type Playlist } from "$lib/study-music/playlists-store.svelte";+ import { spotifyStore } from "$lib/study-music/spotify-store.svelte";+ import { soundcloudStore } from "$lib/study-music/soundcloud-store.svelte";+ import CoverImage from "$lib/study-music-components/CoverImage.svelte";++ let creatingNew = $state(false);+ let newName = $state("");+ let newRef = $state<HTMLInputElement | null>(null);+ let busy = $state(false);++ onMount(async () => {+ void playlistsStore.load();+ if (+ spotifyStore.status.logged_in &&+ spotifyStore.playlists.length === 0+ ) {+ try {+ await spotifyStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ if (+ soundcloudStore.isLoggedIn &&+ soundcloudStore.playlists.length === 0+ ) {+ try {+ await soundcloudStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ });++ const ownedSpotify = $derived(+ spotifyStore.playlists.filter((p) => spotifyStore.isPlaylistOwned(p)),+ );+ const followedSpotify = $derived(+ spotifyStore.playlists.filter((p) => !spotifyStore.isPlaylistOwned(p)),+ );++ function startNew() {+ creatingNew = true;+ newName = "";+ queueMicrotask(() => newRef?.focus());+ }++ async function confirmCreate() {+ const trimmed = newName.trim();+ if (!trimmed || busy) return;+ busy = true;+ try {+ const id = await playlistsStore.create(trimmed);+ creatingNew = false;+ newName = "";+ if (id) goto(`/study/music/playlists/${id}`);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ busy = false;+ }+ }++ function cancelNew() {+ creatingNew = false;+ newName = "";+ }+</script>++<section class="playlists-page">+ <header class="head">+ <h1>{$t("study.music.playlists_title")}</h1>+ <button type="button" class="cta" onclick={startNew} disabled={creatingNew}>+ + {$t("study.music.new_playlist")}+ </button>+ </header>++ {#if creatingNew}+ <div class="new-row">+ <input+ bind:this={newRef}+ bind:value={newName}+ type="text"+ placeholder={$t("study.music.playlist_name_placeholder")}+ onkeydown={(e) => {+ if (e.key === "Enter") confirmCreate();+ else if (e.key === "Escape") cancelNew();+ }}+ />+ <button type="button" class="confirm" onclick={confirmCreate} disabled={!newName.trim() || busy}>+ {$t("study.common.create")}+ </button>+ <button type="button" class="ghost" onclick={cancelNew}>+ {$t("study.common.cancel")}+ </button>+ </div>+ {/if}++ {#if playlistsStore.loading && playlistsStore.list.length === 0}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if playlistsStore.list.length === 0}+ <div class="empty">+ <p>{$t("study.music.playlists_empty_title")}</p>+ <p class="sub">{$t("study.music.playlists_empty_body")}</p>+ <button type="button" class="cta" onclick={startNew}>+ {$t("study.music.new_playlist")}+ </button>+ </div>+ {:else}+ <div class="playlist-grid">+ {#each playlistsStore.list as p (p.id)}+ <a class="playlist-card" href={`/study/music/playlists/${p.id}`}>+ <div class="cover-wrap">+ <CoverImage+ src={p.resolved_cover}+ alt={p.name}+ fallbackSeed={p.name}+ rounded="lg"+ />+ </div>+ <span class="title">{p.name}</span>+ <span class="sub">{p.track_count} faixa(s)</span>+ </a>+ {/each}+ </div>+ {/if}++ {#if ownedSpotify.length > 0}+ <section class="spotify-section">+ <header class="section-head">+ <h2>Suas playlists Spotify</h2>+ <span class="badge-spotify">+ <svg viewBox="0 0 168 168" width="14" height="14" aria-hidden="true">+ <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>+ Suas+ </span>+ </header>+ <div class="playlist-grid">+ {#each ownedSpotify as p (p.id)}+ <a class="playlist-card" href={`/study/music/spotify/playlist/${p.id}`}>+ <div class="cover-wrap">+ <CoverImage+ src={spotifyStore.pickImage(p.images, 300)}+ alt={p.name}+ fallbackSeed={p.name}+ rounded="lg"+ />+ </div>+ <span class="title">{p.name}</span>+ <span class="sub">{p.tracks_total} faixa(s){p.owner_name ? ` · ${p.owner_name}` : ""}</span>+ </a>+ {/each}+ </div>+ </section>+ {/if}++ {#if followedSpotify.length > 0}+ <section class="spotify-section">+ <header class="section-head">+ <h2>Playlists seguidas</h2>+ <span class="badge-warn" title="Em apps em Development mode, o Spotify pode bloquear o acesso às tracks dessas playlists (403)">+ algumas podem dar erro+ </span>+ </header>+ <div class="playlist-grid">+ {#each followedSpotify as p (p.id)}+ <a class="playlist-card" href={`/study/music/spotify/playlist/${p.id}`}>+ <div class="cover-wrap">+ <CoverImage+ src={spotifyStore.pickImage(p.images, 300)}+ alt={p.name}+ fallbackSeed={p.name}+ rounded="lg"+ />+ </div>+ <span class="title">{p.name}</span>+ <span class="sub">{p.tracks_total} faixa(s){p.owner_name ? ` · ${p.owner_name}` : ""}</span>+ </a>+ {/each}+ </div>+ </section>+ {/if}++ {#if soundcloudStore.playlists.length > 0}+ <section class="spotify-section">+ <header class="section-head">+ <h2>Suas playlists SoundCloud</h2>+ <span class="badge-soundcloud">SoundCloud</span>+ </header>+ <div class="playlist-grid">+ {#each soundcloudStore.playlists as p (p.id)}+ <a class="playlist-card" href={`/study/music/soundcloud/playlist/${p.id}`}>+ <div class="cover-wrap">+ <CoverImage+ src={soundcloudStore.pickArtwork(p.artwork_url)}+ alt={p.title}+ fallbackSeed={p.title}+ rounded="lg"+ />+ </div>+ <span class="title">{p.title}</span>+ <span class="sub">{p.track_count} faixa(s){p.user.username ? ` · ${p.user.username}` : ""}</span>+ </a>+ {/each}+ </div>+ </section>+ {/if}+</section>++<style>+ .playlists-page { display: flex; flex-direction: column; gap: 20px; }+ .spotify-section { display: flex; flex-direction: column; gap: 16px; margin-top: 16px; padding-top: 24px; border-top: 1px solid color-mix(in oklab, var(--content-border) 40%, transparent); }+ .section-head { display: flex; align-items: center; gap: 12px; }+ .section-head h2 { margin: 0; font-size: 18px; font-weight: 800; color: var(--secondary); }+ .badge-spotify { display: inline-flex; align-items: center; gap: 6px; font-size: 11px; font-weight: 700; color: #1db954; }+ .badge-warn { font-size: 10px; font-weight: 700; color: #ffa726; padding: 2px 8px; background: rgba(255, 167, 38, 0.12); border-radius: 999px; cursor: help; }+ .badge-soundcloud { font-size: 10px; font-weight: 700; color: #ff5500; padding: 2px 8px; background: rgba(255, 85, 0, 0.12); border-radius: 999px; }+ .head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ flex-wrap: wrap;+ }+ .head h1 {+ margin: 0;+ font-size: 28px;+ font-weight: 800;+ letter-spacing: -0.01em;+ color: var(--secondary);+ }+ .cta {+ padding: 8px 18px;+ background: var(--accent);+ color: var(--on-accent, white);+ border: 0;+ border-radius: 999px;+ font-family: inherit;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: transform 120ms ease;+ }+ .cta:hover { transform: scale(1.03); }+ .cta:disabled { opacity: 0.5; cursor: default; transform: none; }+ .new-row {+ display: flex;+ gap: 8px;+ align-items: center;+ }+ .new-row input {+ flex: 1;+ max-width: 340px;+ padding: 8px 14px;+ border: 1px solid var(--accent);+ border-radius: 8px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: inherit;+ font-size: 13px;+ outline: none;+ }+ .confirm {+ 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:disabled { opacity: 0.5; cursor: default; }+ .ghost {+ padding: 8px 12px;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 8px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 13px;+ cursor: pointer;+ }+ .ghost:hover { color: var(--accent); border-color: var(--accent); }+ .empty {+ padding: 48px 24px;+ text-align: center;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ }+ .empty p { margin: 0; color: var(--secondary); font-weight: 600; }+ .empty .sub { color: var(--tertiary); font-weight: 400; max-width: 50ch; line-height: 1.5; }+ .playlist-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));+ gap: 16px;+ }+ .playlist-card {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px;+ background: color-mix(in oklab, var(--button) 50%, transparent);+ border-radius: 10px;+ color: inherit;+ text-decoration: none;+ transition: background 120ms ease;+ }+ .playlist-card:hover {+ background: color-mix(in oklab, var(--accent) 8%, var(--button));+ }+ .cover-wrap {+ aspect-ratio: 1 / 1;+ width: 100%;+ border-radius: 10px;+ overflow: hidden;+ box-shadow: 0 4px 14px color-mix(in oklab, black 28%, transparent);+ }+ .title {+ font-size: 14px;+ font-weight: 600;+ color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ font-size: 12px;+ color: var(--tertiary);+ }+ .muted { color: var(--tertiary); font-size: 13px; }+</style>diff --git a/src/routes/study/music/playlists/[id]/+page.svelte b/src/routes/study/music/playlists/[id]/+page.sveltenew file mode 100644index 00000000..b0f856bc--- /dev/null+++ b/src/routes/study/music/playlists/[id]/+page.svelte@@ -0,0 +1,525 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import { t } from "$lib/i18n";+ import { fmtDuration, fmtDurationLong } from "$lib/study-music/format";+ import { musicPlayer, type MusicTrack } from "$lib/study-music/player-store.svelte";+ import { playlistsStore } from "$lib/study-music/playlists-store.svelte";+ import CoverImage from "$lib/study-music-components/CoverImage.svelte";++ type PlaylistDetail = {+ id: number;+ name: string;+ description: string | null;+ cover_path: string | null;+ track_count: number;+ total_duration_ms: number | null;+ resolved_cover: string | null;+ created_at: number;+ updated_at: number;+ };++ type PlaylistTrack = MusicTrack & { position: number };++ const playlistId = $derived(Number($page.params.id));++ let detail = $state<PlaylistDetail | null>(null);+ let tracks = $state<PlaylistTrack[]>([]);+ let loading = $state(true);+ let editingName = $state(false);+ let nameValue = $state("");+ let nameRef = $state<HTMLInputElement | null>(null);+ let confirmDeleteOpen = $state(false);+ let dragIndex = $state<number | null>(null);+ let dragOver = $state<number | null>(null);++ async function load() {+ if (!Number.isFinite(playlistId)) return;+ loading = true;+ try {+ const res = await pluginInvoke<{ playlist: PlaylistDetail; tracks: PlaylistTrack[] }>(+ "study",+ "study:music:playlists:get",+ { id: playlistId },+ );+ detail = res.playlist;+ tracks = res.tracks ?? [];+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ void load();+ });++ $effect(() => {+ void playlistId;+ void load();+ });++ function playAll() {+ if (tracks.length === 0) return;+ void musicPlayer.play(tracks[0], tracks);+ }++ function shufflePlay() {+ if (tracks.length === 0) return;+ musicPlayer.shuffle = true;+ const idx = Math.floor(Math.random() * tracks.length);+ void musicPlayer.play(tracks[idx], tracks);+ }++ async function removeTrack(track: PlaylistTrack) {+ try {+ await pluginInvoke("study", "study:music:playlists:remove_track", {+ playlistId,+ trackId: track.id,+ });+ tracks = tracks.filter((t) => t.id !== track.id);+ void playlistsStore.load(true);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ async function moveTrack(from: number, to: number) {+ if (from === to || from < 0 || to < 0 || from >= tracks.length || to >= tracks.length) return;+ const next = [...tracks];+ const [moved] = next.splice(from, 1);+ next.splice(to, 0, moved);+ tracks = next;+ try {+ await pluginInvoke("study", "study:music:playlists:reorder", {+ playlistId,+ trackIds: next.map((t) => t.id),+ });+ void playlistsStore.load(true);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ void load();+ }+ }++ function startEditName() {+ if (!detail) return;+ editingName = true;+ nameValue = detail.name;+ queueMicrotask(() => {+ nameRef?.focus();+ nameRef?.select();+ });+ }++ async function saveName() {+ const trimmed = nameValue.trim();+ if (!trimmed || !detail || trimmed === detail.name) {+ editingName = false;+ nameValue = "";+ return;+ }+ try {+ await playlistsStore.update(detail.id, trimmed);+ detail = { ...detail, name: trimmed };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ editingName = false;+ }+ }++ function cancelEditName() {+ editingName = false;+ nameValue = "";+ }++ async function performDelete() {+ if (!detail) return;+ try {+ await playlistsStore.deleteOne(detail.id);+ showToast("success", $t("study.music.playlist_deleted") as string);+ goto("/study/music/playlists");+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ confirmDeleteOpen = false;+ }+ }++ function onDragStart(e: DragEvent, idx: number) {+ dragIndex = idx;+ if (e.dataTransfer) {+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData("text/plain", String(idx));+ }+ }++ function onDragOver(e: DragEvent, idx: number) {+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = "move";+ dragOver = idx;+ }++ function onDrop(e: DragEvent, idx: number) {+ e.preventDefault();+ if (dragIndex === null) return;+ void moveTrack(dragIndex, idx);+ dragIndex = null;+ dragOver = null;+ }++ function onDragEnd() {+ dragIndex = null;+ dragOver = null;+ }+</script>++<section class="playlist-page">+ {#if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if !detail}+ <p class="error">{$t("study.music.playlist_not_found")}</p>+ {:else}+ <header class="hero">+ <div class="cover-block">+ <CoverImage+ src={detail.resolved_cover}+ alt={detail.name}+ fallbackSeed={detail.name}+ rounded="lg"+ />+ </div>+ <div class="meta">+ <span class="eyebrow">{$t("study.music.eyebrow_playlist")}</span>+ {#if editingName}+ <input+ bind:this={nameRef}+ bind:value={nameValue}+ class="title-edit"+ type="text"+ onkeydown={(e) => {+ if (e.key === "Enter") saveName();+ else if (e.key === "Escape") cancelEditName();+ }}+ onblur={saveName}+ />+ {:else}+ <h1 onclick={startEditName} title={$t("study.music.click_to_rename") as string}>{detail.name}</h1>+ {/if}+ <div class="info">+ <span>{detail.track_count} faixa(s)</span>+ {#if detail.total_duration_ms}+ <span class="dot" aria-hidden="true">·</span>+ <span>{fmtDurationLong(detail.total_duration_ms)}</span>+ {/if}+ </div>+ <div class="actions">+ <button type="button" class="play-big" onclick={playAll} disabled={tracks.length === 0}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ <span>{$t("study.music.play")}</span>+ </button>+ <button+ type="button"+ class="ghost-big"+ onclick={shufflePlay}+ disabled={tracks.length === 0}+ title={$t("study.music.shuffle") as string}+ aria-label={$t("study.music.shuffle") as string}+ >+ <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">+ <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="ghost-big danger"+ onclick={() => (confirmDeleteOpen = true)}+ title={$t("study.music.delete_playlist") as string}+ aria-label={$t("study.music.delete_playlist") as string}+ >+ <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">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>+ <path d="M10 11v6"/>+ <path d="M14 11v6"/>+ <path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/>+ </svg>+ </button>+ </div>+ </div>+ </header>++ {#if tracks.length === 0}+ <div class="empty">+ <p>{$t("study.music.playlist_empty_title")}</p>+ <p class="sub">{$t("study.music.playlist_empty_body")}</p>+ </div>+ {:else}+ <ol class="track-list">+ {#each tracks as track, i (track.id)}+ <li+ class="track-li"+ class:dragover={dragOver === i}+ draggable="true"+ ondragstart={(e) => onDragStart(e, i)}+ ondragover={(e) => onDragOver(e, i)}+ ondrop={(e) => onDrop(e, i)}+ ondragend={onDragEnd}+ >+ <button+ type="button"+ class="play-cell"+ onclick={() => musicPlayer.play(track, tracks)}+ >+ <span class="num">{i + 1}</span>+ <CoverImage src={track.cover_path} alt={track.title ?? track.path} size={36} fallbackSeed={track.album ?? track.title} rounded="sm" />+ <span class="info">+ <span class="title">{track.title ?? track.path}</span>+ {#if track.artist}+ <span class="artist">{track.artist}</span>+ {/if}+ </span>+ {#if track.album}+ <span class="album">{track.album}</span>+ {/if}+ <span class="dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ <div class="row-actions">+ <button+ type="button"+ class="ico"+ onclick={() => moveTrack(i, i - 1)}+ disabled={i === 0}+ aria-label="Subir"+ title="Subir"+ >↑</button>+ <button+ type="button"+ class="ico"+ onclick={() => moveTrack(i, i + 1)}+ disabled={i === tracks.length - 1}+ aria-label="Descer"+ title="Descer"+ >↓</button>+ <button+ type="button"+ class="ico danger"+ onclick={() => removeTrack(track)}+ aria-label={$t("study.music.remove_from_playlist") as string}+ title={$t("study.music.remove_from_playlist") as string}+ >×</button>+ </div>+ </li>+ {/each}+ </ol>+ {/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">+ <h3>{$t("study.music.delete_confirm_title")}</h3>+ <p>{$t("study.music.delete_confirm_msg", { name: detail.name })}</p>+ <div class="confirm-actions">+ <button type="button" class="ghost" onclick={() => (confirmDeleteOpen = false)}>+ {$t("study.common.cancel")}+ </button>+ <button type="button" class="danger" onclick={performDelete}>+ {$t("study.music.delete_confirm")}+ </button>+ </div>+ </div>+ </div>+ {/if}+ {/if}+</section>++<style>+ .playlist-page { display: flex; flex-direction: column; gap: 18px; }+ .hero {+ display: flex;+ align-items: flex-end;+ gap: 24px;+ padding: 24px 4px 18px;+ }+ .cover-block {+ flex-shrink: 0;+ width: clamp(160px, 22vw, 220px);+ aspect-ratio: 1 / 1;+ border-radius: 10px;+ overflow: hidden;+ box-shadow: 0 12px 36px color-mix(in oklab, black 32%, transparent);+ }+ .meta { display: flex; flex-direction: column; gap: 10px; min-width: 0; flex: 1; }+ .eyebrow { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; color: var(--tertiary); }+ .meta h1 {+ margin: 0;+ font-size: clamp(28px, 4.5vw, 56px);+ font-weight: 800;+ letter-spacing: -0.02em;+ color: var(--secondary);+ cursor: text;+ overflow-wrap: anywhere;+ }+ .meta h1:hover { color: var(--accent); }+ .title-edit {+ margin: 0;+ font-size: clamp(28px, 4.5vw, 56px);+ font-weight: 800;+ letter-spacing: -0.02em;+ color: var(--secondary);+ background: transparent;+ border: 0;+ border-bottom: 2px solid var(--accent);+ outline: none;+ font-family: inherit;+ width: 100%;+ }+ .info { display: flex; gap: 6px; align-items: center; color: var(--tertiary); font-size: 13px; }+ .info .dot { opacity: 0.6; }+ .actions { display: flex; align-items: center; gap: 10px; margin-top: 6px; }+ .play-big {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 10px 22px; 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) 35%, transparent);+ transition: transform 120ms ease;+ }+ .play-big:hover:not(:disabled) { transform: scale(1.04); }+ .play-big:disabled { opacity: 0.4; cursor: default; }+ .ghost-big {+ width: 40px; height: 40px; padding: 0;+ background: transparent; border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 50%; color: var(--tertiary); cursor: pointer;+ display: grid; place-items: center;+ transition: color 120ms ease, border-color 120ms ease;+ }+ .ghost-big:hover:not(:disabled) { color: var(--accent); border-color: var(--accent); }+ .ghost-big.danger:hover { color: var(--error, #dc2626); border-color: var(--error, #dc2626); }+ .ghost-big:disabled { opacity: 0.4; cursor: default; }++ .track-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1px; }+ .track-li {+ display: grid;+ grid-template-columns: 1fr auto;+ gap: 8px;+ align-items: center;+ padding: 0 4px;+ border-radius: 6px;+ transition: background 120ms ease;+ }+ .track-li.dragover {+ background: color-mix(in oklab, var(--accent) 16%, transparent);+ outline: 1px dashed var(--accent);+ }+ .play-cell {+ display: grid;+ grid-template-columns: 32px 36px 1fr minmax(120px, 200px) auto;+ gap: 12px;+ align-items: center;+ padding: 6px 8px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: var(--secondary);+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease;+ min-width: 0;+ }+ .play-cell:hover { background: color-mix(in oklab, var(--accent) 6%, transparent); }+ .num { color: var(--tertiary); font-size: 12px; font-variant-numeric: tabular-nums; text-align: center; }+ .info { display: flex; flex-direction: column; min-width: 0; overflow: hidden; }+ .title { font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .artist { font-size: 11px; color: var(--tertiary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .album { font-size: 12px; color: var(--tertiary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .dur { font-size: 12px; color: var(--tertiary); font-variant-numeric: tabular-nums; min-width: 48px; text-align: right; }+ .row-actions {+ display: flex;+ gap: 4px;+ opacity: 0;+ transition: opacity 120ms ease;+ }+ .track-li:hover .row-actions { opacity: 1; }+ .ico {+ width: 26px; height: 26px; padding: 0;+ background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 60%, transparent);+ border-radius: 4px;+ color: var(--tertiary);+ cursor: pointer;+ font-family: inherit;+ font-size: 12px;+ line-height: 1;+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .ico:hover:not(:disabled) {+ color: var(--accent);+ border-color: var(--accent);+ background: color-mix(in oklab, var(--accent) 8%, transparent);+ }+ .ico.danger:hover {+ color: var(--error, #dc2626);+ border-color: var(--error, #dc2626);+ background: color-mix(in oklab, var(--error, #dc2626) 10%, transparent);+ }+ .ico:disabled { opacity: 0.3; cursor: default; }++ .empty {+ padding: 48px 24px;+ text-align: center;+ color: var(--tertiary);+ }+ .empty p { margin: 0; }+ .empty .sub { margin-top: 4px; font-size: 13px; }++ .confirm-overlay {+ position: fixed;+ inset: 0;+ background: color-mix(in oklab, black 50%, transparent);+ display: grid;+ place-items: center;+ z-index: 250;+ }+ .confirm-dialog {+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 12px;+ padding: 20px;+ max-width: 380px;+ box-shadow: 0 16px 40px color-mix(in oklab, black 38%, transparent);+ }+ .confirm-dialog h3 { margin: 0 0 8px; font-size: 16px; color: var(--secondary); }+ .confirm-dialog p { margin: 0 0 16px; color: var(--tertiary); font-size: 13px; }+ .confirm-actions { display: flex; justify-content: flex-end; gap: 8px; }+ .confirm-actions .ghost {+ padding: 8px 14px; background: transparent;+ border: 1px solid color-mix(in oklab, var(--content-border) 70%, transparent);+ border-radius: 8px; color: var(--secondary); font-family: inherit; font-size: 13px; cursor: pointer;+ }+ .confirm-actions .danger {+ 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;+ }+ .muted { color: var(--tertiary); font-size: 13px; }+ .error { color: var(--error, #dc2626); font-size: 13px; }+ @media (max-width: 720px) {+ .hero { flex-direction: column; align-items: flex-start; }+ .play-cell { grid-template-columns: 28px 36px 1fr auto; }+ .album { display: none; }+ }+</style>diff --git a/src/routes/study/music/search/+page.svelte b/src/routes/study/music/search/+page.sveltenew file mode 100644index 00000000..b27731de--- /dev/null+++ b/src/routes/study/music/search/+page.svelte@@ -0,0 +1,235 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { pluginInvoke } from "$lib/plugin-invoke";+ import { t } from "$lib/i18n";+ import TrackRow from "$lib/study-music-components/TrackRow.svelte";+ import AlbumCard from "$lib/study-music-components/AlbumCard.svelte";+ import type { MusicTrack } from "$lib/study-music/player-store.svelte";++ type Album = {+ name: string;+ artist: string | null;+ cover_path: string | null;+ track_count: number;+ year: number | null;+ };++ let q = $state("");+ let tracks = $state<MusicTrack[]>([]);+ let albums = $state<Album[]>([]);+ let artists = $state<string[]>([]);+ let loading = $state(false);+ let inputRef = $state<HTMLInputElement | null>(null);+ let timer: ReturnType<typeof setTimeout> | null = null;++ async function runSearch(query: string) {+ if (!query.trim()) {+ tracks = [];+ albums = [];+ artists = [];+ loading = false;+ return;+ }+ loading = true;+ try {+ const tracksRes = await pluginInvoke<{ tracks: MusicTrack[] }>(+ "study",+ "study:music:tracks:search",+ { q: query, limit: 60 },+ );+ tracks = tracksRes.tracks ?? [];++ const albumNames = new Set<string>();+ const artistNames = new Set<string>();+ const albumByKey = new Map<string, Album>();++ for (const tr of tracks) {+ if (tr.album && !albumNames.has(tr.album)) {+ albumNames.add(tr.album);+ albumByKey.set(tr.album, {+ name: tr.album,+ artist: tr.album_artist ?? tr.artist ?? null,+ cover_path: tr.cover_path,+ track_count: 0,+ year: tr.year ?? null,+ });+ }+ if (tr.artist) artistNames.add(tr.artist);+ if (tr.album_artist) artistNames.add(tr.album_artist);+ }+ for (const tr of tracks) {+ if (tr.album) {+ const a = albumByKey.get(tr.album);+ if (a) a.track_count += 1;+ }+ }+ albums = [...albumByKey.values()].slice(0, 12);+ artists = [...artistNames].slice(0, 20);+ } finally {+ loading = false;+ }+ }++ function onInput(e: Event) {+ q = (e.target as HTMLInputElement).value;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => runSearch(q), 200);+ }++ onMount(() => {+ inputRef?.focus();+ return () => {+ if (timer) clearTimeout(timer);+ };+ });+</script>++<section class="search-page">+ <header class="head">+ <div class="search-box">+ <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.search_placeholder")}+ autocomplete="off"+ />+ {#if q}+ <button+ type="button"+ class="clear"+ onclick={() => { q = ""; tracks = []; albums = []; artists = []; }}+ aria-label={$t("study.common.clear") as string}+ >×</button>+ {/if}+ </div>+ </header>++ {#if !q.trim()}+ <div class="empty">+ <p>{$t("study.music.search_hint")}</p>+ </div>+ {:else if loading}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if tracks.length === 0 && albums.length === 0 && artists.length === 0}+ <div class="empty">+ <p>{$t("study.music.empty_results")}</p>+ </div>+ {:else}+ {#if tracks.length > 0}+ <section class="block">+ <h2>{$t("study.music.tab_tracks")}</h2>+ <ul class="track-list">+ {#each tracks.slice(0, 10) as track (track.id)}+ <TrackRow {track} queue={tracks} showCover showAlbum />+ {/each}+ </ul>+ </section>+ {/if}++ {#if albums.length > 0}+ <section class="block">+ <h2>{$t("study.music.tab_albums")}</h2>+ <div class="album-grid">+ {#each albums as album (album.name + (album.artist ?? ""))}+ <AlbumCard {album} href={`/study/music/album/by-name?name=${encodeURIComponent(album.name)}${album.artist ? `&artist=${encodeURIComponent(album.artist)}` : ""}`} />+ {/each}+ </div>+ </section>+ {/if}++ {#if artists.length > 0}+ <section class="block">+ <h2>{$t("study.music.tab_artists")}</h2>+ <ul class="artist-pills">+ {#each artists as name (name)}+ <li>+ <a class="artist-pill" href={`/study/music/artist/by-name?name=${encodeURIComponent(name)}`}>+ {name}+ </a>+ </li>+ {/each}+ </ul>+ </section>+ {/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 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; }+ .album-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));+ gap: 16px;+ }+ .artist-pills {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ }+ .artist-pill {+ display: inline-flex;+ padding: 6px 14px;+ background: color-mix(in oklab, var(--button) 60%, transparent);+ border: 1px solid color-mix(in oklab, var(--content-border) 50%, transparent);+ border-radius: 999px;+ color: var(--secondary);+ font-size: 12px;+ text-decoration: none;+ transition: border-color 120ms ease, color 120ms ease, background 120ms ease;+ }+ .artist-pill:hover {+ border-color: var(--accent);+ 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.sveltenew file mode 100644index 00000000..c98c366a--- /dev/null+++ b/src/routes/study/music/soundcloud/+page.svelte@@ -0,0 +1,424 @@+<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 {+ soundcloudStore,+ type ScTrack,+ } from "$lib/study-music/soundcloud-store.svelte";+ import { colorFromString } from "$lib/study-music/format";+ import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";++ let booting = $state(true);+ let downloadTrack = $state<ScTrack | null>(null);++ let importOpen = $state(false);+ let importUrl = $state("");+ let importBusy = $state(false);+ let importError = $state<string | 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;+ });++ async function loadRecommended() {+ const seed = soundcloudStore.likedTracks[0] ?? soundcloudStore.streamFeed[0];+ if (!seed) return;+ try {+ const tracks = await soundcloudStore.relatedTracks(seed.id, 12);+ recommended = tracks;+ recommendedSeed = seed;+ } catch (e) {+ console.warn("[soundcloud] related failed", e);+ }+ }++ async function refresh() {+ await soundcloudStore.refreshStatus();+ await soundcloudStore.loadAll();+ void loadRecommended();+ }++ async function openInBrowser() {+ const { open } = await import("@tauri-apps/plugin-shell");+ await open("https://soundcloud.com/signin");+ }++ async function play(track: ScTrack, queue?: ScTrack[]) {+ try {+ await soundcloudStore.playTrack(track, queue);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ 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 openImport() {+ importUrl = "";+ importError = null;+ importOpen = true;+ }++ function closeImport() {+ importOpen = false;+ }++ async function submitImport() {+ if (importBusy) return;+ const url = importUrl.trim();+ if (!url || !url.includes("soundcloud.com")) {+ importError = $t("study.music.sc_import_invalid") as string;+ return;+ }+ importBusy = true;+ importError = null;+ try {+ const res = await soundcloudStore.resolveAnyUrl(url);+ if (res.kind === "track" && res.data?.id) {+ const track: any = res.data;+ const queue: ScTrack[] = [+ {+ id: track.id,+ title: track.title ?? "",+ duration: track.duration ?? 0,+ artwork_url: track.artwork_url ?? null,+ permalink_url: track.permalink_url ?? "",+ streamable: track.streamable ?? true,+ downloadable: track.downloadable ?? false,+ user: {+ id: track.user?.id ?? 0,+ username: track.user?.username ?? "",+ avatar_url: track.user?.avatar_url ?? null,+ permalink: track.user?.permalink ?? "",+ permalink_url: track.user?.permalink_url ?? "",+ },+ playback_count: track.playback_count ?? 0,+ likes_count: track.likes_count ?? 0,+ },+ ];+ await play(queue[0], queue);+ showToast(+ "success",+ $t("study.music.sc_import_success", { title: res.title || track.title }) as string,+ );+ importOpen = false;+ } else if (res.kind === "playlist" && res.data?.id) {+ importOpen = false;+ showToast(+ "success",+ $t("study.music.sc_import_success", { title: res.title }) as string,+ );+ goto(`/study/music/soundcloud/playlist/${res.data.id}`);+ } else if ((res.kind === "user" || res.kind === "user-resource") && res.data?.id) {+ importOpen = false;+ goto(`/study/music/soundcloud/user/${res.data.id}`);+ } else {+ importError = $t("study.music.sc_import_invalid") as string;+ }+ } catch (e) {+ const err = e instanceof Error ? e.message : String(e);+ importError = $t("study.music.sc_import_failed", { error: err }) as string;+ } finally {+ importBusy = false;+ }+ }+</script>++<section class="sc-home">+ <header class="page-head">+ <h1>{$t('study.music.sc_title')}</h1>+ {#if soundcloudStore.isLoggedIn && soundcloudStore.profile}+ <div class="head-actions">+ <button type="button" class="cta-import" onclick={openImport}>+ <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">+ <line x1="12" y1="5" x2="12" y2="19"/>+ <line x1="5" y1="12" x2="19" y2="12"/>+ </svg>+ {$t('study.music.sc_import_url')}+ </button>+ <button type="button" class="ghost-btn" onclick={() => goto("/study/music/soundcloud/search")}>+ <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>+ {$t('study.music.sc_search')}+ </button>+ <button type="button" class="ghost-btn" onclick={refresh} title={$t('study.music.sc_refresh') as string} aria-label={$t('study.music.sc_refresh') 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">+ <polyline points="23 4 23 10 17 10"/>+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>+ </svg>+ </button>+ <span class="profile-pill">+ {#if soundcloudStore.profile.avatar_url}+ <img src={soundcloudStore.pickArtwork(soundcloudStore.profile.avatar_url)} alt="" />+ {/if}+ <span>{soundcloudStore.profile.username}</span>+ </span>+ <button type="button" class="ghost-btn" onclick={() => soundcloudStore.logout()}>{$t('study.music.sc_logout')}</button>+ </div>+ {/if}+ </header>++ {#if booting}+ <p class="muted">{$t('study.music.sc_loading')}</p>+ {:else if !soundcloudStore.isLoggedIn}+ <div class="login-card">+ <div class="logo">+ <svg viewBox="0 0 24 24" width="80" height="80" fill="#ff5500" aria-hidden="true">+ <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>+ <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>+ </div>+ {#if soundcloudStore.error}+ <p class="error">{soundcloudStore.error}</p>+ {/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 recommended.length > 0}+ <section class="block">+ <header class="block-head">+ <h2>{$t('study.music.sc_section_recommended', { name: recommendedSeed?.title ?? $t('study.music.sc_recommended_seed_fallback') })}</h2>+ </header>+ <div class="track-list">+ {#each recommended as track (track.id)}+ <div class="track-row" role="button" tabindex="0" onclick={() => play(track, recommended)} onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); play(track, recommended); } }}>+ <div class="track-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="track-fallback" style:background={colorFromString(track.title)}></div>+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{track.title}</span>+ <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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if soundcloudStore.streamFeed.length > 0}+ <section class="block">+ <header class="block-head"><h2>{$t('study.music.sc_section_stream')}</h2></header>+ <div class="track-list">+ {#each soundcloudStore.streamFeed.slice(0, 12) as track (track.id)}+ <div class="track-row" role="button" tabindex="0" onclick={() => play(track, soundcloudStore.streamFeed)} onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); play(track, soundcloudStore.streamFeed); } }}>+ <div class="track-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="track-fallback" style:background={colorFromString(track.title)}></div>+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{track.title}</span>+ <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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if soundcloudStore.likedTracks.length > 0}+ <section class="block">+ <header class="block-head"><h2>{$t('study.music.sc_section_likes', { count: soundcloudStore.likedTracks.length })}</h2></header>+ <div class="track-list">+ {#each soundcloudStore.likedTracks.slice(0, 30) as track, i (track.id)}+ <div class="track-row" role="button" tabindex="0" onclick={() => play(track, soundcloudStore.likedTracks)} onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); play(track, soundcloudStore.likedTracks); } }}>+ <span class="track-num">{i + 1}</span>+ <div class="track-cover">+ {#if track.artwork_url || track.user.avatar_url}+ <img src={soundcloudStore.pickArtwork(track.artwork_url ?? track.user.avatar_url)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{track.title}</span>+ <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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if soundcloudStore.playlists.length > 0}+ <section class="block">+ <header class="block-head"><h2>{$t('study.music.sc_section_playlists')}</h2></header>+ <div class="grid">+ {#each soundcloudStore.playlists as p (p.id)}+ <a class="card" href={`/study/music/soundcloud/playlist/${p.id}`}>+ <div class="card-cover">+ {#if p.artwork_url}+ <img src={soundcloudStore.pickArtwork(p.artwork_url)} alt="" loading="lazy" />+ {:else}+ <div class="card-fallback" style:background={colorFromString(p.title)}></div>+ {/if}+ </div>+ <h3 class="card-title">{p.title}</h3>+ <p class="card-sub">{$t('study.music.sc_track_count', { count: p.track_count })} · {p.user.username}</p>+ </a>+ {/each}+ </div>+ </section>+ {/if}++ {#if soundcloudStore.followings.length > 0}+ <section class="block">+ <header class="block-head"><h2>{$t('study.music.sc_section_following')}</h2></header>+ <div class="grid">+ {#each soundcloudStore.followings as u (u.id)}+ <a class="card" href={`/study/music/soundcloud/user/${u.id}`}>+ <div class="card-circle">+ {#if u.avatar_url}+ <img src={soundcloudStore.pickArtwork(u.avatar_url)} alt="" loading="lazy" />+ {:else}+ <div class="card-fallback round" style:background={colorFromString(u.username)}>{u.username.slice(0,1).toUpperCase()}</div>+ {/if}+ </div>+ <h3 class="card-title center">{u.username}</h3>+ {#if u.followers_count}<p class="card-sub center">{$t('study.music.sc_followers_count', { count: u.followers_count.toLocaleString() })}</p>{/if}+ </a>+ {/each}+ </div>+ </section>+ {/if}+ {/if}+</section>++{#if downloadTrack}+ <SoundCloudDownloadDialog track={downloadTrack} onClose={() => (downloadTrack = null)} />+{/if}++{#if importOpen}+ <div class="overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) closeImport(); }}>+ <div class="dialog" role="dialog" aria-modal="true">+ <header class="d-head">+ <h3>{$t('study.music.sc_import_url_title')}</h3>+ <button type="button" class="d-close" onclick={closeImport} aria-label="close">×</button>+ </header>+ <div class="d-body">+ <p class="d-hint">{$t('study.music.sc_import_url_desc')}</p>+ <input+ type="url"+ class="d-input"+ 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}+ </div>+ <footer class="d-foot">+ <button type="button" class="ghost-btn" onclick={closeImport}>{$t('common.cancel')}</button>+ <button type="button" class="cta" disabled={importBusy || !importUrl.trim()} onclick={submitImport}>+ {importBusy ? $t('study.music.sc_loading') : $t('study.music.sc_import_action')}+ </button>+ </footer>+ </div>+ </div>+{/if}++<style>+ .sc-home { display: flex; flex-direction: column; gap: 32px; color: rgba(255,255,255,0.95); }+ .page-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }+ .page-head h1 { margin: 0; font-size: clamp(28px,3.5vw,40px); font-weight: 900; letter-spacing: -0.02em; }+ .head-actions { display: flex; align-items: center; gap: 12px; }+ .profile-pill { display: inline-flex; align-items: center; gap: 8px; padding: 4px 12px 4px 4px; background: rgba(255,255,255,0.05); border-radius: 999px; font-size: 13px; font-weight: 600; }+ .profile-pill img { width: 28px; height: 28px; border-radius: 50%; object-fit: cover; }+ .ghost-btn { display: inline-flex; align-items: center; gap: 6px; padding: 7px 16px; background: rgba(255,255,255,0.05); border: 0; 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; }+ .ghost-btn:hover { background: rgba(255,255,255,0.1); }+ .cta-import { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: #ff5500; color: white; border: 0; border-radius: 999px; font-family: inherit; font-size: 12px; font-weight: 700; cursor: pointer; transition: background 200ms ease; }+ .cta-import:hover { background: #ff7733; }+ .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.65); display: grid; place-items: center; z-index: 999; }+ .dialog { background: #1c1c1c; border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; width: min(480px, 92vw); display: flex; flex-direction: column; }+ .d-head { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid rgba(255,255,255,0.05); }+ .d-head h3 { margin: 0; font-size: 16px; font-weight: 700; }+ .d-close { background: transparent; border: 0; color: rgba(255,255,255,0.6); font-size: 22px; line-height: 1; cursor: pointer; padding: 0 8px; }+ .d-body { padding: 16px 20px; display: flex; flex-direction: column; gap: 12px; }+ .d-hint { margin: 0; color: rgba(255,255,255,0.6); font-size: 13px; line-height: 1.5; }+ .d-input { width: 100%; padding: 12px 14px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: inherit; font-size: 14px; box-sizing: border-box; }+ .d-input:focus { outline: 0; border-color: #ff5500; }+ .d-error { margin: 0; color: #e22134; font-size: 13px; }+ .d-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 20px; border-top: 1px solid rgba(255,255,255,0.05); }+ .d-foot .cta { padding: 9px 22px; }+ .d-foot .cta:disabled { opacity: 0.5; cursor: not-allowed; }++ .login-card { margin: 0 auto; max-width: 540px; padding: 56px 32px; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 16px; }+ .login-card h2 { margin: 0; font-size: 28px; font-weight: 800; }+ .login-card p { margin: 0; color: rgba(255,255,255,0.6); font-size: 14px; line-height: 1.6; max-width: 44ch; }+ .login-actions { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; margin-top: 8px; }+ .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); }++ .block { display: flex; flex-direction: column; gap: 16px; }+ .block-head h2 { margin: 0; font-size: 22px; font-weight: 800; }+ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 28px 56px 1fr 60px 32px; gap: 12px; align-items: center; padding: 8px 12px; background: transparent; border: 0; border-radius: 6px; color: inherit; cursor: pointer; text-align: left; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .track-num { color: rgba(255,255,255,0.5); font-size: 12px; text-align: center; }+ .track-cover { width: 44px; height: 44px; border-radius: 4px; overflow: hidden; background: rgba(40,40,40,0.8); }+ .track-cover img { width: 100%; height: 100%; object-fit: cover; }+ .track-fallback { width: 100%; height: 100%; }+ .track-meta { display: flex; flex-direction: column; min-width: 0; }+ .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; }+ .card-cover, .card-circle { aspect-ratio: 1/1; border-radius: 12px; overflow: hidden; margin-bottom: 12px; background: rgba(40,40,40,0.8); }+ .card-circle { border-radius: 50%; }+ .card-cover img, .card-circle img { width: 100%; height: 100%; object-fit: cover; transition: transform 500ms ease; }+ .card:hover .card-cover img, .card:hover .card-circle img { transform: scale(1.05); }+ .card-fallback { width: 100%; height: 100%; display: grid; place-items: center; color: white; font-size: 32px; font-weight: 800; }+ .card-fallback.round { border-radius: 50%; }+ .card-title { margin: 0; font-size: 14px; font-weight: 700; color: white; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; }+ .card-title.center { text-align: center; }+ .card-sub { margin: 4px 0 0; font-size: 12px; color: rgba(255,255,255,0.5); padding: 0 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .card-sub.center { text-align: center; }++ .muted { color: rgba(255,255,255,0.5); font-size: 13px; }+ @media (prefers-reduced-motion: reduce) { .card-cover img, .card-circle img { transition: none; } .card:hover .card-cover img, .card:hover .card-circle img { transform: none; } }+</style>diff --git a/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte b/src/routes/study/music/soundcloud/playlist/[id]/+page.sveltenew file mode 100644index 00000000..61ad69bb--- /dev/null+++ b/src/routes/study/music/soundcloud/playlist/[id]/+page.svelte@@ -0,0 +1,215 @@+<script lang="ts">+ 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 {+ soundcloudStore,+ type ScPlaylist,+ type ScTrack,+ } from "$lib/study-music/soundcloud-store.svelte";+ import { colorFromString } from "$lib/study-music/format";+ import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";++ let playlist = $state<ScPlaylist | null>(null);+ let tracks = $state<ScTrack[]>([]);+ let loading = $state(true);+ let error = $state<string | 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 () => {+ if (!playlistId) {+ goto("/study/music/soundcloud");+ return;+ }+ try {+ const p = await soundcloudStore.getPlaylist(playlistId);+ playlist = p;+ tracks = p?.tracks ?? [];+ } 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)];+ try {+ await soundcloudStore.playTrack(reordered[0], reordered);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ 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")}`;+ }++ 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;+ bulkBusy = true;+ bulkCurrent = 0;+ bulkTotal = tracks.length;+ 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({+ playlistId,+ codec: "mp3",+ outputDir: picked,+ quality: "progressive",+ });+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ bulkUnlisten?.();+ bulkUnlisten = null;+ bulkBusy = false;+ }+ }+</script>++<section class="page">+ <button type="button" class="back" onclick={() => history.back()}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Voltar+ </button>++ {#if playlist}+ <header class="hero">+ <div class="cover">+ {#if playlist.artwork_url}+ <img src={soundcloudStore.pickArtwork(playlist.artwork_url)} alt="" />+ {:else}+ <div class="cover-fb" style:background={colorFromString(playlist.title)}></div>+ {/if}+ </div>+ <div class="info">+ <span class="eyebrow">{playlist.is_album ? "Álbum" : "Playlist"}</span>+ <h1>{playlist.title}</h1>+ <p class="meta">{playlist.user.username} · {playlist.track_count} faixas · {fmtDuration(playlist.duration)}</p>+ {#if playlist.description}+ <p class="desc">{playlist.description}</p>+ {/if}+ <div class="actions">+ <button type="button" class="play-btn" onclick={() => play(0)} disabled={tracks.length === 0}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ Tocar+ </button>+ <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 })+ : $t('study.music.sc_download_all', { count: tracks.length })}+ </button>+ </div>+ </div>+ </header>+ {/if}++ {#if loading}+ <p class="muted">Carregando…</p>+ {:else if error}+ <p class="error">{error}</p>+ {:else}+ <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); } }}>+ <span class="num">{i + 1}</span>+ <div class="cov">+ {#if track.artwork_url}+ <img src={soundcloudStore.pickArtwork(track.artwork_url)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="m">+ <span class="t">{track.title}</span>+ <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>+ </div>+ {/each}+ </div>+ {/if}+</section>++{#if downloadTrack}+ <SoundCloudDownloadDialog track={downloadTrack} onClose={() => (downloadTrack = null)} />+{/if}++<style>+ .page { display: flex; flex-direction: column; gap: 24px; color: rgba(255,255,255,0.95); }+ .back { align-self: flex-start; display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px 6px 8px; background: rgba(255,255,255,0.05); border: 0; border-radius: 999px; color: rgba(255,255,255,0.85); font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }+ .back:hover { background: rgba(255,255,255,0.1); }+ .hero { display: flex; gap: 32px; align-items: flex-end; padding: 24px 0; }+ .cover { width: 220px; height: 220px; border-radius: 8px; overflow: hidden; flex-shrink: 0; box-shadow: 0 4px 60px rgba(0,0,0,0.5); }+ .cover img { width: 100%; height: 100%; object-fit: cover; }+ .cover-fb { width: 100%; height: 100%; }+ .info { display: flex; flex-direction: column; gap: 8px; min-width: 0; }+ .eyebrow { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: rgba(255,255,255,0.6); }+ .info h1 { margin: 0; font-size: clamp(28px,4vw,56px); font-weight: 900; letter-spacing: -0.02em; line-height: 1.05; }+ .meta { margin: 0; color: rgba(255,255,255,0.5); font-size: 13px; }+ .desc { margin: 0; color: rgba(255,255,255,0.4); font-size: 13px; max-width: 60ch; }+ .actions { margin-top: 8px; display: flex; gap: 12px; }+ .play-btn { display: inline-flex; align-items: center; gap: 8px; 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, transform 200ms ease; }+ .play-btn:hover:not(:disabled) { background: #ff7733; transform: scale(1.04); }+ .play-btn:disabled { opacity: 0.5; cursor: default; }+ .bulk-btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 22px; background: rgba(255,255,255,0.06); color: rgba(255,255,255,0.92); border: 1px solid rgba(255,255,255,0.12); border-radius: 999px; font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer; transition: background 200ms ease; }+ .bulk-btn:hover:not(:disabled) { background: rgba(255,255,255,0.12); }+ .bulk-btn:disabled { opacity: 0.6; cursor: not-allowed; }+ .actions { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }+ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 28px 56px 1fr 60px 32px; gap: 12px; align-items: center; padding: 8px 12px; border-radius: 6px; cursor: pointer; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .num { color: rgba(255,255,255,0.5); font-size: 12px; text-align: center; }+ .cov { width: 44px; height: 44px; border-radius: 4px; overflow: hidden; background: rgba(40,40,40,0.8); }+ .cov img { width: 100%; height: 100%; object-fit: cover; }+ .m { display: flex; flex-direction: column; min-width: 0; }+ .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.sveltenew file mode 100644index 00000000..13afafec--- /dev/null+++ b/src/routes/study/music/soundcloud/search/+page.svelte@@ -0,0 +1,203 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ soundcloudStore,+ type ScPlaylist,+ type ScTrack,+ type ScUser,+ } from "$lib/study-music/soundcloud-store.svelte";+ import { colorFromString } from "$lib/study-music/format";+ import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.svelte";++ type Tab = "tracks" | "playlists" | "users";++ let query = $state("");+ let tab = $state<Tab>("tracks");+ let inputRef = $state<HTMLInputElement | null>(null);++ let tracks = $state<ScTrack[]>([]);+ let playlists = $state<ScPlaylist[]>([]);+ let users = $state<ScUser[]>([]);+ let loading = $state(false);+ let downloadTrack = $state<ScTrack | null>(null);+ let timer: ReturnType<typeof setTimeout> | null = null;++ onMount(() => {+ if (!soundcloudStore.isLoggedIn) {+ goto("/study/music/soundcloud");+ return;+ }+ queueMicrotask(() => inputRef?.focus());+ });++ function onInput() {+ if (timer) clearTimeout(timer);+ if (!query.trim()) {+ tracks = [];+ playlists = [];+ users = [];+ return;+ }+ timer = setTimeout(() => doSearch(), 350);+ }++ async function doSearch() {+ const q = query.trim();+ if (!q) return;+ loading = true;+ try {+ const [t, p, u] = await Promise.allSettled([+ soundcloudStore.search("tracks", q, 30),+ soundcloudStore.search("playlists", q, 20),+ soundcloudStore.search("users", q, 20),+ ]);+ tracks = (t.status === "fulfilled" ? (t.value as ScTrack[]) : []) ?? [];+ playlists = (p.status === "fulfilled" ? (p.value as ScPlaylist[]) : []) ?? [];+ users = (u.status === "fulfilled" ? (u.value as ScUser[]) : []) ?? [];+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ loading = false;+ }+ }++ async function play(track: ScTrack, queueAll: ScTrack[]) {+ try {+ await soundcloudStore.playTrack(track, queueAll);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ 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")}`;+ }+</script>++<section class="page">+ <header class="head">+ <button type="button" class="back" onclick={() => goto("/study/music/soundcloud")}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ SoundCloud+ </button>+ </header>++ <div class="search-bar">+ <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">+ <circle cx="11" cy="11" r="8"/>+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>+ </svg>+ <input+ bind:this={inputRef}+ bind:value={query}+ oninput={onInput}+ type="search"+ placeholder="Buscar no SoundCloud…"+ autocomplete="off"+ />+ {#if loading}<span class="spinner"></span>{/if}+ </div>++ {#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>+ <button type="button" class="tab" class:on={tab === "playlists"} onclick={() => (tab = "playlists")} role="tab" aria-selected={tab === "playlists"}>Playlists {playlists.length > 0 ? `(${playlists.length})` : ""}</button>+ <button type="button" class="tab" class:on={tab === "users"} onclick={() => (tab = "users")} role="tab" aria-selected={tab === "users"}>Artistas {users.length > 0 ? `(${users.length})` : ""}</button>+ </div>+ {/if}++ {#if tab === "tracks" && tracks.length > 0}+ <div class="track-list">+ {#each tracks as t, i (t.id)}+ <div class="track-row" role="button" tabindex="0" onclick={() => play(t, tracks)} onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); play(t, tracks); } }}>+ <div class="cov">+ {#if t.artwork_url}<img src={soundcloudStore.pickArtwork(t.artwork_url)} alt="" loading="lazy" />{/if}+ </div>+ <div class="m">+ <span class="t">{t.title}</span>+ <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>+ </div>+ {/each}+ </div>+ {:else if tab === "playlists" && playlists.length > 0}+ <div class="grid">+ {#each playlists as p (p.id)}+ <a class="card" href={`/study/music/soundcloud/playlist/${p.id}`}>+ <div class="card-cover">+ {#if p.artwork_url}<img src={soundcloudStore.pickArtwork(p.artwork_url)} alt="" loading="lazy" />{:else}<div class="cover-fb" style:background={colorFromString(p.title)}></div>{/if}+ </div>+ <h3 class="ct">{p.title}</h3>+ <p class="cs">{p.track_count} faixas · {p.user.username}</p>+ </a>+ {/each}+ </div>+ {:else if tab === "users" && users.length > 0}+ <div class="grid">+ {#each users as u (u.id)}+ <a class="card user-card" href={`/study/music/soundcloud/user/${u.id}`}>+ <div class="card-circle">+ {#if u.avatar_url}<img src={soundcloudStore.pickArtwork(u.avatar_url)} alt="" loading="lazy" />{:else}<div class="cover-fb round" style:background={colorFromString(u.username)}>{u.username.slice(0,1).toUpperCase()}</div>{/if}+ </div>+ <h3 class="ct center">{u.username}</h3>+ {#if u.followers_count}<p class="cs center">{u.followers_count.toLocaleString("pt-BR")} seguidores</p>{/if}+ </a>+ {/each}+ </div>+ {:else if query.trim() && !loading}+ <p class="muted">Nada encontrado para "{query}"</p>+ {/if}+</section>++{#if downloadTrack}+ <SoundCloudDownloadDialog track={downloadTrack} onClose={() => (downloadTrack = null)} />+{/if}++<style>+ .page { display: flex; flex-direction: column; gap: 24px; color: rgba(255,255,255,0.95); }+ .head { display: flex; }+ .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px 6px 8px; background: rgba(255,255,255,0.05); border: 0; border-radius: 999px; color: rgba(255,255,255,0.85); font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }+ .back:hover { background: rgba(255,255,255,0.1); }+ .search-bar { position: relative; display: flex; align-items: center; gap: 12px; background: rgba(255,255,255,0.06); border-radius: 999px; padding: 12px 20px; color: rgba(255,255,255,0.6); }+ .search-bar input { flex: 1; background: transparent; border: 0; outline: 0; color: white; font-family: inherit; font-size: 15px; }+ .spinner { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.2); border-top-color: #ff5500; border-radius: 50%; animation: spin 0.8s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ .tabs { display: flex; gap: 8px; border-bottom: 1px solid rgba(255,255,255,0.08); }+ .tab { padding: 8px 16px; background: transparent; border: 0; border-bottom: 2px solid transparent; color: rgba(255,255,255,0.55); font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer; transition: color 200ms ease, border-color 200ms ease; }+ .tab:hover { color: white; }+ .tab.on { color: white; border-bottom-color: #ff5500; }+ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 56px 1fr 60px 32px; gap: 12px; align-items: center; padding: 8px 12px; border-radius: 6px; cursor: pointer; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .cov { width: 44px; height: 44px; border-radius: 4px; overflow: hidden; background: rgba(40,40,40,0.8); }+ .cov img { width: 100%; height: 100%; object-fit: cover; }+ .m { display: flex; flex-direction: column; min-width: 0; }+ .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); }+ .card-circle { border-radius: 50%; }+ .card-cover img, .card-circle img { width: 100%; height: 100%; object-fit: cover; transition: transform 500ms ease; }+ .card:hover .card-cover img, .card:hover .card-circle img { transform: scale(1.05); }+ .cover-fb { width: 100%; height: 100%; }+ .cover-fb.round { border-radius: 50%; display: grid; place-items: center; color: white; font-size: 32px; font-weight: 800; }+ .ct { margin: 0; font-size: 14px; font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; }+ .ct.center { text-align: center; }+ .cs { margin: 4px 0 0; font-size: 12px; color: rgba(255,255,255,0.5); padding: 0 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .cs.center { text-align: center; }+ .user-card { text-align: center; }+ .muted { color: rgba(255,255,255,0.5); font-size: 13px; text-align: center; padding: 32px 0; }+</style>diff --git a/src/routes/study/music/soundcloud/user/[id]/+page.svelte b/src/routes/study/music/soundcloud/user/[id]/+page.sveltenew file mode 100644index 00000000..7450d5a2--- /dev/null+++ b/src/routes/study/music/soundcloud/user/[id]/+page.svelte@@ -0,0 +1,199 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ soundcloudStore,+ type ScPlaylist,+ type ScTrack,+ type ScUser,+ } from "$lib/study-music/soundcloud-store.svelte";+ import { colorFromString } from "$lib/study-music/format";+ import SoundCloudDownloadDialog from "$lib/study-music-components/SoundCloudDownloadDialog.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 downloadTrack = $state<ScTrack | null>(null);++ const userId = $derived(parseInt($page.params.id ?? "0", 10));++ onMount(async () => {+ if (!userId) {+ goto("/study/music/soundcloud");+ return;+ }+ try {+ const [u, t, p] = await Promise.allSettled([+ soundcloudStore.getUser(userId),+ soundcloudStore.getUserTracks(userId, 50),+ soundcloudStore.getUserPlaylists(userId, 30),+ ]);+ if (u.status === "fulfilled") user = u.value;+ if (t.status === "fulfilled") tracks = t.value;+ if (p.status === "fulfilled") playlists = p.value;+ } 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)];+ try {+ await soundcloudStore.playTrack(reordered[0], reordered);+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ 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")}`;+ }+</script>++<section class="page">+ <button type="button" class="back" onclick={() => history.back()}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Voltar+ </button>++ {#if user}+ <header class="hero">+ <div class="circle">+ {#if user.avatar_url}+ <img src={soundcloudStore.pickArtwork(user.avatar_url)} alt="" />+ {:else}+ <div class="circle-fb" style:background={colorFromString(user.username)}>{user.username.slice(0,1).toUpperCase()}</div>+ {/if}+ </div>+ <div class="info">+ <span class="eyebrow">Artista</span>+ <h1>{user.username}</h1>+ <p class="meta">+ {#if user.followers_count}{user.followers_count.toLocaleString("pt-BR")} seguidores{/if}+ {#if user.city}{user.city}{user.country_code ? `, ${user.country_code}` : ""}{/if}+ </p>+ {#if user.description}+ <p class="desc">{user.description}</p>+ {/if}+ <div class="actions">+ <button type="button" class="play-btn" onclick={() => play(0)} disabled={tracks.length === 0}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ Tocar+ </button>+ </div>+ </div>+ </header>+ {/if}++ {#if loading}+ <p class="muted">Carregando…</p>+ {:else if error}+ <p class="error">{error}</p>+ {:else}+ {#if tracks.length > 0}+ <section class="block">+ <header class="block-head"><h2>Faixas ({tracks.length})</h2></header>+ <div class="track-list">+ {#each tracks.slice(0, 20) 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); } }}>+ <span class="num">{i + 1}</span>+ <div class="cov">+ {#if track.artwork_url}+ <img src={soundcloudStore.pickArtwork(track.artwork_url)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="m">+ <span class="t">{track.title}</span>+ {#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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if playlists.length > 0}+ <section class="block">+ <header class="block-head"><h2>Playlists</h2></header>+ <div class="grid">+ {#each playlists as p (p.id)}+ <a class="card" href={`/study/music/soundcloud/playlist/${p.id}`}>+ <div class="card-cover">+ {#if p.artwork_url}+ <img src={soundcloudStore.pickArtwork(p.artwork_url)} alt="" loading="lazy" />+ {:else}+ <div class="cover-fb" style:background={colorFromString(p.title)}></div>+ {/if}+ </div>+ <h3 class="card-title">{p.title}</h3>+ <p class="card-sub">{p.track_count} faixas</p>+ </a>+ {/each}+ </div>+ </section>+ {/if}+ {/if}+</section>++{#if downloadTrack}+ <SoundCloudDownloadDialog track={downloadTrack} onClose={() => (downloadTrack = null)} />+{/if}++<style>+ .page { display: flex; flex-direction: column; gap: 24px; color: rgba(255,255,255,0.95); }+ .back { align-self: flex-start; display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px 6px 8px; background: rgba(255,255,255,0.05); border: 0; border-radius: 999px; color: rgba(255,255,255,0.85); font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }+ .back:hover { background: rgba(255,255,255,0.1); }+ .hero { display: flex; gap: 32px; align-items: flex-end; padding: 24px 0; }+ .circle { width: 220px; height: 220px; border-radius: 50%; overflow: hidden; flex-shrink: 0; box-shadow: 0 4px 60px rgba(0,0,0,0.5); }+ .circle img { width: 100%; height: 100%; object-fit: cover; }+ .circle-fb { width: 100%; height: 100%; display: grid; place-items: center; color: white; font-size: 64px; font-weight: 800; }+ .info { display: flex; flex-direction: column; gap: 8px; min-width: 0; }+ .eyebrow { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: rgba(255,255,255,0.6); }+ .info h1 { margin: 0; font-size: clamp(28px,4vw,56px); font-weight: 900; letter-spacing: -0.02em; line-height: 1.05; }+ .meta { margin: 0; color: rgba(255,255,255,0.5); font-size: 13px; }+ .desc { margin: 0; color: rgba(255,255,255,0.4); font-size: 13px; max-width: 60ch; }+ .actions { margin-top: 8px; display: flex; gap: 12px; }+ .play-btn { display: inline-flex; align-items: center; gap: 8px; 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, transform 200ms ease; }+ .play-btn:hover:not(:disabled) { background: #ff7733; transform: scale(1.04); }+ .play-btn:disabled { opacity: 0.5; cursor: default; }+ .block { display: flex; flex-direction: column; gap: 16px; }+ .block-head h2 { margin: 0; font-size: 22px; font-weight: 800; }+ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 28px 56px 1fr 60px 32px; gap: 12px; align-items: center; padding: 8px 12px; border-radius: 6px; cursor: pointer; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .num { color: rgba(255,255,255,0.5); font-size: 12px; text-align: center; }+ .cov { width: 44px; height: 44px; border-radius: 4px; overflow: hidden; background: rgba(40,40,40,0.8); }+ .cov img { width: 100%; height: 100%; object-fit: cover; }+ .m { display: flex; flex-direction: column; min-width: 0; }+ .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); }+ .card-cover img { width: 100%; height: 100%; object-fit: cover; transition: transform 500ms ease; }+ .card:hover .card-cover img { transform: scale(1.05); }+ .cover-fb { width: 100%; height: 100%; }+ .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.sveltenew file mode 100644index 00000000..09a7ffe6--- /dev/null+++ b/src/routes/study/music/spotify/+page.svelte@@ -0,0 +1,847 @@+<script lang="ts">+ import { onMount, onDestroy } from "svelte";+ 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 { spotifyStore } from "$lib/study-music/spotify-store.svelte";+ import type {+ SpotifyArtist,+ SpotifyPlaylist,+ SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import { colorFromString } from "$lib/study-music/format";++ let unlistenSuccess: UnlistenFn | null = null;+ let unlistenError: UnlistenFn | null = null;+ let booting = $state(true);++ onMount(async () => {+ try {+ unlistenSuccess = await listen("study-spotify-auth-success", async () => {+ spotifyStore.authInProgress = false;+ await spotifyStore.refreshStatus();+ await spotifyStore.loadAll();+ void spotifyStore.prewarmSdk();+ showToast("success", "Conectado ao Spotify");+ });+ unlistenError = await listen<{ error: string }>(+ "study-spotify-auth-error",+ (event) => {+ spotifyStore.authInProgress = false;+ spotifyStore.error = event.payload.error ?? "Falha na autenticação";+ showToast("error", spotifyStore.error);+ },+ );+ } catch {+ /* ignore — listen unavailable in non-tauri context */+ }++ await spotifyStore.detectCapabilities();+ await spotifyStore.refreshStatus();+ if (spotifyStore.status.logged_in) {+ await spotifyStore.loadAll();+ void spotifyStore.prewarmSdk();+ }+ booting = false;+ });++ async function refreshLibrary() {+ await spotifyStore.loadAll();+ showToast("info", "Biblioteca atualizada");+ }++ onDestroy(() => {+ unlistenSuccess?.();+ unlistenError?.();+ });++ async function doLogin() {+ try {+ await spotifyStore.login();+ showToast(+ "info",+ "Aguardando autorização no navegador. Volte aqui depois de aceitar.",+ );+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ async function doCancel() {+ await spotifyStore.cancelAuth();+ }++ async function doLogout() {+ await spotifyStore.logout();+ showToast("info", "Desconectado do Spotify");+ }++ 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)");+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ function openPlaylist(p: SpotifyPlaylist) {+ goto(`/study/music/spotify/playlist/${p.id}`);+ }++ function openArtist(a: SpotifyArtist) {+ goto(`/study/music/spotify/artist/${a.id}`);+ }++ 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 fmtArtists(track: SpotifyTrack): string {+ return track.artists.map((a) => a.name).join(", ");+ }++ function scrollContainer(id: string, dir: 1 | -1) {+ const el = document.getElementById(id);+ if (!el) return;+ el.scrollBy({ left: dir * 360, behavior: "smooth" });+ }+</script>++<section class="spotify-home">+ <header class="page-head">+ <h1>Spotify</h1>+ {#if spotifyStore.status.logged_in && spotifyStore.profile}+ <div class="head-actions">+ {#if spotifyStore.isPremium}+ <button+ type="button"+ class="ghost-btn"+ onclick={() => goto("/study/music/spotify/search")}+ aria-label="Buscar no Spotify"+ >+ <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+ </button>+ {/if}+ <button type="button" class="ghost-btn" onclick={refreshLibrary}>+ Atualizar+ </button>+ <span class="profile-pill">+ {#if spotifyStore.profile.images?.[0]?.url}+ <img src={spotifyStore.profile.images[0].url} alt="" />+ {/if}+ <span>{spotifyStore.profile.display_name ?? spotifyStore.profile.id}</span>+ {#if spotifyStore.profile.product === "premium"}+ <span class="badge premium">Premium</span>+ {:else if spotifyStore.profile.product}+ <span class="badge">{spotifyStore.profile.product}</span>+ {/if}+ </span>+ <button type="button" class="ghost-btn" onclick={doLogout}>Sair</button>+ </div>+ {/if}+ </header>++ {#if booting}+ <p class="muted">{$t("study.common.loading")}</p>+ {:else if !spotifyStore.status.logged_in}+ <div class="login-card">+ <div class="login-art">+ <svg viewBox="0 0 168 168" width="120" height="120" aria-hidden="true">+ <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>+ </div>+ <h2>Conectar sua conta Spotify</h2>+ <p class="login-body">+ Veja sua biblioteca, playlists e histórico do Spotify dentro do OmniGet.+ Você pode tocar em qualquer dispositivo Spotify ativo (celular, app+ oficial). Em breve, tocar direto aqui também.+ </p>+ {#if !spotifyStore.status.has_client_id}+ <p class="warn">+ ⚠️ Client ID do Spotify não configurado. Reinstale ou rebuilde o plugin+ study.+ </p>+ {/if}+ {#if spotifyStore.error}+ <p class="error">{spotifyStore.error}</p>+ {/if}+ {#if spotifyStore.authInProgress}+ <div class="waiting">+ <span class="spinner"></span>+ <span>Aguardando autorização no navegador…</span>+ <button type="button" class="ghost-btn" onclick={doCancel}>Cancelar</button>+ </div>+ {:else}+ <button+ type="button"+ class="cta-spotify"+ onclick={doLogin}+ disabled={!spotifyStore.status.has_client_id}+ >+ Conectar com Spotify+ </button>+ {/if}+ </div>+ {:else if spotifyStore.loadingLibrary && spotifyStore.savedTracks.length === 0}+ <p class="muted">Carregando biblioteca…</p>+ {:else}+ {#if spotifyStore.isPremium && spotifyStore.widevineSupported}+ <div class="status-banner sdk">+ <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"><polyline points="20 6 9 17 4 12"/></svg>+ Tocando dentro do OmniGet (Web Playback SDK)+ </div>+ {:else if !spotifyStore.isPremium}+ <div class="status-banner info">+ <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="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>+ Modo Free: faixas tocam via YouTube em tempo real (match automático por título/artista).+ </div>+ {:else if spotifyStore.widevineSupported === false}+ <div class="status-banner warn">+ <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="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>+ Widevine DRM indisponível. Vai usar fallback YouTube.+ </div>+ {/if}+ {#if spotifyStore.recentlyPlayed.length > 0}+ <section class="block">+ <header class="block-head">+ <h2>Tocadas recentemente</h2>+ </header>+ <div class="album-pills-grid">+ {#each spotifyStore.recentlyPlayed.slice(0, 8) as track (track.id + (track.played_at ?? ""))}+ <button+ type="button"+ class="track-pill"+ onclick={() => playTrack(track)}+ >+ <div class="track-pill-cover">+ {#if spotifyStore.pickImage(track.album.images, 80)}+ <img src={spotifyStore.pickImage(track.album.images, 80)} alt="" loading="lazy" />+ {:else}+ <div+ class="track-pill-fallback"+ style:background={colorFromString(track.album.name)}+ ></div>+ {/if}+ </div>+ <div class="track-pill-info">+ <span class="track-pill-title">{track.name}</span>+ <span class="track-pill-sub">{fmtArtists(track)}</span>+ </div>+ </button>+ {/each}+ </div>+ </section>+ {/if}++ {#if spotifyStore.playlists.length > 0}+ <section class="block">+ <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">+ <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">+ <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="sp-playlists" class="h-scroll">+ {#each spotifyStore.playlists 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 spotifyStore.pickImage(p.images, 300)}+ <img src={spotifyStore.pickImage(p.images, 300)} 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>+ <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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if spotifyStore.topArtists.length > 0}+ <section class="block">+ <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">+ <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">+ <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="sp-artists" class="h-scroll">+ {#each spotifyStore.topArtists as a (a.id)}+ <div+ class="artist-card"+ role="button"+ tabindex="0"+ onclick={() => openArtist(a)}+ onkeydown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openArtist(a); } }}+ >+ <div class="artist-circle">+ {#if spotifyStore.pickImage(a.images, 200)}+ <img src={spotifyStore.pickImage(a.images, 200)} 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>+ </div>+ {/each}+ </div>+ </section>+ {/if}++ {#if spotifyStore.savedTracks.length > 0}+ <section class="block">+ <header class="block-head">+ <h2>Curtidas</h2>+ </header>+ <div class="track-list">+ {#each spotifyStore.savedTracks.slice(0, 30) as track, i (track.id)}+ <button+ type="button"+ class="track-row"+ onclick={() =>+ playTrack(track, spotifyStore.savedTracks.slice(0, 30))}+ >+ <span class="track-num">{i + 1}</span>+ <div class="track-cover">+ {#if spotifyStore.pickImage(track.album.images, 80)}+ <img src={spotifyStore.pickImage(track.album.images, 80)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title-row">+ <span class="track-title">{track.name}</span>+ {#if spotifyStore.localMatches.has(track.id)}+ <span class="local-badge" title="Já está na sua biblioteca local">+ ●+ </span>+ {/if}+ </span>+ <span class="track-artists">{fmtArtists(track)}</span>+ </div>+ <span class="track-album">{track.album.name}</span>+ <span class="track-dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ {/each}+ </div>+ </section>+ {/if}+ {/if}+</section>++<style>+ .spotify-home {+ display: flex;+ flex-direction: column;+ gap: 32px;+ color: rgba(255, 255, 255, 0.95);+ }+ .page-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+ }+ .page-head h1 {+ margin: 0;+ font-size: clamp(28px, 3.5vw, 40px);+ font-weight: 900;+ letter-spacing: -0.02em;+ }+ .head-actions {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .profile-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 4px 12px 4px 4px;+ background: rgba(255, 255, 255, 0.05);+ border-radius: 999px;+ font-size: 13px;+ font-weight: 600;+ }+ .profile-pill img {+ width: 28px;+ height: 28px;+ border-radius: 50%;+ object-fit: cover;+ }+ .badge {+ font-size: 10px;+ font-weight: 700;+ text-transform: uppercase;+ padding: 2px 6px;+ border-radius: 4px;+ background: rgba(255, 255, 255, 0.08);+ letter-spacing: 0.05em;+ }+ .badge.premium {+ background: #1db954;+ color: #000;+ }+ .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;+ }+ .ghost-btn:hover {+ background: rgba(255, 255, 255, 0.1);+ }++ .login-card {+ margin: 0 auto;+ max-width: 540px;+ padding: 56px 32px;+ text-align: center;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 16px;+ }+ .login-art {+ margin-bottom: 8px;+ }+ .login-card h2 {+ margin: 0;+ font-size: 28px;+ font-weight: 800;+ letter-spacing: -0.01em;+ }+ .login-body {+ margin: 0;+ color: rgba(255, 255, 255, 0.6);+ font-size: 14px;+ line-height: 1.6;+ max-width: 44ch;+ }+ .warn {+ color: #ffa726;+ font-size: 13px;+ margin: 0;+ }+ .error {+ color: #e22134;+ font-size: 13px;+ margin: 0;+ }+ .cta-spotify {+ margin-top: 8px;+ padding: 14px 40px;+ background: #1db954;+ color: #000;+ border: 0;+ border-radius: 999px;+ font-family: inherit;+ font-size: 15px;+ font-weight: 700;+ cursor: pointer;+ transition: transform 200ms ease, background 200ms ease;+ }+ .cta-spotify:hover:not(:disabled) {+ background: #1ed760;+ transform: scale(1.04);+ }+ .cta-spotify:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .waiting {+ display: flex;+ align-items: center;+ gap: 12px;+ color: rgba(255, 255, 255, 0.7);+ font-size: 14px;+ }+ .spinner {+ width: 16px;+ height: 16px;+ border: 2px solid rgba(255, 255, 255, 0.2);+ border-top-color: #1db954;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }+ @keyframes spin {+ to { transform: rotate(360deg); }+ }++ .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;+ }+ .scroll-arrows {+ display: flex;+ gap: 8px;+ }+ .arrow {+ width: 32px;+ height: 32px;+ 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(280px, 1fr));+ gap: 8px;+ }+ .track-pill {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px;+ background: rgba(255, 255, 255, 0.04);+ border: 0;+ border-radius: 8px;+ color: inherit;+ cursor: pointer;+ text-align: left;+ transition: background 200ms ease;+ }+ .track-pill:hover {+ background: rgba(255, 255, 255, 0.08);+ }+ .track-pill-cover {+ width: 56px;+ height: 56px;+ border-radius: 4px;+ overflow: hidden;+ background: rgba(40, 40, 40, 0.8);+ flex-shrink: 0;+ }+ .track-pill-cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .track-pill-fallback {+ width: 100%;+ height: 100%;+ }+ .track-pill-info {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+ }+ .track-pill-title {+ font-size: 14px;+ font-weight: 700;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-pill-sub {+ font-size: 12px;+ color: rgba(255, 255, 255, 0.55);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .h-scroll {+ display: flex;+ gap: 24px;+ overflow-x: auto;+ overflow-y: visible;+ padding: 8px 4px 24px;+ scroll-behavior: smooth;+ scrollbar-width: none;+ }+ .h-scroll::-webkit-scrollbar { display: none; }++ .album-card {+ flex: 0 0 176px;+ cursor: pointer;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 0;+ text-align: left;+ }+ .album-card-cover {+ position: relative;+ aspect-ratio: 1 / 1;+ border-radius: 16px;+ background: rgba(40, 40, 40, 0.8);+ 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);+ }+ .album-card-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ }+ .album-card-title {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .album-card-sub {+ margin: 4px 0 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }++ .artist-card {+ flex: 0 0 144px;+ cursor: pointer;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 0;+ text-align: center;+ }+ .artist-circle {+ aspect-ratio: 1 / 1;+ border-radius: 50%;+ background: rgba(40, 40, 40, 0.8);+ overflow: hidden;+ margin: 0 auto 16px;+ transition: transform 700ms ease;+ position: relative;+ }+ .artist-card:hover .artist-circle {+ transform: scale(1.04);+ }+ .artist-circle img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .artist-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ font-size: 48px;+ font-weight: 800;+ }+ .artist-name {+ margin: 0;+ color: white;+ font-weight: 700;+ font-size: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }++ .track-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .track-row {+ display: grid;+ grid-template-columns: 40px 56px 1fr 1fr 60px;+ gap: 12px;+ align-items: center;+ padding: 8px 12px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: inherit;+ cursor: pointer;+ text-align: left;+ transition: background 200ms ease;+ }+ .track-row:hover {+ background: rgba(255, 255, 255, 0.06);+ }+ .track-num {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ text-align: center;+ }+ .track-cover {+ width: 44px;+ height: 44px;+ border-radius: 4px;+ overflow: hidden;+ background: rgba(40, 40, 40, 0.8);+ }+ .track-cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .track-meta {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }+ .track-title {+ font-size: 14px;+ font-weight: 600;+ color: white;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-artists {+ font-size: 12px;+ color: rgba(255, 255, 255, 0.55);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-album {+ font-size: 13px;+ 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;+ }++ .status-banner {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 8px 14px;+ border-radius: 8px;+ font-size: 12px;+ font-weight: 600;+ align-self: flex-start;+ }+ .status-banner.sdk {+ background: rgba(29, 185, 84, 0.15);+ color: #1db954;+ }+ .status-banner.warn {+ background: rgba(255, 167, 38, 0.15);+ color: #ffa726;+ }+ .status-banner.info {+ background: rgba(100, 181, 246, 0.15);+ color: #64b5f6;+ }+ .track-title-row {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ overflow: hidden;+ }+ .local-badge {+ font-size: 10px;+ color: #1db954;+ line-height: 1;+ flex-shrink: 0;+ }++ .muted {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }++ @media (prefers-reduced-motion: reduce) {+ .cta-spotify, .arrow, .album-card-cover img, .artist-circle, .spinner {+ transition: none;+ animation: none;+ }+ .cta-spotify:hover, .album-card:hover .album-card-cover img,+ .artist-card:hover .artist-circle {+ transform: none;+ }+ }+</style>diff --git a/src/routes/study/music/spotify/album/[id]/+page.svelte b/src/routes/study/music/spotify/album/[id]/+page.sveltenew file mode 100644index 00000000..802f2605--- /dev/null+++ b/src/routes/study/music/spotify/album/[id]/+page.svelte@@ -0,0 +1,237 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ spotifyStore,+ type SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import { colorFromString } from "$lib/study-music/format";++ type AlbumDetail = {+ id: string;+ name: string;+ uri: string;+ images: { url: string; width?: number | null; height?: number | null }[];+ artists: { id: string; name: string; uri: string }[];+ release_date: string | null;+ total_tracks: number;+ label?: string | null;+ popularity?: number | null;+ genres?: string[] | null;+ };++ let album = $state<AlbumDetail | null>(null);+ let tracks = $state<SpotifyTrack[]>([]);+ let isSaved = $state(false);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let savingToggle = $state(false);++ const albumId = $derived($page.params.id ?? "");++ onMount(async () => {+ if (!albumId) {+ goto("/study/music/spotify");+ return;+ }+ if (!spotifyStore.status.logged_in) {+ goto("/study/music/spotify");+ return;+ }++ try {+ const [info, savedRes] = await Promise.allSettled([+ spotifyStore.getAlbum(albumId),+ import("$lib/plugin-invoke").then(({ pluginInvoke }) =>+ pluginInvoke<boolean[]>("study", "study:spotify:albums:contains", {+ ids: [albumId],+ }),+ ),+ ]);++ if (info.status === "fulfilled" && info.value) {+ const a: any = info.value;+ album = {+ id: a.id,+ name: a.name ?? "",+ uri: a.uri ?? "",+ images: a.images ?? [],+ artists: (a.artists ?? []).map((x: any) => ({+ id: x.id,+ name: x.name,+ uri: x.uri,+ })),+ release_date: a.release_date ?? null,+ total_tracks: a.total_tracks ?? 0,+ label: a.label ?? null,+ popularity: a.popularity ?? null,+ genres: a.genres ?? [],+ };+ }+ if (savedRes.status === "fulfilled") {+ isSaved = savedRes.value?.[0] === true;+ }++ tracks = await spotifyStore.getAlbumTracks(albumId);+ tracks = tracks.map((t) => ({+ ...t,+ album: album+ ? {+ id: album.id,+ name: album.name,+ uri: album.uri,+ images: album.images,+ release_date: album.release_date ?? undefined,+ }+ : t.album,+ }));+ } catch (e) {+ error = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ });++ async function playFromIndex(idx: number) {+ if (tracks.length === 0) return;+ const reordered = [...tracks.slice(idx), ...tracks.slice(0, idx)];+ try {+ const mode = await spotifyStore.playTrack(reordered[0], reordered);+ if (mode === "youtube") {+ showToast("info", "Tocando via YouTube (modo Free)");+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ async function toggleSave() {+ if (savingToggle) return;+ savingToggle = true;+ try {+ isSaved = await spotifyStore.toggleSaveAlbum(albumId);+ showToast("success", isSaved ? "Álbum salvo" : "Álbum removido");+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ savingToggle = false;+ }+ }++ 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")}`;+ }+</script>++<section class="album-page">+ <button type="button" class="back-btn" onclick={() => history.back()}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Voltar+ </button>++ {#if album}+ <header class="hero">+ <div class="hero-cover">+ {#if spotifyStore.pickImage(album.images, 300)}+ <img src={spotifyStore.pickImage(album.images, 300)} alt="" />+ {:else}+ <div class="hero-fallback" style:background={colorFromString(album.name)}></div>+ {/if}+ </div>+ <div class="hero-info">+ <span class="eyebrow">Álbum</span>+ <h1>{album.name}</h1>+ <p class="meta">+ {album.artists.map((a) => a.name).join(", ")}{album.release_date ? ` · ${album.release_date.slice(0, 4)}` : ""}+ · {album.total_tracks} faixas+ </p>+ {#if album.genres && album.genres.length > 0}+ <p class="genres">{album.genres.slice(0, 3).join(" · ")}</p>+ {/if}+ <div class="actions">+ <button type="button" class="play-btn" onclick={() => playFromIndex(0)}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ Tocar+ </button>+ <button+ type="button"+ class="fav-btn"+ class:on={isSaved}+ onclick={toggleSave}+ disabled={savingToggle}+ aria-label={isSaved ? "Remover dos seus álbuns" : "Salvar álbum"}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill={isSaved ? "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>+ </header>+ {/if}++ {#if loading}+ <p class="muted">Carregando…</p>+ {:else if error}+ <p class="error">{error}</p>+ {:else}+ <div class="track-list">+ {#each tracks as track, i (track.id + i)}+ <button type="button" class="track-row" onclick={() => playFromIndex(i)}>+ <span class="track-num">{i + 1}</span>+ <div class="track-meta">+ <span class="track-title">{track.name}</span>+ <span class="track-artists">{track.artists.map((a) => a.name).join(", ")}</span>+ </div>+ <span class="track-dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ {/each}+ </div>+ {/if}+</section>++<style>+ .album-page { display: flex; flex-direction: column; gap: 24px; color: rgba(255, 255, 255, 0.95); }+ .back-btn {+ align-self: flex-start; display: inline-flex; align-items: center; gap: 8px;+ padding: 6px 12px 6px 8px; background: rgba(255, 255, 255, 0.05); border: 0;+ border-radius: 999px; color: rgba(255, 255, 255, 0.85);+ font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer;+ }+ .back-btn:hover { background: rgba(255, 255, 255, 0.1); }+ .hero { display: flex; gap: 32px; align-items: flex-end; padding: 24px 0; }+ .hero-cover { width: 220px; height: 220px; border-radius: 8px; overflow: hidden; flex-shrink: 0; box-shadow: 0 4px 60px rgba(0,0,0,0.5); }+ .hero-cover img { width: 100%; height: 100%; object-fit: cover; }+ .hero-fallback { width: 100%; height: 100%; }+ .hero-info { display: flex; flex-direction: column; gap: 12px; min-width: 0; }+ .eyebrow { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: rgba(255,255,255,0.6); }+ .hero-info h1 { margin: 0; font-size: clamp(28px, 4vw, 56px); font-weight: 900; letter-spacing: -0.02em; line-height: 1.05; }+ .meta, .genres { margin: 0; color: rgba(255,255,255,0.5); font-size: 13px; }+ .genres { color: rgba(255,255,255,0.4); }+ .actions { display: flex; align-items: center; gap: 12px; margin-top: 8px; }+ .play-btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 32px; background: #1db954; color: #000; border: 0; border-radius: 999px; font-family: inherit; font-size: 14px; font-weight: 700; cursor: pointer; transition: transform 200ms ease, background 200ms ease; }+ .play-btn:hover { background: #1ed760; transform: scale(1.04); }+ .fav-btn { width: 44px; height: 44px; padding: 0; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.15); border-radius: 50%; color: white; cursor: pointer; display: grid; place-items: center; transition: background 200ms ease; }+ .fav-btn:hover { background: rgba(255,255,255,0.16); }+ .fav-btn.on { color: #1db954; }+ .fav-btn:disabled { opacity: 0.5; cursor: default; }++ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 40px 1fr 60px; gap: 12px; align-items: center; padding: 8px 12px; background: transparent; border: 0; border-radius: 6px; color: inherit; cursor: pointer; text-align: left; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .track-num { color: rgba(255,255,255,0.5); font-size: 13px; text-align: center; }+ .track-meta { display: flex; flex-direction: column; min-width: 0; }+ .track-title { font-size: 14px; font-weight: 600; color: white; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .track-artists { 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; }+ .muted { color: rgba(255,255,255,0.5); font-size: 13px; }+ .error { color: #e22134; font-size: 13px; }+ @media (prefers-reduced-motion: reduce) { .play-btn { transition: none; } .play-btn:hover { transform: none; } }+</style>diff --git a/src/routes/study/music/spotify/artist/[id]/+page.svelte b/src/routes/study/music/spotify/artist/[id]/+page.sveltenew file mode 100644index 00000000..63d3c60f--- /dev/null+++ b/src/routes/study/music/spotify/artist/[id]/+page.svelte@@ -0,0 +1,269 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ spotifyStore,+ type SpotifyArtist,+ type SpotifyTrack,+ type SpotifySavedAlbum,+ } from "$lib/study-music/spotify-store.svelte";+ import { colorFromString } from "$lib/study-music/format";++ let artist = $state<SpotifyArtist | null>(null);+ let topTracks = $state<SpotifyTrack[]>([]);+ let albums = $state<SpotifySavedAlbum[]>([]);+ let isFollowing = $state(false);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let followToggle = $state(false);++ const artistId = $derived($page.params.id ?? "");++ onMount(async () => {+ if (!artistId) {+ goto("/study/music/spotify");+ return;+ }+ if (!spotifyStore.status.logged_in) {+ goto("/study/music/spotify");+ return;+ }+ try {+ const [info, top, albs, follow] = await Promise.allSettled([+ spotifyStore.getArtist(artistId),+ spotifyStore.getArtistTopTracks(artistId),+ spotifyStore.getArtistAlbums(artistId),+ spotifyStore.checkFollowArtists([artistId]),+ ]);++ if (info.status === "fulfilled" && info.value) {+ const a: any = info.value;+ artist = {+ id: a.id,+ name: a.name ?? "",+ uri: a.uri ?? "",+ images: a.images ?? [],+ genres: a.genres ?? [],+ followers: a.followers?.total,+ popularity: a.popularity,+ };+ } else {+ const fromCache = spotifyStore.allArtists.find((x) => x.id === artistId);+ if (fromCache) {+ artist = fromCache;+ }+ }+ if (top.status === "fulfilled") topTracks = top.value;+ if (albs.status === "fulfilled") albums = albs.value;+ if (follow.status === "fulfilled") isFollowing = follow.value[0] === true;++ const failed = [info, top, albs, follow].filter(+ (x) => x.status === "rejected",+ );+ if (+ failed.length > 0 &&+ topTracks.length === 0 &&+ albums.length === 0+ ) {+ const reason = (failed[0] as PromiseRejectedResult).reason;+ const msg = reason instanceof Error ? reason.message : String(reason);+ if (msg.includes("403") || msg.toLowerCase().includes("forbidden")) {+ error =+ "O Spotify bloqueou o acesso a este artista para apps em Development mode. Pode tocar via clicar em uma faixa dele em outra tela.";+ }+ }+ } catch (e) {+ error = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ });++ async function playFromIndex(idx: number) {+ if (topTracks.length === 0) return;+ const reordered = [...topTracks.slice(idx), ...topTracks.slice(0, idx)];+ try {+ const mode = await spotifyStore.playTrack(reordered[0], reordered);+ if (mode === "youtube") {+ showToast("info", "Tocando via YouTube (modo Free)");+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ async function toggleFollow() {+ if (followToggle) return;+ followToggle = true;+ try {+ isFollowing = await spotifyStore.toggleFollowArtist(artistId);+ showToast("success", isFollowing ? "Seguindo" : "Deixou de seguir");+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ followToggle = false;+ }+ }++ 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")}`;+ }+</script>++<section class="artist-page">+ <button type="button" class="back-btn" onclick={() => history.back()}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Voltar+ </button>++ {#if artist}+ <header class="hero">+ <div class="hero-circle">+ {#if spotifyStore.pickImage(artist.images, 400)}+ <img src={spotifyStore.pickImage(artist.images, 400)} alt="" />+ {:else}+ <div class="hero-fallback" style:background={colorFromString(artist.name)}>+ {artist.name.slice(0, 1).toUpperCase()}+ </div>+ {/if}+ </div>+ <div class="hero-info">+ <span class="eyebrow">Artista</span>+ <h1>{artist.name}</h1>+ {#if artist.followers}+ <p class="meta">{artist.followers.toLocaleString("pt-BR")} seguidores</p>+ {/if}+ {#if artist.genres.length > 0}+ <p class="genres">{artist.genres.slice(0, 3).join(" · ")}</p>+ {/if}+ <div class="actions">+ <button type="button" class="play-btn" onclick={() => playFromIndex(0)} disabled={topTracks.length === 0}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>+ Tocar+ </button>+ <button+ type="button"+ class="follow-btn"+ class:on={isFollowing}+ onclick={toggleFollow}+ disabled={followToggle}+ >+ {isFollowing ? "Seguindo" : "Seguir"}+ </button>+ </div>+ </div>+ </header>+ {/if}++ {#if loading}+ <p class="muted">Carregando…</p>+ {:else if error}+ <p class="error">{error}</p>+ {:else}+ {#if topTracks.length > 0}+ <section class="block">+ <header class="block-head"><h2>Populares</h2></header>+ <div class="track-list">+ {#each topTracks.slice(0, 10) as track, i (track.id + i)}+ <button type="button" class="track-row" onclick={() => playFromIndex(i)}>+ <span class="track-num">{i + 1}</span>+ <div class="track-cover">+ {#if spotifyStore.pickImage(track.album.images, 80)}+ <img src={spotifyStore.pickImage(track.album.images, 80)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{track.name}</span>+ <span class="track-album">{track.album.name}</span>+ </div>+ <span class="track-dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ {/each}+ </div>+ </section>+ {/if}++ {#if albums.length > 0}+ <section class="block">+ <header class="block-head"><h2>Discografia</h2></header>+ <div class="album-grid">+ {#each albums as a (a.id)}+ <a class="album-card" href={`/study/music/spotify/album/${a.id}`}>+ <div class="album-cover">+ {#if spotifyStore.pickImage(a.images, 300)}+ <img src={spotifyStore.pickImage(a.images, 300)} alt="" loading="lazy" />+ {:else}+ <div class="album-fallback" style:background={colorFromString(a.name)}></div>+ {/if}+ </div>+ <h3 class="album-title">{a.name}</h3>+ <p class="album-sub">{a.release_date ? a.release_date.slice(0, 4) : ""}{a.total_tracks ? ` · ${a.total_tracks} faixas` : ""}</p>+ </a>+ {/each}+ </div>+ </section>+ {/if}+ {/if}+</section>++<style>+ .artist-page { display: flex; flex-direction: column; gap: 24px; color: rgba(255, 255, 255, 0.95); }+ .back-btn {+ align-self: flex-start; display: inline-flex; align-items: center; gap: 8px;+ padding: 6px 12px 6px 8px; background: rgba(255,255,255,0.05); border: 0;+ border-radius: 999px; color: rgba(255,255,255,0.85);+ font-family: inherit; font-size: 12px; font-weight: 600; cursor: pointer;+ }+ .back-btn:hover { background: rgba(255,255,255,0.1); }++ .hero { display: flex; gap: 32px; align-items: flex-end; padding: 24px 0; }+ .hero-circle { width: 220px; height: 220px; border-radius: 50%; overflow: hidden; flex-shrink: 0; box-shadow: 0 4px 60px rgba(0,0,0,0.5); }+ .hero-circle img { width: 100%; height: 100%; object-fit: cover; }+ .hero-fallback { width: 100%; height: 100%; display: grid; place-items: center; color: white; font-size: 64px; font-weight: 800; }+ .hero-info { display: flex; flex-direction: column; gap: 12px; min-width: 0; }+ .eyebrow { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: rgba(255,255,255,0.6); }+ .hero-info h1 { margin: 0; font-size: clamp(28px, 4vw, 56px); font-weight: 900; letter-spacing: -0.02em; line-height: 1.05; }+ .meta, .genres { margin: 0; color: rgba(255,255,255,0.5); font-size: 13px; }+ .actions { display: flex; align-items: center; gap: 12px; margin-top: 8px; }+ .play-btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 32px; background: #1db954; color: #000; border: 0; border-radius: 999px; font-family: inherit; font-size: 14px; font-weight: 700; cursor: pointer; transition: transform 200ms ease, background 200ms ease; }+ .play-btn:hover { background: #1ed760; transform: scale(1.04); }+ .play-btn:disabled { opacity: 0.5; cursor: default; transform: none; }+ .follow-btn { padding: 10px 20px; background: transparent; border: 1px solid rgba(255,255,255,0.4); border-radius: 999px; color: white; font-family: inherit; font-size: 13px; font-weight: 700; cursor: pointer; transition: border-color 200ms ease, background 200ms ease; }+ .follow-btn:hover { border-color: white; }+ .follow-btn.on { background: rgba(29,185,84,0.15); border-color: #1db954; color: #1db954; }+ .follow-btn:disabled { opacity: 0.5; cursor: default; }++ .block { display: flex; flex-direction: column; gap: 16px; }+ .block-head h2 { margin: 0; font-size: 22px; font-weight: 800; }++ .track-list { display: flex; flex-direction: column; gap: 2px; }+ .track-row { display: grid; grid-template-columns: 40px 56px 1fr 60px; gap: 12px; align-items: center; padding: 8px 12px; background: transparent; border: 0; border-radius: 6px; color: inherit; cursor: pointer; text-align: left; transition: background 200ms ease; }+ .track-row:hover { background: rgba(255,255,255,0.06); }+ .track-num { color: rgba(255,255,255,0.5); font-size: 13px; text-align: center; }+ .track-cover { width: 44px; height: 44px; border-radius: 4px; overflow: hidden; background: rgba(40,40,40,0.8); }+ .track-cover img { width: 100%; height: 100%; object-fit: cover; }+ .track-meta { display: flex; flex-direction: column; min-width: 0; }+ .track-title { font-size: 14px; font-weight: 600; color: white; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .track-album { 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; }++ .album-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 24px; }+ .album-card { background: transparent; border: 0; padding: 0; cursor: pointer; color: inherit; text-align: left; text-decoration: none; }+ .album-cover { aspect-ratio: 1/1; border-radius: 12px; overflow: hidden; margin-bottom: 12px; background: rgba(40,40,40,0.8); transition: transform 300ms ease; }+ .album-cover img { width: 100%; height: 100%; object-fit: cover; transition: transform 500ms ease; }+ .album-card:hover .album-cover img { transform: scale(1.05); }+ .album-fallback { width: 100%; height: 100%; }+ .album-title { margin: 0; font-size: 14px; font-weight: 700; color: white; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; }+ .album-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; }+ @media (prefers-reduced-motion: reduce) { .play-btn { transition: none; } .play-btn:hover { transform: none; } .album-card:hover .album-cover img { transform: none; } }+</style>diff --git a/src/routes/study/music/spotify/playlist/[id]/+page.svelte b/src/routes/study/music/spotify/playlist/[id]/+page.sveltenew file mode 100644index 00000000..aac56edb--- /dev/null+++ b/src/routes/study/music/spotify/playlist/[id]/+page.svelte@@ -0,0 +1,345 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ spotifyStore,+ type SpotifyPlaylist,+ type SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import { colorFromString } from "$lib/study-music/format";++ let tracks = $state<SpotifyTrack[]>([]);+ let playlist = $state<SpotifyPlaylist | null>(null);+ let loading = $state(true);+ let error = $state<string | null>(null);++ const playlistId = $derived($page.params.id ?? "");++ onMount(async () => {+ if (!playlistId) {+ goto("/study/music/spotify");+ return;+ }+ if (!spotifyStore.status.logged_in) {+ goto("/study/music/spotify");+ return;+ }+ if (spotifyStore.playlists.length === 0) {+ try {+ await spotifyStore.loadAll();+ } catch {+ /* ignore */+ }+ }+ playlist = spotifyStore.playlists.find((p) => p.id === playlistId) ?? null;++ try {+ tracks = await spotifyStore.loadPlaylistTracks(playlistId);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ if (msg.includes("403") || msg.toLowerCase().includes("forbidden")) {+ error =+ "Esta playlist é restrita pelo Spotify para apps de terceiros (geralmente é uma playlist curada pelo Spotify, como Discover Weekly ou Daily Mix).";+ } else {+ error = msg;+ }+ } finally {+ loading = false;+ }+ });++ async function playFromIndex(idx: number) {+ if (tracks.length === 0) return;+ const startTrack = tracks[idx] ?? tracks[0];+ const reordered = [+ ...tracks.slice(idx),+ ...tracks.slice(0, idx),+ ];+ try {+ const mode = await spotifyStore.playPlaylistContext(+ playlist?.uri ?? `spotify:playlist:${playlistId}`,+ startTrack,+ reordered,+ );+ if (mode === "youtube") {+ showToast("info", "Tocando via YouTube (modo Free)");+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ 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 fmtArtists(track: SpotifyTrack): string {+ return track.artists.map((a) => a.name).join(", ");+ }+</script>++<section class="playlist-page">+ <button type="button" class="back-btn" onclick={() => goto("/study/music/spotify")}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Voltar+ </button>++ {#if playlist}+ <header class="hero">+ <div class="hero-cover">+ {#if spotifyStore.pickImage(playlist.images, 300)}+ <img src={spotifyStore.pickImage(playlist.images, 300)} alt="" />+ {:else}+ <div class="hero-fallback" style:background={colorFromString(playlist.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>+ <div class="hero-info">+ <span class="eyebrow">Playlist</span>+ <h1>{playlist.name}</h1>+ {#if playlist.description}+ <p class="desc">{playlist.description}</p>+ {/if}+ <p class="meta">+ {playlist.owner_name ?? ""} · {playlist.tracks_total} faixas+ </p>+ <button type="button" class="play-btn" onclick={() => playFromIndex(0)}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true">+ <path d="M8 5v14l11-7z"/>+ </svg>+ Tocar+ </button>+ </div>+ </header>+ {/if}++ {#if loading}+ <p class="muted">Carregando faixas…</p>+ {:else if error}+ <p class="error">{error}</p>+ {:else}+ <div class="track-list">+ {#each tracks as track, i (track.id + i)}+ <button type="button" class="track-row" onclick={() => playFromIndex(i)}>+ <span class="track-num">{i + 1}</span>+ <div class="track-cover">+ {#if spotifyStore.pickImage(track.album.images, 80)}+ <img src={spotifyStore.pickImage(track.album.images, 80)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{track.name}</span>+ <span class="track-artists">{fmtArtists(track)}</span>+ </div>+ <span class="track-album">{track.album.name}</span>+ <span class="track-dur">{fmtDuration(track.duration_ms)}</span>+ </button>+ {/each}+ </div>+ {/if}+</section>++<style>+ .playlist-page {+ display: flex;+ flex-direction: column;+ gap: 24px;+ color: rgba(255, 255, 255, 0.95);+ }+ .back-btn {+ align-self: flex-start;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px 6px 8px;+ background: rgba(255, 255, 255, 0.05);+ border: 0;+ border-radius: 999px;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ }+ .back-btn:hover {+ background: rgba(255, 255, 255, 0.1);+ }++ .hero {+ display: flex;+ gap: 32px;+ align-items: flex-end;+ padding: 24px 0;+ }+ .hero-cover {+ width: 220px;+ height: 220px;+ border-radius: 8px;+ overflow: hidden;+ flex-shrink: 0;+ box-shadow: 0 4px 60px rgba(0, 0, 0, 0.5);+ }+ .hero-cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .hero-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ }+ .hero-info {+ display: flex;+ flex-direction: column;+ gap: 12px;+ min-width: 0;+ }+ .eyebrow {+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ color: rgba(255, 255, 255, 0.6);+ }+ .hero-info h1 {+ margin: 0;+ font-size: clamp(28px, 4vw, 56px);+ font-weight: 900;+ letter-spacing: -0.02em;+ line-height: 1.05;+ }+ .desc {+ margin: 0;+ color: rgba(255, 255, 255, 0.6);+ font-size: 14px;+ }+ .meta {+ margin: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .play-btn {+ align-self: flex-start;+ margin-top: 8px;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 12px 32px;+ background: #1db954;+ color: #000;+ border: 0;+ border-radius: 999px;+ font-family: inherit;+ font-size: 14px;+ font-weight: 700;+ cursor: pointer;+ transition: transform 200ms ease, background 200ms ease;+ }+ .play-btn:hover {+ background: #1ed760;+ transform: scale(1.04);+ }++ .track-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .track-row {+ display: grid;+ grid-template-columns: 40px 56px 1fr 1fr 60px;+ gap: 12px;+ align-items: center;+ padding: 8px 12px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: inherit;+ cursor: pointer;+ text-align: left;+ transition: background 200ms ease;+ }+ .track-row:hover {+ background: rgba(255, 255, 255, 0.06);+ }+ .track-num {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ text-align: center;+ }+ .track-cover {+ width: 44px;+ height: 44px;+ border-radius: 4px;+ overflow: hidden;+ background: rgba(40, 40, 40, 0.8);+ }+ .track-cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .track-meta {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }+ .track-title {+ font-size: 14px;+ font-weight: 600;+ color: white;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-artists {+ font-size: 12px;+ color: rgba(255, 255, 255, 0.55);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-album {+ font-size: 13px;+ 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;+ }++ .muted {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ }+ .error {+ color: #e22134;+ font-size: 13px;+ }++ @media (prefers-reduced-motion: reduce) {+ .play-btn { transition: none; }+ .play-btn:hover { transform: none; }+ }+</style>diff --git a/src/routes/study/music/spotify/search/+page.svelte b/src/routes/study/music/spotify/search/+page.sveltenew file mode 100644index 00000000..1b915944--- /dev/null+++ b/src/routes/study/music/spotify/search/+page.svelte@@ -0,0 +1,474 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { goto } from "$app/navigation";+ import { showToast } from "$lib/stores/toast-store.svelte";+ import {+ spotifyStore,+ type SpotifyArtist,+ type SpotifyPlaylist,+ type SpotifyTrack,+ } from "$lib/study-music/spotify-store.svelte";+ import { colorFromString } from "$lib/study-music/format";++ type Tab = "track" | "playlist" | "artist" | "album";+ type SearchAlbum = {+ id: string;+ name: string;+ uri: string;+ images: { url: string; width?: number | null; height?: number | null }[];+ artists: { name: string }[];+ release_date?: string;+ };++ let query = $state("");+ let tab = $state<Tab>("track");+ let inputRef = $state<HTMLInputElement | null>(null);++ let tracks = $state<SpotifyTrack[]>([]);+ let playlists = $state<SpotifyPlaylist[]>([]);+ let artists = $state<SpotifyArtist[]>([]);+ let albums = $state<SearchAlbum[]>([]);+ let loading = $state(false);+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;++ onMount(async () => {+ if (!spotifyStore.status.logged_in) {+ goto("/study/music/spotify");+ return;+ }+ queueMicrotask(() => inputRef?.focus());+ });++ function onInput() {+ if (debounceTimer) clearTimeout(debounceTimer);+ if (!query.trim()) {+ tracks = [];+ playlists = [];+ artists = [];+ albums = [];+ return;+ }+ debounceTimer = setTimeout(() => doSearch(), 300);+ }++ async function doSearch() {+ const q = query.trim();+ if (!q) return;+ loading = true;+ try {+ const local = spotifyStore.searchLocal(q);+ tracks = local.tracks;+ artists = local.artists;+ playlists = local.playlists;+ const albumsMap = new Map<string, SearchAlbum>();+ for (const t of local.tracks) {+ const a = t.album;+ if (!a?.id || albumsMap.has(a.id)) continue;+ if (!a.name.toLowerCase().includes(q.toLowerCase())) continue;+ albumsMap.set(a.id, {+ id: a.id,+ name: a.name,+ uri: a.uri,+ images: a.images ?? [],+ artists: t.artists.map((x) => ({ name: x.name })),+ release_date: a.release_date,+ });+ }+ albums = [...albumsMap.values()];+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ loading = false;+ }+ }++ 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)");+ }+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ 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")}`;+ }+</script>++<section class="search-page">+ <header class="head">+ <button type="button" class="back-btn" onclick={() => goto("/study/music/spotify")}>+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Spotify+ </button>+ </header>++ <div class="search-bar">+ <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">+ <circle cx="11" cy="11" r="8"/>+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>+ </svg>+ <input+ bind:this={inputRef}+ bind:value={query}+ oninput={onInput}+ type="search"+ placeholder="Buscar nas suas curtidas, recents e top tracks…"+ autocomplete="off"+ />+ {#if loading}+ <span class="spinner"></span>+ {/if}+ </div>++ {#if tracks.length || playlists.length || artists.length || albums.length}+ <div class="tabs" role="tablist">+ <button+ type="button"+ class="tab"+ class:on={tab === "track"}+ onclick={() => (tab = "track")}+ role="tab"+ aria-selected={tab === "track"}+ >+ Faixas {tracks.length > 0 ? `(${tracks.length})` : ""}+ </button>+ <button+ type="button"+ class="tab"+ class:on={tab === "playlist"}+ onclick={() => (tab = "playlist")}+ role="tab"+ aria-selected={tab === "playlist"}+ >+ Playlists {playlists.length > 0 ? `(${playlists.length})` : ""}+ </button>+ <button+ type="button"+ class="tab"+ class:on={tab === "artist"}+ onclick={() => (tab = "artist")}+ role="tab"+ aria-selected={tab === "artist"}+ >+ Artistas {artists.length > 0 ? `(${artists.length})` : ""}+ </button>+ <button+ type="button"+ class="tab"+ class:on={tab === "album"}+ onclick={() => (tab = "album")}+ role="tab"+ aria-selected={tab === "album"}+ >+ Álbuns {albums.length > 0 ? `(${albums.length})` : ""}+ </button>+ </div>+ {/if}++ {#if tab === "track" && tracks.length > 0}+ <div class="track-list">+ {#each tracks as t, i (t.id + i)}+ <button type="button" class="track-row" onclick={() => playTrack(t, tracks)}>+ <div class="track-cover">+ {#if spotifyStore.pickImage(t.album.images, 80)}+ <img src={spotifyStore.pickImage(t.album.images, 80)} alt="" loading="lazy" />+ {/if}+ </div>+ <div class="track-meta">+ <span class="track-title">{t.name}</span>+ <span class="track-artists">{t.artists.map((a) => a.name).join(", ")}</span>+ </div>+ <span class="track-album">{t.album.name}</span>+ <span class="track-dur">{fmtDuration(t.duration_ms)}</span>+ </button>+ {/each}+ </div>+ {:else if tab === "playlist" && playlists.length > 0}+ <div class="grid">+ {#each playlists as p (p.id)}+ <button+ type="button"+ class="card"+ onclick={() => goto(`/study/music/spotify/playlist/${p.id}`)}+ >+ <div class="cover">+ {#if spotifyStore.pickImage(p.images, 300)}+ <img src={spotifyStore.pickImage(p.images, 300)} alt="" loading="lazy" />+ {:else}+ <div class="cover-fallback" style:background={colorFromString(p.name)}></div>+ {/if}+ </div>+ <h3>{p.name}</h3>+ <p>{p.owner_name ?? ""}</p>+ </button>+ {/each}+ </div>+ {:else if tab === "artist" && artists.length > 0}+ <div class="grid">+ {#each artists as a (a.id)}+ <button+ type="button"+ class="card artist"+ onclick={() => goto(`/study/music/spotify/artist/${a.id}`)}+ >+ <div class="cover round">+ {#if spotifyStore.pickImage(a.images, 300)}+ <img src={spotifyStore.pickImage(a.images, 300)} alt="" loading="lazy" />+ {:else}+ <div class="cover-fallback round" style:background={colorFromString(a.name)}>+ {a.name.slice(0, 1).toUpperCase()}+ </div>+ {/if}+ </div>+ <h3>{a.name}</h3>+ <p>Artista</p>+ </button>+ {/each}+ </div>+ {:else if tab === "album" && albums.length > 0}+ <div class="grid">+ {#each albums as a (a.id)}+ <button+ type="button"+ class="card"+ onclick={() => goto(`/study/music/spotify/album/${a.id}`)}+ >+ <div class="cover">+ {#if spotifyStore.pickImage(a.images, 300)}+ <img src={spotifyStore.pickImage(a.images, 300)} alt="" loading="lazy" />+ {:else}+ <div class="cover-fallback" style:background={colorFromString(a.name)}></div>+ {/if}+ </div>+ <h3>{a.name}</h3>+ <p>{a.artists.map((x) => x.name).join(", ")}</p>+ </button>+ {/each}+ </div>+ {:else if query.trim() && !loading}+ <p class="muted">Nada encontrado para "{query}"</p>+ {/if}+</section>++<style>+ .search-page {+ display: flex;+ flex-direction: column;+ gap: 24px;+ color: rgba(255, 255, 255, 0.95);+ }+ .head {+ display: flex;+ gap: 8px;+ }+ .back-btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px 6px 8px;+ background: rgba(255, 255, 255, 0.05);+ border: 0;+ border-radius: 999px;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ }+ .back-btn:hover { background: rgba(255, 255, 255, 0.1); }++ .search-bar {+ position: relative;+ display: flex;+ align-items: center;+ gap: 12px;+ background: rgba(255, 255, 255, 0.06);+ border-radius: 999px;+ padding: 12px 20px;+ color: rgba(255, 255, 255, 0.6);+ }+ .search-bar input {+ flex: 1;+ background: transparent;+ border: 0;+ outline: 0;+ color: white;+ font-family: inherit;+ font-size: 15px;+ }+ .spinner {+ width: 14px;+ height: 14px;+ border: 2px solid rgba(255, 255, 255, 0.2);+ border-top-color: #1db954;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }+ @keyframes spin { to { transform: rotate(360deg); } }++ .tabs {+ display: flex;+ gap: 8px;+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);+ padding-bottom: 0;+ }+ .tab {+ padding: 8px 16px;+ background: transparent;+ border: 0;+ border-bottom: 2px solid transparent;+ color: rgba(255, 255, 255, 0.55);+ font-family: inherit;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: color 200ms ease, border-color 200ms ease;+ }+ .tab:hover { color: white; }+ .tab.on { color: white; border-bottom-color: #1db954; }++ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));+ gap: 24px;+ }+ .card {+ background: transparent;+ border: 0;+ color: inherit;+ cursor: pointer;+ text-align: left;+ padding: 0;+ }+ .cover {+ aspect-ratio: 1 / 1;+ border-radius: 12px;+ overflow: hidden;+ margin-bottom: 12px;+ background: rgba(40, 40, 40, 0.8);+ }+ .cover.round { border-radius: 50%; }+ .cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ transition: transform 500ms ease;+ }+ .card:hover .cover img { transform: scale(1.05); }+ .cover-fallback {+ width: 100%;+ height: 100%;+ display: grid;+ place-items: center;+ color: white;+ font-size: 32px;+ font-weight: 800;+ }+ .cover-fallback.round { border-radius: 50%; }+ .card h3 {+ margin: 0;+ font-size: 14px;+ font-weight: 700;+ color: white;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .card p {+ margin: 4px 0 0;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.5);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 0 4px;+ }+ .card.artist { text-align: center; }+ .card.artist h3, .card.artist p { padding: 0; }++ .track-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .track-row {+ display: grid;+ grid-template-columns: 56px 1fr 1fr 60px;+ gap: 12px;+ align-items: center;+ padding: 8px 12px;+ background: transparent;+ border: 0;+ border-radius: 6px;+ color: inherit;+ cursor: pointer;+ text-align: left;+ transition: background 200ms ease;+ }+ .track-row:hover { background: rgba(255, 255, 255, 0.06); }+ .track-cover {+ width: 44px;+ height: 44px;+ border-radius: 4px;+ overflow: hidden;+ background: rgba(40, 40, 40, 0.8);+ }+ .track-cover img { width: 100%; height: 100%; object-fit: cover; }+ .track-meta {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }+ .track-title {+ font-size: 14px;+ font-weight: 600;+ color: white;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-artists {+ font-size: 12px;+ color: rgba(255, 255, 255, 0.55);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-album {+ font-size: 13px;+ 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;+ }++ .muted {+ color: rgba(255, 255, 255, 0.5);+ font-size: 13px;+ text-align: center;+ padding: 32px 0;+ }++ @media (prefers-reduced-motion: reduce) {+ .card .cover img, .spinner, .tab { transition: none; animation: none; }+ .card:hover .cover img { transform: none; }+ }+</style>diff --git a/src/routes/study/music/youtube/+page.svelte b/src/routes/study/music/youtube/+page.sveltenew file mode 100644index 00000000..d80c49f3--- /dev/null+++ b/src/routes/study/music/youtube/+page.svelte@@ -0,0 +1,721 @@+<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";++ 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 searchQuery = $state("");+ let searchResults = $state<RemoteTrack[]>([]);+ let searchLoading = $state(false);+ let searchError = $state<string | null>(null);+ let searchTimer: ReturnType<typeof setTimeout> | null = null;++ let recs = $state<RemoteTrack[]>([]);+ let recsSeedTitle = $state<string | null>(null);+ let downloadingId = $state<string | null>(null);++ async function load() {+ loading = true;+ try {+ const res = await pluginInvoke<{ playlists: Playlist[] }>(+ "study",+ "study:music:youtube:playlists_list",+ );+ playlists = res.playlists ?? [];+ } finally {+ loading = false;+ }+ }++ async function loadRecommendations() {+ 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);+ }+ }++ function handleSearchInput(e: Event) {+ const value = (e.target as HTMLInputElement).value;+ searchQuery = value;+ if (searchTimer) clearTimeout(searchTimer);+ if (!value.trim()) {+ searchResults = [];+ searchError = null;+ return;+ }+ searchTimer = setTimeout(() => void runSearch(value.trim()), 300);+ }++ async function runSearch(q: string) {+ if (!q) return;+ searchLoading = true;+ searchError = null;+ 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 = [];+ } finally {+ searchLoading = false;+ }+ }++ function clearSearch() {+ searchQuery = "";+ searchResults = [];+ searchError = null;+ }++ 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 playRemote(rt: RemoteTrack, queue: RemoteTrack[]) {+ 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();+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ async function downloadRemote(rt: RemoteTrack) {+ if (downloadingId) return;+ downloadingId = rt.video_id;+ 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);+ } 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;+ try {+ const res = await pluginInvoke<{ imported: number }>(+ "study",+ "study:music:youtube:playlist_refresh",+ { id: p.id },+ );+ 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;+ try {+ await pluginInvoke("study", "study:music:youtube:playlist_remove", { id: p.id });+ await load();+ } 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();+ });+</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>+ </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}+ </div>+ {#if searchLoading}+ <p class="muted small">{$t("study.common.loading")}</p>+ {/if}+ {#if searchError}+ <p class="error small">{searchError}</p>+ {/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" />+ {:else}+ <div class="track-cover-fallback"></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>+ {/each}+ </ul>+ {/if}+ </div>++ {#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" />+ {:else}+ <div class="track-cover-fallback"></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>+ {/each}+ </ul>+ </div>+ {/if}++ {#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" />+ {: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>+ {/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>+ </div>+ </article>+ </li>+ {/each}+ </ul>+ {/if}+</section>++<style>+ .page {+ 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;+ }+ .sub {+ 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;+ }+ .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;+ }+ .empty h2 {+ margin: 0 0 8px;+ font-size: 18px;+ color: rgba(255, 255, 255, 0.95);+ }+ .empty p {+ margin: 0 0 16px;+ font-size: 14px;+ line-height: 1.5;+ }+ .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;+ }+ .grid {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: 18px;+ }+ .card {+ 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;+ }+ .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;+ 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;+ }+ .card-actions {+ position: absolute;+ top: 14px;+ right: 14px;+ 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;+ }+ .ico:hover { background: rgba(0, 0, 0, 0.85); }+ .ico.danger:hover { background: rgb(220, 38, 38); }++ .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;+ 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;+ }+ .track-row:hover { background: rgba(255, 255, 255, 0.04); }+ .track-cover {+ position: relative;+ width: 48px;+ height: 48px;+ border: 0;+ padding: 0;+ background: rgba(0, 0, 0, 0.3);+ border-radius: 6px;+ overflow: hidden;+ cursor: pointer;+ }+ .track-cover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .track-cover-fallback {+ width: 100%;+ height: 100%;+ background: rgba(255, 255, 255, 0.04);+ }+ .track-play-overlay {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ 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;+ overflow: hidden;+ }+ .track-title {+ font-size: 13px;+ font-weight: 600;+ color: rgba(255, 255, 255, 0.95);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .track-sub {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.55);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .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;+ }+ .track-action:disabled { opacity: 0.4; cursor: not-allowed; }+</style>diff --git a/src/routes/study/music/youtube/playlist/[id]/+page.svelte b/src/routes/study/music/youtube/playlist/[id]/+page.sveltenew file mode 100644index 00000000..ed93aa38--- /dev/null+++ b/src/routes/study/music/youtube/playlist/[id]/+page.svelte@@ -0,0 +1,360 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/stores";+ import { pluginInvoke } from "$lib/plugin-invoke";+ 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;+ };++ 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 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,+ };+ }++ 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 ?? [];+ } catch (e) {+ error = e instanceof Error ? e.message : String(e);+ } finally {+ loading = false;+ }+ }++ function playAll() {+ if (tracks.length === 0) return;+ const queue = tracks.map(ytToMusicTrack);+ void musicPlayer.play(queue[0], queue);+ }++ 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 toggleFavorite(t: YtTrack) {+ 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,+ );+ } catch (e) {+ showToast("error", e instanceof Error ? e.message : String(e));+ }+ }++ $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>+ {: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>++ <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}+</section>++<style>+ .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);+ }+ .hero-meta {+ flex: 1;+ 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;+ }+ .hero-sub {+ margin: 0;+ color: rgba(255, 255, 255, 0.65);+ 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;+ }+ .track-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 4px 8px;+ border-radius: 6px;+ }+ .row:hover { background: rgba(255, 255, 255, 0.04); }+ .row-btn {+ flex: 1;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 6px 4px;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.95);+ font-family: inherit;+ text-align: left;+ 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;+ }+ .info {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-width: 0;+ gap: 2px;+ }+ .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); }+</style>diff --git a/src/routes/study/notes/+layout.svelte b/src/routes/study/notes/+layout.svelteindex 454728aa..fe8b1ad1 100644--- a/src/routes/study/notes/+layout.svelte+++ b/src/routes/study/notes/+layout.svelte@@ -2,6 +2,7 @@import MaintenanceCard from "$lib/study-components/MaintenanceCard.svelte";import { STUDY_NOTES_ENABLED } from "$lib/study-feature-flags";import { t } from "$lib/i18n";+ import NbShell from "$lib/study-components/notes/shell/NbShell.svelte";let { children } = $props();</script>@@ -12,5 +13,7 @@detail={$t("study.maintenance.detail_notes") as string}/>{:else}- {@render children?.()}+ <NbShell>+ {@render children?.()}+ </NbShell>{/if}diff --git a/src/routes/study/notes/+page.svelte b/src/routes/study/notes/+page.svelteindex d1cab074..a55605c5 100644--- a/src/routes/study/notes/+page.svelte+++ b/src/routes/study/notes/+page.svelte@@ -4,8 +4,6 @@import { t } from "$lib/i18n";import { awardXp } from "$lib/study-gamification";import ConfirmDialog from "$lib/study-components/ConfirmDialog.svelte";- import SidebarTree from "$lib/study-components/notes/SidebarTree.svelte";- import RefsPanel from "$lib/study-components/notes/RefsPanel.svelte";import CreatePageDialog from "$lib/study-components/notes/CreatePageDialog.svelte";import RenamePageDialog from "$lib/study-components/notes/RenamePageDialog.svelte";import Editor from "$lib/study-components/notes/Editor.svelte";@@ -23,9 +21,6 @@notesPagesEnsure,notesPagesSetAliases,notesPagesSetTags,- notesPagesLinkedRefs,- notesPagesUnlinkedRefs,- notesTagsList,notesJournalToday,notesBlocksPageTree,notesUndoLastOp,@@ -33,23 +28,13 @@notesAssetsListForPage,type NotePage as Page,type BlockNode,- type PageSummary,- type LinkedRef,- type TagSummary,} from "$lib/notes-bridge";-- let sidebarPages = $state<PageSummary[]>([]);- let sidebarTags = $state<TagSummary[]>([]);- let sidebarSearch = $state("");- let recentLimit = $state(50);+ import { notesShell } from "$lib/study-notes/shell-store.svelte";+ import { tabsStore } from "$lib/study-notes/tabs-store.svelte";let currentPage = $state<Page | null>(null);let blockTree = $state<BlockNode[]>([]);- let linkedRefs = $state<LinkedRef[]>([]);- let unlinkedRefs = $state<LinkedRef[]>([]);- let refsLoading = $state(false);-let loading = $state(true);let error = $state("");let notesTableMissing = $state(false);@@ -87,19 +72,22 @@setTimeout(() => (toast = null), 2400);}- async function loadSidebar() {+ function notifyDocksDirty() {try {- const [pages, tags] = await Promise.all([- notesPagesList(),- notesTagsList(30),- ]);- sidebarPages = pages;- sidebarTags = tags;+ window.dispatchEvent(new CustomEvent("study:notes:dirty"));+ } catch {+ /* ignore */+ }+ }++ async function probeNotesAvailability() {+ try {+ await notesPagesList();error = "";notesTableMissing = false;} catch (e) {const raw = e instanceof Error ? e.message : String(e);- console.error("[notes] loadSidebar failed:", raw);+ console.error("[notes] probe failed:", raw);if (/no such table/i.test(raw) || /database\s+disk/i.test(raw)) {notesTableMissing = true;error = "";@@ -110,7 +98,7 @@}}- async function openPage(id: number) {+ async function openPage(id: number, registerTab: boolean = true) {loading = true;error = "";try {@@ -121,7 +109,23 @@aliasesDirty = false;tagsDirty = false;blockTree = await notesBlocksPageTree(id);- await Promise.all([refreshRefs(id), loadCover(id)]);+ notesShell.setActivePage(p.name, p.title ?? null);+ if (registerTab) {+ const wnd = tabsStore.activeWndId;+ if (wnd != null) {+ void tabsStore+ .openTab({ wndId: wnd, pageId: id, viewKind: "editor", activate: true })+ .catch(() => {});+ }+ }+ const initial = blockTree.length > 0 ? blockTree[0].content ?? "" : "";+ const trimmed = initial.trim();+ const words = trimmed+ ? trimmed.replace(/[`*_>#~\-\[\]\(\)\{\}!]+/g, " ").split(/\s+/).filter((w) => w.length > 0).length+ : 0;+ notesShell.setCounts(words, initial.length);+ notesShell.setSaving(false);+ await loadCover(id);} catch (e) {error = e instanceof Error ? e.message : String(e);} finally {@@ -129,22 +133,6 @@}}- async function refreshRefs(pageId: number) {- refsLoading = true;- try {- const [linked, unlinked] = await Promise.all([- notesPagesLinkedRefs(pageId),- notesPagesUnlinkedRefs(pageId),- ]);- linkedRefs = linked;- unlinkedRefs = unlinked;- } catch (e) {- console.error("refreshRefs failed", e);- } finally {- refsLoading = false;- }- }-async function reloadTree() {if (!currentPage) return;blockTree = await notesBlocksPageTree(currentPage.id);@@ -154,7 +142,7 @@try {const r = await notesPagesCreate({ name });createPageOpen = false;- await loadSidebar();+ notifyDocksDirty();await openPage(r.id);void awardXp("page_created", 15, { page_id: r.id, name });showToast("ok", "Página criada");@@ -169,9 +157,10 @@await notesPagesDelete(currentPage.id);currentPage = null;blockTree = [];- linkedRefs = [];- unlinkedRefs = [];- await loadSidebar();+ notesShell.setActivePage(null, null);+ notesShell.setCounts(0, 0);+ notesShell.setSaving(false);+ notifyDocksDirty();showToast("ok", "Página removida");} catch (e) {showToast("err", e instanceof Error ? e.message : String(e));@@ -187,7 +176,7 @@try {const r = await notesPagesRenameCascade({ id: currentPage.id, newName });renameOpen = false;- await loadSidebar();+ notifyDocksDirty();await openPage(currentPage.id);showToast("ok",@@ -238,11 +227,11 @@const p = await notesPagesResolve(name);if (p) {await openPage(p.id);- await loadSidebar();+ notifyDocksDirty();} else {const r = await notesPagesEnsure({ name });await openPage(r.id);- await loadSidebar();+ notifyDocksDirty();}} catch (e) {showToast("err", e instanceof Error ? e.message : String(e));@@ -253,7 +242,7 @@try {const r = await notesJournalToday();await openPage(r.page_id);- await loadSidebar();+ notifyDocksDirty();} catch (e) {showToast("err", e instanceof Error ? e.message : String(e));}@@ -286,32 +275,37 @@}onMount(async () => {- await loadSidebar();+ await probeNotesAvailability();const target = $routePage.url.searchParams.get("page");if (target) {await gotoPageByName(target);- } else if (sidebarPages.length > 0) {- await openPage(sidebarPages[0].id);- } else {+ return;+ }+ if (notesTableMissing || error) {+ loading = false;+ return;+ }+ try {+ const all = await notesPagesList();+ if (all.length > 0) {+ await openPage(all[0].id);+ } else {+ loading = false;+ }+ } catch {loading = false;}});++ $effect(() => {+ const t = tabsStore.activeTab;+ if (!t || t.view_kind !== "editor" || t.page_id == null) return;+ if (currentPage?.id === t.page_id) return;+ void openPage(t.page_id, false);+ });</script><div class="notes-shell" data-surface="notes">- <SidebarTree- pages={sidebarPages}- tags={sidebarTags}- selectedPageId={currentPage?.id ?? null}- searchValue={sidebarSearch}- {recentLimit}- onCreate={() => (createPageOpen = true)}- onSelect={openPage}- onJournalToday={openJournalToday}- onSearchInput={(v) => (sidebarSearch = v)}- onShowMore={() => (recentLimit += 50)}- />-<main class="editor">{#if toast}<div class="toast" class:err={toast.kind === "err"} role="status">@@ -324,12 +318,12 @@{:else if notesTableMissing}<div class="state err"><p>{$t("study.library.error_loading_notes")}</p>- <button class="btn" onclick={() => loadSidebar()}>{$t("common.retry")}</button>+ <button class="btn" onclick={() => probeNotesAvailability()}>{$t("common.retry")}</button></div>{:else if error}<div class="state err"><p>{error}</p>- <button class="btn" onclick={() => loadSidebar()}>{$t("common.retry")}</button>+ <button class="btn" onclick={() => probeNotesAvailability()}>{$t("common.retry")}</button></div>{:else if !currentPage}<div class="state">@@ -452,18 +446,12 @@initialMarkdown={firstBlock?.content ?? ""}onSaved={() => { void reloadTree(); }}onError={(msg) => showToast("err", msg)}+ onStats={(s) => notesShell.setCounts(s.words, s.chars)}+ onSavingChange={(saving) => notesShell.setSaving(saving)}/>{/if}</main>- <RefsPanel- {linkedRefs}- {unlinkedRefs}- loading={refsLoading}- active={currentPage !== null}- pageId={currentPage?.id ?? null}- onPageNavigate={gotoPageByName}- /></div><CoverManager@@ -512,27 +500,11 @@<style>.notes-shell {- display: grid;- grid-template-columns: 280px 1fr 320px;- gap: 12px;- height: calc(100vh - var(--header-height, 64px));+ height: 100%;+ min-height: 0;overflow: hidden;- }- @media (max-width: 1100px) {- .notes-shell {- grid-template-columns: 240px 1fr;- }- .notes-shell :global(.refs-panel) {- display: none;- }- }- @media (max-width: 760px) {- .notes-shell {- grid-template-columns: 1fr;- }- .notes-shell :global(.sidebar) {- display: none;- }+ display: flex;+ flex-direction: column;}.editor-banner {diff --git a/src/routes/study/notes/graph/+page.svelte b/src/routes/study/notes/graph/+page.svelteindex e3db2503..d802f19a 100644--- a/src/routes/study/notes/graph/+page.svelte+++ b/src/routes/study/notes/graph/+page.svelte@@ -458,7 +458,8 @@grid-template-areas:"head head""filters canvas";- height: calc(100vh - var(--header-height, 64px));+ height: 100%;+ min-height: 0;overflow: hidden;}@media (max-width: 760px) {diff --git a/src/routes/study/notes/journal/+page.svelte b/src/routes/study/notes/journal/+page.svelteindex 89ab9243..71f5d5d2 100644--- a/src/routes/study/notes/journal/+page.svelte+++ b/src/routes/study/notes/journal/+page.svelte@@ -422,7 +422,8 @@display: grid;grid-template-columns: 280px 1fr;gap: 12px;- height: calc(100vh - var(--header-height, 64px));+ height: 100%;+ min-height: 0;overflow: hidden;}@media (max-width: 760px) {diff --git a/src/routes/study/notes/templates/+page.svelte b/src/routes/study/notes/templates/+page.svelteindex fea7d041..9e7deaeb 100644--- a/src/routes/study/notes/templates/+page.svelte+++ b/src/routes/study/notes/templates/+page.svelte@@ -566,7 +566,8 @@display: grid;grid-template-columns: 360px 1fr;gap: 12px;- height: calc(100vh - var(--header-height, 64px));+ height: 100%;+ min-height: 0;overflow: hidden;}@media (max-width: 760px) {diff --git a/src/routes/study/progress/+page.svelte b/src/routes/study/progress/+page.svelteindex 789b5f7c..33003954 100644--- a/src/routes/study/progress/+page.svelte+++ b/src/routes/study/progress/+page.svelte@@ -80,11 +80,12 @@function fmtRelDays(secs: number): string {const days = Math.floor((Date.now() / 1000 - secs) / 86400);- if (days <= 0) return "hoje";- if (days === 1) return "ontem";- if (days < 30) return `${days} dias atrás`;- if (days < 365) return `${Math.floor(days / 30)} meses atrás`;- return `${Math.floor(days / 365)} anos atrás`;+ if (days <= 0) return $t("study.progress.time_today") as string;+ if (days === 1) return $t("study.progress.time_yesterday") as string;+ if (days < 30) return $t("study.progress.time_days_ago", { n: days }) as string;+ if (days < 365)+ return $t("study.progress.time_months_ago", { n: Math.floor(days / 30) }) as string;+ return $t("study.progress.time_years_ago", { n: Math.floor(days / 365) }) as string;}function tierColor(tier: string): string {@@ -101,25 +102,26 @@}function achievementLabel(code: string): string {- const map: Record<string, string> = {- "xp:100": "100 XP acumulados",- "xp:500": "500 XP acumulados",- "xp:1000": "1.000 XP acumulados",- "xp:5000": "5.000 XP acumulados",- "xp:10000": "10.000 XP acumulados",- "lessons:1": "Primeira aula",- "lessons:10": "10 aulas concluídas",- "lessons:50": "50 aulas concluídas",- "lessons:100": "100 aulas concluídas",- "focus:60": "1 hora de foco",- "focus:600": "10 horas de foco",- "focus:6000": "100 horas de foco",- "streak:3": "Streak de 3 dias",- "streak:7": "Streak de 1 semana",- "streak:30": "Streak de 30 dias",- "streak:100": "Streak de 100 dias",+ const keyMap: Record<string, string> = {+ "xp:100": "study.progress.ach_label_xp_100",+ "xp:500": "study.progress.ach_label_xp_500",+ "xp:1000": "study.progress.ach_label_xp_1000",+ "xp:5000": "study.progress.ach_label_xp_5000",+ "xp:10000": "study.progress.ach_label_xp_10000",+ "lessons:1": "study.progress.ach_label_lessons_1",+ "lessons:10": "study.progress.ach_label_lessons_10",+ "lessons:50": "study.progress.ach_label_lessons_50",+ "lessons:100": "study.progress.ach_label_lessons_100",+ "focus:60": "study.progress.ach_label_focus_60",+ "focus:600": "study.progress.ach_label_focus_600",+ "focus:6000": "study.progress.ach_label_focus_6000",+ "streak:3": "study.progress.ach_label_streak_3",+ "streak:7": "study.progress.ach_label_streak_7",+ "streak:30": "study.progress.ach_label_streak_30",+ "streak:100": "study.progress.ach_label_streak_100",};- return map[code] ?? code;+ const key = keyMap[code];+ return key ? ($t(key) as string) : code;}type DonutSlice = { name: string; minutes: number; color: string };@@ -133,7 +135,7 @@}));if (subjectBreakdown.unassigned_minutes > 0) {arr.push({- name: "Sem disciplina",+ name: $t("study.progress.chart_subject_unassigned") as string,minutes: subjectBreakdown.unassigned_minutes,color: "var(--tertiary)",});@@ -423,8 +425,8 @@<section class="charts-grid"><article class="card chart-card"><header class="card-head">- <h2>Tempo por curso</h2>- <small class="card-hint">últimos {days} dias</small>+ <h2>{$t("study.progress.chart_time_per_course")}</h2>+ <small class="card-hint">{$t("study.progress.chart_time_period_days", { n: days })}</small></header><div class="chart-body">{#if timePerCourse && timePerCourse.items.length > 0}@@ -444,15 +446,15 @@{/each}</ul>{:else}- <p class="chart-empty">Sem tempo registrado nesse período.</p>+ <p class="chart-empty">{$t("study.progress.chart_time_per_course_empty")}</p>{/if}</div></article><article class="card chart-card"><header class="card-head">- <h2>Atividade por hora</h2>- <small class="card-hint">soma de focos · 24h</small>+ <h2>{$t("study.progress.chart_activity_by_hour")}</h2>+ <small class="card-hint">{$t("study.progress.chart_activity_hint")}</small></header><div class="chart-body">{#if activityByHour && activityByHour.buckets.some((b) => b.minutes > 0)}@@ -479,15 +481,15 @@<span>24h</span></div>{:else}- <p class="chart-empty">Sem atividade nas últimas {days} dias.</p>+ <p class="chart-empty">{$t("study.progress.chart_activity_empty", { n: days })}</p>{/if}</div></article><article class="card chart-card"><header class="card-head">- <h2>Por disciplina</h2>- <small class="card-hint">minutos focados</small>+ <h2>{$t("study.progress.chart_subject")}</h2>+ <small class="card-hint">{$t("study.progress.chart_subject_unit")}</small></header><div class="chart-body">{#if donutSlices.length > 0 && donutTotal > 0}@@ -532,7 +534,7 @@</div>{:else}<p class="chart-empty">- Crie disciplinas e atribua sessões para ver breakdown.+ {$t("study.progress.chart_subject_empty")}</p>{/if}</div>@@ -540,16 +542,16 @@<article class="card chart-card retention-card"><header class="card-head">- <h2>Retenção (Anki)</h2>- <small class="card-hint">FSRS-5</small>+ <h2>{$t("study.progress.retention_title")}</h2>+ <small class="card-hint">{$t("study.progress.retention_method")}</small></header><div class="chart-body retention-stub"><p class="chart-empty">- Retenção real virá da query cross-DB do Anki. Por ora, abra+ {$t("study.progress.retention_stub_before")}<a href="/study/anki/stats" class="card-cta inline">- Estatísticas Anki →+ {$t("study.progress.retention_link")}</a>- para ver retenção, distribuição de intervalos e histórico de revisões.+ {$t("study.progress.retention_stub_after")}</p></div></article>@@ -602,8 +604,8 @@{#if recentAchievements.length > 0}<section class="card achievements-block"><header class="card-head">- <h2>Conquistas recentes</h2>- <a class="head-link" href="/study/achievements">Ver todas →</a>+ <h2>{$t("study.progress.recent_achievements")}</h2>+ <a class="head-link" href="/study/achievements">{$t("study.progress.view_all")}</a></header><ul class="ach-list">{#each recentAchievements as a (a.code)}diff --git a/src/routes/study/read/+page.svelte b/src/routes/study/read/+page.svelteindex 97c2aa91..ed9bacb3 100644--- a/src/routes/study/read/+page.svelte+++ b/src/routes/study/read/+page.svelte@@ -311,8 +311,17 @@cbz: "study:read:cbz:extract_cover",};const pending = books.filter((b) => cmdFor[b.format] && !b.cover_path);- if (pending.length === 0) return;+ if (pending.length === 0) {+ const formats = [...new Set(books.map((b) => b.format))];+ console.info(+ `[read/covers] no extractable covers pending. ${books.length} books, formats: ${formats.join(", ") || "(none)"}`,+ );+ return;+ }+ console.info(`[read/covers] extracting ${pending.length} cover(s)…`);extractingCovers = true;+ let okCount = 0;+ const failures: { id: number; format: string; error: string }[] = [];try {for (const b of pending) {const cmd = cmdFor[b.format];@@ -323,13 +332,26 @@books = books.map((x) =>x.id === b.id ? { ...x, cover_path: res.cover_path } : x,);+ okCount += 1;} catch (e) {- // ignore individual failures (corrupt file, no cover, etc.)+ failures.push({+ id: b.id,+ format: b.format,+ error: e instanceof Error ? e.message : String(e),+ });}}} finally {extractingCovers = false;}+ if (failures.length > 0) {+ console.warn(+ `[read/covers] ${okCount} ok, ${failures.length} failed:`,+ failures,+ );+ } else {+ console.info(`[read/covers] all ${okCount} cover(s) extracted ok`);+ }}let cleaningOrphans = $state(false);@@ -491,7 +513,7 @@);enrichCandidates = Array.isArray(res?.candidates) ? res.candidates : [];if (enrichCandidates.length === 0) {- enrichError = "Nenhum resultado. Tente editar o título do livro antes.";+ enrichError = $t("study.read.enrich_no_results") as string;} else {enrichSelected = enrichCandidates[0];}@@ -528,7 +550,7 @@} as Book;});enrichBook = null;- okMsg = "✓ Metadata atualizado";+ okMsg = $t("study.read.enrich_done") as string;setTimeout(() => (okMsg = ""), 2500);} catch (e) {enrichError = e instanceof Error ? e.message : String(e);@@ -760,13 +782,13 @@<circle cx="11" cy="11" r="7"></circle><path d="M21 21l-4.35-4.35"></path></svg>- <span>Buscar anotações</span>+ <span>{$t("study.read.search_notes_btn")}</span></a><a href="/study/read/downloads" class="ghost-btn"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12 M7 10l5 5 5-5 M5 21h14"></path></svg>- <span>Downloads</span>+ <span>{$t("study.read.downloads_btn")}</span></a><buttontype="button"@@ -1124,10 +1146,10 @@{#if enrichSelected}<div class="enrich-apply"><p class="muted small">{$t("study.read.enrich_apply_hint")}</p>- <label><input type="checkbox" bind:checked={enrichApply.title} disabled={!enrichSelected.title} /> Title: <span class="mono">{enrichSelected.title}</span></label>- <label><input type="checkbox" bind:checked={enrichApply.author} disabled={!enrichSelected.author} /> Author: <span class="mono">{enrichSelected.author ?? "—"}</span></label>- <label><input type="checkbox" bind:checked={enrichApply.publisher} disabled={!enrichSelected.publisher} /> Publisher: <span class="mono">{enrichSelected.publisher ?? "—"}</span></label>- <label><input type="checkbox" bind:checked={enrichApply.cover} disabled={!enrichSelected.cover_url} /> Cover (download)</label>+ <label><input type="checkbox" bind:checked={enrichApply.title} disabled={!enrichSelected.title} /> {$t("study.read.enrich_field_title")} <span class="mono">{enrichSelected.title}</span></label>+ <label><input type="checkbox" bind:checked={enrichApply.author} disabled={!enrichSelected.author} /> {$t("study.read.enrich_field_author")} <span class="mono">{enrichSelected.author ?? "—"}</span></label>+ <label><input type="checkbox" bind:checked={enrichApply.publisher} disabled={!enrichSelected.publisher} /> {$t("study.read.enrich_field_publisher")} <span class="mono">{enrichSelected.publisher ?? "—"}</span></label>+ <label><input type="checkbox" bind:checked={enrichApply.cover} disabled={!enrichSelected.cover_url} /> {$t("study.read.enrich_field_cover")}</label><button type="button" class="cta" onclick={applyEnrichment} disabled={enrichApplying}>{enrichApplying ? $t("study.common.loading") : $t("study.read.enrich_apply_btn")}</button>diff --git a/src/routes/study/read/[id]/+page.svelte b/src/routes/study/read/[id]/+page.svelteindex b161d6a5..9154ea45 100644--- a/src/routes/study/read/[id]/+page.svelte+++ b/src/routes/study/read/[id]/+page.svelte@@ -4,6 +4,7 @@import { goto } from "$app/navigation";import { page } from "$app/stores";import { pluginInvoke } from "$lib/plugin-invoke";+ import { rpcSetSource, rpcClearSource } from "$lib/rpc";import { awardXp } from "$lib/study-gamification";import { t } from "$lib/i18n";import SegmentedControl from "$lib/study-components/SegmentedControl.svelte";@@ -1529,6 +1530,24 @@applyFocusMode(false);popReadingTheme();void session?.stop(false);+ void rpcClearSource("reading");+ });++ $effect(() => {+ if (!book || !meta) return;+ const total = meta.page_count;+ const author = book.author?.trim();+ const stateText = author+ ? `${author} · pág. ${currentPage}/${total}`+ : `pág. ${currentPage}/${total}`;+ void rpcSetSource({+ source: "reading",+ details: book.title ?? "Lendo",+ state: stateText,+ duration: 0,+ position: 0,+ paused: false,+ });});let pendingEpubSelection = $state<EpubSelectionEvent | null>(null);diff --git a/src/routes/study/watch/+page.svelte b/src/routes/study/watch/+page.svelteindex 879c9cb3..3cc7223a 100644--- a/src/routes/study/watch/+page.svelte+++ b/src/routes/study/watch/+page.svelte@@ -1,19 +1,28 @@<script lang="ts">import { onMount } from "svelte";import { convertFileSrc, invoke } from "@tauri-apps/api/core";- import { goto } from "$app/navigation";+ import { goto, replaceState } from "$app/navigation";import { page } from "$app/stores";import { pluginInvoke } from "$lib/plugin-invoke";+ import { showToast } from "$lib/stores/toast-store.svelte";import { t } from "$lib/i18n";import PlayerShell from "$lib/study-components/player/PlayerShell.svelte";+ import ConfirmDialog from "$lib/study-components/ConfirmDialog.svelte";- type BrowseFolder = { path: string; name: string; video_count: number };+ type BrowseFolder = {+ path: string;+ name: string;+ video_count: number;+ preview_videos?: string[];+ latest_mtime?: number | null;+ };type BrowseVideo = {path: string;name: string;stem: string;size: number;subtitle_path: string | null;+ thumbnail_path?: string | null;};type BrowseDocument = {path: string;@@ -45,6 +54,12 @@let listingLoading = $state(false);let videoErr = $state(false);+ let returnUrl = $state(+ (typeof window !== "undefined"+ ? sessionStorage.getItem("study.library.return_url")+ : null) ?? "/study/library?mode=browse",+ );+const videoSrc = $derived(currentPath ? convertFileSrc(currentPath) : "");const subtitleSrc = $derived(currentSubtitle ? convertFileSrc(currentSubtitle) : "",@@ -122,7 +137,55 @@}}+ function isTypingTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ const tag = target.tagName;+ return (+ tag === "INPUT" ||+ tag === "TEXTAREA" ||+ tag === "SELECT" ||+ target.isContentEditable+ );+ }++ $effect(() => {+ if (typeof document === "undefined") return;+ function onKey(e: KeyboardEvent) {+ if (e.key !== "Escape") return;+ if (isTypingTarget(e.target)) return;+ if (document.fullscreenElement) return;+ e.preventDefault();+ back();+ }+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });+function back() {+ if (typeof window !== "undefined") {+ const folderName =+ listing?.path+ ?.replace(/\\/g, "/")+ .split("/")+ .filter(Boolean)+ .pop() ?? "";+ if (folderName) {+ try {+ sessionStorage.setItem(+ "study.library.return_toast",+ JSON.stringify({ folderName }),+ );+ } catch {+ /* ignore */+ }+ }+ const stored = sessionStorage.getItem("study.library.return_url");+ if (stored) {+ sessionStorage.removeItem("study.library.return_url");+ goto(stored);+ return;+ }+ }if (history.length > 1) {history.back();} else {@@ -145,6 +208,162 @@}return `${v.toFixed(v >= 10 || i === 0 ? 0 : 1)} ${units[i]}`;}++ type CtxMenuTarget =+ | { kind: "folder"; path: string; name: string }+ | { kind: "video"; path: string; name: string }+ | { kind: "doc"; path: string; name: string }+ | { kind: "current"; path: string; name: string };++ let contextMenu = $state<{ x: number; y: number; target: CtxMenuTarget } | null>(null);+ let renamingPath = $state<string | null>(null);+ let renameValue = $state("");+ let confirmDeleteOpen = $state(false);+ let pendingDelete = $state<CtxMenuTarget | null>(null);+ let headerMenuOpen = $state(false);++ function openContextMenu(event: MouseEvent, target: CtxMenuTarget) {+ event.preventDefault();+ event.stopPropagation();+ contextMenu = { x: event.clientX, y: event.clientY, target };+ }++ function closeContextMenu() {+ contextMenu = null;+ }++ $effect(() => {+ if (!contextMenu) return;+ function onDoc(e: MouseEvent) {+ const t = e.target as HTMLElement | null;+ if (t && t.closest(".ctx-menu")) return;+ closeContextMenu();+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") closeContextMenu();+ }+ document.addEventListener("mousedown", onDoc);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", onDoc);+ document.removeEventListener("keydown", onKey);+ };+ });++ $effect(() => {+ if (!headerMenuOpen) return;+ function onDoc(e: MouseEvent) {+ const t = e.target as HTMLElement | null;+ if (t && t.closest(".header-menu, .header-menu-btn")) return;+ headerMenuOpen = false;+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") headerMenuOpen = false;+ }+ document.addEventListener("mousedown", onDoc);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", onDoc);+ document.removeEventListener("keydown", onKey);+ };+ });++ function isTypingFsTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || target.isContentEditable;+ }++ async function showInExplorer(path: string) {+ try {+ await pluginInvoke("study", "study:shell:show_in_folder", { path });+ } catch (e) {+ console.error("show_in_folder failed", e);+ }+ closeContextMenu();+ headerMenuOpen = false;+ }++ function startRename(target: CtxMenuTarget) {+ renamingPath = target.path;+ renameValue = target.name;+ closeContextMenu();+ headerMenuOpen = false;+ }++ async function confirmRename(targetPath: string) {+ if (renamingPath !== targetPath) return;+ const trimmed = renameValue.trim();+ if (!trimmed) {+ cancelRename();+ return;+ }+ const wasCurrent = targetPath === currentPath;+ try {+ const res = await pluginInvoke<{ new_path: string; new_name: string }>(+ "study",+ "study:browse:rename",+ { path: targetPath, newName: trimmed },+ );+ renamingPath = null;+ renameValue = "";+ if (wasCurrent && typeof window !== "undefined") {+ const params = new URLSearchParams(window.location.search);+ params.set("path", res.new_path);+ params.set("name", res.new_name);+ try {+ replaceState(`${window.location.pathname}?${params.toString()}`, {});+ } catch {+ window.history.replaceState(null, "", `${window.location.pathname}?${params.toString()}`);+ }+ }+ await loadListing(listingPath);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ }+ }++ function cancelRename() {+ renamingPath = null;+ renameValue = "";+ }++ function startDelete(target: CtxMenuTarget) {+ pendingDelete = target;+ confirmDeleteOpen = true;+ closeContextMenu();+ headerMenuOpen = false;+ }++ async function performDelete() {+ if (!pendingDelete) return;+ const target = pendingDelete;+ const wasCurrent = target.path === currentPath || target.kind === "current";+ try {+ await pluginInvoke("study", "study:browse:delete", { path: target.path });+ showToast(+ "success",+ $t("study.library.delete_toast_done", { name: target.name }) as string,+ );+ if (wasCurrent) {+ back();+ } else {+ await loadListing(listingPath);+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ showToast("error", msg);+ } finally {+ pendingDelete = null;+ confirmDeleteOpen = false;+ }+ }++ function autofocusOnRender(node: HTMLInputElement) {+ node.focus();+ if (node.value.length > 0) node.select();+ }</script><section class="watch-page">@@ -158,6 +377,48 @@{#if currentName}<h1 class="title">{currentName}</h1>{/if}+ {#if currentPath}+ <div class="header-menu-wrap">+ <button+ type="button"+ class="header-menu-btn"+ onclick={() => (headerMenuOpen = !headerMenuOpen)}+ aria-haspopup="menu"+ aria-expanded={headerMenuOpen}+ aria-label={$t("study.library.ctx_open") as string}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">+ <circle cx="5" cy="12" r="2"/>+ <circle cx="12" cy="12" r="2"/>+ <circle cx="19" cy="12" r="2"/>+ </svg>+ </button>+ {#if headerMenuOpen}+ <div class="header-menu" role="menu">+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => showInExplorer(currentPath)}+ >{$t("study.library.ctx_show_in_explorer")}</button>+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() =>+ startRename({ kind: "current", path: currentPath, name: currentName })}+ >{$t("study.library.ctx_rename")}</button>+ <button+ type="button"+ class="ctx-item danger"+ role="menuitem"+ onclick={() =>+ startDelete({ kind: "current", path: currentPath, name: currentName })}+ >{$t("study.library.ctx_delete")}</button>+ </div>+ {/if}+ </div>+ {/if}</header><div class="layout">@@ -209,31 +470,55 @@{/each}{:else}{#each listing.folders as f (f.path)}+ {@const isRenaming = renamingPath === f.path}<li><buttontype="button"class="item folder"- onclick={() => navigateFolder(f.path)}+ class:renaming={isRenaming}+ onclick={() => { if (!isRenaming) navigateFolder(f.path); }}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "folder", path: f.path, name: f.name })}><span class="ico"><svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M3 7v13h18V9h-9l-2-2H3z"/></svg></span>- <span class="name">{f.name}</span>- {#if f.video_count > 0}- <span class="count mono">{f.video_count}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(f.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(f.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="name">{f.name}</span>+ {#if f.video_count > 0}+ <span class="count mono">{f.video_count}</span>+ {/if}{/if}</button></li>{/each}{#each listing.videos as v (v.path)}+ {@const isRenaming = renamingPath === v.path}<li><buttontype="button"class="item video"class:active={v.path === currentPath}- onclick={() => playVideo(v)}+ class:renaming={isRenaming}+ onclick={() => { if (!isRenaming) playVideo(v); }}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "video", path: v.path, name: v.name })}><span class="ico">{#if v.path === currentPath}@@ -246,19 +531,39 @@</svg>{/if}</span>- <span class="name">{v.name}</span>- {#if v.size}- <span class="count mono">{fmtBytes(v.size)}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(v.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(v.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="name">{v.name}</span>+ {#if v.size}+ <span class="count mono">{fmtBytes(v.size)}</span>+ {/if}{/if}</button></li>{/each}{#each listing.documents ?? [] as d (d.path)}+ {@const isRenaming = renamingPath === d.path}<li><buttontype="button"class="item doc"- onclick={() => openDocument(d)}+ class:renaming={isRenaming}+ onclick={() => { if (!isRenaming) openDocument(d); }}+ oncontextmenu={(e) =>+ openContextMenu(e, { kind: "doc", path: d.path, name: d.name })}><span class="ico"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true">@@ -266,8 +571,24 @@<path d="M14 2v6h6"/></svg></span>- <span class="name">{d.name}</span>- <span class="count mono">{d.ext.toUpperCase()}</span>+ {#if isRenaming}+ <input+ class="rename-input"+ type="text"+ bind:value={renameValue}+ onclick={(e) => e.stopPropagation()}+ onkeydown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") confirmRename(d.path);+ else if (e.key === "Escape") cancelRename();+ }}+ onblur={() => confirmRename(d.path)}+ use:autofocusOnRender+ />+ {:else}+ <span class="name">{d.name}</span>+ <span class="count mono">{d.ext.toUpperCase()}</span>+ {/if}</button></li>{/each}@@ -293,7 +614,7 @@videoSrc={videoSrc}title={currentName}courseTitle="Pasta local"- backHref="/study/library?mode=browse"+ backHref={returnUrl}durationMs={null}initialSeconds={0}initialPlaybackSpeed={1}@@ -325,7 +646,7 @@onSpeedChange={() => {}}onSkipGap={() => {}}onTheaterToggle={() => {}}- onClose={() => goto("/study/library?mode=browse")}+ onClose={back}/>{/key}</div>@@ -334,6 +655,83 @@</div></section>+<ConfirmDialog+ bind:open={confirmDeleteOpen}+ title={$t("study.library.delete_confirm_title")}+ message={pendingDelete+ ? ($t(+ pendingDelete.kind === "folder"+ ? "study.library.delete_confirm_msg_folder"+ : "study.library.delete_confirm_msg_file",+ { name: pendingDelete.name },+ ) as string)+ : ""}+ confirmLabel={$t("study.library.delete_confirm_btn")}+ variant="danger"+ onConfirm={performDelete}+/>++{#if contextMenu}+ <div+ class="ctx-menu"+ role="menu"+ style:left="{contextMenu.x}px"+ style:top="{contextMenu.y}px"+ >+ {#if contextMenu.target.kind === "folder"}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => {+ if (contextMenu) {+ const t = contextMenu.target;+ closeContextMenu();+ navigateFolder(t.path);+ }+ }}+ >{$t("study.library.ctx_open")}</button>+ {:else}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => {+ if (contextMenu) {+ const t = contextMenu.target;+ closeContextMenu();+ if (t.kind === "video") {+ const v = listing?.videos.find((vv) => vv.path === t.path);+ if (v) playVideo(v);+ } else if (t.kind === "doc") {+ const d = listing?.documents.find((dd) => dd.path === t.path);+ if (d) void openDocument(d);+ }+ }+ }}+ >{$t("study.library.ctx_open")}</button>+ {/if}+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => contextMenu && showInExplorer(contextMenu.target.path)}+ >{$t("study.library.ctx_show_in_explorer")}</button>+ <button+ type="button"+ class="ctx-item"+ role="menuitem"+ onclick={() => contextMenu && startRename(contextMenu.target)}+ >{$t("study.library.ctx_rename")}</button>+ <button+ type="button"+ class="ctx-item danger"+ role="menuitem"+ onclick={() => contextMenu && startDelete(contextMenu.target)}+ >{$t("study.library.ctx_delete")}</button>+ </div>+{/if}+<style>.watch-page {display: flex;@@ -556,4 +954,101 @@font-size: 14px;font-weight: 500;}++ .header-menu-wrap {+ position: relative;+ flex-shrink: 0;+ }+ .header-menu-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ padding: 0;+ background: transparent;+ border: 1px solid var(--content-border);+ border-radius: 6px;+ color: var(--secondary);+ cursor: pointer;+ transition: border-color 150ms ease, color 150ms ease, background 150ms ease;+ }+ .header-menu-btn:hover {+ border-color: var(--accent);+ color: var(--accent);+ background: color-mix(in oklab, var(--accent) 6%, transparent);+ }+ .header-menu {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ z-index: 50;+ min-width: 200px;+ padding: 4px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 8px;+ box-shadow: 0 8px 24px color-mix(in oklab, black 22%, transparent);+ display: flex;+ flex-direction: column;+ gap: 1px;+ }++ .ctx-menu {+ position: fixed;+ z-index: 200;+ min-width: 180px;+ max-width: 280px;+ padding: 4px;+ background: var(--surface, var(--button-elevated));+ border: 1px solid var(--content-border);+ border-radius: 8px;+ box-shadow: 0 8px 28px color-mix(in oklab, black 22%, transparent);+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .ctx-item {+ display: flex;+ align-items: center;+ padding: 7px 10px;+ background: transparent;+ border: 0;+ border-radius: 5px;+ color: var(--secondary);+ font-family: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+ transition: background 120ms ease, color 120ms ease;+ }+ .ctx-item:hover {+ background: color-mix(in oklab, var(--accent) 10%, transparent);+ }+ .ctx-item.danger {+ color: var(--error, #dc2626);+ }+ .ctx-item.danger:hover {+ background: color-mix(in oklab, var(--error, #dc2626) 12%, transparent);+ }++ .rename-input {+ flex: 1 1 auto;+ min-width: 0;+ padding: 2px 4px;+ border: 1px solid var(--accent);+ border-radius: 4px;+ background: var(--input-bg);+ color: var(--secondary);+ font-family: inherit;+ font-size: inherit;+ outline: none;+ box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent);+ }+ .item.renaming {+ cursor: default;+ }+ .item.renaming:hover {+ background: transparent;+ }</style>