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
//!
//! Extensions for ratatui Paragraph.
//!

use crate::_private::NonExhaustive;
use rat_event::{ct_event, flow, HandleEvent, MouseOnly, Outcome, Regular};
use rat_focus::{FocusFlag, HasFocusFlag};
use rat_scrolled::event::ScrollOutcome;
use rat_scrolled::{Scroll, ScrollArea, ScrollAreaState, ScrollState};
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::Style;
use ratatui::text::Text;
use ratatui::widgets::{Block, StatefulWidget, Widget, Wrap};
#[cfg(feature = "unstable-widget-ref")]
use ratatui::widgets::{StatefulWidgetRef, WidgetRef};

/// List widget.
///
/// Fully compatible with ratatui Paragraph.
/// Add Scroll and event-handling.
#[derive(Debug, Default)]
pub struct Paragraph<'a> {
    w: ratatui::widgets::Paragraph<'a>,
    is_wrap: bool,
    block: Option<Block<'a>>,
    vscroll: Option<Scroll<'a>>,
    hscroll: Option<Scroll<'a>>,
}

/// State & event handling.
#[derive(Debug, Clone)]
pub struct ParagraphState {
    /// Full area of the widget.
    pub area: Rect,
    /// Inner area of the widget.
    pub inner: Rect,

    /// Focus
    pub focus: FocusFlag,

    /// Vertical scroll
    pub vscroll: ScrollState,
    /// Horizontal scroll
    pub hscroll: ScrollState,

    pub non_exhaustive: NonExhaustive,
}

impl<'a> Paragraph<'a> {
    pub fn new<T>(text: T) -> Self
    where
        T: Into<Text<'a>>,
    {
        let t = text.into();
        Self {
            w: ratatui::widgets::Paragraph::new(t),
            ..Self::default()
        }
    }

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

    /// Set both hscroll and vscroll.
    pub fn scroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.clone().override_horizontal());
        self.vscroll = Some(scroll.override_vertical());
        self
    }

    /// Set horizontal scroll.
    pub fn hscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.override_horizontal());
        self
    }

    /// Set vertical scroll.
    pub fn vscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.vscroll = Some(scroll.override_vertical());
        self
    }

    /// Base style.
    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
        self.w = self.w.style(style);
        self
    }

    /// Word wrap.
    pub fn wrap(mut self, wrap: Wrap) -> Self {
        self.is_wrap = true;
        self.w = self.w.wrap(wrap);
        self
    }

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

    /// Text alignment.
    pub fn left_aligned(mut self) -> Self {
        self.w = self.w.left_aligned();
        self
    }

    /// Text alignment.
    pub fn centered(mut self) -> Self {
        self.w = self.w.centered();
        self
    }

    /// Text alignment.
    pub fn right_aligned(mut self) -> Self {
        self.w = self.w.right_aligned();
        self
    }
}

impl<'a> Paragraph<'a> {
    fn layout(&self, area: Rect, state: &mut ParagraphState) {
        state.area = area;

        let scroll = ScrollArea::new()
            .block(self.block.clone())
            .h_scroll(self.hscroll.clone())
            .v_scroll(self.vscroll.clone());

        state.inner = scroll.inner(
            area,
            ScrollAreaState {
                area,
                h_scroll: Some(&mut state.hscroll),
                v_scroll: Some(&mut state.vscroll),
            },
        );

        state.hscroll.set_max_offset(if self.is_wrap {
            0
        } else {
            let w = self.w.line_width();
            let d = state.inner.width as usize;
            w.saturating_sub(d)
        });
        state.hscroll.set_page_len(state.inner.width as usize);

        // 4 is an estimate. line_count seems not very accurate.
        let lines = self.w.line_count(area.width) + 4;
        state
            .vscroll
            .set_max_offset(lines.saturating_sub(state.inner.height as usize));
        state.vscroll.set_page_len(state.inner.height as usize);
    }
}

impl<'a> StatefulWidget for Paragraph<'a> {
    type State = ParagraphState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        self.layout(area, state);

        let scroll = ScrollArea::new()
            .block(self.block)
            .h_scroll(self.hscroll)
            .v_scroll(self.vscroll);
        scroll.render(
            area,
            buf,
            &mut ScrollAreaState {
                area,
                h_scroll: Some(&mut state.hscroll),
                v_scroll: Some(&mut state.vscroll),
            },
        );

        self.w
            .scroll((state.vscroll.offset() as u16, state.hscroll.offset() as u16))
            .render(state.inner, buf);
    }
}

#[cfg(feature = "unstable-widget-ref")]
impl<'a> StatefulWidgetRef for Paragraph<'a> {
    type State = ParagraphState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        self.layout(area, state);

        self.block.render_ref(area, buf);
        if let Some(vscroll) = &self.vscroll {
            vscroll.render_ref(state.vscroll.area, buf, &mut state.vscroll);
        }
        if let Some(hscroll) = &self.hscroll {
            hscroll.render_ref(state.hscroll.area, buf, &mut state.hscroll);
        }

        self.w
            .clone()
            .scroll((state.vscroll.offset() as u16, state.hscroll.offset() as u16))
            .render(state.inner, buf);
    }
}

impl HasFocusFlag for ParagraphState {
    fn focus(&self) -> FocusFlag {
        self.focus.clone()
    }

    fn area(&self) -> Rect {
        self.area
    }
}

impl Default for ParagraphState {
    fn default() -> Self {
        Self {
            area: Default::default(),
            inner: Default::default(),
            focus: Default::default(),
            vscroll: Default::default(),
            hscroll: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

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

    pub fn named(name: &str) -> Self {
        Self {
            focus: FocusFlag::named(name),
            ..Self::default()
        }
    }

    /// Current offset.
    pub fn line_offset(&self) -> usize {
        self.vscroll.offset()
    }

    /// Set limited offset.
    pub fn set_line_offset(&mut self, offset: usize) -> bool {
        self.vscroll.set_offset(offset)
    }

    /// Current offset.
    pub fn col_offset(&self) -> usize {
        self.hscroll.offset()
    }

    /// Set limited offset.
    pub fn set_col_offset(&mut self, offset: usize) -> bool {
        self.hscroll.set_offset(offset)
    }

    /// Scroll left by n.
    pub fn scroll_left(&mut self, n: usize) -> bool {
        self.hscroll.scroll_left(n)
    }

    /// Scroll right by n.
    pub fn scroll_right(&mut self, n: usize) -> bool {
        self.hscroll.scroll_right(n)
    }

    /// Scroll up by n.
    pub fn scroll_up(&mut self, n: usize) -> bool {
        self.vscroll.scroll_up(n)
    }

    /// Scroll down by n.
    pub fn scroll_down(&mut self, n: usize) -> bool {
        self.vscroll.scroll_down(n)
    }
}

impl HandleEvent<crossterm::event::Event, Regular, Outcome> for ParagraphState {
    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: Regular) -> Outcome {
        flow!(if self.is_focused() {
            match event {
                ct_event!(keycode press Up) => self.scroll_up(1).into(),
                ct_event!(keycode press Down) => self.scroll_down(1).into(),
                ct_event!(keycode press Left) => self.scroll_left(1).into(),
                ct_event!(keycode press Right) => self.scroll_right(1).into(),
                ct_event!(keycode press PageUp) => self.scroll_up(self.vscroll.page_len()).into(),
                ct_event!(keycode press PageDown) => self.scroll_down(self.vscroll.page_len).into(),
                ct_event!(keycode press Home) => self.set_line_offset(0).into(),
                ct_event!(keycode press End) => self.set_line_offset(1).into(),
                _ => Outcome::Continue,
            }
        } else {
            Outcome::Continue
        });

        self.handle(event, MouseOnly)
    }
}

impl HandleEvent<crossterm::event::Event, MouseOnly, Outcome> for ParagraphState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: MouseOnly) -> Outcome {
        let mut sas = ScrollAreaState {
            area: self.inner,
            h_scroll: Some(&mut self.hscroll),
            v_scroll: Some(&mut self.vscroll),
        };
        match sas.handle(event, MouseOnly) {
            ScrollOutcome::Up(v) => {
                if self.scroll_up(v) {
                    Outcome::Changed
                } else {
                    Outcome::Continue
                }
            }
            ScrollOutcome::Down(v) => {
                if self.scroll_down(v) {
                    Outcome::Changed
                } else {
                    Outcome::Continue
                }
            }
            ScrollOutcome::Left(v) => {
                if self.scroll_left(v) {
                    Outcome::Changed
                } else {
                    Outcome::Continue
                }
            }
            ScrollOutcome::Right(v) => {
                if self.scroll_right(v) {
                    Outcome::Changed
                } else {
                    Outcome::Continue
                }
            }
            ScrollOutcome::VPos(v) => self.set_line_offset(v).into(),
            ScrollOutcome::HPos(v) => self.set_col_offset(v).into(),
            r => r.into(),
        }
    }
}