revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Tooltip widget for displaying contextual information
//!
//! Provides hover-style tooltips and help text displays.

use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::utils::border::BorderChars;
use crate::widget::theme::{DARK_BG, EDITOR_BG};
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Tooltip position relative to anchor
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TooltipPosition {
    /// Above the anchor
    #[default]
    Top,
    /// Below the anchor
    Bottom,
    /// To the left of anchor
    Left,
    /// To the right of anchor
    Right,
    /// Auto-detect best position
    Auto,
}

/// Tooltip arrow style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TooltipArrow {
    /// No arrow
    #[default]
    None,
    /// Simple arrow
    Simple,
    /// Unicode arrow
    Unicode,
}

impl TooltipArrow {
    fn chars(&self, position: TooltipPosition) -> (char, char) {
        match (self, position) {
            (TooltipArrow::None, _) => (' ', ' '),
            (TooltipArrow::Simple, TooltipPosition::Top) => ('v', 'v'),
            (TooltipArrow::Simple, TooltipPosition::Bottom) => ('^', '^'),
            (TooltipArrow::Simple, TooltipPosition::Left) => ('>', '>'),
            (TooltipArrow::Simple, TooltipPosition::Right) => ('<', '<'),
            (TooltipArrow::Simple, TooltipPosition::Auto) => ('v', 'v'),
            (TooltipArrow::Unicode, TooltipPosition::Top) => ('', ''),
            (TooltipArrow::Unicode, TooltipPosition::Bottom) => ('', ''),
            (TooltipArrow::Unicode, TooltipPosition::Left) => ('', ''),
            (TooltipArrow::Unicode, TooltipPosition::Right) => ('', ''),
            (TooltipArrow::Unicode, TooltipPosition::Auto) => ('', ''),
        }
    }
}

/// Tooltip style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TooltipStyle {
    /// Simple text
    #[default]
    Plain,
    /// With border
    Bordered,
    /// Rounded corners
    Rounded,
    /// Info style (cyan)
    Info,
    /// Warning style (yellow)
    Warning,
    /// Error style (red)
    Error,
    /// Success style (green)
    Success,
}

impl TooltipStyle {
    fn colors(&self) -> (Color, Color) {
        match self {
            TooltipStyle::Plain => (Color::WHITE, DARK_BG),
            TooltipStyle::Bordered => (Color::WHITE, EDITOR_BG),
            TooltipStyle::Rounded => (Color::WHITE, EDITOR_BG),
            TooltipStyle::Info => (Color::WHITE, Color::rgb(30, 80, 100)),
            TooltipStyle::Warning => (Color::BLACK, Color::rgb(180, 150, 0)),
            TooltipStyle::Error => (Color::WHITE, Color::rgb(150, 30, 30)),
            TooltipStyle::Success => (Color::WHITE, Color::rgb(30, 100, 50)),
        }
    }

    fn border_chars(&self) -> Option<BorderChars> {
        match self {
            TooltipStyle::Plain => None,
            TooltipStyle::Bordered
            | TooltipStyle::Info
            | TooltipStyle::Warning
            | TooltipStyle::Error
            | TooltipStyle::Success => Some(BorderChars::SINGLE),
            TooltipStyle::Rounded => Some(BorderChars::ROUNDED),
        }
    }
}

/// Tooltip widget
pub struct Tooltip {
    /// Tooltip text (supports multiple lines)
    text: String,
    /// Position relative to anchor
    position: TooltipPosition,
    /// Anchor point (x, y)
    anchor: (u16, u16),
    /// Visual style
    style: TooltipStyle,
    /// Arrow style
    arrow: TooltipArrow,
    /// Max width (0 = auto)
    max_width: u16,
    /// Visible
    visible: bool,
    /// Custom colors
    fg: Option<Color>,
    bg: Option<Color>,
    /// Title (optional)
    title: Option<String>,
    /// Show delay in frames (for animated appearance)
    delay: u16,
    /// Current delay counter
    delay_counter: u16,
    /// Widget properties
    props: WidgetProps,
}

impl Tooltip {
    /// Create a new tooltip
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            position: TooltipPosition::Top,
            anchor: (0, 0),
            style: TooltipStyle::Bordered,
            arrow: TooltipArrow::Unicode,
            max_width: 40,
            visible: true,
            fg: None,
            bg: None,
            title: None,
            delay: 0,
            delay_counter: 0,
            props: WidgetProps::new(),
        }
    }

    /// Set tooltip text
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = text.into();
        self
    }

    /// Set position
    pub fn position(mut self, position: TooltipPosition) -> Self {
        self.position = position;
        self
    }

    /// Set anchor point
    pub fn anchor(mut self, x: u16, y: u16) -> Self {
        self.anchor = (x, y);
        self
    }

    /// Set style
    pub fn style(mut self, style: TooltipStyle) -> Self {
        self.style = style;
        self
    }

    /// Set arrow style
    pub fn arrow(mut self, arrow: TooltipArrow) -> Self {
        self.arrow = arrow;
        self
    }

    /// Set max width
    pub fn max_width(mut self, width: u16) -> Self {
        self.max_width = width;
        self
    }

    /// Set visibility
    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Set foreground color
    pub fn fg(mut self, color: Color) -> Self {
        self.fg = Some(color);
        self
    }

    /// Set background color
    pub fn bg(mut self, color: Color) -> Self {
        self.bg = Some(color);
        self
    }

    /// Set title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set show delay
    pub fn delay(mut self, frames: u16) -> Self {
        self.delay = frames;
        self
    }

    // Preset styles

    /// Create info tooltip
    pub fn info(text: impl Into<String>) -> Self {
        Self::new(text).style(TooltipStyle::Info)
    }

    /// Create warning tooltip
    pub fn warning(text: impl Into<String>) -> Self {
        Self::new(text).style(TooltipStyle::Warning)
    }

    /// Create error tooltip
    pub fn error(text: impl Into<String>) -> Self {
        Self::new(text).style(TooltipStyle::Error)
    }

    /// Create success tooltip
    pub fn success(text: impl Into<String>) -> Self {
        Self::new(text).style(TooltipStyle::Success)
    }

    /// Show the tooltip
    pub fn show(&mut self) {
        self.visible = true;
        self.delay_counter = 0;
    }

    /// Hide the tooltip
    pub fn hide(&mut self) {
        self.visible = false;
    }

    /// Toggle visibility
    pub fn toggle(&mut self) {
        self.visible = !self.visible;
    }

    /// Check if visible
    pub fn is_visible(&self) -> bool {
        self.visible && self.delay_counter >= self.delay
    }

    /// Tick for delay animation
    pub fn tick(&mut self) {
        if self.delay_counter < self.delay {
            self.delay_counter += 1;
        }
    }

    /// Set anchor position
    pub fn set_anchor(&mut self, x: u16, y: u16) {
        self.anchor = (x, y);
    }

    // Getters for testing
    #[doc(hidden)]
    pub fn get_text(&self) -> &str {
        &self.text
    }

    #[doc(hidden)]
    pub fn get_position(&self) -> TooltipPosition {
        self.position
    }

    #[doc(hidden)]
    pub fn get_anchor(&self) -> (u16, u16) {
        self.anchor
    }

    #[doc(hidden)]
    pub fn get_style(&self) -> TooltipStyle {
        self.style
    }

    #[doc(hidden)]
    pub fn get_arrow(&self) -> TooltipArrow {
        self.arrow
    }

    #[doc(hidden)]
    pub fn get_max_width(&self) -> u16 {
        self.max_width
    }

    #[doc(hidden)]
    pub fn get_delay(&self) -> u16 {
        self.delay
    }

    #[doc(hidden)]
    pub fn get_delay_counter(&self) -> u16 {
        self.delay_counter
    }

    #[doc(hidden)]
    pub fn get_title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Word wrap text
    fn wrap_text(&self) -> Vec<String> {
        let max_width = if self.max_width > 0 {
            self.max_width as usize
        } else {
            40
        };

        let mut lines = Vec::new();
        for line in self.text.lines() {
            if line.len() <= max_width {
                lines.push(line.to_string());
            } else {
                // Simple word wrap
                let mut current_line = String::new();
                for word in line.split_whitespace() {
                    if current_line.is_empty() {
                        current_line = word.to_string();
                    } else if current_line.len() + 1 + word.len() <= max_width {
                        current_line.push(' ');
                        current_line.push_str(word);
                    } else {
                        lines.push(current_line);
                        current_line = word.to_string();
                    }
                }
                if !current_line.is_empty() {
                    lines.push(current_line);
                }
            }
        }

        if lines.is_empty() {
            lines.push(String::new());
        }

        lines
    }

    /// Calculate tooltip dimensions
    fn calculate_dimensions(&self) -> (u16, u16) {
        let lines = self.wrap_text();
        let has_border = self.style.border_chars().is_some();
        let has_title = self.title.is_some();

        let content_width = lines
            .iter()
            .map(|l| crate::utils::display_width(l))
            .max()
            .unwrap_or(0) as u16;
        let title_width = self
            .title
            .as_ref()
            .map(|t| crate::utils::display_width(t) as u16 + 2)
            .unwrap_or(0);
        let text_width = content_width.max(title_width);

        let width = text_width + if has_border { 4 } else { 2 }; // padding + border
        let height = lines.len() as u16
            + if has_border { 2 } else { 0 }
            + if has_title && has_border { 1 } else { 0 };

        (width, height)
    }

    /// Calculate position based on anchor and available space
    fn calculate_position(&self, area_width: u16, area_height: u16) -> (u16, u16, TooltipPosition) {
        let (tooltip_w, tooltip_h) = self.calculate_dimensions();
        let (anchor_x, anchor_y) = self.anchor;
        let arrow_offset: u16 = if matches!(self.arrow, TooltipArrow::None) {
            0
        } else {
            1
        };

        let (x, y, position) = match self.position {
            TooltipPosition::Auto => {
                // Auto-detect best position based on available space
                let space_above = anchor_y;
                let space_below = area_height.saturating_sub(anchor_y + 1);
                let space_left = anchor_x;
                let space_right = area_width.saturating_sub(anchor_x + 1);

                let pos = if space_above >= tooltip_h + arrow_offset {
                    TooltipPosition::Top
                } else if space_below >= tooltip_h + arrow_offset {
                    TooltipPosition::Bottom
                } else if space_right >= tooltip_w + arrow_offset {
                    TooltipPosition::Right
                } else if space_left >= tooltip_w + arrow_offset {
                    TooltipPosition::Left
                } else {
                    TooltipPosition::Top // Default fallback
                };

                // Calculate position for the auto-detected position
                // Note: pos is guaranteed to be Top/Bottom/Left/Right (never Auto)
                // because Auto was resolved to a concrete position above
                let (x, y) = match pos {
                    TooltipPosition::Top => {
                        let x = anchor_x.saturating_sub(tooltip_w / 2);
                        let y = anchor_y.saturating_sub(tooltip_h + arrow_offset);
                        (x, y)
                    }
                    TooltipPosition::Bottom => {
                        let x = anchor_x.saturating_sub(tooltip_w / 2);
                        let y = anchor_y + 1 + arrow_offset;
                        (x, y)
                    }
                    TooltipPosition::Left => {
                        let x = anchor_x.saturating_sub(tooltip_w + arrow_offset);
                        let y = anchor_y.saturating_sub(tooltip_h / 2);
                        (x, y)
                    }
                    TooltipPosition::Right => {
                        let x = anchor_x + 1 + arrow_offset;
                        let y = anchor_y.saturating_sub(tooltip_h / 2);
                        (x, y)
                    }
                    // Auto is handled above and never reaches here
                    TooltipPosition::Auto => {
                        unreachable!("Auto position resolved to concrete position above")
                    }
                };
                (x, y, pos)
            }
            TooltipPosition::Top => {
                let x = anchor_x.saturating_sub(tooltip_w / 2);
                let y = anchor_y.saturating_sub(tooltip_h + arrow_offset);
                (x, y, TooltipPosition::Top)
            }
            TooltipPosition::Bottom => {
                let x = anchor_x.saturating_sub(tooltip_w / 2);
                let y = anchor_y + 1 + arrow_offset;
                (x, y, TooltipPosition::Bottom)
            }
            TooltipPosition::Left => {
                let x = anchor_x.saturating_sub(tooltip_w + arrow_offset);
                let y = anchor_y.saturating_sub(tooltip_h / 2);
                (x, y, TooltipPosition::Left)
            }
            TooltipPosition::Right => {
                let x = anchor_x + 1 + arrow_offset;
                let y = anchor_y.saturating_sub(tooltip_h / 2);
                (x, y, TooltipPosition::Right)
            }
        };

        // Clamp to screen bounds
        let x = x.min(area_width.saturating_sub(tooltip_w));
        let y = y.min(area_height.saturating_sub(tooltip_h));

        (x, y, position)
    }
}

impl Default for Tooltip {
    fn default() -> Self {
        Self::new("")
    }
}

impl View for Tooltip {
    crate::impl_view_meta!("Tooltip");

    fn render(&self, ctx: &mut RenderContext) {
        if !self.visible || (self.delay > 0 && self.delay_counter < self.delay) {
            return;
        }

        let area = ctx.area;
        let (tooltip_w, tooltip_h) = self.calculate_dimensions();
        let (tooltip_x, tooltip_y, actual_position) =
            self.calculate_position(area.width, area.height);

        let (default_fg, default_bg) = self.style.colors();
        let fg = self.fg.unwrap_or(default_fg);
        let bg = self.bg.unwrap_or(default_bg);

        // Build overlay entry (all coordinates relative to tooltip area)
        let overlay_area = crate::layout::Rect::new(tooltip_x, tooltip_y, tooltip_w, tooltip_h);
        let mut entry = crate::widget::traits::OverlayEntry::new(150, overlay_area);

        // Helper to create styled cell
        let cell_with = |ch: char, cell_fg: Color, cell_bg: Color| -> Cell {
            let mut c = Cell::new(ch);
            c.fg = Some(cell_fg);
            c.bg = Some(cell_bg);
            c
        };

        // Background
        for dy in 0..tooltip_h {
            for dx in 0..tooltip_w {
                entry.push(dx, dy, cell_with(' ', fg, bg));
            }
        }

        // Border
        let content_rx;
        let content_ry;

        if let Some(border) = self.style.border_chars() {
            content_rx = 2u16;
            content_ry = 1u16;

            entry.push(0, 0, cell_with(border.top_left, fg, bg));
            for dx in 1..tooltip_w.saturating_sub(1) {
                entry.push(dx, 0, cell_with(border.horizontal, fg, bg));
            }
            entry.push(
                tooltip_w.saturating_sub(1),
                0,
                cell_with(border.top_right, fg, bg),
            );

            // Title (bold)
            if let Some(ref title) = self.title {
                for (i, ch) in title.chars().enumerate() {
                    let rx = 2 + i as u16;
                    if rx < tooltip_w.saturating_sub(2) {
                        let mut c = cell_with(ch, fg, bg);
                        c.modifier |= Modifier::BOLD;
                        entry.push(rx, 1, c);
                    }
                }
            }

            // Side borders
            for dy in 1..tooltip_h.saturating_sub(1) {
                entry.push(0, dy, cell_with(border.vertical, fg, bg));
                entry.push(
                    tooltip_w.saturating_sub(1),
                    dy,
                    cell_with(border.vertical, fg, bg),
                );
            }

            // Bottom border
            let by = tooltip_h.saturating_sub(1);
            entry.push(0, by, cell_with(border.bottom_left, fg, bg));
            for dx in 1..tooltip_w.saturating_sub(1) {
                entry.push(dx, by, cell_with(border.horizontal, fg, bg));
            }
            entry.push(
                tooltip_w.saturating_sub(1),
                by,
                cell_with(border.bottom_right, fg, bg),
            );
        } else {
            content_rx = 1;
            content_ry = 0;
        }

        // Text content
        let lines = self.wrap_text();
        let text_y_off = if self.title.is_some() && self.style.border_chars().is_some() {
            1u16
        } else {
            0
        };

        for (i, line) in lines.iter().enumerate() {
            let ry = content_ry + text_y_off + i as u16;
            if ry >= tooltip_h.saturating_sub(1) {
                break;
            }
            for (j, ch) in line.chars().enumerate() {
                let rx = content_rx + j as u16;
                if rx < tooltip_w.saturating_sub(1) {
                    entry.push(rx, ry, cell_with(ch, fg, bg));
                }
            }
        }

        // Arrow — queue as separate 1-cell overlay at higher z-index
        if !matches!(self.arrow, TooltipArrow::None) {
            let (arrow_char, _) = self.arrow.chars(actual_position);
            let (arrow_abs_x, arrow_abs_y) = match actual_position {
                TooltipPosition::Top => (self.anchor.0, tooltip_y + tooltip_h),
                TooltipPosition::Bottom => (self.anchor.0, tooltip_y.saturating_sub(1)),
                TooltipPosition::Left => (tooltip_x + tooltip_w, self.anchor.1),
                TooltipPosition::Right => (tooltip_x.saturating_sub(1), self.anchor.1),
                TooltipPosition::Auto => (self.anchor.0, tooltip_y + tooltip_h),
            };

            let inside = arrow_abs_x >= tooltip_x
                && arrow_abs_x < tooltip_x + tooltip_w
                && arrow_abs_y >= tooltip_y
                && arrow_abs_y < tooltip_y + tooltip_h;

            let buf_w = ctx.buffer.width();
            let buf_h = ctx.buffer.height();
            if !inside && arrow_abs_x < buf_w && arrow_abs_y < buf_h {
                let arrow_area = crate::layout::Rect::new(arrow_abs_x, arrow_abs_y, 1, 1);
                let mut arrow_entry = crate::widget::traits::OverlayEntry::new(151, arrow_area);
                let mut cell = Cell::new(arrow_char);
                cell.fg = Some(fg);
                arrow_entry.push(0, 0, cell);
                ctx.queue_overlay(arrow_entry);
            }
        }

        // Queue tooltip as overlay; fallback to inline
        if !ctx.queue_overlay(entry.clone()) {
            for oc in &entry.cells {
                ctx.set(tooltip_x + oc.x, tooltip_y + oc.y, oc.cell);
            }
        }
    }
}

impl_styled_view!(Tooltip);
impl_props_builders!(Tooltip);

/// Helper to create a tooltip
pub fn tooltip(text: impl Into<String>) -> Tooltip {
    Tooltip::new(text)
}

// KEEP HERE - accesses private fields
// Tests for private methods that cannot be extracted

#[cfg(test)]
mod tests {
    use super::*;

    // These tests access private methods and must stay inline

    #[test]
    fn test_tooltip_wrap_text() {
        let t = Tooltip::new("This is a very long text that should be wrapped").max_width(20);
        let lines = t.wrap_text();
        assert!(lines.len() > 1);
        assert!(lines.iter().all(|l| l.len() <= 20));
    }

    #[test]
    fn test_tooltip_calculate_dimensions() {
        let t = Tooltip::new("Short").style(TooltipStyle::Bordered);
        let (w, h) = t.calculate_dimensions();
        assert!(w > 5);
        assert!(h >= 3); // At least border + 1 line
    }

    #[test]
    fn test_tooltip_with_title() {
        let t = Tooltip::new("Content")
            .title("Title")
            .style(TooltipStyle::Bordered);

        let (_, h) = t.calculate_dimensions();
        assert!(h >= 4); // border + title + content
    }

    #[test]
    fn test_tooltip_auto_position() {
        let t = Tooltip::new("Test")
            .position(TooltipPosition::Auto)
            .anchor(5, 5);

        let (_, _, pos) = t.calculate_position(40, 20);
        // Should choose a valid position
        assert!(!matches!(pos, TooltipPosition::Auto));
    }
}