jj-compose 0.2.2

Easily split big jujutsu working copy changes into atomic commits
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
//! Turning application state into a frame.

use jj_compose_core::{Field, HEADER_HARD_LIMIT, HEADER_SOFT_LIMIT, Split, overview};
use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style, Stylize},
    text::{Line, Span},
    widgets::{Block, Paragraph},
};
use ratatui_textarea::{CursorMove, TextArea, WrapMode};

use super::{App, Focus, Keymap, Status, View, plural};
use crate::{diff::Mark, vim};

/// The narrowest terminal that shows the diff beside the form rather than
/// above it.
const SIDE_BY_SIDE_MIN_WIDTH: u16 = 100;

impl App {
    pub(super) fn draw(&mut self, frame: &mut Frame<'_>) {
        let [main, status] =
            Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(frame.area());
        // Zoom lasts only while the diff has focus.
        self.zoomed &= self.focus == Focus::Diff;
        // Side by side when there's room; stacked on narrow terminals.
        // Navigation reads `is_vertical`, so it is set from the layout
        // actually drawn: `h` goes wherever the diff is on screen.
        self.is_vertical = main.width < SIDE_BY_SIDE_MIN_WIDTH;
        let [diff_area, form_area] = if self.zoomed {
            [main, Rect::default()]
        } else if !self.is_vertical {
            Layout::horizontal([Constraint::Percentage(50); 2]).areas(main)
        } else {
            Layout::vertical([Constraint::Percentage(40), Constraint::Fill(1)]).areas(main)
        };

        let accent = self.accent();

        // While splitting, the pane is one hunk and a tally, not the diff.
        if self.overview.is_some() && self.choosing() {
            self.draw_overview(frame, diff_area, status, accent);
            return;
        }

        if self.choosing() {
            if self.split.as_ref().is_some_and(Split::is_divided) {
                self.draw_divided(frame, diff_area, status);
            } else {
                self.draw_hunk(frame, diff_area, status, accent);
            }
            return;
        }

        // The pane title is built up in pieces: change ID, then the file at the
        // top (commit 2), then the search (commit 4).
        let mut title = vec![
            Span::raw(format!(" Diff {} ", self.change_id)),
            immutable_marker(self.target.immutable),
        ];
        title.retain(|span| !span.content.is_empty());
        if let Some((n, file)) = self.diff.current_file() {
            let count = self.diff.file_count();
            title.push(Span::raw(format!("· {n}/{count} {} ", file.path)));
            title.push(Span::styled(format!("+{} ", file.added), Color::Green));
            title.push(Span::styled(format!("-{} ", file.removed), Color::Red));
        }
        if let Some((query, n, count)) = self.diff.search_status() {
            title.push(Span::raw(format!("· /{query} {n}/{count} ")));
        }

        let block = pane(
            Line::from(title),
            (self.focus == Focus::Diff).then_some(accent),
        );
        self.diff.render(frame, diff_area, block);

        if !self.zoomed {
            match self.view {
                View::Structured => self.draw_form(frame, form_area),
                View::Raw => self.draw_raw(frame, form_area),
            }
        }
        frame.render_widget(self.status_line(), status);
    }

    /// The whole change as a list, in place of the single hunk.
    fn draw_overview(&self, frame: &mut Frame<'_>, area: Rect, status: Rect, accent: Color) {
        let Some(cursor) = self.overview else {
            return;
        };
        let rows = self.overview_rows();
        let assigned = self.split.as_ref().map_or(0, Split::assigned);
        let hunks = rows.iter().filter(|r| r.hunk.is_some()).count();
        let boxes = self.split.as_ref().map_or_else(Vec::new, Split::pending);
        let mut title = Line::from(vec![
            Span::raw(format!(" Hunks in {} ", self.change_id)),
            immutable_marker(self.target.immutable),
            Span::styled(format!("· {assigned} of {hunks} assigned "), Color::Green),
        ]);
        for span in legend(&boxes) {
            title.push_span(span);
        }

        // The selection, as hunk numbers, and each row's hunk number.
        let selected = self.visual.map(|from| {
            let to = self.split.as_ref().map_or(from, Split::at);
            from.min(to)..=from.max(to)
        });
        if let Some(range) = &selected {
            let n = range.end() - range.start() + 1;
            title.spans.push(Span::styled(
                format!("· VISUAL {n} selected "),
                Style::new().fg(Color::Magenta).add_modifier(Modifier::BOLD),
            ));
        }
        let mut hunk_of = Vec::with_capacity(rows.len());
        let mut next = 0;
        for row in &rows {
            hunk_of.push(row.hunk.map(|_| {
                next += 1;
                next - 1
            }));
        }
        let block = pane(title, Some(accent));
        let inner = block.inner(area);
        frame.render_widget(block, area);
        let height = usize::from(inner.height).max(1);
        // Keep the cursor in view without a scrollbar's worth of state.
        let top = cursor
            .saturating_sub(height / 2)
            .min(rows.len().saturating_sub(height));
        let lines: Vec<Line<'static>> = rows
            .iter()
            .enumerate()
            .skip(top)
            .take(height)
            .map(|(i, row)| {
                let in_selection = selected
                    .as_ref()
                    .zip(hunk_of[i])
                    .is_some_and(|(range, k)| range.contains(&k));
                overview_line(row, i == cursor, in_selection)
            })
            .collect();
        frame.render_widget(Paragraph::new(lines), inner);
        frame.render_widget(self.status_line(), status);
    }

    /// One hunk opened up, a line at a time, with where each line is going.
    fn draw_divided(&mut self, frame: &mut Frame<'_>, area: Rect, status: Rect) {
        let Some(split) = self.split.as_ref() else {
            return;
        };
        let (at, total, path) = (split.at(), split.total(), split.path().to_owned());
        let plan = split.line_plan().unwrap_or_default().to_vec();
        let cursor = split.line_at();
        let selection = self.visual_line.map(|from| (from, cursor));
        let Some(rows) = self.divided_rows(at, &plan, cursor, selection) else {
            return;
        };

        let taken = plan.iter().flatten().count();
        let mut title = vec![
            Span::raw(format!(" Divide {} ", self.change_id)),
            immutable_marker(self.target.immutable),
            Span::raw(format!("· hunk {}/{total} ", at + 1)),
            Span::raw(format!("· {path} · ")),
        ];
        // One character per line, so the division's shape stays visible
        // while the cursor is on one line of it.
        for (i, slot) in plan.iter().enumerate() {
            let (text, color) = match slot {
                Some(n) if *n < 10 => (char::from(b'0' + n).to_string(), box_color(*n)),
                Some(_) => ("+".to_owned(), Color::Gray),
                None => ("·".to_owned(), Color::DarkGray),
            };
            let text = if i == cursor {
                format!("[{text}]")
            } else {
                text
            };
            title.push(Span::styled(text, color));
        }
        title.push(Span::styled(
            format!(" · {taken}/{} taken ", plan.len()),
            Color::DarkGray,
        ));
        title.retain(|span| !span.content.is_empty());

        let line_box = split.box_of_line();
        let block = pane(
            Line::from(title),
            Some(line_box.map_or(Color::DarkGray, box_color)),
        );
        self.diff.render_divided(frame, area, block, at, &rows);
        frame.render_widget(self.status_line(), status);
    }

    /// Which patch lines the divided view draws, in order, and what to say
    /// about each.
    ///
    /// The order is the one `Patch::ordered_lines` gives: a removal next to
    /// the addition replacing it. That is also the order the lines are
    /// written in, so what is on screen is what will be committed.
    fn divided_rows(
        &self,
        at: usize,
        plan: &[Option<u8>],
        cursor: usize,
        selection: Option<(usize, usize)>,
    ) -> Option<Vec<(usize, Mark)>> {
        let id = self.diff.hunks().get(at)?.id;
        let patch = self.diff.patch();
        let hunk = patch.files().get(id.file)?.hunks.get(id.hunk)?;
        let mut nth = 0;
        Some(
            patch
                .ordered_lines(hunk)
                .into_iter()
                .map(|l| {
                    if matches!(patch.line(l).as_bytes().first(), Some(b'+' | b'-')) {
                        let mark = Mark::Line {
                            commit: plan.get(nth).copied().flatten(),
                            cursor: nth == cursor,
                            selected: selection
                                .is_some_and(|(lo, hi)| nth >= lo.min(hi) && nth <= lo.max(hi)),
                        };
                        nth += 1;
                        (l, mark)
                    } else {
                        (l, Mark::Context)
                    }
                })
                .collect(),
        )
    }

    /// One hunk filling the pane, with the plan's shape in the title.
    fn draw_hunk(&mut self, frame: &mut Frame<'_>, area: Rect, status: Rect, accent: Color) {
        let Some(split) = self.split.as_ref() else {
            return;
        };
        let (at, total, path) = (split.at(), split.total(), split.path().to_owned());
        let (assigned, commit) = (split.assigned(), split.box_of());
        let mut title = vec![
            Span::raw(format!(" Split {} ", self.change_id)),
            immutable_marker(self.target.immutable),
            Span::raw(format!("· hunk {}/{total} ", at + 1)),
            Span::raw(format!("· {path} · ")),
        ];
        // The strip is the whole plan at once: a digit per hunk in its box's
        // color, `·` for one left behind, brackets round the one on screen.
        title.extend(strip_spans(split.plan(), at));
        title.push(Span::styled(
            commit.map_or_else(
                || " · unassigned ".to_owned(),
                |n| format!(" · commit {n} "),
            ),
            commit.map_or(Color::DarkGray, box_color),
        ));
        title.push(Span::styled(
            format!("· {assigned}/{total} planned "),
            Color::DarkGray,
        ));
        title.retain(|span| !span.content.is_empty());
        // In split mode nothing is being typed, so the border is free to carry
        // the current hunk's box instead of the keymap's accent.
        let block = pane(Line::from(title), Some(commit.map_or(accent, box_color)));
        self.diff.render_hunk(frame, area, block, at);
        frame.render_widget(self.status_line(), status);
    }

    fn draw_form(&mut self, frame: &mut Frame<'_>, area: Rect) {
        // Trailers are usually a line or two; give the room to the prose.
        let trailer_rows = self.fields[Field::Trailers as usize].lines().len();
        let trailer_height = u16::try_from(trailer_rows.clamp(1, 4)).unwrap_or(4) + 2;
        let [top, subject, body, problem, solution, trailers] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Length(3),
            Constraint::Fill(1),
            Constraint::Fill(1),
            Constraint::Fill(1),
            Constraint::Length(trailer_height),
        ])
        .areas(area);
        let [ty, scope] =
            Layout::horizontal([Constraint::Percentage(40), Constraint::Fill(1)]).areas(top);
        let areas = [ty, scope, subject, body, problem, solution, trailers];

        let header_len = self.draft().header().chars().count();
        let accent = self.accent();
        for (field, area) in Field::ALL.into_iter().zip(areas) {
            let focused = self.focus == Focus::Editor && self.field == field;
            let editor = &mut self.fields[field as usize];
            editor.set_block(pane(
                field_title(field, header_len),
                focused.then_some(accent),
            ));
            editor.set_cursor_style(cursor_style(focused));
            frame.render_widget(&*editor, area);
        }
    }

    fn draw_raw(&mut self, frame: &mut Frame<'_>, area: Rect) {
        let header_len = self.raw.lines()[0].chars().count();
        let title = Line::from(vec![
            Span::raw(" Message (raw) "),
            header_counter(header_len),
        ]);
        let focused = self.focus == Focus::Editor;
        let accent = self.accent();
        self.raw.set_block(pane(title, focused.then_some(accent)));
        self.raw.set_cursor_style(cursor_style(focused));
        frame.render_widget(&self.raw, area);
    }

    /// Border color of the focused pane: green in Vim's Normal mode,
    /// yellow while typing.
    const fn accent(&self) -> Color {
        match (self.keymap, self.vim.mode) {
            (Keymap::Vim, vim::Mode::Insert) | (Keymap::Default, _) => Color::Yellow,
            (Keymap::Vim, _) => Color::Green,
        }
    }

    /// Bottom row: a pending message, or the keys that work right now.
    pub(super) fn status_line(&self) -> Line<'static> {
        if let Some(prompt) = &self.search_prompt {
            return Line::from(format!("/{prompt}▏"));
        }
        match &self.status {
            Some(Status::Error(err)) => return Line::from(format!(" ✗ {err}")).red().bold(),
            Some(Status::Info(info)) => return Line::from(format!(" {info}")).cyan(),
            Some(Status::ConfirmQuit) => {
                return Line::from(
                    " Unsaved changes. Quit again to discard them, or press any other key to keep editing.",
                )
                .yellow()
                .bold();
            }
            None => {}
        }
        if self.overview.is_some() && self.choosing() && self.visual.is_some() {
            let keys =
                " 1-9 commit selection · 0/d none · j/k ]/[ g/G extend · o other end · Esc cancel";
            return Line::from(vec![Span::raw(keys).magenta()]);
        }
        if self.overview.is_some() && self.choosing() {
            let keys = " 1-9 commit · 0 none · j/k row · V select · a/d file · Enter read it · f close · Esc leave";
            return Line::from(vec![Span::raw(keys).dark_gray()]);
        }
        if self.choosing()
            && self.split.as_ref().is_some_and(Split::is_divided)
            && self.visual_line.is_some()
        {
            let keys =
                " 1-9 commit selection · 0/d none · j/k g/G extend · o other end · Esc cancel";
            return Line::from(vec![Span::raw(keys).magenta()]);
        }
        if self.choosing() && self.split.as_ref().is_some_and(Split::is_divided) {
            let keys =
                " 1-9 commit · 0 none · j/k line · V select · e close · Enter message · Esc leave";
            return Line::from(vec![Span::raw(keys).dark_gray()]);
        }
        if self.choosing() {
            let keys = " 1-9 commit · 0 none · n/p hunk · a/d file · e divide · f list · Enter message · Esc leave";
            return Line::from(vec![Span::raw(keys).dark_gray()]);
        }
        let keys = match (self.focus, self.keymap, self.vim.mode) {
            // Name the tool, so `o` says what it will actually open.
            (Focus::Diff, ..) => {
                let open = self.diff_tool.as_deref().unwrap_or("open");
                format!(
                    " j/k scroll · [/] file · {{/}} hunk · f files · / search · z zoom · s split · o/O {open} · l back"
                )
            }
            // A pending split changes what ^s does, so it says so.
            (Focus::Editor, Keymap::Default, _) => self
                .split
                .as_ref()
                .and_then(Split::next_box)
                .map_or_else(
                    || " Tab next · Enter next/newline · Alt-← diff · Alt-s split · ^t raw/form · ^s save · Esc quit".to_owned(),
                    |commit| {
                        let held = self.split.as_ref().map_or(0, |s| s.count(commit));
                        format!(
                            " Tab next · Alt-← hunks · ^s commit {commit} ({held} {}) · ^t raw/form · Esc quit",
                            plural(held, "hunk")
                        )
                    },
                ),
            (Focus::Editor, Keymap::Vim, vim::Mode::Insert) => {
                " Esc normal · Tab next · Enter next/newline · ^t raw/form · ^s save".to_owned()
            }
            (Focus::Editor, Keymap::Vim, vim::Mode::Visual) => {
                " d/c/y operate · Esc cancel".to_owned()
            }
            (Focus::Editor, Keymap::Vim, _) => {
                " i insert · hjkl past an edge: next box · ^d/^u scroll diff · ^t raw/form · ^s save · q quit".to_owned()
            }
        };
        let mut spans = Vec::new();
        if self.keymap == Keymap::Vim {
            let badge = Span::raw(self.vim.mode.label()).black();
            spans.push(badge.bg(self.accent()));
        }
        spans.push(Span::raw(keys).dark_gray());
        Line::from(spans)
    }
}

const fn cursor_style(focused: bool) -> Style {
    if focused {
        Style::new().add_modifier(Modifier::REVERSED)
    } else {
        Style::new()
    }
}

/// The raw message editor, cursor at the start.
pub(super) fn raw_editor(text: &str) -> TextArea<'static> {
    let mut editor = TextArea::new(text.split('\n').map(str::to_owned).collect());
    editor.set_cursor_line_style(Style::new());
    editor.set_wrap_mode(WrapMode::WordOrGlyph);
    editor
}

/// An editor for `field`, pre-filled with `text`, cursor at the end.
pub(super) fn field_editor(field: Field, text: &str) -> TextArea<'static> {
    let mut editor = TextArea::new(text.split('\n').map(str::to_owned).collect());
    editor.set_placeholder_text(field.placeholder());
    // The default underlines the cursor line, which is noisy in a form.
    editor.set_cursor_line_style(Style::new());
    if field.is_multiline() {
        editor.set_wrap_mode(WrapMode::WordOrGlyph);
    }
    editor.move_cursor(CursorMove::Bottom);
    editor.move_cursor(CursorMove::End);
    editor
}

/// The color standing for commit `n`.
///
/// Six, not nine: a terminal has eight colors it can be trusted with, and
/// red and green are spoken for by errors and the diff itself. Past the
/// sixth box the colors repeat, which is why the digit is always drawn too
/// --- the color is a second reading of it, never the only one.
pub const fn box_color(n: u8) -> Color {
    const WHEEL: [Color; 6] = [
        Color::Cyan,
        Color::Magenta,
        Color::Yellow,
        Color::Blue,
        Color::LightGreen,
        Color::LightMagenta,
    ];
    WHEEL[(n as usize).saturating_sub(1) % WHEEL.len()]
}

/// Every pending box, in the color its rows carry, so the colors in the
/// list need no remembering.
///
/// Built as spans rather than drawn in place so the pairing of digit to
/// color can be tested; a terminal's output interleaves the title with
/// cursor moves, which makes it unreadable after the fact.
fn legend(boxes: &[u8]) -> Vec<Span<'static>> {
    if boxes.is_empty() {
        return Vec::new();
    }
    let mut out = vec![Span::raw(format!(
        "\u{b7} {} {} ",
        boxes.len(),
        plural(boxes.len(), "commit")
    ))];
    out.extend(
        boxes
            .iter()
            .map(|&n| Span::styled(format!("{n} "), box_color(n))),
    );
    out
}

/// The plan as one character per hunk, each in its box's color, with the
/// hunk on screen in brackets.
///
/// Built here rather than in core because a colored strip is spans, not a
/// string, and the coloring is the whole point of it.
fn strip_spans(plan: &[Option<u8>], at: usize) -> Vec<Span<'static>> {
    plan.iter()
        .enumerate()
        .map(|(i, slot)| {
            let (text, color) = match slot {
                Some(n) if *n < 10 => (char::from(b'0' + n).to_string(), box_color(*n)),
                Some(_) => ("+".to_owned(), Color::Gray),
                None => ("·".to_owned(), Color::DarkGray),
            };
            let text = if i == at { format!("[{text}]") } else { text };
            Span::styled(text, color)
        })
        .collect()
}

/// A bordered pane, drawn in `accent` when focused.
fn pane(title: Line<'static>, accent: Option<Color>) -> Block<'static> {
    let style = Style::new().fg(accent.unwrap_or(Color::DarkGray));
    Block::bordered()
        .title(title)
        .border_style(style)
        .title_style(style)
}

/// The field's name; Subject also shows a live length counter for the
/// whole header line.
fn field_title(field: Field, header_len: usize) -> Line<'static> {
    let title = format!(" {} ", field.title());
    if field != Field::Subject {
        return Line::from(title);
    }
    Line::from(vec![Span::raw(title), header_counter(header_len)])
}

fn header_counter(len: usize) -> Span<'static> {
    let color = match len {
        0..=HEADER_SOFT_LIMIT => Color::Green,
        n if n <= HEADER_HARD_LIMIT => Color::Yellow,
        _ => Color::Red,
    };
    Span::styled(
        format!("{len}/{HEADER_HARD_LIMIT} "),
        Style::new().fg(color),
    )
}

/// `n` with `word` pluralised the easy way.
/// One row of the overview: a file heading, or a hunk marked or not.
fn overview_line(row: &overview::Row, cursor: bool, selected: bool) -> Line<'static> {
    let color = match row.kind {
        overview::Kind::File => Color::White,
        overview::Kind::InBox(n) => box_color(n),
        // No one box to color it with. Between a loose row and a decided
        // one, which is what it is: the `*` says to look closer.
        overview::Kind::Divided => Color::Gray,
        overview::Kind::Loose => Color::DarkGray,
    };
    let mut style = Style::new().fg(color);
    if row.kind == overview::Kind::File {
        style = style.add_modifier(Modifier::BOLD);
    }
    if cursor {
        style = style.add_modifier(Modifier::REVERSED);
    } else if selected {
        style = style.bg(Color::DarkGray);
    }
    // A bar in the gutter, so the selection reads even without colors.
    let gutter = if selected { '▌' } else { ' ' };
    Line::styled(format!("{gutter}{}", row.text), style)
}

/// A standing reminder that this session is rewriting protected history, so
/// it can't be forgotten three splits in. Empty when it isn't.
pub(super) fn immutable_marker(immutable: bool) -> Span<'static> {
    if immutable {
        Span::styled("· immutable ", Color::Red)
    } else {
        Span::raw("")
    }
}
#[cfg(test)]
mod tests {
    use super::{Color, box_color, immutable_marker, legend, strip_spans};

    /// Six colors, so a seventh box reuses the first. The digit is what
    /// distinguishes them; the color only groups.
    #[test]
    fn the_box_colors_wrap_rather_than_running_out() {
        assert_eq!(box_color(1), box_color(7));
        assert_ne!(box_color(1), box_color(2));
        assert_eq!(box_color(1), ratatui::style::Color::Cyan);
    }

    /// Each box's digit in that box's own color, so the list's colors are
    /// decoded by the title rather than by memory.
    #[test]
    fn the_legend_pairs_every_box_with_its_color() {
        let spans = legend(&[1, 3]);
        let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, "\u{b7} 2 commits 1 3 ");
        let digits: Vec<_> = spans[1..]
            .iter()
            .map(|s| (s.content.trim().to_owned(), s.style.fg))
            .collect();
        assert_eq!(
            digits,
            [
                ("1".to_owned(), Some(box_color(1))),
                ("3".to_owned(), Some(box_color(3))),
            ],
            "box 3 is box 3's color, not the second color in the wheel"
        );
        assert!(legend(&[]).is_empty(), "no boxes, no legend");
    }

    /// The strip is the same mapping, one character per hunk, with the hunk
    /// on screen in brackets and a middle dot for one left behind.
    #[test]
    fn the_strip_colors_each_hunk_by_its_box() {
        let spans = strip_spans(&[Some(1), None, Some(2)], 1);
        let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, "1[\u{b7}]2");
        assert_eq!(spans[0].style.fg, Some(box_color(1)));
        assert_eq!(spans[2].style.fg, Some(box_color(2)));
        assert_eq!(
            spans[1].style.fg,
            Some(Color::DarkGray),
            "a hunk no commit takes is not any box's color"
        );
    }

    #[test]
    fn the_immutable_marker_shows_only_on_protected_history() {
        assert_eq!(immutable_marker(false).content, "");
        assert!(immutable_marker(true).content.contains("immutable"));
    }
}