From: Dominik Csapak <d.csapak@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [PATCH datacenter-manager 07/10] ui: dashboard: top entities: limit color stops by graph width
Date: Thu, 26 Nov 2026 15:49:20 +0100 [thread overview]
Message-ID: <20261126145410.3011676-8-d.csapak@proxmox.com> (raw)
In-Reply-To: <20261126145410.3011676-1-d.csapak@proxmox.com>
the rrd data for the default 'day' timeframe contains 1440 data
points, and we added a color stop for each one. That resulted in
roughly 150 KB of css per graph, even though most of these stops
were not visible at all, since the positions were rounded to whole
percent.
Instead, split the data into buckets, so that each color stop covers
at least two pixels. The gradient interpolates between the stops, so
this looks the same as one stop per pixel. Measure the width of the
graphs when the size of the component or the entities change, since
the column with the names takes up a varying part of it. Also merge
consecutive stops with the same color, as that renders the same.
Use the highest value of a bucket for its color instead of the
average, since short spikes of high usage are what matters most in a
list of the top consumers, and averaging would hide them in narrow
graphs.
Note that short dips and gaps in the data are not visible in narrow
graphs anymore, but the tooltip still shows the raw values.
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
ui/src/dashboard/top_entities.rs | 217 +++++++++++++++++++++++++------
1 file changed, 174 insertions(+), 43 deletions(-)
diff --git a/ui/src/dashboard/top_entities.rs b/ui/src/dashboard/top_entities.rs
index b96240f5..deebfd1d 100644
--- a/ui/src/dashboard/top_entities.rs
+++ b/ui/src/dashboard/top_entities.rs
@@ -4,6 +4,7 @@ use web_sys::HtmlElement;
use yew::virtual_dom::{VComp, VNode};
use proxmox_yew_comp::utils::render_epoch;
+use pwt::dom::DomSizeObserver;
use pwt::prelude::*;
use pwt::state::SharedState;
use pwt::widget::Fa;
@@ -58,6 +59,8 @@ impl From<TopEntities> for VNode {
pub enum Msg {
ShowTooltip(PointerEvent, Resource),
HideTooltip,
+ /// Measure the graph width again, e.g. when the size of the component changed.
+ Measure,
}
struct TooltipInfo {
@@ -69,8 +72,16 @@ struct TooltipInfo {
struct TopEntitiesComp {
/// The graph backgrounds in the same order as the entities, only calculated when the
- /// properties change and not on every re-render, e.g. when moving the tooltip.
+ /// properties or the number of buckets change and not on every re-render, e.g. when moving the
+ /// tooltip.
graph_backgrounds: Vec<AttrValue>,
+ /// The maximum number of buckets the data of a graph gets split into.
+ max_buckets: usize,
+ /// Whether the graph width needs to be measured again after the next render, since the
+ /// entities and with them the width of the name column changed.
+ measure_width: bool,
+ size_observer: Option<DomSizeObserver>,
+ root_ref: NodeRef,
tooltip_info: Option<TooltipInfo>,
tooltip_ref: NodeRef,
tooltip_anchor: NodeRef,
@@ -81,8 +92,14 @@ impl Component for TopEntitiesComp {
type Properties = TopEntities;
fn create(ctx: &yew::Context<Self>) -> Self {
+ // the real width is only known after the first render, see `rendered`
+ let max_buckets = 0;
Self {
- graph_backgrounds: graph_backgrounds(ctx.props()),
+ graph_backgrounds: graph_backgrounds(ctx.props(), max_buckets),
+ max_buckets,
+ measure_width: false,
+ size_observer: None,
+ root_ref: NodeRef::default(),
tooltip_info: None,
tooltip_ref: NodeRef::default(),
tooltip_anchor: NodeRef::default(),
@@ -124,13 +141,25 @@ impl Component for TopEntitiesComp {
Msg::HideTooltip => {
self.tooltip_info = None;
}
+ Msg::Measure => {
+ let Some(width) = self.measure_graph_width() else {
+ return false;
+ };
+ let max_buckets = (width / PIXELS_PER_BUCKET).ceil() as usize;
+ if max_buckets == self.max_buckets {
+ return false;
+ }
+ self.max_buckets = max_buckets;
+ self.graph_backgrounds = graph_backgrounds(props, max_buckets);
+ }
}
true
}
fn changed(&mut self, ctx: &yew::Context<Self>, _old_props: &Self::Properties) -> bool {
- self.graph_backgrounds = graph_backgrounds(ctx.props());
+ self.graph_backgrounds = graph_backgrounds(ctx.props(), self.max_buckets);
+ self.measure_width = true;
true
}
@@ -226,10 +255,22 @@ impl Component for TopEntitiesComp {
.with_child(tooltip)
.into_html_with_ref(self.tooltip_ref.clone())
}))
- .into()
+ .into_html_with_ref(self.root_ref.clone())
}
- fn rendered(&mut self, _ctx: &yew::Context<Self>, _first_render: bool) {
+ fn rendered(&mut self, ctx: &yew::Context<Self>, first_render: bool) {
+ if first_render {
+ if let Some(el) = self.root_ref.cast::<web_sys::Element>() {
+ let link = ctx.link().clone();
+ self.size_observer = Some(DomSizeObserver::new(&el, move |_: (f64, f64)| {
+ link.send_message(Msg::Measure);
+ }));
+ }
+ } else if self.measure_width {
+ self.measure_width = false;
+ ctx.link().send_message(Msg::Measure);
+ }
+
if let Some(tooltip_node) = self.tooltip_ref.get() {
if let Some(anchor) = self.tooltip_anchor.get() {
let _ = align_to(
@@ -249,6 +290,19 @@ impl Component for TopEntitiesComp {
}
}
+impl TopEntitiesComp {
+ /// Returns the width of the graphs, which share the grid column next to the names, or `None`
+ /// if there is no graph.
+ fn measure_graph_width(&self) -> Option<f64> {
+ let graph = self
+ .root_ref
+ .cast::<web_sys::Element>()?
+ .query_selector(".line-usage-graph")
+ .ok()??;
+ Some(graph.get_bounding_client_rect().width())
+ }
+}
+
fn create_tooltip(
remote: &str,
resource: &Resource,
@@ -294,56 +348,133 @@ const BACKGROUND_COLOR: &str = "var(--pwt-color-surface)";
const COLOR_SPACE: &str = "oklab";
+/// The minimum width in pixels a bucket of data points covers in the graph. The RRD data can contain
+/// more points (e.g. 1440 for a day) than the graph is wide in pixels, and every point makes the
+/// style data bigger without any visible difference. Since the gradient interpolates between the
+/// color stops, this looks the same as a stop per pixel.
+const PIXELS_PER_BUCKET: f64 = 2.0;
+
+fn usage_color(value: f64, threshold: f64) -> String {
+ let (ratio, high_color, low_color) = if value < threshold {
+ (value / threshold, WARN_COLOR, GOOD_COLOR)
+ } else {
+ (
+ (value - threshold) / (1.0 - threshold),
+ ERR_COLOR,
+ WARN_COLOR,
+ )
+ };
+
+ match (ratio.clamp(0.0, 1.0) * 100.0).round() as u8 {
+ 0 => low_color.to_string(),
+ 100 => high_color.to_string(),
+ percent => format!("color-mix(in {COLOR_SPACE}, {high_color} {percent}%, {low_color})"),
+ }
+}
+
+/// A range of data points with the highest of their values.
+struct Bucket {
+ start: usize,
+ end: usize,
+ value: Option<f64>,
+}
+
+impl Bucket {
+ /// The position of the bucket, in units of data point indices. Every data point covers the
+ /// interval up to the next one, so this is the center of all intervals of the bucket.
+ fn center(&self) -> f64 {
+ (self.start + self.end) as f64 / 2.0
+ }
+}
+
+/// Splits the data points into at most `max_buckets` buckets of about the same size.
+fn buckets(data: &[Option<f64>], max_buckets: usize) -> impl Iterator<Item = Bucket> + '_ {
+ // the rrd data sometimes contains a last data point that was not collected yet, which should
+ // not be shown as a gap
+ let points = match data.split_last() {
+ Some((None, rest)) => rest,
+ _ => data,
+ };
+ let bucket_count = points.len().min(max_buckets);
+
+ (0..bucket_count).map(move |bucket| {
+ let start = bucket * points.len() / bucket_count;
+ let end = (bucket + 1) * points.len() / bucket_count;
+
+ // the highest value instead of the average, so that short spikes stay visible
+ let max = points[start..end]
+ .iter()
+ .flatten()
+ .copied()
+ .reduce(f64::max);
+
+ Bucket {
+ start,
+ end,
+ value: max,
+ }
+ })
+}
+
/// Returns the CSS 'background-image' value for the usage graph of the given data.
-fn graph_background(data: &[Option<f64>], threshold: f64) -> AttrValue {
- let mut list = Vec::new();
- for (i, point) in data.iter().enumerate() {
- if let Some(point) = point {
- let (left, left_color, right, right_color, percent) = if *point < threshold {
- let point = (point / threshold).clamp(0.0, 1.0);
-
- (
- point * 100.0,
- WARN_COLOR,
- (1.0 - point) * 100.0,
- GOOD_COLOR,
- (i as f64 + 0.5) * 100.0 / data.len() as f64,
- )
- } else {
- let point = ((point - threshold) / (1.0 - threshold)).clamp(0.0, 1.0);
- (
- point * 100.0,
- ERR_COLOR,
- (1.0 - point) * 100.0,
- WARN_COLOR,
- (i as f64 + 0.5) * 100.0 / data.len() as f64,
- )
- };
- list.push(format!(
- "color-mix(in {COLOR_SPACE}, {left_color} {left:.0}%, {right_color} {right:.0}%) {percent:.0}%",
- ));
- } else if (i + 1) < data.len() {
- // only add empty point if it's not the last, since the rrd data sometimes adds
- // data points that were not collected yet.
- list.push(format!(
- "{BACKGROUND_COLOR} {:.0}% {:.0}%",
- i as f64 * 100.0 / data.len() as f64,
- (i as f64 + 1.0) * 100.0 / data.len() as f64,
- ));
+fn graph_background(data: &[Option<f64>], threshold: f64, max_buckets: usize) -> AttrValue {
+ let len = data.len() as f64;
+
+ // color stops as (color, start, end), with the positions in percent
+ let mut stops: Vec<(String, f64, f64)> = Vec::new();
+ for bucket in buckets(data, max_buckets) {
+ let (color, start_pos, end_pos) = match bucket.value {
+ Some(value) => {
+ let pos = bucket.center() * 100.0 / len;
+ (usage_color(value, threshold), pos, pos)
+ }
+ None => (
+ BACKGROUND_COLOR.to_string(),
+ bucket.start as f64 * 100.0 / len,
+ bucket.end as f64 * 100.0 / len,
+ ),
};
+
+ match stops.last_mut() {
+ // extending the previous stop renders identically, but keeps the gradient short
+ Some((last_color, _, last_end)) if *last_color == color => *last_end = end_pos,
+ _ => stops.push((color, start_pos, end_pos)),
+ }
+ }
+
+ match stops.as_slice() {
+ [] => return AttrValue::Static("none"),
+ // older browsers need at least two color stops, so write out the single color twice
+ [(color, _, _)] => return format!("linear-gradient({color}, {color})").into(),
+ _ => {}
}
+
+ let stops: Vec<String> = stops
+ .into_iter()
+ .map(|(color, start, end)| {
+ let (start, end) = (format!("{start:.1}%"), format!("{end:.1}%"));
+ // a stop that does not span a range only needs a single position
+ if start == end {
+ format!("{color} {start}")
+ } else {
+ format!("{color} {start} {end}")
+ }
+ })
+ .collect();
+
format!(
"linear-gradient(in {COLOR_SPACE} to right, {})",
- list.join(", ")
+ stops.join(", ")
)
.into()
}
-fn graph_backgrounds(props: &TopEntities) -> Vec<AttrValue> {
+/// Returns the graph backgrounds for all entities.
+fn graph_backgrounds(props: &TopEntities, max_buckets: usize) -> Vec<AttrValue> {
props
.entities
.iter()
- .map(|entity| graph_background(&entity.rrd_data.data, props.threshold))
+ .map(|entity| graph_background(&entity.rrd_data.data, props.threshold, max_buckets))
.collect()
}
--
2.47.3
next prev parent reply other threads:[~2026-11-26 14:54 UTC|newest]
Thread overview: 11+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-26 14:49 [PATCH datacenter-manager 00/10] dashborad: add widget settings and leaderboard graph types Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 01/10] ui: dashboard: use plural for the container panel Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 02/10] ui: views: keep the icon for custom widget titles Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 03/10] ui: views: add options panel for editing widgets Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 04/10] ui: views: add only one menu entry per widget type Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 05/10] ui: dashboard: top entities: only build graph gradients on change Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 06/10] ui: dashboard: top entities: center data points in their interval Dominik Csapak
2026-11-26 14:49 ` Dominik Csapak [this message]
2026-11-26 14:49 ` [PATCH datacenter-manager 08/10] ui: dashboard: top entities: add line, area and bar graph types Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 09/10] ui: dashboard: top entities: show indicator line for tooltip point Dominik Csapak
2026-11-26 14:49 ` [PATCH datacenter-manager 10/10] docs: custom views: mention the graph types of the leaderboard widget Dominik Csapak
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261126145410.3011676-8-d.csapak@proxmox.com \
--to=d.csapak@proxmox.com \
--cc=pdm-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox