Files
arena-tracker/crates/app/src/page/statistics.rs
T
nessarandClaude Opus 5.5 6c1a62cf6a Move the statistics rendering into page/statistics.rs (#71)
Move only, no behaviour change: the tiles, the charts row and the table
section leave the page, which keeps the shared state, the header row, the
banners and the champ select view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00

374 lines
11 KiB
Rust

//! 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<String>,
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<AnyElement>,
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<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 (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<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.
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<Page>) -> Vec<AnyElement> {
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
}
}