SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Parameters: sort the list by name within each section (#8563) (#8725)
PaddleStroke180a725c0e00
diff --git a/assets/locales/pending/parameters-sort-by-name.json b/assets/locales/pending/parameters-sort-by-name.jsonnew file mode 100644index 0000000000..10c0370fbe--- /dev/null+++ b/assets/locales/pending/parameters-sort-by-name.json@@ -0,0 +1,47 @@+{+ "en": {+ "Back to the original order": "Back to the original order",+ "Sort A to Z": "Sort A to Z",+ "Sort Z to A": "Sort Z to A"+ },+ "ar": {+ "Back to the original order": "العودة إلى الترتيب الأصلي",+ "Sort A to Z": "فرز تصاعدي",+ "Sort Z to A": "فرز تنازلي"+ },+ "de": {+ "Back to the original order": "Zurück zur ursprünglichen Reihenfolge",+ "Sort A to Z": "Von A bis Z sortieren",+ "Sort Z to A": "Von Z bis A sortieren"+ },+ "es": {+ "Back to the original order": "Volver al orden original",+ "Sort A to Z": "Ordenar de la A a la Z",+ "Sort Z to A": "Ordenar de la Z a la A"+ },+ "fr": {+ "Back to the original order": "Revenir à l'ordre d'origine",+ "Sort A to Z": "Trier de A à Z",+ "Sort Z to A": "Trier de Z à A"+ },+ "he": {+ "Back to the original order": "חזרה לסדר המקורי",+ "Sort A to Z": "מיון בסדר עולה",+ "Sort Z to A": "מיון בסדר יורד"+ },+ "ja": {+ "Back to the original order": "元の順序に戻す",+ "Sort A to Z": "昇順で並べ替え",+ "Sort Z to A": "降順で並べ替え"+ },+ "vi": {+ "Back to the original order": "Trở về thứ tự ban đầu",+ "Sort A to Z": "Sắp xếp từ A đến Z",+ "Sort Z to A": "Sắp xếp từ Z đến A"+ },+ "zh": {+ "Back to the original order": "恢复原始顺序",+ "Sort A to Z": "升序排序",+ "Sort Z to A": "降序排序"+ }+}diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rsindex 0cf0121477..edce949800 100644--- a/crates/ui-egui/src/params_dialog.rs+++ b/crates/ui-egui/src/params_dialog.rs@@ -2,7 +2,8 @@//!//! A window over the engine's `parameters.*` commands: favourites first, then user parameters//! (name, unit, expression, value, comment; add, rename, delete) and model parameters grouped by-//! the sketch or feature they drive (editable). Expressions validate as you type+//! the sketch or feature they drive (editable). The Name heading sorts each section, and each+//! model group, by name in natural order (#8563). Expressions validate as you type//! (`expr.evaluate`) with a live model preview; Enter or leaving the field applies them.//! Escape closes the window and discards pending edits and their preview.//! Import and export go through `parameters.import` / `parameters.export`.@@ -27,6 +28,9 @@ const UNITS: [&str; 10] = ["mm", "cm", "m", "in", "ft", "deg", "rad", "", "um",#[derive(Default)]pub struct ParamsDialog {pub filter: String,+ /// The order by name inside each section (#8563); remembered across openings like the+ /// sections' open state.+ pub(crate) sort: ui_kit::Sort,reset_scroll: bool,/// Expressions being edited, by parameter name.pub editing: std::collections::BTreeMap<String, String>,@@ -185,6 +189,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {publish(app, ctx);}let Some(mut d) = app.params.take() else { return };+ d.sort = ctx.data_mut(|m| m.get_persisted(sort_id())).unwrap_or_default();+ let sort = d.sort;ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));let viewport = crate::agent_chat::tool_space(app, crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect())));if !viewport.is_finite() || !viewport.is_positive() {@@ -278,30 +284,16 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {.map(|r| ui_kit::ContentWidth::name(ui, &r.name)).fold(crate::theme::Tokens::get().form_label_width, f32::max).min(crate::theme::Tokens::get().form_card_width);- let favorites: Vec<_> = visible.iter().copied().filter(|r| r.favorite).collect();+ let Sections { favorites, users, groups } = sections(&visible, d.sort);if !favorites.is_empty() {ui_kit::section_count(ui, "favorites", "Favorites", true, Some(favorites.len()), |ui| {table(app, ui, &mut d, &favorites, "fav", name_floor)});}- let users: Vec<_> = visible.iter().copied().filter(|r| r.source == "user").collect();ui_kit::section_count(ui, "users", "User Parameters", true, Some(users.len()), |ui| {table(app, ui, &mut d, &users, "user", name_floor);});ui_kit::section(ui, "models", "Model Parameters", true, |ui| {- // Group once, in listing order, rather than scanning every parameter for- // each feature on every frame (#2733).- let mut groups: Vec<(&str, Vec<&Row>)> = Vec::new();- let mut indices = std::collections::HashMap::new();- for r in visible.iter().filter(|r| r.source != "user") {- let index = *indices.entry(r.group.as_str()).or_insert_with(|| {- groups.push((&r.group, Vec::new()));- groups.len() - 1- });- if let Some((_, members)) = groups.get_mut(index) {- members.push(r);- }- }ui.scope(|ui| {ui.spacing_mut().indent = crate::theme::Tokens::get().space_14;ui.indent("model_groups", |ui| {@@ -344,11 +336,58 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {if let Some(rect) = crate::scenario::rect_of("dialog:header") {crate::scenario::publish_handle("params:title", rect.center());}+ if d.sort != sort {+ let chosen = d.sort;+ ctx.data_mut(|m| m.insert_persisted(sort_id(), chosen));+ }if !close {app.params = Some(d);}}+/// Where the chosen order is kept: egui's persisted memory, like a section's open state.+fn sort_id() -> egui::Id {+ egui::Id::new("sc_params_sort")+}++/// The dialog's sections, each in the chosen order.+struct Sections<'a> {+ favorites: Vec<&'a Row>,+ users: Vec<&'a Row>,+ /// Model parameters by the sketch or feature that drives them, groups in listing order.+ groups: Vec<(&'a str, Vec<&'a Row>)>,+}++/// Split the listed rows into sections and sort each one by name on its own (#8563): a sort+/// orders the rows inside Favorites, User Parameters and each model group, never moves a row+/// to another section, and keeps the groups themselves in the design's order.+fn sections<'a>(visible: &[&'a Row], sort: ui_kit::Sort) -> Sections<'a> {+ fn by_name<'o>(r: &'o &Row) -> &'o str {+ &r.name+ }+ let mut favorites: Vec<_> = visible.iter().copied().filter(|r| r.favorite).collect();+ sort.apply(&mut favorites, by_name);+ let mut users: Vec<_> = visible.iter().copied().filter(|r| r.source == "user").collect();+ sort.apply(&mut users, by_name);+ // Group once, in listing order, rather than scanning every parameter for each feature on+ // every frame (#2733).+ let mut groups: Vec<(&str, Vec<&Row>)> = Vec::new();+ let mut indices = std::collections::HashMap::new();+ for r in visible.iter().copied().filter(|r| r.source != "user") {+ let index = *indices.entry(r.group.as_str()).or_insert_with(|| {+ groups.push((&r.group, Vec::new()));+ groups.len() - 1+ });+ if let Some((_, members)) = groups.get_mut(index) {+ members.push(r);+ }+ }+ for (_, members) in &mut groups {+ sort.apply(members, by_name);+ }+ Sections { favorites, users, groups }+}+fn model_group(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, group: &str, rows: &[&Row], name_floor: f32) {// Focused editors and pending drafts must still receive focus-loss/commit events after// scrolling away. The measured size is used only while the group is idle.@@ -417,7 +456,16 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&RColumn::new("Comment", 1.0).flex(),Column::new("Actions", 0.0).icon_only().min_content_width(ui_kit::table_row_height()),];- ui_kit::table(ui, salt, &columns, crate::i18n::tr("manage.empty"), |ui, table| {+ ui_kit::table_custom(ui, salt, &columns, crate::i18n::tr("manage.empty"), |ui, table| {+ // The Name heading sorts every section at once, each inside itself (#8563).+ table.headers(ui, |ui, index| {+ if index != 1 {+ return false;+ }+ let response = ui_kit::sort_header(ui, "Name", &mut d.sort);+ crate::scenario::publish_handle(&format!("params:sort:{salt}"), response.rect.center());+ true+ });for (index, r) in rows.iter().enumerate() {// Skip cells outside the clip while preserving the table's row geometry (#2723).// Drafts remain live until their edits have been committed.@@ -433,11 +481,14 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&Rd.error = app.run("parameters.favorite", json!({"name": r.name, "favorite": !r.favorite})).err();}if salt == "user" {+ // A sorted list doesn't show the stored order, so moving a row in it+ // would jump to a place nobody sees; moving waits for the listed order.+ let listed = d.sort == ui_kit::Sort::Listed;for (glyph, tip, neighbour, side) in [(ui_kit::MOVE_UP, "Move up", index.checked_sub(1).and_then(|i| rows.get(i)), "before"),(ui_kit::MOVE_DOWN, "Move down", rows.get(index + 1), "after"),] {- let response = ui_kit::compact_button(ui, glyph, tip, neighbour.is_some(), false);+ let response = ui_kit::compact_button(ui, glyph, tip, listed && neighbour.is_some(), false);crate::scenario::publish_handle(&format!("param:{side}:{}", r.name), response.rect.center());if response.clicked()&& let Some(neighbour) = neighbour@@ -1162,6 +1213,110 @@ mod tests {assert!(h.app.params.as_ref().unwrap().error.is_none());}+ /// #8563: sorting orders each section, and each model group, by itself.+ #[test]+ fn sorting_orders_each_section_and_model_group_on_its_own() {+ let row = |name: &str, source: &str, group: &str, favorite: bool| Row {+ name: name.into(),+ source: source.into(),+ group: group.into(),+ favorite,+ ..Default::default()+ };+ let listed = [+ row("d10", "user", "", true),+ row("width", "user", "", false),+ row("d2", "user", "", false),+ row("Alpha", "user", "", true),+ row("d1", "user", "", false),+ row("s_d3", "sketch", "Sketch1", false),+ row("s_d1", "sketch", "Sketch1", true),+ row("b_len", "feature", "Box1", false),+ row("b_h", "feature", "Box1", false),+ row("s_d2", "sketch", "Sketch1", false),+ ];+ let visible: Vec<&Row> = listed.iter().collect();+ fn names<'a>(rows: &[&'a Row]) -> Vec<&'a str> {+ rows.iter().map(|r| r.name.as_str()).collect()+ }+ let shown = |sort| {+ let s = sections(&visible, sort);+ (names(&s.favorites), names(&s.users), s.groups.iter().map(|(g, m)| (g.to_string(), names(m))).collect::<Vec<_>>())+ };+ let (fav, users, groups) = shown(ui_kit::Sort::Listed);+ assert_eq!((fav, users), (vec!["d10", "Alpha", "s_d1"], vec!["d10", "width", "d2", "Alpha", "d1"]), "unsorted: the listed order");+ assert_eq!(groups, [("Sketch1".into(), vec!["s_d3", "s_d1", "s_d2"]), ("Box1".into(), vec!["b_len", "b_h"])]);+ let (fav, users, groups) = shown(ui_kit::Sort::Ascending);+ assert_eq!(fav, ["Alpha", "d10", "s_d1"]);+ assert_eq!(users, ["Alpha", "d1", "d2", "d10", "width"]);+ assert_eq!(+ groups,+ [("Sketch1".into(), vec!["s_d1", "s_d2", "s_d3"]), ("Box1".into(), vec!["b_h", "b_len"])],+ "groups keep the design's order"+ );+ let (fav, users, groups) = shown(ui_kit::Sort::Descending);+ assert_eq!(fav, ["s_d1", "d10", "Alpha"]);+ assert_eq!(users, ["width", "d10", "d2", "d1", "Alpha"]);+ assert_eq!(groups, [("Sketch1".into(), vec!["s_d3", "s_d2", "s_d1"]), ("Box1".into(), vec!["b_len", "b_h"])]);+ }++ /// #8563: clicking a Name heading sorts every table in the window, the choice outlives the+ /// window, and moving a user parameter waits for the listed order.+ #[test]+ fn the_name_heading_sorts_the_window_and_is_remembered() {+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.call("ui.resize", json!({"width": 1600, "height": 1400}));+ h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap();+ for name in ["t10", "span", "t2", "Alpha", "t1"] {+ h.app.run("parameters.add", json!({"name": name, "expression": "10 mm"})).unwrap();+ }+ h.app.start("parameters.change");+ h.frames(6);+ let order = |table: &str, names: &[String]| {+ let mut rows: Vec<_> =+ names.iter().map(|n| (crate::scenario::rect_of(&format!("dialog:table:{table}:{n}")).expect(n).top(), n.clone())).collect();+ rows.sort_by(|a, b| a.0.total_cmp(&b.0));+ rows.into_iter().map(|(_, n)| n).collect::<Vec<_>>()+ };+ let users: Vec<String> = ["t10", "span", "t2", "Alpha", "t1"].map(String::from).to_vec();+ let group = h.app.params.as_ref().unwrap().listed.as_ref().unwrap().1.iter().find(|r| r.source != "user").unwrap().group.clone();+ let model: Vec<String> =+ h.app.params.as_ref().unwrap().listed.as_ref().unwrap().1.iter().filter(|r| r.group == group).map(|r| r.name.clone()).collect();+ assert_eq!(order("user", &users), users, "the listed order by default");+ assert!(model.len() > 1, "the box drives several parameters: {model:?}");+ let mut sorted_model = model.clone();+ ui_kit::Sort::Ascending.apply(&mut sorted_model, |s| s.as_str());++ h.step(&json!({"click": {"handle": "params:sort:user"}})).unwrap();+ h.frames(3);+ assert_eq!(order("user", &users), ["Alpha", "span", "t1", "t2", "t10"]);+ // The bounded card may not show the model group below the user table: filter to it.+ h.app.params.as_mut().unwrap().filter = group.clone();+ h.frames(4);+ assert_eq!(order(&group, &model), sorted_model, "a model group sorts too");+ h.app.params.as_mut().unwrap().filter.clear();+ h.frames(4);+ assert!(crate::scenario::handle_at("param:after:Alpha").is_some());+ let before = h.app.session.doc.params.iter().map(|p| p.name.clone()).collect::<Vec<_>>();+ h.step(&json!({"click": {"handle": "param:after:Alpha"}})).unwrap();+ h.frames(2);+ assert_eq!(h.app.session.doc.params.iter().map(|p| p.name.clone()).collect::<Vec<_>>(), before, "no move while sorted");++ // Closed and opened again: still sorted.+ h.app.params = None;+ h.frames(2);+ h.app.start("parameters.change");+ h.frames(4);+ assert_eq!(h.app.params.as_ref().unwrap().sort, ui_kit::Sort::Ascending);+ h.step(&json!({"click": {"handle": "params:sort:user"}})).unwrap();+ h.frames(3);+ assert_eq!(order("user", &users), ["t10", "t2", "t1", "span", "Alpha"]);+ h.step(&json!({"click": {"handle": "params:sort:user"}})).unwrap();+ h.frames(3);+ assert_eq!(order("user", &users), users, "the third click goes back to the listed order");+ }+/// A design with hundreds of chained parameters.fn big_design() -> crate::scenario::Harness {let mut h = crate::scenario::Harness::new();diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rsindex 4ef81e7a05..6debc7ad07 100644--- a/crates/ui-egui/src/ui_kit/gallery.rs+++ b/crates/ui-egui/src/ui_kit/gallery.rs@@ -981,6 +981,12 @@ const ELEMENTS: &[Element] = &[removable_header(ui, "Width");});}),+ element!("sort_header", |ui, _| {+ ui.allocate_ui(vec2(140.0, row_height()), |ui| {+ ui.set_min_size(vec2(140.0, row_height()));+ sort_header(ui, "Name", &mut Sort::Ascending);+ });+ }),element!("plus_header", |ui, _| {ui.allocate_ui(vec2(140.0, row_height()), |ui| {ui.set_min_size(vec2(140.0, row_height()));diff --git a/crates/ui-egui/src/ui_kit/table.rs b/crates/ui-egui/src/ui_kit/table.rsindex 674be3f105..7568b02bfe 100644--- a/crates/ui-egui/src/ui_kit/table.rs+++ b/crates/ui-egui/src/ui_kit/table.rs@@ -308,6 +308,101 @@ fn header_label(ui: &mut Ui, label: &str) {.on_hover_text(crate::i18n::tr_label(label));}+/// How a table orders its rows by one column. `Listed` keeps the order the owner gave them.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub(crate) enum Sort {+ #[default]+ Listed,+ Ascending,+ Descending,+}++impl Sort {+ /// A click on the header steps ascending, descending, then back to the listed order.+ pub(crate) fn next(self) -> Self {+ match self {+ Sort::Listed => Sort::Ascending,+ Sort::Ascending => Sort::Descending,+ Sort::Descending => Sort::Listed,+ }+ }++ /// Order `items` by `key` in natural order (stable: equal names keep their listed order).+ pub(crate) fn apply<T>(self, items: &mut [T], key: impl Fn(&T) -> &str) {+ match self {+ Sort::Listed => {}+ Sort::Ascending => items.sort_by(|a, b| natural_cmp(key(a), key(b))),+ Sort::Descending => items.sort_by(|a, b| natural_cmp(key(b), key(a))),+ }+ }+}++/// Natural order for names: runs of digits compare by value ("d2" before "d10"), letters+/// ignore case ("Alpha" between "a" and "b"); exact ties fall back to the plain comparison.+fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {+ use std::cmp::Ordering;+ let (mut x, mut y) = (a.chars().peekable(), b.chars().peekable());+ while let (Some(&p), Some(&q)) = (x.peek(), y.peek()) {+ let order = if p.is_ascii_digit() && q.is_ascii_digit() {+ let run = |it: &mut std::iter::Peekable<std::str::Chars<'_>>| {+ let mut digits = String::new();+ while let Some(c) = it.next_if(char::is_ascii_digit) {+ digits.push(c);+ }+ digits+ };+ let (m, n) = (run(&mut x), run(&mut y));+ let (m_value, n_value) = (m.trim_start_matches('0'), n.trim_start_matches('0'));+ // Compare the values by length then digits, so no run can overflow an integer;+ // "01" sorts after "1".+ m_value.len().cmp(&n_value.len()).then_with(|| m_value.cmp(n_value)).then_with(|| m.len().cmp(&n.len()))+ } else {+ x.next();+ y.next();+ p.to_lowercase().cmp(q.to_lowercase())+ };+ if order != Ordering::Equal {+ return order;+ }+ }+ x.next().is_some().cmp(&y.next().is_some()).then_with(|| a.cmp(b))+}++/// A header that sorts the table by its column. Clicking steps through [`Sort::next`]; the+/// chevron shows the current direction (up for ascending), and none when rows are as listed.+/// Tokens: control_radius, hover, space_4/14, font_small, form_dim/primary.+pub(crate) fn sort_header(ui: &mut Ui, label: &str, sort: &mut Sort) -> Response {+ let t = Tokens::get();+ let rect = ui.max_rect();+ let response = ui.allocate_rect(rect, egui::Sense::click());+ if response.hovered() {+ ui.painter().rect_filled(rect, t.control_radius, t.hover);+ }+ let text = crate::i18n::tr_label(label);+ let font = crate::fonts::semibold(t.font_small);+ let width = ui.painter().layout_no_wrap(text.to_owned(), font.clone(), t.form_dim).size().x.ceil();+ let text_rect = egui::Rect::from_min_max(rect.min, egui::pos2((rect.left() + width).min(rect.right() - t.space_14 - t.space_4), rect.bottom()));+ super::text::paint_text(ui, text_rect, text, font, t.form_dim, false);+ let icon =+ egui::Rect::from_center_size(egui::pos2(text_rect.right() + t.space_4 + t.space_14 * 0.5, rect.center().y), vec2(t.space_14, t.space_14));+ match *sort {+ Sort::Ascending => crate::icons::paint_ink_flipped(ui.painter(), icon, "chevron", t.form_primary),+ Sort::Descending => crate::icons::paint_ink(ui.painter(), icon, "chevron", t.form_primary),+ Sort::Listed if response.hovered() => crate::icons::paint_ink(ui.painter(), icon, "chevron", t.form_dim.gamma_multiply(0.5)),+ Sort::Listed => {}+ }+ if response.clicked() {+ *sort = sort.next();+ }+ let tip = match *sort {+ Sort::Listed => "Sort A to Z",+ Sort::Ascending => "Sort Z to A",+ Sort::Descending => "Back to the original order",+ };+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), text));+ response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(crate::i18n::tr_label(tip))+}+/// Column removal appears inside the hovered header only. Keeps the former × button handle.pub(crate) fn removable_header(ui: &mut Ui, label: &str) -> bool {let t = Tokens::get();diff --git a/crates/ui-egui/src/ui_kit/table_tests.rs b/crates/ui-egui/src/ui_kit/table_tests.rsindex 81093035b6..4579cd84ce 100644--- a/crates/ui-egui/src/ui_kit/table_tests.rs+++ b/crates/ui-egui/src/ui_kit/table_tests.rs@@ -348,3 +348,19 @@ fn name_list_gives_the_name_the_width_the_other_cells_leave() {assert_eq!(scenario::count_of("dialog:name:b.step:cut"), Some(0.0));}}++/// #8563: names sort in natural order: numbers by value, letters without regard to case.+#[test]+fn natural_order_compares_numbers_by_value_and_ignores_case() {+ let mut names = vec!["d10", "width", "d2", "Alpha", "d1", "alpha", "Beta", "d02", "x", "x1", "p99999999999999999999999", "p100"];+ Sort::Ascending.apply(&mut names, |s| *s);+ assert_eq!(names, ["Alpha", "alpha", "Beta", "d1", "d2", "d02", "d10", "p100", "p99999999999999999999999", "width", "x", "x1"]);+ Sort::Descending.apply(&mut names, |s| *s);+ assert_eq!(names, ["x1", "x", "width", "p99999999999999999999999", "p100", "d10", "d02", "d2", "d1", "Beta", "alpha", "Alpha"]);+ let mut listed = vec!["d10", "d2", "d1"];+ Sort::Listed.apply(&mut listed, |s| *s);+ assert_eq!(listed, ["d10", "d2", "d1"], "the listed order is left alone");+ assert_eq!(natural_cmp("", ""), std::cmp::Ordering::Equal);+ assert_eq!(natural_cmp("", "a"), std::cmp::Ordering::Less);+ assert_eq!([Sort::Listed.next(), Sort::Ascending.next(), Sort::Descending.next()], [Sort::Ascending, Sort::Descending, Sort::Listed]);+}