paperboy 0.4.0

A Rust TUI API tester
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
use super::listscroll::ListScroll;
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, List, ListItem, ListState, Paragraph, Wrap};

use crate::i18n::Strings;
use crate::remote_flow::{RemoteFlow, RemoteKind, Step, WorkspaceGitFilter};

// The wizard's data model, its file/ref narrowing and its background workers
// live in `crate::remote_flow`, shared with the GUI so the two front-ends
// cannot drift apart. What remains here is the terminal UI's presentation of
// it: the stage the user is on and how each popup is drawn.
pub(crate) use crate::remote_flow::{filter_indices, spawn_workspace_redownload};

use super::app::{MouseHitTarget, MouseLayer, MouseScrollTarget, TuiApp};
use super::draw::*;
use super::editor::*;
use super::theme::*;

/// Which step of the wizard the terminal UI is drawing.
///
/// This is a *view* of [`RemoteFlow`]'s state, not a second copy of it: it
/// carries no data, and [`RemoteWizard::stage`] derives it fresh each time. An
/// in-flight operation and an error both take precedence over the underlying
/// step, because that is what the user needs to see.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RemoteStage {
    Connect,
    Loading,
    PickRef,
    PickFile,
    PickWorkspaceFilter,
    Error,
}

/// The terminal UI's "load from a remote git repo" wizard overlay.
///
/// Everything that decides what happens next lives in `flow`; what is left here
/// is how the terminal presents it — text editors with cursors, a filter string
/// and a highlighted row.
pub(crate) struct RemoteWizard {
    pub(crate) flow: RemoteFlow,
    pub(crate) url: Editor,
    pub(crate) token: Editor,
    /// Recently used git URLs (most recent first), offered as a pickable
    /// dropdown below the URL field. A snapshot taken when the wizard opened.
    pub(crate) recent: Vec<String>,
    /// Connect step: which field has focus (0 = URL, 1 = token).
    pub(crate) field: u8,
    /// `Some` while the recent-URLs dropdown has keyboard focus, indexing into
    /// [`RemoteWizard::recent`].
    pub(crate) recent_sel: Option<usize>,
    /// The list steps' typed filter and highlighted row. Shared by the ref and
    /// file pickers because only one of them is ever on screen, and both are
    /// reset whenever the step changes.
    pub(crate) filter: String,
    pub(crate) sel: usize,
    /// Where the ref/file list is scrolled to, carried between frames (see
    /// [`ListScroll`]). Shared by both pickers for the same reason `filter`
    /// and `sel` are: only one is ever on screen at a time.
    pub(crate) list_scroll: ListScroll,
}

impl RemoteWizard {
    pub(crate) fn new(kind: RemoteKind, recent: Vec<String>) -> Self {
        Self {
            flow: RemoteFlow::new(kind),
            url: Editor::blank(),
            token: Editor::blank(),
            recent,
            field: 0,
            recent_sel: None,
            filter: String::new(),
            sel: 0,
            list_scroll: ListScroll::default(),
        }
    }

    pub(crate) fn kind(&self) -> RemoteKind {
        self.flow.kind
    }

    /// The step to draw, derived from the flow.
    pub(crate) fn stage(&self) -> RemoteStage {
        if self.flow.error().is_some() {
            return RemoteStage::Error;
        }
        if self.flow.busy().is_some() {
            return RemoteStage::Loading;
        }
        match self.flow.step() {
            Step::Connect => RemoteStage::Connect,
            Step::PickRef => RemoteStage::PickRef,
            Step::PickFile => RemoteStage::PickFile,
            // The terminal UI hands the "keep or save" question to its own
            // overlay once the download lands, so the wizard is gone by then.
            Step::PickWorkspaceFilter | Step::WorkspaceStorage => RemoteStage::PickWorkspaceFilter,
        }
    }

    /// Copy the on-screen editors into the flow. Called before any transition
    /// that needs them, so the flow never has to know about [`Editor`].
    pub(crate) fn sync_fields(&mut self) {
        self.flow.url = self.url.text();
        self.flow.token = self.token.text();
    }

    /// Reset the list filter and highlight, for when the step changes under us.
    pub(crate) fn reset_list(&mut self) {
        self.filter.clear();
        self.sel = 0;
    }
}

/// A filterable, scrollable list popup (used for the branch/tag and file
/// pickers). `sel` indexes into the *filtered* list.
pub(crate) fn draw_filter_list(
    f: &mut Frame,
    s: &Strings,
    title: &str,
    filter: &str,
    items: &[String],
    sel: usize,
    th: &Theme,
    scroll: &ListScroll,
) -> usize {
    let w = (f.area().width * 7 / 10).max(50);
    let h = (f.area().height * 7 / 10).max(10);
    let area = centered_rect(w, h, f.area());
    f.render_widget(Clear, area);
    let block = panel_hinted(title.to_string(), s.git_filter_hint, th);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let rows = Layout::vertical([
        Constraint::Length(1), // filter line
        Constraint::Min(1),    // list
    ])
    .split(inner);

    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(s.git_filter_label.to_string(), Style::default().fg(th.dim)),
            Span::styled(filter.to_string(), Style::default().fg(th.text)),
        ])),
        rows[0],
    );

    let vis = filter_indices(items.iter().map(|s| s.as_str()), filter);
    let list_items: Vec<ListItem> = vis
        .iter()
        .map(|&i| ListItem::new(Line::styled(items[i].clone(), Style::default().fg(th.text))))
        .collect();
    let list = List::new(list_items)
        .highlight_style(
            Style::default()
                .bg(th.accent)
                .fg(th.bg)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("\u{203a} ");
    let sel = (!vis.is_empty()).then(|| sel.min(vis.len() - 1));
    let offset = scroll.render(f, rows[1], list, sel, vis.len());
    offset
}

/// A small fixed-choice popup (used by the Workspace git-load file-type
/// filter picker) — like `draw_filter_list` but with no search box, since
/// the choices are a short fixed list rather than something worth typing to
/// narrow down.
pub(crate) fn draw_choice_popup(
    f: &mut Frame,
    title: &str,
    items: &[&str],
    sel: usize,
    hint: &str,
    th: &Theme,
) {
    let content_w = items
        .iter()
        .map(|s| s.chars().count())
        .max()
        .unwrap_or(20)
        .max(title.chars().count());
    let w = (content_w as u16 + 6).clamp(30, f.area().width.max(1));
    let h = (items.len() as u16 + 2).min(f.area().height.max(1));
    let area = centered_rect(w, h, f.area());
    f.render_widget(Clear, area);
    let block = panel_hinted(title.to_string(), hint, th);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let list_items: Vec<ListItem> = items
        .iter()
        .map(|i| ListItem::new(Line::styled(i.to_string(), Style::default().fg(th.text))))
        .collect();
    let list = List::new(list_items)
        .highlight_style(
            Style::default()
                .bg(th.accent)
                .fg(th.bg)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("\u{203a} ");
    let mut st = ListState::default();
    st.select(Some(sel.min(items.len().saturating_sub(1))));
    f.render_stateful_widget(list, inner, &mut st);
}

#[cfg(test)]
pub(crate) fn draw_remote_wizard(f: &mut Frame, w: &RemoteWizard, s: &Strings, th: &Theme) {
    draw_remote_wizard_with_hits(f, w, s, th, None);
}

pub(crate) fn draw_remote_wizard_with_hits(
    f: &mut Frame,
    w: &RemoteWizard,
    s: &Strings,
    th: &Theme,
    app: Option<&TuiApp>,
) {
    if let Some(app) = app {
        app.set_mouse_layer(MouseLayer::Overlay);
    }
    let title = match w.kind() {
        RemoteKind::Collection => s.git_collection_menu,
        RemoteKind::Environment => s.git_env_menu,
        RemoteKind::Report => s.git_report_menu,
        RemoteKind::Workspace => s.git_workspace_menu,
    };
    match w.stage() {
        RemoteStage::Connect => {
            let (field, recent_sel) = (w.field, w.recent_sel);
            // Laid out like the request wizard: label column, value beside it,
            // keys on the border. What each field wants is shown as a dim
            // example inside the empty field rather than as a sentence under
            // it.
            let fields = [
                (s.git_url_label, s.git_url_hint, &w.url, false),
                (s.git_token_label, s.git_token_hint, &w.token, true),
            ];
            let label_w = label_column(fields.iter().map(|(l, _, _, _)| *l));
            // Grow the popup to fit the recent-URLs dropdown, if any (capped so
            // it never grows unreasonably tall).
            let recent_rows = w.recent.len().min(5) as u16;
            let area = centered_rect(74, recent_rows + 4, f.area());
            f.render_widget(Clear, area);
            let hint = if recent_rows > 0 {
                format!("{}  \u{b7}  {}", s.git_connect_hint, s.git_recent_hint)
            } else {
                s.git_connect_hint.to_string()
            };
            let block = panel_hinted(title.to_string(), &hint, th);
            let inner = block.inner(area);
            f.render_widget(block, area);
            let rows = Layout::vertical([
                Constraint::Length(1),           // url
                Constraint::Length(recent_rows), // recent-urls dropdown
                Constraint::Length(1),           // token
            ])
            .split(inner);

            for (i, (label, placeholder, ed, mask)) in fields.iter().enumerate() {
                let row = if i == 0 { rows[0] } else { rows[2] };
                let cols = Layout::horizontal([Constraint::Length(label_w), Constraint::Min(1)])
                    .split(row);
                f.render_widget(
                    Paragraph::new(Span::styled(*label, Style::default().fg(th.accent))),
                    cols[0],
                );
                render_line_field_hinted(f, cols[1], ed, field == i as u8, *mask, placeholder, th);
                if let Some(app) = app {
                    app.push_mouse_hit(
                        MouseLayer::Overlay,
                        row,
                        MouseHitTarget::RemoteWizardRow(i),
                    );
                }
            }

            if recent_rows > 0 {
                let items: Vec<ListItem> = w
                    .recent
                    .iter()
                    .take(5)
                    .enumerate()
                    .map(|(i, u)| {
                        let style = if recent_sel == Some(i) {
                            Style::default()
                                .bg(th.accent)
                                .fg(th.bg)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().fg(th.dim)
                        };
                        ListItem::new(Line::styled(
                            format!("{:pad$}{u}", "", pad = label_w as usize),
                            style,
                        ))
                    })
                    .collect();
                f.render_widget(List::new(items), rows[1]);
                if let Some(app) = app {
                    for i in 0..w.recent.len().min(5) {
                        app.push_mouse_hit(
                            MouseLayer::Overlay,
                            Rect::new(rows[1].x, rows[1].y + i as u16, rows[1].width, 1),
                            MouseHitTarget::RemoteWizardRow(10 + i),
                        );
                    }
                }
            }
        }
        RemoteStage::Loading => {
            let msg = w.flow.busy().map_or(s.git_loading_refs, |p| p.label(s));
            let width = (msg
                .len()
                .max(s.git_loading_hint.len())
                .max(title.chars().count()) as u16
                + 4)
            .min(f.area().width);
            let area = centered_rect(width, 3, f.area());
            f.render_widget(Clear, area);
            let block = panel_hinted(title.to_string(), s.git_loading_hint, th);
            let inner = block.inner(area);
            f.render_widget(block, area);
            f.render_widget(
                Paragraph::new(Span::styled(
                    msg,
                    Style::default().fg(th.text).add_modifier(Modifier::BOLD),
                )),
                inner,
            );
        }
        RemoteStage::PickRef => {
            let labels: Vec<String> = w.flow.ref_choices(s).into_iter().map(|r| r.label).collect();
            let first = draw_filter_list(
                f,
                s,
                s.git_pick_ref_title,
                &w.filter,
                &labels,
                w.sel,
                th,
                &w.list_scroll,
            );
            register_remote_filter_hits(f, app, &w.filter, &labels, first);
        }
        RemoteStage::PickFile => {
            let files = w.flow.pickable_files();
            let first = draw_filter_list(
                f,
                s,
                s.git_pick_file_title,
                &w.filter,
                &files,
                w.sel,
                th,
                &w.list_scroll,
            );
            register_remote_filter_hits(f, app, &w.filter, &files, first);
        }
        RemoteStage::PickWorkspaceFilter => {
            let labels: Vec<&str> = WorkspaceGitFilter::ALL.iter().map(|f| f.label(s)).collect();
            draw_choice_popup(
                f,
                s.git_pick_workspace_filter_title,
                &labels,
                w.sel,
                s.git_workspace_filter_hint,
                th,
            );
            if let Some(app) = app {
                let content_w = labels
                    .iter()
                    .map(|s| s.chars().count())
                    .max()
                    .unwrap_or(20)
                    .max(s.git_pick_workspace_filter_title.chars().count());
                let w = (content_w as u16 + 6).clamp(30, f.area().width.max(1));
                let h = (labels.len() as u16 + 2).min(f.area().height.max(1));
                let area = centered_rect(w, h, f.area());
                let inner = Rect {
                    x: area.x.saturating_add(1),
                    y: area.y.saturating_add(1),
                    width: area.width.saturating_sub(2),
                    height: area.height.saturating_sub(2),
                };
                for i in 0..labels.len().min(inner.height as usize) {
                    app.push_mouse_hit(
                        MouseLayer::Overlay,
                        Rect::new(inner.x, inner.y + i as u16, inner.width, 1),
                        MouseHitTarget::RemoteWizardRow(i),
                    );
                }
            }
        }
        RemoteStage::Error => {
            let e = w.flow.error().unwrap_or_default().to_string();
            let width = (f.area().width * 6 / 10).max(40);
            let area = centered_rect(width, 7, f.area());
            f.render_widget(Clear, area);
            let block = panel_hinted(title.to_string(), s.git_error_hint, th);
            let inner = block.inner(area);
            f.render_widget(block, area);
            f.render_widget(
                Paragraph::new(e)
                    .style(Style::default().fg(th.err))
                    .wrap(Wrap { trim: true }),
                inner,
            );
        }
    }

    /// `first` is the scroll offset the list was actually drawn with — taken
    /// from the draw call rather than recomputed here, because the viewport is
    /// carried between frames now and only the render knows where it ended up.
    fn register_remote_filter_hits(
        f: &Frame,
        app: Option<&TuiApp>,
        filter: &str,
        items: &[String],
        first: usize,
    ) {
        let Some(app) = app else {
            return;
        };
        let w = (f.area().width * 7 / 10).max(50);
        let h = (f.area().height * 7 / 10).max(10);
        let area = centered_rect(w, h, f.area());
        let inner = Rect {
            x: area.x.saturating_add(1),
            y: area.y.saturating_add(1),
            width: area.width.saturating_sub(2),
            height: area.height.saturating_sub(2),
        };
        let rows = Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).split(inner);
        let vis = filter_indices(items.iter().map(|s| s.as_str()), filter);
        if vis.is_empty() {
            return;
        }
        let visible = rows[1].height as usize;
        app.push_mouse_hit(
            MouseLayer::Overlay,
            rows[1],
            MouseHitTarget::Scroll(MouseScrollTarget::RemoteWizard),
        );
        for row in first..vis.len().min(first + visible) {
            app.push_mouse_hit(
                MouseLayer::Overlay,
                Rect::new(
                    rows[1].x,
                    rows[1].y + (row - first) as u16,
                    rows[1].width,
                    1,
                ),
                MouseHitTarget::RemoteWizardRow(row),
            );
        }
    }
}