checklist-tui 0.1.3

A TUI for keeping track of your tasks in slim terminal views
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
use std::collections::HashSet;

use anyhow::{Context, Result};
use chrono::Local;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::backend::database::{add_to_db, update_task_in_db};
use crate::backend::task::{Status, Task, Urgency};
use crate::display::tui::App;

/// Enum to flag if the input being provided by the user
/// is in the context of adding a task, updating one, or
/// doing a "quick add".
#[derive(PartialEq, Eq)]
pub enum EntryMode {
    Add,
    Update,
    QuickAdd,
}

/// Enum to flag the stage we are at during the Add process.
#[derive(PartialEq, PartialOrd, Eq, Ord, Default)]
pub enum Stage {
    Staging,
    #[default]
    Name,
    Urgency,
    Status,
    Description,
    Latest,
    Tags,
    Finished,
}

impl Stage {
    /// Rotates forward through the stages
    /// Begins at Name, ends at Finished
    pub fn next(&mut self) {
        match self {
            Stage::Name => *self = Stage::Urgency,
            Stage::Urgency => *self = Stage::Status,
            Stage::Status => *self = Stage::Description,
            Stage::Description => *self = Stage::Latest,
            Stage::Latest => *self = Stage::Tags,
            Stage::Tags => *self = Stage::Finished,
            _ => {}
        }
    }

    /// Rotates backward through the Stages
    /// Begins at Finished, ends at Name
    pub fn back(&mut self) {
        match self {
            Stage::Finished => *self = Stage::Tags,
            Stage::Tags => *self = Stage::Latest,
            Stage::Latest => *self = Stage::Description,
            Stage::Description => *self = Stage::Status,
            Stage::Status => *self = Stage::Urgency,
            Stage::Urgency => *self = Stage::Name,
            _ => {}
        }
    }
}

/// Struct to capture the inputs provided by a user
#[derive(Default)]
pub struct Inputs {
    pub name: String,
    pub urgency: Urgency,
    pub status: Status,
    pub description: String,
    pub latest: String,
    pub tags: HashSet<String>,
    pub tags_input: String,
}

impl Inputs {
    /// Creates an `Inputs` struct based on a `Task` provided
    pub fn from_task(task: &Task) -> Self {
        Inputs {
            name: task.name.clone(),
            urgency: task.urgency,
            status: task.status,
            description: task.description.clone().unwrap_or("".to_string()),
            latest: task.latest.clone().unwrap_or("".to_string()),
            tags: task.tags.clone().unwrap_or_default(),
            tags_input: "".to_string(),
        }
    }
}

impl App {
    fn get_stage_off_entry_mode(&self) -> &Stage {
        match self.entry_mode {
            EntryMode::Add => &self.add_stage,
            EntryMode::QuickAdd => &self.add_stage,
            EntryMode::Update => &self.update_stage,
        }
    }

    fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
        let stage = self.get_stage_off_entry_mode();

        match stage {
            Stage::Name => new_cursor_pos.clamp(0, self.inputs.name.chars().count()),
            Stage::Description => new_cursor_pos.clamp(0, self.inputs.description.chars().count()),
            Stage::Latest => new_cursor_pos.clamp(0, self.inputs.latest.chars().count()),
            Stage::Tags => new_cursor_pos.clamp(0, self.inputs.tags_input.chars().count()),
            _ => 0,
        }
    }

    fn byte_index(&self) -> usize {
        let stage = self.get_stage_off_entry_mode();

        match stage {
            Stage::Name => self
                .inputs
                .name
                .char_indices()
                .map(|(i, _)| i)
                .nth(self.character_index)
                .unwrap_or(self.inputs.name.len()),
            Stage::Description => self
                .inputs
                .description
                .char_indices()
                .map(|(i, _)| i)
                .nth(self.character_index)
                .unwrap_or(self.inputs.description.len()),
            Stage::Latest => self
                .inputs
                .latest
                .char_indices()
                .map(|(i, _)| i)
                .nth(self.character_index)
                .unwrap_or(self.inputs.latest.len()),
            Stage::Tags => self
                .inputs
                .tags_input
                .char_indices()
                .map(|(i, _)| i)
                .nth(self.character_index)
                .unwrap_or(self.inputs.tags_input.len()),
            _ => 0,
        }
    }

    fn move_cursor_left(&mut self) {
        let cursor_moved_left = self.character_index.saturating_sub(1);
        self.character_index = self.clamp_cursor(cursor_moved_left);
    }

    fn move_cursor_right(&mut self) {
        let cursor_moved_right = self.character_index.saturating_add(1);
        self.character_index = self.clamp_cursor(cursor_moved_right);
    }

    fn enter_char(&mut self, new_char: char) {
        let index = self.byte_index();

        let stage = self.get_stage_off_entry_mode();

        match stage {
            Stage::Name => self.inputs.name.insert(index, new_char),
            Stage::Description => self.inputs.description.insert(index, new_char),
            Stage::Latest => self.inputs.latest.insert(index, new_char),
            Stage::Tags => self.inputs.tags_input.insert(index, new_char),
            _ => {}
        }
        self.move_cursor_right();
    }

    fn delete_char(&mut self) {
        let is_not_cursor_leftmost = self.character_index != 0;
        if is_not_cursor_leftmost {
            let current_index = self.character_index;
            let from_left_to_current_index = current_index - 1;

            let stage = self.get_stage_off_entry_mode();

            match stage {
                Stage::Name => {
                    let before_char_to_delete =
                        self.inputs.name.chars().take(from_left_to_current_index);
                    let after_char_to_delete = self.inputs.name.chars().skip(current_index);
                    self.inputs.name = before_char_to_delete.chain(after_char_to_delete).collect();
                }
                Stage::Description => {
                    let before_char_to_delete = self
                        .inputs
                        .description
                        .chars()
                        .take(from_left_to_current_index);
                    let after_char_to_delete = self.inputs.description.chars().skip(current_index);
                    self.inputs.description =
                        before_char_to_delete.chain(after_char_to_delete).collect();
                }
                Stage::Latest => {
                    let before_char_to_delete =
                        self.inputs.latest.chars().take(from_left_to_current_index);
                    let after_char_to_delete = self.inputs.latest.chars().skip(current_index);
                    self.inputs.latest =
                        before_char_to_delete.chain(after_char_to_delete).collect();
                }
                Stage::Tags => {
                    let before_char_to_delete = self
                        .inputs
                        .tags_input
                        .chars()
                        .take(from_left_to_current_index);
                    let after_char_to_delete = self.inputs.tags_input.chars().skip(current_index);
                    self.inputs.tags_input =
                        before_char_to_delete.chain(after_char_to_delete).collect();
                }
                _ => {}
            }
            self.move_cursor_left();
        }
    }

    /// Handles the `KeyEvent` when user is choosing what to update
    pub fn handle_update_staging(&mut self, key: KeyEvent) {
        let current_index = self.tasklist.state.selected().unwrap();
        match key.code {
            KeyCode::Esc => self.update_popup = !self.update_popup,
            KeyCode::Char(ch) => {
                if ch == '1' {
                    self.update_stage = Stage::Name;
                    self.character_index = self.tasklist.tasks[current_index].name.len();
                }
                if ch == '2' {
                    self.update_stage = Stage::Status;
                }
                if ch == '3' {
                    self.update_stage = Stage::Urgency;
                }
                if ch == '4' {
                    self.update_stage = Stage::Description;
                    self.character_index = self.tasklist.tasks[current_index]
                        .description
                        .clone()
                        .unwrap_or("".to_string())
                        .len();
                }
                if ch == '5' {
                    self.update_stage = Stage::Latest;
                    self.character_index = self.tasklist.tasks[current_index]
                        .latest
                        .clone()
                        .unwrap_or("".to_string())
                        .len();
                }
                if ch == '6' {
                    self.character_index = 0;
                    self.update_stage = Stage::Tags;
                }
            }
            _ => {}
        }
    }

    /// Handles the `KeyEvent` when user is providing text input
    pub fn handle_keys_for_text_inputs(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                if self.entry_mode == EntryMode::Add || self.entry_mode == EntryMode::QuickAdd {
                    self.add_popup = !self.add_popup;
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_popup = !self.update_popup;
                }
            }
            KeyCode::Enter => {
                if self.entry_mode == EntryMode::Add {
                    self.add_stage.next();
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_stage = Stage::Finished;
                }
                if self.entry_mode == EntryMode::QuickAdd {
                    self.add_stage = Stage::Finished;
                }
                self.character_index = 0;
            }
            KeyCode::Left => {
                if key.modifiers == KeyModifiers::CONTROL {
                    if self.entry_mode == EntryMode::Add {
                        self.add_stage.back();
                    }
                    if self.entry_mode == EntryMode::Update {
                        self.update_stage = Stage::Staging;
                    }
                } else {
                    self.move_cursor_left()
                }
            }
            KeyCode::Backspace => self.delete_char(),
            KeyCode::Right => self.move_cursor_right(),
            KeyCode::Char(ch) => self.enter_char(ch),
            _ => {}
        }
    }

    /// Handles the `KeyEvent` when the user is at the Tags `Stage`
    pub fn handle_keys_for_tags(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                if self.entry_mode == EntryMode::Add {
                    self.add_popup = !self.add_popup;
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_popup = !self.update_popup;
                }
            }
            KeyCode::Enter => {
                if self.inputs.tags_input == *"".to_string() {
                    if self.entry_mode == EntryMode::Add {
                        self.add_stage.next();
                    }
                    if self.entry_mode == EntryMode::Update {
                        self.update_stage = Stage::Finished;
                    }
                } else {
                    self.inputs.tags.insert(self.inputs.tags_input.to_string());
                    self.inputs.tags_input = "".to_string();
                }
                self.character_index = 0;
            }
            _ => {}
        }
        if self.highlight_tags {
            match key.code {
                KeyCode::Left => {
                    if key.modifiers == KeyModifiers::CONTROL {
                        if self.entry_mode == EntryMode::Add {
                            self.add_stage.back();
                        }
                        if self.entry_mode == EntryMode::Update {
                            self.update_stage = Stage::Staging;
                        }
                    } else {
                        self.move_tags_highlight_left()
                    }
                }
                KeyCode::Right => {
                    // Move highlight to the right
                    self.move_tags_highlight_right()
                }
                KeyCode::Up => {
                    // Unhighlight tags and place cursor back to character_index
                    self.highlight_tags = !self.highlight_tags
                }
                KeyCode::Char('d') => {
                    // Remove the highlighted tag
                    self.remove_tag();
                }
                _ => {}
            }
        } else {
            match key.code {
                KeyCode::Left => {
                    if key.modifiers == KeyModifiers::CONTROL {
                        if self.entry_mode == EntryMode::Add {
                            self.add_stage.back();
                        }
                        if self.entry_mode == EntryMode::Update {
                            self.update_stage = Stage::Staging;
                        }
                    } else {
                        self.move_cursor_left()
                    }
                }
                KeyCode::Right => {
                    self.move_cursor_right();
                }
                KeyCode::Down => {
                    if !self.inputs.tags.is_empty() {
                        self.highlight_tags = !self.highlight_tags;
                    }
                }
                KeyCode::Char(ch) => self.enter_char(ch),
                KeyCode::Backspace => self.delete_char(),
                _ => {}
            }
        }
    }

    fn move_tags_highlight_left(&mut self) {
        if self.tags_highlight_value > 0 {
            self.tags_highlight_value -= 1;
        }
    }

    fn move_tags_highlight_right(&mut self) {
        if self.tags_highlight_value < self.inputs.tags.len() - 1 {
            self.tags_highlight_value += 1;
        }
    }

    fn remove_tag(&mut self) {
        // Match what our displayed vectors are
        let mut task_tags_vec = Vec::from_iter(self.inputs.tags.clone());
        task_tags_vec.sort();

        // Get the value that is highlighted
        let tags_value = &task_tags_vec[self.tags_highlight_value];
        // Remove said value from our hashset
        self.inputs.tags.remove(tags_value);
        self.move_tags_highlight_left();

        if self.inputs.tags.is_empty() {
            self.highlight_tags = false
        }
    }

    /// Handles the `KeyEvent` when in the Urgency `Stage`
    pub fn handle_keys_for_urgency(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                if self.entry_mode == EntryMode::Add {
                    self.add_popup = !self.add_popup;
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_popup = !self.update_popup;
                }
            }
            KeyCode::Left => {
                if self.entry_mode == EntryMode::Add {
                    self.add_stage.back();
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_stage = Stage::Staging;
                }
            }
            KeyCode::Char(ch) => {
                if ch == '1' {
                    self.inputs.urgency = Urgency::Low;
                } else if ch == '2' {
                    self.inputs.urgency = Urgency::Medium;
                } else if ch == '3' {
                    self.inputs.urgency = Urgency::High;
                } else if ch == '4' {
                    self.inputs.urgency = Urgency::Critical;
                } else {
                    return;
                }

                if self.entry_mode == EntryMode::Add {
                    self.add_stage.next();
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_stage = Stage::Finished;
                }
            }
            _ => {}
        }
    }

    /// Handles the `KeyEvent` when in the Status `Stage`
    pub fn handle_keys_for_status(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                if self.entry_mode == EntryMode::Add {
                    self.add_popup = !self.add_popup;
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_popup = !self.update_popup;
                }
            }
            KeyCode::Left => {
                if self.entry_mode == EntryMode::Add {
                    self.add_stage.back();
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_stage = Stage::Staging;
                }
            }
            KeyCode::Char(ch) => {
                if ch == '1' {
                    self.inputs.status = Status::Open;
                } else if ch == '2' {
                    self.inputs.status = Status::Working;
                } else if ch == '3' {
                    self.inputs.status = Status::Paused;
                } else if ch == '4' {
                    self.inputs.status = Status::Completed;
                } else {
                    return;
                }

                if self.entry_mode == EntryMode::Add {
                    self.add_stage.next();
                }
                if self.entry_mode == EntryMode::Update {
                    self.update_stage = Stage::Finished;
                }
            }
            _ => {}
        }
    }

    /// Adds a new `Task` into the SQLite database based on what is in
    /// the current `Inputs` struct in `App`.
    pub fn add_new_task_in(&mut self) -> Result<()> {
        let description = if self.inputs.description.is_empty() {
            None
        } else {
            Some(self.inputs.description.clone())
        };
        let latest = if self.inputs.latest.is_empty() {
            None
        } else {
            Some(self.inputs.latest.clone())
        };
        let tags = if self.inputs.tags.is_empty() {
            None
        } else {
            Some(self.inputs.tags.clone())
        };

        let new_task = Task::new(
            self.inputs.name.clone(),
            description,
            latest,
            Some(self.inputs.urgency),
            Some(self.inputs.status),
            tags,
        );

        add_to_db(&self.conn, &new_task).context("Failed to add the new task in")?;
        self.update_tasklist()
            .context("Failed to update the tasklist after adding the new task in")?;

        for (i, task) in self.tasklist.tasks.iter().enumerate() {
            if new_task.get_id() == task.get_id() {
                self.tasklist.state.select(Some(i))
            }
        }

        Ok(())
    }

    /// Updates a `Task` in the SQLite database that has been selected
    /// in the TUI.
    pub fn update_selected_task(&mut self) -> Result<()> {
        let current_selection = self.tasklist.state.selected().unwrap();
        let current_uuid = self.tasklist.tasks[current_selection].get_id();

        let description = if self.inputs.description.is_empty() {
            None
        } else {
            Some(self.inputs.description.clone())
        };
        let latest = if self.inputs.latest.is_empty() {
            None
        } else {
            Some(self.inputs.latest.clone())
        };
        let tags = if self.inputs.tags.is_empty() {
            None
        } else {
            Some(self.inputs.tags.clone())
        };

        self.tasklist.tasks[current_selection].name = self.inputs.name.clone();
        self.tasklist.tasks[current_selection].urgency = self.inputs.urgency;
        self.tasklist.tasks[current_selection].status = self.inputs.status;
        if self.tasklist.tasks[current_selection].status == Status::Completed {
            self.tasklist.tasks[current_selection].completed_on = Some(Local::now());
        } else {
            self.tasklist.tasks[current_selection].completed_on = None;
        }
        self.tasklist.tasks[current_selection].description = description;
        self.tasklist.tasks[current_selection].latest = latest;
        self.tasklist.tasks[current_selection].tags = tags;

        update_task_in_db(&self.conn, &self.tasklist.tasks[current_selection])
            .context("Failed to update task in the database")?;
        self.update_tasklist()
            .context("Failed to update the tasklist after adding the new task in")?;

        for (i, task) in self.tasklist.tasks.iter().enumerate() {
            if current_uuid == task.get_id() {
                self.tasklist.state.select(Some(i))
            }
        }

        Ok(())
    }
}