Skip to main content

brep_app/panels/
tree.rs

1//! A reusable, custom-painted TREE-NODE widget — the shared building block for
2//! the engine-native side panels (the history feature tree here; the Scene tree
3//! and others reuse it verbatim). egui's default `CollapsingHeader` draws a
4//! disclosure TRIANGLE and no connector rules; the design reference is a classic
5//! file-tree with **`[+]`/`[-]` collapse boxes + connector lines**, so this
6//! module paints those itself.
7//!
8//! # The node model (immutable-mode friendly)
9//!
10//! A node is ONE row: `⟨connectors⟩ [+/-] ⟨glyph⟩ ⟨label⟩ … ⟨right content⟩`.
11//! Expansion state is OWNED BY THE CALLER (the panels need exclusive-expand +
12//! roll-to side effects), so [`node`] just draws a row and returns what was
13//! clicked; the caller decides whether to recurse into children.
14//!
15//! ## Connector geometry
16//!
17//! Indentation is one [`INDENT`] column per tree level. A node at connector
18//! column `d = guides.len()` draws its `├`/`└` connector at column `d` and its
19//! box slot at column `d + 1`. `guides[i]` (`i < d`) says whether an ANCESTOR's
20//! sibling line passes vertically through this row at column `i`. Descending into
21//! a node's children extends the guide stack by [`child_guides`] with
22//! `!this_node_is_last` — the node's own connector line continues down past its
23//! children only if it has following siblings. This is the standard file-tree
24//! rule and yields the reference's exact rules.
25//!
26//! ## Select and open
27//!
28//! Every tree reads a row the same way: a single click SELECTS the row's object
29//! ([`NodeResponse::clicked`]) and a double click OPENS its dialog
30//! ([`NodeResponse::double_clicked`]). A selected row is drawn with the
31//! selection band behind its whole width ([`TreeRow::highlighted`]), the look
32//! the column trees give theirs.
33//!
34//! ## Reorder by touch: hold, then drag
35//!
36//! A DRAGGABLE row is a reorder handle, and under a mouse it starts its drag at
37//! once. Under a finger that would make every row a wall the list cannot be
38//! scrolled through (owner 2026-11-29: "Drag and drop vs scroll is not good. A
39//! long press before drag and drop would be a good thing on mobile"). So in the
40//! touch layout (`viewport::touch::enabled`) a draggable row does not
41//! sense drag at all: a finger that moves scrolls the list, and only a finger
42//! held still for [`LIFT_HOLD`] lifts the row (a visible band) and starts the
43//! reorder. Every drag-reorder tree goes through [`node`], so every one of them
44//! follows that rule; [`LiftState`] is the gesture, kept pure so it is tested
45//! without a frame.
46//!
47//! This module has NO engine dependency — it is pure egui + geometry, so a later
48//! `brep-ui` crate (and the theme pass, #49) can reuse it unchanged.
49
50use crate::icon_text::IconText;
51use eframe::egui;
52
53/// One tree indentation level, in egui points.
54pub const INDENT: f32 = 16.0;
55/// The collapse box's side length.
56const BOX: f32 = 13.0;
57/// Gap between the box slot, an optional glyph, and the label.
58const GAP: f32 = 4.0;
59/// Right-side gutter reserved before the right-aligned row content (timing,
60/// delete X, field inputs, a Select button) so those controls clear the sidebar
61/// scroll bar instead of underlapping it — an underlapping X eats the click as a
62/// scroll drag rather than firing.
63const RIGHT_PAD: f32 = 10.0;
64
65/// The spec for one tree row. Borrows its strings; holds no state (expansion is
66/// the caller's — see the module docs).
67pub struct TreeRow<'a> {
68    /// Ancestor vertical-guide flags, one per level strictly above this node
69    /// (`true` = a sibling line passes through this row at that level). The
70    /// node's own connector column index is `guides.len()`.
71    pub guides: &'a [bool],
72    /// This node is the LAST among its siblings (`└` vs `├`). Ignored when `root`.
73    pub is_last: bool,
74    /// Draw a `[+]`/`[-]` collapse box (an expandable node) instead of an empty
75    /// box slot (a leaf). A leaf keeps the same label indent so labels align.
76    pub expandable: bool,
77    /// Current expand state — only meaningful when `expandable`.
78    pub expanded: bool,
79    /// The far-left ROOT row (e.g. `Features`): no connector, box at column 0.
80    pub root: bool,
81    /// An optional per-type glyph drawn between the box slot and the label.
82    pub glyph: Option<&'a str>,
83    /// The row's text label.
84    pub label: &'a str,
85    /// Emphasize the label (the selected node).
86    pub selected: bool,
87    /// Paint the selection band behind the whole row — the selected LINE.
88    /// [`Self::selected`] sets it with the emphasis; a column tree, which paints
89    /// its own band across every column, draws its tree cell without it.
90    pub highlighted: bool,
91    /// Make the label a drag handle (`Sense::click_and_drag`) — drag-reorder.
92    pub draggable: bool,
93    /// Override the label's text color (the sketch panel paints a CONFLICTING
94    /// constraint's row red). `None` keeps the theme's text color, including its
95    /// hover/selection behavior.
96    pub tint: Option<egui::Color32>,
97}
98
99impl<'a> TreeRow<'a> {
100    /// A plain expandable branch node.
101    pub fn branch(guides: &'a [bool], is_last: bool, expanded: bool, label: &'a str) -> Self {
102        Self {
103            guides,
104            is_last,
105            expandable: true,
106            expanded,
107            root: false,
108            glyph: None,
109            label,
110            selected: false,
111            highlighted: false,
112            draggable: false,
113            tint: None,
114        }
115    }
116
117    /// A plain leaf node (no collapse box).
118    pub fn leaf(guides: &'a [bool], is_last: bool, label: &'a str) -> Self {
119        Self {
120            guides,
121            is_last,
122            expandable: false,
123            expanded: false,
124            root: false,
125            glyph: None,
126            label,
127            selected: false,
128            highlighted: false,
129            draggable: false,
130            tint: None,
131        }
132    }
133
134    pub fn glyph(mut self, glyph: Option<&'a str>) -> Self {
135        self.glyph = glyph;
136        self
137    }
138    /// Mark the row selected: its label emphasized and its line highlighted.
139    pub fn selected(mut self, selected: bool) -> Self {
140        self.selected = selected;
141        self.highlighted = selected;
142        self
143    }
144    pub fn draggable(mut self, draggable: bool) -> Self {
145        self.draggable = draggable;
146        self
147    }
148    pub fn tint(mut self, tint: Option<egui::Color32>) -> Self {
149        self.tint = tint;
150        self
151    }
152}
153
154/// What happened to a drawn tree row.
155pub struct NodeResponse {
156    /// The whole row rect (for hit publishing / drag-target hit-testing).
157    pub row_rect: egui::Rect,
158    /// The collapse-box rect (for hit publishing).
159    pub box_rect: egui::Rect,
160    /// The `[+]`/`[-]` collapse box was clicked (a pure toggle intent).
161    pub toggled: bool,
162    /// The label response — the DRAG handle and the hover source. Use
163    /// `.drag_started()` / `.drag_stopped()` to reorder and `.hovered()` for a
164    /// text-keyed highlight. For "the row was clicked" use [`Self::clicked`],
165    /// not this: the label's rect is only its own text.
166    pub label: egui::Response,
167    /// The whole ROW BAND, sensing clicks BELOW everything drawn in the row.
168    /// egui hands an overlapped point to the last widget registered there and
169    /// this one is registered first (`UiBuilder::sense`), so the collapse box,
170    /// the label and every control the caller put in `add_right` still take
171    /// their own clicks — the band only ever receives what none of them wanted,
172    /// which is exactly the blank space between them.
173    ///
174    /// It is also the row's KEYBOARD stop: the label is deliberately not
175    /// focusable, so a row is one Tab stop and Enter/Space on it reports
176    /// `clicked()` here.
177    ///
178    /// It senses DRAG as well as click, and it has to: egui withdraws the click
179    /// from a press that outlives `max_click_duration` (0.8 s) or drifts past
180    /// `max_click_dist` (6 pt) whether or not the widget senses drag, so a
181    /// click-only band would go dead under exactly the slow, wobbly press an
182    /// ordinary hand makes. A caller resolves that press through
183    /// [`Self::drag_started`], as the history and constraint trees do.
184    pub band: egui::Response,
185    /// The BAND's drag started, and its press did not begin on one of the row's
186    /// own controls (the collapse box, anything `add_right` drew). Read through
187    /// [`Self::drag_started`].
188    pub band_drag_started: bool,
189    /// A finger's long press LIFTED this row this frame: the touch layout's
190    /// reorder start (see the module docs). Read through [`Self::drag_started`].
191    pub lift_started: bool,
192    /// This press is a touch lift (it lifted on this or an earlier frame). Its
193    /// clicks are not clicks: egui's own long touch reports a click and a
194    /// secondary click at 0.8 s, which would select the row or open its menu
195    /// in the middle of a reorder.
196    pub lifted: bool,
197}
198
199impl NodeResponse {
200    /// The ROW was clicked — on its text or anywhere else in its band that no
201    /// control of its own claimed. This, not `label.clicked()`, is what
202    /// "the user picked this row" means: a row is a click target across its
203    /// whole width, and a label's rect is only as wide as its text. A click
204    /// SELECTS the row's object.
205    pub fn clicked(&self) -> bool {
206        !self.lifted && (self.label.clicked() || self.band.clicked())
207    }
208
209    /// The row was SECONDARY-clicked (a right click, or egui's long touch),
210    /// over the same area as [`Self::clicked`]. A row with a menu opens it from
211    /// this. Never during a touch lift: the hold that lifted the row for a
212    /// reorder is not a request for its menu.
213    pub fn secondary_clicked(&self) -> bool {
214        !self.lifted && (self.band.secondary_clicked() || self.label.secondary_clicked())
215    }
216
217    /// The ROW was double-clicked, over the same area as [`Self::clicked`]. A
218    /// double click OPENS the row's dialog. egui reports the second press as a
219    /// click as well, so on this frame [`Self::clicked`] is true too: a
220    /// consumer checks this first.
221    ///
222    /// egui's TRIPLE click counts. egui numbers a click 3 when the click two
223    /// before it is under 0.6 s old, and a 3 is not a 2 — so a row clicked once
224    /// and then double-clicked a moment later would otherwise never open.
225    pub fn double_clicked(&self) -> bool {
226        !self.lifted && (is_double_click(&self.label) || is_double_click(&self.band))
227    }
228}
229
230/// A response's double click, egui's triple included — see
231/// [`NodeResponse::double_clicked`]. The column trees read their row bands
232/// through this too.
233pub fn is_double_click(response: &egui::Response) -> bool {
234    response.double_clicked() || response.triple_clicked()
235}
236
237impl NodeResponse {
238
239    /// A press on the row turned into a DRAG — on the label or anywhere else
240    /// along the band. A pane that reorders by drag arms itself from this; a
241    /// pane that does not still wants it, because a press egui reclassified as
242    /// a drag is the click it refused to report, and resolving it is the only
243    /// way a slow click on a row still opens that row.
244    pub fn drag_started(&self) -> bool {
245        self.label.drag_started() || self.band_drag_started || self.lift_started
246    }
247}
248
249/// Extend a guide stack for a node's children: the node's own connector column
250/// keeps drawing a vertical line past the children ONLY if the node has more
251/// siblings below it (`!is_last`).
252pub fn child_guides(guides: &[bool], is_last: bool) -> Vec<bool> {
253    let mut next = guides.to_vec();
254    next.push(!is_last);
255    next
256}
257
258/// Draw ONE tree row and return what was interacted with. `add_right` fills the
259/// right-aligned content area (timing + delete, field inputs, a Select button…).
260///
261/// The whole row is a click target: read [`NodeResponse::clicked`], which is the
262/// band and the label together. [`NodeResponse::label`] remains the reorder
263/// drag handle and the source of a text-keyed hover.
264/// The hover band's colour: the theme's hover overlay.
265pub(crate) fn hover_band_fill(theme: &crate::theme::Theme) -> egui::Color32 {
266    theme.colors.hover
267}
268
269pub fn node(
270    ui: &mut egui::Ui,
271    row: TreeRow,
272    add_right: impl FnOnce(&mut egui::Ui),
273) -> NodeResponse {
274    let connector_col = if row.root { 0 } else { row.guides.len() };
275    // The box slot (and thus the label) begins one column right of the connector.
276    let indent = if row.root {
277        0.0
278    } else {
279        (connector_col as f32 + 1.0) * INDENT
280    };
281
282    let mut box_rect = egui::Rect::NOTHING;
283    let mut toggled = false;
284    let mut label_resp: Option<egui::Response> = None;
285    // The selection band's slot, reserved BEFORE the row so the row's contents
286    // paint over it; filled once the row's rect is known.
287    let highlight = ui.painter().add(egui::Shape::Noop);
288    // The row's OWN controls — the collapse box and whatever `add_right` drew.
289    // A press that starts on one of those belongs to it, never to the band.
290    let mut controls = egui::Rect::NOTHING;
291    // The touch layout's reorder handle: hold, then drag (module docs). Such a
292    // row senses NO drag, so a finger that moves is the list's scroll.
293    let hold_to_drag = row.draggable && crate::viewport::touch::enabled(ui.ctx());
294
295    // THE ROW BAND. A row is a click target across its whole width, not only
296    // across its text — so the row is drawn inside a `Ui` that senses clicks
297    // itself. `UiBuilder::sense` registers that rect BEFORE the row's contents
298    // and updates it in place when the scope closes, and egui's hit test hands
299    // an overlapped point to the LAST widget registered there, so every control
300    // inside the row (the collapse box, the label, whatever `add_right` draws)
301    // still takes its own clicks and the band receives only what none of them
302    // wanted. Allocating it AFTER the row instead would invert that and the
303    // band would eat the delete button.
304    let band_sense = if hold_to_drag {
305        egui::Sense::click()
306    } else {
307        egui::Sense::click_and_drag()
308    };
309    let outer = ui.scope_builder(
310        egui::UiBuilder::new().sense(band_sense),
311        |ui| {
312            ui.horizontal(|ui| {
313                // Zero the inter-item spacing so the geometry math is exact; gaps are
314                // added explicitly below.
315                ui.spacing_mut().item_spacing.x = 0.0;
316                if indent > 0.0 {
317                    ui.add_space(indent);
318                }
319
320                // --- collapse box (expandable) or an equally-wide empty slot (leaf) ----
321                let (brect, bresp) = ui.allocate_exact_size(
322                    crate::viewport::touch::target_size(ui.ctx(), egui::vec2(BOX, BOX)),
323                    if row.expandable {
324                        egui::Sense::click()
325                    } else {
326                        egui::Sense::hover()
327                    },
328                );
329                box_rect = brect;
330                if row.expandable {
331                    let painted = egui::Rect::from_center_size(brect.center(), egui::Vec2::splat(BOX));
332                    paint_box(ui, painted, row.expanded);
333                    if bresp.clicked() {
334                        toggled = true;
335                    }
336                }
337                ui.add_space(GAP);
338
339                // --- optional per-type glyph ------------------------------------------
340                // Drawn as catalogued artwork, sized to the row's text. Monochrome
341                // artwork is tinted to the row's text colour, so it reads exactly as the
342                // old font glyph did; colour artwork is left alone. Anything
343                // uncatalogued falls back to text.
344                if let Some(glyph) = row.glyph {
345                    match crate::icons::artwork(glyph) {
346                        Some(icon) => {
347                            // A tree row can be the first thing on screen to draw an
348                            // SVG; `install_image_loaders` is idempotent.
349                            egui_extras::install_image_loaders(ui.ctx());
350                            let height = ui.text_style_height(&egui::TextStyle::Body);
351                            let mut art = crate::icon_text::image(icon, height);
352                            if icon.mono {
353                                art = art.tint(ui.visuals().text_color());
354                            }
355                            ui.add(art);
356                        }
357                        None => {
358                            ui.label(egui::RichText::new(glyph).color(ui.visuals().text_color()));
359                        }
360                    }
361                    ui.add_space(GAP);
362                }
363
364                // --- label (the click / drag handle) ----------------------------------
365                // Tree rows are DATA (owner 2026-11-28: trees, tables and
366                // lists use same-width characters), in the theme's data role;
367                // a selected row reads by its accent band and edge, below.
368                let theme = crate::theme::Theme::of(ui);
369                // The colour stays the ambient one, so a caller's dimmed or
370                // tinted subtree still reads as it did.
371                let mut text = egui::RichText::new(row.label).font(theme.font(crate::theme::Text::Data));
372                if let Some(tint) = row.tint {
373                    text = text.color(tint);
374                }
375                // Click (and, on a reorder handle, drag) but NOT focus: the row's Tab
376                // stop is the band, which covers the whole row rather than just this
377                // text. Two focusable widgets per row would make Tab visit every row
378                // twice and put the keyboard's idea of "the row" on its label.
379                let sense = if row.draggable && !hold_to_drag {
380                    egui::Sense::CLICK | egui::Sense::DRAG
381                } else {
382                    egui::Sense::CLICK
383                };
384                // A DRAGGABLE row is a reorder handle, so its label must NOT be
385                // text-selectable: egui labels are selectable by default, and a press on a
386                // selectable label anchors a text selection that the ensuing reorder drag
387                // then SWEEPS across every row the cursor passes over (the passed-over rows
388                // "light up"). Making only the drag handle non-selectable means the reorder
389                // press never anchors a selection, so no sweep — while every non-draggable
390                // row (fields, groups, scene/settings leaves) keeps default selectable text.
391                // Hover coloring is unaffected: it is computed from the response independent
392                // of `selectable` (see egui `Label`), so ordinary non-drag hover is unchanged.
393                // A label can carry catalogued glyphs of its own — the sketch panel
394                // appends ⛓ / ◐ / ⏚ marks to entity rows — and with no icon font left,
395                // drawing those as text would render a box. `icon_label` draws them from
396                // the same SVG catalog the glyph column uses.
397                //
398                // A DRAGGABLE row keeps the plain `Label`: it is the reorder handle, and
399                // it must stay ONE widget whose response is the drag. Nothing needs
400                // both — a draggable row's glyph goes in the glyph column above, not
401                // inline — and `has_icon` is false for those labels, so this only ever
402                // takes the icon path for the rows that need it.
403                let has_icon = row.label.chars().any(crate::icons::has);
404
405                // --- right-aligned content, THEN the label ----------------------------
406                // The right content is allocated FIRST, from the panel's right edge, and
407                // the label truncates into whatever it leaves — the order the form's
408                // reference lines and the form view's title row already use, for the
409                // same reason. A row's label is not a UI string the app chose: a scene
410                // row is labelled with a SOLID's name, as long as the modelling history
411                // made it. Laid out label-first, at its natural width, a 76-character
412                // name pushed the visibility checkbox 202 pt past the edge of a 320 pt
413                // panel — off the panel, where an ancestor clip eats the click too.
414                //
415                // Both label flavours take a wrap mode, so neither can overflow: the
416                // plain `Label` is the drag handle and keeps its `sense`, and `IconText`
417                // truncates the same way (a row whose label carries ⛓ / ◐ / ⏚ marks).
418                // A label SHORTER than the band still measures its own text, which is
419                // exactly why the row's click target and published rect are the BAND
420                // and not this: a two-word name left four fifths of its row dead.
421                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
422                    ui.add_space(RIGHT_PAD);
423                    add_right(ui);
424                    // What the CALLER put at the row's right edge, as one rect.
425                    // A right-to-left `Ui` grows leftwards from the panel edge,
426                    // so its min_rect here — after the gutter and the caller's
427                    // controls, before the label — is exactly that strip.
428                    controls = ui.min_rect();
429                    ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
430                        label_resp = Some(if has_icon && !row.draggable {
431                            IconText::new(text)
432                                .sense(sense)
433                                .selectable(false)
434                                .truncate()
435                                .show(ui)
436                        } else {
437                            ui.add(
438                                egui::Label::new(text)
439                                    .sense(sense)
440                                    .selectable(!row.draggable)
441                                    .truncate(),
442                            )
443                        });
444                    });
445                });
446            })
447        },
448    );
449    let band = outer.response;
450    let theme = crate::theme::Theme::of(ui);
451    // A press that STARTED on one of the row's own controls is that control's
452    // press, never the row's (see `band_drag_started` below).
453    let press = ui.input(|i| i.pointer.press_origin());
454    let from_a_control = press
455        .is_some_and(|at| box_rect.contains(at) || controls.contains(at));
456    let (lift_started, lifted, held) = if hold_to_drag {
457        touch_lift(ui, band.id, band.interact_rect, from_a_control)
458    } else {
459        (false, false, false)
460    };
461    // A SELECTED row sits on `accent.muted` with a 2 px accent edge on its
462    // left (ui-refresh-spec section 5, tree rows); a highlighted one on the
463    // muted band alone. A row under the pointer takes the hover band, so a
464    // long tree shows which row a click will land on before the click
465    // (ui-polish-2026-10-28 row 13). All are painted into the band's own slot
466    // reserved before the row: no layout moves, and the contents draw over it.
467    if held {
468        // THE LIFT CUE: the held row stands out from the list as a raised
469        // card (accent band, a ring and a shadow under it) for as long as the
470        // finger carries it.
471        let shadow = band.rect.translate(egui::vec2(0.0, 3.0));
472        let ring = egui::Stroke::new(crate::theme::RING, theme.colors.accent_ring);
473        ui.painter().set(
474            highlight,
475            egui::Shape::Vec(vec![
476                egui::Shape::rect_filled(shadow, 2.0, egui::Color32::from_black_alpha(70)),
477                egui::Shape::rect_filled(band.rect, 2.0, theme.colors.accent_muted),
478                egui::Shape::rect_stroke(band.rect, 2.0, ring, egui::StrokeKind::Inside),
479            ]),
480        );
481    } else if !row.root && (row.selected || row.highlighted) {
482        let mut shapes = vec![egui::Shape::Rect(egui::epaint::RectShape::filled(band.rect, 0.0, theme.colors.accent_muted))];
483        if row.selected {
484            let edge = egui::Rect::from_min_max(band.rect.left_top(), egui::pos2(band.rect.left() + crate::theme::RING, band.rect.bottom()));
485            shapes.push(egui::Shape::Rect(egui::epaint::RectShape::filled(edge, 0.0, theme.colors.accent_ring)));
486        }
487        ui.painter().set(highlight, egui::Shape::Vec(shapes));
488    } else if !row.root && band.contains_pointer() && ui.ctx().dragged_id().is_none() {
489        ui.painter().set(highlight, egui::epaint::RectShape::filled(band.rect, 0.0, hover_band_fill(&theme)));
490    }
491
492    let row_rect = outer.inner.response.rect;
493    if !row.root {
494        paint_connectors(ui, row_rect, row.guides, connector_col, row.is_last);
495    }
496    // The row is the keyboard stop, so say so when it holds the focus: nothing
497    // else in the row paints one now that the label is not focusable, and a
498    // focus nobody can see is a focus nobody can use.
499    if band.has_focus() {
500        crate::ui_kit::paint::focus_ring(ui, row_rect, crate::theme::radius::INPUT, &theme);
501    }
502
503    // A band drag whose press STARTED on one of the row's own controls is that
504    // control's press, not a row drag. egui reports both — a click-sensing
505    // button on top and the drag-sensing band beneath are "interested in
506    // different things", so `hit_test` hands back both hits — and without this
507    // the edit button became a reorder handle the moment the hand moved.
508    let band_drag_started = band.drag_started() && !from_a_control;
509
510    NodeResponse {
511        row_rect,
512        box_rect,
513        toggled,
514        label: label_resp.expect("label always drawn"),
515        band,
516        band_drag_started,
517        lift_started,
518        lifted,
519    }
520}
521
522/// How long a finger must rest on a reorder row before the row lifts, in
523/// seconds. Under egui's 0.8 s long touch, so the lift comes first.
524pub const LIFT_HOLD: f64 = 0.45;
525/// How far a finger may wander (points, from where it pressed) and still be
526/// HOLDING. Past it before [`LIFT_HOLD`] the press is a scroll.
527pub const LIFT_SLOP: f32 = 8.0;
528
529/// One press on a hold-to-drag row (module docs), as a pure state machine.
530/// One gesture at a time, app-wide: a reorder is one finger.
531#[derive(Clone, Copy, Debug, Default, PartialEq)]
532pub enum LiftState {
533    /// No press on a reorder row.
534    #[default]
535    Idle,
536    /// A press on `row` at `origin` at `since` (egui seconds), not yet held
537    /// long enough. `touch`: a finger, which must HOLD; a mouse in the touch
538    /// layout (a desktop browser with `?mobile=1`) has no scroll gesture to
539    /// keep apart, so it lifts as soon as it moves.
540    Pending { row: egui::Id, origin: egui::Pos2, since: f64, touch: bool },
541    /// `row` is lifted and is being carried until the press ends.
542    Lifted { row: egui::Id },
543}
544
545/// One frame's input to [`LiftState::step`], as seen by ONE row.
546#[derive(Clone, Copy, Debug)]
547pub struct LiftInput {
548    /// A press began THIS frame, inside this row, not on one of its controls.
549    pub pressed_here: bool,
550    /// Where the press began (with `pressed_here`).
551    pub origin: egui::Pos2,
552    /// The primary pointer is down.
553    pub down: bool,
554    /// The pointer's latest position.
555    pub pos: Option<egui::Pos2>,
556    /// egui's clock.
557    pub time: f64,
558    /// A finger is on the screen.
559    pub touch: bool,
560    /// More than one finger is on the screen (a pinch, not a reorder).
561    pub multi: bool,
562}
563
564impl LiftState {
565    /// Advance the gesture for the row `row`. Returns the new state and
566    /// whether the row lifted on this frame. A state that belongs to another
567    /// row is left as it is.
568    pub fn step(self, row: egui::Id, input: LiftInput) -> (LiftState, bool) {
569        if input.pressed_here && input.down && !input.multi {
570            let pending = LiftState::Pending { row, origin: input.origin, since: input.time, touch: input.touch };
571            return (pending, false);
572        }
573        match self {
574            LiftState::Pending { row: r, origin, since, touch } if r == row => {
575                if !input.down || input.multi {
576                    return (LiftState::Idle, false);
577                }
578                let moved = input.pos.is_some_and(|p| p.distance(origin) > LIFT_SLOP);
579                if moved {
580                    // A finger that travels before the hold is SCROLLING the
581                    // list; a mouse that travels is dragging the row.
582                    return if touch { (LiftState::Idle, false) } else { (LiftState::Lifted { row }, true) };
583                }
584                if touch && input.time - since >= LIFT_HOLD {
585                    return (LiftState::Lifted { row }, true);
586                }
587                (self, false)
588            }
589            LiftState::Lifted { row: r } if r == row => {
590                if input.down { (self, false) } else { (LiftState::Idle, false) }
591            }
592            other => (other, false),
593        }
594    }
595
596    /// Whether this state is `row`'s lift.
597    pub fn holds(self, row: egui::Id) -> bool {
598        matches!(self, LiftState::Lifted { row: r } if r == row)
599    }
600}
601
602/// Run the hold-to-drag gesture for one row this frame: returns
603/// `(lifted this frame, this press is a lift, the row is held now)`.
604fn touch_lift(ui: &egui::Ui, row: egui::Id, rect: egui::Rect, from_a_control: bool) -> (bool, bool, bool) {
605    let key = egui::Id::new("brep-tree-touch-lift");
606    let ctx = ui.ctx();
607    let before: LiftState = ctx.data(|d| d.get_temp(key)).unwrap_or_default();
608    let input = ctx.input(|i| {
609        let origin = i.pointer.press_origin().unwrap_or(egui::Pos2::ZERO);
610        LiftInput {
611            pressed_here: i.pointer.primary_pressed() && !from_a_control && rect.contains(origin),
612            origin,
613            down: i.pointer.primary_down(),
614            pos: i.pointer.latest_pos().or(i.pointer.interact_pos()),
615            time: i.time,
616            touch: i.any_touches(),
617            multi: i.multi_touch().is_some(),
618        }
619    });
620    let (after, started) = before.step(row, input);
621    if after != before {
622        ctx.data_mut(|d| d.insert_temp(key, after));
623    }
624    if let LiftState::Pending { row: r, since, touch: true, .. } = after {
625        if r == row {
626            // An idle app draws no frames: without this a finger held
627            // perfectly still would never reach the deadline.
628            let left = (since + LIFT_HOLD - input.time).max(0.0);
629            ctx.request_repaint_after(std::time::Duration::from_secs_f64(left + 0.01));
630        }
631    }
632    let held = after.holds(row);
633    if held && ctx.dragged_id() != Some(row) {
634        // Take the press from the scroll area (or it scrolls under the
635        // reorder), and take it BACK after egui's 0.8 s long touch drops it.
636        ctx.set_dragged_id(row);
637    }
638    (started, held || before.holds(row), held)
639}
640
641/// Draw a LEAF whose content is a multi-line, WRAPPING colored message — e.g. a
642/// feature's error text shown under its header. Unlike [`node`] (a single
643/// non-wrapping row), the label WRAPS to the available width and the row grows as
644/// tall as it needs; the `└`/`├` connector anchors to the FIRST line so it still
645/// reads as a normal child leaf under its parent. Returns the full row rect.
646pub fn message_leaf(
647    ui: &mut egui::Ui,
648    guides: &[bool],
649    is_last: bool,
650    text: &str,
651    color: egui::Color32,
652) -> egui::Rect {
653    let connector_col = guides.len();
654    // Align the wrapped text with where a LEAF's label starts: indent to the box
655    // slot column, then clear the (empty) box slot + gap.
656    let indent = (connector_col as f32 + 1.0) * INDENT + BOX + GAP;
657    let line_h = ui.text_style_height(&egui::TextStyle::Body);
658    let inner = ui.horizontal(|ui| {
659        ui.spacing_mut().item_spacing.x = 0.0;
660        ui.add_space(indent);
661        // A vertical child claims the remaining row; the wrapping label wraps to its
662        // width (minus the right gutter so it clears the sidebar scroll bar).
663        ui.vertical(|ui| {
664            ui.set_max_width((ui.available_width() - RIGHT_PAD).max(40.0));
665            ui.add(
666                egui::Label::new(egui::RichText::new(text).color(color))
667                    .wrap_mode(egui::TextWrapMode::Wrap),
668            );
669        });
670    });
671    let row_rect = inner.response.rect;
672    let tick_y = row_rect.top() + line_h * 0.5;
673    paint_connectors_at(ui, row_rect, guides, connector_col, is_last, tick_y);
674    row_rect
675}
676
677/// Paint a `[+]`/`[-]` collapse box: a rounded stroked square with a minus bar
678/// (expanded) plus a vertical bar (collapsed → a plus). Theme-aware.
679fn paint_box(ui: &egui::Ui, rect: egui::Rect, expanded: bool) {
680    let painter = ui.painter();
681    let stroke = egui::Stroke::new(1.0, line_color(ui));
682    painter.rect(
683        rect,
684        egui::CornerRadius::same(2),
685        egui::Color32::TRANSPARENT,
686        stroke,
687        egui::StrokeKind::Inside,
688    );
689    let c = rect.center();
690    let arm = rect.width() * 0.28;
691    let sign = egui::Stroke::new(1.4, crate::theme::Theme::of(ui).colors.text_secondary);
692    // horizontal bar (always → the minus of a `[-]`)
693    painter.line_segment(
694        [egui::pos2(c.x - arm, c.y), egui::pos2(c.x + arm, c.y)],
695        sign,
696    );
697    // vertical bar (only when collapsed → completes the plus of a `[+]`)
698    if !expanded {
699        painter.line_segment(
700            [egui::pos2(c.x, c.y - arm), egui::pos2(c.x, c.y + arm)],
701            sign,
702        );
703    }
704}
705
706/// Paint the ancestor guide lines + this node's `├`/`└` connector into the row's
707/// left gutter (over-drawn by the inter-row spacing so verticals join seamlessly
708/// across rows). The `├`/`└` tick lands at the row's vertical center.
709fn paint_connectors(
710    ui: &egui::Ui,
711    row: egui::Rect,
712    guides: &[bool],
713    connector_col: usize,
714    is_last: bool,
715) {
716    paint_connectors_at(ui, row, guides, connector_col, is_last, row.center().y);
717}
718
719/// Like [`paint_connectors`] but with an explicit `tick_y` for the `├`/`└` join —
720/// so a MULTI-LINE row (a wrapping message leaf) can anchor its connector to its
721/// FIRST line instead of the block's vertical center.
722fn paint_connectors_at(
723    ui: &egui::Ui,
724    row: egui::Rect,
725    guides: &[bool],
726    connector_col: usize,
727    is_last: bool,
728    mid: f32,
729) {
730    let painter = ui.painter();
731    let stroke = egui::Stroke::new(1.0, line_color(ui));
732    let sp = ui.spacing().item_spacing.y + 1.0;
733    let left = row.left();
734    let top = row.top() - sp;
735    let bottom = row.bottom() + sp;
736    let col_x = |c: usize| left + c as f32 * INDENT + INDENT * 0.5;
737
738    // Ancestor sibling lines passing through this row.
739    for (i, on) in guides.iter().enumerate() {
740        if *on {
741            let x = col_x(i);
742            painter.line_segment([egui::pos2(x, top), egui::pos2(x, bottom)], stroke);
743        }
744    }
745    // This node's own connector: vertical down to mid (└) or through (├), plus a
746    // horizontal tick reaching the box slot.
747    let x = col_x(connector_col);
748    let v_bottom = if is_last { mid } else { bottom };
749    painter.line_segment([egui::pos2(x, top), egui::pos2(x, v_bottom)], stroke);
750    painter.line_segment(
751        [egui::pos2(x, mid), egui::pos2(x + INDENT * 0.5, mid)],
752        stroke,
753    );
754}
755
756/// The subtle connector / box stroke color — the theme's non-interactive
757/// foreground, dimmed. Theme-aware (light + dark) and the seam the later theme
758/// pass tunes in one place.
759fn line_color(ui: &egui::Ui) -> egui::Color32 {
760    crate::theme::Theme::of(ui).colors.border_strong
761}
762