orgflow-tui 0.1.0

A terminal user interface for orgflow - manage notes and tasks with a smooth workflow
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
use orgflow::{Configuration, Note, OrgDocument, Task};
use std::io;
use std::io::Result as IoResult;

use ratatui::crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
use ratatui::layout::{Direction, Rect};
use ratatui::prelude::Color;
use ratatui::style::Style;
use ratatui::{
    DefaultTerminal, Frame,
    layout::{Constraint, Layout},
    prelude::Line,
    style::Stylize,
    widgets::{Block, Borders, Widget},
};
use tui_textarea::TextArea;

fn main() -> io::Result<()> {
    // Initialise terminal and move to raw mode
    let mut terminal = ratatui::init();

    // Create app and run for infinite loop
    let mut app = App::new()?;
    let app_result = app.run(&mut terminal);

    // Disable raw mode
    ratatui::restore();

    // Return application exit code
    app_result
}

#[derive(Debug)]
struct App {
    document: OrgDocument,
    exit: bool,
    note: TextArea<'static>,
    title: TextArea<'static>,
    note_focus: NoteFocus,
    scratchpad: TextArea<'static>,
    scratchpad_visible: bool,
    current_tab: AppTab,
    current_note_index: usize,
    current_task_index: usize,
}

#[derive(Debug)]
enum AppTab {
    Editor,
    Viewer,
    Tasks,
}

#[derive(Debug)]
enum NoteFocus {
    Title,
    Content,
}

impl<'a> App {
    fn new() -> IoResult<Self> {
        let note = TextArea::default();
        let title = TextArea::default();
        let scratchpad = TextArea::default();
        let basefolder = Configuration::basefolder();
        let refile_path = std::path::Path::new(&basefolder).join("refile.org");
        let document = OrgDocument::from(refile_path.to_str().unwrap())?;

        let focus = NoteFocus::Title;
        let exit = false;
        let scratchpad_visible = false;
        let current_tab = AppTab::Editor;
        let current_note_index = 0;
        let current_task_index = 0;
        let app = App {
            document,
            exit,
            note,
            title,
            note_focus: focus,
            scratchpad,
            scratchpad_visible,
            current_tab,
            current_note_index,
            current_task_index,
        };
        Ok(app)
    }
    /// Start the application
    fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        // Infinite loop until variable set
        while !self.exit {
            // Iterate over frames and draw them one by one
            terminal.draw(|frame| self.draw(frame))?;

            // wait for key events and handle them locally in the application
            match ratatui::crossterm::event::read()? {
                ratatui::crossterm::event::Event::Key(key_event) => {
                    self.handle_key_event(key_event)?
                }
                _ => {}
            }
        }
        Ok(())
    }
    /// Routine about how to draw each frame in application
    fn draw(&self, frame: &mut Frame) {
        frame.render_widget(self, frame.area());
    }

    /// Look for key presses and handle event
    fn handle_key_event(
        &mut self,
        key_event: ratatui::crossterm::event::KeyEvent,
    ) -> io::Result<()> {
        match (
            key_event.kind,
            key_event.code,
            &self.current_tab,
            &self.note_focus,
        ) {
            // Tab switching
            (KeyEventKind::Press, KeyCode::Char('1'), _, _) => {
                self.current_tab = AppTab::Editor;
            }
            (KeyEventKind::Press, KeyCode::Char('2'), _, _) => {
                self.current_tab = AppTab::Viewer;
                // Reset note index if out of bounds
                if self.current_note_index >= self.document.notes.len() {
                    self.current_note_index = 0;
                }
            }
            (KeyEventKind::Press, KeyCode::Char('3'), _, _) => {
                self.current_tab = AppTab::Tasks;
                // Reset task index if out of bounds
                if self.current_task_index >= self.document.tasks.len() {
                    self.current_task_index = 0;
                }
            }
            // Arrow navigation in viewer tab
            (KeyEventKind::Press, KeyCode::Left, AppTab::Viewer, _) => {
                if self.current_note_index > 0 {
                    self.current_note_index -= 1;
                }
            }
            (KeyEventKind::Press, KeyCode::Right, AppTab::Viewer, _) => {
                if self.current_note_index < self.document.notes.len().saturating_sub(1) {
                    self.current_note_index += 1;
                }
            }
            // Arrow navigation in tasks tab
            (KeyEventKind::Press, KeyCode::Up, AppTab::Tasks, _) => {
                if self.current_task_index > 0 {
                    self.current_task_index -= 1;
                }
            }
            (KeyEventKind::Press, KeyCode::Down, AppTab::Tasks, _) => {
                if self.current_task_index < self.document.tasks.len().saturating_sub(1) {
                    self.current_task_index += 1;
                }
            }
            (KeyEventKind::Press, KeyCode::Char('t'), _, _)
                if key_event.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                self.scratchpad_visible = !self.scratchpad_visible;
            }
            (KeyEventKind::Press, KeyCode::Esc, _, _) => self.exit = true,
            (KeyEventKind::Press, KeyCode::Enter, _, _) if self.scratchpad_visible => {
                let task = self.scratchpad.lines().first().unwrap();
                let t = Task::with_today(task);
                self.document.push_task(t);

                // Save to file immediately
                let basefolder = Configuration::basefolder();
                let refile_path = std::path::Path::new(&basefolder).join("refile.org");
                let _ = self.document.to(refile_path.to_str().unwrap());

                self.scratchpad = TextArea::default()
            }
            (_, _, _, _) if self.scratchpad_visible => {
                self.scratchpad.input(key_event);
            }
            // Editor tab specific key handling
            (KeyEventKind::Press, KeyCode::BackTab, AppTab::Editor, NoteFocus::Content) => {
                self.note_focus = NoteFocus::Title
            }
            (KeyEventKind::Press, KeyCode::BackTab, AppTab::Editor, NoteFocus::Title) => {
                self.note_focus = NoteFocus::Content
            }
            (KeyEventKind::Press, KeyCode::Enter, AppTab::Editor, NoteFocus::Title) => {
                self.note_focus = NoteFocus::Content
            }
            (KeyEventKind::Press, KeyCode::Tab, AppTab::Editor, NoteFocus::Title) => {
                self.note_focus = NoteFocus::Content
            }
            (KeyEventKind::Press, KeyCode::Char('s'), AppTab::Editor, _)
                if key_event.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                self.save_note()?;
            }
            (_, _, AppTab::Editor, NoteFocus::Content) => _ = self.note.input(key_event),
            (_, _, AppTab::Editor, NoteFocus::Title) => _ = self.title.input(key_event),
            // Ignore other inputs in viewer mode
            (_, _, AppTab::Viewer, _) => {}
            // Ignore other inputs in tasks mode
            (_, _, AppTab::Tasks, _) => {}
        }
        Ok(())
    }

    fn save_note(&mut self) -> io::Result<()> {
        let title = self.title.lines().join(" ");
        let content: Vec<String> = self.note.lines().iter().map(|s| s.to_string()).collect();

        if !title.trim().is_empty() || !content.is_empty() {
            let note = Note::with(title, content);
            self.document.push_note(note);

            // Save to file
            let basefolder = Configuration::basefolder();
            let refile_path = std::path::Path::new(&basefolder).join("refile.org");
            self.document.to(refile_path.to_str().unwrap())?;

            // Clear the text areas
            self.title = TextArea::default();
            self.note = TextArea::default();
            self.note_focus = NoteFocus::Title;
        }
        Ok(())
    }
}

/// Give App itself the ability to be a Widget (if there is only one widget )
impl<'a> Widget for &App {
    fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
    where
        Self: Sized,
    {
        match self.current_tab {
            AppTab::Editor => render_note_editor(self, area, buf),
            AppTab::Viewer => render_note_viewer(self, area, buf),
            AppTab::Tasks => render_task_viewer(self, area, buf),
        }
    }
}

fn render_note_editor(app: &App, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
    // Create a vertical layout via length
    let vertical_layout = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(3),
        Constraint::Min(0),
    ]);

    // Split input area in above layout
    let [appname_area, title_area, content_area] = vertical_layout.areas(area);

    // Render title in the vertical area
    Line::from("Orgflow - Editor (1) | Viewer (2) | Tasks (3)")
        .bold()
        .centered()
        .render(appname_area, buf);

    // Define title area and its content
    let mut title = TextArea::from(app.title.clone());
    let title_block = Block::default().borders(Borders::ALL).title("Title");
    let title_block = match app.note_focus {
        NoteFocus::Title if !app.scratchpad_visible => {
            title_block.style(Style::default().fg(Color::Yellow))
        }
        _ => title_block,
    };

    // Define content for the note inputs: content (text_area), title (instructions), border (block)
    let mut text_area = TextArea::from(app.note.clone());
    let note_instructions = Line::from(vec![
        " Quit ".into(),
        "<ESC> ".blue().bold(),
        "Switch ".into(),
        "<SHIFT>+<TAB> ".blue().bold(),
        "Save Note ".into(),
        "<CTRL>+<S> ".blue().bold(),
        "Enter Task ".into(),
        "<CTRL>+<T> ".blue().bold(),
        "Tasks ".into(),
        "<3> ".blue().bold(),
    ])
    .centered();
    let note_block = Block::default()
        .borders(Borders::ALL)
        .title("Content")
        .title_bottom(note_instructions);
    let note_block = match app.note_focus {
        NoteFocus::Content if !app.scratchpad_visible => {
            note_block.style(Style::default().fg(Color::Yellow))
        }
        _ => note_block,
    };

    let mut scratchpad = TextArea::from(app.scratchpad.clone());
    let scratchpad_block = Block::default()
        .borders(Borders::ALL)
        .title("Task")
        .style(Style::default().fg(Color::Yellow));

    let scratchpad_area = centered_rect(60, 10, area);

    if app.scratchpad_visible {
        scratchpad.set_block(scratchpad_block);
        scratchpad.render(scratchpad_area, buf);
    }

    // Render each of the contents
    text_area.set_block(note_block);
    text_area.render(content_area, buf);

    title.set_block(title_block);
    title.render(title_area, buf);
}

fn render_note_viewer(app: &App, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
    // Create a vertical layout
    let vertical_layout = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(3),
        Constraint::Min(0),
    ]);

    // Split input area in above layout
    let [appname_area, navigation_area, main_area] = vertical_layout.areas(area);

    // Render title in the vertical area
    Line::from("Orgflow - Editor (1) | Viewer (2) | Tasks (3)")
        .bold()
        .centered()
        .render(appname_area, buf);

    // Show current note info and navigation
    let note_count = app.document.notes.len();
    let current_index = app.current_note_index;

    let navigation_content = if note_count == 0 {
        vec!["No notes available".to_string()]
    } else {
        vec![format!(
            "Note {} of {} (Use ←→ arrows to navigate)",
            current_index + 1,
            note_count
        )]
    };

    let navigation_block = Block::default()
        .borders(Borders::ALL)
        .title("Navigation")
        .style(Style::default().fg(Color::Yellow));

    let mut navigation_display = TextArea::from(navigation_content);
    navigation_display.set_block(navigation_block);
    navigation_display.render(navigation_area, buf);

    if note_count == 0 {
        // Show empty state
        let empty_block = Block::default()
            .borders(Borders::ALL)
            .title("No Notes")
            .title_bottom(
                Line::from(vec![
                    " Quit ".into(),
                    "<ESC> ".blue().bold(),
                    "Editor ".into(),
                    "<1> ".blue().bold(),
                    "Viewer ".into(),
                    "<2> ".blue().bold(),
                    "Tasks ".into(),
                    "<3> ".blue().bold(),
                ])
                .centered(),
            );

        let mut empty_display = TextArea::from(vec!["No notes to display".to_string()]);
        empty_display.set_block(empty_block);
        empty_display.render(main_area, buf);
        return;
    }

    // Create horizontal layout for content and metadata
    let horizontal_layout =
        Layout::horizontal([Constraint::Percentage(70), Constraint::Percentage(30)]);

    let [content_area, metadata_area] = horizontal_layout.areas(main_area);

    // Create vertical layout for content area (title + content)
    let content_vertical = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]);

    let [title_area, note_content_area] = content_vertical.areas(content_area);

    if let Some(note) = app.document.notes.get(current_index) {
        // Display note title
        let title_block = Block::default().borders(Borders::ALL).title("Title");

        let mut title_display = TextArea::from(vec![note.title().to_string()]);
        title_display.set_block(title_block);
        title_display.render(title_area, buf);

        // Display note content
        let content_block = Block::default()
            .borders(Borders::ALL)
            .title("Content")
            .title_bottom(
                Line::from(vec![
                    " Quit ".into(),
                    "<ESC> ".blue().bold(),
                    "Editor ".into(),
                    "<1> ".blue().bold(),
                    "Viewer ".into(),
                    "<2> ".blue().bold(),
                    "Tasks ".into(),
                    "<3> ".blue().bold(),
                ])
                .centered(),
            );

        let content_lines: Vec<String> = note.content().iter().cloned().collect();
        let mut content_display = TextArea::from(content_lines);
        content_display.set_block(content_block);
        content_display.render(note_content_area, buf);

        // Display metadata
        let metadata_lines = vec![
            format!("Level: {}", note.level()),
            format!("Created: {}", note.creation_date()),
            format!("Modified: {}", note.modification_date()),
            format!("GUID: {}", note.guid()),
            format!("Tags: {}", note.tags()),
        ];

        let metadata_block = Block::default().borders(Borders::ALL).title("Metadata");

        let mut metadata_display = TextArea::from(metadata_lines);
        metadata_display.set_block(metadata_block);
        metadata_display.render(metadata_area, buf);
    }
}

fn render_task_viewer(app: &App, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
    // Create a vertical layout
    let vertical_layout = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]);

    // Split input area in above layout
    let [appname_area, main_area] = vertical_layout.areas(area);

    // Render title in the vertical area
    Line::from("Orgflow - Editor (1) | Viewer (2) | Tasks (3)")
        .bold()
        .centered()
        .render(appname_area, buf);

    let task_count = app.document.tasks.len();
    let current_index = app.current_task_index;

    if task_count == 0 {
        // Show empty state
        let empty_block = Block::default()
            .borders(Borders::ALL)
            .title("No Tasks")
            .title_bottom(
                Line::from(vec![
                    " Quit ".into(),
                    "<ESC> ".blue().bold(),
                    "Editor ".into(),
                    "<1> ".blue().bold(),
                    "Viewer ".into(),
                    "<2> ".blue().bold(),
                    "Tasks ".into(),
                    "<3> ".blue().bold(),
                ])
                .centered(),
            );

        let mut empty_display = TextArea::from(vec!["No tasks to display".to_string()]);
        empty_display.set_block(empty_block);
        empty_display.render(main_area, buf);
        return;
    }

    // Create horizontal layout for task list and metadata
    let horizontal_layout =
        Layout::horizontal([Constraint::Percentage(60), Constraint::Percentage(40)]);

    let [task_list_area, metadata_area] = horizontal_layout.areas(main_area);

    // Display task list with current selection highlighted
    let task_list_block = Block::default()
        .borders(Borders::ALL)
        .title(format!("Tasks ({} total)", task_count))
        .title_bottom(
            Line::from(vec![
                " Quit ".into(),
                "<ESC> ".blue().bold(),
                "Navigate ".into(),
                "<↑↓> ".blue().bold(),
                "Editor ".into(),
                "<1> ".blue().bold(),
                "Viewer ".into(),
                "<2> ".blue().bold(),
                "Tasks ".into(),
                "<3> ".blue().bold(),
            ])
            .centered(),
        );

    // Create content area for the task list
    let inner_area = task_list_block.inner(task_list_area);
    task_list_block.render(task_list_area, buf);

    // Render each task line with appropriate styling
    for (i, task) in app.document.tasks.iter().enumerate() {
        if i >= inner_area.height as usize {
            break; // Don't render beyond the available space
        }
        
        let y = inner_area.y + i as u16;
        let prefix = if i == current_index { "" } else { "  " };
        let status = if task.is_completed() { "[x]" } else { "[ ]" };
        let text = format!("{}{} {}", prefix, status, task.description());
        
        let style = if i == current_index {
            Style::default().add_modifier(ratatui::style::Modifier::UNDERLINED)
        } else {
            Style::default()
        };
        
        Line::from(text)
            .style(style)
            .render(
                ratatui::layout::Rect {
                    x: inner_area.x,
                    y,
                    width: inner_area.width,
                    height: 1,
                },
                buf,
            );
    }

    // Display metadata for current task
    if let Some(task) = app.document.tasks.get(current_index) {
        let mut metadata_lines = vec![format!(
            "Status: {}",
            if task.is_completed() {
                "Completed"
            } else {
                "Pending"
            }
        )];

        if let Some(priority) = task.priority_level() {
            metadata_lines.push(format!("Priority: {}", priority));
        } else {
            metadata_lines.push("Priority: None".to_string());
        }

        if let Some(creation_date) = task.creation_date() {
            metadata_lines.push(format!("Created: {}", creation_date));
        } else {
            metadata_lines.push("Created: Unknown".to_string());
        }

        if let Some(completion_date) = task.completion_date() {
            metadata_lines.push(format!("Completed: {}", completion_date));
        } else {
            metadata_lines.push("Completed: N/A".to_string());
        }

        if let Some(tags) = task.tags() {
            metadata_lines.push(format!("Tags: {}", tags));
        } else {
            metadata_lines.push("Tags: None".to_string());
        }

        metadata_lines.push("".to_string());
        metadata_lines.push("Description:".to_string());
        metadata_lines.push(task.description().to_string());

        let metadata_block = Block::default().borders(Borders::ALL).title("Task Details");

        let mut metadata_display = TextArea::from(metadata_lines);
        metadata_display.set_block(metadata_block);
        metadata_display.render(metadata_area, buf);
    }
}

fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Length(3),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}