brep_app/column_tree.rs
1//! A tree table with resizable, reorderable, hideable, sortable columns.
2//!
3//! Callers supply columns, rows, and layout; [`ColumnTreeOut`] reports edits and
4//! actions for the caller to apply after drawing. Consumer-specific behavior stays
5//! in the panel. The first visible column uses [`crate::panels::tree::node`].
6//!
7//! Layout is mutated directly; callers persist it when `layout_changed` is set.
8//! [`ColumnLayout::frozen`] pins leading columns, so this widget owns horizontal
9//! scrolling. Expansion remains caller-owned. Transient drag, menu, and text-edit
10//! state lives in egui memory keyed by [`ColumnTreeSpec::id`]. Text edits commit on
11//! focus loss or Enter because applying a cell edit may rebuild geometry.
12//!
13//! Row actions share one menu for cell clicks and right-clicks. Disabled entries
14//! remain visible with tooltips explaining why they are unavailable.
15
16use crate::color::parse_hex_color;
17use crate::panels::tree::{self, TreeRow};
18use eframe::egui;
19use serde_json::Value;
20use std::collections::{HashMap, HashSet};
21
22/// Minimum column width, in points — narrow enough to park a column out of the
23/// way, wide enough that its resize grip is still catchable.
24pub const MIN_COLUMN_WIDTH: f32 = 28.0;
25
26/// The default width of a column whose [`ColumnLayout`] carries none.
27pub const DEFAULT_COLUMN_WIDTH: f32 = 110.0;
28
29/// Width of the draggable divider strip at a header cell's right edge.
30const GRIP: f32 = 5.0;
31
32/// Horizontal padding inside a cell, so text does not touch the divider.
33const CELL_PAD: f32 = 3.0;
34
35/// Width of the band between the frozen columns and the scrolling ones.
36const FREEZE_GAP: f32 = 4.0;
37
38/// What a column's cells are, and therefore which editor the widget draws.
39#[derive(Debug, Clone, PartialEq)]
40pub enum CellKind {
41 /// Free text. Committed on focus-loss / Enter, NOT per keystroke.
42 Text,
43 /// A number, edited with a drag-value.
44 Numeric { step: f64 },
45 /// A fixed set of choices — a combobox. An empty string is always
46 /// offered as the "unset" choice, so a user can clear a cell.
47 Choice { options: Vec<String> },
48 /// An action button in every row of the column. The widget reports the
49 /// click ([`ColumnTreeOut::buttons`]); the consumer acts.
50 Button { label: String },
51 /// The row's ACTION MENU trigger. Every row draws `label`; clicking it
52 /// opens that row's [`RowNode::actions`] — the same menu a right-click on
53 /// the row opens. A row that declares no action draws the trigger greyed.
54 Actions { label: String },
55 /// Status glyphs drawn inline, from a cell value shaped
56 /// `[{"glyph": "⏚", "color": "#ff9f0a", "tooltip": "…"}, …]` (`color` and
57 /// `tooltip` optional). An optional `action` makes a glyph a button that
58 /// emits a row action. A plain text cell cannot colour part of its own
59 /// content, and these glyphs carry meaning IN their colour — a constraint
60 /// status, an out-of-date badge — so they get a kind rather than being
61 /// flattened into a string.
62 Badges,
63 /// A boolean, drawn as a checkbox. The cell's value is read with
64 /// [`Value::as_bool`]; a missing value reads false. A row that is not
65 /// [`RowNode::editable`] still DRAWS its box (so the column stays
66 /// readable) but cannot be clicked — a derived grouping row has no state
67 /// of its own to toggle.
68 Toggle,
69 /// Displayed, never edited (a derived value — a rolled-up quantity, a
70 /// computed length).
71 ReadOnly,
72}
73
74/// One column: its cell key, its heading, its editor, its default width.
75#[derive(Debug, Clone, PartialEq)]
76pub struct ColumnSpec {
77 /// The key this column reads out of [`RowNode::cells`]. Unique per spec.
78 pub key: String,
79 /// The heading text.
80 pub label: String,
81 pub kind: CellKind,
82 /// Width used when [`ColumnLayout::widths`] carries none for this key.
83 pub default_width: f32,
84}
85
86impl ColumnSpec {
87 /// A column with the default width.
88 pub fn new(key: impl Into<String>, label: impl Into<String>, kind: CellKind) -> Self {
89 Self {
90 key: key.into(),
91 label: label.into(),
92 kind,
93 default_width: DEFAULT_COLUMN_WIDTH,
94 }
95 }
96
97 pub fn width(mut self, width: f32) -> Self {
98 self.default_width = width;
99 self
100 }
101}
102
103/// One entry in a row's action menu: what to call it, whether this ROW allows
104/// it, and how to draw it. Everything here is the consumer's vocabulary — the
105/// widget only ever compares [`RowAction::id`] for equality when it reports the
106/// click back.
107#[derive(Debug, Clone, PartialEq)]
108pub struct RowAction {
109 /// Stable id, handed back in [`RowActionClick::action`].
110 pub id: String,
111 /// The menu text.
112 pub label: String,
113 /// Hover text. Set it on a DISABLED entry to say why it is refused — the
114 /// entry is greyed, not hidden, so this is where the reason is told.
115 pub tooltip: String,
116 /// Whether THIS ROW allows it. A disabled entry is drawn greyed and
117 /// reports nothing.
118 pub enabled: bool,
119 /// Draw a separator line above this entry (grouping, e.g. before a
120 /// destructive tail).
121 pub separator_above: bool,
122 /// Draw in the error colour — an entry that destroys something.
123 pub destructive: bool,
124}
125
126impl RowAction {
127 /// An enabled entry.
128 pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
129 Self {
130 id: id.into(),
131 label: label.into(),
132 tooltip: String::new(),
133 enabled: true,
134 separator_above: false,
135 destructive: false,
136 }
137 }
138
139 pub fn tooltip(mut self, text: impl Into<String>) -> Self {
140 self.tooltip = text.into();
141 self
142 }
143
144 /// Refuse this entry ON THIS ROW, saying why (the greyed entry's tooltip).
145 pub fn disabled(mut self, why: impl Into<String>) -> Self {
146 self.enabled = false;
147 self.tooltip = why.into();
148 self
149 }
150
151 pub fn separator_above(mut self) -> Self {
152 self.separator_above = true;
153 self
154 }
155
156 pub fn destructive(mut self) -> Self {
157 self.destructive = true;
158 self
159 }
160}
161
162/// One row. Rows nest — this is a TREE, not a flat table — and each row's
163/// cells are looked up by column key, so adding a column never touches the
164/// row builder's shape.
165#[derive(Debug, Clone, Default, PartialEq)]
166pub struct RowNode {
167 /// Stable, unique across the whole tree — the id every out-value names.
168 pub id: String,
169 /// Cell values by column key. A missing key draws an empty cell.
170 pub cells: HashMap<String, Value>,
171 /// Whether this row's cells accept edits. A read-only row still draws its
172 /// values (and its buttons), it just cannot be typed into — the BOM's
173 /// nested sub-assembly rows, whose data belongs to another document.
174 pub editable: bool,
175 /// Draw the first column's label emphasized (the selected row).
176 pub selected: bool,
177 /// Expansion is the CALLER's, as in `panels::tree`.
178 pub expanded: bool,
179 /// What this row offers, in menu order. EMPTY means the row offers
180 /// nothing: its trigger cell draws greyed and a right-click on it opens
181 /// nothing (the BOM's nested sub-assembly rows, which own no feature in
182 /// this document).
183 pub actions: Vec<RowAction>,
184 pub children: Vec<RowNode>,
185}
186
187impl RowNode {
188 pub fn new(id: impl Into<String>) -> Self {
189 Self {
190 id: id.into(),
191 editable: true,
192 ..Default::default()
193 }
194 }
195
196 /// Set one cell.
197 pub fn cell(mut self, key: impl Into<String>, value: Value) -> Self {
198 self.cells.insert(key.into(), value);
199 self
200 }
201
202 /// Set this row's action menu.
203 pub fn actions(mut self, actions: Vec<RowAction>) -> Self {
204 self.actions = actions;
205 self
206 }
207}
208
209/// The user's column arrangement — the widget WRITES this (header drag,
210/// divider drag, hide/show, sort click) and the consumer owns and persists it.
211#[derive(Debug, Clone, Default, PartialEq)]
212pub struct ColumnLayout {
213 /// Column keys in display order. Keys absent from the spec are ignored;
214 /// spec columns absent from `order` are appended in spec order, so a
215 /// consumer may start with an empty layout and get the spec's order.
216 pub order: Vec<String>,
217 /// Column keys the user has hidden.
218 pub hidden: HashSet<String>,
219 /// Per-column width overrides, in points.
220 pub widths: HashMap<String, f32>,
221 /// `(column key, ascending)`. `None` = the consumer's own row order.
222 pub sort: Option<(String, bool)>,
223 /// How many LEADING columns are held fixed while the rest scroll
224 /// horizontally. Counted over the arranged order INCLUDING hidden columns,
225 /// so hiding a frozen column does not silently promote the next one into
226 /// the frozen region. `0` = nothing frozen, one plain scrolling table.
227 pub frozen: usize,
228}
229
230/// One cell was edited.
231#[derive(Debug, Clone, PartialEq)]
232pub struct CellEdit {
233 pub row_id: String,
234 pub column: String,
235 pub value: Value,
236}
237
238/// A [`CellKind::Button`] cell was clicked.
239#[derive(Debug, Clone, PartialEq)]
240pub struct CellClick {
241 pub row_id: String,
242 pub column: String,
243}
244
245/// A row's action menu or actionable badge fired.
246#[derive(Debug, Clone, PartialEq)]
247pub struct RowActionClick {
248 pub row_id: String,
249 /// The [`RowAction::id`] the consumer declared.
250 pub action: String,
251}
252
253/// Everything the consumer supplies. Borrowed; the widget holds no state of
254/// its own beyond egui memory.
255pub struct ColumnTreeSpec<'a> {
256 /// Scope key for this tree's transient view state and widget ids. Must be
257 /// STABLE and UNIQUE per tree — two trees sharing it share their drag
258 /// state and their text buffers.
259 pub id: &'a str,
260 /// The columns, in spec order (the fallback order when `layout.order` does
261 /// not name them).
262 pub columns: &'a [ColumnSpec],
263 /// An optional always-open root row above the tree (`"Assembly"`), drawn
264 /// with its own cells taken from `root_cells`.
265 pub root_label: Option<&'a str>,
266 /// Cells for the root row, when there is one.
267 pub root_cells: Option<&'a HashMap<String, Value>>,
268 /// Text drawn in place of the body when `rows` is empty.
269 pub empty_hint: Option<&'a str>,
270 /// Prefix for every published hit key. `""` for a consumer that shows one
271 /// tree at a time.
272 pub hits_prefix: &'a str,
273}
274
275/// What the user did in one drawn frame.
276#[derive(Debug, Default, Clone, PartialEq)]
277pub struct ColumnTreeOut {
278 /// Cell edits, in draw order. A frame can carry at most one (egui gives
279 /// one widget the focus), but the vec keeps the caller from having to care.
280 pub edits: Vec<CellEdit>,
281 /// Button cells clicked this frame.
282 pub buttons: Vec<CellClick>,
283 /// Row action-menu entries chosen this frame.
284 pub actions: Vec<RowActionClick>,
285 /// A row's `[+]`/`[-]` box was clicked — the caller flips its own
286 /// expansion state (expansion is the caller's, as in `panels::tree`).
287 pub toggled: Option<String>,
288 /// A row was clicked (select) — on its first column's label, or anywhere
289 /// else along its band that no cell of its own claimed.
290 pub clicked: Option<String>,
291 /// A row was double-clicked (open its dialog), over the same area as
292 /// [`Self::clicked`]. egui reports the second press as a click too, so on
293 /// this frame `clicked` names the same row: a consumer checks this first.
294 pub double_clicked: Option<String>,
295 /// A row (any of its cells, in either pane) is under the pointer this
296 /// frame — the consumer's hover-to-highlight hook. `None` when the pointer
297 /// is over the header, the root row, or off the table.
298 pub hovered: Option<String>,
299 /// The layout was changed by the user (reorder / resize / hide / sort) —
300 /// the caller persists it.
301 pub layout_changed: bool,
302}
303
304/// Draw ONE complete column tree and return what the user did.
305///
306/// `hits`, when supplied, receives widget screen rects for the headed
307/// verifier, all prefixed with [`ColumnTreeSpec::hits_prefix`]:
308///
309/// | key | what |
310/// |---|---|
311/// | `col:{key}` | a column heading |
312/// | `grip:{key}` | a heading's resize divider |
313/// | `row:{row id}` | the row's click band (of the pane holding column 0) |
314/// | `box:{row id}` | the first column's collapse box |
315/// | `cell:{row id}:{col key}` | one cell's editor |
316/// | `menu:{row id}` | the row's action-menu trigger cell |
317/// | `menuitem:{row id}:{action id}` | one entry of the OPEN action menu |
318/// | `freeze:divider` | the frozen / scrolling boundary (only when frozen) |
319pub fn column_tree(
320 ui: &mut egui::Ui,
321 spec: &ColumnTreeSpec<'_>,
322 layout: &mut ColumnLayout,
323 rows: &[RowNode],
324 mut hits: Option<&mut HashMap<String, egui::Rect>>,
325) -> ColumnTreeOut {
326 let mut out = ColumnTreeOut::default();
327 // The arranged order INCLUDING the hidden columns: the freeze boundary is
328 // counted over THIS, so hiding a frozen column cannot silently promote the
329 // next one into the frozen band.
330 let arranged = arranged_columns(spec, layout);
331 let visible: Vec<&ColumnSpec> = arranged
332 .iter()
333 .copied()
334 .filter(|column| !layout.hidden.contains(&column.key))
335 .collect();
336 if visible.is_empty() {
337 ui.label(egui::RichText::new("(every column is hidden)").weak());
338 return out;
339 }
340
341 // Column widths, in the drawn order.
342 let widths: Vec<f32> = visible
343 .iter()
344 .map(|column| column_width(layout, column))
345 .collect();
346
347 // How many DRAWN columns are frozen. Freezing every column is meaningless
348 // — there is nothing left to scroll it against — and would strand any
349 // column past the pane's right edge with no way to reach it, so it reads
350 // as "frozen: none".
351 let mut frozen = arranged
352 .iter()
353 .take(layout.frozen)
354 .filter(|column| !layout.hidden.contains(&column.key))
355 .count();
356 if frozen >= visible.len() {
357 frozen = 0;
358 }
359
360 ui.spacing_mut().item_spacing.y = 2.0;
361 // The width to lay out in. `available_rect_before_wrap` can be WIDER than
362 // what is on screen — an outer scroll area hands its inner `Ui` a max_rect
363 // that ignores its own viewport — and the horizontal scroll area below
364 // sizes its viewport from this rect. A `full` wider than the clip
365 // overstates that viewport by the difference, and egui clamps scrolling at
366 // `content - viewport`: the last columns then have no scroll position that
367 // brings them inside the pane. In the shipped BOM that stranded the
368 // rightmost column, which is the ACTIONS one — its trigger cell was never
369 // drawn at any scroll offset, so `menu:<row>` was a key the pane could not
370 // publish. Found by the bom-menu verifier migration (2026-09-13); the
371 // right-click trigger on the row was carrying the whole feature.
372 let full = ui.available_rect_before_wrap();
373 let full = egui::Rect::from_min_max(
374 full.min,
375 egui::pos2(full.max.x.min(ui.clip_rect().max.x), full.max.y),
376 );
377 // The frozen band never eats the whole width — something has to be left to
378 // scroll in.
379 let frozen_width: f32 = widths[..frozen]
380 .iter()
381 .sum::<f32>()
382 .min((full.width() - MIN_COLUMN_WIDTH).max(0.0));
383
384 // Which row's action menu either trigger asked for, this frame.
385 let mut pending: Option<MenuOpen> = None;
386 // Heading bounds from BOTH panes, merged: a reorder drag that crosses the
387 // freeze boundary must find its drop target, because dropping a column on
388 // the other side of the boundary is how a column is frozen or unfrozen
389 // with the mouse.
390 let mut bounds: Vec<(String, f32, f32)> = Vec::new();
391 let mut bottom = full.top();
392
393 if frozen > 0 {
394 let rect = egui::Rect::from_min_max(
395 full.min,
396 egui::pos2(full.min.x + frozen_width, full.max.y),
397 );
398 let mut pane = ui.new_child(
399 egui::UiBuilder::new()
400 .max_rect(rect)
401 .layout(egui::Layout::top_down(egui::Align::Min))
402 .id_salt((spec.id, "column-tree-frozen")),
403 );
404 // Clip the frozen band HORIZONTALLY only: its height belongs to the
405 // caller (an outer vertical scroll area owns that axis).
406 pane.set_clip_rect(pane.clip_rect().intersect(egui::Rect::from_x_y_ranges(
407 rect.x_range(),
408 ui.clip_rect().y_range(),
409 )));
410 pane.spacing_mut().item_spacing.y = 2.0;
411 draw_pane(
412 &mut pane,
413 spec,
414 layout,
415 &visible[..frozen],
416 &widths[..frozen],
417 0,
418 frozen_width,
419 rows,
420 &mut hits,
421 &mut out,
422 &mut pending,
423 &mut bounds,
424 );
425 bottom = bottom.max(pane.min_rect().bottom());
426 }
427
428 // The scrolling remainder. The widget owns this scroll area rather than the
429 // caller, because a scroll area OUTSIDE the widget would carry the frozen
430 // columns away with everything else.
431 let scroll_left = full.min.x + if frozen > 0 { frozen_width + FREEZE_GAP } else { 0.0 };
432 let scroll_rect = egui::Rect::from_min_max(egui::pos2(scroll_left, full.min.y), full.max);
433 let viewport = scroll_rect.width();
434 let mut pane = ui.new_child(
435 egui::UiBuilder::new()
436 .max_rect(scroll_rect)
437 .layout(egui::Layout::top_down(egui::Align::Min))
438 .id_salt((spec.id, "column-tree-scrolling")),
439 );
440 let rest: f32 = widths[frozen..].iter().sum();
441 // (egui's default `ScrollSource` drags to scroll on TOUCH only, which is
442 // what we want: a mouse drag-to-scroll would fight the header's reorder
443 // drag and a text cell's selection drag.)
444 egui::ScrollArea::horizontal()
445 .id_salt((spec.id, "column-tree-hscroll"))
446 .show(&mut pane, |ui: &mut egui::Ui| {
447 ui.spacing_mut().item_spacing.y = 2.0;
448 draw_pane(
449 ui,
450 spec,
451 layout,
452 &visible[frozen..],
453 &widths[frozen..],
454 frozen,
455 rest.max(viewport),
456 rows,
457 &mut hits,
458 &mut out,
459 &mut pending,
460 &mut bounds,
461 );
462 if rest > viewport && ui.spacing().scroll.floating {
463 // A GUTTER for the horizontal scrollbar. egui's bars float over
464 // the content, and this one lands on the LAST ROW — where it
465 // silently eats every click on the bottom half of that row's
466 // cells (found by the headed verifier: the action trigger opened
467 // from its top edge and not from its centre). Solid bars already
468 // reserve their own space outside the content.
469 let scroll = ui.spacing().scroll;
470 ui.add_space(scroll.bar_width + scroll.bar_inner_margin + scroll.bar_outer_margin);
471 }
472 });
473 bottom = bottom.max(pane.min_rect().bottom());
474
475 let used = egui::Rect::from_min_max(full.min, egui::pos2(full.max.x, bottom));
476 ui.advance_cursor_after_rect(used);
477
478 // The boundary, so the user can SEE which columns are pinned.
479 if frozen > 0 {
480 let x = full.min.x + frozen_width + FREEZE_GAP * 0.5;
481 let divider = egui::Rect::from_min_max(
482 egui::pos2(x - 1.0, used.top()),
483 egui::pos2(x + 1.0, used.bottom()),
484 );
485 ui.painter()
486 .rect_filled(divider, 0.0, ui.visuals().widgets.active.bg_fill);
487 publish(&mut hits, spec, "freeze:divider", divider);
488 }
489
490 finish_reorder(ui, spec, layout, &arranged, &bounds, &mut out);
491 // ONE menu, drawn from whatever record a trigger left. `pending` is applied
492 // AFTER it — apply it first and the popup's own close-on-click would see
493 // the very click that opened it and shut immediately.
494 row_action_menu(ui, spec, rows, &mut hits, &mut out, &mut pending);
495 out
496}
497
498/// Draw ONE pane — a contiguous run of columns, with the header and every row.
499/// The frozen band and the scrolling remainder are the same code walking the
500/// same rows in the same order, which is what keeps them aligned.
501///
502/// `offset` is the drawn index of `columns[0]`, so the pane holding column 0
503/// (and only it) draws the TREE cell. `band` is the width every row spans here.
504#[allow(clippy::too_many_arguments)]
505fn draw_pane(
506 ui: &mut egui::Ui,
507 spec: &ColumnTreeSpec<'_>,
508 layout: &mut ColumnLayout,
509 columns: &[&ColumnSpec],
510 widths: &[f32],
511 offset: usize,
512 band: f32,
513 rows: &[RowNode],
514 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
515 out: &mut ColumnTreeOut,
516 pending: &mut Option<MenuOpen>,
517 bounds: &mut Vec<(String, f32, f32)>,
518) {
519 header(ui, spec, layout, columns, widths, band, hits, out, bounds);
520 ui.separator();
521
522 if let Some(label) = spec.root_label {
523 let mut cells = spec.root_cells.cloned().unwrap_or_default();
524 // The root's label belongs to whichever column is drawn FIRST — the
525 // tree column follows the user's order, so it is not a fixed key.
526 if offset == 0 {
527 cells.insert(columns[0].key.clone(), Value::String(label.to_string()));
528 }
529 let root = RowNode {
530 id: format!("{}__root", spec.id),
531 cells,
532 editable: false,
533 selected: false,
534 expanded: true,
535 actions: Vec::new(),
536 children: Vec::new(),
537 };
538 draw_row(
539 ui, spec, columns, widths, offset, band, &root, &[], true, true, hits, out, pending,
540 );
541 }
542
543 if rows.is_empty() {
544 if let Some(hint) = spec.empty_hint {
545 if offset == 0 {
546 let guides = tree::child_guides(&[], true);
547 tree::node(ui, TreeRow::leaf(&guides, true, hint), |_| {});
548 } else {
549 // The other pane still spends the same row, so the two panes
550 // keep the same height.
551 ui.allocate_exact_size(
552 egui::vec2(band, ui.spacing().interact_size.y),
553 egui::Sense::hover(),
554 );
555 }
556 }
557 return;
558 }
559
560 let ordered = sorted_siblings(rows, layout);
561 let last = ordered.len();
562 for (index, row) in ordered.iter().enumerate() {
563 draw_subtree(
564 ui,
565 spec,
566 layout,
567 columns,
568 widths,
569 offset,
570 band,
571 row,
572 &[],
573 index + 1 == last,
574 hits,
575 out,
576 pending,
577 );
578 }
579}
580
581/// Every spec column in the user's order — `layout.order` first (spec columns
582/// only), then any spec column the layout has never heard of. Hidden columns
583/// KEEP their slot here; the drawn set filters them out afterwards, and the
584/// freeze boundary counts over this list.
585fn arranged_columns<'a>(
586 spec: &'a ColumnTreeSpec<'_>,
587 layout: &ColumnLayout,
588) -> Vec<&'a ColumnSpec> {
589 let mut out: Vec<&ColumnSpec> = Vec::new();
590 for key in &layout.order {
591 if let Some(column) = spec.columns.iter().find(|c| &c.key == key) {
592 if !out.iter().any(|c| c.key == column.key) {
593 out.push(column);
594 }
595 }
596 }
597 for column in spec.columns {
598 if !out.iter().any(|c| c.key == column.key) {
599 out.push(column);
600 }
601 }
602 out
603}
604
605fn column_width(layout: &ColumnLayout, column: &ColumnSpec) -> f32 {
606 layout
607 .widths
608 .get(&column.key)
609 .copied()
610 .unwrap_or(column.default_width)
611 .max(MIN_COLUMN_WIDTH)
612}
613
614/// One pane's header: a heading per column (click = sort, drag = reorder,
615/// right-click = the show/hide checklist) with a resize grip at each right
616/// edge. The drop of a reorder drag is resolved by [`finish_reorder`] once
617/// BOTH panes have contributed their bounds.
618#[allow(clippy::too_many_arguments)]
619fn header(
620 ui: &mut egui::Ui,
621 spec: &ColumnTreeSpec<'_>,
622 layout: &mut ColumnLayout,
623 visible: &[&ColumnSpec],
624 widths: &[f32],
625 width: f32,
626 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
627 out: &mut ColumnTreeOut,
628 bounds: &mut Vec<(String, f32, f32)>,
629) {
630 let height = ui.spacing().interact_size.y;
631 let (band, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
632 let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
633 let dragging: Option<String> = ui.data(|d| d.get_temp(drag_key));
634
635 let mut x = band.left();
636 // The reorder DROP target is decided from the pointer's x at drag end, so
637 // the boundaries are collected while the headings are laid out.
638 let first = bounds.len();
639 for (column, width) in visible.iter().zip(widths) {
640 let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
641 bounds.push((column.key.clone(), cell.left(), cell.right()));
642
643 let resp = ui.interact(
644 cell,
645 ui.id().with(("column-tree-head", spec.id, &column.key)),
646 egui::Sense::click_and_drag(),
647 );
648 let held = dragging.as_deref() == Some(column.key.as_str());
649 let fill = if held {
650 ui.visuals().selection.bg_fill.gamma_multiply(0.45)
651 } else if resp.hovered() {
652 ui.visuals().widgets.hovered.bg_fill
653 } else {
654 ui.visuals().widgets.noninteractive.bg_fill
655 };
656 ui.painter().rect_filled(cell, 0.0, fill);
657 // The sort marker rides the heading text, so the sorted column is
658 // obvious without a second row of chrome.
659 let marker = match &layout.sort {
660 Some((key, true)) if key == &column.key => " \u{25B2}",
661 Some((key, false)) if key == &column.key => " \u{25BC}",
662 _ => "",
663 };
664 let text = format!("{}{marker}", column.label);
665 ui.painter().text(
666 egui::pos2(cell.left() + CELL_PAD, cell.center().y),
667 egui::Align2::LEFT_CENTER,
668 elide(ui, &text, *width - 2.0 * CELL_PAD),
669 egui::TextStyle::Body.resolve(ui.style()),
670 ui.visuals().strong_text_color(),
671 );
672 publish(hits, spec, &format!("col:{}", column.key), cell);
673
674 // Right-click ANY heading → the show/hide checklist. Hiding lives here
675 // rather than on a toolbar because the column is the thing being
676 // hidden and this is where the user's hand already is.
677 resp.context_menu(|ui| {
678 ui.label(egui::RichText::new("Columns").strong());
679 for candidate in spec.columns {
680 let mut shown = !layout.hidden.contains(&candidate.key);
681 if ui.checkbox(&mut shown, &candidate.label).changed() {
682 if shown {
683 layout.hidden.remove(&candidate.key);
684 } else {
685 layout.hidden.insert(candidate.key.clone());
686 }
687 out.layout_changed = true;
688 }
689 }
690 });
691
692 // A CLICK sorts. egui reports `clicked()` false once a press turns
693 // into a drag, so the click and the reorder drag share the heading
694 // without a mode.
695 if resp.clicked() {
696 layout.sort = match &layout.sort {
697 Some((key, true)) if key == &column.key => Some((column.key.clone(), false)),
698 Some((key, false)) if key == &column.key => None,
699 _ => Some((column.key.clone(), true)),
700 };
701 out.layout_changed = true;
702 }
703 if resp.drag_started() {
704 ui.data_mut(|d| d.insert_temp(drag_key, column.key.clone()));
705 }
706
707 ui.painter().line_segment(
708 [
709 egui::pos2(cell.right(), band.top()),
710 egui::pos2(cell.right(), band.bottom()),
711 ],
712 ui.visuals().widgets.noninteractive.bg_stroke,
713 );
714 x = cell.right();
715 }
716
717 // The resize grips, in a SECOND pass. A grip straddles the divider, so it
718 // overlaps the heading to its right — and egui hands an overlapped point to
719 // the LAST widget registered there. Interleaved with the headings, every
720 // grip would therefore lose its own hit to the next heading and no column
721 // would ever resize.
722 for (column, (_, _, right)) in visible.iter().zip(&bounds[first..]) {
723 let grip_rect = egui::Rect::from_min_max(
724 egui::pos2(right - GRIP * 0.5, band.top()),
725 egui::pos2(right + GRIP * 0.5, band.bottom()),
726 );
727 let grip = ui.interact(
728 grip_rect,
729 ui.id().with(("column-tree-grip", spec.id, &column.key)),
730 egui::Sense::drag(),
731 );
732 if grip.hovered() || grip.dragged() {
733 ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
734 }
735 if grip.dragged() {
736 let next = (column_width(layout, column) + grip.drag_delta().x).max(MIN_COLUMN_WIDTH);
737 layout.widths.insert(column.key.clone(), next);
738 out.layout_changed = true;
739 }
740 publish(hits, spec, &format!("grip:{}", column.key), grip_rect);
741 }
742}
743
744/// Finish a reorder: on release, the dragged column moves to whichever heading
745/// the pointer is over — in EITHER pane, so dragging a column across the freeze
746/// boundary is what freezes or unfreezes it.
747fn finish_reorder(
748 ui: &egui::Ui,
749 spec: &ColumnTreeSpec<'_>,
750 layout: &mut ColumnLayout,
751 arranged: &[&ColumnSpec],
752 bounds: &[(String, f32, f32)],
753 out: &mut ColumnTreeOut,
754) {
755 let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
756 let Some(held) = ui.data(|d| d.get_temp::<String>(drag_key)) else {
757 return;
758 };
759 if ui.input(|i| i.pointer.any_down()) {
760 return;
761 }
762 ui.data_mut(|d| d.remove::<String>(drag_key));
763 let Some(pos) = ui.input(|i| i.pointer.latest_pos()) else {
764 return;
765 };
766 if let Some((target, _, _)) = bounds
767 .iter()
768 .find(|(_, left, right)| pos.x >= *left && pos.x < *right)
769 {
770 if *target != held && move_column(layout, arranged, &held, target) {
771 out.layout_changed = true;
772 }
773 }
774}
775
776/// Move `held` to `target`'s slot in the layout order, materializing the
777/// current arranged order first so a layout that never named its columns still
778/// reorders correctly. Returns whether anything moved.
779fn move_column(
780 layout: &mut ColumnLayout,
781 arranged: &[&ColumnSpec],
782 held: &str,
783 target: &str,
784) -> bool {
785 let mut order: Vec<String> = layout.order.clone();
786 // Seed from the drawn order so the first drag on a fresh layout is not a
787 // no-op against an empty `order`.
788 for column in arranged {
789 if !order.iter().any(|key| key == &column.key) {
790 order.push(column.key.clone());
791 }
792 }
793 let Some(from) = order.iter().position(|key| key == held) else {
794 return false;
795 };
796 let key = order.remove(from);
797 let Some(to) = order.iter().position(|k| k == target) else {
798 order.insert(from.min(order.len()), key);
799 return false;
800 };
801 order.insert(to, key);
802 layout.order = order;
803 true
804}
805
806/// Draw one row and, when it is open, its children — the recursion that keeps
807/// the rows a TREE.
808#[allow(clippy::too_many_arguments)]
809fn draw_subtree(
810 ui: &mut egui::Ui,
811 spec: &ColumnTreeSpec<'_>,
812 layout: &ColumnLayout,
813 visible: &[&ColumnSpec],
814 widths: &[f32],
815 offset: usize,
816 band: f32,
817 row: &RowNode,
818 guides: &[bool],
819 is_last: bool,
820 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
821 out: &mut ColumnTreeOut,
822 pending: &mut Option<MenuOpen>,
823) {
824 draw_row(
825 ui, spec, visible, widths, offset, band, row, guides, is_last, false, hits, out, pending,
826 );
827 if !row.expanded || row.children.is_empty() {
828 return;
829 }
830 let child_guides = tree::child_guides(guides, is_last);
831 let ordered = sorted_siblings(&row.children, layout);
832 let last = ordered.len();
833 for (index, child) in ordered.iter().enumerate() {
834 draw_subtree(
835 ui,
836 spec,
837 layout,
838 visible,
839 widths,
840 offset,
841 band,
842 child,
843 &child_guides,
844 index + 1 == last,
845 hits,
846 out,
847 pending,
848 );
849 }
850}
851
852/// Sort ONE level of siblings by the layout's sort column. Sorting is
853/// per-level so the nesting survives it — a child never overtakes its parent.
854/// A stable sort, so an unsorted-equal run keeps the consumer's order.
855fn sorted_siblings<'a>(rows: &'a [RowNode], layout: &ColumnLayout) -> Vec<&'a RowNode> {
856 let mut out: Vec<&RowNode> = rows.iter().collect();
857 if let Some((key, ascending)) = &layout.sort {
858 out.sort_by(|a, b| {
859 let ordering = compare_cells(a.cells.get(key), b.cells.get(key));
860 if *ascending {
861 ordering
862 } else {
863 ordering.reverse()
864 }
865 });
866 }
867 out
868}
869
870/// Order two cell values: numbers numerically, everything else by its display
871/// text case-insensitively, and an ABSENT/null cell last in ascending order
872/// (an unfilled cell is not a small value, it is a missing one).
873fn compare_cells(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {
874 use std::cmp::Ordering;
875 let empty = |value: Option<&Value>| match value {
876 None | Some(Value::Null) => true,
877 Some(Value::String(text)) => text.is_empty(),
878 _ => false,
879 };
880 match (empty(a), empty(b)) {
881 (true, true) => return Ordering::Equal,
882 (true, false) => return Ordering::Greater,
883 (false, true) => return Ordering::Less,
884 (false, false) => {}
885 }
886 if let (Some(Value::Number(x)), Some(Value::Number(y))) = (a, b) {
887 if let (Some(x), Some(y)) = (x.as_f64(), y.as_f64()) {
888 return x.partial_cmp(&y).unwrap_or(Ordering::Equal);
889 }
890 }
891 display_text(a).to_lowercase().cmp(&display_text(b).to_lowercase())
892}
893
894/// A cell value as the text a cell shows: a string bare (not JSON-quoted), a
895/// number in its shortest form, anything else as its JSON.
896fn display_text(value: Option<&Value>) -> String {
897 match value {
898 None | Some(Value::Null) => String::new(),
899 Some(Value::String(text)) => text.clone(),
900 Some(other) => other.to_string(),
901 }
902}
903
904/// Draw ONE row: the tree cell in column 0, an editor in each other column.
905#[allow(clippy::too_many_arguments)]
906fn draw_row(
907 ui: &mut egui::Ui,
908 spec: &ColumnTreeSpec<'_>,
909 visible: &[&ColumnSpec],
910 widths: &[f32],
911 offset: usize,
912 band_width: f32,
913 row: &RowNode,
914 guides: &[bool],
915 is_last: bool,
916 root: bool,
917 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
918 out: &mut ColumnTreeOut,
919 pending: &mut Option<MenuOpen>,
920) {
921 let height = ui.spacing().interact_size.y;
922 // THE ROW BAND — the row's click target, allocated BEFORE the cells. A row
923 // is picked by clicking anywhere along it, not only on the text in its
924 // first column: in the shipped BOM that text was 40 pt of a 900 pt row, so
925 // 95 % of every row was dead. egui hands an overlapped point to the LAST
926 // widget registered there, and every cell editor is registered after this,
927 // so a button, a checkbox, a text cell and the collapse box all still take
928 // their own clicks — the band receives only what none of them wanted.
929 //
930 // It does NOT take the keyboard focus: the row's Tab stop is the band
931 // inside `tree::node` (drawn once, in whichever pane holds column 0), so a
932 // frozen table does not give one row two stops.
933 let (band, band_resp) =
934 ui.allocate_exact_size(egui::vec2(band_width, height), egui::Sense::CLICK);
935 let clip = ui.clip_rect();
936
937 // TRIGGER 2 — a right-click ANYWHERE on the row. Read off the raw pointer
938 // rather than from a `Response`, because the cell editors are registered
939 // AFTER this band and egui hands an overlapped point to the LAST widget
940 // registered there: a `context_menu` on the band would silently never fire
941 // over a text cell. Reading the position also leaves the band's own primary
942 // click alone, so the select path above and this one cannot fight.
943 let over_row = band.intersect(clip);
944 if !root && over_row.is_positive() && ui.rect_contains_pointer(over_row) {
945 out.hovered = Some(row.id.clone());
946 }
947
948 // The row's published rect IS its band — what a script clicks has to be
949 // what a user can click, and that is the strip, not the name in it.
950 //
951 // A FROZEN table draws the row once per pane, and only the pane holding
952 // column 0 publishes: `click_widget` aims at a rect's CENTRE, and the
953 // centre of the two bands unioned lands in whichever scrolling column
954 // happens to be halfway across — a text editor, a drag-value — where a
955 // click focuses that editor instead of picking the row. The frozen band
956 // leads with the tree column, so its centre is the row. The scrolling
957 // columns are still clickable; they are just not what the key aims at.
958 if !root && offset == 0 && over_row.is_positive() {
959 publish(hits, spec, &format!("row:{}", row.id), over_row);
960 }
961 // A SELECT click anywhere on the band that no cell claimed. The tree cell
962 // reports its own (see below); this is every other column.
963 if !root && band_resp.clicked() {
964 out.clicked = Some(row.id.clone());
965 }
966 if !root && tree::is_double_click(&band_resp) {
967 out.double_clicked = Some(row.id.clone());
968 }
969 if !row.actions.is_empty()
970 && over_row.is_positive()
971 && ui.input(|i| i.pointer.secondary_clicked())
972 {
973 if let Some(pos) = ui.ctx().input(|i| i.pointer.interact_pos()) {
974 // ...and nothing floating (an open menu, the header's own column
975 // checklist) is above that point.
976 let above = ui.ctx().layer_id_at(pos);
977 let ours = above.is_none() || above == Some(ui.layer_id());
978 if over_row.contains(pos) && ours {
979 *pending = Some(MenuOpen {
980 row: row.id.clone(),
981 pos,
982 });
983 }
984 }
985 }
986
987 // The SELECTION band. A selected row is emphasised across its whole width,
988 // not just by bolding the tree cell's text: this table is as wide as its
989 // configured columns, and a picked component has to be findable at a
990 // glance from anywhere in it. Painted BEFORE the cells so every editor
991 // draws over it, and drawn in both panes (each calls this with its own
992 // band) so the highlight does not stop at the frozen boundary.
993 if row.selected && !root {
994 let visible_band = band.intersect(clip);
995 if visible_band.is_positive() {
996 ui.painter().rect_filled(
997 visible_band,
998 0.0,
999 ui.visuals().selection.bg_fill.gamma_multiply(0.35),
1000 );
1001 }
1002 }
1003
1004 let mut x = band.left();
1005 for (index, (column, width)) in visible.iter().zip(widths).enumerate() {
1006 let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
1007 x = cell.right();
1008 let Some(cell_clip) = cell.intersect(clip).is_positive().then_some(cell.intersect(clip))
1009 else {
1010 continue;
1011 };
1012 let mut child = ui.new_child(
1013 egui::UiBuilder::new()
1014 .max_rect(cell.shrink2(egui::vec2(CELL_PAD, 0.0)))
1015 .layout(egui::Layout::left_to_right(egui::Align::Center))
1016 .id_salt(("column-tree-cell", spec.id, &row.id, &column.key)),
1017 );
1018 child.set_clip_rect(cell_clip);
1019
1020 if offset + index == 0 {
1021 // The TREE cell — drawn by `panels::tree::node` itself, so the
1022 // connector rules and collapse boxes are the shared ones.
1023 let label = display_text(row.cells.get(&column.key));
1024 let expandable = !row.children.is_empty();
1025 let mut tree_row = TreeRow {
1026 guides,
1027 is_last,
1028 expandable,
1029 expanded: row.expanded,
1030 root,
1031 glyph: None,
1032 label: &label,
1033 selected: row.selected,
1034 highlighted: false,
1035 draggable: false,
1036 tint: None,
1037 };
1038 if root {
1039 tree_row.expandable = true;
1040 tree_row.expanded = true;
1041 }
1042 let resp = tree::node(&mut child, tree_row, |_| {});
1043 publish(hits, spec, &format!("box:{}", row.id), resp.box_rect);
1044 if resp.toggled {
1045 out.toggled = Some(row.id.clone());
1046 }
1047 // The tree cell has a band of its OWN (`tree::node` draws one), and
1048 // it is registered after this row's, so inside column 0 it is the
1049 // one that hears a blank-space click. Both are the same intent.
1050 if !root && resp.clicked() {
1051 out.clicked = Some(row.id.clone());
1052 }
1053 if !root && resp.double_clicked() {
1054 out.double_clicked = Some(row.id.clone());
1055 }
1056 } else {
1057 let rect = cell_editor(&mut child, spec, row, column, out, pending, hits);
1058 publish(
1059 hits,
1060 spec,
1061 &format!("cell:{}:{}", row.id, column.key),
1062 rect,
1063 );
1064 if matches!(column.kind, CellKind::Actions { .. }) {
1065 publish(hits, spec, &format!("menu:{}", row.id), rect);
1066 }
1067 }
1068 }
1069}
1070
1071/// Draw ONE non-tree cell's editor and return its rect. A non-editable row
1072/// still SHOWS its value and still offers its buttons and its action menu — it
1073/// just cannot be typed into.
1074fn cell_editor(
1075 ui: &mut egui::Ui,
1076 spec: &ColumnTreeSpec<'_>,
1077 row: &RowNode,
1078 column: &ColumnSpec,
1079 out: &mut ColumnTreeOut,
1080 pending: &mut Option<MenuOpen>,
1081 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1082) -> egui::Rect {
1083 let value = row.cells.get(&column.key);
1084 let width = ui.available_width();
1085 let mut emit = |new_value: Value| {
1086 out.edits.push(CellEdit {
1087 row_id: row.id.clone(),
1088 column: column.key.clone(),
1089 value: new_value,
1090 });
1091 };
1092
1093 match &column.kind {
1094 CellKind::Button { label } => {
1095 let button = ui.add_sized([width, ui.available_height()], egui::Button::new(label));
1096 if button.clicked() {
1097 out.buttons.push(CellClick {
1098 row_id: row.id.clone(),
1099 column: column.key.clone(),
1100 });
1101 }
1102 button.rect
1103 }
1104 CellKind::Actions { label } => {
1105 // TRIGGER 1 — the actions cell. Like the right-click it only
1106 // RECORDS which row was asked for; the menu is drawn once, after
1107 // every row, from that record. A row that offers nothing draws the
1108 // trigger greyed rather than dropping it, so the column stays a
1109 // column.
1110 let offered = !row.actions.is_empty();
1111 let button = ui
1112 .add_enabled_ui(offered, |ui| {
1113 ui.add_sized([width, ui.available_height()], egui::Button::new(label))
1114 })
1115 .inner;
1116 if button.clicked() {
1117 *pending = Some(MenuOpen {
1118 row: row.id.clone(),
1119 pos: button.rect.left_bottom(),
1120 });
1121 }
1122 button.rect
1123 }
1124 // A DISPLAY cell: not selectable, so the click reaches the row band
1125 // behind it. egui labels are drag-to-select by default, which senses
1126 // click and drag and would make a derived value the one piece of the
1127 // row you cannot pick the row by.
1128 CellKind::ReadOnly => ui
1129 .add(
1130 egui::Label::new(display_text(value))
1131 .selectable(false)
1132 .truncate(),
1133 )
1134 .rect,
1135 CellKind::Badges => {
1136 let badges = value.and_then(Value::as_array).cloned().unwrap_or_default();
1137 ui.horizontal(|ui| {
1138 ui.spacing_mut().item_spacing.x = 3.0;
1139 for badge in &badges {
1140 let glyph = badge.get("glyph").and_then(Value::as_str).unwrap_or("");
1141 if glyph.is_empty() {
1142 continue;
1143 }
1144 let color = badge
1145 .get("color")
1146 .and_then(Value::as_str)
1147 .and_then(parse_hex_color)
1148 .unwrap_or_else(|| ui.visuals().text_color());
1149 // A badge glyph carries meaning IN its colour, so it is
1150 // drawn from the icon catalog and tinted — there is no icon
1151 // font to render the character with.
1152 // A badge may name an action; status-only badges remain
1153 // passive and continue to let the row receive the click.
1154 if let Some(action) = badge.get("action").and_then(Value::as_str) {
1155 let button = ui.add(crate::icon_text::icon_button_colored(ui, glyph, Some(color)).small().frame(false));
1156 publish(hits, spec, &format!("badge:{}:{action}", row.id), button.rect);
1157 if button.clicked() {
1158 out.actions.push(RowActionClick { row_id: row.id.clone(), action: action.into() });
1159 }
1160 if let Some(tip) = badge.get("tooltip").and_then(Value::as_str) {
1161 button.on_hover_text(tip);
1162 }
1163 continue;
1164 }
1165 let label = match crate::icon_text::glyph(ui, glyph, color) {
1166 Some(art) => ui.add(art),
1167 // …and the text fallback is not selectable either, for
1168 // the same reason the read-only cell is not.
1169 None => ui.add(
1170 egui::Label::new(egui::RichText::new(glyph).color(color))
1171 .selectable(false),
1172 ),
1173 };
1174 if let Some(tip) = badge.get("tooltip").and_then(Value::as_str) {
1175 label.on_hover_text(tip);
1176 }
1177 }
1178 })
1179 .response
1180 .rect
1181 }
1182 CellKind::Toggle => {
1183 // Drawn for every row, clickable only on an editable one: the
1184 // weak-label fallback below would render a bool as the text
1185 // "false", which is not a checkbox.
1186 let mut on = value.and_then(Value::as_bool).unwrap_or(false);
1187 let box_ = ui
1188 .add_enabled_ui(row.editable, |ui| ui.checkbox(&mut on, ""))
1189 .inner;
1190 if box_.changed() {
1191 emit(Value::Bool(on));
1192 }
1193 box_.rect
1194 }
1195 _ if !row.editable => ui
1196 .add(
1197 egui::Label::new(egui::RichText::new(display_text(value)).weak())
1198 .selectable(false)
1199 .truncate(),
1200 )
1201 .rect,
1202 CellKind::Text | CellKind::Numeric { .. } | CellKind::Choice { .. } => {
1203 // The VALUE editors are shared (see [`value_editor`]) — the table
1204 // and the part-properties dialog must agree on what editing a
1205 // `Text` / `Numeric` / `Choice` attribute feels like, because they
1206 // edit the very same stored records.
1207 let salt = egui::Id::new(("column-tree-cell", spec.id, &row.id, &column.key));
1208 let size = egui::vec2(width, ui.available_height());
1209 let (edited, rect) = value_editor(ui, salt, &column.kind, value, size);
1210 if let Some(new_value) = edited {
1211 emit(new_value);
1212 }
1213 rect
1214 }
1215 }
1216}
1217
1218/// Draw the editor for ONE value of a [`CellKind`] and report the committed
1219/// edit, if any. `salt` seeds the per-widget egui ids (an in-progress text
1220/// buffer, a combo's open state), so it must be stable for a given value and
1221/// distinct between values; `size` is the space to fill.
1222///
1223/// Split out of [`cell_editor`] so a consumer that is NOT a table can use the
1224/// same editors: the part-properties dialog edits the same BOM attribute
1225/// records the BOM table's cells do, and a `Choice` that could be cleared in
1226/// one place but not the other, or a text field that committed per keystroke
1227/// in one and on focus-loss in the other, would be one attribute with two
1228/// behaviours. The kinds that only make sense inside a table row (`Button`,
1229/// `Actions`, `Badges`, `Toggle`) stay in [`cell_editor`]; asking for one here
1230/// draws the value read-only.
1231pub fn value_editor(
1232 ui: &mut egui::Ui,
1233 salt: egui::Id,
1234 kind: &CellKind,
1235 value: Option<&Value>,
1236 size: egui::Vec2,
1237) -> (Option<Value>, egui::Rect) {
1238 match kind {
1239 CellKind::Text => {
1240 // An in-progress edit lives in egui memory and commits on
1241 // focus-loss / Enter. Per-keystroke commits are wrong here: a
1242 // consumer's commit can be arbitrarily expensive (the BOM's
1243 // part-level one re-signs a part document and re-heals every
1244 // instance of it), and a half-typed value is not a value.
1245 let buffer_id = salt.with("text");
1246 let stored = display_text(value);
1247 let mut buffer: String =
1248 ui.data(|d| d.get_temp(buffer_id)).unwrap_or_else(|| stored.clone());
1249 let edit = ui.add_sized(size, egui::TextEdit::singleline(&mut buffer));
1250 let entered = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
1251 let mut committed = None;
1252 if edit.has_focus() || edit.changed() {
1253 ui.data_mut(|d| d.insert_temp(buffer_id, buffer.clone()));
1254 }
1255 if edit.lost_focus() || entered {
1256 ui.data_mut(|d| d.remove::<String>(buffer_id));
1257 if buffer != stored {
1258 committed = Some(Value::String(buffer));
1259 }
1260 } else if !edit.has_focus() {
1261 // Unfocused: track the model, so an edit made elsewhere (a
1262 // packed fan-out landing on a sibling row) shows immediately.
1263 ui.data_mut(|d| d.remove::<String>(buffer_id));
1264 }
1265 (committed, edit.rect)
1266 }
1267 CellKind::Numeric { step } => {
1268 let mut number = value.and_then(Value::as_f64).unwrap_or(0.0);
1269 let drag = ui.add_sized(size, egui::DragValue::new(&mut number).speed(*step));
1270 let committed = drag.changed().then(|| serde_json::json!(number));
1271 (committed, drag.rect)
1272 }
1273 CellKind::Choice { options } => {
1274 let current = display_text(value);
1275 let mut chosen = current.clone();
1276 let combo = egui::ComboBox::from_id_salt(salt.with("combo"))
1277 .width(size.x)
1278 .selected_text(if current.is_empty() { "—" } else { ¤t })
1279 .show_ui(ui, |ui| {
1280 // The blank choice is always offered: without it a dropdown
1281 // cell can be set but never cleared.
1282 ui.selectable_value(&mut chosen, String::new(), "—");
1283 for option in options {
1284 ui.selectable_value(&mut chosen, option.clone(), option);
1285 }
1286 });
1287 let committed = (chosen != current).then(|| Value::String(chosen));
1288 (committed, combo.response.rect)
1289 }
1290 _ => {
1291 let label = ui.add(egui::Label::new(display_text(value)).truncate());
1292 (None, label.rect)
1293 }
1294 }
1295}
1296
1297/// Which row's action menu is open, and the point it was opened at. Lives in
1298/// egui memory keyed by [`ColumnTreeSpec::id`] — one record, so there can only
1299/// ever be one open menu per tree.
1300#[derive(Clone)]
1301struct MenuOpen {
1302 row: String,
1303 pos: egui::Pos2,
1304}
1305
1306/// THE action menu — one definition, drawn from whichever trigger recorded a
1307/// [`MenuOpen`]. Neither trigger renders anything itself, so the cell click and
1308/// the right-click cannot drift apart: there is only one menu to drift.
1309fn row_action_menu(
1310 ui: &mut egui::Ui,
1311 spec: &ColumnTreeSpec<'_>,
1312 rows: &[RowNode],
1313 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1314 out: &mut ColumnTreeOut,
1315 pending: &mut Option<MenuOpen>,
1316) {
1317 let key = egui::Id::new((spec.id, "column-tree-menu"));
1318 let mut open: Option<MenuOpen> = ui.data(|d| d.get_temp(key));
1319 let was_open = open.as_ref().map(|state| state.row.clone());
1320
1321 if let Some(state) = open.clone() {
1322 // A row that has gone (or lost every action) takes its menu with it.
1323 match find_row(rows, &state.row) {
1324 Some(row) if !row.actions.is_empty() => {
1325 let (chosen, still_open) = action_menu(
1326 ui.ctx(),
1327 ui.layer_id(),
1328 key.with("popup"),
1329 state.pos,
1330 &row.actions,
1331 |action, rect| {
1332 publish(hits, spec, &format!("menuitem:{}:{}", row.id, action.id), rect);
1333 },
1334 );
1335 if let Some(action) = chosen {
1336 out.actions.push(RowActionClick { row_id: row.id.clone(), action });
1337 }
1338 if !still_open {
1339 open = None;
1340 }
1341 }
1342 _ => open = None,
1343 }
1344 }
1345
1346 // Applied AFTER the draw (see the call site): applying it first would let
1347 // the popup's own close-on-click see the very click that opened it. A
1348 // trigger fired on the row whose menu just closed itself is a TOGGLE — the
1349 // second click on the same trigger shuts it.
1350 if let Some(next) = pending.take() {
1351 let toggled_off = open.is_none() && was_open.as_deref() == Some(next.row.as_str());
1352 open = (!toggled_off).then_some(next);
1353 }
1354 match &open {
1355 Some(state) => ui.data_mut(|d| {
1356 d.insert_temp(key, state.clone());
1357 }),
1358 None => ui.data_mut(|d| d.remove::<MenuOpen>(key)),
1359 }
1360}
1361
1362/// Draw ONE action menu as a popup at `pos` — the body of a row's menu, and
1363/// the menu an object drawn somewhere else opens for that same row: a placed
1364/// view or a sheet dimension right-clicked on the paper, a PMI label chip
1365/// right-clicked in the 3D view. Every one of them draws its entries HERE, so
1366/// the object's menu and its tree row's cannot drift apart.
1367///
1368/// `on_entry` receives each entry's screen rect as it is drawn (the caller's
1369/// `menuitem:` hit key). Returns the id of the entry chosen this frame and
1370/// whether the popup is still open — it closes on any click, on an entry or
1371/// elsewhere, and on Escape.
1372pub fn action_menu(
1373 ctx: &egui::Context,
1374 layer: egui::LayerId,
1375 id: egui::Id,
1376 pos: egui::Pos2,
1377 actions: &[RowAction],
1378 mut on_entry: impl FnMut(&RowAction, egui::Rect),
1379) -> (Option<String>, bool) {
1380 let mut still_open = true;
1381 let mut chosen: Option<String> = None;
1382 egui::Popup::new(id, ctx.clone(), egui::PopupAnchor::Position(pos), layer)
1383 .open_bool(&mut still_open)
1384 .kind(egui::PopupKind::Menu)
1385 .layout(egui::Layout::top_down_justified(egui::Align::Min))
1386 .width(160.0)
1387 .show(|ui| {
1388 for action in actions {
1389 if action.separator_above {
1390 ui.separator();
1391 }
1392 // The caption may lead with a catalogued glyph (🔒 Fix,
1393 // ✖ Delete); it is drawn as artwork, not as a character. A
1394 // destructive entry keeps its red — on the artwork as well as
1395 // the text.
1396 let color = action.destructive.then(|| ui.visuals().error_fg_color);
1397 // An entry never wraps. The popup's `Area` keeps the width it
1398 // measured the last time it was up, so without this a menu
1399 // opened after a narrower one broke its longer entries over
1400 // two lines ("Remove from / sheet" after a dimension's menu).
1401 let button = crate::icon_text::icon_button_colored(ui, &action.label, color)
1402 .wrap_mode(egui::TextWrapMode::Extend);
1403 let entry = ui.add_enabled(action.enabled, button);
1404 on_entry(action, entry.rect);
1405 if !action.tooltip.is_empty() {
1406 // A greyed entry's tooltip is where its refusal is
1407 // explained, so it has to be the DISABLED hover.
1408 if action.enabled {
1409 entry.clone().on_hover_text(&action.tooltip);
1410 } else {
1411 entry.clone().on_disabled_hover_text(&action.tooltip);
1412 }
1413 }
1414 if entry.clicked() {
1415 chosen = Some(action.id.clone());
1416 }
1417 }
1418 });
1419 (chosen, still_open)
1420}
1421
1422/// The row with `id`, anywhere in the tree.
1423fn find_row<'a>(rows: &'a [RowNode], id: &str) -> Option<&'a RowNode> {
1424 for row in rows {
1425 if row.id == id {
1426 return Some(row);
1427 }
1428 if let Some(found) = find_row(&row.children, id) {
1429 return Some(found);
1430 }
1431 }
1432 None
1433}
1434
1435/// Truncate `text` with an ellipsis so it fits `width`.
1436fn elide(ui: &egui::Ui, text: &str, width: f32) -> String {
1437 let font = egui::TextStyle::Body.resolve(ui.style());
1438 let measure = |candidate: &str| {
1439 ui.painter()
1440 .layout_no_wrap(candidate.to_string(), font.clone(), egui::Color32::WHITE)
1441 .rect
1442 .width()
1443 };
1444 if width <= 0.0 || measure(text) <= width {
1445 return text.to_string();
1446 }
1447 let mut cut: Vec<char> = text.chars().collect();
1448 while !cut.is_empty() {
1449 cut.pop();
1450 let candidate: String = cut.iter().collect::<String>() + "\u{2026}";
1451 if measure(&candidate) <= width {
1452 return candidate;
1453 }
1454 }
1455 String::new()
1456}
1457
1458fn publish(
1459 hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1460 spec: &ColumnTreeSpec<'_>,
1461 key: &str,
1462 rect: egui::Rect,
1463) {
1464 if let Some(map) = hits.as_deref_mut() {
1465 map.insert(format!("{}{key}", spec.hits_prefix), rect);
1466 }
1467}
1468
1469