quvyta-framework 0.1.28

A Rust framework for building terminal applications
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
//! Breadcrumbs: the path to the current place, one clickable segment per level.

use crate::event::{Event, MouseButton, MouseKind};
use crate::geometry::{Rect, Size};
use crate::keymap::Key;
use crate::style::CellStyle;
use crate::text;
use crate::theme::State;
use crate::widget::{EventCx, MeasureCx, PaintCx, Widget};

use super::IndexMessage;
use super::popup_menu::{PopupAction, PopupMenu};

/// Cells of padding on each side of a segment's label.
const PAD: u16 = 1;

/// A piece of a laid-out breadcrumb.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Part {
    /// Segment `index`.
    Segment(usize),
    /// The `…` standing for the hidden middle.
    More,
}

#[derive(Debug, Default)]
struct CrumbMemory {
    cursor: Option<Part>,
    hidden: Vec<usize>,
}

/// The path to the current place, such as `workspace › quvyta › crates › src`.
///
/// Every segment but the last opens its level; the last is the current place, bold and not
/// clickable. Segments are bare text that rises on hover; the separator is a faint chevron icon.
/// When the path does not fit, the middle collapses into `…`, which lists the hidden levels.
///
/// Keys while focused: ←/→ move between segments, Home/End jump to the ends, Enter or Space
/// opens the segment (or the list behind `…`).
///
/// A faint path, see [`faint`](Self::faint), is drawn a step quieter for a place the person
/// cannot read, and its segments still open their levels.
///
/// Style keys: `crumb` with `hover`, `focus`; `crumb.current`; `crumb.faint` and
/// `crumb.faint-current` for a faint path; `crumb-separator`;
/// `popup-menu`, `popup-item`, `popup-check` for the hidden levels. Icon: `crumb-separator`.
pub struct Breadcrumb<Msg> {
    segments: Vec<String>,
    on_select: Option<IndexMessage<Msg>>,
    faint: bool,
}

impl<Msg: 'static> Breadcrumb<Msg> {
    /// A path of `segments` from the root to the current place.
    #[must_use]
    pub fn new(segments: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self { segments: segments.into_iter().map(Into::into).collect(), on_select: None, faint: false }
    }

    /// Message for opening segment `index`.
    #[must_use]
    pub fn on_select(mut self, message: impl Fn(usize) -> Msg + 'static) -> Self {
        self.on_select = Some(Box::new(message));
        self
    }

    /// Draws the path faint: every segment a step quieter, the current place too, for a place
    /// shown but not open to the person, such as a folder that cannot be read.
    ///
    /// Only the tone changes. The segments still rise on hover and focus and still open their
    /// levels, so the way back out of the place stays where it always is.
    #[must_use]
    pub fn faint(mut self, faint: bool) -> Self {
        self.faint = faint;
        self
    }

    /// The style variant of a segment: the current place or another, faint or not.
    fn variant(&self, current: bool) -> Option<&'static str> {
        match (self.faint, current) {
            (false, false) => None,
            (false, true) => Some("current"),
            (true, false) => Some("faint"),
            (true, true) => Some("faint-current"),
        }
    }

    fn segment_width(&self, index: usize) -> u16 {
        text::width(&self.segments[index]).saturating_add(PAD * 2)
    }

    fn width_of(&self, parts: &[Part]) -> u16 {
        let count = u16::try_from(parts.len()).unwrap_or(u16::MAX);
        parts
            .iter()
            .map(|part| match part {
                Part::Segment(index) => self.segment_width(*index),
                Part::More => 1 + PAD * 2,
            })
            .fold(0u16, u16::saturating_add)
            .saturating_add(count.saturating_sub(1))
    }

    /// The parts that fit in `width`: everything, or the root, `…` and as many of the last
    /// levels as fit, or at worst `…` and the current place.
    fn parts(&self, width: u16) -> Vec<Part> {
        let count = self.segments.len();
        let all: Vec<Part> = (0..count).map(Part::Segment).collect();
        if count <= 2 || self.width_of(&all) <= width {
            return all;
        }
        let last = count - 1;
        let mut tail = vec![Part::Segment(last)];
        for index in (1..last).rev() {
            let mut candidate = vec![Part::Segment(0), Part::More, Part::Segment(index)];
            candidate.extend(&tail);
            if self.width_of(&candidate) > width {
                break;
            }
            tail.insert(0, Part::Segment(index));
        }
        let mut with_root = vec![Part::Segment(0), Part::More];
        with_root.extend(&tail);
        if self.width_of(&with_root) <= width {
            return with_root;
        }
        vec![Part::More, Part::Segment(last)]
    }

    /// Screen rectangles of `parts` laid out from `area`'s left edge.
    fn layout(&self, parts: &[Part], area: Rect) -> Vec<(Part, Rect)> {
        let mut x = area.x;
        parts
            .iter()
            .map(|part| {
                let width = match part {
                    Part::Segment(index) => self.segment_width(*index),
                    Part::More => 1 + PAD * 2,
                };
                let rect = Rect::new(x, area.y, width, 1).intersect(area);
                x += i32::from(width) + 1;
                (*part, rect)
            })
            .collect()
    }

    fn hidden(parts: &[Part], count: usize) -> Vec<usize> {
        (0..count).filter(|index| !parts.contains(&Part::Segment(*index))).collect()
    }

    fn is_current(&self, part: Part) -> bool {
        part == Part::Segment(self.segments.len().saturating_sub(1))
    }

    fn active(&self) -> bool {
        self.on_select.is_some() && self.segments.len() > 1
    }

    /// The parts the keyboard can rest on, in order.
    fn stops(&self, parts: &[Part]) -> Vec<Part> {
        parts.iter().copied().filter(|part| !self.is_current(*part)).collect()
    }

    fn activate(&self, cx: &mut EventCx<'_, Msg>, part: Part, parts: &[Part]) {
        match part {
            Part::Segment(index) => {
                if let Some(message) = &self.on_select
                    && !self.is_current(part)
                {
                    cx.flash();
                    cx.emit(message(index));
                }
            }
            Part::More => {
                let hidden = Self::hidden(parts, self.segments.len());
                let highlight = hidden.len().saturating_sub(1);
                cx.memory::<CrumbMemory>().hidden = hidden;
                PopupMenu::open(cx, highlight);
            }
        }
    }
}

impl<Msg: 'static> Widget<Msg> for Breadcrumb<Msg> {
    fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
        let all: Vec<Part> = (0..self.segments.len()).map(Part::Segment).collect();
        Size::new(self.width_of(&all), 1).min(available)
    }

    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
        if self.segments.is_empty() || area.is_empty() {
            return;
        }
        let active = self.active();
        if active {
            cx.register_hit(area);
        }
        let focused = active && cx.is_focused();
        let pointer = if active { cx.pointer() } else { None };
        let parts = self.parts(area.width);
        let stops = self.stops(&parts);
        let cursor = {
            let memory = cx.memory::<CrumbMemory>();
            memory.cursor.filter(|part| stops.contains(part)).or_else(|| stops.last().copied())
        };
        let separator = cx.env().icons().glyph("crumb-separator").into_owned();
        let separator_style = cx.style("crumb-separator", None, &[]).text();
        for (position, (part, rect)) in self.layout(&parts, area).into_iter().enumerate() {
            if position > 0 {
                cx.text(rect.x - 1, rect.y, &separator, separator_style, 1);
            }
            if rect.is_empty() {
                continue;
            }
            let current = self.is_current(part);
            let mut states = Vec::new();
            if !current && pointer.is_some_and(|(x, y)| rect.contains(x, y)) {
                states.push(State::Hover);
            }
            if focused && cursor == Some(part) {
                states.push(State::Focus);
            }
            if part == Part::More && PopupMenu::is_open_paint(cx) {
                states.push(State::Active);
                cx.request_overlay(rect);
            }
            let style = cx.style("crumb", self.variant(current), &states).text();
            if let Some(bg) = style.bg {
                cx.clear(rect, bg);
            }
            let label = match part {
                Part::Segment(index) => self.segments[index].as_str(),
                Part::More => text::ELLIPSIS,
            };
            let budget = rect.width.saturating_sub(PAD * 2);
            let shown = text::truncate(label, budget).into_owned();
            cx.text(rect.x + i32::from(PAD), rect.y, &shown, CellStyle { bg: None, ..style }, budget);
        }
        cx.memory::<CrumbMemory>().hidden = Self::hidden(&parts, self.segments.len());
    }

    fn paint_overlay(&self, cx: &mut PaintCx<'_>, anchor: Rect) {
        let hidden = cx.memory::<CrumbMemory>().hidden.clone();
        let labels: Vec<String> = hidden.iter().map(|index| self.segments[*index].clone()).collect();
        PopupMenu::paint(cx, anchor, &labels, None);
    }

    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
        if !self.active() {
            return false;
        }
        if PopupMenu::is_open(cx) {
            let hidden = cx.memory::<CrumbMemory>().hidden.clone();
            let labels: Vec<String> = hidden.iter().map(|index| self.segments[*index].clone()).collect();
            match PopupMenu::event(cx, event, &labels) {
                PopupAction::Chosen(row) => {
                    if let Some(message) = &self.on_select {
                        cx.emit(message(hidden[row]));
                    }
                    return true;
                }
                PopupAction::Used | PopupAction::Closed => return true,
                PopupAction::Ignored => {}
            }
        }
        let area = cx.area();
        let parts = self.parts(area.width);
        let stops = self.stops(&parts);
        match event {
            Event::Key(key) => {
                let remembered = cx.memory::<CrumbMemory>().cursor;
                let Some(position) = remembered
                    .and_then(|part| stops.iter().position(|stop| *stop == part))
                    .or_else(|| stops.len().checked_sub(1))
                else {
                    return false;
                };
                let target = if key.is_plain(Key::Left) {
                    position.saturating_sub(1)
                } else if key.is_plain(Key::Right) {
                    (position + 1).min(stops.len() - 1)
                } else if key.is_plain(Key::Home) {
                    0
                } else if key.is_plain(Key::End) {
                    stops.len() - 1
                } else if key.is_plain(Key::Enter) || key.is_plain(Key::Space) {
                    self.activate(cx, stops[position], &parts);
                    return true;
                } else {
                    return false;
                };
                cx.memory::<CrumbMemory>().cursor = Some(stops[target]);
                true
            }
            Event::Mouse(mouse) if mouse.kind == MouseKind::Down(MouseButton::Left) => {
                let hit = self.layout(&parts, area).into_iter().find(|(_, rect)| rect.contains(mouse.x, mouse.y));
                match hit {
                    Some((part, _)) if !self.is_current(part) => {
                        cx.memory::<CrumbMemory>().cursor = Some(part);
                        self.activate(cx, part, &parts);
                        true
                    }
                    _ => false,
                }
            }
            _ => false,
        }
    }

    fn focusable(&self) -> bool {
        self.active()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::icons::GlyphMode;
    use crate::runtime::{App, Command, Harness};
    use crate::widget::{Length, View};

    struct Files {
        path: Vec<&'static str>,
        width: u16,
        faint: bool,
    }

    impl App for Files {
        type Msg = usize;
        fn update(&mut self, index: usize) -> Command<usize> {
            self.path.truncate(index + 1);
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, usize>) {
            ui.add(Breadcrumb::new(self.path.clone()).on_select(|i| i).faint(self.faint))
                .width(Length::Cells(self.width))
                .id("path");
        }
    }

    fn files(width: u16) -> Files {
        Files { path: vec!["workspace", "quvyta", "crates", "framework", "src", "widgets"], width, faint: false }
    }

    #[test]
    fn segments_open_levels_and_the_current_one_is_bold() {
        let mut h = Harness::new(files(80), 80, 6);
        assert_eq!(h.screen().lines().next(), Some(" workspace › quvyta › crates › framework › src › widgets"));
        assert!(h.is_bold(50, 0), "the current place is bold");
        assert!(!h.is_bold(2, 0));
        h.click_text("crates");
        assert_eq!(h.app().path, vec!["workspace", "quvyta", "crates"]);
        h.click_text("crates");
        assert_eq!(h.app().path.len(), 3, "the current place is not a link");
        h.set_glyph_mode(GlyphMode::Ascii);
        assert_eq!(h.screen().lines().next(), Some(" workspace : quvyta : crates"));
    }

    #[test]
    fn narrow_paths_collapse_the_middle_and_list_it() {
        let mut h = Harness::new(files(34), 34, 8);
        assert_eq!(h.screen().lines().next(), Some(" workspace › … › src › widgets"));
        h.click_text("…").advance(std::time::Duration::from_millis(300));
        let screen = h.screen();
        assert!(screen.contains("quvyta") && screen.contains("framework"), "{screen}");
        h.click_text("framework");
        assert_eq!(h.app().path.last(), Some(&"framework"));
        let tiny = Harness::new(files(14), 14, 1);
        assert_eq!(tiny.screen(), " … › widgets\n");
    }

    #[test]
    fn keyboard_moves_between_segments() {
        let mut h = Harness::new(files(80), 80, 6);
        h.press("tab").press("left").press("left").press("enter");
        assert_eq!(h.app().path, vec!["workspace", "quvyta", "crates"]);
        h.press("home").press("enter");
        assert_eq!(h.app().path, vec!["workspace"]);
        assert!(!h.is_focused("path"), "a single segment has nothing to open");
    }

    #[test]
    fn segments_wider_than_any_screen_do_not_overflow() {
        let long: &'static str = "d".repeat(70_000).leak();
        let h = Harness::new(Files { path: vec!["workspace", long, long, "src"], width: 24, faint: false }, 24, 1);
        assert_eq!(h.screen(), " workspace › … › src\n");
    }

    #[test]
    fn a_faint_path_is_drawn_in_the_themes_faint_tone_and_still_opens_its_levels() {
        let plain = Harness::new(files(80), 80, 6);
        let mut faint = Harness::new(Files { faint: true, ..files(80) }, 80, 6);
        let theme = faint.env().theme();
        let (muted, dim) = (theme.color("muted"), theme.color("dim"));
        assert!(muted.is_some() && muted != dim);
        let (x, y) = faint.find("quvyta").expect("a segment");
        let (x, y) = (u16::try_from(x).expect("on screen"), u16::try_from(y).expect("on screen"));
        assert_eq!(faint.fg(x, y), muted, "a faint segment takes the theme's faint tone");
        assert_eq!(plain.fg(x, y), dim, "a plain one keeps its own");
        assert_ne!(faint.fg(50, 0), plain.fg(50, 0), "the current place is quieter too");
        assert!(faint.is_bold(50, 0), "and still bold");

        faint.click_text("crates");
        assert_eq!(faint.app().path, vec!["workspace", "quvyta", "crates"], "a faint segment still opens its level");
    }
}