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
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
use std::collections::{BTreeMap, HashSet};

use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Rect},
    style::{Color, Style},
    text::Line,
    widgets::{Block, Clear, Padding, Paragraph, StatefulWidget, Widget, Wrap},
};

use crate::popup::PopupSize;
use crate::BorderType;

const CLOSE_SYMBOL: &str = "×";
const BADGE_GAP_X: u16 = 1;
const BADGE_GAP_Y: u16 = 0;
const BORDER_STYLES: Style = Style::new().bold();

/// Dónde se ancla un badge al borde de la pantalla.
///
/// Los badges en el mismo [`BadgeAnchor`] se apilan automáticamente
/// con un gap de 1 celda.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum BadgeAnchor {
    /// Esquina superior izquierda. Stack horizontal hacia la derecha.
    #[default]
    TopLeft,
    /// Borde superior, centrado. Stack horizontal hacia la derecha.
    Top,
    /// Esquina superior derecha. Stack horizontal hacia la izquierda.
    TopRight,
    /// Esquina inferior izquierda. Stack horizontal hacia la derecha.
    BottomLeft,
    /// Borde inferior, centrado. Stack horizontal hacia la derecha.
    Bottom,
    /// Esquina inferior derecha. Stack horizontal hacia la izquierda.
    BottomRight,
    /// Borde izquierdo, centrado verticalmente. Stack vertical hacia abajo.
    Left,
    /// Borde derecho, centrado verticalmente. Stack vertical hacia abajo.
    Right,
}

/// Un badge individual con borde, contenido y posición de anclaje.
///
/// Se usa dentro de un [`BadgeStack`] que maneja el layout automático.
#[derive(Clone)]
pub struct Badge<'a> {
    width: PopupSize,
    height: PopupSize,
    border_color: Color,
    border_type: BorderType,
    padding: u16,
    title: Option<&'a str>,
    content: Vec<Line<'a>>,
    anchor: BadgeAnchor,
    closable: bool,
    bg_color: Option<Color>,
    style: Style,
    alignment: Alignment,
    z_index: u16,
    /// Nivel/fila dentro del mismo anchor.
    /// 0 = más cercano al borde, 1 = una fila/columna arriba, etc.
    layer: u16,
}

impl<'a> Badge<'a> {
    /// Crea un badge con texto plano y color de borde.
    ///
    /// Defaults: width `Fixed(20)`, height `Fixed(3)`, anchor `TopLeft`,
    /// border `Rounded`, padding `0`, closable `true`, alignment `Left`.
    pub fn new(content: &'a str, border_color: Color) -> Self {
        Self {
            width: PopupSize::Fixed(20),
            height: PopupSize::Fixed(3),
            border_color,
            border_type: BorderType::Rounded,
            padding: 0,
            title: None,
            content: vec![Line::from(content)],
            anchor: BadgeAnchor::default(),
            closable: true,
            bg_color: None,
            style: Style::default(),
            alignment: Alignment::Left,
            z_index: 5,
            layer: 0,
        }
    }

    /// Crea un badge con contenido custom (`Vec<Line>`) y color de borde.
    pub fn with_content(content: Vec<Line<'a>>, border_color: Color) -> Self {
        Self {
            content,
            ..Self::new("", border_color)
        }
    }

    pub fn anchor(mut self, anchor: BadgeAnchor) -> Self {
        self.anchor = anchor;
        self
    }

    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    pub fn width(mut self, width: PopupSize) -> Self {
        self.width = width;
        self
    }

    pub fn height(mut self, height: PopupSize) -> Self {
        self.height = height;
        self
    }

    pub fn closable(mut self, closable: bool) -> Self {
        self.closable = closable;
        self
    }

    pub fn title(mut self, title: &'a str) -> Self {
        self.title = Some(title);
        self
    }

    pub fn border_type(mut self, bt: BorderType) -> Self {
        self.border_type = bt;
        self
    }

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

    pub fn bg_color(mut self, color: Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    pub fn padding(mut self, padding: u16) -> Self {
        self.padding = padding;
        self
    }

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

    /// Controla el orden de renderizado dentro del mismo anchor.
    /// Menor valor = se renderiza primero (atrás).
    /// Mayor valor = se renderiza después (adelante).
    pub fn z_index(mut self, z: u16) -> Self {
        self.z_index = z;
        self
    }

    /// Fila/nivel dentro del mismo anchor.
    /// `0` (default) = más cercano al borde.
    /// `1` = una fila arriba (bottom anchors) / abajo (top anchors).
    pub fn layer(mut self, layer: u16) -> Self {
        self.layer = layer;
        self
    }

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

    fn resolve_width(&self, area_width: u16) -> u16 {
        self.resolve(area_width, self.width)
    }

    fn resolve_height(&self, area_height: u16) -> u16 {
        self.resolve(area_height, self.height)
    }

    fn render_at(self, rect: Rect, buf: &mut Buffer) {
        Clear.render(rect, buf);

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

        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::new(
                    self.padding,
                    self.padding,
                    self.padding,
                    self.padding,
                ));

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

            if let Some(t) = self.title {
                b = b.title_top(Line::from(t).left_aligned());
            }

            if self.closable {
                b = b.title_top(Line::from(CLOSE_SYMBOL).right_aligned());
            }

            let inner = b.inner(rect);
            b.render(rect, buf);

            Paragraph::new(self.content)
                .style(self.style)
                .alignment(self.alignment)
                .wrap(Wrap { trim: false })
                .render(inner, buf);
        } else {
            let mut b = Block::default().padding(Padding::new(
                self.padding,
                self.padding,
                self.padding,
                self.padding,
            ));

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

            let inner = b.inner(rect);
            b.render(rect, buf);

            Paragraph::new(self.content)
                .style(self.style)
                .alignment(self.alignment)
                .wrap(Wrap { trim: false })
                .render(inner, buf);
        }
    }
}

/// Contenedor que acumula múltiples [`Badge`]s y los renderiza
/// anclados a los bordes del área.
///
/// Los badges se agrupan por [`BadgeAnchor`] y se apilan automáticamente
/// (gap de 1 celda) en la dirección correspondiente.
///
/// # Ejemplo
///
/// ```no_run
/// use ratatui::style::Color;
/// use hefesto_widgets::{Badge, BadgeAnchor, BadgeStack};
///
/// let stack = BadgeStack::new()
///     .push(Badge::new(" main", Color::Green).anchor(BadgeAnchor::TopLeft))
///     .push(Badge::new(" 3 warnings", Color::Yellow).anchor(BadgeAnchor::TopRight));
/// ```
#[derive(Clone, Default)]
pub struct BadgeStack<'a> {
    badges: Vec<Badge<'a>>,
}

impl<'a> BadgeStack<'a> {
    pub fn new() -> Self {
        Self { badges: Vec::new() }
    }

    /// Agrega un badge al stack.
    pub fn push(mut self, badge: Badge<'a>) -> Self {
        self.badges.push(badge);
        self
    }

    /// Retorna el z-index máximo entre todos los badges del stack.
    pub(crate) fn max_z_index(&self) -> u16 {
        self.badges.iter().map(|b| b.z_index).max().unwrap_or(0)
    }

    /// Renderiza todos los badges con un estado interno default
    /// (todos visibles). No consume `self`.
    ///
    /// Útil para renderizar badges como fondo de otro widget
    /// (ej: dentro de un [`Popup`](crate::Popup)).
    pub fn render_all(&self, area: Rect, buf: &mut Buffer) {
        let mut grouped: BTreeMap<(BadgeAnchor, u16), Vec<&Badge<'_>>> = BTreeMap::new();
        for badge in &self.badges {
            grouped.entry((badge.anchor, badge.layer)).or_default().push(badge);
        }

        let mut by_anchor: BTreeMap<BadgeAnchor, Vec<(u16, Vec<&Badge<'_>>)>> = BTreeMap::new();
        for ((anchor, layer), badges) in grouped {
            by_anchor.entry(anchor).or_default().push((layer, badges));
        }
        for layers in by_anchor.values_mut() {
            layers.sort_by_key(|(l, _)| *l);
        }

        for (anchor, layers) in by_anchor {
            let mut offset: u16 = 0;

            for (_layer, mut badges) in layers {
                badges.sort_by_key(|b| b.z_index);

                let sizes: Vec<(u16, u16)> = badges
                    .iter()
                    .map(|b| (b.resolve_width(area.width), b.resolve_height(area.height)))
                    .collect();

                let rects = group_rects(area, anchor, &sizes, offset);

                let max_dim = match anchor {
                    BadgeAnchor::TopLeft
                    | BadgeAnchor::Top
                    | BadgeAnchor::TopRight
                    | BadgeAnchor::BottomLeft
                    | BadgeAnchor::Bottom
                    | BadgeAnchor::BottomRight => {
                        sizes.iter().map(|(_, h)| *h).max().unwrap_or(0)
                    }
                    BadgeAnchor::Left | BadgeAnchor::Right => {
                        sizes.iter().map(|(w, _)| *w).max().unwrap_or(0)
                    }
                };
                offset += max_dim + BADGE_GAP_Y;

                for (badge, rect) in badges.into_iter().zip(rects) {
                    badge.clone().render_at(rect, buf);
                }
            }
        }
    }
}

/// Estado mutable del [`BadgeStack`].
///
/// Trackea qué badges están descartados (dismissed).
///
/// ```no_run
/// use hefesto_widgets::BadgeStackState;
///
/// let mut state = BadgeStackState::default();
/// state.dismiss(2);
/// assert!(!state.is_visible(2));
/// ```
#[derive(Default)]
pub struct BadgeStackState {
    dismissed: HashSet<usize>,
}

impl BadgeStackState {
    /// Marca un badge como descartado (no se renderiza).
    pub fn dismiss(&mut self, index: usize) {
        self.dismissed.insert(index);
    }

    /// `true` si el badge en `index` debe ser visible.
    pub fn is_visible(&self, index: usize) -> bool {
        !self.dismissed.contains(&index)
    }

    /// Reabre todos los badges descartados.
    pub fn reset(&mut self) {
        self.dismissed.clear();
    }
}

/// Calcula los `Rect`s para un grupo de badges con el mismo anclaje.
///
/// `layer_offset` desplaza la capa según la dirección del anchor:
/// - top anchors → desplaza hacia abajo (aumenta y)
/// - bottom anchors → desplaza hacia arriba (disminuye y)
/// - left anchors → desplaza hacia la derecha (aumenta x)
/// - right anchors → desplaza hacia la izquierda (disminuye x)
fn group_rects(area: Rect, anchor: BadgeAnchor, sizes: &[(u16, u16)], layer_offset: u16) -> Vec<Rect> {
    let gap = BADGE_GAP_X;
    let max_w = area.width;
    let max_h = area.height;

    if sizes.is_empty() {
        return Vec::new();
    }

    match anchor {
        BadgeAnchor::TopLeft
        | BadgeAnchor::Top
        | BadgeAnchor::Bottom
        | BadgeAnchor::BottomLeft => {
            let y0 = match anchor {
                BadgeAnchor::TopLeft | BadgeAnchor::Top => layer_offset,
                BadgeAnchor::BottomLeft | BadgeAnchor::Bottom => {
                    let max_badge_h = sizes.iter().map(|(_, h)| *h).max().unwrap_or(0);
                    max_h.saturating_sub(max_badge_h + layer_offset)
                }
                _ => unreachable!(),
            };

            let total_w: u16 = sizes
                .iter()
                .map(|(w, _)| w + gap)
                .sum::<u16>()
                .saturating_sub(gap);

            let start_x = match anchor {
                BadgeAnchor::TopLeft | BadgeAnchor::BottomLeft => 0,
                BadgeAnchor::Top | BadgeAnchor::Bottom => max_w.saturating_sub(total_w) / 2,
                _ => unreachable!(),
            };

            let mut x = start_x;
            sizes
                .iter()
                .map(|(w, h)| {
                    let rect = Rect {
                        x: x.min(max_w.saturating_sub(1)),
                        y: y0,
                        width: (*w).min(max_w.saturating_sub(x)),
                        height: (*h).min(max_h.saturating_sub(y0)),
                    };
                    x += w + gap;
                    rect
                })
                .collect()
        }

        BadgeAnchor::TopRight | BadgeAnchor::BottomRight => {
            let y0 = match anchor {
                BadgeAnchor::TopRight => layer_offset,
                BadgeAnchor::BottomRight => {
                    let max_badge_h = sizes.iter().map(|(_, h)| *h).max().unwrap_or(0);
                    max_h.saturating_sub(max_badge_h + layer_offset)
                }
                _ => unreachable!(),
            };

            let total_w: u16 = sizes
                .iter()
                .map(|(w, _)| w + gap)
                .sum::<u16>()
                .saturating_sub(gap);

            let start_x = max_w.saturating_sub(total_w);

            let mut x = start_x;
            sizes
                .iter()
                .map(|(w, h)| {
                    let rect = Rect {
                        x: x.min(max_w.saturating_sub(1)),
                        y: y0,
                        width: (*w).min(max_w.saturating_sub(x)),
                        height: (*h).min(max_h.saturating_sub(y0)),
                    };
                    x += w + gap;
                    rect
                })
                .collect()
        }

        BadgeAnchor::Left | BadgeAnchor::Right => {
            let x0 = match anchor {
                BadgeAnchor::Left => layer_offset,
                BadgeAnchor::Right => {
                    let max_badge_w = sizes.iter().map(|(w, _)| *w).max().unwrap_or(0);
                    max_w.saturating_sub(max_badge_w + layer_offset)
                }
                _ => unreachable!(),
            };

            let total_h: u16 = sizes
                .iter()
                .map(|(_, h)| h + gap)
                .sum::<u16>()
                .saturating_sub(gap);

            let start_y = max_h.saturating_sub(total_h) / 2;

            let mut y = start_y;
            sizes
                .iter()
                .map(|(w, h)| {
                    let rect = Rect {
                        x: x0,
                        y: y.min(max_h.saturating_sub(1)),
                        width: (*w).min(max_w.saturating_sub(x0)),
                        height: (*h).min(max_h.saturating_sub(y)),
                    };
                    y += h + gap;
                    rect
                })
                .collect()
        }
    }
}

impl StatefulWidget for BadgeStack<'_> {
    type State = BadgeStackState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let mut grouped: BTreeMap<(BadgeAnchor, u16), Vec<Badge<'_>>> = BTreeMap::new();

        for (i, badge) in self.badges.into_iter().enumerate() {
            if state.is_visible(i) {
                grouped.entry((badge.anchor, badge.layer)).or_default().push(badge);
            }
        }

        let mut by_anchor: BTreeMap<BadgeAnchor, Vec<(u16, Vec<Badge<'_>>)>> = BTreeMap::new();
        for ((anchor, layer), badges) in grouped {
            by_anchor.entry(anchor).or_default().push((layer, badges));
        }
        for layers in by_anchor.values_mut() {
            layers.sort_by_key(|(l, _)| *l);
        }

        for (anchor, layers) in by_anchor {
            let mut offset: u16 = 0;

            for (_layer, mut badges) in layers {
                badges.sort_by_key(|b| b.z_index);

                let sizes: Vec<(u16, u16)> = badges
                    .iter()
                    .map(|b| (b.resolve_width(area.width), b.resolve_height(area.height)))
                    .collect();

                let rects = group_rects(area, anchor, &sizes, offset);

                let max_dim = match anchor {
                    BadgeAnchor::TopLeft
                    | BadgeAnchor::Top
                    | BadgeAnchor::TopRight
                    | BadgeAnchor::BottomLeft
                    | BadgeAnchor::Bottom
                    | BadgeAnchor::BottomRight => {
                        sizes.iter().map(|(_, h)| *h).max().unwrap_or(0)
                    }
                    BadgeAnchor::Left | BadgeAnchor::Right => {
                        sizes.iter().map(|(w, _)| *w).max().unwrap_or(0)
                    }
                };
                offset += max_dim + BADGE_GAP_Y;

                for (badge, rect) in badges.into_iter().zip(rects) {
                    badge.render_at(rect, buf);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;