edamame 0.1.1

A fast TUI Markdown editor and viewer
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
//! Body content for the update-check modal.
//!
//! Pure content builder in the [`super::about`] mold: the modal adapter
//! (`crate::app::modal::update`) owns the status and the spinner
//! timing and calls [`body_lines`] each frame with plain values, so
//! this module stays free of any `app`-layer dependency and is testable
//! as a function of its inputs.  [`UpdateReport`] is deliberately the
//! `ui` layer's own vocabulary rather than a re-used
//! `app::update_check::ReleaseStatus` — nothing under `src/ui/` imports
//! `crate::app`, and this is not the module to start.
//!
//! Release notes arrive here already truncated, control-stripped and
//! capped (`app::update_check::parse::sanitize_notes`), and are then
//! given *structural* styling only — see [`note_lines`]: a heading is
//! bolded, a list marker becomes a bullet, and nothing else about a
//! line is interpreted.  They are **never** re-parsed as Markdown:
//! this is text fetched from the network, and a parser would let a
//! release body choose emphasis, links, images, and layout inside an
//! app modal.  `**bold**` and `[text](url)` therefore stay literal,
//! which is correct — it is what the release page says.

use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

use crate::config::Theme;

/// Braille spinner frames, advanced by the modal while a check is in
/// flight.
pub const SPINNER_FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

/// What the modal is reporting right now.
pub enum UpdateReport<'a> {
    /// A check is in flight; nothing conclusive to show yet.
    Checking { spinner_frame: usize },
    /// The latest release is not newer than the installed build.
    UpToDate { tag: &'a str },
    /// A newer release exists, with whatever notes it carried.
    Available { tag: &'a str, notes: &'a [String] },
    /// A release was found but the two versions could not be ordered
    /// (a pre-release or build suffix, or a tag not shaped like a
    /// version).  Both numbers are shown and the verdict says so —
    /// claiming "up to date" over two rows that disagree is the state
    /// this variant exists to prevent.
    Inconclusive { tag: &'a str },
    /// The check could not be completed.
    Failed,
}

/// Left column of the two version rows, wide enough for the longer
/// label plus a separating space, so the values line up under each
/// other.
const VERSION_LABEL_WIDTH: usize = "Installed version: ".len();

/// Build the modal body.  `installed` is the bare Cargo version
/// (`0.1.0`); the `v` prefix is added here so it reads like a tag.
///
/// Both conclusive states share the same shape — a one-line verdict,
/// then the two version rows — so the numbers are read off a table
/// rather than out of a sentence, and moving between the two states
/// doesn't rearrange the page.
pub fn body_lines(theme: &Theme, report: UpdateReport<'_>, installed: &str) -> Vec<Line<'static>> {
    match report {
        UpdateReport::Checking { spinner_frame } => {
            let frame = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];
            vec![Line::from(Span::styled(
                format!("Checking for updates… {frame}"),
                theme.modal_description,
            ))]
        }
        UpdateReport::UpToDate { tag } => {
            let mut out = vec![
                Line::from(Span::styled("edamame is up to date.".to_owned(), theme.h1)),
                Line::raw(""),
            ];
            out.extend(version_rows(theme, installed, tag));
            out
        }
        UpdateReport::Inconclusive { tag } => {
            let mut out = vec![
                Line::from(Span::styled(
                    "Couldn't compare versions.".to_owned(),
                    theme.h1,
                )),
                Line::raw(""),
            ];
            out.extend(version_rows(theme, installed, tag));
            out.push(Line::raw(""));
            out.push(Line::from(Span::styled(
                "The latest release isn't named like a plain version number, so \
                 edamame can't tell whether it is newer. Check the release page \
                 to be sure."
                    .to_owned(),
                theme.modal_description,
            )));
            out
        }
        UpdateReport::Failed => vec![
            Line::from(Span::styled(
                "Couldn't check for updates.".to_owned(),
                theme.h1,
            )),
            Line::raw(""),
            Line::from(Span::styled(
                "GitHub could not be reached. Your installed version is unchanged.".to_owned(),
                theme.modal_description,
            )),
        ],
        UpdateReport::Available { tag, notes } => {
            let mut out = vec![
                Line::from(Span::styled("Update available.".to_owned(), theme.h1)),
                Line::raw(""),
            ];
            out.extend(version_rows(theme, installed, tag));
            // A release cut without a matching CHANGELOG.md heading has
            // no notes.  Emit nothing rather than an empty "What's new"
            // heading over blank space — the version alone is still the
            // news.
            if !notes.is_empty() {
                out.push(Line::raw(""));
                out.extend(note_lines(notes));
            }
            out
        }
    }
}

/// Glyph substituted for a list marker (`-`, `*`, `+`).
const BULLET: &str = "•";

/// Render the release notes with *structural* styling only: an ATX
/// heading loses its `#` run and is bolded, a list marker becomes a
/// [`BULLET`], and the blank line Keep a Changelog puts under every
/// heading is dropped.  Everything else is emitted verbatim.
///
/// This is deliberately not Markdown rendering, and the distinction is
/// the whole safety argument.  The notes are remote text; parsing them
/// would let a release body choose emphasis, links, images, and layout
/// inside an app modal.  Here the *line* is classified locally, over
/// text `parse::sanitize_notes` has already bounded, and the outcome is
/// a choice between three fixed local styles.  A release body can make
/// a line a heading; it cannot make it anything this function doesn't
/// already know how to draw.  Don't grow this into an inline parser —
/// `**bold**` and `[text](url)` stay literal on purpose.
///
/// A wrapped line's continuation starts at column 0: `ModalView` owns
/// the wrapping (`Paragraph` with `Wrap { trim: false }`), so there is
/// no hanging indent to be had without pre-wrapping the body, which
/// double-wraps at narrow widths — see the modal-sizing rule in
/// `AGENTS.md`.
fn note_lines(notes: &[String]) -> Vec<Line<'static>> {
    let mut out: Vec<Line<'static>> = Vec::with_capacity(notes.len());
    let mut after_heading = false;
    for raw in notes {
        if let Some(text) = heading_text(raw) {
            // A blank before a heading separates the sections and is
            // kept; the one *after* it is Keep a Changelog's shape
            // rather than anything the reader needs, and rows are the
            // scarce resource in a modal.
            out.push(Line::from(Span::styled(
                text.to_owned(),
                Style::new().add_modifier(Modifier::BOLD),
            )));
            after_heading = true;
            continue;
        }
        if raw.trim().is_empty() {
            let previous_was_blank = out.last().is_some_and(|l| l.width() == 0);
            if !after_heading && !previous_was_blank && !out.is_empty() {
                out.push(Line::raw(""));
            }
            continue;
        }
        after_heading = false;
        out.push(Line::raw(bulleted(raw)));
    }
    while out.last().is_some_and(|l| l.width() == 0) {
        out.pop();
    }
    out
}

/// The text of an ATX heading (`## Added` → `Added`), or `None` for any
/// other line.  CommonMark wants one to six `#` followed by a space;
/// the closing-`#` form is not worth recognizing in a changelog.
fn heading_text(line: &str) -> Option<&str> {
    let hashes = line.len() - line.trim_start_matches('#').len();
    (1..=6)
        .contains(&hashes)
        .then(|| line[hashes..].strip_prefix(' '))
        .flatten()
        .map(str::trim)
        .filter(|text| !text.is_empty())
}

/// A list item with its marker swapped for [`BULLET`], indentation
/// preserved so nesting still reads; any other line unchanged.
fn bulleted(line: &str) -> String {
    let indent = line.len() - line.trim_start().len();
    let rest = &line[indent..];
    match rest
        .strip_prefix("- ")
        .or_else(|| rest.strip_prefix("* "))
        .or_else(|| rest.strip_prefix("+ "))
    {
        Some(item) => format!("{}{BULLET} {item}", &line[..indent]),
        None => line.to_owned(),
    }
}

/// The installed / latest pair, in that order — what the user has
/// first, then what is out there, so the comparison reads downward.
fn version_rows(theme: &Theme, installed: &str, latest: &str) -> [Line<'static>; 2] {
    [
        version_row(theme, "Installed version:", format!("v{installed}")),
        version_row(theme, "Latest release:", latest.to_owned()),
    ]
}

/// One label/value row.  The label is padded to a fixed column rather
/// than styled into a separate aligned block, because the modal body is
/// left-aligned text: padding is all the alignment there is.
fn version_row(theme: &Theme, label: &str, value: String) -> Line<'static> {
    Line::from(vec![
        Span::styled(
            format!("{label:<width$}", width = VERSION_LABEL_WIDTH),
            theme.text_muted(),
        ),
        Span::raw(value),
    ])
}

#[cfg(test)]
mod tests {
    use super::*;

    fn theme() -> &'static Theme {
        Box::leak(Box::new(Theme::default()))
    }

    fn text(lines: &[Line<'static>]) -> String {
        lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn checking_shows_the_requested_spinner_frame() {
        let body = text(&body_lines(
            theme(),
            UpdateReport::Checking { spinner_frame: 2 },
            "0.1.0",
        ));
        assert!(body.contains(SPINNER_FRAMES[2]), "{body}");
    }

    #[test]
    fn the_spinner_frame_wraps_rather_than_panicking() {
        let body = text(&body_lines(
            theme(),
            UpdateReport::Checking {
                spinner_frame: SPINNER_FRAMES.len() + 1,
            },
            "0.1.0",
        ));
        assert!(body.contains(SPINNER_FRAMES[1]), "{body}");
    }

    #[test]
    fn up_to_date_states_the_verdict_then_both_versions() {
        let body = text(&body_lines(
            theme(),
            UpdateReport::UpToDate { tag: "v0.1.0" },
            "0.1.0",
        ));
        // The verdict is a sentence on its own; the numbers are rows.
        assert!(body.starts_with("edamame is up to date."), "{body}");
        assert!(body.contains("Installed version: v0.1.0"), "{body}");
        assert!(body.contains("Latest release:    v0.1.0"), "{body}");
    }

    #[test]
    fn the_two_version_rows_align_their_values() {
        // The labels differ in length, so the shorter one is padded —
        // a left-aligned body has no other way to make a column.
        let body = text(&body_lines(
            theme(),
            UpdateReport::UpToDate { tag: "v0.2.0" },
            "0.1.0",
        ));
        let value = |label: &str| {
            body.lines()
                .find(|l| l.starts_with(label))
                .map(|l| l[VERSION_LABEL_WIDTH..].to_owned())
                .expect("row present")
        };
        // Both values start at exactly the label column, so the shorter
        // label must have been padded out to it.
        assert_eq!(value("Installed version:"), "v0.1.0");
        assert_eq!(value("Latest release:"), "v0.2.0");
    }

    #[test]
    fn inconclusive_never_claims_a_verdict_it_did_not_reach() {
        let body = text(&body_lines(
            theme(),
            UpdateReport::Inconclusive { tag: "v0.2.0-rc1" },
            "0.1.0",
        ));
        assert!(body.starts_with("Couldn't compare versions."));
        // Both numbers are still shown — that is the whole point.
        assert!(body.contains("Installed version:"), "{body}");
        assert!(body.contains("v0.1.0"), "{body}");
        assert!(body.contains("v0.2.0-rc1"), "{body}");
        // And it must not assert the thing it cannot know.
        assert!(!body.contains("up to date"));
        assert!(!body.contains("Update available"));
    }

    #[test]
    fn failed_says_so_without_blaming_the_installed_version() {
        let body = text(&body_lines(theme(), UpdateReport::Failed, "0.1.0"));
        assert!(body.contains("Couldn't check for updates"), "{body}");
        assert!(body.contains("unchanged"), "{body}");
    }

    #[test]
    fn available_lists_the_notes_under_the_versions() {
        let notes = vec![
            "### Added".to_owned(),
            "- **bold** stays literal".to_owned(),
        ];
        let body = text(&body_lines(
            theme(),
            UpdateReport::Available {
                tag: "v0.2.0",
                notes: &notes,
            },
            "0.1.0",
        ));
        assert!(body.starts_with("Update available."), "{body}");
        assert!(body.contains("Installed version: v0.1.0"), "{body}");
        assert!(body.contains("Latest release:    v0.2.0"), "{body}");
        // Structural styling only: the heading loses its `#` run and
        // the marker becomes a bullet…
        assert!(body.contains("\nAdded"), "{body}");
        // …but nothing *inside* a line is interpreted.
        assert!(body.contains("• **bold** stays literal"), "{body}");
    }

    #[test]
    fn a_heading_is_bolded_and_a_list_marker_becomes_a_bullet() {
        let notes = vec!["## Fixed".to_owned(), "* a bug".to_owned()];
        let lines = note_lines(&notes);
        assert_eq!(text(&lines), "Fixed\n• a bug");
        assert!(
            lines[0].spans[0]
                .style
                .add_modifier
                .contains(Modifier::BOLD),
            "the heading carries the only styling this function applies"
        );
        assert_eq!(
            lines[1].spans[0].style,
            Style::default(),
            "a list item is plain text with a swapped marker"
        );
    }

    #[test]
    fn the_blank_under_a_heading_goes_but_the_one_above_it_stays() {
        // Keep a Changelog's shape: `### Added`, blank, items, blank,
        // `### Changed`.  Rows are scarce in a modal, and the blank
        // under a heading separates nothing.
        let notes =
            ["### Added", "", "- one", "", "### Changed", "", "- two", ""].map(str::to_owned);
        assert_eq!(text(&note_lines(&notes)), "Added\n• one\n\nChanged\n• two");
    }

    #[test]
    fn nesting_and_ordinary_prose_are_left_alone() {
        let notes = [
            "Some prose - with a dash.",
            "- top",
            "  - nested",
            "1. numbered",
            "#not-a-heading",
        ]
        .map(str::to_owned);
        assert_eq!(
            text(&note_lines(&notes)),
            "Some prose - with a dash.\n• top\n  • nested\n1. numbered\n#not-a-heading"
        );
    }

    #[test]
    fn available_without_notes_omits_the_notes_block() {
        let body = body_lines(
            theme(),
            UpdateReport::Available {
                tag: "v0.2.0",
                notes: &[],
            },
            "0.1.0",
        );
        assert_eq!(
            body.len(),
            4,
            "headline, blank, and the two version rows — nothing else"
        );
        assert!(!text(&body).ends_with('\n'));
    }
}