//! The champion table: one row per champion, only the visible rows built (issue #31: a row is //! one element per cell, unlike gpui-component's DataTable, which costs a layout per cell). use std::ops::Range; use arena_tracker_core::{ChampionRow, Column as SortKey, Date, sort_rows}; use gpui_kit::component::scroll::Scrollbar; use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use crate::text::{decimal, state_label}; struct Spec { title: &'static str, key: SortKey, width: f32, numeric: bool, } const fn spec(title: &'static str, key: SortKey, width: f32, numeric: bool) -> Spec { Spec { title, key, width, numeric, } } const SPECS: [Spec; 9] = [ spec("Champion", SortKey::Champion, 220., false), spec("État", SortKey::State, 110., false), spec("Parties", SortKey::Matches, 90., true), spec("Meilleur Placement", SortKey::BestPlacement, 160., true), spec("Top 1", SortKey::Top1, 80., true), spec("Victoires", SortKey::Wins, 100., true), spec("Placement moyen", SortKey::AveragePlacement, 150., true), spec("Tentatives", SortKey::Attempts, 110., true), spec("Dernière Partie", SortKey::LastMatch, 150., true), ]; const ROW_HEIGHT: f32 = 32.; const PORTRAIT: f32 = 24.; pub struct ChampionTable { rows: Vec, in_season: bool, /// The user's choice; `None` means the default for the view. sort: Option<(SortKey, bool)>, /// The clicked champion's id: it stays selected through sorting and reloads. selected: Option, scroll: UniformListScrollHandle, } impl ChampionTable { pub fn new() -> ChampionTable { ChampionTable { rows: Vec::new(), in_season: false, sort: None, selected: None, scroll: UniformListScrollHandle::new(), } } /// Replaces the rows (already filtered) and keeps them sorted. pub fn set_rows(&mut self, rows: Vec, in_season: bool) { self.rows = rows; self.in_season = in_season; self.resort(); } /// Column and `descending`. fn sorted_by(&self) -> (SortKey, bool) { self.sort .filter(|(key, _)| self.in_season || *key != SortKey::Attempts) .unwrap_or(if self.in_season { (SortKey::Attempts, true) } else { (SortKey::Matches, true) }) } fn resort(&mut self) { let (key, descending) = self.sorted_by(); sort_rows(&mut self.rows, key, descending); } /// A header click cycles descending, ascending, then back to the view's default order. fn sort_by(&mut self, key: SortKey) { self.sort = match self.sorted_by() { (sorted, true) if sorted == key => Some((key, false)), (sorted, false) if sorted == key => None, _ => Some((key, true)), }; self.resort(); } /// The Attempts column only exists in a Season, where there is a Challenge. fn columns(&self) -> impl Iterator + use<> { let in_season = self.in_season; SPECS .iter() .filter(move |spec| in_season || spec.key != SortKey::Attempts) } fn header(&self, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); let (head, foreground, border, muted) = ( theme.table_head, theme.table_head_foreground, theme.border, theme.muted_foreground, ); let (sorted, descending) = self.sorted_by(); div() .h_flex() .w_full() .flex_shrink_0() .h(px(ROW_HEIGHT)) .pr(Scrollbar::width()) .border_b_1() .border_color(border) .bg(head) .text_color(foreground) .children(self.columns().map(|spec| { let icon = match spec.key { key if key == sorted && descending => IconName::SortDescending, key if key == sorted => IconName::SortAscending, _ => IconName::ChevronsUpDown, }; cell(spec) .id(spec.title) .gap_1() .cursor_pointer() .on_click(cx.listener(move |table, _, _, cx| { table.sort_by(spec.key); cx.notify(); })) .child(spec.title) .child( Icon::new(icon) .size_3() .when(spec.key != sorted, |icon| icon.text_color(muted)), ) })) } fn row(&self, ix: usize, cx: &mut Context) -> AnyElement { let theme = cx.theme(); let row = &self.rows[ix]; let id = row.champion.id; let selected_bg = if theme.list.active_highlight { theme.tokens.table_active } else { theme.tokens.accent }; div() .id(ix) .h_flex() .w_full() .h(px(ROW_HEIGHT)) .pr(Scrollbar::width()) .border_b_1() .border_color(theme.table_row_border) .when(ix % 2 == 1, |tr| tr.bg(theme.tokens.table_even)) .map(|tr| { if self.selected == Some(id) { tr.bg(selected_bg) } else { tr.hover(|style| style.bg(theme.tokens.table_hover)) } }) .on_click(cx.listener(move |table, _, _, cx| { table.selected = Some(id); cx.notify(); })) .children(self.columns().map(|spec| { let td = cell(spec); if spec.key != SortKey::Champion { return td.child(cell_text(row, spec.key)); } let portrait = match &row.portrait { Some(path) => img(path.clone()).size(px(PORTRAIT)).into_any_element(), None => div().size(px(PORTRAIT)).bg(theme.border).into_any_element(), }; td.gap_2().child(portrait).child(row.champion.name.clone()) })) .into_any_element() } } /// A cell of `spec`'s column, header or body: fixed width, shrinking with the window. // Text past it is clipped: an ellipsis (`text_ellipsis`) cost 0.2 ms per frame (#31). fn cell(spec: &Spec) -> Div { div() .h_flex() .w(px(spec.width)) .min_w_0() .h_full() .px_2() .overflow_hidden() .whitespace_nowrap() .when(spec.numeric, |td| td.justify_end()) } fn or_dash(value: Option) -> String { value.map_or_else(|| "-".into(), |v| v.to_string()) } fn cell_text(row: &ChampionRow, key: SortKey) -> String { match key { SortKey::State => state_label(row.state).into(), SortKey::Champion => row.champion.name.clone(), SortKey::Matches => row.matches.to_string(), SortKey::BestPlacement => or_dash(row.best_placement), SortKey::Top1 => row.top1.to_string(), SortKey::Wins => row.wins.to_string(), SortKey::AveragePlacement => row.average_placement.map_or("-".into(), |a| decimal(a, 1)), SortKey::Attempts => or_dash(row.attempts), SortKey::LastMatch => or_dash(row.last_match_ms.map(Date::from_ms)), } } impl Render for ChampionTable { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); let (background, border, radius, muted) = ( theme.table, theme.border, theme.radius, theme.muted_foreground, ); let body = if self.rows.is_empty() { div() .flex_1() .flex() .items_center() .justify_center() .text_color(muted) .child("Aucun champion à afficher") .into_any_element() } else { uniform_list( "champions", self.rows.len(), cx.processor(|table, range: Range, _, cx| { range.map(|ix| table.row(ix, cx)).collect::>() }), ) .flex_1() .track_scroll(&self.scroll) .into_any_element() }; div() .v_flex() .relative() .size_full() .overflow_hidden() .text_sm() .bg(background) .border_1() .border_color(border) .rounded(radius) .child(self.header(cx)) .child(body) .when(!self.rows.is_empty(), |table| { table.child( div() .absolute() .top(px(ROW_HEIGHT)) .right_0() .bottom_0() .w(Scrollbar::width()) .child(Scrollbar::vertical(&self.scroll)), ) }) } } #[cfg(test)] pub(crate) mod tests { use arena_tracker_core::{Champion, ChampionRow, ChampionState}; // Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`. use super::{ChampionTable, SortKey, cell_text}; pub(crate) fn row(name: &str) -> ChampionRow { ChampionRow { champion: Champion { id: 1, key: name.into(), name: name.into(), }, portrait: None, matches: 0, best_placement: None, top1: 0, wins: 0, average_placement: None, last_match_ms: None, attempts: None, state: None, } } #[test] fn missing_values_show_a_dash() { let row = row("Ahri"); for key in [ SortKey::BestPlacement, SortKey::AveragePlacement, SortKey::Attempts, SortKey::LastMatch, ] { assert_eq!(cell_text(&row, key), "-"); } assert_eq!(cell_text(&row, SortKey::State), ""); } #[test] fn values_are_formatted_in_french() { let row = ChampionRow { matches: 3, best_placement: Some(1), average_placement: Some(2.5), last_match_ms: Some(1_700_000_000_000), attempts: Some(2), state: Some(ChampionState::Completed), ..row("Ahri") }; assert_eq!(cell_text(&row, SortKey::AveragePlacement), "2,5"); assert_eq!(cell_text(&row, SortKey::LastMatch), "14/11/2023"); assert_eq!(cell_text(&row, SortKey::Attempts), "2"); assert_eq!(cell_text(&row, SortKey::State), "Validé"); } #[test] fn the_app_asset_source_serves_the_sort_icons() { use gpui_kit::AssetSource; use gpui_kit::component::{IconName, IconNamed as _}; for icon in [ IconName::SortAscending, IconName::SortDescending, IconName::ChevronsUpDown, ] { let path = icon.path(); let svg = AssetSource::load(&gpui_kit::assets::Assets, &path); assert!(matches!(svg, Ok(Some(_))), "icon manquante : {path}"); } } #[test] fn attempts_column_is_hidden_outside_a_season() { let mut table = ChampionTable::new(); assert!(table.columns().all(|spec| spec.key != SortKey::Attempts)); table.set_rows(vec![], true); assert!(table.columns().any(|spec| spec.key == SortKey::Attempts)); } #[test] fn a_header_cycles_descending_ascending_then_the_default_order() { let mut table = ChampionTable::new(); table.set_rows(vec![], true); assert_eq!(table.sorted_by(), (SortKey::Attempts, true)); table.sort_by(SortKey::Wins); assert_eq!(table.sorted_by(), (SortKey::Wins, true)); table.sort_by(SortKey::Wins); assert_eq!(table.sorted_by(), (SortKey::Wins, false)); table.sort_by(SortKey::Wins); assert_eq!(table.sorted_by(), (SortKey::Attempts, true)); // The default column starts descending, so its first click turns it ascending. table.sort_by(SortKey::Attempts); assert_eq!(table.sorted_by(), (SortKey::Attempts, false)); } }