quvyta-framework 0.1.34

A Rust framework for building terminal applications
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Vertical scrolling of any content.

use std::time::Duration;

use crate::event::{Event, KeyEvent, KeyKind, MouseButton, MouseKind};
use crate::geometry::{Rect, Size, clamp_u16};
use crate::keymap::{Key, KeyChord, Modifiers};
use crate::motion::Easing;
use crate::widget::{Axis, Container, EventCx, Flex, Length, MeasureCx, Node, PaintCx, Widget, WidgetId};

use super::rows::{self, WHEEL_ROWS};
use super::scrollbar::{self, ScrollMetrics, ScrollbarStyle};

/// Shows content taller than its area and scrolls it with the wheel, the scrollbar or the
/// keyboard (↑/↓, PgUp/PgDn, Space/Shift+Space, Home/End while focused). When focus moves to a
/// widget inside that is out of view, the view scrolls to it. When a widget inside asks to show
/// a part of itself with [`PaintCx::reveal`], such as a code view going to a line, the view glides
/// just far enough to show it, or jumps there when motion is reduced.
///
/// Space pages down and Shift+Space pages back, the way a person reads long text in a browser or
/// a viewer. A focused widget inside that uses Space for its own keeps it, and an application that
/// binds Space to an action of its own keeps it too, so a music player playing while its lyrics
/// scroll keeps play and pause on Space and pages with the page keys.
///
/// With [`ScrollView::follow_end`] the view keeps the end of growing content in view, for a
/// conversation or command output that arrives while the person watches.
///
/// Style keys: `scrollbar` (`style`, `track`, `thumb`) with `hover`, and `scrollbar.<style>`;
/// `log-more` for the rows-below note of a view that stopped following. Framework string:
/// `quvyta.log.below`.
pub struct ScrollView<Msg> {
    content: Vec<Node<Msg>>,
    scrollbar: Option<ScrollbarStyle>,
    follow_end: bool,
}

#[derive(Debug, Default)]
struct ScrollMemory {
    offset: u16,
    content_height: u16,
    revealed: Option<WidgetId>,
    dragging: bool,
    /// A move towards an area a widget asked to reveal, or towards the end, while it runs.
    glide: Option<Glide>,
    /// Whether the person moved away from the end, so growth no longer follows it.
    detached: bool,
    /// Whether a frame was painted yet: the first one opens at the end without gliding.
    painted: bool,
    /// Where the rows-below note was painted in the last frame; a click on it follows the end.
    note: Option<Rect>,
}

impl ScrollMemory {
    /// Records a move from offset `from` to offset `to`, where `max` is the end: reaching the
    /// end follows it again, and any move up from `from` stops following. A move down that
    /// stops short of the end changes nothing, so a key pressed while the view glides to the
    /// end keeps following.
    fn moved(&mut self, from: u16, to: u16, max: u16) {
        if to >= max {
            self.detached = false;
        } else if to < from {
            self.detached = true;
        }
    }
}

/// A scroll from one offset to another that started at `start`.
#[derive(Debug, Clone, Copy)]
struct Glide {
    from: u16,
    to: u16,
    start: Duration,
}

/// The offset that shows the content rows `top..bottom` in a view `height` rows tall, moving
/// the least from `offset`: an area already in view, or covering the whole view, stays put.
fn offset_showing(top: i32, bottom: i32, offset: u16, height: u16) -> u16 {
    let (start, end) = (i32::from(offset), i32::from(offset) + i32::from(height));
    if top >= start && bottom <= end || top <= start && bottom >= end {
        offset
    } else if top < start || bottom - top > i32::from(height) {
        clamp_u16(top)
    } else {
        clamp_u16(bottom - i32::from(height))
    }
}

impl<Msg: 'static> ScrollView<Msg> {
    /// An empty scroll view; add content with [`View::add_with`](crate::widget::View::add_with).
    #[must_use]
    pub fn new() -> Self {
        Self { content: vec![Node::new(Flex::new(Axis::Column, Vec::new()), 0)], scrollbar: None, follow_end: false }
    }

    /// Draws the scrollbar in `style` whatever the theme chooses.
    #[must_use]
    pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self {
        self.scrollbar = Some(style);
        self
    }

    /// Keeps the end of the content in view while it grows, as long as the person is at the end.
    ///
    /// The first frame opens at the end. When the content grows, the view glides to the new end
    /// over the theme's `page` duration, or jumps there when motion is reduced. Scrolling up with
    /// the wheel, the keys or the scrollbar stops following, and a faint note at the bottom
    /// counts the rows below; End, scrolling back to the bottom or a click on the note follows
    /// again. Content that fits the view always counts as at the end.
    ///
    /// Focus keeps its usual pull: a widget inside that takes focus is scrolled into view. When
    /// that move leaves the end, it stops following just as scrolling up does, so focusing
    /// something earlier in the content holds it in view; when the focused widget sits at the
    /// end, such as a reply field below a conversation, the view keeps following and the field
    /// stays in view as the content grows. An area a widget asks to reveal follows the same rule.
    ///
    /// ```
    /// use qframe::prelude::*;
    /// use qframe::widgets::ScrollView;
    ///
    /// struct Chat(Vec<String>);
    ///
    /// impl App for Chat {
    ///     type Msg = String;
    ///     fn update(&mut self, line: String) -> Command<String> {
    ///         self.0.push(line);
    ///         Command::none()
    ///     }
    ///     fn view(&self, ui: &mut View<'_, String>) {
    ///         ui.add_with(ScrollView::new().follow_end(true), |ui| {
    ///             for line in &self.0 {
    ///                 ui.add(Text::new(line.clone()));
    ///             }
    ///         })
    ///         .fill();
    ///     }
    /// }
    ///
    /// let lines = (1..=9).map(|n| format!("line {n}")).collect();
    /// let mut h = Harness::new(Chat(lines), 20, 3);
    /// assert!(h.screen().contains("line 9"), "the first frame opens at the end");
    /// h.set_reduced_motion(true).send("line 10".to_owned());
    /// assert!(h.screen().contains("line 10"));
    /// ```
    #[must_use]
    pub fn follow_end(mut self, follow: bool) -> Self {
        self.follow_end = follow;
        self
    }

    fn metrics(memory: &ScrollMemory, area: Rect) -> ScrollMetrics {
        ScrollMetrics {
            total: usize::from(memory.content_height),
            visible: usize::from(area.height),
            offset: usize::from(memory.offset),
        }
    }

    fn scroll_to(cx: &mut EventCx<'_, Msg>, offset: i32) {
        let area = cx.area();
        let memory = cx.memory::<ScrollMemory>();
        let max = memory.content_height.saturating_sub(area.height);
        let from = memory.offset;
        memory.offset = clamp_u16(offset).min(max);
        memory.glide = None;
        memory.moved(from, memory.offset, max);
    }

    /// Whether `key` pages up as a person reading long text does: PgUp, and the Shift+Space
    /// that pages back with it in browsers and viewers.
    fn is_page_up(cx: &EventCx<'_, Msg>, key: &KeyEvent) -> bool {
        let shifted = KeyChord { key: Key::Space, mods: Modifiers { shift: true, ..Modifiers::default() } };
        key.is_plain(Key::PageUp) || Self::is_space(cx, key, shifted)
    }

    /// Whether `key` pages down as a person reading long text does: PgDn, and the Space that
    /// pages with it in browsers and viewers.
    fn is_page_down(cx: &EventCx<'_, Msg>, key: &KeyEvent) -> bool {
        key.is_plain(Key::PageDown) || Self::is_space(cx, key, KeyChord::plain(Key::Space))
    }

    /// Whether `key` is a press of `chord` and the keymap in force does not give it to the
    /// application. A music player that binds Space to play and pause keeps it while its scroll
    /// view of lyrics has focus, and the person reads on with the page keys.
    fn is_space(cx: &EventCx<'_, Msg>, key: &KeyEvent, chord: KeyChord) -> bool {
        key.kind != KeyKind::Release && key.chord == chord && !cx.is_reserved(&key.chord)
    }

    /// Heads for the end `max` unless the person moved away from it: at once on the first frame
    /// or with reduced motion, otherwise as a glide from where the view is.
    fn follow(cx: &mut PaintCx<'_>, max: u16) {
        let reduced = cx.reduced_motion();
        let now = cx.now();
        let memory = cx.memory::<ScrollMemory>();
        let first = !std::mem::replace(&mut memory.painted, true);
        if max == 0 || memory.glide.is_none() && memory.offset >= max {
            memory.detached = false;
        }
        let heading = memory.glide.map_or(memory.offset, |glide| glide.to);
        if memory.detached || heading == max {
            return;
        }
        if first || reduced {
            memory.offset = max;
            memory.glide = None;
        } else {
            memory.glide = Some(Glide { from: memory.offset, to: max, start: now });
        }
    }

    /// Moves along a running glide and returns the offset to paint at.
    fn glide(cx: &mut PaintCx<'_>, offset: u16, max: u16) -> u16 {
        let Some(glide) = cx.memory::<ScrollMemory>().glide else {
            return offset;
        };
        let duration = cx.env().theme().motion().page;
        let progress = cx.progress_since(glide.start, duration, Easing::EaseOut);
        let (from, to) = (f32::from(glide.from), f32::from(glide.to));
        // The offsets are u16, so the rounded value between them fits.
        let now = (from + (to - from) * progress).round() as u16;
        let memory = cx.memory::<ScrollMemory>();
        memory.offset = now.min(max);
        if progress >= 1.0 {
            memory.glide = None;
        }
        memory.offset
    }

    /// The offset that shows `focused`, whose area is `rect`, having just taken the focus. A
    /// widget clicked into is where the person already looks, so a click never scrolls. A widget
    /// that names where the keyboard is inside it ([`PaintCx::focus_spot`]) is shown there; one
    /// taller than the view that is already partly on screen stays where it is, rather than the
    /// view jumping to its top and hiding what is above it.
    fn focus_offset(cx: &PaintCx<'_>, focused: WidgetId, rect: Rect, content: Rect, area: Rect, offset: u16) -> u16 {
        let clicked =
            cx.interaction.focus_by_pointer && cx.interaction.pointer.is_some_and(|(x, y)| rect.contains(x, y));
        if clicked {
            return offset;
        }
        let spot = cx.frame.focus_spots.get(&focused).copied();
        let target = spot.unwrap_or(rect);
        let visible = target.y < area.bottom() && target.bottom() > area.y;
        if spot.is_none() && target.height > area.height && visible {
            return offset;
        }
        let top = target.y - content.y;
        offset_showing(top, top + i32::from(target.height), offset, area.height)
    }

    /// Takes the last area a widget inside asked to reveal this frame and scrolls to it.
    fn take_reveal(cx: &mut PaintCx<'_>, content: Rect, area: Rect, offset: u16) {
        let id = cx.id();
        let mut wanted = None;
        for (asker, rect) in std::mem::take(&mut cx.frame.reveals) {
            if asker != id && cx.frame.is_within(asker, id) {
                wanted = Some(rect);
            } else {
                cx.frame.reveals.push((asker, rect));
            }
        }
        let Some(rect) = wanted else { return };
        let top = rect.y - content.y;
        let max = content.height.saturating_sub(area.height);
        let target = offset_showing(top, top + i32::from(rect.height), offset, area.height).min(max);
        let reduced = cx.reduced_motion();
        let now = cx.now();
        let memory = cx.memory::<ScrollMemory>();
        memory.moved(offset, target, max);
        if reduced {
            memory.offset = target;
            memory.glide = None;
        } else {
            memory.glide = (target != offset).then_some(Glide { from: offset, to: target, start: now });
        }
        if target != offset {
            cx.request_frame_in(Duration::ZERO);
        }
    }
}

impl<Msg: 'static> Default for ScrollView<Msg> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Msg: 'static> Container<Msg> for ScrollView<Msg> {
    fn set_children(&mut self, children: Vec<Node<Msg>>) {
        let mut column = Node::new(Flex::new(Axis::Column, children), 0);
        column.layout.width = Length::Fill(1);
        self.content = vec![column];
    }
}

impl<Msg: 'static> Widget<Msg> for ScrollView<Msg> {
    fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size {
        let content = self.content.first().map_or(Size::default(), |c| cx.measure_child(c, available));
        Size::new(content.width.saturating_add(1), content.height).min(available)
    }

    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
        let Some(content) = self.content.first() else {
            return;
        };
        cx.register_hit(area);
        let full = cx.measure_child(content, Size::new(area.width, u16::MAX)).height;
        let overflows = full > area.height;
        let width = if overflows { area.width.saturating_sub(2) } else { area.width };
        let height = if overflows { cx.measure_child(content, Size::new(width, u16::MAX)).height } else { full };
        let max = height.saturating_sub(area.height);
        let offset = {
            let memory = cx.memory::<ScrollMemory>();
            memory.content_height = height;
            memory.offset = memory.offset.min(max);
            memory.offset
        };
        let offset = if self.follow_end {
            Self::follow(cx, max);
            cx.memory::<ScrollMemory>().offset
        } else {
            offset
        };
        let offset = Self::glide(cx, offset, max);
        let content_rect = Rect::new(area.x, area.y - i32::from(offset), width, height);
        cx.with_clip(area, |cx| cx.paint_child(content, content_rect));
        Self::take_reveal(cx, content_rect, area, offset);

        if let Some(focused) = cx.interaction.focused
            && focused != cx.id()
            && cx.frame.is_within(focused, cx.id())
            && let Some(rect) = cx.frame.rects.get(&focused).copied()
            && cx.memory::<ScrollMemory>().revealed != Some(focused)
        {
            cx.memory::<ScrollMemory>().revealed = Some(focused);
            let new_offset = Self::focus_offset(cx, focused, rect, content_rect, area, offset);
            let memory = cx.memory::<ScrollMemory>();
            if new_offset != offset {
                memory.moved(offset, new_offset, max);
                memory.offset = new_offset;
                memory.glide = None;
                cx.request_frame_in(Duration::ZERO);
            }
        }

        let note = {
            let memory = cx.memory::<ScrollMemory>();
            let below = max.saturating_sub(memory.offset);
            (self.follow_end && memory.detached && below > 0).then_some(below)
        };
        let note = note.map(|below| {
            let note = rows::paint_below_note(cx, Rect::new(area.x, area.y, width, area.height), below.into());
            cx.register_hit(note);
            note
        });
        cx.memory::<ScrollMemory>().note = note;

        if overflows {
            let metrics = Self::metrics(cx.memory::<ScrollMemory>(), area);
            let active =
                cx.memory::<ScrollMemory>().dragging || cx.pointer().is_some_and(|(x, _)| x >= area.right() - 1);
            scrollbar::paint(cx, Rect::new(area.right() - 1, area.y, 1, area.height), metrics, active, self.scrollbar);
        }
    }

    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
        let area = cx.area();
        let (offset, metrics) = {
            let memory = cx.memory::<ScrollMemory>();
            (i32::from(memory.offset), Self::metrics(memory, area))
        };
        let page = i32::from(area.height.saturating_sub(1).max(1));
        match event {
            Event::Key(key) => {
                let target = if key.is_plain(Key::Up) {
                    offset - 1
                } else if key.is_plain(Key::Down) {
                    offset + 1
                } else if Self::is_page_up(cx, key) {
                    offset - page
                } else if Self::is_page_down(cx, key) {
                    offset + page
                } else if key.is_plain(Key::Home) {
                    0
                } else if key.is_plain(Key::End) {
                    i32::MAX
                } else {
                    return false;
                };
                if !metrics.overflows() {
                    return false;
                }
                Self::scroll_to(cx, target);
                true
            }
            Event::Mouse(mouse) => {
                let on_bar = metrics.overflows() && mouse.x == area.right() - 1;
                let on_note = cx.memory::<ScrollMemory>().note.is_some_and(|note| note.contains(mouse.x, mouse.y));
                match mouse.kind {
                    MouseKind::Down(MouseButton::Left) if on_note => {
                        Self::scroll_to(cx, i32::MAX);
                        true
                    }
                    MouseKind::ScrollUp if metrics.overflows() => {
                        Self::scroll_to(cx, offset - i32::from(WHEEL_ROWS));
                        true
                    }
                    MouseKind::ScrollDown if metrics.overflows() => {
                        Self::scroll_to(cx, offset + i32::from(WHEEL_ROWS));
                        true
                    }
                    MouseKind::Down(MouseButton::Left) if on_bar => {
                        cx.capture_pointer();
                        cx.memory::<ScrollMemory>().dragging = true;
                        let target = metrics.offset_at(clamp_u16(mouse.y - area.y), area.height);
                        Self::scroll_to(cx, i32::try_from(target).unwrap_or(i32::MAX));
                        true
                    }
                    MouseKind::Drag(MouseButton::Left) if cx.memory::<ScrollMemory>().dragging => {
                        let target = metrics.offset_at(clamp_u16(mouse.y - area.y), area.height);
                        Self::scroll_to(cx, i32::try_from(target).unwrap_or(i32::MAX));
                        true
                    }
                    MouseKind::Up(MouseButton::Left) if cx.memory::<ScrollMemory>().dragging => {
                        cx.memory::<ScrollMemory>().dragging = false;
                        true
                    }
                    _ => false,
                }
            }
            _ => false,
        }
    }

    fn focusable(&self) -> bool {
        true
    }

    fn children(&self) -> &[Node<Msg>] {
        &self.content
    }

    fn children_mut(&mut self) -> &mut [Node<Msg>] {
        &mut self.content
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::env::{AssetDirs, Env};
    use crate::runtime::{App, Command, Harness};
    use crate::widget::View;
    use crate::widgets::{Button, Text};

    struct Demo;

    impl App for Demo {
        type Msg = ();
        fn update(&mut self, _: ()) -> Command<()> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, ()>) {
            ui.add_with(ScrollView::new(), |ui| {
                for i in 0..20 {
                    ui.add(Text::new(format!("line {i}")));
                }
                ui.add(Button::new("Bottom").on_press(())).id("bottom");
            })
            .fill();
        }
    }

    #[test]
    fn scrolls_with_keys_and_wheel() {
        let mut h = Harness::new(Demo, 20, 5);
        assert!(h.screen().starts_with("line 0"));
        h.press("tab").press("pgdn");
        assert!(h.screen().starts_with("line 4"), "{}", h.screen());
        h.mouse(MouseKind::ScrollDown, 2, 2);
        assert!(h.screen().starts_with("line 7"));
        h.press("end");
        assert!(h.screen().contains("Bottom"));
        h.press("home");
        assert!(h.screen().starts_with("line 0"));
    }

    /// A hundred lines in a ten-row view with a button at the end: the shape of a document a
    /// person reads with the space bar, and of a player whose lyrics scroll.
    #[derive(Default)]
    struct Pages {
        seen: Vec<Msg>,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Msg {
        Pressed(&'static str),
        Action(String),
    }

    impl App for Pages {
        type Msg = Msg;
        fn update(&mut self, msg: Msg) -> Command<Msg> {
            self.seen.push(msg);
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            ui.add_with(ScrollView::new(), |ui| {
                for i in 0..100 {
                    ui.add(Text::new(format!("line {i}")));
                }
                ui.add(Button::new("The end").on_press(Msg::Pressed("end"))).id("end");
            })
            .fill()
            .id("pages");
        }
        fn action(&self, name: &str) -> Option<Msg> {
            Some(Msg::Action(name.to_owned()))
        }
    }

    /// The view focused by one Tab, the way a person reaches it before reading, with the
    /// application's own keys given as the text a music player would compile into its binary.
    fn reading(keys: &str) -> Harness<Pages> {
        let dirs =
            AssetDirs { keymap_source: Some(("keymap.toml".to_owned(), keys.to_owned())), ..AssetDirs::default() };
        let env = Env::load_with(&dirs, |_| None).expect("the keymap comes from text and nothing is read from disk");
        let mut h = Harness::with_env(Pages::default(), env, 20, 10);
        h.press("tab");
        assert!(h.is_focused("pages"), "{}", h.screen());
        h
    }

    /// The first row on screen, which names the content the view is scrolled to.
    fn top(h: &Harness<Pages>) -> String {
        h.screen().lines().next().unwrap_or_default().trim_end().to_owned()
    }

    #[test]
    fn space_pages_a_focused_view_exactly_as_the_page_keys_do() {
        let mut spaced = reading("");
        spaced.press("space");
        assert_eq!(top(&spaced), "line 9", "{}", spaced.screen());
        let mut paged = reading("");
        paged.press("pgdn");
        assert_eq!(spaced.screen(), paged.screen(), "space is pgdn");

        spaced.press("shift+space");
        let mut back = reading("");
        back.press("pgup");
        assert_eq!(spaced.screen(), back.screen(), "shift+space is pgup");
        assert_eq!(top(&spaced), "line 0", "{}", spaced.screen());
    }

    #[test]
    fn a_focused_button_inside_the_view_keeps_space() {
        let mut h = reading("");
        h.press("tab");
        assert!(h.is_focused("end"), "{}", h.screen());
        let before = top(&h);
        h.press("space");
        assert_eq!(h.app().seen, [Msg::Pressed("end")], "the button answered the Space");
        assert_eq!(top(&h), before, "and the view stayed where it was");
    }

    #[test]
    fn a_space_the_application_bound_to_its_own_action_pages_nothing() {
        let mut h = reading("[app]\nplay = \"space\"\n");
        h.press("space");
        assert_eq!(h.app().seen, [Msg::Action("play".to_owned())], "the application's own Space answered");
        assert_eq!(top(&h), "line 0", "and the view stayed where it was");
        // Only the plain Space is bound to the application; the page back beside it still moves.
        h.press("pgdn");
        assert_eq!(top(&h), "line 9", "{}", h.screen());
        h.press("shift+space");
        assert_eq!(top(&h), "line 0", "{}", h.screen());
    }

    #[test]
    fn reveals_focused_widget() {
        let mut h = Harness::new(Demo, 20, 5);
        h.press("tab").press("tab");
        assert!(h.is_focused("bottom"));
        assert!(h.screen().contains("Bottom"), "{}", h.screen());
    }

    #[test]
    fn draws_scrollbar_only_when_needed() {
        // The default block style is colour only, so the scrollbar column is read by its colours.
        let h = Harness::new(Demo, 20, 30);
        let muted = h.env().theme().color("muted");
        assert_ne!(h.bg(19, 0), muted);
        let short = Harness::new(Demo, 20, 5);
        assert_eq!(short.bg(19, 0), muted, "the thumb sits at the top");
        assert_eq!(short.bg(19, 4), short.env().theme().color("raised"), "the track runs below it");
    }

    struct Pinned(Option<ScrollbarStyle>);

    impl App for Pinned {
        type Msg = ();
        fn update(&mut self, _: ()) -> Command<()> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, ()>) {
            let view = self.0.map_or_else(ScrollView::new, |style| ScrollView::new().scrollbar(style));
            ui.add_with(view, |ui| {
                for i in 0..20 {
                    ui.add(Text::new(format!("line {i}")));
                }
            })
            .fill();
        }
    }

    /// The scrollbar column, top to bottom, with blank cells as spaces.
    fn bar(h: &Harness<Pinned>) -> String {
        h.screen().lines().map(|line| format!("{line:<10}").chars().nth(9).unwrap_or(' ')).collect()
    }

    #[test]
    fn every_style_draws_its_own_column() {
        let expected = [
            (ScrollbarStyle::Block, "    "),
            (ScrollbarStyle::Half, "▐▕▕▕"),
            (ScrollbarStyle::Thin, "▕   "),
            (ScrollbarStyle::Dots, "•···"),
        ];
        for (style, column) in expected {
            let mut h = Harness::new(Pinned(Some(style)), 10, 4);
            assert_eq!(bar(&h), column, "{style:?}");
            let theme = h.env().theme();
            let (raised, muted, canvas) = (theme.color("raised"), theme.color("muted"), theme.color("canvas"));
            let thumb = if style == ScrollbarStyle::Dots { theme.color("dim") } else { muted };
            match style {
                ScrollbarStyle::Block => assert_eq!((h.bg(9, 0), h.bg(9, 3)), (muted, raised)),
                ScrollbarStyle::Thin => assert_eq!(h.bg(9, 3), canvas, "thin draws no track"),
                ScrollbarStyle::Half => assert_eq!(h.fg(9, 0), muted),
                ScrollbarStyle::Dots => assert_eq!((h.fg(9, 0), h.fg(9, 3)), (theme.color("dim"), muted)),
            }
            h.set_glyph_mode(crate::icons::GlyphMode::Ascii);
            assert!(h.screen().is_ascii(), "{style:?}");
            assert_eq!(h.bg(9, 0), thumb, "ASCII thumb is a coloured cell in {style:?}");
        }
    }

    #[test]
    fn theme_word_chooses_the_style_and_pinning_wins() {
        let dir = std::env::temp_dir().join(format!("quvyta-scrollbar-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let theme = "[meta]\nname = \"Dotted\"\nextends = \"monochrome\"\n[style.scrollbar]\nstyle = \"dots\"\n";
        std::fs::write(dir.join("dotted.toml"), theme).expect("theme file");
        let dirs = crate::env::AssetDirs { themes: Some(dir.clone()), ..Default::default() };
        let env = crate::env::Env::load(&dirs).expect("loads");
        let mut h = Harness::with_env(Pinned(None), env.clone(), 10, 4);
        h.set_glyph_mode(crate::icons::GlyphMode::Unicode).set_theme("dotted");
        assert_eq!(bar(&h), "•···");
        let mut pinned = Harness::with_env(Pinned(Some(ScrollbarStyle::Thin)), env, 10, 4);
        pinned.set_glyph_mode(crate::icons::GlyphMode::Unicode).set_theme("dotted");
        assert_eq!(bar(&pinned), "▕   ");
        std::fs::remove_dir_all(dir).ok();
    }
}

#[cfg(test)]
#[path = "scroll_view_follow_tests.rs"]
mod follow_tests;