Sort the cards by Mastery Points or A to Z and remember the choice (#76)

The statistics rows carry the Mastery Points: None for an Account whose
points were never fetched, Some(0) for a champion missing from the last
list. One card order, computed only when the statistics or the preference
change, feeds the home grid, the Anvil row and « Autres champions ». The
sort selector stays visible during a champ select, the choice is saved
with the other preferences, and the sheet shows the Mastery Points
(unknown ones after the known, and not as zero).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-21 02:26:14 +01:00
1 parent 815daf33cb
commit a457a19fe5
11 files changed
+857 -55

No files matched your search

+32 -1
View File
@@ -8,7 +8,7 @@ use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::text::ordinal;
use crate::text::{ordinal, thousands};
/// Width over height.
pub const ASPECT: f32 = 0.68;
@@ -33,6 +33,8 @@ const PLAYED: &str = "Parties";
const WINS: &str = "Victoires";
const BEST_PLACEMENT: &str = "Meilleur Placement";
const ATTEMPTS: &str = "Tentatives";
const MASTERY: &str = "Points de maîtrise";
const UNKNOWN: &str = "Inconnus";
/// Only on a Completed champion.
pub const FIRST_TOP_1: &str = "Premier top 1";
const NONE: &str = "—";
@@ -158,6 +160,12 @@ fn sheet_lines(row: &ChampionRow) -> Vec<(&'static str, SharedString)> {
.map_or_else(|| NONE.into(), |placement| ordinal(placement).into()),
),
(ATTEMPTS, count(row.attempts)),
// Unknown is not zero: the points were never fetched for this Account.
(
MASTERY,
row.mastery_points
.map_or_else(|| UNKNOWN.into(), |points| thousands(points).into()),
),
];
if let Some(date) = challenge.and_then(|c| c.completed_on) {
lines.push((FIRST_TOP_1, date.to_string().into()));
@@ -379,6 +387,7 @@ mod tests {
attempts: None,
state: None,
challenge,
mastery_points: Some(154_320),
}
}
@@ -462,6 +471,7 @@ mod tests {
("Victoires", "0".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "0".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
@@ -484,6 +494,7 @@ mod tests {
("Victoires", "2".into()),
("Meilleur Placement", "2ᵉ".into()),
("Tentatives", "5".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
assert!(card.sheet.iter().all(|(label, _)| *label != FIRST_TOP_1));
@@ -506,6 +517,7 @@ mod tests {
("Victoires", "3".into()),
("Meilleur Placement", "1ᵉʳ".into()),
("Tentatives", "4".into()),
("Points de maîtrise", "154\u{202f}320".into()),
("Premier top 1", "02/03/2026".into()),
]
);
@@ -521,10 +533,29 @@ mod tests {
("Victoires", "—".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "—".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_shows_zero_points_as_zero_and_unknown_points_as_unknown() {
let mut row = row(None);
row.mastery_points = Some(0);
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "0".to_string())
);
row.mastery_points = None;
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "Inconnus".to_string())
);
}
#[test]
fn a_row_without_a_challenge_has_no_marks() {
let card = Card::from_row(&row(None));
+91
View File
@@ -0,0 +1,91 @@
//! The one order every section of cards follows: the chosen sort applied to the statistics' rows.
use arena_tracker_core::{ChampionRow, ChampionSort};
/// The positions of `rows` in display order. `rows` come A to Z (French collation), and every
/// sort is stable, so that order breaks every tie.
///
/// - `Name`: the rows' own order.
/// - `Mastery`: the champions with known points by points descending, then the ones whose points
/// are unknown (an unknown value is not a zero). When no row has a known value, the rows' own
/// order: the sort falls back to A to Z, and the player's preference stays as it is.
pub fn card_order(rows: &[ChampionRow], sort: ChampionSort) -> Vec<usize> {
let mut order: Vec<usize> = (0..rows.len()).collect();
if sort == ChampionSort::Mastery && rows.iter().any(|row| row.mastery_points.is_some()) {
// `None` sorts before every `Some`: reversed, the known values come first, highest first.
order.sort_by_key(|&ix| std::cmp::Reverse(rows[ix].mastery_points));
}
order
}
#[cfg(test)]
mod tests {
use arena_tracker_core::{Champion, ChampionRow, ChampionSort};
use super::card_order;
use crate::champion_table::tests::row;
/// Rows A to Z, as the statistics give them, each with its points.
fn rows(points: &[(&str, Option<u64>)]) -> Vec<ChampionRow> {
points
.iter()
.enumerate()
.map(|(id, (name, points))| ChampionRow {
champion: Champion {
id: id as u32 + 1,
..row(name).champion
},
mastery_points: *points,
..row(name)
})
.collect()
}
fn names(rows: &[ChampionRow], order: &[usize]) -> Vec<String> {
order
.iter()
.map(|&ix| rows[ix].champion.name.clone())
.collect()
}
#[test]
fn mastery_sorts_by_points_descending_then_by_name() {
let rows = rows(&[
("Ahri", Some(500)),
("Brand", Some(9_000)),
("Garen", Some(500)),
("Jinx", Some(0)),
("Zed", Some(500)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(
names(&rows, &order),
["Brand", "Ahri", "Garen", "Zed", "Jinx"]
);
}
#[test]
fn an_unknown_value_comes_after_the_known_ones_even_zero() {
let rows = rows(&[
("Ahri", None),
("Brand", Some(0)),
("Garen", None),
("Jinx", Some(12)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(names(&rows, &order), ["Jinx", "Brand", "Ahri", "Garen"]);
}
#[test]
fn without_any_known_value_the_cards_are_sorted_a_to_z() {
let rows = rows(&[("Ahri", None), ("Brand", None), ("Zed", None)]);
assert_eq!(card_order(&rows, ChampionSort::Mastery), [0, 1, 2]);
}
#[test]
fn the_name_sort_keeps_the_rows_order_whatever_the_points() {
let rows = rows(&[("Ahri", Some(1)), ("Brand", None), ("Zed", Some(900))]);
assert_eq!(card_order(&rows, ChampionSort::Name), [0, 1, 2]);
assert!(card_order(&[], ChampionSort::Mastery).is_empty());
}
}
+1
View File
@@ -307,6 +307,7 @@ pub(crate) mod tests {
attempts: None,
state: None,
challenge: None,
mastery_points: None,
}
}
+93 -4
View File
@@ -3,6 +3,7 @@
mod card;
mod card_grid;
mod card_images;
mod card_order;
mod champion_table;
mod page;
#[cfg(feature = "profile")]
@@ -25,7 +26,7 @@ use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::*;
use gpui_kit::*;
use page::Page;
use page::{ChampionSortChosen, Launch, Page};
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use worker::{Msg, spawn_follower};
@@ -49,6 +50,7 @@ struct RootView {
tx: Sender<Msg>,
_form_events: Subscription,
_champ_select: Subscription,
_sort: Subscription,
}
impl RootView {
@@ -62,12 +64,16 @@ impl RootView {
// Without a key the page still shows what is stored; only a true first launch (no key
// and nothing stored) has nothing to show, so the key form stands in for the page.
let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty();
let champion_sort = store.preferences().champion_sort;
let (tx, rx) = unbounded();
let page = cx.new(|cx| {
Page::new(
tracker.clone(),
notice,
!first_launch,
Launch {
notice,
following: !first_launch,
champion_sort,
},
rx,
tx.clone(),
window,
@@ -109,6 +115,14 @@ impl RootView {
}
},
);
// Saved with the other preferences; a failure keeps the choice for the session.
let sort = cx.subscribe(
&page,
|this, _, ChampionSortChosen(sort): &ChampionSortChosen, cx| {
this.form
.update(cx, |form, cx| form.save_champion_sort(*sort, cx));
},
);
let screen = if first_launch {
Screen::Prompt
} else {
@@ -125,6 +139,7 @@ impl RootView {
tx,
_form_events: form_events,
_champ_select: champ_select,
_sort: sort,
}
}
@@ -353,7 +368,7 @@ mod tests {
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{Config, RiotApi, Tracker, UpdateChannel};
use arena_tracker_core::{ChampionSort, Config, RiotApi, Tracker, UpdateChannel};
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{
AppContext as _, Entity, FontWeight, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
@@ -470,4 +485,78 @@ mod tests {
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
/// A unique folder under the system's temporary one, removed when dropped.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(name: &str) -> TempDir {
let dir =
std::env::temp_dir().join(format!("arena-tracker-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The app opened on the config file at `path` (the file is read, or missing).
fn open_app(
cx: &mut TestAppContext,
path: &Path,
load: fn(&Path) -> Result<Config, arena_tracker_core::Error>,
) -> (VisualTestContext, Entity<RootView>) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = load(path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(
Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap(),
),
riot_id: String::new(),
notice: None,
store: KeyStore::new(path.to_path_buf(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, window, cx))
})
.unwrap()
});
(VisualTestContext::from_window(window, cx), root)
}
#[gpui::test]
fn the_chosen_sort_is_saved_with_the_preferences_and_found_again_at_the_next_launch(
cx: &mut TestAppContext,
) {
let dir = TempDir::new("sort-76");
let path = dir.0.join("config.toml");
let (mut window, root) = open_app(cx, &path, Config::load_or_default);
let page = root.read_with(&window, |root, _| root.page.clone());
assert_eq!(
page.read_with(&window, |page, _| page.champion_sort()),
None
);
page.update(&mut window, |page, cx| {
page.choose_sort(ChampionSort::Name, cx)
});
let saved = std::fs::read_to_string(&path).unwrap();
assert!(saved.contains("champion_sort = \"name\""), "{saved}");
drop((window, root, page));
// The app opened again, from the file.
let (window, root) = open_app(cx, &path, Config::load);
let page = root.read_with(&window, |root, _| root.page.clone());
page.read_with(&window, |page, _| {
assert_eq!(page.champion_sort(), Some(ChampionSort::Name));
assert_eq!(page.home_filter(), arena_tracker_core::StateFilter::All);
});
}
}
+495 -31
View File
@@ -6,9 +6,9 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChampSelect, ChampionRow, ChampionSearch, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, account_riot_id,
same_riot_id,
Account, ChampSelect, ChampionRow, ChampionSearch, ChampionSort, Format, ProgressCheck, Scope,
SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
account_riot_id, same_riot_id,
};
use gpui_kit::base::Button as BaseButton;
use gpui_kit::base::async_util::{Receiver, Sender};
@@ -25,6 +25,7 @@ mod statistics;
use crate::card::Card;
use crate::card_grid::CardGrid;
use crate::card_order::card_order;
use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, official_differs, sync_line};
use crate::worker::{
@@ -36,6 +37,11 @@ use statistics::ChartsRow;
pub(crate) const PAGE_PADDING: f32 = 12.;
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
/// The sorts on offer, in the selector's order.
const SORTS: [(ChampionSort, &str); 2] = [
(ChampionSort::Mastery, "Maîtrise"),
(ChampionSort::Name, "A–Z"),
];
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
@@ -90,12 +96,25 @@ impl SelectItem for AccountItem {
}
}
/// What the page starts from.
pub struct Launch {
pub notice: Option<String>,
/// A follower thread is already running, its first round is pending.
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
}
/// The page entered or left an Arena champ select.
pub struct ChampSelectTransition {
pub entered: bool,
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The player chose a sort for the cards: to be saved with the other preferences.
pub struct ChampionSortChosen(pub ChampionSort);
impl EventEmitter<ChampionSortChosen> for Page {}
/// The two pages the navigation switches between.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Tab {
@@ -161,6 +180,16 @@ pub struct Page {
home_filter: StateFilter,
home_search: ChampionSearch,
home_search_input: Entity<InputState>,
/// The sort the player chose, saved with the preferences; `None` until one is chosen, which
/// sorts by Mastery Points.
champion_sort: Option<ChampionSort>,
sort_select: Entity<SelectState<Vec<SharedString>>>,
/// The positions of the home statistics' rows in the cards' order, which every section
/// follows. Computed again only when those statistics or the sort change (`reorder`).
order: Vec<usize>,
/// How many times `order` was computed.
#[cfg(test)]
reorders: usize,
stored: Option<usize>,
account_select: Entity<SelectState<Vec<AccountItem>>>,
account_items: Vec<AccountItem>,
@@ -193,16 +222,19 @@ pub struct Page {
}
impl Page {
/// `following`: a follower thread is already running, its first round is pending.
pub fn new(
tracker: Arc<Tracker>,
notice: Option<String>,
following: bool,
launch: Launch,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let Launch {
notice,
following,
champion_sort,
} = launch;
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
@@ -225,6 +257,13 @@ impl Page {
let format_names = vec![SharedString::from(ALL_FORMATS)];
let format_select = cx
.new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx));
let sorts: Vec<SharedString> = SORTS.iter().map(|(_, label)| (*label).into()).collect();
let chosen = SORTS
.iter()
.position(|(sort, _)| Some(*sort) == champion_sort)
.unwrap_or(0);
let sort_select =
cx.new(|cx| SelectState::new(sorts, Some(IndexPath::new(chosen)), window, cx));
let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let charts = cx.new(|_| ChartsRow::new());
let home_search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
@@ -290,6 +329,18 @@ impl Page {
this.recompute(window, cx);
},
),
cx.subscribe(
&sort_select,
|this, _, event: &SelectEvent<Vec<SharedString>>, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
if let Some((sort, _)) = SORTS.iter().find(|(_, label)| *label == name.as_ref())
{
this.choose_sort(*sort, cx);
}
},
),
cx.subscribe_in(
&format_select,
window,
@@ -354,6 +405,11 @@ impl Page {
home_filter: StateFilter::All,
home_search: ChampionSearch::new(""),
home_search_input,
champion_sort,
sort_select,
order: Vec::new(),
#[cfg(test)]
reorders: 0,
stored: None,
account_select,
account_items: Vec::new(),
@@ -513,6 +569,7 @@ impl Page {
self.home_stats = None;
self.home_error = None;
self.stored = None;
self.reorder();
// A new selection starts with « Autres champions » folded and searchless.
self.fold_others(window, cx);
self.reload_in_background(window, cx);
@@ -800,6 +857,7 @@ impl Page {
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reorder();
if self.in_champ_select() {
// Neither the charts, the table nor the home grid are shown during a selection.
self.prepare_home_labels();
@@ -840,12 +898,59 @@ impl Page {
self.home_fraction = fraction;
}
/// One card per champion, in the statistics' order (A to Z), for when the statistics change.
fn prepare_home_cards(&mut self, cx: &mut Context<Self>) {
let cards: Rc<[Card]> = self
/// Computes the cards' order again: for when the home statistics (the champ select's during
/// a selection) or the sort change, and for nothing else.
fn reorder(&mut self) {
let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery);
let rows = self
.home_statistics()
.map(|s| s.rows.iter().map(Card::from_row).collect())
.unwrap_or_default();
.map_or(&[][..], |s| s.rows.as_slice());
self.order = card_order(rows, sort);
#[cfg(test)]
{
self.reorders += 1;
}
}
/// The home statistics' rows in the cards' order: the single iteration the home grid, the
/// Anvil champions and « Autres champions » all follow.
fn ordered_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
self.order.iter().filter_map(move |&ix| rows.get(ix))
}
#[cfg(test)]
pub(crate) fn champion_sort(&self) -> Option<ChampionSort> {
self.champion_sort
}
#[cfg(test)]
pub(crate) fn home_filter(&self) -> StateFilter {
self.home_filter
}
/// The player chose a sort: the cards of every section follow it, and it is saved.
pub(crate) fn choose_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
if self.champion_sort == Some(sort) {
return;
}
self.champion_sort = Some(sort);
self.reorder();
if self.in_champ_select() {
self.prepare_champ_select(cx);
} else {
self.prepare_home_cards(cx);
self.refresh_home(cx);
}
cx.emit(ChampionSortChosen(sort));
cx.notify();
}
/// One card per champion, in the cards' order, for when the statistics or the sort change.
fn prepare_home_cards(&mut self, cx: &mut Context<Self>) {
let cards: Rc<[Card]> = self.ordered_rows().map(Card::from_row).collect();
self.home_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
}
@@ -869,13 +974,13 @@ impl Page {
(None, false) if self.status.updating.is_none() => "Compte indisponible".into(),
(None, false) => "Chargement des statistiques…".into(),
};
// The same rows in the same order as the home grid (`prepare_home_cards`): the
// The same rows in the same order as the home grid (`ordered_rows`): the
// cards keep their place whatever the champ select does. An id the rows do not know is
// skipped.
let cards: Rc<[Card]> = match self.live_champ_select() {
Some(pick) => {
let anvil = pick.anvil_champions.as_deref().unwrap_or_default();
self.champ_select_order()
self.ordered_rows()
.filter(|row| anvil.contains(&row.champion.id))
.map(|row| {
Card::from_row(row)
@@ -894,19 +999,13 @@ impl Page {
self.prepare_others(cx);
}
/// The master order of the champ select's cards, which every section follows: the
/// statistics' rows, as the home grid's.
fn champ_select_order(&self) -> impl Iterator<Item = &ChampionRow> {
self.stats.iter().flat_map(|stats| stats.rows.iter())
}
/// The rows of « Autres champions »: those whose id is not an Anvil one, in the master
/// order; all of them when the client gave no list.
fn other_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let anvil = self
.live_champ_select()
.and_then(|pick| pick.anvil_champions.as_deref());
self.champ_select_order()
self.ordered_rows()
.filter(move |row| anvil.is_none_or(|ids| !ids.contains(&row.champion.id)))
}
@@ -1000,9 +1099,9 @@ impl Page {
if self.tab != Tab::Challenge || self.in_champ_select() {
return;
}
// The cards are the rows, in the same order: a card's index is its row's.
let rows = self.home_statistics().into_iter().flat_map(|s| &s.rows);
let shown: Vec<usize> = rows
// The cards are the rows in the cards' order: a card's index is its position.
let shown: Vec<usize> = self
.ordered_rows()
.enumerate()
.filter(|(_, row)| {
self.home_filter.keeps(row) && self.home_search.matches(&row.champion)
@@ -1174,9 +1273,9 @@ mod tests {
use std::sync::Arc;
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionState, Charts,
Date, Format, MatchHistorySource, RiotApi, Season, SeasonScope, SourceError, StateFilter,
Statistics, Tracker,
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
ChampionState, Charts, Date, Format, MatchHistorySource, RiotApi, Season, SeasonScope,
SourceError, StateFilter, Statistics, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
@@ -1185,7 +1284,7 @@ mod tests {
point, px, size,
};
use super::{Page, Tab};
use super::{ChampionSortChosen, Page, SelectEvent, Tab};
use crate::card::ASPECT;
use crate::card_grid::CardGrid;
use crate::champion_table::tests::row;
@@ -1205,6 +1304,15 @@ mod tests {
fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<Page>, VisualTestContext) {
open_page_with_sort(cx, tracker, None)
}
/// `champion_sort`: the sort saved by an earlier run.
fn open_page_with_sort(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
@@ -1220,7 +1328,20 @@ mod tests {
..Default::default()
};
gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| Page::new(tracker, None, false, rx, tx, window, cx))
cx.new(|cx| {
Page::new(
tracker,
super::Launch {
notice: None,
following: false,
champion_sort,
},
rx,
tx,
window,
cx,
)
})
})
.unwrap()
});
@@ -2331,8 +2452,34 @@ mod tests {
}
Ok(payload.to_string())
}
fn champion_mastery(&self, _: &str, puuid: &str) -> Result<Vec<(u32, u64)>, SourceError> {
Ok(if puuid == "Joueur" {
MASTERY.to_vec()
} else {
Vec::new()
})
}
}
/// Joueur's Mastery Points. Xin Zhao (5) and Morgana (25) are missing from the list: known,
/// no points.
const MASTERY: [(u32, u64); 7] = [
(64, 120_000),
(16, 40_000),
(50, 9_000),
(233, 5_000),
(68, 900),
(12, 300),
(103, 100),
];
/// The Anvil champions of the capture by Mastery Points, then those without an anvil.
const ANVIL_BY_MASTERY: [u32; 5] = [64, 16, 233, 68, 5];
const OTHERS_BY_MASTERY: [u32; 4] = [50, 12, 103, 25];
const ALL_A_TO_Z: [&str; 9] = [
"Ahri", "Alistar", "Briar", "Lee Sin", "Morgana", "Rumble", "Soraka", "Swain", "Xin Zhao",
];
struct Catalog;
impl ChampionSource for Catalog {
@@ -2365,16 +2512,31 @@ mod tests {
/// The tracker of Joueur (and of Autre, who has played nothing), on the catalog.
fn joueur_tracker() -> Tracker {
joueur_tracker_with(false)
}
/// `mastery`: Joueur is the Account being followed and its points were fetched.
fn joueur_tracker_with(mastery: bool) -> Tracker {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
// One folder per tracker: the tests run in parallel.
static TRACKERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = TRACKERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let portraits =
std::env::temp_dir().join(format!("arena-tracker-74-{}", std::process::id()));
std::env::temp_dir().join(format!("arena-tracker-74-{}-{n}", std::process::id()));
let tracker = tracker.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
let _ = std::fs::remove_dir(portraits);
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
if mastery {
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
// Without a client, a round adopts the Riot ID it is given, then asks for the points.
tracker.follow_client(0, Some(JOUEUR), &mut |_| {});
assert!(tracker.mastery("Joueur").unwrap().is_some());
} else {
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
}
tracker
}
@@ -3126,4 +3288,306 @@ mod tests {
assert!(weak.upgrade().is_none(), "the folded grid's cache is kept");
assert_eq!(in_atlas(&mut window), 0);
}
// The sort of the cards (#76).
/// A row with a name, an id and its Mastery Points.
fn with_points(id: u32, name: &str, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
mastery_points: points,
..row(name)
}
}
/// A to Z, as the statistics give them.
fn rows_with_points() -> Vec<ChampionRow> {
vec![
with_points(1, "Ahri", None),
with_points(2, "Brand", Some(500)),
with_points(3, "Garen", Some(9_000)),
with_points(4, "Jinx", Some(500)),
with_points(5, "Lux", Some(0)),
with_points(6, "Zed", None),
]
}
const BY_MASTERY: [&str; 6] = ["Garen", "Brand", "Jinx", "Lux", "Ahri", "Zed"];
const A_TO_Z: [&str; 6] = ["Ahri", "Brand", "Garen", "Jinx", "Lux", "Zed"];
/// The sorts the page reports, in order.
fn record_sorts(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Rc<RefCell<Vec<ChampionSort>>> {
let chosen = Rc::new(RefCell::new(Vec::new()));
let events = chosen.clone();
cx.update(|_, cx| {
cx.subscribe(page, move |_, event: &ChampionSortChosen, _| {
events.borrow_mut().push(event.0)
})
.detach()
});
chosen
}
/// The player picks `label` in the sort selector.
fn pick_sort(page: &Entity<Page>, cx: &mut VisualTestContext, label: &'static str) {
let select = page.read_with(cx, |p, _| p.sort_select.clone());
cx.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some(label.into())))
})
});
draw(cx);
}
fn reorders(page: &Entity<Page>, cx: &mut VisualTestContext) -> usize {
page.read_with(cx, |p, _| p.reorders)
}
#[gpui::test]
fn the_home_follows_the_mastery_points_until_another_sort_is_chosen(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
// Nothing chosen: Mastery Points descending, ties by name, unknown ones last.
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert!(cx.debug_bounds("sort").is_some());
let generation = page.read_with(cx, |p, _| p.stats_generation);
let before = reorders(&page, cx);
pick_sort(&page, cx, "A–Z");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Name]);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
// The statistics are as they were: only the cards moved.
assert_eq!(p.stats_generation, generation);
let rows = p.stats.as_ref().unwrap().rows.iter();
assert_eq!(
rows.map(|r| r.champion.name.as_str()).collect::<Vec<_>>(),
A_TO_Z
);
});
assert_eq!(reorders(&page, cx), before + 1);
// The filter and the search apply to the new order.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(grid_names(&grid, cx), A_TO_Z);
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert_eq!(
*chosen.borrow(),
[ChampionSort::Name, ChampionSort::Mastery]
);
// Choosing what is already chosen reports nothing.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(chosen.borrow().len(), 2);
}
#[gpui::test]
fn without_any_known_value_the_cards_are_a_to_z_and_the_preference_is_untouched(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
let unknown: Vec<ChampionRow> = rows_with_points()
.into_iter()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
show(&page, cx, statistics(0, 6, unknown));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert!(chosen.borrow().is_empty());
// The cards say it: unknown, not zero.
let sheets = grid.read_with(cx, |grid, _| grid.shown_cards());
assert!(sheets.iter().all(|card| {
card.sheet
.iter()
.any(|(label, value)| *label == "Points de maîtrise" && value == "Inconnus")
}));
// Mastery chosen on purpose is still A to Z while nothing is known, and is saved.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Mastery]);
// The points arrive: the preference now applies.
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
}
#[gpui::test]
fn a_saved_sort_is_there_at_the_first_draw(cx: &mut TestAppContext) {
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let (page, cx) = open_page_with_sort(cx, tracker, Some(ChampionSort::Name));
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
assert_eq!(p.home_filter, StateFilter::All);
});
}
#[gpui::test]
fn the_cards_are_sorted_again_only_when_the_data_or_the_preference_change(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let count = reorders(&page, cx);
// Hovering a card, the search, the filter and the champ-select-less rounds change
// neither the data nor the preference.
let card = grid.read_with(cx, |grid, _| grid.shown_cards()[0].id);
let id: &'static str = Box::leak(format!("card-{card}").into_boxed_str());
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("r");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(reorders(&page, cx), count);
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(reorders(&page, cx), count + 1, "new data");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "new preference");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "same preference");
}
#[gpui::test]
async fn alias_filters_sort_and_the_champ_select_all_follow_one_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
let chosen = record_sorts(&page, &mut window);
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let type_search = |window: &mut VisualTestContext, text: &str| {
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
window.simulate_input(text);
};
// Soraka, Swain, Briar, Rumble... by Mastery Points, the zeros by name.
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[64, 16, 50, 233, 68, 12, 103, 25, 5]
);
// An alias.
type_search(&mut window, "srk");
assert_eq!(grid_names(&home_grid, &mut window), ["Soraka"]);
// A name part and a filter: Soraka is Completed, so « Restants » drops it.
type_search(&mut window, "a");
page.update(&mut window, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[50, 233, 12, 103, 25, 5]
);
pick_sort(&page, &mut window, "A–Z");
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[103, 12, 233, 25, 50, 5]
);
// Entering a champ select: the Anvil row follows the sort, so does « Autres champions »,
// and the selector stays.
send(&page, &mut window, &frames()[0]);
window.update(|w, cx| {
page.update(cx, |p, cx| p.reload_in_background(w, cx));
});
cx.condition(&page, |p, _| {
p.stats.as_ref().is_some_and(|s| s.rows.len() == 9)
})
.await;
draw(&mut window);
assert!(window.debug_bounds("sort").is_some());
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
click_others(&mut window);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
pick_sort(&page, &mut window, "Maîtrise");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_BY_MASTERY);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_BY_MASTERY);
// Reasons still go with their cards.
assert_eq!(
reasons(&anvil_cards(&page, &mut window), 16),
[Reason::Completed]
);
// The statistics themselves stay A to Z.
page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
let names: Vec<_> = rows.map(|row| row.champion.name.as_str()).collect();
assert_eq!(names, ALL_A_TO_Z);
});
pick_sort(&page, &mut window, "A–Z");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
// Leaving gives back « Tous » and an empty search, with the sort kept.
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.home_filter, StateFilter::All);
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
});
assert_eq!(
*chosen.borrow(),
[
ChampionSort::Name,
ChampionSort::Mastery,
ChampionSort::Name
]
);
assert_eq!(grid_names(&home_grid, &mut window), ALL_A_TO_Z);
}
}
+48 -17
View File
@@ -3,6 +3,7 @@
use arena_tracker_core::StateFilter;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
@@ -68,6 +69,25 @@ impl Page {
vec![column.into_any_element()]
}
/// The sort selector: a sort icon and the choice, « Maîtrise » or « A–Z ». It stays on the
/// home and during a selection, and applies to every section of cards.
fn sort_selector(&self, cx: &App) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
div()
.h_flex()
.items_center()
.gap_1()
.debug_selector(|| "sort".into())
.child(Icon::new(IconName::SortAscending).small().text_color(muted))
.child(
Select::new(&self.sort_select)
.id("sort")
.accessibility_label("Trier les cartes")
.w(px(140.))
.min_w(px(110.)),
)
}
/// What stands in place of the Anvil champions row, if anything: the statistics are missing,
/// or the client gave no list (which does not make any champion « sans enclume »), or an
/// empty one.
@@ -95,27 +115,37 @@ impl Page {
.child(
div()
.h_flex()
.flex_wrap()
.items_center()
.gap(px(6.))
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions de l'Enclume"),
.h_flex()
.items_center()
.gap(px(6.))
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Champions de l'Enclume"),
)
.when(row.is_none(), |heading| {
heading.child(
div()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(border)
.rounded(px(6.))
.text_xs()
.text_color(muted)
.child(self.anvil_count.clone()),
)
}),
)
.when(row.is_none(), |heading| {
heading.child(
div()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(border)
.rounded(px(6.))
.text_xs()
.text_color(muted)
.child(self.anvil_count.clone()),
)
}),
.child(self.sort_selector(cx)),
)
.child(match row {
Some(line) => div()
@@ -251,6 +281,7 @@ impl Page {
.h_flex()
.items_center()
.gap_3()
.child(self.sort_selector(cx))
.child(
TabBar::new("home-filter")
.segmented()
+25 -1
View File
@@ -4,7 +4,9 @@ use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference, UpdateChannel};
use arena_tracker_core::{
ChampionSort, Config, Error, Preferences, RiotApi, ThemePreference, UpdateChannel,
};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
@@ -62,6 +64,10 @@ impl KeyStore {
!self.config.riot_api_key.is_empty()
}
pub fn preferences(&self) -> Preferences {
self.config.preferences
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
@@ -286,6 +292,24 @@ impl KeyForm {
cx.notify();
}
/// Saves the cards' sort with the other preferences. Nothing else changes, and a failed
/// write only shows the usual message in the settings: the page keeps the choice.
pub fn save_champion_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
let preferences = Preferences {
champion_sort: Some(sort),
..self.store.config.preferences
};
if preferences == self.store.config.preferences {
return;
}
self.preference_error = self
.store
.save_preferences(preferences)
.is_err()
.then(|| "Impossible d’enregistrer les préférences.".into());
cx.notify();
}
fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.config.preferences;
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
+23
View File
@@ -16,6 +16,20 @@ pub fn stored(count: usize) -> String {
}
}
/// An integer in French format: groups of three digits separated by a narrow no-break space
/// (U+202F), as `toLocaleString('fr-FR')` writes it: `154 320`.
pub fn thousands(value: u64) -> String {
let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, digit) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push('\u{202f}');
}
out.push(digit);
}
out
}
/// A Placement as the sheet writes it: « 1ᵉʳ », « 2ᵉ », « 3ᵉ »…
pub fn ordinal(placement: u8) -> String {
match placement {
@@ -77,6 +91,15 @@ mod tests {
assert_eq!(decimal(2.0 / 3.0, 1), "0,7");
}
#[test]
fn thousands_are_grouped_with_a_narrow_no_break_space() {
assert_eq!(thousands(0), "0");
assert_eq!(thousands(999), "999");
assert_eq!(thousands(1_000), "1\u{202f}000");
assert_eq!(thousands(154_320), "154\u{202f}320");
assert_eq!(thousands(1_234_567), "1\u{202f}234\u{202f}567");
}
#[test]
fn placements_are_written_as_french_ordinals() {
assert_eq!(ordinal(1), "1ᵉʳ");