kimun-notes 0.11.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
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
use std::sync::Arc;
use std::sync::mpsc::Receiver;

use async_trait::async_trait;
use chrono::NaiveDate;
use kimun_core::NoteVault;
use kimun_core::nfs::VaultPath;
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Position, Rect};
use ratatui::style::Style;
use ratatui::widgets::{Block, Borders, Clear, Paragraph};

use crate::components::Component;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, InputEvent};
use crate::components::file_list::{FileListComponent, FileListEntry};
use crate::components::single_line_input::{InputOutcome, SingleLineInput};
use crate::keys::KeyBindings;
use crate::settings::icons::Icons;
use crate::settings::themes::Theme;

pub mod file_finder_provider;
pub mod link_results_provider;
pub mod search_provider;

// ---------------------------------------------------------------------------
// NoteBrowserProvider trait
// ---------------------------------------------------------------------------

#[async_trait]
pub trait NoteBrowserProvider: Send + Sync {
    /// Called on every query change. Empty string = initial/empty state (recent notes).
    async fn load(&self, query: &str) -> Vec<FileListEntry>;

    /// Whether to prepend a "Create: <query>" entry when query is non-empty.
    /// Defaults to false. Used by future FileFinderProvider.
    fn allows_create(&self) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------
// NoteBrowserModal
// ---------------------------------------------------------------------------

pub struct NoteBrowserModal {
    title: String,
    search_query: SingleLineInput,
    provider: Arc<dyn NoteBrowserProvider>,
    file_list: FileListComponent,
    list_rect: Rect,
    preview_text: String,
    vault: Arc<NoteVault>,
    tx: AppTx,
    // List async loading
    load_task: Option<tokio::task::JoinHandle<()>>,
    load_rx: Option<Receiver<Vec<FileListEntry>>>,
    // Preview async loading
    preview_task: Option<tokio::task::JoinHandle<()>>,
    preview_rx: Option<Receiver<String>>,
}

impl NoteBrowserModal {
    pub fn new(
        title: impl Into<String>,
        provider: impl NoteBrowserProvider + 'static,
        vault: Arc<NoteVault>,
        key_bindings: KeyBindings,
        icons: Icons,
        tx: AppTx,
    ) -> Self {
        Self::new_with_query(
            title,
            provider,
            vault,
            key_bindings,
            icons,
            tx,
            String::new(),
        )
    }

    fn new_with_query(
        title: impl Into<String>,
        provider: impl NoteBrowserProvider + 'static,
        vault: Arc<NoteVault>,
        key_bindings: KeyBindings,
        icons: Icons,
        tx: AppTx,
        initial_query: String,
    ) -> Self {
        let file_list = FileListComponent::new(key_bindings, icons);
        let mut modal = Self {
            title: title.into(),
            search_query: SingleLineInput::new(),
            provider: Arc::new(provider),
            file_list,
            list_rect: Rect::default(),
            preview_text: String::new(),
            vault,
            tx: tx.clone(),
            load_task: None,
            load_rx: None,
            preview_task: None,
            preview_rx: None,
        };
        if !initial_query.is_empty() {
            modal.search_query.set_value(initial_query);
        }
        modal.schedule_load(tx);
        modal
    }

    // ── Async list loading ─────────────────────────────────────────────────

    fn schedule_load(&mut self, tx: AppTx) {
        if let Some(handle) = self.load_task.take() {
            handle.abort();
        }
        let query = self.search_query.value().to_string();
        let provider = Arc::clone(&self.provider);
        let (result_tx, result_rx) = std::sync::mpsc::channel();
        self.load_rx = Some(result_rx);

        let handle = tokio::spawn(async move {
            let entries = provider.load(&query).await;
            result_tx.send(entries).ok();
            tx.send(AppEvent::Redraw).ok();
        });
        self.load_task = Some(handle);
    }

    fn poll_load(&mut self) {
        let Some(rx) = &self.load_rx else { return };
        match rx.try_recv() {
            Ok(entries) => {
                self.file_list.clear();
                let mut create_entry: Option<FileListEntry> = None;
                for entry in entries {
                    if matches!(entry, FileListEntry::CreateNote { .. }) {
                        create_entry = Some(entry);
                    } else {
                        self.file_list.push_entry(entry);
                    }
                }
                if let Some(entry) = create_entry {
                    self.file_list.prepend_create_entry(entry);
                }
                self.load_rx = None;
                self.load_task = None;
                self.refresh_preview();
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {}
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.load_rx = None;
            }
        }
    }

    // ── Async preview loading ──────────────────────────────────────────────

    fn schedule_preview(&mut self, path: VaultPath) {
        if let Some(handle) = self.preview_task.take() {
            handle.abort();
        }
        let vault = Arc::clone(&self.vault);
        let tx = self.tx.clone();
        let (result_tx, result_rx) = std::sync::mpsc::channel();
        self.preview_rx = Some(result_rx);

        let handle = tokio::spawn(async move {
            let text = vault.get_note_text(&path).await.unwrap_or_default();
            result_tx.send(text).ok();
            tx.send(AppEvent::Redraw).ok();
        });
        self.preview_task = Some(handle);
    }

    fn poll_preview(&mut self) {
        let Some(rx) = &self.preview_rx else { return };
        match rx.try_recv() {
            Ok(text) => {
                self.preview_text = text;
                self.preview_rx = None;
                self.preview_task = None;
            }
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.preview_rx = None;
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {}
        }
    }

    fn open_selected_entry(&self, tx: &AppTx) {
        let Some(entry) = self.file_list.selected_entry() else {
            return;
        };
        if let FileListEntry::CreateNote { path, .. } = entry {
            let path = path.clone();
            let vault = Arc::clone(&self.vault);
            let tx = tx.clone();
            tokio::spawn(async move {
                vault.load_or_create_note(&path, None).await.ok();
                tx.send(AppEvent::OpenPath(path)).ok();
                tx.send(AppEvent::CloseNoteBrowser).ok();
            });
            return;
        }
        let path = entry.path().clone();
        tx.send(AppEvent::OpenPath(path)).ok();
        tx.send(AppEvent::CloseNoteBrowser).ok();
    }

    /// Construct the modal with a pre-filled search query.
    ///
    /// Behaves exactly like [`new`](Self::new) except the search input is
    /// pre-populated with `query` (cursor placed at the end) and an initial
    /// load is triggered for that query string.  Only a single `schedule_load`
    /// call is made — the query is pre-filled before the task is spawned so
    /// there is no empty-load race.
    pub fn with_initial_query<S: Into<String>>(
        title: impl Into<String>,
        provider: impl NoteBrowserProvider + 'static,
        vault: Arc<NoteVault>,
        key_bindings: KeyBindings,
        icons: Icons,
        tx: AppTx,
        query: S,
    ) -> Self {
        Self::new_with_query(
            title,
            provider,
            vault,
            key_bindings,
            icons,
            tx,
            query.into(),
        )
    }

    // ── Test-only accessors ────────────────────────────────────────────────

    /// Returns the current search input text. Test-only.
    #[cfg(test)]
    pub(super) fn query_text(&self) -> &str {
        self.search_query.value()
    }

    /// Returns the cursor position as a char count (not bytes). Test-only.
    #[cfg(test)]
    pub(super) fn cursor_char_count(&self) -> usize {
        self.search_query.cursor_char_offset()
    }

    /// Called after selection changes to kick off a preview load for the
    /// highlighted note, or clear the preview if a non-note entry is selected.
    fn refresh_preview(&mut self) {
        let maybe_path = self.file_list.selected_entry().and_then(|e| match e {
            FileListEntry::Note { path, .. } => Some(path.clone()),
            _ => None,
        });
        if let Some(path) = maybe_path {
            self.schedule_preview(path);
        } else {
            self.preview_text.clear();
            if let Some(h) = self.preview_task.take() {
                h.abort();
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Component impl
// ---------------------------------------------------------------------------

impl Component for NoteBrowserModal {
    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        use ratatui::crossterm::event::{KeyCode, KeyModifiers, MouseButton, MouseEventKind};

        if let InputEvent::Mouse(mouse) = event {
            let r = self.list_rect;
            if !r.contains(Position {
                x: mouse.column,
                y: mouse.row,
            }) {
                return EventState::NotConsumed;
            }
            match mouse.kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    if mouse.row > r.y {
                        let rel_row = mouse.row - r.y - 1;
                        let prev = self.file_list.selected_display_idx();
                        if let Some(idx) = self.file_list.select_at_visual_row(rel_row) {
                            if prev == Some(idx) {
                                self.open_selected_entry(tx);
                            } else {
                                self.refresh_preview();
                            }
                        }
                    }
                    EventState::Consumed
                }
                MouseEventKind::ScrollUp => {
                    self.file_list.scroll_up();
                    EventState::Consumed
                }
                MouseEventKind::ScrollDown => {
                    self.file_list.scroll_down();
                    EventState::Consumed
                }
                _ => EventState::Consumed,
            }
        } else {
            let InputEvent::Key(key) = event else {
                return EventState::NotConsumed;
            };
            // List nav handled directly; everything else forwards to the input.
            match key.code {
                KeyCode::Up => {
                    self.file_list.select_prev();
                    self.refresh_preview();
                    return EventState::Consumed;
                }
                KeyCode::Down => {
                    self.file_list.select_next();
                    self.refresh_preview();
                    return EventState::Consumed;
                }
                _ => {}
            }
            // Drop Ctrl/Alt-modified chars so combos don't leak as text.
            if let KeyCode::Char(_) = key.code {
                let non_shift = key.modifiers - KeyModifiers::SHIFT;
                if !non_shift.is_empty() {
                    return EventState::Consumed;
                }
            }
            match self.search_query.handle_key(key) {
                InputOutcome::Cancel => {
                    tx.send(AppEvent::CloseNoteBrowser).ok();
                    EventState::Consumed
                }
                InputOutcome::Submit => {
                    self.open_selected_entry(tx);
                    EventState::Consumed
                }
                InputOutcome::Changed => {
                    self.schedule_load(tx.clone());
                    EventState::Consumed
                }
                InputOutcome::Consumed => EventState::Consumed,
                InputOutcome::NotConsumed => EventState::NotConsumed,
            }
        }
    }

    fn render(&mut self, f: &mut Frame, area: Rect, theme: &Theme, _focused: bool) {
        self.poll_load();
        self.poll_preview();

        let popup_rect = centered_rect(80, 75, area);

        // Clear the area behind the modal so the editor doesn't bleed through.
        f.render_widget(Clear, popup_rect);

        let outer_block = Block::default()
            .title(format!(" {} ", self.title))
            .borders(Borders::ALL)
            .border_style(theme.border_style(true))
            .style(theme.panel_style());
        let inner = outer_block.inner(popup_rect);
        f.render_widget(outer_block, popup_rect);

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

        // ── Search box ────────────────────────────────────────────────────
        let search_block = Block::default()
            .title(" Search ")
            .borders(Borders::ALL)
            .border_style(theme.border_style(true))
            .style(theme.panel_style());
        let search_inner = search_block.inner(rows[0]);
        f.render_widget(search_block, rows[0]);
        self.search_query.render(
            f,
            search_inner,
            Style::default()
                .fg(theme.fg.to_ratatui())
                .bg(theme.bg_panel.to_ratatui()),
            0,
            true,
        );

        // ── List + Preview ────────────────────────────────────────────────
        let columns = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(rows[1]);

        self.list_rect = columns[0];
        self.file_list.render(f, columns[0], theme, false);

        let preview_block = Block::default()
            .title(" Preview ")
            .borders(Borders::ALL)
            .border_style(theme.border_style(false))
            .style(theme.panel_style());
        let preview_inner = preview_block.inner(columns[1]);
        f.render_widget(preview_block, columns[1]);
        f.render_widget(
            Paragraph::new(self.preview_text.as_str()).style(
                Style::default()
                    .fg(theme.fg.to_ratatui())
                    .bg(theme.bg.to_ratatui()),
            ),
            preview_inner,
        );

        // ── Hint bar ──────────────────────────────────────────────────────
        f.render_widget(
            Paragraph::new("↑↓: navigate  |  Enter: open  |  Esc: close")
                .style(Style::default().fg(theme.fg_secondary.to_ratatui())),
            rows[2],
        );
    }

    fn hint_shortcuts(&self) -> Vec<(String, String)> {
        vec![
            ("↑↓".to_string(), "navigate".to_string()),
            ("Enter".to_string(), "open".to_string()),
            ("Esc".to_string(), "close".to_string()),
        ]
    }
}

// ---------------------------------------------------------------------------
// Layout helper
// ---------------------------------------------------------------------------

fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let popup_height = area.height * percent_y / 100;
    let popup_width = area.width * percent_x / 100;
    Rect {
        x: area.x + (area.width.saturating_sub(popup_width)) / 2,
        y: area.y + (area.height.saturating_sub(popup_height)) / 2,
        width: popup_width,
        height: popup_height,
    }
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

pub(super) fn format_journal_date(date: NaiveDate) -> String {
    date.format("%A, %B %-d, %Y").to_string()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings::AppSettings;
    use crate::test_support::{mouse_down_at, temp_vault};
    use tokio::sync::mpsc::unbounded_channel;

    struct EmptyProvider;

    #[async_trait]
    impl NoteBrowserProvider for EmptyProvider {
        async fn load(&self, _query: &str) -> Vec<FileListEntry> {
            Vec::new()
        }
    }

    async fn make_modal() -> NoteBrowserModal {
        let vault = temp_vault("modal").await;
        let settings = AppSettings::default();
        let (tx, _rx) = unbounded_channel();
        NoteBrowserModal::new(
            "test",
            EmptyProvider,
            vault,
            settings.key_bindings.clone(),
            settings.icons(),
            tx,
        )
    }

    /// The modal's mouse handler scopes by `list_rect` (set during render),
    /// not by any rect carried by `FileListComponent`.  Clicks outside that
    /// rect must not be consumed.
    #[tokio::test]
    async fn modal_mouse_down_outside_list_rect_is_not_consumed() {
        let mut modal = make_modal().await;
        modal.list_rect = Rect {
            x: 10,
            y: 10,
            width: 20,
            height: 10,
        };
        let (tx, _rx) = unbounded_channel();

        // Click well outside the list rect.
        let result = modal.handle_input(&mouse_down_at(0, 0), &tx);
        assert_eq!(result, EventState::NotConsumed);
    }

    /// Mirrors the bounds-check used by `SidebarComponent`: a click on the
    /// modal's list_rect.y row is on the block border and must not panic, and
    /// must not select anything (the guard `mouse.row > r.y` skips it).
    #[tokio::test]
    async fn modal_mouse_down_on_list_border_does_not_panic() {
        let mut modal = make_modal().await;
        modal.list_rect = Rect {
            x: 10,
            y: 10,
            width: 20,
            height: 10,
        };
        let (tx, _rx) = unbounded_channel();
        // Click the very top row of the list rect (the block border).
        let result = modal.handle_input(&mouse_down_at(15, 10), &tx);
        assert_eq!(result, EventState::Consumed);
        assert!(modal.file_list.selected_display_idx().is_none());
    }

    #[test]
    fn centered_rect_is_centered() {
        let area = Rect {
            x: 0,
            y: 0,
            width: 100,
            height: 40,
        };
        let r = centered_rect(80, 75, area);
        assert_eq!(r.width, 80);
        assert_eq!(r.height, 30);
        assert_eq!(r.x, 10); // (100 - 80) / 2
        assert_eq!(r.y, 5); // (40 - 30) / 2
    }

    #[test]
    fn centered_rect_does_not_underflow() {
        // Very small area — must not panic.
        let area = Rect {
            x: 0,
            y: 0,
            width: 5,
            height: 5,
        };
        let _ = centered_rect(80, 75, area);
    }

    // ── initial-query tests ───────────────────────────────────────────────

    #[tokio::test]
    async fn modal_constructed_with_initial_query_prefills_input() {
        let vault = temp_vault("modal_iq").await;
        let settings = AppSettings::default();
        let (tx, _rx) = unbounded_channel();
        let modal = NoteBrowserModal::with_initial_query(
            "test",
            EmptyProvider,
            vault,
            settings.key_bindings.clone(),
            settings.icons(),
            tx,
            "#important",
        );
        assert_eq!(modal.query_text(), "#important");
        assert_eq!(modal.cursor_char_count(), "#important".chars().count());
    }

    #[tokio::test]
    async fn modal_new_has_empty_query() {
        let modal = make_modal().await;
        assert_eq!(modal.query_text(), "");
        assert_eq!(modal.cursor_char_count(), 0);
    }

    /// `with_initial_query` must call `schedule_load` exactly once, with the
    /// query already pre-filled.  Verified indirectly: the visible state after
    /// construction must match the supplied query and the cursor must sit at
    /// the end — just as if a single properly-initialised load were scheduled.
    #[tokio::test]
    async fn with_initial_query_does_not_double_schedule() {
        let vault = temp_vault("modal_iq_once").await;
        let settings = AppSettings::default();
        let (tx, _rx) = unbounded_channel();
        let modal = NoteBrowserModal::with_initial_query(
            "test",
            EmptyProvider,
            vault,
            settings.key_bindings.clone(),
            settings.icons(),
            tx,
            "#important",
        );
        assert_eq!(modal.query_text(), "#important");
        assert_eq!(modal.cursor_char_count(), "#important".chars().count());
        // A load task must have been spawned (Some), confirming schedule_load
        // was called.  If it were called twice the second abort() would race;
        // that scenario is ruled out by code inspection: new_with_query is the
        // only call site for schedule_load during construction.
        assert!(modal.load_task.is_some());
    }
}