Files
arena-tracker/crates/app/src/page/statistics.rs
T
nessarandClaude Opus 5.5 e7ff365069
CI / core (pull_request) Successful in 1m34s
CI / core (push) Successful in 1m35s
Settle names and module homes after third review (#103)
- Rename CardPosition/CardPositions/positions() to DrawnCard/DrawnCards/
  drawn_cards(): "position" is a word CONTEXT.md avoids for Placement.
- Move the Account and status queries from page/statistics/scope.rs to
  page/displayed.rs, since the whole page uses them.
- Move the home's own statistics state (settle_home_scope, set_home_result,
  forget_home, home_is_current) to page/home/data.rs, leaving home.rs to
  queries and rendering.
- Move the profiling flag shown() from display.rs to page/profiling.rs.
- Narrow Page::new to pub(crate), and restore the domain phrase in the
  same_riot_id doc comment and the page.rs module doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:16:00 +01:00

395 lines
13 KiB
Rust

//! The « Statistiques » tab: the analysis of one Account, Season and Format.
mod data;
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 _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{Page, shown};
use crate::text::{decimal, official_note};
use crate::theme::{heading, surface};
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<String>,
theme: &Theme,
) -> impl IntoElement {
div()
.v_flex()
.flex_1()
.gap_1()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(label),
)
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
.children(note.map(|note| {
div()
.text_xs()
.text_color(theme.muted_foreground)
.child(note)
}))
}
fn challenge_tiles(
c: &ChallengeSummary,
official: Option<&ProgressCheck>,
theme: &Theme,
) -> 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,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), None, theme))
.child(tile("Tentatives par champion validé", average, None, theme))
.child(tile(
"Du premier coup",
c.first_tries.to_string(),
None,
theme,
))
}
/// A titled card holding a chart, or `empty` in its place.
fn card(
title: Div,
chart: Option<AnyElement>,
empty: &'static str,
theme: &Theme,
) -> impl IntoElement {
let body = chart.unwrap_or_else(|| {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(theme.muted_foreground)
.child(empty)
.into_any_element()
});
div()
.v_flex()
.flex_1()
.min_w_0()
.h_full()
.gap_2()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(title.text_sm())
.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(in crate::page) struct ChartsRow {
/// Empty when there are no statistics.
charts: Charts,
in_season: bool,
/// Guards the cache in tests.
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl ChartsRow {
pub(in crate::page) 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(in crate::page) fn set(
&mut self,
charts: Option<&Charts>,
in_season: bool,
cx: &mut Context<Self>,
) {
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<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let theme = cx.theme();
let charts = &self.charts;
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(
heading(cx).child("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é",
theme,
)
.into_any_element(),
);
}
cards.push(
card(
heading(cx).child("Répartition des Placements"),
if shown("placements") {
placements_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
NO_MATCH,
theme,
)
.into_any_element(),
);
if self.in_season {
cards.push(
card(
heading(cx).child("Tentatives pour valider"),
if shown("attempts") {
attempts_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
theme,
)
.into_any_element(),
);
}
div().h_flex().size_full().gap_3().children(cards)
}
}
fn placements_chart(charts: &Charts) -> Option<AnyElement> {
(!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<AnyElement> {
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<AnyElement> {
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.
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(in crate::page) fn statistics_content(&self, cx: &mut Context<Page>) -> Vec<AnyElement> {
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();
// The Season and Format only exist where they are analysed: with the title, under the
// transition's veil, so the header does not change while the screen leaving is visible.
content.push(
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_3()
.when(shown("statistics-title"), |row| {
row.child(heading(cx).text_3xl().child("Statistiques"))
})
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.children(self.statistics_selectors()),
)
.into_any_element(),
);
if shown("tiles")
&& let Some(c) = challenge
{
content.push(challenge_tiles(c, self.official(), cx.theme()).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")
.pill()
.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.))
// A cached view, laid out by the space the page gives it: the veil of a
// transition, which draws the page again at each frame, does not draw it.
.child(
self.table
.clone()
.cached(StyleRefinement::default().size_full()),
)
.into_any_element(),
);
}
content
}
}