kimun-notes 0.24.1

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
pub use create_note_dialog::CreateNoteDialog;
pub use delete_dialog::DeleteConfirmDialog;
pub use file_ops_menu::FileOpsMenuDialog;
pub use help_dialog::HelpDialog;
pub use move_dialog::MoveDialog;
pub use pinned_notes_dialog::PinnedNotesDialog;
pub use quick_note_modal::QuickNoteModal;
pub use rename_dialog::RenameDialog;
pub use save_search_dialog::SaveSearchDialog;
pub use sort_dialog::SortDialog;
pub use theme_picker::ThemePickerDialog;
pub use update_dialog::UpdateAvailableDialog;
pub use workspace_switcher::WorkspaceSwitcherModal;

use std::sync::Arc;

use kimun_core::NoteVault;
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, Borders, Paragraph, Widget};

use crate::components::Component;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, InputEvent, OverlayData, SaveSource, SortTarget};
use crate::components::file_list::{SortField, SortOrder};
use crate::components::overlay::{Overlay, OverlayKind, OverlayMsg};
use crate::settings::themes::Theme;

// ---------------------------------------------------------------------------
// ValidationState — shared by RenameDialog and MoveDialog
// ---------------------------------------------------------------------------

/// Tracks the current state of an async name / destination availability check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationState {
    /// No check has been triggered yet (initial state).
    Idle,
    /// A check is in progress.
    Pending,
    /// The name / destination is available (does not already exist).
    Available,
    /// The name / destination is already taken.
    Taken,
}

pub mod create_note_dialog;
pub mod delete_dialog;
pub mod file_ops_menu;
pub mod help_dialog;
pub mod move_dialog;
pub mod pinned_notes_dialog;
pub mod quick_note_modal;
pub mod rename_dialog;
pub mod save_search_dialog;
pub mod sort_dialog;
pub mod theme_picker;
pub mod update_dialog;
pub mod workspace_switcher;

pub enum ActiveDialog {
    Menu(FileOpsMenuDialog),
    Delete(DeleteConfirmDialog),
    Rename(RenameDialog),
    Move(MoveDialog),
    CreateNote(CreateNoteDialog),
    Help(HelpDialog),
    QuickNote(QuickNoteModal),
    WorkspaceSwitcher(WorkspaceSwitcherModal),
    SaveSearch(SaveSearchDialog),
    Sort(SortDialog),
    PinnedNotes(PinnedNotesDialog),
    ThemePicker(ThemePickerDialog),
    UpdateAvailable(UpdateAvailableDialog),
}

impl ActiveDialog {
    pub fn set_error(&mut self, msg: String) {
        match self {
            ActiveDialog::Menu(_) => {} // menu has no error state
            ActiveDialog::Delete(d) => d.error = Some(msg),
            ActiveDialog::Rename(d) => d.error = Some(msg),
            ActiveDialog::Move(d) => d.error = Some(msg),
            ActiveDialog::CreateNote(d) => d.error = Some(msg),
            ActiveDialog::Help(_) => {}
            ActiveDialog::QuickNote(d) => d.error = Some(msg),
            ActiveDialog::WorkspaceSwitcher(_) => {} // no error state
            ActiveDialog::SaveSearch(_) => {}        // no error state
            ActiveDialog::Sort(_) => {}              // no error state
            ActiveDialog::PinnedNotes(_) => {} // no error state: its own failures arrive as PinnedNotesLoaded(Err) and flash
            ActiveDialog::ThemePicker(_) => {} // no error state
            ActiveDialog::UpdateAvailable(_) => {} // no error state
        }
    }

    // Constructors for the dialogs opened by EditorScreen via OverlayHost.
    pub fn help(key_bindings: &crate::keys::KeyBindings) -> Self {
        ActiveDialog::Help(HelpDialog::new(key_bindings))
    }

    /// The full leader-tree cheatsheet (leader `?`).
    pub fn cheatsheet(settings: &crate::settings::AppSettings) -> Self {
        ActiveDialog::Help(HelpDialog::cheatsheet(settings))
    }

    /// The search query syntax reference (F1 over the Find drawer view).
    pub fn query_syntax() -> Self {
        ActiveDialog::Help(HelpDialog::query_syntax())
    }

    /// The live theme picker (leader `v c`).
    pub fn theme_picker(settings: &crate::settings::AppSettings) -> Self {
        ActiveDialog::ThemePicker(ThemePickerDialog::new(settings))
    }

    /// The update-available dialog.
    pub fn update(status: &crate::update::UpdateStatus) -> Self {
        ActiveDialog::UpdateAvailable(UpdateAvailableDialog::new(status))
    }

    pub fn quick_note(vault: Arc<NoteVault>) -> Self {
        ActiveDialog::QuickNote(QuickNoteModal::new(vault))
    }

    pub fn workspace_switcher(settings: &crate::settings::AppSettings) -> Self {
        ActiveDialog::WorkspaceSwitcher(WorkspaceSwitcherModal::new(settings))
    }

    pub fn create_note(
        path: kimun_core::nfs::VaultPath,
        vault: Arc<NoteVault>,
        content: Option<String>,
    ) -> Self {
        ActiveDialog::CreateNote(CreateNoteDialog::new(path, vault, content))
    }

    /// Open the save-search dialog. `provenance` is the saved-search name the
    /// query came from (the breadcrumb), pre-filled as the default name. The
    /// existing names load in the background and arrive via
    /// [`OverlayData::SavedSearchNamesLoaded`] to drive the dialog's hint.
    pub fn save_search(
        query: String,
        provenance: Option<String>,
        source: SaveSource,
        vault: Arc<NoteVault>,
        tx: &AppTx,
    ) -> Self {
        let tx = tx.clone();
        tokio::spawn(async move {
            if let Ok(searches) = vault.list_saved_searches().await {
                let names = searches.into_iter().map(|s| s.name).collect();
                tx.send(AppEvent::OverlayData(OverlayData::SavedSearchNamesLoaded(
                    names,
                )))
                .ok();
            }
        });
        ActiveDialog::SaveSearch(SaveSearchDialog::new(query, provenance, source))
    }

    pub fn sort(
        target: SortTarget,
        field: SortField,
        order: SortOrder,
        group_directories: bool,
    ) -> Self {
        ActiveDialog::Sort(SortDialog::new(target, field, order, group_directories))
    }

    /// The pinned-notes dialog (leader `f p`). Loads in the background and
    /// arrives via [`OverlayData::PinnedNotesLoaded`].
    pub fn pinned_notes(vault: Arc<NoteVault>, tx: &AppTx) -> Self {
        ActiveDialog::PinnedNotes(PinnedNotesDialog::new(vault, tx))
    }

    pub fn file_ops_menu(path: kimun_core::nfs::VaultPath) -> Self {
        ActiveDialog::Menu(FileOpsMenuDialog::new(path))
    }

    pub fn delete(path: kimun_core::nfs::VaultPath, vault: Arc<NoteVault>) -> Self {
        ActiveDialog::Delete(DeleteConfirmDialog::new(path, vault))
    }

    pub fn rename(path: kimun_core::nfs::VaultPath, vault: Arc<NoteVault>) -> Self {
        ActiveDialog::Rename(RenameDialog::new(path, vault))
    }

    pub fn move_to(path: kimun_core::nfs::VaultPath, vault: Arc<NoteVault>, tx: &AppTx) -> Self {
        ActiveDialog::Move(MoveDialog::new(path, vault, tx))
    }
}

impl Overlay for ActiveDialog {
    fn kind(&self) -> OverlayKind {
        OverlayKind::Dialog
    }

    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        <Self as Component>::handle_input(self, event, tx)
    }

    fn handle_data(
        &mut self,
        data: &OverlayData,
        _vault: &Arc<NoteVault>,
        tx: &AppTx,
    ) -> OverlayMsg {
        match data {
            OverlayData::RenameValidation { available } => {
                if let ActiveDialog::Rename(d) = self {
                    d.validation_state = if *available {
                        ValidationState::Available
                    } else {
                        ValidationState::Taken
                    };
                    d.validation_task = None;
                }
                OverlayMsg::Consumed
            }
            OverlayData::MoveDirectoriesLoaded(paths) => {
                if let ActiveDialog::Move(d) = self {
                    d.all_dirs = paths.clone();
                    d.filtered = None;
                    d.load_task = None;
                    if d.list_state.selected().is_none() && !d.results().is_empty() {
                        d.list_state.select(Some(0));
                    }
                    d.spawn_validation(tx);
                }
                OverlayMsg::Consumed
            }
            OverlayData::MoveFilterResults(paths) => {
                if let ActiveDialog::Move(d) = self {
                    d.filter_task = None;
                    d.filtered = Some(paths.clone());
                    if !d.results().is_empty() {
                        d.list_state.select(Some(0));
                    } else {
                        d.list_state.select(None);
                    }
                    d.spawn_validation(tx);
                }
                OverlayMsg::Consumed
            }
            OverlayData::MoveDestValidation { available } => {
                if let ActiveDialog::Move(d) = self {
                    d.dest_validation = if *available {
                        ValidationState::Available
                    } else {
                        ValidationState::Taken
                    };
                    d.validation_task = None;
                }
                OverlayMsg::Consumed
            }
            OverlayData::SavedSearchNamesLoaded(names) => {
                if let ActiveDialog::SaveSearch(d) = self {
                    d.set_existing_names(names.clone());
                }
                OverlayMsg::Consumed
            }
            OverlayData::PinnedNotesLoaded(result) => {
                if let ActiveDialog::PinnedNotes(d) = self {
                    d.handle_loaded(result, tx);
                }
                OverlayMsg::Consumed
            }
            OverlayData::Error(text) => {
                self.set_error(text.clone());
                OverlayMsg::Consumed
            }
        }
    }

    fn render(&mut self, f: &mut Frame, area: Rect, theme: &Theme) {
        <Self as Component>::render(self, f, area, theme, true);
    }
}

impl Component for ActiveDialog {
    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        let InputEvent::Key(key) = event else {
            return EventState::NotConsumed;
        };
        match self {
            ActiveDialog::Menu(d) => d.handle_key(*key, tx),
            ActiveDialog::Delete(d) => d.handle_key(*key, tx),
            ActiveDialog::Rename(d) => d.handle_key(*key, tx),
            ActiveDialog::Move(d) => d.handle_key(*key, tx),
            ActiveDialog::CreateNote(d) => d.handle_key(*key, tx),
            ActiveDialog::Help(d) => d.handle_key(*key, tx),
            ActiveDialog::QuickNote(d) => d.handle_key(*key, tx),
            ActiveDialog::WorkspaceSwitcher(d) => d.handle_key(*key, tx),
            ActiveDialog::SaveSearch(d) => d.handle_input(event, tx),
            ActiveDialog::Sort(d) => d.handle_input(event, tx),
            ActiveDialog::PinnedNotes(d) => d.handle_input(event, tx),
            ActiveDialog::ThemePicker(d) => d.handle_key(*key, tx),
            ActiveDialog::UpdateAvailable(d) => d.handle_key(*key, tx),
        }
    }

    fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, focused: bool) {
        match self {
            ActiveDialog::Menu(d) => d.render(f, rect, theme, focused),
            ActiveDialog::Delete(d) => d.render(f, rect, theme, focused),
            ActiveDialog::Rename(d) => d.render(f, rect, theme, focused),
            ActiveDialog::Move(d) => d.render(f, rect, theme, focused),
            ActiveDialog::CreateNote(d) => d.render(f, rect, theme, focused),
            ActiveDialog::Help(d) => d.render(f, rect, theme, focused),
            ActiveDialog::QuickNote(d) => d.render(f, rect, theme, focused),
            ActiveDialog::WorkspaceSwitcher(d) => d.render(f, rect, theme, focused),
            ActiveDialog::SaveSearch(d) => d.render(f, rect, theme, focused),
            ActiveDialog::Sort(d) => d.render(f, rect, theme, focused),
            ActiveDialog::PinnedNotes(d) => d.render(f, rect, theme, focused),
            ActiveDialog::ThemePicker(d) => d.render(f, rect, theme, focused),
            ActiveDialog::UpdateAvailable(d) => d.render(f, rect, theme, focused),
        }
    }
}

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

/// Renders a pre-computed path string (should already include leading spaces).
pub(super) fn render_path_row(f: &mut Frame, rect: Rect, path: &str, fg: Color, bg: Color) {
    f.render_widget(
        Paragraph::new(path).style(Style::default().fg(fg).bg(bg)),
        rect,
    );
}

/// Renders a single-line horizontal rule (TOP border only).
pub(super) fn render_separator(f: &mut Frame, rect: Rect, gray: Color, bg: Color) {
    Block::default()
        .borders(Borders::TOP)
        .border_style(Style::default().fg(gray))
        .style(Style::default().bg(bg))
        .render(rect, f.buffer_mut());
}

/// Renders `  Error: {msg}` in the theme's error color on the panel background.
pub(super) fn render_error_row(f: &mut Frame, rect: Rect, msg: &str, theme: &Theme) {
    f.render_widget(
        Paragraph::new(format!("  Error: {msg}")).style(
            Style::default()
                .fg(theme.red.to_ratatui())
                .bg(theme.bg_panel.to_ratatui()),
        ),
        rect,
    );
}

/// Renders `{enter_text}  [Esc] Cancel` split into two horizontal columns.
/// The Enter part is dimmed when `enter_active` is `false`.
pub(super) fn render_confirm_hint(
    f: &mut Frame,
    rect: Rect,
    enter_text: &str,
    enter_active: bool,
    fg: Color,
    gray: Color,
    bg: Color,
) {
    let enter_style = if enter_active {
        Style::default().fg(fg).bg(bg)
    } else {
        Style::default().fg(gray).bg(bg).add_modifier(Modifier::DIM)
    };
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(enter_text.len() as u16 + 1),
            Constraint::Min(1),
        ])
        .split(rect);
    f.render_widget(Paragraph::new(enter_text).style(enter_style), chunks[0]);
    f.render_widget(
        Paragraph::new("  [Esc] Cancel").style(Style::default().fg(gray).bg(bg)),
        chunks[1],
    );
}

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

/// Centre a dialog of exactly `width` × `height` characters.
pub(super) use crate::components::fixed_centered_rect;

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

    #[test]
    fn active_dialog_help_variant_compiles() {
        let dialog = HelpDialog::new(&KeyBindings::empty());
        let _active: ActiveDialog = ActiveDialog::Help(dialog);
    }

    #[test]
    fn active_dialog_sort_variant_compiles() {
        use crate::components::events::SortTarget;
        use crate::components::file_list::{SortField, SortOrder};
        let _active: ActiveDialog = ActiveDialog::sort(
            SortTarget::Sidebar,
            SortField::Name,
            SortOrder::Ascending,
            false,
        );
    }

    /// Every dialog test for `PinnedNotesDialog` calls `set_rows` directly,
    /// bypassing the routing this module owns. A regression here (e.g. the
    /// `PinnedNotesLoaded` arm losing its `if let` guard, or matching the
    /// wrong variant) would leave the dialog permanently empty with none of
    /// those tests failing — so this drives the real `handle_data` path.
    #[tokio::test]
    async fn active_dialog_routes_pinned_notes_loaded_rows() {
        use crate::components::events::PinnedRow;
        use kimun_core::nfs::VaultPath;
        use tokio::sync::mpsc::unbounded_channel;

        let vault = crate::test_support::temp_vault("active-dialog-pinned").await;
        let (tx, _rx) = unbounded_channel();
        let mut active = ActiveDialog::pinned_notes(vault.clone(), &tx);

        let rows = vec![PinnedRow {
            path: VaultPath::new("a.md"),
            missing: false,
        }];
        let msg = active.handle_data(
            &OverlayData::PinnedNotesLoaded(Ok(rows.clone())),
            &vault,
            &tx,
        );
        assert!(matches!(msg, OverlayMsg::Consumed));

        match &active {
            ActiveDialog::PinnedNotes(d) => assert_eq!(d.rows(), rows.as_slice()),
            _ => panic!("expected ActiveDialog::PinnedNotes"),
        }
    }

    /// A foreign `OverlayData::Error` — a rename or paste task failing after
    /// its own dialog closed — must not be routed into the pinned-notes
    /// dialog as if it were the reload it is waiting on: that would clear
    /// its in-flight guard and reopen the overlapping-write race.
    #[tokio::test]
    async fn active_dialog_leaves_pinned_notes_alone_on_a_foreign_error() {
        use tokio::sync::mpsc::unbounded_channel;

        let vault = crate::test_support::temp_vault("active-dialog-pinned-err").await;
        let (tx, mut rx) = unbounded_channel();
        let mut active = ActiveDialog::pinned_notes(vault.clone(), &tx);

        let msg = active.handle_data(
            &OverlayData::Error("rename failed".to_string()),
            &vault,
            &tx,
        );
        assert!(matches!(msg, OverlayMsg::Consumed));
        assert!(
            rx.try_recv().is_err(),
            "a foreign error must not be flashed as a pinned-notes failure"
        );
        match &active {
            ActiveDialog::PinnedNotes(d) => assert!(
                !d.is_loaded(),
                "a foreign error must not settle the dialog's own load"
            ),
            _ => panic!("expected ActiveDialog::PinnedNotes"),
        }
    }
}