diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index 7fa27d8..cf8dc13 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -4,31 +4,28 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ - Account, ChallengeSummary, ChampSelect, ChampionRow, ChampionSearch, Charts, Format, - ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, - UpdateProblem, account_riot_id, same_riot_id, + Account, ChampSelect, ChampionRow, ChampionSearch, Format, ProgressCheck, Scope, SeasonScope, + StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, account_riot_id, + same_riot_id, }; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; use gpui_kit::component::alert::Alert; -use gpui_kit::component::chart::{AreaChart, BarChart}; -use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::component::input::{InputEvent, InputState}; use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState}; -use gpui_kit::component::tab::{Tab, TabBar}; use gpui_kit::component::{ActiveTheme as _, IndexPath, Sizable as _}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; +mod statistics; + use crate::champion_table::ChampionTable; -use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, sync_line}; +use crate::text::{CLIENT_ABSENT, official_differs, sync_line}; use crate::worker::{LiveChampSelect, Msg, RefreshGate, spawn_refresh, spawn_statistics}; +use statistics::ChartsRow; const ALL_SEASONS: &str = "Toutes les Saisons"; const ALL_FORMATS: &str = "Tous les Formats"; -const NO_MATCH: &str = "Aucune Partie"; -/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves -/// each chart 150 px: change them together. -const CHARTS_HEIGHT: f32 = 206.; /// While an import runs, the page is recomputed at most this often. const RELOAD_EVERY: Duration = Duration::from_secs(1); @@ -142,21 +139,6 @@ pub struct Page { _listener: Task<()>, } -/// The state filters on offer: the Challenge ones only make sense in a Season. -fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] { - const SEASON: [(&str, StateFilter); 4] = [ - ("Tous", StateFilter::All), - ("Validés", StateFilter::Completed), - ("Restants", StateFilter::Remaining), - ("Jamais joués", StateFilter::NeverPlayed), - ]; - if in_season { - &SEASON - } else { - &[SEASON[0], SEASON[3]] - } -} - impl Page { /// `following`: a follower thread is already running, its first round is pending. pub fn new( @@ -844,278 +826,12 @@ fn champion_label(row: Option<&ChampionRow>, id: u32) -> String { row.map_or_else(|| format!("Champion {id}"), |row| row.champion.name.clone()) } -fn tile( - label: &'static str, - value: String, - note: Option, - border: Hsla, - muted: Hsla, -) -> impl IntoElement { - div() - .v_flex() - .flex_1() - .gap_1() - .p_3() - .border_1() - .border_color(border) - .rounded_md() - .child(div().text_sm().text_color(muted).child(label)) - .child( - div() - .text_xl() - .font_weight(FontWeight::SEMIBOLD) - .child(value), - ) - .children(note.map(|note| div().text_xs().text_color(muted).child(note))) -} - -fn challenge_tiles( - c: &ChallengeSummary, - official: Option<&ProgressCheck>, - border: Hsla, - muted: Hsla, -) -> impl IntoElement { - let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2)); - // Next to the count whether the app agrees or not; the banner covers the difference. - let note = match official { - Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => { - Some(official_note(*n)) - } - _ => None, - }; - div() - .h_flex() - .gap_3() - .child(tile( - "Champions validés", - format!("{} / {}", c.completed, c.total), - note, - border, - muted, - )) - .child(tile( - "Tentatives", - c.attempts.to_string(), - None, - border, - muted, - )) - .child(tile( - "Tentatives par champion validé", - average, - None, - border, - muted, - )) - .child(tile( - "Du premier coup", - c.first_tries.to_string(), - None, - border, - muted, - )) -} - -/// A titled card holding a chart, or `empty` in its place. -fn card( - title: &'static str, - chart: Option, - empty: &'static str, - border: Hsla, - muted: Hsla, -) -> impl IntoElement { - let body = chart.unwrap_or_else(|| { - div() - .size_full() - .flex() - .items_center() - .justify_center() - .text_color(muted) - .child(empty) - .into_any_element() - }); - div() - .v_flex() - .flex_1() - .min_w_0() - .h_full() - .gap_2() - .p_3() - .border_1() - .border_color(border) - .rounded_md() - .child( - div() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) - .child(title), - ) - .child(div().flex_1().min_h_0().w_full().children(Some(body))) -} - -/// The charts, a cached view: hovering the table, which redraws the page, does not draw them -/// again (#31). The page updates it from `show_statistics`. -struct ChartsRow { - /// Empty when there are no statistics. - charts: Charts, - in_season: bool, - /// Guards the cache in tests. - #[cfg(test)] - renders: usize, -} - -impl ChartsRow { - fn new() -> ChartsRow { - ChartsRow { - charts: Charts { - placements: vec![], - completed_over_time: vec![], - attempts_to_complete: [0; 5], - }, - in_season: false, - #[cfg(test)] - renders: 0, - } - } - - /// Shows `charts`, or none; drawing them again only when they changed, since reloads keep - /// coming during an import. - fn set(&mut self, charts: Option<&Charts>, in_season: bool, cx: &mut Context) { - let charts = charts.cloned().unwrap_or_else(|| ChartsRow::new().charts); - if (&self.charts, self.in_season) != (&charts, in_season) { - self.charts = charts; - self.in_season = in_season; - cx.notify(); - } - } -} - -impl Render for ChartsRow { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - #[cfg(test)] - { - self.renders += 1; - } - let (border, muted) = { - let theme = cx.theme(); - (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(), - ]; - if self.in_season { - cards.push( - card( - "Champions validés au fil de la Saison", - if shown("completed") { - completed_chart(charts) - } else { - Some(div().size_full().into_any_element()) - }, - "Aucun champion validé", - border, - muted, - ) - .into_any_element(), - ); - cards.push( - card( - "Tentatives pour valider", - if shown("attempts") { - attempts_chart(charts) - } else { - Some(div().size_full().into_any_element()) - }, - "Aucun champion validé", - border, - muted, - ) - .into_any_element(), - ); - } - div().h_flex().size_full().gap_3().children(cards) - } -} - -fn placements_chart(charts: &Charts) -> Option { - (!charts.placements.is_empty()).then(|| { - BarChart::new(charts.placements.clone()) - .id("placements") - .band(|(placement, _)| placement.to_string()) - .value(|(_, count)| *count as f64) - .label(|(_, count)| count.to_string()) - .name("Parties") - .into_any_element() - }) -} - -fn completed_chart(charts: &Charts) -> Option { - let points: Vec<(String, f64)> = charts - .completed_over_time - .iter() - .map(|(day, count)| (day.to_string(), *count as f64)) - .collect(); - // The counts only grow, so the last one is the highest. The y axis runs from 0 to a - // multiple of 4 in four steps with no padding: every tick is then a whole number. - let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n); - let top = top.div_ceil(4).max(1) * 4; - (!points.is_empty()).then(|| { - AreaChart::new(points) - .id("completed") - .x(|(day, _)| day.clone()) - .y(|(_, count)| *count) - .linear() - .x_tick_count(3) - .y_axis(true) - .y_domain(0., top as f64) - .y_padding(0., 0.) - .y_tick_count(5) - .name("Champions validés") - .into_any_element() - }) -} - -fn attempts_chart(charts: &Charts) -> Option { - const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"]; - let bars: Vec<(&str, usize)> = LABELS - .into_iter() - .zip(charts.attempts_to_complete) - .collect(); - bars.iter().any(|(_, count)| *count > 0).then(|| { - BarChart::new(bars) - .id("attempts") - .band(|(label, _)| *label) - .value(|(_, count)| *count as f64) - .label(|(_, count)| count.to_string()) - .name("Champions") - .into_any_element() - }) -} - impl Render for Page { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let (border, muted) = { - let theme = cx.theme(); - (theme.border, theme.muted_foreground) - }; + let muted = cx.theme().muted_foreground; if self.in_champ_select() { return self.champ_select_view(cx); } - let options = filters(self.in_season()); - let selected = options.iter().position(|(_, f)| *f == self.filter); - let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref()); let busy = self.busy(); let status_line = sync_line(busy, self.progress, self.crashed, self.stored); @@ -1155,18 +871,7 @@ impl Render for Page { .text_color(muted) .child("Non mis à jour") })) - .child( - Select::new(&self.season_select) - .id("season") - .w(px(220.)) - .min_w(px(130.)), - ) - .child( - Select::new(&self.format_select) - .id("format") - .w(px(220.)) - .min_w(px(130.)), - ), + .children(self.statistics_selectors()), ) .child( div().h_flex().items_center().gap_3().flex_shrink_0().child( @@ -1182,45 +887,7 @@ impl Render for Page { .when(shown("banners"), |page| { page.child(div().v_flex().gap_1().children(self.banners())) }) - .when(shown("tiles"), |page| { - page.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted))) - }) - .child( - self.charts - .clone() - .cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT))), - ) - .when(shown("tabs"), |page| { - page.child( - div() - .h_flex() - .items_center() - .justify_between() - .gap_3() - .child( - TabBar::new("state-filter") - .segmented() - .selected_index(selected.unwrap_or(0)) - .children(options.iter().map(|(label, _)| Tab::new().label(*label))) - .on_click(cx.listener(|this, ix: &usize, _, cx| { - if let Some((_, filter)) = filters(this.in_season()).get(*ix) { - this.filter = *filter; - this.refresh_table(cx); - cx.notify(); - } - })), - ) - .child( - Input::new(&self.search_input) - .cleanable(true) - .w(px(260.)) - .min_w(px(150.)), - ), - ) - }) - .when(shown("table"), |page| { - page.child(div().flex_1().min_h(px(240.)).child(self.table.clone())) - }) + .children(self.statistics_content(cx)) } } diff --git a/crates/app/src/page/statistics.rs b/crates/app/src/page/statistics.rs new file mode 100644 index 0000000..81350f3 --- /dev/null +++ b/crates/app/src/page/statistics.rs @@ -0,0 +1,373 @@ +//! The « Statistiques » tab: the analysis of one Account, Season and Format. + +use arena_tracker_core::{ChallengeSummary, Charts, ProgressCheck, StateFilter}; +use gpui_kit::component::chart::{AreaChart, BarChart}; +use gpui_kit::component::input::Input; +use gpui_kit::component::select::Select; +use gpui_kit::component::tab::{Tab, TabBar}; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::*; + +use super::{Page, shown}; +use crate::text::{decimal, official_note}; + +const NO_MATCH: &str = "Aucune Partie"; + +/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves +/// each chart 150 px: change them together. +const CHARTS_HEIGHT: f32 = 206.; + +/// The state filters on offer: the Challenge ones only make sense in a Season. +fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] { + const SEASON: [(&str, StateFilter); 4] = [ + ("Tous", StateFilter::All), + ("Validés", StateFilter::Completed), + ("Restants", StateFilter::Remaining), + ("Jamais joués", StateFilter::NeverPlayed), + ]; + if in_season { + &SEASON + } else { + &[SEASON[0], SEASON[3]] + } +} + +fn tile( + label: &'static str, + value: String, + note: Option, + border: Hsla, + muted: Hsla, +) -> impl IntoElement { + div() + .v_flex() + .flex_1() + .gap_1() + .p_3() + .border_1() + .border_color(border) + .rounded_md() + .child(div().text_sm().text_color(muted).child(label)) + .child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child(value), + ) + .children(note.map(|note| div().text_xs().text_color(muted).child(note))) +} + +fn challenge_tiles( + c: &ChallengeSummary, + official: Option<&ProgressCheck>, + border: Hsla, + muted: Hsla, +) -> impl IntoElement { + let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2)); + // Next to the count whether the app agrees or not; the banner covers the difference. + let note = match official { + Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => { + Some(official_note(*n)) + } + _ => None, + }; + div() + .h_flex() + .gap_3() + .child(tile( + "Champions validés", + format!("{} / {}", c.completed, c.total), + note, + border, + muted, + )) + .child(tile( + "Tentatives", + c.attempts.to_string(), + None, + border, + muted, + )) + .child(tile( + "Tentatives par champion validé", + average, + None, + border, + muted, + )) + .child(tile( + "Du premier coup", + c.first_tries.to_string(), + None, + border, + muted, + )) +} + +/// A titled card holding a chart, or `empty` in its place. +fn card( + title: &'static str, + chart: Option, + empty: &'static str, + border: Hsla, + muted: Hsla, +) -> impl IntoElement { + let body = chart.unwrap_or_else(|| { + div() + .size_full() + .flex() + .items_center() + .justify_center() + .text_color(muted) + .child(empty) + .into_any_element() + }); + div() + .v_flex() + .flex_1() + .min_w_0() + .h_full() + .gap_2() + .p_3() + .border_1() + .border_color(border) + .rounded_md() + .child( + div() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ) + .child(div().flex_1().min_h_0().w_full().children(Some(body))) +} + +/// The charts, a cached view: hovering the table, which redraws the page, does not draw them +/// again (#31). The page updates it from `show_statistics`. +pub(super) struct ChartsRow { + /// Empty when there are no statistics. + charts: Charts, + in_season: bool, + /// Guards the cache in tests. + #[cfg(test)] + pub(super) renders: usize, +} + +impl ChartsRow { + pub(super) fn new() -> ChartsRow { + ChartsRow { + charts: Charts { + placements: vec![], + completed_over_time: vec![], + attempts_to_complete: [0; 5], + }, + in_season: false, + #[cfg(test)] + renders: 0, + } + } + + /// Shows `charts`, or none; drawing them again only when they changed, since reloads keep + /// coming during an import. + pub(super) fn set(&mut self, charts: Option<&Charts>, in_season: bool, cx: &mut Context) { + let charts = charts.cloned().unwrap_or_else(|| ChartsRow::new().charts); + if (&self.charts, self.in_season) != (&charts, in_season) { + self.charts = charts; + self.in_season = in_season; + cx.notify(); + } + } +} + +impl Render for ChartsRow { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + #[cfg(test)] + { + self.renders += 1; + } + let (border, muted) = { + let theme = cx.theme(); + (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(), + ]; + if self.in_season { + cards.push( + card( + "Champions validés au fil de la Saison", + if shown("completed") { + completed_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, + "Aucun champion validé", + border, + muted, + ) + .into_any_element(), + ); + cards.push( + card( + "Tentatives pour valider", + if shown("attempts") { + attempts_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, + "Aucun champion validé", + border, + muted, + ) + .into_any_element(), + ); + } + div().h_flex().size_full().gap_3().children(cards) + } +} + +fn placements_chart(charts: &Charts) -> Option { + (!charts.placements.is_empty()).then(|| { + BarChart::new(charts.placements.clone()) + .id("placements") + .band(|(placement, _)| placement.to_string()) + .value(|(_, count)| *count as f64) + .label(|(_, count)| count.to_string()) + .name("Parties") + .into_any_element() + }) +} + +fn completed_chart(charts: &Charts) -> Option { + let points: Vec<(String, f64)> = charts + .completed_over_time + .iter() + .map(|(day, count)| (day.to_string(), *count as f64)) + .collect(); + // The counts only grow, so the last one is the highest. The y axis runs from 0 to a + // multiple of 4 in four steps with no padding: every tick is then a whole number. + let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n); + let top = top.div_ceil(4).max(1) * 4; + (!points.is_empty()).then(|| { + AreaChart::new(points) + .id("completed") + .x(|(day, _)| day.clone()) + .y(|(_, count)| *count) + .linear() + .x_tick_count(3) + .y_axis(true) + .y_domain(0., top as f64) + .y_padding(0., 0.) + .y_tick_count(5) + .name("Champions validés") + .into_any_element() + }) +} + +fn attempts_chart(charts: &Charts) -> Option { + const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"]; + let bars: Vec<(&str, usize)> = LABELS + .into_iter() + .zip(charts.attempts_to_complete) + .collect(); + bars.iter().any(|(_, count)| *count > 0).then(|| { + BarChart::new(bars) + .id("attempts") + .band(|(label, _)| *label) + .value(|(_, count)| *count as f64) + .label(|(_, count)| count.to_string()) + .name("Champions") + .into_any_element() + }) +} + +impl Page { + /// The Season and Format selectors, which only the statistics have. + pub(super) fn statistics_selectors(&self) -> [AnyElement; 2] { + [ + Select::new(&self.season_select) + .id("season") + .w(px(220.)) + .min_w(px(130.)) + .into_any_element(), + Select::new(&self.format_select) + .id("format") + .w(px(220.)) + .min_w(px(130.)) + .into_any_element(), + ] + } + + /// Under the banners: the Challenge tiles, the charts, the filters and the table. + pub(super) fn statistics_content(&self, cx: &mut Context) -> Vec { + let (border, muted) = { + let theme = cx.theme(); + (theme.border, theme.muted_foreground) + }; + let options = filters(self.in_season()); + let selected = options.iter().position(|(_, f)| *f == self.filter); + let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref()); + let mut content = Vec::new(); + if shown("tiles") + && let Some(c) = challenge + { + content.push(challenge_tiles(c, self.official(), border, muted).into_any_element()); + } + content.push( + self.charts + .clone() + .cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT))) + .into_any_element(), + ); + if shown("tabs") { + content.push( + div() + .h_flex() + .items_center() + .justify_between() + .gap_3() + .child( + TabBar::new("state-filter") + .segmented() + .selected_index(selected.unwrap_or(0)) + .children(options.iter().map(|(label, _)| Tab::new().label(*label))) + .on_click(cx.listener(|this, ix: &usize, _, cx| { + if let Some((_, filter)) = filters(this.in_season()).get(*ix) { + this.filter = *filter; + this.refresh_table(cx); + cx.notify(); + } + })), + ) + .child( + Input::new(&self.search_input) + .cleanable(true) + .w(px(260.)) + .min_w(px(150.)), + ) + .into_any_element(), + ); + } + if shown("table") { + content.push( + div() + .flex_1() + .min_h(px(240.)) + .child(self.table.clone()) + .into_any_element(), + ); + } + content + } +}