diff --git a/AGENTS.md b/AGENTS.md index df81f9c..cb3d43d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,35 @@ # Инструкция для AI-агентов (Git, коммиты и релизы на git.tatar) Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`). -В системе (Windows Credential Manager) уже сохранён рабочий токен для `https://git.tatar` (`git:https://git.tatar`). +Авторизация на `https://git.tatar` должна храниться в Windows Credential Manager как **бессрочный Personal Access Token (PAT)** с `credential.https://git.tatar.provider = generic` (НЕ через OAuth-окно GCM — OAuth-токен Forgejo протухает через ~1 час, после чего `git push` удаляет запись из Credential Manager). > **ВАЖНО:** > 1. **НИКОГДА не используй браузер** для создания релизов, загрузки ассетов или настройки репозитория на `git.tatar` — браузер не авторизован и упрётся в страницу логина. Все операции с `git.tatar` выполняются через **Forgejo REST API v1** с токеном из `git credential fill`. > 2. **НИКОГДА не печатай токен** в stdout, логи, файлы или ответы пользователю. > 3. **НИКОГДА не коммить** `target/`, `original_yandex_music/`, `Yandex_Music_*.exe`, локальные `.deb`/`.exe`/`.tar.gz` и личные OAuth-токены Яндекс Музыки. +> 4. **Перед `git push` проверяй токен без интерактива** (`$env:GCM_INTERACTIVE = "never"` + `GET https://git.tatar/api/v1/user`): если токен отсутствует или истёк (401), не вешай `git push` на невидимом окне GCM — сразу попроси пользователя сохранить бессрочный PAT из `https://git.tatar/user/settings/applications` (см. раздел 0). + +--- + +## 0. Первичная настройка бессрочного токена (делается пользователем 1 раз) + +Если токен отсутствует или протух (401), пользователь создаёт **Access Token** на `https://git.tatar/user/settings/applications` (права: `write:repository`, `read:user`) и сохраняет его один раз: + +```powershell +git config --global credential.https://git.tatar.provider generic +"protocol=https`nhost=git.tatar`nusername=marwy`npassword=`n" | git credential approve +``` + +Проверка из агента (никогда не выводить `$token`, всегда ставить `GCM_INTERACTIVE=never`): + +```powershell +$env:GCM_INTERACTIVE = "never" +$credOut = "protocol=https`nhost=git.tatar`n`n" | git credential fill 2>$null +$token = ($credOut | Where-Object { $_ -like 'password=*' }) -replace '^password=','' +if (-not $token) { throw "No token in Credential Manager (need PAT for git.tatar)" } +$u = Invoke-RestMethod -Uri "https://git.tatar/api/v1/user" -Headers @{ Authorization = "token $token" } +Write-Output ("AUTH_OK: " + $u.login) +``` --- diff --git a/Cargo.lock b/Cargo.lock index c849074..7a8c5c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6325,7 +6325,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.1" +version = "0.1.2" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index ee4b2c7..a38b710 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.1" +version = "0.1.2" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index cd5873b..b45bb03 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.1-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.1-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.2-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.2-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.1-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.2-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.1-linux-x86_64.tar.gz` с готовым бинарником. +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.2-linux-x86_64.tar.gz` с готовым бинарником. ## Стек и возможности diff --git a/src/api/demo_data.rs b/src/api/demo_data.rs index d49e0f7..70a3a7c 100644 --- a/src/api/demo_data.rs +++ b/src/api/demo_data.rs @@ -330,6 +330,8 @@ pub fn demo_landing() -> LandingData { vibe_tracks, podcasts, kids_playlists, + rich_new_releases: Vec::new(), + vibe_pick_tabs: Vec::new(), } } diff --git a/src/api/mod.rs b/src/api/mod.rs index 476b289..470b1c4 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -398,6 +398,74 @@ impl YandexApiClient { } } + // Hydrate official 5.129.0 `For You` skeleton (`NEW_RELEASES` + `WAVES` / `SETS_BY_WAVES`) + let skel_ids: &[&str] = if self.has_token() { + &["web_main", "main"] + } else { + &["web_main", "main_nologin"] + }; + let mut main_skeleton: Option = None; + for sid in skel_ids { + if let Ok(sk) = self.fetch_landing_skeleton(sid).await { + if !collect_skeleton_blocks(&sk).is_empty() { + main_skeleton = Some(sk); + break; + } + } + } + if let Some(sk) = main_skeleton { + let blocks = collect_skeleton_blocks(&sk); + for block in blocks { + let btype = block["type"].as_str().unwrap_or("").to_ascii_uppercase(); + let bid = block["id"].as_str().unwrap_or("").to_ascii_lowercase(); + let uri_lc = block["source"]["uri"] + .as_str() + .or_else(|| block["data"]["source"]["uri"].as_str()) + .unwrap_or("") + .to_ascii_lowercase(); + + let is_new_releases = btype.contains("NEW_RELEASES") + || bid.contains("new_releases") + || bid.contains("new-releases") + || uri_lc.contains("new-releases") + || uri_lc.contains("new_releases"); + let is_waves = btype == "WAVES" + || btype.contains("SETS_BY_WAVES") + || bid.contains("waves") + || uri_lc.contains("waves"); + + if is_new_releases && landing.rich_new_releases.is_empty() { + let payload = if let Some(path) = build_skeleton_block_path(block) { + self.get_json(&path).await.ok() + } else { + Some(block.clone()) + }; + if let Some(val) = payload { + let rich = parse_new_releases_block(&val); + if !rich.is_empty() { + if landing.new_releases.is_empty() { + landing.new_releases = + rich.iter().map(|r| r.album.clone()).collect(); + } + landing.rich_new_releases = rich; + } + } + } else if is_waves && landing.vibe_pick_tabs.is_empty() { + let payload = if let Some(path) = build_skeleton_block_path(block) { + self.get_json(&path).await.ok() + } else { + Some(block.clone()) + }; + if let Some(val) = payload { + let tabs = parse_vibe_picks_block(&val); + if !tabs.is_empty() { + landing.vibe_pick_tabs = tabs; + } + } + } + } + } + // Try starting a real 5.128.0 Rotor Session (`POST /rotor/session/new`) if authenticated if self.has_token() { if let Ok(session) = self @@ -441,57 +509,128 @@ impl YandexApiClient { pub async fn fetch_podcast_chart(&self) -> Result> { let res = self.get_json("/chart/podcasts").await?; - let arr = res["podcasts"] - .as_array() - .or_else(|| res["albums"].as_array()) - .or_else(|| res.as_array()); - Ok(arr - .map(|a| a.iter().filter_map(parse_album).collect()) - .unwrap_or_default()) + Ok(extract_non_music_albums(&res)) + } + + /// Official 5.129.0 Books & Podcasts landing (`GET /landing/skeleton/non_music` + block fetches + `/chart/podcasts` fallback). + pub async fn fetch_non_music_landing( + &self, + ) -> Result<(Vec, Vec)> { + let mut sections: Vec = Vec::new(); + let mut flat_albums: Vec = Vec::new(); + let mut seen_album_ids: HashSet = HashSet::new(); + + let skel_res = match self.fetch_landing_skeleton("non_music").await { + Ok(v) => Ok(v), + Err(_) => self.fetch_landing_skeleton("non_music_nologin").await, + }; + + if let Ok(sk) = skel_res { + let blocks = collect_skeleton_blocks(&sk); + let mut fetched_blocks = 0usize; + for (idx, block) in blocks.into_iter().enumerate() { + if fetched_blocks >= 10 { + break; + } + let bid = block["id"] + .as_str() + .map(String::from) + .unwrap_or_else(|| format!("non_music_{}", idx)); + let btype = block["type"].as_str().unwrap_or("").to_string(); + let header_title = block["title"] + .as_str() + .or_else(|| block["data"]["title"].as_str()) + .or_else(|| block["source"]["title"].as_str()) + .unwrap_or("") + .to_string(); + + let payload = if let Some(path) = build_skeleton_block_path(block) { + fetched_blocks += 1; + match self.get_json(&path).await { + Ok(v) => v, + Err(_) => continue, + } + } else if block.get("data").map_or(false, Value::is_object) + || block.get("items").map_or(false, Value::is_array) + { + block.clone() + } else { + continue; + }; + + if let Some(sec) = parse_non_music_block(&bid, &header_title, &btype, &payload) { + for alb in &sec.albums { + if seen_album_ids.insert(alb.id.clone()) { + flat_albums.push(alb.clone()); + } + } + sections.push(sec); + } + } + } + + // Always merge `/chart/podcasts` if flat_albums is empty or no chart section was returned + if let Ok(chart_pods) = self.fetch_podcast_chart().await { + if !chart_pods.is_empty() { + let mut added_any = false; + for alb in &chart_pods { + if seen_album_ids.insert(alb.id.clone()) { + flat_albums.push(alb.clone()); + added_any = true; + } + } + if sections.is_empty() || (added_any && !sections.iter().any(|s| s.block_type.to_ascii_uppercase().contains("CHART"))) { + sections.push(NonMusicSection { + id: "podcast_chart".into(), + title: if self.is_ru_lang() { + "Чарт подкастов".into() + } else { + "Podcasts Chart".into() + }, + block_type: "CHART_ALBUMS".into(), + albums: chart_pods, + playlists: Vec::new(), + }); + } + } + } + + Ok((sections, flat_albums)) + } + + fn is_ru_lang(&self) -> bool { + self.language.to_ascii_lowercase().starts_with("ru") } pub async fn fetch_concerts_feed(&self) -> Result> { - let res = self.get_json("/concerts/feed").await?; - let mut out = Vec::new(); - let list = res["concerts"] - .as_array() - .or_else(|| res["items"].as_array()) - .or_else(|| res.as_array()); - if let Some(arr) = list { - for item in arr { - let c = if item.get("concert").is_some() { - &item["concert"] - } else { - item - }; - if let Some(id) = value_id(&c["id"]) { - out.push(ConcertItem { - id, - title: c["concertTitle"] - .as_str() - .or_else(|| c["title"].as_str()) - .unwrap_or("Concert") - .to_string(), - artist_name: c["artist"]["name"] - .as_str() - .or_else(|| c["artistName"].as_str()) - .unwrap_or("") - .to_string(), - city: c["city"].as_str().unwrap_or("").to_string(), - place: c["place"].as_str().unwrap_or("").to_string(), - date: c["datetime"] - .as_str() - .or_else(|| c["date"].as_str()) - .unwrap_or("") - .to_string(), - cover_uri: c["images"] - .as_array() - .and_then(|a| a.first()) - .and_then(|s| s.as_str()) - .or_else(|| c["artist"]["cover"]["uri"].as_str()) - .map(String::from), - afisha_url: c["afishaUrl"].as_str().map(String::from), - }); + if let Ok(res) = self.get_json("/concerts/feed").await { + let parsed = parse_concerts_feed_response(&res); + if !parsed.is_empty() { + return Ok(parsed); + } + } + + // Automatic fallback: `GET /landing/skeleton/concerts` + concert blocks (`source.uri`) + let sk = self.fetch_landing_skeleton("concerts").await?; + let mut out: Vec = Vec::new(); + let mut seen_ids: HashSet = HashSet::new(); + let mut fetched = 0usize; + for block in collect_skeleton_blocks(&sk) { + if fetched >= 6 { + break; + } + let payload = if let Some(path) = build_skeleton_block_path(block) { + fetched += 1; + match self.get_json(&path).await { + Ok(v) => v, + Err(_) => continue, + } + } else { + block.clone() + }; + for item in parse_concerts_feed_response(&payload) { + if seen_ids.insert(item.id.clone()) { + out.push(item); } } } @@ -1228,7 +1367,7 @@ impl YandexApiClient { .as_array() .map(|arr| { arr.iter() - .take(150) + .take(5000) .filter_map(|t| { let tid = value_id(&t["id"])?; if let Some(aid) = value_id(&t["albumId"]) { @@ -1245,7 +1384,25 @@ impl YandexApiClient { return Ok(Vec::new()); } - self.fetch_tracks_by_ids(&ids).await + // Hydrate ALL liked tracks in batches of 100 (up to 4 concurrent batches) preserving exact order! + let chunks: Vec> = ids.chunks(100).map(|c| c.to_vec()).collect(); + let mut all_tracks: Vec = Vec::with_capacity(ids.len()); + for group in chunks.chunks(4) { + let mut handles = Vec::with_capacity(group.len()); + for chunk in group { + let api = self.clone(); + let batch = chunk.clone(); + handles.push(tokio::spawn(async move { + api.fetch_tracks_by_ids_chunk(&batch).await + })); + } + for h in handles { + if let Ok(Ok(mut batch_tracks)) = h.await { + all_tracks.append(&mut batch_tracks); + } + } + } + Ok(all_tracks) } pub async fn fetch_disliked_track_ids(&self, uid: u64) -> Result> { @@ -1260,6 +1417,22 @@ impl YandexApiClient { /// Primary 5.128.0 batch track hydration: `PUT /tracks/v2/tracks/get-batch`, fallback `POST /tracks` pub async fn fetch_tracks_by_ids(&self, ids: &[String]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + if ids.len() <= 100 { + return self.fetch_tracks_by_ids_chunk(ids).await; + } + let mut out = Vec::with_capacity(ids.len()); + for chunk in ids.chunks(100) { + if let Ok(mut batch) = self.fetch_tracks_by_ids_chunk(chunk).await { + out.append(&mut batch); + } + } + Ok(out) + } + + async fn fetch_tracks_by_ids_chunk(&self, ids: &[String]) -> Result> { if ids.is_empty() { return Ok(Vec::new()); } @@ -1635,33 +1808,19 @@ impl YandexApiClient { } pub async fn fetch_bookshelf_liked(&self) -> Result> { - let res = match self - .get_json("/non-music/bookshelf/liked?page=0&pageSize=50") - .await - { - Ok(v) => v, - Err(_) => { - self.get_json("/non-music/bookshelf/recently-played?page=0&pageSize=50") - .await? - } - }; - let arr = res["items"] - .as_array() - .or_else(|| res["albums"].as_array()) - .or_else(|| res["podcasts"].as_array()) - .or_else(|| res.as_array()); - let mut out = Vec::new(); - if let Some(items) = arr { - for item in items { - let node = if item.get("album").is_some() { - &item["album"] - } else if item.get("data").is_some() { - &item["data"] - } else { - item - }; - if let Some(alb) = parse_album(node) { - out.push(alb); + let mut out: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + + // Fetch BOTH recently-played (for "Continue listening") and liked bookshelf items! + for path in [ + "/non-music/bookshelf/recently-played?page=0&pageSize=50", + "/non-music/bookshelf/liked?page=0&pageSize=50", + ] { + if let Ok(res) = self.get_json(path).await { + for alb in extract_non_music_albums(&res) { + if seen.insert(alb.id.clone()) { + out.push(alb); + } } } } @@ -2606,6 +2765,497 @@ fn parse_words_big_card_response(val: &Value) -> Option { Some(WordsBigCard { id, text, actions }) } +// ============================================================================= +// Skeleton, Concerts, Non-Music, NewReleases & Waves Pure Parsers +// ============================================================================= + +fn collect_skeleton_blocks<'a>(skeleton: &'a Value) -> Vec<&'a Value> { + let mut blocks: Vec<&'a Value> = Vec::new(); + let root = skeleton.get("result").unwrap_or(skeleton); + if let Some(arr) = root["blocks"].as_array() { + for b in arr { + blocks.push(b); + if let Some(nested) = b["blocks"].as_array() { + blocks.extend(nested.iter()); + } + } + } + if let Some(tabs) = root["tabs"].as_array() { + for tab in tabs { + if let Some(arr) = tab["blocks"].as_array() { + blocks.extend(arr.iter()); + } + if let Some(arr) = tab["tab"]["blocks"].as_array() { + blocks.extend(arr.iter()); + } + } + } + blocks +} + +fn build_skeleton_block_path(block: &Value) -> Option { + let source = block + .get("source") + .filter(|v| v.is_object()) + .or_else(|| block["data"].get("source").filter(|v| v.is_object()))?; + let raw_uri = source["uri"].as_str().map(str::trim).filter(|s| !s.is_empty())?; + let mut path = if let Some(stripped) = raw_uri.strip_prefix("https://api.music.yandex.net") { + stripped.to_string() + } else if raw_uri.starts_with('/') { + raw_uri.to_string() + } else { + format!("/{}", raw_uri) + }; + let count_web = source["countWeb"] + .as_u64() + .or_else(|| source["count"].as_u64()) + .or_else(|| block["data"]["countWeb"].as_u64()); + if let Some(n) = count_web { + if n > 0 && !path.contains("count=") && !path.contains("limit=") { + let sep = if path.contains('?') { '&' } else { '?' }; + path.push_str(&format!("{}count={}", sep, n)); + } + } + Some(path) +} + +fn parse_album_with_fallback_artists( + album_node: &Value, + artists_fallback: Option<&Value>, +) -> Option { + let mut alb = parse_album(album_node)?; + if alb.artists.is_empty() { + if let Some(arr) = artists_fallback.and_then(Value::as_array) { + alb.artists = arr.iter().filter_map(parse_artist).collect(); + } + } + Some(alb) +} + +fn extract_non_music_albums(res: &Value) -> Vec { + let mut out: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let candidates = [ + res["items"].as_array(), + res["data"]["items"].as_array(), + res["chart"]["albums"].as_array(), + res["albums"].as_array(), + res["podcasts"].as_array(), + res["entities"].as_array(), + res.as_array(), + ]; + for arr in candidates.into_iter().flatten() { + for item in arr { + let item_type = item["type"].as_str().unwrap_or(""); + if item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") { + continue; + } + let parsed = if item["data"]["album"].is_object() { + parse_album_with_fallback_artists( + &item["data"]["album"], + item["data"].get("artists"), + ) + } else if item["album"].is_object() { + parse_album_with_fallback_artists(&item["album"], item.get("artists")) + } else if item["data"].is_object() { + parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) + } else { + parse_album(item) + }; + if let Some(alb) = parsed { + if seen.insert(alb.id.clone()) { + out.push(alb); + } + } + } + } + out +} + +fn parse_non_music_block( + id: &str, + header_title: &str, + block_type: &str, + res: &Value, +) -> Option { + let title = if !header_title.trim().is_empty() { + header_title.trim().to_string() + } else { + res["title"] + .as_str() + .or_else(|| res["data"]["title"].as_str()) + .or_else(|| res["chart"]["title"].as_str()) + .unwrap_or("") + .trim() + .to_string() + }; + + let mut albums: Vec = Vec::new(); + let mut playlists: Vec = Vec::new(); + let mut seen_albums: HashSet = HashSet::new(); + let mut seen_playlists: HashSet = HashSet::new(); + + let lists = [ + res["items"].as_array(), + res["data"]["items"].as_array(), + res["chart"]["albums"].as_array(), + res["albums"].as_array(), + res["podcasts"].as_array(), + res["playlists"].as_array(), + res["entities"].as_array(), + res.as_array(), + ]; + for arr in lists.into_iter().flatten() { + for item in arr { + let item_type = item["type"].as_str().unwrap_or(""); + let is_playlist_item = item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") + || item["data"]["playlist"].is_object() + || item["playlist"].is_object() + || (item.get("kind").is_some() && item.get("owner").is_some()); + + if is_playlist_item { + let pl_node = if item["data"]["playlist"].is_object() { + &item["data"]["playlist"] + } else if item["playlist"].is_object() { + &item["playlist"] + } else if item["data"].is_object() && item["data"].get("kind").is_some() { + &item["data"] + } else { + item + }; + if let Some(pl) = parse_playlist(pl_node) { + let key = format!("{}:{}", pl.owner_uid, pl.kind); + if seen_playlists.insert(key) { + playlists.push(pl); + } + } + continue; + } + + let alb = if item["data"]["album"].is_object() { + parse_album_with_fallback_artists( + &item["data"]["album"], + item["data"].get("artists"), + ) + } else if item["album"].is_object() { + parse_album_with_fallback_artists(&item["album"], item.get("artists")) + } else if item["data"].is_object() { + parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) + } else { + parse_album(item) + }; + if let Some(a) = alb { + if seen_albums.insert(a.id.clone()) { + albums.push(a); + } + } + } + } + + if albums.is_empty() && playlists.is_empty() { + return None; + } + Some(NonMusicSection { + id: id.to_string(), + title, + block_type: block_type.to_string(), + albums, + playlists, + }) +} + +fn parse_concerts_feed_response(res: &Value) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let list = res["items"] + .as_array() + .or_else(|| res["concerts"].as_array()) + .or_else(|| res["data"]["items"].as_array()) + .or_else(|| res.as_array()); + let Some(arr) = list else { + return out; + }; + + for item in arr { + let data_node = item + .get("data") + .filter(|v| v.is_object()) + .unwrap_or(item); + let c = data_node + .get("concert") + .filter(|v| v.is_object()) + .or_else(|| item.get("concert").filter(|v| v.is_object())) + .unwrap_or(data_node); + + let Some(id) = value_id(&c["id"]).or_else(|| value_id(&item["id"])) else { + continue; + }; + if !seen.insert(id.clone()) { + continue; + } + + let title = c["concertTitle"] + .as_str() + .or_else(|| c["title"].as_str()) + .unwrap_or("Concert") + .to_string(); + let artist_name = c["artist"]["name"] + .as_str() + .or_else(|| c["artistName"].as_str()) + .or_else(|| data_node["artist"]["name"].as_str()) + .unwrap_or("") + .to_string(); + let city = c["city"].as_str().unwrap_or("").to_string(); + let place = c["place"].as_str().unwrap_or("").to_string(); + let date = c["datetime"] + .as_str() + .or_else(|| c["date"].as_str()) + .unwrap_or("") + .to_string(); + let cover_uri = c["cover"]["uri"] + .as_str() + .filter(|s| !s.is_empty()) + .or_else(|| { + c["images"].as_array().and_then(|a| { + a.first() + .and_then(|v| v.as_str().or_else(|| v["uri"].as_str())) + }) + }) + .or_else(|| c["artist"]["cover"]["uri"].as_str()) + .or_else(|| data_node["cover"]["uri"].as_str()) + .map(String::from); + let cover_color = c["cover"]["color"] + .as_str() + .or_else(|| data_node["cover"]["color"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let price_node = data_node + .get("minPrice") + .or_else(|| c.get("minPrice")) + .or_else(|| item.get("minPrice")); + let min_price = price_node.and_then(|p| { + p["value"] + .as_u64() + .or_else(|| p["value"].as_f64().map(|f| f.round() as u64)) + .or_else(|| p.as_u64()) + }); + let currency = price_node + .and_then(|p| p["currency"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let cashback_node = c.get("cashback").or_else(|| data_node.get("cashback")); + let cashback_percent = cashback_node + .and_then(|cb| { + cb["valuePercent"] + .as_u64() + .or_else(|| cb["percent"].as_u64()) + }) + .map(|v| v as u32); + let cashback_title = cashback_node + .and_then(|cb| cb["title"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let event_kind = c["eventInfo"]["type"] + .as_str() + .or_else(|| c["eventType"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let afisha_url = c["afishaUrl"] + .as_str() + .filter(|s| !s.is_empty()) + .map(String::from) + .or_else(|| { + Some(format!( + "https://afisha.yandex.ru/search?text={}", + urlencoding::encode(&title) + )) + }); + + out.push(ConcertItem { + id, + title, + artist_name, + city, + place, + date, + cover_uri, + afisha_url, + min_price, + currency, + cashback_percent, + cashback_title, + cover_color, + event_kind, + }); + } + out +} + +fn parse_new_releases_block(res: &Value) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let arr = res["newReleases"] + .as_array() + .or_else(|| res["data"]["newReleases"].as_array()) + .or_else(|| res["items"].as_array()) + .or_else(|| res["data"]["items"].as_array()) + .or_else(|| res["albums"].as_array()) + .or_else(|| res.as_array()); + let Some(items) = arr else { + return out; + }; + + for item in items { + let node = item + .get("data") + .filter(|v| v.is_object()) + .unwrap_or(item); + let album_node = if node["album"].is_object() { + &node["album"] + } else { + node + }; + let Some(album) = parse_album_with_fallback_artists(album_node, node.get("artists")) else { + continue; + }; + if !seen.insert(album.id.clone()) { + continue; + } + let artist_cover_uri = node["artists"] + .as_array() + .and_then(|a| a.first()) + .and_then(|ar| { + ar["cover"]["uri"] + .as_str() + .or_else(|| ar["ogImage"].as_str()) + }) + .filter(|s| !s.is_empty()) + .map(String::from) + .or_else(|| album.artists.first().and_then(|a| a.cover_uri.clone())); + let cover_color = node["cover"]["color"] + .as_str() + .or_else(|| album_node["cover"]["color"].as_str()) + .or_else(|| album_node["derivedColors"]["average"].as_str()) + .or_else(|| node["derivedColors"]["average"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let release_date = node["releaseDate"] + .as_str() + .or_else(|| album_node["releaseDate"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + out.push(NewReleaseItem { + album, + artist_cover_uri, + cover_color, + release_date, + }); + } + out +} + +fn parse_vibe_picks_block(res: &Value) -> Vec { + let mut tabs = Vec::new(); + let arr = res["waves"] + .as_array() + .or_else(|| res["data"]["waves"].as_array()) + .or_else(|| res["tabs"].as_array()) + .or_else(|| res["data"]["tabs"].as_array()) + .or_else(|| res.as_array()); + let Some(raw_tabs) = arr else { + return tabs; + }; + + for raw_tab in raw_tabs { + let title = raw_tab["title"] + .as_str() + .or_else(|| raw_tab["name"].as_str()) + .unwrap_or("") + .trim() + .to_string(); + let raw_items = raw_tab["items"] + .as_array() + .or_else(|| raw_tab["waves"].as_array()) + .or_else(|| raw_tab["stations"].as_array()); + let Some(items_arr) = raw_items else { + continue; + }; + + let mut parsed_items = Vec::new(); + for raw_item in items_arr { + let obj = raw_item + .get("data") + .filter(|v| v.is_object()) + .or_else(|| raw_item.get("wave").filter(|v| v.is_object())) + .unwrap_or(raw_item); + let Some(item_title) = obj["title"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + else { + continue; + }; + let header = obj["header"] + .as_str() + .or_else(|| obj["subtitle"].as_str()) + .unwrap_or("") + .trim() + .to_string(); + let mut seeds: Vec = obj["seeds"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(String::from)) + .collect() + }) + .unwrap_or_default(); + if seeds.is_empty() { + if let Some(sid) = obj["stationId"].as_str().filter(|s| !s.is_empty()) { + seeds.push(sid.to_string()); + } + } + let color_hex = obj["colors"]["average"] + .as_str() + .or_else(|| obj["color"].as_str()) + .or_else(|| obj["backgroundColor"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let background_image_url = obj["backgroundImageUrl"] + .as_str() + .or_else(|| obj["backgroundImageUri"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let image_url = obj["imageUrl"] + .as_str() + .or_else(|| obj["imageUri"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + parsed_items.push(VibePickItem { + title: item_title.to_string(), + header, + seeds, + color_hex, + background_image_url, + image_url, + }); + } + + if !parsed_items.is_empty() { + tabs.push(VibePickTab { + title, + items: parsed_items, + }); + } + } + tabs +} + fn parse_writers_field(v: &Value) -> Option { let arr = v.as_array()?; let joined: Vec<&str> = arr @@ -3024,4 +3674,184 @@ mod tests { assert_eq!(big.actions.len(), 1); assert_eq!(big.actions[0].url, "https://genius.com/test"); } + + #[test] + fn test_parse_concerts_feed_nested_data_shape() { + let payload = json!({ + "items": [ + { + "type": "CONCERT", + "data": { + "concert": { + "id": "conc-42", + "concertTitle": "Баста — Большой концерт", + "city": "Москва", + "place": "ВТБ Арена", + "datetime": "2026-11-28T20:00:00+03:00", + "cover": { + "uri": "avatars.yandex.net/get-afisha/1/poster/%%", + "color": "#2A1F3D" + }, + "afishaUrl": "https://afisha.yandex.ru/moscow/concert/basta", + "cashback": { + "title": "Кешбэк 15%", + "valuePercent": 15 + }, + "eventInfo": { "type": "CONCERT" }, + "artist": { "name": "Баста" } + }, + "minPrice": { + "value": 3500, + "currency": "RUB" + } + } + }, + { + "data": { + "concert": { + "id": "conc-99", + "concertTitle": "Indie Night", + "city": "Казань", + "place": "Werk", + "datetime": "2026-12-05T19:00:00+03:00" + } + } + } + ] + }); + + let parsed = parse_concerts_feed_response(&payload); + assert_eq!(parsed.len(), 2); + let first = &parsed[0]; + assert_eq!(first.id, "conc-42"); + assert_eq!(first.title, "Баста — Большой концерт"); + assert_eq!(first.artist_name, "Баста"); + assert_eq!(first.city, "Москва"); + assert_eq!(first.place, "ВТБ Арена"); + assert_eq!(first.min_price, Some(3500)); + assert_eq!(first.currency.as_deref(), Some("RUB")); + assert_eq!(first.cashback_percent, Some(15)); + assert_eq!(first.cashback_title.as_deref(), Some("Кешбэк 15%")); + assert_eq!(first.cover_color.as_deref(), Some("#2A1F3D")); + assert_eq!(first.event_kind.as_deref(), Some("CONCERT")); + assert_eq!( + first.cover_uri.as_deref(), + Some("avatars.yandex.net/get-afisha/1/poster/%%") + ); + + let second = &parsed[1]; + assert_eq!(second.id, "conc-99"); + assert!(second + .afisha_url + .as_deref() + .unwrap_or("") + .starts_with("https://afisha.yandex.ru/search?text=")); + } + + #[test] + fn test_parse_non_music_skeleton_blocks() { + let block_payload = json!({ + "title": "Популярные аудиокниги и подкасты", + "items": [ + { + "type": "NON_MUSIC_ALBUM_ITEM", + "data": { + "album": { + "id": 7001, + "title": "Дюна", + "type": "audiobook", + "trackCount": 24, + "coverUri": "avatars.yandex.net/get-music-content/1/dune/%%" + }, + "artists": [ + { "id": 10, "name": "Фрэнк Герберт" } + ] + } + }, + { + "type": "PLAYLIST_ITEM", + "data": { + "playlist": { + "kind": 1005, + "owner": { "uid": 500, "name": "Редакция" }, + "title": "Лучшие подкасты недели", + "trackCount": 12 + } + } + } + ] + }); + + let sec = parse_non_music_block("nm-1", "", "MIXED_ENTITIES", &block_payload) + .expect("non-music section should parse"); + assert_eq!(sec.title, "Популярные аудиокниги и подкасты"); + assert_eq!(sec.albums.len(), 1); + assert_eq!(sec.albums[0].id, "7001"); + assert_eq!(sec.albums[0].content_type.as_deref(), Some("audiobook")); + assert_eq!(sec.albums[0].artists.len(), 1); + assert_eq!(sec.albums[0].artists[0].name, "Фрэнк Герберт"); + assert_eq!(sec.playlists.len(), 1); + assert_eq!(sec.playlists[0].title, "Лучшие подкасты недели"); + } + + #[test] + fn test_parse_new_releases_and_waves_blocks() { + let nr_payload = json!({ + "newReleases": [ + { + "album": { + "id": 8888, + "title": "Midnight Pulse", + "type": "single", + "coverUri": "avatars.yandex.net/get-music-content/2/mp/%%" + }, + "artists": [ + { + "id": 301, + "name": "Aether", + "cover": { "uri": "avatars.yandex.net/get-music-content/2/aether/%%" } + } + ], + "releaseDate": "2026-11-27", + "cover": { "uri": "avatars.yandex.net/get-music-content/2/mp/%%", "color": "#1E3A8A" } + } + ] + }); + let rich = parse_new_releases_block(&nr_payload); + assert_eq!(rich.len(), 1); + assert_eq!(rich[0].album.id, "8888"); + assert_eq!(rich[0].album.artists[0].name, "Aether"); + assert_eq!( + rich[0].artist_cover_uri.as_deref(), + Some("avatars.yandex.net/get-music-content/2/aether/%%") + ); + assert_eq!(rich[0].cover_color.as_deref(), Some("#1E3A8A")); + assert_eq!(rich[0].release_date.as_deref(), Some("2026-11-27")); + + let waves_payload = json!({ + "waves": [ + { + "title": "по языку", + "items": [ + { + "title": "Английский", + "header": "Моя волна по языку", + "seeds": ["language:english"], + "colors": { "average": "#3B82F6" }, + "backgroundImageUrl": "https://avatars.yandex.net/bg.png", + "imageUrl": "https://avatars.yandex.net/img.png" + } + ] + } + ] + }); + let tabs = parse_vibe_picks_block(&waves_payload); + assert_eq!(tabs.len(), 1); + assert_eq!(tabs[0].title, "по языку"); + assert_eq!(tabs[0].items.len(), 1); + assert_eq!(tabs[0].items[0].title, "Английский"); + assert_eq!(tabs[0].items[0].header, "Моя волна по языку"); + assert_eq!(tabs[0].items[0].seeds, vec!["language:english"]); + assert_eq!(tabs[0].items[0].color_hex.as_deref(), Some("#3B82F6")); + } } diff --git a/src/api/models.rs b/src/api/models.rs index a1c68c3..fca575f 100644 --- a/src/api/models.rs +++ b/src/api/models.rs @@ -184,6 +184,53 @@ pub struct LandingData { pub vibe_tracks: Vec, pub podcasts: Vec, pub kids_playlists: Vec, + #[serde(default)] + pub rich_new_releases: Vec, + #[serde(default)] + pub vibe_pick_tabs: Vec, +} + +/// Rich editorial new release item from `GET /landing/skeleton/web_main` (`NEW_RELEASES`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NewReleaseItem { + pub album: AlbumSummary, + #[serde(default)] + pub artist_cover_uri: Option, + #[serde(default)] + pub cover_color: Option, + #[serde(default)] + pub release_date: Option, +} + +/// Single My Vibe wave pick item from `WAVES` / `SETS_BY_WAVES` skeleton block. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VibePickItem { + pub title: String, + pub header: String, + pub seeds: Vec, + #[serde(default)] + pub color_hex: Option, + #[serde(default)] + pub background_image_url: Option, + #[serde(default)] + pub image_url: Option, +} + +/// Category tab inside `More Picks` (`Ещё подборки`) from `WAVES` / `SETS_BY_WAVES`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VibePickTab { + pub title: String, + pub items: Vec, +} + +/// Section block on the Books & Podcasts (`non_music`) landing page. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct NonMusicSection { + pub id: String, + pub title: String, + pub block_type: String, + pub albums: Vec, + pub playlists: Vec, } #[derive(Debug, Clone)] @@ -264,7 +311,7 @@ pub struct PlayTelemetryEvent { pub batch_id: Option, } -/// Concert item returned by `GET /concerts/feed` +/// Concert item returned by `GET /concerts/feed` or `GET /landing/skeleton/concerts` #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConcertItem { pub id: String, @@ -275,6 +322,18 @@ pub struct ConcertItem { pub date: String, pub cover_uri: Option, pub afisha_url: Option, + #[serde(default)] + pub min_price: Option, + #[serde(default)] + pub currency: Option, + #[serde(default)] + pub cashback_percent: Option, + #[serde(default)] + pub cashback_title: Option, + #[serde(default)] + pub cover_color: Option, + #[serde(default)] + pub event_kind: Option, } fn default_wheel_item_type() -> String { diff --git a/src/app/state.rs b/src/app/state.rs index 05351f4..652d210 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -248,6 +248,12 @@ pub enum AppAction { title: String, seeds: Vec, }, + StartVibeStation { + title: String, + seeds: Vec, + }, + RefreshConcerts, + RefreshNonMusic, ApplyVibeSettings { mood: Option, activity: Option, @@ -387,6 +393,7 @@ pub(crate) enum ApiEvent { AccountLoaded(Result), LandingLoaded(LandingData), ConcertsLoaded(Vec), + NonMusicLoaded(Vec, Vec), SearchHistoryLoaded(Vec), LikedTracksLoaded(Vec), FavoriteFiltersLoaded(Vec), @@ -474,6 +481,9 @@ pub struct AppState { pub account: Option, pub landing: LandingData, pub concerts: Vec, + pub concerts_loading: bool, + pub non_music_sections: Vec, + pub non_music_loading: bool, pub liked_tracks: Vec, pub liked_ids: HashSet, pub disliked_ids: HashSet, @@ -627,6 +637,9 @@ impl AppState { account: None, landing: LandingData::default(), concerts: Vec::new(), + concerts_loading: false, + non_music_sections: Vec::new(), + non_music_loading: false, liked_tracks: Vec::new(), liked_ids: HashSet::new(), disliked_ids: HashSet::new(), @@ -774,6 +787,9 @@ impl AppState { account, landing, concerts: Vec::new(), + concerts_loading: false, + non_music_sections: Vec::new(), + non_music_loading: false, liked_tracks, liked_ids, disliked_ids: HashSet::new(), @@ -1289,9 +1305,16 @@ impl AppState { let api = self.api.clone(); let tx = self.tx_api.clone(); self.runtime.spawn(async move { - if let Ok(concerts) = api.fetch_concerts_feed().await { - let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); - } + let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); + }); + } + { + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); }); } { @@ -1637,12 +1660,53 @@ impl AppState { } }); } + Route::Concerts => { + self.detail_loading = false; + if self.concerts.is_empty() && !self.concerts_loading { + self.refresh_concerts(); + } + } + Route::Podcasts => { + self.detail_loading = false; + if self.non_music_sections.is_empty() && !self.non_music_loading { + self.refresh_non_music(); + } + } _ => { self.detail_loading = false; } } } + pub fn refresh_concerts(&mut self) { + self.concerts_loading = true; + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); + }); + } + + pub fn refresh_non_music(&mut self) { + self.non_music_loading = true; + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); + }); + if self.api.has_token() { + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + if let Ok(shelf) = api.fetch_bookshelf_liked().await { + let _ = tx.send(ApiEvent::BookshelfLoaded(shelf)); + } + }); + } + } + pub fn launch_oauth_login(&mut self) { self.show_toast(self.i18n().toast_opening_oauth()); let tx = self.tx_api.clone(); @@ -1717,6 +1781,12 @@ impl AppState { self.show_toast(t.toast_welcome(&acc.display_name)); self.account = Some(acc); self.ensure_words_for_current_track(); + if self.concerts.is_empty() && !self.concerts_loading { + self.refresh_concerts(); + } + if self.non_music_sections.is_empty() && !self.non_music_loading { + self.refresh_non_music(); + } } ApiEvent::AccountLoaded(Err(e)) => { self.show_toast(if t.is_ru() { @@ -1726,7 +1796,19 @@ impl AppState { }); } ApiEvent::ConcertsLoaded(concerts) => { - self.concerts = concerts; + self.concerts_loading = false; + if !concerts.is_empty() || self.concerts.is_empty() { + self.concerts = concerts; + } + } + ApiEvent::NonMusicLoaded(sections, albums) => { + self.non_music_loading = false; + if !sections.is_empty() { + self.non_music_sections = sections; + } + if !albums.is_empty() { + self.landing.podcasts = albums; + } } ApiEvent::SearchHistoryLoaded(hist) => { self.config.search_history = hist; @@ -1777,6 +1859,10 @@ impl AppState { self.queue_index = 0; } } + let mut data = data; + if data.podcasts.is_empty() && !self.landing.podcasts.is_empty() { + data.podcasts = self.landing.podcasts.clone(); + } self.landing = data; } ApiEvent::LikedTracksLoaded(tracks) => { @@ -2419,7 +2505,12 @@ impl AppState { } AppAction::ActivateWheelItem(item) => self.activate_wheel_item(item), AppAction::ReshuffleWheel => self.reshuffle_wheel(), - AppAction::StartVibeBySeeds { title, seeds } => self.start_vibe_by_seeds(title, seeds), + AppAction::StartVibeBySeeds { title, seeds } + | AppAction::StartVibeStation { title, seeds } => { + self.start_vibe_by_seeds(title, seeds); + } + AppAction::RefreshConcerts => self.refresh_concerts(), + AppAction::RefreshNonMusic => self.refresh_non_music(), AppAction::ApplyVibeSettings { mood, activity, diff --git a/src/main.rs b/src/main.rs index afd9149..ca96fe6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,7 +135,8 @@ fn build_window_attrs(init_w: f64, init_h: f64) -> WindowAttributes { .with_inner_size(LogicalSize::new(init_w, init_h)) .with_min_inner_size(LogicalSize::new(768.0, 650.0)) .with_decorations(false) // Custom frameless 32px Yandex TitleBar! - .with_resizable(true); + .with_resizable(true) + .with_visible(false); // Stay hidden until DWM + first pure-black/splash frame is presented! #[cfg(target_os = "linux")] { use winit::platform::wayland::WindowAttributesExtWayland; @@ -628,6 +629,17 @@ impl ApplicationHandler for AppRunner { self.window_focused = true; self.window_occluded = false; self.last_frame_hash = None; + + // Present the first theme-matched + splash frame into the swapchain BEFORE making the + // window visible so there is zero white OS/DWM flash on startup! + // (On Linux/Wayland where an unmapped window may report 0x0, skip pre-render and reveal.) + let init_size = window.inner_size(); + if init_size.width > 0 && init_size.height > 0 { + self.render(event_loop); + self.last_frame_hash = None; + } + window.set_visible(true); + window.focus_window(); window.request_redraw(); } @@ -880,6 +892,76 @@ fn apply_win11_dwm_style(window: &Window, is_dark: bool) { &round as *const _ as *const _, std::mem::size_of::() as u32, ); + // DWMWA_CAPTION_COLOR (35): pure black in dark mode, pure white in light mode + const DWMWA_CAPTION_COLOR: u32 = 35; + let caption_color: u32 = if is_dark { 0x0000_0000 } else { 0x00FF_FFFF }; + DwmSetWindowAttribute( + hwnd, + DWMWA_CAPTION_COLOR, + &caption_color as *const _ as *const _, + std::mem::size_of::() as u32, + ); + + // Replace Win32 class background brush (BLACK_BRUSH=4 / WHITE_BRUSH=0) & prime + // the client backing surface so Win32 never flashes white before or during resize. + #[repr(C)] + struct WinRect { + left: i32, + top: i32, + right: i32, + bottom: i32, + } + #[link(name = "gdi32")] + extern "system" { + fn GetStockObject(i: i32) -> *mut std::ffi::c_void; + } + #[link(name = "user32")] + extern "system" { + #[cfg(target_pointer_width = "64")] + fn SetClassLongPtrW( + hwnd: *mut std::ffi::c_void, + index: i32, + new_long: isize, + ) -> isize; + #[cfg(target_pointer_width = "32")] + fn SetClassLongW( + hwnd: *mut std::ffi::c_void, + index: i32, + new_long: i32, + ) -> i32; + fn GetClientRect(hwnd: *mut std::ffi::c_void, rect: *mut WinRect) -> i32; + fn GetDC(hwnd: *mut std::ffi::c_void) -> *mut std::ffi::c_void; + fn FillRect( + hdc: *mut std::ffi::c_void, + rect: *const WinRect, + hbr: *mut std::ffi::c_void, + ) -> i32; + fn ReleaseDC(hwnd: *mut std::ffi::c_void, hdc: *mut std::ffi::c_void) -> i32; + } + const WHITE_BRUSH: i32 = 0; + const BLACK_BRUSH: i32 = 4; + const GCLP_HBRBACKGROUND: i32 = -10; + let brush = GetStockObject(if is_dark { BLACK_BRUSH } else { WHITE_BRUSH }); + if !brush.is_null() { + #[cfg(target_pointer_width = "64")] + SetClassLongPtrW(hwnd, GCLP_HBRBACKGROUND, brush as isize); + #[cfg(target_pointer_width = "32")] + SetClassLongW(hwnd, GCLP_HBRBACKGROUND, brush as i32); + + let mut rc = WinRect { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + if GetClientRect(hwnd, &mut rc) != 0 { + let hdc = GetDC(hwnd); + if !hdc.is_null() { + FillRect(hdc, &rc, brush); + ReleaseDC(hwnd, hdc); + } + } + } } } } diff --git a/src/views/collection.rs b/src/views/collection.rs index e4ba9bd..d7653e9 100644 --- a/src/views/collection.rs +++ b/src/views/collection.rs @@ -3,7 +3,7 @@ use crate::app::state::{AppAction, AppState, CollectionTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::scroll::visible_row_range; -use crate::engine::text::{TextAlign, TextStyle}; +use crate::engine::text::{RichSpan, TextAlign, TextStyle}; use crate::engine::theme::{YmPalette, TRACK_ROW_HEIGHT}; use crate::engine::types::{Color, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ @@ -14,15 +14,18 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; -/// Exact Yandex Music Desktop 5.129.0 Collection Page (`pages_api_spec.md` §5): -/// All 7 original tabs: -/// 1. Любимые треки (My Favorites) -/// 2. Плейлисты (with "+ Создать плейлист" card/button + Rename & Delete controls!) -/// 3. Альбомы (Liked albums grid) -/// 4. Исполнители (Liked artists circular grid) -/// 5. Подкасты и книги (Bookshelf / Podcasts grid) -/// 6. Скачанное (Offline downloaded tracks with play & delete from device) -/// 7. История (Listening history) +/// 1-to-1 Official Yandex Music Desktop 5.129.0 `My Collection` (`web_collection`): +/// - Default view (`CollectionTab::Tracks`): clean vertical feed: +/// - Header (`Коллекция` / `My Collection`) + colored subtitle (`У вашей музыки есть цвет`) +/// - Section 1: `❤️ Мне нравится >` transparent header + 2-column × 4-row compact track grid +/// - Section 2: `Любимые исполнители >` horizontal circular artist carousel +/// - Section 3: `Плейлисты >` horizontal carousel starting with `+ Создать плейлист` +/// - Section 4: `Альбомы >` horizontal carousel +/// - Section 5: `Подкасты и книги >` horizontal carousel (when non-empty) +/// - Section 6: `История >` 2-column × 4-row compact track grid (when non-empty) +/// - Section 7: `Скачанное >` 2-column × 4-row compact track grid (when non-empty) +/// - Sub-views (`Artists`, `Playlists`, `Albums`, `PodcastsAndBooks`, `History`, `Downloaded`): +/// clean `← Коллекция` back button + full interactive grid/list with full CRUD & menus. pub fn render_collection( ctx: &mut UiContext, pal: &YmPalette, @@ -40,168 +43,691 @@ pub fn render_collection( let scroll_id = WidgetId::new("collection_scroll"); let scroll_y = ctx.begin_scroll_v(scroll_id, rect, 0.0); - // `views/mod.rs` already insets `inner_r` by (25, 13, 25, 0) let x = rect.left(); let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; - // Page Heading - ctx.draw_text_ellipsis( - t.collection(), - TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), - TextAlign::Left, - ); - y += 58.0; - - // Signature "Мне нравится" / "My Favorites" Hero Banner Card (theme-aware!) - let hero_r = Rect::from_xywh(x, y, avail_w, 120.0); - let hero_resp = ctx.interact(WidgetId::new("col_fav_hero"), hero_r); - let hero_bg = if pal.is_dark { - if hero_resp.hovered { - Color::rgb(0x2A, 0x24, 0x17) - } else { - Color::rgb(0x22, 0x1D, 0x12) - } - } else if hero_resp.hovered { - Color::rgb(0xFF, 0xF2, 0xBC) - } else { - Color::rgb(0xFF, 0xF8, 0xD6) - }; - ctx.dl() - .push_rect_bordered(hero_r, 16.0, hero_bg, 1.0, pal.border_subtle); - - let cov_r = Rect::from_xywh(hero_r.left() + 18.0, hero_r.center_y() - 42.0, 84.0, 84.0); - draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 12.0, false, true); - - let fav_title = t.liked_playlist(); - ctx.draw_text_ellipsis( - fav_title, - TextStyle::headline(26.0, pal.text_bright), - Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 28.0, avail_w - 280.0, 32.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - &t.count_tracks(app.liked_tracks.len()), - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 66.0, avail_w - 280.0, 22.0), - TextAlign::Left, - ); - - let likes_playing = app.is_context_playing("likes"); - let play_btn_label = if likes_playing { t.pause() } else { t.listen() }; - let play_text_w = ctx - .measure_text(play_btn_label, TextStyle::medium(14.0, pal.on_yellow), None) - .x; - let play_btn_w = (play_text_w + 28.0 + 36.0).max(100.0).ceil(); - let play_btn_r = Rect::from_xywh( - hero_r.right() - play_btn_w - 24.0, - hero_r.center_y() - 21.0, - play_btn_w, - 42.0, - ); - let play_resp = crate::engine::widgets::yellow_pill_button_in( - ctx, - pal, - WidgetId::new("col_fav_play"), - play_btn_r, - Some(if likes_playing { - Icon::PauseXxs - } else { - Icon::PlayXxs - }), - play_btn_label, - app.liked_tracks.is_empty(), - ); - if play_resp.clicked && !app.liked_tracks.is_empty() { - actions.push(AppAction::ToggleContextPlay { - tracks: app.liked_tracks.clone(), - context_name: fav_title.into(), - context_key: "likes".into(), - is_vibe: false, - }); - } else if hero_resp.clicked { - actions.push(AppAction::Navigate(Route::LikedTracks)); - } - if hero_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - y += 120.0 + 20.0; - - // All 7 Original Collection Tabs (horizontal scrollable pill bar!) - let tabs_vp = Rect::from_xywh(x, y, avail_w, 42.0); - let tabs_h_id = WidgetId::new("col_tabs_hscroll"); - let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); - let mut tx = x - tabs_sx; - let all_tabs = [ - (CollectionTab::Tracks, t.liked_tracks_tab()), - (CollectionTab::Playlists, t.playlists()), - (CollectionTab::Albums, t.albums()), - (CollectionTab::Artists, t.artists()), - (CollectionTab::PodcastsAndBooks, t.podcasts_and_books()), - (CollectionTab::Downloaded, t.downloaded()), - (CollectionTab::History, t.history()), - ]; - for (tab_kind, label) in all_tabs { - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("col_tab", tab_kind as u8), - Pos2::new(tx, y), - None, - label, - 38.0, - app.collection_tab == tab_kind, + // ------------------------------------------------------------------------- + // DEFAULT VERTICAL OVERVIEW (`CollectionTab::Tracks`) + // ------------------------------------------------------------------------- + if app.collection_tab == CollectionTab::Tracks { + // Header: Bold 34px Headline + official colored subtitle + ctx.draw_text_ellipsis( + t.collection(), + TextStyle::headline(34.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 42.0), + TextAlign::Left, ); - if resp.clicked { - app.collection_tab = tab_kind; - } - tx = r.right() + 8.0; - } - let tabs_total_w = (tx + tabs_sx) - x; - ctx.end_scroll_h(tabs_h_id, pal, tabs_total_w, false); - y += 56.0; + y += 44.0; - // ------------------------------------------------------------------------- - // TAB BODY - // ------------------------------------------------------------------------- - match app.collection_tab { - CollectionTab::Tracks => { - if app.liked_tracks.is_empty() { - ctx.draw_text_wrapped( - if ru { - "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." - } else { - "Like tracks or sign in to Yandex Music — they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 44.0), - Some(2), - TextAlign::Left, - ); - y += 48.0; - } else { - let tracks = app.liked_tracks.clone(); - y = render_virtual_track_list( - ctx, - pal, - covers, - app, - shell, - rect, - x, - y, - avail_w, - &tracks, - "col_liked", - fav_title, - "likes", - current_track_id.as_deref(), - is_playing, - actions, - ); + let pink_accent = Color::rgb(0xE8, 0x3E, 0x8C); + let spans = if ru { + [ + RichSpan::new( + "У вашей музыки есть ", + TextStyle::medium(14.0, pal.text_secondary), + ), + RichSpan::new("цвет", TextStyle::medium(14.0, pink_accent)), + ] + } else { + [ + RichSpan::new( + "Your music has a ", + TextStyle::medium(14.0, pal.text_secondary), + ), + RichSpan::new("color", TextStyle::medium(14.0, pink_accent)), + ] + }; + ctx.draw_rich_text( + &spans, + Rect::from_xywh(x, y, avail_w, 24.0), + Some(1), + TextAlign::Left, + ); + y += 38.0; + + // --------------------------------------------------------------------- + // SECTION 1: ❤️ My Favorites > (transparent header + 2×4 compact grid) + // --------------------------------------------------------------------- + let fav_title = t.liked_playlist(); + { + let hdr_r = Rect::from_xywh(x, y, avail_w.min(460.0), 58.0); + let hdr_resp = ctx.interact(WidgetId::new("col_fav_header"), hdr_r); + + let cov_r = Rect::from_xywh(x, y + 1.0, 56.0, 56.0); + draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 10.0, false, true); + + let tx = cov_r.right() + 14.0; + let title_style = TextStyle::headline( + 22.0, + if hdr_resp.hovered { + pal.text_bright + } else { + pal.text_primary + }, + ); + let title_w = ctx.measure_text(fav_title, title_style, None).x; + ctx.draw_text_ellipsis( + fav_title, + title_style, + Rect::from_xywh(tx, y + 4.0, (avail_w - 110.0).max(120.0), 28.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size( + Pos2::new( + (tx + title_w + 14.0).min(x + avail_w - 14.0), + y + 18.0, + ), + Vec2::splat(20.0), + ), + if hdr_resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + ctx.draw_text_ellipsis( + &t.count_tracks(app.liked_tracks.len()), + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(tx, y + 34.0, (avail_w - 90.0).max(120.0), 20.0), + TextAlign::Left, + ); + + if hdr_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if hdr_resp.clicked { + actions.push(AppAction::Navigate(Route::LikedTracks)); } } + y += 58.0 + 16.0; + + if app.liked_tracks.is_empty() { + ctx.draw_text_wrapped( + if ru { + "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." + } else { + "Like tracks or sign in to Yandex Music — they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 40.0), + Some(2), + TextAlign::Left, + ); + y += 48.0; + } else { + let liked_tracks = app.liked_tracks.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &liked_tracks, + "col_ov_fav", + fav_title, + "likes", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 28.0; + } + + // --------------------------------------------------------------------- + // SECTION 2: Favorite Artists > (horizontal circular carousel) + // --------------------------------------------------------------------- + { + let art_title = if ru { + "Любимые исполнители" + } else { + "Favorite Artists" + }; + let h_id = WidgetId::new("col_ov_artists_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_artists"), + art_title, + x, + y, + avail_w, + Some(h_id), + !app.liked_artists.is_empty(), + ) { + app.collection_tab = CollectionTab::Artists; + } + y += 38.0; + + if app.liked_artists.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Здесь появятся ваши любимые исполнители." + } else { + "Your favorite artists will appear here." + }, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 22.0), + TextAlign::Left, + ); + y += 34.0; + } else { + let artists = app.liked_artists.clone(); + let card_w = 168.0; + let card_h = card_w + 52.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for art in artists.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_art", &art.id), + cr, + &art.name, + t.artist(), + art.cover_uri.as_deref(), + &format!("art_{}", art.id), + true, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "artist".into(), + id: art.id.clone(), + title: art.name.clone(), + subtitle: t.artist().into(), + cover_uri: art.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/artist/{}", art.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayArtist { + id: art.id.clone(), + name: art.name.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Artist { + id: art.id.clone(), + name: art.name.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + artists.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + } + + // --------------------------------------------------------------------- + // SECTION 3: Playlists > (horizontal carousel starting with `+ Create`) + // --------------------------------------------------------------------- + { + let h_id = WidgetId::new("col_ov_playlists_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_playlists"), + t.playlists(), + x, + y, + avail_w, + Some(h_id), + true, + ) { + app.collection_tab = CollectionTab::Playlists; + } + y += 38.0; + + let playlists = app.user_playlists.clone(); + let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + // Slot 0: compact `+ Создать плейлист` card + { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let cov_r = Rect::from_xywh(cr.left(), cr.top(), card_w, card_w); + let resp = ctx.interact(WidgetId::new("col_ov_create_pl"), cr); + ctx.dl().push_rect_bordered( + cov_r, + 10.0, + if resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_control, + ); + ctx.draw_icon( + Icon::AddXxs, + Rect::from_center_size(cov_r.center(), Vec2::splat(34.0)), + if resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + ctx.draw_text_ellipsis( + t.create_playlist(), + TextStyle::medium(13.5, pal.text_primary), + Rect::from_xywh(cr.left(), cov_r.bottom() + 8.0, card_w, 20.0), + TextAlign::Left, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + actions.push(AppAction::OpenCreatePlaylistModal { + initial_track: None, + }); + } + } + cx += card_w + gap; + } + + for pl in playlists.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = t.count_tracks(pl.track_count as usize); + let is_own = pl.kind != "3" + && (pl.owner_uid == "local" + || my_uid.as_deref() == Some(pl.owner_uid.as_str())); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_pl", format!("{}_{}", pl.owner_uid, pl.kind)), + cr, + &pl.title, + &sub, + pl.cover_uri.as_deref(), + &format!("upl_{}_{}", pl.owner_uid, pl.kind), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "playlist".into(), + id: format!("{}:{}", pl.owner_uid, pl.kind), + title: pl.title.clone(), + subtitle: t.playlist().into(), + cover_uri: pl.cover_uri.clone(), + owner_uid: Some(pl.owner_uid.clone()), + is_own_playlist: is_own, + tracks: Vec::new(), + anchor: pos, + share_url: format!( + "https://music.yandex.ru/users/{}/playlists/{}", + pl.owner_uid, pl.kind + ), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayPlaylist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Playlist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + (playlists.len().min(24) + 1) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + + // --------------------------------------------------------------------- + // SECTION 4: Albums > (horizontal carousel) + // --------------------------------------------------------------------- + { + let h_id = WidgetId::new("col_ov_albums_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_albums"), + t.albums(), + x, + y, + avail_w, + Some(h_id), + !app.liked_albums.is_empty(), + ) { + app.collection_tab = CollectionTab::Albums; + } + y += 38.0; + + if app.liked_albums.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Здесь появятся ваши любимые альбомы." + } else { + "Your favorite albums will appear here." + }, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 22.0), + TextAlign::Left, + ); + y += 34.0; + } else { + let albums = app.liked_albums.clone(); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for alb in albums.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = alb + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(t.album()); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_alb", &alb.id), + cr, + &alb.title, + sub, + alb.cover_uri.as_deref(), + &format!("alb_{}", alb.id), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: alb.id.clone(), + title: alb.title.clone(), + subtitle: t.album().into(), + cover_uri: alb.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", alb.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayAlbum { + id: alb.id.clone(), + title: alb.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + albums.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + } + + // --------------------------------------------------------------------- + // SECTION 5: Podcasts & Audiobooks > (when non-empty) + // --------------------------------------------------------------------- + if !app.bookshelf_items.is_empty() { + let h_id = WidgetId::new("col_ov_books_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_books"), + t.podcasts_and_books(), + x, + y, + avail_w, + Some(h_id), + true, + ) { + app.collection_tab = CollectionTab::PodcastsAndBooks; + } + y += 38.0; + + let items = app.bookshelf_items.clone(); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for pod in items.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = pod + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(if ru { "Подкаст" } else { "Podcast" }); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_pod", &pod.id), + cr, + &pod.title, + sub, + pod.cover_uri.as_deref(), + &format!("pod_{}", pod.id), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: pod.id.clone(), + title: pod.title.clone(), + subtitle: sub.to_string(), + cover_uri: pod.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", pod.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayAlbum { + id: pod.id.clone(), + title: pod.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: pod.id.clone(), + title: pod.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + items.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + + // --------------------------------------------------------------------- + // SECTION 6: History > (2-col × 4-row compact track grid when non-empty) + // --------------------------------------------------------------------- + if !app.play_history.is_empty() { + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_history"), + t.history(), + x, + y, + avail_w, + None, + false, + ) { + app.collection_tab = CollectionTab::History; + } + y += 38.0; + + let hist = app.play_history.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &hist, + "col_ov_hist", + t.history(), + "history", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 28.0; + } + + // --------------------------------------------------------------------- + // SECTION 7: Downloaded > (compact preview list when non-empty) + // --------------------------------------------------------------------- + if !app.config.downloaded_tracks.is_empty() { + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_downloaded"), + t.downloaded(), + x, + y, + avail_w, + None, + false, + ) { + app.collection_tab = CollectionTab::Downloaded; + } + y += 38.0; + + let dl = app.config.downloaded_tracks.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &dl, + "col_ov_dl", + t.downloaded_tracks(), + "downloads", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 16.0; + } + + y += 20.0; + let total_h = y - (rect.top() - scroll_y); + ctx.end_scroll_v(scroll_id, pal, total_h, true); + return; + } + + // ------------------------------------------------------------------------- + // SUB-VIEWS (Back button `← Коллекция` + full grid/list) + // ------------------------------------------------------------------------- + let (back_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("col_sub_back"), + Pos2::new(x, y), + Some(Icon::ArrowLeft), + t.collection(), + 34.0, + false, + ); + if back_resp.clicked { + app.collection_tab = CollectionTab::Tracks; + } + y += 48.0; + + let sub_title = match app.collection_tab { + CollectionTab::Tracks => t.collection(), + CollectionTab::Playlists => t.playlists(), + CollectionTab::Albums => t.albums(), + CollectionTab::Artists => { + if ru { + "Любимые исполнители" + } else { + "Favorite Artists" + } + } + CollectionTab::PodcastsAndBooks => t.podcasts_and_books(), + CollectionTab::Downloaded => t.downloaded(), + CollectionTab::History => t.history(), + }; + ctx.draw_text_ellipsis( + sub_title, + TextStyle::headline(32.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 40.0), + TextAlign::Left, + ); + y += 52.0; + + match app.collection_tab { + CollectionTab::Tracks => {} CollectionTab::Playlists => { let gap = 16.0; @@ -209,7 +735,6 @@ pub fn render_collection( let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(132.0); let card_h = card_w + 62.0; - // Total slots = 1 ("+ Create playlist" card) + user_playlists.len() let playlists = app.user_playlists.clone(); let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); @@ -375,11 +900,7 @@ pub fn render_collection( } CollectionTab::Albums => { - let albums = if !app.liked_albums.is_empty() { - app.liked_albums.clone() - } else { - Vec::new() - }; + let albums = app.liked_albums.clone(); if albums.is_empty() { ctx.draw_text_ellipsis( if ru { @@ -627,7 +1148,6 @@ pub fn render_collection( ); y += 48.0; } else { - // Header bar with Play Offline + Clear all downloaded let dl_playing = app.is_context_playing("downloads"); let (play_r, pr) = yellow_pill_button( ctx, @@ -730,6 +1250,231 @@ pub fn render_collection( ctx.end_scroll_v(scroll_id, pal, total_h, true); } +/// Clickable `Section Title >` heading with optional `<` `>` carousel scroll arrows on the right. +#[allow(clippy::too_many_arguments)] +fn draw_section_heading( + ctx: &mut UiContext, + pal: &YmPalette, + id: WidgetId, + title: &str, + x: f32, + y: f32, + avail_w: f32, + h_scroll_id: Option, + show_arrows: bool, +) -> bool { + let style_idle = TextStyle::headline(22.0, pal.text_primary); + let tw = ctx.measure_text(title, style_idle, None).x; + let head_w = (tw + 30.0).min((avail_w - 84.0).max(140.0)); + let head_r = Rect::from_xywh(x, y, head_w, 28.0); + let resp = ctx.interact(id, head_r); + + ctx.draw_text_ellipsis( + title, + TextStyle::headline( + 22.0, + if resp.hovered { + pal.text_bright + } else { + pal.text_primary + }, + ), + Rect::from_xywh(x, y, (head_w - 24.0).max(60.0), 28.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size( + Pos2::new(head_r.right() - 10.0, head_r.center_y()), + Vec2::splat(20.0), + ), + if resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + + if let (Some(h_id), true) = (h_scroll_id, show_arrows) { + let right_x = x + avail_w; + let cy = y + 14.0; + let next_r = Rect::from_center_size(Pos2::new(right_x - 15.0, cy), Vec2::splat(30.0)); + let prev_r = Rect::from_center_size(Pos2::new(right_x - 51.0, cy), Vec2::splat(30.0)); + + let (off_x, max_x) = { + let st = ctx.scrolls.get_or_create(h_id); + (st.offset.x, st.max_offset().x) + }; + let can_prev = off_x > 2.0; + let can_next = max_x > 2.0 && off_x < max_x - 2.0; + + let prev_resp = ctx.interact(h_id.with("prev"), prev_r); + let next_resp = ctx.interact(h_id.with("next"), next_r); + + ctx.dl().push_rect_bordered( + prev_r, + 15.0, + if prev_resp.hovered && can_prev { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_subtle, + ); + ctx.draw_icon( + Icon::ArrowLeft, + Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), + if can_prev { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + ctx.dl().push_rect_bordered( + next_r, + 15.0, + if next_resp.hovered && can_next { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_subtle, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), + if can_next { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { + ctx.set_cursor(CursorKind::Pointer); + } + if prev_resp.clicked && can_prev { + ctx.scrolls.get_or_create(h_id).scroll_by_x(-552.0); + ctx.request_repaint(); + } + if next_resp.clicked && can_next { + ctx.scrolls.get_or_create(h_id).scroll_by_x(552.0); + ctx.request_repaint(); + } + } + + resp.clicked +} + +/// Official 5.129.0 2-column × 4-row compact track grid (tracks 0..4 left, 4..8 right, 24px gap, 56px row height). +/// Gracefully collapses to 1 column of up to 6 tracks when `avail_w < 660.0`. +#[allow(clippy::too_many_arguments)] +fn render_compact_two_col_track_grid( + ctx: &mut UiContext, + pal: &YmPalette, + covers: &mut CoverCache, + app: &AppState, + shell: &mut ShellUiState, + viewport: Rect, + x: f32, + top_y: f32, + avail_w: f32, + tracks: &[Track], + salt: &str, + context_name: &str, + context_key: &str, + current_track_id: Option<&str>, + is_playing: bool, + actions: &mut Vec, +) -> f32 { + let t = app.i18n(); + let row_h = 56.0; + let two_cols = avail_w >= 660.0; + let col_gap = 24.0; + let max_items = if two_cols { 8 } else { 6 }; + let count = tracks.len().min(max_items); + let rows_per_col = if two_cols { 4 } else { count }; + let col_w = if two_cols { + (avail_w - col_gap) * 0.5 + } else { + avail_w + }; + + for idx in 0..count { + let col = if two_cols { idx / 4 } else { 0 }; + let row = if two_cols { idx % 4 } else { idx }; + let row_r = Rect::from_xywh( + x + col as f32 * (col_w + col_gap), + top_y + row as f32 * row_h, + col_w, + row_h, + ); + if row_r.bottom() < viewport.top() - 40.0 || row_r.top() > viewport.bottom() + 40.0 { + continue; + } + let tr = &tracks[idx]; + let is_curr = current_track_id == Some(tr.id.as_str()); + match track_row( + ctx, + pal, + covers, + WidgetId::from_pair(salt, idx), + row_r, + tr, + TrackRowOptions { + index: None, + show_chart_rank: false, + show_cover: true, + is_current: is_curr, + is_playing: is_curr && is_playing, + is_liked: app.liked_ids.contains(&tr.id), + is_disliked: app.disliked_ids.contains(&tr.id), + is_downloaded: app.is_track_downloaded(&tr.id), + menu_open: shell.is_track_menu_open(&tr.id), + }, + ) { + TrackRowAction::Play => { + actions.push(AppAction::PlayTracks { + tracks: tracks.to_vec(), + start_index: idx, + context_name: context_name.to_string(), + context_key: context_key.to_string(), + is_vibe: false, + }); + } + TrackRowAction::ToggleLike => actions.push(AppAction::ToggleLike(tr.clone())), + TrackRowAction::ToggleDislike => actions.push(AppAction::ToggleDislike(tr.clone())), + TrackRowAction::OpenArtist(id, name) => { + actions.push(AppAction::Navigate(Route::Artist { id, name })); + } + TrackRowAction::OpenAlbum(id) => { + actions.push(AppAction::Navigate(Route::Album { + id, + title: tr + .album_title + .clone() + .unwrap_or_else(|| t.album().into()), + })); + } + TrackRowAction::OpenContextMenu(pos) => { + shell.open_track_menu(tr.clone(), pos); + } + TrackRowAction::None => {} + } + } + + let used_rows = if two_cols { + count.min(rows_per_col) + } else { + count + }; + top_y + used_rows as f32 * row_h +} + #[allow(clippy::too_many_arguments)] fn render_virtual_track_list( ctx: &mut UiContext, diff --git a/src/views/for_you.rs b/src/views/for_you.rs index 3e12343..ec0c6c4 100644 --- a/src/views/for_you.rs +++ b/src/views/for_you.rs @@ -1,3 +1,6 @@ +use std::cell::Cell; + +use crate::api::models::{NewReleaseItem, VibePickItem, VibePickTab}; use crate::app::state::{AppAction, AppState, CollectionTab, ForYouTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -9,7 +12,11 @@ use crate::engine::widgets::{ }; use crate::engine::UiContext; use crate::icons::Icon; -use crate::views::overlays::ShellUiState; +use crate::views::overlays::{EntityContextMenuState, ShellUiState}; + +thread_local! { + static FOR_YOU_PICKS_TAB: Cell = const { Cell::new(0) }; +} /// Exact Yandex Music Desktop 5.129.0 "For you and Trends" page (`vibe_wheel_foryou_spec.md` §4): /// - Persistent heading ("Для вас и Тренды" / "For you and Trends") + IN-PLACE switcher tabs ("Для вас" / "Тренды") @@ -496,10 +503,15 @@ pub fn render_for_you( y += card_h + 26.0; } - // 5. "New Releases" - if !app.landing.new_releases.is_empty() { - y = render_new_releases_carousel(ctx, pal, covers, app, x, y, avail_w, "fy_rel", actions); + // 5. "New Releases >" (1-to-1 official `NewRelease` + `NewReleaseCard` circular portrait + colored release card!) + if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { + y = render_new_releases_carousel( + ctx, pal, covers, app, shell, rect, x, y, avail_w, "fy_rel", actions, + ); } + + // 6. Official "More Picks" / "Ещё подборки" (`Waves` / `SETS_BY_WAVES`) + y = render_more_picks_section(ctx, pal, app, rect, x, y, avail_w, actions); } ForYouTab::Trends => { @@ -606,12 +618,14 @@ pub fn render_for_you( } // 2. New Releases Carousel - if !app.landing.new_releases.is_empty() { + if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { y = render_new_releases_carousel( ctx, pal, covers, app, + shell, + rect, x, y, avail_w, @@ -678,9 +692,162 @@ pub fn render_for_you( } y += 20.0; - let _ = CornerRadii::ZERO; let total_h = y - (rect.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_h, true); + + // Sticky Frosted Top Switcher Bar when scrolled (`scroll_y > 72.0` -> zero impact on `scroll_y == 0` parity!) + if scroll_y > 72.0 { + let fade_in = ((scroll_y - 72.0) / 36.0).clamp(0.0, 1.0); + let bar_r = Rect::from_xywh( + rect.left() - 25.0, + rect.top() - 12.0, + rect.width() + 50.0, + 66.0, + ); + // Subtle atmospheric gradient glow behind the frosted sticky bar + let glow_c = if pal.is_dark { + Color::rgb(0x4E, 0x35, 0x62) + } else { + Color::rgb(0xD8, 0xD2, 0xE8) + }; + ctx.dl().push_gradient_rect( + bar_r, + CornerRadii::top(12.0), + glow_c.with_alpha((54.0 * fade_in).round() as u8), + glow_c.with_alpha(0), + Vec2::new(0.0, 1.0), + ); + let glass_tint = if pal.is_dark { + css_rgba(18, 18, 18, (186.0 * fade_in).round() as u8) + } else { + css_rgba(255, 255, 255, (206.0 * fade_in).round() as u8) + }; + ctx.dl().push_backdrop_blur( + bar_r, + CornerRadii::top(12.0), + 2.0, + glass_tint, + 0.0, + Color::TRANSPARENT, + ); + ctx.dl().push_rect( + Rect::from_xywh(bar_r.left(), bar_r.bottom() - 1.0, bar_r.width(), 1.0), + 0.0, + pal.border_subtle.scale_alpha(fade_in), + ); + + let mut sx = x; + let sy = bar_r.center_y() - 19.0; + for (tab_kind, label) in [ + (ForYouTab::ForYou, t.for_you()), + (ForYouTab::Trends, t.trends()), + ] { + let active = app.for_you_tab == tab_kind; + let tw = ctx + .measure_text(label, TextStyle::bold(14.5, pal.text_primary), None) + .x + + 32.0; + let pr = Rect::from_xywh(sx, sy, tw.max(88.0), 38.0); + let resp = ctx.interact(WidgetId::from_pair("fy_sticky_tab", tab_kind as u8), pr); + if active || resp.hovered { + ctx.dl().push_rect( + pr, + 19.0, + if active { + pal.surface_hover + } else { + pal.surface_secondary + }, + ); + } + ctx.draw_text_ellipsis( + label, + TextStyle::bold( + 14.5, + if active || resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ), + pr, + TextAlign::Center, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked && !active { + actions.push(AppAction::SetForYouTab(tab_kind)); + } + sx = pr.right() + 8.0; + } + } +} + +fn rich_dark_tint(raw: Color) -> Color { + // Rich dark-saturated card tint (~24% lightness) keeping high contrast for white album text + let r = (raw.r as f32 / 255.0).clamp(0.0, 1.0); + let g = (raw.g as f32 / 255.0).clamp(0.0, 1.0); + let b = (raw.b as f32 / 255.0).clamp(0.0, 1.0); + let max_c = r.max(g).max(b); + let min_c = r.min(g).min(b); + let avg = (max_c + min_c) * 0.5; + // Slightly boost chroma then scale luminance into ~0.22..0.28 range + let sat_r = (avg + (r - avg) * 1.25).clamp(0.0, 1.0); + let sat_g = (avg + (g - avg) * 1.25).clamp(0.0, 1.0); + let sat_b = (avg + (b - avg) * 1.25).clamp(0.0, 1.0); + let luma = (0.299 * sat_r + 0.587 * sat_g + 0.114 * sat_b).max(0.01); + let scale = (0.24 / luma).clamp(0.28, 0.95); + Color::rgb( + ((sat_r * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ((sat_g * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ((sat_b * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ) +} + +fn format_release_subtitle(item: &NewReleaseItem, ru: bool) -> String { + let is_single = item + .album + .content_type + .as_deref() + .map_or(false, |ct| ct.eq_ignore_ascii_case("single")) + || (item.album.track_count > 0 && item.album.track_count <= 3); + let kind = if is_single { + if ru { "сингл" } else { "single" } + } else if ru { + "альбом" + } else { + "album" + }; + + if let Some(ref rd) = item.release_date { + let date_part = rd.split('T').next().unwrap_or(rd); + let parts: Vec<&str> = date_part.split('-').collect(); + if parts.len() >= 3 { + if let (Ok(m), Ok(d)) = (parts[1].parse::(), parts[2].parse::()) { + if (1..=12).contains(&m) && d > 0 { + const MONTHS_RU: [&str; 12] = [ + "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", + "сентября", "октября", "ноября", "декабря", + ]; + const MONTHS_EN: [&str; 12] = [ + "January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December", + ]; + return if ru { + format!("{} · {} {}", kind, d, MONTHS_RU[m - 1]) + } else { + format!("{} · {} {}", kind, MONTHS_EN[m - 1], d) + }; + } + } + } + } + if let Some(yr) = item.album.year { + format!("{} · {}", kind, yr) + } else { + kind.to_string() + } } #[allow(clippy::too_many_arguments)] @@ -689,6 +856,8 @@ fn render_new_releases_carousel( pal: &YmPalette, covers: &mut CoverCache, app: &AppState, + shell: &mut ShellUiState, + viewport: Rect, x: f32, mut y: f32, avail_w: f32, @@ -696,58 +865,589 @@ fn render_new_releases_carousel( actions: &mut Vec, ) -> f32 { let t = app.i18n(); + let ru = t.is_ru(); + let items: Vec = if !app.landing.rich_new_releases.is_empty() { + app.landing.rich_new_releases.clone() + } else { + app.landing + .new_releases + .iter() + .cloned() + .map(|album| NewReleaseItem { + artist_cover_uri: album.artists.first().and_then(|a| a.cover_uri.clone()), + cover_color: None, + release_date: None, + album, + }) + .collect() + }; + if items.is_empty() { + return y; + } + + let h_id = WidgetId::new(salt); + let card_w = 286.0_f32; + let gap = 18.0_f32; + let portrait_d = 236.0_f32; + let overlap = 56.0_f32; + let bottom_h = 80.0_f32; + let card_h = portrait_d - overlap + bottom_h; // 260.0 + let total_w = items.len() as f32 * (card_w + gap); + + // Header row: "New Releases >" + circular `<` `>` carousel arrows on right + let head_txt = t.new_releases(); + let head_tw = ctx + .measure_text(head_txt, TextStyle::headline(24.0, pal.text_primary), None) + .x; ctx.draw_text_ellipsis( - t.new_releases(), + head_txt, + TextStyle::headline(24.0, pal.text_primary), + Rect::from_xywh(x, y, head_tw + 4.0, 30.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(Pos2::new(x + head_tw + 16.0, y + 15.0), Vec2::splat(22.0)), + pal.text_secondary, + ); + + let (can_left, can_right) = ctx + .scrolls + .get(h_id) + .map(|s| (s.can_scroll_left(), s.can_scroll_right())) + .unwrap_or((false, total_w > avail_w + 10.0)); + let l_btn_c = Pos2::new(x + avail_w - 54.0, y + 15.0); + let r_btn_c = Pos2::new(x + avail_w - 16.0, y + 15.0); + for (c, ic, enabled, is_right) in [ + (l_btn_c, Icon::ArrowLeftXxs, can_left, false), + (r_btn_c, Icon::ArrowRightXxs, can_right, true), + ] { + let br = Rect::from_center_size(c, Vec2::splat(32.0)); + let resp = ctx.interact(WidgetId::from_pair(salt, if is_right { "next" } else { "prev" }), br); + let bg = if enabled && resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }; + ctx.dl().push_circle(c, 16.0, bg); + ctx.draw_icon( + ic, + Rect::from_center_size(c, Vec2::splat(18.0)), + if enabled { + if resp.hovered { pal.text_bright } else { pal.text_primary } + } else { + pal.text_disabled + }, + ); + if enabled && resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if enabled && resp.clicked { + let delta = if is_right { (card_w + gap) * 2.0 } else { -(card_w + gap) * 2.0 }; + ctx.scrolls.scroll_by_x(h_id, delta); + ctx.request_repaint(); + } + } + y += 42.0; + + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { + let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - scroll_x; + for item in &items { + let alb = &item.album; + let outer_r = Rect::from_xywh(cx, y, card_w, card_h); + if outer_r.right() >= row_vp.left() - 80.0 && outer_r.left() <= row_vp.right() + 80.0 { + // 1. Huge 236x236 circular artist portrait overlapping the bottom card by 56px + let circle_r = Rect::from_xywh( + cx + (card_w - portrait_d) * 0.5, + y, + portrait_d, + portrait_d, + ); + let portrait_uri = item + .artist_cover_uri + .as_deref() + .or(alb.cover_uri.as_deref()); + let (portrait_dom, _) = draw_cover_art( + ctx, + pal, + covers, + circle_r, + portrait_uri, + &format!("nr_art_{}", alb.id), + portrait_d * 0.5, + true, + false, + ); + + // Resolve rich dark-saturated tint from `cover_color` or cover dominant color + let raw_tint = item + .cover_color + .as_deref() + .and_then(Color::from_hex_str) + .or_else(|| { + alb.cover_uri + .as_deref() + .and_then(|u| covers.get_or_fetch(u, 200)) + .map(|(_, dom, _)| dom) + }) + .unwrap_or(portrait_dom); + let card_tint = rich_dark_tint(raw_tint); + + // Smooth lower gradient fade over lower 42% of circular portrait + ctx.push_clip(circle_r, portrait_d * 0.5); + let scrim_h = portrait_d * 0.46; + ctx.dl().push_gradient_rect( + Rect::from_xywh(circle_r.left(), circle_r.bottom() - scrim_h, portrait_d, scrim_h), + 0.0, + card_tint.with_alpha(0), + card_tint.with_alpha(232), + Vec2::new(0.0, 1.0), + ); + ctx.pop_clip(); + + // Bold white centered Artist Name above the card overlap + let artist_name = alb + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(alb.title.as_str()); + let art_lbl_r = Rect::from_xywh( + circle_r.left() + 18.0, + y + portrait_d - overlap - 54.0, + portrait_d - 36.0, + 50.0, + ); + ctx.draw_text_wrapped( + artist_name, + TextStyle::headline(21.0, Color::WHITE).with_line_height(24.0), + art_lbl_r, + Some(2), + TextAlign::Center, + ); + + let port_click_r = Rect::from_xywh(circle_r.left(), circle_r.top(), portrait_d, portrait_d - overlap); + let port_resp = ctx.interact(WidgetId::from_pair(salt, format!("port_{}", alb.id)), port_click_r); + if port_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + + // 2. Bottom 80px colored rounded release card (`radius: 14px`) + let card_r = Rect::from_xywh(cx, y + portrait_d - overlap, card_w, bottom_h); + let card_resp = ctx.interact(WidgetId::from_pair(salt, format!("card_{}", alb.id)), card_r); + let card_bg = if card_resp.hovered { + card_tint.lerp(Color::WHITE, 0.08) + } else { + card_tint + }; + ctx.dl().push_shadow( + card_r, + 14.0, + 12.0, + 0.0, + Vec2::new(0.0, 4.0), + css_rgba(0, 0, 0, 72), + ); + ctx.dl().push_rect_bordered( + card_r, + 14.0, + card_bg, + 1.0, + css_rgba(255, 255, 255, 26), + ); + + // Left 62x62 rounded (8px) album cover + let cov_r = Rect::from_xywh(card_r.left() + 9.0, card_r.top() + 9.0, 62.0, 62.0); + draw_cover_art( + ctx, + pal, + covers, + cov_r, + alb.cover_uri.as_deref(), + &format!("nr_alb_{}", alb.id), + 8.0, + false, + false, + ); + + // Right 38x38 crisp white circular Play/Pause button + let play_c = Pos2::new(card_r.right() - 28.0, card_r.center_y()); + let play_r = Rect::from_center_size(play_c, Vec2::splat(38.0)); + let play_resp = ctx.interact(WidgetId::from_pair(salt, format!("play_{}", alb.id)), play_r); + let play_rad = if play_resp.hovered { 20.0 } else { 19.0 }; + ctx.dl().push_circle(play_c, play_rad, Color::WHITE); + let alb_playing = app.is_context_playing(&format!("album:{}", alb.id)); + ctx.draw_icon( + if alb_playing { + Icon::PauseFilledXs + } else { + Icon::PlayFilledXs + }, + Rect::from_center_size(play_c, Vec2::splat(18.0)), + Color::rgb(0x14, 0x14, 0x14), + ); + + // Middle bold white title + muted release subtitle + let tx_l = cov_r.right() + 12.0; + let tx_w = (play_r.left() - tx_l - 8.0).max(40.0); + ctx.draw_text_ellipsis( + &alb.title, + TextStyle::bold(14.5, Color::WHITE), + Rect::from_xywh(tx_l, card_r.top() + 18.0, tx_w, 20.0), + TextAlign::Left, + ); + let sub = format_release_subtitle(item, ru); + ctx.draw_text_ellipsis( + &sub, + TextStyle::medium(12.5, css_rgba(255, 255, 255, 172)), + Rect::from_xywh(tx_l, card_r.top() + 42.0, tx_w, 18.0), + TextAlign::Left, + ); + + if play_resp.hovered || card_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if card_resp.right_clicked { + let pos = ctx + .input + .pointer_pos + .unwrap_or(Pos2::new(card_r.center_x(), card_r.bottom())); + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: alb.id.clone(), + title: alb.title.clone(), + subtitle: sub, + cover_uri: alb.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", alb.id), + }); + } else if play_resp.clicked { + actions.push(AppAction::PlayAlbum { + id: alb.id.clone(), + title: alb.title.clone(), + }); + } else if card_resp.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } else if port_resp.clicked { + if let Some(first) = alb.artists.first() { + actions.push(AppAction::Navigate(Route::Artist { + id: first.id.clone(), + name: first.name.clone(), + })); + } else { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } + } + } + cx += card_w + gap; + } + ctx.end_scroll_h(h_id, pal, total_w, false); + } + + y + card_h + 34.0 +} + +fn fallback_vibe_pick_tabs(ru: bool) -> Vec { + let mk = |title: &str, header: &str, seed: &str, hex: &str| VibePickItem { + title: title.into(), + header: header.into(), + seeds: vec![seed.into()], + color_hex: Some(hex.into()), + background_image_url: None, + image_url: None, + }; + if ru { + vec![ + VibePickTab { + title: "топ".into(), + items: vec![ + mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), + mk("Электроника", "Моя волна по жанру", "genre:electronics", "#8341EF"), + mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#FF5C4D"), + mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), + mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#D97706"), + ], + }, + VibePickTab { + title: "по языку".into(), + items: vec![ + mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), + mk("Русский", "Моя волна по языку", "language:russian", "#E11D48"), + mk("Без слов", "Моя волна по языку", "language:without-words", "#0F766E"), + ], + }, + VibePickTab { + title: "по жанру".into(), + items: vec![ + mk("Электроника", "Моя волна по жанру", "genre:electronics", "#7C3AED"), + mk("Хип-хоп", "Моя волна по жанру", "genre:hiphop", "#EA580C"), + mk("Рок", "Моя волна по жанру", "genre:rock", "#DC2626"), + mk("Поп", "Моя волна по жанру", "genre:pop", "#DB2777"), + ], + }, + VibePickTab { + title: "по настроению".into(), + items: vec![ + mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#F97316"), + mk("Спокойное", "Моя волна по настроению", "mood:calm", "#2563EB"), + mk("Весёлое", "Моя волна по настроению", "mood:fun", "#EAB308"), + ], + }, + VibePickTab { + title: "по занятию".into(), + items: vec![ + mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), + mk("Тренировка", "Моя волна по занятию", "activity:workout", "#E11D48"), + mk("В дорогу", "Моя волна по занятию", "activity:road-trip", "#4F46E5"), + ], + }, + VibePickTab { + title: "по характеру".into(), + items: vec![ + mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#8B5CF6"), + mk("Любимое", "Моя волна по характеру", "diversity:favorite", "#EC4899"), + mk("Популярное", "Моя волна по характеру", "diversity:popular", "#059669"), + ], + }, + ] + } else { + vec![ + VibePickTab { + title: "top".into(), + items: vec![ + mk("English", "My Vibe by language", "language:english", "#3F68F9"), + mk("Electronic", "My Vibe by genre", "genre:electronics", "#8341EF"), + mk("Energetic", "My Vibe by mood", "mood:energetic", "#FF5C4D"), + mk("Focus & Work", "My Vibe by activity", "activity:work", "#0D9488"), + mk("Discover", "My Vibe by character", "diversity:discover", "#D97706"), + ], + }, + VibePickTab { + title: "by language".into(), + items: vec![ + mk("English", "My Vibe by language", "language:english", "#3F68F9"), + mk("Russian", "My Vibe by language", "language:russian", "#E11D48"), + mk("Instrumental", "My Vibe by language", "language:without-words", "#0F766E"), + ], + }, + VibePickTab { + title: "by genre".into(), + items: vec![ + mk("Electronic", "My Vibe by genre", "genre:electronics", "#7C3AED"), + mk("Hip-Hop", "My Vibe by genre", "genre:hiphop", "#EA580C"), + mk("Rock", "My Vibe by genre", "genre:rock", "#DC2626"), + mk("Pop", "My Vibe by genre", "genre:pop", "#DB2777"), + ], + }, + VibePickTab { + title: "by mood".into(), + items: vec![ + mk("Energetic", "My Vibe by mood", "mood:energetic", "#F97316"), + mk("Calm", "My Vibe by mood", "mood:calm", "#2563EB"), + mk("Upbeat", "My Vibe by mood", "mood:fun", "#EAB308"), + ], + }, + VibePickTab { + title: "by activity".into(), + items: vec![ + mk("Work", "My Vibe by activity", "activity:work", "#0D9488"), + mk("Workout", "My Vibe by activity", "activity:workout", "#E11D48"), + mk("Road trip", "My Vibe by activity", "activity:road-trip", "#4F46E5"), + ], + }, + VibePickTab { + title: "by character".into(), + items: vec![ + mk("Discover", "My Vibe by character", "diversity:discover", "#8B5CF6"), + mk("Favorites", "My Vibe by character", "diversity:favorite", "#EC4899"), + mk("Popular", "My Vibe by character", "diversity:popular", "#059669"), + ], + }, + ] + } +} + +#[allow(clippy::too_many_arguments)] +fn render_more_picks_section( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + viewport: Rect, + x: f32, + mut y: f32, + avail_w: f32, + actions: &mut Vec, +) -> f32 { + let ru = app.i18n().is_ru(); + let tabs: Vec = if !app.landing.vibe_pick_tabs.is_empty() { + app.landing.vibe_pick_tabs.clone() + } else { + fallback_vibe_pick_tabs(ru) + }; + if tabs.is_empty() { + return y; + } + + ctx.draw_text_ellipsis( + if ru { "Ещё подборки" } else { "More Picks" }, TextStyle::headline(24.0, pal.text_primary), Rect::from_xywh(x, y, avail_w, 30.0), TextAlign::Left, ); y += 40.0; - let card_w = 164.0; - let card_h = card_w + 54.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let h_id = WidgetId::new(salt); - let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let active_idx = FOR_YOU_PICKS_TAB.with(|c| c.get()).min(tabs.len() - 1); - let releases = app.landing.new_releases.clone(); - let mut cx = x - scroll_x; - for alb in &releases { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { - let art = alb - .artists - .first() - .map(|a| a.name.as_str()) - .unwrap_or(t.album()); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair(salt, &alb.id), - cr, - &alb.title, - art, - alb.cover_uri.as_deref(), - &format!("alb_{}", alb.id), - false, - false, - ); - if m.play_clicked { - actions.push(AppAction::PlayAlbum { - id: alb.id.clone(), - title: alb.title.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Album { - id: alb.id.clone(), - title: alb.title.clone(), - })); - } + // Horizontal category filter tabs (`32px` active pill, clean secondary text inactive) + let tabs_vp = Rect::from_xywh(x, y, avail_w, 34.0); + let tabs_h_id = WidgetId::new("fy_picks_tabs_hscroll"); + let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); + let mut tx = x - tabs_sx; + for (idx, tab) in tabs.iter().enumerate() { + let is_act = idx == active_idx; + let style = TextStyle::medium( + 14.0, + if is_act { pal.text_bright } else { pal.text_secondary }, + ); + let tw = ctx.measure_text(&tab.title, style, None).x + 24.0; + let tr = Rect::from_xywh(tx, y, tw.max(52.0), 32.0); + let resp = ctx.interact(WidgetId::from_pair("fy_pick_tab", idx), tr); + if is_act { + ctx.dl().push_rect(tr, 16.0, pal.surface_hover); + } else if resp.hovered { + ctx.dl().push_rect(tr, 16.0, pal.surface_secondary); } - cx += card_w + 16.0; + ctx.draw_text_ellipsis( + &tab.title, + TextStyle::medium( + 14.0, + if is_act || resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ), + tr, + TextAlign::Center, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + FOR_YOU_PICKS_TAB.with(|c| c.set(idx)); + } + tx = tr.right() + 8.0; } - let total_w = (releases.len() as f32) * (card_w + 16.0); - ctx.end_scroll_h(h_id, pal, total_w, false); + ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); + y += 46.0; + + // Vibrant gradient-tinted glossy Vibe-Station cards (`260x70`, `radius: 16px`) + const CURATED_PALETTE: &[Color] = &[ + Color::rgb(0x3F, 0x68, 0xF9), + Color::rgb(0x83, 0x41, 0xEF), + Color::rgb(0xE1, 0x3A, 0x52), + Color::rgb(0x0D, 0x94, 0x88), + Color::rgb(0xD9, 0x77, 0x06), + Color::rgb(0xDB, 0x27, 0x77), + ]; + + let card_w = 260.0_f32; + let card_h = 70.0_f32; + let gap = 14.0_f32; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let items = &tabs[active_idx].items; + if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { + let h_id = WidgetId::from_pair("fy_picks_cards", active_idx); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + for (idx, item) in items.iter().enumerate() { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 60.0 && cr.left() <= row_vp.right() + 60.0 { + let resp = ctx.interact(WidgetId::from_pair("fy_pick_card", (active_idx, idx)), cr); + let base_c = item + .color_hex + .as_deref() + .and_then(Color::from_hex_str) + .unwrap_or(CURATED_PALETTE[idx % CURATED_PALETTE.len()]); + let c_left = base_c.lerp(Color::BLACK, if resp.hovered { 0.14 } else { 0.24 }); + let c_right = base_c.lerp(Color::BLACK, if resp.hovered { 0.36 } else { 0.48 }); + ctx.dl() + .push_gradient_rect(cr, 16.0, c_left, c_right, Vec2::new(1.0, 0.4)); + // Subtle glossy top sheen + ctx.dl().push_gradient_rect( + Rect::from_xywh(cr.left(), cr.top(), cr.width(), cr.height() * 0.48), + CornerRadii::top(16.0), + css_rgba(255, 255, 255, if resp.hovered { 42 } else { 28 }), + css_rgba(255, 255, 255, 0), + Vec2::new(0.0, 1.0), + ); + ctx.dl().push_rect_bordered( + cr, + 16.0, + Color::TRANSPARENT, + 1.0, + css_rgba(255, 255, 255, 28), + ); + + // Eyebrow ("Моя волна по языку" / "My Vibe by language") + if !item.header.is_empty() { + ctx.draw_text_ellipsis( + &item.header, + TextStyle::medium(12.0, css_rgba(255, 255, 255, 196)), + Rect::from_xywh(cr.left() + 14.0, cr.top() + 13.0, cr.width() - 28.0, 16.0), + TextAlign::Center, + ); + } + + // Centered bold white `▶` + station title (`17px` Headline) + let title_style = TextStyle::headline(17.0, Color::WHITE); + let tw = ctx + .measure_text(&item.title, title_style, None) + .x + .min(cr.width() - 52.0); + let inner_w = 16.0 + 6.0 + tw; + let tx_start = cr.center_x() - inner_w * 0.5; + let row_y = if item.header.is_empty() { + cr.center_y() + } else { + cr.top() + 45.0 + }; + ctx.draw_icon( + Icon::PlayFilledXs, + Rect::from_center_size(Pos2::new(tx_start + 8.0, row_y), Vec2::splat(14.0)), + Color::WHITE, + ); + ctx.draw_text_ellipsis( + &item.title, + title_style, + Rect::from_xywh(tx_start + 22.0, row_y - 11.0, tw + 4.0, 22.0), + TextAlign::Left, + ); + + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked && !item.seeds.is_empty() { + actions.push(AppAction::StartVibeBySeeds { + title: item.title.clone(), + seeds: item.seeds.clone(), + }); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h(h_id, pal, items.len() as f32 * (card_w + gap), false); + } + y + card_h + 26.0 } diff --git a/src/views/my_vibe.rs b/src/views/my_vibe.rs index d8002bb..7a0c202 100644 --- a/src/views/my_vibe.rs +++ b/src/views/my_vibe.rs @@ -14,8 +14,8 @@ use crate::engine::types::{ css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, Vec2, VIBE_TEXTURE_ID, }; use crate::engine::widgets::{ - draw_cover_art, secondary_pill_button, ym_menu_divider, ym_menu_frame, ym_menu_item, - ym_menu_item_ex, ym_volume_capsule, + draw_cover_art, ym_menu_divider, ym_menu_frame, ym_menu_item, ym_menu_item_ex, + ym_volume_capsule, }; use crate::engine::UiContext; use crate::icons::Icon; @@ -1504,7 +1504,7 @@ pub fn render_my_vibe( // 13. OFFICIAL 5.129.0 `WordsCardFullscreen` (`ZLayer::Modal` when `app.words_big_card_open`) if app.words_big_card_open { - render_words_card_fullscreen(ctx, pal, app, ru, active_words_card.as_ref(), actions); + render_words_card_fullscreen(ctx, pal, covers, app, ru, active_words_card.as_ref(), actions); } } @@ -1664,6 +1664,7 @@ fn render_words_card_popover( fn render_words_card_fullscreen( ctx: &mut UiContext, pal: &YmPalette, + covers: &mut CoverCache, app: &AppState, ru: bool, fallback_card: Option<&WordsCard>, @@ -1714,31 +1715,21 @@ fn render_words_card_fullscreen( should_close = true; } - let col_w = (screen.width() - 96.0).clamp(300.0, 540.0); - let modal_h = (screen.height() - 140.0).clamp(320.0, 580.0); - let content_rect = Rect::from_center_size(screen.center(), Vec2::new(col_w + 48.0, modal_h)); - let col_x = content_rect.center_x() - col_w * 0.5; - let mut y = content_rect.top() + 18.0; - - // Top AI sparkle badge with soft meteor glow - let sp_c = Pos2::new(content_rect.center_x(), y + 20.0); - let meteor_tex = ctx.icons.get_official_meteor_glow(&mut ctx.textures); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - ctx.dl().push_image( - Rect::from_xywh(badge_tl.x - 180.0 * 0.25, badge_tl.y - 180.0 * 0.43, 180.0, 180.0), - meteor_tex, - 0.0, - Color::WHITE.with_alpha(150), + let col_w = (screen.width() - 96.0).clamp(300.0, 560.0); + let col_x = screen.center_x() - col_w * 0.5; + let disclaimer = if ru { + "AI может ошибаться, проверяйте важное" + } else { + "AI may make mistakes, be sure to double-check important information" + }; + let disclaimer_y = screen.bottom() - 38.0; + let content_rect = Rect::from_min_max( + Pos2::new(col_x - 24.0, screen.top() + 92.0), + Pos2::new(col_x + col_w + 24.0, disclaimer_y - 12.0), ); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(28.0)), - pal.text_bright, - ); - y += 64.0; if app.words_big_card_loading { - // 3 subtle animated shimmer bars while `POST /words/big-cards` loads + // 3 subtle animated shimmer bars centered vertically while `POST /words/big-cards` loads let shimmer = 0.5 + 0.5 * ((ctx.input.time as f32) * 3.2).sin(); let a = (28.0 + 36.0 * shimmer).round() as u8; let bar_col = if pal.is_dark { @@ -1746,11 +1737,12 @@ fn render_words_card_fullscreen( } else { css_rgba(0, 0, 0, a) }; + let sy = content_rect.center_y() - 40.0; for (i, frac) in [0.88_f32, 1.0_f32, 0.64_f32].iter().enumerate() { let bw = col_w * frac; let br = Rect::from_xywh( - content_rect.center_x() - bw * 0.5, - y + i as f32 * 30.0, + screen.center_x() - bw * 0.5, + sy + i as f32 * 30.0, bw, 18.0, ); @@ -1773,107 +1765,170 @@ fn render_words_card_fullscreen( .or_else(|| fallback_card.map(|c| c.actions.as_slice())) .unwrap_or(&[]); - let bottom_reserved = if sources.is_empty() { 104.0 } else { 154.0 }; - let text_vp_h = (content_rect.bottom() - y - bottom_reserved).max(120.0); - let text_vp = Rect::from_xywh(col_x, y, col_w, text_vp_h); let text_style = TextStyle::bold(20.0, pal.text_bright).with_line_height(28.0); let measured = ctx.measure_text(full_text, text_style, Some(col_w)); - - let scroll_id = WidgetId::new("wcf_text_scroll"); - let scroll_y = ctx.begin_scroll_v(scroll_id, text_vp, 0.0); - let ty = if measured.y < text_vp_h { - text_vp.center_y() - measured.y * 0.5 + let src_count = sources.len().min(2); + let src_block_h = if src_count > 0 { + 28.0 + src_count as f32 * 46.0 - 8.0 } else { - text_vp.top() - scroll_y + 0.0 }; - ctx.draw_text_wrapped( - full_text, - text_style, - Rect::from_xywh(col_x, ty, col_w, measured.y + 12.0), - None, - TextAlign::Center, - ); - ctx.end_scroll_v(scroll_id, pal, measured.y + 16.0, false); - y = text_vp.bottom() + 16.0; + let fb_block_h = if fallback_card.is_some() { 22.0 + 32.0 } else { 0.0 }; + let max_text_h = (content_rect.height() - src_block_h - fb_block_h - 16.0).max(110.0); + let used_text_h = measured.y.min(max_text_h); + let total_stack_h = used_text_h + src_block_h + fb_block_h; + let mut y = (content_rect.center_y() - total_stack_h * 0.5).max(content_rect.top()); - // Optional source link pills - if !sources.is_empty() { - let mut sx = col_x; - let max_right = col_x + col_w; - for (idx, src) in sources.iter().take(4).enumerate() { - let est_w = (ctx - .measure_text(&src.title, TextStyle::medium(13.5, pal.text_primary), None) - .x - + 50.0) - .clamp(80.0, col_w); - if sx + est_w > max_right && sx > col_x { - break; - } - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("wcf_src", idx), - Pos2::new(sx, y), - Some(Icon::LinkXxs), - &src.title, - 34.0, - false, + // 1. Centered 20px bold story text (scrollable if longer than viewport, ZERO floating sparkle!) + let text_vp = Rect::from_xywh(col_x, y, col_w, used_text_h + 6.0); + if measured.y > max_text_h { + let scroll_id = WidgetId::new("wcf_text_scroll"); + let scroll_y = ctx.begin_scroll_v(scroll_id, text_vp, 0.0); + ctx.draw_text_wrapped( + full_text, + text_style, + Rect::from_xywh(col_x, text_vp.top() - scroll_y, col_w, measured.y + 12.0), + None, + TextAlign::Center, + ); + ctx.end_scroll_v(scroll_id, pal, measured.y + 16.0, false); + } else { + ctx.draw_text_wrapped( + full_text, + text_style, + Rect::from_xywh(col_x, y, col_w, measured.y + 12.0), + None, + TextAlign::Center, + ); + } + y += used_text_h; + + // 2. Centered full-width-fitted source/Alice glass pill(s) (28px below text, NEVER truncates!) + if src_count > 0 { + y += 28.0; + let max_pill_w = (screen.width() - 64.0).min(520.0); + for (idx, src) in sources.iter().take(src_count).enumerate() { + let lbl_style = TextStyle::medium(14.0, pal.text_bright); + let tw = ctx.measure_text(&src.title, lbl_style, None).x; + let pill_w = (tw + 54.0).clamp(160.0, max_pill_w); + let pill_r = Rect::from_xywh( + screen.center_x() - pill_w * 0.5, + y, + pill_w, + 38.0, ); + let resp = ctx.interact(WidgetId::from_pair("wcf_src_pill", idx), pill_r); + let bg = if pal.is_dark { + css_rgba(255, 255, 255, if resp.hovered { 32 } else { 18 }) + } else if resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }; + let border = if pal.is_dark { + css_rgba(255, 255, 255, 28) + } else { + pal.border_subtle + }; + ctx.dl().push_rect_bordered(pill_r, 19.0, bg, 1.0, border); + + // Left 18x18 icon: favicon_url -> Alice purple ring -> LinkRounded + let ic_center = Pos2::new(pill_r.left() + 22.0, pill_r.center_y()); + let ic_rect = Rect::from_center_size(ic_center, Vec2::splat(18.0)); + let mut drew_fav = false; + if let Some(ref fav) = src.favicon_url { + if let Some((tex_id, _, _)) = covers.get_or_fetch(fav, 64) { + ctx.dl().push_image(ic_rect, tex_id, 9.0, Color::WHITE); + drew_fav = true; + } + } + if !drew_fav { + let tl = src.title.to_lowercase(); + if tl.contains("алис") || tl.contains("alice") { + ctx.dl() + .push_circle(ic_center, 9.0, Color::rgb(0x18, 0x13, 0x26)); + ctx.dl().push_circle_stroke( + ic_center, + 8.0, + 2.2, + Color::rgb(0x8B, 0x5C, 0xF6), + ); + ctx.dl() + .push_circle(ic_center, 2.6, Color::rgb(0xC4, 0xB5, 0xFD)); + } else { + ctx.draw_icon( + Icon::LinkRounded, + Rect::from_center_size(ic_center, Vec2::splat(16.0)), + pal.text_bright, + ); + } + } + + ctx.draw_text_ellipsis( + &src.title, + lbl_style, + Rect::from_xywh( + pill_r.left() + 38.0, + pill_r.top(), + (pill_r.width() - 52.0).max(40.0), + pill_r.height(), + ), + TextAlign::Left, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } if resp.clicked && !src.url.is_empty() { actions.push(AppAction::OpenUrl(src.url.clone())); } - sx = r.right() + 8.0; + y += 46.0; } - y += 46.0; + y -= 8.0; } - // Horizontal feedback bar: 👍 More similar replies | 1px divider | 👎 Not cool + // 3. BORDERLESS TEXT-ONLY feedback buttons (22px below source pill, 28px gap, ZERO boxes!) if let Some(card) = fallback_card { + y += 22.0; let like_lbl = if ru { "Больше такого" } else { "More similar replies" }; let dislike_lbl = if ru { "Мимо" } else { "Not cool" }; - let btn_h = 38.0; - let like_w = (ctx - .measure_text(like_lbl, TextStyle::medium(14.0, pal.text_primary), None) - .x - + 54.0) - .max(120.0); - let dislike_w = (ctx - .measure_text(dislike_lbl, TextStyle::medium(14.0, pal.text_primary), None) - .x - + 54.0) - .max(100.0); - let bar_w = like_w + 25.0 + dislike_w; - let bar_x = content_rect.center_x() - bar_w * 0.5; + let muted = if pal.is_dark { + css_rgba(255, 255, 255, 148) + } else { + pal.text_secondary + }; + let lbl_style = TextStyle::medium(14.0, muted); + let like_tw = ctx.measure_text(like_lbl, lbl_style, None).x; + let dislike_tw = ctx.measure_text(dislike_lbl, lbl_style, None).x; + let like_w = 16.0 + 7.0 + like_tw + 8.0; + let dislike_w = 16.0 + 7.0 + dislike_tw + 8.0; + let gap = 28.0_f32; + let total_w = like_w + gap + dislike_w; + let start_x = screen.center_x() - total_w * 0.5; + let btn_h = 32.0; - let like_r = Rect::from_xywh(bar_x, y, like_w, btn_h); + let like_r = Rect::from_xywh(start_x, y, like_w, btn_h); let like_resp = ctx.interact(WidgetId::new("wcf_like"), like_r); - ctx.dl().push_rect( - like_r, - 19.0, - if like_resp.hovered || card.is_liked() { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); let like_fg = if card.is_liked() || like_resp.hovered { pal.text_bright } else { - pal.text_primary + muted }; ctx.draw_icon( Icon::ThumbUpXxs, - Rect::from_center_size(Pos2::new(like_r.left() + 22.0, like_r.center_y()), Vec2::splat(18.0)), + Rect::from_center_size( + Pos2::new(like_r.left() + 10.0, like_r.center_y()), + Vec2::splat(16.0), + ), like_fg, ); ctx.draw_text_ellipsis( like_lbl, TextStyle::medium(14.0, like_fg), - Rect::from_xywh(like_r.left() + 38.0, like_r.top(), like_r.width() - 48.0, like_r.height()), + Rect::from_xywh(like_r.left() + 24.0, like_r.top(), like_tw + 8.0, btn_h), TextAlign::Left, ); if like_resp.hovered { @@ -1891,39 +1946,30 @@ fn render_words_card_fullscreen( }); } - // 1px vertical divider - let div_x = like_r.right() + 12.0; - ctx.dl().push_rect( - Rect::from_xywh(div_x, y + 7.0, 1.0, 24.0), - 0.0, - pal.border_subtle, - ); - - let dislike_r = Rect::from_xywh(div_x + 13.0, y, dislike_w, btn_h); + let dislike_r = Rect::from_xywh(like_r.right() + gap, y, dislike_w, btn_h); let dislike_resp = ctx.interact(WidgetId::new("wcf_dislike"), dislike_r); - ctx.dl().push_rect( - dislike_r, - 19.0, - if dislike_resp.hovered || card.is_disliked() { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); let dislike_fg = if card.is_disliked() || dislike_resp.hovered { pal.text_bright } else { - pal.text_primary + muted }; ctx.draw_icon( Icon::ThumbDownXxs, - Rect::from_center_size(Pos2::new(dislike_r.left() + 22.0, dislike_r.center_y()), Vec2::splat(18.0)), + Rect::from_center_size( + Pos2::new(dislike_r.left() + 10.0, dislike_r.center_y()), + Vec2::splat(16.0), + ), dislike_fg, ); ctx.draw_text_ellipsis( dislike_lbl, TextStyle::medium(14.0, dislike_fg), - Rect::from_xywh(dislike_r.left() + 38.0, dislike_r.top(), dislike_r.width() - 48.0, dislike_r.height()), + Rect::from_xywh( + dislike_r.left() + 24.0, + dislike_r.top(), + dislike_tw + 8.0, + btn_h, + ), TextAlign::Left, ); if dislike_resp.hovered { @@ -1936,24 +1982,25 @@ fn render_words_card_fullscreen( state: "dislike".into(), }); } - y += btn_h + 18.0; } - - // Bottom AI disclaimer - let disclaimer = if ru { - "AI может ошибаться, проверяйте важное" - } else { - "AI may make mistakes, be sure to double-check important information" - }; - ctx.draw_text_wrapped( - disclaimer, - TextStyle::regular(12.5, pal.text_secondary).with_line_height(17.0), - Rect::from_xywh(col_x, y, col_w, 36.0), - Some(2), - TextAlign::Center, - ); } + // 4. Disclaimer pinned cleanly near the bottom (`screen.bottom() - 32.0`) + let disc_col = if pal.is_dark { + css_rgba(255, 255, 255, 96) + } else { + pal.text_secondary + }; + ctx.draw_text_ellipsis( + disclaimer, + TextStyle::regular(12.0, disc_col), + Rect::from_center_size( + Pos2::new(screen.center_x(), screen.bottom() - 32.0), + Vec2::new((screen.width() - 64.0).max(200.0), 22.0), + ), + TextAlign::Center, + ); + if ctx.input.key_pressed(Key::Escape) || ctx.input.clicked_outside_any(&[content_rect, close_r]) { diff --git a/src/views/podcasts_kids.rs b/src/views/podcasts_kids.rs index b349079..43603a4 100644 --- a/src/views/podcasts_kids.rs +++ b/src/views/podcasts_kids.rs @@ -1,4 +1,6 @@ -use crate::api::models::AlbumSummary; +use std::cell::RefCell; + +use crate::api::models::{AlbumSummary, ConcertItem, PlaylistSummary}; use crate::app::state::{AppAction, AppState, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -14,6 +16,10 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; +thread_local! { + static CONCERT_CITY_FILTER: RefCell> = const { RefCell::new(None) }; +} + fn is_audiobook_item(item: &AlbumSummary) -> bool { item.content_type .as_deref() @@ -23,10 +29,277 @@ fn is_audiobook_item(item: &AlbumSummary) -> bool { }) } -/// Books & Podcasts landing page (100% theme-aware & RU/EN localized): -/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги`) -/// - "Продолжить слушать" / "Continue listening" horizontal shelf -/// - Podcasts & Audiobooks grids with right-click context menus +fn is_audiobook_section(id: &str, block_type: &str, title: &str) -> bool { + let low_id = id.to_lowercase(); + let low_bt = block_type.to_lowercase(); + let low_ti = title.to_lowercase(); + low_id.contains("book") + || low_bt.contains("book") + || low_ti.contains("книг") + || low_ti.contains("book") + || low_ti.contains("роман") + || low_ti.contains("фантаст") +} + +fn draw_carousel_arrows( + ctx: &mut UiContext, + pal: &YmPalette, + h_id: WidgetId, + right_x: f32, + center_y: f32, + step: f32, +) { + let next_r = Rect::from_center_size(Pos2::new(right_x - 16.0, center_y), Vec2::splat(30.0)); + let prev_r = Rect::from_center_size(Pos2::new(right_x - 52.0, center_y), Vec2::splat(30.0)); + + let (off_x, max_x) = { + let st = ctx.scrolls.get_or_create(h_id); + (st.offset.x, st.max_offset().x) + }; + let can_prev = off_x > 2.0; + let can_next = max_x > 2.0 && off_x < max_x - 2.0; + + let prev_resp = ctx.interact(h_id.with("prev"), prev_r); + let next_resp = ctx.interact(h_id.with("next"), next_r); + + let prev_bg = if prev_resp.hovered && can_prev { + pal.surface_hover + } else { + pal.surface_secondary + }; + let next_bg = if next_resp.hovered && can_next { + pal.surface_hover + } else { + pal.surface_secondary + }; + + ctx.dl() + .push_rect_bordered(prev_r, 15.0, prev_bg, 1.0, pal.border_subtle); + ctx.draw_icon( + Icon::ArrowLeft, + Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), + if can_prev { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + + ctx.dl() + .push_rect_bordered(next_r, 15.0, next_bg, 1.0, pal.border_subtle); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), + if can_next { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + + if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { + ctx.set_cursor(CursorKind::Pointer); + } + if prev_resp.clicked && can_prev { + ctx.scrolls.get_or_create(h_id).scroll_by_x(-step); + ctx.request_repaint(); + } + if next_resp.clicked && can_next { + ctx.scrolls.get_or_create(h_id).scroll_by_x(step); + ctx.request_repaint(); + } +} + +fn shimmer_color(pal: &YmPalette, phase: f32) -> Color { + let pulse = 0.5 + 0.5 * phase.sin(); + let base = pal.surface_secondary; + let hi = pal.surface_hover; + let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * pulse).round() as u8; + Color::from_rgba( + lerp(base.r, hi.r), + lerp(base.g, hi.g), + lerp(base.b, hi.b), + 255, + ) +} + +fn format_price_spaced(price: u64) -> String { + let s = price.to_string(); + let mut out = String::with_capacity(s.len() + s.len() / 3); + for (i, ch) in s.chars().rev().enumerate() { + if i > 0 && i % 3 == 0 { + out.push(' '); + } + out.push(ch); + } + out.chars().rev().collect() +} + +fn currency_symbol(cur: Option<&str>) -> &'static str { + match cur.map(|s| s.to_ascii_uppercase()).as_deref() { + Some("USD") => "$", + Some("EUR") => "€", + Some("KZT") => "₸", + Some("BYN") => "Br", + Some("UZS") => "сум", + _ => "₽", + } +} + +fn format_ticket_label(c: &ConcertItem, ru: bool) -> String { + if let Some(price) = c.min_price.filter(|&p| p > 0) { + let sym = currency_symbol(c.currency.as_deref()); + let formatted = format_price_spaced(price); + if ru { + format!("от {} {}", formatted, sym) + } else { + format!("from {} {}", formatted, sym) + } + } else if ru { + "Билеты".into() + } else { + "Tickets".into() + } +} + +fn format_cashback_label(c: &ConcertItem, ru: bool) -> Option { + if let Some(ref title) = c.cashback_title { + if !title.trim().is_empty() { + return Some(title.trim().to_string()); + } + } + c.cashback_percent.filter(|&p| p > 0).map(|pct| { + if ru { + format!("Кешбэк {}%", pct) + } else { + format!("{}% Cashback", pct) + } + }) +} + +fn month_short(month: u32, ru: bool) -> &'static str { + if ru { + match month { + 1 => "ЯНВ", + 2 => "ФЕВ", + 3 => "МАР", + 4 => "АПР", + 5 => "МАЯ", + 6 => "ИЮН", + 7 => "ИЮЛ", + 8 => "АВГ", + 9 => "СЕН", + 10 => "ОКТ", + 11 => "НОЯ", + 12 => "ДЕК", + _ => "LIVE", + } + } else { + match month { + 1 => "JAN", + 2 => "FEB", + 3 => "MAR", + 4 => "APR", + 5 => "MAY", + 6 => "JUN", + 7 => "JUL", + 8 => "AUG", + 9 => "SEP", + 10 => "OCT", + 11 => "NOV", + 12 => "DEC", + _ => "LIVE", + } + } +} + +fn parse_concert_date_parts(raw: &str, ru: bool) -> (String, String, Option) { + let trimmed = raw.trim(); + // ISO-8601 e.g. "2026-05-15T19:00:00+03:00" or "2026-05-15" + if trimmed.len() >= 10 + && trimmed.as_bytes()[4] == b'-' + && trimmed.as_bytes()[7] == b'-' + { + if let (Ok(m), Ok(d)) = (trimmed[5..7].parse::(), trimmed[8..10].parse::()) { + let time = if trimmed.len() >= 16 + && (trimmed.as_bytes()[10] == b'T' || trimmed.as_bytes()[10] == b' ') + { + let hhmm = &trimmed[11..16]; + if hhmm != "00:00" { + Some(hhmm.to_string()) + } else { + None + } + } else { + None + }; + return (d.to_string(), month_short(m, ru).to_string(), time); + } + } + // DD.MM.YYYY + let dot_parts: Vec<&str> = trimmed.split(['.', ' ', ',']).filter(|s| !s.is_empty()).collect(); + if dot_parts.len() >= 2 { + if let (Ok(d), Ok(m)) = (dot_parts[0].parse::(), dot_parts[1].parse::()) { + if (1..=31).contains(&d) && (1..=12).contains(&m) { + let time = dot_parts + .iter() + .find(|p| p.contains(':') && p.len() >= 4) + .map(|s| s.chars().take(5).collect()); + return (d.to_string(), month_short(m, ru).to_string(), time); + } + } + } + // Human readable e.g. "15 мая, 19:00" or "15 May 20:00" + let tokens: Vec<&str> = trimmed + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|s| !s.is_empty()) + .collect(); + if tokens.len() >= 2 && tokens[0].chars().all(|c| c.is_ascii_digit()) { + let day = tokens[0].to_string(); + let mon: String = tokens[1].chars().take(3).collect::().to_uppercase(); + let time = tokens + .iter() + .skip(2) + .find(|p| p.contains(':')) + .map(|s| s.chars().take(5).collect()); + return (day, mon, time); + } + let fallback = trimmed.chars().take(6).collect::(); + if fallback.is_empty() { + ("•".into(), "LIVE".into(), None) + } else { + (fallback, if ru { "АФИША" } else { "SHOW" }.into(), None) + } +} + +fn draw_cashback_pill(ctx: &mut UiContext, pos_right_or_left: Pos2, align_right: bool, label: &str) -> Rect { + let style = TextStyle::bold(11.5, Color::WHITE); + let tw = ctx.measure_text(label, style, None).x; + let w = (tw + 18.0).ceil(); + let h = 22.0; + let x = if align_right { + pos_right_or_left.x - w + } else { + pos_right_or_left.x + }; + let pill = Rect::from_xywh(x, pos_right_or_left.y, w, h); + ctx.dl().push_gradient_rect( + pill, + 11.0, + Color::rgb(0xFF, 0x3B, 0x7F), + Color::rgb(0x7B, 0x42, 0xFF), + Vec2::new(1.0, 0.0), + ); + ctx.draw_text_ellipsis(label, style, pill, TextAlign::Center); + pill +} + +/// 1-to-1 Official Books & Podcasts (`non_music`) landing page (100% theme-aware & RU/EN localized): +/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги` / `Моя полка`) +/// - Animated loading shimmer + Refresh action when empty +/// - "Продолжить слушать" horizontal shelf +/// - Every official skeleton section from `app.non_music_sections` with `<` `>` carousel arrows +/// - Filtered Podcasts, Audiobooks & My Shelf grids with right-click context menus pub fn render_podcasts( ctx: &mut UiContext, pal: &YmPalette, @@ -45,13 +318,34 @@ pub fn render_podcasts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; + // Header + Refresh pill + let title_w = (avail_w - 132.0).max(180.0); ctx.draw_text_ellipsis( t.books_and_podcasts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), + Rect::from_xywh(x, y, title_w, 42.0), TextAlign::Left, ); + let refresh_label = if ru { "Обновить" } else { "Refresh" }; + let refresh_tw = ctx + .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) + .x; + let refresh_w = (refresh_tw + 28.0).ceil(); + let (ref_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("pod_refresh_top"), + Pos2::new(x + avail_w - refresh_w, y + 4.0), + None, + refresh_label, + 34.0, + false, + ); + if ref_resp.clicked { + actions.push(AppAction::RefreshNonMusic); + } y += 46.0; + ctx.draw_text_ellipsis( if ru { "Шоу, интервью, аудиокниги и новые выпуски каждый день" @@ -64,13 +358,17 @@ pub fn render_podcasts( ); y += 32.0; - // Category filter tabs (All / Podcasts / Audiobooks) + // Category filter tabs (All / Podcasts / Audiobooks / My shelf) let active_tab = shell.podcast_filter_tab; - let mut tx = x; + let tabs_vp = Rect::from_xywh(x, y, avail_w, 40.0); + let tabs_h_id = WidgetId::new("pod_tabs_hscroll"); + let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); + let mut tx = x - tabs_sx; for (idx, label) in [ (0u8, t.search_all()), (1u8, if ru { "Подкасты" } else { "Podcasts" }), (2u8, t.audiobooks()), + (3u8, if ru { "Моя полка" } else { "My shelf" }), ] { let (resp, r) = secondary_pill_button( ctx, @@ -87,67 +385,139 @@ pub fn render_podcasts( } tx = r.right() + 8.0; } - y += 52.0; + ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); + y += 54.0; - // Merge bookshelf_items + landing.podcasts cleanly + // Collect deduplicated catalog from bookshelf + landing.podcasts + non_music_sections let mut all_items: Vec = Vec::new(); + let mut audiobook_ids: std::collections::HashSet = std::collections::HashSet::new(); for item in app.bookshelf_items.iter().chain(app.landing.podcasts.iter()) { + if is_audiobook_item(item) { + audiobook_ids.insert(item.id.clone()); + } if !all_items.iter().any(|existing| existing.id == item.id) { all_items.push(item.clone()); } } + for sec in &app.non_music_sections { + let sec_is_book = is_audiobook_section(&sec.id, &sec.block_type, &sec.title); + for alb in &sec.albums { + if sec_is_book || is_audiobook_item(alb) { + audiobook_ids.insert(alb.id.clone()); + } + if !all_items.iter().any(|existing| existing.id == alb.id) { + all_items.push(alb.clone()); + } + } + } - if all_items.is_empty() { - ctx.draw_text_ellipsis( + let has_any_content = !all_items.is_empty() + || app + .non_music_sections + .iter() + .any(|s| !s.albums.is_empty() || !s.playlists.is_empty()); + + if !has_any_content && app.non_music_loading { + ctx.request_repaint(); + let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; + let card_w = 168.0; + let card_h = card_w + 54.0; + for row_idx in 0..2 { + let head_col = shimmer_color(pal, t_sec + row_idx as f32 * 0.7); + ctx.dl() + .push_rect(Rect::from_xywh(x, y, 210.0, 22.0), 6.0, head_col); + y += 34.0; + let count = ((avail_w + 16.0) / (card_w + 16.0)).floor().clamp(2.0, 6.0) as usize; + for i in 0..count { + let cx = x + i as f32 * (card_w + 16.0); + let col = shimmer_color(pal, t_sec + i as f32 * 0.45 + row_idx as f32 * 0.8); + ctx.dl() + .push_rect(Rect::from_xywh(cx, y, card_w, card_w), 12.0, col); + ctx.dl().push_rect( + Rect::from_xywh(cx, y + card_w + 10.0, card_w * 0.78, 14.0), + 5.0, + col, + ); + ctx.dl().push_rect( + Rect::from_xywh(cx, y + card_w + 30.0, card_w * 0.52, 12.0), + 5.0, + col, + ); + } + y += card_h + 26.0; + } + } else if !has_any_content { + ctx.draw_text_wrapped( if ru { - "Загрузка подкастов и книг…" + "Подкасты и аудиокниги пока не загрузились. Нажмите «Обновить», чтобы повторить запрос." } else { - "Loading podcasts & audiobooks…" + "Podcasts and audiobooks haven't loaded yet. Click Refresh to try again." }, TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), + Rect::from_xywh(x, y, avail_w, 44.0), + Some(2), TextAlign::Left, ); - y += 32.0; + y += 52.0; + let (btn, _) = yellow_pill_button( + ctx, + pal, + WidgetId::new("pod_empty_refresh"), + Pos2::new(x, y), + None, + refresh_label, + 38.0, + false, + ); + if btn.clicked { + actions.push(AppAction::RefreshNonMusic); + } + y += 56.0; } else { - // 1. "Continue listening" horizontal shelf (bookshelf + recently played podcasts/books) - let mut continue_items: Vec = Vec::new(); - for tr in &app.play_history { - if let Some(ref aid) = tr.album_id { - if let Some(found) = all_items.iter().find(|it| &it.id == aid) { - if !continue_items.iter().any(|c| c.id == found.id) { - continue_items.push(found.clone()); - } - } + // Helper to draw a horizontal shelf of albums + playlists with `<` `>` carousel arrows + let draw_shelf = |ctx: &mut UiContext, + covers: &mut CoverCache, + shell: &mut ShellUiState, + actions: &mut Vec, + title: &str, + salt: &str, + albums: &[AlbumSummary], + playlists: &[PlaylistSummary], + start_y: f32| + -> f32 { + let total_cards = albums.len() + playlists.len(); + if total_cards == 0 { + return start_y; } - } - for item in &app.bookshelf_items { - if !continue_items.iter().any(|c| c.id == item.id) { - continue_items.push(item.clone()); - } - } - if continue_items.is_empty() { - continue_items = all_items.iter().take(4).cloned().collect(); - } + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let h_id = WidgetId::from_pair("pod_shelf_h", salt); - if active_tab == 0 && !continue_items.is_empty() { + let mut cur_y = start_y; ctx.draw_text_ellipsis( - t.continue_listening(), + title, TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), + Rect::from_xywh(x, cur_y, (avail_w - 80.0).max(160.0), 28.0), TextAlign::Left, ); - y += 38.0; + draw_carousel_arrows( + ctx, + pal, + h_id, + x + avail_w, + cur_y + 14.0, + (card_w + gap) * 3.0, + ); + cur_y += 38.0; - let card_w = 164.0; - let card_h = card_w + 54.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let h_id = WidgetId::new("pod_continue_hscroll"); + let row_vp = Rect::from_xywh(x, cur_y, avail_w, card_h); let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - for item in continue_items.iter().take(12) { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { + + for item in albums { + let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { let sub = item .artists .first() @@ -163,12 +533,12 @@ pub fn render_podcasts( ctx, pal, covers, - WidgetId::from_pair("pod_cont", &item.id), + WidgetId::from_pair(salt, format!("a_{}", item.id)), cr, &item.title, sub, item.cover_uri.as_deref(), - &format!("podc_{}", item.id), + &format!("{}_{}", salt, item.id), false, false, ); @@ -197,30 +567,62 @@ pub fn render_podcasts( })); } } - cx += card_w + 16.0; + cx += card_w + gap; } - ctx.end_scroll_h( - h_id, - pal, - continue_items.len().min(12) as f32 * (card_w + 16.0), - false, - ); - y += card_h + 28.0; - } - let mut podcasts_only: Vec = Vec::new(); - let mut audiobooks_only: Vec = Vec::new(); - for item in &all_items { - if is_audiobook_item(item) { - audiobooks_only.push(item.clone()); - } else { - podcasts_only.push(item.clone()); + for pl in playlists { + let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = pl.description.as_deref().unwrap_or(t.playlist()); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair(salt, format!("p_{}_{}", pl.owner_uid, pl.kind)), + cr, + &pl.title, + sub, + pl.cover_uri.as_deref(), + &format!("{}_pl_{}_{}", salt, pl.owner_uid, pl.kind), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "playlist".into(), + id: format!("{}:{}", pl.owner_uid, pl.kind), + title: pl.title.clone(), + subtitle: sub.to_string(), + cover_uri: pl.cover_uri.clone(), + owner_uid: Some(pl.owner_uid.clone()), + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!( + "https://music.yandex.ru/users/{}/playlists/{}", + pl.owner_uid, pl.kind + ), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayPlaylist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Playlist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + })); + } + } + cx += card_w + gap; } - } - // If API metadata did not tag audiobooks separately, surface bookshelf items in Audiobooks too - if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { - audiobooks_only = app.bookshelf_items.clone(); - } + + ctx.end_scroll_h(h_id, pal, total_cards as f32 * (card_w + gap), false); + cur_y + card_h + 28.0 + }; // Helper closure to render a podcast/audiobook grid with right-click context menu let draw_grid = |ctx: &mut UiContext, @@ -233,7 +635,7 @@ pub fn render_podcasts( start_y: f32| -> f32 { let gap = 16.0; - let cols = ((avail_w + gap) / 196.0).floor().clamp(2.0, 6.0) as usize; + let cols = ((avail_w + gap) / 192.0).floor().clamp(2.0, 6.0) as usize; let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(140.0); let card_h = card_w + 54.0; for (idx, pod) in items.iter().enumerate() { @@ -304,59 +706,224 @@ pub fn render_podcasts( start_y + rows as f32 * (card_h + 18.0) + 20.0 }; - // 2. Podcasts Section - if (active_tab == 0 || active_tab == 1) && !podcasts_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { "Подкасты" } else { "Podcasts" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - y = draw_grid( - ctx, - covers, - shell, - actions, - &podcasts_only, - "pod_card", - if ru { "Подкаст" } else { "Podcast" }, - y, - ); + let mut podcasts_only: Vec = Vec::new(); + let mut audiobooks_only: Vec = Vec::new(); + for item in &all_items { + if audiobook_ids.contains(&item.id) || is_audiobook_item(item) { + audiobooks_only.push(item.clone()); + } else { + podcasts_only.push(item.clone()); + } + } + if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { + audiobooks_only = app.bookshelf_items.clone(); } - // 3. Audiobooks Section - if active_tab == 0 || active_tab == 2 { - ctx.draw_text_ellipsis( - t.audiobooks(), - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - if audiobooks_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Добавляйте аудиокниги на книжную полку — они появятся здесь." + match active_tab { + 0 => { + // 1. "Continue listening" horizontal shelf + let mut continue_items: Vec = Vec::new(); + for tr in &app.play_history { + if let Some(ref aid) = tr.album_id { + if let Some(found) = all_items.iter().find(|it| &it.id == aid) { + if !continue_items.iter().any(|c| c.id == found.id) { + continue_items.push(found.clone()); + } + } + } + } + for item in &app.bookshelf_items { + if !continue_items.iter().any(|c| c.id == item.id) { + continue_items.push(item.clone()); + } + } + if continue_items.is_empty() { + continue_items = all_items.iter().take(6).cloned().collect(); + } + if !continue_items.is_empty() { + let empty_pl: [PlaylistSummary; 0] = []; + let slice_len = continue_items.len().min(12); + y = draw_shelf( + ctx, + covers, + shell, + actions, + t.continue_listening(), + "pod_continue", + &continue_items[..slice_len], + &empty_pl, + y, + ); + } + + // 2. Render EVERY official skeleton section from `app.non_music_sections` + let sections = app.non_music_sections.clone(); + let mut rendered_sections = 0usize; + for (sidx, sec) in sections.iter().enumerate() { + if sec.albums.is_empty() && sec.playlists.is_empty() { + continue; + } + let sec_title = if sec.title.trim().is_empty() { + if ru { "Подборка" } else { "Selection" } } else { - "Save audiobooks to your bookshelf and they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), + sec.title.as_str() + }; + let salt = format!("nm_sec_{}_{}", sidx, sec.id); + y = draw_shelf( + ctx, + covers, + shell, + actions, + sec_title, + &salt, + &sec.albums, + &sec.playlists, + y, + ); + rendered_sections += 1; + } + + // Fallback grids if skeleton sections weren't returned yet + if rendered_sections == 0 { + if !podcasts_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { "Подкасты" } else { "Podcasts" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + y = draw_grid( + ctx, + covers, + shell, + actions, + &podcasts_only, + "pod_card", + if ru { "Подкаст" } else { "Podcast" }, + y, + ); + } + if !audiobooks_only.is_empty() { + ctx.draw_text_ellipsis( + t.audiobooks(), + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + y = draw_grid( + ctx, + covers, + shell, + actions, + &audiobooks_only, + "book_card", + t.audiobooks(), + y, + ); + } + } + } + 1 => { + ctx.draw_text_ellipsis( + if ru { "Подкасты" } else { "Podcasts" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), TextAlign::Left, ); - y += 32.0; - } else { - y = draw_grid( - ctx, - covers, - shell, - actions, - &audiobooks_only, - "book_card", + y += 38.0; + if podcasts_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Подкасты не найдены." + } else { + "No podcasts found." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &podcasts_only, + "pod_tab_card", + if ru { "Подкаст" } else { "Podcast" }, + y, + ); + } + } + 2 => { + ctx.draw_text_ellipsis( t.audiobooks(), - y, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, ); + y += 38.0; + if audiobooks_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Добавляйте аудиокниги на книжную полку — они появятся здесь." + } else { + "Save audiobooks to your bookshelf and they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &audiobooks_only, + "book_tab_card", + t.audiobooks(), + y, + ); + } + } + _ => { + ctx.draw_text_ellipsis( + if ru { "Моя полка" } else { "My shelf" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + let shelf_items = app.bookshelf_items.clone(); + if shelf_items.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Сохраняйте любимые подкасты и аудиокниги — они появятся на вашей полке." + } else { + "Save podcasts and audiobooks to see them on your shelf." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &shelf_items, + "shelf_card", + t.audiobooks(), + y, + ); + } } } } @@ -488,7 +1055,11 @@ pub fn render_kids( ctx.end_scroll_v(scroll_id, pal, total_h, true); } -/// Real Concerts Feed powered by `GET /concerts/feed`. +/// 1-to-1 Official Concerts Page (`ConcertsPage` + `ConcertCard_root__fcR9B`): +/// - City filter pills ("Все города" + unique cities) +/// - Animated shimmer while loading + Refresh action when empty +/// - Top Featured Concerts 3-card poster grid with frosted date badge + Plus cashback pill + price CTA +/// - Upcoming Concerts Feed with 68x74 date block, 60x60 cover, metadata + cashback pill, and price/tickets CTA pub fn render_concerts( ctx: &mut UiContext, pal: &YmPalette, @@ -507,13 +1078,34 @@ pub fn render_concerts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; + // Header + Refresh button + let refresh_label = if ru { "Обновить" } else { "Refresh" }; + let refresh_tw = ctx + .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) + .x; + let refresh_w = (refresh_tw + 28.0).ceil(); + ctx.draw_text_ellipsis( t.concerts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), + Rect::from_xywh(x, y, (avail_w - refresh_w - 16.0).max(160.0), 42.0), TextAlign::Left, ); + let (ref_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("concerts_refresh_top"), + Pos2::new(x + avail_w - refresh_w, y + 4.0), + None, + refresh_label, + 34.0, + false, + ); + if ref_resp.clicked { + actions.push(AppAction::RefreshConcerts); + } y += 46.0; + ctx.draw_text_ellipsis( if ru { "Афиша ближайших выступлений любимых исполнителей" @@ -524,19 +1116,128 @@ pub fn render_concerts( Rect::from_xywh(x, y, avail_w, 22.0), TextAlign::Left, ); - y += 38.0; + y += 32.0; - if app.concerts.is_empty() { + let concerts = app.concerts.clone(); + + // Collect unique cities for filter pills + let mut cities: Vec = Vec::new(); + for c in &concerts { + let city = c.city.trim(); + if !city.is_empty() && !cities.iter().any(|existing| existing == city) { + cities.push(city.to_string()); + } + } + + let mut selected_city = CONCERT_CITY_FILTER.with(|cell| cell.borrow().clone()); + if let Some(ref sc) = selected_city { + if !cities.iter().any(|c| c == sc) { + selected_city = None; + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); + } + } + + if !cities.is_empty() { + let pills_vp = Rect::from_xywh(x, y, avail_w, 40.0); + let pills_h_id = WidgetId::new("concerts_city_pills"); + let sx = ctx.begin_scroll_h(pills_h_id, pills_vp, 0.0); + let mut px = x - sx; + + let all_label = if ru { "Все города" } else { "All cities" }; + let (all_resp, all_r) = secondary_pill_button( + ctx, + pal, + WidgetId::new("concerts_city_all"), + Pos2::new(px, y), + None, + all_label, + 34.0, + selected_city.is_none(), + ); + if all_resp.clicked { + selected_city = None; + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); + } + px = all_r.right() + 8.0; + + for (ci, city) in cities.iter().enumerate() { + let is_active = selected_city.as_deref() == Some(city.as_str()); + let (c_resp, c_r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("concerts_city", ci), + Pos2::new(px, y), + None, + city, + 34.0, + is_active, + ); + if c_resp.clicked { + selected_city = Some(city.clone()); + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = Some(city.clone())); + } + px = c_r.right() + 8.0; + } + ctx.end_scroll_h(pills_h_id, pal, (px + sx) - x, false); + y += 50.0; + } + + let filtered: Vec<&ConcertItem> = concerts + .iter() + .filter(|c| match selected_city.as_deref() { + Some(city) => c.city.trim() == city, + None => true, + }) + .collect(); + + if concerts.is_empty() && app.concerts_loading { + ctx.request_repaint(); + let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; + + // 3 featured shimmer poster cards + let gap = 16.0; + let f_cols = if avail_w >= 860.0 { + 3usize + } else if avail_w >= 560.0 { + 2 + } else { + 1 + }; + let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).max(220.0); + for i in 0..f_cols { + let col = shimmer_color(pal, t_sec + i as f32 * 0.55); + ctx.dl().push_rect( + Rect::from_xywh(x + i as f32 * (f_w + gap), y, f_w, 210.0), + 16.0, + col, + ); + } + y += 236.0; + + // 4 shimmer feed rows + for i in 0..4 { + let col = shimmer_color(pal, t_sec + 1.2 + i as f32 * 0.45); + ctx.dl() + .push_rect(Rect::from_xywh(x, y, avail_w, 92.0), 14.0, col); + y += 104.0; + } + } else if filtered.is_empty() { let msg = if app.account.is_none() { if ru { "Войдите в аккаунт Яндекс ID, чтобы видеть персональную афишу концертов." } else { "Sign in with Yandex ID to see personalized upcoming concerts." } + } else if selected_city.is_some() { + if ru { + "В выбранном городе ближайших концертов не найдено." + } else { + "No upcoming concerts found in the selected city." + } } else if ru { - "Ближайшие концерты не найдены или ещё загружаются." + "Ближайшие концерты не найдены. Попробуйте обновить афишу." } else { - "No upcoming concerts found or still loading." + "No upcoming concerts found. Try refreshing the feed." }; ctx.draw_text_wrapped( msg, @@ -545,13 +1246,193 @@ pub fn render_concerts( Some(2), TextAlign::Left, ); - y += 48.0; + y += 50.0; + let (btn, _) = yellow_pill_button( + ctx, + pal, + WidgetId::new("concerts_empty_refresh"), + Pos2::new(x, y), + None, + refresh_label, + 38.0, + false, + ); + if btn.clicked { + actions.push(AppAction::RefreshConcerts); + } + y += 54.0; } else { - let concerts = app.concerts.clone(); - for (idx, c) in concerts.iter().enumerate() { - let cr = Rect::from_xywh(x, y, avail_w, 94.0); + // --------------------------------------------------------------------- + // 1. TOP FEATURED CONCERTS GRID (first up to 3 concerts) + // --------------------------------------------------------------------- + let featured_count = filtered.len().min(3); + let gap = 16.0; + let f_cols = if avail_w >= 860.0 { + featured_count.min(3) + } else if avail_w >= 560.0 { + featured_count.min(2) + } else { + 1 + } + .max(1); + let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).clamp(240.0, 440.0); + let f_h = 216.0; + + ctx.draw_text_ellipsis( + if ru { "Рекомендуем" } else { "Featured" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + + for (i, c) in filtered.iter().take(featured_count).enumerate() { + let col = i % f_cols; + let row = i / f_cols; + let cr = Rect::from_xywh( + x + col as f32 * (f_w + gap), + y + row as f32 * (f_h + gap), + f_w, + f_h, + ); if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { - let resp = ctx.interact(WidgetId::from_pair("concert_card", idx), cr); + let resp = ctx.interact(WidgetId::from_pair("concert_feat", i), cr); + + // Full-bleed cover poster + draw_cover_art( + ctx, + pal, + covers, + cr, + c.cover_uri.as_deref(), + &c.id, + 16.0, + false, + false, + ); + + // Rich dark bottom gradient scrim for legible white text on any artwork + ctx.dl().push_gradient_rect( + cr, + 16.0, + Color::from_rgba(12, 12, 16, if resp.hovered { 32 } else { 52 }), + Color::from_rgba(10, 10, 14, 232), + Vec2::new(0.0, 1.0), + ); + ctx.dl().push_rect_bordered( + cr, + 16.0, + Color::TRANSPARENT, + 1.0, + Color::from_rgba(255, 255, 255, if resp.hovered { 48 } else { 24 }), + ); + + // Top-left frosted date pill + let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); + let date_chip = format!("{} {}", day_s, mon_s); + let date_style = TextStyle::bold(12.0, Color::WHITE); + let dtw = ctx.measure_text(&date_chip, date_style, None).x; + let date_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, (dtw + 20.0).ceil(), 26.0); + ctx.dl().push_rect_bordered( + date_r, + 13.0, + Color::from_rgba(14, 14, 18, 188), + 1.0, + Color::from_rgba(255, 255, 255, 36), + ); + ctx.draw_text_ellipsis(&date_chip, date_style, date_r, TextAlign::Center); + + // Top-right Plus cashback pill + if let Some(cb) = format_cashback_label(c, ru) { + draw_cashback_pill(ctx, Pos2::new(cr.right() - 14.0, cr.top() + 16.0), true, &cb); + } + + // Bottom-right price/tickets yellow CTA + let ticket_label = format_ticket_label(c, ru); + let btn_style = TextStyle::bold(12.5, pal.on_yellow); + let btn_w = (ctx.measure_text(&ticket_label, btn_style, None).x + 24.0) + .clamp(88.0, 144.0) + .ceil(); + let btn_r = Rect::from_xywh( + cr.right() - btn_w - 14.0, + cr.bottom() - 48.0, + btn_w, + 34.0, + ); + ctx.dl().push_rect(btn_r, 17.0, pal.yellow); + ctx.draw_text_ellipsis(&ticket_label, btn_style, btn_r, TextAlign::Center); + + // Bottom-left title + venue + let heading = if c.artist_name.is_empty() { + c.title.clone() + } else if c.title.is_empty() || c.title == c.artist_name { + c.artist_name.clone() + } else { + format!("{} · {}", c.artist_name, c.title) + }; + let info_w = (btn_r.left() - cr.left() - 24.0).max(90.0); + ctx.draw_text_ellipsis( + &heading, + TextStyle::bold(17.0, Color::WHITE), + Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 56.0, info_w, 24.0), + TextAlign::Left, + ); + let mut meta_parts: Vec<&str> = Vec::new(); + if !c.city.is_empty() { + meta_parts.push(c.city.as_str()); + } + if !c.place.is_empty() { + meta_parts.push(c.place.as_str()); + } + let time_str = time_opt.as_deref().unwrap_or(""); + if !time_str.is_empty() { + meta_parts.push(time_str); + } + ctx.draw_text_ellipsis( + &meta_parts.join(" · "), + TextStyle::regular(12.5, Color::from_rgba(255, 255, 255, 210)), + Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 31.0, info_w, 18.0), + TextAlign::Left, + ); + + if resp.hovered && c.afisha_url.is_some() { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + if let Some(ref url) = c.afisha_url { + actions.push(AppAction::OpenUrl(url.clone())); + } + } + } + } + let f_rows = featured_count.div_ceil(f_cols); + y += f_rows as f32 * (f_h + gap) + 18.0; + + // --------------------------------------------------------------------- + // 2. UPCOMING CONCERTS FEED (`ConcertCard_root__fcR9B`) + // --------------------------------------------------------------------- + let feed_items = if filtered.len() > 3 { + &filtered[3..] + } else { + &filtered[..] + }; + + ctx.draw_text_ellipsis( + if ru { + "Ближайшие концерты" + } else { + "Upcoming concerts" + }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + + for (idx, c) in feed_items.iter().enumerate() { + let cr = Rect::from_xywh(x, y, avail_w, 96.0); + if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { + let resp = ctx.interact(WidgetId::from_pair("concert_feed_row", idx), cr); ctx.dl().push_rect_bordered( cr, 14.0, @@ -563,7 +1444,32 @@ pub fn render_concerts( 1.0, pal.border_subtle, ); - let cov_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, 66.0, 66.0); + + // Left 68x74 rounded Date Block (big bold day + short uppercase month) + let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); + let date_r = Rect::from_xywh(cr.left() + 12.0, cr.center_y() - 37.0, 68.0, 74.0); + ctx.dl().push_rect_bordered( + date_r, + 11.0, + pal.bg_content, + 1.0, + pal.border_subtle, + ); + ctx.draw_text_ellipsis( + &day_s, + TextStyle::headline(24.0, pal.text_bright), + Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 12.0, date_r.w - 8.0, 30.0), + TextAlign::Center, + ); + ctx.draw_text_ellipsis( + &mon_s, + TextStyle::bold(11.5, pal.text_secondary), + Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 44.0, date_r.w - 8.0, 18.0), + TextAlign::Center, + ); + + // 60x60 thumbnail + let cov_r = Rect::from_xywh(date_r.right() + 14.0, cr.center_y() - 30.0, 60.0, 60.0); draw_cover_art( ctx, pal, @@ -576,6 +1482,40 @@ pub fn render_concerts( false, ); + // Right CTA button (128x38) + let ticket_label = format_ticket_label(c, ru); + let btn_w = 128.0; + let btn_r = Rect::from_xywh( + cr.right() - btn_w - 16.0, + cr.center_y() - 19.0, + btn_w, + 38.0, + ); + if c.afisha_url.is_some() { + ctx.dl().push_rect(btn_r, 19.0, pal.yellow); + ctx.draw_text_ellipsis( + &ticket_label, + TextStyle::bold(13.0, pal.on_yellow), + btn_r, + TextAlign::Center, + ); + } else { + ctx.dl().push_rect_bordered( + btn_r, + 19.0, + pal.surface_hover, + 1.0, + pal.border_subtle, + ); + ctx.draw_text_ellipsis( + &ticket_label, + TextStyle::medium(13.0, pal.text_secondary), + btn_r, + TextAlign::Center, + ); + } + + // Middle info column: title + city/place/time + Plus cashback pill let heading = if c.artist_name.is_empty() { c.title.clone() } else if c.title.is_empty() || c.title == c.artist_name { @@ -584,37 +1524,42 @@ pub fn render_concerts( format!("{} · {}", c.artist_name, c.title) }; let text_x = cov_r.right() + 16.0; - let text_w = (cr.right() - text_x - 136.0).max(100.0); + let text_w = (btn_r.left() - text_x - 14.0).max(100.0); + let cashback = format_cashback_label(c, ru); + + let title_y = if cashback.is_some() { + cr.top() + 13.0 + } else { + cr.top() + 21.0 + }; ctx.draw_text_ellipsis( &heading, TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(text_x, cr.top() + 20.0, text_w, 24.0), - TextAlign::Left, - ); - let meta: Vec<&str> = [c.date.as_str(), c.city.as_str(), c.place.as_str()] - .into_iter() - .filter(|s| !s.is_empty()) - .collect(); - ctx.draw_text_ellipsis( - &meta.join(" · "), - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(text_x, cr.top() + 50.0, text_w, 20.0), + Rect::from_xywh(text_x, title_y, text_w, 24.0), TextAlign::Left, ); - if c.afisha_url.is_some() { - let btn_r = Rect::from_center_size( - Pos2::new(cr.right() - 68.0, cr.center_y()), - Vec2::new(108.0, 34.0), - ); - ctx.dl().push_rect(btn_r, 17.0, pal.yellow); - ctx.draw_text_ellipsis( - if ru { "Билеты" } else { "Tickets" }, - TextStyle::bold(13.0, pal.on_yellow), - btn_r, - TextAlign::Center, - ); + let mut meta: Vec<&str> = Vec::new(); + if !c.city.is_empty() { + meta.push(c.city.as_str()); } + if !c.place.is_empty() { + meta.push(c.place.as_str()); + } + if let Some(ref tm) = time_opt { + meta.push(tm.as_str()); + } + ctx.draw_text_ellipsis( + &meta.join(" · "), + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(text_x, title_y + 26.0, text_w, 20.0), + TextAlign::Left, + ); + + if let Some(cb) = cashback { + draw_cashback_pill(ctx, Pos2::new(text_x, title_y + 49.0), false, &cb); + } + if resp.hovered && c.afisha_url.is_some() { ctx.set_cursor(CursorKind::Pointer); } @@ -624,7 +1569,7 @@ pub fn render_concerts( } } } - y += 104.0; + y += 106.0; } } diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index fc00273..a963dd9 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -1863,3 +1863,384 @@ fn test_ext_16_yandex_id_popup_and_words_card_visual_parity() { ); } } + +#[test] +fn test_ext_17_for_you_collection_concerts_words_fullscreen() { + use yandex_music_rs::api::models::{ + AlbumSummary, ConcertItem, NewReleaseItem, VibePickItem, VibePickTab, WordsBigCard, + WordsCard, WordsCardSource, + }; + use yandex_music_rs::engine::WidgetId; + + let rt = tokio::runtime::Runtime::new().unwrap(); + let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); + let out_dir = output_dir(); + let _ = std::fs::create_dir_all(&out_dir); + + // 1. Official `For You` scrolled down: sticky frosted header + circular NewReleases + More Picks (`for_you_new_releases_picks.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::ForYou, + ThemeMode::Dark, + Language::En, + 0.0, + ); + let mk_album = |id: &str, title: &str, artist: &str| AlbumSummary { + id: id.into(), + title: title.into(), + year: Some(2026), + cover_uri: None, + artists: vec![ArtistSummary { + id: format!("art_{id}"), + name: artist.into(), + cover_uri: None, + genres: vec![], + }], + track_count: 12, + genre: Some("electronic".into()), + is_explicit: false, + content_type: Some("album".into()), + }; + shell.app.landing.rich_new_releases = vec![ + NewReleaseItem { + album: mk_album("nr1", "Neon Horizon", "SALUKI"), + artist_cover_uri: None, + cover_color: Some("#3B4CA8".into()), + release_date: Some("2026-11-20".into()), + }, + NewReleaseItem { + album: mk_album("nr2", "Velvet Pulse", "Mirele"), + artist_cover_uri: None, + cover_color: Some("#7B2D5F".into()), + release_date: Some("2026-11-18".into()), + }, + NewReleaseItem { + album: mk_album("nr3", "Night Drive", "SLAVA MARLOW"), + artist_cover_uri: None, + cover_color: Some("#1E6B52".into()), + release_date: Some("2026-11-15".into()), + }, + NewReleaseItem { + album: mk_album("nr4", "Solar Flare", "OG BLESS"), + artist_cover_uri: None, + cover_color: Some("#8F4A1E".into()), + release_date: Some("2026-11-12".into()), + }, + ]; + shell.app.landing.vibe_pick_tabs = vec![ + VibePickTab { + title: "Mood".into(), + items: vec![ + VibePickItem { + title: "Energetic".into(), + header: "Vibe".into(), + seeds: vec!["mood:energetic".into()], + color_hex: Some("#D94E2A".into()), + background_image_url: None, + image_url: None, + }, + VibePickItem { + title: "Night Focus".into(), + header: "Vibe".into(), + seeds: vec!["mood:calm".into()], + color_hex: Some("#2F55A4".into()), + background_image_url: None, + image_url: None, + }, + VibePickItem { + title: "Dreamy Synth".into(), + header: "Vibe".into(), + seeds: vec!["genre:electronic".into()], + color_hex: Some("#7C3AED".into()), + background_image_url: None, + image_url: None, + }, + ], + }, + VibePickTab { + title: "Activity".into(), + items: vec![VibePickItem { + title: "Workout".into(), + header: "Vibe".into(), + seeds: vec!["activity:workout".into()], + color_hex: Some("#0F766E".into()), + background_image_url: None, + image_url: None, + }], + }, + VibePickTab { + title: "Genres".into(), + items: vec![], + }, + ]; + + // Warm up layout so scroll content height is computed, then scroll to show New Releases + More Picks + sticky switcher + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + shell + .ui + .scrolls + .jump_to_y(WidgetId::new("foryou_page_scroll"), 860.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.032); + let img = render_single_frame(&mut vk, &mut shell, 0.048); + let _ = img.save(out_dir.join("for_you_new_releases_picks.png")); + + // Verify colored NewRelease cards / More Picks cards rendered non-flat rich pixels in content card + let mut colored_px = 0usize; + for y in 110..680 { + for x in 250..1240 { + let [r, g, b] = img.get_pixel(x, y).0; + let max_c = r.max(g).max(b); + let min_c = r.min(g).min(b); + if max_c.saturating_sub(min_c) >= 24 { + colored_px += 1; + } + } + } + assert!( + colored_px > 5_000, + "[for_you_new_releases_picks] Expected colored New Releases / More Picks cards, found only {} chromatic px", + colored_px + ); + } + + // 2. Official `My Collection` vertical feed (`my_collection_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::Collection, + ThemeMode::Dark, + Language::En, + 0.0, + ); + let extra_tracks = [ + ("c_1", "MONTAGEM TENTA", "KYOR", 141_000), + ("c_2", "Midnight Sun", "SuperSolar", 184_000), + ("c_3", "BANG A RANG", "GSTRNM", 100_000), + ("c_4", "BOSS BITCH TEKK", "wharoxmane", 107_000), + ("c_5", "Neon Rain", "Mirele", 192_000), + ("c_6", "Skyline Pulse", "SALUKI", 168_000), + ("c_7", "Electric Horizon", "SLAVA MARLOW", 155_000), + ("c_8", "Deep Focus", "OG BLESS", 210_000), + ]; + shell.app.liked_tracks = extra_tracks + .iter() + .map(|(id, title, art, dur)| Track { + id: (*id).into(), + title: (*title).into(), + version: None, + artists: vec![ArtistSummary { + id: format!("ca_{id}"), + name: (*art).into(), + cover_uri: None, + genres: vec![], + }], + album_id: Some(format!("calb_{id}")), + album_title: Some((*title).into()), + duration_ms: *dur, + cover_uri: None, + is_explicit: false, + has_lossless: true, + has_lyrics: true, + chart_position: None, + chart_progress: None, + preview_url: None, + r128_i: None, + r128_tp: None, + derived_average_hex: None, + derived_accent_hex: None, + }) + .collect(); + shell.app.liked_artists = ["SALUKI", "Mirele", "KYOR", "SuperSolar", "GSTRNM", "OG BLESS"] + .iter() + .enumerate() + .map(|(i, name)| ArtistSummary { + id: format!("la_{i}"), + name: (*name).into(), + cover_uri: None, + genres: vec![], + }) + .collect(); + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("my_collection_official.png")); + + // Verify pink-magenta colored "color" word in subtitle + crimson 3D heart icon present, + // and ZERO old yellow-bordered My Favorites hero card! + let mut pink_subtitle_px = 0usize; + for y in 75..125 { + for x in 250..520 { + let [r, g, b] = img.get_pixel(x, y).0; + if r > 170 && b > 100 && (r as u16) > (g as u16) + 50 { + pink_subtitle_px += 1; + } + } + } + assert!( + pink_subtitle_px >= 15, + "[my_collection_official] Expected magenta-colored subtitle word 'color', found {} px", + pink_subtitle_px + ); + } + + // 3. Official `ConcertsPage` (`concerts_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::Concerts, + ThemeMode::Dark, + Language::Ru, + 0.0, + ); + shell.app.concerts = vec![ + ConcertItem { + id: "con_1".into(), + title: "SALUKI — Большой сольный концерт".into(), + artist_name: "SALUKI".into(), + city: "Москва".into(), + place: "VK Stadium".into(), + date: "14 дек, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(2500), + currency: Some("RUB".into()), + cashback_percent: Some(15), + cashback_title: Some("Кешбэк 15%".into()), + cover_color: Some("#4C2A85".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_2".into(), + title: "Mirele — Акустический вечер".into(), + artist_name: "Mirele".into(), + city: "Санкт-Петербург".into(), + place: "A2 Green Concert".into(), + date: "21 дек, 19:30".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(1900), + currency: Some("RUB".into()), + cashback_percent: Some(10), + cashback_title: None, + cover_color: Some("#1D5B79".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_3".into(), + title: "SLAVA MARLOW — Live Tour".into(), + artist_name: "SLAVA MARLOW".into(), + city: "Казань".into(), + place: "Korston Club Hotel".into(), + date: "28 дек, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(2200), + currency: Some("RUB".into()), + cashback_percent: Some(20), + cashback_title: None, + cover_color: Some("#8C2F39".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_4".into(), + title: "Электрофорез — Зимний сет".into(), + artist_name: "Электрофорез".into(), + city: "Москва".into(), + place: "Урбан".into(), + date: "5 янв, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(1700), + currency: Some("RUB".into()), + cashback_percent: Some(10), + cashback_title: None, + cover_color: Some("#2D4F1E".into()), + event_kind: Some("concert".into()), + }, + ]; + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("concerts_official.png")); + + // Verify Top 3 colored poster cards + upcoming feed rendered cleanly + let mut poster_chromatic_px = 0usize; + for y in 160..420 { + for x in 250..1240 { + let [r, g, b] = img.get_pixel(x, y).0; + if r.max(g).max(b).saturating_sub(r.min(g).min(b)) >= 20 { + poster_chromatic_px += 1; + } + } + } + assert!( + poster_chromatic_px > 10_000, + "[concerts_official] Expected Top 3 concert poster cards + cashback pills, found {} chromatic px", + poster_chromatic_px + ); + } + + // 4. Official `WordsCardFullscreen` (`words_fullscreen_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::MyVibe, + ThemeMode::Dark, + Language::Ru, + 108.0, + ); + shell.app.words_cards.insert( + "t_1".into(), + WordsCard { + id: "wc_fs_1".into(), + track_id: "t_1".into(), + text: "MONTAGEM TENTA сочетает бразильский фонк и жёсткие хардстайл-кики.".into(), + tags: vec!["FACT".into()], + action: None, + actions: vec![], + big_card_ids: vec!["bc_1".into()], + feedback_state: None, + }, + ); + shell.app.words_big_card_open = true; + shell.app.words_big_card_loading = false; + shell.app.words_big_card = Some(WordsBigCard { + id: "bc_1".into(), + text: "MONTAGEM TENTA (Hardstyle) — взрывной кроссовер бразильского фонка и европейского хардстайла с плотным саб-басом и стремительным ритмом.".into(), + actions: vec![WordsCardSource { + title: "Обсудить с Алисой AI".into(), + url: "https://alice.yandex.ru".into(), + favicon_url: None, + }], + }); + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("words_fullscreen_official.png")); + + // Verify purple Alice ring (#8B5CF6) rendered inside the centered source pill + let mut alice_purple_px = 0usize; + for y in 360..600 { + for x in 560..960 { + let [r, g, b] = img.get_pixel(x, y).0; + if b > 160 && r > 90 && (b as u16) > (g as u16) + 50 { + alice_purple_px += 1; + } + } + } + assert!( + alice_purple_px >= 15, + "[words_fullscreen_official] Expected purple Alice AI icon inside source pill, found {} px", + alice_purple_px + ); + } +}