diff --git a/crates/app/src/card.rs b/crates/app/src/card.rs new file mode 100644 index 0000000..646c505 --- /dev/null +++ b/crates/app/src/card.rs @@ -0,0 +1,325 @@ +//! The champion card: the one representation of a champion, on the home today and in the Arena +//! champ select later. A `Card` is built once when the statistics change; `card` only lays it out. + +use std::path::PathBuf; + +use arena_tracker_core::{ChampionRow, Marks}; +use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +/// Width over height. +pub const ASPECT: f32 = 0.68; +const RADIUS: f32 = 10.; +/// The border is inside the radius: the layers it holds are rounded one pixel less. +const INNER_RADIUS: f32 = RADIUS - 1.; + +// The caption and badges sit on the dark shade, in both themes: their colours are fixed. +const ACCENT: u32 = 0xc4b3fc; +const INK: u32 = 0x201732; +const MARK_ON: u32 = 0xdfd4ff; +const MARK_OFF: u32 = 0xcdccd4; +const MARK_OFF_RING: u32 = 0xacaab7; +const BADGE_BG: u32 = 0x202027ee; +const BADGE_TEXT: u32 = 0xf0eff3; + +/// Why a card is greyed out. Later tickets add the champ select's reasons (banned, taken by an +/// ally, not offered). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + /// At least one top 1 in the Season. + Completed, +} + +impl Reason { + pub fn label(self) -> &'static str { + match self { + Reason::Completed => "Validé", + } + } + + fn icon(self) -> IconName { + match self { + Reason::Completed => IconName::Check, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Card { + pub id: u32, + pub name: SharedString, + /// The square icon today; the tall art later. + pub portrait: Option, + pub marks: Marks, + /// In display order. A card with any reason is greyed. + pub reasons: Vec, +} + +impl Card { + /// A row without a Challenge (no Season) has no Marks. + pub fn from_row(row: &ChampionRow) -> Card { + let marks = row.challenge.map_or( + Marks { + played: false, + won: false, + completed: false, + }, + |challenge| challenge.marks(), + ); + Card { + id: row.champion.id, + name: row.champion.name.clone().into(), + portrait: row.portrait.clone(), + marks, + reasons: if marks.completed { + vec![Reason::Completed] + } else { + Vec::new() + }, + } + } + + pub fn greyed(&self) -> bool { + !self.reasons.is_empty() + } +} + +/// One card, as wide as its parent gives it, `ASPECT` wide over tall. Hovering only changes the +/// border colour. +pub fn card(card: &Card, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let (border, ring, background) = (theme.border, theme.ring, theme.muted); + let greyed = card.greyed(); + let id = card.id; + div() + .id(("card", id)) + .relative() + .flex_1() + .min_w_0() + .aspect_ratio(ASPECT) + .overflow_hidden() + .rounded(px(RADIUS)) + .border_1() + .border_color(border) + .bg(background) + .hover(move |style| style.border_color(ring)) + .debug_selector(|| format!("card-{id}")) + .children(card.portrait.as_ref().map(|path| { + img(path.clone()) + .absolute() + .inset_0() + .size_full() + .rounded(px(INNER_RADIUS)) + .object_fit(ObjectFit::Cover) + .grayscale(greyed) + })) + // Stands for the mockup's `brightness(.72)`, which the image element cannot do. + .when(greyed, |el| { + el.child( + div() + .absolute() + .inset_0() + .rounded(px(INNER_RADIUS)) + .bg(hsla(0., 0., 0., 0.28)), + ) + }) + .child(shade()) + .when(greyed, |el| el.child(reasons(&card.reasons))) + .child(caption(card)) +} + +/// Keeps the caption readable on any portrait. +fn shade() -> Div { + let clear = hsla(240. / 360., 0.3, 0.06, 0.); + let dark = hsla(240. / 360., 0.3, 0.06, 0.95); + div() + .absolute() + .inset_0() + .rounded(px(INNER_RADIUS)) + .bg(linear_gradient( + 180., + linear_color_stop(clear, 0.5), + linear_color_stop(dark, 0.92), + )) +} + +fn reasons(reasons: &[Reason]) -> Div { + div() + .absolute() + .top(px(9.)) + .left(px(8.)) + .right(px(8.)) + .h_flex() + .items_start() + .flex_wrap() + .gap(px(3.)) + .children(reasons.iter().map(|reason| { + div() + .h_flex() + .items_center() + .gap(px(4.)) + .px(px(6.)) + .py(px(3.)) + .rounded(px(4.)) + .bg(rgba(BADGE_BG)) + .text_color(rgb(BADGE_TEXT)) + .text_size(px(10.)) + .font_weight(FontWeight::SEMIBOLD) + .child(Icon::new(reason.icon()).size(px(12.))) + .child(reason.label()) + })) +} + +fn caption(card: &Card) -> Div { + div() + .absolute() + .left(px(12.)) + .right(px(8.)) + .bottom(px(12.)) + .v_flex() + .child( + div() + .text_size(px(18.)) + .font_weight(FontWeight::SEMIBOLD) + .line_height(relative(1.18)) + .text_color(white()) + .child(card.name.clone()), + ) + .child( + div() + .h_flex() + .items_center() + .flex_wrap() + .mt(px(7.)) + .gap_x(px(10.)) + .gap_y(px(4.)) + .child(mark("Joué", card.marks.played)) + .child(mark("Victoire", card.marks.won)), + ) +} + +/// A dot, filled with a check when on, and its label. +fn mark(label: &'static str, on: bool) -> Div { + div() + .h_flex() + .items_center() + .gap(px(4.)) + .text_size(px(10.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(rgb(if on { MARK_ON } else { MARK_OFF })) + .child( + div() + .flex() + .items_center() + .justify_center() + .size(px(11.)) + .rounded_full() + .border_1() + .border_color(rgb(if on { ACCENT } else { MARK_OFF_RING })) + .when(on, |dot| { + dot.bg(rgb(ACCENT)) + .text_color(rgb(INK)) + .child(Icon::new(IconName::Check).size(px(8.))) + }), + ) + .child(label) +} + +#[cfg(test)] +mod tests { + use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, Date}; + + // Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`. + use super::{Card, Reason}; + + fn row(challenge: Option) -> ChampionRow { + ChampionRow { + champion: Champion { + id: 4, + key: "TwistedFate".into(), + name: "Twisted Fate".into(), + }, + portrait: None, + card_portrait: None, + matches: 0, + best_placement: None, + top1: 0, + wins: 0, + average_placement: None, + last_match_ms: None, + attempts: None, + state: None, + challenge, + } + } + + fn day() -> Date { + Date { + year: 2026, + month: 3, + day: 2, + } + } + + fn marks(card: &Card) -> (bool, bool) { + (card.marks.played, card.marks.won) + } + + #[test] + fn a_champion_never_played_has_no_mark_and_keeps_its_colours() { + let card = Card::from_row(&row(Some(ChampionChallenge::default()))); + assert_eq!(marks(&card), (false, false)); + assert!(card.reasons.is_empty()); + assert!(!card.greyed()); + } + + #[test] + fn a_champion_played_without_a_win_has_only_the_played_mark() { + let challenge = ChampionChallenge { + matches: 3, + best_placement: Some(4), + ..Default::default() + }; + let card = Card::from_row(&row(Some(challenge))); + assert_eq!(marks(&card), (true, false)); + assert!(!card.greyed()); + } + + #[test] + fn a_champion_with_a_win_but_no_top_1_is_in_colour_with_both_marks() { + let challenge = ChampionChallenge { + matches: 2, + wins: 1, + best_placement: Some(2), + completed_on: None, + }; + let card = Card::from_row(&row(Some(challenge))); + assert_eq!(marks(&card), (true, true)); + assert!(!card.marks.completed); + assert!(!card.greyed()); + } + + #[test] + fn a_completed_champion_is_greyed_with_the_validated_reason() { + let challenge = ChampionChallenge { + matches: 4, + wins: 2, + best_placement: Some(1), + completed_on: Some(day()), + }; + let card = Card::from_row(&row(Some(challenge))); + assert_eq!(marks(&card), (true, true)); + assert_eq!(card.reasons, [Reason::Completed]); + assert_eq!(card.reasons[0].label(), "Validé"); + assert!(card.greyed()); + assert_eq!(card.name.as_ref(), "Twisted Fate"); + } + + #[test] + fn a_row_without_a_challenge_has_no_marks() { + let card = Card::from_row(&row(None)); + assert_eq!(marks(&card), (false, false)); + assert!(!card.greyed()); + } +} diff --git a/crates/app/src/card_grid.rs b/crates/app/src/card_grid.rs new file mode 100644 index 0000000..bd89c14 --- /dev/null +++ b/crates/app/src/card_grid.rs @@ -0,0 +1,237 @@ +//! The card grid: all the cards a list shows, in rows of the same count, only the visible rows +//! built. It is its own view because it owns the scrolling and the hover of its cards. + +use std::ops::Range; +use std::rc::Rc; + +use gpui_kit::component::scroll::Scrollbar; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::*; + +use crate::card::{ASPECT, Card, card}; +use crate::page::PAGE_PADDING; + +/// The widest content column of the home, as in the mockup. +pub const MAX_WIDTH: f32 = 1264.; + +/// How many cards fit a row of a window `width` wide, with the mockup's breakpoints. +fn columns(width: Pixels) -> usize { + match width.as_f32() { + w if w >= 1000. => 6, + w if w >= 720. => 4, + w if w >= 480. => 3, + _ => 2, + } +} + +/// Smaller gaps in the narrow layouts, as in the mockup. +fn gap(columns: usize) -> f32 { + if columns >= 4 { 14. } else { 10. } +} + +/// What a frame needs to know, from the window width alone: `uniform_list` measures its first +/// row without knowing the list's width, so the row height cannot come from the layout. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Metrics { + columns: usize, + gap: f32, + /// A card's height; a row is this plus a gap tall. + card_height: f32, +} + +impl Metrics { + fn of(window_width: Pixels) -> Metrics { + let columns = columns(window_width); + let gap = gap(columns); + // The column the page centres, minus the scrollbar's lane. + let content = (window_width.as_f32() - 2. * PAGE_PADDING).min(MAX_WIDTH) + - Scrollbar::width().as_f32(); + let card_width = (content - gap * (columns - 1) as f32) / columns as f32; + Metrics { + columns, + gap, + card_height: (card_width / ASPECT).max(0.), + } + } +} + +pub struct CardGrid { + /// All the cards, A to Z; rebuilt only when the statistics change. + cards: Rc<[Card]>, + /// Indices into `cards`, after the filter and the search. + shown: Vec, + scroll: UniformListScrollHandle, + /// Guard the light rendering in tests. + #[cfg(test)] + pub(crate) renders: usize, + #[cfg(test)] + pub(crate) card_builds: usize, + #[cfg(test)] + pub(crate) set_cards_calls: usize, +} + +impl CardGrid { + pub fn new() -> CardGrid { + CardGrid { + cards: Rc::new([]), + shown: Vec::new(), + scroll: UniformListScrollHandle::new(), + #[cfg(test)] + renders: 0, + #[cfg(test)] + card_builds: 0, + #[cfg(test)] + set_cards_calls: 0, + } + } + + /// Replaces the cards; the grid is drawn again only when they differ (reloads keep coming + /// during an import). `set_shown` follows, as the indices belong to the cards. + pub fn set_cards(&mut self, cards: Rc<[Card]>, cx: &mut Context) { + #[cfg(test)] + { + self.set_cards_calls += 1; + } + if *self.cards != *cards { + self.cards = cards; + cx.notify(); + } + } + + pub fn set_shown(&mut self, shown: Vec, cx: &mut Context) { + if self.shown != shown { + self.shown = shown; + cx.notify(); + } + } + + #[cfg(test)] + pub(crate) fn names(&self) -> Vec { + self.shown + .iter() + .filter_map(|&ix| self.cards.get(ix)) + .map(|card| card.name.clone()) + .collect() + } + + /// How far the grid is scrolled down. + #[cfg(test)] + pub(crate) fn scrolled(&self) -> Pixels { + -self.scroll.0.borrow().base_handle.offset().y + } + + fn row(&mut self, ix: usize, metrics: Metrics, cx: &mut Context) -> AnyElement { + let start = ix * metrics.columns; + let row = div() + .h_flex() + .items_start() + .w_full() + .h(px(metrics.card_height + metrics.gap)) + .pb(px(metrics.gap)) + .pr(Scrollbar::width()) + .gap(px(metrics.gap)); + let slots = (start..start + metrics.columns).map(|slot| { + // A stale index shows nothing rather than panicking. + match self.shown.get(slot).and_then(|&c| self.cards.get(c)) { + Some(data) => { + #[cfg(test)] + { + self.card_builds += 1; + } + card(data, cx).into_any_element() + } + // The last row keeps every card the same width. + None => div().flex_1().min_w_0().into_any_element(), + } + }); + row.children(slots.collect::>()).into_any_element() + } +} + +impl Render for CardGrid { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + #[cfg(test)] + { + self.renders += 1; + } + if self.shown.is_empty() { + let muted = cx.theme().muted_foreground; + return div() + .w_full() + .debug_selector(|| "no-champion".into()) + .py(px(30.)) + .text_color(muted) + .child("Aucun champion trouvé") + .into_any_element(); + } + let metrics = Metrics::of(window.viewport_size().width); + let rows = self.shown.len().div_ceil(metrics.columns); + div() + .relative() + .size_full() + .child( + uniform_list( + "cards", + rows, + cx.processor(move |grid, range: Range, _, cx| { + range + .map(|ix| grid.row(ix, metrics, cx)) + .collect::>() + }), + ) + .size_full() + .track_scroll(&self.scroll), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(Scrollbar::width()) + .child(Scrollbar::vertical(&self.scroll)), + ) + .into_any_element() + } +} + +#[cfg(test)] +mod tests { + use gpui_kit::px; + + // Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`. + use super::{Metrics, columns}; + + #[test] + fn the_columns_follow_the_mockups_breakpoints() { + for (width, expected) in [ + (2560., 6), + (1280., 6), + (1000., 6), + (999., 4), + (720., 4), + (719., 3), + (480., 3), + (479., 2), + (300., 2), + ] { + assert_eq!(columns(px(width)), expected, "{width} px"); + } + } + + #[test] + fn the_cards_fill_the_column_the_page_centres() { + use gpui_kit::component::scroll::Scrollbar; + for (window, column) in [(1280., 1256.), (3000., 1264.), (800., 776.), (500., 476.)] { + let metrics = Metrics::of(px(window)); + let card_width = metrics.card_height * super::ASPECT; + let row = card_width * metrics.columns as f32 + + metrics.gap * (metrics.columns - 1) as f32 + + Scrollbar::width().as_f32(); + assert!( + (row - column).abs() < 0.01, + "{window} px: {row} vs {column}" + ); + } + } +} diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index abd4983..1ea570e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,5 +1,7 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +mod card; +mod card_grid; mod champion_table; mod page; #[cfg(feature = "profile")] diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index c67c9d4..91535a2 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -1,6 +1,7 @@ //! The page and its two tabs: the shared state, the header row with its navigation, the banners and //! the champ select view. `home` and `statistics` render what is under the banners. +use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -22,6 +23,8 @@ use gpui_kit::*; mod home; mod statistics; +use crate::card::Card; +use crate::card_grid::CardGrid; use crate::champion_table::ChampionTable; use crate::text::{CLIENT_ABSENT, official_differs, sync_line}; use crate::worker::{ @@ -29,6 +32,8 @@ use crate::worker::{ }; use statistics::ChartsRow; +/// 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"; const ALL_FORMATS: &str = "Tous les Formats"; /// While an import runs, the page is recomputed at most this often. @@ -168,8 +173,10 @@ pub struct Page { format_names: Vec, charts: Entity, table: Entity, - /// Temporary: the cards replace it (#72). - home_table: Entity, + /// The home's champions, one card each. + home_grid: Entity, + /// How many cards the grid shows, prepared when the filter or search change. + home_shown_count: SharedString, _subscriptions: Vec, _listener: Task<()>, } @@ -211,7 +218,7 @@ impl Page { let charts = cx.new(|_| ChartsRow::new()); let home_search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher")); let table = cx.new(|_| ChampionTable::new()); - let home_table = cx.new(|_| ChampionTable::new()); + let home_grid = cx.new(|_| CardGrid::new()); let subscriptions = vec![ cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| { @@ -333,7 +340,8 @@ impl Page { format_names, charts, table, - home_table, + home_grid, + home_shown_count: SharedString::default(), _subscriptions: subscriptions, _listener: listener, }; @@ -747,6 +755,7 @@ impl Page { return; } self.prepare_home_labels(); + self.prepare_home_cards(cx); let charts = self.stats.as_ref().map(|s| &s.charts); let in_season = self.in_season(); self.charts @@ -778,6 +787,16 @@ 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) { + let cards: Rc<[Card]> = self + .home_statistics() + .map(|s| s.rows.iter().map(Card::from_row).collect()) + .unwrap_or_default(); + self.home_grid + .update(cx, |grid, cx| grid.set_cards(cards, cx)); + } + fn in_champ_select(&self) -> bool { self.champ_select.is_some() } @@ -865,21 +884,24 @@ impl Page { }); } - /// Rebuilds the home's rows from its own filter and search, with the total untouched; while - /// the home is not shown, the next switch does. + /// Recomputes which cards the home shows from its own filter and search, with the total + /// untouched; while the home is not shown, the next switch does. fn refresh_home(&mut self, cx: &mut Context) { 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 rows = rows - .filter(|row| self.home_filter.keeps(row) && self.home_search.matches(&row.champion)) - .cloned() + let shown: Vec = rows + .enumerate() + .filter(|(_, row)| { + self.home_filter.keeps(row) && self.home_search.matches(&row.champion) + }) + .map(|(ix, _)| ix) .collect(); - self.home_table.update(cx, |table, cx| { - table.set_rows(rows, true); - cx.notify(); - }); + self.home_shown_count = shown.len().to_string().into(); + self.home_grid + .update(cx, |grid, cx| grid.set_shown(shown, cx)); } fn champ_select_view(&self, cx: &App) -> Div { @@ -1044,7 +1066,7 @@ impl Render for Page { .v_flex() .size_full() .gap_3() - .p_3() + .p(px(PAGE_PADDING)) .when(shown("header"), |page| { page.child( // The selectors give way first (down to their minimum width), then the status @@ -1111,17 +1133,20 @@ mod tests { use std::sync::Arc; use arena_tracker_core::{ - Account, ChallengeSummary, Champion, ChampionRow, ChampionState, Charts, Date, Format, - MatchHistorySource, RiotApi, Season, SeasonScope, SourceError, StateFilter, Statistics, - Tracker, + Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionState, Charts, + Date, Format, MatchHistorySource, RiotApi, Season, SeasonScope, SourceError, StateFilter, + Statistics, Tracker, }; use gpui_kit::base::async_util::unbounded; use gpui_kit::{ AppContext as _, Bounds, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, - TestAppContext, VisualTestContext, WindowBounds, WindowOptions, point, px, size, + ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, WindowBounds, WindowOptions, + point, px, size, }; use super::{Page, Tab}; + use crate::card::ASPECT; + use crate::card_grid::CardGrid; use crate::champion_table::tests::row; fn open_page(cx: &mut TestAppContext) -> (Entity, VisualTestContext) { @@ -1532,7 +1557,7 @@ mod tests { assert_eq!(page.home_season, None); assert!(page.home_statistics().is_none()); assert!(page.home_count.is_empty()); - assert!(page.home_table.read(cx).names().is_empty()); + assert!(page.home_grid.read(cx).names().is_empty()); }); } @@ -1561,11 +1586,11 @@ mod tests { ), ); cx.update(|window, cx| window.draw(cx).clear(cx)); - let (input, table) = page.read_with(cx, |p, _| { - (p.home_search_input.clone(), p.home_table.clone()) + let (input, grid) = page.read_with(cx, |p, _| { + (p.home_search_input.clone(), p.home_grid.clone()) }); let names = |cx: &mut VisualTestContext| { - let mut names = table.read_with(cx, |table, _| table.names()); + let mut names = grid_names(&grid, cx); names.sort(); names }; @@ -1681,6 +1706,253 @@ mod tests { assert!(charts.read_with(cx, |charts, _| charts.renders) > 0); } + fn grid_names(grid: &Entity, cx: &mut VisualTestContext) -> Vec { + grid.read_with(cx, |grid, _| { + grid.names().iter().map(|name| name.to_string()).collect() + }) + } + + fn draw(cx: &mut VisualTestContext) { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + /// Never played champions with distinct ids, in A to Z order. + fn champions(count: u32) -> Vec { + (1..=count) + .map(|id| ChampionRow { + champion: Champion { + id, + key: format!("Champion{id}"), + name: format!("Champion {id:03}"), + }, + state: Some(ChampionState::NeverPlayed), + challenge: Some(ChampionChallenge::default()), + ..row("") + }) + .collect() + } + + #[gpui::test] + fn the_grid_follows_the_alias_search_and_the_filters(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + let champion = |id, key: &str, name: &str, state, matches, completed: bool| ChampionRow { + champion: Champion { + id, + key: key.into(), + name: name.into(), + }, + state: Some(state), + matches, + challenge: Some(ChampionChallenge { + matches, + completed_on: completed.then_some(Date { + year: 2026, + month: 3, + day: 2, + }), + ..Default::default() + }), + ..row(name) + }; + // As the statistics give them: A to Z, the accented name where French collation puts it. + show( + &page, + cx, + statistics( + 1, + 4, + vec![ + champion(86, "Garen", "Garen", ChampionState::NeverPlayed, 0, false), + champion(107, "Rengar", "Rengar", ChampionState::InProgress, 5, false), + champion( + 4, + "TwistedFate", + "Twisted Fate", + ChampionState::Completed, + 3, + true, + ), + champion(238, "Zed", "Éd", ChampionState::NeverPlayed, 0, false), + ], + ), + ); + draw(cx); + let (input, grid) = page.read_with(cx, |p, _| { + (p.home_search_input.clone(), p.home_grid.clone()) + }); + let shown_count = + |cx: &mut VisualTestContext| page.read_with(cx, |p, _| p.home_shown_count.to_string()); + // « Tous »: everything, never played and completed ones included, in the given order. + assert_eq!( + grid_names(&grid, cx), + ["Garen", "Rengar", "Twisted Fate", "Éd"] + ); + assert_eq!(shown_count(cx), "4"); + draw(cx); + assert!(cx.debug_bounds("no-champion").is_none()); + + cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx))); + cx.simulate_input("TF"); + assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]); + assert_eq!(shown_count(cx), "1"); + + cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx))); + assert_eq!(grid_names(&grid, cx).len(), 4); + cx.simulate_input("ren"); + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Remaining; + p.refresh_home(cx); + }); + assert_eq!(grid_names(&grid, cx), ["Garen", "Rengar"]); + + // Nothing completed matches: the grid says so. + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Completed; + p.refresh_home(cx); + }); + assert!(grid_names(&grid, cx).is_empty()); + assert_eq!(shown_count(cx), "0"); + draw(cx); + assert!(cx.debug_bounds("no-champion").is_some()); + assert!(cx.debug_bounds("card-4").is_none()); + + // « Validés » alone brings the completed card back. + cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx))); + assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]); + draw(cx); + assert!(cx.debug_bounds("card-4").is_some()); + assert!(cx.debug_bounds("no-champion").is_none()); + } + + #[gpui::test] + fn a_card_is_as_wide_as_the_mockups_and_a_card_without_a_portrait_renders( + cx: &mut TestAppContext, + ) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(0, 30, champions(30))); + draw(cx); + let first = cx + .debug_bounds("card-1") + .expect("the first card is not drawn"); + let second = cx.debug_bounds("card-2").unwrap(); + let next_row = cx.debug_bounds("card-7").unwrap(); + // 6 columns at 1280 px, as tall as the aspect says. + assert_eq!(first.origin.y, second.origin.y); + assert!(next_row.origin.x == first.origin.x); + let (width, height) = (first.size.width.as_f32(), first.size.height.as_f32()); + assert!((height - width / ASPECT).abs() < 1., "{width} x {height}"); + // The first-row measure sizes every row: the next one starts a card and a gap lower. + let step = (next_row.origin.y - first.origin.y).as_f32(); + assert!( + (step - (height + 14.)).abs() < 1., + "step {step}, card {height}" + ); + assert!( + ((second.origin.x - first.origin.x).as_f32() - width - 14.).abs() < 1., + "gap between columns" + ); + // None of these cards has a portrait. + page.read_with(cx, |page, cx| { + assert!( + page.home_grid + .read(cx) + .names() + .contains(&"Champion 001".into()) + ); + }); + } + + #[gpui::test] + fn only_the_visible_cards_are_built(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(0, 170, champions(170))); + draw(cx); + let grid = page.read_with(cx, |page, _| page.home_grid.clone()); + let built = grid.read_with(cx, |grid, _| grid.card_builds); + // A few rows of 6 under 860 px, the first measured again: far from the 170 cards. + assert!(built > 0); + assert!(built <= 8 * 6, "{built} cards built for 170"); + } + + // Hovering outside the grid draws the page again, not the cards: the grid is a cached view + // (rule #1), like the charts row. + #[gpui::test] + fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(0, 170, champions(170))); + draw(cx); + let grid = page.read_with(cx, |page, _| page.home_grid.clone()); + let renders = grid.read_with(cx, |grid, _| grid.renders); + assert!(renders > 0); + + // A navigation button's hover style redraws the window. + for _ in 0..2 { + let button = center(cx, "tab-statistics"); + cx.simulate_mouse_move(button, None, Modifiers::none()); + draw(cx); + cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none()); + draw(cx); + } + assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders); + + // The count does move when the grid changes. + grid.update(cx, |_, cx| cx.notify()); + draw(cx); + assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders + 1); + } + + // Hovering a card or scrolling the grid draws the grid, and nothing upstream: the cards are + // not built again and no statistics are computed. + #[gpui::test] + fn scrolling_or_hovering_the_grid_does_not_recompute_the_statistics(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show(&page, cx, statistics(0, 170, champions(170))); + draw(cx); + let grid = page.read_with(cx, |page, _| page.home_grid.clone()); + let generation = page.read_with(cx, |page, _| page.stats_generation); + let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls); + let renders = grid.read_with(cx, |grid, _| grid.renders); + assert!(set_cards > 0); + + let hovers = Rc::new(Cell::new(0)); + let _subscription = cx.update(|_, cx| { + let hovers = hovers.clone(); + cx.observe(&grid, move |_, _| hovers.set(hovers.get() + 1)) + }); + for id in ["card-1", "card-2"] { + let card = center(cx, id); + cx.simulate_mouse_move(card, None, Modifiers::none()); + draw(cx); + } + assert!(hovers.get() > 0, "no card was hovered"); + assert!(grid.read_with(cx, |grid, _| grid.renders) > renders); + + let over = center(cx, "card-1"); + cx.simulate_event(ScrollEvent { + position: over, + delta: ScrollDelta::Pixels(point(px(0.), px(-400.))), + ..Default::default() + }); + draw(cx); + assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.)); + + assert_eq!( + grid.read_with(cx, |grid, _| grid.set_cards_calls), + set_cards, + "the cards were built again" + ); + assert_eq!( + page.read_with(cx, |page, _| page.stats_generation), + generation + ); + assert!(!page.read_with(cx, |page, _| page.stats_job.running())); + } + fn center(cx: &mut VisualTestContext, id: &'static str) -> gpui_kit::Point { cx.debug_bounds(id).unwrap().center() } diff --git a/crates/app/src/page/home.rs b/crates/app/src/page/home.rs index 6bbec1f..f7c67e8 100644 --- a/crates/app/src/page/home.rs +++ b/crates/app/src/page/home.rs @@ -7,6 +7,7 @@ use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; use gpui_kit::*; use super::{Page, shown}; +use crate::card_grid::MAX_WIDTH; /// The filters on offer, whatever the Season. pub(super) const FILTERS: [(&str, StateFilter); 3] = [ @@ -16,23 +17,77 @@ pub(super) const FILTERS: [(&str, StateFilter); 3] = [ ]; impl Page { - /// Under the banners: the Season and its counter, then the filters, search and champions. - /// It holds no chart (#71): the cached charts row only belongs to the Statistics tab. + /// Under the banners: the Season and its counter, then the heading with the filters and + /// search, and the cards. It holds no chart (#71): the cached charts row only belongs to the + /// Statistics tab. Everything is one centred column, as wide as the mockup's. pub(super) fn home_content(&self, cx: &mut Context) -> Vec { - let mut content = Vec::new(); + let mut column = div() + .v_flex() + .flex_1() + .min_h_0() + .w_full() + .max_w(px(MAX_WIDTH)) + .mx_auto() + .gap_3(); if shown("home-header") { - content.push(self.home_header(cx).into_any_element()); + column = column.child(self.home_header(cx)); } - if self.home_season.is_none() { - return content; + if self.home_season.is_some() { + if shown("home-tools") { + column = column.child(self.home_heading(cx)); + } + if shown("cards") { + // Cached: only a change to the cards, the filter, the search or a hover or + // scroll over them draws the grid again. Its size comes from this style. + column = column.child( + self.home_grid + .clone() + .cached(StyleRefinement::default().w_full().flex_1().min_h(px(240.))), + ); + } } - if shown("home-tools") { - let selected = FILTERS.iter().position(|(_, f)| *f == self.home_filter); - content.push( + vec![column.into_any_element()] + } + + /// « Mes champions » with how many cards are shown, and on the right the filters and search. + fn home_heading(&self, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let (muted, border) = (theme.muted_foreground, theme.border); + let selected = FILTERS.iter().position(|(_, f)| *f == self.home_filter); + div() + .h_flex() + .flex_wrap() + .items_center() + .justify_between() + .gap_x_3() + .gap_y_2() + .child( + div() + .h_flex() + .items_center() + .gap(px(6.)) + .child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child("Mes champions"), + ) + .child( + div() + .px(px(7.)) + .py(px(2.)) + .border_1() + .border_color(border) + .rounded(px(6.)) + .text_xs() + .text_color(muted) + .child(self.home_shown_count.clone()), + ), + ) + .child( div() .h_flex() .items_center() - .justify_between() .gap_3() .child( TabBar::new("home-filter") @@ -52,20 +107,8 @@ impl Page { .cleanable(true) .w(px(260.)) .min_w(px(150.)), - ) - .into_any_element(), - ); - } - if shown("home-list") { - content.push( - div() - .flex_1() - .min_h(px(240.)) - .child(self.home_table.clone()) - .into_any_element(), - ); - } - content + ), + ) } /// The Season, the title and, beside it, the champions Completed out of the Challenge's total. diff --git a/docs/performance.md b/docs/performance.md index d7eab3b..c929524 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -35,8 +35,8 @@ Budgets are checked by a **full benchmark before each major release** (X.0.0; ot - **Window moves and idle CPU**: `powershell.exe -ExecutionPolicy Bypass -File scripts/move-probe.ps1 -Title "Arena Tracker"` from WSL, with the app open. It moves the window 240 times per second without touching the mouse, after an idle phase. `MOVE block` is the time each move holds the UI thread, close to the cost of the frame it causes; `IDLE cpu` is budget 2. Compare with File Explorer with `-Class CabinetWClass`. A real title-bar drag (Windows' modal move loop) is not covered: check it by hand. - **Champion table hover**: `powershell.exe -ExecutionPolicy Bypass -File scripts/hover-probe.ps1 -Title "Arena Tracker"` from WSL, with the « Statistiques » tab showing the table under the default band (adjust `-Top` and `-Bottom` otherwise). The app opens on « Défi »: open « Statistiques » first, as the band targets its table. After an idle phase, it posts synthetic mouse moves across table rows 240 times per second without touching the real cursor. Compare `HOVER cpu` with `IDLE cpu`; `HOVER ping` shows how long input waits behind the UI thread while hovering (budget 1). The default band is `-X 0.25 -Top 0.62 -Bottom 0.95 -Step 0.04` (fractions of the client area, about one row per move in a window at least 800 px tall). Leave the real cursor still over the window, outside the table: when it is outside the window, GPUI sees each synthetic move as the mouse entering then leaving, and refreshes the whole window, bypassing cached views. -- **Where a frame goes**: build with `scripts/prod build --features profile` (never for everyday use) and start the app with `ARENA_TRACKER_PROFILE=` (from WSL, pass it through `WSLENV`, e.g. `WSLENV=ARENA_TRACKER_PROFILE/p:ARENA_TRACKER_HIDE`). Every second it appends the frames GPUI drew (`draw`: total, `request_layout`, `prepaint`, `paint` in ms), their presentation (`present`) and the views' own time (`view`, recorded by GPUI from 0.5 ms). `ARENA_TRACKER_HIDE=`, read at start, removes parts of the page so that a part's cost is the difference with the full page under the hover probe: `header`, `banners` (both tabs), then for « Statistiques » `tiles`, `placements`, `completed`, `attempts` (the three charts keep their height), `tabs`, `table`, and for « Défi » `home-header` (Season, title and counter), `home-tools` (filters and search), `home-list` (its champion table). +- **Where a frame goes**: build with `scripts/prod build --features profile` (never for everyday use) and start the app with `ARENA_TRACKER_PROFILE=` (from WSL, pass it through `WSLENV`, e.g. `WSLENV=ARENA_TRACKER_PROFILE/p:ARENA_TRACKER_HIDE`). Every second it appends the frames GPUI drew (`draw`: total, `request_layout`, `prepaint`, `paint` in ms), their presentation (`present`) and the views' own time (`view`, recorded by GPUI from 0.5 ms). `ARENA_TRACKER_HIDE=`, read at start, removes parts of the page so that a part's cost is the difference with the full page under the hover probe: `header`, `banners` (both tabs), then for « Statistiques » `tiles`, `placements`, `completed`, `attempts` (the three charts keep their height), `tabs`, `table`, and for « Défi » `home-header` (Season, title and counter), `home-tools` (the heading row: title, count, filters and search), `cards` (the card grid). - **Memory**: working set of `arena-tracker.exe` in Task Manager, or `Get-Process arena-tracker` in PowerShell, once the page is fully loaded. -- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is the page's one cached view (#31), and « Défi » never renders it (a structural test guards that too). A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache. +- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is a cached view (#31), and « Défi » never renders it (a structural test guards that too). The home's card grid is the other (#72): its size comes from its style, and structural tests check that hovering outside it does not render its cards and that hovering or scrolling it recomputes no statistics. A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache. GPUI and gpui-component are not modified to meet a budget: the app's own rendering cost is the lever (ADR-0004).