hefesto-widgets 0.7.3

Ratatui widgets for the Hefesto TUI toolkit: popups, scrollable lists, trees, text input and spinners
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
use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Constraint, Layout, Rect},
    text::Line,
    style::{Color, Style},
    widgets::{
        Block, Borders, Clear, Padding, Paragraph, Widget, Wrap,
    },
};

use crate::badge::BadgeStack;
use crate::styles::decorate_with_dots_with_pattern;
use crate::styles::BACKGROUND_DOT_SYMBOL;
use crate::styles::DotPattern;

const BORDER_STYLES: Style = Style::new().bold();
const AUTO_WIDTH_PCT: u16 = 80;
const AUTO_HEIGHT_PCT: u16 = 70;
const EMPTY_MSG: &str = "No content";

/// Configuration for the background dot grid pattern.
#[derive(Clone)]
pub struct DotGridConfig {
    pub color: Color,
    pub symbol: String,
    pub density_x: u16,
    pub density_y: u16,
    pub pattern: DotPattern,
}

impl Default for DotGridConfig {
    fn default() -> Self {
        Self {
            color: Color::DarkGray,
            symbol: BACKGROUND_DOT_SYMBOL.to_string(),
            density_x: 4,
            density_y: 2,
            pattern: DotPattern::default(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PopupSize {
    Fixed(u16),
    Percent(u16),
    Auto,
    Max(u16),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderType {
    Plain,
    #[default]
    Rounded,
    Double,
    Thick,
    QuadrantInside,
    QuadrantOutside,
    None,
}

impl BorderType {
    pub(crate) fn has_border(&self) -> bool {
        !matches!(self, Self::None)
    }

    pub fn to_ratatui(&self) -> ratatui::widgets::BorderType {
        match self {
            Self::Plain => ratatui::widgets::BorderType::Plain,
            Self::Rounded => ratatui::widgets::BorderType::Rounded,
            Self::Double => ratatui::widgets::BorderType::Double,
            Self::Thick => ratatui::widgets::BorderType::Thick,
            Self::QuadrantInside => ratatui::widgets::BorderType::QuadrantInside,
            Self::QuadrantOutside => ratatui::widgets::BorderType::QuadrantOutside,
            Self::None => panic!("BorderType::None must be filtered before calling to_ratatui"),
        }
    }
}

/// A configurable popup widget for ratatui.
///
/// Supports absolute positioning via `position(x, y)`, relative positioning
/// via `origin(x, y)`, auto-centering, configurable borders, header mode,
/// background fill via `bg_color`, and customizable text alignment/wrapping.
///
/// By default a subtle diagonal dot pattern is rendered in the empty area
/// outside the popup. Call [`no_background`](Self::no_background) to disable it,
/// or [`background_dots`](Self::background_dots) to customize.
#[derive(Clone)]
pub struct Popup<'a> {
    width: PopupSize,
    height: PopupSize,
    border_color: Color,
    border_type: BorderType,
    padding: u16,
    title: Option<&'a str>,
    content: Vec<Line<'a>>,
    empty_message: Option<&'a str>,
    position: Option<(u16, u16)>,
    origin: Option<(u16, u16)>,
    header: bool,
    alignment: Alignment,
    wrap: Wrap,
    bg_color: Option<Color>,
    dot_grid: Option<DotGridConfig>,
    badges: Option<BadgeStack<'a>>,
    z_index: u16,
}

impl<'a> Popup<'a> {
    /// Creates a new `Popup` with the given border color and default settings.
    ///
    /// Defaults: width/height `Auto` (80%/70% of area), border `Rounded`,
    /// padding `1`, alignment `Center`, wrap with `trim: false`, no title,
    /// no content, no header.
    /// Creates a new `Popup` with the given border color and default settings.
    ///
    /// Defaults: width/height `Auto` (80%/70% of area), border `Rounded`,
    /// padding `1`, alignment `Center`, wrap with `trim: false`, no title,
    /// no content, no header. A subtle dot background is enabled by default.
    pub fn new(border_color: Color) -> Self {
        Self {
            width: PopupSize::Auto,
            height: PopupSize::Auto,
            border_color,
            border_type: BorderType::Rounded,
            padding: 1,
            title: None,
            content: vec![],
            empty_message: None,
            position: None,
            origin: None,
            header: false,
            alignment: Alignment::Center,
            wrap: Wrap { trim: false },
            bg_color: None,
            dot_grid: Some(DotGridConfig::default()),
            badges: None,
            z_index: 10,
        }
    }

    /// Sets the title displayed in the popup border (non-header mode).
    ///
    /// When `BorderType::None` is set and header mode is off, the title
    /// is rendered as a pseudo-header bar inside the popup content area.
    pub fn title(mut self, title: &'a str) -> Self {
        self.title = Some(title);
        self
    }

    /// Sets the content lines to display inside the popup.
    pub fn content(mut self, content: Vec<Line<'a>>) -> Self {
        self.content = content;
        self
    }

    /// Sets the preferred width: `Fixed(n)`, `Percent(p)`, `Auto`, or
    /// `Max(max)`. When `position` or `origin` is set, the resulting width
    /// is clamped to fit within the remaining area.
    pub fn width(mut self, width: PopupSize) -> Self {
        self.width = width;
        self
    }

    /// Sets the preferred height. See [`width`](Self::width) for sizing
    /// behavior.
    pub fn height(mut self, height: PopupSize) -> Self {
        self.height = height;
        self
    }

    /// Sets the border style. When `BorderType::None`, no border is drawn
    /// and the title (if set and header mode is off) renders as a
    /// pseudo-header bar inside the content area.
    pub fn border_type(mut self, border_type: BorderType) -> Self {
        self.border_type = border_type;
        self
    }

    /// Sets the inner padding between the border and the content.
    pub fn padding(mut self, padding: u16) -> Self {
        self.padding = padding;
        self
    }

    /// Sets a custom message shown when content is empty.
    pub fn empty_message(mut self, msg: &'a str) -> Self {
        self.empty_message = Some(msg);
        self
    }

    /// Places the popup at an absolute `(x, y)` position using the
    /// configured width/height. Coordinates are clamped to the area bounds.
    pub fn position(mut self, x: u16, y: u16) -> Self {
        self.position = Some((x, y));
        self
    }

    /// Places the popup at an `(x, y)` origin using the configured
    /// width/height. Coordinates and size are clamped to the area bounds.
    pub fn origin(mut self, x: u16, y: u16) -> Self {
        self.origin = Some((x, y));
        self
    }

    /// Enables header mode: renders a separate header bar below the border
    /// instead of a border title.
    pub fn header(mut self) -> Self {
        self.header = true;
        self
    }

    /// Returns whether header mode is enabled.
    pub fn has_header(&self) -> bool {
        self.header
    }

    /// Sets the border color.
    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = color;
        self
    }

    /// Sets the background color for the entire popup area, including the
    /// border cells (if any) and the content area.
    ///
    /// When `None` (default), the popup inherits the terminal's background.
    /// The border's `fg` color is preserved on top of the background.
    pub fn bg_color(mut self, color: Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    /// Disables the background dot grid for this popup.
    pub fn no_background(mut self) -> Self {
        self.dot_grid = None;
        self
    }

    /// Customizes the background dot grid (color, symbol, density for both axes).
    ///
    /// Spacing: 1 = every cell, 4 = every 4th cell.
    /// Use [`background_spacing`](Self::background_spacing) to set x/y independently.
    pub fn background_dots(mut self, color: Color, symbol: &str, density: u16) -> Self {
        self.dot_grid = Some(DotGridConfig {
            color,
            symbol: symbol.to_string(),
            density_x: density,
            density_y: density,
            pattern: DotPattern::default(),
        });
        self
    }

    /// Sets horizontal and vertical spacing independently.
    ///
    /// For example `spacing(4, 2)` in Grid mode means one dot every 4
    /// columns and every 2 rows.
    pub fn background_spacing(mut self, density_x: u16, density_y: u16) -> Self {
        if let Some(ref mut dg) = self.dot_grid {
            dg.density_x = density_x;
            dg.density_y = density_y;
        } else {
            self.dot_grid = Some(DotGridConfig {
                density_x,
                density_y,
                ..DotGridConfig::default()
            });
        }
        self
    }

    /// Sets the dot pattern for the background grid.
    ///
    /// If no dot grid has been configured yet, creates one with defaults.
    pub fn background_pattern(mut self, pattern: DotPattern) -> Self {
        if let Some(ref mut dg) = self.dot_grid {
            dg.pattern = pattern;
        } else {
            self.dot_grid = Some(DotGridConfig {
                pattern,
                ..DotGridConfig::default()
            });
        }
        self
    }

    /// Attaches badges to this popup. Badges are rendered in the background
    /// layer (low z-index) before the popup chrome, so the popup appears on top.
    pub fn badges(mut self, badges: BadgeStack<'a>) -> Self {
        self.badges = Some(badges);
        self
    }

    /// Sets the z-index for render ordering.
    ///
    /// Higher values render on top. Default is 10.
    /// Badges default to 5, so popups render on top by default.
    /// Set `z_index` lower than the badge stack's max to render
    /// the popup behind the badges.
    pub fn z_index(mut self, z: u16) -> Self {
        self.z_index = z;
        self
    }

    pub(crate) fn get_border_color(&self) -> Color {
        self.border_color
    }

    pub(crate) fn get_height(&self) -> PopupSize {
        self.height
    }

    /// Sets the text alignment inside the popup (default: `Center`).
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Sets the wrap behavior (default: `Wrap { trim: false }`).
    pub fn wrap(mut self, wrap: Wrap) -> Self {
        self.wrap = wrap;
        self
    }

    fn resolve(&self, available: u16) -> u16 {
        match self.width {
            PopupSize::Fixed(v) => v,
            PopupSize::Percent(p) => available * p / 100,
            PopupSize::Auto => available * AUTO_WIDTH_PCT / 100,
            PopupSize::Max(max) => (available * AUTO_WIDTH_PCT / 100).min(max),
        }
    }

    fn resolve_height(&self, available: u16) -> u16 {
        match self.height {
            PopupSize::Fixed(v) => v,
            PopupSize::Percent(p) => available * p / 100,
            PopupSize::Auto => available * AUTO_HEIGHT_PCT / 100,
            PopupSize::Max(max) => (available * AUTO_HEIGHT_PCT / 100).min(max),
        }
    }

    pub(crate) fn centered_rect(area: Rect, width: u16, height: u16) -> Rect {
        Rect {
            x: (area.width.saturating_sub(width)) / 2,
            y: (area.height.saturating_sub(height)) / 2,
            width: width.min(area.width),
            height: height.min(area.height),
        }
    }
}

impl Popup<'_> {
    /// Returns the vertical offset from the top of the popup to where content
    /// begins, accounting for the border, header bar, pseudo-header, and padding.
    ///
    /// Useful for consumers that render custom content inside the popup area.
    pub fn content_offset(&self) -> u16 {
        let border_size: u16 = if self.border_type.has_border() { 1 } else { 0 };
        if self.header {
            return border_size + 2; // no padding on top in header mode
        }
        let extra: u16 = if !self.border_type.has_border() && self.title.is_some() {
            1
        } else {
            0
        };
        border_size + extra + self.padding
    }

    /// Resolves the final `Rect` for this popup within the given `area`.
    ///
    /// Priority: `position` > `origin` > centered. Coordinates and size are
    /// clamped to ensure the popup stays within the area bounds.
    pub fn resolve_rect(&self, area: Rect) -> Rect {
        let w = self.resolve(area.width);
        let h = self.resolve_height(area.height);
        if let Some((x, y)) = self.position {
            let x = x.min(area.width.saturating_sub(1));
            let y = y.min(area.height.saturating_sub(1));
            let w = w.min(area.width - x);
            let h = h.min(area.height - y);
            Rect { x, y, width: w, height: h }
        } else if let Some((ox, oy)) = self.origin {
            let ox = ox.min(area.width.saturating_sub(1));
            let oy = oy.min(area.height.saturating_sub(1));
            let w = w.min(area.width - ox);
            let h = h.min(area.height - oy);
            Rect { x: ox, y: oy, width: w, height: h }
        } else {
            Self::centered_rect(area, w, h)
        }
    }

    /// Renders a header bar with the given `title` inside `area`.
    pub fn render_header(area: Rect, buf: &mut Buffer, border_color: Color, title: &str) {
        let block = Block::bordered()
            .borders(Borders::BOTTOM)
            .border_style(BORDER_STYLES.fg(border_color))
            .padding(Padding::new(1, 1, 0, 0));
        let inner = block.inner(area);
        let para = Paragraph::new(title);
        para.render(inner, buf);
        block.render(area, buf);
    }

    /// Renders the popup chrome (clear, border/block, header) and returns
    /// the inner content area.
    pub fn render_inner(&self, area: Rect, buf: &mut Buffer) -> Rect {
        if let Some(ref cfg) = self.dot_grid {
            decorate_with_dots_with_pattern(
                buf, area, cfg.color, &cfg.symbol, cfg.density_x, cfg.density_y, cfg.pattern,
            );
        }

        let badges_on_top = self
            .badges
            .as_ref()
            .map_or(false, |b| b.max_z_index() >= self.z_index);

        if !badges_on_top {
            if let Some(ref badges) = self.badges {
                badges.render_all(area, buf);
            }
        }

        let popup_rect = self.resolve_rect(area);
        Clear.render(popup_rect, buf);

        let padding = if self.header {
            Padding::new(self.padding, self.padding, 0, self.padding)
        } else {
            Padding::new(self.padding, self.padding, self.padding, self.padding)
        };

        let bg_style = self.bg_color.map(|c| Style::new().bg(c));

        let block = if self.border_type.has_border() {
            let mut b = Block::bordered()
                .border_type(self.border_type.to_ratatui())
                .border_style(BORDER_STYLES.fg(self.border_color))
                .padding(padding);

            if let Some(s) = bg_style {
                b = b.style(s);
            }

            if !self.header {
                if let Some(title) = self.title {
                    b = b.title(title);
                }
            }

            b
        } else {
            let mut b = Block::default().padding(padding);

            if let Some(s) = bg_style {
                b = b.style(s);
            }

            b
        };

        let inner = block.inner(popup_rect);
        block.render(popup_rect, buf);

        if badges_on_top {
            if let Some(ref badges) = self.badges {
                badges.render_all(area, buf);
            }
        }

        if !self.border_type.has_border() && self.title.is_some() && !self.header {
            let chunks = Layout::vertical([
                Constraint::Length(1),
                Constraint::Min(0),
            ]).split(inner);

            let mut title_style = BORDER_STYLES.fg(self.border_color);
            if let Some(bg) = self.bg_color {
                title_style = title_style.bg(bg);
            }

            Paragraph::new(Line::from(self.title.unwrap_or("")))
                .style(title_style)
                .render(chunks[0], buf);

            chunks[1]
        } else if self.header {
            let chunks = Layout::vertical([
                Constraint::Length(2),
                Constraint::Min(0),
            ]).split(inner);

            Self::render_header(
                chunks[0], buf,
                self.border_color,
                self.title.unwrap_or(""),
            );

            chunks[1]
        } else {
            inner
        }
    }
}

impl Widget for Popup<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let inner = self.render_inner(area, buf);

        let display: Vec<Line<'_>> = if self.content.is_empty() {
            let msg = self.empty_message.unwrap_or(EMPTY_MSG);
            vec![Line::from(msg)]
        } else {
            self.content
        };

        let para = Paragraph::new(display)
            .alignment(self.alignment)
            .wrap(self.wrap);
        para.render(inner, buf);
    }
}

#[cfg(test)]
mod tests;