tui-lipan 0.2.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets 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
//! Toast widget.

use std::sync::Arc;

use unicode_width::UnicodeWidthStr;

use crate::core::element::Element;
use crate::style::{Align, BorderStyle, Length, Padding, Paint, Rect, RichText, Span, Style};
use crate::widgets::frame::EdgeDecoration;
use crate::widgets::text::Overflow;
use crate::widgets::{BorderLabels, Frame, FrameLabel, Text};

pub(crate) const COPY_GLYPH: &str = "";

pub(crate) fn copy_zone_with_right_padding(rect: Rect, right_padding: u16) -> Rect {
    let glyph_width = UnicodeWidthStr::width(COPY_GLYPH).max(1) as u16;
    if rect.w <= glyph_width + 1 + right_padding || rect.h == 0 {
        return Rect {
            x: rect.x,
            y: rect.y,
            w: 0,
            h: 0,
        };
    }

    Rect {
        x: rect.x + rect.w.saturating_sub(glyph_width + 1 + right_padding) as i16,
        y: rect.y,
        w: glyph_width,
        h: 1,
    }
}

/// A transient notification message.
#[derive(Clone)]
pub struct Toast {
    /// Message content.
    pub message: Arc<str>,
    /// Duration in seconds.
    pub duration: f64,
    /// Dismiss when clicked on.
    pub dismiss_on_click: bool,
    /// Show a copy affordance that copies the whole toast message when clicked.
    pub copyable: bool,
    /// Optional visual affordance for copyable toasts.
    pub copy_affordance: ToastCopyAffordance,
    pub(crate) title: Option<Arc<str>>,
    pub(crate) title_prefix: Option<RichText>,
    pub(crate) title_suffix: Option<RichText>,
    pub(crate) title_alignment: Align,
    pub(crate) title_style: Style,
    pub(crate) message_style: Style,
    pub(crate) frame_style: Style,
    pub(crate) border: bool,
    pub(crate) border_style: BorderStyle,
    pub(crate) header_padding: Padding,
    pub(crate) padding: Padding,
    pub(crate) decorations: Vec<EdgeDecoration>,
    pub(crate) width: Length,
    pub(crate) height: Length,
    pub(crate) min_width: Option<Length>,
    pub(crate) max_width: Option<Length>,
    pub(crate) wrap: bool,
}

/// Visual affordance used for copyable toasts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ToastCopyAffordance {
    /// Do not render an explicit copy control. The toast can still be copied by right-clicking it.
    None,
    /// Render the copy glyph in the top border when the toast has a border.
    BorderGlyph,
}

impl Toast {
    /// Create a new toast with the given message.
    pub fn new(message: impl Into<Arc<str>>) -> Self {
        Self {
            message: message.into(),
            duration: 3.0,
            dismiss_on_click: true,
            copyable: false,
            copy_affordance: ToastCopyAffordance::BorderGlyph,
            title: None,
            title_prefix: None,
            title_suffix: None,
            title_alignment: Align::Start,
            title_style: Style::default(),
            message_style: Style::default(),
            frame_style: Style::default(),
            border: true,
            border_style: BorderStyle::Rounded,
            header_padding: Padding::default(),
            padding: Padding::default(),
            decorations: Vec::new(),
            width: Length::Auto,
            height: Length::Auto,
            min_width: None,
            max_width: None,
            wrap: true,
        }
    }

    /// Set duration in seconds.
    pub fn duration(mut self, secs: f64) -> Self {
        self.duration = secs;
        self
    }

    /// Set title.
    pub fn title(mut self, title: Option<impl Into<Arc<str>>>) -> Self {
        self.title = title.map(Into::into);
        self
    }

    /// Set an optional prefix rendered before the title.
    pub fn title_prefix(mut self, prefix: impl Into<RichText>) -> Self {
        self.title_prefix = Some(prefix.into());
        self
    }

    /// Set an optional suffix rendered after the title.
    pub fn title_suffix(mut self, suffix: impl Into<RichText>) -> Self {
        self.title_suffix = Some(suffix.into());
        self
    }

    /// Set the title alignment in the top border.
    pub fn title_alignment(mut self, align: Align) -> Self {
        self.title_alignment = align;
        self
    }

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

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

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

    /// Draw a border.
    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

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

    /// Set padding for the header (title). Top/bottom are ignored.
    pub fn header_padding(mut self, padding: impl Into<Padding>) -> Self {
        self.header_padding = padding.into();
        self
    }

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

    /// Add an edge decoration.
    pub fn decoration(mut self, decoration: EdgeDecoration) -> Self {
        self.decorations.push(decoration);
        self
    }

    /// Replace all edge decorations.
    pub fn decorations(mut self, decorations: Vec<EdgeDecoration>) -> Self {
        self.decorations = decorations;
        self
    }

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

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

    /// Set minimum width.
    pub fn min_width(mut self, width: Length) -> Self {
        self.min_width = Some(width);
        self
    }

    /// Set maximum width (wraps content when exceeded).
    pub fn max_width(mut self, width: Length) -> Self {
        self.max_width = Some(width);
        self
    }

    /// Set whether clicking on the toast dismisses it.
    pub fn dismiss_on_click(mut self, dismiss: bool) -> Self {
        self.dismiss_on_click = dismiss;
        self
    }

    /// Set whether the toast can copy its message.
    ///
    /// Copyable toasts copy their message when right-clicked. When the toast has a border and
    /// [`ToastCopyAffordance::BorderGlyph`] is enabled, they also show a copy glyph that can be
    /// clicked with the left mouse button.
    pub fn copyable(mut self, copyable: bool) -> Self {
        self.copyable = copyable;
        self
    }

    /// Set the optional visual copy affordance for copyable toasts.
    pub fn copy_affordance(mut self, affordance: ToastCopyAffordance) -> Self {
        self.copy_affordance = affordance;
        self
    }

    /// Set whether message text should wrap.
    pub fn wrap(mut self, wrap: bool) -> Self {
        self.wrap = wrap;
        self
    }

    /// Convert to element.
    pub fn into_element(self) -> Element {
        let min_width = self.min_width;
        let max_width = self.max_width;

        // Give the message the frame's background so it reads as one surface - but never a
        // translucent one. The frame has already composited that paint against what it covers;
        // handing the same paint to the text would composite it a second time, over the result,
        // leaving a darker patch behind the words. Left unset, the text simply keeps the surface
        // the frame painted.
        let mut message_style = self.message_style;
        if message_style.bg.is_none()
            && !self
                .frame_style
                .bg
                .is_some_and(|bg| matches!(bg, Paint::Alpha { alpha, .. } if alpha < 255))
        {
            message_style.bg = self.frame_style.bg;
        }

        let overflow = if self.wrap {
            Overflow::Wrap
        } else {
            Overflow::Auto
        };

        let render_copy_affordance = self.copyable
            && self.border
            && matches!(self.copy_affordance, ToastCopyAffordance::BorderGlyph);
        let mut frame = Frame::new()
            .border(self.border)
            .border_style(self.border_style)
            .padding(self.padding)
            .style(self.frame_style)
            .child(
                Text::new(self.message.clone())
                    .style(message_style)
                    .overflow(overflow),
            )
            .width(self.width)
            .height(self.height);

        let title_suffix = if render_copy_affordance {
            let mut suffix = self.title_suffix.clone().unwrap_or_default();
            if !suffix.is_empty() {
                suffix.spans.push(Span::new(" "));
            }
            suffix.spans.push(Span::new(COPY_GLYPH));
            Some(suffix)
        } else {
            self.title_suffix.clone()
        };
        let mut header = BorderLabels::new()
            .padding(self.header_padding)
            .style(self.title_style);
        let mut title = RichText::new();
        if let Some(prefix) = self.title_prefix {
            title.spans.extend(prefix.spans);
        }
        if let Some(title_text) = self.title {
            if !title.is_empty() {
                title.spans.push(Span::new(""));
            }
            title.spans.push(Span::new(title_text));
        }
        if let Some(suffix) = title_suffix {
            if !title.is_empty() {
                title.spans.push(Span::new(""));
            }
            title.spans.extend(suffix.spans);
        }
        if !title.is_empty() {
            let label = FrameLabel::new(title);
            header = match self.title_alignment {
                Align::Center => header.center(label),
                Align::End => header.right(label),
                Align::Start | Align::Stretch => header.left(label),
            };
        }
        if render_copy_affordance {
            header = header.right(FrameLabel::new(COPY_GLYPH));
        }
        frame = frame.header(header);
        if !self.decorations.is_empty() {
            frame = frame.decorations(self.decorations.clone());
        }

        let mut element: Element = frame.into();
        if let Some(min_width) = min_width {
            element = element.min_width(min_width);
        }
        if let Some(max_width) = max_width {
            element = element.max_width(max_width);
        }
        element
    }
}

impl From<Toast> for Element {
    fn from(toast: Toast) -> Self {
        toast.into_element()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::element::ElementKind;

    #[test]
    fn copyable_defaults_to_false() {
        let toast = Toast::new("message");

        assert!(!toast.copyable);
        assert_eq!(toast.copy_affordance, ToastCopyAffordance::BorderGlyph);
    }

    #[test]
    fn copy_zone_tracks_top_right_header_label_cell() {
        let zone = copy_zone_with_right_padding(
            Rect {
                x: 10,
                y: 5,
                w: 20,
                h: 3,
            },
            0,
        );

        assert_eq!(zone.x, 28);
        assert_eq!(zone.y, 5);
        assert_eq!(zone.w, 1);
        assert_eq!(zone.h, 1);
        assert!(zone.contains(28, 5));
        assert!(!zone.contains(29, 5));
        assert!(!zone.contains(28, 6));
    }

    #[test]
    fn copy_zone_accounts_for_header_right_padding() {
        let zone = copy_zone_with_right_padding(
            Rect {
                x: 10,
                y: 5,
                w: 20,
                h: 3,
            },
            2,
        );

        assert_eq!(zone.x, 26);
        assert_eq!(zone.y, 5);
        assert_eq!(zone.w, 1);
        assert_eq!(zone.h, 1);
    }

    #[test]
    fn copyable_borderless_toast_does_not_render_hidden_copy_suffix() {
        let element = Toast::new("message")
            .copyable(true)
            .border(false)
            .into_element();

        let ElementKind::Frame(frame) = element.kind else {
            panic!("toast should lower to a frame");
        };
        assert!(!frame.props.header.has_labels());
    }

    #[test]
    fn copy_affordance_none_does_not_render_copy_suffix() {
        let element = Toast::new("message")
            .copyable(true)
            .copy_affordance(ToastCopyAffordance::None)
            .into_element();

        let ElementKind::Frame(frame) = element.kind else {
            panic!("toast should lower to a frame");
        };
        assert!(!frame.props.header.has_labels());
    }
}