kimun-notes 0.21.0

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
//! The **Activity Rail** — the fixed-width icon strip on the far left of the
//! editor screen. Each cell names a drawer view; the active cell shows a
//! green edge bar and green glyph. CFG is pinned to the bottom.

use ratatui::Frame;
use ratatui::crossterm::event::KeyCode;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::components::drawer::DrawerView;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, InputEvent};
use crate::components::panel::panel_block;
use crate::keys::KeyBindings;
use crate::settings::themes::Theme;

/// Total column width the rail occupies, borders included.
pub const RAIL_WIDTH: u16 = 7;

/// The full rail catalog in presentation order. CFG is last and pinned to the
/// bottom of the strip by a spacer. SEM only appears when the server is
/// reachable for search (the rail is rebuilt on any RAG-status change).
const ITEMS: [(&str, DrawerView); 8] = [
    ("FIL", DrawerView::Files),
    ("FND", DrawerView::Find),
    ("SEM", DrawerView::Semantic),
    ("ASK", DrawerView::Ask),
    ("TAG", DrawerView::Tags),
    ("LNK", DrawerView::Links),
    ("OUT", DrawerView::Outline),
    ("CFG", DrawerView::Config),
];

/// The rail glyph for a drawer view, resolved through the icon set so the
/// nerd-font / ASCII fallback policy applies to the rail like everywhere else.
fn glyph_for(icons: &crate::settings::icons::Icons, view: DrawerView) -> &'static str {
    match view {
        DrawerView::Files => icons.rail_files,
        DrawerView::Find => icons.rail_find,
        // No dedicated icon field yet; `~` reads as "similar" and is ASCII-safe.
        DrawerView::Semantic => "~",
        // No dedicated icon field yet; `?` reads as "ask" and is ASCII-safe.
        DrawerView::Ask => "?",
        DrawerView::Tags => icons.rail_tags,
        DrawerView::Links => icons.rail_links,
        DrawerView::Outline => icons.rail_outline,
        DrawerView::Config => icons.rail_config,
    }
}

/// Rows each rail cell occupies (glyph line + label line + gap).
const CELL_ROWS: u16 = 3;

/// Which feature-gated rail items are currently visible — a server-status
/// snapshot passed into `ActivityRail::new`/`PanelSet::rebuild_rail`. Named
/// fields instead of two positional bools so a caller can't silently swap
/// SEM and ASK.
#[derive(Debug, Clone, Copy, Default)]
pub struct RailCaps {
    /// SEM appears when the server is reachable for search (an embedder is
    /// configured) — `RagStatus::search_available`, mirroring how `ask` tracks
    /// `RagStatus::llm_available`.
    pub semantic: bool,
    /// ASK appears when the server can answer questions (an LLM configured).
    pub ask: bool,
}

pub struct ActivityRail {
    /// The visible items, in presentation order: [`ITEMS`] minus the views
    /// whose feature is off (SEM without a search-reachable server).
    items: Vec<(&'static str, DrawerView)>,
    /// The item the keyboard cursor sits on (the item `Enter` opens).
    cursor: usize,
    /// The row each item was drawn at on the last render, for click
    /// hit-testing.
    item_rows: Vec<(DrawerView, Rect)>,
    /// Icon set resolving the rail glyphs (nerd-font / ASCII).
    icons: crate::settings::icons::Icons,
    /// Bindings resolving the focus-cycle hint combos.
    key_bindings: KeyBindings,
}

impl ActivityRail {
    pub fn new(
        key_bindings: KeyBindings,
        icons: crate::settings::icons::Icons,
        caps: RailCaps,
    ) -> Self {
        let items = ITEMS
            .into_iter()
            .filter(|(_, view)| caps.semantic || *view != DrawerView::Semantic)
            // ASK appears only when the server can answer questions (an LLM is
            // configured); the rail is rebuilt when that changes.
            .filter(|(_, view)| caps.ask || *view != DrawerView::Ask)
            .collect();
        Self {
            items,
            cursor: 0,
            item_rows: Vec::new(),
            icons,
            key_bindings,
        }
    }

    /// The drawer view under the keyboard cursor.
    pub fn cursor_view(&self) -> DrawerView {
        self.items[self.cursor].1
    }

    /// Whether `view` is currently on the rail (its feature gate is on).
    #[cfg(test)]
    pub fn shows(&self, view: DrawerView) -> bool {
        self.items.iter().any(|(_, v)| *v == view)
    }

    /// Move the keyboard cursor onto `view` (e.g. after a click or a leader
    /// path switched the drawer), so rail navigation continues from there.
    /// A view the rail doesn't show (hidden SEM) leaves the cursor in place.
    pub fn set_cursor(&mut self, view: DrawerView) {
        if let Some(i) = self.items.iter().position(|(_, v)| *v == view) {
            self.cursor = i;
        }
    }

    /// The item at the given screen cell, from the last render.
    pub fn view_at(&self, column: u16, row: u16) -> Option<DrawerView> {
        self.item_rows
            .iter()
            .find(|(_, rect)| rect.contains(ratatui::layout::Position::new(column, row)))
            .map(|(view, _)| *view)
    }

    pub fn hint_shortcuts(&self) -> Vec<(String, String)> {
        use crate::keys::action_shortcuts::ActionShortcuts;

        let mut hints = vec![
            ("↑/↓".into(), "Move".into()),
            ("Enter".into(), "Open/close".into()),
        ];
        hints.extend(crate::components::hints::hints_for(
            &self.key_bindings,
            &[
                (ActionShortcuts::FocusSidebar, "\u{2190} focus left"),
                (ActionShortcuts::FocusEditor, "focus right \u{2192}"),
            ],
        ));
        hints
    }

    pub fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        // Click on a rail item → switch the drawer to it (spec §3); the
        // toggle-on-active-click refinement lands with Phase 03.
        if let InputEvent::Mouse(mouse) = event {
            use ratatui::crossterm::event::{MouseButton, MouseEventKind};
            if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left))
                && let Some(view) = self.view_at(mouse.column, mouse.row)
            {
                self.set_cursor(view);
                tx.send(AppEvent::OpenDrawerView(view)).ok();
                return EventState::Consumed;
            }
            return EventState::NotConsumed;
        }
        let InputEvent::Key(key) = event else {
            return EventState::NotConsumed;
        };
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                self.cursor = self.cursor.saturating_sub(1);
                EventState::Consumed
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.cursor = (self.cursor + 1).min(self.items.len() - 1);
                EventState::Consumed
            }
            KeyCode::Enter => {
                tx.send(AppEvent::OpenDrawerView(self.cursor_view())).ok();
                EventState::Consumed
            }
            _ => EventState::NotConsumed,
        }
    }

    /// `active` is the drawer view currently shown (None when the drawer is
    /// hidden); it gets the green edge bar + glyph.
    pub fn render(
        &mut self,
        f: &mut Frame,
        rect: Rect,
        theme: &Theme,
        focused: bool,
        active: Option<DrawerView>,
    ) {
        let block = panel_block("", theme, focused);
        let inner = block.inner(rect);
        f.render_widget(block, rect);
        self.item_rows.clear();

        let accent = Style::default().fg(theme.focus_border.to_ratatui());
        let dim = Style::default().fg(theme.gray.to_ratatui());
        let cursor_style = Style::default()
            .fg(theme.fg_bright.to_ratatui())
            .add_modifier(Modifier::BOLD);

        // CFG (last item) is pinned to the bottom; the rest stack from the top.
        let (top_items, bottom_item) = self.items.split_at(self.items.len() - 1);

        let icons = self.icons.clone();
        let draw = |idx: usize,
                    label: &str,
                    view: DrawerView,
                    y: u16,
                    f: &mut Frame,
                    rows: &mut Vec<(DrawerView, Rect)>| {
            if y + 1 >= inner.bottom() {
                return;
            }
            let glyph = glyph_for(&icons, view);
            let is_active = active == Some(view);
            let is_cursor = focused && idx == self.cursor;
            let glyph_style = if is_active {
                accent
            } else if is_cursor {
                cursor_style
            } else {
                dim
            };
            let label_style = if is_cursor { cursor_style } else { dim };
            let cell = Rect::new(inner.x, y, inner.width, 2);
            // Labels are all three letters wide, so centering yields one
            // column of padding on each side of the 5-wide inner strip.
            f.render_widget(
                Paragraph::new(vec![
                    Line::from(Span::styled(glyph, glyph_style)),
                    Line::from(Span::styled(label, label_style)),
                ])
                .alignment(ratatui::layout::Alignment::Center),
                cell,
            );
            // CFG is drawn last; on cramped rails its cell can overlap a top
            // item — insert at the FRONT so hit-testing favors the
            // most-recently drawn (topmost) cell.
            rows.insert(0, (view, cell));
        };

        let mut y = inner.y;
        for (i, (label, view)) in top_items.iter().enumerate() {
            draw(i, label, *view, y, f, &mut self.item_rows);
            y += CELL_ROWS;
        }
        // Bottom-pinned CFG.
        let (label, view) = bottom_item[0];
        let cfg_y = inner.bottom().saturating_sub(2).max(y);
        draw(
            self.items.len() - 1,
            label,
            view,
            cfg_y,
            f,
            &mut self.item_rows,
        );

        // The active item's marker is the rail's own left border: recolor the
        // border segment beside the active cell green (and thicken it), so
        // the highlight reads as part of the panel chrome rather than an
        // extra in-cell bar.
        if let Some((_, cell)) = self
            .item_rows
            .iter()
            .find(|(view, _)| active == Some(*view))
        {
            let buf = f.buffer_mut();
            for dy in 0..cell.height {
                let pos = ratatui::layout::Position::new(rect.x, cell.y + dy);
                if let Some(border_cell) = buf.cell_mut(pos) {
                    border_cell.set_symbol("");
                    border_cell.set_fg(theme.focus_border.to_ratatui());
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{KeyEvent, KeyModifiers};
    use tokio::sync::mpsc::unbounded_channel;

    fn key(code: KeyCode) -> InputEvent {
        InputEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
    }

    fn rail_with(semantic_visible: bool, ask_visible: bool) -> ActivityRail {
        let settings = crate::settings::AppSettings::default();
        ActivityRail::new(
            settings.key_bindings,
            crate::settings::icons::Icons::new(false),
            RailCaps {
                semantic: semantic_visible,
                ask: ask_visible,
            },
        )
    }

    fn rail_with_semantic(semantic_visible: bool) -> ActivityRail {
        rail_with(semantic_visible, false)
    }

    fn test_rail() -> ActivityRail {
        rail_with(true, true)
    }

    /// The drawer views the rail currently shows, in order.
    fn rail_views(rail: &ActivityRail) -> Vec<DrawerView> {
        rail.items.iter().map(|(_, v)| *v).collect()
    }

    #[test]
    fn rail_hides_ask_without_llm() {
        let rail = rail_with(true, false);
        assert!(rail_views(&rail).contains(&DrawerView::Semantic));
        assert!(!rail_views(&rail).contains(&DrawerView::Ask));
    }

    #[test]
    fn rail_shows_ask_with_llm() {
        let rail = rail_with(true, true);
        assert!(rail_views(&rail).contains(&DrawerView::Ask));
    }

    #[test]
    fn cursor_moves_and_clamps() {
        let mut rail = test_rail();
        let (tx, _rx) = unbounded_channel();
        assert_eq!(rail.cursor_view(), DrawerView::Files);

        rail.handle_input(&key(KeyCode::Up), &tx);
        assert_eq!(rail.cursor_view(), DrawerView::Files); // clamped at top

        rail.handle_input(&key(KeyCode::Down), &tx);
        assert_eq!(rail.cursor_view(), DrawerView::Find);
        for _ in 0..10 {
            rail.handle_input(&key(KeyCode::Down), &tx);
        }
        assert_eq!(rail.cursor_view(), DrawerView::Config); // clamped at bottom
    }

    #[test]
    fn enter_emits_open_drawer_view() {
        let mut rail = test_rail();
        let (tx, mut rx) = unbounded_channel();
        rail.handle_input(&key(KeyCode::Down), &tx);
        rail.handle_input(&key(KeyCode::Enter), &tx);
        match rx.try_recv() {
            Ok(AppEvent::OpenDrawerView(view)) => assert_eq!(view, DrawerView::Find),
            other => panic!("expected OpenDrawerView, got {other:?}"),
        }
    }

    #[test]
    fn set_cursor_tracks_view() {
        let mut rail = test_rail();
        rail.set_cursor(DrawerView::Outline);
        assert_eq!(rail.cursor_view(), DrawerView::Outline);
    }

    #[test]
    fn hints_include_focus_cycle() {
        let rail = test_rail();
        let labels: Vec<String> = rail
            .hint_shortcuts()
            .into_iter()
            .map(|(_, label)| label)
            .collect();
        assert!(labels.contains(&"\u{2190} focus left".to_string()));
        assert!(labels.contains(&"focus right \u{2192}".to_string()));
    }

    #[test]
    fn semantic_hidden_when_no_server_configured() {
        let mut rail = rail_with_semantic(false);
        let (tx, _rx) = unbounded_channel();

        // SEM is not on the rail: FND steps straight to TAG.
        rail.handle_input(&key(KeyCode::Down), &tx);
        assert_eq!(rail.cursor_view(), DrawerView::Find);
        rail.handle_input(&key(KeyCode::Down), &tx);
        assert_eq!(rail.cursor_view(), DrawerView::Tags);

        // Bottom clamp still lands on the pinned CFG.
        for _ in 0..10 {
            rail.handle_input(&key(KeyCode::Down), &tx);
        }
        assert_eq!(rail.cursor_view(), DrawerView::Config);

        // Pointing the cursor at the hidden view is a no-op.
        rail.set_cursor(DrawerView::Tags);
        rail.set_cursor(DrawerView::Semantic);
        assert_eq!(rail.cursor_view(), DrawerView::Tags);
    }

    #[test]
    fn rail_labels_are_three_chars() {
        // The render centers labels in the 5-wide inner strip; exactly three
        // characters guarantees one column of padding on each side.
        for (label, _) in ITEMS {
            assert_eq!(label.len(), 3, "rail label {label:?} must be 3 chars");
        }
    }
}