From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 0CE511FF0B3 for ; Thu, 26 Nov 2026 15:54:25 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 5264521735; Thu, 26 Nov 2026 15:54:17 +0100 (CET) From: Dominik Csapak 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 Message-ID: <20261126145410.3011676-8-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261126145410.3011676-1-d.csapak@proxmox.com> References: <20261126145410.3011676-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.259 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: UAPKZBOM3UKSFK3NLYP6IICNX4RUMG24 X-Message-ID-Hash: UAPKZBOM3UKSFK3NLYP6IICNX4RUMG24 X-MailFrom: d.csapak@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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 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, + /// 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, + root_ref: NodeRef, tooltip_info: Option, tooltip_ref: NodeRef, tooltip_anchor: NodeRef, @@ -81,8 +92,14 @@ impl Component for TopEntitiesComp { type Properties = TopEntities; fn create(ctx: &yew::Context) -> 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, _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, _first_render: bool) { + fn rendered(&mut self, ctx: &yew::Context, first_render: bool) { + if first_render { + if let Some(el) = self.root_ref.cast::() { + 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 { + let graph = self + .root_ref + .cast::()? + .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, +} + +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], max_buckets: usize) -> impl Iterator + '_ { + // 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], 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], 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 = 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 { +/// Returns the graph backgrounds for all entities. +fn graph_backgrounds(props: &TopEntities, max_buckets: usize) -> Vec { 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