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
use chrono::{Local, Timelike};
use ratatui::{
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
    Frame,
};
use std::collections::HashMap;

use crate::app::{App, InputMode};
use crate::dashboard::utils::{
    breathe_color, breathe_t, calculate_minutes_per_row, dim_toward_bg, format_duration_seconds,
    string_to_color, themed_rgb,
};

pub fn draw_timeline(f: &mut Frame, app: &App, area: Rect) {
    if app.entries.is_empty() {
        let empty = Paragraph::new("No entries\nfor this day.\n\nPress 'n'\nto create one.")
            .block(Block::default().borders(Borders::ALL).title("Timeline"))
            .style(Style::default().fg(Color::Gray));
        f.render_widget(empty, area);
        return;
    }

    // Get editing times to potentially expand the range
    let (editing_start, editing_end, editing_field) = match &app.input_mode {
        InputMode::Editing {
            start_time,
            end_time,
            current_field,
            ..
        }
        | InputMode::Creating {
            start_time,
            end_time,
            current_field,
            ..
        } => {
            let start = chrono::NaiveTime::parse_from_str(start_time, "%H:%M")
                .ok()
                .map(|t| app.current_date.and_time(t));
            let end = if !end_time.is_empty() {
                chrono::NaiveTime::parse_from_str(end_time, "%H:%M")
                    .ok()
                    .map(|t| app.current_date.and_time(t))
            } else {
                None
            };
            (start, end, Some(*current_field))
        }
        _ => (None, None, None),
    };

    // Get time bounds from entries
    // Entries can be out of order based on display_order, so we use app-level methods
    let earliest_start = app.get_earliest_start_time().unwrap();
    let mut end_time = app.get_latest_end_time(Some(app.current_date)).unwrap_or(earliest_start);
    let has_running = app.entries.iter().any(|e| e.is_running());

    // Round start time down to previous full hour
    let start_time = earliest_start
        .with_minute(0)
        .unwrap()
        .with_second(0)
        .unwrap();

    // Expand range to include editing times
    if let Some(edit_start) = editing_start {
        end_time = end_time.max(edit_start);
    }
    if let Some(edit_end) = editing_end {
        end_time = end_time.max(edit_end);
    }

    // Only extend to the future if viewing today's date
    let today = Local::now().date_naive();
    if app.current_date == today {
        let now = Local::now().naive_local();
        let future_time = now + chrono::Duration::minutes(10);
        end_time = end_time.max(future_time);
    }

    // Ensure minimum range of at least 5 minutes for better visibility
    let min_duration = chrono::Duration::minutes(5);
    if end_time.signed_duration_since(start_time) < min_duration {
        end_time = start_time + min_duration;
    }

    // Round end time up to next full hour
    if end_time.minute() > 0 || end_time.second() > 0 {
        end_time = end_time
            .with_minute(0)
            .unwrap()
            .with_second(0)
            .unwrap()
            + chrono::Duration::hours(1);
    }

    let total_duration = end_time.signed_duration_since(start_time);

    // Build vertical timeline
    let mut lines = vec![];

    // Header info: show actual entry times, not the rounded view window
    let actual_end = if has_running {
        Local::now().naive_local()
    } else {
        app.entries.iter().filter_map(|e| e.end_time).max().unwrap_or(earliest_start)
    };
    let actual_total_seconds = actual_end.signed_duration_since(earliest_start).num_seconds().max(0);

    lines.push(Line::from(vec![
        Span::styled("Start: ", Style::default().fg(Color::Gray)),
        Span::styled(
            earliest_start.format("%H:%M").to_string(),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    lines.push(Line::from(vec![
        Span::styled(
            if has_running { "Now:   " } else { "End:   " },
            Style::default().fg(Color::Gray),
        ),
        Span::styled(
            actual_end.format("%H:%M").to_string(),
            Style::default()
                .fg(if has_running {
                    Color::Green
                } else {
                    Color::Yellow
                })
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    lines.push(Line::from(vec![
        Span::styled("Total: ", Style::default().fg(Color::Gray)),
        Span::styled(
            format_duration_seconds(actual_total_seconds),
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "".repeat(31),
        Style::default().fg(Color::DarkGray),
    )));

    // Calculate timeline resolution
    let total_minutes = total_duration.num_minutes();
    let available_rows = (area.height.saturating_sub(10)) as usize; // Account for header and borders
    let minutes_per_row = calculate_minutes_per_row(total_minutes, available_rows);
    let bar_height = ((total_minutes + minutes_per_row - 1) / minutes_per_row) as usize; // Ceiling division

    // Use colors from config
    let colors: Vec<Color> = app
        .config
        .colors
        .iter()
        .map(|s| string_to_color(s))
        .collect();

    // The currently highlighted entry (if any) gets a slow "breathe" on its
    // timeline bar. `breathe` is a single eased 0..1..0 wave shared by all rows
    // of that entry so the whole bar pulses in sync.
    let selected_entry_id = if app.at_work_selected {
        None
    } else {
        app.selected_index
            .and_then(|i| app.entries.get(i))
            .map(|e| e.id)
    };
    // When eye candy is hidden, freeze the breathe wave at its midpoint so the
    // selected bar/marker still picks up a static highlight tint but doesn't pulse.
    let breathe = if app.config.hide_eye_candy { 0.5 } else { breathe_t() };

    // Collect editing indicator times to always show them
    let mut editing_times = vec![];
    if let Some(s) = editing_start {
        editing_times.push((s, true)); // true = start
    }
    if let Some(e) = editing_end {
        editing_times.push((e, false)); // false = end
    }

    // Pre-calculate first and last row indices for each running entry
    let mut entry_row_bounds = vec![];
    for entry in app.entries.iter() {
        if !entry.is_running() {
            continue;
        }

        let entry_start_offset = entry
            .start_time
            .signed_duration_since(start_time)
            .num_seconds();
        let entry_end = entry.end_time.unwrap_or_else(|| Local::now().naive_local());
        let entry_end_offset = entry_end.signed_duration_since(start_time).num_seconds();

        let mut first_row = None;
        let mut last_row = None;

        for r in 0..=bar_height {
            let r_seconds = r as i64 * minutes_per_row * 60;
            if r_seconds >= entry_start_offset && r_seconds < entry_end_offset {
                if first_row.is_none() {
                    first_row = Some(r);
                }
                last_row = Some(r);
            }
        }

        if let (Some(first), Some(last)) = (first_row, last_row) {
            entry_row_bounds.push((entry.id, first, last));
        }
    }

    // The row just below each running entry's last row gets a blinking
    // half-height line in the entry's color — reads as the bar "growing" into the
    // current-time frontier. Keyed by row → palette RGB of that entry.
    let mut growth_rows: HashMap<usize, (u8, u8, u8)> = HashMap::new();
    for (entry_id, _first, last) in &entry_row_bounds {
        if let Some(entry) = app.entries.iter().find(|e| e.id == *entry_id) {
            if entry.off_work {
                continue;
            }
            let rgb = themed_rgb(colors[entry.color as usize % colors.len()], &app.term_palette);
            growth_rows.insert(last + 1, rgb);
        }
    }

    // Build map of which entries overlap at each row (for showing multiple entries)
    let mut row_entries: HashMap<usize, Vec<(i64, Color, bool)>> = HashMap::new();
    for entry in app.entries.iter() {
        let entry_start_offset = entry
            .start_time
            .signed_duration_since(start_time)
            .num_seconds();
        let entry_end = entry.end_time.unwrap_or_else(|| Local::now().naive_local());
        let entry_end_offset = entry_end.signed_duration_since(start_time).num_seconds();
        let entry_color = colors[entry.color as usize % colors.len()];

        for r in 0..=bar_height {
            let r_seconds = r as i64 * minutes_per_row * 60;
            if r_seconds >= entry_start_offset && r_seconds < entry_end_offset {
                row_entries.entry(r).or_insert_with(Vec::new).push((
                    entry.id,
                    entry_color,
                    entry.is_running(),
                ));
            }
        }
    }

    // At Work span (effective workday bounds) → mark rows that fall within it with a thin
    // cyan left-edge line (cyan = the workday/At Work accent color) so the full presence
    // window reads as a continuous gutter line, even where no task is logged. The first and
    // last rows get a rounded nubbin cap; rows outside the span keep a blank gutter for alignment.
    fn workday_edge(in_span: bool, is_start: bool, is_end: bool) -> Span<'static> {
        let _ = (is_start, is_end);
        if !in_span {
            return Span::raw(" ");
        }
        let ch = "";
        Span::styled(ch, Style::default().fg(Color::Cyan))
    }
    let workday_offsets = app.at_work_span().map(|(s, e, _)| {
        (
            s.signed_duration_since(start_time).num_seconds(),
            e.signed_duration_since(start_time).num_seconds(),
        )
    });
    let in_workday = |row_secs: i64| -> bool {
        workday_offsets
            .map(|(s, e)| row_secs >= s && row_secs < e)
            .unwrap_or(false)
    };
    // First/last rows inside the workday span, for nubbin caps.
    let (workday_first_row, workday_last_row) = {
        let mut first = None;
        let mut last = None;
        for r in 0..=bar_height {
            if in_workday(r as i64 * minutes_per_row * 60) {
                if first.is_none() {
                    first = Some(r);
                }
                last = Some(r);
            }
        }
        (first, last)
    };

    // Build vertical bars for each row
    // We want to ensure the last row shows the end time, so we use <= bar_height
    for row in 0..=bar_height {
        let row_start_time = start_time + chrono::Duration::minutes(row as i64 * minutes_per_row);
        let row_start_seconds = row as i64 * minutes_per_row * 60;

        // Check if we should force-show an editing indicator at this position
        let mut forced_indicator = None;
        let half_row_seconds = minutes_per_row * 30; // Half a row in seconds
        for (edit_time, is_start) in &editing_times {
            let edit_offset = edit_time.signed_duration_since(start_time).num_seconds();
            // Show indicator if we're close to this time or if no row would naturally show it
            if row_start_seconds >= (edit_offset - half_row_seconds)
                && row_start_seconds <= (edit_offset + half_row_seconds)
            {
                forced_indicator = Some((*edit_time, *is_start));
                break;
            }
        }

        // Find which entry (if any) covers this time slice
        let mut entry_info = None;
        for entry in app.entries.iter() {
            let entry_start_offset = entry
                .start_time
                .signed_duration_since(start_time)
                .num_seconds();
            let entry_end = entry.end_time.unwrap_or_else(|| Local::now().naive_local());
            let entry_end_offset = entry_end.signed_duration_since(start_time).num_seconds();

            if row_start_seconds >= entry_start_offset && row_start_seconds < entry_end_offset {
                // Check if this is first or last row for a running entry
                let mut is_first_row = false;
                let mut is_last_row = false;

                if entry.is_running() {
                    for (entry_id, first, last) in &entry_row_bounds {
                        if *entry_id == entry.id {
                            is_first_row = row == *first;
                            is_last_row = row == *last;
                            break;
                        }
                    }
                }

                entry_info = Some((
                    colors[entry.color as usize % colors.len()],
                    entry.is_running(),
                    is_first_row,
                    is_last_row,
                    entry.off_work,
                    Some(entry.id) == selected_entry_id,
                ));
                break;
            }
        }

        let line = if let Some((edit_time, is_start)) = forced_indicator {
            // Show editing indicator — laid out exactly like a normal row
            // (`{time} {workday_edge} {20-char bar}`) so the workday gutter
            // line keeps flowing through it and columns stay aligned.
            let time_label = edit_time.format("%H:%M").to_string();
            let (label, is_active) = if is_start {
                ("START", editing_field == Some(1))
            } else {
                ("END",   editing_field == Some(2))
            };
            let row_in_workday = in_workday(row_start_seconds);
            let edge = workday_edge(
                row_in_workday,
                workday_first_row == Some(row),
                workday_last_row == Some(row),
            );
            // Active field gets a yellow tag (the universal "you're editing
            // this" accent); the other endpoint shows a muted dim-gray tag so
            // it's still readable but recedes.
            let (fg, bg) = if is_active {
                (Color::Black, Color::Yellow)
            } else {
                (Color::Gray, Color::Indexed(238))
            };
            let inner = format!("{} ", label);
            let padding = 20usize.saturating_sub(inner.chars().count());
            let bar_text = format!("{}{}", inner, " ".repeat(padding));
            Line::from(vec![
                Span::styled(
                    format!("{} ", time_label),
                    Style::default()
                        .fg(if is_active { Color::Yellow } else { Color::Gray })
                        .add_modifier(Modifier::BOLD),
                ),
                edge,
                Span::styled(
                    bar_text,
                    Style::default()
                        .fg(fg)
                        .bg(bg)
                        .add_modifier(Modifier::BOLD),
                ),
            ])
        } else {
            let time_label = row_start_time.format("%H:%M").to_string();

            // Get all entries at this row for overlap detection
            let entries_at_row = row_entries.get(&row).map(|v| v.as_slice()).unwrap_or(&[]);
            let has_overlap = entries_at_row.len() > 1;

            let row_in_workday = in_workday(row_start_seconds);
            let edge = workday_edge(
                row_in_workday,
                workday_first_row == Some(row),
                workday_last_row == Some(row),
            );

            if let Some((color, is_running, is_first_row, is_last_row, off_work, is_selected)) =
                entry_info
            {
                // Base palette RGB of this entry (before any selection pulse),
                // used for the running "now frontier" tip glow below.
                let base_rgb = themed_rgb(color, &app.term_palette);
                // When highlighted, pulse the bar's fill color (lighter ↔
                // dark/saturated). Off-work breathes its gray rather than the
                // palette color, so it stays gray (just animated) when selected.
                let color = if is_selected {
                    let base = if off_work {
                        (158, 158, 158) // ANSI 256 grayscale index 247
                    } else {
                        base_rgb
                    };
                    let (r, g, b) = breathe_color(base, breathe);
                    Color::Rgb(r, g, b)
                } else if off_work {
                    Color::Indexed(247)
                } else {
                    color
                };
                let _ = (is_first_row, is_last_row);
                let mut spans = vec![
                    Span::styled(
                        format!("{} ", time_label),
                        Style::default().fg(dim_toward_bg(Color::Gray, &app.term_palette, 0.55)),
                    ),
                    edge,
                ];

                if off_work {
                    // Off work (e.g. lunch): light-gray hatch, distinct from colored work bars.
                    spans.push(Span::styled("".repeat(20), Style::default().fg(color)));
                } else if is_running {
                    // Running entries render solid like stopped ones; the "live"
                    // cue is the blinking half-height growth line below the bar
                    // (see growth_rows / the empty-row branch).
                    spans.push(Span::styled("".repeat(20), Style::default().fg(color)));
                } else {
                    // Stopped entry: just the color
                    spans.push(Span::styled("".repeat(20), Style::default().fg(color)));
                }

                // Matching marker on the right side of the timeline bar: a
                // breathing white ◀ pointing at the selected entry's bar. Matches
                // the marker in the Time Entries list.
                if is_selected {
                    let (wr, wg, wb) =
                        breathe_color(themed_rgb(Color::White, &app.term_palette), breathe);
                    spans.push(Span::raw(" "));
                    spans.push(Span::styled(
                        "",
                        Style::default()
                            .fg(Color::Rgb(wr, wg, wb))
                            .add_modifier(Modifier::BOLD),
                    ));
                }

                // Add overlap indicators (small circles after the bar)
                if has_overlap {
                    spans.push(Span::raw(" "));
                    for (idx, (_, overlap_color, overlap_running)) in
                        entries_at_row.iter().enumerate()
                    {
                        if idx > 0 {
                            // Skip the first entry (already shown in main bar)
                            if *overlap_running {
                                // Running overlapping entry: show both green and color
                                spans.push(Span::styled(
                                    "",
                                    Style::default()
                                        .fg(Color::Green)
                                        .add_modifier(Modifier::BOLD),
                                ));
                                spans.push(Span::styled(
                                    "",
                                    Style::default()
                                        .fg(*overlap_color)
                                        .add_modifier(Modifier::BOLD),
                                ));
                            } else {
                                // Stopped overlapping entry: just the color
                                spans.push(Span::styled("", Style::default().fg(*overlap_color)));
                            }
                        }
                    }
                }

                Line::from(spans)
            } else if let Some(&rgb) = growth_rows.get(&row) {
                // Blinking half-height growth line under a running entry: the bar
                // "grows" into this row toward the current time. Fades between the
                // entry color and a near-background dim on a ~1.1s cycle.
                let blink = {
                    const P: f64 = 1100.0;
                    let ms = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_millis() as f64;
                    let p = (ms % P) / P;
                    let tri = if p < 0.5 { p * 2.0 } else { 2.0 - p * 2.0 };
                    tri * tri * (3.0 - 2.0 * tri) // smoothstep ease
                };
                let bg = app.term_palette.get(&0).copied().unwrap_or((0, 0, 0));
                let mix = |a: u8, b: u8, t: f64| (a as f64 + (b as f64 - a as f64) * t).round() as u8;
                // dim end sits 80% toward background; blink lerps dim → full color.
                let chan = |c: u8, b: u8| {
                    let dim = mix(c, b, 0.80);
                    mix(dim, c, blink)
                };
                let blink_color = Color::Rgb(chan(rgb.0, bg.0), chan(rgb.1, bg.1), chan(rgb.2, bg.2));
                Line::from(vec![
                    Span::styled(
                        format!("{} ", time_label),
                        Style::default().fg(dim_toward_bg(Color::Gray, &app.term_palette, 0.6)),
                    ),
                    edge,
                    Span::styled("".repeat(20), Style::default().fg(blink_color)),
                ])
            } else {
                // Empty row: faint horizontal guide lines for visual structure.
                // Brightness is a 3-step hierarchy (full hour > half > other),
                // expressed as how far each blends toward the terminal background
                // so it tracks the user's theme rather than a fixed gray.
                let is_full_hour = row_start_time.minute() == 0;
                let (line_char, line_dim, label_dim) = if is_full_hour {
                    ("", 0.55, 0.45)
                } else if row_start_time.minute() == 30 {
                    ("", 0.70, 0.62)
                } else {
                    ("", 0.82, 0.74)
                };
                Line::from(vec![
                    Span::styled(
                        format!("{} ", time_label),
                        Style::default().fg(dim_toward_bg(Color::Gray, &app.term_palette, label_dim)),
                    ),
                    edge,
                    Span::styled(
                        line_char.repeat(20),
                        Style::default().fg(dim_toward_bg(Color::Gray, &app.term_palette, line_dim)),
                    ),
                ])
            }
        };

        lines.push(line);
    }

    let timeline =
        Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title("Timeline"));
    f.render_widget(timeline, area);
}