trackWork 0.15.0

A terminal-based time tracking application for managing work sessions
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, Paragraph},
    Frame,
};

use crate::app::{App, InputMode};
use crate::dashboard::utils::{breathe_color, breathe_t, dim_toward_bg, themed_rgb};
use std::collections::HashMap;
use crate::ui::string_to_color;

/// Render `text` as a shimmer wave: a bright band sweeps left→right, then the
/// whole string rests for a beat before the next sweep. Used to make a running
/// entry's duration feel "alive".
///
/// When `green` (the terminal's real ANSI green, from OSC 4) is available, each
/// char's color is a smooth lerp from that green toward white by its distance to
/// the band center — a true gradient that matches the user's theme. Otherwise we
/// fall back to named `Green`/`LightGreen` shades.
fn shimmer_spans(text: &str, green: Option<(u8, u8, u8)>) -> Vec<Span<'static>> {
    const SWEEP_MS: f64 = 1400.0; // time for the band to cross the text
    const PAUSE_MS: f64 = 1100.0; // all-normal rest between sweeps
    const WIDTH: f64 = 4.0; // half-width of the bright band, in chars

    let chars: Vec<char> = text.chars().collect();
    let n = chars.len() as f64;
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as f64;

    let t = millis % (SWEEP_MS + PAUSE_MS);
    // Band head travels from -WIDTH to n+WIDTH during the sweep, then parks
    // far off the end (everything normal) for the pause.
    let head = if t < SWEEP_MS {
        -WIDTH + (t / SWEEP_MS) * (n + 2.0 * WIDTH)
    } else {
        f64::INFINITY
    };

    chars
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let d = (head - i as f64).abs();
            // 0.0 at/outside the band edge, 1.0 at the center.
            let intensity = ((WIDTH - d) / WIDTH).clamp(0.0, 1.0);
            let style = match green {
                Some(g) => {
                    let (r, gr, b) = lighten(g, intensity * 0.7);
                    let s = Style::default().fg(Color::Rgb(r, gr, b));
                    if intensity > 0.75 {
                        s.add_modifier(Modifier::BOLD)
                    } else {
                        s
                    }
                }
                None => {
                    if intensity > 0.7 {
                        Style::default().fg(Color::LightGreen).add_modifier(Modifier::BOLD)
                    } else if intensity > 0.0 {
                        Style::default().fg(Color::LightGreen)
                    } else {
                        Style::default().fg(Color::Green)
                    }
                }
            };
            Span::styled(c.to_string(), style)
        })
        .collect()
}

/// Lerp an RGB color toward white by `t` (0.0 = unchanged, 1.0 = white).
fn lighten((r, g, b): (u8, u8, u8), t: f64) -> (u8, u8, u8) {
    let f = |c: u8| (c as f64 + (255.0 - c as f64) * t).round().clamp(0.0, 255.0) as u8;
    (f(r), f(g), f(b))
}

/// Build the `[   duration   ]` spans. Precedence: a highlighted entry's time
/// breathes (slow pulse in its time color); else a running entry's time
/// shimmers; else it's static. When `eye_candy` is false the animations are
/// suppressed and the time renders flat.
fn duration_spans(
    duration: &str,
    running: bool,
    selected: bool,
    time_style: Style,
    palette: &HashMap<u8, (u8, u8, u8)>,
    eye_candy: bool,
) -> Vec<Span<'static>> {
    let text = format!("{:>12}", duration);
    let mut out = vec![Span::styled("[".to_string(), time_style)];
    if selected {
        let base = themed_rgb(time_style.fg.unwrap_or(Color::White), palette);
        let (r, g, b) = if eye_candy {
            breathe_color(base, breathe_t())
        } else {
            base
        };
        out.push(Span::styled(
            text,
            Style::default().fg(Color::Rgb(r, g, b)).add_modifier(Modifier::BOLD),
        ));
    } else if running && eye_candy {
        out.extend(shimmer_spans(&text, palette.get(&2).copied()));
    } else {
        out.push(Span::styled(text, time_style));
    }
    out.push(Span::styled("]".to_string(), time_style));
    out
}

pub fn draw_entries(f: &mut Frame, app: &App, area: Rect) {
    // Pin the per-day "At Work" row above the entry list when it exists.
    let list_area = if app.has_day_row() {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(0)])
            .split(area);
        draw_at_work_row(f, app, chunks[0]);
        chunks[1]
    } else {
        area
    };

    draw_entry_list(f, app, list_area);
}

/// `Xh YYm ZZs` / `YYm ZZs` / `ZZs` — collapse leading zero units so short
/// durations stay readable. Used by the "At Work" row's work-hours math.
fn format_duration_seconds(seconds: i64) -> String {
    let hours = seconds / 3600;
    let minutes = (seconds % 3600) / 60;
    let secs = seconds % 60;
    if hours > 0 {
        format!("{}h {:02}m {:02}s", hours, minutes, secs)
    } else if minutes > 0 {
        format!("{}m {:02}s", minutes, secs)
    } else {
        format!("{}s", secs)
    }
}

fn draw_at_work_row(f: &mut Frame, app: &App, area: Rect) {
    let Some((start, end, manual)) = app.at_work_span() else {
        return;
    };

    // Day span = end - start (presence). Work hours = span minus off-work
    // entries — the actual productive time the top bar used to show. Math is
    // surfaced inline as "(span - off_work off work)" so the subtraction is
    // visible, not just the result.
    let span_seconds = end.signed_duration_since(start).num_seconds().max(0);
    let now = chrono::Local::now().naive_local();
    let off_work_seconds: i64 = app
        .entries
        .iter()
        .filter(|e| e.off_work)
        .map(|e| {
            e.end_time
                .unwrap_or(now)
                .signed_duration_since(e.start_time)
                .num_seconds()
                .max(0)
        })
        .sum();
    let work_seconds = (span_seconds - off_work_seconds).max(0);

    let is_running = app.entries.iter().any(|e| e.is_running());
    let selected = app.at_work_selected;
    let label_color = if selected { Color::White } else { Color::Cyan };
    // Theme-aware dim: blend white toward bg so the math reads on both light
    // and dark terminals. Plain `DarkGray` was invisible on dark themes when
    // the row wasn't highlighted.
    let muted = if selected {
        Color::Gray
    } else {
        dim_toward_bg(Color::White, &app.term_palette, 0.55)
    };

    let mut spans = vec![
        Span::styled("", Style::default().fg(label_color).add_modifier(Modifier::BOLD)),
        Span::styled(
            format!("{} - {}", start.format("%H:%M"), end.format("%H:%M")),
            Style::default().fg(if selected { Color::White } else { Color::Gray }),
        ),
        Span::raw("   "),
        Span::styled("Work hours: ", Style::default().fg(if selected { Color::White } else { Color::Gray })),
        Span::styled(
            format_duration_seconds(work_seconds),
            Style::default().fg(Color::Green).add_modifier(Modifier::BOLD),
        ),
    ];
    if is_running {
        spans.push(Span::styled(
            " < running",
            Style::default().fg(Color::Green).add_modifier(Modifier::BOLD),
        ));
    }
    if off_work_seconds > 0 {
        spans.push(Span::styled(
            format!(
                "   ({} - {} off work)",
                format_duration_seconds(span_seconds),
                format_duration_seconds(off_work_seconds),
            ),
            Style::default().fg(muted),
        ));
    } else {
        spans.push(Span::styled(
            format!("   ({})", format_duration_seconds(span_seconds)),
            Style::default().fg(muted),
        ));
    }
    if manual {
        spans.push(Span::styled(
            "  ( manual )",
            Style::default().fg(muted),
        ));
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .title("At Work")
        .border_style(if selected {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });
    let style = if selected {
        Style::default().bg(Color::DarkGray)
    } else {
        Style::default()
    };

    let para = Paragraph::new(Line::from(spans)).block(block).style(style);
    f.render_widget(para, area);
}

fn draw_entry_list(f: &mut Frame, app: &App, area: Rect) {
    // Use colors from config
    let colors: Vec<Color> = app
        .config
        .colors
        .iter()
        .map(|s| string_to_color(s))
        .collect();

    let items: Vec<ListItem> = app
        .entries
        .iter()
        .enumerate()
        .map(|(idx, entry)| {
            let start = entry.start_time.format("%H:%M").to_string();
            let end = entry
                .end_time
                .map(|t| t.format("%H:%M").to_string())
                .unwrap_or_else(|| "...".to_string());
            let duration = entry.duration_formatted();

            // Off-work entries (lunch/personal) are always gray — matching the
            // timeline's gray hatch — rather than a palette color.
            let entry_color = if entry.off_work {
                Color::Indexed(247)
            } else {
                colors[entry.color as usize % colors.len()]
            };

            let is_selected = !app.at_work_selected && Some(idx) == app.selected_index;

            let time_style = if entry.is_running() {
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Blue)
            };

            // Check if this entry has a synced task name
            let task_name = if !entry.issue_key.is_empty() {
                app.task_names.get(&entry.issue_key).cloned()
            } else {
                None
            };

            // The leading dot breathes in sync when the entry is highlighted
            // (unless eye candy is off — then it stays static).
            let dot_color = if is_selected && !app.config.hide_eye_candy {
                let (r, g, b) = breathe_color(themed_rgb(entry_color, &app.term_palette), breathe_t());
                Color::Rgb(r, g, b)
            } else {
                entry_color
            };

            let mut row1_spans = vec![
                Span::styled(
                    "",
                    Style::default().fg(dot_color).add_modifier(Modifier::BOLD),
                ),
                Span::raw(" "),
            ];

            // For entries with a task name: first row is description + time
            // For entries without: keep original layout
            if task_name.is_some() {
                row1_spans.push(Span::styled(
                    format!("{:5} - {:5}", start, end),
                    Style::default().fg(Color::Gray),
                ));
                row1_spans.push(Span::raw("  "));
                row1_spans.extend(duration_spans(&duration, entry.is_running(), is_selected, time_style, &app.term_palette, !app.config.hide_eye_candy));
                row1_spans.push(Span::raw("  "));
                row1_spans.push(Span::raw(&entry.description));
                if entry.logged {
                    row1_spans.push(Span::styled(
                        " ( logged )",
                        Style::default().fg(Color::Green),
                    ));
                }
                if entry.off_work {
                    row1_spans.push(Span::styled(
                        " ( off work )",
                        Style::default().fg(Color::Magenta),
                    ));
                }
            } else {
                row1_spans.push(Span::styled(
                    format!("{:5} - {:5}", start, end),
                    Style::default().fg(Color::Gray),
                ));
                row1_spans.push(Span::raw("  "));
                row1_spans.extend(duration_spans(&duration, entry.is_running(), is_selected, time_style, &app.term_palette, !app.config.hide_eye_candy));
                row1_spans.push(Span::raw("  "));

                if !entry.issue_key.is_empty() {
                    row1_spans.push(Span::styled(
                        format!("[{}] ", entry.issue_key),
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    ));
                }

                row1_spans.push(Span::raw(&entry.description));

                if entry.logged {
                    row1_spans.push(Span::styled(
                        " ( logged )",
                        Style::default().fg(Color::Green),
                    ));
                }
                if entry.off_work {
                    row1_spans.push(Span::styled(
                        " ( off work )",
                        Style::default().fg(Color::Magenta),
                    ));
                }
            }

            // Breathing white ◀ marker on the selected row, matching the one on
            // its bar in the timeline panel. Static white when eye candy is off.
            if is_selected {
                let base = themed_rgb(Color::White, &app.term_palette);
                let (r, g, b) = if app.config.hide_eye_candy {
                    base
                } else {
                    breathe_color(base, breathe_t())
                };
                row1_spans.push(Span::raw("  "));
                row1_spans.push(Span::styled(
                    "",
                    Style::default()
                        .fg(Color::Rgb(r, g, b))
                        .add_modifier(Modifier::BOLD),
                ));
            }

            let style = if !app.at_work_selected && Some(idx) == app.selected_index {
                Style::default().bg(Color::DarkGray).fg(Color::White)
            } else {
                Style::default()
            };

            if let Some(name) = task_name {
                // Two-row display
                let secondary_color = if is_selected {
                    Color::Gray
                } else {
                    Color::DarkGray
                };
                let row2_spans = vec![
                    Span::raw("  "),
                    Span::styled("→ task: ", Style::default().fg(secondary_color)),
                    Span::styled(
                        format!("[{}]", entry.issue_key),
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::raw(" "),
                    Span::styled(
                        name,
                        Style::default().fg(secondary_color),
                    ),
                ];
                ListItem::new(vec![
                    Line::from(row1_spans),
                    Line::from(row2_spans),
                ]).style(style)
            } else {
                ListItem::new(Line::from(row1_spans)).style(style)
            }
        })
        .collect();

    let list = List::new(items).block(Block::default().borders(Borders::ALL).title("Time Entries"));

    f.render_widget(list, area);
}

pub fn draw_suggestions_modal(f: &mut Frame, app: &App) {
    if let InputMode::Creating {
        suggestions,
        selected_suggestion,
        ..
    } = &app.input_mode
    {
        // Calculate modal size - centered and smaller than full screen
        let area = f.area();
        let modal_width = area.width.min(80);
        let modal_height = (suggestions.len() as u16 + 4).min(20); // +4 for borders and "new" option

        let modal_x = (area.width.saturating_sub(modal_width)) / 2;
        let modal_y = (area.height.saturating_sub(modal_height)) / 2;

        let modal_area = Rect {
            x: modal_x,
            y: modal_y,
            width: modal_width,
            height: modal_height,
        };

        // Clear background with a semi-transparent effect (we'll use borders to simulate this)
        let background = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Cyan))
            .title(" Quick Select (↑↓ to navigate, Enter to select) ")
            .style(Style::default().bg(Color::Black));
        f.render_widget(background, modal_area);

        // Inner area for the list
        let inner_area = Rect {
            x: modal_area.x + 1,
            y: modal_area.y + 1,
            width: modal_area.width.saturating_sub(2),
            height: modal_area.height.saturating_sub(2),
        };

        // Build items list
        let mut items = vec![];

        // First item: "New" option
        let new_style = if *selected_suggestion == 0 {
            Style::default()
                .bg(Color::DarkGray)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Green)
        };
        items.push(ListItem::new(Line::from(vec![Span::styled(
            "  → New (blank entry)",
            new_style,
        )])));

        // Add all suggestions
        for (idx, (issue_key, description, usage_count)) in suggestions.iter().enumerate() {
            let is_selected = *selected_suggestion == idx + 1;
            let style = if is_selected {
                Style::default().bg(Color::DarkGray).fg(Color::White)
            } else {
                Style::default()
            };

            let spans = vec![
                Span::raw("  "),
                Span::styled(
                    format!("[{}]", issue_key),
                    if is_selected {
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Yellow)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD)
                    },
                ),
                Span::raw(" "),
                Span::styled(description, style),
                Span::raw(" "),
                Span::styled(
                    format!("({}×)", usage_count),
                    if is_selected {
                        Style::default().bg(Color::DarkGray).fg(Color::DarkGray)
                    } else {
                        Style::default().fg(Color::DarkGray)
                    },
                ),
            ];

            items.push(ListItem::new(Line::from(spans)).style(style));
        }

        let list = List::new(items);
        f.render_widget(list, inner_area);
    }
}

pub fn draw_operations_menu(f: &mut Frame, app: &App) {
    let operations = [
        "Sync all task names from Jira",
        "Weekly summary",
        "Keyboard shortcuts",
        "Settings",
    ];

    let area = f.area();
    let modal_width = 50u16.min(area.width);
    let modal_height = (operations.len() as u16 + 2).min(area.height);
    let modal_x = (area.width.saturating_sub(modal_width)) / 2;
    let modal_y = (area.height.saturating_sub(modal_height)) / 2;
    let modal_area = Rect {
        x: modal_x,
        y: modal_y,
        width: modal_width,
        height: modal_height,
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .title(" Operations (↑↓ Enter, Esc to close) ")
        .style(Style::default().bg(Color::Black));
    f.render_widget(block, modal_area);

    let inner_area = Rect {
        x: modal_area.x + 1,
        y: modal_area.y + 1,
        width: modal_area.width.saturating_sub(2),
        height: modal_area.height.saturating_sub(2),
    };

    if let InputMode::OperationsMenu { selected_index } = &app.input_mode {
        let items: Vec<ListItem> = operations
            .iter()
            .enumerate()
            .map(|(i, op)| {
                let style = if i == *selected_index {
                    Style::default()
                        .bg(Color::DarkGray)
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                };
                ListItem::new(Line::from(vec![
                    Span::raw("  "),
                    Span::styled(*op, style),
                ])).style(style)
            })
            .collect();
        let list = List::new(items);
        f.render_widget(list, inner_area);
    }
}

/// Read-only modal listing extra keyboard shortcuts not shown in the main help bar.
pub fn draw_hotkeys(f: &mut Frame, _app: &App) {
    // (key, description)
    let shortcuts = [
        ("Shift+L", "Mark entry logged (without sending to Jira)"),
        ("t", "Open Tasks"),
        ("Shift+↑/↓", "Move entry up/down"),
        ("K / J", "Move entry up/down (works on any terminal)"),
        ("↑ on top entry", "Select the \"At Work\" day row"),
        ("w", "Show changelog / What's New"),
    ];

    let area = f.area();
    let modal_width = 60u16.min(area.width);
    let modal_height = (shortcuts.len() as u16 + 2).min(area.height);
    let modal_x = (area.width.saturating_sub(modal_width)) / 2;
    let modal_y = (area.height.saturating_sub(modal_height)) / 2;
    let modal_area = Rect {
        x: modal_x,
        y: modal_y,
        width: modal_width,
        height: modal_height,
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .title(" Keyboard shortcuts (any key to close) ")
        .style(Style::default().bg(Color::Black));
    f.render_widget(block, modal_area);

    let inner_area = Rect {
        x: modal_area.x + 1,
        y: modal_area.y + 1,
        width: modal_area.width.saturating_sub(2),
        height: modal_area.height.saturating_sub(2),
    };

    let lines: Vec<Line> = shortcuts
        .iter()
        .map(|(key, desc)| {
            Line::from(vec![
                Span::raw("  "),
                Span::styled(
                    format!("{:<16}", key),
                    Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
                ),
                Span::raw(*desc),
            ])
        })
        .collect();
    f.render_widget(Paragraph::new(lines), inner_area);
}