Show the home's champions as a grid of cards with Played and Win marks (#72)

Add the champion card (portrait, name, "Joué" and "Victoire" marks, greyed with
"Validé" once completed) and a cached, virtualised card grid that replaces the
home's table. Columns follow the window width as in the mockup. Cards are built
once per statistics change; hovering or scrolling only redraws the grid.
Profiling part `home-list` becomes `cards`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 21:21:16 +01:00
1 parent bd4de1ec05
commit bd9f1c7c98
6 files changed
+927 -48

No files matched your search

+325
View File
@@ -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<PathBuf>,
pub marks: Marks,
/// In display order. A card with any reason is greyed.
pub reasons: Vec<Reason>,
}
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<ChampionChallenge>) -> 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());
}
}
+237
View File
@@ -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<usize>,
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<Self>) {
#[cfg(test)]
{
self.set_cards_calls += 1;
}
if *self.cards != *cards {
self.cards = cards;
cx.notify();
}
}
pub fn set_shown(&mut self, shown: Vec<usize>, cx: &mut Context<Self>) {
if self.shown != shown {
self.shown = shown;
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<SharedString> {
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<Self>) -> 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::<Vec<_>>()).into_any_element()
}
}
impl Render for CardGrid {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> 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<usize>, _, cx| {
range
.map(|ix| grid.row(ix, metrics, cx))
.collect::<Vec<_>>()
}),
)
.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}"
);
}
}
}
+2
View File
@@ -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")]
+294 -22
View File
@@ -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<SharedString>,
charts: Entity<ChartsRow>,
table: Entity<ChampionTable>,
/// Temporary: the cards replace it (#72).
home_table: Entity<ChampionTable>,
/// The home's champions, one card each.
home_grid: Entity<CardGrid>,
/// How many cards the grid shows, prepared when the filter or search change.
home_shown_count: SharedString,
_subscriptions: Vec<Subscription>,
_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<Self>) {
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<Self>) {
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<usize> = 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<Page>, 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<CardGrid>, cx: &mut VisualTestContext) -> Vec<String> {
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<ChampionRow> {
(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<gpui_kit::Pixels> {
cx.debug_bounds(id).unwrap().center()
}
+67 -24
View File
@@ -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<Page>) -> Vec<AnyElement> {
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<Page>) -> 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.