Skip to main content

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 {
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).
468                let scroll = ui.spacing().scroll;
469                ui.add_space(scroll.bar_width + scroll.bar_inner_margin + scroll.bar_outer_margin);
470            }
471        });
472    bottom = bottom.max(pane.min_rect().bottom());
473
474    let used = egui::Rect::from_min_max(full.min, egui::pos2(full.max.x, bottom));
475    ui.advance_cursor_after_rect(used);
476
477    // The boundary, so the user can SEE which columns are pinned.
478    if frozen > 0 {
479        let x = full.min.x + frozen_width + FREEZE_GAP * 0.5;
480        let divider = egui::Rect::from_min_max(
481            egui::pos2(x - 1.0, used.top()),
482            egui::pos2(x + 1.0, used.bottom()),
483        );
484        ui.painter()
485            .rect_filled(divider, 0.0, ui.visuals().widgets.active.bg_fill);
486        publish(&mut hits, spec, "freeze:divider", divider);
487    }
488
489    finish_reorder(ui, spec, layout, &arranged, &bounds, &mut out);
490    // ONE menu, drawn from whatever record a trigger left. `pending` is applied
491    // AFTER it — apply it first and the popup's own close-on-click would see
492    // the very click that opened it and shut immediately.
493    row_action_menu(ui, spec, rows, &mut hits, &mut out, &mut pending);
494    out
495}
496
497/// Draw ONE pane — a contiguous run of columns, with the header and every row.
498/// The frozen band and the scrolling remainder are the same code walking the
499/// same rows in the same order, which is what keeps them aligned.
500///
501/// `offset` is the drawn index of `columns[0]`, so the pane holding column 0
502/// (and only it) draws the TREE cell. `band` is the width every row spans here.
503#[allow(clippy::too_many_arguments)]
504fn draw_pane(
505    ui: &mut egui::Ui,
506    spec: &ColumnTreeSpec<'_>,
507    layout: &mut ColumnLayout,
508    columns: &[&ColumnSpec],
509    widths: &[f32],
510    offset: usize,
511    band: f32,
512    rows: &[RowNode],
513    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
514    out: &mut ColumnTreeOut,
515    pending: &mut Option<MenuOpen>,
516    bounds: &mut Vec<(String, f32, f32)>,
517) {
518    header(ui, spec, layout, columns, widths, band, hits, out, bounds);
519    ui.separator();
520
521    if let Some(label) = spec.root_label {
522        let mut cells = spec.root_cells.cloned().unwrap_or_default();
523        // The root's label belongs to whichever column is drawn FIRST — the
524        // tree column follows the user's order, so it is not a fixed key.
525        if offset == 0 {
526            cells.insert(columns[0].key.clone(), Value::String(label.to_string()));
527        }
528        let root = RowNode {
529            id: format!("{}__root", spec.id),
530            cells,
531            editable: false,
532            selected: false,
533            expanded: true,
534            actions: Vec::new(),
535            children: Vec::new(),
536        };
537        draw_row(
538            ui, spec, columns, widths, offset, band, &root, &[], true, true, hits, out, pending,
539        );
540    }
541
542    if rows.is_empty() {
543        if let Some(hint) = spec.empty_hint {
544            if offset == 0 {
545                let guides = tree::child_guides(&[], true);
546                tree::node(ui, TreeRow::leaf(&guides, true, hint), |_| {});
547            } else {
548                // The other pane still spends the same row, so the two panes
549                // keep the same height.
550                ui.allocate_exact_size(
551                    egui::vec2(band, ui.spacing().interact_size.y),
552                    egui::Sense::hover(),
553                );
554            }
555        }
556        return;
557    }
558
559    let ordered = sorted_siblings(rows, layout);
560    let last = ordered.len();
561    for (index, row) in ordered.iter().enumerate() {
562        draw_subtree(
563            ui,
564            spec,
565            layout,
566            columns,
567            widths,
568            offset,
569            band,
570            row,
571            &[],
572            index + 1 == last,
573            hits,
574            out,
575            pending,
576        );
577    }
578}
579
580/// Every spec column in the user's order — `layout.order` first (spec columns
581/// only), then any spec column the layout has never heard of. Hidden columns
582/// KEEP their slot here; the drawn set filters them out afterwards, and the
583/// freeze boundary counts over this list.
584fn arranged_columns<'a>(
585    spec: &'a ColumnTreeSpec<'_>,
586    layout: &ColumnLayout,
587) -> Vec<&'a ColumnSpec> {
588    let mut out: Vec<&ColumnSpec> = Vec::new();
589    for key in &layout.order {
590        if let Some(column) = spec.columns.iter().find(|c| &c.key == key) {
591            if !out.iter().any(|c| c.key == column.key) {
592                out.push(column);
593            }
594        }
595    }
596    for column in spec.columns {
597        if !out.iter().any(|c| c.key == column.key) {
598            out.push(column);
599        }
600    }
601    out
602}
603
604fn column_width(layout: &ColumnLayout, column: &ColumnSpec) -> f32 {
605    layout
606        .widths
607        .get(&column.key)
608        .copied()
609        .unwrap_or(column.default_width)
610        .max(MIN_COLUMN_WIDTH)
611}
612
613/// One pane's header: a heading per column (click = sort, drag = reorder,
614/// right-click = the show/hide checklist) with a resize grip at each right
615/// edge. The drop of a reorder drag is resolved by [`finish_reorder`] once
616/// BOTH panes have contributed their bounds.
617#[allow(clippy::too_many_arguments)]
618fn header(
619    ui: &mut egui::Ui,
620    spec: &ColumnTreeSpec<'_>,
621    layout: &mut ColumnLayout,
622    visible: &[&ColumnSpec],
623    widths: &[f32],
624    width: f32,
625    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
626    out: &mut ColumnTreeOut,
627    bounds: &mut Vec<(String, f32, f32)>,
628) {
629    let height = ui.spacing().interact_size.y;
630    let (band, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
631    let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
632    let dragging: Option<String> = ui.data(|d| d.get_temp(drag_key));
633
634    let mut x = band.left();
635    // The reorder DROP target is decided from the pointer's x at drag end, so
636    // the boundaries are collected while the headings are laid out.
637    let first = bounds.len();
638    for (column, width) in visible.iter().zip(widths) {
639        let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
640        bounds.push((column.key.clone(), cell.left(), cell.right()));
641
642        let resp = ui.interact(
643            cell,
644            ui.id().with(("column-tree-head", spec.id, &column.key)),
645            egui::Sense::click_and_drag(),
646        );
647        let held = dragging.as_deref() == Some(column.key.as_str());
648        let fill = if held {
649            ui.visuals().selection.bg_fill.gamma_multiply(0.45)
650        } else if resp.hovered() {
651            ui.visuals().widgets.hovered.bg_fill
652        } else {
653            ui.visuals().widgets.noninteractive.bg_fill
654        };
655        ui.painter().rect_filled(cell, 0.0, fill);
656        // The sort marker rides the heading text, so the sorted column is
657        // obvious without a second row of chrome.
658        let marker = match &layout.sort {
659            Some((key, true)) if key == &column.key => " \u{25B2}",
660            Some((key, false)) if key == &column.key => " \u{25BC}",
661            _ => "",
662        };
663        let text = format!("{}{marker}", column.label);
664        ui.painter().text(
665            egui::pos2(cell.left() + CELL_PAD, cell.center().y),
666            egui::Align2::LEFT_CENTER,
667            elide(ui, &text, *width - 2.0 * CELL_PAD),
668            egui::TextStyle::Body.resolve(ui.style()),
669            ui.visuals().strong_text_color(),
670        );
671        publish(hits, spec, &format!("col:{}", column.key), cell);
672
673        // Right-click ANY heading → the show/hide checklist. Hiding lives here
674        // rather than on a toolbar because the column is the thing being
675        // hidden and this is where the user's hand already is.
676        resp.context_menu(|ui| {
677            ui.label(egui::RichText::new("Columns").strong());
678            for candidate in spec.columns {
679                let mut shown = !layout.hidden.contains(&candidate.key);
680                if ui.checkbox(&mut shown, &candidate.label).changed() {
681                    if shown {
682                        layout.hidden.remove(&candidate.key);
683                    } else {
684                        layout.hidden.insert(candidate.key.clone());
685                    }
686                    out.layout_changed = true;
687                }
688            }
689        });
690
691        // A CLICK sorts. egui reports `clicked()` false once a press turns
692        // into a drag, so the click and the reorder drag share the heading
693        // without a mode.
694        if resp.clicked() {
695            layout.sort = match &layout.sort {
696                Some((key, true)) if key == &column.key => Some((column.key.clone(), false)),
697                Some((key, false)) if key == &column.key => None,
698                _ => Some((column.key.clone(), true)),
699            };
700            out.layout_changed = true;
701        }
702        if resp.drag_started() {
703            ui.data_mut(|d| d.insert_temp(drag_key, column.key.clone()));
704        }
705
706        ui.painter().line_segment(
707            [
708                egui::pos2(cell.right(), band.top()),
709                egui::pos2(cell.right(), band.bottom()),
710            ],
711            ui.visuals().widgets.noninteractive.bg_stroke,
712        );
713        x = cell.right();
714    }
715
716    // The resize grips, in a SECOND pass. A grip straddles the divider, so it
717    // overlaps the heading to its right — and egui hands an overlapped point to
718    // the LAST widget registered there. Interleaved with the headings, every
719    // grip would therefore lose its own hit to the next heading and no column
720    // would ever resize.
721    for (column, (_, _, right)) in visible.iter().zip(&bounds[first..]) {
722        let grip_rect = egui::Rect::from_min_max(
723            egui::pos2(right - GRIP * 0.5, band.top()),
724            egui::pos2(right + GRIP * 0.5, band.bottom()),
725        );
726        let grip = ui.interact(
727            grip_rect,
728            ui.id().with(("column-tree-grip", spec.id, &column.key)),
729            egui::Sense::drag(),
730        );
731        if grip.hovered() || grip.dragged() {
732            ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
733        }
734        if grip.dragged() {
735            let next = (column_width(layout, column) + grip.drag_delta().x).max(MIN_COLUMN_WIDTH);
736            layout.widths.insert(column.key.clone(), next);
737            out.layout_changed = true;
738        }
739        publish(hits, spec, &format!("grip:{}", column.key), grip_rect);
740    }
741}
742
743/// Finish a reorder: on release, the dragged column moves to whichever heading
744/// the pointer is over — in EITHER pane, so dragging a column across the freeze
745/// boundary is what freezes or unfreezes it.
746fn finish_reorder(
747    ui: &egui::Ui,
748    spec: &ColumnTreeSpec<'_>,
749    layout: &mut ColumnLayout,
750    arranged: &[&ColumnSpec],
751    bounds: &[(String, f32, f32)],
752    out: &mut ColumnTreeOut,
753) {
754    let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
755    let Some(held) = ui.data(|d| d.get_temp::<String>(drag_key)) else {
756        return;
757    };
758    if ui.input(|i| i.pointer.any_down()) {
759        return;
760    }
761    ui.data_mut(|d| d.remove::<String>(drag_key));
762    let Some(pos) = ui.input(|i| i.pointer.latest_pos()) else {
763        return;
764    };
765    if let Some((target, _, _)) = bounds
766        .iter()
767        .find(|(_, left, right)| pos.x >= *left && pos.x < *right)
768    {
769        if *target != held && move_column(layout, arranged, &held, target) {
770            out.layout_changed = true;
771        }
772    }
773}
774
775/// Move `held` to `target`'s slot in the layout order, materializing the
776/// current arranged order first so a layout that never named its columns still
777/// reorders correctly. Returns whether anything moved.
778fn move_column(
779    layout: &mut ColumnLayout,
780    arranged: &[&ColumnSpec],
781    held: &str,
782    target: &str,
783) -> bool {
784    let mut order: Vec<String> = layout.order.clone();
785    // Seed from the drawn order so the first drag on a fresh layout is not a
786    // no-op against an empty `order`.
787    for column in arranged {
788        if !order.iter().any(|key| key == &column.key) {
789            order.push(column.key.clone());
790        }
791    }
792    let Some(from) = order.iter().position(|key| key == held) else {
793        return false;
794    };
795    let key = order.remove(from);
796    let Some(to) = order.iter().position(|k| k == target) else {
797        order.insert(from.min(order.len()), key);
798        return false;
799    };
800    order.insert(to, key);
801    layout.order = order;
802    true
803}
804
805/// Draw one row and, when it is open, its children — the recursion that keeps
806/// the rows a TREE.
807#[allow(clippy::too_many_arguments)]
808fn draw_subtree(
809    ui: &mut egui::Ui,
810    spec: &ColumnTreeSpec<'_>,
811    layout: &ColumnLayout,
812    visible: &[&ColumnSpec],
813    widths: &[f32],
814    offset: usize,
815    band: f32,
816    row: &RowNode,
817    guides: &[bool],
818    is_last: bool,
819    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
820    out: &mut ColumnTreeOut,
821    pending: &mut Option<MenuOpen>,
822) {
823    draw_row(
824        ui, spec, visible, widths, offset, band, row, guides, is_last, false, hits, out, pending,
825    );
826    if !row.expanded || row.children.is_empty() {
827        return;
828    }
829    let child_guides = tree::child_guides(guides, is_last);
830    let ordered = sorted_siblings(&row.children, layout);
831    let last = ordered.len();
832    for (index, child) in ordered.iter().enumerate() {
833        draw_subtree(
834            ui,
835            spec,
836            layout,
837            visible,
838            widths,
839            offset,
840            band,
841            child,
842            &child_guides,
843            index + 1 == last,
844            hits,
845            out,
846            pending,
847        );
848    }
849}
850
851/// Sort ONE level of siblings by the layout's sort column. Sorting is
852/// per-level so the nesting survives it — a child never overtakes its parent.
853/// A stable sort, so an unsorted-equal run keeps the consumer's order.
854fn sorted_siblings<'a>(rows: &'a [RowNode], layout: &ColumnLayout) -> Vec<&'a RowNode> {
855    let mut out: Vec<&RowNode> = rows.iter().collect();
856    if let Some((key, ascending)) = &layout.sort {
857        out.sort_by(|a, b| {
858            let ordering = compare_cells(a.cells.get(key), b.cells.get(key));
859            if *ascending {
860                ordering
861            } else {
862                ordering.reverse()
863            }
864        });
865    }
866    out
867}
868
869/// Order two cell values: numbers numerically, everything else by its display
870/// text case-insensitively, and an ABSENT/null cell last in ascending order
871/// (an unfilled cell is not a small value, it is a missing one).
872fn compare_cells(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {
873    use std::cmp::Ordering;
874    let empty = |value: Option<&Value>| match value {
875        None | Some(Value::Null) => true,
876        Some(Value::String(text)) => text.is_empty(),
877        _ => false,
878    };
879    match (empty(a), empty(b)) {
880        (true, true) => return Ordering::Equal,
881        (true, false) => return Ordering::Greater,
882        (false, true) => return Ordering::Less,
883        (false, false) => {}
884    }
885    if let (Some(Value::Number(x)), Some(Value::Number(y))) = (a, b) {
886        if let (Some(x), Some(y)) = (x.as_f64(), y.as_f64()) {
887            return x.partial_cmp(&y).unwrap_or(Ordering::Equal);
888        }
889    }
890    display_text(a).to_lowercase().cmp(&display_text(b).to_lowercase())
891}
892
893/// A cell value as the text a cell shows: a string bare (not JSON-quoted), a
894/// number in its shortest form, anything else as its JSON.
895fn display_text(value: Option<&Value>) -> String {
896    match value {
897        None | Some(Value::Null) => String::new(),
898        Some(Value::String(text)) => text.clone(),
899        Some(other) => other.to_string(),
900    }
901}
902
903/// Draw ONE row: the tree cell in column 0, an editor in each other column.
904#[allow(clippy::too_many_arguments)]
905fn draw_row(
906    ui: &mut egui::Ui,
907    spec: &ColumnTreeSpec<'_>,
908    visible: &[&ColumnSpec],
909    widths: &[f32],
910    offset: usize,
911    band_width: f32,
912    row: &RowNode,
913    guides: &[bool],
914    is_last: bool,
915    root: bool,
916    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
917    out: &mut ColumnTreeOut,
918    pending: &mut Option<MenuOpen>,
919) {
920    let height = ui.spacing().interact_size.y;
921    // THE ROW BAND — the row's click target, allocated BEFORE the cells. A row
922    // is picked by clicking anywhere along it, not only on the text in its
923    // first column: in the shipped BOM that text was 40 pt of a 900 pt row, so
924    // 95 % of every row was dead. egui hands an overlapped point to the LAST
925    // widget registered there, and every cell editor is registered after this,
926    // so a button, a checkbox, a text cell and the collapse box all still take
927    // their own clicks — the band receives only what none of them wanted.
928    //
929    // It does NOT take the keyboard focus: the row's Tab stop is the band
930    // inside `tree::node` (drawn once, in whichever pane holds column 0), so a
931    // frozen table does not give one row two stops.
932    let (band, band_resp) =
933        ui.allocate_exact_size(egui::vec2(band_width, height), egui::Sense::CLICK);
934    let clip = ui.clip_rect();
935
936    // TRIGGER 2 — a right-click ANYWHERE on the row. Read off the raw pointer
937    // rather than from a `Response`, because the cell editors are registered
938    // AFTER this band and egui hands an overlapped point to the LAST widget
939    // registered there: a `context_menu` on the band would silently never fire
940    // over a text cell. Reading the position also leaves the band's own primary
941    // click alone, so the select path above and this one cannot fight.
942    let over_row = band.intersect(clip);
943    if !root && over_row.is_positive() && ui.rect_contains_pointer(over_row) {
944        out.hovered = Some(row.id.clone());
945    }
946
947    // The row's published rect IS its band — what a script clicks has to be
948    // what a user can click, and that is the strip, not the name in it.
949    //
950    // A FROZEN table draws the row once per pane, and only the pane holding
951    // column 0 publishes: `click_widget` aims at a rect's CENTRE, and the
952    // centre of the two bands unioned lands in whichever scrolling column
953    // happens to be halfway across — a text editor, a drag-value — where a
954    // click focuses that editor instead of picking the row. The frozen band
955    // leads with the tree column, so its centre is the row. The scrolling
956    // columns are still clickable; they are just not what the key aims at.
957    if !root && offset == 0 && over_row.is_positive() {
958        publish(hits, spec, &format!("row:{}", row.id), over_row);
959    }
960    // A SELECT click anywhere on the band that no cell claimed. The tree cell
961    // reports its own (see below); this is every other column.
962    if !root && band_resp.clicked() {
963        out.clicked = Some(row.id.clone());
964    }
965    if !root && tree::is_double_click(&band_resp) {
966        out.double_clicked = Some(row.id.clone());
967    }
968    if !row.actions.is_empty()
969        && over_row.is_positive()
970        && ui.input(|i| i.pointer.secondary_clicked())
971    {
972        if let Some(pos) = ui.ctx().input(|i| i.pointer.interact_pos()) {
973            // ...and nothing floating (an open menu, the header's own column
974            // checklist) is above that point.
975            let above = ui.ctx().layer_id_at(pos);
976            let ours = above.is_none() || above == Some(ui.layer_id());
977            if over_row.contains(pos) && ours {
978                *pending = Some(MenuOpen {
979                    row: row.id.clone(),
980                    pos,
981                });
982            }
983        }
984    }
985
986    // The SELECTION band. A selected row is emphasised across its whole width,
987    // not just by bolding the tree cell's text: this table is as wide as its
988    // configured columns, and a picked component has to be findable at a
989    // glance from anywhere in it. Painted BEFORE the cells so every editor
990    // draws over it, and drawn in both panes (each calls this with its own
991    // band) so the highlight does not stop at the frozen boundary.
992    if row.selected && !root {
993        let visible_band = band.intersect(clip);
994        if visible_band.is_positive() {
995            ui.painter().rect_filled(
996                visible_band,
997                0.0,
998                ui.visuals().selection.bg_fill.gamma_multiply(0.35),
999            );
1000        }
1001    }
1002
1003    let mut x = band.left();
1004    for (index, (column, width)) in visible.iter().zip(widths).enumerate() {
1005        let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
1006        x = cell.right();
1007        let Some(cell_clip) = cell.intersect(clip).is_positive().then_some(cell.intersect(clip))
1008        else {
1009            continue;
1010        };
1011        let mut child = ui.new_child(
1012            egui::UiBuilder::new()
1013                .max_rect(cell.shrink2(egui::vec2(CELL_PAD, 0.0)))
1014                .layout(egui::Layout::left_to_right(egui::Align::Center))
1015                .id_salt(("column-tree-cell", spec.id, &row.id, &column.key)),
1016        );
1017        child.set_clip_rect(cell_clip);
1018
1019        if offset + index == 0 {
1020            // The TREE cell — drawn by `panels::tree::node` itself, so the
1021            // connector rules and collapse boxes are the shared ones.
1022            let label = display_text(row.cells.get(&column.key));
1023            let expandable = !row.children.is_empty();
1024            let mut tree_row = TreeRow {
1025                guides,
1026                is_last,
1027                expandable,
1028                expanded: row.expanded,
1029                root,
1030                glyph: None,
1031                label: &label,
1032                selected: row.selected,
1033                highlighted: false,
1034                draggable: false,
1035                tint: None,
1036            };
1037            if root {
1038                tree_row.expandable = true;
1039                tree_row.expanded = true;
1040            }
1041            let resp = tree::node(&mut child, tree_row, |_| {});
1042            publish(hits, spec, &format!("box:{}", row.id), resp.box_rect);
1043            if resp.toggled {
1044                out.toggled = Some(row.id.clone());
1045            }
1046            // The tree cell has a band of its OWN (`tree::node` draws one), and
1047            // it is registered after this row's, so inside column 0 it is the
1048            // one that hears a blank-space click. Both are the same intent.
1049            if !root && resp.clicked() {
1050                out.clicked = Some(row.id.clone());
1051            }
1052            if !root && resp.double_clicked() {
1053                out.double_clicked = Some(row.id.clone());
1054            }
1055        } else {
1056            let rect = cell_editor(&mut child, spec, row, column, out, pending, hits);
1057            publish(
1058                hits,
1059                spec,
1060                &format!("cell:{}:{}", row.id, column.key),
1061                rect,
1062            );
1063            if matches!(column.kind, CellKind::Actions { .. }) {
1064                publish(hits, spec, &format!("menu:{}", row.id), rect);
1065            }
1066        }
1067    }
1068}
1069
1070/// Draw ONE non-tree cell's editor and return its rect. A non-editable row
1071/// still SHOWS its value and still offers its buttons and its action menu — it
1072/// just cannot be typed into.
1073fn cell_editor(
1074    ui: &mut egui::Ui,
1075    spec: &ColumnTreeSpec<'_>,
1076    row: &RowNode,
1077    column: &ColumnSpec,
1078    out: &mut ColumnTreeOut,
1079    pending: &mut Option<MenuOpen>,
1080    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1081) -> egui::Rect {
1082    let value = row.cells.get(&column.key);
1083    let width = ui.available_width();
1084    let mut emit = |new_value: Value| {
1085        out.edits.push(CellEdit {
1086            row_id: row.id.clone(),
1087            column: column.key.clone(),
1088            value: new_value,
1089        });
1090    };
1091
1092    match &column.kind {
1093        CellKind::Button { label } => {
1094            let button = ui.add_sized([width, ui.available_height()], egui::Button::new(label));
1095            if button.clicked() {
1096                out.buttons.push(CellClick {
1097                    row_id: row.id.clone(),
1098                    column: column.key.clone(),
1099                });
1100            }
1101            button.rect
1102        }
1103        CellKind::Actions { label } => {
1104            // TRIGGER 1 — the actions cell. Like the right-click it only
1105            // RECORDS which row was asked for; the menu is drawn once, after
1106            // every row, from that record. A row that offers nothing draws the
1107            // trigger greyed rather than dropping it, so the column stays a
1108            // column.
1109            let offered = !row.actions.is_empty();
1110            let button = ui
1111                .add_enabled_ui(offered, |ui| {
1112                    ui.add_sized([width, ui.available_height()], egui::Button::new(label))
1113                })
1114                .inner;
1115            if button.clicked() {
1116                *pending = Some(MenuOpen {
1117                    row: row.id.clone(),
1118                    pos: button.rect.left_bottom(),
1119                });
1120            }
1121            button.rect
1122        }
1123        // A DISPLAY cell: not selectable, so the click reaches the row band
1124        // behind it. egui labels are drag-to-select by default, which senses
1125        // click and drag and would make a derived value the one piece of the
1126        // row you cannot pick the row by.
1127        CellKind::ReadOnly => ui
1128            .add(
1129                egui::Label::new(display_text(value))
1130                    .selectable(false)
1131                    .truncate(),
1132            )
1133            .rect,
1134        CellKind::Badges => {
1135            let badges = value.and_then(Value::as_array).cloned().unwrap_or_default();
1136            ui.horizontal(|ui| {
1137                ui.spacing_mut().item_spacing.x = 3.0;
1138                for badge in &badges {
1139                    let glyph = badge.get("glyph").and_then(Value::as_str).unwrap_or("");
1140                    if glyph.is_empty() {
1141                        continue;
1142                    }
1143                    let color = badge
1144                        .get("color")
1145                        .and_then(Value::as_str)
1146                        .and_then(parse_hex_color)
1147                        .unwrap_or_else(|| ui.visuals().text_color());
1148                    // A badge glyph carries meaning IN its colour, so it is
1149                    // drawn from the icon catalog and tinted — there is no icon
1150                    // font to render the character with.
1151                    // A badge may name an action; status-only badges remain
1152                    // passive and continue to let the row receive the click.
1153                    if let Some(action) = badge.get("action").and_then(Value::as_str) {
1154                        let button = ui.add(crate::icon_text::icon_button_colored(ui, glyph, Some(color)).small().frame(false));
1155                        publish(hits, spec, &format!("badge:{}:{action}", row.id), button.rect);
1156                        if button.clicked() {
1157                            out.actions.push(RowActionClick { row_id: row.id.clone(), action: action.into() });
1158                        }
1159                        if let Some(tip) = badge.get("tooltip").and_then(Value::as_str) {
1160                            button.on_hover_text(tip);
1161                        }
1162                        continue;
1163                    }
1164                    let label = match crate::icon_text::glyph(ui, glyph, color) {
1165                        Some(art) => ui.add(art),
1166                        // …and the text fallback is not selectable either, for
1167                        // the same reason the read-only cell is not.
1168                        None => ui.add(
1169                            egui::Label::new(egui::RichText::new(glyph).color(color))
1170                                .selectable(false),
1171                        ),
1172                    };
1173                    if let Some(tip) = badge.get("tooltip").and_then(Value::as_str) {
1174                        label.on_hover_text(tip);
1175                    }
1176                }
1177            })
1178            .response
1179            .rect
1180        }
1181        CellKind::Toggle => {
1182            // Drawn for every row, clickable only on an editable one: the
1183            // weak-label fallback below would render a bool as the text
1184            // "false", which is not a checkbox.
1185            let mut on = value.and_then(Value::as_bool).unwrap_or(false);
1186            let box_ = ui
1187                .add_enabled_ui(row.editable, |ui| ui.checkbox(&mut on, ""))
1188                .inner;
1189            if box_.changed() {
1190                emit(Value::Bool(on));
1191            }
1192            box_.rect
1193        }
1194        _ if !row.editable => ui
1195            .add(
1196                egui::Label::new(egui::RichText::new(display_text(value)).weak())
1197                    .selectable(false)
1198                    .truncate(),
1199            )
1200            .rect,
1201        CellKind::Text | CellKind::Numeric { .. } | CellKind::Choice { .. } => {
1202            // The VALUE editors are shared (see [`value_editor`]) — the table
1203            // and the part-properties dialog must agree on what editing a
1204            // `Text` / `Numeric` / `Choice` attribute feels like, because they
1205            // edit the very same stored records.
1206            let salt = egui::Id::new(("column-tree-cell", spec.id, &row.id, &column.key));
1207            let size = egui::vec2(width, ui.available_height());
1208            let (edited, rect) = value_editor(ui, salt, &column.kind, value, size);
1209            if let Some(new_value) = edited {
1210                emit(new_value);
1211            }
1212            rect
1213        }
1214    }
1215}
1216
1217/// Draw the editor for ONE value of a [`CellKind`] and report the committed
1218/// edit, if any. `salt` seeds the per-widget egui ids (an in-progress text
1219/// buffer, a combo's open state), so it must be stable for a given value and
1220/// distinct between values; `size` is the space to fill.
1221///
1222/// Split out of [`cell_editor`] so a consumer that is NOT a table can use the
1223/// same editors: the part-properties dialog edits the same BOM attribute
1224/// records the BOM table's cells do, and a `Choice` that could be cleared in
1225/// one place but not the other, or a text field that committed per keystroke
1226/// in one and on focus-loss in the other, would be one attribute with two
1227/// behaviours. The kinds that only make sense inside a table row (`Button`,
1228/// `Actions`, `Badges`, `Toggle`) stay in [`cell_editor`]; asking for one here
1229/// draws the value read-only.
1230pub fn value_editor(
1231    ui: &mut egui::Ui,
1232    salt: egui::Id,
1233    kind: &CellKind,
1234    value: Option<&Value>,
1235    size: egui::Vec2,
1236) -> (Option<Value>, egui::Rect) {
1237    match kind {
1238        CellKind::Text => {
1239            // An in-progress edit lives in egui memory and commits on
1240            // focus-loss / Enter. Per-keystroke commits are wrong here: a
1241            // consumer's commit can be arbitrarily expensive (the BOM's
1242            // part-level one re-signs a part document and re-heals every
1243            // instance of it), and a half-typed value is not a value.
1244            let buffer_id = salt.with("text");
1245            let stored = display_text(value);
1246            let mut buffer: String =
1247                ui.data(|d| d.get_temp(buffer_id)).unwrap_or_else(|| stored.clone());
1248            let edit = ui.add_sized(size, egui::TextEdit::singleline(&mut buffer));
1249            let entered = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
1250            let mut committed = None;
1251            if edit.has_focus() || edit.changed() {
1252                ui.data_mut(|d| d.insert_temp(buffer_id, buffer.clone()));
1253            }
1254            if edit.lost_focus() || entered {
1255                ui.data_mut(|d| d.remove::<String>(buffer_id));
1256                if buffer != stored {
1257                    committed = Some(Value::String(buffer));
1258                }
1259            } else if !edit.has_focus() {
1260                // Unfocused: track the model, so an edit made elsewhere (a
1261                // packed fan-out landing on a sibling row) shows immediately.
1262                ui.data_mut(|d| d.remove::<String>(buffer_id));
1263            }
1264            (committed, edit.rect)
1265        }
1266        CellKind::Numeric { step } => {
1267            let mut number = value.and_then(Value::as_f64).unwrap_or(0.0);
1268            let drag = ui.add_sized(size, egui::DragValue::new(&mut number).speed(*step));
1269            let committed = drag.changed().then(|| serde_json::json!(number));
1270            (committed, drag.rect)
1271        }
1272        CellKind::Choice { options } => {
1273            let current = display_text(value);
1274            let mut chosen = current.clone();
1275            let combo = egui::ComboBox::from_id_salt(salt.with("combo"))
1276                .width(size.x)
1277                .selected_text(if current.is_empty() { "—" } else { &current })
1278                .show_ui(ui, |ui| {
1279                    // The blank choice is always offered: without it a dropdown
1280                    // cell can be set but never cleared.
1281                    ui.selectable_value(&mut chosen, String::new(), "—");
1282                    for option in options {
1283                        ui.selectable_value(&mut chosen, option.clone(), option);
1284                    }
1285                });
1286            let committed = (chosen != current).then(|| Value::String(chosen));
1287            (committed, combo.response.rect)
1288        }
1289        _ => {
1290            let label = ui.add(egui::Label::new(display_text(value)).truncate());
1291            (None, label.rect)
1292        }
1293    }
1294}
1295
1296/// Which row's action menu is open, and the point it was opened at. Lives in
1297/// egui memory keyed by [`ColumnTreeSpec::id`] — one record, so there can only
1298/// ever be one open menu per tree.
1299#[derive(Clone)]
1300struct MenuOpen {
1301    row: String,
1302    pos: egui::Pos2,
1303}
1304
1305/// THE action menu — one definition, drawn from whichever trigger recorded a
1306/// [`MenuOpen`]. Neither trigger renders anything itself, so the cell click and
1307/// the right-click cannot drift apart: there is only one menu to drift.
1308fn row_action_menu(
1309    ui: &mut egui::Ui,
1310    spec: &ColumnTreeSpec<'_>,
1311    rows: &[RowNode],
1312    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1313    out: &mut ColumnTreeOut,
1314    pending: &mut Option<MenuOpen>,
1315) {
1316    let key = egui::Id::new((spec.id, "column-tree-menu"));
1317    let mut open: Option<MenuOpen> = ui.data(|d| d.get_temp(key));
1318    let was_open = open.as_ref().map(|state| state.row.clone());
1319
1320    if let Some(state) = open.clone() {
1321        // A row that has gone (or lost every action) takes its menu with it.
1322        match find_row(rows, &state.row) {
1323            Some(row) if !row.actions.is_empty() => {
1324                let (chosen, still_open) = action_menu(
1325                    ui.ctx(),
1326                    ui.layer_id(),
1327                    key.with("popup"),
1328                    state.pos,
1329                    &row.actions,
1330                    |action, rect| {
1331                        publish(hits, spec, &format!("menuitem:{}:{}", row.id, action.id), rect);
1332                    },
1333                );
1334                if let Some(action) = chosen {
1335                    out.actions.push(RowActionClick { row_id: row.id.clone(), action });
1336                }
1337                if !still_open {
1338                    open = None;
1339                }
1340            }
1341            _ => open = None,
1342        }
1343    }
1344
1345    // Applied AFTER the draw (see the call site): applying it first would let
1346    // the popup's own close-on-click see the very click that opened it. A
1347    // trigger fired on the row whose menu just closed itself is a TOGGLE — the
1348    // second click on the same trigger shuts it.
1349    if let Some(next) = pending.take() {
1350        let toggled_off = open.is_none() && was_open.as_deref() == Some(next.row.as_str());
1351        open = (!toggled_off).then_some(next);
1352    }
1353    match &open {
1354        Some(state) => ui.data_mut(|d| {
1355            d.insert_temp(key, state.clone());
1356        }),
1357        None => ui.data_mut(|d| d.remove::<MenuOpen>(key)),
1358    }
1359}
1360
1361/// Draw ONE action menu as a popup at `pos` — the body of a row's menu, and
1362/// the menu an object drawn somewhere else opens for that same row: a placed
1363/// view or a sheet dimension right-clicked on the paper, a PMI label chip
1364/// right-clicked in the 3D view. Every one of them draws its entries HERE, so
1365/// the object's menu and its tree row's cannot drift apart.
1366///
1367/// `on_entry` receives each entry's screen rect as it is drawn (the caller's
1368/// `menuitem:` hit key). Returns the id of the entry chosen this frame and
1369/// whether the popup is still open — it closes on any click, on an entry or
1370/// elsewhere, and on Escape.
1371pub fn action_menu(
1372    ctx: &egui::Context,
1373    layer: egui::LayerId,
1374    id: egui::Id,
1375    pos: egui::Pos2,
1376    actions: &[RowAction],
1377    mut on_entry: impl FnMut(&RowAction, egui::Rect),
1378) -> (Option<String>, bool) {
1379    let mut still_open = true;
1380    let mut chosen: Option<String> = None;
1381    egui::Popup::new(id, ctx.clone(), egui::PopupAnchor::Position(pos), layer)
1382        .open_bool(&mut still_open)
1383        .kind(egui::PopupKind::Menu)
1384        .layout(egui::Layout::top_down_justified(egui::Align::Min))
1385        .width(160.0)
1386        .show(|ui| {
1387            for action in actions {
1388                if action.separator_above {
1389                    ui.separator();
1390                }
1391                // The caption may lead with a catalogued glyph (🔒 Fix,
1392                // ✖ Delete); it is drawn as artwork, not as a character. A
1393                // destructive entry keeps its red — on the artwork as well as
1394                // the text.
1395                let color = action.destructive.then(|| ui.visuals().error_fg_color);
1396                // An entry never wraps. The popup's `Area` keeps the width it
1397                // measured the last time it was up, so without this a menu
1398                // opened after a narrower one broke its longer entries over
1399                // two lines ("Remove from / sheet" after a dimension's menu).
1400                let button = crate::icon_text::icon_button_colored(ui, &action.label, color)
1401                    .wrap_mode(egui::TextWrapMode::Extend);
1402                let entry = ui.add_enabled(action.enabled, button);
1403                on_entry(action, entry.rect);
1404                if !action.tooltip.is_empty() {
1405                    // A greyed entry's tooltip is where its refusal is
1406                    // explained, so it has to be the DISABLED hover.
1407                    if action.enabled {
1408                        entry.clone().on_hover_text(&action.tooltip);
1409                    } else {
1410                        entry.clone().on_disabled_hover_text(&action.tooltip);
1411                    }
1412                }
1413                if entry.clicked() {
1414                    chosen = Some(action.id.clone());
1415                }
1416            }
1417        });
1418    (chosen, still_open)
1419}
1420
1421/// The row with `id`, anywhere in the tree.
1422fn find_row<'a>(rows: &'a [RowNode], id: &str) -> Option<&'a RowNode> {
1423    for row in rows {
1424        if row.id == id {
1425            return Some(row);
1426        }
1427        if let Some(found) = find_row(&row.children, id) {
1428            return Some(found);
1429        }
1430    }
1431    None
1432}
1433
1434/// Truncate `text` with an ellipsis so it fits `width`.
1435fn elide(ui: &egui::Ui, text: &str, width: f32) -> String {
1436    let font = egui::TextStyle::Body.resolve(ui.style());
1437    let measure = |candidate: &str| {
1438        ui.painter()
1439            .layout_no_wrap(candidate.to_string(), font.clone(), egui::Color32::WHITE)
1440            .rect
1441            .width()
1442    };
1443    if width <= 0.0 || measure(text) <= width {
1444        return text.to_string();
1445    }
1446    let mut cut: Vec<char> = text.chars().collect();
1447    while !cut.is_empty() {
1448        cut.pop();
1449        let candidate: String = cut.iter().collect::<String>() + "\u{2026}";
1450        if measure(&candidate) <= width {
1451            return candidate;
1452        }
1453    }
1454    String::new()
1455}
1456
1457fn publish(
1458    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
1459    spec: &ColumnTreeSpec<'_>,
1460    key: &str,
1461    rect: egui::Rect,
1462) {
1463    if let Some(map) = hits.as_deref_mut() {
1464        map.insert(format!("{}{key}", spec.hits_prefix), rect);
1465    }
1466}
1467
1468