From 5ba32518754ba772b64d7102b3f5e01359fe98cb Mon Sep 17 00:00:00 2001
From: Nessar
Date: Thu, 19 Nov 2026 20:25:31 +0100
Subject: [PATCH] Fix champ select review findings (#13)
- redraw the page on hover and lock-in changes, and reset the settings form
when champ select takes the window away
- keep the current pick when a client read fails; only a real answer that
the draft is over ends it
- read the client once per wake and share it between the follower and the
live selection, reuse session event payloads, and touch only the cached
champion list an event concerns
- replay the captured raw client responses in the fake and cover the list
cache, event updates and the anvil-champion read
- name the five champions anvil champions and the set pickable, document
them, and prepare redraw strings ahead of render
---
CONTEXT.md | 15 ++
crates/app/src/main.rs | 2 +
crates/app/src/stats_page.rs | 203 ++++++++++++++++----------
crates/app/src/text.rs | 2 +-
crates/app/src/worker.rs | 63 +++++---
crates/core/src/champ_select.rs | 242 ++++++++++++++++++++++++++-----
crates/core/src/client.rs | 60 +++++++-
crates/core/src/follow.rs | 117 ++++++++++-----
crates/core/src/league_client.rs | 199 +++++++++++++++++--------
crates/core/src/lib.rs | 8 +-
crates/core/tests/common/mod.rs | 70 +++++++--
crates/core/tests/follow.rs | 89 ++++++++----
12 files changed, 799 insertions(+), 271 deletions(-)
diff --git a/CONTEXT.md b/CONTEXT.md
index 47d7caa..928d160 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -52,6 +52,18 @@ _Avoid_: Split, run
A League of Legends account; the active Account is the one signed in to the game client.
_Avoid_: Player, profile, summoner
+**Champ select**:
+The draft before an Arena Match, where each player bans and picks a champion; only an Arena champ select opens the champ select view.
+_Avoid_: Draft, selection
+
+**Anvil champions**:
+The five champions the game favours in the current Arena patch and shows during champ select; the game client calls them crowd favorites.
+_Avoid_: Crowd favorites, favorites
+
+**Pickable**:
+A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player.
+_Avoid_: Available, owned, remaining
+
**Official Progress**:
The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge.
_Avoid_: Riot challenge, tracker
@@ -71,5 +83,8 @@ The interface is in French. Each glossary term has one French word in user-facin
| Win | Victoire |
| Season | Saison |
| Account | Compte |
+| Champ select | Sélection des champions |
+| Anvil champions | Champions de l'Enclume |
+| Pickable | Disponible |
| Official Progress | Progression officielle |
| Placement, Format, Top N | unchanged |
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index bdf651a..3fd14ec 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -93,6 +93,8 @@ impl RootView {
window,
|this, _, _: &stats_page::ChampSelectTransition, window, cx| {
if this.screen == Screen::Settings {
+ // Champ select takes the window away: do not bring back half-typed edits.
+ this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Page;
this.focus.focus(window, cx);
cx.notify();
diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs
index 6ff8ac9..0aa0c6d 100644
--- a/crates/app/src/stats_page.rs
+++ b/crates/app/src/stats_page.rs
@@ -4,8 +4,9 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
- Account, ChallengeSummary, ChampSelect, ChampionSearch, Charts, Format, ProgressCheck, Scope,
- SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
+ Account, ChallengeSummary, ChampSelect, ChampionRow, ChampionSearch, Charts, Format,
+ ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker,
+ UpdateProblem, same_riot_id,
};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::StyledExt as _;
@@ -86,8 +87,13 @@ pub struct StatsPage {
/// As of the last follower round or refresh.
status: Status,
selection: crate::worker::Selection,
- current_pick: Vec,
- favorites: Vec,
+ /// The current champion's cells, prepared when the pick or the statistics change.
+ current_labels: Vec,
+ /// What the panel says when the current champion has no statistics row.
+ current_fallback: SharedString,
+ /// What the panel says while the statistics are missing.
+ selection_notice: SharedString,
+ anvil_labels: Vec,
accounts: Vec,
last_active: Option,
/// The Account the user picked instead of following the one being updated.
@@ -249,8 +255,10 @@ impl StatsPage {
tx,
notice,
selection: None,
- current_pick: Vec::new(),
- favorites: Vec::new(),
+ current_labels: Vec::new(),
+ current_fallback: SharedString::default(),
+ selection_notice: SharedString::default(),
+ anvil_labels: Vec::new(),
accounts: Vec::new(),
last_active: None,
pinned: None,
@@ -350,12 +358,15 @@ impl StatsPage {
if self.selection == selection {
return;
}
- let next = selection.as_ref().and_then(|s| s.as_ref().ok());
- let changed_page = self.selection.is_some() != selection.is_some();
- let previous = self.selection.as_ref().and_then(|s| s.as_ref().ok());
+ let previous = self.selection.as_ref();
+ let next = selection.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 =
- previous.map(|(_, s)| &s.pickable) != next.map(|(_, s)| &s.pickable);
+ let pool_changed = match (previous, next) {
+ (Some((_, before)), Some((_, after))) => !before.same_pickable(after),
+ (None, None) => false,
+ _ => true,
+ };
self.selection = selection;
if switch {
self.stats_generation += 1;
@@ -371,8 +382,12 @@ impl StatsPage {
if pool_changed || switch {
self.refresh_table(cx);
}
+ // A hover or lock-in changes neither the Account nor the pool: redraw the page
+ // so the current-pick panel follows, even when the table is untouched.
+ cx.notify();
}
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
@@ -388,6 +403,9 @@ impl StatsPage {
if reload {
self.reload_in_background(window, cx);
}
+ if self.in_champ_select() {
+ self.update_picks();
+ }
}
Msg::Refreshed(status) => {
self.status = status;
@@ -483,7 +501,7 @@ impl StatsPage {
cx: &mut Context,
) -> Option {
self.last_reload = Instant::now();
- if self.selection.is_some() {
+ if self.in_champ_select() {
if computing {
self.stats_generation += 1;
}
@@ -494,12 +512,11 @@ impl StatsPage {
.tracker
.current_season(now.as_millis() as i64)
.map(|s| s.name);
- let (id, _) = self.selection.as_ref()?.as_ref().ok()?;
- let id = id.to_lowercase();
+ let (id, _) = self.selection.as_ref()?;
return self
.accounts
.iter()
- .find(|a| riot_id(a).to_lowercase() == id)
+ .find(|a| same_riot_id(&riot_id(a), id))
.filter(|_| self.current_season.is_some())
.map(|a| a.puuid.clone());
}
@@ -525,7 +542,7 @@ impl StatsPage {
}
fn statistics_scope(&self) -> Scope {
- if self.selection.is_some()
+ if self.in_champ_select()
&& let Some(season) = &self.current_season
{
return Scope {
@@ -590,7 +607,7 @@ impl StatsPage {
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) {
- if self.selection.is_some() {
+ if self.in_champ_select() {
self.update_picks();
self.refresh_table(cx);
cx.notify();
@@ -615,50 +632,75 @@ impl StatsPage {
cx.notify();
}
- fn live_pick(&self) -> Option<&ChampSelect> {
- self.selection.as_ref()?.as_ref().ok().map(|(_, pick)| pick)
+ fn in_champ_select(&self) -> bool {
+ self.selection.is_some()
+ }
+
+ fn live_champ_select(&self) -> Option<&ChampSelect> {
+ self.selection.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_pick();
- let current = pick
+ 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();
- self.favorites = pick
- .into_iter()
- .flat_map(|s| {
- s.crowd_favorites.iter().flatten().map(|id| {
- let row = rows.iter().find(|r| r.champion.id == *id);
- let mut label =
- row.map_or_else(|| format!("Champion {id}"), |r| r.champion.name.clone());
- if let Some(state) = row.and_then(|r| r.state) {
- label.push_str(" · ");
- label.push_str(crate::text::state_label(Some(state)));
- }
- if !s.pickable.contains(id) && s.current != Some(*id) {
- label.push_str(" · Indisponible");
- }
- SharedString::from(label)
- })
+ let mut anvil_labels: Vec = pick
+ .map(|s| {
+ s.anvil_champions
+ .iter()
+ .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()
})
- .collect();
- self.favorites.sort();
- self.current_pick = current;
+ .unwrap_or_default();
+ anvil_labels.sort();
+ let current_fallback = match pick {
+ Some(s) => match s.current {
+ Some(id) if current_labels.is_empty() => {
+ let row = rows.iter().find(|r| r.champion.id == id);
+ format!("{} · Statistiques indisponibles", champion_label(row, id)).into()
+ }
+ Some(_) => SharedString::default(),
+ None => "Aucun champion sélectionné".into(),
+ },
+ None => "Sélection indisponible dans le client.".into(),
+ };
+ let selection_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.selection_notice = selection_notice;
}
fn refresh_table(&mut self, cx: &mut Context) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| match &self.selection {
- Some(Ok((_, pick))) => pick.remaining(row),
- Some(Err(_)) => false,
+ Some((_, pick)) => pick.remaining(row),
None => self.filter.keeps(row) && self.search.matches(&row.champion),
})
.cloned()
.collect();
- let in_season = self.selection.is_some() || self.in_season();
+ let in_season = self.in_champ_select() || self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
@@ -666,7 +708,6 @@ impl StatsPage {
}
fn champ_select_view(&self, cx: &App) -> Div {
- let pick = self.live_pick();
let border = cx.theme().border;
let mut page = div().v_flex().size_full().p_3().gap_3().child(
div()
@@ -674,10 +715,10 @@ impl StatsPage {
.font_weight(FontWeight::SEMIBOLD)
.child("Sélection des champions · Arena"),
);
- let Some(pick) = pick else {
+ if self.live_champ_select().is_none() {
return page.child("Sélection indisponible dans le client.");
- };
- page = page.child(match self.current_pick.split_first() {
+ }
+ page = page.child(match self.current_labels.split_first() {
Some((name, labels)) => div()
.h_flex()
.items_center()
@@ -691,10 +732,7 @@ impl StatsPage {
.cloned()
.map(|label| div().text_sm().child(label)),
),
- None => div().child(pick.current.map_or_else(
- || "Aucun champion sélectionné".to_owned(),
- |id| format!("Champion {id} · Statistiques indisponibles"),
- )),
+ None => div().child(self.current_fallback.clone()),
});
page.child(
div()
@@ -707,7 +745,7 @@ impl StatsPage {
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
- .child("Favoris du public · Enclume"),
+ .child("Champions de l'Enclume"),
)
.child(
div()
@@ -715,9 +753,14 @@ impl StatsPage {
.flex_wrap()
.gap_x_4()
.gap_y_1()
- .children(self.favorites.iter().cloned().map(|name| div().child(name)))
- .when(self.favorites.is_empty(), |row| {
- row.child("Aucun favori communiqué par le client")
+ .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")
}),
),
)
@@ -727,16 +770,7 @@ impl StatsPage {
.child("Champions disponibles à valider"),
)
.when(self.stats.is_none(), |page| {
- page.child(self.stats_error.clone().unwrap_or_else(|| {
- if self.current_season.is_none() {
- "Aucune Saison en cours"
- } else if self.status.updating.is_none() {
- "Compte indisponible"
- } else {
- "Chargement des statistiques…"
- }
- .into()
- }))
+ page.child(self.selection_notice.clone())
})
.when(self.stats.is_some(), |page| {
page.child(div().flex_1().min_h_0().child(self.table.clone()))
@@ -777,6 +811,11 @@ impl StatsPage {
}
}
+/// 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())
+}
+
fn tile(
label: &'static str,
value: String,
@@ -1043,7 +1082,7 @@ impl Render for StatsPage {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
- if self.selection.is_some() {
+ if self.in_champ_select() {
return self.champ_select_view(cx);
}
let options = filters(self.in_season());
@@ -1308,11 +1347,7 @@ mod tests {
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 {
- current: Some(39),
- pickable: [39].into(),
- crowd_favorites: Some(vec![39]),
- };
+ let pick = ChampSelect::new(Some(39), [39].into(), vec![39]);
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.pinned = Some("Bob".into());
@@ -1320,21 +1355,35 @@ mod tests {
p.filter = StateFilter::NeverPlayed;
p.reload(w, cx);
assert!(p.stats.as_ref().unwrap().rows.is_empty());
- p.apply(Msg::Selection(Some(Ok(("Alice#EUW".into(), pick)))), w, cx);
+ p.apply(Msg::Selection(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
- cx.condition(&page, |p, _| !p.current_pick.is_empty()).await;
+ cx.condition(&page, |p, _| !p.current_labels.is_empty())
+ .await;
page.read_with(cx, |p, cx| {
- assert_eq!(p.current_pick[0].as_ref(), "Irelia");
+ assert_eq!(p.current_labels[0].as_ref(), "Irelia");
assert!(
- p.current_pick
+ p.current_labels
.iter()
.any(|l| l.starts_with("Tentatives · 1"))
);
- assert_eq!(p.favorites.len(), 1);
- assert!(p.favorites[0].starts_with("Irelia · "));
+ assert_eq!(p.anvil_labels.len(), 1);
+ assert!(p.anvil_labels[0].starts_with("Irelia · "));
assert_eq!(p.table.read(cx).names(), ["Irelia"]);
});
+
+ // A hover change touches neither the Account nor the pool: the panel must still update.
+ let next = ChampSelect::new(None, [39].into(), vec![39]);
+ window.update(|w, cx| {
+ page.update(cx, |p, cx| {
+ p.apply(Msg::Selection(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é");
+ });
+
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::Selection(None), w, cx);
diff --git a/crates/app/src/text.rs b/crates/app/src/text.rs
index 694bd48..0b99908 100644
--- a/crates/app/src/text.rs
+++ b/crates/app/src/text.rs
@@ -30,7 +30,7 @@ pub const CLIENT_ABSENT: &str =
const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne.";
pub fn riot_id(account: &Account) -> String {
- format!("{}#{}", account.game_name, account.tag_line)
+ arena_tracker_core::riot_id(&account.game_name, &account.tag_line)
}
/// The discreet line under the Challenge tile.
diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs
index aae96ed..80ed6e2 100644
--- a/crates/app/src/worker.rs
+++ b/crates/app/src/worker.rs
@@ -7,11 +7,12 @@ use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
- ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker,
+ ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker,
};
use gpui_kit::base::async_util::Sender;
-pub type Selection = Option>;
+/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
+pub type Selection = Option<(String, ChampSelect)>;
pub enum Msg {
Selection(Selection),
@@ -111,7 +112,9 @@ fn spawn_guarded(tx: Sender, on_panic: Msg, body: impl FnOnce(&Sender)
});
}
-/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds and a live selection subscription. `fallback_riot_id` is the configured Riot ID.
+/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds
+/// and a live selection subscription. Each wake reads the client once and shares that read with
+/// both. `fallback_riot_id` is the configured Riot ID.
/// The champion catalog and portraits are fetched on another thread, so a first launch's
/// import never waits for them.
pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sender) {
@@ -122,14 +125,23 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende
});
// Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks.
let (wake, rounds) = std::sync::mpsc::sync_channel(1);
+ let latest = Arc::new(std::sync::Mutex::new(None));
let history = tracker.clone();
+ let history_latest = latest.clone();
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty());
let mut first = true;
for () in rounds {
- let changed = history.follow_client(now_ms(), fallback, &mut |progress| {
+ let snapshot = history_latest.lock().unwrap().take();
+ let mut progress = |progress| {
let _ = tx.try_send(Msg::Progress(progress));
- });
+ };
+ let changed = match snapshot {
+ Some(snapshot) => {
+ history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress)
+ }
+ None => history.follow_client(now_ms(), fallback, &mut progress),
+ };
if tx
.try_send(Msg::Round {
status: history.status(),
@@ -144,24 +156,41 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
let mut previous = None;
- let mut selection_only = false;
+ let mut snapshot = tracker.client_snapshot();
+ let mut share = true;
while !tx.is_closed() {
- if !selection_only
- && matches!(
+ // The follower round uses the same read as the live selection: one gameflow request
+ // per wake, and none for a champ select event.
+ if share {
+ *latest.lock().unwrap() = Some(snapshot.clone());
+ if matches!(
wake.try_send(()),
Err(std::sync::mpsc::TrySendError::Disconnected(()))
- )
- {
- break;
- }
- let selection = tracker.champ_select();
- if selection != previous {
- if tx.try_send(Msg::Selection(selection.clone())).is_err() {
+ ) {
break;
}
- previous = selection;
}
- selection_only = tracker.wait_for_client();
+ match tracker.champ_select_with(&snapshot) {
+ Ok(selection) if selection != previous => {
+ if tx.try_send(Msg::Selection(selection.clone())).is_err() {
+ break;
+ }
+ previous = selection;
+ }
+ Ok(_) => {}
+ // A failed read is not the draft ending: keep what the page shows.
+ Err(_) => {}
+ }
+ // A champ select event costs no request while the draft is already known; any other
+ // event, or a snapshot that predates the draft, needs a fresh read.
+ share = tracker.wait_for_client() == ClientEvent::Other
+ || !snapshot
+ .gameflow
+ .as_ref()
+ .is_ok_and(|flow| flow.is_arena_champ_select());
+ if share {
+ snapshot = tracker.client_snapshot();
+ }
}
});
}
diff --git a/crates/core/src/champ_select.rs b/crates/core/src/champ_select.rs
index 2c477c3..67012c8 100644
--- a/crates/core/src/champ_select.rs
+++ b/crates/core/src/champ_select.rs
@@ -1,17 +1,37 @@
//! The local player's pick and the champions offered during an Arena champ select.
use std::collections::HashSet;
+use std::sync::Arc;
use serde_json::Value;
use crate::league_client::parse;
use crate::{ChampionRow, ChampionState, ClientError};
-#[derive(Clone, Debug, PartialEq)]
+pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids";
+pub(crate) const DISABLED_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids";
+pub(crate) const ANVIL_EVENT: &str =
+ "OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list";
+
+/// The local player's live pick and the champions they can still pick.
+#[derive(Clone, Debug)]
pub struct ChampSelect {
pub current: Option,
- /// The five anvil champions. None when the client could not report the list.
- pub crowd_favorites: Option>,
- pub pickable: HashSet,
+ /// The five anvil champions; empty when the client reports none. The client calls them
+ /// crowd favorites.
+ pub anvil_champions: Vec,
+ /// The champions the draft offers, before its bans and the other players' picks. Shared with
+ /// the client's cache instead of cloned on every session event.
+ pickable: Arc>,
+ /// Banned or taken by another player in this session.
+ excluded: HashSet,
+}
+
+impl PartialEq for ChampSelect {
+ fn eq(&self, other: &Self) -> bool {
+ self.current == other.current
+ && self.anvil_champions == other.anvil_champions
+ && self.same_pickable(other)
+ }
}
fn champion_id(value: &Value) -> Option {
@@ -25,33 +45,51 @@ fn array(value: &Value) -> Result<&[Value], ClientError> {
.ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))
}
+fn ids(body: &str) -> Result, ClientError> {
+ Ok(array(&parse(body)?)?
+ .iter()
+ .filter_map(champion_id)
+ .collect())
+}
+
+fn ids_from_event(data: &Value) -> Option> {
+ data.as_array()
+ .map(|ids| ids.iter().filter_map(champion_id).collect())
+}
+
+fn ordered_ids(data: &Value) -> Option> {
+ data.as_array()
+ .map(|ids| ids.iter().filter_map(champion_id).collect())
+}
+
impl ChampSelect {
- pub fn available_champions(
+ /// A selection with nothing banned or taken, for tests and callers with a ready pool.
+ pub fn new(current: Option, pickable: HashSet, anvil_champions: Vec) -> Self {
+ Self {
+ current,
+ anvil_champions,
+ pickable: Arc::new(pickable),
+ excluded: HashSet::new(),
+ }
+ }
+
+ /// The champions the client offers, minus those disabled for this draft. The pickable list
+ /// is the client's answer to what the player can pick: it already includes free-rotation and
+ /// rented champions, so ownership is not consulted.
+ pub fn pickable_champions(
pickable: &str,
disabled: &str,
- owned: &str,
- ) -> Result, ClientError> {
- let mut ids: HashSet<_> = array(&parse(owned)?)?
- .iter()
- .filter(|c| c["ownership"]["owned"] == true)
- .filter_map(|c| champion_id(&c["id"]))
- .collect();
- for id in array(&parse(disabled)?)?.iter().filter_map(champion_id) {
- ids.remove(&id);
- }
- Ok(array(&parse(pickable)?)?
- .iter()
- .filter_map(champion_id)
- .filter(|id| ids.contains(id))
- .collect())
+ ) -> Result>, ClientError> {
+ let pickable = ids(pickable)?;
+ let disabled = ids(disabled)?;
+ Ok(Arc::new(pickable.difference(&disabled).copied().collect()))
}
pub fn from_session(
- body: &str,
- mut pickable: HashSet,
- crowd_favorites: Option>,
+ session: &Value,
+ pickable: Arc>,
+ anvil_champions: Vec,
) -> Result {
- let session = parse(body)?;
let local = session["localPlayerCellId"]
.as_i64()
.ok_or(ClientError::Absent)?;
@@ -62,12 +100,13 @@ impl ChampSelect {
.ok_or(ClientError::Absent)?;
let current =
champion_id(&me["championId"]).or_else(|| champion_id(&me["championPickIntent"]));
+ let mut excluded = HashSet::new();
for player in team
.iter()
.filter(|p| p["cellId"] != local && p["team"] == me["team"])
{
if let Some(id) = champion_id(&player["championId"]) {
- pickable.remove(&id);
+ excluded.insert(id);
}
}
// In Arena the confirmed bans were in actions while both team ban lists were empty.
@@ -77,21 +116,20 @@ impl ChampSelect {
&& action["completed"] == true
&& let Some(id) = champion_id(&action["championId"])
{
- pickable.remove(&id);
+ excluded.insert(id);
}
}
}
for key in ["myTeamBans", "theirTeamBans"] {
if let Some(bans) = session["bans"][key].as_array() {
- for id in bans.iter().filter_map(champion_id) {
- pickable.remove(&id);
- }
+ excluded.extend(bans.iter().filter_map(champion_id));
}
}
Ok(Self {
current,
+ anvil_champions,
pickable,
- crowd_favorites,
+ excluded,
})
}
@@ -100,22 +138,154 @@ impl ChampSelect {
rows.iter().find(|r| r.champion.id == id)
}
+ /// Whether the local player can still pick this champion. Their own pick always stays
+ /// pickable.
+ pub fn can_pick(&self, id: u32) -> bool {
+ self.current == Some(id) || (self.pickable.contains(&id) && !self.excluded.contains(&id))
+ }
+
+ /// Whether both selections offer the same champions, whatever the current pick. The shared
+ /// set makes the common case a pointer comparison.
+ pub fn same_pickable(&self, other: &Self) -> bool {
+ (Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable)
+ && self.excluded == other.excluded
+ }
+
+ /// A champion still to complete in the Challenge and pickable in this draft. The player's
+ /// own hovered or locked champion stays in the list while not Completed: they can pick it.
pub fn remaining(&self, row: &ChampionRow) -> bool {
- row.state.is_some_and(|s| s != ChampionState::Completed)
- && self.pickable.contains(&row.champion.id)
+ row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id)
+ }
+}
+
+/// The champion lists of a draft: fetched once, then updated from the client's events.
+#[derive(Debug, Default)]
+pub(crate) struct ChampSelectLists {
+ /// The client's pickable list, before the disabled champions are removed.
+ offered: HashSet,
+ disabled: HashSet,
+ anvil: Vec,
+ /// `offered` minus `disabled`, rebuilt only when either list changes.
+ pickable: Arc>,
+}
+
+impl ChampSelectLists {
+ pub(crate) fn fetch(
+ pickable: &str,
+ disabled: &str,
+ anvil: Option<&str>,
+ ) -> Result {
+ let mut lists = Self {
+ offered: ids(pickable)?,
+ disabled: ids(disabled)?,
+ ..Self::default()
+ };
+ if let Some(body) = anvil
+ && let Ok(value) = parse(body)
+ && let Some(ids) = ordered_ids(&value)
+ {
+ lists.anvil = ids;
+ }
+ lists.rebuild();
+ Ok(lists)
+ }
+
+ fn rebuild(&mut self) {
+ self.pickable = Arc::new(self.offered.difference(&self.disabled).copied().collect());
+ }
+
+ pub(crate) fn pickable(&self) -> Arc> {
+ self.pickable.clone()
+ }
+
+ pub(crate) fn anvil(&self) -> &[u32] {
+ &self.anvil
+ }
+
+ /// Applies one client event. Returns false when the topic concerns something else; the lists
+ /// it does not concern are left untouched.
+ pub(crate) fn apply_event(&mut self, topic: &str, data: &Value) -> bool {
+ match topic {
+ PICKABLE_EVENT => {
+ if let Some(ids) = ids_from_event(data) {
+ self.offered = ids;
+ self.rebuild();
+ }
+ true
+ }
+ DISABLED_EVENT => {
+ if let Some(ids) = ids_from_event(data) {
+ self.disabled = ids;
+ self.rebuild();
+ }
+ true
+ }
+ ANVIL_EVENT => {
+ if let Some(ids) = ordered_ids(data) {
+ self.anvil = ids;
+ }
+ true
+ }
+ _ => false,
+ }
}
}
#[cfg(test)]
mod tests {
use super::*;
+ use serde_json::json;
#[test]
- fn pickable_excludes_disabled_unowned_and_unavailable_champions() {
- let owned = r#"[{"id":1,"ownership":{"owned":true}},{"id":2,"ownership":{"owned":false}},{"id":3,"ownership":{"owned":true}},{"id":4,"ownership":{"owned":true}}]"#;
+ fn pickable_excludes_disabled_champions() {
assert_eq!(
- ChampSelect::available_champions("[1,2,3]", "[3]", owned).unwrap(),
- HashSet::from([1])
+ &*ChampSelect::pickable_champions("[1,2,3]", "[3]").unwrap(),
+ &HashSet::from([1, 2])
);
}
+
+ #[test]
+ fn the_lists_change_only_for_the_events_that_concern_them() {
+ let mut lists = ChampSelectLists::fetch("[1,2,3]", "[3]", Some("[9,8]")).unwrap();
+ assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
+ assert_eq!(lists.anvil(), [9, 8]);
+
+ // A gameflow event used to clear the whole cache, costing three requests again.
+ assert!(!lists.apply_event(
+ "OnJsonApiEvent_lol-gameflow_v1_session",
+ &json!({"phase": "ChampSelect"})
+ ));
+ assert_eq!(&*lists.pickable(), &HashSet::from([1, 2]));
+ assert_eq!(lists.anvil(), [9, 8]);
+
+ assert!(lists.apply_event(PICKABLE_EVENT, &json!([1, 4])));
+ assert_eq!(&*lists.pickable(), &HashSet::from([1, 4]));
+ assert_eq!(lists.anvil(), [9, 8]);
+
+ assert!(lists.apply_event(DISABLED_EVENT, &json!([1])));
+ assert_eq!(&*lists.pickable(), &HashSet::from([4]));
+
+ assert!(lists.apply_event(ANVIL_EVENT, &json!([5, 6])));
+ assert_eq!(lists.anvil(), [5, 6]);
+ }
+
+ #[test]
+ fn the_anvil_champions_are_read_once_when_the_draft_starts() {
+ assert!(
+ ChampSelectLists::fetch("[]", "[]", None)
+ .unwrap()
+ .anvil()
+ .is_empty()
+ );
+ assert_eq!(
+ ChampSelectLists::fetch("[]", "[]", Some("[1,2]"))
+ .unwrap()
+ .anvil(),
+ [1, 2]
+ );
+ // A malformed anvil answer only loses the anvil list, not the pickable one.
+ let lists = ChampSelectLists::fetch("[7]", "[]", Some("not json")).unwrap();
+ assert_eq!(&*lists.pickable(), &HashSet::from([7]));
+ assert!(lists.anvil().is_empty());
+ }
}
diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs
index afedbf4..0210a80 100644
--- a/crates/core/src/client.rs
+++ b/crates/core/src/client.rs
@@ -12,12 +12,41 @@ pub trait GameClientSource: Send + Sync {
fn champ_select(&self) -> Result {
Err(ClientError::Absent)
}
- /// Blocks until the client reports a change or `timeout` elapses.
- fn wait_for_change(&self, timeout: Duration);
- /// True when only the live selection needs another read.
- fn wait_for_selection_event(&self, timeout: Duration) -> bool {
- self.wait_for_change(timeout);
- false
+ /// Blocks until the client reports an event or `timeout` elapses, and says which kind it was.
+ fn wait_for_event(&self, timeout: Duration) -> ClientEvent;
+}
+
+/// What a wait saw: a champ select change, or anything else (gameflow, summoner, a timeout).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum ClientEvent {
+ /// The champ select session or one of its champion lists changed.
+ Selection,
+ /// Anything else.
+ #[default]
+ Other,
+}
+
+/// One read of the client, shared by the follower round and the live selection: a wake makes one
+/// gameflow request, not one per reader.
+#[derive(Clone, Debug)]
+pub struct ClientSnapshot {
+ pub signed_in: Result<(String, String), ClientError>,
+ pub gameflow: Result,
+}
+
+impl ClientSnapshot {
+ pub fn read(source: &dyn GameClientSource) -> Self {
+ Self {
+ signed_in: source.signed_in(),
+ gameflow: source.gameflow(),
+ }
+ }
+
+ pub fn absent() -> Self {
+ Self {
+ signed_in: Err(ClientError::Absent),
+ gameflow: Err(ClientError::Absent),
+ }
}
}
@@ -58,6 +87,13 @@ pub struct Gameflow {
pub game_id: Option,
}
+impl Gameflow {
+ /// The only time the live pick is shown.
+ pub fn is_arena_champ_select(&self) -> bool {
+ self.arena && self.phase == GamePhase::ChampSelect
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -84,4 +120,16 @@ mod tests {
assert_eq!(GamePhase::from_client(name), phase, "{name}");
}
}
+
+ #[test]
+ fn only_an_arena_champ_select_shows_the_live_pick() {
+ let flow = |phase, arena| Gameflow {
+ phase,
+ arena,
+ game_id: None,
+ };
+ assert!(flow(GamePhase::ChampSelect, true).is_arena_champ_select());
+ assert!(!flow(GamePhase::ChampSelect, false).is_arena_champ_select());
+ assert!(!flow(GamePhase::InGame, true).is_arena_champ_select());
+ }
}
diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs
index c60c55d..da78d11 100644
--- a/crates/core/src/follow.rs
+++ b/crates/core/src/follow.rs
@@ -5,7 +5,7 @@ use std::time::Duration;
use rusqlite::OptionalExtension;
-use crate::client::{GameClientSource, GamePhase, Gameflow};
+use crate::client::{ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow};
use crate::error::{Error, SourceError};
use crate::model::{Account, SyncProgress, SyncReport};
use crate::seasons::Season;
@@ -129,14 +129,20 @@ pub(crate) struct Follow {
official_progress: ProgressCheck,
}
-fn riot_id(account: &Account) -> String {
- format!("{}#{}", account.game_name, account.tag_line)
+/// `gameName#tagLine`, the one place a Riot ID is built.
+pub fn riot_id(game_name: &str, tag_line: &str) -> String {
+ format!("{game_name}#{tag_line}")
}
-fn same_riot_id(a: &str, b: &str) -> bool {
+/// Riot IDs differ in case only when they name the same Account.
+pub fn same_riot_id(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
+fn account_riot_id(account: &Account) -> String {
+ riot_id(&account.game_name, &account.tag_line)
+}
+
impl Tracker {
/// Without a client, it is always absent.
pub fn with_client(mut self, client: Box) -> Tracker {
@@ -191,16 +197,39 @@ impl Tracker {
now_ms: i64,
fallback_riot_id: Option<&str>,
on_progress: &mut dyn FnMut(SyncProgress),
+ ) -> bool {
+ self.follow_client_with(
+ now_ms,
+ fallback_riot_id,
+ &self.client_snapshot(),
+ on_progress,
+ )
+ }
+
+ /// One read of the client for this wake; the follower round and the live selection share it.
+ pub fn client_snapshot(&self) -> ClientSnapshot {
+ match &self.client {
+ Some(client) => ClientSnapshot::read(client.as_ref()),
+ None => ClientSnapshot::absent(),
+ }
+ }
+
+ /// A follower round on a client read already made for this wake.
+ pub fn follow_client_with(
+ &self,
+ now_ms: i64,
+ fallback_riot_id: Option<&str>,
+ snapshot: &ClientSnapshot,
+ on_progress: &mut dyn FnMut(SyncProgress),
) -> bool {
let before = self.status();
let mut added = 0;
- let (signed_in, gameflow) = match &self.client {
- Some(client) => match client.signed_in() {
- Ok((name, tag)) => (Some(format!("{name}#{tag}")), client.gameflow().ok()),
- Err(_) => (None, None),
- },
- None => (None, None),
- };
+ let signed_in = snapshot
+ .signed_in
+ .as_ref()
+ .ok()
+ .map(|(name, tag)| riot_id(name, tag));
+ let gameflow = snapshot.gameflow.as_ref().ok().cloned();
let adopt = {
let mut follow = self.follow();
if let Some(id) = fallback_riot_id.map(str::trim).filter(|id| !id.is_empty()) {
@@ -287,7 +316,7 @@ impl Tracker {
.follow()
.updating
.as_ref()
- .is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) =>
+ .is_some_and(|a| same_riot_id(&account_riot_id(a), signed_in)) =>
{
client
.official_progress(&track)
@@ -303,29 +332,51 @@ impl Tracker {
self.status() != before || added > 0
}
- /// The signed-in Riot ID and its live pick. Independent of slow Match history imports.
- pub fn champ_select(&self) -> Option> {
- let client = self.client.as_ref()?;
- let flow = client.gameflow().ok()?;
- (flow.arena && flow.phase == GamePhase::ChampSelect).then(|| {
- let (name, tag) = client.signed_in()?;
- Ok((format!("{name}#{tag}"), client.champ_select()?))
- })
+ /// The signed-in Riot ID and its live pick, independent of slow Match history imports.
+ /// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select
+ /// is running.
+ pub fn champ_select(&self) -> Result