Show live Arena champion picks and crowd favorites (#13)

This commit is contained in:
nessar authored and nessar committed 2026-11-19 22:17:14 +01:00
1 parent fabaa8a60f
commit f4a9e5e7a8
11 files changed
+636 -39

No files matched your search

+13
View File
@@ -194,6 +194,19 @@ impl ChampionTable {
}
}
/// Prepared on pick/statistics changes so a redraw only lays out the labels.
pub fn pick_labels(row: &ChampionRow) -> Vec<SharedString> {
SPECS
.iter()
.map(|spec| {
if spec.key == SortKey::Champion {
return row.champion.name.clone().into();
}
format!("{} · {}", spec.title, cell_text(row, spec.key)).into()
})
.collect()
}
/// A cell of `spec`'s column, header or body: fixed width, shrinking with the window.
// Text past it is clipped: an ellipsis (`text_ellipsis`) cost 0.2 ms per frame (#31).
fn cell(spec: &Spec) -> Div {
+14 -1
View File
@@ -43,6 +43,7 @@ struct RootView {
fallback_riot_id: String,
tx: Sender<Msg>,
_form_events: Subscription,
_champ_select: Subscription,
}
impl RootView {
@@ -82,10 +83,22 @@ impl RootView {
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
}
this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Page;
this.focus.focus(window, cx);
cx.notify();
});
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, _: &stats_page::ChampSelectTransition, window, cx| {
if this.screen == Screen::Settings {
this.screen = Screen::Page;
this.focus.focus(window, cx);
cx.notify();
}
},
);
let screen = if first_launch {
Screen::Prompt
} else {
@@ -101,6 +114,7 @@ impl RootView {
fallback_riot_id: riot_id,
tx,
_form_events: form_events,
_champ_select: champ_select,
}
}
@@ -120,7 +134,6 @@ impl Render for RootView {
let settings = settings_button(self.screen == Screen::Page, cx).on_click(cx.listener(
|this, _, window, cx| {
if this.screen == Screen::Page {
this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Settings;
this.focus.focus(window, cx);
cx.notify();
+255 -16
View File
@@ -4,8 +4,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
Account, ChallengeSummary, ChampSelect, ChampionSearch, Charts, Format, ProgressCheck, Scope,
SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::StyledExt as _;
@@ -76,12 +76,18 @@ impl SelectItem for AccountItem {
}
}
pub struct ChampSelectTransition;
impl EventEmitter<ChampSelectTransition> for StatsPage {}
pub struct StatsPage {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
selection: crate::worker::Selection,
current_pick: Vec<SharedString>,
favorites: Vec<SharedString>,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
@@ -242,6 +248,9 @@ impl StatsPage {
tracker,
tx,
notice,
selection: None,
current_pick: Vec::new(),
favorites: Vec::new(),
accounts: Vec::new(),
last_active: None,
pinned: None,
@@ -337,14 +346,39 @@ impl StatsPage {
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::Selection(selection) => {
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 switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id);
let pool_changed =
previous.map(|(_, s)| &s.pickable) != next.map(|(_, s)| &s.pickable);
self.selection = selection;
if switch {
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.stored = None;
self.reload_in_background(window, cx);
}
if changed_page {
cx.emit(ChampSelectTransition);
}
self.update_picks();
if pool_changed || switch {
self.refresh_table(cx);
}
}
Msg::Round { status, reload } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
let unchanged = status == self.status
if status == self.status
&& !reload
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed;
if unchanged {
&& !self.crashed
{
return;
}
self.status = status;
@@ -449,6 +483,26 @@ impl StatsPage {
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
if self.selection.is_some() {
if computing {
self.stats_generation += 1;
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
self.current_season = self
.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();
return self
.accounts
.iter()
.find(|a| riot_id(a).to_lowercase() == id)
.filter(|_| self.current_season.is_some())
.map(|a| a.puuid.clone());
}
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
@@ -470,6 +524,21 @@ impl StatsPage {
viewed
}
fn statistics_scope(&self) -> Scope {
if self.selection.is_some()
&& 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(
@@ -481,10 +550,7 @@ impl StatsPage {
let viewed = self.prepare_statistics(start_job, window, cx);
if let Some(puuid) = viewed {
if start_job {
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
let scope = self.statistics_scope();
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
@@ -512,10 +578,7 @@ impl StatsPage {
self.stats_error = None;
self.stored = None;
if let Some(puuid) = &viewed {
let scope = Scope {
season: self.season.clone(),
format: self.format,
};
let scope = self.statistics_scope();
match self.tracker.statistics(puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")),
@@ -527,6 +590,12 @@ impl StatsPage {
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.selection.is_some() {
self.update_picks();
self.refresh_table(cx);
cx.notify();
return;
}
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
self.charts
@@ -546,19 +615,134 @@ impl StatsPage {
cx.notify();
}
fn live_pick(&self) -> Option<&ChampSelect> {
self.selection.as_ref()?.as_ref().ok().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
.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)
})
})
.collect();
self.favorites.sort();
self.current_pick = current;
}
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.filter(|row| match &self.selection {
Some(Ok((_, pick))) => pick.remaining(row),
Some(Err(_)) => false,
None => self.filter.keeps(row) && self.search.matches(&row.champion),
})
.cloned()
.collect();
let in_season = self.in_season();
let in_season = self.selection.is_some() || self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
});
}
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()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Sélection des champions · Arena"),
);
let Some(pick) = pick else {
return page.child("Sélection indisponible dans le client.");
};
page = page.child(match self.current_pick.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(pick.current.map_or_else(
|| "Aucun champion sélectionné".to_owned(),
|id| format!("Champion {id} · Statistiques indisponibles"),
)),
});
page.child(
div()
.v_flex()
.gap_2()
.p_3()
.border_1()
.border_color(border)
.rounded_md()
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.child("Favoris du public · Enclume"),
)
.child(
div()
.h_flex()
.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")
}),
),
)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.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()
}))
})
.when(self.stats.is_some(), |page| {
page.child(div().flex_1().min_h_0().child(self.table.clone()))
})
}
/// One line each, the most important first; the stored data stays visible under all.
fn banners(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
@@ -859,6 +1043,9 @@ impl Render for StatsPage {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
if self.selection.is_some() {
return self.champ_select_view(cx);
}
let options = filters(self.in_season());
let selected = options.iter().position(|(_, f)| *f == self.filter);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
@@ -1110,6 +1297,58 @@ mod tests {
});
}
#[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 {
current: Some(39),
pickable: [39].into(),
crowd_favorites: Some(vec![39]),
};
window.update(|w, cx| {
page.update(cx, |p, 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::Selection(Some(Ok(("Alice#EUW".into(), pick)))), w, cx);
})
});
cx.condition(&page, |p, _| !p.current_pick.is_empty()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.current_pick[0].as_ref(), "Irelia");
assert!(
p.current_pick
.iter()
.any(|l| l.starts_with("Tentatives · 1"))
);
assert_eq!(p.favorites.len(), 1);
assert!(p.favorites[0].starts_with("Irelia · "));
assert_eq!(p.table.read(cx).names(), ["Irelia"]);
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::Selection(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!(p.table.read(cx).names().is_empty());
});
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
+48 -13
View File
@@ -6,16 +6,24 @@ use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker};
use arena_tracker_core::{
ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker,
};
use gpui_kit::base::async_util::Sender;
pub type Selection = Option<Result<(String, ChampSelect), ClientError>>;
pub enum Msg {
Selection(Selection),
/// A sync is fetching Matches.
Progress(SyncProgress),
/// The champion catalog and portraits were refreshed.
Champions,
/// A follower round ended; `reload` when the stored data may have changed.
Round { status: Status, reload: bool },
Round {
status: Status,
reload: bool,
},
/// A refresh ended.
Refreshed(Status),
/// Statistics for a requested scope were computed.
@@ -103,8 +111,7 @@ fn spawn_guarded(tx: Sender<Msg>, on_panic: Msg, body: impl FnOnce(&Sender<Msg>)
});
}
/// Keeps the active Account up to date for as long as the app runs: one thread, rounds of
/// `follow_client` separated by `wait_for_client`. `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. `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<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
@@ -113,20 +120,48 @@ pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sende
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
// Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks.
let (wake, rounds) = std::sync::mpsc::sync_channel(1);
let history = tracker.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;
loop {
let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| {
for () in rounds {
let changed = history.follow_client(now_ms(), fallback, &mut |progress| {
let _ = tx.try_send(Msg::Progress(progress));
});
let status = tracker.status();
let _ = tx.try_send(Msg::Round {
status,
reload: changed || first,
});
if tx
.try_send(Msg::Round {
status: history.status(),
reload: changed || first,
})
.is_err()
{
break;
}
first = false;
tracker.wait_for_client();
}
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
let mut previous = None;
let mut selection_only = false;
while !tx.is_closed() {
if !selection_only
&& 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();
}
});
}