diff --git a/crates/ui-egui/src/bom_panel.rs b/crates/ui-egui/src/bom_panel.rs index 03759418f..108dba9e5 100644 --- a/crates/ui-egui/src/bom_panel.rs +++ b/crates/ui-egui/src/bom_panel.rs @@ -69,6 +69,41 @@ fn text(row: &Value, k: &str) -> String { } } +/// The grid's headers and the row key each column shows. +const HEADERS: [&str; 6] = ["Item", "Part number", "Description", "Rev", "Qty", "Definition"]; +const COLUMN_KEYS: [&str; 6] = ["item", "part_number", "description", "revision", "count", "definition"]; +/// The column that takes the space the others leave, truncating its text. +const DESCRIPTION: usize = 2; +const COLUMN_SPACING: f32 = 14.0; + +/// Each column's width: every column fits its widest cell, Description takes what is left. +fn column_widths(ui: &egui::Ui, rows: &[Value]) -> [f32; 6] { + let font = egui::TextStyle::Body.resolve(ui.style()); + let width = |s: &str| ui.painter().layout_no_wrap(s.to_owned(), font.clone(), egui::Color32::PLACEHOLDER).size().x.ceil(); + // The item cell is a picker button, padded on both sides. + let padding = 2.0 * ui.spacing().button_padding.x; + let mut widths = HEADERS.map(width); + for row in rows.iter().flat_map(|r| std::iter::once(r).chain(r["children"].as_array().into_iter().flatten())) { + for (i, key) in COLUMN_KEYS.iter().enumerate() { + let w = width(&text(row, key)) + if i == 0 { padding } else { 0.0 }; + widths[i] = widths[i].max(w); + } + } + let others: f32 = widths.iter().enumerate().filter(|(i, _)| *i != DESCRIPTION).map(|(_, w)| w).sum(); + let left = ui.available_width() - others - COLUMN_SPACING * (HEADERS.len() - 1) as f32; + widths[DESCRIPTION] = left.max(width(HEADERS[DESCRIPTION])); + widths +} + +/// One grid cell exactly `width` wide; text wider than that truncates. +fn cell(ui: &mut egui::Ui, width: f32, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + ui.allocate_ui_with_layout(egui::vec2(width, crate::ui_kit::row_height()), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(width); + add(ui) + }) + .inner +} + /// The label of one of [`BOM_KEYS`]. fn field_label(key: &str) -> &str { metadata::key(key).map_or(key, |k| crate::i18n::tr(k.label)) @@ -122,31 +157,34 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }); ui.separator(); egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - egui::Grid::new("sc_bom_grid").num_columns(6).striped(true).spacing([14.0, 4.0]).show(ui, |ui| { - for h in ["Item", "Part number", "Description", "Rev", "Qty", "Definition"] { - ui.label(RichText::new(h).strong().color(t.text_dim)); + let widths = column_widths(ui, &rows); + // The item cell (a picker for a row, dim text for a sub-part) is drawn by the caller. + let rest = |ui: &mut egui::Ui, row: &Value| { + for (i, key) in COLUMN_KEYS.iter().enumerate().skip(1) { + let dim = *key == "definition"; + cell(ui, widths[i], |ui| { + ui.label(if dim { RichText::new(text(row, key)).color(t.text_dim) } else { RichText::new(text(row, key)) }) + }); + } + ui.end_row(); + }; + // No minimum column width: the widths above add up to the grid's, so padding a + // narrow column (Rev, Qty) would push the grid out of the window. + egui::Grid::new("sc_bom_grid").num_columns(6).striped(true).min_col_width(0.0).spacing([COLUMN_SPACING, 4.0]).show(ui, |ui| { + for (h, w) in HEADERS.iter().zip(widths) { + cell(ui, w, |ui| ui.label(RichText::new(*h).strong().color(t.text_dim))); } ui.end_row(); for (i, row) in rows.iter().enumerate() { let picked = d.picked == Some(i); - if crate::ui_kit::list_picker(ui, &i.to_string(), &text(row, "item"), picked).clicked() { + if cell(ui, widths[0], |ui| crate::ui_kit::list_picker(ui, &i.to_string(), &text(row, "item"), picked)).clicked() { d.picked = if picked { None } else { Some(i) }; d.fields = BOM_KEYS.iter().map(|k| text(row, k)).collect(); } - ui.label(text(row, "part_number")); - ui.label(text(row, "description")); - ui.label(text(row, "revision")); - ui.label(text(row, "count")); - ui.label(RichText::new(text(row, "definition")).color(t.text_dim)); - ui.end_row(); + rest(ui, row); for c in row["children"].as_array().into_iter().flatten() { - ui.label(RichText::new(text(c, "item")).color(t.text_dim)); - ui.label(text(c, "part_number")); - ui.label(text(c, "description")); - ui.label(text(c, "revision")); - ui.label(text(c, "count")); - ui.label(RichText::new(text(c, "definition")).color(t.text_dim)); - ui.end_row(); + cell(ui, widths[0], |ui| ui.label(RichText::new(text(c, "item")).color(t.text_dim))); + rest(ui, c); } } }); @@ -251,6 +289,58 @@ mod tests { assert_eq!((&m["part_number"], &m["description"], &m["revision"]), (&json!("PL-100"), &json!("Plate, 3 mm"), &json!("B")), "{m}"); } + /// `column_widths` for `rows` in a grid `width` wide, and the measured width of each text. + fn widths_in(width: f32, rows: &[serde_json::Value], texts: &[&str]) -> ([f32; 6], Vec) { + let ctx = egui::Context::default(); + let mut out = ([0.0; 6], Vec::new()); + // The first frame loads the fonts. + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| { + ui.allocate_ui(egui::vec2(width, 100.0), |ui| { + ui.set_max_width(width); + let font = egui::TextStyle::Body.resolve(ui.style()); + let measure = |s: &str| ui.painter().layout_no_wrap(s.to_owned(), font.clone(), egui::Color32::PLACEHOLDER).size().x; + out = (super::column_widths(ui, rows), texts.iter().map(|s| measure(s)).collect()); + }); + }) + .textures_delta + .clear(); + out + } + + #[test] + fn columns_fit_their_contents_and_the_description_takes_the_rest() { + let short = + [json!({"item": 1, "part_number": "ISO 4762 M5x16", "description": "Bolt", "revision": "A", "count": 12, "definition": "SHCS M5x16"})]; + let (w, text) = widths_in(800.0, &short, &["ISO 4762 M5x16", "SHCS M5x16"]); + assert!(w[1] >= text[0] && w[5] >= text[1], "part number and definition are not cut: {w:?} {text:?}"); + let used = w.iter().sum::() + super::COLUMN_SPACING * 5.0; + assert!((used - 800.0).abs() < 0.5, "the description fills the grid: {w:?} uses {used}"); + + let long = [json!({"item": 1, "part_number": "P", "description": "Socket head cap screw ".repeat(20), "count": 1})]; + let (w, _) = widths_in(800.0, &long, &[]); + assert!(w[2] < 800.0, "a long description truncates instead of widening the grid: {w:?}"); + + let (w, header) = widths_in(10.0, &short, &["Description"]); + assert!(w.iter().all(|x| x.is_finite() && *x >= 0.0), "{w:?}"); + assert!(w[2] >= header[0], "the description keeps its header in a narrow grid: {w:?}"); + } + + #[test] + fn the_description_column_takes_the_window_width() { + let mut h = Harness::new(); + h.app.run("component.create", json!({"name": "Plate"})).unwrap(); + h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 3})).unwrap(); + h.app.run("component.activate", json!({"component": 0})).unwrap(); + h.app.run("component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "description": "Plate"})).unwrap(); + h.step(&json!({"start": "assembly.bom"})).unwrap(); + h.frames(2); + let (Some(desc), Some(rev)) = (h.widget("Description"), h.widget("Rev")) else { panic!("the grid's headers are drawn") }; + // Before, every column but the last was as narrow as a button and the grid used a third of the window. + let card = f64::from(crate::theme::Tokens::get().form_card_width); + assert!(rev[0] - desc[0] > card, "Description spreads out: it starts at {}, Rev at {}", desc[0], rev[0]); + } + #[test] fn sub_parts_show_under_their_part() { let mut h = Harness::new();