Show the Anvil champions as cards during an Arena champ select (#74)

The home takes the selection: the Challenge of the signed-in Account for the
current Season, then a row of the Anvil champions in the home grid's order with
the reasons Validé, Banni, Pris par un allié and Indisponible. The old text view
is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 21:32:51 +01:00
1 parent 05b8cc6d60
commit 6f2a6244cc
8 files changed
+790 -220

No files matched your search

+553 -178
View File
@@ -6,9 +6,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChampSelect, ChampionRow, ChampionSearch, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, account_riot_id,
same_riot_id,
Account, ChampSelect, ChampionSearch, 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};
@@ -116,13 +115,9 @@ pub struct Page {
champ_select_account: Option<String>,
/// The Riot ID `champ_select_account` was resolved for.
champ_select_riot_id: Option<String>,
/// The current champion's cells, prepared when the pick or the statistics change.
current_labels: Vec<SharedString>,
/// What the panel says when the current champion has no statistics row.
current_fallback: SharedString,
/// What the panel says while the statistics are missing.
/// 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,
anvil_labels: Vec<SharedString>,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
@@ -177,6 +172,11 @@ pub struct Page {
home_grid: Entity<CardGrid>,
/// 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,
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
@@ -219,6 +219,7 @@ impl Page {
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 subscriptions = vec![
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
@@ -299,10 +300,7 @@ impl Page {
champ_select: None,
champ_select_account: None,
champ_select_riot_id: None,
current_labels: Vec::new(),
current_fallback: SharedString::default(),
champ_select_notice: SharedString::default(),
anvil_labels: Vec::new(),
accounts: Vec::new(),
last_active: None,
pinned: None,
@@ -342,6 +340,8 @@ impl Page {
table,
home_grid,
home_shown_count: SharedString::default(),
anvil_grid,
anvil_count: SharedString::default(),
_subscriptions: subscriptions,
_listener: listener,
};
@@ -382,11 +382,21 @@ impl Page {
.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.viewed().is_some_and(|viewed| {
&& self.displayed().is_some_and(|viewed| {
self.status
.updating
.as_ref()
@@ -397,7 +407,7 @@ impl Page {
/// 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.viewed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid);
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()),
@@ -425,6 +435,10 @@ impl Page {
}
fn set_tab(&mut self, tab: Tab, cx: &mut Context<Self>) {
// The selection 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;
// The tab left was not kept up to date.
@@ -451,12 +465,15 @@ impl Page {
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);
let pool_changed = match (previous, next) {
(Some((_, before)), Some((_, after))) => !before.same_pickable(after),
(None, None) => false,
_ => true,
};
self.champ_select = champ_select;
if changed_page {
if self.in_champ_select() {
// The selection is about the Challenge, whatever tab was open.
self.tab = Tab::Challenge;
} else {
self.reset_home_view(window, cx);
}
}
if switch {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
@@ -474,12 +491,9 @@ impl Page {
entered: self.in_champ_select(),
});
}
self.update_picks();
if pool_changed || switch {
self.refresh_table(cx);
}
// A hover or lock-in changes neither the Account nor the pool: the page is
// redrawn by the notification at the end of this message.
// 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).
@@ -499,7 +513,7 @@ impl Page {
self.reload_in_background(window, cx);
}
if self.in_champ_select() {
self.update_picks();
self.prepare_champ_select(cx);
}
}
Msg::Refreshed(status) => {
@@ -579,7 +593,12 @@ impl Page {
// The live champ select's Account may now be in the list: resolve it again.
self.champ_select_riot_id = None;
}
let viewed = self.viewed().map(|a| a.puuid.clone());
// 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);
@@ -606,9 +625,11 @@ impl Page {
if computing {
self.stats_generation += 1;
}
// The champ select view has no home.
// The home is the champ select's: its Challenge is the current Season's, which is
// the Statistics scope for the whole selection.
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);
}
@@ -749,8 +770,9 @@ impl Page {
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.in_champ_select() {
self.update_picks();
self.refresh_table(cx);
// Neither the charts, the table nor the home grid are shown during a selection.
self.prepare_home_labels();
self.prepare_champ_select(cx);
cx.notify();
return;
}
@@ -805,79 +827,63 @@ impl Page {
self.champ_select.as_ref().map(|(_, pick)| pick)
}
fn update_picks(&mut self) {
let rows = self.stats.as_ref().map_or(&[][..], |s| s.rows.as_slice());
let pick = self.live_champ_select();
let current_labels = pick
.and_then(|s| s.current_row(rows))
.map(crate::champion_table::pick_labels)
.unwrap_or_default();
let mut anvil_labels: Vec<SharedString> = pick
.map(|s| {
s.anvil_champions
.iter()
.flatten()
.map(|id| {
let row = rows.iter().find(|r| r.champion.id == *id);
let mut label = champion_label(row, *id);
if let Some(state) = row.and_then(|r| r.state) {
label.push_str(" · ");
label.push_str(crate::text::state_label(Some(state)));
}
if !s.can_pick(*id) {
label.push_str(" · Indisponible");
}
SharedString::from(label)
})
.collect()
})
.unwrap_or_default();
anvil_labels.sort();
/// 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.
let loading = self.stats.is_none()
&& self.stats_error.is_none()
&& self.current_season.is_some()
&& self.status.updating.is_some();
let current_fallback = pick.map_or_else(SharedString::default, |s| match s.current {
Some(id) if current_labels.is_empty() => {
let row = rows.iter().find(|r| r.champion.id == id);
let note = if loading {
"Chargement des statistiques…"
} else {
"Statistiques indisponibles"
};
format!("{} · {note}", champion_label(row, id)).into()
}
Some(_) => SharedString::default(),
None => "Aucun champion sélectionné".into(),
});
let champ_select_notice = match (&self.stats_error, self.stats.is_some()) {
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() => "Aucune Saison en cours".into(),
(None, false) if self.status.updating.is_none() => "Compte indisponible".into(),
(None, false) => "Chargement des statistiques…".into(),
};
self.current_labels = current_labels;
self.anvil_labels = anvil_labels;
self.current_fallback = current_fallback;
self.champ_select_notice = champ_select_notice;
// The same rows in the same order as the home grid (`prepare_home_cards`): 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.stats.as_ref(), self.live_champ_select()) {
(Some(stats), Some(pick)) => {
let anvil = pick.anvil_champions.as_deref().unwrap_or_default();
stats
.rows
.iter()
.filter(|row| anvil.contains(&row.champion.id))
.map(|row| {
Card::from_row(row)
.with_unavailability(pick.unavailability(row.champion.id))
})
.collect()
}
_ => 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);
});
}
/// 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 && !self.in_champ_select() {
if self.tab != Tab::Statistics {
return;
}
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| match &self.champ_select {
Some((_, pick)) => pick.remaining(row),
None => self.filter.keeps(row) && self.search.matches(&row.champion),
})
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_champ_select() || self.in_season();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
@@ -904,73 +910,6 @@ impl Page {
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
fn champ_select_view(&self, cx: &App) -> Div {
let border = cx.theme().border;
let page = div().v_flex().size_full().p_3().gap_3().child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Sélection des champions · Arena"),
);
page.child(match self.current_labels.split_first() {
Some((name, labels)) => div()
.h_flex()
.items_center()
.flex_wrap()
.gap_x_4()
.gap_y_1()
.child(div().font_weight(FontWeight::SEMIBOLD).child(name.clone()))
.children(
labels
.iter()
.cloned()
.map(|label| div().text_sm().child(label)),
),
None => div().child(self.current_fallback.clone()),
})
.child(
div()
.v_flex()
.gap_2()
.p_3()
.border_1()
.border_color(border)
.rounded_md()
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions de l'Enclume"),
)
.child(
div()
.h_flex()
.flex_wrap()
.gap_x_4()
.gap_y_1()
.children(
self.anvil_labels
.iter()
.cloned()
.map(|name| div().child(name)),
)
.when(self.anvil_labels.is_empty(), |row| {
row.child("Aucun champion de l'Enclume communiqué par le client")
}),
),
)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions disponibles à valider"),
)
.when(self.stats.is_none(), |page| {
page.child(self.champ_select_notice.clone())
})
.when(self.stats.is_some(), |page| {
page.child(div().flex_1().min_h_0().child(self.table.clone()))
})
}
/// 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();
@@ -992,7 +931,10 @@ impl Page {
.flex_shrink_0()
.children(tabs.map(|(id, label, tab)| {
let current = self.tab == tab;
// The selection 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()
@@ -1004,9 +946,10 @@ impl Page {
.focus_visible(|style| style.border_color(ring))
.text_color(if current { active_foreground } else { muted })
.when(current, |button| button.bg(active))
.when(!current, |button| {
.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)
@@ -1048,17 +991,9 @@ impl Page {
}
}
/// The champion's name, or the client's id when the catalog does not know it.
fn champion_label(row: Option<&ChampionRow>, id: u32) -> String {
row.map_or_else(|| format!("Champion {id}"), |row| row.champion.name.clone())
}
impl Render for Page {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
if self.in_champ_select() {
return self.champ_select_view(cx);
}
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
@@ -1089,6 +1024,8 @@ impl Render for Page {
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The selection is about the signed-in Account.
.disabled(self.in_champ_select())
.w(px(260.))
.min_w(px(150.)),
)
@@ -1284,7 +1221,6 @@ mod tests {
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
// The table that follows the champ select pool back is the Statistics one.
p.set_tab(Tab::Statistics, cx);
p.pinned = Some("Bob".into());
p.season = SeasonScope::AllSeasons;
@@ -1294,30 +1230,25 @@ mod tests {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
cx.condition(&page, |p, _| !p.current_labels.is_empty())
.await;
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.current_labels[0].as_ref(), "Irelia");
assert!(
p.current_labels
.iter()
.any(|l| l.starts_with("Tentatives · 1"))
);
assert_eq!(p.anvil_labels.len(), 1);
assert!(p.anvil_labels[0].starts_with("Irelia · "));
assert_eq!(p.table.read(cx).names(), ["Irelia"]);
// The selection 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 panel must still update.
// 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, _| {
assert!(p.current_labels.is_empty());
assert_eq!(p.current_fallback.as_ref(), "Aucun champion sélectionné");
page.read_with(cx, |p, cx| {
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
window.update(|w, cx| {
@@ -1330,6 +1261,7 @@ mod tests {
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());
});
}
@@ -2218,4 +2150,447 @@ mod tests {
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())
}
}
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 {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let portraits =
std::env::temp_dir().join(format!("arena-tracker-74-{}", std::process::id()));
let tracker = tracker.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
let _ = std::fs::remove_dir(portraits);
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 selection: 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_selection_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, 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 selection.
let statistics = center(&mut window, "tab-statistics");
window.simulate_click(statistics, Modifiers::none());
page.update(&mut window, |p, cx| p.set_tab(Tab::Statistics, cx));
assert_eq!(page.read_with(&window, |p, _| p.tab), Tab::Challenge);
// Bans and ally picks are the selection'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 selection, 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 selection 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]
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());
}
}