petitcarnets 0.0.11

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
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
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
//! A notebook: write a note, read a guide under it, and export the note
//! into the guide. An original petitcarnets example, not a port of a
//! Bubble Tea one: three Bubbles components used together the way an
//! application would, through the public API only. A text area to write
//! in, a viewport over a long rendered document that scrolls with
//! Bubbles' keys, and a progress bar that follows an export task's
//! progress messages. Each component keeps Bubbles' default key map,
//! and the help at the bottom shows the focused one's keys.
//!
//! Tab moves between the note and the guide; ctrl+s exports the note
//! into the guide, a line a step, the bar following the task; ? shows
//! every key while the guide has the focus; esc or ctrl+c quits.
//!
//! The export task writes on a timer (`tea::tick`) rather than a thread,
//! so the tests run it on the virtual clock.
//!
//! `cargo run --example notes`

use petitcarnets as tea;
use std::time::Duration;
use tea::bubbles::help;
use tea::bubbles::key::Binding;
use tea::bubbles::{progress, textarea, viewport};
use tea::style::{Color, Style, height};

/// The text area's rows.
pub(crate) const EDITOR_HEIGHT: usize = 5;
/// How long the task takes to write a line.
pub(crate) const STEP: Duration = Duration::from_millis(200);
/// The rows that are neither the guide nor the help: the note and its
/// title, the guide's title, the bar, the status and three blank lines.
const CHROME: usize = EDITOR_HEIGHT + 8;

const TITLE: Style = Style::new().bold(true).foreground(Color::Palette(212));
const DIM: Style = Style::new().faint(true);
const HEADING: Style = Style::new().bold(true).foreground(Color::Palette(99));
const QUOTE: Style = Style::new().italic(true).foreground(Color::Palette(244));

/// The guide, in the little Markdown [`render`] reads.
pub(crate) const GUIDE: &str = "# Keeping a notebook

A notebook is a small thing to carry and a large thing to keep. Write in the note above; ctrl+s copies it to the end of this guide.

## Before you start

- Write the date at the top of each page, every time, even when the page is only a list.
- Number the pages, so that an index at the back can find them again later.
- Leave the last pages blank for that index.

## While you write

Write in full sentences when you can. A note that made sense on the train makes less sense a month later, and none at all a year later.

Draw a line under each entry. The line says the thought is finished, and the next one starts fresh.

- Short entries are fine.
- Wrong entries are fine; cross them out, do not tear them out.
- Copy what you will look up again: a measurement, a recipe, a phone number.

## Reading it back

Once a week, read the last week's pages. Mark what still matters with a star in the margin, and copy the stars to the index.

## Moving around this guide

The guide is a viewport with Bubbles' keys: up and down or k and j move a line, f, space and pgdown a page down, b and pgup a page up, d and u half a page.

Left and right, or h and l, move sideways, for the lines too long for the window, like this one, which goes on past the edge to show it.

## A last word

Fill one, and start the next. A shelf of full notebooks is the best record of a life there is, and the cheapest.";

/// The guide as the terminal shows it: headings in colour, bullets for
/// dashes, the exported notes at the end.
pub(crate) fn render(guide: &str, notes: &[String]) -> String {
    let mut out: Vec<String> = guide.lines().map(render_line).collect();
    if !notes.is_empty() {
        out.extend([String::new(), HEADING.paint("Your notes"), String::new()]);
        out.extend(
            notes
                .iter()
                .map(|n| format!("  {}", QUOTE.paint(&format!("│ {n}")))),
        );
    }
    out.join("\n")
}

fn render_line(line: &str) -> String {
    if let Some(title) = line.strip_prefix("# ") {
        HEADING.underline(true).paint(title)
    } else if let Some(title) = line.strip_prefix("## ") {
        HEADING.paint(title)
    } else if let Some(item) = line.strip_prefix("- ") {
        format!("  • {item}")
    } else {
        line.to_owned()
    }
}

/// The application's messages: its components' own, routed down with
/// [`tea::Msg::route`] and back up with [`tea::Cmd::map`], and the
/// export task's progress.
pub(crate) enum Msg {
    Note(textarea::Msg),
    Bar(progress::Msg),
    Progress(Progress),
}

/// The task wrote a line: `written` of `total` now.
pub(crate) struct Progress {
    pub(crate) line: String,
    pub(crate) written: u32,
    pub(crate) total: u32,
}

/// An export under way: the note's lines and how many are written.
pub(crate) struct Export {
    pub(crate) lines: Vec<String>,
    pub(crate) written: Vec<String>,
}

/// Which component has the keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Focus {
    Note,
    Guide,
}

/// The application's own keys; the components bring theirs.
pub(crate) struct Keys {
    pub(crate) switch: Binding,
    pub(crate) export: Binding,
    pub(crate) help: Binding,
    pub(crate) quit: Binding,
}

impl Default for Keys {
    fn default() -> Self {
        Self {
            switch: Binding::new(&["tab"]).with_help("tab", "switch"),
            export: Binding::new(&["ctrl+s"]).with_help("ctrl+s", "export"),
            help: Binding::new(&["?"]).with_help("?", "more"),
            quit: Binding::new(&["esc", "ctrl+c"]).with_help("esc", "quit"),
        }
    }
}

pub(crate) struct Model {
    pub(crate) note: textarea::Model,
    pub(crate) guide: viewport::Model,
    pub(crate) bar: progress::Model,
    pub(crate) help: help::Model,
    pub(crate) keys: Keys,
    pub(crate) focus: Focus,
    pub(crate) export: Option<Export>,
    pub(crate) notes: Vec<String>,
    pub(crate) status: String,
    pub(crate) size: (usize, usize),
}

pub(crate) fn new_model() -> Model {
    let mut note = textarea::Model::new();
    note.placeholder = "Write a note...".into();
    note.set_virtual_cursor(false);
    let _ = note.focus();
    let mut guide = viewport::Model::new(0, 0);
    guide.fill_height = true;
    guide.set_content(&render(GUIDE, &[]));
    let mut m = Model {
        note,
        guide,
        bar: progress::Model::new().with_default_blend(),
        help: help::Model::new(),
        keys: Keys::default(),
        focus: Focus::Note,
        export: None,
        notes: Vec::new(),
        status: "Not exported yet.".into(),
        size: (0, 0),
    };
    m.sync_keys();
    m
}

/// The note's message, if `m` is one.
const fn note_msg(m: &Msg) -> Option<textarea::Msg> {
    match m {
        Msg::Note(n) => Some(*n),
        _ => None,
    }
}

/// The bar's message, if `m` is one.
const fn bar_msg(m: &Msg) -> Option<progress::Msg> {
    match m {
        Msg::Bar(f) => Some(*f),
        _ => None,
    }
}

/// `n` of `total` as a fraction.
fn fraction(n: u32, total: u32) -> f64 {
    f64::from(n) / f64::from(total.max(1))
}

impl Model {
    /// Turns the application's keys on and off with the focus and the
    /// task: `?` types into the note, and one export runs at a time.
    fn sync_keys(&mut self) {
        self.keys.help.set_enabled(self.focus == Focus::Guide);
        self.keys.export.set_enabled(self.export.is_none());
    }

    /// Sizes the components to the window, the guide taking what the
    /// others leave.
    fn layout(&mut self) {
        let (w, h) = self.size;
        self.note.set_width(w);
        self.note.set_height(EDITOR_HEIGHT);
        self.bar.set_width(w);
        self.guide.set_width(w);
        self.help.set_width(w);
        let help = height(&self.help.view(&HelpKeys(self)));
        self.guide
            .set_height(h.saturating_sub(CHROME + help).max(1));
    }

    /// The application's own keys, `None` for a key the components get.
    fn key(&mut self, k: &tea::Key) -> Option<tea::Cmd<Msg>> {
        let cmd = if self.keys.quit.matches(k) {
            tea::quit()
        } else if self.keys.switch.matches(k) {
            self.switch_focus()
        } else if self.keys.export.matches(k) {
            self.start_export()
        } else if self.keys.help.matches(k) {
            self.help.show_all = !self.help.show_all;
            tea::Cmd::none()
        } else {
            return None;
        };
        self.sync_keys();
        self.layout();
        Some(cmd)
    }

    fn switch_focus(&mut self) -> tea::Cmd<Msg> {
        if self.focus == Focus::Note {
            self.focus = Focus::Guide;
            self.note.blur();
            tea::Cmd::none()
        } else {
            self.focus = Focus::Note;
            self.note.focus().map(Msg::Note)
        }
    }

    /// Starts the task on the note's lines.
    fn start_export(&mut self) -> tea::Cmd<Msg> {
        let lines: Vec<String> = self.note.value().lines().map(str::to_owned).collect();
        if lines.iter().all(|l| l.trim().is_empty()) {
            "Nothing to export yet.".clone_into(&mut self.status);
            return tea::Cmd::none();
        }
        self.export = Some(Export {
            lines,
            written: Vec::new(),
        });
        "Exporting...".clone_into(&mut self.status);
        tea::batch([self.bar.set_percent(0.0).map(Msg::Bar), self.write_next()])
    }

    /// The task's next step: it writes a line and reports how far it is.
    fn write_next(&self) -> tea::Cmd<Msg> {
        let Some(export) = &self.export else {
            return tea::Cmd::none();
        };
        let n = export.written.len();
        let line = export.lines[n].clone();
        let total = u32::try_from(export.lines.len()).unwrap_or(u32::MAX);
        let written = u32::try_from(n + 1).unwrap_or(u32::MAX);
        tea::tick(STEP, move |_| {
            Msg::Progress(Progress {
                line,
                written,
                total,
            })
        })
    }

    /// A step done: the bar follows, and the last one puts the note in
    /// the guide.
    fn progress(&mut self, p: Progress) -> tea::Cmd<Msg> {
        let Some(export) = &mut self.export else {
            return tea::Cmd::none();
        };
        export.written.push(p.line);
        let bar = self
            .bar
            .set_percent(fraction(p.written, p.total))
            .map(Msg::Bar);
        if p.written < p.total {
            self.status = format!("Exporting: {} of {} lines", p.written, p.total);
            return tea::batch([bar, self.write_next()]);
        }
        if let Some(done) = self.export.take() {
            self.notes.extend(done.written);
        }
        self.status = format!("Exported {} lines into the guide.", p.total);
        self.guide.set_content(&render(GUIDE, &self.notes));
        self.guide.goto_bottom();
        self.sync_keys();
        bar
    }

    /// Passes a message down: the note's and the bar's own through
    /// `route`, keys to the guide only while it has the focus (a blurred
    /// text area ignores them itself).
    fn children(&mut self, msg: &tea::Msg<Msg>) -> tea::Cmd<Msg> {
        let mut cmds = Vec::new();
        if let Some(m) = msg.route(note_msg) {
            cmds.push(self.note.update(&m).map(Msg::Note));
        }
        if let Some(m) = msg.route(bar_msg) {
            cmds.push(self.bar.update(&m).map(Msg::Bar));
        }
        let key = matches!(msg, tea::Msg::KeyPress(_));
        if !key || self.focus == Focus::Guide {
            cmds.push(self.guide.update(msg));
        }
        tea::batch(cmds)
    }

    fn title(&self, name: &str, focus: Focus, info: &str) -> String {
        let style = if self.focus == focus { TITLE } else { DIM };
        format!("{}  {}", style.paint(name), DIM.paint(info))
    }
}

impl tea::Model for Model {
    type Msg = Msg;

    fn update(&mut self, msg: tea::Msg<Msg>) -> tea::Cmd<Msg> {
        if let tea::Msg::KeyPress(k) = &msg {
            if let Some(cmd) = self.key(k) {
                return cmd;
            }
        }
        match msg {
            tea::Msg::WindowSize(size) => {
                self.size = (usize::from(size.width), usize::from(size.height));
                self.layout();
                tea::Cmd::none()
            }
            tea::Msg::App(Msg::Progress(p)) => self.progress(p),
            msg => self.children(&msg),
        }
    }

    fn view(&self) -> tea::View {
        let lines = format!(
            "line {} of {}",
            self.note.line() + 1,
            self.note.line_count()
        );
        let read = format!("{:.0}%", self.guide.scroll_percent() * 100.0);
        let content = [
            self.title("Note", Focus::Note, &lines),
            self.note.view(),
            String::new(),
            self.title("Guide", Focus::Guide, &read),
            self.guide.view(),
            String::new(),
            self.bar.view(),
            DIM.paint(&self.status),
            String::new(),
            self.help.view(&HelpKeys(self)),
        ]
        .join("\n");
        let mut v = tea::View::new(content)
            .with_alt_screen(true)
            .with_mouse_mode(tea::MouseMode::CellMotion);
        if let Some(mut c) = self.note.cursor() {
            c.y += 1;
            v = v.with_cursor(c);
        }
        v
    }
}

/// The help for whichever component has the focus, then the
/// application's keys.
pub(crate) struct HelpKeys<'a>(pub(crate) &'a Model);

impl help::KeyMap for HelpKeys<'_> {
    fn short_help(&self) -> Vec<Binding> {
        let (m, app) = (self.0, &self.0.keys);
        let mut keys = match m.focus {
            Focus::Note => {
                let k = &m.note.key_map;
                vec![k.insert_newline.clone(), k.word_forward.clone()]
            }
            Focus::Guide => {
                let k = &m.guide.key_map;
                vec![k.down.clone(), k.page_down.clone()]
            }
        };
        keys.extend([&app.switch, &app.export, &app.help, &app.quit].map(Binding::clone));
        keys
    }

    fn full_help(&self) -> Vec<Vec<Binding>> {
        let (m, app) = (self.0, &self.0.keys);
        let mut groups = match m.focus {
            Focus::Note => {
                let k = &m.note.key_map;
                vec![
                    vec![
                        &k.line_previous,
                        &k.line_next,
                        &k.character_backward,
                        &k.character_forward,
                    ],
                    vec![
                        &k.word_backward,
                        &k.word_forward,
                        &k.line_start,
                        &k.line_end,
                    ],
                    vec![
                        &k.insert_newline,
                        &k.delete_word_backward,
                        &k.input_begin,
                        &k.input_end,
                    ],
                ]
            }
            Focus::Guide => {
                let k = &m.guide.key_map;
                vec![
                    vec![&k.up, &k.down, &k.left, &k.right],
                    vec![&k.page_down, &k.page_up, &k.half_page_down, &k.half_page_up],
                ]
            }
        };
        groups.push(vec![&app.switch, &app.export, &app.help, &app.quit]);
        groups
            .into_iter()
            .map(|g| g.into_iter().cloned().collect())
            .collect()
    }
}

// `pub(crate)`: `tests/bubbles_examples.rs` includes this file for its model.
pub(crate) fn main() -> Result<(), tea::Error> {
    let _ = tea::Program::new(new_model()).run()?;
    Ok(())
}