From: Dominik Csapak <d.csapak@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [PATCH yew-widget-toolkit 17/38] widget: charts: world map: split the map into one path per region
Date: Fri, 27 Nov 2026 17:12:14 +0100 [thread overview]
Message-ID: <20261127161241.3713494-18-d.csapak@proxmox.com> (raw)
In-Reply-To: <20261127161241.3713494-1-d.csapak@proxmox.com>
instead of drawing all areas and all lines of a feature with one path
each.
A browser draws in tiles, and for each tile it has to go through the
whole path, even if only a small part of it is visible there. With the
tens of thousands of points of our world map, that made panning and
zooming slow, and also every other change on the map, since the map
below is drawn again then too. Paths that are completely outside of
what has to be drawn are skipped cheaply though, so collect the shapes
in one path per region (a twelfth of the width of the map).
A hole only cuts out of the shapes of its own path, so all rings of a
polygon go into the path of the region its outline is in.
The shapes are rendered by a component of their own that compares them
by reference. The Map renders for every step of a pan or zoom, and yew
would compare all of the paths each time otherwise.
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
src/widget/charts/world_map.rs | 261 +++++++++++++++++++++++++--------
1 file changed, 203 insertions(+), 58 deletions(-)
diff --git a/src/widget/charts/world_map.rs b/src/widget/charts/world_map.rs
index c5a68e4..a73d279 100644
--- a/src/widget/charts/world_map.rs
+++ b/src/widget/charts/world_map.rs
@@ -1,9 +1,12 @@
+use std::collections::BTreeMap;
+use std::fmt::Write;
use std::marker::PhantomData;
use std::rc::Rc;
use derivative::Derivative;
use geojson::{Feature, GeoJson, Geometry};
use yew::prelude::*;
+use yew::virtual_dom::{VComp, VNode};
use crate::prelude::*;
use crate::widget::canvas::{Group, Path};
@@ -19,6 +22,10 @@ const WIDTH: f64 = 3600.0; // use 10 units per longitude
const WIDTH_RATIO: f64 = 1.65;
const HEIGHT: f64 = WIDTH / WIDTH_RATIO;
+// The side length of the regions that the shapes of the map are split into. A browser skips the
+// paths outside of the area it has to draw, which is much cheaper than clipping one huge path.
+const REGION_SIZE: f64 = WIDTH / 12.0;
+
/// Represents a Location in the world using the geographic coordinate system.
#[derive(Clone, Copy, PartialEq)]
pub struct Location {
@@ -113,29 +120,29 @@ impl<T: MapPointData> WorldMap<T> {
}
pub struct WorldMapComp<T: MapPointData> {
- shapes: Vec<FeatureShapes>,
+ shapes: Rc<Vec<FeatureShapes>>,
_phantom_data: PhantomData<T>,
}
-/// The shapes of a GeoJSON feature as SVG path commands.
+/// The shapes of a GeoJSON feature as SVG path commands, with one path per region of the map.
struct FeatureShapes {
/// The `kind` property of the feature, so that a style sheet can tell the features apart.
kind: Option<AttrValue>,
/// The polygons of the feature.
- areas: AttrValue,
+ areas: Vec<AttrValue>,
/// The line strings of the feature, which are not filled.
- lines: AttrValue,
+ lines: Vec<AttrValue>,
}
impl FeatureShapes {
fn new(kind: Option<&str>, geometry: &Geometry) -> Self {
- let mut areas = Vec::new();
- let mut lines = Vec::new();
- parse_geometry(geometry, &mut areas, &mut lines);
+ let mut areas = RegionPaths::default();
+ let mut lines = RegionPaths::default();
+ add_geometry(geometry, &mut areas, &mut lines);
Self {
kind: kind.map(|kind| kind.to_owned().into()),
- areas: areas.join(" ").into(),
- lines: lines.join(" ").into(),
+ areas: areas.into_paths(),
+ lines: lines.into_paths(),
}
}
@@ -145,6 +152,87 @@ impl FeatureShapes {
}
}
+/// Collects path commands, grouped by the region of the map they draw in.
+#[derive(Default)]
+struct RegionPaths(BTreeMap<(i32, i32), String>);
+
+impl RegionPaths {
+ /// Adds lines to the path of the region that the first one is in.
+ ///
+ /// The rings of a polygon have to stay together that way, since a hole only cuts out of the
+ /// shapes of its own path.
+ fn add(&mut self, lines: &[Vec<Vec<f64>>], close: bool) {
+ let lines: Vec<Vec<Coordinates>> = lines
+ .iter()
+ .map(|line| {
+ line.iter()
+ .filter(|position| position.len() >= 2)
+ .map(|position| project(Location::new(position[0], position[1])))
+ .collect()
+ })
+ .collect();
+ let Some(first) = lines.iter().find(|line| !line.is_empty()) else {
+ return;
+ };
+
+ let (mut min, mut max) = (first[0], first[0]);
+ for point in first {
+ min = Coordinates {
+ x: min.x.min(point.x),
+ y: min.y.min(point.y),
+ };
+ max = Coordinates {
+ x: max.x.max(point.x),
+ y: max.y.max(point.y),
+ };
+ }
+ let region = (
+ ((min.x + max.x) / 2.0 / REGION_SIZE) as i32,
+ ((min.y + max.y) / 2.0 / REGION_SIZE) as i32,
+ );
+
+ let path = self.0.entry(region).or_default();
+ for line in lines.iter().filter(|line| !line.is_empty()) {
+ let mut command = 'M';
+ for point in line {
+ // writing to a String never fails
+ let _ = write!(path, "{command}{:.2},{:.2}", point.x, point.y);
+ command = 'L';
+ }
+ if close {
+ path.push('Z');
+ }
+ }
+ }
+
+ fn into_paths(self) -> Vec<AttrValue> {
+ self.0.into_values().map(AttrValue::from).collect()
+ }
+}
+
+fn add_geometry(geometry: &Geometry, areas: &mut RegionPaths, lines: &mut RegionPaths) {
+ match &geometry.value {
+ geojson::Value::Polygon(rings) => areas.add(rings, true),
+ geojson::Value::MultiPolygon(polygons) => {
+ for rings in polygons {
+ areas.add(rings, true);
+ }
+ }
+ geojson::Value::LineString(line) => lines.add(std::slice::from_ref(line), false),
+ geojson::Value::MultiLineString(multi_line) => {
+ for line in multi_line {
+ lines.add(std::slice::from_ref(line), false);
+ }
+ }
+ geojson::Value::GeometryCollection(geometries) => {
+ for geometry in geometries {
+ add_geometry(geometry, areas, lines);
+ }
+ }
+ geojson::Value::Point(_) | geojson::Value::MultiPoint(_) => {}
+ }
+}
+
fn calculate_shapes(geojson: &GeoJson) -> Vec<FeatureShapes> {
match geojson {
GeoJson::Geometry(geometry) => vec![FeatureShapes::new(None, geometry)],
@@ -156,29 +244,74 @@ fn calculate_shapes(geojson: &GeoJson) -> Vec<FeatureShapes> {
}
}
+/// The background of a [WorldMap].
+///
+/// The shapes are big, and a [Map] renders a lot while it is panned and zoomed. Comparing them
+/// by reference lets yew skip them then.
+#[derive(Properties, Clone, Derivative)]
+#[derivative(PartialEq)]
+struct WorldMapShapes {
+ #[derivative(PartialEq(compare_with = "Rc::ptr_eq"))]
+ shapes: Rc<Vec<FeatureShapes>>,
+}
+
+struct WorldMapShapesComp;
+
+impl Component for WorldMapShapesComp {
+ type Message = ();
+ type Properties = WorldMapShapes;
+
+ fn create(_ctx: &Context<Self>) -> Self {
+ Self
+ }
+
+ fn view(&self, ctx: &Context<Self>) -> Html {
+ let props = ctx.props();
+ let features = props.shapes.iter().map(|feature| {
+ Group::new()
+ .class("pwt-world-map-feature")
+ .attribute("data-kind", feature.kind.clone())
+ .children(
+ feature
+ .areas
+ .iter()
+ .map(|path| Path::new().d(path.clone()).into()),
+ )
+ .children(
+ feature
+ .lines
+ .iter()
+ .map(|path| Path::new().d(path.clone()).fill("none").into()),
+ )
+ .into()
+ });
+
+ Group::new().children(features).into()
+ }
+}
+
+impl From<WorldMapShapes> for VNode {
+ fn from(val: WorldMapShapes) -> Self {
+ VComp::new::<WorldMapShapesComp>(Rc::new(val), None).into()
+ }
+}
+
impl<T: MapPointData + 'static> yew::Component for WorldMapComp<T> {
type Message = ();
type Properties = WorldMap<T>;
fn create(ctx: &Context<Self>) -> Self {
Self {
- shapes: calculate_shapes(&ctx.props().map_data),
+ shapes: Rc::new(calculate_shapes(&ctx.props().map_data)),
_phantom_data: PhantomData::<T>,
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let props = ctx.props();
- let features = self.shapes.iter().map(|feature| {
- Group::new()
- .class("pwt-world-map-feature")
- .attribute("data-kind", feature.kind.clone())
- .with_child(Path::new().d(feature.areas.clone()))
- .with_child(Path::new().d(feature.lines.clone()).fill("none"))
- .into()
- });
+ let shapes = Rc::clone(&self.shapes);
- Map::new(Group::new().children(features))
+ Map::new(WorldMapShapes { shapes })
.with_std_props(&props.std_props)
.listeners(&props.listeners)
.class("pwt-world-map")
@@ -193,7 +326,7 @@ impl<T: MapPointData + 'static> yew::Component for WorldMapComp<T> {
fn changed(&mut self, ctx: &Context<Self>, old_props: &Self::Properties) -> bool {
let props = ctx.props();
if !Rc::ptr_eq(&props.map_data, &old_props.map_data) {
- self.shapes = calculate_shapes(&props.map_data);
+ self.shapes = Rc::new(calculate_shapes(&props.map_data));
}
true
}
@@ -208,46 +341,58 @@ fn project(location: Location) -> Coordinates {
}
}
-fn ring_to_path(coordinates: &[Vec<f64>]) -> String {
- let mut path = line_to_path(coordinates);
- path.push('Z');
- path
-}
+#[cfg(test)]
+mod test {
+ use geojson::{Geometry, Value};
-fn line_to_path(coordinates: &[Vec<f64>]) -> String {
- let mut path = String::new();
- let mut prefix = "M";
- for list in coordinates {
- if list.len() < 2 {
- continue;
- }
- let Coordinates { x, y } = project(Location::new(list[0], list[1]));
- path.push_str(&format!("{prefix}{:.2},{:.2}", x, y));
- prefix = "L";
+ use super::FeatureShapes;
+
+ // a square with the given corner and side length in degrees
+ fn square(longitude: f64, latitude: f64, size: f64) -> Vec<Vec<f64>> {
+ vec![
+ vec![longitude, latitude],
+ vec![longitude + size, latitude],
+ vec![longitude + size, latitude + size],
+ vec![longitude, latitude + size],
+ vec![longitude, latitude],
+ ]
}
- path
-}
-fn parse_geometry(geometry: &Geometry, areas: &mut Vec<String>, lines: &mut Vec<String>) {
- match &geometry.value {
- geojson::Value::Polygon(polygon) => {
- areas.append(&mut polygon.iter().map(|ring| ring_to_path(ring)).collect());
- }
- geojson::Value::MultiPolygon(items) => {
- for poly in items {
- areas.append(&mut poly.iter().map(|ring| ring_to_path(ring)).collect())
- }
- }
- geojson::Value::LineString(line) => lines.push(line_to_path(line)),
- geojson::Value::MultiLineString(line) => {
- lines.append(&mut line.iter().map(|ring| line_to_path(ring)).collect())
- }
- geojson::Value::GeometryCollection(items) => {
- for geom in items {
- parse_geometry(geom, areas, lines);
- }
- }
- geojson::Value::Point(_) => {}
- geojson::Value::MultiPoint(_) => {}
+ fn shapes(value: Value) -> (Vec<String>, Vec<String>) {
+ let shapes = FeatureShapes::new(None, &Geometry::new(value));
+ let strings = |paths: &[yew::AttrValue]| -> Vec<String> {
+ paths.iter().map(|path| path.to_string()).collect()
+ };
+ (strings(&shapes.areas), strings(&shapes.lines))
+ }
+
+ #[test]
+ fn test_split_by_region() {
+ let europe = square(10.0, 40.0, 10.0);
+ let australia = square(130.0, -30.0, 10.0);
+ let europe_path =
+ "M1900.00,606.06L2000.00,606.06L2000.00,484.85L1900.00,484.85L1900.00,606.06";
+
+ // far apart, so they end up in a path each
+ let polygons = vec![vec![europe.clone()], vec![australia.clone()]];
+ let (areas, lines) = shapes(Value::MultiPolygon(polygons));
+ assert_eq!(areas.len(), 2);
+ assert_eq!(areas[0], format!("{europe_path}Z"));
+ assert!(lines.is_empty());
+
+ // a hole has to be in the path of its polygon, even if it is in another region
+ let hole = square(-170.0, -80.0, 1.0);
+ let polygons = vec![vec![europe.clone(), hole], vec![australia.clone()]];
+ let (with_hole, _) = shapes(Value::MultiPolygon(polygons));
+ assert_eq!(with_hole.len(), 2);
+ assert!(with_hole[0].starts_with(&areas[0]));
+ assert!(with_hole[0].len() > areas[0].len() && with_hole[0].ends_with('Z'));
+ assert_eq!(with_hole[1], areas[1]);
+
+ // lines are not closed and each one is on its own
+ let (areas, lines) = shapes(Value::MultiLineString(vec![europe, australia]));
+ assert!(areas.is_empty());
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0], europe_path);
}
}
--
2.47.3
next prev parent reply other threads:[~2026-11-27 16:14 UTC|newest]
Thread overview: 41+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-27 16:11 [PATCH datacenter-manager/proxmox-geojson-data/yew-widget-toolkit/yew-widget-toolkit-assets 00/38] map: show running remote migrations and rework the world map Dominik Csapak
2026-11-27 16:11 ` [PATCH proxmox-geojson-data 01/38] generate the borders between countries as lines without duplicates Dominik Csapak
2026-11-28 19:46 ` Thomas Lamprecht
2026-11-27 16:11 ` [PATCH yew-widget-toolkit-assets 02/38] charts: world map: add classes for the map and its features Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 03/38] charts: map: stack the map and its points in two layers Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 04/38] charts: map: show locations as a dot with a halo Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 05/38] charts: map: show the buttons as one panel Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 06/38] charts: map: add classes for connections Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 07/38] charts: world map: add class for the shade of the night Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 08/38] charts: map: add classes for the shares and the ping of a location Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 09/38] charts: map: add class for the shadow of a connection Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 10/38] charts: map: add class for the labels of locations Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit-assets 11/38] charts: map: add class for the status of a map Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 12/38] widget: charts: map: factor out the radius factor of a cluster Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 13/38] widget: charts: map: close the info card with the first click after a drag Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 14/38] widget: menu: open the menu of a button above it if there is no room below Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 15/38] widget: charts: world map: compare the map data by reference Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 16/38] widget: charts: world map: draw polygons as areas and line strings as lines Dominik Csapak
2026-11-27 16:12 ` Dominik Csapak [this message]
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 18/38] widget: charts: map: draw the points in an svg element of their own Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 19/38] widget: charts: map: don't render if the pointer moves over the same point Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 20/38] widget: charts: map: keep the tooltip on its points when clustering anew Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 21/38] widget: charts: world map: add a graticule Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 22/38] widget: charts: map: animate changes of the view Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 23/38] widget: charts: map: draw points as a dot with a halo and their count Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 24/38] widget: charts: map: let the style sheet color the zoom buttons Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 25/38] widget: charts: map: allow drawing connections between points Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 26/38] widget: charts: map: allow additional buttons in the panel Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 27/38] widget: charts: world map: allow shading the night Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 28/38] widget: charts: map: add helpers to show shares and to ping a point Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 29/38] widget: charts: map: draw a shadow below connections Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 30/38] widget: charts: map: allow showing labels next to the points Dominik Csapak
2026-11-27 16:12 ` [PATCH yew-widget-toolkit 31/38] widget: charts: map: allow showing a status in a corner of the map Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 32/38] ui: views: map: only load and parse the world map once Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 33/38] ui: views: map: only format the titles once when sorting Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 34/38] ui: views: map: show running remote migrations Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 35/38] ui: views: map: shade the night on the map Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 36/38] ui: views: map: show the states of a cluster and ping problems Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 37/38] ui: views: map: show the names of the locations Dominik Csapak
2026-11-27 16:12 ` [PATCH datacenter-manager 38/38] ui: views: map: show a summary of the remotes and migrations Dominik Csapak
2026-11-28 23:48 ` [PATCH datacenter-manager/proxmox-geojson-data/yew-widget-toolkit/yew-widget-toolkit-assets 00/38] map: show running remote migrations and rework the world map Thomas Lamprecht
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=20261127161241.3713494-18-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