The card under the pointer or the keyboard rises over its grid in about 0.35 s: 10 px with a gold glow, 4 px without for a greyed card, the illustration zooming to 107 % inside it while the caption fades and the sheet slides up over the lower half. Leaving it mid-way starts from where it is; a wheel drops it at once; in the hand a veil lays on the other cards. With Windows animations off the sheet shows without sliding and the card stays put. The grids never change on hover or focus any more: they record where they placed their visible cards, and the page draws the lifted cards in a deferred layer over them, asking for frames only while one moves. Structural tests check that a hover, through its animation, draws no grid, builds no card and computes no statistics. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
553 lines
20 KiB
Rust
553 lines
20 KiB
Rust
//! 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, and the
|
|
//! portraits they show (`card_images`). Its cards never change on hover or focus: the card under
|
|
//! the pointer or the keyboard is drawn lifted over the grid (`card_lift`), from where the grid
|
|
//! last placed it.
|
|
|
|
use std::cell::RefCell;
|
|
use std::collections::HashMap;
|
|
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::card_images::{self, CardImages};
|
|
use crate::page::PAGE_PADDING;
|
|
|
|
actions!(card_grid, [NextCard, PreviousCard]);
|
|
|
|
/// The grid's key context, where Tab and Shift-Tab move between its cards.
|
|
const CONTEXT: &str = "CardGrid";
|
|
|
|
/// Binds Tab and Shift-Tab in the grid's context, where they win over gpui-kit's root: the
|
|
/// rows are virtual, so the next card may not be built yet and the root cannot reach it.
|
|
pub fn init(cx: &mut App) {
|
|
cx.bind_keys([
|
|
KeyBinding::new("tab", NextCard, Some(CONTEXT)),
|
|
KeyBinding::new("shift-tab", PreviousCard, Some(CONTEXT)),
|
|
]);
|
|
}
|
|
|
|
/// 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: its
|
|
/// `max-width` rules apply up to and including 1000, 720 and 480 px.
|
|
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.),
|
|
}
|
|
}
|
|
|
|
/// What one row of the list takes: a card and the gap under it.
|
|
fn row_height(&self) -> f32 {
|
|
self.card_height + self.gap
|
|
}
|
|
}
|
|
|
|
/// How tall a row of cards is in a window `window_width` wide: the least height that shows a
|
|
/// whole row, for a grid that shares its column with other sections.
|
|
pub fn row_height(window_width: Pixels) -> Pixels {
|
|
px(Metrics::of(window_width).row_height())
|
|
}
|
|
|
|
/// The card under the pointer, or the one the keyboard is on, changed: its id, or none.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct CardHovered(pub Option<u32>);
|
|
|
|
/// A wheel moved the cards under a still pointer: none of them stays lifted.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct CardsMoved;
|
|
|
|
/// Where the grid last drew a card, in the window, and the part of the window it showed of it.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Placed {
|
|
pub bounds: Bounds<Pixels>,
|
|
pub visible: Bounds<Pixels>,
|
|
}
|
|
|
|
/// The cards the grid drew last, by id: filled as its rows are laid out, read between its draws.
|
|
pub type Placements = Rc<RefCell<HashMap<u32, Placed>>>;
|
|
|
|
/// What makes one card reachable with the keyboard: its handle, and the subscriptions that lift
|
|
/// it while the keyboard is on it.
|
|
struct CardFocus {
|
|
handle: FocusHandle,
|
|
_subscriptions: [Subscription; 2],
|
|
}
|
|
|
|
pub struct CardGrid {
|
|
/// All the cards in the order the page gives (the chosen sort); replaced when the statistics
|
|
/// or the sort change.
|
|
cards: Rc<[Card]>,
|
|
/// Indices into `cards`, after the filter and the search.
|
|
shown: Vec<usize>,
|
|
scroll: UniformListScrollHandle,
|
|
/// The card under the pointer or the keyboard, which is lifted.
|
|
hovered: Option<u32>,
|
|
/// Where the visible cards were drawn last.
|
|
placed: Placements,
|
|
/// How far the list was scrolled when last drawn: a wheel that leaves it there (at either
|
|
/// end) moves no card from under the pointer.
|
|
drawn_scroll: Pixels,
|
|
/// One per card id, kept across `set_cards` and dropped with the card.
|
|
focus: HashMap<u32, CardFocus>,
|
|
/// The cards changed since the focus handles were last matched to them.
|
|
focus_stale: bool,
|
|
/// All the rows built as a plain column, with no scrolling of its own: for a short list
|
|
/// whose height comes from its content (the Anvil champions row of a champ select).
|
|
fit_content: bool,
|
|
/// The portraits of the cards it paints, its own: made by its first render.
|
|
images: Option<Entity<CardImages>>,
|
|
/// 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 EventEmitter<CardHovered> for CardGrid {}
|
|
impl EventEmitter<CardsMoved> for CardGrid {}
|
|
|
|
impl CardGrid {
|
|
pub fn new() -> CardGrid {
|
|
CardGrid {
|
|
cards: Rc::new([]),
|
|
shown: Vec::new(),
|
|
scroll: UniformListScrollHandle::new(),
|
|
hovered: None,
|
|
placed: Placements::default(),
|
|
drawn_scroll: Pixels::ZERO,
|
|
focus: HashMap::new(),
|
|
focus_stale: false,
|
|
fit_content: false,
|
|
images: None,
|
|
#[cfg(test)]
|
|
renders: 0,
|
|
#[cfg(test)]
|
|
card_builds: 0,
|
|
#[cfg(test)]
|
|
set_cards_calls: 0,
|
|
}
|
|
}
|
|
|
|
/// A grid that is as tall as its rows and builds them all. It has the home grid's cards and
|
|
/// metrics. The parent uses the same row height to lay out the cached hand.
|
|
pub fn fit_content() -> CardGrid {
|
|
CardGrid {
|
|
fit_content: true,
|
|
..CardGrid::new()
|
|
}
|
|
}
|
|
|
|
pub fn hand_height(&self, window_width: Pixels) -> Option<Pixels> {
|
|
let metrics = Metrics::of(window_width);
|
|
let rows = self.shown.len().div_ceil(metrics.columns);
|
|
(rows > 0).then(|| px(metrics.row_height() * rows as f32))
|
|
}
|
|
|
|
/// 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;
|
|
self.focus_stale = true;
|
|
self.forget_hover_if_gone(cx);
|
|
cx.notify();
|
|
}
|
|
}
|
|
|
|
/// Gives every card a focus handle, reusing the ones of the ids already there. It runs when
|
|
/// the grid is drawn after `set_cards`, as subscribing needs the window.
|
|
fn sync_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
self.focus_stale = false;
|
|
let mut previous = std::mem::take(&mut self.focus);
|
|
for card in self.cards.iter() {
|
|
let id = card.id;
|
|
let focus = previous.remove(&id).unwrap_or_else(|| {
|
|
let handle = cx.focus_handle().tab_stop(true);
|
|
// As `:focus-visible`: a card focused by a click is already under the pointer.
|
|
let gained = cx.on_focus_in(&handle, window, move |grid, window, cx| {
|
|
if window.last_input_was_keyboard() {
|
|
grid.hover(Some(id), cx);
|
|
}
|
|
});
|
|
let lost = cx.on_focus_out(&handle, window, move |grid, _, _, cx| {
|
|
grid.set_hovered(id, false, cx);
|
|
});
|
|
CardFocus {
|
|
handle,
|
|
_subscriptions: [gained, lost],
|
|
}
|
|
});
|
|
self.focus.insert(id, focus);
|
|
}
|
|
}
|
|
|
|
fn set_hovered(&mut self, id: u32, hovered: bool, cx: &mut Context<Self>) {
|
|
let next = match (hovered, self.hovered) {
|
|
(true, _) => Some(id),
|
|
(false, Some(current)) if current == id => None,
|
|
(false, current) => current,
|
|
};
|
|
self.hover(next, cx);
|
|
}
|
|
|
|
/// The one change of the card under the pointer or the keyboard: it is told (the ring
|
|
/// lights that card's tick, the card is lifted over the grid), and the grid is not drawn
|
|
/// again.
|
|
fn hover(&mut self, next: Option<u32>, cx: &mut Context<Self>) {
|
|
if next != self.hovered {
|
|
self.hovered = next;
|
|
cx.emit(CardHovered(next));
|
|
}
|
|
}
|
|
|
|
/// The card under the pointer is no longer shown (filtered out, or gone with new cards):
|
|
/// none is hovered until the pointer moves again.
|
|
fn forget_hover_if_gone(&mut self, cx: &mut Context<Self>) {
|
|
let shown = |id| {
|
|
(self.shown.iter()).any(|&ix| self.cards.get(ix).is_some_and(|card| card.id == id))
|
|
};
|
|
if self.hovered.is_some_and(|id| !shown(id)) {
|
|
self.hover(None, cx);
|
|
}
|
|
}
|
|
|
|
/// Moves the focus `step` cards on in the grid's order, scrolling its row into view since
|
|
/// only the visible rows are built. At either end the key goes on, to leave the grid.
|
|
fn move_focus(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
|
|
let focused = |card: &Card| {
|
|
self.focus
|
|
.get(&card.id)
|
|
.is_some_and(|focus| focus.handle.is_focused(window))
|
|
};
|
|
let current = self
|
|
.shown
|
|
.iter()
|
|
.position(|&ix| self.cards.get(ix).is_some_and(focused));
|
|
let target = current
|
|
.and_then(|current| current.checked_add_signed(step))
|
|
.filter(|&target| target < self.shown.len());
|
|
let handle = target.and_then(|target| {
|
|
let card = self.cards.get(*self.shown.get(target)?)?;
|
|
Some((target, self.focus.get(&card.id)?.handle.clone()))
|
|
});
|
|
let Some((target, handle)) = handle else {
|
|
cx.propagate();
|
|
return;
|
|
};
|
|
if !self.fit_content {
|
|
let columns = Metrics::of(window.viewport_size().width).columns;
|
|
self.scroll
|
|
.scroll_to_item(target / columns, ScrollStrategy::Nearest);
|
|
}
|
|
window.focus(&handle, cx);
|
|
}
|
|
|
|
/// How far down the list is scrolled, as its next layout will put it: a wheel past either end
|
|
/// is held there.
|
|
fn scrolled_to(&self) -> Pixels {
|
|
let handle = &self.scroll.0.borrow().base_handle;
|
|
handle
|
|
.offset()
|
|
.y
|
|
.max(-handle.max_offset().y)
|
|
.min(Pixels::ZERO)
|
|
}
|
|
|
|
/// The grid is not shown any more: its portraits are given back, in memory and in the
|
|
/// window's atlas, and load again when it is drawn.
|
|
pub fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
// Nor is any of its cards under the pointer: the ring's tick goes out.
|
|
self.hover(None, cx);
|
|
self.placed.borrow_mut().clear();
|
|
let released = self
|
|
.images
|
|
.as_ref()
|
|
.is_some_and(|images| images.update(cx, |images, cx| images.release(window, cx)));
|
|
if released {
|
|
// A cached view replays its last paint unless it is drawn again.
|
|
cx.notify();
|
|
}
|
|
}
|
|
|
|
pub fn set_shown(&mut self, shown: Vec<usize>, cx: &mut Context<Self>) {
|
|
if self.shown != shown {
|
|
self.shown = shown;
|
|
self.forget_hover_if_gone(cx);
|
|
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()
|
|
}
|
|
|
|
/// The cards shown, in order.
|
|
#[cfg(test)]
|
|
pub(crate) fn shown_cards(&self) -> Vec<Card> {
|
|
self.shown
|
|
.iter()
|
|
.filter_map(|&ix| self.cards.get(ix))
|
|
.cloned()
|
|
.collect()
|
|
}
|
|
|
|
/// The portraits its cards show, for a card drawn over it.
|
|
pub fn images(&self) -> Option<&Entity<CardImages>> {
|
|
self.images.as_ref()
|
|
}
|
|
|
|
/// Where its visible cards were drawn last.
|
|
pub fn placed(&self) -> &Placements {
|
|
&self.placed
|
|
}
|
|
|
|
/// One of its cards, shown or not.
|
|
pub fn card(&self, id: u32) -> Option<&Card> {
|
|
self.cards.iter().find(|card| card.id == id)
|
|
}
|
|
|
|
/// A grid as tall as its rows: the hand of a champ select.
|
|
pub fn is_hand(&self) -> bool {
|
|
self.fit_content
|
|
}
|
|
|
|
/// 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 ids: Vec<Option<u32>> = (start..start + metrics.columns)
|
|
.map(|slot| {
|
|
let card = self.shown.get(slot).and_then(|&c| self.cards.get(c))?;
|
|
Some(card.id)
|
|
})
|
|
.collect();
|
|
let placed = self.placed.clone();
|
|
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))
|
|
// Only a row painted is laid out here, not one `uniform_list` merely measures.
|
|
.on_children_prepainted(move |bounds, window, _| {
|
|
let visible = window.content_mask().bounds;
|
|
let mut placed = placed.borrow_mut();
|
|
for (id, bounds) in ids.iter().zip(bounds) {
|
|
if let Some(id) = id {
|
|
placed.insert(*id, Placed { bounds, visible });
|
|
}
|
|
}
|
|
});
|
|
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;
|
|
}
|
|
let focus = self.focus.get(&data.id).map(|focus| &focus.handle);
|
|
let id = data.id;
|
|
card(data, focus, cx)
|
|
.on_hover(cx.listener(move |grid, hovered: &bool, _, cx| {
|
|
grid.set_hovered(id, *hovered, 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 CardGrid {
|
|
/// The grid's key context, its portraits and what it reacts to besides its cards.
|
|
fn with_cards_behaviour(
|
|
&self,
|
|
root: Div,
|
|
images: Entity<CardImages>,
|
|
cx: &mut Context<Self>,
|
|
) -> Div {
|
|
card_images::provide(root, images)
|
|
.key_context(CONTEXT)
|
|
// A wheel scroll moves cards under a still pointer without a hover event: the
|
|
// sheet of the card that was under it would stay. The next mouse move hovers again.
|
|
.on_scroll(cx.listener(|grid, _: &ScrollEvent, _, cx| {
|
|
// The list has scrolled first. A grid that fits its content is moved by its
|
|
// parent's scrolling instead, which it cannot see.
|
|
let moved = grid.fit_content || grid.scrolled_to() != grid.drawn_scroll;
|
|
if moved {
|
|
grid.hover(None, cx);
|
|
cx.emit(CardsMoved);
|
|
}
|
|
}))
|
|
.on_action(cx.listener(|grid, _: &NextCard, window, cx| grid.move_focus(1, window, cx)))
|
|
.on_action(
|
|
cx.listener(|grid, _: &PreviousCard, window, cx| grid.move_focus(-1, window, cx)),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl Render for CardGrid {
|
|
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
#[cfg(test)]
|
|
{
|
|
self.renders += 1;
|
|
}
|
|
if self.focus_stale {
|
|
self.sync_focus(window, cx);
|
|
}
|
|
self.drawn_scroll = self.scrolled_to();
|
|
// Only the rows drawn now place their cards.
|
|
self.placed.borrow_mut().clear();
|
|
let images = (self.images)
|
|
.get_or_insert_with(|| CardImages::new(cx))
|
|
.clone();
|
|
images.update(cx, |images, cx| images.start_render(window, cx));
|
|
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);
|
|
if self.fit_content {
|
|
// The same rows and cards (sheet, hover, keyboard focus), all built, as a column.
|
|
let rows: Vec<_> = (0..rows).map(|ix| self.row(ix, metrics, cx)).collect();
|
|
return self
|
|
.with_cards_behaviour(div().v_flex().w_full(), images, cx)
|
|
.children(rows)
|
|
.into_any_element();
|
|
}
|
|
self.with_cards_behaviour(div().relative().size_full(), images, cx)
|
|
.debug_selector(|| "card-list".into())
|
|
.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),
|
|
(1001., 6),
|
|
(1000., 4),
|
|
(721., 4),
|
|
(720., 3),
|
|
(481., 3),
|
|
(480., 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}"
|
|
);
|
|
}
|
|
}
|
|
}
|