showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
heatmap.go
2.5 KB · 86 lines
1package render23import (4 "fmt"5 "html/template"6 "strings"7 "time"8)910// The heatmap's grid. The activity bars use the same columns.11const (12 cell = 1013 gap = 314 left = 28 // room for weekday labels15 top = 16 // room for month labels16 weeks = 5317)1819// colX is the left edge of week column col.20func colX(col int) int { return left + col*(cell+gap) }2122// monthCols lists the columns that get a month label: the first Sunday of23// each month, leaving out the last two columns.24func monthCols(start time.Time, n int) []int {25 var out []int26 last := time.Month(0)27 for col := 0; col < n-2; col++ {28 if m := start.AddDate(0, 0, 7*col).Month(); m != last {29 last = m30 out = append(out, col)31 }32 }33 return out34}3536// Heatmap draws daily counts (keyed "2006-01-02", UTC) ending on the day of37// end as an inline SVG of the last n week columns. The total and the38// aria-label cover the whole year. Colours come from CSS classes, since the39// CSP forbids inline styles.40func Heatmap(counts map[string]int, end time.Time, n int) (template.HTML, int) {41 end = time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, time.UTC)42 start := WeekStart(end, n-1)43 max, total := 0, 044 for d := WeekStart(end, weeks-1); !d.After(end); d = d.AddDate(0, 0, 1) {45 c := counts[d.Format("2006-01-02")]46 total += c47 if c > max && !d.Before(start) {48 max = c49 }50 }5152 w, h := colX(n), top+7*(cell+gap)53 var b strings.Builder54 fmt.Fprintf(&b, `<svg class="heatmap" viewBox="0 0 %d %d" role="img" aria-label="%d commits in the last year">`, w, h, total)55 for i, label := range []string{"Mon", "Wed", "Fri"} {56 fmt.Fprintf(&b, `<text x="0" y="%d">%s</text>`, top+(2*i+1)*(cell+gap)+cell-1, label)57 }58 months := monthCols(start, n)59 for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {60 col, row := int(d.Sub(start).Hours()/24)/7, int(d.Weekday())61 x, y := colX(col), top+row*(cell+gap)62 if row == 0 && len(months) > 0 && months[0] == col {63 months = months[1:]64 fmt.Fprintf(&b, `<text x="%d" y="%d">%s</text>`, x, top-5, d.Format("Jan"))65 }66 c := counts[d.Format("2006-01-02")]67 fmt.Fprintf(&b, `<rect class="h%d" x="%d" y="%d" width="%d" height="%d" rx="2"><title>%s on %s</title></rect>`,68 level(c, max), x, y, cell, cell, commits(c), d.Format("Jan 2, 2006"))69 }70 b.WriteString(`</svg>`)71 return template.HTML(b.String()), total72}7374func level(n, max int) int {75 if n <= 0 || max <= 0 {76 return 077 }78 return (4*n + max - 1) / max // ceil(4n/max), 1..479}8081func commits(n int) string {82 if n == 1 {83 return "1 commit"84 }85 return fmt.Sprintf("%d commits", n)86}