1use std::sync::Arc;
2use std::sync::mpsc::Receiver;
3
4use chrono::NaiveDate;
5use kimun_core::NoteVault;
6use kimun_core::nfs::VaultPath;
7use ratatui::Frame;
8use ratatui::layout::{Constraint, Direction, Layout, Rect};
9use ratatui::style::Style;
10use ratatui::widgets::{Block, Borders, Paragraph};
11
12use crate::components::autocomplete::AutocompleteMode;
13use crate::components::event_state::EventState;
14use crate::components::events::{
15 AppEvent, AppTx, AppTxExt, InputEvent, OverlayData, redraw_callback,
16};
17use crate::components::file_list::FileListEntry;
18use crate::components::overlay::{Overlay, OverlayKind, OverlayMsg};
19use crate::components::panel::{ModalBg, ModalSpec, modal_chrome};
20use crate::components::preview_highlight;
21use crate::components::saved_search_breadcrumb::SavedSearchBreadcrumb;
22use crate::components::search_list::{
23 KeyReaction, RowSource, SearchList, SearchMouse, VaultSuggestions,
24};
25use crate::keys::KeyBindings;
26use crate::keys::action_shortcuts::ActionShortcuts;
27use crate::settings::icons::Icons;
28use crate::settings::themes::Theme;
29
30pub mod file_finder_provider;
31pub mod link_results_provider;
32pub mod search_provider;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum BrowserScope {
46 Query,
49 Files,
51}
52
53pub struct NoteBrowserModal {
54 scope: BrowserScope,
55 prefix_glyph: &'static str,
57 title: String,
58 list: SearchList<FileListEntry>,
59 vault: Arc<NoteVault>,
60 tx: AppTx,
61 preview_text: String,
62 preview_task: Option<tokio::task::JoinHandle<()>>,
64 preview_rx: Option<Receiver<String>>,
65 preview_path: Option<VaultPath>,
69 key_bindings: KeyBindings,
71 saved_search: SavedSearchBreadcrumb,
75 error: Option<String>,
78}
79
80impl NoteBrowserModal {
81 pub fn new(
82 title: impl Into<String>,
83 scope: BrowserScope,
84 provider: impl RowSource<FileListEntry>,
85 vault: Arc<NoteVault>,
86 key_bindings: KeyBindings,
87 icons: Icons,
88 tx: AppTx,
89 ) -> Self {
90 Self::new_with_query(
91 title,
92 scope,
93 provider,
94 vault,
95 key_bindings,
96 icons,
97 tx,
98 String::new(),
99 )
100 }
101
102 #[allow(clippy::too_many_arguments)]
108 pub fn with_initial_query<S: Into<String>>(
109 title: impl Into<String>,
110 scope: BrowserScope,
111 provider: impl RowSource<FileListEntry>,
112 vault: Arc<NoteVault>,
113 key_bindings: KeyBindings,
114 icons: Icons,
115 tx: AppTx,
116 query: S,
117 ) -> Self {
118 Self::new_with_query(
119 title,
120 scope,
121 provider,
122 vault,
123 key_bindings,
124 icons,
125 tx,
126 query.into(),
127 )
128 }
129
130 #[allow(clippy::too_many_arguments)]
131 fn new_with_query(
132 title: impl Into<String>,
133 scope: BrowserScope,
134 provider: impl RowSource<FileListEntry>,
135 vault: Arc<NoteVault>,
136 key_bindings: KeyBindings,
137 icons: Icons,
138 tx: AppTx,
139 initial_query: String,
140 ) -> Self {
141 let prefix_glyph = match scope {
142 BrowserScope::Query => icons.rail_find,
143 BrowserScope::Files => icons.rail_files,
144 };
145 let mut builder = SearchList::builder(provider, redraw_callback(tx.clone()))
146 .initial_query(initial_query)
147 .icons(icons)
148 .autocomplete(
149 Arc::new(VaultSuggestions {
150 vault: vault.clone(),
151 }),
152 AutocompleteMode::SearchQuery,
153 );
154 if scope == BrowserScope::Query {
155 builder = builder.highlight_query();
156 }
157 let list = builder.build();
158 let mut modal = Self {
159 scope,
160 prefix_glyph,
161 title: title.into(),
162 list,
163 vault,
164 tx,
165 preview_text: String::new(),
166 preview_task: None,
167 preview_rx: None,
168 preview_path: None,
169 key_bindings,
170 saved_search: SavedSearchBreadcrumb::default(),
171 error: None,
172 };
173 modal.refresh_preview(None);
174 modal
175 }
176
177 fn preview_needles(&self) -> Vec<String> {
181 if self.scope != BrowserScope::Query {
182 return Vec::new();
183 }
184 crate::components::query_highlight::emphasis_needles(self.list.query())
185 }
186
187 fn emphasis(&self) -> Option<Vec<String>> {
190 let needles = self.preview_needles();
191 (!needles.is_empty()).then_some(needles)
192 }
193
194 fn schedule_preview(&mut self, path: VaultPath) {
197 if let Some(handle) = self.preview_task.take() {
198 handle.abort();
199 }
200 let vault = Arc::clone(&self.vault);
201 let tx = self.tx.clone();
202 let (result_tx, result_rx) = std::sync::mpsc::channel();
203 self.preview_rx = Some(result_rx);
204
205 let handle = tokio::spawn(async move {
206 let text = vault.get_note_text(&path).await.unwrap_or_default();
207 result_tx.send(text).ok();
208 tx.send(AppEvent::Redraw).ok();
209 });
210 self.preview_task = Some(handle);
211 }
212
213 fn poll_preview(&mut self) {
214 let Some(rx) = &self.preview_rx else { return };
215 match rx.try_recv() {
216 Ok(text) => {
217 self.preview_text = text;
218 self.preview_rx = None;
219 self.preview_task = None;
220 }
221 Err(std::sync::mpsc::TryRecvError::Disconnected) => {
222 self.preview_rx = None;
223 }
224 Err(std::sync::mpsc::TryRecvError::Empty) => {}
225 }
226 }
227
228 fn refresh_preview(&mut self, selected: Option<&FileListEntry>) {
231 let maybe_path = selected.and_then(|e| match e {
232 FileListEntry::Note { path, .. } => Some(path.clone()),
233 _ => None,
234 });
235 if let Some(path) = maybe_path {
236 self.schedule_preview(path);
237 } else {
238 self.preview_text.clear();
239 if let Some(h) = self.preview_task.take() {
240 h.abort();
241 }
242 }
243 }
244
245 fn selected_note_path(&self) -> Option<VaultPath> {
248 self.list.selected_row().and_then(|e| match e {
249 FileListEntry::Note { path, .. } => Some(path.clone()),
250 _ => None,
251 })
252 }
253
254 fn refresh_preview_from_list(&mut self) {
256 let path = self.selected_note_path();
257 self.preview_path = path.clone();
258 match path {
259 Some(path) => self.schedule_preview(path),
260 None => {
261 self.preview_text.clear();
262 if let Some(h) = self.preview_task.take() {
263 h.abort();
264 }
265 }
266 }
267 }
268
269 fn open_selected(&self, tx: &AppTx) {
274 let Some(entry) = self.list.selected_row() else {
275 return;
276 };
277 if let FileListEntry::CreateNote { path, .. } = entry {
278 let path = path.clone();
279 let vault = Arc::clone(&self.vault);
280 let tx = tx.clone();
281 tokio::spawn(async move {
282 match vault.load_or_create_note(&path, None).await {
283 Ok((_, created)) => tx.announce_and_open(path, created),
284 Err(e) => {
285 tx.send(AppEvent::OverlayData(OverlayData::Error(e.to_string())))
286 .ok();
287 }
288 }
289 });
290 return;
291 }
292 let path = entry.path().clone();
293 tx.send(AppEvent::OpenPath {
294 path,
295 emphasis: self.emphasis(),
296 })
297 .ok();
298 }
299
300 #[cfg(test)]
303 fn saved_search_breadcrumb(&self) -> Option<String> {
304 self.saved_search.label(self.list.query())
305 }
306
307 #[cfg(test)]
311 pub(super) fn query_text(&self) -> &str {
312 self.list.query()
313 }
314}
315
316impl Overlay for NoteBrowserModal {
321 fn kind(&self) -> OverlayKind {
322 OverlayKind::NoteBrowser
323 }
324
325 fn query(&self) -> Option<&str> {
326 Some(self.list.query())
327 }
328
329 fn saved_search_provenance(&self) -> Option<&str> {
330 self.saved_search.name()
331 }
332
333 fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
334 match event {
335 InputEvent::Mouse(mouse) => match self.list.handle_mouse(mouse) {
336 SearchMouse::Activated(_) => {
337 self.open_selected(tx);
338 EventState::Consumed
339 }
340 SearchMouse::Context(_) | SearchMouse::Selected(_) | SearchMouse::Scrolled => {
341 self.refresh_preview_from_list();
342 EventState::Consumed
343 }
344 SearchMouse::ContentScrollUp | SearchMouse::ContentScrollDown => {
347 EventState::Consumed
348 }
349 SearchMouse::None => EventState::NotConsumed,
350 },
351 InputEvent::Key(key) => {
352 self.error = None;
354 match self.list.handle_key(key) {
355 KeyReaction::Submit => {
356 self.open_selected(tx);
357 EventState::Consumed
358 }
359 KeyReaction::Cancel => {
360 tx.send(AppEvent::CloseOverlay).ok();
361 EventState::Consumed
362 }
363 KeyReaction::Consumed => {
364 let accepted = self.list.take_accepted_saved_search();
368 let blank = self.list.query().trim().is_empty();
369 self.saved_search
370 .on_query_consumed(accepted, self.list.query(), blank);
371 self.refresh_preview_from_list();
372 EventState::Consumed
373 }
374 KeyReaction::Intercepted(_) | KeyReaction::Unhandled => EventState::NotConsumed,
375 }
376 }
377 _ => EventState::NotConsumed,
378 }
379 }
380
381 fn handle_data(
382 &mut self,
383 data: &OverlayData,
384 _vault: &Arc<NoteVault>,
385 _tx: &AppTx,
386 ) -> OverlayMsg {
387 if let OverlayData::Error(text) = data {
390 self.error = Some(text.clone());
391 OverlayMsg::Consumed
392 } else {
393 OverlayMsg::NotConsumed
394 }
395 }
396
397 fn render(&mut self, f: &mut Frame, area: Rect, theme: &Theme) {
398 self.poll_preview();
399
400 let popup_rect = crate::components::centered_rect(75, 75, area);
401
402 let modal_style = Style::default()
404 .fg(theme.fg.to_ratatui())
405 .bg(theme.bg_hard.to_ratatui());
406 let title = format!(" {} ", self.title);
407 let inner = modal_chrome(
408 f,
409 popup_rect,
410 theme,
411 ModalSpec {
412 title: Some(&title),
413 bg: ModalBg::Hard,
414 ..Default::default()
415 },
416 );
417
418 let rows = Layout::default()
419 .direction(Direction::Vertical)
420 .constraints([
421 Constraint::Length(3),
422 Constraint::Min(0),
423 Constraint::Length(1),
424 ])
425 .split(inner);
426
427 let search_title = self
431 .saved_search
432 .border_title(self.list.query(), " Search ");
433 let result_count = self.list.match_count();
434 let search_block = Block::default()
435 .title(search_title)
436 .title(
437 ratatui::text::Line::from(ratatui::text::Span::styled(
438 format!(" {result_count} results "),
439 Style::default().fg(theme.gray.to_ratatui()),
440 ))
441 .right_aligned(),
442 )
443 .borders(Borders::ALL)
444 .border_style(theme.border_style(true))
445 .style(modal_style);
446 let search_inner = search_block.inner(rows[0]);
447 f.render_widget(search_block, rows[0]);
448 let prefix = format!("{} ", self.prefix_glyph);
450 let prefix_w = unicode_width::UnicodeWidthStr::width(prefix.as_str()) as u16;
451 f.render_widget(
452 Paragraph::new(prefix).style(
453 Style::default()
454 .fg(theme.yellow.to_ratatui())
455 .bg(theme.bg_hard.to_ratatui()),
456 ),
457 Rect {
458 width: prefix_w.min(search_inner.width),
459 ..search_inner
460 },
461 );
462 let input_rect = Rect {
463 x: search_inner.x.saturating_add(prefix_w),
464 width: search_inner.width.saturating_sub(prefix_w),
465 ..search_inner
466 };
467 self.list.render_query(f, input_rect, theme, true);
468
469 let columns = Layout::default()
471 .direction(Direction::Horizontal)
472 .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
473 .split(rows[1]);
474
475 let list_block = Block::default()
479 .borders(Borders::ALL)
480 .border_style(theme.border_style(false))
481 .style(modal_style);
482 let list_inner = list_block.inner(columns[0]);
483 f.render_widget(list_block, columns[0]);
484 self.list.render(f, list_inner, theme, false);
485 self.list.set_list_rect(list_inner);
486 self.list.set_panel_rect(popup_rect);
488
489 if self.selected_note_path() != self.preview_path {
494 self.refresh_preview_from_list();
495 }
496
497 let needles = self.preview_needles();
500 let match_count = count_matches(&self.preview_text, &needles);
501 let preview_title = match (&self.preview_path, match_count) {
502 (Some(path), Some(n)) => {
503 format!(" {} · {} matches ", path.get_name(), n)
504 }
505 (Some(path), None) => format!(" {} ", path.get_name()),
506 (None, _) => " Preview ".to_string(),
507 };
508 let preview_block = Block::default()
509 .title(preview_title)
510 .borders(Borders::ALL)
511 .border_style(theme.border_style(false))
512 .style(modal_style);
513 let preview_inner = preview_block.inner(columns[1]);
514 f.render_widget(preview_block, columns[1]);
515 f.render_widget(
516 Paragraph::new(highlight_matches(
517 &self.preview_text,
518 &needles,
519 theme,
520 modal_style,
521 )),
522 preview_inner,
523 );
524
525 let hint = match &self.error {
527 Some(err) => Paragraph::new(format!("⚠ {err}"))
528 .style(Style::default().fg(theme.red.to_ratatui())),
529 None => Paragraph::new("↑↓: navigate | Enter: open | Esc: close")
530 .style(Style::default().fg(theme.fg_secondary.to_ratatui())),
531 };
532 f.render_widget(hint, rows[2]);
533
534 self.list.render_autocomplete(f, popup_rect, theme);
537 }
538
539 fn hint_shortcuts(&self) -> Vec<(String, String)> {
540 let mut hints = vec![
541 ("↑↓".to_string(), "navigate".to_string()),
542 ("Enter".to_string(), "open".to_string()),
543 ("Esc".to_string(), "close".to_string()),
544 ];
545 if let Some(k) = self
546 .key_bindings
547 .first_combo_for(&ActionShortcuts::SaveCurrentQuery)
548 {
549 hints.push((k, "save query".to_string()));
550 }
551 hints
552 }
553}
554
555pub(crate) fn format_journal_date(date: NaiveDate) -> String {
560 date.format("%A, %B %-d, %Y").to_string()
561}
562
563fn count_matches(text: &str, needles: &[String]) -> Option<usize> {
573 if needles.is_empty() {
574 return None;
575 }
576 Some(preview_highlight::match_ranges(text, needles).len())
577}
578
579fn highlight_matches<'a>(
583 text: &'a str,
584 needles: &[String],
585 theme: &Theme,
586 base: Style,
587) -> ratatui::text::Text<'a> {
588 use ratatui::text::{Line, Span};
589 if needles.is_empty() {
590 return ratatui::text::Text::styled(text, base);
591 }
592 let emphasis = base.patch(
593 Style::default()
594 .fg(theme.color_search_match.to_ratatui())
595 .add_modifier(ratatui::style::Modifier::BOLD),
596 );
597 let mut lines = Vec::new();
598 for line in text.lines() {
599 let ranges = preview_highlight::match_ranges(line, needles);
600 if ranges.is_empty() {
601 lines.push(Line::styled(line, base));
602 continue;
603 }
604 let spans = preview_highlight::style_ranges(line, &ranges, |s, hit| {
606 Span::styled(s, if hit { emphasis } else { base })
607 });
608 lines.push(Line::from(spans));
609 }
610 ratatui::text::Text::from(lines)
611}
612
613#[cfg(test)]
614mod tests {
615 use super::*;
616 use crate::components::search_list::{Emit, RowSource};
617 use crate::settings::AppSettings;
618 use crate::test_support::temp_vault;
619 use async_trait::async_trait;
620 use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
621 use tokio::sync::mpsc::unbounded_channel;
622
623 #[test]
624 fn count_matches_matches_highlighted_ranges() {
625 assert_eq!(count_matches("anything", &[]), None);
627 let needles = vec!["foo".to_string(), "foobar".to_string()];
630 assert_eq!(count_matches("foobar", &needles), Some(1));
631 assert_eq!(count_matches("foo and foo", &["foo".to_string()]), Some(2));
633 }
634
635 struct OneNoteSource {
638 path: VaultPath,
639 }
640
641 #[async_trait]
642 impl RowSource<FileListEntry> for OneNoteSource {
643 async fn load(&self, _query: &str, emit: Emit<FileListEntry>) {
644 emit.replace(vec![FileListEntry::Note {
645 path: self.path.clone(),
646 title: "Note".to_string(),
647 filename: self.path.to_string(),
648 journal_date: None,
649 is_open: false,
650 }]);
651 }
652 }
653
654 async fn make_modal_with(source: impl RowSource<FileListEntry>, tx: AppTx) -> NoteBrowserModal {
655 let vault = temp_vault("modal").await;
656 let settings = AppSettings::default();
657 NoteBrowserModal::new(
658 "test",
659 BrowserScope::Query,
660 source,
661 vault,
662 settings.key_bindings.clone(),
663 settings.icons(),
664 tx,
665 )
666 }
667
668 #[tokio::test]
669 async fn dialog_error_surfaces_then_clears_on_keystroke() {
670 let (tx, _rx) = unbounded_channel();
671 let path = VaultPath::note_path_from("/a.md");
672 let mut modal = make_modal_with(OneNoteSource { path }, tx.clone()).await;
673 let vault = temp_vault("modal_err").await;
674
675 let consumed = modal.handle_data(&OverlayData::Error("boom".to_string()), &vault, &tx);
676 assert!(matches!(consumed, OverlayMsg::Consumed));
677 assert_eq!(modal.error.as_deref(), Some("boom"));
678
679 modal.handle_input(
681 &InputEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)),
682 &tx,
683 );
684 assert_eq!(modal.error, None, "keystroke should clear the error");
685 }
686
687 #[tokio::test]
688 async fn modal_constructed_with_initial_query_prefills_input() {
689 let vault = temp_vault("modal_iq").await;
690 let settings = AppSettings::default();
691 let (tx, _rx) = unbounded_channel();
692 let modal = NoteBrowserModal::with_initial_query(
693 "test",
694 BrowserScope::Query,
695 OneNoteSource {
696 path: VaultPath::note_path_from("/a.md"),
697 },
698 vault,
699 settings.key_bindings.clone(),
700 settings.icons(),
701 tx,
702 "#important",
703 );
704 assert_eq!(modal.query_text(), "#important");
705 }
706
707 #[tokio::test]
711 async fn submit_opens_selected_note() {
712 let (tx, mut rx) = unbounded_channel();
713 let path = VaultPath::note_path_from("/a.md");
714 let mut modal = make_modal_with(OneNoteSource { path: path.clone() }, tx.clone()).await;
715 modal.list.poll_until_idle().await;
717
718 Overlay::handle_input(
719 &mut modal,
720 &InputEvent::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)),
721 &tx,
722 );
723
724 let mut events = Vec::new();
725 while let Ok(ev) = rx.try_recv() {
726 events.push(ev);
727 }
728 assert!(
729 events
730 .iter()
731 .any(|e| matches!(e, AppEvent::OpenPath { path: p, .. } if *p == path)),
732 "expected OpenPath, got {events:?}"
733 );
734 assert!(
735 !events.iter().any(|e| matches!(e, AppEvent::CloseOverlay)),
736 "select must not emit CloseOverlay; editor's OpenPath handler closes the overlay, got {events:?}"
737 );
738 }
739
740 #[tokio::test]
744 async fn refresh_preview_tracks_selected_path() {
745 let (tx, _rx) = unbounded_channel();
746 let path = VaultPath::note_path_from("/a.md");
747 let mut modal = make_modal_with(OneNoteSource { path: path.clone() }, tx.clone()).await;
748 modal.list.poll_until_idle().await;
749 assert_eq!(modal.preview_path, None, "no path tracked before refresh");
750
751 modal.refresh_preview_from_list();
752 assert_eq!(
753 modal.preview_path,
754 Some(path),
755 "preview_path should track the selected note"
756 );
757 }
758
759 #[tokio::test]
761 async fn esc_closes_modal() {
762 let (tx, mut rx) = unbounded_channel();
763 let mut modal = make_modal_with(
764 OneNoteSource {
765 path: VaultPath::note_path_from("/a.md"),
766 },
767 tx.clone(),
768 )
769 .await;
770 Overlay::handle_input(
771 &mut modal,
772 &InputEvent::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
773 &tx,
774 );
775 let mut sent = false;
776 while let Ok(ev) = rx.try_recv() {
777 if matches!(ev, AppEvent::CloseOverlay) {
778 sent = true;
779 }
780 }
781 assert!(sent, "expected CloseOverlay on Esc");
782 }
783
784 #[tokio::test(flavor = "multi_thread")]
787 async fn accepting_saved_search_pins_breadcrumb() {
788 let vault = temp_vault("modal-ss").await;
789 vault.validate_and_init().await.unwrap();
790 vault.save_search("todo-week", "#todo").await.unwrap();
791 let settings = AppSettings::default();
792 let (tx, _rx) = unbounded_channel();
793 let mut modal = NoteBrowserModal::new(
794 "test",
795 BrowserScope::Query,
796 OneNoteSource {
797 path: VaultPath::note_path_from("/a.md"),
798 },
799 vault,
800 settings.key_bindings.clone(),
801 settings.icons(),
802 tx.clone(),
803 );
804
805 for ch in ['?', 't', 'o'] {
808 Overlay::handle_input(
809 &mut modal,
810 &InputEvent::Key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)),
811 &tx,
812 );
813 for _ in 0..30 {
814 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
815 modal.list.poll();
816 }
817 }
818 Overlay::handle_input(
819 &mut modal,
820 &InputEvent::Key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)),
821 &tx,
822 );
823
824 assert_eq!(modal.query_text(), "#todo");
825 assert_eq!(
826 modal.saved_search_breadcrumb().as_deref(),
827 Some("todo-week")
828 );
829 assert_eq!(Overlay::saved_search_provenance(&modal), Some("todo-week"));
832 }
833}