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 62F3D1FF0B4 for ; Fri, 27 Nov 2026 17:14:21 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id EE4C92173E; Fri, 27 Nov 2026 17:13:31 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH yew-widget-toolkit 22/38] widget: charts: map: animate changes of the view Date: Fri, 27 Nov 2026 17:12:19 +0100 Message-ID: <20261127161241.3713494-23-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261127161241.3713494-1-d.csapak@proxmox.com> References: <20261127161241.3713494-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.250 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: S2SRNWYWV3N7BICSGEN7MN5XHPUTOGHY X-Message-ID-Hash: S2SRNWYWV3N7BICSGEN7MN5XHPUTOGHY 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: when zooming with the wheel or the buttons, and when a clicked point gets centered. Jumping there at once makes it hard to follow where the view went, especially for bigger steps. To do that, keep the view the user asked for separate from the one that is shown, and move the shown one towards it with each animation frame. It covers the same share of the remaining way per time, so a new target during a running animation (e.g. the next wheel step) only changes where it is heading. The scale changes by factors and the pan in proportion to the scale, so the point a zoom is centered on stays where it is. Dragging and pinching still move the view directly, since the map has to stay under the pointer. There is also no animation for users that prefer reduced motion. Signed-off-by: Dominik Csapak --- Cargo.toml | 1 + src/widget/charts/map/mod.rs | 134 ++++++++++++++++++++++++----- src/widget/charts/map/zoom_info.rs | 80 +++++++++++++++++ 3 files changed, 192 insertions(+), 23 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0f3f88c..ad9cbbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,6 +72,7 @@ wasm-logger = "0.2" gloo-events = "0.2" gloo-timers = "0.3" gloo-history = "0.2" +gloo-render = "0.2" gloo-utils = "0.2" serde = { version = "1.0", features = ["derive", "rc"] } serde_json = "1.0" diff --git a/src/widget/charts/map/mod.rs b/src/widget/charts/map/mod.rs index 37a595a..093cfe1 100644 --- a/src/widget/charts/map/mod.rs +++ b/src/widget/charts/map/mod.rs @@ -1,5 +1,6 @@ use std::marker::PhantomData; +use gloo_render::{AnimationFrame, request_animation_frame}; use wasm_bindgen::prelude::Closure; use wasm_bindgen::{JsCast, UnwrapThrowExt}; @@ -43,6 +44,14 @@ impl MapPoint { } } +// How fast the shown view follows a change of the view: after this time in milliseconds it has +// covered about two thirds of the way, after three times as long nearly all of it. +const VIEW_ANIMATION_TIME_CONSTANT: f64 = 70.0; + +// The first frame of an animation has no frame before it to measure the time from, so assume the +// frame time of a common display. +const FIRST_FRAME_TIME: f64 = 1000.0 / 60.0; + /// An interactive Map that handles interaction (zooming, panning) and draws /// [MapPoint]s on top of the given SVG element. /// @@ -101,6 +110,8 @@ pub enum Msg { Drag(GestureDragEvent), UpdateInfoAlignment, PointerDown, + /// An animation frame at the given time in milliseconds. + AnimateView(f64), } #[derive(PartialEq, Clone)] @@ -124,7 +135,14 @@ impl Cluster { } pub struct MapComp { - zoom: ZoomInfo, + // the view the user asked for + target_view: ZoomInfo, + // the view that is shown, it follows the target view when a change is animated + shown_view: ZoomInfo, + // the next frame of the animation, while the shown view is on its way to the target view + animation_frame: Option, + // the time of the last frame of the animation, its first frame has none + last_frame_time: Option, pinch_start_scale: f64, pinch_last_center: Coordinates, fit_scale: f64, @@ -173,14 +191,14 @@ impl MapComp { let base = &points[index]; let mut overlapping = Vec::new(); let mut non_overlapping = Vec::new(); - let base_coordinates = self.zoom.map_point(base.coordinates); + let base_coordinates = self.shown_view.map_point(base.coordinates); // accumulate the cluster center while partitioning, starting from the base point let mut x_center = base.coordinates.x; let mut y_center = base.coordinates.y; for compare_index in indices.into_iter() { let p = &points[compare_index]; - let point_coordinates = self.zoom.map_point(p.coordinates); + let point_coordinates = self.shown_view.map_point(p.coordinates); let dx = base_coordinates.x - point_coordinates.x; let dy = base_coordinates.y - point_coordinates.y; if dx * dx + dy * dy < (2.0 * effective_radius).powi(2) { @@ -219,6 +237,58 @@ impl MapComp { self.clusters = clusters; } + /// Shows the target view at once. + fn jump_to_target_view(&mut self, ctx: &Context) { + // there is nothing left to do for a running animation + self.animation_frame = None; + let scale_changed = self.shown_view.get_zoom_level() != self.target_view.get_zoom_level(); + self.shown_view = self.target_view; + // the points only overlap differently if the scale changes + if scale_changed { + self.cluster_points(ctx); + } + } + + /// Moves the shown view to the target view over the next animation frames. + fn animate_to_target_view(&mut self, ctx: &Context) { + if prefers_reduced_motion() { + self.jump_to_target_view(ctx); + } else if self.animation_frame.is_none() { + self.last_frame_time = None; + self.request_animation_frame(ctx); + } + } + + /// Asks for the next frame of the animation. The frame is cancelled if it gets dropped. + fn request_animation_frame(&mut self, ctx: &Context) { + let link = ctx.link().clone(); + self.animation_frame = Some(request_animation_frame(move |time| { + link.send_message(Msg::AnimateView(time)) + })); + } + + /// Moves the shown view a step towards the target view, for an animation frame at `time`. + fn animate_view(&mut self, ctx: &Context, time: f64) { + let elapsed = match self.last_frame_time { + // never backwards, whatever the times of the frames are + Some(last_frame_time) => (time - last_frame_time).max(0.0), + None => FIRST_FRAME_TIME, + }; + self.last_frame_time = Some(time); + // covering the same share of the remaining way per time is independent of the frame rate + let fraction = 1.0 - (-elapsed / VIEW_ANIMATION_TIME_CONSTANT).exp(); + + let old_scale = self.shown_view.get_zoom_level(); + if self.shown_view.approach(&self.target_view, fraction) { + self.animation_frame = None; + } else { + self.request_animation_frame(ctx); + } + if self.shown_view.get_zoom_level() != old_scale { + self.cluster_points(ctx); + } + } + fn align_tooltip(&self) { if let Some((_, x, y)) = self.tooltip && let Some(el) = self.tooltip_ref.get() @@ -261,6 +331,13 @@ impl MapComp { } } +fn prefers_reduced_motion() -> bool { + matches!( + gloo_utils::window().match_media("(prefers-reduced-motion: reduce)"), + Ok(Some(query)) if query.matches() + ) +} + impl Drop for MapComp { fn drop(&mut self) { gloo_utils::document() @@ -302,7 +379,10 @@ impl yew::Component for MapComp { .unwrap_throw(); let mut this = Self { - zoom, + target_view: zoom, + shown_view: zoom, + animation_frame: None, + last_frame_time: None, pinch_start_scale: 1.0, pinch_last_center: Coordinates { x: 0.0, y: 0.0 }, svg_ref: NodeRef::default(), @@ -334,16 +414,19 @@ impl yew::Component for MapComp { return false; }; let coords = client_to_svg_coords(&svg, x as f64, y as f64); - if !self.zoom.update_zoom(change, coords[0], coords[1]) { + if !self.target_view.update_zoom(change, coords[0], coords[1]) { return false; } - self.cluster_points(ctx); + self.animate_to_target_view(ctx); } Msg::ButtonZoom(change) => { - if !self.zoom.update_zoom(change, width / 2.0, height / 2.0) { + if !self + .target_view + .update_zoom(change, width / 2.0, height / 2.0) + { return false; } - self.cluster_points(ctx); + self.animate_to_target_view(ctx); } Msg::PinchZoom(event) => { let Some(svg) = self.svg_ref.get() else { @@ -358,21 +441,20 @@ impl yew::Component for MapComp { let y = coords[1]; match event.phase { GesturePhase::Start => { - self.pinch_start_scale = self.zoom.get_zoom_level(); + self.pinch_start_scale = self.target_view.get_zoom_level(); self.pinch_last_center = Coordinates { x, y }; } GesturePhase::Update => { - self.zoom + self.target_view .move_pan(x - self.pinch_last_center.x, y - self.pinch_last_center.y); self.pinch_last_center = Coordinates { x, y }; - if self.zoom.update_zoom( + self.target_view.update_zoom( zoom_info::ZoomAction::Scale(self.pinch_start_scale * event.scale), x, y, - ) { - // re-cluster on scale change, like wheel/button zoom - self.cluster_points(ctx); - } + ); + // the map has to stay under the fingers + self.jump_to_target_view(ctx); } GesturePhase::End => return false, } @@ -388,11 +470,13 @@ impl yew::Component for MapComp { if let Some((start_x, start_y)) = self.grab_start { let x = event.x() as f64; let y = event.y() as f64; - self.zoom.move_pan( + self.target_view.move_pan( (x - start_x) / self.fit_scale, (y - start_y) / self.fit_scale, ); self.grab_start = Some((x, y)); + // the map has to stay under the pointer + self.jump_to_target_view(ctx); } } GesturePhase::End => { @@ -431,8 +515,9 @@ impl yew::Component for MapComp { } else { self.info_visible = Some(index); if let Some(cluster) = self.clusters.get(index) { - self.zoom.center_point(cluster.center); + self.target_view.center_point(cluster.center); self.tooltip = None; + self.animate_to_target_view(ctx); } } } @@ -456,6 +541,7 @@ impl yew::Component for MapComp { self.update_info_alignment(ctx); return false; } + Msg::AnimateView(time) => self.animate_view(ctx, time), } true } @@ -468,7 +554,7 @@ impl yew::Component for MapComp { let effective_radius = props.info_point_radius / self.fit_scale; - let zoom_level = self.zoom.get_zoom_level(); + let zoom_level = self.target_view.get_zoom_level(); let is_zoomed = zoom_level != 1.0; let fully_zoomed = zoom_level >= props.max_zoom_level; @@ -484,7 +570,7 @@ impl yew::Component for MapComp { .with_child( Group::new() .with_child(props.map.clone()) - .style("transform", self.zoom.get_transform()), + .style("transform", self.shown_view.get_transform()), ); let overlay = Canvas::new() @@ -529,10 +615,10 @@ impl yew::Component for MapComp { .map(|index| &ctx.props().points[*index]) .collect(); - let center = self.zoom.map_point(cluster.center); + let center = self.shown_view.map_point(cluster.center); // don't render points, tooltips and info boxes that are out of bounds - if self.zoom.is_out_of_bounds(center) { + if self.shown_view.is_out_of_bounds(center) { continue; } @@ -654,16 +740,18 @@ impl yew::Component for MapComp { || props.height != old_props.height || props.max_zoom_level != old_props.max_zoom_level { - self.zoom = ZoomInfo::new(props.width, props.height, props.max_zoom_level); + self.target_view = ZoomInfo::new(props.width, props.height, props.max_zoom_level); + self.shown_view = self.target_view; need_clustering = true; } if props.points != old_props.points { need_clustering = true; if old_props.points.is_empty() && !props.points.is_empty() { - self.zoom.zoom_to_points( + self.target_view.zoom_to_points( ctx.props().points.iter().map(|poi| poi.coordinates), 2.0 * props.info_point_radius, ); + self.shown_view = self.target_view; } } diff --git a/src/widget/charts/map/zoom_info.rs b/src/widget/charts/map/zoom_info.rs index 4daca61..ce2547c 100644 --- a/src/widget/charts/map/zoom_info.rs +++ b/src/widget/charts/map/zoom_info.rs @@ -3,7 +3,17 @@ use crate::widget::charts::map::Coordinates; // ratio per zooming step const ZOOMING_RATIO: f64 = 1.1; +// Scales this close only differ by rounding errors. A step between them can round to no step at +// all, and a pan in proportion to it would never move then. +const SAME_SCALE_TOLERANCE: f64 = 1e-9; + +// how close a view has to be to count as the same, as ratio of the scales and as pan relative to +// the size of the map +const REACHED_SCALE_TOLERANCE: f64 = 0.001; +const REACHED_PAN_TOLERANCE: f64 = 0.0005; + /// Represents a zooming state +#[derive(Clone, Copy, PartialEq)] pub struct ZoomInfo { pan: (f64, f64), user_scale: f64, @@ -150,6 +160,35 @@ impl ZoomInfo { self.zoom_to_point(mid_point, width.max(height * self.width / self.height)); } + /// Moves the view the given fraction of the way towards `target`. + /// + /// Returns true when the target is reached, which also happens if it is nearly reached. + pub fn approach(&mut self, target: &ZoomInfo, fraction: f64) -> bool { + let ratio = target.user_scale / self.user_scale; + let (scale, pan_fraction) = if (ratio - 1.0).abs() < SAME_SCALE_TOLERANCE { + (target.user_scale, fraction) + } else { + // scales are ratios, so steps of the same factor look equally big + let scale = self.user_scale * ratio.powf(fraction); + // panning in proportion to the scale keeps the point in place that a zoom is + // centered on + let pan_fraction = (scale - self.user_scale) / (target.user_scale - self.user_scale); + (scale, pan_fraction) + }; + self.pan.0 += (target.pan.0 - self.pan.0) * pan_fraction; + self.pan.1 += (target.pan.1 - self.pan.1) * pan_fraction; + self.user_scale = scale; + + let pan_tolerance = self.width.max(self.height) * REACHED_PAN_TOLERANCE; + let reached = (target.user_scale / self.user_scale - 1.0).abs() <= REACHED_SCALE_TOLERANCE + && (target.pan.0 - self.pan.0).abs() <= pan_tolerance + && (target.pan.1 - self.pan.1).abs() <= pan_tolerance; + if reached { + *self = *target; + } + reached + } + /// tests if the given point is outside the current view pub fn is_out_of_bounds(&self, coordinates: Coordinates) -> bool { !(0.0..=self.width).contains(&coordinates.x) @@ -187,4 +226,45 @@ mod test { assert_eq!(zoom.get_zoom_level(), 2.0); } + + #[test] + fn test_approach() { + let start = ZoomInfo::new(200.0, 200.0, 100.0); + let mut target = start; + target.update_zoom(ZoomAction::Scale(16.0), 50.0, 150.0); + + let mut view = start; + assert!(!view.approach(&target, 0.5)); + assert_eq!(view.get_zoom_level(), 4.0); + // the point the zoom is centered on stays where it is + let center = Coordinates { x: 50.0, y: 150.0 }; + assert_eq!(view.map_point(center), center); + + assert!(view.approach(&target, 1.0)); + assert!(view == target); + + // close enough counts as reached + let mut view = target; + view.move_pan(-0.05, 0.0); + assert!(view != target); + assert!(view.approach(&target, 0.1)); + assert!(view == target); + } + + #[test] + fn test_approach_rounding_error() { + // zooming in and out again does not always end at exactly the same scale + let mut target = ZoomInfo::new(200.0, 200.0, 100.0); + for _ in 0..7 { + target.update_zoom(ZoomAction::In, 50.0, 50.0); + } + let mut view = target; + target.update_zoom(ZoomAction::In, 150.0, 150.0); + target.update_zoom(ZoomAction::Out, 50.0, 50.0); + assert!(view.get_zoom_level() != target.get_zoom_level()); + + let reached = (0..100).any(|_| view.approach(&target, 0.2)); + assert!(reached); + assert!(view == target); + } } -- 2.47.3