tuile 0.3.0

Textual-grade widgets, design system, animation and app runtime on top of ratatui
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
//! Application header with icon, title, subtitle, clock, and action buttons.
//!
//! ```no_run
//! use tuile::prelude::*;
//! # let area = Rect::new(0, 0, 80, 3);
//! # let mut buf = Buffer::empty(area);
//! let mut state = AppHeaderState::default();
//! AppHeader::new().title("Settings").icon("⊛").clock(true).render(area, &mut buf, &mut state);
//! ```

use crossterm::event::{KeyEvent, MouseEvent};
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::Modifier;

use crate::core::{Hit, HitBox, MinSize, Outcome};
use crate::draw::{self, fill, put, put_centered, put_right, st};
use crate::runtime::local_hms;
use crate::theme::{self, Theme};

/// State for the app header: hit tracking for icon and actions.
#[derive(Clone, Debug, Default)]
pub struct AppHeaderState {
    /// HitBoxes for actions (right-aligned clickable labels).
    pub hits: Vec<HitBox>,
    /// Index of the hovered action.
    pub hover: Option<usize>,
    /// Icon hitbox.
    icon_hit: HitBox,
    /// Index of the action that was clicked (take with `take_action`).
    pressed: Option<usize>,
    /// True if icon was clicked (take with `take_icon_click`).
    icon_clicked: bool,
}

impl AppHeaderState {
    pub fn new() -> Self {
        Default::default()
    }

    /// Take the pressed action index (consumes it).
    pub fn take_action(&mut self) -> Option<usize> {
        self.pressed.take()
    }

    /// Take icon click (consumes it).
    pub fn take_icon_click(&mut self) -> bool {
        std::mem::take(&mut self.icon_clicked)
    }
}

impl crate::core::Interactive for AppHeaderState {
    fn handle_key(&mut self, _k: KeyEvent) -> Outcome {
        Outcome::Ignored
    }

    fn handle_mouse(&mut self, m: MouseEvent) -> Outcome {
        let mut out = Outcome::Ignored;

        // Icon
        let ih = self.icon_hit.mouse(&m);
        if ih == Hit::Press {
            self.icon_clicked = true;
            out = Outcome::Changed;
        } else if ih == Hit::HoverChanged {
            out = Outcome::Consumed;
        }

        // Actions
        self.hover = None;
        for (i, hit) in self.hits.iter_mut().enumerate() {
            let h = hit.mouse(&m);
            if h == Hit::Press {
                self.pressed = Some(i);
                out = Outcome::Submitted;
            } else if h == Hit::HoverChanged && hit.hover {
                self.hover = Some(i);
                out = Outcome::Consumed;
            }
        }

        out
    }
}

/// Fixed-height app header that renders a left icon+title+subtitle and right-aligned action labels plus an optional clock.
#[derive(Clone, Debug)]
pub struct AppHeader {
    title: String,
    subtitle: Option<String>,
    icon: Option<String>,
    clock: bool,
    clock_seconds: bool,
    tall: bool,
    right: Option<String>,
    actions: Vec<String>,
    theme: Option<Theme>,
}

impl AppHeader {
    pub fn new() -> Self {
        Self {
            title: String::new(),
            subtitle: None,
            icon: None,
            clock: false,
            clock_seconds: false,
            tall: false,
            right: None,
            actions: Vec::new(),
            theme: None,
        }
    }

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

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

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

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

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

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

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

    pub fn actions(mut self, a: &[&str]) -> Self {
        self.actions = a.iter().map(|s| s.to_string()).collect();
        self
    }

    pub fn theme(mut self, t: &Theme) -> Self {
        self.theme = Some(*t);
        self
    }
    pub fn render(self, area: Rect, buf: &mut Buffer, state: &mut AppHeaderState) {
        let th = self.theme.unwrap_or_else(theme::current);

        if draw::refuse(buf, area, self.min_size(), th.text_disabled) {
            state.hits.clear();
            state.icon_hit.set_area(Rect::default());
            return;
        }

        fill(buf, area, th.panel);

        if self.tall {
            // Tall: 3 rows, subtitle centered on row 2
            if area.height < 3 {
                return;
            }

            // Icon
            if let Some(ref icon) = self.icon {
                let icon_area = Rect {
                    x: area.x + 1,
                    y: area.y,
                    width: icon.len() as u16 + 2,
                    height: 1,
                };
                state.icon_hit.set_area(icon_area);
                let icon_bg = if state.icon_hit.hover {
                    th.hover_bg
                } else {
                    th.panel
                };
                fill(buf, icon_area, icon_bg);
                put(
                    buf,
                    area.x + 1,
                    area.y,
                    icon,
                    icon.len() as u16,
                    st(th.foreground, icon_bg),
                );
            } else {
                state.icon_hit.set_area(Rect::default());
            }

            // Title row 1
            put_centered(
                buf,
                Rect { height: 1, ..area },
                &self.title,
                st(th.foreground, th.panel).add_modifier(Modifier::BOLD),
            );

            // Subtitle row 2
            if let Some(ref sub) = self.subtitle {
                put_centered(
                    buf,
                    Rect {
                        y: area.y + 1,
                        height: 1,
                        ..area
                    },
                    sub,
                    st(th.text_muted, th.panel),
                );
            }

            // Actions row 2 right
            let mut x = area.right();
            state.hits.clear();
            state.hits.resize(self.actions.len(), HitBox::default());
            for (i, act) in self.actions.iter().enumerate().rev() {
                let w = act.len() as u16 + 2;
                x = x.saturating_sub(w + 1);
                let r = Rect {
                    x,
                    y: area.y + 1,
                    width: w,
                    height: 1,
                };
                state.hits[i].set_area(r);
                let bg = if state.hover == Some(i) {
                    th.hover_bg
                } else {
                    th.panel
                };
                fill(buf, r, bg);
                put(
                    buf,
                    x,
                    area.y + 1,
                    &format!(" {} ", act),
                    w,
                    st(th.accent, bg),
                );
            }

            // Clock row 2 or row 0 right
            if self.clock && area.width > 40 {
                let (h, m, s) = local_hms();
                let text = if self.clock_seconds {
                    format!("{:02}:{:02}:{:02}", h, m, s)
                } else {
                    format!("{:02}:{:02}", h, m)
                };
                let clock_w = text.len() as u16 + 2;
                let clock_area = Rect {
                    x: area.right().saturating_sub(clock_w + 1),
                    y: area.y,
                    width: clock_w,
                    height: 1,
                };
                let clock_bg = th.panel.blend(Theme::shade(th.foreground, -1), 0.05);
                fill(buf, clock_area, clock_bg);
                put_centered(buf, clock_area, &text, st(th.foreground, clock_bg));
            }
        } else {
            // Normal: 1 row
            // Icon
            let mut x_offset = 0;
            if let Some(ref icon) = self.icon {
                let icon_area = Rect {
                    x: area.x + 1,
                    y: area.y,
                    width: icon.len() as u16 + 2,
                    height: 1,
                };
                state.icon_hit.set_area(icon_area);
                let icon_bg = if state.icon_hit.hover {
                    th.hover_bg
                } else {
                    th.panel
                };
                fill(buf, icon_area, icon_bg);
                put(
                    buf,
                    area.x + 1,
                    area.y,
                    icon,
                    icon.len() as u16,
                    st(th.foreground, icon_bg),
                );
                x_offset = icon_area.width + 1;
            } else {
                state.icon_hit.set_area(Rect::default());
            }

            let title_text = if let Some(sub) = &self.subtitle {
                format!("{} · {}", self.title, sub)
            } else {
                self.title.clone()
            };
            put_centered(
                buf,
                Rect {
                    x: area.x + x_offset,
                    width: area.width.saturating_sub(x_offset),
                    ..area
                },
                &title_text,
                st(th.foreground, th.panel).add_modifier(Modifier::BOLD),
            );

            // Right text
            if let Some(ref right_text) = self.right {
                put_right(buf, area, right_text, st(th.foreground, th.panel));
            }

            // Actions
            let mut x = area.right();
            state.hits.clear();
            state.hits.resize(self.actions.len(), HitBox::default());
            for (i, act) in self.actions.iter().enumerate().rev() {
                let w = act.len() as u16 + 2;
                x = x.saturating_sub(w + 1);
                let r = Rect {
                    x,
                    y: area.y,
                    width: w,
                    height: 1,
                };
                state.hits[i].set_area(r);
                let bg = if state.hover == Some(i) {
                    th.hover_bg
                } else {
                    th.panel
                };
                fill(buf, r, bg);
                put(buf, x, area.y, &format!(" {} ", act), w, st(th.accent, bg));
            }

            // Clock
            if self.clock && area.width > 40 {
                let (h, m, s) = local_hms();
                let text = if self.clock_seconds {
                    format!("{:02}:{:02}:{:02}", h, m, s)
                } else {
                    format!("{:02}:{:02}", h, m)
                };
                let clock_w = text.len() as u16 + 2;
                let clock_area = Rect {
                    x: area.right().saturating_sub(clock_w + 1),
                    y: area.y,
                    width: clock_w,
                    height: 1,
                };
                let clock_bg = th.panel.blend(Theme::shade(th.foreground, -1), 0.05);
                fill(buf, clock_area, clock_bg);
                put_centered(buf, clock_area, &text, st(th.foreground, clock_bg));
            }
        }
    }
}

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

impl MinSize for AppHeader {
    /// Compact header is 1 row, tall header is 3 rows.
    fn min_size(&self) -> (u16, u16) {
        if self.tall { (8, 3) } else { (8, 1) }
    }
}

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

    #[test]
    fn header_renders_without_panic() {
        let mut state = AppHeaderState::new();
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 1));
        AppHeader::new()
            .title("Test")
            .render(buf.area, &mut buf, &mut state);
    }

    #[test]
    fn header_tall_mode() {
        let mut state = AppHeaderState::new();
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 3));
        let area = buf.area;
        AppHeader::new()
            .title("Test")
            .subtitle("Sub")
            .tall(true)
            .render(area, &mut buf, &mut state);

        // In tall mode, title is on row 0 and subtitle is on row 1
        let row0: String = (0..area.width)
            .map(|x| buf[(x, 0)].symbol().to_string())
            .collect();
        let row1: String = (0..area.width)
            .map(|x| buf[(x, 1)].symbol().to_string())
            .collect();

        assert!(row0.contains("Test"), "{row0}");
        assert!(row1.contains("Sub"), "{row1}");
        assert!(
            !row0.contains("Sub"),
            "title row should not contain subtitle: {row0}"
        );
    }

    #[test]
    fn header_actions_clickable() {
        let mut state = AppHeaderState::new();
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 1));
        AppHeader::new()
            .title("Test")
            .actions(&["Action1", "Action2"])
            .render(buf.area, &mut buf, &mut state);
        assert_eq!(state.hits.len(), 2);
    }
}