ratado 0.2.0

A fast, keyboard-driven terminal task manager built with Rust and Ratatui
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
//! Search view for finding tasks.
//!
//! Provides full-text search functionality with live filtering and result highlighting.

use ratatui::{
    layout::{Constraint, Layout, Rect},
    style::{Modifier, Style},
    symbols::border,
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame,
};

use crate::models::{Priority, Task, TaskStatus};
use crate::utils::format_relative_date;
use super::theme;

/// A search result with match information.
#[derive(Debug, Clone)]
pub struct SearchResult {
    /// The matching task
    pub task: Task,
    /// Match position in title (start, end)
    pub title_match: Option<(usize, usize)>,
    /// Snippet from description with match
    pub desc_snippet: Option<String>,
    /// Matching tag name (if search matched a tag)
    pub tag_match: Option<String>,
}

/// Performs search on tasks and returns matching results.
///
/// Searches in task title, description, and tags (case-insensitive).
/// Tag searches can use the `#tag` syntax or just the tag name.
pub fn search_tasks(query: &str, tasks: &[Task]) -> Vec<SearchResult> {
    let query_lower = query.to_lowercase();
    if query_lower.is_empty() {
        return Vec::new();
    }

    // Check if searching specifically for a tag (starts with #)
    let tag_query = if query_lower.starts_with('#') {
        Some(query_lower.trim_start_matches('#'))
    } else {
        None
    };

    tasks
        .iter()
        .filter_map(|task| {
            let title_lower = task.title.to_lowercase();
            let title_match = title_lower.find(&query_lower).map(|start| {
                (start, start + query_lower.len())
            });

            let desc_snippet = task.description.as_ref().and_then(|desc| {
                let desc_lower = desc.to_lowercase();
                desc_lower.find(&query_lower).map(|pos| {
                    // Extract snippet around match
                    let start = pos.saturating_sub(20);
                    let end = (pos + query_lower.len() + 30).min(desc.len());
                    let prefix = if start > 0 { "..." } else { "" };
                    let suffix = if end < desc.len() { "..." } else { "" };
                    format!("{}{}{}", prefix, &desc[start..end], suffix)
                })
            });

            // Search in tags - match if any tag contains the query
            let search_term = tag_query.unwrap_or(&query_lower);
            let tag_match = task.tags.iter().find(|tag| {
                tag.to_lowercase().contains(search_term)
            }).cloned();

            if title_match.is_some() || desc_snippet.is_some() || tag_match.is_some() {
                Some(SearchResult {
                    task: task.clone(),
                    title_match,
                    desc_snippet,
                    tag_match,
                })
            } else {
                None
            }
        })
        .collect()
}

/// Renders the search view.
pub fn render_search(
    frame: &mut Frame,
    query: &str,
    cursor_pos: usize,
    results: &[SearchResult],
    selected_index: usize,
    area: Rect,
) {
    render_search_with_context(frame, query, cursor_pos, results, selected_index, area, None);
}

/// Renders the search view with optional project context.
pub fn render_search_with_context(
    frame: &mut Frame,
    query: &str,
    cursor_pos: usize,
    results: &[SearchResult],
    selected_index: usize,
    area: Rect,
    project_name: Option<&str>,
) {
    // Clear the area
    frame.render_widget(Clear, area);

    // Main layout: search input at top, results below
    let chunks = Layout::vertical([
        Constraint::Length(3), // Search input
        Constraint::Min(0),    // Results
    ])
    .split(area);

    // Render search input with project context
    render_search_input_with_context(frame, query, cursor_pos, chunks[0], project_name);

    // Render results
    render_search_results(frame, query, results, selected_index, chunks[1]);
}

/// Renders the search input box with optional project context.
fn render_search_input_with_context(
    frame: &mut Frame,
    query: &str,
    cursor_pos: usize,
    area: Rect,
    project_name: Option<&str>,
) {
    let title = match project_name {
        Some(name) if name != "All Tasks" => format!(" Search in: {} ", name),
        _ => " Search Tasks ".to_string(),
    };

    let block = Block::default()
        .title(Span::styled(
            title,
            Style::default().fg(theme::INFO).add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::ALL)
        .border_set(border::ROUNDED)
        .border_style(Style::default().fg(theme::INFO))
        .style(Style::default().bg(theme::BG_ELEVATED));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Show search query with cursor
    let display_text = format!("/{}", query);
    let mut spans = Vec::new();

    for (i, c) in display_text.chars().enumerate() {
        let style = if i == cursor_pos + 1 {
            // Cursor position (offset by 1 for the '/')
            Style::default().bg(theme::ACCENT).fg(theme::BG_DARK)
        } else {
            Style::default().fg(theme::TEXT_PRIMARY)
        };
        spans.push(Span::styled(c.to_string(), style));
    }

    // Show cursor at end if at end of text
    if cursor_pos >= query.len() {
        spans.push(Span::styled(" ", Style::default().bg(theme::ACCENT)));
    }

    let paragraph = Paragraph::new(Line::from(spans));
    frame.render_widget(paragraph, inner);
}

/// Renders the search results list.
fn render_search_results(
    frame: &mut Frame,
    query: &str,
    results: &[SearchResult],
    selected_index: usize,
    area: Rect,
) {
    let block = Block::default()
        .title(Span::styled(
            format!(" Results ({}) ", results.len()),
            Style::default().fg(theme::TEXT_SECONDARY),
        ))
        .borders(Borders::ALL)
        .border_set(border::ROUNDED)
        .border_style(Style::default().fg(theme::BORDER))
        .style(Style::default().bg(theme::BG_ELEVATED));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    if results.is_empty() {
        let msg = if query.is_empty() {
            "Type to search..."
        } else {
            "No matching tasks found"
        };
        let paragraph = Paragraph::new(msg)
            .style(Style::default().fg(theme::TEXT_MUTED));
        frame.render_widget(paragraph, inner);
        return;
    }

    let mut lines: Vec<Line> = Vec::new();
    let visible_height = inner.height as usize;

    // Calculate scroll offset to keep selected item visible
    // Each result takes 2 lines (task + description/spacing)
    let lines_per_result = 2;
    let visible_results = visible_height / lines_per_result;
    let scroll_offset = if selected_index >= visible_results {
        selected_index - visible_results + 1
    } else {
        0
    };

    for (i, result) in results.iter().enumerate().skip(scroll_offset) {
        if lines.len() >= visible_height {
            break;
        }

        let is_selected = i == selected_index;

        // Render task row similar to task list
        let task_line = render_task_result(&result.task, result.title_match, is_selected, inner.width);
        lines.push(task_line);

        // Render match info (description snippet or tag match) if present
        if lines.len() < visible_height {
            if let Some(ref snippet) = result.desc_snippet {
                let desc_line = render_description_snippet(snippet, query, is_selected);
                lines.push(desc_line);
            } else if let Some(ref tag) = result.tag_match {
                let tag_line = render_tag_match(tag, query, is_selected);
                lines.push(tag_line);
            } else {
                // Empty line for spacing
                lines.push(Line::from(""));
            }
        }
    }

    let paragraph = Paragraph::new(lines);
    frame.render_widget(paragraph, inner);
}

/// Renders a task result row similar to the main task list.
fn render_task_result(
    task: &Task,
    title_match: Option<(usize, usize)>,
    is_selected: bool,
    width: u16,
) -> Line<'static> {
    // Checkbox based on status
    let checkbox = match task.status {
        TaskStatus::Pending => "[ ]",
        TaskStatus::InProgress => "[â–¸]",
        TaskStatus::Completed | TaskStatus::Archived => "[✓]",
    };

    // Priority indicator
    let priority = match task.priority {
        Priority::Urgent => "!!",
        Priority::High => " !",
        Priority::Medium => "  ",
        Priority::Low => " ↓",
    };

    // Priority color
    let priority_style = match task.priority {
        Priority::Urgent => Style::default().fg(theme::PRIORITY_URGENT).add_modifier(Modifier::BOLD),
        Priority::High => Style::default().fg(theme::PRIORITY_HIGH),
        Priority::Medium => Style::default(),
        Priority::Low => Style::default().fg(theme::PRIORITY_LOW),
    };

    // Due date
    let due_str = task
        .due_date
        .map(format_relative_date)
        .unwrap_or_default();

    // Calculate available width for title
    let fixed_width = 5 + 3 + 3 + 2 + due_str.len() + 2; // selector + checkbox + priority + spacing + due
    let title_width = (width as usize).saturating_sub(fixed_width).max(10);

    // Base style based on task state
    let base_style = if task.status == TaskStatus::Completed || task.status == TaskStatus::Archived {
        Style::default().fg(theme::TEXT_COMPLETED)
    } else if task.is_overdue() {
        Style::default().fg(theme::DUE_OVERDUE)
    } else if task.is_due_today() {
        Style::default().fg(theme::DUE_TODAY)
    } else if task.is_due_this_week() {
        Style::default().fg(theme::DUE_WEEK)
    } else {
        Style::default().fg(theme::TEXT_PRIMARY)
    };

    // Selection indicator and style
    let (selector, selector_style) = if is_selected {
        ("â–¶ ", Style::default().fg(theme::ACCENT).add_modifier(Modifier::BOLD))
    } else {
        ("  ", Style::default())
    };

    // Row style with selection highlight
    let row_style = if is_selected {
        base_style.add_modifier(Modifier::BOLD)
    } else {
        base_style
    };

    // Build spans
    let mut spans = vec![
        Span::styled(selector.to_string(), selector_style),
        Span::styled(format!("{} ", checkbox), row_style),
        Span::styled(format!("{} ", priority), priority_style),
    ];

    // Add title with match highlighting
    let title = &task.title;
    if let Some((start, end)) = title_match {
        // Before match
        if start > 0 {
            let before = truncate_str(&title[..start], title_width);
            spans.push(Span::styled(before, row_style));
        }

        // The match (highlighted with underline)
        let match_text = &title[start..end.min(title.len())];
        let match_style = row_style.add_modifier(Modifier::UNDERLINED | Modifier::BOLD);
        spans.push(Span::styled(match_text.to_string(), match_style));

        // After match
        if end < title.len() {
            let remaining_width = title_width.saturating_sub(end);
            let after = truncate_str(&title[end..], remaining_width);
            spans.push(Span::styled(after, row_style));
        }
    } else {
        // No match in title
        let truncated = truncate_str(title, title_width);
        spans.push(Span::styled(truncated, row_style));
    }

    // Add due date
    if !due_str.is_empty() {
        spans.push(Span::styled(
            format!("  {}", due_str),
            Style::default().fg(theme::TEXT_MUTED),
        ));
    }

    Line::from(spans)
}

/// Renders a tag match with highlighting.
fn render_tag_match(tag: &str, query: &str, _is_selected: bool) -> Line<'static> {
    let indent = "     "; // Align with task title after selector + checkbox + priority
    let tag_style = Style::default().fg(theme::TAG);

    // Find and highlight the match in the tag
    let query_clean = query.to_lowercase().trim_start_matches('#').to_string();
    let tag_lower = tag.to_lowercase();

    if let Some(pos) = tag_lower.find(&query_clean) {
        let before = &tag[..pos];
        let matched = &tag[pos..pos + query_clean.len()];
        let after = &tag[pos + query_clean.len()..];

        let match_style = tag_style.add_modifier(Modifier::UNDERLINED | Modifier::BOLD);

        Line::from(vec![
            Span::styled(indent.to_string(), Style::default()),
            Span::styled("Tag: #".to_string(), Style::default().fg(theme::TEXT_MUTED)),
            Span::styled(before.to_string(), tag_style),
            Span::styled(matched.to_string(), match_style),
            Span::styled(after.to_string(), tag_style),
        ])
    } else {
        Line::from(vec![
            Span::styled(indent.to_string(), Style::default()),
            Span::styled("Tag: ".to_string(), Style::default().fg(theme::TEXT_MUTED)),
            Span::styled(format!("#{}", tag), tag_style),
        ])
    }
}

/// Renders a description snippet with the match highlighted.
fn render_description_snippet(snippet: &str, query: &str, _is_selected: bool) -> Line<'static> {
    let indent = "     "; // Align with task title after selector + checkbox + priority
    let base_style = Style::default().fg(theme::TEXT_MUTED);

    // Find and highlight the match in the snippet
    let query_lower = query.to_lowercase();
    let snippet_lower = snippet.to_lowercase();

    if let Some(pos) = snippet_lower.find(&query_lower) {
        let before = &snippet[..pos];
        let matched = &snippet[pos..pos + query.len()];
        let after = &snippet[pos + query.len()..];

        let match_style = base_style.add_modifier(Modifier::UNDERLINED | Modifier::BOLD);

        Line::from(vec![
            Span::styled(indent.to_string(), Style::default()),
            Span::styled(before.to_string(), base_style),
            Span::styled(matched.to_string(), match_style),
            Span::styled(after.to_string(), base_style),
        ])
    } else {
        Line::from(vec![
            Span::styled(indent.to_string(), Style::default()),
            Span::styled(snippet.to_string(), base_style),
        ])
    }
}

/// Truncates a string to fit within a given width, adding ellipsis if needed.
fn truncate_str(s: &str, max_width: usize) -> String {
    if s.len() <= max_width {
        s.to_string()
    } else if max_width > 3 {
        format!("{}...", &s[..max_width - 3])
    } else {
        s[..max_width].to_string()
    }
}

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

    fn sample_tasks() -> Vec<Task> {
        vec![
            {
                let mut t = Task::new("Buy groceries");
                t.description = Some("Get milk and bread from the store".to_string());
                t.tags = vec!["shopping".to_string(), "home".to_string()];
                t
            },
            {
                let mut t = Task::new("Write documentation");
                t.description = Some("Update the README file".to_string());
                t.tags = vec!["work".to_string()];
                t
            },
            {
                let mut t = Task::new("Fix bug in search");
                t.priority = Priority::High;
                t.tags = vec!["work".to_string(), "urgent".to_string()];
                t
            },
        ]
    }

    #[test]
    fn test_search_by_title() {
        let tasks = sample_tasks();
        let results = search_tasks("groceries", &tasks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].task.title, "Buy groceries");
        assert!(results[0].title_match.is_some());
    }

    #[test]
    fn test_search_by_description() {
        let tasks = sample_tasks();
        let results = search_tasks("README", &tasks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].task.title, "Write documentation");
        assert!(results[0].desc_snippet.is_some());
    }

    #[test]
    fn test_search_by_tag() {
        let tasks = sample_tasks();
        let results = search_tasks("shopping", &tasks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].task.title, "Buy groceries");
        assert!(results[0].tag_match.is_some());
        assert_eq!(results[0].tag_match.as_ref().unwrap(), "shopping");
    }

    #[test]
    fn test_search_by_tag_with_hash() {
        let tasks = sample_tasks();
        let results = search_tasks("#urgent", &tasks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].task.title, "Fix bug in search");
        assert!(results[0].tag_match.is_some());
    }

    #[test]
    fn test_search_tag_multiple_results() {
        let tasks = sample_tasks();
        let results = search_tasks("work", &tasks);
        assert_eq!(results.len(), 2); // Both "Write documentation" and "Fix bug" have #work
    }

    #[test]
    fn test_search_case_insensitive() {
        let tasks = sample_tasks();
        let results = search_tasks("BUG", &tasks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].task.title, "Fix bug in search");
    }

    #[test]
    fn test_search_no_results() {
        let tasks = sample_tasks();
        let results = search_tasks("nonexistent", &tasks);
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_empty_query() {
        let tasks = sample_tasks();
        let results = search_tasks("", &tasks);
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_multiple_results() {
        let tasks = sample_tasks();
        // "the" appears in two tasks
        let results = search_tasks("the", &tasks);
        assert_eq!(results.len(), 2);
    }
}