Search the champion table by name and known aliases (#18) #42

Merged
nessar merged 1 commits from feat/18-champion-search into main 2026-11-17 23:40:34 +01:00
7 changed files with 467 additions and 28 deletions

No files matched your search

+5
View File
@@ -69,6 +69,11 @@ impl ChampionTable {
self.resort();
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<String> {
self.rows.iter().map(|r| r.champion.name.clone()).collect()
}
/// Column and `descending`.
fn sorted_by(&self) -> (SortKey, bool) {
self.sort
+129 -22
View File
@@ -4,14 +4,15 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
Account, ChallengeSummary, Charts, Format, ProgressCheck, Scope, SeasonScope, StateFilter,
Statistics, Status, SyncProgress, Tracker, UpdateProblem,
Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope,
StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem,
};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::StyledExt as _;
use gpui_kit::component::alert::Alert;
use gpui_kit::component::button::Button;
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _};
@@ -104,6 +105,9 @@ pub struct StatsPage {
season: SeasonScope,
format: Option<Format>,
filter: StateFilter,
/// Kept and reapplied whenever the table's rows are rebuilt.
search: ChampionSearch,
search_input: Entity<InputState>,
stats: Option<Statistics>,
stats_error: Option<String>,
stored: Option<usize>,
@@ -171,10 +175,18 @@ impl StatsPage {
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 search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher un champion"));
let charts = cx.new(|_| ChartsRow::new());
let table = cx.new(|_| ChampionTable::new());
let subscriptions = vec![
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.search = ChampionSearch::new(&input.read(cx).value());
this.refresh_table(cx);
}
}),
cx.subscribe_in(
&account_select,
window,
@@ -253,6 +265,8 @@ impl StatsPage {
season,
format: None,
filter: StateFilter::All,
search: ChampionSearch::new(""),
search_input,
stats: None,
stats_error: None,
stored: None,
@@ -537,7 +551,10 @@ impl StatsPage {
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows.filter(|row| self.filter.keeps(row)).cloned().collect();
let rows = rows
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
@@ -940,17 +957,30 @@ impl Render for StatsPage {
)
.when(shown("tabs"), |page| {
page.child(
TabBar::new("state-filter")
.segmented()
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = filters(this.in_season()).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
}
})),
div()
.h_flex()
.items_center()
.justify_between()
.gap_3()
.child(
TabBar::new("state-filter")
.segmented()
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = filters(this.in_season()).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
}
})),
)
.child(
Input::new(&self.search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
),
)
})
.when(shown("table"), |page| {
@@ -966,20 +996,19 @@ mod tests {
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{RiotApi, Tracker};
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Charts, RiotApi, StateFilter, Statistics, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
AppContext as _, Bounds, Modifiers, TestAppContext, VisualTestContext, WindowBounds,
WindowOptions, point, px, size,
AppContext as _, Bounds, Entity, Modifiers, TestAppContext, VisualTestContext,
WindowBounds, WindowOptions, point, px, size,
};
use super::StatsPage;
use crate::champion_table::tests::row;
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
fn open_page(cx: &mut TestAppContext) -> (Entity<StatsPage>, VisualTestContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(
Tracker::open(
@@ -1004,7 +1033,85 @@ mod tests {
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
(page, VisualTestContext::from_window(window, cx))
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
..row(name)
};
page.update(cx, |page, _| {
page.stats = Some(Statistics {
challenge: None,
rows: vec![
ChampionRow {
state: Some(ChampionState::Completed),
..champion(4, "TwistedFate", "Twisted Fate")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
..champion(86, "Garen", "Garen")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
matches: 5,
..champion(107, "Rengar", "Rengar")
},
],
charts: Charts {
placements: Vec::new(),
completed_over_time: Vec::new(),
attempts_to_complete: [0; 5],
},
formats: Vec::new(),
});
});
let (input, table) = page.read_with(cx, |p, _| (p.search_input.clone(), p.table.clone()));
let names = |cx: &mut VisualTestContext| table.read_with(cx, |table, _| table.names());
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("ren");
assert_eq!(names(cx), ["Rengar", "Garen"]);
// The clear button's own path: it empties the field and the table follows.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(names(cx).len(), 3);
cx.simulate_input("TF");
assert_eq!(names(cx), ["Twisted Fate"]);
cx.simulate_input("z");
assert!(names(cx).is_empty());
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input(" ");
assert_eq!(names(cx).len(), 3);
// Combined with a state filter, the table keeps its sort (most Matches first).
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input("ren");
page.update(cx, |page, cx| {
page.filter = StateFilter::Completed;
page.refresh_table(cx);
});
assert!(names(cx).is_empty());
page.update(cx, |page, cx| {
page.filter = StateFilter::NeverPlayed;
page.refresh_table(cx);
});
assert_eq!(names(cx), ["Rengar", "Garen"]);
}
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let (table, charts) =
page.read_with(cx, |page, _| (page.table.clone(), page.charts.clone()));
// Enough rows to fill the table, under the points hovered below.
+188
View File
@@ -0,0 +1,188 @@
# Champion key, then an alias (Data Dragon id, tab, alias). Sources: docs/research/champion-search-aliases.md, plus English names the catalog lacks.
Aatrox aa
Aatrox aat
Akali aka
Akshan ak
Alistar Cow
Alistar Ali
Amumu Mummy
Amumu amu
Anivia aniv
Annie ann
Aphelios aph
AurelionSol ASol
AurelionSol Sol
AurelionSol a sol
Bard Brad
Belveth bel
Blitzcrank Blitz
Blitzcrank blit
Braum brm
Briar bri
Caitlyn Cait
Camille cam
Camille cami
Cassiopeia Cass
Chogath Cho
Corki cor
Darius dar
Diana dia
Draven dra
Draven drav
DrMundo Dr
DrMundo Mundo
DrMundo dm
DrMundo mun
Ekko ek
Elise eli
Evelynn Eve
Ezreal Ez
Fiddlesticks Fid
Fiddlesticks Fiddle
Fiddlesticks fids
Fiora fio
Galio gal
Galio gali
Gangplank Gp
Garen gar
Gragas grag
Graves grav
Hecarim Hec
Hecarim heca
Heimerdinger Heimer
Heimerdinger Donger
Heimerdinger heim
Heimerdinger heime
Illaoi ill
Irelia ire
Ivern ive
Janna jan
JarvanIV J4
JarvanIV jarvan
JarvanIV jarvan 4
Jayce jc
Jinx jnx
Kaisa ks
Kaisa kai
Kalista kali
Karma karm
Karthus kart
Karthus karth
Kassadin Kass
Kassadin kassa
Katarina Kat
Katarina kata
Kayle kayl
Kennen ken
Khazix k6
Khazix kha
Kindred kin
Kindred kind
KogMaw Kog
KSante ksa
Leblanc LB
LeeSin Lee
Leona leo
Lillia lil
Lissandra Liss
Lucian luc
MasterYi Yi
Malphite Malph
Malphite malp
Malzahar Malz
Malzahar malza
Maokai Tree
Maokai mao
Milio mil
MissFortune MF
Mordekaiser Mord
Mordekaiser morde
Morgana Morg
Naafiri naa
Nasus Susan
Nautilus Naut
Neeko nee
Nidalee Nid
Nidalee nida
Nilah nil
Nocturne Noct
Nocturne noc
Orianna Ori
Orianna oriana
Pantheon Panth
Poppy pop
Qiyana qiy
Quinn quin
Rakan rak
Rammus ram
RekSai rek
Renata rg
Renekton Gator
Renekton rene
Renekton renek
Rengar ren
Rengar reng
Riven riv
Rumble rum
Samira sam
Samira sami
Sejuani Sej
Sejuani seju
Senna sen
Seraphine ser
Seraphine sera
Shyvana Shyv
Singed sin
Sivir siv
Skarner skar
Smolder smo
Smolder sml
Soraka srk
Soraka raka
Swain swa
Sylas syl
Syndra syn
TahmKench TK
TahmKench tahm
TahmKench kench
Taliyah tali
Talon tal
Taric tar
Teemo tee
Thresh thr
Tristana Trist
Tristana tris
Trundle Troll
Trundle trun
Tryndamere Trynd
Tryndamere tryn
Tryndamere trynda
TwistedFate TF
Twitch twi
Urgot ur
Urgot urg
Varus var
Vayne vn
Vayne vay
Veigar vei
Veigar veig
Velkoz vel
Viego vie
Viktor vik
Vladimir Vlad
Volibear Voli
Warwick WW
MonkeyKing wu
MonkeyKing wuk
Xayah xay
Xerath xer
XinZhao Xin
XinZhao xz
Yasuo Yas
Yone y1
Yorick yor
Yuumi yuu
Zaahen zaa
Ziggs zig
Zilean Zil
Nunu Nunu & Willump
1 # Champion key, then an alias (Data Dragon id, tab, alias). Sources: docs/research/champion-search-aliases.md, plus English names the catalog lacks.
2 Aatrox aa
3 Aatrox aat
4 Akali aka
5 Akshan ak
6 Alistar Cow
7 Alistar Ali
8 Amumu Mummy
9 Amumu amu
10 Anivia aniv
11 Annie ann
12 Aphelios aph
13 AurelionSol ASol
14 AurelionSol Sol
15 AurelionSol a sol
16 Bard Brad
17 Belveth bel
18 Blitzcrank Blitz
19 Blitzcrank blit
20 Braum brm
21 Briar bri
22 Caitlyn Cait
23 Camille cam
24 Camille cami
25 Cassiopeia Cass
26 Chogath Cho
27 Corki cor
28 Darius dar
29 Diana dia
30 Draven dra
31 Draven drav
32 DrMundo Dr
33 DrMundo Mundo
34 DrMundo dm
35 DrMundo mun
36 Ekko ek
37 Elise eli
38 Evelynn Eve
39 Ezreal Ez
40 Fiddlesticks Fid
41 Fiddlesticks Fiddle
42 Fiddlesticks fids
43 Fiora fio
44 Galio gal
45 Galio gali
46 Gangplank Gp
47 Garen gar
48 Gragas grag
49 Graves grav
50 Hecarim Hec
51 Hecarim heca
52 Heimerdinger Heimer
53 Heimerdinger Donger
54 Heimerdinger heim
55 Heimerdinger heime
56 Illaoi ill
57 Irelia ire
58 Ivern ive
59 Janna jan
60 JarvanIV J4
61 JarvanIV jarvan
62 JarvanIV jarvan 4
63 Jayce jc
64 Jinx jnx
65 Kaisa ks
66 Kaisa kai
67 Kalista kali
68 Karma karm
69 Karthus kart
70 Karthus karth
71 Kassadin Kass
72 Kassadin kassa
73 Katarina Kat
74 Katarina kata
75 Kayle kayl
76 Kennen ken
77 Khazix k6
78 Khazix kha
79 Kindred kin
80 Kindred kind
81 KogMaw Kog
82 KSante ksa
83 Leblanc LB
84 LeeSin Lee
85 Leona leo
86 Lillia lil
87 Lissandra Liss
88 Lucian luc
89 MasterYi Yi
90 Malphite Malph
91 Malphite malp
92 Malzahar Malz
93 Malzahar malza
94 Maokai Tree
95 Maokai mao
96 Milio mil
97 MissFortune MF
98 Mordekaiser Mord
99 Mordekaiser morde
100 Morgana Morg
101 Naafiri naa
102 Nasus Susan
103 Nautilus Naut
104 Neeko nee
105 Nidalee Nid
106 Nidalee nida
107 Nilah nil
108 Nocturne Noct
109 Nocturne noc
110 Orianna Ori
111 Orianna oriana
112 Pantheon Panth
113 Poppy pop
114 Qiyana qiy
115 Quinn quin
116 Rakan rak
117 Rammus ram
118 RekSai rek
119 Renata rg
120 Renekton Gator
121 Renekton rene
122 Renekton renek
123 Rengar ren
124 Rengar reng
125 Riven riv
126 Rumble rum
127 Samira sam
128 Samira sami
129 Sejuani Sej
130 Sejuani seju
131 Senna sen
132 Seraphine ser
133 Seraphine sera
134 Shyvana Shyv
135 Singed sin
136 Sivir siv
137 Skarner skar
138 Smolder smo
139 Smolder sml
140 Soraka srk
141 Soraka raka
142 Swain swa
143 Sylas syl
144 Syndra syn
145 TahmKench TK
146 TahmKench tahm
147 TahmKench kench
148 Taliyah tali
149 Talon tal
150 Taric tar
151 Teemo tee
152 Thresh thr
153 Tristana Trist
154 Tristana tris
155 Trundle Troll
156 Trundle trun
157 Tryndamere Trynd
158 Tryndamere tryn
159 Tryndamere trynda
160 TwistedFate TF
161 Twitch twi
162 Urgot ur
163 Urgot urg
164 Varus var
165 Vayne vn
166 Vayne vay
167 Veigar vei
168 Veigar veig
169 Velkoz vel
170 Viego vie
171 Viktor vik
172 Vladimir Vlad
173 Volibear Voli
174 Warwick WW
175 MonkeyKing wu
176 MonkeyKing wuk
177 Xayah xay
178 Xerath xer
179 XinZhao Xin
180 XinZhao xz
181 Yasuo Yas
182 Yone y1
183 Yorick yor
184 Yuumi yuu
185 Zaahen zaa
186 Ziggs zig
187 Zilean Zil
188 Nunu Nunu & Willump
+135
View File
@@ -0,0 +1,135 @@
//! Searching champions by name, Data Dragon id or known alias (issue #18).
use std::collections::HashMap;
use std::sync::OnceLock;
use crate::champions::Champion;
use crate::statistics::collate;
/// Data Dragon id, then an alias: kept local, U.GG and Liquipedia are research sources only.
const ALIASES: &str = include_str!("champion_aliases.tsv");
/// Case, accents and everything but letters and digits do not count.
fn normalize(text: &str) -> String {
collate(text)
.chars()
.filter(|c| c.is_alphanumeric())
.collect()
}
/// Normalized aliases by Data Dragon id: the id is the stable champion identifier.
fn aliases(key: &str) -> &'static [String] {
static BY_KEY: OnceLock<HashMap<&str, Vec<String>>> = OnceLock::new();
let by_key = BY_KEY.get_or_init(|| {
let mut by_key: HashMap<&str, Vec<String>> = HashMap::new();
for line in ALIASES.lines().filter(|l| !l.starts_with('#')) {
if let Some((key, alias)) = line.split_once('\t') {
by_key.entry(key).or_default().push(normalize(alias));
}
}
by_key
});
by_key.get(key).map_or(&[], Vec::as_slice)
}
/// A search query, normalized once for all the rows.
pub struct ChampionSearch(String);
impl ChampionSearch {
pub fn new(query: &str) -> ChampionSearch {
ChampionSearch(normalize(query))
}
/// An empty query (or only spaces and punctuation) keeps every champion; otherwise the
/// query is part of the name or id, or is exactly one of the champion's aliases.
pub fn matches(&self, champion: &Champion) -> bool {
let query = &self.0;
query.is_empty()
|| normalize(&champion.name).contains(query)
|| normalize(&champion.key).contains(query)
|| aliases(&champion.key).iter().any(|a| a == query)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::champions::decode_catalog;
fn catalog() -> Vec<Champion> {
let body = include_str!("../tests/fixtures/ddragon/champion.json");
decode_catalog("16.22.1", body).unwrap().champions
}
fn found(query: &str) -> Vec<String> {
let search = ChampionSearch::new(query);
let hits = catalog().into_iter().filter(|c| search.matches(c));
let mut names: Vec<String> = hits.map(|c| c.name).collect();
names.sort();
names
}
#[test]
fn finds_the_ticket_examples() {
assert_eq!(found("tf"), ["Twisted Fate"]);
assert_eq!(found("ksante"), ["K'Santé"]);
assert_eq!(found("asol"), ["Aurelion Sol"]);
}
#[test]
fn ignores_case_accents_whitespace_and_punctuation() {
for (query, name) in [
("maitre yi", "Maître Yi"),
("Master Yi", "Maître Yi"),
("MAÎTRE-YI", "Maître Yi"),
("seraphine", "Séraphine"),
("zoe", "Zoé"),
("K’Santé", "K'Santé"),
("K Sante", "K'Santé"),
("kaisa", "Kai'Sa"),
("cho gath", "Cho'Gath"),
("velkoz", "Vel'Koz"),
("dr. mundo", "Dr. Mundo"),
("nunu & willump", "Nunu et Willump"),
("monkeyking", "Wukong"),
("a sol", "Aurelion Sol"),
] {
assert!(found(query).contains(&name.to_string()), "{query}");
}
}
#[test]
fn keeps_every_matching_champion() {
assert_eq!(
found("ren"),
["Garen", "Renata Glasc", "Renekton", "Rengar"]
);
// An alias is an exact match: it hides no other name match.
assert_eq!(
found("ks"),
["Akshan", "Fiddlesticks", "K'Santé", "Kai'Sa", "Rek'Sai"]
);
}
#[test]
fn a_blank_query_keeps_every_champion() {
for query in ["", " ", "'-. "] {
assert_eq!(found(query).len(), 173);
}
assert!(found("zzzz").is_empty());
}
/// Every alias of the research inventory finds its champion.
#[test]
fn every_alias_finds_its_champion() {
let catalog = catalog();
let mut count = 0;
for line in ALIASES.lines().filter(|l| !l.starts_with('#')) {
let (key, alias) = line.split_once('\t').unwrap();
let champion = catalog.iter().find(|c| c.key == key).expect(key);
assert!(ChampionSearch::new(alias).matches(champion), "{alias}");
count += 1;
}
assert!(count >= 185, "{count}");
}
}
+1 -1
View File
@@ -97,7 +97,7 @@ struct CatalogEntry {
name: String,
}
fn decode_catalog(version: &str, body: &str) -> Result<ChampionCatalog, SourceError> {
pub(crate) fn decode_catalog(version: &str, body: &str) -> Result<ChampionCatalog, SourceError> {
let file: CatalogFile = serde_json::from_str(body)
.map_err(|e| SourceError::Other(format!("Champions illisibles : {e}")))?;
let mut champions = file
+2
View File
@@ -1,3 +1,4 @@
mod champion_search;
mod champions;
mod client;
mod config;
@@ -11,6 +12,7 @@ mod seasons;
mod statistics;
mod tracker;
pub use champion_search::ChampionSearch;
pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon};
pub use client::{ClientError, GameClientSource, GamePhase, Gameflow};
pub use config::{Config, data_dir};
+7 -5
View File
@@ -166,15 +166,17 @@ impl StateFilter {
}
/// Alphabetical order for French names: case and accents do not count.
fn collate(name: &str) -> String {
pub(crate) fn collate(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| match c {
'à' | 'â' | 'ä' => 'a',
'à' | 'á' | 'â' | 'ä' | 'ã' | 'å' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'î' | 'ï' => 'i',
'ô' | 'ö' => 'o',
'ù' | 'û' | 'ü' => 'u',
'í' | 'ì' | 'î' | 'ï' => 'i',
'ó' | 'ò' | 'ô' | 'ö' | 'õ' => 'o',
'ú' | 'ù' | 'û' | 'ü' => 'u',
'ý' | 'ÿ' => 'y',
'ñ' => 'n',
'ç' => 'c',
other => other,
})