garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

cartopolis-agent · 2026-11-30T19:15:11Z

fix(atlas): a data layer's 'other' is always index 7, grey

A record outside a layer's ranked values carried the index values.len(),
so with four values 'other' took the fifth colour - the orange next to
the second value's - on the map and in the key, and 'other' would change
colour as the layer gained a value. It is MAX_VALUES now, the palette's
grey, and the keys (Layers ▸ Data, the Admin preview) list 'other' only
when a layer has as many values as are kept, since only then can a
record fall outside them.
crates/atlas/src/feeds.rs                          | 54 ++++++++++++++++-
 .../atlas/web/src/components/pages/feeds/feeds.tsx | 10 ++--
 crates/cartopolis/src/systems/gui/feeds.rs         | 67 ++++++++++++++++++----
 crates/geo/src/formats/feeds.rs                    |  3 +-
 4 files changed, 117 insertions(+), 17 deletions(-)

diff --git a/crates/atlas/src/feeds.rs b/crates/atlas/src/feeds.rs
index cc6c5ce9..1ad7f967 100644
--- a/crates/atlas/src/feeds.rs
+++ b/crates/atlas/src/feeds.rs
@@ -912,7 +912,7 @@ pub fn build(def: &Def, rows: &[Row]) -> Built {
                 .values
                 .iter()
                 .position(|x| *x == v)
-                .unwrap_or(built.values.len()) as i64
+                .unwrap_or(MAX_VALUES) as i64
         };
         let mut title = text(&def.title);
         if title.is_empty() {
@@ -1142,6 +1142,58 @@ mod tests {
         assert!(s.cells > 10);
     }
 
+    /// Writes a served tree of three real layers into `$FEEDS_SITE`, for a
+    /// capture against a stand-in data host:
+    /// `FEEDS_SITE=/tmp/site cargo test -p cartopolis_atlas live_stand_in -- --ignored`.
+    #[test]
+    #[ignore = "asks www.triplexl.nl and writes $FEEDS_SITE"]
+    fn live_stand_in() {
+        let Some(site) = std::env::var_os("FEEDS_SITE") else {
+            return;
+        };
+        let data = tempfile::tempdir().unwrap();
+        let feeds = Feeds::new(data.path(), Path::new(&site));
+        let hea = "https://www.triplexl.nl/datasets/archixl/hunzeenaas";
+        let layers = [
+            def(),
+            Def {
+                id: "nzv-gemalen".into(),
+                name: "Gemalen".into(),
+                source: Source {
+                    query: "gemalen-kaart".into(),
+                    ..def().source
+                },
+                colour_by: "functie".into(),
+                fields: vec!["code".into(), "functie".into(), "capaciteit".into()],
+                ..def()
+            },
+            Def {
+                id: "hea-peil".into(),
+                name: "Peil bij stuwen".into(),
+                group: "Waterschap Hunze en Aa's".into(),
+                source: Source {
+                    kind: SourceKind::Triplexl,
+                    dataset: hea.into(),
+                    query: "peil-kaart".into(),
+                },
+                colour_by: "toestand".into(),
+                fields: vec![
+                    "peil".into(),
+                    "streefpeil".into(),
+                    "verschil".into(),
+                    "gemeten".into(),
+                ],
+                credit: "Waterschap Hunze en Aa's open data".into(),
+                ..def()
+            },
+        ];
+        for d in &layers {
+            feeds.save(d).unwrap();
+            let s = feeds.refresh(&d.id).unwrap();
+            eprintln!("{}: {} placed in {} cells", d.id, s.placed, s.cells);
+        }
+    }
+
     #[test]
     fn a_definition_is_checked_before_it_is_kept() {
         let mut d = def();
diff --git a/crates/atlas/web/src/components/pages/feeds/feeds.tsx b/crates/atlas/web/src/components/pages/feeds/feeds.tsx
index 9e19e4ee..e4f0c568 100644
--- a/crates/atlas/web/src/components/pages/feeds/feeds.tsx
+++ b/crates/atlas/web/src/components/pages/feeds/feeds.tsx
@@ -217,10 +217,12 @@ class NewFeed extends MithrilComponent<{onDone: (saved: boolean) => void}> {
                                         {v}
                                     </span>
                                 ))}
-                                <span>
-                                    <i style={`background: ${colour(p.values.length)}`} />
-                                    other
-                                </span>
+                                {p.values.length >= 7 && (
+                                    <span>
+                                        <i style={`background: ${colour(7)}`} />
+                                        other
+                                    </span>
+                                )}
                             </div>
                         )}
                     </Card>
diff --git a/crates/cartopolis/src/systems/gui/feeds.rs b/crates/cartopolis/src/systems/gui/feeds.rs
index 288d3d2e..7db6c4f0 100644
--- a/crates/cartopolis/src/systems/gui/feeds.rs
+++ b/crates/cartopolis/src/systems/gui/feeds.rs
@@ -28,7 +28,7 @@ use bevy::prelude::*;
 use bevy::tasks::IoTaskPool;
 use big_space::prelude::GridCell;
 use cartopolis_core::world::{lat_lng_to_tile, tile_to_meters};
-use cartopolis_geo::formats::feeds::{Feed, Index, Record};
+use cartopolis_geo::formats::feeds::{Feed, Index, Record, MAX_VALUES};
 use cartopolis_geo::formats::CACHE_ZOOM;
 use web_time::Instant;
 
@@ -83,8 +83,8 @@ pub fn colour(value: i64) -> theme::Rgba8 {
     }
 }
 
-/// A layer's key: its values with their colours, and "other" when some
-/// records fall outside them.
+/// A layer's key: its values with their colours, and "other" when there can
+/// be records outside them (atlas keeps [`MAX_VALUES`] at most).
 #[must_use]
 pub fn key(feed: &Feed) -> Vec<(String, theme::Rgba8)> {
     let mut out: Vec<(String, theme::Rgba8)> = feed
@@ -93,8 +93,8 @@ pub fn key(feed: &Feed) -> Vec<(String, theme::Rgba8)> {
         .enumerate()
         .map(|(i, v)| (v.clone(), colour(i as i64)))
         .collect();
-    if !out.is_empty() {
-        out.push(("other".into(), colour(feed.values.len() as i64)));
+    if feed.values.len() >= MAX_VALUES {
+        out.push(("other".into(), colour(MAX_VALUES as i64)));
     }
     out
 }
@@ -155,6 +155,12 @@ pub struct Feeds {
     /// The key of the dot the library's tap landed on, opened next frame by
     /// [`place_feeds`].
     pub lib_tapped: Option<String>,
+    /// A scripted capture (`--ui feeds`): turn every published layer on once
+    /// the index is in.
+    pub script_all: bool,
+    /// A scripted capture (`--ui feedcard`): open the card of the dot nearest
+    /// the middle of the view, once there is one.
+    pub open_nearest: bool,
 }
 
 impl Feeds {
@@ -177,6 +183,16 @@ impl Feeds {
     }
 }
 
+impl crate::systems::stream_watch::StreamBusy for Feeds {
+    const NAME: &'static str = "data_layers_feeds";
+
+    /// Reading the index, a manifest, or a cell. Nothing is asked for with
+    /// every layer off, so then it is never busy.
+    fn stream_busy(&self) -> bool {
+        self.index_loading || !self.in_flight.is_empty() || self.manifests.values().any(|m| m.loading)
+    }
+}
+
 fn due(read: Option<Instant>, failed: Option<Instant>, ttl: Duration) -> bool {
     if failed.is_some_and(|t| t.elapsed() < RETRY_AFTER) {
         return false;
@@ -234,7 +250,12 @@ async fn read_cell(id: &str, (cx, cy): (i64, i64), stamp: u64) -> Option<Vec<Rec
         .map(|c| c.records)
 }
 
-fn spawn(inbox: &Arc<Mutex<Vec<Arrival>>>, work: impl std::future::Future<Output = Arrival> + Send + 'static) {
+/// Read in the background and leave the answer in the inbox. Conditionally
+/// `Send`: a browser's fetch future is not.
+fn spawn(
+    inbox: &Arc<Mutex<Vec<Arrival>>>,
+    work: impl bevy::tasks::ConditionalSendFuture<Output = Arrival> + 'static,
+) {
     let inbox = inbox.clone();
     IoTaskPool::get()
         .spawn(async move {
@@ -263,7 +284,7 @@ fn ring_radius(altitude_m: f64) -> i64 {
 #[allow(clippy::too_many_arguments)]
 pub fn drive_feeds(
     mut feeds: ResMut<Feeds>,
-    dl: Res<DataLayers>,
+    mut dl: ResMut<DataLayers>,
     right_panel: Res<RightPanel>,
     stream: Res<MapStream>,
     camera: AnchoredCamera,
@@ -309,6 +330,17 @@ pub fn drive_feeds(
         }
     }
 
+    if feeds.script_all {
+        let off: Vec<String> = feeds
+            .list()
+            .iter()
+            .filter(|f| !dl.feeds.get(&f.id).copied().unwrap_or(false))
+            .map(|f| f.id.clone())
+            .collect();
+        for id in off {
+            dl.feeds.insert(id, true);
+        }
+    }
     let on: Vec<String> = dl
         .feeds
         .iter()
@@ -316,7 +348,7 @@ pub fn drive_feeds(
         .map(|(id, _)| id.clone())
         .collect();
     let browsing = right_panel.is(RightPanel::Layers) && dl.category == LayerCategory::Data;
-    if (browsing || !on.is_empty())
+    if (browsing || feeds.script_all || !on.is_empty())
         && !feeds.index_loading
         && due(feeds.index_read_at, feeds.index_failed_at, INDEX_TTL)
     {
@@ -525,6 +557,15 @@ pub fn place_feeds(
     {
         feeds.card = Some(card);
     }
+    if feeds.open_nearest && feeds.card.is_none() {
+        let middle = metrics.viewport_pts() / 2.0;
+        if let Some((_, card)) = marks
+            .iter()
+            .min_by(|a, b| a.0.at.distance(middle).total_cmp(&b.0.at.distance(middle)))
+        {
+            feeds.card = Some(card.clone());
+        }
+    }
     // A card whose layer was turned off goes with it.
     if feeds
         .card
@@ -609,9 +650,13 @@ mod tests {
         assert_eq!(colour(0), PALETTE[0]);
         assert_eq!(colour(99), PALETTE[7]);
         assert_eq!(colour(-1), PALETTE[0]);
-        let k = key(&feed());
-        assert_eq!(k.len(), 3);
-        assert_eq!(k[2].0, "other");
+        // Two values: nothing can be "other".
+        assert_eq!(key(&feed()).len(), 2);
+        let mut full = feed();
+        full.values = (0..MAX_VALUES).map(|i| format!("v{i}")).collect();
+        let k = key(&full);
+        assert_eq!(k.len(), MAX_VALUES + 1);
+        assert_eq!(k[MAX_VALUES], ("other".to_string(), PALETTE[7]));
     }
 
     #[test]
diff --git a/crates/geo/src/formats/feeds.rs b/crates/geo/src/formats/feeds.rs
index 18024ad0..395e431d 100644
--- a/crates/geo/src/formats/feeds.rs
+++ b/crates/geo/src/formats/feeds.rs
@@ -48,7 +48,8 @@ pub struct Feed {
     pub records: u64,
     /// The values of `colour_by`, most common first, at most
     /// [`MAX_VALUES`]; a record whose value is not among them has the index
-    /// `values.len()`, "other".
+    /// [`MAX_VALUES`], "other" — the same index whatever `values` holds, so
+    /// "other" keeps its colour when a layer gains a value.
     #[serde(default)]
     pub values: Vec<String>,
     /// Where the data comes from, for "via …" — `"TripleXL"`.