diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index cf8dc13..1862f45 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -1,4 +1,5 @@ -//! The page: banners, Challenge header, charts and champion table for one Account. +//! The page and its two tabs: the shared state, the header row with its navigation, the banners and +//! the champ select view. `home` and `statistics` render what is under the banners. use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -8,6 +9,7 @@ use arena_tracker_core::{ StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, account_riot_id, same_riot_id, }; +use gpui_kit::base::Button as BaseButton; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; use gpui_kit::component::alert::Alert; @@ -17,11 +19,14 @@ use gpui_kit::component::{ActiveTheme as _, IndexPath, Sizable as _}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; +mod home; mod statistics; use crate::champion_table::ChampionTable; use crate::text::{CLIENT_ABSENT, official_differs, sync_line}; -use crate::worker::{LiveChampSelect, Msg, RefreshGate, spawn_refresh, spawn_statistics}; +use crate::worker::{ + LiveChampSelect, Msg, RefreshGate, compute_statistics, spawn_refresh, spawn_statistics, +}; use statistics::ChartsRow; const ALL_SEASONS: &str = "Toutes les Saisons"; @@ -86,6 +91,15 @@ pub struct ChampSelectTransition { } impl EventEmitter for Page {} +/// The two pages the navigation switches between. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Tab { + /// « Défi », the home: the Challenge of one Season. + Challenge, + /// « Statistiques »: the analysis by Account, Season and Format. + Statistics, +} + pub struct Page { tracker: Arc, tx: Sender, @@ -119,6 +133,9 @@ pub struct Page { crashed: bool, last_reload: Instant, current_season: Option, + /// Not persisted: the app opens on the Challenge. + tab: Tab, + /// The Season of the Statistics tab. season: SeasonScope, format: Option, filter: StateFilter, @@ -127,6 +144,22 @@ pub struct Page { search_input: Entity, stats: Option, stats_error: Option, + /// The Season whose Challenge the home shows: the one chosen on the Statistics tab, else the + /// current one. None when there is no such Season. + home_season: Option, + /// The home's scope when it differs from the Statistics tab's, else the home reads `stats`. + home_scope: Option, + /// Only for a `home_scope`. + home_stats: Option, + home_error: Option, + /// « N / total », prepared when the statistics change. + home_count: SharedString, + /// Completed over total, for the progress line. + home_fraction: f32, + /// The home's own filter and search: never persisted, « Tous » at each launch. + home_filter: StateFilter, + home_search: ChampionSearch, + home_search_input: Entity, stored: Option, account_select: Entity>>, account_items: Vec, @@ -135,6 +168,8 @@ pub struct Page { format_names: Vec, charts: Entity, table: Entity, + /// Temporary: the cards replace it (#72). + home_table: Entity, _subscriptions: Vec, _listener: Task<()>, } @@ -174,7 +209,9 @@ impl Page { .new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx)); let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher")); let charts = cx.new(|_| ChartsRow::new()); + let home_search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher")); let table = cx.new(|_| ChampionTable::new()); + let home_table = cx.new(|_| ChampionTable::new()); let subscriptions = vec![ cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| { @@ -183,6 +220,12 @@ impl Page { this.refresh_table(cx); } }), + cx.subscribe(&home_search_input, |this, input, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + this.home_search = ChampionSearch::new(&input.read(cx).value()); + this.refresh_home(cx); + } + }), cx.subscribe_in( &account_select, window, @@ -265,6 +308,7 @@ impl Page { crashed: false, last_reload: Instant::now(), current_season, + tab: Tab::Challenge, season, format: None, filter: StateFilter::All, @@ -272,6 +316,15 @@ impl Page { search_input, stats: None, stats_error: None, + home_season: None, + home_scope: None, + home_stats: None, + home_error: None, + home_count: SharedString::default(), + home_fraction: 0., + home_filter: StateFilter::All, + home_search: ChampionSearch::new(""), + home_search_input, stored: None, account_select, account_items: Vec::new(), @@ -280,6 +333,7 @@ impl Page { format_names, charts, table, + home_table, _subscriptions: subscriptions, _listener: listener, }; @@ -332,13 +386,46 @@ impl Page { }) } - /// The game's own count, only meaningful for the Account being updated in the current Season. + /// The game's own count, only meaningful for the Account being updated in the current Season, + /// whether the page shows it as the home's Challenge or as the selected Season. fn official(&self) -> Option<&ProgressCheck> { let updated = matches!((self.viewed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid); - let current = matches!((&self.season, &self.current_season), (SeasonScope::Season(s), Some(c)) if s == c); + let shown = match (self.tab, &self.season) { + (Tab::Challenge, _) => self.home_season.as_deref(), + (Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()), + (Tab::Statistics, SeasonScope::AllSeasons) => None, + }; + let current = shown.is_some() && shown == self.current_season.as_deref(); (updated && current).then_some(&self.status.official_progress) } + /// What the home reads: its own statistics when its scope differs, else the Statistics tab's. + fn home_statistics(&self) -> Option<&Statistics> { + self.home_season.as_ref()?; + match self.home_scope { + Some(_) => self.home_stats.as_ref(), + None => self.stats.as_ref(), + } + } + + /// The tab's own statistics error: the home may have computed its own. + fn error(&self) -> Option<&String> { + match (self.tab, &self.home_scope) { + (Tab::Challenge, Some(_)) => self.home_error.as_ref(), + _ => self.stats_error.as_ref(), + } + } + + fn set_tab(&mut self, tab: Tab, cx: &mut Context) { + if self.tab != tab { + self.tab = tab; + // The tab left was not kept up to date. + self.refresh_table(cx); + self.refresh_home(cx); + cx.notify(); + } + } + fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context) { match msg { Msg::Progress(progress) => { @@ -369,6 +456,8 @@ impl Page { self.stats_generation += 1; self.stats = None; self.stats_error = None; + self.home_stats = None; + self.home_error = None; self.stored = None; self.reload_in_background(window, cx); } @@ -418,11 +507,13 @@ impl Page { Msg::Statistics { generation, stats, + home, stored, } => { if generation == self.stats_generation { self.stats_error = stats.as_ref().err().cloned(); self.stats = stats.ok(); + self.set_home_result(home); self.stored = stored; self.show_statistics(window, cx); } @@ -507,6 +598,8 @@ impl Page { if computing { self.stats_generation += 1; } + // The champ select view has no home. + self.home_scope = None; self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name); let puuid = self.champ_select_account()?; return self.current_season.is_some().then_some(puuid); @@ -516,6 +609,7 @@ impl Page { { self.filter = StateFilter::All; } + self.settle_home_scope(); let viewed = self.viewed().map(|a| a.puuid.clone()); if computing || viewed != self.shown { self.stats_generation += 1; @@ -532,6 +626,31 @@ impl Page { viewed } + /// The Season of the home's Challenge, and the scope to compute for it when the Statistics + /// tab's does not already cover it. The Format never applies to the home. + fn settle_home_scope(&mut self) { + let season = match &self.season { + SeasonScope::Season(name) => Some(name), + // A Challenge belongs to one Season: the current one stands in. + SeasonScope::AllSeasons => self.current_season.as_ref(), + }; + self.home_season = season.map(|name| name.clone().into()); + let home = season.map(|name| Scope { + season: SeasonScope::Season(name.clone()), + format: None, + }); + self.home_scope = home.filter(|home| *home != self.statistics_scope()); + } + + /// Keeps what the job computed for the home's own scope, if it had one. + fn set_home_result(&mut self, home: Option>>) { + (self.home_stats, self.home_error) = match home.map(|result| *result) { + Some(Ok(stats)) => (Some(stats), None), + Some(Err(error)) => (None, Some(error)), + None => (None, None), + }; + } + /// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the /// Accounts do), so preparing statistics builds no Riot ID per Account every time. fn champ_select_account(&mut self) -> Option { @@ -579,6 +698,7 @@ impl Page { self.tracker.clone(), puuid, scope, + self.home_scope.clone(), self.stats_generation, self.tx.clone(), ); @@ -589,6 +709,8 @@ impl Page { } self.stats = None; self.stats_error = None; + self.home_stats = None; + self.home_error = None; self.stored = None; self.show_statistics(window, cx); } @@ -599,13 +721,18 @@ impl Page { let viewed = self.prepare_statistics(true, window, cx); self.stats = None; self.stats_error = None; + self.home_stats = None; + self.home_error = None; self.stored = None; if let Some(puuid) = &viewed { let scope = self.statistics_scope(); - match self.tracker.statistics(puuid, &scope) { + match compute_statistics(&self.tracker, puuid, &scope) { Ok(stats) => self.stats = Some(stats), - Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")), + Err(error) => self.stats_error = Some(error), } + let home = (self.home_scope.clone()) + .map(|home| Box::new(compute_statistics(&self.tracker, puuid, &home))); + self.set_home_result(home); self.stored = self.tracker.match_count(puuid).ok(); } self.show_statistics(window, cx); @@ -619,6 +746,7 @@ impl Page { cx.notify(); return; } + self.prepare_home_labels(); let charts = self.stats.as_ref().map(|s| &s.charts); let in_season = self.in_season(); self.charts @@ -635,9 +763,21 @@ impl Page { .update(cx, |select, cx| select.set_items(names, window, cx)); } self.refresh_table(cx); + self.refresh_home(cx); cx.notify(); } + /// The counter's text and the progress line's length, for when the statistics change. + fn prepare_home_labels(&mut self) { + let challenge = self.home_statistics().and_then(|s| s.challenge.as_ref()); + let count = challenge.map(|c| format!("{} / {}", c.completed, c.total)); + let fraction = challenge.map_or(0., |c| { + (c.completed as f32 / c.total.max(1) as f32).clamp(0., 1.) + }); + self.home_count = count.unwrap_or_default().into(); + self.home_fraction = fraction; + } + fn in_champ_select(&self) -> bool { self.champ_select.is_some() } @@ -704,7 +844,11 @@ impl Page { self.champ_select_notice = champ_select_notice; } + /// Rebuilds the Statistics tab's rows; while it is not shown, the next switch does. fn refresh_table(&mut self, cx: &mut Context) { + if self.tab != Tab::Statistics && !self.in_champ_select() { + return; + } let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows .filter(|row| match &self.champ_select { @@ -720,6 +864,23 @@ impl Page { }); } + /// Rebuilds the home's rows from its own filter and search, with the total untouched; while + /// the home is not shown, the next switch does. + fn refresh_home(&mut self, cx: &mut Context) { + if self.tab != Tab::Challenge || self.in_champ_select() { + return; + } + let rows = self.home_statistics().into_iter().flat_map(|s| &s.rows); + let rows = rows + .filter(|row| self.home_filter.keeps(row) && self.home_search.matches(&row.champion)) + .cloned() + .collect(); + self.home_table.update(cx, |table, cx| { + table.set_rows(rows, true); + cx.notify(); + }); + } + fn champ_select_view(&self, cx: &App) -> Div { let border = cx.theme().border; let page = div().v_flex().size_full().p_3().gap_3().child( @@ -787,6 +948,49 @@ impl Page { }) } + /// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them. + fn navigation(&self, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let (ring, muted, active, active_foreground, hover, hover_foreground) = ( + theme.ring, + theme.tab_foreground, + theme.tab_active, + theme.tab_active_foreground, + theme.accent, + theme.accent_foreground, + ); + let tabs = [ + ("tab-challenge", "Défi", Tab::Challenge), + ("tab-statistics", "Statistiques", Tab::Statistics), + ]; + div() + .h_flex() + .gap_1() + .flex_shrink_0() + .children(tabs.map(|(id, label, tab)| { + let current = self.tab == tab; + BaseButton::new(id) + .px_3() + .py_1() + .rounded_md() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + // Always bordered, so the focus ring does not shift the label. + .border_1() + .border_color(transparent_black()) + .focus_visible(|style| style.border_color(ring)) + .text_color(if current { active_foreground } else { muted }) + .when(current, |button| button.bg(active)) + .when(!current, |button| { + button.hover(|style| style.bg(hover).text_color(hover_foreground)) + }) + .accessibility_label(label) + .debug_selector(|| id.into()) + .child(label) + .on_click(cx.listener(move |this, _, _, cx| this.set_tab(tab, cx))) + })) + } + /// One line each, the most important first; the stored data stays visible under all. fn banners(&self) -> Vec { let mut banners = Vec::new(); @@ -811,7 +1015,7 @@ impl Page { if let Some(notice) = &self.notice { banners.push(Alert::warning("notice", notice.clone())); } - if let Some(error) = &self.stats_error { + if let Some(error) = self.error() { banners.push(Alert::error("stats", error.clone())); } banners @@ -857,6 +1061,7 @@ impl Render for Page { .items_center() .gap_3() .min_w_0() + .child(self.navigation(cx)) .child( Select::new(&self.account_select) .id("account") @@ -871,7 +1076,10 @@ impl Render for Page { .text_color(muted) .child("Non mis à jour") })) - .children(self.statistics_selectors()), + // The Season and Format only exist where they are analysed. + .when(self.tab == Tab::Statistics, |group| { + group.children(self.statistics_selectors()) + }), ) .child( div().h_flex().items_center().gap_3().flex_shrink_0().child( @@ -887,7 +1095,10 @@ impl Render for Page { .when(shown("banners"), |page| { page.child(div().v_flex().gap_1().children(self.banners())) }) - .children(self.statistics_content(cx)) + .children(match self.tab { + Tab::Challenge => self.home_content(cx), + Tab::Statistics => self.statistics_content(cx), + }) } } @@ -899,16 +1110,17 @@ mod tests { use std::sync::Arc; use arena_tracker_core::{ - Account, Champion, ChampionRow, ChampionState, Charts, Format, MatchHistorySource, RiotApi, - SourceError, StateFilter, Statistics, Tracker, + Account, ChallengeSummary, Champion, ChampionRow, ChampionState, Charts, Date, Format, + MatchHistorySource, RiotApi, Season, SeasonScope, SourceError, StateFilter, Statistics, + Tracker, }; use gpui_kit::base::async_util::unbounded; use gpui_kit::{ - AppContext as _, Bounds, Entity, Modifiers, TestAppContext, VisualTestContext, - WindowBounds, WindowOptions, point, px, size, + AppContext as _, Bounds, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, + TestAppContext, VisualTestContext, WindowBounds, WindowOptions, point, px, size, }; - use super::Page; + use super::{Page, Tab}; use crate::champion_table::tests::row; fn open_page(cx: &mut TestAppContext) -> (Entity, VisualTestContext) { @@ -1045,6 +1257,8 @@ mod tests { let pick = ChampSelect::new(Some(39), [39].into(), vec![39]); window.update(|w, cx| { page.update(cx, |p, cx| { + // The table that follows the champ select pool back is the Statistics one. + p.set_tab(Tab::Statistics, cx); p.pinned = Some("Bob".into()); p.season = SeasonScope::AllSeasons; p.filter = StateFilter::NeverPlayed; @@ -1162,6 +1376,9 @@ mod tests { formats: Vec::new(), }); }); + // The search field of the Statistics tab is only there on that tab. + page.update(cx, |page, cx| page.set_tab(Tab::Statistics, cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); let (input, table) = page.read_with(cx, |p, _| (p.search_input.clone(), p.table.clone())); let names = |cx: &mut VisualTestContext| table.read_with(cx, |table, _| table.names()); cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx))); @@ -1200,6 +1417,8 @@ mod tests { fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) { let (page, cx) = open_page(cx); let cx = &mut { cx }; + // The table hovered is the Statistics tab's: the app opens on the Challenge. + page.update(cx, |page, cx| page.set_tab(Tab::Statistics, cx)); let (table, charts) = page.read_with(cx, |page, _| (page.table.clone(), page.charts.clone())); // Enough rows to fill the table, under the points hovered below. @@ -1233,4 +1452,275 @@ mod tests { renders + 1 ); } + + fn season(name: &str, year: i32) -> Season { + Season { + name: name.into(), + start: Date { + year, + month: 1, + day: 1, + }, + official_track: None, + } + } + + /// A page with a current Season (and no Account), on made-up statistics. + fn open_page_in_season(cx: &mut TestAppContext) -> (Entity, VisualTestContext) { + open_page_with_tracker( + cx, + Tracker::open( + Path::new(":memory:"), + Box::new(RiotApi::new(String::new(), "europe")), + ) + .unwrap() + .with_seasons(vec![season("Saison", 2020)]), + ) + } + + fn statistics(completed: usize, total: usize, rows: Vec) -> Statistics { + Statistics { + challenge: Some(ChallengeSummary { + completed, + total, + attempts: 0, + average_attempts: None, + first_tries: 0, + }), + rows, + charts: Charts { + // Not empty, so the charts row has something new to draw. + placements: vec![(1, 2)], + completed_over_time: Vec::new(), + attempts_to_complete: [0; 5], + }, + formats: Vec::new(), + } + } + + fn show(page: &Entity, cx: &mut VisualTestContext, stats: Statistics) { + cx.update(|window, cx| { + page.update(cx, |page, cx| { + page.stats = Some(stats); + page.show_statistics(window, cx); + }) + }); + } + + #[gpui::test] + fn the_app_opens_on_the_challenge_with_all_champions_selected(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + page.read_with(cx, |page, _| { + assert_eq!(page.tab, Tab::Challenge); + assert_eq!(page.home_filter, StateFilter::All); + assert_eq!(super::home::FILTERS[0].0, "Tous"); + assert_eq!(page.home_season.as_deref(), Some("Saison")); + }); + } + + #[gpui::test] + fn without_a_current_season_the_home_has_no_challenge(cx: &mut TestAppContext) { + let (page, cx) = open_page(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(1, 3, vec![row("Ahri")])); + cx.update(|window, cx| window.draw(cx).clear(cx)); + page.read_with(cx, |page, cx| { + // « Toutes les Saisons », and no current Season to stand in. + assert_eq!(page.season, SeasonScope::AllSeasons); + assert_eq!(page.home_season, None); + assert!(page.home_statistics().is_none()); + assert!(page.home_count.is_empty()); + assert!(page.home_table.read(cx).names().is_empty()); + }); + } + + #[gpui::test] + fn the_counter_keeps_its_total_while_a_search_and_a_filter_reduce_the_list( + cx: &mut TestAppContext, + ) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + let champion = |name: &str, state| ChampionRow { + state: Some(state), + ..row(name) + }; + show( + &page, + cx, + statistics( + 1, + 4, + vec![ + champion("Ahri", ChampionState::Completed), + champion("Annie", ChampionState::InProgress), + champion("Akali", ChampionState::NeverPlayed), + champion("Zed", ChampionState::NeverPlayed), + ], + ), + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let (input, table) = page.read_with(cx, |p, _| { + (p.home_search_input.clone(), p.home_table.clone()) + }); + let names = |cx: &mut VisualTestContext| { + let mut names = table.read_with(cx, |table, _| table.names()); + names.sort(); + names + }; + let counter = |cx: &mut VisualTestContext| { + page.read_with(cx, |p, _| (p.home_count.to_string(), p.home_fraction)) + }; + assert_eq!(names(cx), ["Ahri", "Akali", "Annie", "Zed"]); + assert_eq!(counter(cx), ("1 / 4".to_string(), 0.25)); + + // The home's search is its own: the Statistics tab's is untouched. + cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx))); + cx.simulate_input("an"); + assert_eq!(names(cx), ["Annie"]); + assert_eq!(counter(cx), ("1 / 4".to_string(), 0.25)); + assert!(page.read_with(cx, |p, _| p.search.matches(&row("Zed").champion))); + + cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx))); + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Remaining; + p.refresh_home(cx); + }); + assert_eq!(names(cx), ["Akali", "Annie", "Zed"]); + cx.simulate_input("a"); + assert_eq!(names(cx), ["Akali", "Annie"]); + assert_eq!(counter(cx), ("1 / 4".to_string(), 0.25)); + + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Completed; + p.refresh_home(cx); + }); + assert_eq!(names(cx), ["Ahri"]); + assert_eq!(counter(cx), ("1 / 4".to_string(), 0.25)); + } + + #[gpui::test] + fn the_home_follows_the_season_of_the_statistics_but_not_their_format(cx: &mut TestAppContext) { + cx.executor().allow_parking(); + let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)) + .unwrap() + .with_seasons(vec![season("Ancienne", 2020), season("Récente", 2026)]); + tracker.sync("Alice#EUW", &mut |_| {}).unwrap(); + let (page, mut window) = open_page_with_tracker(cx, tracker); + let recompute = |window: &mut VisualTestContext, change: &dyn Fn(&mut Page)| { + window.update(|window, cx| { + page.update(cx, |page, cx| { + change(page); + page.recompute(window, cx); + }) + }); + }; + let home = |cx: &mut VisualTestContext| { + page.read_with(cx, |page, _| { + ( + page.home_season.clone(), + page.home_scope.is_some(), + page.home_statistics().cloned(), + ) + }) + }; + + // The current Season, with no Format: the home reads the Statistics tab's result. + let (season, apart, current) = home(&mut window); + assert_eq!(season.as_deref(), Some("Récente")); + assert!(!apart); + let current = current.unwrap(); + assert_eq!(current.rows.iter().map(|r| r.matches).sum::(), 1); + + // Another Format on the Statistics tab: the home keeps its Challenge. + recompute(&mut window, &|page| { + page.tab = Tab::Statistics; + page.format = Some(Format::Arena3x6); + }); + let (season, apart, same) = home(&mut window); + assert_eq!(season.as_deref(), Some("Récente")); + assert!(apart); + assert_eq!(same.as_ref(), Some(¤t)); + + // Another Season: the home follows. + recompute(&mut window, &|page| { + page.format = None; + page.season = SeasonScope::Season("Ancienne".into()); + }); + let (season, apart, other) = home(&mut window); + assert_eq!(season.as_deref(), Some("Ancienne")); + assert!(!apart); + let other = other.unwrap(); + assert_ne!(other, current); + assert_eq!(other.rows.iter().map(|r| r.matches).sum::(), 0); + + // « Toutes les Saisons » has no Challenge: the current Season stands in for the home. + recompute(&mut window, &|page| page.season = SeasonScope::AllSeasons); + let (season, apart, all) = home(&mut window); + assert_eq!(season.as_deref(), Some("Récente")); + assert!(apart); + assert_eq!(all.as_ref(), Some(¤t)); + assert!(page.read_with(&window, |page, _| { + page.stats.as_ref().unwrap().challenge.is_none() + })); + } + + // Guards the home's one rule of rule #1: it draws no chart (the cached row is not in its tree). + #[gpui::test] + fn the_home_does_not_render_the_charts(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(0, 1, vec![row("Ahri")])); + let charts = page.read_with(cx, |page, _| page.charts.clone()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!(charts.read_with(cx, |charts, _| charts.renders), 0); + + page.update(cx, |page, cx| page.set_tab(Tab::Statistics, cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!(charts.read_with(cx, |charts, _| charts.renders) > 0); + } + + fn center(cx: &mut VisualTestContext, id: &'static str) -> gpui_kit::Point { + cx.debug_bounds(id).unwrap().center() + } + + #[gpui::test] + fn the_navigation_switches_tabs_with_the_mouse(cx: &mut TestAppContext) { + let (page, cx) = open_page(cx); + let cx = &mut { cx }; + let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!(tab(cx), Tab::Challenge); + + let statistics = center(cx, "tab-statistics"); + cx.simulate_click(statistics, Modifiers::none()); + assert_eq!(tab(cx), Tab::Statistics); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let challenge = center(cx, "tab-challenge"); + cx.simulate_click(challenge, Modifiers::none()); + assert_eq!(tab(cx), Tab::Challenge); + } + + #[gpui::test] + fn the_navigation_switches_tabs_with_the_keyboard(cx: &mut TestAppContext) { + let (page, cx) = open_page(cx); + let cx = &mut { cx }; + cx.update(|window, cx| window.draw(cx).clear(cx)); + // Tab reaches « Défi » first, then « Statistiques ». + cx.update(|window, cx| { + window.focus_next(cx); + window.focus_next(cx); + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let enter = + cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap()); + cx.simulate_event(KeyDownEvent { + keystroke: enter.clone(), + is_held: false, + prefer_character_input: false, + }); + cx.simulate_event(KeyUpEvent { keystroke: enter }); + assert_eq!(page.read_with(cx, |page, _| page.tab), Tab::Statistics); + } } diff --git a/crates/app/src/page/home.rs b/crates/app/src/page/home.rs new file mode 100644 index 0000000..6bbec1f --- /dev/null +++ b/crates/app/src/page/home.rs @@ -0,0 +1,146 @@ +//! The « Défi » tab, the home: the Challenge of one Season, and its champions. + +use arena_tracker_core::StateFilter; +use gpui_kit::component::input::Input; +use gpui_kit::component::tab::{Tab, TabBar}; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::*; + +use super::{Page, shown}; + +/// The filters on offer, whatever the Season. +pub(super) const FILTERS: [(&str, StateFilter); 3] = [ + ("Tous", StateFilter::All), + ("Restants", StateFilter::Remaining), + ("Validés", StateFilter::Completed), +]; + +impl Page { + /// Under the banners: the Season and its counter, then the filters, search and champions. + /// It holds no chart (#71): the cached charts row only belongs to the Statistics tab. + pub(super) fn home_content(&self, cx: &mut Context) -> Vec { + let mut content = Vec::new(); + if shown("home-header") { + content.push(self.home_header(cx).into_any_element()); + } + if self.home_season.is_none() { + return content; + } + if shown("home-tools") { + let selected = FILTERS.iter().position(|(_, f)| *f == self.home_filter); + content.push( + div() + .h_flex() + .items_center() + .justify_between() + .gap_3() + .child( + TabBar::new("home-filter") + .segmented() + .selected_index(selected.unwrap_or(0)) + .children(FILTERS.iter().map(|(label, _)| Tab::new().label(*label))) + .on_click(cx.listener(|this, ix: &usize, _, cx| { + if let Some((_, filter)) = FILTERS.get(*ix) { + this.home_filter = *filter; + this.refresh_home(cx); + cx.notify(); + } + })), + ) + .child( + Input::new(&self.home_search_input) + .cleanable(true) + .w(px(260.)) + .min_w(px(150.)), + ) + .into_any_element(), + ); + } + if shown("home-list") { + content.push( + div() + .flex_1() + .min_h(px(240.)) + .child(self.home_table.clone()) + .into_any_element(), + ); + } + content + } + + /// The Season, the title and, beside it, the champions Completed out of the Challenge's total. + fn home_header(&self, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let (muted, border, foreground, fill) = ( + theme.muted_foreground, + theme.border, + theme.foreground, + theme.progress_bar, + ); + let counter = match &self.home_season { + Some(_) if self.home_count.is_empty() => None, + Some(_) => Some( + // The line is as wide as the text above it: the block shrinks to its content. + div() + .v_flex() + .flex_shrink_0() + .gap(px(5.)) + .child( + div() + .h_flex() + .gap_1() + .whitespace_nowrap() + .text_xs() + .text_color(muted) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(foreground) + .child(self.home_count.clone()), + ) + .child("champions validés"), + ) + .child( + div() + .w_full() + .h(px(2.)) + .bg(border) + .child(div().h_full().w(relative(self.home_fraction)).bg(fill)), + ) + .into_any_element(), + ), + None => Some( + div() + .text_sm() + .whitespace_nowrap() + .text_color(muted) + .child("Aucune Saison en cours") + .into_any_element(), + ), + }; + div() + .v_flex() + .gap_1() + .children( + self.home_season + .clone() + .map(|season| div().text_xs().text_color(muted).child(season)), + ) + .child( + div() + .h_flex() + .flex_wrap() + .items_center() + .justify_between() + .gap_x_4() + .gap_y_1() + .child( + div() + .text_3xl() + .font_weight(FontWeight::SEMIBOLD) + .child("Défi de saison"), + ) + .children(counter), + ) + } +} diff --git a/crates/app/src/page/statistics.rs b/crates/app/src/page/statistics.rs index 81350f3..cd7da2d 100644 --- a/crates/app/src/page/statistics.rs +++ b/crates/app/src/page/statistics.rs @@ -189,20 +189,8 @@ impl Render for ChartsRow { (theme.border, theme.muted_foreground) }; let charts = &self.charts; - let mut cards = vec![ - card( - "Répartition des Placements", - if shown("placements") { - placements_chart(charts) - } else { - Some(div().size_full().into_any_element()) - }, - NO_MATCH, - border, - muted, - ) - .into_any_element(), - ]; + let mut cards = Vec::new(); + // The curve first: it is the Season's story, the others detail it. if self.in_season { cards.push( card( @@ -218,6 +206,22 @@ impl Render for ChartsRow { ) .into_any_element(), ); + } + cards.push( + card( + "Répartition des Placements", + if shown("placements") { + placements_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, + NO_MATCH, + border, + muted, + ) + .into_any_element(), + ); + if self.in_season { cards.push( card( "Tentatives pour valider", diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index e089935..7280e8a 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -28,10 +28,13 @@ pub enum Msg { }, /// A refresh ended. Refreshed(Status), - /// Statistics for a requested scope were computed. + /// Statistics for a requested scope were computed, with those of the home's own scope when it + /// differs (`home`: none when it does not). Statistics { generation: u64, stats: Result, + // Boxed: the enum is as large as its largest message. + home: Option>>, stored: Option, }, /// A worker thread panicked. @@ -226,32 +229,44 @@ pub fn spawn_refresh(tracker: Arc, tx: Sender) { }); } -/// Computes the statistics of `puuid` for `scope` on a below-normal worker. +/// The statistics of `puuid` for `scope`, with the error as the page shows it. +pub fn compute_statistics( + tracker: &Tracker, + puuid: &str, + scope: &Scope, +) -> Result { + tracker + .statistics(puuid, scope) + .map_err(|e| format!("Statistiques indisponibles : {e}")) +} + +/// Computes the statistics of `puuid` for `scope`, and for `home_scope` when it differs, on a +/// below-normal worker: one job, so the page has one result to wait for. pub fn spawn_statistics( tracker: Arc, puuid: String, scope: Scope, + home_scope: Option, generation: u64, tx: Sender, ) { spawn_guarded(tx, Msg::Crashed, move |tx| { // A panic is reported as this job's result, not as `Crashed`: the page's statistics job // must end with a result whatever happens, and a crash banner is for the other workers. - let (stats, stored) = catch_unwind(AssertUnwindSafe(|| { - let stats = tracker - .statistics(&puuid, &scope) - .map_err(|e| format!("Statistiques indisponibles : {e}")); - (stats, tracker.match_count(&puuid).ok()) + let apart = home_scope.is_some(); + let (stats, home, stored) = catch_unwind(AssertUnwindSafe(|| { + let stats = compute_statistics(&tracker, &puuid, &scope); + let home = home_scope.map(|home| Box::new(compute_statistics(&tracker, &puuid, &home))); + (stats, home, tracker.match_count(&puuid).ok()) })) .unwrap_or_else(|_| { - ( - Err("Statistiques indisponibles : erreur interne".into()), - None, - ) + let error = || "Statistiques indisponibles : erreur interne".to_string(); + (Err(error()), apart.then(|| Box::new(Err(error()))), None) }); let _ = tx.try_send(Msg::Statistics { generation, stats, + home, stored, }); }); @@ -300,6 +315,7 @@ mod tests { season: SeasonScope::AllSeasons, format: None, }, + None, 42, tx.clone(), ); @@ -308,28 +324,57 @@ mod tests { Ok(Msg::Statistics { generation: 42, stats: Ok(stats), + home: None, stored: Some(0), }) if stats.rows.is_empty() && stats.challenge.is_none() )); spawn_statistics( - tracker, + tracker.clone(), "account".into(), Scope { season: SeasonScope::Season("missing".into()), format: None, }, + None, 43, - tx, + tx.clone(), ); assert!(matches!( gpui_kit::block_on(rx.recv()), Ok(Msg::Statistics { generation: 43, stats: Err(error), + home: None, stored: Some(0), }) if error.starts_with("Statistiques indisponibles : ") )); + + // A home scope of its own is computed by the same job, and fails on its own. + let missing = |season: &str| Scope { + season: SeasonScope::Season(season.into()), + format: None, + }; + spawn_statistics( + tracker, + "account".into(), + Scope { + season: SeasonScope::AllSeasons, + format: None, + }, + Some(missing("missing")), + 44, + tx, + ); + assert!(matches!( + gpui_kit::block_on(rx.recv()), + Ok(Msg::Statistics { + generation: 44, + stats: Ok(_), + home: Some(home), + stored: Some(0), + }) if home.is_err() + )); } #[test]