Files
arena-tracker/crates/app/src/stats_page.rs
T
nessarandClaude Sonnet 5.5 3edfa629d4
CI / core (pull_request) Successful in 1m9s
CI / core (push) Successful in 36s
Search the champion table by name and known aliases (#18)
A search field above the table filters the rows as the user types, with the
state filter and the sort kept. A row matches when the normalized query (case,
accents, spaces and punctuation ignored) is part of its name or Data Dragon id,
or equals one of its aliases exactly. The aliases come from the U.GG and
Liquipedia inventory researched for the ticket and are stored locally by
Data Dragon id.

Not measured yet against the rule #1 budgets (release build, reference machine).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 23:34:11 +01:00

1149 lines
41 KiB
Rust

//! The statistics page: banners, Challenge header, charts and champion table for one Account.
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::StyledExt as _;
use gpui_kit::component::alert::Alert;
use gpui_kit::component::button::Button;
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::input::{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 _, Disableable as _, IndexPath, Sizable as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line};
use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics};
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);
/// Hides page parts for issue #27 measurements only with `--features profile`.
#[inline]
pub fn shown(part: &str) -> bool {
#[cfg(feature = "profile")]
{
static HIDDEN: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
!HIDDEN
.get_or_init(|| {
std::env::var("ARENA_TRACKER_HIDE")
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.map(str::to_owned)
.collect()
})
.iter()
.any(|hidden| hidden == part)
}
#[cfg(not(feature = "profile"))]
{
let _ = part;
true
}
}
pub enum PageEvent {
OpenSettings,
}
/// One Account in the selector; its value is the puuid.
#[derive(Clone, PartialEq)]
struct AccountItem {
puuid: String,
title: SharedString,
}
impl SelectItem for AccountItem {
type Value = String;
fn title(&self) -> SharedString {
self.title.clone()
}
fn value(&self) -> &String {
&self.puuid
}
}
pub struct StatsPage {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
pinned: Option<String>,
/// The Account of the last requested statistics.
shown: Option<String>,
progress: Option<SyncProgress>,
refresh: RefreshGate,
stats_job: RefreshGate,
stats_generation: u64,
/// Until the follower's first round ends.
pending_round: bool,
crashed: bool,
last_reload: Instant,
current_season: Option<String>,
season: SeasonScope,
format: Option<Format>,
filter: StateFilter,
/// Kept and reapplied whenever the table's rows are rebuilt.
search: ChampionSearch,
search_input: Entity<InputState>,
stats: Option<Statistics>,
stats_error: Option<String>,
stored: Option<usize>,
account_select: Entity<SelectState<Vec<AccountItem>>>,
account_items: Vec<AccountItem>,
season_select: Entity<SelectState<Vec<SharedString>>>,
format_select: Entity<SelectState<Vec<SharedString>>>,
format_names: Vec<SharedString>,
charts: Entity<ChartsRow>,
table: Entity<ChampionTable>,
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
impl EventEmitter<PageEvent> for StatsPage {}
/// 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 StatsPage {
/// `following`: a follower thread is already running, its first round is pending.
pub fn new(
tracker: Arc<Tracker>,
notice: Option<String>,
following: bool,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
.rev()
.map(|s| s.name.into())
.chain([ALL_SEASONS.into()])
.collect();
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let current_season = tracker.current_season(now_ms).map(|s| s.name);
let season = current_season
.clone()
.map_or(SeasonScope::AllSeasons, SeasonScope::Season);
let selected = match &season {
SeasonScope::Season(name) => seasons.iter().position(|s| s.as_ref() == name.as_str()),
SeasonScope::AllSeasons => Some(seasons.len() - 1),
};
let account_select =
cx.new(|cx| SelectState::new(Vec::<AccountItem>::new(), None, window, cx));
let season_select =
cx.new(|cx| SelectState::new(seasons, selected.map(IndexPath::new), window, cx));
let format_names = vec![SharedString::from(ALL_FORMATS)];
let format_select = cx
.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 un champion"));
let charts = cx.new(|_| ChartsRow::new());
let table = cx.new(|_| ChampionTable::new());
let subscriptions = vec![
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.search = ChampionSearch::new(&input.read(cx).value());
this.refresh_table(cx);
}
}),
cx.subscribe_in(
&account_select,
window,
|this, _, event: &SelectEvent<Vec<AccountItem>>, window, cx| {
let SelectEvent::Confirm(Some(puuid)) = event else {
return;
};
// Picking the Account being updated is following it again.
let following = this
.status
.updating
.as_ref()
.is_some_and(|a| a.puuid == *puuid);
this.pinned = (!following).then(|| puuid.clone());
this.reload(window, cx);
},
),
cx.subscribe_in(
&season_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
this.season = if name.as_ref() == ALL_SEASONS {
SeasonScope::AllSeasons
} else {
SeasonScope::Season(name.to_string())
};
this.recompute(window, cx);
},
),
cx.subscribe_in(
&format_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
let formats = this.stats.iter().flat_map(|s| s.formats.iter());
this.format = formats.copied().find(|f| f.name() == name.as_ref());
this.recompute(window, cx);
},
),
];
// gpui-kit's async channel wakes the page on sends, with no timer or extra dependency.
let listener = cx.spawn_in(window, async move |this, cx| {
while let Ok(msg) = rx.recv().await {
let applied = cx
.update(|window, app| this.update(app, |page, cx| page.apply(msg, window, cx)));
// The window or the page is gone: nothing left to update.
if !matches!(applied, Ok(Ok(()))) {
return;
}
}
});
let mut page = StatsPage {
status: tracker.status(),
tracker,
tx,
notice,
accounts: Vec::new(),
last_active: None,
pinned: None,
shown: None,
progress: None,
refresh: RefreshGate::default(),
stats_job: RefreshGate::default(),
stats_generation: 0,
pending_round: following,
crashed: false,
last_reload: Instant::now(),
current_season,
season,
format: None,
filter: StateFilter::All,
search: ChampionSearch::new(""),
search_input,
stats: None,
stats_error: None,
stored: None,
account_select,
account_items: Vec::new(),
season_select,
format_select,
format_names,
charts,
table,
_subscriptions: subscriptions,
_listener: listener,
};
page.reload(window, cx);
page
}
/// The follower thread was just started.
pub fn following(&mut self, cx: &mut Context<Self>) {
self.pending_round = true;
cx.notify();
}
/// Starts a refresh, or queues one behind the refresh already running.
pub fn begin_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
cx.notify();
}
fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
/// Whether one Season is selected, rather than all of them: only a Season has a Challenge.
fn in_season(&self) -> bool {
matches!(self.season, SeasonScope::Season(_))
}
/// The Account shown: the pinned one, else the one being updated.
fn viewed(&self) -> Option<&Account> {
self.pinned
.as_ref()
.and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid))
.or(self.status.updating.as_ref())
.or(self.last_active.as_ref())
.or(self.accounts.first())
}
/// Whether the Account shown is not the one being updated (or none is), so only stored
/// data is shown. Unknown until the follower's first round has reported.
fn stale(&self) -> bool {
!self.pending_round
&& self.viewed().is_some_and(|viewed| {
self.status
.updating
.as_ref()
.is_none_or(|updating| updating.puuid != viewed.puuid)
})
}
/// The game's own count, only meaningful for the Account being updated in the current 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);
(updated && current).then_some(&self.status.official_progress)
}
fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context<Self>) {
match msg {
Msg::Progress(progress) => {
self.progress = Some(progress);
if self.last_reload.elapsed() >= RELOAD_EVERY {
self.reload_in_background(window, cx);
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::Round { status, reload } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
let unchanged = status == self.status
&& !reload
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed;
if unchanged {
return;
}
self.status = status;
self.pending_round = false;
self.progress = None;
self.crashed = false;
if reload {
self.reload_in_background(window, cx);
}
}
Msg::Refreshed(status) => {
self.status = status;
self.progress = None;
self.crashed = false;
self.reload_in_background(window, cx);
// A request made while this one ran (a key saved meanwhile) is served now.
if self.refresh.finished() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
}
Msg::Statistics {
generation,
stats,
stored,
} => {
if generation == self.stats_generation {
self.stats_error = stats.as_ref().err().cloned();
self.stats = stats.ok();
self.stored = stored;
self.show_statistics(window, cx);
}
if self.stats_job.finished() {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => {
self.refresh.reset();
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
}
cx.notify();
}
/// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
/// visible nor a hidden window waits for them (rule #1).
fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reload_accounts(window, cx);
let start_job = self.stats_job.request();
self.recompute_in_background(start_job, window, cx);
}
/// Re-reads the Accounts, then the statistics of the one shown.
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reload_accounts(window, cx);
self.recompute(window, cx);
}
/// Re-reads the Accounts and selects the one shown.
fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.accounts = self.tracker.accounts().unwrap_or_default();
self.last_active = self.tracker.last_active_account().ok().flatten();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
let items: Vec<AccountItem> = self
.accounts
.iter()
.map(|a| AccountItem {
puuid: a.puuid.clone(),
title: riot_id(a).into(),
})
.collect();
let changed = items != self.account_items;
self.account_items = items.clone();
let viewed = self.viewed().map(|a| a.puuid.clone());
self.account_select.update(cx, |select, cx| {
if changed {
select.set_items(items, window, cx);
}
if let Some(puuid) = &viewed
&& select.selected_value() != Some(puuid)
{
select.set_selected_value(puuid, window, cx);
}
});
}
/// Settles the scope of the next statistics. Earlier results become stale when they are
/// computed again (`computing`) or when the viewed Account changed; a request merely queued
/// behind a running job keeps that job's result for the same scope.
fn prepare_statistics(
&mut self,
computing: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
self.filter = StateFilter::All;
}
let viewed = self.viewed().map(|a| a.puuid.clone());
if computing || viewed != self.shown {
self.stats_generation += 1;
}
if viewed != self.shown {
// Another Account may not have played the selected Format.
self.shown = viewed.clone();
if self.format.take().is_some() {
self.format_select.update(cx, |select, cx| {
select.set_selected_index(Some(IndexPath::new(0)), window, cx)
});
}
}
viewed
}
/// Requests the statistics from a worker (`start_job`: none is running), or shows none when no
/// Account is viewed.
fn recompute_in_background(
&mut self,
start_job: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let viewed = self.prepare_statistics(start_job, window, cx);
if let Some(puuid) = viewed {
if start_job {
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
puuid,
scope,
self.stats_generation,
self.tx.clone(),
);
}
} else {
if start_job {
self.stats_job.reset();
}
self.stats = None;
self.stats_error = None;
self.stored = None;
self.show_statistics(window, cx);
}
}
/// Recomputes the statistics for the current scope; never called while rendering.
fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let viewed = self.prepare_statistics(true, window, cx);
self.stats = None;
self.stats_error = None;
self.stored = None;
if let Some(puuid) = &viewed {
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
match self.tracker.statistics(puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")),
}
self.stored = self.tracker.match_count(puuid).ok();
}
self.show_statistics(window, cx);
}
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
self.charts
.update(cx, |row, cx| row.set(charts, in_season, cx));
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
.iter()
.flat_map(|s| s.formats.iter().map(|f| SharedString::from(f.name()))),
);
if names != self.format_names {
self.format_names = names.clone();
self.format_select
.update(cx, |select, cx| select.set_items(names, window, cx));
}
self.refresh_table(cx);
cx.notify();
}
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
});
}
/// One line each, the most important first; the stored data stays visible under all.
fn banners(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
if let Some(problem) = &self.status.problem {
let message = problem.message();
banners.push(match problem {
UpdateProblem::MatchPending
| UpdateProblem::RateLimited
| UpdateProblem::NoAccount => Alert::warning("problem", message),
_ => Alert::error("problem", message),
});
}
if let Some(ProgressCheck::Differs { app, official }) = self.official() {
banners.push(Alert::warning(
"official",
official_differs(*app, *official),
));
}
if !self.pending_round && !self.status.client_running {
banners.push(Alert::info("client", CLIENT_ABSENT));
}
if let Some(notice) = &self.notice {
banners.push(Alert::warning("notice", notice.clone()));
}
if let Some(error) = &self.stats_error {
banners.push(Alert::error("stats", error.clone()));
}
banners
.into_iter()
.map(|alert| alert.small().into_any_element())
.collect()
}
}
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`.
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<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 Render for StatsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
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 busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
div()
.v_flex()
.size_full()
.gap_3()
.p_3()
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the buttons
// wrap onto a second line: nothing is ever clipped.
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.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.)),
),
)
.child(
div()
.h_flex()
.items_center()
.gap_3()
.flex_shrink_0()
.child(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
)
.child(
Button::new("refresh")
.label("Actualiser")
.disabled(busy)
.on_click(
cx.listener(|this, _, _, cx| this.begin_refresh(cx)),
),
)
.child(Button::new("settings").label("Paramètres").on_click(
cx.listener(|_, _, _, cx| cx.emit(PageEvent::OpenSettings)),
)),
),
)
})
.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()))
})
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Charts, RiotApi, 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,
};
use super::StatsPage;
use crate::champion_table::tests::row;
fn open_page(cx: &mut TestAppContext) -> (Entity<StatsPage>, VisualTestContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
let bounds = Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
};
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
};
gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| StatsPage::new(tracker, None, false, rx, tx, window, cx))
})
.unwrap()
});
(page, VisualTestContext::from_window(window, cx))
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
..row(name)
};
page.update(cx, |page, _| {
page.stats = Some(Statistics {
challenge: None,
rows: vec![
ChampionRow {
state: Some(ChampionState::Completed),
..champion(4, "TwistedFate", "Twisted Fate")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
..champion(86, "Garen", "Garen")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
matches: 5,
..champion(107, "Rengar", "Rengar")
},
],
charts: Charts {
placements: Vec::new(),
completed_over_time: Vec::new(),
attempts_to_complete: [0; 5],
},
formats: Vec::new(),
});
});
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)));
cx.simulate_input("ren");
assert_eq!(names(cx), ["Rengar", "Garen"]);
// The clear button's own path: it empties the field and the table follows.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(names(cx).len(), 3);
cx.simulate_input("TF");
assert_eq!(names(cx), ["Twisted Fate"]);
cx.simulate_input("z");
assert!(names(cx).is_empty());
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input(" ");
assert_eq!(names(cx).len(), 3);
// Combined with a state filter, the table keeps its sort (most Matches first).
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input("ren");
page.update(cx, |page, cx| {
page.filter = StateFilter::Completed;
page.refresh_table(cx);
});
assert!(names(cx).is_empty());
page.update(cx, |page, cx| {
page.filter = StateFilter::NeverPlayed;
page.refresh_table(cx);
});
assert_eq!(names(cx), ["Rengar", "Garen"]);
}
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { 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.
table.update(cx, |table, cx| {
let rows = (1..=20).map(|n| row(&format!("Champion {n}")));
table.set_rows(rows.collect(), false);
cx.notify();
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let renders = charts.read_with(cx, |charts, _| charts.renders);
assert!(renders > 0);
// A row's hover style notifies the table, which redraws the page.
let hovers = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let hovers = hovers.clone();
cx.observe(&table, move |_, _| hovers.set(hovers.get() + 1))
});
for y in [700., 740.] {
cx.simulate_mouse_move(point(px(300.), px(y)), None, Modifiers::none());
cx.update(|window, cx| window.draw(cx).clear(cx));
}
assert!(hovers.get() > 0, "no row was hovered");
assert_eq!(charts.read_with(cx, |charts, _| charts.renders), renders);
// The count does move when the charts change.
charts.update(cx, |_, cx| cx.notify());
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(
charts.read_with(cx, |charts, _| charts.renders),
renders + 1
);
}
}