kimun-notes 0.24.6

A terminal-based notes application
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
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
//! The two-line **status bar** pinned to the bottom of the editor screen.
//!
//! Line 1 — context + actions: a focus-context indicator (`⌨ EDITOR` when a
//! text field holds the cursor, `≣ LIST` when a list/panel is focused)
//! followed by the focused surface's key hints, with the global hints
//! right-aligned. There is no editing "mode"; focus is the only state.
//!
//! Line 2 — document state: path · ln/col · modified/saved · backlink count
//! · git status · (in query contexts) match count.

use std::time::{Duration, Instant};

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::components::events::{AppEvent, AppTx};
use crate::components::hints::Hint;
use crate::settings::themes::Theme;

const FLASH_DURATION: Duration = Duration::from_secs(2);

/// Rows the status bar occupies.
pub const STATUS_BAR_HEIGHT: u16 = 2;

/// Document state shown on line 2. `None` fields render nothing — each
/// segment appears only when it has a value.
#[derive(Default)]
pub struct DocState<'a> {
    pub path: &'a str,
    pub dirty: bool,
    /// 1-based cursor line/column, when a text buffer holds the cursor.
    pub ln_col: Option<(usize, usize)>,
    /// Backlink count of the open note (async-loaded).
    pub backlinks: Option<usize>,
    /// Property count of the open note — renders the clickable `⊞ N props`.
    pub props: Option<usize>,
    /// Workspace git status summary, e.g. `git ✓` / `git ●3`.
    pub git: Option<String>,
    /// Result count when a query context is focused.
    pub matches: Option<usize>,
    /// Link-under-cursor affordance: `→ target · N backlinks`.
    pub link: Option<String>,
    /// Newer release available, e.g. `⬆ 0.18.0` — clickable, opens the
    /// update dialog.
    pub update: Option<String>,
    /// RAG server status, e.g. `rag: online` — absent when no server is set.
    pub rag: Option<String>,
}

/// Everything the status bar shows for the current frame.
pub struct StatusContext<'a> {
    /// Label of the focused surface (panel or overlay), e.g. `EDITOR`.
    pub focus_label: &'a str,
    /// True when a text field holds the cursor (`⌨`); false for lists (`≣`).
    pub editing: bool,
    /// Key hints for the focused surface.
    pub hints: &'a [Hint],
    /// Always-on hints, right-aligned (from `hints::global_hints`).
    pub global_hints: &'a [Hint],
    /// Document state for line 2.
    pub doc: DocState<'a>,
}

/// A line-2 segment that reacts to a click.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FooterTarget {
    /// `⊞ N props` — opens the properties dialog.
    Props,
    /// `⬆ x.y.z` — opens the update dialog.
    Update,
    /// `N backlinks` — opens the LINKS drawer on its backlinks tab.
    Backlinks,
    /// `→ target` — follows the link under the cursor (the mouse's Ctrl+N).
    Link,
}

pub struct FooterBar {
    key_flash: Option<(String, Instant)>,
    /// Clickable segments from the last render, clipped to the row.
    targets: Vec<(Rect, FooterTarget)>,
}

impl FooterBar {
    pub fn new() -> Self {
        Self {
            key_flash: None,
            targets: Vec::new(),
        }
    }

    /// The flash message being shown, if any (expiry not checked).
    #[cfg(test)]
    pub fn flash_text(&self) -> Option<&str> {
        self.key_flash.as_ref().map(|(t, _)| t.as_str())
    }

    /// Show a key-flash message for 2 seconds. Schedules a delayed redraw so
    /// the message disappears even when no user input arrives in the meantime.
    pub fn flash(&mut self, text: String, tx: &AppTx) {
        self.key_flash = Some((text, Instant::now()));
        let tx2 = tx.clone();
        tokio::spawn(async move {
            tokio::time::sleep(FLASH_DURATION).await;
            let _ = tx2.send(AppEvent::Redraw);
        });
    }

    pub fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, ctx: &StatusContext) {
        let StatusContext {
            focus_label,
            editing,
            hints,
            global_hints,
            doc,
        } = ctx;

        // Expire stale key flash
        if let Some((_, instant)) = &self.key_flash
            && instant.elapsed() >= FLASH_DURATION
        {
            self.key_flash = None;
        }

        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(1), Constraint::Length(1)])
            .split(rect);

        let secondary = Style::default().fg(theme.fg_secondary.to_ratatui());
        let muted = Style::default().fg(theme.gray.to_ratatui());
        let keycap = Style::default().fg(theme.yellow.to_ratatui());

        // ── Line 1: focus context + hints (or the key flash) ────────────────
        if let Some((flash, _)) = &self.key_flash {
            f.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    flash.as_str(),
                    Style::default()
                        .fg(theme.accent.to_ratatui())
                        .add_modifier(Modifier::BOLD),
                )))
                .alignment(Alignment::Center),
                rows[0],
            );
        } else {
            // Right-aligned global hints first, so the left side knows how
            // much width remains.
            let mut right_spans: Vec<Span> = Vec::new();
            for (i, (key, label)) in global_hints.iter().enumerate() {
                if i > 0 {
                    right_spans.push(Span::styled("  ", secondary));
                }
                right_spans.push(Span::styled(format!("{key} "), keycap));
                right_spans.push(Span::styled(label.clone(), secondary));
            }
            let mut right_width: u16 = right_spans.iter().map(|s| s.content.width() as u16).sum();
            // Context hints outrank global hints: on a narrow terminal the
            // globals drop entirely rather than squeezing out the focus
            // indicator and the surface's own hints.
            const MIN_CONTEXT_WIDTH: u16 = 30;
            if right_width + 1 + MIN_CONTEXT_WIDTH > rows[0].width {
                right_spans.clear();
                right_width = 0;
            }
            let cols = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Min(0), Constraint::Length(right_width + 1)])
                .split(rows[0]);

            let glyph = if *editing { "⌨" } else { "≣" };
            let mut spans = vec![Span::styled(
                format!(" {glyph} {focus_label}  "),
                Style::default()
                    .fg(theme.fg_bright.to_ratatui())
                    .add_modifier(Modifier::BOLD),
            )];
            let sep = Span::styled("  ", secondary);
            for (i, (key, label)) in hints.iter().enumerate() {
                if i > 0 {
                    spans.push(sep.clone());
                }
                if key.is_empty() {
                    // Mode / command-line label from the nvim backend — make it pop.
                    spans.push(Span::styled(
                        format!(" {label} "),
                        Style::default()
                            .fg(theme.accent.to_ratatui())
                            .add_modifier(Modifier::BOLD),
                    ));
                } else {
                    spans.push(Span::styled(format!("{key} "), keycap));
                    spans.push(Span::styled(label.clone(), secondary));
                }
            }
            f.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
            f.render_widget(
                Paragraph::new(Line::from(right_spans)).alignment(Alignment::Right),
                cols[1],
            );
        }

        // ── Line 2: document state, `·`-separated segments ──────────────────
        // The path yields to the live segments: when the line would overflow,
        // the path is head-truncated with an ellipsis so ln/col, dirty state,
        // git, and match count stay visible.
        let tail_width: usize = {
            let mut w = 0usize;
            if let Some((ln, col)) = doc.ln_col {
                w += format!(" · ln {ln} col {col}").width();
            }
            w += if doc.dirty {
                " · ● modified".width()
            } else {
                " · ✓ saved".width()
            };
            if let Some(n) = doc.props {
                w += " · ".width() + props_label(n).width();
            }
            if let Some(count) = doc.backlinks {
                w += format!(" · {count} backlinks").width();
            }
            if let Some(git) = &doc.git {
                w += " · ".width() + git.width();
            }
            if let Some(matches) = doc.matches {
                w += format!(" · {matches} matches").width();
            }
            if let Some(update) = &doc.update {
                w += " · ".width() + update.width();
            }
            if let Some(rag) = &doc.rag {
                w += " · ".width() + rag.width();
            }
            w
        };
        let path_budget = (rect.width as usize).saturating_sub(tail_width + 1);
        let path_display = fit_path(doc.path, path_budget);
        let mut segments: Vec<Span> = vec![Span::styled(format!(" {path_display}"), muted)];
        let push = |segments: &mut Vec<Span>, span: Span<'static>| {
            segments.push(Span::styled(" · ", muted));
            segments.push(span);
        };
        if let Some((ln, col)) = doc.ln_col {
            push(
                &mut segments,
                Span::styled(format!("ln {ln} col {col}"), muted),
            );
        }
        let state_span = if doc.dirty {
            Span::styled("● modified", Style::default().fg(theme.yellow.to_ratatui()))
        } else {
            Span::styled("✓ saved", Style::default().fg(theme.green.to_ratatui()))
        };
        push(&mut segments, state_span);
        self.targets.clear();
        // Where the next pushed segment will land: everything already pushed
        // plus the separator `push` puts in front of it.
        let row = rows[1];
        let target_rect = |segments: &[Span], label: &str| -> Option<Rect> {
            let x_before: u16 = segments
                .iter()
                .map(|s| s.content.width() as u16)
                .sum::<u16>()
                + " · ".width() as u16;
            let x = row.x.saturating_add(x_before);
            (x < row.right()).then(|| Rect {
                x,
                y: row.y,
                width: (label.width() as u16).min(row.right() - x),
                height: 1,
            })
        };
        if let Some(n) = doc.props {
            let label = props_label(n);
            if let Some(r) = target_rect(&segments, &label) {
                self.targets.push((r, FooterTarget::Props));
            }
            push(&mut segments, Span::styled(label, theme.action()));
        }
        if let Some(count) = doc.backlinks {
            let label = format!("{count} backlinks");
            if let Some(r) = target_rect(&segments, &label) {
                self.targets.push((r, FooterTarget::Backlinks));
            }
            push(&mut segments, Span::styled(label, theme.action()));
        }
        if let Some(git) = &doc.git {
            push(&mut segments, Span::styled(git.clone(), muted));
        }
        if let Some(matches) = doc.matches {
            push(
                &mut segments,
                Span::styled(
                    format!("{matches} matches"),
                    Style::default().fg(theme.fg_secondary.to_ratatui()),
                ),
            );
        }
        if let Some(link) = &doc.link {
            if let Some(r) = target_rect(&segments, link) {
                self.targets.push((r, FooterTarget::Link));
            }
            push(&mut segments, Span::styled(link.clone(), theme.action()));
        }
        if let Some(update) = &doc.update {
            if let Some(r) = target_rect(&segments, update) {
                self.targets.push((r, FooterTarget::Update));
            }
            push(
                &mut segments,
                Span::styled(update.clone(), theme.action().add_modifier(Modifier::BOLD)),
            );
        }
        if let Some(rag) = &doc.rag {
            push(
                &mut segments,
                Span::styled(rag.clone(), Style::default().fg(theme.green.to_ratatui())),
            );
        }
        for (r, _) in &self.targets {
            crate::components::clickable::register(*r);
        }
        f.render_widget(Paragraph::new(Line::from(segments)), rows[1]);
    }
}

fn props_label(n: usize) -> String {
    if n == 0 {
        "⊞ props".to_string()
    } else {
        format!("⊞ {n} props")
    }
}

impl FooterBar {
    /// The clickable segment under (col,row) from the last render.
    pub fn target_at(&self, col: u16, row: u16) -> Option<FooterTarget> {
        crate::components::clickable::target_at(&self.targets, col, row)
    }
}

impl Default for FooterBar {
    fn default() -> Self {
        Self::new()
    }
}

/// Fit `path` into `budget` display columns for the footer. When it overflows,
/// keep the trailing portion (the note-name end is the most useful part) and
/// prefix it with `…`. Truncation lands on grapheme-cluster boundaries and
/// measures by rendered width, so a multi-codepoint cluster (emoji presentation
/// sequence, combining mark) is never split or reordered.
fn fit_path(path: &str, budget: usize) -> String {
    if path.width() <= budget {
        return path.to_string();
    }
    let mut acc = 0usize;
    let keep: String = path
        .graphemes(true)
        .rev()
        .take_while(|g| {
            acc += g.width();
            acc < budget
        })
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    format!("…{keep}")
}

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

    #[test]
    fn props_segment_is_clickable_where_drawn() {
        use ratatui::{Terminal, backend::TestBackend};
        let theme = Theme::gruvbox_dark();
        let mut bar = FooterBar::new();
        let mut t = Terminal::new(TestBackend::new(100, 2)).unwrap();
        let ctx = StatusContext {
            focus_label: "EDITOR",
            editing: true,
            hints: &[],
            global_hints: &[],
            doc: DocState {
                path: "n.md",
                props: Some(3),
                ..Default::default()
            },
        };
        t.draw(|f| bar.render(f, f.area(), &theme, &ctx)).unwrap();
        let buf = t.backend().buffer().clone();
        let (col, _) = crate::test_support::find_text(&buf, "⊞ 3 props").expect("segment drawn");
        assert_eq!(bar.target_at(col, 1), Some(FooterTarget::Props));
        assert_eq!(bar.target_at(col + 8, 1), Some(FooterTarget::Props));
        assert_eq!(bar.target_at(col.saturating_sub(2), 1), None);
        assert_eq!(bar.target_at(col, 0), None, "line 1 is not the segment");
    }

    #[test]
    fn update_segment_is_clickable_where_drawn() {
        use ratatui::{Terminal, backend::TestBackend};
        let theme = Theme::gruvbox_dark();
        let mut bar = FooterBar::new();
        let mut t = Terminal::new(TestBackend::new(100, 2)).unwrap();
        let ctx = StatusContext {
            focus_label: "EDITOR",
            editing: true,
            hints: &[],
            global_hints: &[],
            doc: DocState {
                path: "n.md",
                props: Some(3),
                update: Some("⬆ 9.9.9".into()),
                ..Default::default()
            },
        };
        t.draw(|f| bar.render(f, f.area(), &theme, &ctx)).unwrap();
        let buf = t.backend().buffer().clone();
        let (col, _) = crate::test_support::find_text(&buf, "⬆ 9.9.9").expect("segment drawn");
        assert_eq!(bar.target_at(col, 1), Some(FooterTarget::Update));
        assert_eq!(bar.target_at(col + 6, 1), Some(FooterTarget::Update));
        assert_eq!(bar.target_at(col.saturating_sub(2), 1), None);
    }

    #[test]
    fn backlinks_and_link_segments_are_clickable() {
        use ratatui::{Terminal, backend::TestBackend};
        let theme = Theme::gruvbox_dark();
        let mut bar = FooterBar::new();
        let mut t = Terminal::new(TestBackend::new(120, 2)).unwrap();
        let ctx = StatusContext {
            focus_label: "EDITOR",
            editing: true,
            hints: &[],
            global_hints: &[],
            doc: DocState {
                path: "n.md",
                backlinks: Some(4),
                link: Some("→ other".into()),
                ..Default::default()
            },
        };
        t.draw(|f| bar.render(f, f.area(), &theme, &ctx)).unwrap();
        let buf = t.backend().buffer().clone();
        let at = |s: &str| crate::test_support::find_text(&buf, s).expect("drawn").0;
        assert_eq!(
            bar.target_at(at("4 backlinks"), 1),
            Some(FooterTarget::Backlinks)
        );
        assert_eq!(
            bar.target_at(at("→ other") + 2, 1),
            Some(FooterTarget::Link)
        );
    }

    #[test]
    fn no_props_segment_without_count() {
        use ratatui::{Terminal, backend::TestBackend};
        let theme = Theme::gruvbox_dark();
        let mut bar = FooterBar::new();
        let mut t = Terminal::new(TestBackend::new(100, 2)).unwrap();
        let ctx = StatusContext {
            focus_label: "EDITOR",
            editing: true,
            hints: &[],
            global_hints: &[],
            doc: DocState {
                path: "n.md",
                ..Default::default()
            },
        };
        t.draw(|f| bar.render(f, f.area(), &theme, &ctx)).unwrap();
        assert!(!(0..100).any(|c| bar.target_at(c, 1).is_some()));
    }

    #[test]
    fn short_path_returned_whole() {
        assert_eq!(fit_path("notes/foo", 20), "notes/foo");
    }

    #[test]
    fn overflowing_ascii_path_keeps_trailing_with_ellipsis() {
        // "abcdefghij" (10 cols) into budget 5: keep trailing clusters while
        // cumulative width stays strictly < 5 → "ghij" (4 cols); "f" would
        // reach 5 and stop. Matches the pre-extraction truncation behavior.
        assert_eq!(fit_path("abcdefghij", 5), "…ghij");
    }

    #[test]
    fn cjk_width_counted_as_two_columns() {
        // "猫猫猫" is 6 display cols; budget 6 fits whole (no ellipsis).
        assert_eq!(fit_path("猫猫猫", 6), "猫猫猫");
    }

    #[test]
    fn emoji_cluster_not_split_or_reordered() {
        // Flag 🇪🇸 = two regional indicators, one cluster (2 cols). Budget 2 on
        // "z🇪🇸" forces the cut to land *inside* the flag. A per-codepoint
        // truncation would keep a lone regional indicator (🇸 — half a flag);
        // grapheme-aware truncation must never emit a partial cluster, so the
        // flag is kept whole or dropped entirely (here: dropped → just "…").
        let es = "\u{1F1F8}"; // ES regional indicator (the 2nd half)
        let flag = "\u{1F1EA}\u{1F1F8}";
        let path = format!("z{flag}");
        let out = fit_path(&path, 2);
        assert!(out.starts_with('…'), "expected ellipsis prefix: {out:?}");
        assert!(
            !out.contains(es) || out.contains(flag),
            "regional indicator emitted without its full flag cluster: {out:?}"
        );
    }
}