From a79f26398e006dcb50425a0abbf479e2d27c2a1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 23:17:16 -0500 Subject: [PATCH 1/9] feat(symbology): group several Unique Values classes into one legend entry (#3308) --- crates/engine/command-surface.txt | 1 + crates/engine/src/cmd/layer.rs | 68 +++++++++++--- crates/engine/src/tests.rs | 76 ++++++++++++++++ crates/map/src/symbology.rs | 144 ++++++++++++++++++++++++++++++ crates/ui-egui/src/panes.rs | 80 ++++++++++++++++- docs/user-guide/cartography.md | 10 +++ 6 files changed, 368 insertions(+), 11 deletions(-) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index b257a8c359..7b617b07a6 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -245,6 +245,7 @@ layer.fields layer? layer.fillLayers layer? value? index? other? fills layer.geocode table? layer? address provider? url? name? places? layer.group layer? group before? +layer.groupClasses layer? values label? layer.indent layer? layer.invertRamp layer? layer.lightShadow layer? lighting? shadows? diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..4564ba1b52 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -229,6 +229,11 @@ pub fn commands() -> Vec { .params( r##"{"layer"?, "value"?: text|number (a Unique Values class), "index"?: number (a Graduated Colors class, 0 = the lowest), "other"?: true (Unique Values' ), "color"?: "#RRGGBB" (preserves polygon translucency, minimum alpha 150)|"#RRGGBBAA" (sets alpha exactly), "outline"?: "#RRGGBB"|"#RRGGBBAA", "label"?: text (the legend label; "" goes back to the value or range)}"##, ), + C::new("layer.groupClasses", "Group Classes", "Style › Drawing", group_classes).roles(&[]).effects(crate::policy::Effects::NONE) + .when(need_feature_layer) + .params( + r##"{"layer"?, "values": [text|number, …] (two or more Unique Values classes; they take the symbol, strokes and fills of the first of them in the class list's order, and one label, so a legend lists them as one entry), "label"?: text (default: the values joined with ", ")}"##, + ), C::new("layer.color", "Symbol Color", "Style › Drawing", |s, p| { let hex = s_req(p, "color")?; let c = Rgba::from_hex(hex).ok_or("color must be #RRGGBB or #RRGGBBAA")?; @@ -8365,6 +8370,20 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { Ok(out) } +/// A Unique Values class's key, as a command's parameter names it. +fn class_value(v: &Value) -> Result { + Ok(match v { + Value::String(t) => t.clone(), + // As the data prints it (the classes' own keys): `1000.0` is the class "1000". + Value::Number(n) => match (n.as_i64(), n.as_f64()) { + (Some(i), _) => rustgis_data::Value::Int(i).to_string(), + (None, Some(x)) => rustgis_data::Value::Float(x).to_string(), + _ => n.to_string(), + }, + _ => return Err("value must be a text or a number".into()), + }) +} + /// The class `value`, `index` or `other: true` name in a command's parameters, or `None` when /// none does. fn class_ref(p: &Value) -> Result, String> { @@ -8375,16 +8394,7 @@ fn class_ref(p: &Value) -> Result, String> { }; Ok(Some(match (p.get("value"), index, other) { (None, None, false) => return Ok(None), - (Some(v), None, false) => ClassRef::Value(match v { - Value::String(t) => t.clone(), - // As the data prints it (the classes' own keys): `1000.0` is the class "1000". - Value::Number(n) => match (n.as_i64(), n.as_f64()) { - (Some(i), _) => rustgis_data::Value::Int(i).to_string(), - (None, Some(x)) => rustgis_data::Value::Float(x).to_string(), - _ => n.to_string(), - }, - _ => return Err("value must be a text or a number".into()), - }), + (Some(v), None, false) => ClassRef::Value(class_value(v)?), (None, Some(i), false) => ClassRef::Index(usize::try_from(i).map_err(|_| "index is too large")?), (None, None, true) => ClassRef::Other, _ => return Err("name one class: value (Unique Values), index (Graduated Colors) or other: true".into()), @@ -8425,6 +8435,44 @@ fn class_style(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"label": e.label, "color": e.symbol.fill.hex(), "outline": e.symbol.stroke.hex()})) } +/// `layer.groupClasses`: several Unique Values classes listed as one legend entry (#3308). +fn group_classes(s: &mut Session, p: &Value) -> CmdResult { + let values = p.get("values").and_then(Value::as_array).ok_or("values is a list of two or more Unique Values classes")?; + let values = values.iter().map(class_value).collect::, _>>()?; + let label = match p.get("label") { + None => None, + Some(Value::String(t)) => Some(t.as_str()), + Some(_) => return Err("label must be a text (an empty one joins the values)".into()), + }; + let id = s.layer_id(p)?; + let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; + let group = l.renderer.group_classes(&values, label)?; + // What No Fill hid follows the group too, or Restore Fill would set the classes apart. + let first = ClassRef::Value(group.first.clone()); + let at = symbol_position(&l.renderer, &first); + let mut now = 0; + l.renderer.map_symbols(|_| now += 1); + if let Some(hidden) = &mut l.hidden_fills { + let others: std::collections::HashSet<&str> = group.values.iter().filter(|v| **v != group.first).map(String::as_str).collect(); + hidden.class_fills.retain(|(c, _)| !matches!(c, ClassRef::Value(v) if others.contains(v.as_str()))); + if let Some(fills) = hidden.class_fills.iter().find(|(c, _)| *c == first).map(|(_, f)| f.clone()) { + let copies = group.values.iter().filter(|v| others.contains(v.as_str())); + hidden.class_fills.extend(copies.map(|v| (ClassRef::Value(v.clone()), fills.clone()))); + } + // The saved opacities are by symbol, while they still match them, as Restore Fill needs. + if let (Renderer::Unique { classes, .. }, true) = (&l.renderer, hidden.alphas.len() == now) + && let Some(a) = at.and_then(|i| hidden.alphas.get(i).copied()) + { + for ((k, _), alpha) in classes.iter().zip(&mut hidden.alphas) { + if others.contains(k.as_str()) { + *alpha = a; + } + } + } + } + Ok(json!({"label": group.label, "values": group.values})) +} + /// These loaders interpret `layer` inside an external file/database, never as a map layer. /// The selector remains frozen with its path/address, including the loader's empty default. pub(crate) fn external_dataset_selector(command: &str) -> bool { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1fb37c4ae3..570889cab6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12554,6 +12554,82 @@ fn layer_class_style_edits_one_class() { assert!(s.run("layer.classStyle", &json!({"layer": "Countries", "index": 3, "label": "x"})).is_err()); } +/// `layer.groupClasses`: several Unique Values classes become one legend entry (#3308). +#[test] +fn layer_group_classes_makes_one_legend_entry() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let renderer = |s: &Session| s.map().layer_by_name("Countries").unwrap().renderer.clone(); + let before = renderer(&s); + let rows = before.legend().len(); + let r = s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["Asia", "Africa"]})).unwrap(); + assert_eq!(r, json!({"label": "Asia, Africa", "values": ["Asia", "Africa"]})); + assert_eq!(renderer(&s).legend().len(), rows - 1); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(renderer(&s), before); + s.run("edit.redo", &Value::Null).unwrap(); + assert_eq!(renderer(&s).legend().len(), rows - 1); + // The group is the classes' own looks and labels: a saved project keeps it. + let saved = serde_json::to_string(s.map()).unwrap(); + let opened: rustgis_map::Map = serde_json::from_str(&saved).unwrap(); + assert_eq!(opened.layer_by_name("Countries").unwrap().renderer, renderer(&s)); + // Refused, with nothing changed. + let grouped = renderer(&s); + for bad in [ + json!({"layer": "Countries"}), + json!({"layer": "Countries", "values": "Asia"}), + json!({"layer": "Countries", "values": []}), + json!({"layer": "Countries", "values": ["Europe"]}), + json!({"layer": "Countries", "values": ["Europe", "Atlantis"]}), + json!({"layer": "Countries", "values": ["Europe", true]}), + json!({"layer": "Countries", "values": ["Europe", "Oceania"], "label": 5}), + ] { + assert!(s.run("layer.groupClasses", &bad).is_err(), "{bad}"); + } + assert_eq!(renderer(&s), grouped); + // Numbers name their classes as the data prints them. + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "pop_est"})).unwrap(); + let rustgis_map::Renderer::Unique { classes, .. } = renderer(&s) else { panic!("unique renderer expected") }; + let whole: Vec = classes.iter().filter_map(|(k, _)| k.parse().ok()).take(2).collect(); + let r = s.run("layer.groupClasses", &json!({"layer": "Countries", "values": [whole[0], whole[1] as f64], "label": "Few"})).unwrap(); + assert_eq!(r["values"], json!([whole[0].to_string(), whole[1].to_string()])); + // Only Unique Values has classes to group. + s.run("layer.symbology", &json!({"layer": "Countries", "type": "graduated", "field": "pop_est", "classes": 3})).unwrap(); + assert!(s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["a", "b"]})).is_err()); +} + +/// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. +#[test] +fn layer_group_classes_under_no_fill_restores_one_opacity() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let id = s.map().layer_by_name("Countries").unwrap().id; + let first = |s: &Session| { + let r = &s.map().layer(id).unwrap().renderer; + r.class_entries().into_iter().find(|e| e.label == "AA").unwrap().symbol.fill + }; + s.run("layer.classStyle", &json!({"layer": id, "value": "Africa", "color": "#12345640"})).unwrap(); + // Fills of their own, hidden by No Fill: the group takes the first one's (none for Africa). + s.run("layer.fillLayers", &json!({"layer": id, "value": "Asia", "fills": [{"color": "#FF0000"}]})).unwrap(); + s.run("layer.noFill", &json!({"layer": id})).unwrap(); + s.run("layer.groupClasses", &json!({"layer": id, "values": ["Africa", "Asia"], "label": "AA"})).unwrap(); + s.run("layer.restoreFill", &json!({"layer": id})).unwrap(); + assert_eq!(first(&s).a(), 0x40); + let rows = |s: &Session, label: &str| { + let legend = s.map().layer(id).unwrap().renderer.legend(); + legend.into_iter().filter(|e| e.label == label).collect::>() + }; + assert_eq!(rows(&s, "AA").len(), 1); + assert!(rows(&s, "AA")[0].fills.is_empty()); + // And a first class with fills gives them to the rest. + s.run("layer.fillLayers", &json!({"layer": id, "value": "Africa", "fills": [{"color": "#00FF00"}]})).unwrap(); + s.run("layer.noFill", &json!({"layer": id})).unwrap(); + s.run("layer.groupClasses", &json!({"layer": id, "values": ["Africa", "Europe"], "label": "AE"})).unwrap(); + s.run("layer.restoreFill", &json!({"layer": id})).unwrap(); + assert_eq!(rows(&s, "AE").len(), 1); + assert_eq!(rows(&s, "AE")[0].fills.len(), 1); +} + /// Read classes by their command identity, not their sorted legend position. fn class_style_rows(s: &Session, layer: &str) -> Vec<(Value, rustgis_map::Symbol)> { match &s.map().layer_by_name(layer).unwrap().renderer { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 26052011d6..9dd005210c 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1125,6 +1125,17 @@ fn class_mismatch(r: &Renderer) -> String { } } +/// What [`Renderer::group_classes`] made. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassGroup { + /// The label every class of the group has now. + pub label: String, + /// Their values, each once, in the order given. + pub values: Vec, + /// The value whose look the others took: the first of them in [`Renderer::class_order`]. + pub first: String, +} + /// What [`Renderer::set_class_style`] changes in a class; `None` leaves that part as it is. #[derive(Clone, Debug, Default, PartialEq)] pub struct ClassStyle { @@ -2242,6 +2253,52 @@ impl Renderer { self.class_entries().into_iter().nth(row).ok_or_else(|| "the class has no legend row".into()) } + /// Gives the Unique Values classes named one look (the symbol, stacked strokes and fills of + /// the first of them in [`Renderer::class_order`]) and one label, so a legend lists them as + /// one entry (#3308). With no `label`, or an empty one, it is their values joined with ", ". + /// Each stays its own class. Refused with nothing changed unless two or more different values + /// are named and each is a class. + pub fn group_classes(&mut self, values: &[String], label: Option<&str>) -> Result { + let order = self.class_order(); + let Renderer::Unique { classes, class_labels, class_strokes, class_fills, .. } = self else { + return Err("only Unique Values classes can be grouped".into()); + }; + let keys: std::collections::HashSet<&str> = classes.iter().map(|(k, _)| k.as_str()).collect(); + let mut named = std::collections::HashSet::new(); + let mut list = Vec::new(); + for v in values { + if !keys.contains(v.as_str()) { + return Err(format!("no class with the value '{v}'")); + } + if named.insert(v.as_str()) { + list.push(v.clone()); + } + } + let first = order.iter().filter_map(|&i| classes.get(i)).find(|(k, _)| named.contains(k.as_str())); + let Some((first, symbol)) = first.filter(|_| list.len() > 1).cloned() else { + return Err("name two or more different classes to group".into()); + }; + let label = label.map(normalize_label).filter(|t| !t.is_empty()).unwrap_or_else(|| normalize_label(&list.join(", "))); + // Every entry of a repeated value, so that none of them is listed apart. + for (_, s) in classes.iter_mut().filter(|(k, _)| named.contains(k.as_str())) { + *s = symbol; + } + let strokes = class_strokes.get(&first).cloned(); + let fills = class_fills.get(&first).cloned(); + for v in &list { + class_labels.insert(v.clone(), label.clone()); + match &strokes { + Some(x) => class_strokes.insert(v.clone(), x.clone()), + None => class_strokes.remove(v), + }; + match &fills { + Some(x) => class_fills.insert(v.clone(), x.clone()), + None => class_fills.remove(v), + }; + } + Ok(ClassGroup { label, values: list, first }) + } + /// Carries hand-made class edits over from `old` when the symbology is applied again (#314). /// On the same field (or expression), a class that is still there keeps its legend label (a Graduated Colors /// class keeps its edits only while the ranges are the same: they belong to a range). With the @@ -5332,6 +5389,93 @@ mod tests { assert_eq!(r.class_entries(), r.legend()); } + fn group(r: &mut Renderer, values: &[&str], label: Option<&str>) -> Result { + let values: Vec = values.iter().map(|v| v.to_string()).collect(); + r.group_classes(&values, label).map(|g| g.label) + } + + /// Grouping gives the classes named one look and one label, so a legend lists them once (#3308). + #[test] + fn grouped_classes_take_the_first_ones_look_and_one_label() { + let s = |c| Symbol::default_for(GeometryType::Polygon, c); + let base = unique(&[("c", s(0)), ("d", s(1)), ("e", s(2))], s(3), Ramp::Ember); + // With no label, the values joined, each once; the one not named stays as it was. + for values in [&["c", "d"][..], &["c", "d", "c"]] { + let mut r = base.clone(); + assert_eq!(group(&mut r, values, None).unwrap(), "c, d"); + assert_eq!(rows(r.legend()), named(&["c, d", "e", OTHER_VALUES])); + let e = r.class_entries(); + assert_eq!([e[0].symbol, e[1].symbol, e[2].symbol], [s(0), s(0), s(2)]); + } + let mut r = base.clone(); + assert_eq!(group(&mut r, &["c", "d"], Some(" C or D\n")).unwrap(), "C or D"); + assert_eq!(rows(r.legend()), named(&["C or D", "e", OTHER_VALUES])); + // An empty label is none. + let mut r = base.clone(); + assert_eq!(group(&mut r, &["d", "c"], Some(" ")).unwrap(), "d, c"); + // A label that is one of the values is still every class's own. + let mut r = base.clone(); + group(&mut r, &["c", "d"], Some("c")).unwrap(); + assert_eq!(rows(r.legend()), named(&["c", "e", OTHER_VALUES])); + // Cut as every label is. + let long = "x".repeat(MAX_LABEL + 100); + let mut r = base.clone(); + assert_eq!(group(&mut r, &["c", "d"], Some(&long)).unwrap().chars().count(), MAX_LABEL); + let mut r = unique(&[(&long, s(0)), ("d", s(1))], s(3), Ramp::Ember); + assert_eq!(group(&mut r, &[&long, "d"], None).unwrap().chars().count(), MAX_LABEL); + // Editing one afterwards sets it apart again. + let mut r = base; + group(&mut r, &["c", "d"], None).unwrap(); + let style = ClassStyle { color: Some(Rgba::rgb(1, 2, 3)), ..Default::default() }; + r.set_class_style(&ClassRef::Value("d".into()), &style, GeometryType::Polygon).unwrap(); + assert_eq!(rows(r.legend()), named(&["c, d", "c, d", "e", OTHER_VALUES])); + } + + /// The look is the symbol and the stacks of the first class in the list's order, not in the + /// order the values are given. + #[test] + fn a_group_copies_the_first_listed_classes_stacks() { + let s = |c| Symbol::default_for(GeometryType::Polygon, c); + let mut r = unique(&[("5", s(0)), ("1", s(1)), ("3", s(2))], s(3), Ramp::Ember); + let stroke = vec![LineStroke::default()]; + let fill = vec![FillLayer::default()]; + if let Renderer::Unique { class_strokes, class_fills, .. } = &mut r { + class_strokes.insert("1".into(), stroke.clone()); + class_fills.insert("1".into(), fill.clone()); + class_strokes.insert("5".into(), vec![LineStroke::default(), LineStroke::default()]); + } + group(&mut r, &["5", "1"], None).unwrap(); + let Renderer::Unique { classes, class_strokes, class_fills, .. } = &r else { panic!("{r:?}") }; + assert_eq!((classes[0].1, classes[1].1, classes[2].1), (s(1), s(1), s(2))); + assert_eq!((class_strokes.get("5"), class_fills.get("5")), (Some(&stroke), Some(&fill))); + // The first has none of its own: the others lose theirs. + group(&mut r, &["5", "3"], None).unwrap(); + let Renderer::Unique { class_strokes, class_fills, .. } = &r else { panic!("{r:?}") }; + assert_eq!((class_strokes.get("5"), class_fills.get("5")), (None, None)); + assert_eq!((class_strokes.get("1"), class_fills.get("1")), (Some(&stroke), Some(&fill))); + // A repeated value takes the look in every entry. + let mut r = unique(&[("a", s(0)), ("b", s(1)), ("a", s(2))], s(3), Ramp::Ember); + group(&mut r, &["b", "a"], Some("ab")).unwrap(); + assert_eq!(rows(r.legend()), named(&["ab", OTHER_VALUES])); + } + + /// Refused whole: nothing changes. + #[test] + fn a_group_that_cant_be_made_changes_nothing() { + let s = |c| Symbol::default_for(GeometryType::Polygon, c); + let mut r = unique(&[("c", s(0)), ("d", s(1))], s(3), Ramp::Ember); + let before = r.clone(); + for values in [&[][..], &["c"], &["c", "c"]] { + assert!(group(&mut r, values, None).unwrap_err().contains("two or more"), "{values:?}"); + } + let err = group(&mut r, &["c", "d", "zz"], None).unwrap_err(); + assert!(err.contains("'zz'"), "{err}"); + assert_eq!(r, before); + let mut graduated = graduated(&[5.0, 10.0], &[s(0), s(1)], Ramp::Ember); + assert!(group(&mut graduated, &["c", "d"], None).unwrap_err().contains("Unique Values")); + assert!(group(&mut Renderer::Single(s(0)), &["c", "d"], None).unwrap_err().contains("Unique Values")); + } + fn unique(classes: &[(&str, Symbol)], other: Symbol, ramp: Ramp) -> Renderer { Renderer::Unique { field: "g".into(), diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index cc173fa557..a4a4ea551d 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5487,7 +5487,8 @@ fn run_class_style(app: &mut RustGisApp, params: Value) { /// The renderer's legend rows. A Unique Values or Graduated Colors class can be edited in place /// (#314): its colour button and its legend label, which applies when the field loses focus and -/// goes back to the value or range when cleared. +/// goes back to the value or range when cleared. Unique Values classes can also be ticked and, +/// two or more of them, grouped into one legend entry (#3308). fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { // Each row's class, as layer.classStyle names it (and as the renderer does); none for // renderers without classes. @@ -5522,6 +5523,11 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { _ => ((0..legend.len()).take(MAX_EXPRESSION_CLASSES).collect(), legend.len().saturating_sub(MAX_EXPRESSION_CLASSES)), }; let mut seen = std::collections::HashSet::new(); + // The classes ticked to be grouped, by value (not by row, which another can take). + let ticks_key = egui::Id::unique(("group_classes", l.id, l.renderer.field().unwrap_or_default())); + let ticks: Vec = ui.data(|d| d.get_temp(ticks_key)).unwrap_or_default(); + // Those still listed, in the list's order. + let mut ticked = Vec::new(); for i in rows { let Some(e) = legend.get(i) else { continue }; // A value listed twice is drawn with its first class (`symbol_for`): the repeat @@ -5551,6 +5557,13 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { p }; ui.horizontal(|ui| { + if let ClassRef::Value(v) = class_ref { + let mut on = ticks.contains(v); + ui.checkbox(&mut on, "").on_hover_text(tl!("Tick two or more classes to group them")); + if on { + ticked.push(v.clone()); + } + } // A fill No Fill hides shows the opacity Restore Fill gives back, so a colour // picked here is drawn (#2308). let fill = e.symbol.fill; @@ -5632,6 +5645,33 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { }; ui.label(egui::RichText::new(note).size(11.5).color(t.text_dim)); } + let label_key = ticks_key.with("label"); + if ticked.len() > 1 { + // The label typed, or the values joined while none is. + let typed: Option = ui.data(|d| d.get_temp(label_key)); + let mut label = typed.unwrap_or_else(|| normalize_label(&ticked.join(", "))); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Group as")).size(11.5).color(t.text)); + // The button at the right, the label in the room left of it. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tl!("Group")).clicked() { + let params = json!({"layer": l.id, "values": ticked, "label": label}); + match app.run("layer.groupClasses", params) { + Ok(_) => ticked.clear(), + Err(e) => app.session.notify(e, true), + } + ui.data_mut(|d| d.remove::(label_key)); + } + let edit = egui::TextEdit::singleline(&mut label).char_limit(MAX_LABEL).desired_width(ui.available_width()); + if ui.add(edit).on_hover_text(tl!("Legend label of the group")).changed() { + ui.data_mut(|d| d.insert_temp(label_key, label)); + } + }); + }); + } else { + ui.data_mut(|d| d.remove::(label_key)); + } + ui.data_mut(|d| d.insert_temp(ticks_key, ticked)); }, ); } @@ -10047,6 +10087,44 @@ pub(crate) mod tests { assert_eq!(h.query_all_by_role(Role::TextInput).count(), classes_len + 1); } + /// Two classes ticked in the Symbology pane's list can be grouped there: one command, one undo + /// step (#3308). + #[test] + fn the_class_list_groups_the_classes_ticked() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + + let mut app = RustGisApp::with_sample(); + app.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let id = layer(&app, "Countries"); + let renderer = app.session.map().layer(id).unwrap().renderer.clone(); + let (before, listed) = (renderer.legend().len(), renderer.class_entries()); + let mut h = egui_kittest::Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(8).build_ui_state( + move |ui, app: &mut RustGisApp| { + let layer = app.session.map().layer(id).unwrap().clone(); + legend_list(app, ui, &layer, &Tokens::light()); + }, + app, + ); + h.run_steps(2); + // A box on each class, none on ``. + assert_eq!(h.query_all_by_role(Role::CheckBox).count(), listed.len() - 1); + // The later one first: the label still names them as the list does. + h.query_all_by_role(Role::CheckBox).nth(1).unwrap().click(); + h.run_steps(2); + assert!(h.query_by_label("Group").is_none(), "one class is no group"); + h.query_all_by_role(Role::CheckBox).next().unwrap().click(); + h.run_steps(2); + let depth = h.state().session.undo_depth(); + h.get_by_label("Group").click(); + h.run_steps(2); + let legend = h.state().session.map().layer(id).unwrap().renderer.legend(); + assert_eq!(legend.len(), before - 1); + assert_eq!(legend[0].label, format!("{}, {}", listed[0].label, listed[1].label)); + assert_eq!(h.state().session.undo_depth(), depth + 1); + assert!(h.query_by_label("Group").is_none(), "the ticks are cleared"); + } + /// Editing opacity must not turn a transparent red or a near-transparent colour into black. /// Exercise the real class picker and command, including one-step undo after the edit. #[test] diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 4e2dd063db..0cc68226c3 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -265,6 +265,16 @@ layer.classStyle={"layer":"Countries","index":0,"color":"#2E6B4FFF"} layer.classStyle={"layer":"Countries","other":true,"label":"No data"} ``` +To list several Unique Values classes as one legend entry, tick two or more of them in the list, +type the entry's label (their values joined, to start with) and press **Group**. They take the +colour, outline, strokes and fills of the first one ticked, in the list's order. Each value stays +its own class, so changing one's colour or label afterwards lists it apart again; to rename a +group, tick its classes and group them with the new label. By command: + +```text +layer.groupClasses={"layer":"Countries","values":["1. High income: OECD","2. High income: nonOECD"],"label":"High income"} +``` + `value` names a Unique Values class, `index` a Graduated Colors class (0 is the lowest) and `other` the `` class; `outline` sets a class's outline colour. `#RRGGBBAA` sets the fill opacity exactly for every geometry type: `FF` is fully opaque for From 3dbd35b1106bf679ccd4f1fc091e23a0e7174c3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 23:38:59 -0500 Subject: [PATCH 2/9] fix(symbology): say what stacks a group replaces, and keep the label of a refused group --- crates/engine/src/cmd/layer.rs | 23 +++++++++++++++++++++-- crates/engine/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/map/src/symbology.rs | 10 +++++++++- crates/ui-egui/src/panes.rs | 7 +++++-- docs/user-guide/cartography.md | 3 ++- 5 files changed, 65 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 4564ba1b52..3917e63c5a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8446,7 +8446,7 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { }; let id = s.layer_id(p)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; - let group = l.renderer.group_classes(&values, label)?; + let mut group = l.renderer.group_classes(&values, label)?; // What No Fill hid follows the group too, or Restore Fill would set the classes apart. let first = ClassRef::Value(group.first.clone()); let at = symbol_position(&l.renderer, &first); @@ -8454,8 +8454,17 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { l.renderer.map_symbols(|_| now += 1); if let Some(hidden) = &mut l.hidden_fills { let others: std::collections::HashSet<&str> = group.values.iter().filter(|v| **v != group.first).map(String::as_str).collect(); + let fills = hidden.class_fills.iter().find(|(c, _)| *c == first).map(|(_, f)| f.clone()); + for (c, own) in &hidden.class_fills { + if let ClassRef::Value(v) = c + && others.contains(v.as_str()) + && Some(own) != fills.as_ref() + { + group.replaced.insert(v.clone()); + } + } hidden.class_fills.retain(|(c, _)| !matches!(c, ClassRef::Value(v) if others.contains(v.as_str()))); - if let Some(fills) = hidden.class_fills.iter().find(|(c, _)| *c == first).map(|(_, f)| f.clone()) { + if let Some(fills) = fills { let copies = group.values.iter().filter(|v| others.contains(v.as_str())); hidden.class_fills.extend(copies.map(|v| (ClassRef::Value(v.clone()), fills.clone()))); } @@ -8470,6 +8479,16 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { } } } + if !group.replaced.is_empty() { + s.notify( + format!( + "{} class(es) had strokes or fills of their own, replaced by those of '{}'; Undo brings them back", + group.replaced.len(), + group.first + ), + false, + ); + } Ok(json!({"label": group.label, "values": group.values})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 570889cab6..4705035d90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12598,6 +12598,34 @@ fn layer_group_classes_makes_one_legend_entry() { assert!(s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["a", "b"]})).is_err()); } +/// Grouping says how many classes lost strokes or fills of their own, shown or hidden by No Fill, +/// and nothing when none did. +#[test] +fn layer_group_classes_says_what_stacks_it_replaced() { + for hidden in [false, true] { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let group = |s: &mut Session, values: Value| { + s.notices.clear(); + s.run("layer.groupClasses", &json!({"layer": "Countries", "values": values})).unwrap(); + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("of their own")).collect::>() + }; + assert!(group(&mut s, json!(["Africa", "Asia"])).is_empty(), "colours are what a group changes"); + let red = json!([{"color": "#FF0000"}]); + for value in ["Europe", "Oceania"] { + s.run("layer.fillLayers", &json!({"layer": "Countries", "value": value, "fills": red})).unwrap(); + } + if hidden { + s.run("layer.noFill", &json!({"layer": "Countries"})).unwrap(); + } + // The same fills on both: nothing is lost. + assert!(group(&mut s, json!(["Europe", "Oceania"])).is_empty()); + let said = group(&mut s, json!(["Africa", "Europe", "Oceania"])); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 class(es)"), "{said:?}"); + } +} + /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. #[test] fn layer_group_classes_under_no_fill_restores_one_opacity() { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 9dd005210c..fffed4c9cc 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1134,6 +1134,8 @@ pub struct ClassGroup { pub values: Vec, /// The value whose look the others took: the first of them in [`Renderer::class_order`]. pub first: String, + /// The values whose own strokes or fills differed from the first one's, now replaced. + pub replaced: std::collections::HashSet, } /// What [`Renderer::set_class_style`] changes in a class; `None` leaves that part as it is. @@ -2285,7 +2287,13 @@ impl Renderer { } let strokes = class_strokes.get(&first).cloned(); let fills = class_fills.get(&first).cloned(); + let mut replaced = std::collections::HashSet::new(); for v in &list { + if class_strokes.get(v).is_some_and(|own| Some(own) != strokes.as_ref()) + || class_fills.get(v).is_some_and(|own| Some(own) != fills.as_ref()) + { + replaced.insert(v.clone()); + } class_labels.insert(v.clone(), label.clone()); match &strokes { Some(x) => class_strokes.insert(v.clone(), x.clone()), @@ -2296,7 +2304,7 @@ impl Renderer { None => class_fills.remove(v), }; } - Ok(ClassGroup { label, values: list, first }) + Ok(ClassGroup { label, values: list, first, replaced }) } /// Carries hand-made class edits over from `old` when the symbology is applied again (#314). diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index a4a4ea551d..7d87cb22cc 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5657,10 +5657,13 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { if ui.button(tl!("Group")).clicked() { let params = json!({"layer": l.id, "values": ticked, "label": label}); match app.run("layer.groupClasses", params) { - Ok(_) => ticked.clear(), + Ok(_) => { + ticked.clear(); + ui.data_mut(|d| d.remove::(label_key)); + } + // The ticks and the label typed stay, to try again. Err(e) => app.session.notify(e, true), } - ui.data_mut(|d| d.remove::(label_key)); } let edit = egui::TextEdit::singleline(&mut label).char_limit(MAX_LABEL).desired_width(ui.available_width()); if ui.add(edit).on_hover_text(tl!("Legend label of the group")).changed() { diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 0cc68226c3..0446729299 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -267,7 +267,8 @@ layer.classStyle={"layer":"Countries","other":true,"label":"No data"} To list several Unique Values classes as one legend entry, tick two or more of them in the list, type the entry's label (their values joined, to start with) and press **Group**. They take the -colour, outline, strokes and fills of the first one ticked, in the list's order. Each value stays +colour, outline, strokes and fills of the first of the ticked classes in the list's order; a notice +says how many had strokes or fills of their own that were replaced. Each value stays its own class, so changing one's colour or label afterwards lists it apart again; to rename a group, tick its classes and group them with the new label. By command: From 567256fb5748316751e042053eac7a9314d037d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 23:45:20 -0500 Subject: [PATCH 3/9] fix(symbology): name the class checkboxes and drop a group label typed for other classes --- crates/map/src/symbology.rs | 4 ++-- crates/ui-egui/src/panes.rs | 30 +++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index fffed4c9cc..b53718302f 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -5479,8 +5479,8 @@ mod tests { let err = group(&mut r, &["c", "d", "zz"], None).unwrap_err(); assert!(err.contains("'zz'"), "{err}"); assert_eq!(r, before); - let mut graduated = graduated(&[5.0, 10.0], &[s(0), s(1)], Ramp::Ember); - assert!(group(&mut graduated, &["c", "d"], None).unwrap_err().contains("Unique Values")); + let mut ranges = graduated(&[5.0, 10.0], &[s(0), s(1)], Ramp::Ember); + assert!(group(&mut ranges, &["c", "d"], None).unwrap_err().contains("Unique Values")); assert!(group(&mut Renderer::Single(s(0)), &["c", "d"], None).unwrap_err().contains("Unique Values")); } diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 7d87cb22cc..6968c032b5 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5559,7 +5559,10 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { ui.horizontal(|ui| { if let ClassRef::Value(v) = class_ref { let mut on = ticks.contains(v); - ui.checkbox(&mut on, "").on_hover_text(tl!("Tick two or more classes to group them")); + let tick = ui.checkbox(&mut on, ""); + // Named for screen readers by the class it ticks. + tick.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, &e.label)); + tick.on_hover_text(tl!("Tick two or more classes to group them")); if on { ticked.push(v.clone()); } @@ -5646,6 +5649,10 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { ui.label(egui::RichText::new(note).size(11.5).color(t.text_dim)); } let label_key = ticks_key.with("label"); + // A label typed for other ticks doesn't name these. + if ticked != ticks { + ui.data_mut(|d| d.remove::(label_key)); + } if ticked.len() > 1 { // The label typed, or the values joined while none is. let typed: Option = ui.data(|d| d.get_temp(label_key)); @@ -5671,8 +5678,6 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { } }); }); - } else { - ui.data_mut(|d| d.remove::(label_key)); } ui.data_mut(|d| d.insert_temp(ticks_key, ticked)); }, @@ -10095,7 +10100,7 @@ pub(crate) mod tests { #[test] fn the_class_list_groups_the_classes_ticked() { use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; + use egui_kittest::kittest::{NodeT, Queryable}; let mut app = RustGisApp::with_sample(); app.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); @@ -10116,7 +10121,22 @@ pub(crate) mod tests { h.query_all_by_role(Role::CheckBox).nth(1).unwrap().click(); h.run_steps(2); assert!(h.query_by_label("Group").is_none(), "one class is no group"); - h.query_all_by_role(Role::CheckBox).next().unwrap().click(); + h.get_by_role_and_label(Role::CheckBox, &listed[0].label).click(); + h.run_steps(2); + // A label typed for these two doesn't stay for another set. + let group_label = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.query_all_by_role(Role::TextInput).last().unwrap().accesskit_node().value().unwrap_or_default() + }; + h.query_all_by_role(Role::TextInput).last().unwrap().focus(); + h.run_steps(2); + h.query_all_by_role(Role::TextInput).last().unwrap().type_text("x"); + h.run_steps(2); + assert!(group_label(&h).contains('x'), "{}", group_label(&h)); + h.get_by_role_and_label(Role::CheckBox, &listed[2].label).click(); + h.run_steps(2); + let three = format!("{}, {}, {}", listed[0].label, listed[1].label, listed[2].label); + assert_eq!(group_label(&h), three); + h.get_by_role_and_label(Role::CheckBox, &listed[2].label).click(); h.run_steps(2); let depth = h.state().session.undo_depth(); h.get_by_label("Group").click(); From 061d142818aeb507660ab9519f3ea06816ab3f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 23:50:45 -0500 Subject: [PATCH 4/9] fix(symbology): word the replaced-stacks notice for a first class without stacks --- crates/engine/src/cmd/layer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3917e63c5a..06f11e27e9 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8482,7 +8482,7 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { if !group.replaced.is_empty() { s.notify( format!( - "{} class(es) had strokes or fills of their own, replaced by those of '{}'; Undo brings them back", + "{} class(es) lost the strokes or fills they had of their own, to match '{}'; Undo brings them back", group.replaced.len(), group.first ), From 41d93d658fbaf1d90156a9a8e39c133981e5aef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 04:35:17 -0500 Subject: [PATCH 5/9] fix(symbology): say how many legend labels a group replaces --- crates/engine/src/cmd/layer.rs | 6 ++++++ crates/engine/src/tests.rs | 23 ++++++++++++++++++++++- crates/map/src/symbology.rs | 8 ++++++-- docs/user-guide/cartography.md | 5 +++-- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 06f11e27e9..debb789f58 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8489,6 +8489,12 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { false, ); } + if group.relabelled > 0 { + s.notify( + format!("{} class(es) had a legend label of their own, replaced by '{}'; Undo brings them back", group.relabelled, group.label), + false, + ); + } Ok(json!({"label": group.label, "values": group.values})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4705035d90..c49e13ec0e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12608,7 +12608,7 @@ fn layer_group_classes_says_what_stacks_it_replaced() { let group = |s: &mut Session, values: Value| { s.notices.clear(); s.run("layer.groupClasses", &json!({"layer": "Countries", "values": values})).unwrap(); - s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("of their own")).collect::>() + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("strokes or fills")).collect::>() }; assert!(group(&mut s, json!(["Africa", "Asia"])).is_empty(), "colours are what a group changes"); let red = json!([{"color": "#FF0000"}]); @@ -12626,6 +12626,27 @@ fn layer_group_classes_says_what_stacks_it_replaced() { } } +/// Grouping says how many classes had a legend label of their own that the group's replaced, and +/// nothing when none did. +#[test] +fn layer_group_classes_says_what_labels_it_replaced() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let group = |s: &mut Session, values: Value, label: &str| { + s.notices.clear(); + s.run("layer.groupClasses", &json!({"layer": "Countries", "values": values, "label": label})).unwrap(); + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("legend label")).collect::>() + }; + assert!(group(&mut s, json!(["Africa", "Asia"]), "AA").is_empty(), "no class had a label of its own"); + // The same label again replaces nothing. + assert!(group(&mut s, json!(["Africa", "Asia"]), "AA").is_empty()); + s.run("layer.classStyle", &json!({"layer": "Countries", "value": "Europe", "label": "Old world"})).unwrap(); + // Two of the group above and the one typed by hand; Oceania had none. + let said = group(&mut s, json!(["Africa", "Asia", "Europe", "Oceania"]), "All"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("3 class(es)") && said[0].contains("'All'"), "{said:?}"); +} + /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. #[test] fn layer_group_classes_under_no_fill_restores_one_opacity() { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index b53718302f..8e15bcb18c 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1136,6 +1136,8 @@ pub struct ClassGroup { pub first: String, /// The values whose own strokes or fills differed from the first one's, now replaced. pub replaced: std::collections::HashSet, + /// How many of them had a legend label of their own, other than the group's, now replaced. + pub relabelled: usize, } /// What [`Renderer::set_class_style`] changes in a class; `None` leaves that part as it is. @@ -2288,13 +2290,15 @@ impl Renderer { let strokes = class_strokes.get(&first).cloned(); let fills = class_fills.get(&first).cloned(); let mut replaced = std::collections::HashSet::new(); + let mut relabelled = 0; for v in &list { if class_strokes.get(v).is_some_and(|own| Some(own) != strokes.as_ref()) || class_fills.get(v).is_some_and(|own| Some(own) != fills.as_ref()) { replaced.insert(v.clone()); } - class_labels.insert(v.clone(), label.clone()); + let own = class_labels.insert(v.clone(), label.clone()); + relabelled += usize::from(own.is_some_and(|own| own != label)); match &strokes { Some(x) => class_strokes.insert(v.clone(), x.clone()), None => class_strokes.remove(v), @@ -2304,7 +2308,7 @@ impl Renderer { None => class_fills.remove(v), }; } - Ok(ClassGroup { label, values: list, first, replaced }) + Ok(ClassGroup { label, values: list, first, replaced, relabelled }) } /// Carries hand-made class edits over from `old` when the symbology is applied again (#314). diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 0446729299..c167eb0bbb 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -267,8 +267,9 @@ layer.classStyle={"layer":"Countries","other":true,"label":"No data"} To list several Unique Values classes as one legend entry, tick two or more of them in the list, type the entry's label (their values joined, to start with) and press **Group**. They take the -colour, outline, strokes and fills of the first of the ticked classes in the list's order; a notice -says how many had strokes or fills of their own that were replaced. Each value stays +colour, outline, strokes and fills of the first of the ticked classes in the list's order, and the +group's label in place of their own. A notice says how many had a legend label, or strokes or +fills, of their own that were replaced. Each value stays its own class, so changing one's colour or label afterwards lists it apart again; to rename a group, tick its classes and group them with the new label. By command: From 548fea4622cc54e27fb715ca99c29f6a18ca7601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 04:38:48 -0500 Subject: [PATCH 6/9] fix(symbology): keep a repeated first value and each map's ticks apart from the rest of a group --- crates/engine/src/cmd/layer.rs | 3 ++- crates/engine/src/tests.rs | 21 +++++++++++++++++++ crates/ui-egui/src/panes.rs | 38 +++++++++++++++++++++++++++++++++- 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index debb789f58..fee8bd55a9 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8473,7 +8473,8 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { && let Some(a) = at.and_then(|i| hidden.alphas.get(i).copied()) { for ((k, _), alpha) in classes.iter().zip(&mut hidden.alphas) { - if others.contains(k.as_str()) { + // Every entry of a repeated value, the first one's too. + if others.contains(k.as_str()) || *k == group.first { *alpha = a; } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c49e13ec0e..4300da41b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12679,6 +12679,27 @@ fn layer_group_classes_under_no_fill_restores_one_opacity() { assert_eq!(rows(&s, "AE")[0].fills.len(), 1); } +/// Every entry of a repeated value, the first class's too, comes back from Restore Fill with the +/// group's one opacity. +#[test] +fn layer_group_classes_under_no_fill_covers_a_repeated_first_value() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let id = s.map().layer_by_name("Countries").unwrap().id; + // A value listed twice, as an imported style can bring it, each at an opacity of its own. + let rustgis_map::Renderer::Unique { classes, .. } = &mut s.map_mut().layer_mut(id).unwrap().renderer else { + panic!("unique renderer expected") + }; + let mut twin = classes.iter().find(|(k, _)| k == "Africa").unwrap().clone(); + twin.1.fill = twin.1.fill.with_alpha(0x20); + classes.push(twin); + s.run("layer.noFill", &json!({"layer": id})).unwrap(); + s.run("layer.groupClasses", &json!({"layer": id, "values": ["Africa", "Asia"], "label": "AA"})).unwrap(); + s.run("layer.restoreFill", &json!({"layer": id})).unwrap(); + let legend = s.map().layer(id).unwrap().renderer.legend(); + assert_eq!(legend.iter().filter(|e| e.label == "AA").count(), 1, "{legend:?}"); +} + /// Read classes by their command identity, not their sorted legend position. fn class_style_rows(s: &Session, layer: &str) -> Vec<(Value, rustgis_map::Symbol)> { match &s.map().layer_by_name(layer).unwrap().renderer { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 6968c032b5..8d484b29bd 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5524,7 +5524,9 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { }; let mut seen = std::collections::HashSet::new(); // The classes ticked to be grouped, by value (not by row, which another can take). - let ticks_key = egui::Id::unique(("group_classes", l.id, l.renderer.field().unwrap_or_default())); + // Layer ids repeat across maps, so the map is part of the key. + let map = (app.session.project.active_map, app.session.map().name.clone()); + let ticks_key = egui::Id::unique(("group_classes", map, l.id, l.renderer.field().unwrap_or_default())); let ticks: Vec = ui.data(|d| d.get_temp(ticks_key)).unwrap_or_default(); // Those still listed, in the list's order. let mut ticked = Vec::new(); @@ -10148,6 +10150,40 @@ pub(crate) mod tests { assert!(h.query_by_label("Group").is_none(), "the ticks are cleared"); } + /// Layer ids repeat across maps: the ticks made on one map's layer aren't another's. + #[test] + fn class_ticks_stay_with_their_map() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + + let mut app = RustGisApp::with_sample(); + app.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let id = layer(&app, "Countries"); + let map = app.session.map().name.clone(); + let mut other = app.session.map().clone(); + other.name = "Other map".into(); + app.session.project.maps.push(other); + let mut h = egui_kittest::Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(8).build_ui_state( + move |ui, app: &mut RustGisApp| { + let layer = app.session.map().layer(id).unwrap().clone(); + legend_list(app, ui, &layer, &Tokens::light()); + }, + app, + ); + h.run_steps(2); + for i in 0..2 { + h.query_all_by_role(Role::CheckBox).nth(i).unwrap().click(); + h.run_steps(2); + } + assert!(h.query_by_label("Group").is_some()); + h.state_mut().run("map.activate", json!({"name": "Other map"})).unwrap(); + h.run_steps(2); + assert!(h.query_by_label("Group").is_none(), "the other map's layer has no ticks"); + h.state_mut().run("map.activate", json!({"name": map})).unwrap(); + h.run_steps(2); + assert!(h.query_by_label("Group").is_some(), "its own are still there"); + } + /// Editing opacity must not turn a transparent red or a near-transparent colour into black. /// Exercise the real class picker and command, including one-step undo after the edit. #[test] From c77af8f21d0dcc92229e14a30d8aa183f51b6887 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 04:52:40 -0500 Subject: [PATCH 7/9] fix(symbology): say how many classes a group restyles --- crates/engine/src/cmd/layer.rs | 13 +++++++++++++ crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/map/src/symbology.rs | 10 ++++++++-- docs/user-guide/cartography.md | 4 ++-- 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index fee8bd55a9..2abc471639 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8475,6 +8475,9 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { for ((k, _), alpha) in classes.iter().zip(&mut hidden.alphas) { // Every entry of a repeated value, the first one's too. if others.contains(k.as_str()) || *k == group.first { + if *alpha != a && *k != group.first { + group.restyled.insert(k.clone()); + } *alpha = a; } } @@ -8490,6 +8493,16 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { false, ); } + if !group.restyled.is_empty() { + s.notify( + format!( + "{} class(es) took the colour, outline, size and marker of '{}'; Undo brings theirs back", + group.restyled.len(), + group.first + ), + false, + ); + } if group.relabelled > 0 { s.notify( format!("{} class(es) had a legend label of their own, replaced by '{}'; Undo brings them back", group.relabelled, group.label), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4300da41b8..e97a80f970 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12647,6 +12647,31 @@ fn layer_group_classes_says_what_labels_it_replaced() { assert!(said[0].starts_with("3 class(es)") && said[0].contains("'All'"), "{said:?}"); } +/// Grouping says how many classes had a symbol, or an opacity No Fill hid, other than the one +/// they took, and nothing when none did. +#[test] +fn layer_group_classes_says_what_symbols_it_replaced() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + let group = |s: &mut Session| { + s.notices.clear(); + s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["Africa", "Asia", "Europe"]})).unwrap(); + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("took the colour")).collect::>() + }; + let said = group(&mut s); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 class(es)") && said[0].contains("'Africa'"), "{said:?}"); + assert!(group(&mut s).is_empty(), "they look alike already"); + // Only the opacity No Fill hid differs. + s.run("layer.classStyle", &json!({"layer": "Countries", "value": "Asia", "color": "#3B7DD820"})).unwrap(); + s.run("layer.classStyle", &json!({"layer": "Countries", "value": "Africa", "color": "#3B7DD880"})).unwrap(); + s.run("layer.classStyle", &json!({"layer": "Countries", "value": "Europe", "color": "#3B7DD880"})).unwrap(); + s.run("layer.noFill", &json!({"layer": "Countries"})).unwrap(); + let said = group(&mut s); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("1 class(es)"), "{said:?}"); +} + /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. #[test] fn layer_group_classes_under_no_fill_restores_one_opacity() { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 8e15bcb18c..c5cd105076 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1138,6 +1138,8 @@ pub struct ClassGroup { pub replaced: std::collections::HashSet, /// How many of them had a legend label of their own, other than the group's, now replaced. pub relabelled: usize, + /// The values, other than the first, whose symbol differed from the one they took. + pub restyled: std::collections::HashSet, } /// What [`Renderer::set_class_style`] changes in a class; `None` leaves that part as it is. @@ -2284,7 +2286,11 @@ impl Renderer { }; let label = label.map(normalize_label).filter(|t| !t.is_empty()).unwrap_or_else(|| normalize_label(&list.join(", "))); // Every entry of a repeated value, so that none of them is listed apart. - for (_, s) in classes.iter_mut().filter(|(k, _)| named.contains(k.as_str())) { + let mut restyled = std::collections::HashSet::new(); + for (k, s) in classes.iter_mut().filter(|(k, _)| named.contains(k.as_str())) { + if *s != symbol && *k != first { + restyled.insert(k.clone()); + } *s = symbol; } let strokes = class_strokes.get(&first).cloned(); @@ -2308,7 +2314,7 @@ impl Renderer { None => class_fills.remove(v), }; } - Ok(ClassGroup { label, values: list, first, replaced, relabelled }) + Ok(ClassGroup { label, values: list, first, replaced, relabelled, restyled }) } /// Carries hand-made class edits over from `old` when the symbology is applied again (#314). diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index c167eb0bbb..36cfcdb948 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -268,8 +268,8 @@ layer.classStyle={"layer":"Countries","other":true,"label":"No data"} To list several Unique Values classes as one legend entry, tick two or more of them in the list, type the entry's label (their values joined, to start with) and press **Group**. They take the colour, outline, strokes and fills of the first of the ticked classes in the list's order, and the -group's label in place of their own. A notice says how many had a legend label, or strokes or -fills, of their own that were replaced. Each value stays +group's label in place of their own. Notices say how many had another symbol, a legend label, +or strokes or fills of their own that were replaced. Each value stays its own class, so changing one's colour or label afterwards lists it apart again; to rename a group, tick its classes and group them with the new label. By command: From 29e962d5841085e7cc3ac04ee30dcabcfdc9aabf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 05:14:55 -0500 Subject: [PATCH 8/9] fix(symbology): say a group's cut label, name what it restyles and keep ticks to their layer --- crates/engine/src/cmd/layer.rs | 11 +++++++---- crates/engine/src/tests.rs | 36 +++++++++++++++++++++++++++++++++- crates/map/src/symbology.rs | 14 ++++++++++--- crates/ui-egui/src/panes.rs | 21 ++++++++++++-------- docs/user-guide/cartography.md | 7 ++++--- 5 files changed, 70 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2abc471639..0bca3c2e1c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3,7 +3,7 @@ use std::path::Path; use rustgis_data::{Dataset, GeometryType, photo}; -use rustgis_map::symbology::{ClassRef, ClassStyle, LABEL_SIZE, MAX_STROKES}; +use rustgis_map::symbology::{ClassRef, ClassStyle, LABEL_SIZE, MAX_LABEL, MAX_STROKES}; use rustgis_map::{ ClassMethod, Glyph, HiddenFills, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, Marker, NoFill, Picture, Placements, Ramp, Renderer, Rgba, @@ -232,7 +232,7 @@ pub fn commands() -> Vec { C::new("layer.groupClasses", "Group Classes", "Style › Drawing", group_classes).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_feature_layer) .params( - r##"{"layer"?, "values": [text|number, …] (two or more Unique Values classes; they take the symbol, strokes and fills of the first of them in the class list's order, and one label, so a legend lists them as one entry), "label"?: text (default: the values joined with ", ")}"##, + r##"{"layer"?, "values": [text|number, …] (two or more Unique Values classes; they take the symbol, strokes and fills of the first of them in the class list's order, and one label, so a legend lists them as one entry), "label"?: text (default, or when empty: the values joined with ", "; cut to 200 characters)}"##, ), C::new("layer.color", "Symbol Color", "Style › Drawing", |s, p| { let hex = s_req(p, "color")?; @@ -8475,7 +8475,7 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { for ((k, _), alpha) in classes.iter().zip(&mut hidden.alphas) { // Every entry of a repeated value, the first one's too. if others.contains(k.as_str()) || *k == group.first { - if *alpha != a && *k != group.first { + if *alpha != a { group.restyled.insert(k.clone()); } *alpha = a; @@ -8496,13 +8496,16 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { if !group.restyled.is_empty() { s.notify( format!( - "{} class(es) took the colour, outline, size and marker of '{}'; Undo brings theirs back", + "{} class(es) took the symbol of '{}' (colour, outline, size, marker or the opacity No Fill hid); Undo brings theirs back", group.restyled.len(), group.first ), false, ); } + if group.cut > 0 { + s.notify(format!("The group's label was cut to {MAX_LABEL} characters; {} were left out", group.cut), false); + } if group.relabelled > 0 { s.notify( format!("{} class(es) had a legend label of their own, replaced by '{}'; Undo brings them back", group.relabelled, group.label), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e97a80f970..e66e5bd739 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12656,7 +12656,7 @@ fn layer_group_classes_says_what_symbols_it_replaced() { let group = |s: &mut Session| { s.notices.clear(); s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["Africa", "Asia", "Europe"]})).unwrap(); - s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("took the colour")).collect::>() + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("took the symbol")).collect::>() }; let said = group(&mut s); assert_eq!(said.len(), 1, "{said:?}"); @@ -12672,6 +12672,34 @@ fn layer_group_classes_says_what_symbols_it_replaced() { assert!(said[0].starts_with("1 class(es)"), "{said:?}"); } +/// A group's label past the longest a legend keeps says how much of it was cut, whether it was +/// given or made from the values. +#[test] +fn layer_group_classes_says_when_it_cuts_the_label() { + let mut s = world(); + let (a, b) = ("a".repeat(150), "b".repeat(150)); + let text = format!("x,y,v\n1,2,{a}\n2,3,{b}\n"); + s.run("layer.addDataText", &json!({"fileName": "long.csv", "text": text, "x": "x", "y": "y"})).unwrap(); + s.run("layer.symbology", &json!({"layer": "long", "type": "unique", "field": "v"})).unwrap(); + let group = |s: &mut Session, label: Option| { + s.notices.clear(); + let mut p = json!({"layer": "long", "values": [a, b]}); + if let Some(label) = label { + p["label"] = json!(label); + } + s.run("layer.groupClasses", &p).unwrap(); + s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("was cut")).collect::>() + }; + // 150 + ", " + 150. + let said = group(&mut s, None); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("102 were left out"), "{said:?}"); + let said = group(&mut s, Some("y".repeat(250))); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("50 were left out"), "{said:?}"); + assert!(group(&mut s, Some(" short ".into())).is_empty()); +} + /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. #[test] fn layer_group_classes_under_no_fill_restores_one_opacity() { @@ -12720,6 +12748,12 @@ fn layer_group_classes_under_no_fill_covers_a_repeated_first_value() { classes.push(twin); s.run("layer.noFill", &json!({"layer": id})).unwrap(); s.run("layer.groupClasses", &json!({"layer": id, "values": ["Africa", "Asia"], "label": "AA"})).unwrap(); + // The twin counts with Asia: it lost an opacity of its own, whatever its value. + assert!( + s.notices.iter().any(|n| n.text.starts_with("2 class(es) took the symbol of 'Africa'")), + "{:?}", + s.notices.iter().map(|n| &n.text).collect::>() + ); s.run("layer.restoreFill", &json!({"layer": id})).unwrap(); let legend = s.map().layer(id).unwrap().renderer.legend(); assert_eq!(legend.iter().filter(|e| e.label == "AA").count(), 1, "{legend:?}"); diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index c5cd105076..4b4ef5ab22 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1140,6 +1140,8 @@ pub struct ClassGroup { pub relabelled: usize, /// The values, other than the first, whose symbol differed from the one they took. pub restyled: std::collections::HashSet, + /// How many characters the label, given or made from the values, lost past [`MAX_LABEL`]. + pub cut: usize, } /// What [`Renderer::set_class_style`] changes in a class; `None` leaves that part as it is. @@ -2284,11 +2286,17 @@ impl Renderer { let Some((first, symbol)) = first.filter(|_| list.len() > 1).cloned() else { return Err("name two or more different classes to group".into()); }; - let label = label.map(normalize_label).filter(|t| !t.is_empty()).unwrap_or_else(|| normalize_label(&list.join(", "))); + let asked = match label.filter(|t| !normalize_label(t).is_empty()) { + Some(t) => t.to_string(), + None => list.join(", "), + }; + let label = normalize_label(&asked); + let length = asked.trim().chars().count(); + let cut = if length > MAX_LABEL { length - label.chars().count() } else { 0 }; // Every entry of a repeated value, so that none of them is listed apart. let mut restyled = std::collections::HashSet::new(); for (k, s) in classes.iter_mut().filter(|(k, _)| named.contains(k.as_str())) { - if *s != symbol && *k != first { + if *s != symbol { restyled.insert(k.clone()); } *s = symbol; @@ -2314,7 +2322,7 @@ impl Renderer { None => class_fills.remove(v), }; } - Ok(ClassGroup { label, values: list, first, replaced, relabelled, restyled }) + Ok(ClassGroup { label, values: list, first, replaced, relabelled, restyled, cut }) } /// Carries hand-made class edits over from `old` when the symbology is applied again (#314). diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 8d484b29bd..f01fc4d9dc 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5524,9 +5524,8 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { }; let mut seen = std::collections::HashSet::new(); // The classes ticked to be grouped, by value (not by row, which another can take). - // Layer ids repeat across maps, so the map is part of the key. - let map = (app.session.project.active_map, app.session.map().name.clone()); - let ticks_key = egui::Id::unique(("group_classes", map, l.id, l.renderer.field().unwrap_or_default())); + // By the live layer: layer ids and map names repeat across maps and projects. + let ticks_key = egui::Id::unique(("group_classes", l.instance_id(), l.renderer.field().unwrap_or_default())); let ticks: Vec = ui.data(|d| d.get_temp(ticks_key)).unwrap_or_default(); // Those still listed, in the list's order. let mut ticked = Vec::new(); @@ -5658,7 +5657,8 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { if ticked.len() > 1 { // The label typed, or the values joined while none is. let typed: Option = ui.data(|d| d.get_temp(label_key)); - let mut label = typed.unwrap_or_else(|| normalize_label(&ticked.join(", "))); + // Sent whole: the command cuts a long one and says so. + let mut label = typed.unwrap_or_else(|| ticked.join(", ")); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Group as")).size(11.5).color(t.text)); // The button at the right, the label in the room left of it. @@ -10150,7 +10150,7 @@ pub(crate) mod tests { assert!(h.query_by_label("Group").is_none(), "the ticks are cleared"); } - /// Layer ids repeat across maps: the ticks made on one map's layer aren't another's. + /// Layer ids repeat across maps and projects: the ticks made on one layer aren't another's. #[test] fn class_ticks_stay_with_their_map() { use egui::accesskit::Role; @@ -10160,9 +10160,8 @@ pub(crate) mod tests { app.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); let id = layer(&app, "Countries"); let map = app.session.map().name.clone(); - let mut other = app.session.map().clone(); - other.name = "Other map".into(); - app.session.project.maps.push(other); + app.run("map.duplicate", json!({"name": "Other map"})).unwrap(); + app.run("map.activate", json!({"name": map})).unwrap(); let mut h = egui_kittest::Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(8).build_ui_state( move |ui, app: &mut RustGisApp| { let layer = app.session.map().layer(id).unwrap().clone(); @@ -10182,6 +10181,12 @@ pub(crate) mod tests { h.state_mut().run("map.activate", json!({"name": map})).unwrap(); h.run_steps(2); assert!(h.query_by_label("Group").is_some(), "its own are still there"); + // Another project, with the same map names, layer ids and field. + let mut other = RustGisApp::with_sample(); + other.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap(); + h.state_mut().session.project = other.session.project.clone(); + h.run_steps(2); + assert!(h.query_by_label("Group").is_none(), "another project's layer has no ticks"); } /// Editing opacity must not turn a transparent red or a near-transparent colour into black. diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 36cfcdb948..bff2bf87ac 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -267,9 +267,10 @@ layer.classStyle={"layer":"Countries","other":true,"label":"No data"} To list several Unique Values classes as one legend entry, tick two or more of them in the list, type the entry's label (their values joined, to start with) and press **Group**. They take the -colour, outline, strokes and fills of the first of the ticked classes in the list's order, and the -group's label in place of their own. Notices say how many had another symbol, a legend label, -or strokes or fills of their own that were replaced. Each value stays +symbol (colour, outline, size and marker), strokes and fills of the first of the ticked classes in +the list's order, and the group's label in place of their own. Notices say how many had another +symbol, a legend label, or strokes or fills of their own that were replaced, and how much of a +label longer than 200 characters was cut. Each value stays its own class, so changing one's colour or label afterwards lists it apart again; to rename a group, tick its classes and group them with the new label. By command: From 0324cc12e6ba1808091d0cea6b608fa450c035c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 06:15:51 -0500 Subject: [PATCH 9/9] fix(symbology): count a group label's cut as it is kept --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/tests.rs | 6 ++++++ crates/map/src/symbology.rs | 11 ++++++++--- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 0bca3c2e1c..d529b1ce80 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -8504,7 +8504,7 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { ); } if group.cut > 0 { - s.notify(format!("The group's label was cut to {MAX_LABEL} characters; {} were left out", group.cut), false); + s.notify(format!("The group's label was cut to at most {MAX_LABEL} characters; {} were left out", group.cut), false); } if group.relabelled > 0 { s.notify( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e66e5bd739..40f7efdbbd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12698,6 +12698,12 @@ fn layer_group_classes_says_when_it_cuts_the_label() { assert_eq!(said.len(), 1, "{said:?}"); assert!(said[0].contains("50 were left out"), "{said:?}"); assert!(group(&mut s, Some(" short ".into())).is_empty()); + // Control characters at the ends are spaces, trimmed before anything is cut. + assert!(group(&mut s, Some(format!("{}A", "\0".repeat(201)))).is_empty()); + // A space left at the cut goes too: the label is shorter than the most, and the count says so. + let said = group(&mut s, Some(format!("{} z", "y".repeat(199)))); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("at most 200") && said[0].contains("2 were left out"), "{said:?}"); } /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 4b4ef5ab22..518f09222a 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2291,8 +2291,7 @@ impl Renderer { None => list.join(", "), }; let label = normalize_label(&asked); - let length = asked.trim().chars().count(); - let cut = if length > MAX_LABEL { length - label.chars().count() } else { 0 }; + let cut = one_line(&asked).chars().count().saturating_sub(label.chars().count()); // Every entry of a repeated value, so that none of them is listed apart. let mut restyled = std::collections::HashSet::new(); for (k, s) in classes.iter_mut().filter(|(k, _)| named.contains(k.as_str())) { @@ -2506,8 +2505,14 @@ fn carry_class(new: Symbol, old: &Symbol, scheme: Rgba, g: GeometryType) -> Symb /// line breaks become spaces), trimmed, cut to [`MAX_LABEL`] characters and trimmed again (a cut /// can end in a space). An editor compares its text this way to tell whether it changed. pub fn normalize_label(t: &str) -> String { + one_line(t).chars().take(MAX_LABEL).collect::().trim_end().to_string() +} + +/// A label as [`normalize_label`] reads it, before it is cut: control characters as spaces, and no +/// space at either end. +fn one_line(t: &str) -> String { let t: String = t.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); - t.trim().chars().take(MAX_LABEL).collect::().trim_end().to_string() + t.trim().to_string() } /// The first values in a map's order, never more than `max` kept, each with how many features