void-focus 0.3.0-alpha.5

A feature-rich terminal focus timer with task tracking
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
use super::*;

fn popup_size(popup: &crate::app::Popup) -> (u16, u16) {
    match popup {
        crate::app::Popup::AddSubtask(_) => (48, 24),
        crate::app::Popup::ConfirmDelete(_)
        | crate::app::Popup::BulkConfirm(_)
        | crate::app::Popup::EmptyQueueChoice => (50, 28),
        _ => (68, 78),
    }
}

fn popup_min_size(popup: &crate::app::Popup) -> (u16, u16) {
    match popup {
        crate::app::Popup::AddSubtask(_) => (36, 10),
        _ => (32, 10),
    }
}

fn popup_rect(popup: &crate::app::Popup, area: Rect) -> Rect {
    let (pw, ph) = popup_size(popup);
    let (min_w, min_h) = popup_min_size(popup);
    let mut r = centered_rect(pw, ph, area);
    r.width = r.width.max(min_w).min(area.width);
    r.height = r.height.max(min_h).min(area.height);
    r
}

fn rect_ok(area: Rect) -> bool {
    area.width > 0 && area.height > 0
}

pub(crate) fn draw_popup(f: &mut Frame, app: &mut App, popup: &crate::app::Popup) {
    let icons = app.icons;
    let area = f.area();
    let popup_area = popup_rect(popup, area);
    f.render_widget(Clear, popup_area);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(app.theme.accent))
        .style(Style::default().bg(app.theme.bg))
        .title(Span::styled(
            match popup {
                crate::app::Popup::AddTask => format!(" {} Add Task ", icons.plus),
                crate::app::Popup::EditTask(_) => format!(" {} Edit Task ", icons.edit),
                crate::app::Popup::ConfirmDelete(_) => format!(" {} Confirm Delete ", icons.delete),
                crate::app::Popup::EmptyQueueChoice => format!(" {} All Tasks Done ", icons.check),
                crate::app::Popup::AddSubtask(_) => format!(" {} Add Subtask ", icons.plus),
                crate::app::Popup::BulkConfirm(_) => format!(" {} Bulk Action ", icons.tasks),
            },
            Style::default()
                .fg(app.theme.accent)
                .add_modifier(Modifier::BOLD),
        ));
    let body = block.inner(popup_area);
    f.render_widget(block, popup_area);

    match popup {
        crate::app::Popup::AddTask | crate::app::Popup::EditTask(_) => {
            let theme = &app.theme;
            let chunks = popup_body_layout(body, PopupLayout::Form);
            if chunks.is_empty() {
                return;
            }
            let form_area = chunks[0];
            let (left_area, right_area) = if matches!(app.input_field, InputField::DueDate) {
                let cols = Layout::default()
                    .direction(Direction::Horizontal)
                    .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
                    .split(form_area);
                (cols[0], Some(cols[1]))
            } else {
                (form_area, None)
            };

            let cursor = |active: bool, text: &str| -> String {
                if active {
                    if text.is_empty() {
                        "|".to_string()
                    } else {
                        format!("{}|", text)
                    }
                } else if text.is_empty() {
                    "—".to_string()
                } else {
                    text.to_string()
                }
            };
            let due_display = if matches!(app.input_field, InputField::DueDate) {
                cursor(true, &app.input_due_date)
            } else if app.input_due_date.is_empty() {
                "—".to_string()
            } else {
                app.input_due_date.clone()
            };
            let tags_display = cursor(matches!(app.input_field, InputField::Tags), &app.input_tags);
            let value_max = left_area.width.saturating_sub(22) as usize;
            let p = Paragraph::new(vec![
                popup_field_line(
                    theme,
                    "Title",
                    cursor(
                        matches!(app.input_field, InputField::Title),
                        &truncate_field(&app.input_buffer, value_max),
                    ),
                    matches!(app.input_field, InputField::Title),
                    value_max,
                ),
                popup_field_line(
                    theme,
                    "Estimate (min)",
                    if matches!(app.input_field, InputField::Estimate) {
                        format!("{}|", app.input_number)
                    } else {
                        app.input_number.to_string()
                    },
                    matches!(app.input_field, InputField::Estimate),
                    value_max,
                ),
                popup_field_line(
                    theme,
                    "Priority",
                    app.input_priority.label().to_string(),
                    matches!(app.input_field, InputField::Priority),
                    value_max,
                ),
                popup_field_line(
                    theme,
                    "Due (YYYY-MM-DD)",
                    truncate_field(&due_display, value_max),
                    matches!(app.input_field, InputField::DueDate),
                    value_max,
                ),
                popup_field_line(
                    theme,
                    "Tags (comma-sep)",
                    truncate_field(&tags_display, value_max),
                    matches!(app.input_field, InputField::Tags),
                    value_max,
                ),
            ]);
            f.render_widget(p, left_area);

            if let Some(r) = right_area {
                let d = app.calendar_date;
                if let Ok(time_date) = time::Date::from_calendar_date(
                    d.year(),
                    time::Month::try_from(d.month() as u8).unwrap_or(time::Month::January),
                    d.day() as u8,
                ) {
                    let mut store = ratatui::widgets::calendar::CalendarEventStore::default();
                    store.add(
                        time_date,
                        Style::default()
                            .bg(theme.accent)
                            .fg(theme.on_accent)
                            .add_modifier(Modifier::BOLD),
                    );

                    let monthly = ratatui::widgets::calendar::Monthly::new(time_date, store)
                        .show_month_header(
                            Style::default()
                                .fg(theme.accent)
                                .add_modifier(Modifier::BOLD),
                        )
                        .show_weekdays_header(Style::default().fg(theme.dim));
                    f.render_widget(monthly, r);
                }
            }
            let hint = if matches!(app.input_field, InputField::DueDate) {
                "←→ day Ā· ↑↓ week Ā· Tab field Ā· Enter save Ā· Esc cancel"
            } else {
                "Tab field Ā· Enter save Ā· Esc cancel"
            };
            if chunks.len() > 1 {
                draw_popup_hint(f, chunks[1], theme, hint);
            }
        }
        crate::app::Popup::ConfirmDelete(id) => {
            let theme = &app.theme;
            let chunks = popup_body_layout(body, PopupLayout::Message);
            if chunks.is_empty() {
                return;
            }
            let title = app
                .data
                .tasks
                .iter()
                .find(|t| t.id == *id)
                .map(|t| t.title.as_str())
                .unwrap_or("Unknown task");
            let p = Paragraph::new(vec![
                Line::from(Span::styled(
                    format!("Delete \"{}\"?", title),
                    Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                Line::from(Span::styled(
                    "Press y or Enter to confirm, n or Esc to cancel.",
                    Style::default().fg(theme.dim),
                )),
                Line::from(Span::styled(
                    "This cannot be undone.",
                    Style::default().fg(theme.error),
                )),
            ]);
            f.render_widget(p, chunks[0]);
        }
        crate::app::Popup::EmptyQueueChoice => {
            let theme = &app.theme;
            let chunks = popup_body_layout(body, PopupLayout::Message);
            if chunks.is_empty() {
                return;
            }
            let p = Paragraph::new(vec![
                Line::from(Span::styled(
                    "You've completed every task in your queue.",
                    Style::default().fg(theme.text),
                )),
                Line::from(""),
                Line::from(Span::styled(
                    "[Enter]  Continue free focus (log general sessions)",
                    Style::default().fg(theme.success),
                )),
                Line::from(Span::styled(
                    "[p]      Pause the timer",
                    Style::default().fg(theme.warning),
                )),
                Line::from(Span::styled(
                    "[a]      Add another task",
                    Style::default().fg(theme.accent),
                )),
                Line::from(Span::styled(
                    "[Esc]    Dismiss",
                    Style::default().fg(theme.dim),
                )),
            ]);
            f.render_widget(p, chunks[0]);
        }
        crate::app::Popup::AddSubtask(id) => {
            draw_add_subtask_popup(f, app, body, *id);
        }
        crate::app::Popup::BulkConfirm(action) => {
            let theme = &app.theme;
            let chunks = popup_body_layout(body, PopupLayout::Message);
            if chunks.is_empty() {
                return;
            }
            let (title, detail, accent) = match action {
                crate::app::BulkAction::MarkDone => (
                    "Mark selected tasks as done?",
                    format!("{} task(s) selected.", app.bulk_selected.len()),
                    theme.success,
                ),
                crate::app::BulkAction::Delete => (
                    "Delete selected tasks?",
                    format!(
                        "{} task(s) will be removed permanently.",
                        app.bulk_selected.len()
                    ),
                    theme.error,
                ),
            };
            let p = Paragraph::new(vec![
                Line::from(Span::styled(
                    title,
                    Style::default().fg(accent).add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                Line::from(Span::styled(detail, Style::default().fg(theme.text))),
                Line::from(""),
                Line::from(Span::styled(
                    "[y] confirm  [n/Esc] cancel",
                    Style::default().fg(theme.dim),
                )),
            ]);
            f.render_widget(p, chunks[0]);
        }
    }
}

enum PopupLayout {
    Form,
    Subtask,
    Message,
}

fn popup_body_layout(body: Rect, kind: PopupLayout) -> Vec<Rect> {
    if !rect_ok(body) {
        return vec![];
    }
    let margin = u16::from(body.height >= 8 && body.width >= 8);
    let constraints = match kind {
        PopupLayout::Form => vec![Constraint::Min(4), Constraint::Length(1)],
        PopupLayout::Subtask => vec![
            Constraint::Length(1),
            Constraint::Length(3),
            Constraint::Length(1),
        ],
        PopupLayout::Message => vec![Constraint::Min(1)],
    };
    Layout::default()
        .direction(Direction::Vertical)
        .margin(margin)
        .constraints(constraints)
        .split(body)
        .to_vec()
}

fn task_title(app: &App, id: u64) -> String {
    app.data
        .tasks
        .iter()
        .find(|t| t.id == id)
        .map(|t| t.title.clone())
        .unwrap_or_else(|| "Unknown task".into())
}

fn draw_add_subtask_popup(f: &mut Frame, app: &App, body: Rect, task_id: u64) {
    let theme = &app.theme;
    let chunks = popup_body_layout(body, PopupLayout::Subtask);
    if chunks.len() < 3 {
        return;
    }
    let parent = task_title(app, task_id);
    let existing = app
        .data
        .tasks
        .iter()
        .find(|t| t.id == task_id)
        .map(|t| t.subtasks.len())
        .unwrap_or(0);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("Task  ", Style::default().fg(theme.dim)),
            Span::styled(
                super::widgets::truncate(&parent, chunks[0].width.saturating_sub(8) as usize),
                Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!(
                    "  ({existing} subtask{})",
                    if existing == 1 { "" } else { "s" }
                ),
                Style::default().fg(theme.dim),
            ),
        ])),
        chunks[0],
    );
    draw_singleline_editor(f, chunks[1], theme, &app.input_buffer);
    draw_action_footer(
        f,
        chunks[2],
        theme,
        &[
            ("Enter", "add", theme.success),
            ("q", "done", theme.warning),
        ],
    );
}

fn draw_action_footer(
    f: &mut Frame,
    area: Rect,
    theme: &crate::app::Theme,
    actions: &[(&str, &str, ratatui::style::Color)],
) {
    if area.height == 0 || area.width == 0 {
        return;
    }
    let sep = Block::default()
        .borders(Borders::TOP)
        .border_style(Style::default().fg(theme.panel_border))
        .style(Style::default().bg(theme.bg));
    let inner = sep.inner(area);
    f.render_widget(sep, area);

    let mut spans: Vec<Span> = Vec::new();
    for (i, (key, label, color)) in actions.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw("  "));
        }
        spans.push(Span::styled(
            format!(" {key} "),
            Style::default().fg(*color).add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(
            format!(" {label}"),
            Style::default().fg(theme.dim),
        ));
    }
    f.render_widget(Paragraph::new(Line::from(spans)), inner);
}

fn draw_singleline_editor(f: &mut Frame, area: Rect, theme: &crate::app::Theme, text: &str) {
    if !rect_ok(area) {
        return;
    }
    let input_block = Block::default()
        .title(Span::styled(" Title ", Style::default().fg(theme.dim)))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent))
        .style(Style::default().bg(theme.panel).fg(theme.text));
    let inner = input_block.inner(area);
    f.render_widget(input_block, area);
    if !rect_ok(inner) {
        return;
    }
    let max_w = inner.width.saturating_sub(2) as usize;
    let content = if text.is_empty() {
        Line::from(vec![
            Span::styled("Subtask title…", Style::default().fg(theme.dim)),
            Span::styled("|", Style::default().fg(theme.accent)),
        ])
    } else {
        Line::from(Span::styled(
            format_input_line(text, max_w),
            Style::default().fg(theme.text),
        ))
    };
    f.render_widget(Paragraph::new(content).alignment(Alignment::Left), inner);
}

fn draw_popup_hint(f: &mut Frame, area: Rect, theme: &crate::app::Theme, hint: &str) {
    if area.height == 0 {
        return;
    }
    let max = area.width.saturating_sub(2) as usize;
    f.render_widget(
        Paragraph::new(Span::styled(
            super::widgets::truncate(hint, max),
            Style::default().fg(theme.dim),
        )),
        area,
    );
}

fn format_input_line(text: &str, max_w: usize) -> String {
    if text.is_empty() {
        return "|".to_string();
    }
    let max_text = max_w.saturating_sub(1);
    format!("{}|", super::widgets::truncate(text, max_text))
}

fn truncate_field(s: &str, max: usize) -> String {
    super::widgets::truncate(s, max)
}

pub(crate) fn popup_field_line(
    theme: &crate::app::Theme,
    label: &str,
    value: String,
    active: bool,
    value_max: usize,
) -> Line<'static> {
    let label_style = if active {
        Style::default()
            .fg(theme.accent)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(theme.dim)
    };
    let value_style = if active {
        Style::default().fg(theme.text).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(theme.text)
    };
    Line::from(vec![
        Span::styled(format!("{:<20} ", label), label_style),
        Span::styled(truncate_field(&value, value_max), value_style),
    ])
}

pub(crate) fn draw_input(f: &mut Frame, app: &App, area: Rect) {
    let theme = &app.theme;
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([Constraint::Length(3), Constraint::Min(1)])
        .split(area);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent))
        .title(Span::styled(" Input ", Style::default().fg(theme.accent)));
    let p = Paragraph::new(format!("{}|", app.input_buffer))
        .style(Style::default().fg(theme.text))
        .block(block);
    f.render_widget(p, chunks[0]);
}