agg-gui 0.1.0

A Rust GUI framework built on AGG — immediate-mode widgets, Y-up layout, halo-AA rendering via tess2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! `TreeView` — compositional tree widget with expand/collapse, multi-select,
//! keyboard navigation, and drag-and-drop reordering.
//!
//! Each visible row is represented by a `TreeRow` child widget stored in
//! `row_widgets`.  The framework recurses into these children after `paint()`
//! returns, so the `clip_rect` set at the end of `paint()` is active during
//! child painting.

mod node;
mod drag;
pub mod row;

pub use node::{NodeIcon, TreeNode};
pub use row::{ExpandToggle, NodeIconWidget, TreeRow};
use node::{DragState, DropPosition, FlatRow, flatten_visible};
use drag::{apply_drop, compute_drop_target, paint_drop_child_highlight,
           paint_drop_line, paint_ghost};
use row::{EXPAND_W, icon_color};

use std::sync::Arc;

use crate::event::{Event, EventResult, Key, Modifiers, MouseButton};
use crate::geometry::{Point, Rect, Size};
use crate::draw_ctx::DrawCtx;
use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
use crate::text::Font;
use crate::widget::Widget;

const SCROLLBAR_W: f64 = 10.0;
const DRAG_THRESHOLD: f64 = 4.0;

// ---------------------------------------------------------------------------
// RowMeta
// ---------------------------------------------------------------------------

/// Metadata for one visible row; parallel to `row_widgets` after `layout()`.
struct RowMeta {
    /// Index into `self.nodes` for this row.
    node_idx: usize,
    /// Bounds of the `ExpandToggle` in **TreeView-local** coordinates.
    /// `None` if the node has no children.
    toggle_rect: Option<Rect>,
}

// ---------------------------------------------------------------------------
// TreeView struct
// ---------------------------------------------------------------------------

pub struct TreeView {
    bounds: Rect,
    /// One `TreeRow` per currently-visible node; rebuilt each `layout()` call.
    row_widgets: Vec<Box<dyn Widget>>,
    base: WidgetBase,
    /// Parallel to `row_widgets` — metadata for hit-testing in `on_event()`.
    row_metas: Vec<RowMeta>,

    pub nodes: Vec<TreeNode>,

    // Scroll state
    scroll_offset: f64,
    content_height: f64,

    // Row metrics
    pub row_height: f64,
    pub indent_width: f64,
    pub font: Arc<Font>,
    pub font_size: f64,

    // Interaction
    pub drag_enabled: bool,
    /// When `true`, clicking anywhere on a row that has children also toggles
    /// its expansion state.  When `false` (the default), only the expand-toggle
    /// arrow collapses/expands; clicks elsewhere only select.
    ///
    /// Set to `true` for file-explorer-style trees (the demo Tree tab).
    /// Leave `false` for the inspector tree, where clicking selects without
    /// accidentally collapsing an expanded branch.
    pub toggle_on_row_click: bool,
    focused: bool,
    /// Flat-row index of the row under the cursor.
    hovered_row: Option<usize>,
    /// Node index used as the keyboard cursor / shift-click anchor.
    cursor_node: Option<usize>,
    /// Active drag gesture.
    drag: Option<DragState>,
    /// Current computed drop target.
    drop_target: Option<DropPosition>,

    // Scrollbar drag
    hovered_scrollbar: bool,
    dragging_scrollbar: bool,
    sb_drag_start_y: f64,
    sb_drag_start_offset: f64,
}

// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------

impl TreeView {
    pub fn new(font: Arc<Font>) -> Self {
        Self {
            bounds: Rect::default(),
            row_widgets: Vec::new(),
            base: WidgetBase::new(),
            row_metas: Vec::new(),
            nodes: Vec::new(),
            scroll_offset: 0.0,
            content_height: 0.0,
            row_height: 24.0,
            indent_width: 16.0,
            font,
            font_size: 13.0,
            drag_enabled: false,
            toggle_on_row_click: false,
            focused: false,
            hovered_row: None,
            cursor_node: None,
            drag: None,
            drop_target: None,
            hovered_scrollbar: false,
            dragging_scrollbar: false,
            sb_drag_start_y: 0.0,
            sb_drag_start_offset: 0.0,
        }
    }

    pub fn with_row_height(mut self, h: f64) -> Self { self.row_height = h; self }
    pub fn with_indent_width(mut self, w: f64) -> Self { self.indent_width = w; self }
    pub fn with_font_size(mut self, s: f64) -> Self { self.font_size = s; self }
    pub fn with_drag_enabled(mut self) -> Self { self.drag_enabled = true; self }
    pub fn with_toggle_on_row_click(mut self) -> Self { self.toggle_on_row_click = true; self }

    pub fn with_margin(mut self, m: Insets)    -> Self { self.base.margin   = m; self }
    pub fn with_h_anchor(mut self, h: HAnchor) -> Self { self.base.h_anchor = h; self }
    pub fn with_v_anchor(mut self, v: VAnchor) -> Self { self.base.v_anchor = v; self }
    pub fn with_min_size(mut self, s: Size)    -> Self { self.base.min_size = s; self }
    pub fn with_max_size(mut self, s: Size)    -> Self { self.base.max_size = s; self }

    /// Add a root-level node; returns its index.
    pub fn add_root(&mut self, label: impl Into<String>, icon: NodeIcon) -> usize {
        let order = self.nodes.iter().filter(|n| n.parent.is_none()).count() as u32;
        let idx = self.nodes.len();
        self.nodes.push(TreeNode::new(label, icon, None, order));
        idx
    }

    /// Add a child of `parent_idx`; returns its index.
    pub fn add_child(
        &mut self,
        parent_idx: usize,
        label: impl Into<String>,
        icon: NodeIcon,
    ) -> usize {
        let order = self.nodes
            .iter()
            .filter(|n| n.parent == Some(parent_idx))
            .count() as u32;
        let idx = self.nodes.len();
        self.nodes.push(TreeNode::new(label, icon, Some(parent_idx), order));
        idx
    }

    /// Expand the node at `idx`.
    pub fn expand(&mut self, idx: usize) {
        if idx < self.nodes.len() { self.nodes[idx].is_expanded = true; }
    }
}

// ---------------------------------------------------------------------------
// Geometry helpers
// ---------------------------------------------------------------------------

impl TreeView {
    fn scrollbar_x(&self) -> f64 { self.bounds.width - SCROLLBAR_W }

    fn max_scroll(&self) -> f64 {
        (self.content_height - self.bounds.height).max(0.0)
    }

    fn thumb_metrics(&self) -> Option<(f64, f64)> {
        let h = self.bounds.height;
        if self.content_height <= h { return None; }
        let ratio = h / self.content_height;
        let thumb_h = (h * ratio).max(20.0);
        let track_h = h - thumb_h;
        let thumb_y = track_h * (1.0 - self.scroll_offset / self.max_scroll());
        Some((thumb_y, thumb_h))
    }

    /// Is `local_pos` in the scrollbar strip?
    fn in_scrollbar(&self, local_pos: Point) -> bool {
        local_pos.x >= self.scrollbar_x()
    }

    /// Returns the flat-row index (into `row_metas`/`row_widgets`) for the row
    /// under `pos` in TreeView-local coordinates, or `None`.
    fn row_index_at(&self, pos: Point) -> Option<usize> {
        for (i, widget) in self.row_widgets.iter().enumerate() {
            let b = widget.bounds();
            // Clamp to visible content area — rows scrolled off-screen have b.y < 0
            // or b.y + b.height > self.bounds.height; exclude those slivers.
            if pos.y >= b.y.max(0.0)
                && pos.y < (b.y + b.height).min(self.bounds.height)
                && pos.x >= 0.0
                && pos.x < self.bounds.width - SCROLLBAR_W
            {
                return Some(i);
            }
        }
        None
    }
}

// ---------------------------------------------------------------------------
// Selection helpers
// ---------------------------------------------------------------------------

impl TreeView {
    fn select_single(&mut self, node_idx: usize) {
        for n in &mut self.nodes { n.is_selected = false; }
        self.nodes[node_idx].is_selected = true;
        self.cursor_node = Some(node_idx);
    }

    fn toggle_select(&mut self, node_idx: usize) {
        self.nodes[node_idx].is_selected = !self.nodes[node_idx].is_selected;
        self.cursor_node = Some(node_idx);
    }

    fn range_select(&mut self, anchor_node: usize, target_node: usize, rows: &[FlatRow]) {
        let a = rows.iter().position(|r| r.node_idx == anchor_node);
        let b = rows.iter().position(|r| r.node_idx == target_node);
        if let (Some(a), Some(b)) = (a, b) {
            let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
            for n in &mut self.nodes { n.is_selected = false; }
            for r in &rows[lo..=hi] {
                self.nodes[r.node_idx].is_selected = true;
            }
        }
        self.cursor_node = Some(target_node);
    }

    fn move_cursor(&mut self, delta: i32, rows: &[FlatRow]) {
        if rows.is_empty() { return; }
        let cur_flat = self.cursor_node
            .and_then(|ni| rows.iter().position(|r| r.node_idx == ni))
            .unwrap_or(0);
        let new_flat = (cur_flat as i32 + delta)
            .clamp(0, rows.len() as i32 - 1) as usize;
        let ni = rows[new_flat].node_idx;
        self.select_single(ni);
        // Scroll to keep the new row visible.
        self.scroll_to_row(new_flat);
    }

    /// Returns the node index currently under the cursor, or `None`.
    pub fn hovered_node_idx(&self) -> Option<usize> {
        self.hovered_row.and_then(|ri| self.row_metas.get(ri).map(|m| m.node_idx))
    }

    fn scroll_to_row(&mut self, flat_idx: usize) {
        // `row_widgets` bounds reflect the `scroll_offset` from the last `layout()` call.
        // The framework calls `layout()` every frame before rendering, so `scroll_offset`
        // changes here will be reflected before the next mouse hit-test.
        // Y-up coordinates: y_bottom is the lower edge (smaller Y) and y_top is the upper edge (larger Y).
        let y_bottom = self.bounds.height
            - (flat_idx as f64 + 1.0) * self.row_height
            + self.scroll_offset;
        let y_top = y_bottom + self.row_height;
        if y_bottom < 0.0 {
            self.scroll_offset = (self.scroll_offset - y_bottom).min(self.max_scroll());
        } else if y_top > self.bounds.height {
            self.scroll_offset = (self.scroll_offset - (y_top - self.bounds.height)).max(0.0);
        }
    }
}

// ---------------------------------------------------------------------------
// Widget impl
// ---------------------------------------------------------------------------

impl Widget for TreeView {
    fn type_name(&self) -> &'static str { "TreeView" }
    fn bounds(&self) -> Rect { self.bounds }
    fn set_bounds(&mut self, b: Rect) { self.bounds = b; }
    fn children(&self) -> &[Box<dyn Widget>] { &self.row_widgets }
    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> { &mut self.row_widgets }
    fn is_focusable(&self) -> bool { true }

    fn margin(&self)   -> Insets  { self.base.margin }
    fn h_anchor(&self) -> HAnchor { self.base.h_anchor }
    fn v_anchor(&self) -> VAnchor { self.base.v_anchor }
    fn min_size(&self) -> Size    { self.base.min_size }
    fn max_size(&self) -> Size    { self.base.max_size }

    fn hit_test(&self, local_pos: Point) -> bool {
        // Capture all events during drags even if cursor leaves bounds.
        if self.drag.is_some() || self.dragging_scrollbar { return true; }
        let b = self.bounds();
        local_pos.x >= 0.0 && local_pos.x <= b.width
            && local_pos.y >= 0.0 && local_pos.y <= b.height
    }

    fn layout(&mut self, available: Size) -> Size {
        let rows = flatten_visible(&self.nodes);
        self.content_height = rows.len() as f64 * self.row_height;
        self.scroll_offset = self.scroll_offset.clamp(0.0, self.max_scroll());

        let h         = available.height;
        let w         = available.width - SCROLLBAR_W;
        let rh        = self.row_height;
        let ind       = self.indent_width;
        let font_size = self.font_size;

        self.row_widgets.clear();
        self.row_metas.clear();

        for (i, flat) in rows.iter().enumerate() {
            // Skip the node being dragged — its ghost is painted at the cursor instead.
            if self.drag.as_ref().map_or(false, |d| d.live && d.node_idx == flat.node_idx) {
                continue;
            }

            let node = &self.nodes[flat.node_idx];

            // Y position of this row in TreeView-local (Y-up) coordinates.
            let y_bot = h - (i as f64 + 1.0) * rh + self.scroll_offset;

            let mut tree_row = TreeRow::new(
                flat.node_idx,
                flat.depth,
                flat.has_children,
                node.is_expanded,
                node.is_selected,
                self.hovered_row == Some(i),
                self.focused,
                node.icon,
                node.label.clone(),
                Arc::clone(&self.font),
                font_size,
                ind,
                rh,
            );

            tree_row.layout(Size::new(w, rh));
            tree_row.set_bounds(Rect::new(0.0, y_bot, w, rh));

            // toggle_rect in TreeView-local coords = row's y_bot + toggle's local y offset.
            let toggle_rect = if flat.has_children {
                let tlb = tree_row.toggle_local_bounds;
                Some(Rect::new(tlb.x, y_bot + tlb.y, tlb.width, tlb.height))
            } else {
                None
            };

            self.row_metas.push(RowMeta { node_idx: flat.node_idx, toggle_rect });
            self.row_widgets.push(Box::new(tree_row));
        }

        available
    }

    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
        let h = self.bounds.height;
        let w = self.bounds.width;
        let content_w = w - SCROLLBAR_W;
        let v = ctx.visuals().clone();

        // Background — follow the theme's window fill rather than hard-coded white.
        ctx.set_fill_color(v.window_fill);
        ctx.begin_path();
        ctx.rect(0.0, 0.0, w, h);
        ctx.fill();

        // Scrollbar — theme-aware track and thumb.
        let sb_x = self.scrollbar_x();
        if self.content_height > h {
            ctx.set_fill_color(v.scroll_track);
            ctx.begin_path();
            ctx.rect(sb_x, 0.0, SCROLLBAR_W, h);
            ctx.fill();
            if let Some((thumb_y, thumb_h)) = self.thumb_metrics() {
                let thumb_color = if self.dragging_scrollbar {
                    v.scroll_thumb_dragging
                } else if self.hovered_scrollbar {
                    v.scroll_thumb_hovered
                } else {
                    v.scroll_thumb
                };
                ctx.set_fill_color(thumb_color);
                ctx.begin_path();
                ctx.rounded_rect(sb_x + 2.0, thumb_y, SCROLLBAR_W - 4.0, thumb_h, 3.0);
                ctx.fill();
            }
        }

        // Content clip — rows must not bleed into the scrollbar strip.
        // This clip is active during framework recursion into row_widgets (after paint() returns).
        ctx.clip_rect(0.0, 0.0, content_w, h);

        // Drop indicator and ghost (drag feedback)
        let rows = flatten_visible(&self.nodes);
        if let Some(drop_target) = self.drop_target {
            if self.drag.as_ref().map_or(false, |d| d.live) {
                let rh  = self.row_height;
                let off = self.scroll_offset;
                let ind = self.indent_width;
                let ref_node = match drop_target {
                    DropPosition::Before(ni) | DropPosition::After(ni) | DropPosition::AsChild(ni) => ni,
                };
                if let Some(ri) = rows.iter().position(|r| r.node_idx == ref_node) {
                    let y_bot = h - (ri as f64 + 1.0) * rh + off;
                    let indent = rows[ri].depth as f64 * ind + EXPAND_W;
                    match drop_target {
                        DropPosition::Before(_) => paint_drop_line(ctx, indent, y_bot + rh, content_w - indent),
                        DropPosition::After(_)  => paint_drop_line(ctx, indent, y_bot, content_w - indent),
                        DropPosition::AsChild(_) => paint_drop_child_highlight(ctx, y_bot, content_w, rh),
                    }
                }
            }
        }
        if let Some(drag) = &self.drag {
            if drag.live {
                let label = self.nodes[drag.node_idx].label.clone();
                let ic    = icon_color(self.nodes[drag.node_idx].icon);
                let pos   = drag.current_pos;
                let rh    = self.row_height;
                let font  = Arc::clone(&self.font);
                let fs    = self.font_size;
                paint_ghost(ctx, &label, pos, content_w, rh, &font, fs, ic);
            }
        }
    }

    fn on_event(&mut self, event: &Event) -> EventResult {
        // Every consumed event in a tree view mutates some visible state —
        // selection, expansion, scroll offset, hover row, focus ring.  Wrap
        // the dispatch so a `Consumed` result translates to a repaint
        // request.  Events that bubble away as `Ignored` do NOT tick,
        // honouring the "only repaint on real change" contract.
        let result = match event {
            Event::FocusGained => { self.focused = true;  EventResult::Consumed }
            Event::FocusLost   => { self.focused = false; EventResult::Consumed }

            Event::MouseWheel { delta_y, .. } => {
                // Convention: delta_y > 0 = user scrolled DOWN (wants to see content below).
                // Increasing scroll_offset shifts content UP → reveals lower rows. ✓
                self.scroll_offset =
                    (self.scroll_offset + delta_y * 40.0).clamp(0.0, self.max_scroll());
                self.hovered_row = None; // stale after layout rebuild on next frame
                EventResult::Consumed
            }

            Event::MouseMove { pos } => self.handle_mouse_move(*pos),
            Event::MouseDown { pos, button: MouseButton::Left, modifiers } => {
                self.handle_mouse_down(*pos, *modifiers)
            }
            Event::MouseUp { button: MouseButton::Left, pos, .. } => {
                self.handle_mouse_up(*pos)
            }
            Event::KeyDown { key, modifiers } => self.handle_key_down(key, *modifiers),
            _ => EventResult::Ignored,
        };
        if result == EventResult::Consumed {
            crate::animation::request_tick();
        }
        result
    }
}

// ---------------------------------------------------------------------------
// Mouse event handlers
// ---------------------------------------------------------------------------

impl TreeView {
    fn handle_mouse_move(&mut self, pos: Point) -> EventResult {
        self.hovered_scrollbar = self.in_scrollbar(pos);

        if self.dragging_scrollbar {
            if let Some((_, thumb_h)) = self.thumb_metrics() {
                let h = self.bounds.height;
                let track_h = (h - thumb_h).max(1.0);
                let delta_y = self.sb_drag_start_y - pos.y;
                let spp = self.max_scroll() / track_h;
                self.scroll_offset =
                    (self.sb_drag_start_offset + delta_y * spp).clamp(0.0, self.max_scroll());
            }
            return EventResult::Consumed;
        }

        if let Some(drag) = &mut self.drag {
            let dx = pos.x - drag.current_pos.x;
            let dy = pos.y - drag.current_pos.y;
            drag.current_pos = pos;
            if !drag.live && (dx * dx + dy * dy).sqrt() > DRAG_THRESHOLD {
                drag.live = true;
            }
            if drag.live {
                let node_idx = drag.node_idx;
                let rows = flatten_visible(&self.nodes);
                self.drop_target = compute_drop_target(
                    pos, &rows, &self.nodes,
                    self.bounds.height, self.row_height,
                    self.scroll_offset, self.drag.as_ref().unwrap(),
                );
                let _ = node_idx;
            }
            return EventResult::Consumed;
        }

        self.hovered_row = self.row_index_at(pos);
        EventResult::Ignored
    }

    fn handle_mouse_down(&mut self, pos: Point, mods: Modifiers) -> EventResult {
        if self.in_scrollbar(pos) {
            self.dragging_scrollbar = true;
            self.sb_drag_start_y = pos.y;
            self.sb_drag_start_offset = self.scroll_offset;
            return EventResult::Consumed;
        }

        let Some(flat_i) = self.row_index_at(pos) else {
            return EventResult::Ignored;
        };
        let meta     = &self.row_metas[flat_i];
        let node_idx = meta.node_idx;

        // Expand/collapse: any click on a row with children toggles it when
        // `toggle_on_row_click` is enabled (file-explorer style).  Otherwise
        // only the expand-toggle arrow triggers expansion so that clicking a
        // row in the inspector tree selects it without accidentally collapsing
        // a branch the user was browsing.
        if self.toggle_on_row_click {
            if meta.toggle_rect.is_some() {
                self.nodes[node_idx].is_expanded = !self.nodes[node_idx].is_expanded;
            }
        } else if let Some(tr) = meta.toggle_rect {
            if pos.x >= tr.x && pos.x < tr.x + tr.width
                && pos.y >= tr.y && pos.y < tr.y + tr.height
            {
                self.nodes[node_idx].is_expanded = !self.nodes[node_idx].is_expanded;
            }
        }

        // Selection
        if mods.ctrl {
            self.toggle_select(node_idx);
        } else if mods.shift {
            if let Some(a) = self.cursor_node {
                let rows2 = flatten_visible(&self.nodes);
                self.range_select(a, node_idx, &rows2);
            } else {
                self.select_single(node_idx);
            }
        } else {
            self.select_single(node_idx);
            if self.drag_enabled {
                let y_bot = self.row_widgets[flat_i].bounds().y;
                self.drag = Some(DragState {
                    node_idx,
                    _cursor_row_offset: pos.y - y_bot,
                    current_pos: pos,
                    live: false,
                });
            }
        }

        EventResult::Consumed
    }

    fn handle_mouse_up(&mut self, pos: Point) -> EventResult {
        // Scrollbar drag end
        if self.dragging_scrollbar {
            self.dragging_scrollbar = false;
            return EventResult::Consumed;
        }

        // Node drag end
        if let Some(drag) = self.drag.take() {
            if drag.live {
                if let Some(target) = self.drop_target.take() {
                    apply_drop(&mut self.nodes, drag.node_idx, target);
                }
            } else {
                // Was a click, not a drag — finalize single-select.
                self.select_single(drag.node_idx);
            }
            self.drop_target = None;
            return EventResult::Consumed;
        }

        let _ = pos;
        EventResult::Ignored
    }

    fn handle_key_down(&mut self, key: &Key, mods: Modifiers) -> EventResult {
        let rows = flatten_visible(&self.nodes);
        match key {
            Key::ArrowDown => { self.move_cursor(1, &rows);  EventResult::Consumed }
            Key::ArrowUp   => { self.move_cursor(-1, &rows); EventResult::Consumed }
            Key::ArrowRight => {
                if let Some(ni) = self.cursor_node {
                    if !self.nodes[ni].is_expanded
                        && rows.iter().any(|r| r.node_idx == ni && r.has_children)
                    {
                        self.nodes[ni].is_expanded = true;
                    } else {
                        // Move to first child
                        if rows.iter().any(|r| r.node_idx == ni) {
                            self.move_cursor(1, &rows);
                        }
                    }
                }
                EventResult::Consumed
            }
            Key::ArrowLeft => {
                if let Some(ni) = self.cursor_node {
                    if self.nodes[ni].is_expanded {
                        self.nodes[ni].is_expanded = false;
                    } else if let Some(parent_idx) = self.nodes[ni].parent {
                        self.select_single(parent_idx);
                        if let Some(fi) = rows.iter().position(|r| r.node_idx == parent_idx) {
                            self.scroll_to_row(fi);
                        }
                    }
                }
                EventResult::Consumed
            }
            Key::Char(' ') | Key::Enter => {
                if let Some(ni) = self.cursor_node {
                    if rows.iter().any(|r| r.node_idx == ni && r.has_children) {
                        self.nodes[ni].is_expanded = !self.nodes[ni].is_expanded;
                    }
                }
                EventResult::Consumed
            }
            Key::Tab => EventResult::Ignored, // let App handle focus advancement
            _ => {
                let _ = mods;
                EventResult::Ignored
            }
        }
    }
}