Files
arena-tracker/crates/app/src/page.rs
T
nessarandClaude Opus 5.5 4612d89a3d Keep a whole row in "Autres champions" and tidy the cards code (#75)
- "Autres champions" grid is never shorter than one card row.
- A Format change keeps the home's statistics (#71); the home cards
  are built when "Defi" is shown again; hidden grids give back their
  decoded portraits; the card holds its portrait as Arc<Path>.
- Unavailability becomes Unpickable (glossary), "selection" becomes
  "champ select" in comments (#74); the statistics error is shown by
  the banner only during a champ select.
- Column breakpoints follow the mockup's max-width rules, the home
  tools row is search, filters, sort; stale comments fixed.
- Tests: whole row, hidden grids, stats scopes, error shown once, and
  the capture's reasons end to end in the open section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00

3946 lines
157 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The page and its two tabs: the shared state, the header row with its navigation and the
//! banners. `home` (which also holds the champ select's sections) and `statistics` render what
//! is under the banners.
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChampSelect, ChampionRow, ChampionSearch, ChampionSort, Format, ProgressCheck, Scope,
SeasonScope, 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;
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::{ActiveTheme as _, IndexPath, Sizable as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
mod home;
mod statistics;
use crate::card::Card;
use crate::card_grid::CardGrid;
use crate::card_order::card_order;
use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, official_differs, sync_line};
use crate::worker::{
LiveChampSelect, Msg, RefreshGate, compute_statistics, spawn_refresh, spawn_statistics,
};
use statistics::ChartsRow;
/// The page's padding on every side: the card grid derives its width from it.
pub(crate) const PAGE_PADDING: f32 = 12.;
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
/// The sorts on offer, in the selector's order.
const SORTS: [(ChampionSort, &str); 2] = [
(ChampionSort::Mastery, "Maîtrise"),
(ChampionSort::Name, "A–Z"),
];
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// 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
}
}
/// 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
}
}
/// What the page starts from.
pub struct Launch {
pub notice: Option<String>,
/// A follower thread is already running, its first round is pending.
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
}
/// The page entered or left an Arena champ select.
pub struct ChampSelectTransition {
pub entered: bool,
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The player chose a sort for the cards: to be saved with the other preferences.
pub struct ChampionSortChosen(pub ChampionSort);
impl EventEmitter<ChampionSortChosen> 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<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
champ_select: LiveChampSelect,
/// The Account of `champ_select`, resolved when its Riot ID changes.
champ_select_account: Option<String>,
/// The Riot ID `champ_select_account` was resolved for.
champ_select_riot_id: Option<String>,
/// What the Anvil champions area says while the statistics are missing, else empty; prepared
/// when the champ select, the statistics or the status change.
champ_select_notice: SharedString,
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>,
/// Not persisted: the app opens on the Challenge.
tab: Tab,
/// The Season of the Statistics tab.
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>,
/// 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<SharedString>,
/// The home's scope when it differs from the Statistics tab's, else the home reads `stats`.
home_scope: Option<Scope>,
/// Only for a `home_scope`.
home_stats: Option<Statistics>,
home_error: Option<String>,
/// The Account and scope `home_stats` or `home_error` were computed for: the home does not
/// depend on the Format, so a change of Format keeps them.
home_computed: Option<(String, Scope)>,
/// « 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<InputState>,
/// The sort the player chose, saved with the preferences; `None` until one is chosen, which
/// sorts by Mastery Points.
champion_sort: Option<ChampionSort>,
sort_select: Entity<SelectState<Vec<SharedString>>>,
/// The positions of the home statistics' rows in the cards' order, which every section
/// follows. Computed again only when those statistics or the sort change (`reorder`).
order: Vec<usize>,
/// How many times `order` was computed.
#[cfg(test)]
reorders: usize,
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>,
/// The home's champions, one card each.
home_grid: Entity<CardGrid>,
/// The home's cards were not rebuilt for the latest statistics, as the home was not shown.
home_cards_stale: bool,
/// How many cards the grid shows, prepared when the filter or search change.
home_shown_count: SharedString,
/// The Anvil champions of the champ select, one card each in the home grid's order, with
/// the reasons the champ select gives. Only drawn during a champ select.
anvil_grid: Entity<CardGrid>,
/// How many Anvil champions the row shows, prepared with the cards.
anvil_count: SharedString,
/// « Autres champions »: folded at each new champ select. While it is, it holds no card.
others_open: bool,
/// Filters this section only; emptied with each new champ select.
others_search: ChampionSearch,
others_search_input: Entity<InputState>,
/// The champions without an Anvil (all of them when the list is unknown), only built while
/// the section is open: a virtualized grid, as the home's.
others_grid: Entity<CardGrid>,
/// The section's header button, which the keyboard reaches.
others_focus: FocusHandle,
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
impl Page {
pub fn new(
tracker: Arc<Tracker>,
launch: Launch,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let Launch {
notice,
following,
champion_sort,
} = launch;
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
.rev()
.map(|s| s.name.into())
.chain([ALL_SEASONS.into()])
.collect();
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 sorts: Vec<SharedString> = SORTS.iter().map(|(_, label)| (*label).into()).collect();
let chosen = SORTS
.iter()
.position(|(sort, _)| Some(*sort) == champion_sort)
.unwrap_or(0);
let sort_select =
cx.new(|cx| SelectState::new(sorts, Some(IndexPath::new(chosen)), 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_grid = cx.new(|_| CardGrid::new());
let anvil_grid = cx.new(|_| CardGrid::fit_content());
let others_search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let others_grid = cx.new(|_| CardGrid::new());
let others_focus = cx.focus_handle().tab_stop(true);
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(&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(
&others_search_input,
|this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.others_search = ChampionSearch::new(&input.read(cx).value());
this.refresh_others(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(
&sort_select,
|this, _, event: &SelectEvent<Vec<SharedString>>, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
if let Some((sort, _)) = SORTS.iter().find(|(_, label)| *label == name.as_ref())
{
this.choose_sort(*sort, 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 = Page {
status: tracker.status(),
tracker,
tx,
notice,
champ_select: None,
champ_select_account: None,
champ_select_riot_id: None,
champ_select_notice: SharedString::default(),
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,
tab: Tab::Challenge,
season,
format: None,
filter: StateFilter::All,
search: ChampionSearch::new(""),
search_input,
stats: None,
stats_error: None,
home_season: None,
home_scope: None,
home_stats: None,
home_error: None,
home_computed: None,
home_count: SharedString::default(),
home_fraction: 0.,
home_filter: StateFilter::All,
home_search: ChampionSearch::new(""),
home_search_input,
champion_sort,
sort_select,
order: Vec::new(),
#[cfg(test)]
reorders: 0,
stored: None,
account_select,
account_items: Vec::new(),
season_select,
format_select,
format_names,
charts,
table,
home_grid,
home_cards_stale: false,
home_shown_count: SharedString::default(),
anvil_grid,
anvil_count: SharedString::default(),
others_open: false,
others_search: ChampionSearch::new(""),
others_search_input,
others_grid,
others_focus,
_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 request_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
cx.notify();
}
pub 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())
}
/// The Account whose data the page shows: during a champ select the one signed in to the
/// client, whatever the pinned or followed one is, else `viewed`.
fn displayed(&self) -> Option<&Account> {
if self.in_champ_select() {
let puuid = self.champ_select_account.as_deref()?;
return self.accounts.iter().find(|a| a.puuid == puuid);
}
self.viewed()
}
/// 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.displayed().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,
/// whether the page shows it as the home's Challenge or as the selected Season.
fn official(&self) -> Option<&ProgressCheck> {
let updated = matches!((self.displayed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid);
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, window: &mut Window, cx: &mut Context<Self>) {
// The champ select takes the window: the Statistics tab waits for its end.
if tab == Tab::Statistics && self.in_champ_select() {
return;
}
if self.tab != tab {
self.tab = tab;
if tab == Tab::Statistics {
// The home grid is not shown: its portraits are given back, and come back
// with the grid.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
}
// The tab left was not kept up to date.
self.refresh_table(cx);
if self.home_cards_stale {
self.prepare_home_cards(cx);
}
self.refresh_home(cx);
cx.notify();
}
}
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::ChampSelect(champ_select) => {
if self.champ_select == champ_select {
return;
}
let previous = self.champ_select.as_ref();
let next = champ_select.as_ref();
let changed_page = previous.is_some() != next.is_some();
let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id);
self.champ_select = champ_select;
if changed_page {
if self.in_champ_select() {
// The champ select is about the Challenge, whatever tab was open.
self.tab = Tab::Challenge;
// The home grid gives way to the champ select's sections.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
} else {
self.reset_home_view(window, cx);
self.anvil_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
}
}
if switch {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
self.champ_select_riot_id = None;
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.reorder();
// A new champ select starts with « Autres champions » folded and searchless.
self.fold_others(window, cx);
self.reload_in_background(window, cx);
}
if changed_page {
cx.emit(ChampSelectTransition {
entered: self.in_champ_select(),
});
}
// Any change (a hover or a lock-in too) changes the reasons of the cards. Only
// the client's events get here: no polling.
self.prepare_champ_select(cx);
}
Msg::Round { status, reload } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
if status == self.status
&& !reload
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed
{
return;
}
self.status = status;
self.pending_round = false;
self.progress = None;
self.crashed = false;
if reload {
self.reload_in_background(window, cx);
}
if self.in_champ_select() {
self.prepare_champ_select(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,
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);
}
if self.stats_job.finished() {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => self.mark_crashed(),
Msg::RefreshCrashed => {
self.refresh.reset();
self.mark_crashed();
}
}
cx.notify();
}
fn mark_crashed(&mut self) {
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
/// 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: account_riot_id(a).into(),
})
.collect();
let changed = items != self.account_items;
self.account_items = items.clone();
if changed {
// The live champ select's Account may now be in the list: resolve it again.
self.champ_select_riot_id = None;
}
// During a champ select the selector (disabled) shows the signed-in Account.
let viewed = if self.in_champ_select() {
self.champ_select_account()
} else {
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 self.in_champ_select() {
if computing {
self.stats_generation += 1;
}
// The home is the champ select's: its Challenge is the current Season's, which is
// the Statistics scope for the whole champ select.
self.home_scope = None;
self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name);
self.home_season = self.current_season.clone().map(Into::into);
let puuid = self.champ_select_account()?;
return self.current_season.is_some().then_some(puuid);
}
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
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;
}
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
}
/// 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 was computed for the home's own scope, if it had one, and for which Account.
fn set_home_result(&mut self, home: Option<Box<Result<Statistics, String>>>) {
self.home_computed = home
.as_ref()
.and_then(|_| self.shown.clone().zip(self.home_scope.clone()));
(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),
};
}
fn forget_home(&mut self) {
self.home_stats = None;
self.home_error = None;
self.home_computed = None;
}
/// Whether the home's own statistics were computed for the Account and scope it has now.
fn home_is_current(&self) -> bool {
match (&self.shown, &self.home_scope, &self.home_computed) {
(Some(puuid), Some(scope), Some((computed_puuid, computed_scope))) => {
puuid == computed_puuid && scope == computed_scope
}
_ => false,
}
}
/// 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<String> {
let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?;
if self.champ_select_riot_id.as_deref() != Some(id) {
self.champ_select_riot_id = Some(id.into());
self.champ_select_account = self
.accounts
.iter()
.find(|a| same_riot_id(&account_riot_id(a), id))
.map(|a| a.puuid.clone());
}
self.champ_select_account.clone()
}
fn statistics_scope(&self) -> Scope {
if self.in_champ_select()
&& let Some(season) = &self.current_season
{
return Scope {
season: SeasonScope::Season(season.clone()),
format: None,
};
}
Scope {
season: self.season.clone(),
format: self.format,
}
}
/// 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 = self.statistics_scope();
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
puuid,
scope,
self.home_scope.clone(),
self.stats_generation,
self.tx.clone(),
);
}
} else {
if start_job {
self.stats_job.reset();
}
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.show_statistics(window, cx);
}
}
/// Recomputes the statistics for the current scope; never called while rendering. The home's
/// own statistics are kept when they were computed for the same Account and scope (a change
/// of Format leaves them as they are).
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;
let keep_home = viewed.is_some() && self.home_is_current();
if !keep_home {
self.forget_home();
}
if let Some(puuid) = &viewed {
let scope = self.statistics_scope();
match compute_statistics(&self.tracker, puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(error) => self.stats_error = Some(error),
}
if !keep_home {
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);
}
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reorder();
if self.in_champ_select() {
// Neither the charts, the table nor the home grid are shown during a champ select.
self.prepare_home_labels();
self.prepare_champ_select(cx);
cx.notify();
return;
}
self.prepare_home_labels();
self.prepare_home_cards(cx);
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);
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;
}
/// Computes the cards' order again: for when the home statistics (the champ select's during
/// a champ select) or the sort change, and for nothing else.
fn reorder(&mut self) {
let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery);
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
self.order = card_order(rows, sort);
#[cfg(test)]
{
self.reorders += 1;
}
}
/// The home statistics' rows in the cards' order: the single iteration the home grid, the
/// Anvil champions and « Autres champions » all follow.
fn ordered_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
self.order.iter().filter_map(move |&ix| rows.get(ix))
}
/// The player chose a sort: the cards of every section follow it, and it is saved.
pub(crate) fn choose_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
if self.champion_sort == Some(sort) {
return;
}
self.champion_sort = Some(sort);
self.reorder();
if self.in_champ_select() {
self.prepare_champ_select(cx);
} else {
self.prepare_home_cards(cx);
self.refresh_home(cx);
}
cx.emit(ChampionSortChosen(sort));
cx.notify();
}
/// One card per champion, in the cards' order, for when the statistics or the sort change.
/// While the home is not shown the next switch to it does (`home_cards_stale`).
fn prepare_home_cards(&mut self, cx: &mut Context<Self>) {
if self.tab != Tab::Challenge {
self.home_cards_stale = true;
return;
}
self.home_cards_stale = false;
let cards: Rc<[Card]> = self.ordered_rows().map(Card::from_row).collect();
self.home_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
}
fn in_champ_select(&self) -> bool {
self.champ_select.is_some()
}
fn live_champ_select(&self) -> Option<&ChampSelect> {
self.champ_select.as_ref().map(|(_, pick)| pick)
}
/// What the Anvil champions area shows: the row's cards, or the notice that stands in
/// for them. For when the champ select, the statistics or the status change.
fn prepare_champ_select(&mut self, cx: &mut Context<Self>) {
// Statistics are missing rather than absent when they are still on their way.
self.champ_select_notice = match (&self.stats_error, self.stats.is_some()) {
(Some(error), _) => error.clone().into(),
(None, true) => SharedString::default(),
(None, false) if self.current_season.is_none() => home::NO_SEASON.into(),
(None, false) if self.status.updating.is_none() => "Compte indisponible".into(),
(None, false) => "Chargement des statistiques…".into(),
};
// The same rows in the same order as the home grid (`ordered_rows`): the
// cards keep their place whatever the champ select does. An id the rows do not know is
// skipped.
let cards: Rc<[Card]> = match self.live_champ_select() {
Some(pick) => {
let anvil = pick.anvil_champions.as_deref().unwrap_or_default();
self.ordered_rows()
.filter(|row| anvil.contains(&row.champion.id))
.map(|row| {
Card::from_row(row).with_unpickable(pick.unpickable(row.champion.id))
})
.collect()
}
None => Rc::new([]),
};
self.anvil_count = cards.len().to_string().into();
let shown = (0..cards.len()).collect();
self.anvil_grid.update(cx, |grid, cx| {
grid.set_cards(cards, cx);
grid.set_shown(shown, cx);
});
self.prepare_others(cx);
}
/// The rows of « Autres champions »: those whose id is not an Anvil one, in the master
/// order; all of them when the client gave no list.
fn other_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let anvil = self
.live_champ_select()
.and_then(|pick| pick.anvil_champions.as_deref());
self.ordered_rows()
.filter(move |row| anvil.is_none_or(|ids| !ids.contains(&row.champion.id)))
}
/// Builds the cards of « Autres champions », for when the section opens or the champ select
/// or the statistics change; while it is folded, nothing is built.
fn prepare_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let cards: Rc<[Card]> = match self.live_champ_select() {
Some(pick) => self
.other_rows()
.map(|row| Card::from_row(row).with_unpickable(pick.unpickable(row.champion.id)))
.collect(),
None => Rc::new([]),
};
self.others_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
self.refresh_others(cx);
}
/// Recomputes which cards of « Autres champions » its search keeps: the cards are the rows
/// of `other_rows`, in the same order.
fn refresh_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let shown: Vec<usize> = self
.other_rows()
.enumerate()
.filter(|(_, row)| self.others_search.matches(&row.champion))
.map(|(ix, _)| ix)
.collect();
self.others_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// Opens or folds « Autres champions »; folded, it gives its cards back.
fn toggle_others(&mut self, cx: &mut Context<Self>) {
self.others_open = !self.others_open;
if self.others_open {
self.prepare_others(cx);
} else {
self.others_grid = cx.new(|_| CardGrid::new());
}
cx.notify();
}
/// Folds « Autres champions » and empties its search, for a new champ select.
fn fold_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.others_open {
self.others_open = false;
self.others_grid = cx.new(|_| CardGrid::new());
}
self.others_search = ChampionSearch::new("");
self.others_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
/// At the end of a champ select the home is as at launch: « Tous » and an empty search. The
/// Account and Season viewed were never touched.
fn reset_home_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.home_filter = StateFilter::All;
self.home_search = ChampionSearch::new("");
self.home_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
/// Rebuilds the Statistics tab's rows; while it is not shown, the next switch does.
fn refresh_table(&mut self, cx: &mut Context<Self>) {
if self.tab != Tab::Statistics {
return;
}
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();
});
}
/// Recomputes which cards the home shows 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<Self>) {
if self.tab != Tab::Challenge || self.in_champ_select() {
return;
}
// The cards are the rows in the cards' order: a card's index is its position.
let shown: Vec<usize> = self
.ordered_rows()
.enumerate()
.filter(|(_, row)| {
self.home_filter.keeps(row) && self.home_search.matches(&row.champion)
})
.map(|(ix, _)| ix)
.collect();
self.home_shown_count = shown.len().to_string().into();
self.home_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them.
fn navigation(&self, cx: &mut Context<Self>) -> 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;
// The champ select takes the window: « Statistiques » waits for its end.
let disabled = tab == Tab::Statistics && self.in_champ_select();
BaseButton::new(id)
.disabled(disabled)
.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 && !disabled, |button| {
button.hover(|style| style.bg(hover).text_color(hover_foreground))
})
.when(disabled, |button| button.opacity(0.5))
.accessibility_label(label)
.debug_selector(|| id.into())
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}))
}
/// 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.error() {
banners.push(Alert::error("stats", error.clone()));
}
banners
.into_iter()
.map(|alert| alert.small().into_any_element())
.collect()
}
#[cfg(test)]
pub(crate) fn champion_sort(&self) -> Option<ChampionSort> {
self.champion_sort
}
#[cfg(test)]
pub(crate) fn home_filter(&self) -> StateFilter {
self.home_filter
}
}
impl Render for Page {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
div()
.v_flex()
.size_full()
.gap_3()
.p(px(PAGE_PADDING))
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the status
// wraps 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(self.navigation(cx))
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The champ select is about the signed-in Account.
.disabled(self.in_champ_select())
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
}))
// 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(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
),
),
)
})
.when(shown("banners"), |page| {
page.child(div().v_flex().gap_1().children(self.banners()))
})
.children(match self.tab {
Tab::Challenge => self.home_content(window, cx),
Tab::Statistics => self.statistics_content(cx),
})
}
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
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, Focusable as _, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, WindowBounds,
WindowOptions, point, px, size,
};
use super::{ChampionSortChosen, Page, SelectEvent, Tab};
use crate::card::ASPECT;
use crate::card_grid::{CardGrid, row_height};
use crate::champion_table::tests::row;
fn switch_tab(page: &Entity<Page>, cx: &mut VisualTestContext, tab: Tab) {
cx.update(|window, cx| page.update(cx, |page, cx| page.set_tab(tab, window, cx)));
}
fn open_page(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
)
}
fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<Page>, VisualTestContext) {
open_page_with_sort(cx, tracker, None)
}
/// `champion_sort`: the sort saved by an earlier run.
fn open_page_with_sort(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
let tracker = Arc::new(tracker);
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| {
Page::new(
tracker,
super::Launch {
notice: None,
following: false,
champion_sort,
},
rx,
tx,
window,
cx,
)
})
})
.unwrap()
});
(page, VisualTestContext::from_window(window, cx))
}
struct RefreshHistory;
impl MatchHistorySource for RefreshHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Alice" && queue_id == 1750 && start == 0 {
vec!["EUW1_9000000006".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, _: &str) -> Result<String, SourceError> {
Ok(
include_str!("../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json")
.replace("fixture-puuid-self", "Alice"),
)
}
}
/// A page on Alice's 3x6 statistics with the Format filter set, whose refresh worker meets Bob
/// (the client adopted another Account) before the UI does.
async fn refresh_towards_bob(cx: &mut TestAppContext, pin_alice: bool) -> Entity<Page> {
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory))
.unwrap()
.with_seasons(Vec::new());
tracker.sync("Alice#EUW", &mut |_| {}).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
window.update(|window, cx| {
page.update(cx, |page, cx| {
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.stats.as_ref().unwrap().formats, [Format::Arena3x6]);
if pin_alice {
page.pinned = Some("Alice".into());
}
page.format = Some(Format::Arena3x6);
page.recompute(window, cx);
page.tracker.follow_client(0, Some("Bob#EUW"), &mut |_| {});
page.request_refresh(cx);
});
});
cx.condition(&page, |page, _| !page.busy()).await;
page
}
#[gpui::test]
async fn a_refresh_keeps_following_the_account_being_updated(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, false).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned, None);
assert_eq!(page.viewed().unwrap().puuid, "Bob");
// Another Account may not have played the Format: the filter is dropped
// (`prepare_statistics`), whatever the refresh.
assert_eq!(page.format, None);
});
}
#[gpui::test]
async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, true).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned.as_deref(), Some("Alice"));
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.format, Some(Format::Arena3x6));
});
}
#[gpui::test]
async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pinned_page(
cx: &mut TestAppContext,
) {
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, SeasonScope};
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {});
let (page, mut window) = open_page_with_tracker(cx, tracker);
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Bob".into());
p.season = SeasonScope::AllSeasons;
p.filter = StateFilter::NeverPlayed;
p.reload(w, cx);
assert!(p.stats.as_ref().unwrap().rows.is_empty());
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
// The champ select takes the home, about the signed-in Account's current Season.
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.displayed().unwrap().puuid, "Alice");
assert_eq!(p.home_season, p.current_season.clone().map(Into::into));
assert!(p.home_season.is_some());
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
// A hover change touches neither the Account nor the pool: the card follows it.
let next = ChampSelect::new(None, [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), next))), w, cx);
})
});
page.read_with(cx, |p, cx| {
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(None), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.viewed().unwrap().puuid, "Bob");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.filter, StateFilter::NeverPlayed);
assert_eq!(p.tab, Tab::Challenge);
assert!(p.table.read(cx).names().is_empty());
});
}
#[gpui::test]
fn only_entering_a_champ_select_is_reported_as_an_entry(cx: &mut TestAppContext) {
use crate::worker::Msg;
use arena_tracker_core::ChampSelect;
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &super::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
let hovered = |current| ChampSelect::new(current, [39].into(), Some(vec![39]));
for champ_select in [
None,
Some(("Alice#EUW".into(), hovered(Some(39)))),
Some(("Alice#EUW".into(), hovered(None))),
None,
None,
] {
window.update(|w, cx| {
page.update(cx, |p, cx| p.apply(Msg::ChampSelect(champ_select), w, cx))
});
}
assert_eq!(*entered.borrow(), [true, false]);
}
#[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(),
});
});
// The search field of the Statistics tab is only there on that tab.
switch_tab(&page, cx, Tab::Statistics);
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)));
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 };
// The table hovered is the Statistics tab's: the app opens on the Challenge.
switch_tab(&page, cx, Tab::Statistics);
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
);
}
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<Page>, 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<ChampionRow>) -> 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<Page>, 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_grid.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, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let names = |cx: &mut VisualTestContext| {
let mut names = grid_names(&grid, cx);
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::<usize>(), 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(&current));
// 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::<usize>(), 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(&current));
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);
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
assert!(charts.read_with(cx, |charts, _| charts.renders) > 0);
}
fn grid_names(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) -> Vec<String> {
grid.read_with(cx, |grid, _| {
grid.names().iter().map(|name| name.to_string()).collect()
})
}
fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Never played champions with distinct ids, in A to Z order.
fn champions(count: u32) -> Vec<ChampionRow> {
(1..=count)
.map(|id| ChampionRow {
champion: Champion {
id,
key: format!("Champion{id}"),
name: format!("Champion {id:03}"),
},
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
..row("")
})
.collect()
}
#[gpui::test]
fn the_grid_follows_the_alias_search_and_the_filters(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str, state, matches, completed: bool| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
state: Some(state),
matches,
challenge: Some(ChampionChallenge {
matches,
completed_on: completed.then_some(Date {
year: 2026,
month: 3,
day: 2,
}),
..Default::default()
}),
..row(name)
};
// As the statistics give them: A to Z, the accented name where French collation puts it.
show(
&page,
cx,
statistics(
1,
4,
vec![
champion(86, "Garen", "Garen", ChampionState::NeverPlayed, 0, false),
champion(107, "Rengar", "Rengar", ChampionState::InProgress, 5, false),
champion(
4,
"TwistedFate",
"Twisted Fate",
ChampionState::Completed,
3,
true,
),
champion(238, "Zed", "Éd", ChampionState::NeverPlayed, 0, false),
],
),
);
draw(cx);
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let shown_count =
|cx: &mut VisualTestContext| page.read_with(cx, |p, _| p.home_shown_count.to_string());
// « Tous »: everything, never played and completed ones included, in the given order.
assert_eq!(
grid_names(&grid, cx),
["Garen", "Rengar", "Twisted Fate", "Éd"]
);
assert_eq!(shown_count(cx), "4");
draw(cx);
assert!(cx.debug_bounds("no-champion").is_none());
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("TF");
assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]);
assert_eq!(shown_count(cx), "1");
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(grid_names(&grid, cx).len(), 4);
cx.simulate_input("ren");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(grid_names(&grid, cx), ["Garen", "Rengar"]);
// Nothing completed matches: the grid says so.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
assert!(grid_names(&grid, cx).is_empty());
assert_eq!(shown_count(cx), "0");
draw(cx);
assert!(cx.debug_bounds("no-champion").is_some());
assert!(cx.debug_bounds("card-4").is_none());
// « Validés » alone brings the completed card back.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]);
draw(cx);
assert!(cx.debug_bounds("card-4").is_some());
assert!(cx.debug_bounds("no-champion").is_none());
}
#[gpui::test]
fn the_cards_keep_the_aspect_and_the_rows_their_pitch_and_a_card_without_a_portrait_renders(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 30, champions(30)));
draw(cx);
let first = cx
.debug_bounds("card-1")
.expect("the first card is not drawn");
let second = cx.debug_bounds("card-2").unwrap();
let next_row = cx.debug_bounds("card-7").unwrap();
// 6 columns at 1280 px, as tall as the aspect says.
assert_eq!(first.origin.y, second.origin.y);
assert!(next_row.origin.x == first.origin.x);
let (width, height) = (first.size.width.as_f32(), first.size.height.as_f32());
assert!((height - width / ASPECT).abs() < 1., "{width} x {height}");
// The first-row measure sizes every row: the next one starts a card and a gap lower.
let step = (next_row.origin.y - first.origin.y).as_f32();
assert!(
(step - (height + 14.)).abs() < 1.,
"step {step}, card {height}"
);
assert!(
((second.origin.x - first.origin.x).as_f32() - width - 14.).abs() < 1.,
"gap between columns"
);
// None of these cards has a portrait.
page.read_with(cx, |page, cx| {
assert!(
page.home_grid
.read(cx)
.names()
.contains(&"Champion 001".into())
);
});
}
#[gpui::test]
fn only_the_visible_cards_are_built(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let built = grid.read_with(cx, |grid, _| grid.card_builds);
// A few rows of 6 under 860 px, the first measured again: far from the 170 cards.
assert!(built > 0);
assert!(built <= 8 * 6, "{built} cards built for 170");
}
// While « Statistiques » is shown the home is not: its cards wait for the next switch to it.
#[gpui::test]
fn the_home_cards_are_not_built_while_statistiques_is_shown(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let built = |cx: &mut VisualTestContext| grid.read_with(cx, |grid, _| grid.set_cards_calls);
let calls = built(cx);
assert!(calls > 0);
switch_tab(&page, cx, Tab::Statistics);
show(&page, cx, statistics(0, 8, champions(8)));
assert_eq!(built(cx), calls, "the cards were built while hidden");
assert!(page.read_with(cx, |page, _| page.home_cards_stale));
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(built(cx), calls + 1);
assert!(!page.read_with(cx, |page, _| page.home_cards_stale));
assert_eq!(grid_names(&grid, cx).len(), 8);
// Nothing changed meanwhile: coming back builds nothing more.
switch_tab(&page, cx, Tab::Statistics);
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(built(cx), calls + 1);
}
// Hovering outside the grid draws the page again, not the cards: the grid is a cached view
// (rule #1), like the charts row.
#[gpui::test]
fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(renders > 0);
// A navigation button's hover style redraws the window.
for _ in 0..2 {
let button = center(cx, "tab-statistics");
cx.simulate_mouse_move(button, None, Modifiers::none());
draw(cx);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
// The count does move when the grid changes.
grid.update(cx, |_, cx| cx.notify());
draw(cx);
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders + 1);
}
// Hovering a card or scrolling the grid notifies the grid view, which GPUI draws again along
// with its parent, the page (it is not a cached view). What the test proves is that this
// costs no statistics and no cards: the statistics are not computed again and the cards are
// not built again.
#[gpui::test]
fn scrolling_or_hovering_the_grid_does_not_recompute_the_statistics(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(set_cards > 0);
let hovers = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let hovers = hovers.clone();
cx.observe(&grid, move |_, _| hovers.set(hovers.get() + 1))
});
for id in ["card-1", "card-2"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
assert!(hovers.get() > 0, "no card was hovered");
assert!(grid.read_with(cx, |grid, _| grid.renders) > renders);
let over = center(cx, "card-1");
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
..Default::default()
});
draw(cx);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
fn center(cx: &mut VisualTestContext, id: &'static str) -> gpui_kit::Point<gpui_kit::Pixels> {
cx.debug_bounds(id).unwrap().center()
}
/// `champions`, the first one Completed (first top 1 on 2 March 2026) and the second one
/// remaining with a 2nd place.
fn sheet_champions(count: u32) -> Vec<ChampionRow> {
let mut rows = champions(count);
rows[0].state = Some(ChampionState::Completed);
rows[0].attempts = Some(3);
rows[0].challenge = Some(ChampionChallenge {
matches: 4,
wins: 2,
best_placement: Some(1),
completed_on: Some(Date {
year: 2026,
month: 3,
day: 2,
}),
});
rows[1].state = Some(ChampionState::InProgress);
rows[1].attempts = Some(2);
rows[1].challenge = Some(ChampionChallenge {
matches: 2,
wins: 1,
best_placement: Some(2),
completed_on: None,
});
rows
}
const DATE: &str = "Premier top 1";
/// Whether the card's sheet was built in the last draw, and then whether it has the date.
fn sheet(cx: &mut VisualTestContext, id: u32) -> Option<bool> {
cx.debug_bounds(Box::leak(format!("sheet-{id}").into_boxed_str()))?;
Some(
cx.debug_bounds(Box::leak(format!("sheet-{id}-{DATE}").into_boxed_str()))
.is_some(),
)
}
fn sheet_ids(cx: &mut VisualTestContext, count: u32) -> Vec<u32> {
(1..=count).filter(|&id| sheet(cx, id).is_some()).collect()
}
#[gpui::test]
fn the_sheet_shows_on_hover_with_the_date_of_a_completed_champion_only(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
assert!(sheet_ids(cx, 12).is_empty(), "a sheet is built at rest");
let completed = center(cx, "card-1");
cx.simulate_mouse_move(completed, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [1]);
assert_eq!(sheet(cx, 1), Some(true));
let remaining = center(cx, "card-2");
cx.simulate_mouse_move(remaining, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(false));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(
sheet_ids(cx, 12).is_empty(),
"the sheet stays after the pointer left"
);
}
#[gpui::test]
fn scrolling_the_grid_hides_the_sheet_of_the_card_that_was_under_the_pointer(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let over = center(cx, "card-1");
cx.simulate_mouse_move(over, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 170), [1]);
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-20.))),
..Default::default()
});
draw(cx);
assert!(sheet_ids(cx, 170).is_empty(), "the sheet stuck to its card");
}
/// The focus on the sort selector, the last stop of the home's tools before the cards.
fn focus_sort(page: &Entity<Page>, cx: &mut VisualTestContext) {
let select = page.read_with(cx, |p, _| p.sort_select.clone());
cx.update(|window, cx| {
let handle = select.read(cx).focus_handle(cx);
window.focus(&handle, cx)
});
draw(cx);
}
fn press(cx: &mut VisualTestContext, keys: &str) {
cx.simulate_keystrokes(keys);
draw(cx);
}
#[gpui::test]
fn the_sheet_shows_on_keyboard_focus_and_follows_tab(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 40, sheet_champions(40)));
draw(cx);
focus_sort(&page, cx);
draw(cx);
assert!(sheet_ids(cx, 40).is_empty());
// From the sort selector, the last stop before the cards, Tab reaches the first card, the Completed one.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
// The next card: the previous sheet goes, the remaining champion has no date.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [2]);
assert_eq!(sheet(cx, 2), Some(false));
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [3]);
// Shift-Tab goes back.
press(cx, "shift-tab");
press(cx, "shift-tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
}
#[gpui::test]
fn tab_scrolls_the_row_of_the_next_card_into_view(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
focus_sort(&page, cx);
draw(cx);
assert!(
cx.debug_bounds("card-25").is_none(),
"card 25 is already built"
);
assert_eq!(grid.read_with(cx, |grid, _| grid.scrolled()), px(0.));
// Rows of 6: the 25th card opens the 5th row, below what 860 px shows.
for _ in 0..25 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 170), [25]);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
let bounds = cx.debug_bounds("card-25").expect("the row was not built");
assert!(bounds.bottom() <= px(860.), "{bounds:?}");
// Back across the row boundary, upwards.
for _ in 0..6 {
press(cx, "shift-tab");
}
assert_eq!(sheet_ids(cx, 170), [19]);
let bounds = cx.debug_bounds("card-19").expect("the row was not built");
assert!(bounds.origin.y >= px(0.), "{bounds:?}");
}
#[gpui::test]
fn tab_leaves_the_grid_after_its_last_card(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 3, sheet_champions(3)));
draw(cx);
focus_sort(&page, cx);
for _ in 0..3 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 3), [3]);
press(cx, "tab");
assert!(sheet_ids(cx, 3).is_empty(), "the focus stayed in the grid");
}
// Hovering or tabbing over the cards notifies the grid view (GPUI draws its parent page again
// too): the cards are not built again and no statistics are computed.
#[gpui::test]
fn showing_a_sheet_does_not_rebuild_the_cards_nor_recompute_the_statistics(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
for id in ["card-1", "card-2", "card-1"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
let hovered_renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(hovered_renders > renders, "the grid was not drawn");
focus_sort(&page, cx);
for _ in 0..10 {
press(cx, "tab");
}
assert!(grid.read_with(cx, |grid, _| grid.renders) > hovered_renders);
// The key presses ended the pointer's hover: the focused card alone shows its sheet.
assert_eq!(sheet_ids(cx, 170), [10]);
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
#[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);
}
// The Arena champ select of #13, replayed into the page (#74). The capture is the one the
// core replays: local cell 16, ally 17; the Anvil champions are 233, 64, 5, 16 and 68 and
// the client only offers 103, 12, 16, 233, 25 and 50.
use arena_tracker_core::{
ChampSelect, ChampSelectReader, ChampionCatalog, ChampionSource, ClientError,
};
use serde_json::{Value, json};
use crate::card::{Card, Reason};
const JOUEUR: &str = "Joueur#EUW";
const ANVIL: [u32; 5] = [233, 64, 5, 16, 68];
/// The Anvil champions of the capture in the order of the home: A to Z by name.
const ANVIL_A_TO_Z: [u32; 5] = [233, 64, 68, 16, 5];
const ANVIL_CARDS: [&str; 5] = ["card-233", "card-64", "card-68", "card-16", "card-5"];
/// (id, key, name): the champions of the capture.
const CATALOG: [(u32, &str, &str); 9] = [
(12, "Alistar", "Alistar"),
(16, "Soraka", "Soraka"),
(25, "Morgana", "Morgana"),
(50, "Swain", "Swain"),
(64, "LeeSin", "Lee Sin"),
(5, "XinZhao", "Xin Zhao"),
(68, "Rumble", "Rumble"),
(103, "Ahri", "Ahri"),
(233, "Briar", "Briar"),
];
/// Joueur completed 16 (a top 1) and played 233 (a 4th place).
struct JoueurHistory;
impl MatchHistorySource for JoueurHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Joueur" && queue_id == 1750 && start == 0 {
vec!["EUW1_1".into(), "EUW1_2".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let (champion, name, placement) = match id {
"EUW1_1" => (16, "Soraka", 1),
"EUW1_2" => (233, "Briar", 4),
_ => return Err(SourceError::NotFound),
};
let raw =
include_str!("../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json")
.replace("fixture-puuid-self", "Joueur");
let mut payload: Value = serde_json::from_str(&raw).unwrap();
payload["metadata"]["matchId"] = id.into();
for player in payload["info"]["participants"].as_array_mut().unwrap() {
if player["puuid"] == "Joueur" {
player["championId"] = champion.into();
player["championName"] = name.into();
player["placement"] = placement.into();
player["win"] = (placement <= 3).into();
}
}
Ok(payload.to_string())
}
fn champion_mastery(&self, _: &str, puuid: &str) -> Result<Vec<(u32, u64)>, SourceError> {
Ok(if puuid == "Joueur" {
MASTERY.to_vec()
} else {
Vec::new()
})
}
}
/// Joueur's Mastery Points. Xin Zhao (5) and Morgana (25) are missing from the list: known,
/// no points.
const MASTERY: [(u32, u64); 7] = [
(64, 120_000),
(16, 40_000),
(50, 9_000),
(233, 5_000),
(68, 900),
(12, 300),
(103, 100),
];
/// The Anvil champions of the capture by Mastery Points, then those without an anvil.
const ANVIL_BY_MASTERY: [u32; 5] = [64, 16, 233, 68, 5];
const OTHERS_BY_MASTERY: [u32; 4] = [50, 12, 103, 25];
const ALL_A_TO_Z: [&str; 9] = [
"Ahri", "Alistar", "Briar", "Lee Sin", "Morgana", "Rumble", "Soraka", "Swain", "Xin Zhao",
];
struct Catalog;
impl ChampionSource for Catalog {
fn latest_version(&self) -> Result<String, SourceError> {
Ok("1.0".into())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
Ok(ChampionCatalog {
version: version.into(),
champions: CATALOG
.iter()
.map(|&(id, key, name)| Champion {
id,
key: key.into(),
name: name.into(),
})
.collect(),
})
}
fn portrait(&self, _: &str, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
fn card_portrait(&self, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
}
/// The tracker of Joueur (and of Autre, who has played nothing), on the catalog.
fn joueur_tracker() -> Tracker {
joueur_tracker_with(false)
}
/// `mastery`: Joueur is the Account being followed and its points were fetched.
fn joueur_tracker_with(mastery: bool) -> Tracker {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
// One folder per tracker: the tests run in parallel.
static TRACKERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = TRACKERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let portraits =
std::env::temp_dir().join(format!("arena-tracker-74-{}-{n}", std::process::id()));
let tracker = tracker.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
let _ = std::fs::remove_dir(portraits);
if mastery {
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
// Without a client, a round adopts the Riot ID it is given, then asks for the points.
tracker.follow_client(0, Some(JOUEUR), &mut |_| {});
assert!(tracker.mastery("Joueur").unwrap().is_some());
} else {
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
}
tracker
}
fn capture() -> Value {
serde_json::from_str(include_str!(
"../../core/tests/fixtures/client/arena_champ_select.json"
))
.unwrap()
}
/// The champ select as the page gets it from a session, the lists being those of the capture
/// but the Anvil one.
fn read_champ_select(
reader: &ChampSelectReader,
session: Value,
anvil: Option<String>,
) -> ChampSelect {
let capture = capture();
reader.set_session(session);
reader
.read(
|| Err(ClientError::Absent),
|| {
Ok((
capture["pickableChampionIds"].to_string(),
capture["disabledChampionIds"].to_string(),
anvil,
))
},
)
.unwrap()
}
/// The five frames of the capture, read through one reader as the follower does.
fn frames() -> Vec<ChampSelect> {
let capture = capture();
let reader = ChampSelectReader::default();
capture["sessions"]
.as_array()
.unwrap()
.iter()
.map(|session| {
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&reader, session.clone(), anvil)
})
.collect()
}
/// Frame 0 with these completed bans, and `ally` confirmed.
fn with_bans_and_ally(bans: &[u32], ally: u32) -> ChampSelect {
let capture = capture();
let mut session = capture["sessions"][0].clone();
session["actions"] = json!([bans
.iter()
.map(|id| json!({"type": "ban", "championId": id, "completed": true}))
.collect::<Vec<_>>()]);
session["myTeam"][1]["championId"] = ally.into();
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&ChampSelectReader::default(), session, anvil)
}
fn send(page: &Entity<Page>, window: &mut VisualTestContext, pick: &ChampSelect) {
let live = Some((JOUEUR.to_string(), pick.clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
}
fn leave(page: &Entity<Page>, window: &mut VisualTestContext) {
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(None), w, cx)
})
});
}
fn anvil_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.anvil_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
fn ids(cards: &[Card]) -> Vec<u32> {
cards.iter().map(|card| card.id).collect()
}
fn reasons(cards: &[Card], id: u32) -> Vec<Reason> {
cards.iter().find(|c| c.id == id).unwrap().reasons.clone()
}
fn bounds(window: &mut VisualTestContext) -> Vec<gpui_kit::Bounds<gpui_kit::Pixels>> {
ANVIL_CARDS
.iter()
.map(|id| window.debug_bounds(id).expect("the card is not drawn"))
.collect()
}
#[gpui::test]
async fn the_arena_capture_fills_the_anvil_row_in_the_homes_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
// The home's own order, which the row follows.
let home_order: Vec<u32> = page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
rows.map(|row| row.champion.id)
.filter(|id| ANVIL.contains(id))
.collect()
});
assert_eq!(home_order, ANVIL_A_TO_Z);
let frames = frames();
assert_eq!(frames.len(), 5);
send(&page, &mut window, &frames[0]);
// Until the statistics are there, the row is replaced by what is missing.
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some("Compte indisponible"))
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let first = bounds(&mut window);
// Never greyed by the champ select: 233 and 16 are offered, the rest is not offered.
let baseline = [
(233, vec![]),
(64, vec![Reason::NotOffered]),
(68, vec![Reason::NotOffered]),
(16, vec![Reason::Completed]),
(5, vec![Reason::NotOffered]),
];
for (frame, pick) in frames.iter().enumerate() {
if frame > 0 {
send(&page, &mut window, pick);
}
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
// 12 (banned), 25 (ally) and 50 (banned) are not Anvil champions: never in the row.
assert_eq!(ids(&cards), ANVIL_A_TO_Z, "frame {frame}");
for (id, expected) in &baseline {
assert_eq!(
&reasons(&cards, *id),
expected,
"frame {frame}, champion {id}"
);
}
// The cards keep their place.
assert_eq!(bounds(&mut window), first, "frame {frame}");
}
// The marks come with the Challenge of the signed-in Account.
let cards = anvil_cards(&page, &mut window);
let mark = |id| cards.iter().find(|c| c.id == id).unwrap().marks;
assert!(mark(16).completed && mark(16).won);
assert!(mark(233).played && !mark(233).completed);
assert!(!mark(64).played);
// Reasons add up: 16 is Completed and banned, 233 banned and confirmed by an ally. The
// labels change and the cards stay.
send(&page, &mut window, &with_bans_and_ally(&[16, 233, 12], 233));
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
assert_eq!(reasons(&cards, 16), [Reason::Completed, Reason::Banned]);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
assert_eq!(reasons(&cards, 64), [Reason::NotOffered]);
assert_eq!(bounds(&mut window), first);
// The cards are as big as the home's, on one row of six at 1280 px.
let (width, height) = (first[0].size.width.as_f32(), first[0].size.height.as_f32());
assert!((height - width / ASPECT).abs() < 1., "{width} x {height}");
assert_eq!(first[0].origin.y, first[1].origin.y);
let gap = (first[1].origin.x - first[0].origin.x).as_f32() - width;
assert!((gap - 14.).abs() < 1., "gap {gap}");
}
#[gpui::test]
async fn the_champ_select_takes_the_home_and_gives_it_back_as_it_was(cx: &mut TestAppContext) {
use arena_tracker_core::SeasonScope;
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
// Autre, on « Toutes les Saisons », with a filter and a search on the home.
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Autre".into());
p.season = SeasonScope::AllSeasons;
p.home_filter = StateFilter::Completed;
p.reload(w, cx);
});
input.update(cx, |input, cx| input.set_value("ah", w, cx));
});
page.read_with(&window, |p, _| {
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.tab, Tab::Statistics);
});
draw(&mut window);
let frames = frames();
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
// The Challenge of the signed-in Account in the current Season, whatever the
// Statistics tab shows.
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.displayed().unwrap().puuid, "Joueur");
assert_eq!(p.home_season.as_deref(), Some("Saison"));
assert_eq!(p.home_count.as_ref(), "1 / 9");
assert!(p.stats.as_ref().unwrap().challenge.is_some());
});
// The row is there; the grid, its filters and its search are not.
assert!(window.debug_bounds("anvil-row").is_some());
assert!(window.debug_bounds("card-233").is_some());
assert!(window.debug_bounds("home-tools").is_none());
assert!(window.debug_bounds("card-103").is_none());
// « Statistiques » is out of reach during the champ select.
let statistics = center(&mut window, "tab-statistics");
window.simulate_click(statistics, Modifiers::none());
switch_tab(&page, &mut window, Tab::Statistics);
assert_eq!(page.read_with(&window, |p, _| p.tab), Tab::Challenge);
// Bans and ally picks are the champ select's.
send(&page, &mut window, &with_bans_and_ally(&[16, 233], 233));
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, cx| {
// As before the champ select, with « Tous » and no search on the home.
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.home_filter, StateFilter::All);
assert!(p.home_search_input.read(cx).value().is_empty());
assert_eq!(p.home_shown_count.as_ref(), "9");
assert_eq!(p.home_grid.read(cx).names().len(), 9);
assert_eq!(p.home_count.as_ref(), "0 / 9");
assert!(p.anvil_grid.read(cx).names().is_empty());
});
assert_eq!(
home_grid.read_with(&window, |grid, _| grid.names().len()),
9
);
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("card-103").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
// Another champ select starts clean.
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 16), [Reason::Completed]);
assert_eq!(reasons(&cards, 233), []);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
}
#[gpui::test]
async fn an_unknown_or_empty_anvil_list_is_said_soberly(cx: &mut TestAppContext) {
cx.executor().allow_parking();
for (anvil, line) in [
(None, "Champions de l'Enclume non communiqués par le client"),
(
Some("[]"),
"Aucun Champion de l'Enclume dans cette sélection",
),
] {
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(
&ChampSelectReader::default(),
session,
anvil.map(str::to_string),
);
send(&page, &mut window, &pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some(line))
});
// No row, and no champion is presented as « sans enclume ».
assert!(anvil_cards(&page, &mut window).is_empty());
assert!(window.debug_bounds("anvil-notice").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("card-103").is_none());
assert!(window.debug_bounds("card-16").is_none());
}
}
#[gpui::test]
async fn missing_statistics_are_said_once_and_leave_nothing_to_browse(cx: &mut TestAppContext) {
cx.executor().allow_parking();
// No current Season: the header says so, and the Anvil area does not say it again.
let (page, mut window) = open_page(cx);
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.champ_select_notice, "Aucune Saison en cours");
});
assert!(window.debug_bounds("no-season").is_some());
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("others-toggle").is_none());
// The statistics are on their way: the area says so, and there is nothing to browse yet.
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.anvil_line().as_deref(),
Some("Chargement des statistiques…")
);
});
assert!(window.debug_bounds("no-season").is_none());
assert!(window.debug_bounds("anvil-notice").is_some());
assert!(window.debug_bounds("others-toggle").is_none());
// Once they are there, the section is offered.
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("others-toggle").is_some());
}
/// What the non-anvil champions of the capture are, in the home's order (A to Z by name).
const OTHERS_A_TO_Z: [u32; 4] = [103, 12, 25, 50];
fn others_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.others_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
fn others_open(page: &Entity<Page>, window: &mut VisualTestContext) -> bool {
page.read_with(window, |p, _| p.others_open)
}
fn click_others(window: &mut VisualTestContext) {
let toggle = center(window, "others-toggle");
window.simulate_click(toggle, Modifiers::none());
draw(window);
}
/// Presses and releases `key` on the focused element, as the navigation's test does.
fn activate(window: &mut VisualTestContext, key: &str) {
let keystroke =
window.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
window.simulate_event(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
});
window.simulate_event(KeyUpEvent { keystroke });
draw(window);
}
/// Tab, until the section's header has the focus.
fn focus_others_toggle(page: &Entity<Page>, window: &mut VisualTestContext) {
for _ in 0..60 {
window.update(|w, cx| w.focus_next(cx));
draw(window);
if window.update(|w, cx| page.read(cx).others_focus.is_focused(w)) {
return;
}
}
panic!("Tab never reached « Autres champions »");
}
fn search_others(page: &Entity<Page>, window: &mut VisualTestContext, text: &str) {
let input = page.read_with(window, |p, _| p.others_search_input.clone());
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
if !text.is_empty() {
window.simulate_input(text);
}
draw(window);
}
/// The page in the first frame of the capture, once its statistics are there.
async fn page_in_champ_select(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
(page, window)
}
#[gpui::test]
async fn others_is_folded_at_entry_and_builds_no_card(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
assert!(!others_open(&page, &mut window));
assert!(window.debug_bounds("others-toggle").is_some());
assert!(window.debug_bounds("anvil-row").is_some());
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
grid.read_with(&window, |grid, _| {
assert_eq!(grid.renders, 0);
assert_eq!(grid.card_builds, 0);
assert_eq!(grid.set_cards_calls, 0);
});
assert!(window.debug_bounds("card-103").is_none());
// The frames and the statistics keep coming while it is folded: still nothing.
for pick in &frames()[1..] {
send(&page, &mut window, pick);
draw(&mut window);
}
grid.read_with(&window, |grid, _| {
assert_eq!((grid.renders, grid.set_cards_calls), (0, 0));
});
page.read_with(&window, |p, _| {
assert_eq!(p.others_title(), "Autres champions")
});
}
#[gpui::test]
async fn others_opens_and_closes_with_the_mouse_and_the_keyboard(cx: &mut TestAppContext) {
let pick = with_bans_and_ally(&[12, 50], 25);
let (page, mut window) = page_in_champ_select(cx, &pick).await;
let anvil_before = anvil_cards(&page, &mut window);
click_others(&mut window);
assert!(others_open(&page, &mut window));
// Every champion without an anvil, banned or taken ones included, in the home's order.
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), OTHERS_A_TO_Z);
assert_eq!(reasons(&cards, 103), []);
assert_eq!(reasons(&cards, 12), [Reason::Banned]);
assert_eq!(reasons(&cards, 25), [Reason::TakenByAlly]);
assert_eq!(reasons(&cards, 50), [Reason::Banned]);
assert!(window.debug_bounds("card-103").is_some());
assert!(window.debug_bounds("card-12").is_some());
// The anvil row is untouched.
assert_eq!(anvil_cards(&page, &mut window), anvil_before);
click_others(&mut window);
assert!(!others_open(&page, &mut window));
assert!(window.debug_bounds("card-103").is_none());
assert!(others_cards(&page, &mut window).is_empty());
// With the keyboard: Tab reaches the header, Enter opens it and Space folds it.
focus_others_toggle(&page, &mut window);
activate(&mut window, "enter");
assert!(others_open(&page, &mut window));
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
activate(&mut window, "space");
assert!(!others_open(&page, &mut window));
activate(&mut window, "enter");
assert!(others_open(&page, &mut window));
// The lock-ins of the champ select reach the open section, which keeps its place.
send(&page, &mut window, &with_bans_and_ally(&[103], 25));
draw(&mut window);
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), OTHERS_A_TO_Z);
assert_eq!(reasons(&cards, 103), [Reason::Banned]);
assert_eq!(reasons(&cards, 12), []);
}
#[gpui::test]
async fn others_shows_the_completed_champions_it_holds(cx: &mut TestAppContext) {
// 16 is Completed; with only 233 an Anvil champion it is one of the others.
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(&ChampSelectReader::default(), session, Some("[233]".into()));
let (page, mut window) = page_in_champ_select(cx, &pick).await;
click_others(&mut window);
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), [103, 12, 64, 25, 68, 16, 50, 5]);
assert_eq!(reasons(&cards, 16), [Reason::Completed]);
assert_eq!(reasons(&cards, 64), [Reason::NotOffered]);
assert_eq!(ids(&anvil_cards(&page, &mut window)), [233]);
}
#[gpui::test]
async fn the_search_of_others_filters_only_that_section(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
let anvil_before = anvil_cards(&page, &mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
search_others(&page, &mut window, "ahr");
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// By alias: « cow » is Alistar's.
search_others(&page, &mut window, "cow");
assert_eq!(grid_names(&grid, &mut window), ["Alistar"]);
// An Anvil champion is not in this section, whoever searches for it.
search_others(&page, &mut window, "xz");
assert!(grid_names(&grid, &mut window).is_empty());
assert!(window.debug_bounds("no-champion").is_some());
// The anvil row and the home's search are intact.
assert_eq!(anvil_cards(&page, &mut window), anvil_before);
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
page.read_with(&window, |p, cx| {
assert!(p.home_search_input.read(cx).value().is_empty())
});
search_others(&page, &mut window, "");
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
}
#[gpui::test]
async fn a_new_champ_select_folds_others_and_empties_its_search(cx: &mut TestAppContext) {
let frames = frames();
let (page, mut window) = page_in_champ_select(cx, &frames[0]).await;
let fresh = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| {
assert!(!p.others_open);
assert!(p.others_search_input.read(cx).value().is_empty());
assert_eq!(p.others_grid.read(cx).renders, 0);
assert!(p.others_grid.read(cx).shown_cards().is_empty());
})
};
// The frames of the same champ select keep it open, with its search.
click_others(&mut window);
search_others(&page, &mut window, "ahr");
send(&page, &mut window, &frames[1]);
draw(&mut window);
assert!(others_open(&page, &mut window));
assert_eq!(others_cards(&page, &mut window).len(), 1);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// Leaving, then entering again.
leave(&page, &mut window);
draw(&mut window);
fresh(&mut window);
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("others-toggle").is_some());
assert!(window.debug_bounds("card-103").is_none());
// The champ select of another Riot ID.
click_others(&mut window);
search_others(&page, &mut window, "cow");
let live = Some(("Autre#EUW".to_string(), frames[0].clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
fresh(&mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("card-103").is_none());
}
#[gpui::test]
async fn others_lists_every_champion_when_the_anvil_list_is_unknown(cx: &mut TestAppContext) {
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(&ChampSelectReader::default(), session, None);
let (page, mut window) = page_in_champ_select(cx, &pick).await;
page.read_with(&window, |p, _| {
assert_eq!(p.others_title(), "Tous les champions")
});
click_others(&mut window);
let all: Vec<u32> = page.read_with(&window, |p, _| {
p.stats
.as_ref()
.unwrap()
.rows
.iter()
.map(|r| r.champion.id)
.collect()
});
assert_eq!(all.len(), 9);
assert_eq!(ids(&others_cards(&page, &mut window)), all);
assert!(anvil_cards(&page, &mut window).is_empty());
assert!(window.debug_bounds("card-233").is_some());
}
#[gpui::test]
fn others_builds_only_the_visible_cards_and_hovering_elsewhere_does_not_draw_them(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_page_in_season(cx);
send(&page, &mut window, &frames()[0]);
// The statistics of the Account, as the worker would give them: 170 champions, most
// of them without an anvil.
show(&page, &mut window, statistics(0, 170, champions(170)));
draw(&mut window);
click_others(&mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let (built, renders) = grid.read_with(&window, |grid, _| (grid.card_builds, grid.renders));
// 170 champions less the Anvil ones the statistics know: 5, 16, 64 and 68.
assert_eq!(
grid.read_with(&window, |grid, _| grid.shown_cards().len()),
166
);
assert!(built > 0 && built <= 8 * 6, "{built} cards built for 170");
assert!(renders > 0);
// Hovering the header, outside the cards, draws the page and not the cards.
let toggle = center(&mut window, "others-toggle");
for dx in 0..5 {
window.simulate_mouse_move(
point(toggle.x + px(dx as f32 * 7.), toggle.y),
None,
Modifiers::none(),
);
draw(&mut window);
}
assert_eq!(grid.read_with(&window, |grid, _| grid.renders), renders);
}
#[gpui::test]
fn no_champ_select_changes_nothing(cx: &mut TestAppContext) {
let (page, mut window) = open_page_in_season(cx);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &super::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
show(&page, &mut window, statistics(0, 1, vec![row("Ahri")]));
let generation = page.read_with(&window, |p, _| p.stats_generation);
leave(&page, &mut window);
draw(&mut window);
assert!(entered.borrow().is_empty());
page.read_with(&window, |p, _| {
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.stats_generation, generation);
assert_eq!(p.anvil_line(), None);
});
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
}
// The tall card portraits (#77).
use std::path::PathBuf;
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
/// Joueur's tracker on the catalog, with the card portraits of `keys` on disk under `dir`.
fn tracker_with_portraits(dir: &Path, keys: &[&str]) -> Tracker {
let portraits = dir.join("portraits");
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)])
.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
let cards = portraits.join("cards");
std::fs::create_dir_all(&cards).unwrap();
for key in keys {
std::fs::write(cards.join(format!("{key}.jpg")), PORTRAIT_JPEG).unwrap();
}
tracker
}
fn card_portrait(dir: &Path, key: &str) -> PathBuf {
dir.join("portraits")
.join("cards")
.join(format!("{key}.jpg"))
}
// The worker saves a portrait, then tells the page: the card shows it without a restart.
#[gpui::test]
async fn a_card_portrait_saved_while_the_app_runs_shows_once_the_worker_tells(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("portrait-arrives");
let (page, mut window) =
open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &[]));
let grid = page.read_with(&window, |p, _| p.home_grid.clone());
let ahri = |grid: &CardGrid| {
let cards = grid.shown_cards().into_iter();
cards
.filter(|card| card.id == 103)
.map(|card| card.portrait.map(|path| path.to_path_buf()))
.next()
};
assert_eq!(grid.read_with(&window, |grid, _| ahri(grid)), Some(None));
draw(&mut window);
let path = card_portrait(dir.path(), "Ahri");
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
window
.update(|w, cx| page.update(cx, |p, cx| p.apply(crate::worker::Msg::Champions, w, cx)));
cx.condition(&grid, |grid, _| ahri(grid) == Some(Some(path.clone())))
.await;
// Drawn, through the grid's own cache.
draw(&mut window);
window.run_until_parked();
draw(&mut window);
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the grid was not drawn");
assert_eq!(images.read_with(&window, |i, _| i.held()), [path]);
assert_eq!(images.read_with(&window, |i, _| i.loaded()).len(), 1);
}
// The Anvil row is a grid of its own, not cached, with no `uniform_list`: its portraits go
// through its own cache too, never through the app-wide one.
#[gpui::test]
async fn the_anvil_row_reads_its_portraits_through_its_own_cache(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("anvil-portraits");
let keys = ["Briar", "LeeSin", "Rumble", "Soraka", "XinZhao"];
let (page, mut window) =
open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
window.run_until_parked();
draw(&mut window);
let grid = page.read_with(&window, |p, _| p.anvil_grid.clone());
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the row was not drawn");
let mut expected: Vec<_> = keys
.iter()
.map(|key| card_portrait(dir.path(), key))
.collect();
expected.sort();
assert_eq!(images.read_with(&window, |i, _| i.held()), expected);
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
window.update(|w, cx| {
assert!(loaded.iter().all(|image| w.has_image_atlas_entry(image)));
for path in &expected {
let source = gpui_kit::ImageSource::from(path.clone());
assert!(!source.is_asset_cached(cx), "{path:?}");
}
});
}
// Folding « Autres champions » drops its grid, and with it its portraits, on the GPU too.
#[gpui::test]
async fn folding_others_frees_its_portraits(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("others-portraits");
let keys = ["Ahri", "Alistar", "Morgana", "Swain"];
let (page, mut window) =
open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
click_others(&mut window);
window.run_until_parked();
draw(&mut window);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the section was not drawn");
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
let in_atlas = |window: &mut VisualTestContext| {
window.update(|w, _| {
(loaded.iter())
.filter(|image| w.has_image_atlas_entry(image))
.count()
})
};
assert_eq!(in_atlas(&mut window), keys.len());
let weak = images.downgrade();
drop((images, grid));
click_others(&mut window);
assert!(!others_open(&page, &mut window));
window.run_until_parked();
assert!(weak.upgrade().is_none(), "the folded grid's cache is kept");
assert_eq!(in_atlas(&mut window), 0);
}
// A grid that is not shown gives its portraits back, on the GPU too, and loads them again
// when it is shown.
#[gpui::test]
async fn a_grid_that_is_not_shown_gives_its_portraits_back(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("hidden-portraits");
let keys = [
"Ahri", "Alistar", "Briar", "LeeSin", "Morgana", "Rumble", "Soraka", "Swain", "XinZhao",
];
let (page, mut window) =
open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
let load = |window: &mut VisualTestContext| {
draw(window);
window.run_until_parked();
draw(window);
};
let held = |grid: &Entity<CardGrid>, window: &mut VisualTestContext| {
let images = grid.read_with(window, |grid, _| grid.images().cloned());
let images = images.expect("the grid was never drawn");
images.read_with(window, |images, _| images.held().len())
};
let home = page.read_with(&window, |p, _| p.home_grid.clone());
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
let images = home.read_with(&window, |grid, _| grid.images().cloned().unwrap());
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
let in_atlas = |window: &mut VisualTestContext| {
window.update(|w, _| {
(loaded.iter())
.filter(|image| w.has_image_atlas_entry(image))
.count()
})
};
assert_eq!(in_atlas(&mut window), keys.len());
// « Statistiques » shows no card.
switch_tab(&page, &mut window, Tab::Statistics);
draw(&mut window);
assert_eq!(held(&home, &mut window), 0);
assert!(images.read_with(&window, |i, _| i.loaded()).is_empty());
assert_eq!(in_atlas(&mut window), 0);
// Back on « Défi » they load again.
switch_tab(&page, &mut window, Tab::Challenge);
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
assert_eq!(
images.read_with(&window, |i, _| i.loaded()).len(),
keys.len()
);
// A champ select takes the home's place with its own sections.
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
load(&mut window);
assert_eq!(held(&home, &mut window), 0);
let anvil = page.read_with(&window, |p, _| p.anvil_grid.clone());
assert_eq!(held(&anvil, &mut window), ANVIL.len());
// And gives the Anvil row up when it ends.
leave(&page, &mut window);
assert_eq!(held(&anvil, &mut window), 0);
cx.condition(&page, |p, _| p.stats.is_some()).await;
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
assert_eq!(held(&anvil, &mut window), 0);
}
// « Autres champions » is open in a column that also scrolls: its grid keeps at least a
// whole row, not the sliver the Anvil row leaves it in a 860 px window.
#[gpui::test]
async fn the_open_others_grid_shows_a_whole_row(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
draw(&mut window);
let list = window
.debug_bounds("card-list")
.expect("the open section's grid is not drawn");
let row = row_height(px(1280.));
assert!(
list.size.height >= row,
"{:?} tall for a row of {row:?}",
list.size.height
);
assert!(window.debug_bounds("card-103").is_some());
assert!(others_open(&page, &mut window));
}
/// The statistics' error is the banner's alone during a champ select: the Anvil area does
/// not repeat it, and nothing is left to browse.
#[gpui::test]
async fn a_statistics_error_is_said_once_during_a_champ_select(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let error = "Statistiques indisponibles : disque plein";
window.update(|_, cx| {
page.update(cx, |p, cx| {
p.stats = None;
p.stats_error = Some(error.into());
p.prepare_champ_select(cx);
cx.notify();
})
});
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.champ_select_notice, error);
assert_eq!(p.error().map(String::as_str), Some(error));
});
// The banner says it; the area says nothing and offers nothing to browse.
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("others-toggle").is_none());
assert!(window.debug_bounds("no-season").is_none());
}
// The Season's statistics are computed once while the Format changes: it does not apply to
// the home.
#[gpui::test]
async fn changing_the_format_recomputes_only_the_statistics_scope(cx: &mut TestAppContext) {
use crate::worker::COMPUTED;
use arena_tracker_core::Scope;
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let scope = |season: SeasonScope, format| Scope { season, format };
let saison = || SeasonScope::Season("Saison".into());
let computed = |window: &mut VisualTestContext, change: &dyn Fn(&mut Page)| {
COMPUTED.with(|computed| computed.borrow_mut().clear());
window.update(|w, cx| {
page.update(cx, |p, cx| {
change(p);
p.recompute(w, cx)
})
});
COMPUTED.with(|computed| computed.borrow().clone())
};
// A Format: the statistics for it, and the home's, which were read from the former.
let first = computed(&mut window, &|p| p.format = Some(Format::Arena3x6));
assert_eq!(
first,
[
scope(saison(), Some(Format::Arena3x6)),
scope(saison(), None)
]
);
// Another Format: the home's statistics are kept.
let kept = page.read_with(&window, |p, _| p.home_stats.clone());
let second = computed(&mut window, &|p| p.format = Some(Format::BraveryArena));
assert_eq!(second, [scope(saison(), Some(Format::BraveryArena))]);
page.read_with(&window, |p, _| {
assert!(p.home_stats.is_some() && p.home_stats == kept);
});
// All the Seasons while the current one is the home's: same scope, kept.
let third = computed(&mut window, &|p| p.season = SeasonScope::AllSeasons);
assert_eq!(
third,
[scope(SeasonScope::AllSeasons, Some(Format::BraveryArena))]
);
// Back to « Tous les Formats » on the current Season: the statistics are the home's.
let fourth = computed(&mut window, &|p| {
p.season = saison();
p.format = None;
});
assert_eq!(fourth, [scope(saison(), None)]);
page.read_with(&window, |p, _| assert!(p.home_stats.is_none()));
// A Format again: the home's statistics were the Statistics tab's, and are computed.
let fifth = computed(&mut window, &|p| {
p.format = Some(Format::Arena3x6);
});
assert_eq!(
fifth,
[
scope(saison(), Some(Format::Arena3x6)),
scope(saison(), None)
]
);
}
/// The reasons of the capture on the cards of « Autres champions », drawn end to end.
#[gpui::test]
async fn a_reason_appearing_on_a_card_of_others_is_drawn_without_moving_it(
cx: &mut TestAppContext,
) {
let frames = frames();
let (page, mut window) = page_in_champ_select(cx, &frames[0]).await;
click_others(&mut window);
let name = |prefix: &str, id: u32, label: &str| -> &'static str {
Box::leak(format!("{prefix}-{id}{label}").into_boxed_str())
};
let badge = |window: &mut VisualTestContext, id: u32, label: &str| {
window
.debug_bounds(name("reason", id, &format!("-{label}")))
.is_some()
};
let places = |window: &mut VisualTestContext| {
OTHERS_A_TO_Z.map(|id| {
window
.debug_bounds(name("card", id, ""))
.expect("not drawn")
})
};
let first = places(&mut window);
for id in OTHERS_A_TO_Z {
assert!(!badge(&mut window, id, "Banni"), "frame 0, {id}");
}
// Frame 1: 12 is banned; 25 is only an ally's pre-pick, which leaves it as it is.
send(&page, &mut window, &frames[1]);
draw(&mut window);
assert!(badge(&mut window, 12, "Banni"));
assert!(!badge(&mut window, 25, "Pris par un allié"));
assert!(!badge(&mut window, 25, "Banni"));
assert!(!badge(&mut window, 50, "Banni"));
assert_eq!(places(&mut window), first);
// Frame 2: 50 too.
send(&page, &mut window, &frames[2]);
draw(&mut window);
assert!(badge(&mut window, 12, "Banni") && badge(&mut window, 50, "Banni"));
assert!(!badge(&mut window, 25, "Pris par un allié"));
assert_eq!(places(&mut window), first);
// Frame 3: the ally confirms 25.
for frame in [&frames[3], &frames[4]] {
send(&page, &mut window, frame);
draw(&mut window);
assert!(badge(&mut window, 25, "Pris par un allié"));
assert!(badge(&mut window, 12, "Banni") && badge(&mut window, 50, "Banni"));
assert!(!badge(&mut window, 103, "Banni"));
assert_eq!(places(&mut window), first);
}
}
// The sort of the cards (#76).
/// A row with a name, an id and its Mastery Points.
fn with_points(id: u32, name: &str, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
mastery_points: points,
..row(name)
}
}
/// A to Z, as the statistics give them.
fn rows_with_points() -> Vec<ChampionRow> {
vec![
with_points(1, "Ahri", None),
with_points(2, "Brand", Some(500)),
with_points(3, "Garen", Some(9_000)),
with_points(4, "Jinx", Some(500)),
with_points(5, "Lux", Some(0)),
with_points(6, "Zed", None),
]
}
const BY_MASTERY: [&str; 6] = ["Garen", "Brand", "Jinx", "Lux", "Ahri", "Zed"];
const A_TO_Z: [&str; 6] = ["Ahri", "Brand", "Garen", "Jinx", "Lux", "Zed"];
/// The sorts the page reports, in order.
fn record_sorts(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Rc<RefCell<Vec<ChampionSort>>> {
let chosen = Rc::new(RefCell::new(Vec::new()));
let events = chosen.clone();
cx.update(|_, cx| {
cx.subscribe(page, move |_, event: &ChampionSortChosen, _| {
events.borrow_mut().push(event.0)
})
.detach()
});
chosen
}
/// The player picks `label` in the sort selector.
fn pick_sort(page: &Entity<Page>, cx: &mut VisualTestContext, label: &'static str) {
let select = page.read_with(cx, |p, _| p.sort_select.clone());
cx.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some(label.into())))
})
});
draw(cx);
}
fn reorders(page: &Entity<Page>, cx: &mut VisualTestContext) -> usize {
page.read_with(cx, |p, _| p.reorders)
}
#[gpui::test]
fn the_home_follows_the_mastery_points_until_another_sort_is_chosen(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
// Nothing chosen: Mastery Points descending, ties by name, unknown ones last.
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert!(cx.debug_bounds("sort").is_some());
let generation = page.read_with(cx, |p, _| p.stats_generation);
let before = reorders(&page, cx);
pick_sort(&page, cx, "A–Z");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Name]);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
// The statistics are as they were: only the cards moved.
assert_eq!(p.stats_generation, generation);
let rows = p.stats.as_ref().unwrap().rows.iter();
assert_eq!(
rows.map(|r| r.champion.name.as_str()).collect::<Vec<_>>(),
A_TO_Z
);
});
assert_eq!(reorders(&page, cx), before + 1);
// The filter and the search apply to the new order.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(grid_names(&grid, cx), A_TO_Z);
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert_eq!(
*chosen.borrow(),
[ChampionSort::Name, ChampionSort::Mastery]
);
// Choosing what is already chosen reports nothing.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(chosen.borrow().len(), 2);
}
#[gpui::test]
fn without_any_known_value_the_cards_are_a_to_z_and_the_preference_is_untouched(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
let unknown: Vec<ChampionRow> = rows_with_points()
.into_iter()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
show(&page, cx, statistics(0, 6, unknown));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert!(chosen.borrow().is_empty());
// The cards say it: unknown, not zero.
let sheets = grid.read_with(cx, |grid, _| grid.shown_cards());
assert!(sheets.iter().all(|card| {
card.sheet
.iter()
.any(|(label, value)| *label == "Points de maîtrise" && value == "Inconnus")
}));
// Mastery chosen on purpose is still A to Z while nothing is known, and is saved.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Mastery]);
// The points arrive: the preference now applies.
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
}
#[gpui::test]
fn a_saved_sort_is_there_at_the_first_draw(cx: &mut TestAppContext) {
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let (page, cx) = open_page_with_sort(cx, tracker, Some(ChampionSort::Name));
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
assert_eq!(p.home_filter, StateFilter::All);
});
}
#[gpui::test]
fn the_cards_are_sorted_again_only_when_the_data_or_the_preference_change(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let count = reorders(&page, cx);
// Hovering a card, the search, the filter and the champ-select-less rounds change
// neither the data nor the preference.
let card = grid.read_with(cx, |grid, _| grid.shown_cards()[0].id);
let id: &'static str = Box::leak(format!("card-{card}").into_boxed_str());
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("r");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(reorders(&page, cx), count);
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(reorders(&page, cx), count + 1, "new data");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "new preference");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "same preference");
}
#[gpui::test]
async fn alias_filters_sort_and_the_champ_select_all_follow_one_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
let chosen = record_sorts(&page, &mut window);
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let type_search = |window: &mut VisualTestContext, text: &str| {
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
window.simulate_input(text);
};
// Soraka, Swain, Briar, Rumble... by Mastery Points, the zeros by name.
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[64, 16, 50, 233, 68, 12, 103, 25, 5]
);
// An alias.
type_search(&mut window, "srk");
assert_eq!(grid_names(&home_grid, &mut window), ["Soraka"]);
// A name part and a filter: Soraka is Completed, so « Restants » drops it.
type_search(&mut window, "a");
page.update(&mut window, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[50, 233, 12, 103, 25, 5]
);
pick_sort(&page, &mut window, "A–Z");
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[103, 12, 233, 25, 50, 5]
);
// Entering a champ select: the Anvil row follows the sort, so does « Autres champions »,
// and the selector stays.
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| {
p.stats.as_ref().is_some_and(|s| s.rows.len() == 9)
})
.await;
draw(&mut window);
assert!(window.debug_bounds("sort").is_some());
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
click_others(&mut window);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
pick_sort(&page, &mut window, "Maîtrise");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_BY_MASTERY);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_BY_MASTERY);
// Reasons still go with their cards.
assert_eq!(
reasons(&anvil_cards(&page, &mut window), 16),
[Reason::Completed]
);
// The statistics themselves stay A to Z.
page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
let names: Vec<_> = rows.map(|row| row.champion.name.as_str()).collect();
assert_eq!(names, ALL_A_TO_Z);
});
pick_sort(&page, &mut window, "A–Z");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
// Leaving gives back « Tous » and an empty search, with the sort kept.
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.home_filter, StateFilter::All);
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
});
assert_eq!(
*chosen.borrow(),
[
ChampionSort::Name,
ChampionSort::Mastery,
ChampionSort::Name
]
);
assert_eq!(grid_names(&home_grid, &mut window), ALL_A_TO_Z);
}
}