▍ humdrum codex / ticktock v0.0.2
license AGPL-3.0
1.8 KB raw
 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
package grid

import (
	"fmt"
	"time"

	"ticktock/internal/store"
)

// Grid describes the fixed-slot day window.
type Grid struct {
	SlotMin  int // minutes per slot
	FirstMin int // minute-of-day at row 0, slot-aligned
	Rows     int // number of slots
}

func parseHM(s string) (int, error) {
	t, err := time.Parse("15:04", s)
	if err != nil {
		return 0, fmt.Errorf("time %q: %w", s, err)
	}
	return t.Hour()*60 + t.Minute(), nil
}

func minuteOfDay(t time.Time) int { return t.Hour()*60 + t.Minute() }

func floorTo(min, slot int) int { return (min / slot) * slot }
func ceilTo(min, slot int) int  { return ((min + slot - 1) / slot) * slot }

// BuildGrid computes the slot window: [startMin,endMin] from config, expanded
// outward to cover every entry's start and (if ended) end. Running entries
// contribute only their start.
func BuildGrid(slot, startMin, endMin int, entries []store.Entry) Grid {
	first, last := startMin, endMin
	for _, e := range entries {
		s := minuteOfDay(e.Start)
		if s < first {
			first = s
		}
		if !e.Running() {
			en := minuteOfDay(e.End)
			if en > last {
				last = en
			}
		} else if s > last {
			last = s
		}
	}
	first = floorTo(first, slot)
	last = ceilTo(last, slot)
	rows := (last - first) / slot
	if rows < 1 {
		rows = 1
	}
	return Grid{SlotMin: slot, FirstMin: first, Rows: rows}
}

// SlotMinute returns the minute-of-day at the start of the given row. Passing
// row == Rows yields the window end (one past the last slot).
func (g Grid) SlotMinute(row int) int { return g.FirstMin + row*g.SlotMin }

// RowOf returns the row containing minute, clamped to the grid.
func (g Grid) RowOf(min int) int {
	r := (min - g.FirstMin) / g.SlotMin
	if min < g.FirstMin {
		r = 0
	}
	if r < 0 {
		r = 0
	}
	if r > g.Rows-1 {
		r = g.Rows - 1
	}
	return r
}