rat-widget 3.0.2

ratatui widgets extended edition
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
//!
//! A simple dialog frame and buttons.
//!
use crate::_private::NonExhaustive;
use crate::button::{Button, ButtonState, ButtonStyle};
use crate::event::{
    ButtonOutcome, ConsumedEvent, Dialog, HandleEvent, Outcome, Regular, ct_event, flow,
};
use crate::focus::{FocusBuilder, FocusFlag, HasFocus};
use crate::layout::{DialogItem, LayoutOuter};
use crate::text::HasScreenCursor;
use crate::util::{block_padding2, reset_buf_area};
use rat_event::MouseOnly;
use rat_reloc::RelocatableState;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Flex, Position, Rect, Size};
use ratatui_core::style::Style;
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_crossterm::crossterm::event::Event;
use ratatui_widgets::block::Block;
use ratatui_widgets::borders::BorderType;

/// Renders the frame and the Ok/Cancel buttons for a dialog window.
///
/// After rendering BaseDialogState::widget_area is available
/// to render any content.
#[derive(Debug, Clone, Default)]
pub struct DialogFrame<'a> {
    block: Block<'a>,
    button_style: ButtonStyle,
    layout: LayoutOuter,
    ok_text: &'a str,
    no_cancel: bool,
    cancel_text: &'a str,
}

/// Combined styles.
#[derive(Debug, Clone)]
pub struct DialogFrameStyle {
    pub style: Style,
    pub block: Option<Block<'static>>,
    pub border_style: Option<Style>,
    pub title_style: Option<Style>,
    pub button_style: Option<ButtonStyle>,
    pub layout: Option<LayoutOuter>,
    pub ok_text: Option<&'static str>,
    pub no_cancel: Option<bool>,
    pub cancel_text: Option<&'static str>,
    pub non_exhaustive: NonExhaustive,
}

impl Default for DialogFrameStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            block: Default::default(),
            border_style: Default::default(),
            title_style: Default::default(),
            button_style: Default::default(),
            layout: Default::default(),
            ok_text: Default::default(),
            no_cancel: Default::default(),
            cancel_text: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

#[derive(Debug, Clone)]
pub struct DialogFrameState {
    /// Area for the dialog.
    /// __read only__ set with each render.
    pub area: Rect,
    /// Area for the dialog-content.
    /// __read only__ set with each render.
    pub widget_area: Rect,

    /// ok-button
    pub ok: ButtonState,
    /// no cancel button
    pub no_cancel: bool,
    /// cancel-button
    pub cancel: ButtonState,

    pub non_exhaustive: NonExhaustive,
}

impl<'a> DialogFrame<'a> {
    pub fn new() -> Self {
        Self {
            block: Block::bordered().border_type(BorderType::Plain),
            button_style: Default::default(),
            layout: LayoutOuter::new()
                .left(Constraint::Percentage(19))
                .top(Constraint::Length(3))
                .right(Constraint::Percentage(19))
                .bottom(Constraint::Length(3)),
            ok_text: "Ok",
            no_cancel: false,
            cancel_text: "Cancel",
        }
    }

    pub fn styles(mut self, styles: DialogFrameStyle) -> Self {
        if let Some(block) = styles.block {
            self.block = block;
        }
        self.block = self.block.style(styles.style);
        if let Some(border_style) = styles.border_style {
            self.block = self.block.border_style(border_style);
        }
        if let Some(title_style) = styles.title_style {
            self.block = self.block.title_style(title_style);
        }
        if let Some(button_style) = styles.button_style {
            self.button_style = button_style;
        }
        if let Some(layout) = styles.layout {
            self.layout = layout;
        }
        if let Some(ok_text) = styles.ok_text {
            self.ok_text = ok_text;
        }
        if let Some(no_cancel) = styles.no_cancel {
            self.no_cancel = no_cancel;
        }
        if let Some(cancel_text) = styles.cancel_text {
            self.cancel_text = cancel_text;
        }
        self
    }

    /// Base style for the dialog.
    pub fn style(mut self, style: Style) -> Self {
        self.block = self.block.style(style);
        self
    }

    /// Block for the dialog.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = block;
        self
    }

    /// Sets the border-style for the Block, if any.
    pub fn border_style(mut self, style: Style) -> Self {
        self.block = self.block.border_style(style);
        self
    }

    /// Sets the title-style for the Block, if any.
    pub fn title_style(mut self, style: Style) -> Self {
        self.block = self.block.title_style(style);
        self
    }

    /// Button style.
    pub fn button_style(mut self, style: ButtonStyle) -> Self {
        self.button_style = style;
        self
    }

    /// Ok text.
    pub fn ok_text(mut self, str: &'a str) -> Self {
        self.ok_text = str;
        self
    }

    /// No cancel button.
    pub fn no_cancel(mut self) -> Self {
        self.no_cancel = true;
        self
    }

    /// Cancel text.
    pub fn cancel_text(mut self, str: &'a str) -> Self {
        self.cancel_text = str;
        self
    }

    /// Margin constraint for the left side.
    pub fn left(mut self, left: Constraint) -> Self {
        self.layout = self.layout.left(left);
        self
    }

    /// Margin constraint for the top side.
    pub fn top(mut self, top: Constraint) -> Self {
        self.layout = self.layout.top(top);
        self
    }

    /// Margin constraint for the right side.
    pub fn right(mut self, right: Constraint) -> Self {
        self.layout = self.layout.right(right);
        self
    }

    /// Margin constraint for the bottom side.
    pub fn bottom(mut self, bottom: Constraint) -> Self {
        self.layout = self.layout.bottom(bottom);
        self
    }

    /// Put at a fixed position.
    pub fn position(mut self, pos: Position) -> Self {
        self.layout = self.layout.position(pos);
        self
    }

    /// Constraint for the width.
    pub fn width(mut self, width: Constraint) -> Self {
        self.layout = self.layout.width(width);
        self
    }

    /// Constraint for the height.
    pub fn height(mut self, height: Constraint) -> Self {
        self.layout = self.layout.height(height);
        self
    }

    /// Set at a fixed size.
    pub fn size(mut self, size: Size) -> Self {
        self.layout = self.layout.size(size);
        self
    }

    /// Calculate the resulting dialog area.
    /// Returns the inner area that is available for drawing widgets.
    pub fn layout_size(&self, area: Rect) -> Rect {
        let l_dlg = if self.no_cancel {
            self.layout.layout_dialog(
                area,
                block_padding2(&self.block),
                [Constraint::Length(10)],
                1,
                Flex::End,
            )
        } else {
            self.layout.layout_dialog(
                area,
                block_padding2(&self.block),
                [Constraint::Length(12), Constraint::Length(10)],
                1,
                Flex::End,
            )
        };
        l_dlg.widget_for(DialogItem::Content)
    }
}

impl<'a> StatefulWidget for DialogFrame<'a> {
    type State = DialogFrameState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let l_dlg = if self.no_cancel {
            self.layout.layout_dialog(
                area,
                block_padding2(&self.block),
                [Constraint::Length(10)],
                1,
                Flex::End,
            )
        } else {
            self.layout.layout_dialog(
                area,
                block_padding2(&self.block),
                [Constraint::Length(12), Constraint::Length(10)],
                1,
                Flex::End,
            )
        };
        state.area = l_dlg.area();
        state.widget_area = l_dlg.widget_for(DialogItem::Content);
        state.no_cancel = self.no_cancel;

        reset_buf_area(l_dlg.area(), buf);
        self.block.render(state.area, buf);

        if self.no_cancel {
            Button::new(self.ok_text).styles(self.button_style).render(
                l_dlg.widget_for(DialogItem::Button(0)),
                buf,
                &mut state.ok,
            );
        } else {
            Button::new(self.cancel_text)
                .styles(self.button_style.clone())
                .render(
                    l_dlg.widget_for(DialogItem::Button(0)),
                    buf,
                    &mut state.cancel,
                );
            Button::new(self.ok_text).styles(self.button_style).render(
                l_dlg.widget_for(DialogItem::Button(1)),
                buf,
                &mut state.ok,
            );
        }
    }
}

impl Default for DialogFrameState {
    fn default() -> Self {
        let z = Self {
            area: Default::default(),
            widget_area: Default::default(),
            ok: Default::default(),
            no_cancel: Default::default(),
            cancel: Default::default(),
            non_exhaustive: NonExhaustive,
        };
        z.ok.focus.set(true);
        z
    }
}

impl HasFocus for DialogFrameState {
    fn build(&self, builder: &mut FocusBuilder) {
        builder.widget(&self.ok);
        if !self.no_cancel {
            builder.widget(&self.cancel);
        }
    }

    fn focus(&self) -> FocusFlag {
        unimplemented!()
    }

    fn area(&self) -> Rect {
        unimplemented!()
    }
}

impl HasScreenCursor for DialogFrameState {
    fn screen_cursor(&self) -> Option<(u16, u16)> {
        None
    }
}

impl RelocatableState for DialogFrameState {
    fn relocate(&mut self, shift: (i16, i16), clip: Rect) {
        self.area.relocate(shift, clip);
        self.widget_area.relocate(shift, clip);
        self.ok.relocate(shift, clip);
        self.cancel.relocate(shift, clip);
    }
}

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

    pub fn named(_name: &str) -> Self {
        Self::default()
    }
}

/// Result type for event-handling.
pub enum DialogOutcome {
    /// Continue with event-handling.
    /// In the event-loop this waits for the next event.
    Continue,
    /// Break event-handling without repaint.
    /// In the event-loop this waits for the next event.
    Unchanged,
    /// Break event-handling and repaints/renders the application.
    /// In the event-loop this calls `render`.
    Changed,
    /// Ok pressed
    Ok,
    /// Cancel pressed
    Cancel,
}

impl ConsumedEvent for DialogOutcome {
    fn is_consumed(&self) -> bool {
        !matches!(self, DialogOutcome::Continue)
    }
}

impl From<DialogOutcome> for Outcome {
    fn from(value: DialogOutcome) -> Self {
        match value {
            DialogOutcome::Continue => Outcome::Continue,
            DialogOutcome::Unchanged => Outcome::Unchanged,
            DialogOutcome::Changed => Outcome::Changed,
            DialogOutcome::Ok => Outcome::Changed,
            DialogOutcome::Cancel => Outcome::Changed,
        }
    }
}

impl From<Outcome> for DialogOutcome {
    fn from(value: Outcome) -> Self {
        match value {
            Outcome::Continue => DialogOutcome::Continue,
            Outcome::Unchanged => DialogOutcome::Unchanged,
            Outcome::Changed => DialogOutcome::Changed,
        }
    }
}

impl HandleEvent<Event, Dialog, DialogOutcome> for DialogFrameState {
    fn handle(&mut self, event: &Event, _: Dialog) -> DialogOutcome {
        flow!({
            if !self.no_cancel {
                match self.cancel.handle(event, Regular) {
                    ButtonOutcome::Pressed => DialogOutcome::Cancel,
                    r => Outcome::from(r).into(),
                }
            } else {
                DialogOutcome::Continue
            }
        });
        flow!(match self.ok.handle(event, Regular) {
            ButtonOutcome::Pressed => {
                DialogOutcome::Ok
            }
            r => Outcome::from(r).into(),
        });

        flow!(match event {
            ct_event!(keycode press Esc) if !self.no_cancel => {
                DialogOutcome::Cancel
            }
            ct_event!(keycode press Enter) | ct_event!(keycode press F(12)) => {
                DialogOutcome::Ok
            }
            _ => DialogOutcome::Unchanged,
        });

        DialogOutcome::Unchanged
    }
}

impl HandleEvent<Event, MouseOnly, DialogOutcome> for DialogFrameState {
    fn handle(&mut self, event: &Event, _: MouseOnly) -> DialogOutcome {
        flow!({
            if !self.no_cancel {
                match self.cancel.handle(event, MouseOnly) {
                    ButtonOutcome::Pressed => DialogOutcome::Cancel,
                    r => Outcome::from(r).into(),
                }
            } else {
                DialogOutcome::Continue
            }
        });
        flow!(match self.ok.handle(event, MouseOnly) {
            ButtonOutcome::Pressed => {
                DialogOutcome::Ok
            }
            r => Outcome::from(r).into(),
        });

        DialogOutcome::Unchanged
    }
}

/// Handle events for the popup.
/// Call before other handlers to deal with intersections
/// with other widgets.
pub fn handle_events(state: &mut DialogFrameState, _focus: bool, event: &Event) -> DialogOutcome {
    HandleEvent::handle(state, event, Dialog)
}

/// Handle only mouse-events.
pub fn handle_mouse_events(state: &mut DialogFrameState, event: &Event) -> DialogOutcome {
    HandleEvent::handle(state, event, MouseOnly)
}