Draw the champion table and the charts more cheaply (#31)
CI / core (pull_request) Successful in 1m12s

The champion table is now the app's own view, a uniform_list with one
plain element per cell, instead of gpui-component's DataTable, which
gave each row a horizontal virtual list and each cell its own layout,
id and accessibility node. A full frame of the statistics page costs a
third less: on the manual checks machine, drawing it went from 2.37 to
1.57 ms at the median and from 3.72 to 2.50 ms at the 99th percentile.
Sorting by header click, scrolling, click-to-select (now following the
champion through sorts and reloads), stripes and hover stay; dragging
column edges, arrow-key selection and screen-reader table roles go.
Columns shrink with a narrow window, clipped, with room left for the
scrollbar; an ellipsis cost 0.2 ms per frame.

The charts row is a cached view of fixed height, so hovering a row no
longer paints the charts again (about 0.1 ms at the median, 0.2 ms at
the 99th percentile). A structural test guards it, with GPUI's own test
support as a dev-dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-17 22:17:07 +01:00
1 parent 2c1dde684c
commit 8318a5875e
5 files changed
+828 -184

No files matched your search

+207 -78
View File
@@ -14,7 +14,6 @@ use gpui_kit::component::button::Button;
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::table::{DataTable, TableState};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
@@ -26,7 +25,9 @@ use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics};
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
const NO_MATCH: &str = "Aucune Partie";
const CHART_HEIGHT: f32 = 150.;
/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves
/// each chart 150 px: change them together.
const CHARTS_HEIGHT: f32 = 206.;
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
@@ -111,8 +112,8 @@ pub struct StatsPage {
season_select: Entity<SelectState<Vec<SharedString>>>,
format_select: Entity<SelectState<Vec<SharedString>>>,
format_names: Vec<SharedString>,
table: Entity<TableState<ChampionTable>>,
table_in_season: bool,
charts: Entity<ChartsRow>,
table: Entity<ChampionTable>,
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
@@ -170,8 +171,8 @@ impl StatsPage {
let format_names = vec![SharedString::from(ALL_FORMATS)];
let format_select = cx
.new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx));
let table =
cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false));
let charts = cx.new(|_| ChartsRow::new());
let table = cx.new(|_| ChampionTable::new());
let subscriptions = vec![
cx.subscribe_in(
@@ -260,8 +261,8 @@ impl StatsPage {
season_select,
format_select,
format_names,
charts,
table,
table_in_season: false,
_subscriptions: subscriptions,
_listener: listener,
};
@@ -287,6 +288,11 @@ impl StatsPage {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
/// Whether one Season is selected, rather than all of them: only a Season has a Challenge.
fn in_season(&self) -> bool {
matches!(self.season, SeasonScope::Season(_))
}
/// The Account shown: the pinned one, else the one being updated.
fn viewed(&self) -> Option<&Account> {
self.pinned
@@ -508,8 +514,12 @@ impl StatsPage {
self.show_statistics(window, cx);
}
/// Shows `stats`: the Format choices and the table.
/// Shows `stats`: the Format choices, the charts and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
self.charts
.update(cx, |row, cx| row.set(charts, in_season, cx));
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
@@ -528,15 +538,9 @@ impl StatsPage {
fn refresh_table(&mut self, cx: &mut Context<Self>) {
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows.filter(|row| self.filter.keeps(row)).cloned().collect();
let in_season = matches!(self.season, SeasonScope::Season(_));
// Only a change of columns needs `refresh`, which also resets the column widths.
let columns_changed = in_season != self.table_in_season;
self.table_in_season = in_season;
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.delegate_mut().set_rows(rows, in_season);
if columns_changed {
table.refresh(cx);
}
table.set_rows(rows, in_season);
cx.notify();
});
}
@@ -669,6 +673,7 @@ fn card(
.v_flex()
.flex_1()
.min_w_0()
.h_full()
.gap_2()
.p_3()
.border_1()
@@ -680,7 +685,103 @@ fn card(
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.child(div().h(px(CHART_HEIGHT)).w_full().children(Some(body)))
.child(div().flex_1().min_h_0().w_full().children(Some(body)))
}
/// The charts, a cached view: hovering the table, which redraws the page, does not draw them
/// again (#31). The page updates it from `show_statistics`.
struct ChartsRow {
/// Empty when there are no statistics.
charts: Charts,
in_season: bool,
/// Guards the cache in tests.
#[cfg(test)]
renders: usize,
}
impl ChartsRow {
fn new() -> ChartsRow {
ChartsRow {
charts: Charts {
placements: vec![],
completed_over_time: vec![],
attempts_to_complete: [0; 5],
},
in_season: false,
#[cfg(test)]
renders: 0,
}
}
/// Shows `charts`, or none; drawing them again only when they changed, since reloads keep
/// coming during an import.
fn set(&mut self, charts: Option<&Charts>, in_season: bool, cx: &mut Context<Self>) {
let charts = charts.cloned().unwrap_or_else(|| ChartsRow::new().charts);
if (&self.charts, self.in_season) != (&charts, in_season) {
self.charts = charts;
self.in_season = in_season;
cx.notify();
}
}
}
impl Render for ChartsRow {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let (border, muted) = {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
let charts = &self.charts;
let mut cards = vec![
card(
"Répartition des Placements",
if shown("placements") {
placements_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
NO_MATCH,
border,
muted,
)
.into_any_element(),
];
if self.in_season {
cards.push(
card(
"Champions validés au fil de la Saison",
if shown("completed") {
completed_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
cards.push(
card(
"Tentatives pour valider",
if shown("attempts") {
attempts_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
}
div().h_flex().size_full().gap_3().children(cards)
}
}
fn placements_chart(charts: &Charts) -> Option<AnyElement> {
@@ -744,60 +845,9 @@ impl Render for StatsPage {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
};
let in_season = matches!(self.season, SeasonScope::Season(_));
let options = filters(in_season);
let options = filters(self.in_season());
let selected = options.iter().position(|(_, f)| *f == self.filter);
let empty = Charts {
placements: vec![],
completed_over_time: vec![],
attempts_to_complete: [0; 5],
};
let charts = self.stats.as_ref().map_or(&empty, |s| &s.charts);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
let mut cards = vec![
card(
"Répartition des Placements",
if shown("placements") {
placements_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
NO_MATCH,
border,
muted,
)
.into_any_element(),
];
if in_season {
cards.push(
card(
"Champions validés au fil de la Saison",
if shown("completed") {
completed_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
cards.push(
card(
"Tentatives pour valider",
if shown("attempts") {
attempts_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
border,
muted,
)
.into_any_element(),
);
}
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
@@ -883,7 +933,11 @@ impl Render for StatsPage {
.when(shown("tiles"), |page| {
page.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted)))
})
.child(div().h_flex().gap_3().children(cards))
.child(
self.charts
.clone()
.cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT))),
)
.when(shown("tabs"), |page| {
page.child(
TabBar::new("state-filter")
@@ -891,8 +945,7 @@ impl Render for StatsPage {
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
let in_season = matches!(this.season, SeasonScope::Season(_));
if let Some((_, filter)) = filters(in_season).get(*ix) {
if let Some((_, filter)) = filters(this.in_season()).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
@@ -901,12 +954,88 @@ impl Render for StatsPage {
)
})
.when(shown("table"), |page| {
page.child(
div()
.flex_1()
.min_h(px(240.))
.child(DataTable::new(&self.table).stripe(true)),
)
page.child(div().flex_1().min_h(px(240.)).child(self.table.clone()))
})
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{RiotApi, Tracker};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
AppContext as _, Bounds, Modifiers, TestAppContext, VisualTestContext, WindowBounds,
WindowOptions, point, px, size,
};
use super::StatsPage;
use crate::champion_table::tests::row;
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
let bounds = Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
};
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
};
gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| StatsPage::new(tracker, None, false, rx, tx, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
let (table, charts) =
page.read_with(cx, |page, _| (page.table.clone(), page.charts.clone()));
// Enough rows to fill the table, under the points hovered below.
table.update(cx, |table, cx| {
let rows = (1..=20).map(|n| row(&format!("Champion {n}")));
table.set_rows(rows.collect(), false);
cx.notify();
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let renders = charts.read_with(cx, |charts, _| charts.renders);
assert!(renders > 0);
// A row's hover style notifies the table, which redraws the page.
let hovers = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let hovers = hovers.clone();
cx.observe(&table, move |_, _| hovers.set(hovers.get() + 1))
});
for y in [700., 740.] {
cx.simulate_mouse_move(point(px(300.), px(y)), None, Modifiers::none());
cx.update(|window, cx| window.draw(cx).clear(cx));
}
assert!(hovers.get() > 0, "no row was hovered");
assert_eq!(charts.read_with(cx, |charts, _| charts.renders), renders);
// The count does move when the charts change.
charts.update(cx, |_, cx| cx.notify());
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(
charts.read_with(cx, |charts, _| charts.renders),
renders + 1
);
}
}