rat_popup/
popup.rs

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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use crate::PopupConstraint;
use crate::_private::NonExhaustive;
use crate::event::PopupOutcome;
use rat_event::util::MouseFlags;
use rat_event::{ct_event, HandleEvent, Popup};
use rat_focus::{ContainerFlag, FocusContainer};
use rat_scrolled::{Scroll, ScrollArea, ScrollAreaState, ScrollState, ScrollStyle};
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::prelude::BlockExt;
use ratatui::style::Style;
#[cfg(feature = "unstable-widget-ref")]
use ratatui::widgets::StatefulWidgetRef;
use ratatui::widgets::{Block, StatefulWidget};

/// Provides the core for popup widgets.
///
/// This does widget can calculate the placement of a popup widget
/// using the [placement](PopupCore::constraint), [offset](PopupCore::offset)
/// and the outer [boundary](PopupCore::boundary).
///
/// It provides the widget area as [widget_area](PopupCoreState::widget_area).
/// It's up to the user to render the actual content for the popup.
///
/// ## Event handling
///
/// The widget will detect any suspicious mouse activity outside its bounds
/// and returns [PopupOutcome::Hide] if it finds such.
///
/// The widget doesn't change its active/visible state by itself,
/// it's up to the caller to do this.
///
/// __See__
/// See the examples some variants.
///
#[derive(Debug, Clone)]
pub struct PopupCore<'a> {
    style: Style,

    constraint: PopupConstraint,
    offset: (i16, i16),
    boundary_area: Option<Rect>,

    block: Option<Block<'a>>,
    h_scroll: Option<Scroll<'a>>,
    v_scroll: Option<Scroll<'a>>,
}

/// Complete styles for the popup.
#[derive(Debug, Clone)]
pub struct PopupStyle {
    /// Baseline style.
    pub style: Style,
    /// Extra offset added after applying the constraints.
    pub offset: Option<(i16, i16)>,
    /// Block for the popup.
    pub block: Option<Block<'static>>,
    /// Style for scroll bars.
    pub scroll: Option<ScrollStyle>,

    /// non-exhaustive struct.
    pub non_exhaustive: NonExhaustive,
}

#[derive(Debug, Clone)]
pub struct PopupCoreState {
    /// Area for the widget.
    /// This is the area given to render(), corrected by the
    /// given constraints.
    /// __read only__. renewed for each render.
    pub area: Rect,
    /// Area where the widget can render it's content.
    /// __read only__. renewed for each render.
    pub widget_area: Rect,

    /// Horizontal scroll state if active.
    /// __read+write__
    pub h_scroll: ScrollState,
    /// Vertical scroll state if active.
    /// __read+write__
    pub v_scroll: ScrollState,

    /// Active flag for the popup.
    ///
    /// Uses a ContainerFlag that can be combined with the FocusFlags
    /// your widget uses for handling its focus to detect the
    /// transition 'Did the popup loose focus and should it be closed now'.
    ///
    /// If you don't rely on Focus this way, this will just be a boolean
    /// flag that indicates active/visible.
    ///
    /// __See__
    /// See the examples how to use for both cases.
    /// __read+write__
    pub active: ContainerFlag,

    /// Mouse flags.
    /// __read+write__
    pub mouse: MouseFlags,

    /// non-exhaustive struct.
    pub non_exhaustive: NonExhaustive,
}

impl<'a> Default for PopupCore<'a> {
    fn default() -> Self {
        Self {
            style: Default::default(),
            constraint: PopupConstraint::None,
            offset: (0, 0),
            boundary_area: None,
            block: None,
            h_scroll: None,
            v_scroll: None,
        }
    }
}

impl<'a> PopupCore<'a> {
    /// New.
    pub fn new() -> Self {
        Self::default()
    }

    /// Placement of the popup widget.
    /// See placement for the options.
    pub fn constraint(mut self, constraint: PopupConstraint) -> Self {
        self.constraint = constraint;
        self
    }

    /// Adds an extra offset to the widget area.
    ///
    /// This can be used to
    /// * place the widget under the mouse cursor.
    /// * align the widget not by the outer bounds but by
    ///   the text content.
    pub fn offset(mut self, offset: (i16, i16)) -> Self {
        self.offset = offset;
        self
    }

    /// Sets only the x offset.
    /// See [offset](Self::offset)
    pub fn x_offset(mut self, offset: i16) -> Self {
        self.offset.0 = offset;
        self
    }

    /// Sets only the y offset.
    /// See [offset](Self::offset)
    pub fn y_offset(mut self, offset: i16) -> Self {
        self.offset.1 = offset;
        self
    }

    /// Sets outer boundaries for the resulting widget.
    ///
    /// This will be used to ensure that the widget is fully visible,
    /// after calculation its position using the other parameters.
    ///
    /// If not set it will use [Buffer::area] for this.
    pub fn boundary(mut self, boundary: Rect) -> Self {
        self.boundary_area = Some(boundary);
        self
    }

    /// Sets outer boundaries for the resulting widget.
    ///
    /// This will be used to ensure that the widget is fully visible,
    /// after calculation its position using the other parameters.
    ///
    /// If not set it will use [Buffer::area] for this.
    pub fn boundary_opt(mut self, boundary: Option<Rect>) -> Self {
        self.boundary_area = boundary;
        self
    }

    /// Set styles
    pub fn styles(mut self, styles: PopupStyle) -> Self {
        self.style = styles.style;
        if let Some(offset) = styles.offset {
            self.offset = offset;
        }
        if let Some(block) = styles.block {
            self.block = Some(block);
        }
        if let Some(styles) = styles.scroll {
            if let Some(h_scroll) = self.h_scroll {
                self.h_scroll = Some(h_scroll.styles(styles.clone()));
            }
            if let Some(v_scroll) = self.v_scroll {
                self.v_scroll = Some(v_scroll.styles(styles));
            }
        }
        self
    }

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

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

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

    /// Horizontal scroll
    pub fn h_scroll(mut self, h_scroll: Scroll<'a>) -> Self {
        self.h_scroll = Some(h_scroll);
        self
    }

    /// Horizontal scroll
    pub fn h_scroll_opt(mut self, h_scroll: Option<Scroll<'a>>) -> Self {
        self.h_scroll = h_scroll;
        self
    }

    /// Vertical scroll
    pub fn v_scroll(mut self, v_scroll: Scroll<'a>) -> Self {
        self.v_scroll = Some(v_scroll);
        self
    }

    /// Vertical scroll
    pub fn v_scroll_opt(mut self, v_scroll: Option<Scroll<'a>>) -> Self {
        self.v_scroll = v_scroll;
        self
    }

    /// Get the padding the block imposes as a Size.
    pub fn get_block_size(&self) -> Size {
        let area = Rect::new(0, 0, 20, 20);
        let inner = self.block.inner_if_some(area);
        Size {
            width: (inner.left() - area.left()) + (area.right() - inner.right()),
            height: (inner.top() - area.top()) + (area.bottom() - inner.bottom()),
        }
    }
}

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

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        if !state.active.is_container_focused() {
            state.clear_areas();
            return;
        }
        self.layout(area, self.boundary_area.unwrap_or(buf.area), state);
        clear_area(area, self.style, buf);

        let mut scroll_area_state = ScrollAreaState {
            area,
            h_scroll: Some(&mut state.h_scroll),
            v_scroll: Some(&mut state.v_scroll),
        };

        let scroll_area = ScrollArea::new()
            .block(self.block.clone()) // todo: clones?
            .h_scroll(self.h_scroll.clone())
            .v_scroll(self.v_scroll.clone());

        state.widget_area = scroll_area.inner(
            area,
            ScrollAreaState::new()
                .h_scroll(&mut state.h_scroll)
                .v_scroll(&mut state.v_scroll),
        );

        scroll_area.render(area, buf, &mut scroll_area_state);
    }
}

impl<'a> StatefulWidget for PopupCore<'a> {
    type State = PopupCoreState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        if !state.active.is_container_focused() {
            state.clear_areas();
            return;
        }
        self.layout(area, self.boundary_area.unwrap_or(buf.area), state);

        clear_area(state.area, self.style, buf);

        let scroll_area = ScrollArea::new()
            .block(self.block)
            .h_scroll(self.h_scroll)
            .v_scroll(self.v_scroll);

        state.widget_area = scroll_area.inner(
            state.area,
            ScrollAreaState {
                area: Default::default(),
                h_scroll: Some(&mut state.h_scroll),
                v_scroll: Some(&mut state.v_scroll),
            },
        );

        scroll_area.render(
            state.area,
            buf,
            &mut ScrollAreaState {
                area: Default::default(),
                h_scroll: Some(&mut state.h_scroll),
                v_scroll: Some(&mut state.v_scroll),
            },
        );
    }
}

fn clear_area(area: Rect, style: Style, buf: &mut Buffer) {
    for y in area.top()..area.bottom() {
        for x in area.left()..area.right() {
            if let Some(cell) = buf.cell_mut((x, y)) {
                cell.reset();
                cell.set_style(style);
            }
        }
    }
}

impl<'a> PopupCore<'a> {
    fn layout(&self, area: Rect, boundary_area: Rect, state: &mut PopupCoreState) {
        // helper fn
        fn center(len: u16, within: u16) -> u16 {
            ((within as i32 - len as i32) / 2).clamp(0, i16::MAX as i32) as u16
        }
        let middle = center;
        fn right(len: u16, within: u16) -> u16 {
            within.saturating_sub(len)
        }
        let bottom = right;

        let mut area = match self.constraint {
            PopupConstraint::None => area,
            PopupConstraint::Above(rel) | PopupConstraint::AboveLeft(rel) => Rect::new(
                rel.x,
                rel.y.saturating_sub(area.height),
                area.width,
                area.height,
            ),
            PopupConstraint::AboveCenter(rel) => Rect::new(
                rel.x + center(area.width, rel.width),
                rel.y.saturating_sub(area.height),
                area.width,
                area.height,
            ),
            PopupConstraint::AboveRight(rel) => Rect::new(
                rel.x + right(area.width, rel.width),
                rel.y.saturating_sub(area.height),
                area.width,
                area.height,
            ),
            PopupConstraint::Below(rel) | PopupConstraint::BelowLeft(rel) => Rect::new(
                rel.x, //
                rel.bottom(),
                area.width,
                area.height,
            ),
            PopupConstraint::BelowCenter(rel) => Rect::new(
                rel.x + center(area.width, rel.width),
                rel.bottom(),
                area.width,
                area.height,
            ),
            PopupConstraint::BelowRight(rel) => Rect::new(
                rel.x + right(area.width, rel.width),
                rel.bottom(),
                area.width,
                area.height,
            ),

            PopupConstraint::Left(rel) | PopupConstraint::LeftTop(rel) => Rect::new(
                rel.x.saturating_sub(area.width),
                rel.y,
                area.width,
                area.height,
            ),
            PopupConstraint::LeftMiddle(rel) => Rect::new(
                rel.x.saturating_sub(area.width),
                rel.y + middle(area.height, rel.height),
                area.width,
                area.height,
            ),
            PopupConstraint::LeftBottom(rel) => Rect::new(
                rel.x.saturating_sub(area.width),
                rel.y + bottom(area.height, rel.height),
                area.width,
                area.height,
            ),
            PopupConstraint::Right(rel) | PopupConstraint::RightTop(rel) => Rect::new(
                rel.right(), //
                rel.y,
                area.width,
                area.height,
            ),
            PopupConstraint::RightMiddle(rel) => Rect::new(
                rel.right(),
                rel.y + middle(area.height, rel.height),
                area.width,
                area.height,
            ),
            PopupConstraint::RightBottom(rel) => Rect::new(
                rel.right(),
                rel.y + bottom(area.height, rel.height),
                area.width,
                area.height,
            ),

            PopupConstraint::Position(x, y) => Rect::new(
                x, //
                y,
                area.width,
                area.height,
            ),

            PopupConstraint::AboveOrBelow(rel) => {
                if area.height.saturating_add_signed(-self.offset.1) < rel.y {
                    Rect::new(
                        rel.x,
                        rel.y.saturating_sub(area.height),
                        area.width,
                        area.height,
                    )
                } else {
                    Rect::new(
                        rel.x, //
                        rel.bottom(),
                        area.width,
                        area.height,
                    )
                }
            }
            PopupConstraint::BelowOrAbove(rel) => {
                if (rel.bottom() + area.height).saturating_add_signed(self.offset.1)
                    <= boundary_area.height
                {
                    Rect::new(
                        rel.x, //
                        rel.bottom(),
                        area.width,
                        area.height,
                    )
                } else {
                    Rect::new(
                        rel.x,
                        rel.y.saturating_sub(area.height),
                        area.width,
                        area.height,
                    )
                }
            }
        };

        // offset
        area.x = area.x.saturating_add_signed(self.offset.0);
        area.y = area.y.saturating_add_signed(self.offset.1);

        // keep in sight
        if area.left() < boundary_area.left() {
            let corr = boundary_area.left().saturating_sub(area.left());
            area.x += corr;
        }
        if area.right() >= boundary_area.right() {
            let corr = area.right().saturating_sub(boundary_area.right());
            area.x = area.x.saturating_sub(corr);
        }
        if area.top() < boundary_area.top() {
            let corr = boundary_area.top().saturating_sub(area.top());
            area.y += corr;
        }
        if area.bottom() >= boundary_area.bottom() {
            let corr = area.bottom().saturating_sub(boundary_area.bottom());
            area.y = area.y.saturating_sub(corr);
        }

        // shrink to size
        if area.right() > boundary_area.right() {
            let corr = area.right() - boundary_area.right();
            area.width = area.width.saturating_sub(corr);
        }
        if area.bottom() > boundary_area.bottom() {
            let corr = area.bottom() - boundary_area.bottom();
            area.height = area.height.saturating_sub(corr);
        }

        state.area = area;
    }
}

impl Default for PopupStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            offset: None,
            block: None,
            scroll: None,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl Default for PopupCoreState {
    fn default() -> Self {
        Self {
            area: Default::default(),
            widget_area: Default::default(),
            h_scroll: Default::default(),
            v_scroll: Default::default(),
            active: ContainerFlag::named("popup"),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl PopupCoreState {
    /// New
    #[inline]
    pub fn new() -> Self {
        Default::default()
    }

    /// New with a focus name.
    pub fn named(name: &str) -> Self {
        Self {
            active: ContainerFlag::named(name),
            ..Default::default()
        }
    }

    /// Is the popup active/visible.
    pub fn is_active(&self) -> bool {
        self.active.is_container_focused()
    }

    /// Flip visibility of the popup.
    pub fn flip_active(&mut self) {
        self.set_active(!self.active.get());
    }

    /// Show the popup.
    ///
    /// If the popup is hidden this will clear all the areas.
    pub fn set_active(&mut self, active: bool) {
        self.active.set(active);
        if !active {
            // reset all extra flags too.
            self.active.clear();
            self.clear_areas();
        }
    }

    /// Clear the areas.
    pub fn clear_areas(&mut self) {
        self.area = Default::default();
        self.widget_area = Default::default();
        self.v_scroll.area = Default::default();
        self.h_scroll.area = Default::default();
    }
}

impl HandleEvent<crossterm::event::Event, Popup, PopupOutcome> for PopupCoreState {
    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: Popup) -> PopupOutcome {
        // this only works out if the active flag is actually used
        // as a container flag. but that's fine.

        // TODO: this is too spooky ...
        // let r0 = if self.active.container_lost_focus() {
        //     PopupOutcome::Hide
        // } else {
        //     PopupOutcome::Continue
        // };

        if self.is_active() {
            match event {
                ct_event!(mouse down Left for x,y)
                | ct_event!(mouse down Right for x,y)
                | ct_event!(mouse down Middle for x,y)
                    if !self.area.contains((*x, *y).into()) =>
                {
                    PopupOutcome::Hide
                }
                _ => PopupOutcome::Continue,
            }
        } else {
            PopupOutcome::Continue
        }
    }
}