Files
arena-tracker/crates/app/src/card.rs
T
nessarandClaude Opus 5.5 a457a19fe5 Sort the cards by Mastery Points or A to Z and remember the choice (#76)
The statistics rows carry the Mastery Points: None for an Account whose
points were never fetched, Some(0) for a champion missing from the last
list. One card order, computed only when the statistics or the preference
change, feeds the home grid, the Anvil row and « Autres champions ». The
sort selector stays visible during a champ select, the choice is saved
with the other preferences, and the sheet shows the Mastery Points
(unknown ones after the known, and not as zero).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00

643 lines
20 KiB
Rust

//! 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, Unavailability};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::text::{ordinal, thousands};
/// 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;
// The sheet is dark in both themes, like the shade it replaces.
const SHEET_BG: u32 = 0x16161ef5;
const SHEET_LABEL: u32 = 0xb4b4c3;
// The sheet's lines, in order. Mastery Points will join them (one more line).
const PLAYED: &str = "Parties";
const WINS: &str = "Victoires";
const BEST_PLACEMENT: &str = "Meilleur Placement";
const ATTEMPTS: &str = "Tentatives";
const MASTERY: &str = "Points de maîtrise";
const UNKNOWN: &str = "Inconnus";
/// Only on a Completed champion.
pub const FIRST_TOP_1: &str = "Premier top 1";
const NONE: &str = "—";
/// Why a card is greyed out, in the order the badges are shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
/// At least one top 1 in the Season.
Completed,
/// Banned in the champ select.
Banned,
/// Confirmed by an ally in the champ select.
TakenByAlly,
/// The champ select does not offer the champion.
NotOffered,
}
impl Reason {
pub fn label(self) -> &'static str {
match self {
Reason::Completed => "Validé",
Reason::Banned => "Banni",
Reason::TakenByAlly => "Pris par un allié",
Reason::NotOffered => "Indisponible",
}
}
fn icon(self) -> IconName {
match self {
Reason::Completed => IconName::Check,
Reason::Banned => IconName::Ban,
Reason::TakenByAlly => IconName::User,
Reason::NotOffered => IconName::EyeOff,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Card {
pub id: u32,
pub name: SharedString,
/// The tall portrait, else the square icon while the tall one is not downloaded yet.
pub portrait: Option<PathBuf>,
pub marks: Marks,
/// In display order. A card with any reason is greyed.
pub reasons: Vec<Reason>,
/// The lines of the sheet shown on hover and focus, as label and value, prepared with the
/// card so showing it reads nothing.
pub sheet: Vec<(&'static str, SharedString)>,
}
/// What the grid knows of a card that the card does not: whether to show its sheet, and the
/// focus handle that makes it reachable with the keyboard.
#[derive(Clone, Copy, Default)]
pub struct CardState<'a> {
pub sheet: bool,
pub focus: Option<&'a FocusHandle>,
}
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.card_portrait.clone().or_else(|| row.portrait.clone()),
marks,
reasons: if marks.completed {
vec![Reason::Completed]
} else {
Vec::new()
},
sheet: sheet_lines(row),
}
}
/// Adds the champ select's reasons after the Season's. The player's own pick has none.
pub fn with_unavailability(mut self, unavailability: Unavailability) -> Card {
let Unavailability {
banned,
taken_by_ally,
not_offered,
} = unavailability;
for (applies, reason) in [
(banned, Reason::Banned),
(taken_by_ally, Reason::TakenByAlly),
(not_offered, Reason::NotOffered),
] {
if applies {
self.reasons.push(reason);
}
}
self
}
pub fn greyed(&self) -> bool {
!self.reasons.is_empty()
}
}
/// The sheet's figures for the Season, all Formats; « — » where there is none (no Season, or no
/// Match). The date is only there once the champion is Completed.
fn sheet_lines(row: &ChampionRow) -> Vec<(&'static str, SharedString)> {
let challenge = row.challenge;
let count = |n: Option<usize>| -> SharedString {
n.map_or_else(|| NONE.into(), |n| n.to_string().into())
};
let mut lines = vec![
(PLAYED, count(challenge.map(|c| c.matches))),
(WINS, count(challenge.map(|c| c.wins))),
(
BEST_PLACEMENT,
challenge
.and_then(|c| c.best_placement)
.map_or_else(|| NONE.into(), |placement| ordinal(placement).into()),
),
(ATTEMPTS, count(row.attempts)),
// Unknown is not zero: the points were never fetched for this Account.
(
MASTERY,
row.mastery_points
.map_or_else(|| UNKNOWN.into(), |points| thousands(points).into()),
),
];
if let Some(date) = challenge.and_then(|c| c.completed_on) {
lines.push((FIRST_TOP_1, date.to_string().into()));
}
lines
}
/// One card, as wide as its parent gives it, `ASPECT` wide over tall. Hovering only changes the
/// border colour; the sheet covers it when `state` says so, and a focus handle makes it a tab
/// stop with an accent border while the keyboard is on it. The caller adds its own listeners.
pub fn card(card: &Card, state: CardState<'_>, cx: &App) -> Stateful<Div> {
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))
.when_some(state.focus, |el, handle| {
el.track_focus(handle)
.focus_visible(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))
.when(state.sheet, |el| el.child(sheet(card)))
}
/// Over the whole card, as the mockup's `.card-info`: the name, then a line per figure. Only the
/// shown cards build it.
fn sheet(card: &Card) -> Div {
let id = card.id;
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.v_flex()
.justify_center()
.p(px(12.))
.bg(rgba(SHEET_BG))
.text_size(px(12.))
.text_color(rgb(SHEET_LABEL))
.debug_selector(|| format!("sheet-{id}"))
.child(
div()
.mb(px(10.))
.text_size(px(17.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(card.name.clone()),
)
.children(card.sheet.iter().map(|(label, value)| {
div()
.h_flex()
.justify_between()
.gap(px(4.))
.py(px(2.))
.debug_selector(|| format!("sheet-{id}-{label}"))
.child(*label)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(value.clone()),
)
}))
}
/// 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 std::path::PathBuf;
use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, Date, Unavailability};
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::{Card, FIRST_TOP_1, 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,
mastery_points: Some(154_320),
}
}
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");
}
fn lines(card: &Card) -> Vec<(&'static str, String)> {
card.sheet
.iter()
.map(|(label, value)| (*label, value.to_string()))
.collect()
}
#[test]
fn the_sheet_of_a_champion_never_played_is_empty_figures_without_a_date() {
let mut row = row(Some(ChampionChallenge::default()));
row.attempts = Some(0);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "0".to_string()),
("Victoires", "0".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "0".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_of_a_remaining_champion_has_its_best_placement_and_no_date() {
let challenge = ChampionChallenge {
matches: 5,
wins: 2,
best_placement: Some(2),
completed_on: None,
};
let mut row = row(Some(challenge));
row.attempts = Some(5);
let card = Card::from_row(&row);
assert_eq!(
lines(&card),
[
("Parties", "5".to_string()),
("Victoires", "2".into()),
("Meilleur Placement", "2ᵉ".into()),
("Tentatives", "5".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
assert!(card.sheet.iter().all(|(label, _)| *label != FIRST_TOP_1));
}
#[test]
fn the_sheet_of_a_completed_champion_has_the_date_of_its_first_top_1() {
let challenge = ChampionChallenge {
matches: 6,
wins: 3,
best_placement: Some(1),
completed_on: Some(day()),
};
let mut row = row(Some(challenge));
row.attempts = Some(4);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "6".to_string()),
("Victoires", "3".into()),
("Meilleur Placement", "1ᵉʳ".into()),
("Tentatives", "4".into()),
("Points de maîtrise", "154\u{202f}320".into()),
("Premier top 1", "02/03/2026".into()),
]
);
}
#[test]
fn the_sheet_of_a_row_without_a_season_has_dashes_and_no_date() {
let card = Card::from_row(&row(None));
assert_eq!(
lines(&card),
[
("Parties", "—".to_string()),
("Victoires", "—".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "—".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_shows_zero_points_as_zero_and_unknown_points_as_unknown() {
let mut row = row(None);
row.mastery_points = Some(0);
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "0".to_string())
);
row.mastery_points = None;
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "Inconnus".to_string())
);
}
#[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());
}
#[test]
fn the_tall_portrait_is_shown_and_the_square_icon_stands_in_while_it_is_missing() {
let tall = PathBuf::from("portraits/cards/TwistedFate.jpg");
let square = PathBuf::from("portraits/TwistedFate.png");
let both = ChampionRow {
portrait: Some(square.clone()),
card_portrait: Some(tall.clone()),
..row(None)
};
assert_eq!(Card::from_row(&both).portrait, Some(tall));
let downloading = ChampionRow {
card_portrait: None,
..both
};
assert_eq!(Card::from_row(&downloading).portrait, Some(square));
// Neither: the card keeps its plain background.
assert_eq!(Card::from_row(&row(None)).portrait, None);
}
fn completed_row() -> ChampionRow {
row(Some(ChampionChallenge {
matches: 1,
wins: 1,
best_placement: Some(1),
completed_on: Some(day()),
}))
}
fn unavailable(banned: bool, taken_by_ally: bool, not_offered: bool) -> Unavailability {
Unavailability {
banned,
taken_by_ally,
not_offered,
}
}
#[test]
fn the_champ_selects_reasons_add_up_in_a_fixed_order() {
let all = unavailable(true, true, true);
let card = Card::from_row(&completed_row()).with_unavailability(all);
assert_eq!(
card.reasons,
[
Reason::Completed,
Reason::Banned,
Reason::TakenByAlly,
Reason::NotOffered
]
);
let labels: Vec<_> = card.reasons.iter().map(|r| r.label()).collect();
assert_eq!(
labels,
["Validé", "Banni", "Pris par un allié", "Indisponible"]
);
let card = Card::from_row(&row(None)).with_unavailability(unavailable(false, true, false));
assert_eq!(card.reasons, [Reason::TakenByAlly]);
let card =
Card::from_row(&completed_row()).with_unavailability(unavailable(true, false, false));
assert_eq!(card.reasons, [Reason::Completed, Reason::Banned]);
}
#[test]
fn a_champion_the_champ_select_does_not_hold_back_is_not_greyed_by_it() {
let card = Card::from_row(&row(None)).with_unavailability(Unavailability::default());
assert!(card.reasons.is_empty());
assert!(!card.greyed());
// The player's own pick has no reason from the selection, but a Completed one stays.
let card = Card::from_row(&completed_row()).with_unavailability(Unavailability::default());
assert_eq!(card.reasons, [Reason::Completed]);
assert!(card.greyed());
let card = Card::from_row(&row(None)).with_unavailability(unavailable(false, false, true));
assert!(card.greyed());
}
}