diff --git a/crates/app/src/champion_table.rs b/crates/app/src/champion_table.rs index 2062685..3e831f1 100644 --- a/crates/app/src/champion_table.rs +++ b/crates/app/src/champion_table.rs @@ -69,6 +69,11 @@ impl ChampionTable { self.resort(); } + #[cfg(test)] + pub(crate) fn names(&self) -> Vec { + self.rows.iter().map(|r| r.champion.name.clone()).collect() + } + /// Column and `descending`. fn sorted_by(&self) -> (SortKey, bool) { self.sort diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 2fafc1a..4980b3f 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -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, filter: StateFilter, + /// Kept and reapplied whenever the table's rows are rebuilt. + search: ChampionSearch, + search_input: Entity, stats: Option, stats_error: Option, stored: Option, @@ -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) { 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, 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. diff --git a/crates/core/src/champion_aliases.tsv b/crates/core/src/champion_aliases.tsv new file mode 100644 index 0000000..3ca6665 --- /dev/null +++ b/crates/core/src/champion_aliases.tsv @@ -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 diff --git a/crates/core/src/champion_search.rs b/crates/core/src/champion_search.rs new file mode 100644 index 0000000..9636a42 --- /dev/null +++ b/crates/core/src/champion_search.rs @@ -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>> = OnceLock::new(); + let by_key = BY_KEY.get_or_init(|| { + let mut by_key: HashMap<&str, Vec> = 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 { + let body = include_str!("../tests/fixtures/ddragon/champion.json"); + decode_catalog("16.22.1", body).unwrap().champions + } + + fn found(query: &str) -> Vec { + let search = ChampionSearch::new(query); + let hits = catalog().into_iter().filter(|c| search.matches(c)); + let mut names: Vec = 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}"); + } +} diff --git a/crates/core/src/champions.rs b/crates/core/src/champions.rs index c42e99d..a50ab42 100644 --- a/crates/core/src/champions.rs +++ b/crates/core/src/champions.rs @@ -97,7 +97,7 @@ struct CatalogEntry { name: String, } -fn decode_catalog(version: &str, body: &str) -> Result { +pub(crate) fn decode_catalog(version: &str, body: &str) -> Result { let file: CatalogFile = serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Champions illisibles : {e}")))?; let mut champions = file diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 47f33d3..3b01f4f 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -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}; diff --git a/crates/core/src/statistics.rs b/crates/core/src/statistics.rs index caeea62..fdd2420 100644 --- a/crates/core/src/statistics.rs +++ b/crates/core/src/statistics.rs @@ -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, })