minui 0.4.2

A minimalist Rust framework for TUIs and terminal games.
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
//! Scroll Demo
//!
//! Demonstrates MinUI's unified scrolling architecture:
//! - `ScrollBox` provides a scrollable viewport backed by a shared `ScrollState`
//! - `ScrollBar` binds to the same `ScrollState` for thumb dragging + arrow buttons
//! - Interaction routing via `InteractionCache` + `WidgetArea`
//! - Scrollbar auto-hide UX via `AutoHide`
//!
//! Controls:
//! - Mouse wheel: vertical scroll (only when over a registered scroll target / or focused)
//! - Horizontal wheel (if your terminal sends it): horizontal scroll (same routing policy)
//! - Drag scrollbar thumbs (with app-level mouse capture)
//! - Click scrollbar arrows
//! - Arrow keys: scroll (Up/Down/Left/Right)
//! - Press 'q' to quit
//!
//! Notes:
//! - `ScrollBox` is sized each frame based on terminal size.
//! - Content is built each frame (no cloning required).
//! - Scrollbars are auto-hidden unless:
//!   - you recently scrolled, or
//!   - the mouse is near the scrollbar area, or
//!   - you are actively dragging the thumb.

use minui::MouseButton;
use minui::prelude::*;
use minui::ui::{AutoHide, InteractionCache};
use minui::widgets::controls::scrollbar::{ScrollBar, ScrollBarOptions, ScrollUnit};
use minui::widgets::scroll::{ScrollOrientation, ScrollSize, ScrollState};
use minui::widgets::{WidgetArea, WindowView};

use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;

const ID_SCROLLBOX: usize = 1;
const ID_SCROLLBOX_VIEWPORT: usize = 4;

// Scrollbar composite ids (root + thumb/track + arrows)
const ID_VSCROLL_ROOT: usize = 2;
const ID_VSCROLL_THUMB: usize = 5;
const ID_VSCROLL_ARROW_START: usize = 6;
const ID_VSCROLL_ARROW_END: usize = 7;

const ID_HSCROLL_ROOT: usize = 3;
const ID_HSCROLL_THUMB: usize = 8;
const ID_HSCROLL_ARROW_START: usize = 9;
const ID_HSCROLL_ARROW_END: usize = 10;

struct ScrollDemoState {
    ui: InteractionCache,
    scroll: Rc<RefCell<ScrollState>>,
    vbar: ScrollBar,
    hbar: ScrollBar,

    // App-level mouse capture for dragging.
    // Once captured, we keep routing drag/release events to the captured widget id even if the
    // mouse leaves the original area.
    active_drag_id: Option<usize>,

    // Auto-hide behavior for scrollbars.
    // NOTE: This is app-level policy (Phase 1), not owned by the widgets.
    autohide: AutoHide,
}

fn main() -> minui::Result<()> {
    // Shared scroll model (content size + viewport size + offsets).
    // Seed with non-zero sizes so scrollbar math is sane before first draw.
    let scroll = Rc::new(RefCell::new(ScrollState::new(
        ScrollSize::new(1, 1),
        ScrollSize::new(1, 1),
    )));

    // Initial scrollbars; sizes are refreshed every draw frame.
    let vbar = ScrollBar::new(
        1,
        1,
        Rc::clone(&scroll),
        ScrollBarOptions {
            orientation: ScrollOrientation::Vertical,
            show_arrows: true,
            scroll_step: Some(1),
            ..ScrollBarOptions::default()
        },
    );

    let hbar = ScrollBar::new(
        1,
        1,
        Rc::clone(&scroll),
        ScrollBarOptions {
            orientation: ScrollOrientation::Horizontal,
            show_arrows: true,
            scroll_step: Some(2),
            ..ScrollBarOptions::default()
        },
    );

    let initial = ScrollDemoState {
        ui: InteractionCache::new(),
        scroll,
        vbar,
        hbar,
        active_drag_id: None,
        autohide: AutoHide::new(Duration::from_millis(900), 2),
    };

    let mut app = App::new(initial)?;

    app.run(
        // ============================
        // Update: route events
        // ============================
        |state, event| {
            // Observe mouse position for proximity-based scrollbar reveal.
            state.ui.observe_event(&event);

            // Quit (prefer modifier-aware events, with legacy fallback)
            if let Event::KeyWithModifiers(k) = event {
                if matches!(k.key, KeyKind::Char('q')) {
                    return false;
                }
            }
            if matches!(event, Event::Character('q')) {
                return false;
            }

            // Mouse capture:
            // - On left-click, capture the *draggable* region under cursor (thumb/track).
            // - During drag/release, keep routing to the captured id even if the cursor leaves.
            match event {
                Event::MouseClick {
                    x,
                    y,
                    button: MouseButton::Left,
                } => {
                    state.active_drag_id = None;

                    if let Some(hit) = state.ui.hit_test(x, y) {
                        if hit.flags.draggable {
                            state.active_drag_id = Some(hit.id);
                        } else if hit.flags.focusable {
                            // Click-to-focus: focus only focusable regions (e.g. scrollbox frame/panel).
                            state.ui.focus(hit.id);
                        }
                    }
                }
                Event::MouseRelease {
                    button: MouseButton::Left,
                    ..
                } => {
                    // Release always clears capture (but we still route the release event below).
                    // This mirrors common UI "mouse capture" behavior.
                    // NOTE: we clear after routing by storing the old value.
                }
                _ => {}
            }

            // Mouse wheel scrolling:
            // Route ONLY to the scroll target under cursor (preferred) or the focused scroll target.
            //
            // Policy:
            // - If the mouse is over a registered `scrollable` region, scroll.
            // - Otherwise, if the currently focused id corresponds to a `scrollable` region this frame,
            //   scroll that.
            // - Otherwise: ignore wheel input.
            //
            // Also mark "activity" so scrollbars reveal for a short time.
            match event {
                Event::MouseScroll { delta } => {
                    let mut should_scroll = false;

                    if let Some((mx, my)) = state.ui.last_mouse_pos() {
                        if let Some(hit) = state.ui.hit_test(mx, my) {
                            should_scroll = hit.flags.scrollable;
                        }
                    } else if let Some(focused) = state.ui.focused() {
                        if let Some(entry) = state.ui.get(focused) {
                            should_scroll = entry.flags.scrollable;
                        }
                    }

                    if should_scroll {
                        state.autohide.mark_activity();

                        // Convention: delta > 0 scrolls up, delta < 0 scrolls down.
                        // We invert to translate "scroll down" into positive offset movement.
                        let dy: i16 = -(delta as i16);
                        state
                            .scroll
                            .borrow_mut()
                            .scroll_by(ScrollOrientation::Vertical, dy);
                    }
                }
                Event::MouseScrollHorizontal { delta } => {
                    let mut should_scroll = false;

                    if let Some((mx, my)) = state.ui.last_mouse_pos() {
                        if let Some(hit) = state.ui.hit_test(mx, my) {
                            should_scroll = hit.flags.scrollable;
                        }
                    } else if let Some(focused) = state.ui.focused() {
                        if let Some(entry) = state.ui.get(focused) {
                            should_scroll = entry.flags.scrollable;
                        }
                    }

                    if should_scroll {
                        state.autohide.mark_activity();

                        let dx: i16 = -(delta as i16);
                        state
                            .scroll
                            .borrow_mut()
                            .scroll_by(ScrollOrientation::Horizontal, dx);
                    }
                }
                _ => {}
            }

            // Keyboard scrolling (prefer modifier-aware events, with legacy fallback).
            match event {
                Event::KeyWithModifiers(k) => match k.key {
                    KeyKind::Up => state
                        .vbar
                        .scroll_by_fraction(-1.0 / 5.0, ScrollUnit::Viewport),
                    KeyKind::Down => state
                        .vbar
                        .scroll_by_fraction(1.0 / 5.0, ScrollUnit::Viewport),
                    KeyKind::Left => state
                        .hbar
                        .scroll_by_fraction(-1.0 / 5.0, ScrollUnit::Viewport),
                    KeyKind::Right => state
                        .hbar
                        .scroll_by_fraction(1.0 / 5.0, ScrollUnit::Viewport),
                    _ => {}
                },

                // Legacy fallback.
                Event::KeyUp => state
                    .vbar
                    .scroll_by_fraction(-1.0 / 5.0, ScrollUnit::Viewport),
                Event::KeyDown => state
                    .vbar
                    .scroll_by_fraction(1.0 / 5.0, ScrollUnit::Viewport),
                Event::KeyLeft => state
                    .hbar
                    .scroll_by_fraction(-1.0 / 5.0, ScrollUnit::Viewport),
                Event::KeyRight => state
                    .hbar
                    .scroll_by_fraction(1.0 / 5.0, ScrollUnit::Viewport),

                _ => {}
            }

            // Route pointer events into scrollbars (click/drag/arrows).
            //
            // IMPORTANT:
            // - Only route if the relevant areas were registered (i.e. visible).
            // - If a drag is captured, keep routing drag/release to the captured scrollbar *owner*
            //   even if the cursor leaves the original region.
            //
            // This uses a simple id→owner mapping (still immediate-mode; no retained tree).
            let captured = state.active_drag_id;

            // Helper: map an interaction id to the owning scrollbar.
            let owner_for = |id: usize| -> Option<&'static str> {
                match id {
                    ID_VSCROLL_ROOT
                    | ID_VSCROLL_THUMB
                    | ID_VSCROLL_ARROW_START
                    | ID_VSCROLL_ARROW_END => Some("v"),
                    ID_HSCROLL_ROOT
                    | ID_HSCROLL_THUMB
                    | ID_HSCROLL_ARROW_START
                    | ID_HSCROLL_ARROW_END => Some("h"),
                    _ => None,
                }
            };

            // Determine which owners should receive this event.
            let mut route_vbar = false;
            let mut route_hbar = false;

            if let Some(id) = captured {
                match owner_for(id) {
                    Some("v") => route_vbar = true,
                    Some("h") => route_hbar = true,
                    _ => {}
                }
            } else if let Some((mx, my)) = state.ui.last_mouse_pos() {
                if let Some(hit_id) = state.ui.hit_test_id(mx, my) {
                    match owner_for(hit_id) {
                        Some("v") => route_vbar = true,
                        Some("h") => route_hbar = true,
                        _ => {}
                    }
                }
            }

            if route_vbar {
                if let Some(entry) = state.ui.get(ID_VSCROLL_ROOT) {
                    let _ = state.vbar.handle_event(&event, entry.area);
                }
            }
            if route_hbar {
                if let Some(entry) = state.ui.get(ID_HSCROLL_ROOT) {
                    let _ = state.hbar.handle_event(&event, entry.area);
                }
            }

            // Clear capture after routing a left-button release.
            if matches!(
                event,
                Event::MouseRelease {
                    button: MouseButton::Left,
                    ..
                }
            ) {
                state.active_drag_id = None;
            }

            true
        },
        // ============================
        // Draw: register areas + draw
        // ============================
        |state, window| {
            state.ui.begin_frame();

            let (term_w, term_h) = window.get_size();

            // Layout constants
            let margin: u16 = 1;
            let header_h: u16 = 1;

            // Scrollbar sizes (vbar on the right, hbar on bottom)
            let vbar_w: u16 = 1;
            let hbar_h: u16 = 1;

            // ScrollBox styling affects its *outer* size vs the *inner* content viewport.
            // Because the ScrollBox draws a border + padding, we must reserve extra space so
            // the right/bottom borders don't get overwritten by scrollbars.
            let box_border: u16 = 1; // single-line border thickness
            let box_padding: u16 = 1; // we set ContainerPadding::uniform(1) below

            // Compute a safe outer rect for the ScrollBox (what you pass to with_position_and_size)
            // leaving room for:
            // - header line
            // - scrollbars (drawn OUTSIDE the ScrollBox frame)
            //
            // IMPORTANT:
            // - The ScrollBox outer rect must be fully within the terminal bounds.
            // - The scrollbars are then placed at `outer_x + outer_w` (right) and `outer_y + outer_h` (bottom),
            //   so we must reserve 1 extra column/row for them as well.
            let outer_x = margin;
            let outer_y = margin + header_h;

            // Total insets that reduce the usable inner content area.
            let inner_inset_x = box_border + box_padding;
            let inner_inset_y = box_border + box_padding;

            // Available space inside terminal margins for the ScrollBox outer rect.
            // We reserve the scrollbar column/row OUTSIDE the ScrollBox.
            let max_outer_w = term_w.saturating_sub(margin * 2).saturating_sub(vbar_w);
            let max_outer_h = term_h
                .saturating_sub(margin * 2)
                .saturating_sub(header_h)
                .saturating_sub(hbar_h);

            // Clamp outer size to available space. Do NOT force a minimum that can exceed terminal bounds.
            // If the terminal is too small, we'll end up with a very small box (and the scrollbars may be skipped).
            let outer_w = max_outer_w;
            let outer_h = max_outer_h;

            // Inner viewport (content area) starts after border+padding.
            // NOTE: these are currently unused in this example, but kept for clarity.
            let viewport_x = outer_x + inner_inset_x;
            let viewport_y = outer_y + inner_inset_y;
            let viewport_w = outer_w.saturating_sub(inner_inset_x * 2);
            let viewport_h = outer_h.saturating_sub(inner_inset_y * 2);

            let _ = (viewport_x, viewport_y, viewport_w, viewport_h);

            // Header / help line
            window.write_str(
                margin,
                margin,
                "Scroll demo: wheel/drag scrollbars • arrows/keys work • press 'q' to quit",
            )?;

            // Build content each frame (no cloning needed).
            // Use a row gap to exercise gap-aware content measurement in ScrollBox.
            let mut content = Container::vertical().with_row_gap(Gap::Pixels(1));

            // Lots of lines (taller than viewport).
            for i in 0..150u16 {
                content = content.add_child(
                    Label::new(format!(
                        "Line {:03} | The quick brown fox jumps over the lazy dog. {}",
                        i,
                        if i % 5 == 0 { "[drag the thumb]" } else { "" }
                    ))
                    .with_text_color(Color::White),
                );
            }

            // ScrollBox bound to shared state and sized to viewport.
            let scrollbox = ScrollBox::both()
                .with_state(Rc::clone(&state.scroll))
                // IMPORTANT: pass the OUTER rect (includes border/padding), not the inner viewport.
                .with_position_and_size(outer_x, outer_y, outer_w, outer_h)
                .with_border()
                .with_border_chars(BorderChars::single_line())
                .with_title("Scrollable content")
                .with_title_alignment(TitleAlignment::Left)
                .with_padding(minui::widgets::ContainerPadding::uniform(1))
                .with_row_gap(Gap::Pixels(1))
                .add_child(content);

            // Register scrollbox interaction regions:
            // - outer frame as focusable (panel/split-friendly)
            // - inner viewport as scrollable (wheel routing)
            let outer_area = WidgetArea::new(outer_x, outer_y, outer_w, outer_h);
            scrollbox.register_with_ids(
                &mut state.ui,
                outer_area,
                ID_SCROLLBOX,
                ID_SCROLLBOX_VIEWPORT,
            );

            // Draw scrollbox (updates ScrollState sizes + applies offsets via WindowView).
            scrollbox.draw(window)?;

            // Vertical scrollbar area (right side)
            // Place it just outside the ScrollBox's outer border so it doesn't overwrite the frame.
            // This must still be inside the terminal bounds (x < term_w).
            let vbar_x = outer_x + outer_w;
            let vbar_y = outer_y;
            let vbar_h = outer_h;

            // If there isn't room for the scrollbar column (e.g. tiny terminals), just skip drawing it.
            if vbar_x >= term_w {
                return Ok(());
            }

            // Resize + sync existing scrollbar instead of recreating it every frame.
            // Recreating would reset drag state, making thumb dragging feel broken.
            state.vbar.set_size(1, vbar_h);
            state.vbar.set_show_arrows(true);
            state.vbar.set_scroll_step(Some(1));
            state.vbar.sync_from_state_and_resize_parts();

            let v_area = WidgetArea::new(vbar_x, vbar_y, 1, vbar_h);

            // Auto-hide policy: show if recently scrolled, mouse is near, or currently dragging.
            // Reveal policy:
            // - show when recently scrolled
            // - show when mouse is near the scrollbar area
            // - show when mouse is near the scrollbox RIGHT edge strip (even if the bar itself is hidden)
            // - show while dragging
            let mouse_pos = state.ui.last_mouse_pos();

            // Only consider proximity to a thin strip along the scrollbox's right edge.
            // This prevents the scrollbars from staying visible just because the cursor is somewhere
            // inside/near the scrollbox.
            let near_scrollbox_right_edge = if let Some((mx, my)) = mouse_pos {
                // A 1-column strip at the right edge of the scrollbox.
                let edge_x = outer_x + outer_w.saturating_sub(1);
                let edge_strip = WidgetArea::new(edge_x, outer_y, 1, outer_h);
                state.autohide.is_point_near_area(mx, my, edge_strip)
            } else {
                false
            };

            let show_vbar = state
                .autohide
                .should_show(v_area, mouse_pos, state.vbar.is_dragging())
                || near_scrollbox_right_edge;

            if show_vbar {
                // Register sub-areas so routing can distinguish thumb vs arrows.
                // Root is scrollable (hover target), thumb/track is draggable, arrows are focusable.
                state.vbar.register_with_ids(
                    &mut state.ui,
                    v_area,
                    ID_VSCROLL_ROOT,
                    ID_VSCROLL_THUMB,
                    Some(ID_VSCROLL_ARROW_START),
                    Some(ID_VSCROLL_ARROW_END),
                );

                {
                    let mut view = WindowView {
                        window,
                        x_offset: vbar_x,
                        y_offset: vbar_y,
                        scroll_x: 0,
                        scroll_y: 0,
                        width: 1,
                        height: vbar_h,
                    };
                    state.vbar.draw(&mut view)?;
                }
            }

            // Horizontal scrollbar area (bottom)
            // Place it just outside the ScrollBox's outer border so it doesn't overwrite the frame.
            // This must still be inside the terminal bounds (y < term_h).
            let hbar_x = outer_x;
            let hbar_y = outer_y + outer_h;
            let hbar_w = outer_w;

            // If there isn't room for the scrollbar row (e.g. tiny terminals), just skip drawing it.
            if hbar_y >= term_h {
                return Ok(());
            }

            // Resize + sync existing scrollbar instead of recreating it every frame.
            // Recreating would reset drag state, making thumb dragging feel broken.
            state.hbar.set_size(hbar_w, 1);
            state.hbar.set_show_arrows(true);
            state.hbar.set_scroll_step(Some(2));
            state.hbar.sync_from_state_and_resize_parts();

            let h_area = WidgetArea::new(hbar_x, hbar_y, hbar_w, 1);

            // Auto-hide policy: show if recently scrolled, mouse is near, or currently dragging.
            // Reveal policy:
            // - show when recently scrolled
            // - show when mouse is near the scrollbar area
            // - show when mouse is near the scrollbox BOTTOM edge strip (even if the bar itself is hidden)
            // - show while dragging
            let mouse_pos = state.ui.last_mouse_pos();

            // Only consider proximity to a thin strip along the scrollbox's bottom edge.
            // This prevents the scrollbars from staying visible just because the cursor is somewhere
            // inside/near the scrollbox.
            let near_scrollbox_bottom_edge = if let Some((mx, my)) = mouse_pos {
                // A 1-row strip at the bottom edge of the scrollbox.
                let edge_y = outer_y + outer_h.saturating_sub(1);
                let edge_strip = WidgetArea::new(outer_x, edge_y, outer_w, 1);
                state.autohide.is_point_near_area(mx, my, edge_strip)
            } else {
                false
            };

            let show_hbar = state
                .autohide
                .should_show(h_area, mouse_pos, state.hbar.is_dragging())
                || near_scrollbox_bottom_edge;

            if show_hbar {
                // Register sub-areas so routing can distinguish thumb vs arrows.
                // Root is scrollable (hover target), thumb/track is draggable, arrows are focusable.
                state.hbar.register_with_ids(
                    &mut state.ui,
                    h_area,
                    ID_HSCROLL_ROOT,
                    ID_HSCROLL_THUMB,
                    Some(ID_HSCROLL_ARROW_START),
                    Some(ID_HSCROLL_ARROW_END),
                );

                {
                    let mut view = WindowView {
                        window,
                        x_offset: hbar_x,
                        y_offset: hbar_y,
                        scroll_x: 0,
                        scroll_y: 0,
                        width: hbar_w,
                        height: 1,
                    };
                    state.hbar.draw(&mut view)?;
                }
            }

            window.end_frame()?;
            Ok(())
        },
    )?;

    Ok(())
}