kimun_notes/components/events.rs
1use std::num::NonZeroU64;
2use std::sync::Arc;
3use std::time::Duration;
4
5use ratatui::crossterm::event::{KeyEvent, MouseEvent};
6use tokio::sync::mpsc::UnboundedSender;
7
8use kimun_core::{NoteVault, nfs::VaultPath};
9
10use crate::components::file_list::{SortField, SortOrder};
11
12/// Which panel a sort selection applies to.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum SortTarget {
15 Sidebar,
16 Query,
17}
18
19/// The surface a save-current-query action sourced its query from. Carried
20/// through the save-search dialog so the editor knows whether the Query
21/// panel's breadcrumb should re-pin after the save — by identity, not by
22/// comparing query text (equal text from different surfaces must not collide).
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SaveSource {
25 QueryPanel,
26 NoteBrowser,
27}
28
29/// All events that flow through the system — both input events (from crossterm)
30/// and app-level messages sent by components / screens to the main loop.
31#[derive(Debug, Clone)]
32pub enum AppEvent {
33 Input(InputEvent),
34 OpenScreen(ScreenEvent),
35
36 // ── App-level messages ───────────────────────────────────────────────────
37 Quit,
38 Redraw,
39 Autosave,
40 /// Background autosave task finished. `saved_revision` carries the
41 /// editor's `content_revision` at the moment the save was *issued*
42 /// on success, `None` if the write failed. The editor screen uses
43 /// `path` to ignore stale completions for notes the user has
44 /// already navigated away from, and `saved_revision` to clear the
45 /// dirty flag iff the buffer is still at that revision (i.e. no
46 /// edits during the save). `NonZeroU64` because the editor's
47 /// `content_revision` is never zero.
48 AutosaveCompleted {
49 path: VaultPath,
50 saved_revision: Option<NonZeroU64>,
51 /// The note's recomputed title (first body line) from the save, so the
52 /// sidebar row can be retitled. `None` when the save failed.
53 title: Option<String>,
54 },
55 /// Open a note (or directory) — `emphasis` carries the originating
56 /// query's needles when the open comes from a query result, so the
57 /// editor lights up the matched spans (spec §5.1). Use
58 /// [`AppEvent::open`] for the plain case.
59 OpenPath {
60 path: VaultPath,
61 emphasis: Option<Vec<String>>,
62 },
63 FocusSidebar,
64 /// Switch the drawer to the given view and reveal it (sent by the
65 /// activity rail and, later, by leader paths / mouse clicks).
66 OpenDrawerView(crate::components::drawer::DrawerView),
67 /// Run the query `#<label>` in the FIND drawer (sent by the TAGS drawer).
68 RunTagQuery(String),
69 /// Jump the editor cursor to the first heading with this text (sent by
70 /// the OUTLINE drawer).
71 JumpToHeading(String),
72 /// Run a leader-tree action (sent by the command palette after it has
73 /// closed itself, so the action sees no open overlay).
74 ExecuteLeaderAction(crate::keys::leader::LeaderAction),
75 /// Show a transient footer flash — async tasks report results with it.
76 FlashMessage(String),
77 /// Apply (and optionally persist) a resolved theme — sent by the theme
78 /// picker: previews on selection move, persists on Enter. Carries the
79 /// full `Theme` so applying never re-reads the themes directory.
80 ApplyTheme {
81 theme: Box<crate::settings::themes::Theme>,
82 persist: bool,
83 },
84 /// Async-loaded backlink count for the link target under the editor
85 /// cursor (status line 2's `→ target · N backlinks` affordance).
86 LinkTargetMeta {
87 target: String,
88 count: usize,
89 },
90 /// Async-loaded backlink count for the note at `path` (status line 2).
91 BacklinkCountLoaded {
92 path: VaultPath,
93 count: usize,
94 },
95 /// Async-loaded workspace git summary for the status bar, `None` when
96 /// the workspace is not a git repository.
97 GitStatusLoaded(Option<String>),
98 /// Sent by PreferencesScreen when user confirms Save. The shared settings
99 /// reference already contains the updated values.
100 PreferencesSaved,
101 /// Sent by PreferencesScreen when user discards or closes unchanged.
102 ClosePreferences,
103 /// Sent by VaultSection; PreferencesScreen::handle_app_message intercepts.
104 OpenFileBrowser,
105 /// Sent by IndexingSection; PreferencesScreen intercepts.
106 TriggerFastReindex,
107 TriggerFullReindex,
108 /// Sent by indexing tokio task on completion.
109 IndexingDone(Result<Duration, String>),
110 /// Open (or create) today's journal entry and switch to it in the editor.
111 OpenJournal,
112 /// Dismiss the active editor overlay (note browser, Saved Searches modal,
113 /// or dialog). The single close path for everything owned by `OverlayHost`.
114 CloseOverlay,
115 /// Follow the link under the editor cursor: note name/path or external URL.
116 FollowLink(String),
117 /// Open the search modal pre-filled with `#<name>` to browse notes by label.
118 FollowLabel(String),
119 /// Insert raw text at the editor's cursor (replacing any active selection).
120 /// Used by the screen layer to deliver async results back to the editor —
121 /// e.g. the markdown link generated after a clipboard image is saved as an attachment.
122 InsertAtCursor(String),
123
124 // ── File-operation dialog messages ───────────────────────────────────────
125 /// Request to show the file-operations menu (delete / rename / move).
126 ShowFileOpsMenu(VaultPath),
127 /// Request to show the delete confirmation dialog for the given entry.
128 ShowDeleteDialog(VaultPath),
129 /// Request to show the rename dialog for the given entry.
130 ShowRenameDialog(VaultPath),
131 /// Request to show the move dialog for the given entry.
132 ShowMoveDialog(VaultPath),
133 /// Confirmation that the given entry was successfully deleted.
134 EntryDeleted(VaultPath),
135 /// Confirmation that an entry was successfully renamed.
136 EntryRenamed {
137 from: VaultPath,
138 to: VaultPath,
139 },
140 /// Confirmation that an entry was successfully moved.
141 EntryMoved {
142 from: VaultPath,
143 to: VaultPath,
144 },
145 /// Notification that a note was just created at this path. The current
146 /// screen refreshes its sidebar if it is browsing the note's directory.
147 /// Opening the note is a separate concern (the creator emits `OpenPath`).
148 EntryCreated(VaultPath),
149 /// A dialog operation failed; carries a human-readable error message.
150 DialogError(String),
151
152 /// A vault was found to be structurally unusable (conflicts, invalid layout, etc.).
153 /// Carries a formatted, human-readable error message.
154 ///
155 /// Handled by `handle_app_message` in `main.rs`, which clears the workspace,
156 /// saves settings, and opens the settings screen with an error overlay.
157 /// To add a new conflict source: emit this event from the detection site; no
158 /// other files need to change.
159 VaultConflict(String),
160
161 // ── Dialog async result messages ─────────────────────────────────────────
162 /// Rename dialog: name availability check result.
163 RenameValidation {
164 available: bool,
165 },
166 /// Move dialog: directory list has loaded.
167 MoveDirectoriesLoaded(Vec<VaultPath>),
168 /// Move dialog: fuzzy filter results are ready.
169 MoveFilterResults(Vec<VaultPath>),
170 /// Move dialog: destination existence check result.
171 MoveDestValidation {
172 available: bool,
173 },
174 /// Save-search dialog: existing saved-search names have loaded (drives
175 /// the update/overwrite/save-new hint).
176 SavedSearchNamesLoaded(Vec<String>),
177
178 // ── Workspace messages ──────────────────────────────────────────────
179 /// User switched to a different workspace. Carries the workspace name.
180 /// Handled by main.rs to rebuild the vault and navigate to StartScreen.
181 WorkspaceSwitched(String),
182
183 /// Persist a saved search (emitted by the save-search dialog on submit).
184 /// `source` is the surface the query was sourced from, decided when the
185 /// dialog opened — it drives whether the panel breadcrumb re-pins.
186 SaveSearchConfirmed {
187 name: String,
188 query: String,
189 source: SaveSource,
190 },
191
192 /// A saved search was written to disk (success path of
193 /// `SaveSearchConfirmed`). The editor re-pins the panel breadcrumb here —
194 /// only once the write actually succeeded.
195 SavedSearchPersisted {
196 name: String,
197 query: String,
198 source: SaveSource,
199 },
200
201 /// The background saved-search write failed; surface it to the user.
202 SavedSearchSaveFailed {
203 name: String,
204 },
205
206 /// A saved search was chosen in the Saved Searches modal.
207 SavedSearchSelected {
208 query: String,
209 name: String,
210 },
211
212 /// Sort selection changed in the sort dialog — apply live to `target`.
213 /// When `persist` is set (sidebar's "save as default"), also write the
214 /// choice to settings. `group_directories` is sidebar-only (the query panel
215 /// ignores it).
216 SortChanged {
217 target: SortTarget,
218 field: SortField,
219 order: SortOrder,
220 group_directories: bool,
221 persist: bool,
222 },
223}
224
225impl AppEvent {
226 pub fn send_input(event: InputEvent) -> Self {
227 AppEvent::Input(event)
228 }
229
230 /// `OpenPath` without query emphasis — the common case.
231 pub fn open(path: kimun_core::nfs::VaultPath) -> Self {
232 AppEvent::OpenPath {
233 path,
234 emphasis: None,
235 }
236 }
237}
238
239// ── Input events ────────────────────────────────────────────────────────
240#[derive(Debug, Clone)]
241pub enum InputEvent {
242 Key(KeyEvent),
243 Mouse(MouseEvent),
244 /// Bracketed-paste payload from the terminal. On macOS this is what
245 /// Cmd+V delivers, since the terminal intercepts Cmd combos before they
246 /// reach the TUI. The string may be empty when the clipboard holds only
247 /// non-text content (e.g. an image).
248 Paste(String),
249}
250
251// ── Screen events ────────────────────────────────────────────────────────
252#[derive(Debug, Clone)]
253pub enum ScreenEvent {
254 Start,
255 OpenPreferences,
256 /// Open the settings screen with an error overlay already shown.
257 OpenPreferencesWithError(String),
258 /// Navigate to the editor for the given vault root path.
259 OpenEditor(Arc<NoteVault>, VaultPath),
260 /// Navigate to the browse screen for the given vault root and directory path.
261 OpenBrowse(Arc<NoteVault>, VaultPath),
262}
263
264/// Convenience alias used throughout the codebase.
265pub type AppTx = UnboundedSender<AppEvent>;
266
267/// Sender helpers for the create-then-open sequence shared by every
268/// note-creation site (create dialog, quick note, note browser, sidebar,
269/// journal).
270pub trait AppTxExt {
271 /// Announce a freshly created note so sidebars browsing its directory
272 /// refresh, then open it. The notification is gated on `created` (an
273 /// already-existing note needs no refresh); the note is opened regardless.
274 fn announce_and_open(&self, path: VaultPath, created: bool);
275}
276
277impl AppTxExt for AppTx {
278 fn announce_and_open(&self, path: VaultPath, created: bool) {
279 if created {
280 self.send(AppEvent::EntryCreated(path.clone())).ok();
281 }
282 self.send(AppEvent::open(path)).ok();
283 }
284}
285
286/// Build a `Send + Sync` callback that fires `AppEvent::Redraw` on the
287/// app event bus. Used by long-lived components (autocomplete query
288/// task, etc.) that need to wake the render loop from a background
289/// thread but should not be aware of `AppEvent` themselves.
290pub fn redraw_callback(tx: AppTx) -> Arc<dyn Fn() + Send + Sync + 'static> {
291 Arc::new(move || {
292 let _ = tx.send(AppEvent::Redraw);
293 })
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 fn _assert_new_variants_exist(e: AppEvent) {
301 match e {
302 AppEvent::ShowDeleteDialog(_) => {}
303 AppEvent::ShowRenameDialog(_) => {}
304 AppEvent::ShowMoveDialog(_) => {}
305 AppEvent::EntryDeleted(_) => {}
306 AppEvent::EntryRenamed { from: _, to: _ } => {}
307 AppEvent::EntryMoved { from: _, to: _ } => {}
308 AppEvent::DialogError(_) => {}
309 _ => {}
310 }
311 }
312
313 #[test]
314 fn sort_events_construct() {
315 use crate::components::file_list::{SortField, SortOrder};
316 let _ = AppEvent::SortChanged {
317 target: SortTarget::Sidebar,
318 field: SortField::Name,
319 order: SortOrder::Ascending,
320 group_directories: true,
321 persist: false,
322 };
323 let _ = AppEvent::SortChanged {
324 target: SortTarget::Query,
325 field: SortField::Title,
326 order: SortOrder::Descending,
327 group_directories: false,
328 persist: true,
329 };
330 }
331}