kimun-notes 0.24.5

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
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
use std::collections::BTreeMap;

use ratatui::Frame;
use ratatui::crossterm::event::KeyCode;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::widgets::Paragraph;

use crate::components::Component;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, InputEvent};
use crate::components::panel::{ModalSpec, modal_chrome};
use crate::keys::KeyBindings;
use crate::keys::action_shortcuts::ShortcutCategory;
use crate::settings::themes::Theme;

// ---------------------------------------------------------------------------
// HelpRow
// ---------------------------------------------------------------------------

pub enum HelpRow {
    Header(String),
    Separator,
    Binding { keys: String, label: String },
    Blank,
}

// ---------------------------------------------------------------------------
// HelpDialog
// ---------------------------------------------------------------------------

pub struct HelpDialog {
    pub rows: Vec<HelpRow>,
    /// Window title — distinguishes the flat F1 help from the leader-tree
    /// cheatsheet, which share this widget.
    title: &'static str,
    scroll: usize,
    /// Cached body height from last render, used for PageUp/PageDown page size.
    last_body_height: u16,
}

impl HelpDialog {
    pub fn new(key_bindings: &KeyBindings, tree: &crate::keys::leader::LeaderNode) -> Self {
        use crate::keys::action_shortcuts::ActionShortcuts;
        use crate::keys::leader::{LeaderAction, LeaderNode};

        let mut by_category: BTreeMap<ShortcutCategory, Vec<(String, String)>> = BTreeMap::new();

        let map = key_bindings.to_hashmap();
        let mut entries: Vec<_> = map.into_iter().collect();
        entries.sort_by_key(|(action, _)| action.to_string());

        for (action, mut combos) in entries {
            combos.sort();
            let keys = combos
                .iter()
                .map(|c| c.to_string())
                .collect::<Vec<_>>()
                .join(" / ");
            let label = action.label();
            by_category
                .entry(action.category())
                .or_default()
                .push((keys, label));
        }

        // Formatting carries no default chord — it lives on the leader's
        // `+text` group, because `Ctrl+I` is Tab's byte outside the kitty
        // keyboard protocol. This list is built from the binding map, so with
        // nothing bound the whole section would vanish and formatting would
        // read as removed rather than moved. Name the route, and read it off
        // the tree the cheatsheet renders from, so a rebound or relabelled
        // group is described as it is. Listed beside any chord the user
        // bound: the leader is the route that always works.
        //
        // Both conditions matter. With the gateway unbound there is no
        // `<leader> t` to reach, so there is nothing truthful to say — which
        // is why the gateway is read as an Option rather than defaulted to a
        // placeholder. And a tree with no group holding `TextBold` (an
        // override removed it) has no route to name.
        let text_group = tree.children().iter().find(|(_, node)| {
            node.children().iter().any(|(_, leaf)| {
                matches!(
                    leaf,
                    LeaderNode::Leaf {
                        action: LeaderAction::TextBold,
                        ..
                    }
                )
            })
        });
        if let Some(leader) = key_bindings.first_combo_for(&ActionShortcuts::Leader)
            && let Some((key, group)) = text_group
        {
            let leaves = group
                .children()
                .iter()
                .map(|(_, leaf)| leaf.label())
                .collect::<Vec<_>>()
                .join(" / ");
            by_category
                .entry(ShortcutCategory::TextEditing)
                .or_default()
                .push((
                    format!("{leader} {key}"),
                    format!("{leaves} ({})", group.label()),
                ));
        }

        let mut rows: Vec<HelpRow> = Vec::new();
        for (category, bindings) in by_category {
            if bindings.is_empty() {
                continue;
            }
            rows.push(HelpRow::Blank);
            rows.push(HelpRow::Header(category.to_string()));
            rows.push(HelpRow::Separator);
            for (keys, label) in bindings {
                rows.push(HelpRow::Binding { keys, label });
            }
        }
        rows.push(HelpRow::Blank);

        Self {
            rows,
            title: " Keyboard Shortcuts ",
            scroll: 0,
            last_body_height: 20,
        }
    }

    /// The full leader-tree cheatsheet (leader `?`): every sequence in the
    /// tree as `gateway keys → description`, grouped per top-level group,
    /// followed by the flat Tier-0 bindings. Built from the same
    /// `leader_tree()` the engine and the which-key overlay walk — one
    /// source, three surfaces.
    pub fn cheatsheet(settings: &crate::settings::AppSettings) -> Self {
        use crate::keys::action_shortcuts::ActionShortcuts;
        use crate::keys::leader::LeaderNode;

        let key_bindings = &settings.key_bindings;
        let gateway = key_bindings
            .first_combo_for(&ActionShortcuts::Leader)
            .unwrap_or_else(|| "leader".to_string());

        fn walk(node: &LeaderNode, prefix: &str, rows: &mut Vec<HelpRow>) {
            for (key, child) in node.children() {
                let keys = format!("{prefix} {key}");
                match child {
                    LeaderNode::Leaf { label, .. } => rows.push(HelpRow::Binding {
                        keys,
                        label: (*label).to_string(),
                    }),
                    LeaderNode::Group { .. } => walk(child, &keys, rows),
                }
            }
        }

        let tree = settings.leader_tree();
        let mut rows: Vec<HelpRow> = Vec::new();
        // Current configuration up top (spec phase-10: surface theme + keys).
        rows.push(HelpRow::Header("Configuration".to_string()));
        rows.push(HelpRow::Separator);
        rows.push(HelpRow::Binding {
            keys: settings.get_theme().name,
            label: "active theme (leader v c to switch)".to_string(),
        });
        rows.push(HelpRow::Binding {
            keys: gateway.clone(),
            label: "leader gateway".to_string(),
        });
        rows.push(HelpRow::Binding {
            keys: format!("{} ms", settings.leader_timeout_ms),
            label: "which-key reveal timeout".to_string(),
        });
        rows.push(HelpRow::Binding {
            keys: "F1 in Find".to_string(),
            label: "search query syntax".to_string(),
        });
        for row in tree.display_children() {
            if row.is_group {
                // Group: find the child node by its single key and walk it.
                let key = row.keys.chars().next().expect("group keys are one char");
                let child = tree.child(key).expect("display row names a real child");
                rows.push(HelpRow::Blank);
                rows.push(HelpRow::Header(format!("{gateway} {key}  {}", row.label)));
                rows.push(HelpRow::Separator);
                walk(child, &format!("{gateway} {key}"), &mut rows);
            } else {
                rows.push(HelpRow::Blank);
                rows.push(HelpRow::Binding {
                    keys: format!("{gateway} {}", row.keys),
                    label: row.label,
                });
            }
        }

        // Tier-0: the flat always-on bindings, from the same help builder.
        let flat = Self::new(key_bindings, &tree);
        rows.push(HelpRow::Blank);
        rows.push(HelpRow::Header("Always-on shortcuts".to_string()));
        rows.push(HelpRow::Separator);
        rows.extend(
            flat.rows
                .into_iter()
                .filter(|r| matches!(r, HelpRow::Binding { .. })),
        );
        rows.push(HelpRow::Blank);

        Self {
            rows,
            title: " Cheatsheet — leader keys ",
            scroll: 0,
            last_body_height: 20,
        }
    }

    /// Reference card for the search query language (F1 over the Find drawer
    /// view). Operators, modifiers, and a few worked examples — mirrors the
    /// canonical table in `docs/.../search.md`, condensed to the
    /// keys|label shape the help widget already renders. The full prose guide
    /// lives on the docs site, not here.
    pub fn query_syntax() -> Self {
        // (short / long, meaning) — sourced from search.md's operator table.
        const OPERATORS: &[(&str, &str)] = &[
            ("(type text)", "full-text body search"),
            ("= / name:", "by note name"),
            ("@ / in:", "by section heading"),
            ("/ / pt:", "by path / folder"),
            ("# / lb:", "by label (tag)"),
            ("< / lk:", "links TO it (backlinks)"),
            ("> / fwd:", "it links to (forward)"),
            ("^ / or:", "sort results (-^ = desc)"),
        ];
        const MODIFIERS: &[(&str, &str)] = &[
            ("- prefix", "exclude (e.g. -#draft)"),
            ("*", "wildcard prefix (screen*)"),
            ("\" \"", "quote values with spaces"),
        ];
        const EXAMPLES: &[(&str, &str)] = &[
            ("#finance report", "labelled finance + text"),
            ("@work -cancelled", "Work section, not cancelled"),
            ("<kimun #project", "kimun backlinks + label"),
        ];

        fn section(rows: &mut Vec<HelpRow>, header: &str, entries: &[(&str, &str)]) {
            rows.push(HelpRow::Header(header.to_string()));
            rows.push(HelpRow::Separator);
            for (keys, label) in entries {
                rows.push(HelpRow::Binding {
                    keys: (*keys).to_string(),
                    label: (*label).to_string(),
                });
            }
            rows.push(HelpRow::Blank);
        }

        let mut rows: Vec<HelpRow> = Vec::new();
        section(&mut rows, "Operators", OPERATORS);
        section(&mut rows, "Modifiers", MODIFIERS);
        section(&mut rows, "Examples", EXAMPLES);

        Self {
            rows,
            title: " Search Query Syntax ",
            scroll: 0,
            last_body_height: 20,
        }
    }

    fn scroll_up(&mut self) {
        self.scroll = self.scroll.saturating_sub(1);
    }

    fn scroll_down(&mut self) {
        // Clamped to rows.len() so render's slice is always valid even if called
        // between renders.
        self.scroll = self
            .scroll
            .saturating_add(1)
            .min(self.rows.len().saturating_sub(1));
    }

    fn page_up(&mut self) {
        let page = (self.last_body_height as usize).max(1);
        self.scroll = self.scroll.saturating_sub(page);
    }

    fn page_down(&mut self) {
        let page = (self.last_body_height as usize).max(1);
        self.scroll = self
            .scroll
            .saturating_add(page)
            .min(self.rows.len().saturating_sub(1));
    }

    /// Key handler — mirrors the `handle_key` pattern used by all other dialog types.
    pub fn handle_key(
        &mut self,
        key: ratatui::crossterm::event::KeyEvent,
        tx: &AppTx,
    ) -> EventState {
        match key.code {
            KeyCode::Esc => {
                tx.send(AppEvent::CloseOverlay).ok();
            }
            KeyCode::Up => self.scroll_up(),
            KeyCode::Down => self.scroll_down(),
            KeyCode::PageUp => self.page_up(),
            KeyCode::PageDown => self.page_down(),
            _ => {}
        }
        EventState::Consumed
    }
}

const OUTER_WIDTH: u16 = 50;
const KEYS_COL_WIDTH: u16 = 18;

impl Component for HelpDialog {
    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        let InputEvent::Key(key) = event else {
            return EventState::NotConsumed;
        };
        self.handle_key(*key, tx)
    }

    fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, _focused: bool) {
        let content_rows = self.rows.len() as u16;
        let desired_height = content_rows + 4; // borders(2) + footer(1) + bottom blank(1)
        let max_height = (rect.height * 60 / 100).max(10);
        let outer_height = desired_height.min(max_height);

        let popup_area = super::fixed_centered_rect(OUTER_WIDTH, outer_height, rect);
        let inner = modal_chrome(
            f,
            popup_area,
            theme,
            ModalSpec {
                title: Some(self.title),
                border: Some(Style::default().fg(theme.fg.to_ratatui())),
                ..Default::default()
            },
        );

        if inner.height < 2 {
            return;
        }

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

        let body_area = chunks[0];
        let footer_area = chunks[1];

        let bg = theme.bg_panel.to_ratatui();
        let fg = theme.fg.to_ratatui();
        let gray = theme.gray.to_ratatui();
        let fg_accent = theme.selection_fg.to_ratatui();

        // Cache for PageUp/PageDown.
        self.last_body_height = body_area.height;

        // Clamp scroll.
        let body_height = body_area.height as usize;
        let max_scroll = self.rows.len().saturating_sub(body_height);
        self.scroll = self.scroll.min(max_scroll);

        // Render visible rows.
        let visible = &self.rows[self.scroll..];
        for (y, row) in (body_area.y..).zip(visible.iter()) {
            if y >= body_area.y + body_area.height {
                break;
            }
            let row_rect = Rect {
                x: body_area.x,
                y,
                width: body_area.width,
                height: 1,
            };
            match row {
                HelpRow::Blank => {}
                HelpRow::Header(title) => {
                    f.render_widget(
                        Paragraph::new(format!("  {title}")).style(
                            Style::default()
                                .fg(fg_accent)
                                .bg(bg)
                                .add_modifier(Modifier::BOLD),
                        ),
                        row_rect,
                    );
                }
                HelpRow::Separator => {
                    super::render_separator(f, row_rect, gray, bg);
                }
                HelpRow::Binding { keys, label } => {
                    let cols = Layout::default()
                        .direction(Direction::Horizontal)
                        .constraints([
                            Constraint::Length(2),
                            Constraint::Length(KEYS_COL_WIDTH),
                            Constraint::Min(1),
                        ])
                        .split(row_rect);
                    f.render_widget(
                        Paragraph::new(keys.as_str()).style(Style::default().fg(fg_accent).bg(bg)),
                        cols[1],
                    );
                    f.render_widget(
                        Paragraph::new(label.as_str()).style(Style::default().fg(fg).bg(bg)),
                        cols[2],
                    );
                }
            }
        }

        f.render_widget(
            Paragraph::new("  [↑↓ PgUp/PgDn] Scroll   [Esc] Close")
                .style(Style::default().fg(gray).bg(bg)),
            footer_area,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::KeyBindings;
    use crate::keys::action_shortcuts::{ActionShortcuts, TextAction};
    use crate::keys::key_strike::KeyStrike;

    fn bindings_with_bold_and_quit() -> KeyBindings {
        let mut kb = KeyBindings::empty();
        kb.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyB, ActionShortcuts::Text(TextAction::Bold))
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit);
        kb
    }

    /// Formatting moved to the leader, so F1 has no chord to list for it.
    /// It must still say where formatting went — a missing section reads as a
    /// removed feature.
    #[test]
    fn f1_names_the_leader_route_when_no_formatting_chord_is_bound() {
        let dialog = HelpDialog::new(
            &crate::settings::AppSettings::default().key_bindings,
            &crate::keys::leader::leader_tree(),
        );
        let row = dialog.rows.iter().find_map(|r| match r {
            HelpRow::Binding { keys, label } if label.contains("bold") => {
                Some((keys.clone(), label.clone()))
            }
            _ => None,
        });
        let (keys, label) = row.expect("F1 must point at the formatting route");
        assert!(keys.ends_with(" t"), "should name the +text group: {keys}");
        assert!(
            keys.starts_with("ctrl&B"),
            "prefixed by the gateway: {keys}"
        );
        assert_eq!(label, "bold / italic / strikethrough (+text)");
    }

    /// The leader route is the primary way to format, so it is listed even
    /// beside a chord the user bound — a lone `TextEditor-Underline` chord is
    /// a no-op, and hiding the three leaves that work behind it was the bug.
    #[test]
    fn f1_lists_the_leader_route_beside_a_real_formatting_chord() {
        let mut kb = bindings_with_bold_and_quit();
        kb.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyG, ActionShortcuts::Leader);
        let dialog = HelpDialog::new(&kb, &crate::keys::leader::leader_tree());
        let labels: Vec<&str> = dialog
            .rows
            .iter()
            .filter_map(|r| match r {
                HelpRow::Binding { label, .. } => Some(label.as_str()),
                _ => None,
            })
            .collect();
        assert!(labels.contains(&"Bold"), "{labels:?}");
        assert!(
            labels.iter().any(|l| l.contains("+text")),
            "the leader route must stand beside the chord: {labels:?}"
        );
    }

    /// The row is read off the tree, so a rebound or relabelled `+text`
    /// group shows up as it really is rather than as the shipped default.
    #[test]
    fn f1_formatting_hint_follows_the_tree() {
        use crate::keys::leader::{LeaderAction, LeaderNode};
        let tree = LeaderNode::Group {
            label: "leader".into(),
            children: vec![(
                'x',
                LeaderNode::Group {
                    label: "+fmt".into(),
                    children: vec![
                        (
                            'b',
                            LeaderNode::Leaf {
                                label: "bold",
                                action: LeaderAction::TextBold,
                            },
                        ),
                        (
                            'i',
                            LeaderNode::Leaf {
                                label: "italic",
                                action: LeaderAction::TextItalic,
                            },
                        ),
                    ],
                },
            )],
        };
        let dialog = HelpDialog::new(&crate::settings::AppSettings::default().key_bindings, &tree);
        let row = dialog.rows.iter().find_map(|r| match r {
            HelpRow::Binding { keys, label } if label.contains("+fmt") => {
                Some((keys.clone(), label.clone()))
            }
            _ => None,
        });
        let (keys, label) = row.expect("the hint must be built from the tree");
        assert_eq!(keys, "ctrl&B x");
        assert_eq!(label, "bold / italic (+fmt)");
    }

    #[test]
    fn rows_contain_both_categories() {
        let dialog = HelpDialog::new(
            &bindings_with_bold_and_quit(),
            &crate::keys::leader::leader_tree(),
        );
        let headers: Vec<String> = dialog
            .rows
            .iter()
            .filter_map(|r| {
                if let HelpRow::Header(s) = r {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .collect();
        assert!(headers.contains(&"Text Editing".to_string()));
        assert!(headers.contains(&"Other".to_string()));
        assert!(!headers.contains(&"Navigation".to_string()));
        assert!(!headers.contains(&"Notes".to_string()));
    }

    #[test]
    fn binding_row_has_correct_keys_and_label() {
        let dialog = HelpDialog::new(
            &bindings_with_bold_and_quit(),
            &crate::keys::leader::leader_tree(),
        );
        let binding = dialog.rows.iter().find_map(|r| {
            if let HelpRow::Binding { keys, label } = r
                && label == "Bold"
            {
                return Some(keys.clone());
            }
            None
        });
        assert!(binding.is_some(), "expected a Bold binding row");
        assert_eq!(binding.unwrap(), "ctrl&B");
    }

    #[test]
    fn empty_keybindings_produces_no_rows() {
        let dialog = HelpDialog::new(&KeyBindings::empty(), &crate::keys::leader::leader_tree());
        assert!(
            !dialog
                .rows
                .iter()
                .any(|r| matches!(r, HelpRow::Binding { .. }))
        );
        assert!(!dialog.rows.iter().any(|r| matches!(r, HelpRow::Header(_))));
    }
}