Add the « Parties » tab: the Account's Matches and their recap (#123)

Newest first, the most recent chosen at each opening; teams by Placement
with the Account highlighted, and « Indisponible » where the source says
nothing. The list is its own virtualized view; below 900 px it goes behind
a button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-24 00:20:35 +01:00
1 parent 9999a68be5
commit beb5e5037b
25 files changed
+2367 -30

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
//! The player's wall clock: a Match's start as the date and time Windows shows, with the
//! daylight saving time in force on that day, not today's.
use arena_tracker_core::Date;
/// A day and a time of day on the player's clock.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalTime {
pub date: Date,
pub hour: u8,
pub minute: u8,
}
impl LocalTime {
/// The UTC day and time of that instant: the clock where Windows cannot tell.
pub fn utc(epoch_ms: i64) -> LocalTime {
const MS_PER_MINUTE: i64 = 60_000;
let minutes = epoch_ms.rem_euclid(86_400_000) / MS_PER_MINUTE;
LocalTime {
date: Date::from_ms(epoch_ms),
hour: (minutes / 60) as u8,
minute: (minutes % 60) as u8,
}
}
}
/// That instant on the player's clock.
pub fn local_time(epoch_ms: i64) -> LocalTime {
#[cfg(windows)]
if let Some(local) = windows::local_time(epoch_ms) {
return local;
}
LocalTime::utc(epoch_ms)
}
#[cfg(windows)]
mod windows {
use super::LocalTime;
use arena_tracker_core::Date;
#[repr(C)]
#[derive(Default)]
struct FileTime {
low: u32,
high: u32,
}
#[repr(C)]
#[derive(Default)]
struct SystemTime {
year: u16,
month: u16,
day_of_week: u16,
day: u16,
hour: u16,
minute: u16,
second: u16,
milliseconds: u16,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn FileTimeToSystemTime(file_time: *const FileTime, system_time: *mut SystemTime) -> i32;
fn SystemTimeToTzSpecificLocalTime(
time_zone: *const core::ffi::c_void,
universal: *const SystemTime,
local: *mut SystemTime,
) -> i32;
}
/// Milliseconds from 1601-01-01, where Windows counts from, to 1970-01-01.
const EPOCH_FROM_1601_MS: i64 = 11_644_473_600_000;
/// `None` when Windows refuses the instant.
pub(super) fn local_time(epoch_ms: i64) -> Option<LocalTime> {
let ticks = u64::try_from(epoch_ms.checked_add(EPOCH_FROM_1601_MS)?)
.ok()?
.checked_mul(10_000)?;
let file_time = FileTime {
low: ticks as u32,
high: (ticks >> 32) as u32,
};
let (mut universal, mut local) = (SystemTime::default(), SystemTime::default());
// SAFETY: both structures are the Win32 layouts, alive for the calls; a null time zone
// is the one in force.
let converted = unsafe {
FileTimeToSystemTime(&file_time, &mut universal) != 0
&& SystemTimeToTzSpecificLocalTime(core::ptr::null(), &universal, &mut local) != 0
};
converted.then(|| LocalTime {
date: Date {
year: i32::from(local.year),
month: local.month as u8,
day: local.day as u8,
},
hour: local.hour as u8,
minute: local.minute as u8,
})
}
}
#[cfg(test)]
mod tests {
use super::{LocalTime, local_time};
use arena_tracker_core::Date;
#[test]
fn the_utc_clock_splits_the_instant() {
// 2026-11-15 17:29:12 UTC.
let time = LocalTime::utc(1_794_763_752_767);
assert_eq!(
time,
LocalTime {
date: Date {
year: 2026,
month: 11,
day: 15
},
hour: 17,
minute: 29,
}
);
}
#[test]
fn the_local_clock_is_whole_minutes_away_from_utc() {
// Whatever the machine's time zone: at most 14 hours away, by whole quarter hours.
let at = 1_794_763_752_767;
let local = local_time(at);
let minutes = |t: LocalTime| {
(Date::start_ms(&t.date) / 60_000) + i64::from(t.hour) * 60 + i64::from(t.minute)
};
let shift = minutes(local) - minutes(LocalTime::utc(at));
assert!(shift.abs() <= 14 * 60 && shift % 15 == 0, "{shift}");
}
}
+2
View File
@@ -7,6 +7,7 @@ mod card_images;
mod card_lift;
mod card_order;
mod champion_table;
mod local_time;
mod logon;
mod minimized;
mod motion;
@@ -321,6 +322,7 @@ fn main() {
app.run(move |cx| {
gpui_kit::init(cx);
card_grid::init(cx);
page::init(cx);
theme::init(cx);
#[cfg(feature = "profile")]
profile::start(cx);
+15 -5
View File
@@ -1,6 +1,6 @@
//! The page and its screens: the shared state. `navigation` switches between them, `display`
//! renders the header row and the alerts; `home`, `champ_select` and `statistics` render the
//! content under them.
//! renders the header row and the alerts; `home`, `champ_select`, `statistics` and `matches`
//! render the content under them.
use crate::banner_art::BannerArt;
use crate::card::Card;
@@ -35,6 +35,7 @@ mod home;
mod hover;
mod lifecycle;
mod links;
mod matches;
mod navigation;
mod playback;
mod profiling;
@@ -46,6 +47,11 @@ mod worker_messages;
#[cfg(test)]
mod tests;
/// Binds the keys of the page's own views.
pub(crate) fn init(cx: &mut App) {
matches::init(cx);
}
/// 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";
@@ -102,15 +108,17 @@ impl EventEmitter<ChampSelectTransition> for Page {}
pub struct ChampionSortChosen(pub ChampionSort);
impl EventEmitter<ChampionSortChosen> for Page {}
/// The screens the page switches between: « Défi » is a tab of the top bar, « Statistiques »
/// its detail page, opened from the banner, and « Sélection » the tab of a phase, there only
/// while an Arena champ select runs.
/// The screens the page switches between: « Défi » and « Parties » are tabs of the top bar,
/// « Statistiques » the Challenge's detail page, opened from the banner, and « Sélection » the
/// tab of a phase, there only while an Arena champ select runs.
#[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,
/// « Parties »: the Matches of the Challenge's Account and the recap of one.
Matches,
/// « Sélection »: the champ select's banner, its Anvil champions and « Autres champions ».
ChampSelect,
}
@@ -306,6 +314,8 @@ pub struct Page {
champ_select_scrollbar: Entity<PageScrollbar>,
/// The section's header button, which the keyboard reaches.
others_focus: FocusHandle,
/// « Parties »: its list, its recap and the jobs that read them.
matches: matches::Matches,
/// Lights the ring's tick of the card hovered in « Autres champions », lifts it, and scrolls the
/// champ select to the card the keyboard reaches; its grid is made again at each fold.
others_hover: [Subscription; 3],
+6 -2
View File
@@ -140,8 +140,11 @@ impl Render for Page {
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The champ select is about the signed-in Account.
.disabled(self.in_champ_select())
// The champ select is about the signed-in Account,
// « Parties » about the Challenge's.
.disabled(
self.in_champ_select() || self.tab == Tab::Matches,
)
.w(px(260.))
.min_w(px(150.)),
)
@@ -179,6 +182,7 @@ impl Render for Page {
.children(match self.shown_tab {
Tab::Challenge => self.home_content(window, cx),
Tab::Statistics => self.statistics_content(cx),
Tab::Matches => self.matches_content(window, cx),
Tab::ChampSelect => self.champ_select_content(window, cx),
})
.when(self.fade.is_some(), |screen| {
+2 -2
View File
@@ -42,7 +42,7 @@ impl Page {
pub(in crate::page) 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.shown_tab, &self.season) {
(Tab::Challenge | Tab::ChampSelect, _) => self.home_season.as_deref(),
(Tab::Challenge | Tab::ChampSelect | Tab::Matches, _) => self.home_season.as_deref(),
(Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()),
(Tab::Statistics, SeasonScope::AllSeasons) => None,
};
@@ -53,7 +53,7 @@ impl Page {
/// The tab's own statistics error: the home may have computed its own.
pub(in crate::page) fn error(&self) -> Option<&String> {
match (self.shown_tab, &self.home_scope) {
(Tab::Challenge | Tab::ChampSelect, Some(_)) => self.home_error.as_ref(),
(Tab::Challenge | Tab::ChampSelect | Tab::Matches, Some(_)) => self.home_error.as_ref(),
_ => self.stats_error.as_ref(),
}
}
+1
View File
@@ -24,6 +24,7 @@ impl Page {
.update(cx, |art, cx| art.release(window, cx));
self.table
.update(cx, |table, cx| table.release_images(window, cx));
self.release_matches_images(window, cx);
}
/// The page is back in front of « Paramètres ».
+377
View File
@@ -0,0 +1,377 @@
//! « Parties »: the stored Matches of the Challenge's Account, newest first, and beside them the
//! Match Recap of the one chosen. The list is read on a worker when the screen shows (or the
//! stored Matches change while it does), and only the Match chosen is decoded, on a worker too:
//! nothing runs while the screen is hidden but marking the list stale (rule #1).
mod list;
mod recap;
mod screen;
mod shown;
pub(in crate::page) use list::MatchList;
#[cfg(test)]
pub(in crate::page) use list::MatchRow as Row;
pub use list::init;
use list::{MatchChosen, MatchRow};
use shown::{Champions, ShownRecap};
#[cfg(test)]
pub(in crate::page) use shown::{ShownPlayer, Slot, UNAVAILABLE};
use super::{Page, Tab};
use crate::card_images::CardImages;
use crate::text::ordinal;
use crate::worker::{MatchEntry, RefreshGate, spawn_match_list, spawn_recap};
use arena_tracker_core::MatchRecap;
use gpui_kit::*;
/// The recap beside the list.
pub(in crate::page) enum Recap {
/// No Match chosen.
None,
/// The Match chosen is being decoded.
Loading,
/// The Match is no longer stored.
Missing,
Failed(SharedString),
Ready {
recap: Box<MatchRecap>,
shown: Box<ShownRecap>,
},
}
/// The state of « Parties ».
pub(in crate::page) struct Matches {
/// Its own view: the selection, the scrolling and the hover.
pub(in crate::page) list: Entity<MatchList>,
/// The Account the list is of.
puuid: Option<String>,
/// Its Matches, newest first; `None` until the first list of that Account arrives.
entries: Option<Vec<MatchEntry>>,
/// Why the last list failed: the Matches already known stay.
error: Option<SharedString>,
/// The stored Matches may have changed since the list was read.
stale: bool,
job: RefreshGate,
generation: u64,
/// The Match chosen. Not kept from one opening of the screen to the next.
pub(in crate::page) selected: Option<String>,
pub(in crate::page) recap: Recap,
recap_job: RefreshGate,
recap_generation: u64,
/// The portraits of the recap, given back when the screen hides.
recap_images: Entity<CardImages>,
/// In a narrow window, the list is open over the recap.
pub(in crate::page) list_open: bool,
_chosen: Subscription,
}
impl Matches {
pub(in crate::page) fn new(cx: &mut Context<Page>) -> Matches {
let list = cx.new(MatchList::new);
let chosen = cx.subscribe(&list, |page, _, event: &MatchChosen, cx| {
page.choose_match(event.match_id.clone(), event.close, cx)
});
Matches {
list,
puuid: None,
entries: None,
error: None,
stale: true,
job: RefreshGate::default(),
generation: 0,
selected: None,
recap: Recap::None,
recap_job: RefreshGate::default(),
recap_generation: 0,
recap_images: CardImages::new(cx),
list_open: false,
_chosen: chosen,
}
}
#[cfg(test)]
pub(in crate::page) fn entries(&self) -> Option<&[MatchEntry]> {
self.entries.as_deref()
}
#[cfg(test)]
pub(in crate::page) fn recap_images(&self) -> &Entity<CardImages> {
&self.recap_images
}
#[cfg(test)]
pub(in crate::page) fn generation(&self) -> u64 {
self.generation
}
/// A list or a recap is being read.
#[cfg(test)]
pub(in crate::page) fn reading(&self) -> bool {
self.job.running() || self.recap_job.running()
}
#[cfg(test)]
pub(in crate::page) fn error(&self) -> Option<&SharedString> {
self.error.as_ref()
}
/// The recap shown, once decoded.
#[cfg(test)]
pub(in crate::page) fn shown(&self) -> Option<&ShownRecap> {
match &self.recap {
Recap::Ready { shown, .. } => Some(shown),
_ => None,
}
}
}
impl Page {
/// The stored Matches or the Account may have changed. The list follows the Challenge's
/// Account at once, never mixing two Accounts' Matches, and is read again while it shows;
/// hidden, it is only marked stale.
pub(in crate::page) fn matches_changed(&mut self, cx: &mut Context<Self>) {
let puuid = self.displayed().map(|a| a.puuid.clone());
let matches = &mut self.matches;
if puuid != matches.puuid {
matches.puuid = puuid;
matches.entries = None;
matches.error = None;
matches.selected = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
matches.list_open = false;
matches
.list
.update(cx, |list, cx| list.set_rows(Vec::new(), None, cx));
}
matches.stale = true;
if self.shown_tab == Tab::Matches {
self.request_matches();
}
}
/// Reads the list on a worker, or queues the reading behind the one running: an earlier
/// result is stale.
fn request_matches(&mut self) {
let matches = &mut self.matches;
matches.stale = false;
matches.generation += 1;
if matches.puuid.is_some() && matches.job.request() {
self.spawn_match_list();
}
}
/// Starts the reading the gate let through; none while the screen is hidden.
fn spawn_match_list(&mut self) {
match self.matches.puuid.clone() {
Some(puuid) if self.shown_tab == Tab::Matches => spawn_match_list(
self.tracker.clone(),
puuid,
self.matches.generation,
self.tx.clone(),
),
_ => self.matches.job.reset(),
}
}
/// The screen arrives: the list is read again if the stored Matches changed, and the most
/// recent Match is chosen, the previous choice forgotten.
pub(in crate::page) fn open_matches(&mut self, cx: &mut Context<Self>) {
let matches = &mut self.matches;
matches.selected = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
matches.list_open = false;
matches.list.update(cx, |list, _| list.scroll_to_top());
if matches.stale || matches.entries.is_none() {
// The most recent is chosen when the list arrives.
self.request_matches();
} else {
self.choose_newest();
}
self.dress_matches(cx);
}
/// The screen leaves: the recap goes, and the portraits of both sides. A list or a recap
/// still being read is dropped, and nothing queued starts.
pub(in crate::page) fn close_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let matches = &mut self.matches;
matches.generation += 1;
matches.stale = true;
matches.selected = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
self.release_matches_images(window, cx);
}
pub(in crate::page) fn release_matches_images(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.matches
.list
.update(cx, |list, cx| list.release_images(window, cx));
self.matches
.recap_images
.update(cx, |images, cx| images.release(window, cx));
}
/// A list read by the worker.
pub(in crate::page) fn apply_matches(
&mut self,
generation: u64,
result: Result<Vec<MatchEntry>, String>,
cx: &mut Context<Self>,
) {
if generation == self.matches.generation {
match result {
Ok(entries) => self.show_matches(entries, cx),
// The Matches already known stay.
Err(error) => self.matches.error = Some(error.into()),
}
}
if self.matches.job.finished() {
self.spawn_match_list();
}
}
fn show_matches(&mut self, entries: Vec<MatchEntry>, cx: &mut Context<Self>) {
let matches = &mut self.matches;
matches.error = None;
let previous = matches.entries.replace(entries).unwrap_or_default();
let entries = matches.entries.as_deref().unwrap_or_default();
// The Match chosen stays chosen while it is listed, as a sync lists them again.
let kept = (matches.selected.as_ref())
.and_then(|id| entries.iter().find(|entry| entry.match_id == *id))
// Published or corrected meanwhile: decoded again.
.map(|entry| previous.contains(entry));
match kept {
Some(true) => {}
Some(false) => self.request_recap(),
None => self.choose_newest(),
}
self.dress_matches(cx);
}
fn choose_newest(&mut self) {
let newest = (self.matches.entries.iter().flatten().next()).map(|e| e.match_id.clone());
self.matches.selected = newest;
self.request_recap();
}
/// The list chose a Match: its recap is decoded.
fn choose_match(&mut self, match_id: String, close: bool, cx: &mut Context<Self>) {
if close {
self.matches.list_open = false;
}
if self.matches.selected.as_deref() != Some(match_id.as_str()) {
self.matches.selected = Some(match_id);
self.request_recap();
}
cx.notify();
}
/// Decodes the Match chosen on a worker, one at a time: a choice made meanwhile is decoded
/// once it reports, and its result dropped.
fn request_recap(&mut self) {
let matches = &mut self.matches;
matches.recap_generation += 1;
let Some(selected) = &matches.selected else {
matches.recap = Recap::None;
return;
};
// The same Match decoded again keeps its recap until the new one arrives.
let same =
matches!(&matches.recap, Recap::Ready { recap, .. } if recap.match_id == *selected);
if !same {
matches.recap = Recap::Loading;
}
if matches.recap_job.request() {
self.spawn_recap();
}
}
/// Starts the decoding the gate let through; none while the screen is hidden.
fn spawn_recap(&mut self) {
let matches = &self.matches;
match (&matches.puuid, &matches.selected) {
(Some(puuid), Some(selected)) if self.shown_tab == Tab::Matches => spawn_recap(
self.tracker.clone(),
puuid.clone(),
selected.clone(),
matches.recap_generation,
self.tx.clone(),
),
_ => self.matches.recap_job.reset(),
}
}
/// A Match Recap decoded by the worker.
pub(in crate::page) fn apply_recap(
&mut self,
generation: u64,
result: Result<Option<MatchRecap>, String>,
cx: &mut Context<Self>,
) {
if generation == self.matches.recap_generation {
self.matches.recap = match result {
Ok(Some(recap)) => {
let champions = self.champions();
let shown = ShownRecap::new(&recap, self.chosen_champion(), &champions);
Recap::Ready {
recap: Box::new(recap),
shown: Box::new(shown),
}
}
Ok(None) => Recap::Missing,
Err(error) => Recap::Failed(format!("Récapitulatif indisponible : {error}").into()),
};
}
if self.matches.recap_job.finished() {
self.spawn_recap();
}
cx.notify();
}
/// The champions' names and portraits, as the statistics have them.
fn champions(&self) -> Champions {
Champions::of(self.home_statistics().or(self.stats.as_ref()))
}
/// The champion of the Match chosen, from its row.
fn chosen_champion(&self) -> (u32, &str) {
let matches = &self.matches;
(matches.entries.iter().flatten())
.find(|entry| Some(&entry.match_id) == matches.selected.as_ref())
.map_or((0, ""), |e| (e.champion_id, e.champion_name.as_str()))
}
/// Writes the rows of the list and the recap with the champions' names and portraits, which
/// the statistics may bring after the Matches.
pub(in crate::page) fn dress_matches(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Matches && self.tab != Tab::Matches {
return;
}
let champions = self.champions();
let rows: Vec<MatchRow> = (self.matches.entries.iter().flatten())
.map(|entry| MatchRow {
match_id: entry.match_id.clone(),
champion: champions.name(entry.champion_id, &entry.champion_name),
portrait: champions.portrait(entry.champion_id),
when: entry.when.clone().into(),
placement: ordinal(entry.placement).into(),
provisional: entry.provisional,
})
.collect();
let selected = self.matches.selected.clone();
self.matches
.list
.update(cx, |list, cx| list.set_rows(rows, selected.as_deref(), cx));
let champion = self.chosen_champion();
let champion = (champion.0, champion.1.to_string());
if let Recap::Ready { recap, shown } = &mut self.matches.recap {
**shown = ShownRecap::new(recap, (champion.0, &champion.1), &champions);
}
}
}
+291
View File
@@ -0,0 +1,291 @@
//! The list of « Parties »: one row per Match, newest first, only the rows in view built. It is
//! its own view, the one part of the screen with a state of its own: the selection, the
//! scrolling and the hover. Choosing a row, with the pointer or the keyboard, tells the page,
//! which opens its Match Recap.
use std::ops::Range;
use std::path::PathBuf;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card_images::{self, CardImages};
use crate::theme::gold_ink;
actions!(match_list, [SelectPrevious, SelectNext, OpenSelected]);
/// The list's key context, where the arrows move the selection and Enter opens it.
const CONTEXT: &str = "MatchList";
const ROW_HEIGHT: f32 = 52.;
const PORTRAIT: f32 = 36.;
pub fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("up", SelectPrevious, Some(CONTEXT)),
KeyBinding::new("down", SelectNext, Some(CONTEXT)),
KeyBinding::new("enter", OpenSelected, Some(CONTEXT)),
]);
}
/// One row, written by the page when the list arrives: nothing is formatted while drawing.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct MatchRow {
pub(in crate::page) match_id: String,
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
pub(in crate::page) when: SharedString,
pub(in crate::page) placement: SharedString,
pub(in crate::page) provisional: bool,
}
/// A Match was chosen in the list; `close`: by a click or Enter, which closes the list laid
/// over the recap in a narrow window. The arrows only move the selection.
pub(in crate::page) struct MatchChosen {
pub(in crate::page) match_id: String,
pub(in crate::page) close: bool,
}
pub(in crate::page) struct MatchList {
rows: Vec<MatchRow>,
selected: Option<usize>,
scroll: UniformListScrollHandle,
focus: FocusHandle,
/// The portraits of the rows painted only (budget 4). Created at the first render.
images: Option<Entity<CardImages>>,
/// Guards the cache in tests.
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl EventEmitter<MatchChosen> for MatchList {}
impl MatchList {
pub(in crate::page) fn new(cx: &mut Context<Self>) -> MatchList {
MatchList {
rows: Vec::new(),
selected: None,
scroll: UniformListScrollHandle::new(),
focus: cx.focus_handle().tab_stop(true),
images: None,
#[cfg(test)]
renders: 0,
}
}
/// Shows `rows` with the Match `selected`; draws again only when something changed, as a
/// sync lists them again.
pub(in crate::page) fn set_rows(
&mut self,
rows: Vec<MatchRow>,
selected: Option<&str>,
cx: &mut Context<Self>,
) {
let selected_ix = selected.and_then(|id| rows.iter().position(|r| r.match_id == id));
if rows != self.rows || selected_ix != self.selected {
self.rows = rows;
self.selected = selected_ix;
cx.notify();
}
}
/// Back to the top, as at each opening of the screen.
pub(in crate::page) fn scroll_to_top(&mut self) {
self.scroll.scroll_to_item(0, ScrollStrategy::Top);
}
/// The list is not shown any more: its portraits are given back, in memory and in the
/// window's atlas.
pub(in crate::page) fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let released = (self.images.as_ref())
.is_some_and(|images| images.update(cx, |images, cx| images.release(window, cx)));
if released {
// A cached view replays its last paint unless it is drawn again.
cx.notify();
}
}
#[cfg(test)]
pub(in crate::page) fn rows(&self) -> &[MatchRow] {
&self.rows
}
#[cfg(test)]
pub(in crate::page) fn selected(&self) -> Option<&str> {
Some(self.rows.get(self.selected?)?.match_id.as_str())
}
#[cfg(test)]
pub(in crate::page) fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
fn choose(&mut self, ix: usize, close: bool, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(ix) else {
return;
};
let match_id = row.match_id.clone();
self.selected = Some(ix);
self.scroll.scroll_to_item(ix, ScrollStrategy::Nearest);
cx.emit(MatchChosen { match_id, close });
cx.notify();
}
/// The arrows: the row above or below the selection, which stays within the list.
fn step(&mut self, step: isize, cx: &mut Context<Self>) {
let last = self.rows.len().saturating_sub(1);
let target = match self.selected {
Some(ix) => ix.saturating_add_signed(step).min(last),
None => 0,
};
if Some(target) != self.selected {
self.choose(target, false, cx);
}
}
fn row(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let row = &self.rows[ix];
let selected = self.selected == Some(ix);
let selected_bg = if theme.list.active_highlight {
theme.tokens.table_active
} else {
theme.tokens.accent
};
let (muted, gold, hover, border) = (
theme.muted_foreground,
gold_ink(theme),
theme.tokens.table_hover,
theme.table_row_border,
);
let portrait = match &row.portrait {
Some(path) => img(path.clone())
.size(px(PORTRAIT))
.rounded_md()
.into_any_element(),
None => div()
.size(px(PORTRAIT))
.rounded_md()
.bg(theme.border)
.into_any_element(),
};
div()
.id(ix)
.debug_selector(move || format!("match-row-{ix}"))
.h_flex()
.w_full()
.h(px(ROW_HEIGHT))
.pl_3()
.pr(Scrollbar::width())
.gap_3()
.items_center()
.relative()
.border_b_1()
.border_color(border)
.map(|tr| {
if selected {
// A gold stroke on the left, as the selected tab's colour.
tr.bg(selected_bg).child(
div()
.absolute()
.left_0()
.top_0()
.bottom_0()
.w(px(3.))
.bg(gold),
)
} else {
tr.hover(|style| style.bg(hover))
}
})
.on_click(cx.listener(move |list, _, window, cx| {
window.focus(&list.focus, cx);
list.choose(ix, true, cx);
}))
.child(portrait)
.child(
div()
.v_flex()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(row.champion.clone()),
)
.child(div().text_xs().text_color(muted).child(row.when.clone())),
)
.child(
div()
.v_flex()
.items_end()
.flex_shrink_0()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child(row.placement.clone()),
)
.children(
(row.provisional)
.then(|| div().text_xs().text_color(gold).child("Provisoire")),
),
)
.into_any_element()
}
}
impl Render for MatchList {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
let ring = cx.theme().ring;
card_images::provide(div(), images)
.id("match-list")
.debug_selector(|| "match-list".into())
.key_context(CONTEXT)
.track_focus(&self.focus)
.on_action(cx.listener(|list, _: &SelectPrevious, _, cx| list.step(-1, cx)))
.on_action(cx.listener(|list, _: &SelectNext, _, cx| list.step(1, cx)))
.on_action(cx.listener(|list, _: &OpenSelected, _, cx| {
if let Some(ix) = list.selected {
list.choose(ix, true, cx);
}
}))
.relative()
.size_full()
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.child(
uniform_list(
"matches",
self.rows.len(),
cx.processor(|list, range: Range<usize>, _, cx| {
range.map(|ix| list.row(ix, cx)).collect::<Vec<_>>()
}),
)
.size_full()
.track_scroll(&self.scroll),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(Scrollbar::width())
.child(Scrollbar::vertical(&self.scroll)),
)
}
}
+265
View File
@@ -0,0 +1,265 @@
//! The recap of « Parties », drawn as functions of the page's render: the Match Recap of the
//! Match chosen, already written (`ShownRecap`), its teams by Placement and one line per
//! player, the Account's in gold.
use std::path::PathBuf;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::shown::{ShownPlayer, ShownRecap, ShownTeam, Slot, Value};
use crate::theme::{gold_ink, heading, surface};
const PORTRAIT: f32 = 32.;
const HEADER_PORTRAIT: f32 = 48.;
const SLOT: f32 = 24.;
fn portrait(path: Option<&PathBuf>, size: f32, theme: &Theme) -> AnyElement {
match path {
Some(path) => img(path.clone())
.size(px(size))
.flex_shrink_0()
.rounded_md()
.into_any_element(),
None => div()
.size(px(size))
.flex_shrink_0()
.rounded_md()
.bg(theme.border)
.into_any_element(),
}
}
/// A value, muted when it says its absence.
fn value(value: &Value, theme: &Theme) -> Div {
div()
.whitespace_nowrap()
.when(value.missing, |text| {
text.text_color(theme.muted_foreground)
})
.child(value.text.clone())
}
/// A caption over its value.
fn stat(caption: &'static str, shown: &Value, width: f32, theme: &Theme) -> Div {
div()
.v_flex()
.w(px(width))
.flex_shrink_0()
.child(
div()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(caption),
)
.child(value(shown, theme).text_sm())
}
/// The Account's champion, when and how the Match was played, and « Provisoire ».
pub(in crate::page) fn header(recap: &ShownRecap, cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.h_flex()
.items_center()
.gap_3()
.child(portrait(recap.portrait.as_ref(), HEADER_PORTRAIT, theme))
.child(
div()
.v_flex()
.min_w_0()
.child(heading(cx).text_2xl().child(recap.champion.clone()))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(recap.details.clone()),
),
)
.children(recap.provisional.then(|| provisional_badge(theme)))
}
/// « Provisoire »: the Match is not published by Riot yet.
pub(in crate::page) fn provisional_badge(theme: &Theme) -> impl IntoElement {
div()
.flex_shrink_0()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(gold_ink(theme))
.rounded(px(6.))
.text_xs()
.text_color(gold_ink(theme))
.debug_selector(|| "recap-provisional".into())
.child("Provisoire")
}
/// The teams by Placement, the Account's highlighted.
pub(in crate::page) fn teams(recap: &ShownRecap, cx: &App) -> impl IntoElement {
let mut index = 0;
div()
.v_flex()
.gap_3()
.children(recap.teams.iter().map(|shown| {
let first = index;
index += shown.players.len();
team(shown, first, cx)
}))
}
/// `first`: the index of its first player in the recap, which names their item slots.
fn team(shown: &ShownTeam, first: usize, cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.v_flex()
.gap_1()
.child(
value(&shown.placement, theme)
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.when(shown.account && !shown.placement.missing, |text| {
text.text_color(gold_ink(theme))
}),
)
.children(
(shown.players.iter())
.enumerate()
.map(|(ix, shown)| player(shown, first + ix, theme)),
)
}
/// One line per player: who, their level, K/D/A and damage to champions, then their items and
/// augments under their name.
fn player(shown: &ShownPlayer, ix: usize, theme: &Theme) -> impl IntoElement {
let gold = gold_ink(theme);
let identity = div()
.v_flex()
.flex_1()
.min_w(px(140.))
.overflow_hidden()
.child(
div()
.text_sm()
.whitespace_nowrap()
.font_weight(FontWeight::SEMIBOLD)
.child(shown.champion.clone()),
)
.child(value(&shown.riot_id, theme).text_xs());
div()
.v_flex()
.gap_1()
.px_2()
.py_1()
.rounded_md()
.border_1()
.map(|line| {
if shown.is_account {
line.border_color(gold)
.bg(gold.opacity(0.08))
.debug_selector(|| "recap-account".into())
} else {
line.border_color(transparent_black())
}
})
.child(
div()
.h_flex()
.items_center()
.gap_3()
.child(portrait(shown.portrait.as_ref(), PORTRAIT, theme))
.child(identity)
.child(stat("Niveau", &shown.level, 72., theme))
.child(stat("K/D/A", &shown.kda, 120., theme))
.child(stat("Dégâts aux champions", &shown.damage, 140., theme)),
)
.child(
div()
.h_flex()
.flex_wrap()
.items_center()
.gap_1()
.pl(px(PORTRAIT + 12.))
.child(items(&shown.items, ix, theme))
.child(augments(&shown.augments, theme)),
)
}
/// What stands for items or augments the source does not give: « Objets : Indisponible ».
fn absent(caption: &'static str, word: &Value, theme: &Theme) -> AnyElement {
div()
.mr_2()
.text_xs()
.whitespace_nowrap()
.text_color(theme.muted_foreground)
.child(format!("{caption} : {}", word.text))
.into_any_element()
}
fn items(slots: &Result<[Slot; 7], Value>, player: usize, theme: &Theme) -> AnyElement {
let slots = match slots {
Ok(slots) => slots,
Err(word) => return absent("Objets", word, theme),
};
div()
.h_flex()
.gap(px(3.))
.mr_2()
.children(slots.iter().enumerate().map(|(ix, slot)| {
let base = div()
.id(("recap-item", player * 7 + ix))
.size(px(SLOT))
.flex()
.items_center()
.justify_center()
.rounded(px(4.))
.border_1()
.border_color(theme.border);
match slot {
Slot::Empty => base,
Slot::Item(title) => {
let title = title.clone();
base.bg(surface(theme))
.tooltip(move |window, cx| Tooltip::new(title.clone()).build(window, cx))
.child(
Icon::new(IconName::Frame)
.xsmall()
.text_color(theme.muted_foreground),
)
}
Slot::Missing => base
.border_dashed()
.tooltip(|window, cx| Tooltip::new("Indisponible").build(window, cx)),
}
}))
.into_any_element()
}
fn augments(augments: &Result<Vec<SharedString>, Value>, theme: &Theme) -> AnyElement {
let muted = theme.muted_foreground;
match augments.as_deref() {
Err(word) => absent("Améliorations", word, theme),
Ok([]) => div()
.text_xs()
.text_color(muted)
.child("Aucune amélioration")
.into_any_element(),
Ok(augments) => div()
.h_flex()
.flex_wrap()
.gap_1()
.children(augments.iter().map(|augment| {
div()
.px(px(6.))
.py(px(1.))
.rounded(px(6.))
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.text_xs()
.child(augment.clone())
}))
.into_any_element(),
}
}
+213
View File
@@ -0,0 +1,213 @@
//! How « Parties » is laid out: the place of the banner, then the list and the recap side by
//! side, or the list behind a button in a narrow window.
use super::{Recap, recap};
use crate::card_images;
use crate::page::Page;
use crate::page::home::{StatsNotice, notice_line};
use crate::text::stored;
use crate::theme::heading;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
/// Narrower than this, the list hides behind a button and shows over the recap.
const NARROW: f32 = 900.;
const LIST_WIDTH: f32 = 320.;
impl Page {
/// Under the status messages: the place of the banner, then the list and the recap side by
/// side, the list behind a button in a narrow window.
pub(in crate::page) fn matches_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let muted = cx.theme().muted_foreground;
// The banner (#110) comes here.
let title = div()
.h_flex()
.items_center()
.debug_selector(|| "matches-banner".into())
.child(heading(cx).text_3xl().child("Parties"));
let matches = &self.matches;
let body = match (&matches.puuid, &matches.entries) {
(None, _) => notice_line("matches-notice", StatsNotice::NoAccount.label(None), muted),
(_, None) => match &matches.error {
Some(error) => self.matches_error(error, cx),
None => notice_line("matches-notice", "Chargement des Parties…".into(), muted),
},
(_, Some(entries)) if entries.is_empty() => {
notice_line("matches-notice", stored(0).into(), muted)
}
(_, Some(_)) => self.matches_split(window, cx),
};
let error = (matches.entries.is_some())
.then_some(matches.error.as_ref())
.flatten()
.map(|error| self.matches_error(error, cx));
vec![
title.into_any_element(),
div()
.v_flex()
.flex_1()
.min_h_0()
.gap_3()
.children(error)
.child(body)
.into_any_element(),
]
}
fn matches_error(&self, error: &SharedString, cx: &App) -> AnyElement {
div()
.text_sm()
.text_color(cx.theme().danger)
.debug_selector(|| "matches-error".into())
.child(error.clone())
.into_any_element()
}
/// The list (≈ 320 px) and the recap; narrower than `NARROW`, the list opens over the
/// recap from a button.
fn matches_split(&self, window: &mut Window, cx: &mut Context<Page>) -> AnyElement {
let theme = cx.theme();
let narrow = window.viewport_size().width < px(NARROW);
let list = div()
.w(px(LIST_WIDTH))
.max_w_full()
.flex_shrink_0()
.h_full()
.overflow_hidden()
.bg(theme.background)
.border_1()
.border_color(theme.border)
.rounded(theme.radius)
// A cached view: the page drawn again (the veil, the recap arriving) does not draw
// the list.
.child((self.matches.list.clone()).cached(StyleRefinement::default().size_full()));
let recap = div()
.id("recap-scroll")
.flex_1()
.min_w_0()
.h_full()
.overflow_y_scroll()
.child(self.recap_pane(window, cx));
if !narrow {
return div()
.h_flex()
.items_start()
.flex_1()
.min_h_0()
.gap_3()
.child(list)
.child(recap)
.into_any_element();
}
let open = self.matches.list_open;
div()
.v_flex()
.flex_1()
.min_h_0()
.gap_2()
.child(self.list_toggle(open, cx))
.child(
div()
.relative()
.flex()
.flex_1()
.min_h_0()
.child(recap)
.when(open, |area| {
area.child(
list.absolute()
.top_0()
.left_0()
.bottom_0()
.shadow_lg()
.debug_selector(|| "matches-list-over".into()),
)
}),
)
.into_any_element()
}
/// « Parties » with a chevron: opens the list over the recap, or closes it.
fn list_toggle(&self, open: bool, cx: &mut Context<Page>) -> impl IntoElement {
let theme = cx.theme();
let (ring, border, hover, hover_foreground) = (
theme.ring,
theme.border,
theme.accent,
theme.accent_foreground,
);
BaseButton::new("matches-list-toggle")
.self_start()
.h_flex()
.items_center()
.gap_1()
.px_3()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.border_1()
.border_color(border)
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label("Parties")
.debug_selector(|| "matches-list-toggle".into())
.child("Parties")
.child(
Icon::new(if open {
IconName::ChevronUp
} else {
IconName::ChevronDown
})
.small(),
)
.on_click(cx.listener(|page, _, _, cx| {
page.matches.list_open = !page.matches.list_open;
cx.notify();
}))
}
/// The recap of the Match chosen, or what stands in its place.
fn recap_pane(&self, window: &mut Window, cx: &mut Context<Page>) -> impl IntoElement {
let images = self.matches.recap_images.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
let muted = cx.theme().muted_foreground;
let content: Vec<AnyElement> = match &self.matches.recap {
Recap::None => Vec::new(),
Recap::Loading => vec![notice_line(
"recap-loading",
"Chargement du récapitulatif…".into(),
muted,
)],
Recap::Missing => vec![notice_line(
"recap-missing",
"Cette Partie n’est plus enregistrée.".into(),
muted,
)],
Recap::Failed(error) => vec![
div()
.text_sm()
.text_color(cx.theme().danger)
.debug_selector(|| "recap-error".into())
.child(error.clone())
.into_any_element(),
],
Recap::Ready { shown, .. } => vec![
recap::header(shown, cx).into_any_element(),
recap::teams(shown, cx).into_any_element(),
],
};
card_images::provide(div(), images)
.v_flex()
.gap_4()
.pr_2()
.debug_selector(|| "recap".into())
.children(content)
}
}
+278
View File
@@ -0,0 +1,278 @@
//! What the recap of « Parties » shows, written once when its Match Recap arrives (or the
//! champions' names and portraits do): the page's render only lays it out.
use std::collections::HashMap;
use std::path::PathBuf;
use arena_tracker_core::{MatchRecap, RecapPlayer, Statistics};
use gpui_kit::SharedString;
use crate::local_time::local_time;
use crate::text::{duration, match_time, ordinal, thousands};
/// A value absent from the source: never shown as 0.
pub(in crate::page) const UNAVAILABLE: &str = "Indisponible";
/// The same in a Provisional Match, whose source gives less until Riot publishes it.
pub(in crate::page) const PENDING: &str = "En attente";
/// The catalog's name and square portrait of each champion, by id.
#[derive(Default)]
pub(in crate::page) struct Champions(HashMap<u32, (SharedString, Option<PathBuf>)>);
impl Champions {
/// From statistics, whose rows hold every champion of the catalog whatever their scope.
pub(in crate::page) fn of(stats: Option<&Statistics>) -> Champions {
Champions(
(stats.iter().flat_map(|s| s.rows.iter()))
.map(|row| {
let name = SharedString::from(row.champion.name.clone());
(row.champion.id, (name, row.portrait.clone()))
})
.collect(),
)
}
/// The catalog's name, else the one the Match gives (Riot's key, such as « MonkeyKing »).
pub(in crate::page) fn name(&self, id: u32, fallback: &str) -> SharedString {
self.0
.get(&id)
.map_or_else(|| fallback.to_string().into(), |(name, _)| name.clone())
}
pub(in crate::page) fn portrait(&self, id: u32) -> Option<PathBuf> {
self.0.get(&id).and_then(|(_, portrait)| portrait.clone())
}
}
/// A value, or the word for its absence, which is drawn muted.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct Value {
pub(in crate::page) text: SharedString,
pub(in crate::page) missing: bool,
}
impl Value {
fn of<T>(value: Option<T>, missing: &'static str, show: impl FnOnce(T) -> String) -> Value {
match value {
Some(value) => Value {
text: show(value).into(),
missing: false,
},
None => Value {
text: missing.into(),
missing: true,
},
}
}
}
/// One of the seven item slots.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) enum Slot {
/// The source says the slot is empty (item 0).
Empty,
/// A neutral icon, titled « Objet n » until the items have names.
Item(SharedString),
/// The source does not give this slot.
Missing,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownPlayer {
pub(in crate::page) is_account: bool,
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
pub(in crate::page) riot_id: Value,
pub(in crate::page) level: Value,
pub(in crate::page) kda: Value,
/// The word for their absence when the source gives no slot at all.
pub(in crate::page) items: Result<[Slot; 7], Value>,
/// « Amélioration n » each; the word for their absence when the source gives no augment
/// field.
pub(in crate::page) augments: Result<Vec<SharedString>, Value>,
pub(in crate::page) damage: Value,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownTeam {
/// « 1ᵉʳ », or the word for an absent Placement.
pub(in crate::page) placement: Value,
/// The team of the Account the recap is for.
pub(in crate::page) account: bool,
pub(in crate::page) players: Vec<ShownPlayer>,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownRecap {
/// The Account's champion.
pub(in crate::page) champion: SharedString,
pub(in crate::page) portrait: Option<PathBuf>,
/// « 15 nov. 2026 · 18:29 · Arena 3x6 · 31 min 14 s ».
pub(in crate::page) details: SharedString,
pub(in crate::page) provisional: bool,
/// By Placement, best first, as the core ranks them.
pub(in crate::page) teams: Vec<ShownTeam>,
}
impl ShownRecap {
/// `champion`: the Account's, from its row, should the recap not find the Account.
pub(in crate::page) fn new(
recap: &MatchRecap,
champion: (u32, &str),
champions: &Champions,
) -> ShownRecap {
let missing = if recap.provisional {
PENDING
} else {
UNAVAILABLE
};
let account = (recap.teams.iter().flat_map(|t| t.players.iter())).find(|p| p.is_account);
let (champion_id, fallback) =
account.map_or(champion, |p| (p.champion_id, p.champion_name.as_str()));
let length = recap
.duration_s
.map_or_else(|| format!("Durée : {}", missing.to_lowercase()), duration);
let details = [
match_time(local_time(recap.started_at_ms)),
recap.format.name(),
length,
]
.join(" · ");
ShownRecap {
champion: champions.name(champion_id, fallback),
portrait: champions.portrait(champion_id),
details: details.into(),
provisional: recap.provisional,
teams: (recap.teams.iter())
.map(|team| ShownTeam {
placement: Value::of(team.placement, missing, ordinal),
account: team.players.iter().any(|p| p.is_account),
players: (team.players.iter())
.map(|p| player(p, missing, champions))
.collect(),
})
.collect(),
}
}
}
fn player(p: &RecapPlayer, missing: &'static str, champions: &Champions) -> ShownPlayer {
let count = |value: Option<u32>| value.map_or_else(|| missing.to_string(), |v| v.to_string());
let kda = [p.kills, p.deaths, p.assists];
let absent = || Value::of(None::<()>, missing, |_| String::new());
let items = (p.items.iter().any(Option::is_some))
.then(|| {
p.items.map(|slot| match slot {
Some(0) => Slot::Empty,
Some(id) => Slot::Item(format!("Objet {id}").into()),
None => Slot::Missing,
})
})
.ok_or_else(absent);
ShownPlayer {
is_account: p.is_account,
champion: champions.name(p.champion_id, &p.champion_name),
portrait: champions.portrait(p.champion_id),
riot_id: Value::of(p.riot_id.clone(), missing, |id| id),
level: Value::of(p.level, missing, |level| level.to_string()),
// Each part says its own absence; all three absent is one word.
kda: Value::of(
kda.iter().any(Option::is_some).then_some(kda),
missing,
|kda| kda.map(count).join(" / "),
),
items,
augments: (p.augments.as_ref())
.map(|augments| {
(augments.iter())
.map(|id| format!("Amélioration {id}").into())
.collect()
})
.ok_or_else(absent),
damage: Value::of(p.damage_to_champions.total, missing, thousands),
}
}
#[cfg(test)]
mod tests {
use super::*;
use arena_tracker_core::{DamageByType, Format, RecapTeam};
fn recap(provisional: bool, players: Vec<RecapPlayer>) -> MatchRecap {
MatchRecap {
match_id: "EUW1_1".into(),
provisional,
format: Format::Arena3x6,
started_at_ms: 1_794_763_752_767,
duration_s: None,
game_version: None,
teams: vec![RecapTeam {
placement: None,
players,
}],
}
}
#[test]
fn an_absent_value_is_unavailable_and_a_zero_stays_zero() {
let given = RecapPlayer {
is_account: true,
champion_id: 39,
champion_name: "Irelia".into(),
kills: Some(0),
deaths: Some(0),
assists: None,
level: Some(0),
items: [Some(0), Some(3157), None, None, None, None, None],
augments: Some(vec![]),
damage_to_champions: DamageByType {
total: Some(0),
..DamageByType::default()
},
..RecapPlayer::default()
};
let shown = ShownRecap::new(&recap(false, vec![given]), (1, "x"), &Champions::default());
let team = &shown.teams[0];
assert_eq!(team.placement.text, UNAVAILABLE);
assert!(team.placement.missing && team.account);
let p = &team.players[0];
assert_eq!(p.riot_id.text, UNAVAILABLE);
assert!(p.riot_id.missing);
assert_eq!((p.level.text.as_ref(), p.level.missing), ("0", false));
assert_eq!(p.kda.text, "0 / 0 / Indisponible");
assert_eq!(p.damage.text, "0");
let slots = p.items.as_ref().unwrap();
assert_eq!(slots[0], Slot::Empty);
assert_eq!(slots[1], Slot::Item("Objet 3157".into()));
assert_eq!(slots[2], Slot::Missing);
assert_eq!(p.augments, Ok(vec![]));
assert!(shown.details.ends_with("Arena 3x6 · Durée : indisponible"));
assert_eq!(shown.champion, "Irelia");
}
#[test]
fn a_player_without_any_field_is_unavailable_everywhere() {
let bare = RecapPlayer {
champion_id: 39,
champion_name: "Irelia".into(),
..RecapPlayer::default()
};
let shown = ShownRecap::new(&recap(false, vec![bare]), (39, "x"), &Champions::default());
let p = &shown.teams[0].players[0];
for value in [&p.riot_id, &p.level, &p.kda, &p.damage] {
assert_eq!((value.text.as_ref(), value.missing), (UNAVAILABLE, true));
}
for absent in [p.items.as_ref().err(), p.augments.as_ref().err()] {
assert_eq!(absent.map(|v| v.text.as_ref()), Some(UNAVAILABLE));
}
}
#[test]
fn a_provisional_match_waits_for_its_values() {
let bare = RecapPlayer::default();
let shown = ShownRecap::new(&recap(true, vec![bare]), (39, "x"), &Champions::default());
assert!(shown.provisional);
assert_eq!(shown.teams[0].players[0].level.text, PENDING);
assert_eq!(shown.teams[0].placement.text, PENDING);
}
}
+32 -11
View File
@@ -1,5 +1,6 @@
//! The navigation between the screens: the tabs of the top bar, and the veil under which the
//! screen arriving replaces the one leaving. « La phase décide »: entering an Arena champ select
//! The navigation between the screens: the tabs of the top bar (« Défi », « Parties » and,
//! during an Arena champ select, « Sélection »), and the veil under which the screen arriving
//! replaces the one leaving. « La phase décide »: entering an Arena champ select
//! shows « Sélection », its end shows « Défi »; nothing else moves the player.
use super::{Page, Tab};
@@ -12,8 +13,8 @@ use gpui_kit::*;
impl Page {
/// The tabs as buttons: they take the keyboard focus, and Enter or Space activates them.
/// « Défi » stays lit on « Statistiques », the Challenge's detail page, and takes back to the
/// Challenge from there. « Sélection », right of it, is there only while an Arena champ
/// select runs.
/// Challenge from there. « Parties » is right of it, then « Sélection », there only while an
/// Arena champ select runs.
pub(super) fn navigation(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (ring, muted, active, active_foreground, hover, hover_foreground) = (
@@ -26,16 +27,18 @@ impl Page {
);
let champ_select =
(self.in_champ_select()).then_some(("tab-champ-select", "Sélection", Tab::ChampSelect));
let tabs = [("tab-challenge", "Défi", Tab::Challenge)]
.into_iter()
.chain(champ_select);
let tabs = [
("tab-challenge", "Défi", Tab::Challenge),
("tab-matches", "Parties", Tab::Matches),
]
.into_iter()
.chain(champ_select);
div()
.h_flex()
.gap_1()
.flex_shrink_0()
.children(tabs.map(|(id, label, tab)| {
// « Défi » covers « Statistiques » too.
let current = (self.tab == Tab::ChampSelect) == (tab == Tab::ChampSelect);
let current = self.lit(tab);
BaseButton::new(id)
.px_3()
.py_1()
@@ -60,6 +63,14 @@ impl Page {
}))
}
/// Whether the top bar lights `tab`: the one chosen, « Défi » on « Statistiques » too.
pub(super) fn lit(&self, tab: Tab) -> bool {
match self.tab {
Tab::Statistics => tab == Tab::Challenge,
chosen => chosen == tab,
}
}
pub(super) fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
// « Sélection » only exists while the champ select runs.
if tab == Tab::ChampSelect && !self.in_champ_select() {
@@ -100,6 +111,12 @@ impl Page {
// twice, and no card waits to go down.
self.forget_stage();
}
if left == Tab::Matches {
self.close_matches(window, cx);
}
if self.shown_tab == Tab::Matches {
self.open_matches(cx);
}
// The screen arriving was not kept up to date while hidden, and is prepared only now: a
// switch undone under the veil prepares nothing.
self.refresh_table(cx);
@@ -125,11 +142,15 @@ impl Page {
grid.update(cx, |grid, cx| grid.release_images(window, cx));
}
}
if shown == Tab::Statistics {
if shown != Tab::Matches {
self.release_matches_images(window, cx);
}
if matches!(shown, Tab::Statistics | Tab::Matches) {
// Neither banner is shown: its illustration goes too.
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
} else {
}
if shown != Tab::Statistics {
self.table
.update(cx, |table, cx| table.release_images(window, cx));
}
+2
View File
@@ -85,6 +85,7 @@ impl Page {
let ring = cx.new(|_| Ring::new());
let banner_art = BannerArt::new(cx);
let others_hover = Self::light_and_reveal(&others_grid, cx);
let matches = super::matches::Matches::new(cx);
let mut subscriptions = Vec::new();
subscriptions.extend(Self::light_on_hover(&home_grid, cx));
@@ -288,6 +289,7 @@ impl Page {
paging,
champ_select_scrollbar,
others_focus,
matches,
others_hover,
_subscriptions: subscriptions,
_listener: listener,
+4
View File
@@ -62,6 +62,8 @@ impl Page {
select.set_selected_value(puuid, window, cx);
}
});
// The stored Matches may have changed, or the Account.
self.matches_changed(cx);
}
/// Settles the scope of the next statistics. Earlier results become stale when they are
@@ -222,6 +224,8 @@ impl Page {
.update(cx, |select, cx| select.set_items(names, window, cx));
}
self.refresh_table(cx);
// The champions' names and portraits of « Parties » come with the statistics.
self.dress_matches(cx);
if self.hold_grid {
// The cards changed in place; their order, which are shown and their count wait for
// the pointer to leave, prepared now.
+2
View File
@@ -13,6 +13,8 @@ mod champ_select_tab;
mod grid;
mod home;
mod match_animation;
mod matches;
mod matches_fixtures;
mod navigation;
mod page_fixtures;
mod portraits;
+338
View File
@@ -0,0 +1,338 @@
use super::matches_fixtures::{
ALICE, BOB, chosen, listed, open_matches, recap_id, recap_ready, sign_in_bob, tracker,
};
use super::page_fixtures::{
assert_at_rest, center, draw, open_page, open_page_with_tracker, press, show, statistics,
switch_tab,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::local_time::local_time;
use crate::page::Tab;
use crate::page::matches::{Recap, Row, ShownPlayer, Slot, UNAVAILABLE};
use crate::text::match_time;
use crate::worker::Msg;
use arena_tracker_core::{Champion, ChampionRow};
use gpui_kit::{Modifiers, SharedString, TestAppContext, VisualTestContext, px, size};
fn click(cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_click(at, Modifiers::none());
draw(cx);
}
/// The Account's player in the recap shown.
fn account_player(
page: &gpui_kit::Entity<crate::page::Page>,
cx: &mut VisualTestContext,
) -> ShownPlayer {
page.read_with(cx, |p, _| {
let shown = p.matches.shown().unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.is_account)
.unwrap()
.clone()
})
}
#[gpui::test]
fn the_matches_tab_is_right_of_the_challenge_and_lit_alone(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
draw(cx);
let (challenge, matches) = (center(cx, "tab-challenge"), center(cx, "tab-matches"));
assert!(matches.x > challenge.x);
let lit = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, _| (p.lit(Tab::Challenge), p.lit(Tab::Matches)))
};
assert_eq!(lit(cx), (true, false));
click(cx, "tab-matches");
assert_eq!(page.read_with(cx, |p, _| p.tab), Tab::Matches);
assert_eq!(lit(cx), (false, true));
// « Défi » stays lit on its detail page.
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(lit(cx), (true, false));
}
#[gpui::test]
async fn opening_the_tab_lists_the_matches_newest_first_and_opens_the_most_recent(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
assert_eq!(listed(&page, cx), ALICE);
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[0]));
assert_eq!(recap_id(&page, cx).as_deref(), Some(ALICE[0]));
let rows: Vec<Row> = page.read_with(cx, |p, cx| p.matches.list.read(cx).rows().to_vec());
let champions: Vec<_> = rows.iter().map(|r| r.champion.as_ref()).collect();
assert_eq!(champions, ["Irelia", "Ahri", "Irelia"]);
let placements: Vec<_> = rows.iter().map(|r| r.placement.as_ref()).collect();
assert_eq!(placements, ["2ᵉ", "2ᵉ", "2ᵉ"]);
// Its date and time on the player's clock; no Format in the row.
assert_eq!(rows[0].when, match_time(local_time(1_794_763_752_767)));
assert!(rows.iter().all(|r| !r.provisional));
assert!(cx.debug_bounds("match-list").is_some());
assert!(cx.debug_bounds("matches-list-toggle").is_none());
// Nothing runs at rest.
assert_at_rest(cx);
}
#[gpui::test]
async fn the_choice_is_not_kept_from_one_opening_to_the_next(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
click(&mut window, "match-row-2");
assert_eq!(chosen(&page, &mut window).as_deref(), Some(ALICE[2]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[2]));
switch_tab(&page, &mut window, Tab::Challenge);
// Hidden, the screen keeps no recap.
assert!(page.read_with(&window, |p, _| matches!(p.matches.recap, Recap::None)));
switch_tab(&page, &mut window, Tab::Matches);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(ALICE[0]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn the_arrows_move_the_choice_through_the_list(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx2 = &mut window;
// A click gives the list the keyboard.
click(cx2, "match-row-0");
press(cx2, "down");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[1]));
press(cx2, "down");
press(cx2, "down");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[2]));
press(cx2, "up");
assert_eq!(chosen(&page, cx2).as_deref(), Some(ALICE[1]));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[1]));
}
#[gpui::test]
async fn the_recap_ranks_the_teams_and_highlights_the_account(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
click(&mut window, "match-row-2");
recap_ready(&page, cx).await;
let cx = &mut window;
draw(cx);
page.read_with(cx, |p, _| {
let shown = p.matches.shown().unwrap();
assert_eq!(shown.champion, "Irelia");
assert!(
shown.details.contains("Arena 3x6 · 23 min 00 s"),
"{}",
shown.details
);
let placements: Vec<_> = shown
.teams
.iter()
.map(|t| t.placement.text.as_ref())
.collect();
assert_eq!(placements, ["1ᵉʳ", "2ᵉ", "3ᵉ"]);
let accounts: Vec<_> = shown.teams.iter().map(|t| t.account).collect();
assert_eq!(accounts, [false, true, false]);
// An old Match names a player by their summoner name.
let names: Vec<_> = (shown.teams[0].players.iter())
.map(|p| p.riot_id.text.as_ref())
.collect();
assert_eq!(names, ["Autre03#FIX", "VieuxNom"]);
});
let me = account_player(&page, cx);
assert_eq!(me.riot_id.text, "Joueur#EUW");
assert_eq!(
[&me.level, &me.kda, &me.damage].map(|v| v.text.to_string()),
["18", "12 / 2 / 5", "30\u{202f}000"].map(String::from)
);
let item = |id: u32| Slot::Item(SharedString::from(format!("Objet {id}")));
assert_eq!(
me.items,
Ok([
item(3157),
item(3089),
Slot::Empty,
item(3020),
Slot::Empty,
Slot::Empty,
item(3340)
])
);
let augments: Vec<SharedString> = ["Amélioration 101", "Amélioration 212", "Amélioration 305"]
.map(SharedString::from)
.to_vec();
assert_eq!(me.augments, Ok(augments));
assert!(cx.debug_bounds("recap-account").is_some());
assert!(cx.debug_bounds("recap-provisional").is_none());
}
#[gpui::test]
async fn a_match_without_statistics_says_they_are_unavailable(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let me = account_player(&page, &mut window);
for value in [&me.level, &me.kda, &me.damage] {
assert_eq!((value.text.as_ref(), value.missing), (UNAVAILABLE, true));
}
assert_eq!(me.items.as_ref().unwrap_err().text, UNAVAILABLE);
assert_eq!(me.augments.as_ref().unwrap_err().text, UNAVAILABLE);
// Its Riot ID is given.
assert_eq!(me.riot_id.text, "Joueur#EUW");
}
#[gpui::test]
async fn a_new_account_in_the_client_switches_the_list_without_mixing(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (tracker, signed_in) = tracker();
let (page, mut window) = open_page_with_tracker(cx, tracker);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), ALICE);
sign_in_bob(&page, &signed_in, &mut window);
// At once: none of Alice's Matches stays.
assert!(listed(&page, &mut window).is_empty());
assert_eq!(chosen(&page, &mut window), None);
recap_ready(&page, cx).await;
assert_eq!(listed(&page, &mut window), [BOB]);
assert_eq!(chosen(&page, &mut window).as_deref(), Some(BOB));
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(BOB));
}
#[gpui::test]
async fn known_matches_stay_during_a_sync_and_after_a_failure(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
cx.update(|window, cx| {
page.update(cx, |page, cx| {
// Something stored changed: the list is read again, the Matches stay meanwhile.
page.apply(Msg::Champions, window, cx);
assert_eq!(page.matches.entries().map(<[_]>::len), Some(3));
let generation = page.matches.generation();
page.apply(
Msg::Matches {
generation,
matches: Err("Parties indisponibles : base verrouillée".into()),
},
window,
cx,
);
assert_eq!(page.matches.entries().map(<[_]>::len), Some(3));
assert!(page.matches.error().is_some());
})
});
draw(cx);
assert!(cx.debug_bounds("matches-error").is_some());
assert!(cx.debug_bounds("match-row-0").is_some());
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
fn without_an_account_the_screen_says_so(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
switch_tab(&page, cx, Tab::Matches);
draw(cx);
assert!(cx.debug_bounds("matches-banner").is_some());
assert!(cx.debug_bounds("matches-notice").is_some());
assert!(cx.debug_bounds("match-list").is_none());
}
#[gpui::test]
async fn a_narrow_window_puts_the_list_behind_a_button(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
cx.simulate_resize(size(px(800.), px(700.)));
draw(cx);
assert!(cx.debug_bounds("match-list").is_none());
click(cx, "matches-list-toggle");
assert!(cx.debug_bounds("matches-list-over").is_some());
// Choosing a Match closes the list.
click(cx, "match-row-1");
assert!(cx.debug_bounds("matches-list-over").is_none());
assert_eq!(chosen(&page, cx).as_deref(), Some(ALICE[1]));
}
#[gpui::test]
async fn the_list_builds_only_its_rows_in_view_and_is_not_drawn_with_the_page(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
let list = page.read_with(cx, |p, _| p.matches.list.clone());
let rows: Vec<Row> = (0..300)
.map(|ix| Row {
match_id: format!("EUW1_{ix}"),
champion: "Irelia".into(),
portrait: None,
when: "15 nov. 2026 · 17:29".into(),
placement: "2ᵉ".into(),
provisional: ix == 0,
})
.collect();
cx.update(|_, cx| list.update(cx, |list, cx| list.set_rows(rows, Some("EUW1_0"), cx)));
draw(cx);
assert!(cx.debug_bounds("match-row-0").is_some());
assert!(cx.debug_bounds("match-row-200").is_none());
// The page drawn again (the recap arriving, the veil) does not draw the list.
let renders = |cx: &mut VisualTestContext| list.read_with(cx, |list, _| list.renders);
let before = renders(cx);
cx.update(|_, cx| page.update(cx, |_, cx| cx.notify()));
draw(cx);
assert_eq!(renders(cx), before);
}
#[gpui::test]
async fn the_portraits_go_with_the_screen(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
let cx = &mut window;
let dir = TestDir::new("matches-portraits");
let path = dir.path().join("Irelia.png");
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
let mut irelia = crate::champion_table::tests::row("Irelia");
irelia.champion = Champion {
id: 39,
key: "Irelia".into(),
name: "Irelia".into(),
};
irelia.portrait = Some(path);
let rows: Vec<ChampionRow> = vec![irelia];
show(&page, cx, statistics(0, 1, rows));
draw(cx);
cx.run_until_parked();
draw(cx);
let (list_images, recap_images) = page.read_with(cx, |p, cx| {
let list = p.matches.list.read(cx).images().cloned().unwrap();
(list, p.matches.recap_images().clone())
});
let held = |cx: &mut VisualTestContext| {
(
list_images.read_with(cx, |images, _| images.held().len()),
recap_images.read_with(cx, |images, _| images.held().len()),
)
};
let (list, recap) = held(cx);
assert!(list > 0 && recap > 0, "{list} {recap}");
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(held(cx), (0, 0));
}
#[gpui::test]
async fn a_list_arriving_once_the_screen_left_starts_nothing(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, tracker().0);
switch_tab(&page, &mut window, Tab::Matches);
switch_tab(&page, &mut window, Tab::Challenge);
cx.condition(&page, |p, _| !p.matches.reading()).await;
page.read_with(&window, |p, _| {
// Dropped: no Match is chosen, and none is decoded.
assert_eq!(p.matches.selected, None);
assert!(matches!(p.matches.recap, Recap::None));
});
// Back on the screen, the list is read again and the most recent opens.
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
@@ -0,0 +1,177 @@
use super::page_fixtures::{MATCH_1750, draw, open_page_with_tracker, switch_tab};
use crate::page::matches::Recap;
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{
Account, ChampSelect, ClientError, ClientEvent, GameClientSource, Gameflow, MatchHistorySource,
SourceError, Tracker,
};
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// The Match whose recap has every field: Irelia, 2nd, on 13 May 2026.
pub(super) const RECAP_1750: &str =
include_str!("../../../../core/tests/fixtures/riot/match_1750_recap.json");
/// Alice's Matches, newest first: Irelia on 15 Nov. 2026 (a payload without statistics), Ahri on
/// 21 Sept. 2026, Irelia on 13 May 2026 (the full recap).
pub(super) const ALICE: [&str; 3] = ["EUW1_9000000006", "EUW1_9000000008", "EUW1_9000000007"];
/// Bob's only Match.
pub(super) const BOB: &str = "EUW1_9000000009";
/// Alice and Bob, each with their Arena 3x6 Matches, made from the core's Match-V5 fixtures.
pub(super) struct TwoAccounts;
impl MatchHistorySource for TwoAccounts {
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> {
if queue_id != 1750 || start != 0 {
return Ok(Vec::new());
}
Ok(match puuid {
"Alice" => ALICE.map(String::from).to_vec(),
"Bob" => vec![BOB.into()],
_ => Vec::new(),
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let other = |start: &str| {
MATCH_1750
.replace("EUW1_9000000006", id)
.replace("1794763752767", start)
};
Ok(match id {
"EUW1_9000000006" => MATCH_1750.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000007" => RECAP_1750.replace("fixture-puuid-self", "Alice"),
"EUW1_9000000008" => other("1790000000000")
.replace("\"championId\": 39,", "\"championId\": 103,")
.replace("\"championName\": \"Irelia\"", "\"championName\": \"Ahri\"")
.replace("fixture-puuid-self", "Alice"),
_ => other("1794763752767").replace("fixture-puuid-self", "Bob"),
})
}
}
/// A game client in its lobby, with the game name signed in (tag line « EUW »).
pub(super) struct Lobby(pub(super) Arc<Mutex<String>>);
impl GameClientSource for Lobby {
fn signed_in(&self) -> Result<(String, String), ClientError> {
Ok((self.0.lock().unwrap().clone(), "EUW".into()))
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
Ok(Gameflow::default())
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
}
/// A tracker that knows both Accounts, Alice signed in to the client; the name signs another
/// one in.
pub(super) fn tracker() -> (Tracker, Arc<Mutex<String>>) {
let signed_in = Arc::new(Mutex::new("Alice".to_string()));
let tracker = Tracker::open(Path::new(":memory:"), Box::new(TwoAccounts))
.unwrap()
.with_seasons(Vec::new())
.with_client(Box::new(Lobby(signed_in.clone())));
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, None, &mut |_| {});
(tracker, signed_in)
}
/// « Parties » opened by hand on Alice's Matches, once its list and the recap of the most
/// recent are there.
pub(super) async fn open_matches(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, tracker().0);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
(page, window)
}
/// Waits for the list and the recap of the Match chosen.
pub(super) async fn recap_ready(page: &Entity<Page>, cx: &mut TestAppContext) {
cx.condition(page, |p, _| {
p.matches.entries().is_some() && matches!(p.matches.recap, Recap::Ready { .. })
})
.await;
}
/// The Matches of the list, in its order.
pub(super) fn listed(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<String> {
page.read_with(cx, |p, cx| {
let list = p.matches.list.read(cx);
list.rows().iter().map(|r| r.match_id.clone()).collect()
})
}
/// The Match chosen, as the page and the list have it: they agree.
pub(super) fn chosen(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, cx| {
let selected = p.matches.selected.clone();
assert_eq!(p.matches.list.read(cx).selected(), selected.as_deref());
selected
})
}
/// The Match whose recap is shown.
pub(super) fn recap_id(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, _| match &p.matches.recap {
Recap::Ready { recap, .. } => Some(recap.match_id.clone()),
_ => None,
})
}
/// Bob signs in to the client instead of Alice, and the follower's round says so.
pub(super) fn sign_in_bob(
page: &Entity<Page>,
signed_in: &Mutex<String>,
cx: &mut VisualTestContext,
) {
*signed_in.lock().unwrap() = "Bob".into();
cx.update(|window, cx| {
page.update(cx, |page, cx| {
page.tracker.follow_client(0, None, &mut |_| {});
let status = page.tracker.status();
assert_eq!(status.updating.as_ref().unwrap().puuid, "Bob");
page.apply(
Msg::Round {
status,
reload: true,
matches: Vec::new(),
},
window,
cx,
);
})
});
}
+5 -4
View File
@@ -80,14 +80,15 @@ fn the_banner_link_and_the_back_button_work_with_the_keyboard(cx: &mut TestAppCo
let cx = &mut { cx };
let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab);
draw(cx);
// Tab reaches « Défi », then the account selector, then « Statistiques › » in the banner.
tab_then_enter(cx, 3);
// Tab reaches « Défi », « Parties », then the account selector, then « Statistiques › » in
// the banner.
tab_then_enter(cx, 4);
assert_eq!(tab(cx), Tab::Statistics);
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
// On the page, « Défi », the selector, then « ‹ Défi ».
tab_then_enter(cx, 3);
// On the page, « Défi », « Parties », the selector, then « ‹ Défi ».
tab_then_enter(cx, 4);
assert_eq!(tab(cx), Tab::Challenge);
}
@@ -60,6 +60,7 @@ pub(super) fn open_page_with_sort(
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
cx.update(crate::page::init);
let tracker = Arc::new(tracker);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
+5
View File
@@ -98,6 +98,11 @@ impl Page {
self.recompute_in_background(true, window, cx);
}
}
Msg::Matches {
generation,
matches,
} => self.apply_matches(generation, matches, cx),
Msg::Recap { generation, recap } => self.apply_recap(generation, *recap, cx),
Msg::Crashed => self.mark_crashed(),
Msg::RefreshCrashed => {
self.refresh.reset();
+34
View File
@@ -2,6 +2,8 @@
use arena_tracker_core::{ChampionState, Date, SyncProgress};
use crate::local_time::LocalTime;
/// Fixed decimals with a decimal comma: `1,96`.
pub fn decimal(value: f64, digits: usize) -> String {
format!("{value:.digits$}").replace('.', ",")
@@ -59,6 +61,22 @@ pub fn short_date(date: Date) -> String {
format!("{} {month}", date.day)
}
/// When a Match started, as its row and its recap write it: « 15 nov. 2026 · 18:29 ».
pub fn match_time(time: LocalTime) -> String {
format!(
"{} {} · {}:{:02}",
short_date(time.date),
time.date.year,
time.hour,
time.minute
)
}
/// A Match's length: « 31 min 14 s ».
pub fn duration(seconds: u32) -> String {
format!("{} min {:02} s", seconds / 60, seconds % 60)
}
pub fn state_label(state: Option<ChampionState>) -> &'static str {
match state {
Some(ChampionState::Completed) => "Validé",
@@ -143,6 +161,22 @@ mod tests {
assert_eq!(short_date(date(8, 31)), "31 août");
}
#[test]
fn match_times_and_lengths_are_written_in_french() {
let time = LocalTime {
date: Date {
year: 2026,
month: 11,
day: 5,
},
hour: 9,
minute: 4,
};
assert_eq!(match_time(time), "5 nov. 2026 · 9:04");
assert_eq!(duration(1874), "31 min 14 s");
assert_eq!(duration(60), "1 min 00 s");
}
#[test]
fn stored_matches_are_pluralised() {
assert_eq!(stored(0), "Aucune Partie enregistrée");
+18 -3
View File
@@ -1,5 +1,5 @@
//! Background threads: following the game client, refreshing, computing statistics and
//! downloading updates. They talk to the page through `Msg`, and to the settings through
//! Background threads: following the game client, refreshing, computing statistics, reading
//! the Matches of « Parties » and downloading updates. They talk to the page through `Msg`, and to the settings through
//! `UpdateChecked`.
use std::panic::{AssertUnwindSafe, catch_unwind};
@@ -8,10 +8,15 @@ use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
ChampSelect, ClientEvent, MatchRecap, Scope, Statistics, Status, SyncProgress, Tracker,
UpdateChannel,
};
use gpui_kit::base::async_util::Sender;
mod matches;
pub use matches::{MatchEntry, spawn_match_list, spawn_recap};
/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
pub type LiveChampSelect = Option<(String, ChampSelect)>;
@@ -38,6 +43,16 @@ pub enum Msg {
home: Option<Box<Result<Statistics, String>>>,
stored: Option<usize>,
},
/// The Matches of the Account of « Parties », newest first.
Matches {
generation: u64,
matches: Result<Vec<MatchEntry>, String>,
},
/// The Match Recap of the Match opened on « Parties »: `None` when it is no longer stored.
Recap {
generation: u64,
recap: Box<Result<Option<MatchRecap>, String>>,
},
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
+142
View File
@@ -0,0 +1,142 @@
//! The jobs of « Parties »: the list of an Account's Matches, and the Match Recap of the one
//! opened. Each runs on a below-normal thread and always reports, a panic as an error, so the
//! page's gate for it is never left waiting.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use arena_tracker_core::{Format, Tracker};
use gpui_kit::base::async_util::Sender;
use super::{Msg, spawn_guarded};
use crate::local_time::local_time;
use crate::text::match_time;
/// One Match of the list, as its row needs it: nothing of its payload is read for the list.
#[derive(Clone, Debug, PartialEq)]
pub struct MatchEntry {
pub match_id: String,
pub champion_id: u32,
/// As the Match names it; the row prefers the catalog's name.
pub champion_name: String,
pub started_at_ms: i64,
/// When it started, on the player's clock, written here rather than on the UI thread.
pub when: String,
pub placement: u8,
pub provisional: bool,
/// Not in the row: kept for the filters to come.
pub format: Format,
}
/// The stored Matches of `puuid`, newest first.
pub fn match_list(tracker: &Tracker, puuid: &str) -> Result<Vec<MatchEntry>, String> {
let matches = tracker
.matches(puuid)
.map_err(|e| format!("Parties indisponibles : {e}"))?;
// The store gives them oldest first.
Ok(matches
.into_iter()
.rev()
.map(|m| MatchEntry {
when: match_time(local_time(m.started_at_ms)),
match_id: m.match_id,
champion_id: m.champion_id,
champion_name: m.champion_name,
started_at_ms: m.started_at_ms,
placement: m.placement,
provisional: m.provisional,
format: m.format,
})
.collect())
}
/// Lists the Matches of `puuid` for « Parties ».
pub fn spawn_match_list(tracker: Arc<Tracker>, puuid: String, generation: u64, tx: Sender<Msg>) {
spawn_guarded(tx, Msg::Crashed, move |tx| {
let matches = catch_unwind(AssertUnwindSafe(|| match_list(&tracker, &puuid)))
.unwrap_or_else(|_| Err("Parties indisponibles : erreur interne".into()));
let _ = tx.try_send(Msg::Matches {
generation,
matches,
});
});
}
/// Decodes the Match Recap of one Match of `puuid`: only the Match opened is decoded.
pub fn spawn_recap(
tracker: Arc<Tracker>,
puuid: String,
match_id: String,
generation: u64,
tx: Sender<Msg>,
) {
spawn_guarded(tx, Msg::Crashed, move |tx| {
let recap = catch_unwind(AssertUnwindSafe(|| {
(tracker.match_recap(&puuid, &match_id)).map_err(|e| e.to_string())
}))
.unwrap_or_else(|_| Err("erreur interne".into()));
let _ = tx.try_send(Msg::Recap {
generation,
recap: Box::new(recap),
});
});
}
#[cfg(test)]
mod tests {
use super::match_list;
use arena_tracker_core::{Account, MatchHistorySource, SourceError, Tracker};
use std::path::Path;
const MATCH: &str =
include_str!("../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json");
const RECAP: &str = include_str!("../../../core/tests/fixtures/riot/match_1750_recap.json");
struct TwoMatches;
impl MatchHistorySource for TwoMatches {
fn resolve_account(&self, name: &str, tag: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: "fixture-puuid-self".into(),
game_name: name.into(),
tag_line: tag.into(),
})
}
fn match_ids(
&self,
_: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if queue_id == 1750 && start == 0 {
vec!["EUW1_9000000007".into(), "EUW1_9000000006".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
Ok(if id == "EUW1_9000000006" {
MATCH
} else {
RECAP
}
.into())
}
}
#[test]
fn the_list_is_newest_first_without_reading_payloads() {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(TwoMatches)).unwrap();
tracker.sync("Joueur#EUW", &mut |_| {}).unwrap();
let list = match_list(&tracker, "fixture-puuid-self").unwrap();
let ids: Vec<_> = list.iter().map(|m| m.match_id.as_str()).collect();
assert_eq!(ids, ["EUW1_9000000006", "EUW1_9000000007"]);
assert_eq!(list[0].placement, 2);
assert!(list[0].when.contains("2026"), "{}", list[0].when);
assert!(match_list(&tracker, "someone-else").unwrap().is_empty());
}
}