plannotator-tui 0.11.2

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Drawing: header, optional tree, gutter + document, annotation rail, footer, and the
//! floating toolbar and compose box. Pure over `App` except for recording geometry for
//! hit-testing.

use plannotator_tui_schema::Kind;
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use unicode_width::UnicodeWidthStr;

use super::{App, Focus, GUTTER, Geometry, Mode, TOOLBAR, glyph, label};
use crate::gate::Gate;
use crate::keys::Action;
use crate::theme::palette;
use crate::ui::chips::chips;
use crate::ui::compose;
use crate::wrap::wrap_line;

const RAIL_WIDTH: u16 = 36;
const RAIL_MIN_WIDTH: u16 = 28;
/// Below this the rail is dropped and annotations are only marked in the gutter.
const RAIL_MIN_TOTAL_WIDTH: u16 = 80;
const TREE_WIDTH: u16 = 28;
/// Below this the tree is hidden unless toggled on; Tab still reaches it.
pub(super) const TREE_MIN_TOTAL_WIDTH: u16 = 120;

fn accent(kind: Kind) -> Color {
    match kind {
        Kind::Comment => palette().comment,
        Kind::LooksGood => palette().looks_good,
        Kind::Delete => palette().delete,
    }
}

/// Painting precedence when annotations overlap a cell.
fn priority(kind: Kind) -> u8 {
    match kind {
        Kind::Comment => 0,
        Kind::LooksGood => 1,
        Kind::Delete => 2,
    }
}

impl App {
    pub(crate) fn draw(&mut self, frame: &mut Frame) {
        let area = self.viewport(frame.area());
        let [header, body, footer] = Layout::vertical([
            Constraint::Length(self.header_height(area.width)),
            Constraint::Min(1),
            Constraint::Length(self.footer_height(area.width)),
        ])
        .areas(area);

        let show_tree = self.tree_shown(area.width) || (self.tree.is_some() && self.focus == Focus::Tree);
        let tree_width = if show_tree { TREE_WIDTH } else { 0 };
        // A hidden rail gives its columns to the text, which reflows below as on a resize.
        let rail_fits = area.width.saturating_sub(tree_width) >= RAIL_MIN_TOTAL_WIDTH;
        let rail_width = if self.rail_shown() && rail_fits {
            (area.width * 3 / 10).clamp(RAIL_MIN_WIDTH, RAIL_WIDTH)
        } else {
            0
        };
        // `[ui] doc_width` is the reading column: text wraps to it, and it sits centred in the
        // columns the tree and the rail leave. Only a cap that binds moves anything.
        let gap = u16::from(rail_width > 0);
        let room = body.width.saturating_sub(tree_width + GUTTER + gap + rail_width);
        let cap = self.ui.doc_width.max(20);
        let (margin, text, spare) = if self.ui.doc_width > 0 && room > cap {
            ((room - cap) / 2, Constraint::Length(cap), Constraint::Min(gap))
        } else {
            (0, Constraint::Min(20), Constraint::Length(gap))
        };
        let [tree, _margin, gutter, doc, _spare, rail] = Layout::horizontal([
            Constraint::Length(tree_width),
            Constraint::Length(margin),
            Constraint::Length(GUTTER),
            text,
            spare,
            Constraint::Length(rail_width),
        ])
        .areas(body);
        let old_height = self.geometry.doc.height;
        self.geometry = Geometry {
            screen: frame.area(),
            tree,
            doc,
            width: area.width,
            column_room: room,
            ..Geometry::default()
        };
        self.settle_layout_for_view();

        // A layout is at least one column wide, so an empty pane must not count as a resize.
        let layout_width = usize::from(doc.width).max(1);
        if self.open.layout.width != layout_width {
            self.open.layout.reflow(layout_width);
            self.clear_selection();
            self.scroll_by(0);
            // Clearing the selection can change the footer's height, so lay out again.
            return self.draw(frame);
        }
        if doc.height < old_height {
            self.keep_focus_in_view(old_height);
        }

        self.draw_header(frame, header);
        if show_tree {
            // A resize may have changed the tree's height; keep the window in range.
            self.tree_scroll_by(0);
            self.draw_tree(frame, tree);
        }
        self.draw_document(frame, gutter, doc);
        if rail_width > 0 {
            self.draw_rail(frame, rail);
        }
        self.draw_footer(frame, footer);
        match &self.mode {
            Mode::Compose => self.draw_compose(frame, &self.compose_title("comment")),
            Mode::Edit(_) => self.draw_compose(frame, &self.compose_title("edit")),
            Mode::AttachImage(_) => {
                self.draw_compose(frame, " image path \u{b7} enter attaches \u{b7} esc cancels ");
            }
            Mode::Browse if self.pending.is_some() => self.draw_toolbar(frame),
            Mode::Pick => self.draw_pick(frame),
            Mode::FileSearch => self.draw_file_search(frame),
            Mode::Archive => self.draw_archive(frame),
            Mode::ReviewMenu => self.draw_review_menu(frame),
            Mode::PickTarget => self.draw_pi_picker(frame),
            Mode::Browse | Mode::ConfirmQuit | Mode::ConfirmClearAll | Mode::Search => {}
        }
    }

    fn draw_tree(&self, frame: &mut Frame, area: Rect) {
        let Some(tree) = &self.tree else { return };
        let focused = self.focus == Focus::Tree;
        let border =
            if focused { Style::new().fg(palette().accent) } else { Style::new().fg(Color::DarkGray) };
        let block = Block::default().borders(Borders::RIGHT).border_style(border);
        let inner = block.inner(area);
        frame.render_widget(block, area);
        let open_path = match &self.open.source.provenance {
            plannotator_tui_schema::Provenance::File { path } => Some(path.as_path()),
            _ => None,
        };
        let lines: Vec<Line<'static>> = tree
            .rows
            .iter()
            .enumerate()
            .skip(self.tree_scroll)
            .take(usize::from(inner.height))
            .map(|(i, row)| {
                let indent = "  ".repeat(row.depth);
                let name = if row.is_dir {
                    let arrow = if row.expanded { "\u{25be}" } else { "\u{25b8}" };
                    format!("{indent}{arrow} {}/", row.name)
                } else {
                    format!("{indent}{}", row.name)
                };
                let mut style = if row.is_dir { Style::new().dim() } else { Style::new() };
                if open_path == Some(row.path.as_path()) {
                    style = style.bold().fg(palette().accent);
                }
                let row_bg = (focused && i == self.tree_cursor).then(|| palette().block_bg);
                if let Some(bg) = row_bg {
                    style = style.bg(bg);
                }
                // Name on the left, annotation count right-aligned; nothing shown at zero.
                let count = if row.annotations > 0 { row.annotations.to_string() } else { String::new() };
                let width = usize::from(inner.width);
                let name: String = name.chars().take(width.saturating_sub(count.len() + 2)).collect();
                let pad = width.saturating_sub(1 + name.chars().count() + count.len());
                let with_bg = |s: Style| row_bg.map_or(s, |bg| s.bg(bg));
                Line::from(vec![
                    Span::styled(format!(" {name}"), style),
                    Span::styled(" ".repeat(pad), with_bg(Style::new())),
                    Span::styled(count, with_bg(Style::new().fg(palette().comment))),
                ])
            })
            .collect();
        frame.render_widget(Paragraph::new(lines), inner);
    }

    fn draw_document(&self, frame: &mut Frame, gutter: Rect, doc: Rect) {
        let placed = self.open.store.placed();
        let text_selection_active = self.selection.is_some();
        let doc_focused = self.focus == Focus::Document;
        let buf = frame.buffer_mut();

        for y in 0..doc.height {
            let row_index = self.scroll + usize::from(y);
            let Some(block) = self.open.layout.block_at_row(row_index) else { continue };
            let (Some(row), Some(line)) =
                (self.open.layout.row(row_index), self.open.layout.drawn_line(row_index))
            else {
                continue;
            };
            let screen_y = doc.y + y;
            buf.set_line(doc.x, screen_y, &line, doc.width);

            if block == self.selected && !text_selection_active && self.pending.is_none() && doc_focused {
                buf.set_style(
                    Rect { x: doc.x, y: screen_y, width: doc.width, height: 1 },
                    Style::new().bg(palette().block_bg),
                );
            }

            let mut row_has_annotation = false;
            for (col, cell) in row.cells.iter().enumerate().take(usize::from(doc.width)) {
                let Some(offset) = cell else { continue };
                let kind = placed
                    .iter()
                    .filter(|p| p.range.contains(offset))
                    .map(crate::store::Placed::kind)
                    .max_by_key(|&k| priority(k));
                let Some(kind) = kind else { continue };
                row_has_annotation = true;
                let style = match kind {
                    Kind::Comment => Style::new().bg(palette().comment_bg),
                    Kind::LooksGood => Style::new().bg(palette().approve_bg),
                    Kind::Delete => {
                        Style::new().fg(palette().delete).add_modifier(Modifier::CROSSED_OUT | Modifier::DIM)
                    }
                };
                buf.set_style(Rect { x: doc.x + col as u16, y: screen_y, width: 1, height: 1 }, style);
            }

            // Search matches paint over the annotation tints, in a colour of their own, and
            // under the selection and the cursor.
            if let Some(styles) = self.search_styles(&row.cells) {
                for (col, style) in styles.iter().enumerate().take(usize::from(doc.width)) {
                    if let Some(style) = style {
                        buf.set_style(
                            Rect { x: doc.x + col as u16, y: screen_y, width: 1, height: 1 },
                            *style,
                        );
                    }
                }
            }

            if let Some(cols) = self.selection.and_then(|s| s.columns_on(row_index, row.cells.len().max(1))) {
                let start = cols.start.min(usize::from(doc.width)) as u16;
                let end = cols.end.min(usize::from(doc.width)) as u16;
                if end > start {
                    let rect = Rect { x: doc.x + start, y: screen_y, width: end - start, height: 1 };
                    buf.set_style(rect, palette().selection);
                }
            }

            // Keyboard cursor, visible while roaming or selecting with the keyboard.
            if doc_focused
                && (self.roam || self.selection.is_some_and(|s| s.dragging))
                && row_index == self.cursor.0
            {
                let x = doc.x + (self.cursor.1.min(usize::from(doc.width).saturating_sub(1))) as u16;
                buf.set_style(Rect { x, y: screen_y, width: 1, height: 1 }, palette().cursor);
            }

            let marker = match (block == self.selected, row_has_annotation) {
                (true, _) => Span::styled("▍", Style::new().fg(palette().accent)),
                (false, true) => Span::styled("▍", Style::new().fg(palette().comment)),
                (false, false) => Span::raw(" "),
            };
            buf.set_span(gutter.x, screen_y, &marker, 1);
        }
    }

    /// Screen position for a floating widget anchored at the pending selection: one row
    /// above its first row when there is room, else just below its last row.
    fn float_origin(&self, height: u16, width: u16) -> Option<Rect> {
        let pending = self.pending.as_ref()?;
        let doc = self.geometry.doc;
        let (row, col) = pending.at;
        if row < self.scroll || row >= self.scroll + usize::from(doc.height) {
            return None;
        }
        let screen_row = doc.y + (row - self.scroll) as u16;
        let width = width.min(doc.width);
        let x = (doc.x + col as u16).min(doc.right().saturating_sub(width));
        let y = if screen_row >= doc.y + height {
            screen_row - height
        } else {
            let last_row = self.selection.map_or(row, |s| s.ordered().1.0);
            let below = doc.y + last_row.saturating_sub(self.scroll) as u16 + 1;
            below.min(doc.bottom().saturating_sub(height))
        };
        Some(Rect { x, y, width, height })
    }

    fn draw_toolbar(&mut self, frame: &mut Frame) {
        let labels: Vec<String> = TOOLBAR
            .iter()
            .map(|(g, l, a, _)| match self.keys.hint(*a) {
                key if key.is_empty() => format!(" {g} {l} "),
                key => format!(" {g} {l} ({key}) "),
            })
            .collect();
        let width: u16 = labels.iter().map(|l| l.width() as u16).sum::<u16>() + 1;
        let Some(rect) = self.float_origin(1, width) else { return };
        frame.render_widget(Clear, rect);
        let buf = frame.buffer_mut();
        buf.set_style(rect, Style::new().bg(palette().toolbar_bg));
        let mut x = rect.x + 1;
        let mut spans = [0..0, 0..0, 0..0];
        for ((label, item), span) in labels.iter().zip(TOOLBAR.iter()).zip(spans.iter_mut()) {
            let w = label.width() as u16;
            let style = Style::new().fg(chips().toolbar(item.3)).bg(palette().toolbar_bg).bold();
            buf.set_span(x, rect.y, &Span::styled(label.as_str(), style), w);
            *span = x..x + w;
            x += w;
        }
        self.geometry.toolbar = Some((rect, spans));
    }

    /// The compose box title, or its discard question.
    fn compose_title(&self, verb: &str) -> String {
        self.compose.heading(verb, self.shift_enter, &self.keys)
    }

    /// `[ui] comment_width`, raised to where the title still fits on the box's two borders.
    fn compose_width(&self) -> u16 {
        self.ui.comment_width.max(38)
    }

    /// The columns the compose box wraps to: as last drawn or, for keys that arrive before
    /// its first frame, as configured.
    pub(super) fn compose_wrap(&self) -> usize {
        match self.geometry.compose_wrap {
            0 => usize::from(self.compose_width().saturating_sub(compose::CHROME)),
            drawn => drawn,
        }
    }

    /// The compose box: at the pending selection when there is one, else over the rail
    /// bubble being edited, else centered. `[ui] comment_width` caps its width; a narrower
    /// pane narrows it further.
    fn compose_rect(&self, area: Rect, height: u16) -> Rect {
        let width = self.compose_width();
        self.float_origin(height, width).or_else(|| self.edit_origin(height, width)).unwrap_or_else(|| {
            let area = self.viewport(area);
            let width = width.min(area.width);
            Rect { x: area.x + (area.width - width) / 2, y: area.y + area.height / 2, width, height }
        })
    }

    fn draw_compose(&mut self, frame: &mut Frame, title: &str) {
        let width = self.compose_rect(frame.area(), 1).width;
        let wrap_width = usize::from(width.saturating_sub(compose::CHROME));
        self.geometry.compose_wrap = wrap_width;
        let rect = self.compose_rect(frame.area(), compose::height(&self.compose, wrap_width));
        compose::draw(frame, rect, &self.compose, title);
    }

    fn edit_origin(&self, height: u16, width: u16) -> Option<Rect> {
        let (Mode::Edit(id) | Mode::AttachImage(id)) = &self.mode else { return None };
        let (rect, _) = self.geometry.bubbles.iter().find(|(_, bubble_id)| bubble_id == id)?;
        let area = self.geometry.doc.union(*rect);
        let x = rect.right().saturating_sub(width).max(area.x);
        Some(Rect { x, y: rect.y, width: width.min(area.width), height })
    }

    fn draw_rail(&mut self, frame: &mut Frame, rail: Rect) {
        let view_end = self.scroll + usize::from(rail.height);
        let rail_focused = self.focus == Focus::Rail;
        let mut next_y = rail.y;
        let placed = self.open.store.placed();
        let mut bubbles = Vec::new();
        for (index, placed) in placed.iter().enumerate() {
            let Some(block) = self.open.doc.block_containing(placed.range.start) else { continue };
            let Some(rendered) = self.open.layout.blocks.get(block) else { continue };
            let anchor_row =
                self.open.layout.first_row_in_range(block, placed.range).unwrap_or(rendered.first_row);
            if anchor_row + 1 < self.scroll.saturating_sub(2)
                || anchor_row >= view_end
                || next_y >= rail.bottom()
            {
                continue;
            }
            let anchored_y = rail.y + anchor_row.saturating_sub(self.scroll) as u16;
            let y = anchored_y.max(next_y);
            let kind = placed.kind();
            let body = if placed.annotation.body.is_empty() {
                label(kind).to_owned()
            } else {
                placed.annotation.body.clone()
            };
            let inner_width = usize::from(rail.width.saturating_sub(4));
            let lines: Vec<Line<'static>> =
                wrap_line(&Line::from(body.as_str()), &[], inner_width).into_iter().map(|r| r.line).collect();
            let height = (lines.len() as u16 + 2).min(rail.bottom().saturating_sub(y));
            if height < 3 {
                break;
            }
            let highlighted = if rail_focused { index == self.rail_cursor } else { block == self.selected };
            let border =
                if highlighted { Style::new().fg(accent(kind)) } else { Style::new().fg(Color::DarkGray) };
            let border = if rail_focused && index == self.rail_cursor { border.bold() } else { border };
            let sent = if self.is_file_review() && !self.open.store.is_pending(placed.annotation) {
                " · sent"
            } else {
                ""
            };
            let images = match placed.annotation.plannotator_tui.images.len() {
                0 => String::new(),
                1 => " · 1 image".to_owned(),
                n => format!(" · {n} images"),
            };
            let from = match &placed.annotation.author_name {
                Some(name) => format!(" · {name}"),
                None => String::new(),
            };
            let title = Span::styled(
                format!(" {} {}{from}{images}{sent} ", glyph(kind), short_id(&placed.annotation.id)),
                Style::new().fg(accent(kind)),
            );
            let bubble = Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(border)
                .title(title);
            let rect = Rect { x: rail.x, y, width: rail.width, height };
            let inner = bubble.inner(rect);
            frame.render_widget(bubble, rect);
            let body_style =
                if placed.annotation.body.is_empty() { Style::new().dim().italic() } else { Style::new() };
            let text_area = Rect { x: inner.x + 1, width: inner.width.saturating_sub(1), ..inner };
            frame.render_widget(Paragraph::new(lines).style(body_style), text_area);
            bubbles.push((rect, placed.annotation.id.clone()));
            next_y = y + height;
        }
        self.geometry.bubbles = bubbles;
    }

    fn draw_footer(&mut self, frame: &mut Frame, mut area: Rect) {
        if self.mode == Mode::ConfirmQuit {
            // The question owns the footer: the browse help would name keys that are not
            // live while it is up.
            let answers = [(Action::Yes, "send"), (Action::No, "quit"), (Action::Back, "cancel")]
                .into_iter()
                .filter_map(|(action, label)| self.keys.labelled(action, label))
                .collect::<Vec<_>>()
                .join(" · ");
            let question =
                format!(" send feedback to {} before quitting? {answers}", self.delivery.describe());
            frame.render_widget(Paragraph::new(Line::from(Span::raw(question).bold())), area);
            return;
        }
        if self.mode == Mode::Search {
            self.draw_search_prompt(frame, area);
            return;
        }
        if self.mode == Mode::ConfirmClearAll {
            let answers = [(Action::Yes, "clear"), (Action::No, "cancel")]
                .into_iter()
                .filter_map(|(action, label)| self.keys.labelled(action, label))
                .collect::<Vec<_>>()
                .join(" · ");
            let question =
                format!(" clear all {} annotation(s) on current document? {answers}", self.open.store.len());
            frame.render_widget(Paragraph::new(Line::from(Span::raw(question).bold())), area);
            return;
        }
        let (text, hint_rows) = self.footer_text(area.width);
        // A pane too short for any footer has no row to put the button on.
        if let Some(label) = self.undo_label().filter(|_| area.height > 0) {
            let width = (label.width() as u16).min(area.width);
            let y = area.bottom().saturating_sub(1);
            let rect = Rect { x: area.right() - width, y, width, height: 1 };
            frame
                .render_widget(Paragraph::new(label.as_str()).style(Style::new().fg(palette().accent)), rect);
            self.geometry.undo_button = Some(rect);
            area.width = area.width.saturating_sub(width);
        }
        // Paired from the bottom, so a pane too short for every row keeps the one with the text.
        for (index, (hints, y)) in hint_rows.iter().rev().zip((area.y..area.bottom()).rev()).enumerate() {
            let row = Rect { y, height: 1, ..area };
            let hints = if hints.is_empty() { String::new() } else { format!("{hints} ") };
            let help_area = if index == 0 {
                let [text_area, help_area] =
                    Layout::horizontal([Constraint::Min(0), Constraint::Length(hints.width() as u16)])
                        .areas(row);
                frame.render_widget(Paragraph::new(Line::from(Span::raw(text.as_str()).dim())), text_area);
                help_area
            } else {
                row
            };
            frame
                .render_widget(Paragraph::new(Line::from(Span::raw(hints).dim()).right_aligned()), help_area);
        }
    }

    /// The footer's rows at `width`; the questions that take it over need one.
    fn footer_height(&self, width: u16) -> u16 {
        if matches!(self.mode, Mode::ConfirmQuit | Mode::ConfirmClearAll | Mode::Search) {
            return 1;
        }
        self.footer_text(width).1.len() as u16
    }

    /// The button that undoes a finished review, as drawn at the end of the footer.
    fn undo_label(&self) -> Option<String> {
        if self.mode != Mode::Browse || self.undo_archive.is_empty() {
            return None;
        }
        let label = self.keys.labelled(Action::UndoFinish, "Undo finish");
        Some(format!(" {} ", label.as_deref().unwrap_or("Undo finish")))
    }

    /// The footer's left text and its key hints in rows; the last row sits beside the text.
    fn footer_text(&self, viewport_width: u16) -> (String, Vec<String>) {
        let orphans = self.open.store.orphans();
        // The status leads: it is the transient half of the line, and the name and counters
        // it pushes right are on screen for the whole session anyway.
        let mut parts: Vec<String> = self.status.iter().cloned().collect();
        parts.extend(self.search_label());
        parts.extend([
            self.open.source.name.clone(),
            format!(
                "{} annotations{}",
                self.open.store.len(),
                if orphans > 0 { format!(" ({orphans} orphaned)") } else { String::new() }
            ),
            match &self.pending {
                Some(p) => {
                    let chars = self.open.doc.source.get(p.range.clone()).map_or(0, |s| s.chars().count());
                    format!("selected {chars} chars")
                }
                None if self.open.doc.blocks.is_empty() => "empty document".to_owned(),
                None => format!("block {}/{}", self.selected + 1, self.open.doc.blocks.len()),
            },
        ]);
        if self.notes_rail.closed() {
            parts.push(match self.keys.hint(Action::ToggleNotes) {
                key if key.is_empty() => "notes hidden".to_owned(),
                key => format!("notes hidden: {key} shows them"),
            });
        } else if self.rail_shown() && viewport_width < RAIL_MIN_TOTAL_WIDTH {
            parts.push("rail hidden: widen to ≥80 cols".into());
        }
        let text = format!(" {}", parts.join(" · "));
        let undo = self.undo_label().map_or(0, |label| label.width());
        // One column stays free after the hints, and one between them and the text.
        let width = usize::from(viewport_width).saturating_sub(undo + 1);
        let beside_text = width.saturating_sub(text.width() + 1);
        (text, crate::ui::hints::flow(&self.footer_help(), width, beside_text))
    }

    /// The key help for the focused pane, in the user's keys.
    fn footer_help(&self) -> Vec<String> {
        // A text box takes every key and its border names the ones it answers.
        if matches!(self.mode, Mode::Compose | Mode::Edit(_) | Mode::AttachImage(_)) {
            return Vec::new();
        }
        // Each hint names its action's first key; an unbound action drops out of the line.
        let key = |action, label| self.keys.labelled(action, label);
        let bare = |hint: String| (!hint.is_empty()).then_some(hint);
        let up_down = bare(
            [Action::Down, Action::Up]
                .map(|action| self.keys.hint(action))
                .iter()
                .filter(|k| !k.is_empty())
                .cloned()
                .collect::<Vec<_>>()
                .join("/"),
        );
        let tab = bare(self.keys.hint(Action::CycleFocus));
        // `send-and-close` is bound only in a reply review, so only a reply review names it.
        let send_and_close =
            if self.is_file_review() { None } else { key(Action::SendAndClose, "send+quit") };
        let quit = [send_and_close, key(Action::Quit, "quit")];
        let approve = (self.gate == Gate::Approve).then(|| key(Action::Approve, "approve")).flatten();
        // The image keys act on the current note; removing is offered only when it has one.
        let note = self.current_note();
        let has_images = note.as_deref().is_some_and(|id| self.open.store.has_images(id));
        let remove_image = has_images.then(|| key(Action::RemoveImage, "remove image")).flatten();
        // One hint for both: the footer has to fit 80 columns.
        let marks = [Action::LooksGood, Action::Delete]
            .map(|action| self.keys.hint(action))
            .into_iter()
            .filter(|hint| !hint.is_empty())
            .collect::<Vec<_>>()
            .join("/");
        let marks = bare(marks).map(|keys| format!("{keys} mark"));
        // While a search is shown its steps lead, and its Esc clears it; `/` starts one
        // otherwise.
        let search_steps = self.has_search().then(|| {
            let keys = [Action::NextMatch, Action::PreviousMatch]
                .map(|action| self.keys.hint(action))
                .into_iter()
                .filter(|hint| !hint.is_empty())
                .collect::<Vec<_>>()
                .join("/");
            bare(keys).map(|keys| format!("{keys} match"))
        });
        let search_steps = search_steps.flatten();
        let clear_search = self.has_search().then(|| key(Action::Back, "clear search")).flatten();
        let help: Vec<Option<String>> = match self.focus {
            _ if self.pending.is_some() => vec![
                key(Action::LooksGood, "looks good"),
                key(Action::Comment, "comment"),
                key(Action::Delete, "delete"),
                (!self.ui.copy_on_select).then(|| key(Action::CopySelection, "copy")).flatten(),
                key(Action::Back, "clear"),
            ],
            Focus::Tree => vec![
                up_down,
                key(Action::Confirm, "open"),
                key(Action::ToggleHidden, "hidden"),
                key(Action::Send, "send"),
                approve,
                key(Action::ToggleTree, "hide"),
                key(Action::Quit, "quit"),
            ],
            Focus::Rail => [
                up_down,
                key(Action::Edit, "edit"),
                key(Action::Remove, "remove"),
                key(Action::AttachImage, "image"),
                remove_image,
                key(Action::ToggleNotes, "hide"),
                tab,
            ]
            .into_iter()
            .chain(quit)
            .collect(),
            Focus::Document if self.roam => [
                bare(self.keys.directions_hint()).map(|keys| format!("{keys} move")),
                key(Action::Visual, "select"),
                key(Action::Comment, "comment"),
                key(Action::Back, "blocks"),
            ]
            .into_iter()
            .chain(quit)
            .collect(),
            Focus::Document => [
                search_steps,
                clear_search,
                key(Action::MoveCursor, "move"),
                key(Action::Visual, "select"),
                key(Action::Comment, "comment"),
                marks,
                note.is_some().then(|| key(Action::AttachImage, "image")).flatten(),
                remove_image,
                key(Action::Send, "send"),
                approve,
                (!self.has_search()).then(|| key(Action::Search, "search")).flatten(),
                tab,
            ]
            .into_iter()
            .chain(quit)
            .collect(),
        };
        // Quick Open works from any pane of a folder review, so every pane's help names it,
        // last.
        let find =
            if self.tree.is_some() && self.pending.is_none() { key(Action::QuickOpen, "find") } else { None };
        help.into_iter().chain([find]).flatten().collect()
    }
}

/// The tail of an id, enough to tell bubbles apart: `anno_…F0123` → `F0123`.
fn short_id(id: &str) -> String {
    let tail: Vec<char> = id.chars().rev().take(5).collect();
    tail.into_iter().rev().collect()
}