Skip to content
quarry Artifact [9d6e626bd0]
Login

Artifact [9d6e626bd0]

Artifact 9d6e626bd084288f42b9432fc4de8ff1b5b9d228205240986eee61083ead9d30:


package web

// The activity profile (RFC 0013): the core sample — a window of
// check-ins as dots, hour of day or path on Y, one colour per person —
// and the core slice, the whole history folded to one cell per day and
// one row per year. Both are drawn here as inline SVG from the two ops'
// output, so a reader without JavaScript gets the whole picture and
// the controls are links. The canvas that replaces the sample when a
// script runs is a later landing; the SVG stays as its first paint.

import (
	"fmt"
	"html/template"
	"math"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/ops"
)

// The op rows, as the registry marshals them.
type activityAuthor struct {
	Name     string `json:"name"`
	Checkins int    `json:"checkins"`
	Files    int    `json:"files"`
	Hue      int    `json:"hue"`
	Shade    int    `json:"shade"`
}

type activityRow struct {
	Day    int    `json:"day"`
	Hour   int    `json:"hour"`
	Author int    `json:"author"`
	Merge  int    `json:"merge"`
	Files  int    `json:"files"`
	Hash   string `json:"hash"`
	Branch string `json:"branch"`
}

type activityTouch struct {
	Day       int `json:"day"`
	Path      int `json:"path"`
	Author    int `json:"author"`
	Inherited int `json:"inherited"`
}

type activityOut struct {
	Since   string           `json:"since"`
	Until   string           `json:"until"`
	Authors []activityAuthor `json:"authors"`
	Paths   []string         `json:"paths"`
	Rows    []activityRow    `json:"rows"`
	Touches []activityTouch  `json:"touches"`
	Window  string           `json:"window"`
}

type activityDay struct {
	N       int     `json:"n"`
	Merges  int     `json:"merges"`
	Top     [][]int `json:"top"`
	Authors int     `json:"authors"`
	Path    int     `json:"path"`
}

type activityDaysOut struct {
	First    string                 `json:"first"`
	Last     string                 `json:"last"`
	Authors  []activityAuthor       `json:"authors"`
	Days     map[string]activityDay `json:"days"`
	Paths    []string               `json:"paths"`
	Releases map[string]string      `json:"releases"`
}

// activityView is what the activity page template draws from.
type activityView struct {
	Axis   string // "clock" or "tree"
	Branch string
	User   string
	Since  string
	Until  string
	Window string // "picked" or "given"
	// Halved counts how many times the window was cut in half to fit
	// the tree SVG under its byte budget (§7). Zero is the normal case.
	Halved  int
	Rows    int
	Touches int // authored touches — the dots on the tree axis
	// Merges is ?merges=1: the tree axis asked for the touches a merge
	// carried in. The SVG never draws them; the canvas does (§3, §7).
	Merges   bool
	Sample   template.HTML
	Slice    template.HTML
	Legend   []activityLegend
	Branches []string
	// Summary is the marginal the sighted reader takes from the shape,
	// as rows for a visually hidden table (§10).
	Summary      []activitySummary
	SummaryLabel string
	Years        []activityYear // the slice's numbers, for its hidden table
	YearsTotal   int            // years in the repository's history
	AllYears     bool           // ?years=all: every year, not the last sliceYears
}

type activityYear struct {
	Label    string
	Checkins int
	Days     int
	Merges   int
	Lead     string // who led the most days
	LeadPct  int
}

type activityLegend struct {
	Index    int
	Name     string
	Checkins int
	Files    int
	Colour   template.CSS // hsl(...) with theme tokens; html/template would reject the var()
	URL      string
	Current  bool
}

type activitySummary struct {
	Label string
	N     int
}

// activityByteBudget is the size the tree axis must stay under; past
// it the server halves the window and says so (§7). A variable so a
// test can force the halving without a 25,000-touch fixture.
var activityByteBudget = 1 << 20

// activityColour is a person's colour as a CSS value: hue from the op,
// saturation and lightness from the theme tokens, shade stepping the
// lightness so neighbours on the wheel stay apart (§6).
func activityColour(a activityAuthor) string {
	if a.Shade == 0 {
		return fmt.Sprintf("hsl(%d var(--dot-s) var(--dot-l))", a.Hue)
	}
	return fmt.Sprintf("hsl(%d var(--dot-s) calc(var(--dot-l) + %d%%))", a.Hue, a.Shade*8)
}

// activityURL is a link to the activity page. merges is the tree
// axis's own state and is dropped anywhere else, so a clock-axis link
// written with the flag on still comes out clean.
func activityURL(repo, axis, branch, user string, merges bool) string {
	q := url.Values{}
	if axis != "" && axis != "clock" {
		q.Set("axis", axis)
	}
	if merges && axis == "tree" {
		q.Set("merges", "1")
	}
	if branch != "" {
		q.Set("branch", branch)
	}
	if user != "" {
		q.Set("user", user)
	}
	u := "/r/" + url.PathEscape(repo) + "/activity"
	if len(q) > 0 {
		u += "?" + q.Encode()
	}
	return u
}

func dayAfter(iso string, n int) string {
	t, err := time.Parse("2006-01-02", iso)
	if err != nil {
		return iso
	}
	return t.AddDate(0, 0, n).Format("2006-01-02")
}

func daysSpan(since, until string) int {
	a, err1 := time.Parse("2006-01-02", since)
	b, err2 := time.Parse("2006-01-02", until)
	if err1 != nil || err2 != nil || b.Before(a) {
		return 1
	}
	return int(b.Sub(a).Hours()/24) + 1
}

func esc(s string) string { return template.HTMLEscapeString(s) }

// activityHandler serves /r/{repo}/activity.
func activityHandler(r *ops.Registry) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := req.URL.Query()
		axis := q.Get("axis")
		if axis == "" {
			axis = "clock"
		}
		if axis != "clock" && axis != "tree" {
			fail(r, w, req, fmt.Errorf("axis must be clock or tree: %w", ops.ErrInvalid))
			return
		}
		v := activityView{Axis: axis, Branch: q.Get("branch"), User: q.Get("user"),
			Merges: axis == "tree" && q.Get("merges") == "1"}
		since, until := q.Get("since"), q.Get("until")

		var act activityOut
		fetch := func() error {
			out, err := invoke(req.Context(), r, "repo.activity", url.Values{
				"repo": {repo}, "branch": {v.Branch}, "user": {v.User},
				"since": {since}, "until": {until},
			})
			if err != nil {
				return err
			}
			act = activityOut{}
			remarshal(out, &act)
			return nil
		}
		if err := fetch(); err != nil {
			fail(r, w, req, err)
			return
		}
		// The tree axis is one dot per authored file; on a large
		// window that is more bytes than a page should be. Halve the
		// window until it fits, at most a few times, and say so.
		var sample string
		for {
			sample = coreSampleSVG(repo, axis, v.Merges, act)
			if axis != "tree" || len(sample) <= activityByteBudget || v.Halved >= 4 {
				break
			}
			span := daysSpan(act.Since, act.Until)
			if span < 2 {
				break
			}
			since, until = dayAfter(act.Since, span/2), act.Until
			if err := fetch(); err != nil {
				fail(r, w, req, err)
				return
			}
			v.Halved++
		}
		v.Sample = template.HTML(sample)
		v.Since, v.Until, v.Window = act.Since, act.Until, act.Window
		v.Rows = len(act.Rows)
		for _, t := range act.Touches {
			if t.Inherited == 0 {
				v.Touches++
			}
		}
		v.Legend = activityLegendOf(repo, axis, v.Branch, v.User, v.Merges, act.Authors)
		v.SummaryLabel, v.Summary = activitySummaryOf(axis, act)
		if out, err := invoke(req.Context(), r, "branch.list",
			url.Values{"repo": {repo}, "limit": {"40"}, "open": {"1"}}); err == nil {
			var bl struct {
				Branches []branchRow `json:"branches"`
			}
			remarshal(out, &bl)
			for _, b := range bl.Branches {
				v.Branches = append(v.Branches, b.Name)
			}
		}
		// ?frag=1 is the same page asked for as a fragment: the view
		// region alone, as one Datastar patch into #act-view. The
		// slice is outside that region and is not rebuilt.
		if q.Get("frag") != "" {
			var buf strings.Builder
			if err := activityPage.ExecuteTemplate(&buf, "act-view", pageData{Repo: repo, Activity: &v}); err != nil {
				http.Error(w, "view render failed", http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "text/event-stream")
			w.Header().Set("Cache-Control", "no-store")
			fmt.Fprint(w, "event: datastar-patch-elements\ndata: mode inner\ndata: selector #act-view\n")
			for _, line := range strings.Split(buf.String(), "\n") {
				fmt.Fprintf(w, "data: elements %s\n", line)
			}
			fmt.Fprint(w, "\n")
			return
		}

		if out, err := invoke(req.Context(), r, "repo.activity.days",
			url.Values{"repo": {repo}, "branch": {v.Branch}}); err == nil {
			var days activityDaysOut
			remarshal(out, &days)
			spans := yearSpans(days)
			v.YearsTotal = len(spans)
			if q.Get("years") == "all" {
				v.AllYears = true
			} else if len(spans) > sliceYears {
				spans = spans[:sliceYears]
			}
			svg, years := coreSliceSVG(days, spans, false)
			v.Slice, v.Years = template.HTML(svg), years
		}
		render(r, w, req, activityPage, pageData{
			Title: "Activity", Repo: repo, Activity: &v,
		})
	}
}

func activityLegendOf(repo, axis, branch, user string, merges bool, authors []activityAuthor) []activityLegend {
	n := len(authors)
	if n > 24 {
		n = 24
	}
	out := make([]activityLegend, 0, n)
	for i, a := range authors[:n] {
		out = append(out, activityLegend{
			Index: i, Name: a.Name, Checkins: a.Checkins, Files: a.Files,
			Colour:  template.CSS(activityColour(a)),
			URL:     activityURL(repo, axis, branch, a.Name, merges),
			Current: a.Name == user,
		})
	}
	return out
}

// activitySummaryOf is the right-hand marginal as numbers: per hour on
// the clock axis, the ten most-touched paths on the tree axis.
func activitySummaryOf(axis string, act activityOut) (string, []activitySummary) {
	if axis == "clock" {
		var hours [24]int
		for _, r := range act.Rows {
			if r.Hour >= 0 && r.Hour < 24 {
				hours[r.Hour]++
			}
		}
		out := make([]activitySummary, 0, 24)
		for h, n := range hours {
			out = append(out, activitySummary{Label: fmt.Sprintf("%02d:00", h), N: n})
		}
		return "check-ins by hour (UTC)", out
	}
	counts := make(map[int]int)
	for _, t := range act.Touches {
		if t.Inherited == 0 {
			counts[t.Path]++
		}
	}
	idx := make([]int, 0, len(counts))
	for p := range counts {
		idx = append(idx, p)
	}
	sort.Slice(idx, func(i, j int) bool {
		if counts[idx[i]] != counts[idx[j]] {
			return counts[idx[i]] > counts[idx[j]]
		}
		return idx[i] < idx[j]
	})
	if len(idx) > 10 {
		idx = idx[:10]
	}
	out := make([]activitySummary, 0, len(idx))
	for _, p := range idx {
		if p >= 0 && p < len(act.Paths) {
			out = append(out, activitySummary{Label: act.Paths[p], N: counts[p]})
		}
	}
	return "most-changed files", out
}

// Layout of the core sample, in viewBox units.
const (
	sampleW      = 960
	sampleLeft   = 60 // axis labels, and the tree axis's date rail
	sampleRight  = 70 // the per-hour / per-day marginal
	sampleTop    = 48 // the per-day marginal
	sampleBottom = 22 // date labels
	sampleHour   = 12 // one hour's height on the clock axis
)

// Layout of the tree axis (§7): time runs down the page and files
// across, so the block is the same height whatever the repository —
// one narrow column per path, one row per day. When the window is
// longer than the plot the rows overlap, and that overlap is the
// texture, not a defect.
const (
	treeTop      = 112 // the per-path bars (48) and the rotated directory labels
	treeBottom   = 14
	treePlotH    = 520
	treeH        = treeTop + treePlotH + treeBottom
	treeBarH     = 48  // the per-path marginal's tallest bar
	treeBandMin  = 46  // a directory band narrower than this gets no label
	treeMonthMax = 900 // past this span the date rail steps by year
	treeDense    = 120 // past this many paths the dot shrinks with the column
)

// coreSampleSVG draws the window. Dots are grouped by author so the
// colour is set once per person, not once per dot: the group carries
// --c and the stylesheet does the rest. On the clock axis a dot is a
// link to its check-in; the tree axis is drawn by treeSampleSVG, where
// a dot is a (check-in, file) pair and inherited touches are not drawn
// (§3) — the merge is on the clock axis, where it happened.
func coreSampleSVG(repo, axis string, merges bool, act activityOut) string {
	if axis == "tree" {
		return treeSampleSVG(merges, act)
	}
	span := daysSpan(act.Since, act.Until)
	pw := float64(sampleW - sampleLeft - sampleRight)
	dx := pw / float64(span)
	x := func(day int) float64 { return sampleLeft + (float64(day)+0.5)*dx }

	ph := 24 * sampleHour
	h := sampleTop + ph + sampleBottom

	var b strings.Builder
	// Every dot is a link, and an image may not hold focusable things;
	// this chart is a group with a name.
	fmt.Fprintf(&b, `<svg class="act act-clock" viewBox="0 0 %d %d" role="group" aria-label="%s" data-axis="clock" data-rows="%d" data-since="%s" data-until="%s" data-window="%s">`,
		sampleW, h, esc(activitySentence(act)), len(act.Rows), esc(act.Since), esc(act.Until), esc(act.Window))
	fmt.Fprintf(&b, `<title>%s</title>`, esc(activitySentence(act)))

	// Per-day counts for the top marginal.
	perDay := make([]int, span)
	for _, r := range act.Rows {
		if r.Day >= 0 && r.Day < span {
			perDay[r.Day]++
		}
	}
	maxDay := 0
	for _, n := range perDay {
		if n > maxDay {
			maxDay = n
		}
	}
	b.WriteString(`<g class="mx" data-marginal="days">`)
	if maxDay > 0 {
		scale := float64(sampleTop-10) / float64(maxDay)
		bw := dx
		if bw < 1 {
			bw = 1
		}
		for d, n := range perDay {
			if n == 0 {
				continue
			}
			bh := float64(n) * scale
			fmt.Fprintf(&b, `<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>`,
				sampleLeft+float64(d)*dx, float64(sampleTop-4)-bh, bw, bh)
		}
	}
	b.WriteString(`</g>`)

	// Hour labels and the right marginal.
	plotTop := float64(sampleTop)
	var perHour [24]int
	for _, r := range act.Rows {
		if r.Hour >= 0 && r.Hour < 24 {
			perHour[r.Hour]++
		}
	}
	maxH := 0
	for _, n := range perHour {
		if n > maxH {
			maxH = n
		}
	}
	b.WriteString(`<g class="ax">`)
	for hr := 0; hr < 24; hr += 3 {
		fmt.Fprintf(&b, `<text x="%d" y="%.1f">%02d:00</text>`,
			sampleLeft-6, plotTop+float64(hr)*sampleHour+9, hr)
	}
	b.WriteString(`</g><g class="my" data-marginal="hours">`)
	if maxH > 0 {
		scale := float64(sampleRight-10) / float64(maxH)
		for hr, n := range perHour {
			if n == 0 {
				continue
			}
			fmt.Fprintf(&b, `<rect x="%d" y="%.1f" width="%.1f" height="%d"/>`,
				sampleW-sampleRight+4, plotTop+float64(hr)*sampleHour+1, float64(n)*scale, sampleHour-2)
		}
	}
	b.WriteString(`</g>`)

	// Date labels along the bottom: the first of each month that has
	// room, or just the ends on a short window.
	b.WriteString(`<g class="ax ax-x">`)
	yb := float64(sampleTop+ph) + 14
	if since, err := time.Parse("2006-01-02", act.Since); err == nil {
		// A label is ~60 units wide; pick the month step that fits.
		step := 1
		for _, st := range []int{1, 2, 3, 6, 12} {
			step = st
			if float64(span)/30.4/float64(st)*60 <= pw {
				break
			}
		}
		for d := 0; d < span; d++ {
			t := since.AddDate(0, 0, d)
			if t.Day() != 1 || (int(t.Month())-1)%step != 0 {
				continue
			}
			fmt.Fprintf(&b, `<text x="%.1f" y="%.1f">%s</text>`, x(d), yb, t.Format("Jan 2006"))
		}
	}
	b.WriteString(`</g>`)

	// The dots, one group per author. The radius is an attribute, not
	// only a style: engines without CSS geometry would draw nothing.
	byAuthor := make([][]string, len(act.Authors))
	for _, r := range act.Rows {
		if r.Author < 0 || r.Author >= len(byAuthor) {
			continue
		}
		cls := "dot"
		if r.Merge != 0 {
			cls = "dot merge"
		}
		title := fmt.Sprintf("%s %s %02d:00", act.Authors[r.Author].Name, dayAfter(act.Since, r.Day), r.Hour)
		if r.Merge != 0 {
			title += " · merge"
		} else if r.Files == 1 {
			title += " · 1 file"
		} else {
			title += fmt.Sprintf(" · %d files", r.Files)
		}
		if r.Branch != "" {
			title += " · " + r.Branch
		}
		byAuthor[r.Author] = append(byAuthor[r.Author], fmt.Sprintf(
			`<a href="/r/%s/checkin/%s"><circle class="%s" cx="%.1f" cy="%.1f" r="2.4"><title>%s</title></circle></a>`,
			url.PathEscape(repo), url.PathEscape(r.Hash), cls, x(r.Day), plotTop+float64(r.Hour)*sampleHour+sampleHour/2, esc(title)))
	}
	writeAuthorGroups(&b, act, byAuthor)
	b.WriteString(`</svg>`)
	return b.String()
}

// treeSampleSVG draws the tree axis: one column per path, one row per
// day with the newest at the top, so the picture's height is fixed and
// only the columns thin out as a repository grows. Only authored
// touches are dots — the inherited ones a merge carried in are the
// canvas's business (merges says the page asked for them), and drawing
// them here would double the bytes for a picture the reader can only
// see with a pointer anyway.
func treeSampleSVG(merges bool, act activityOut) string {
	span := daysSpan(act.Since, act.Until)
	paths := len(act.Paths)
	pw := float64(sampleW - sampleLeft - sampleRight)
	colW := pw
	if paths > 0 {
		colW = pw / float64(paths)
	}
	rowH := float64(treePlotH) / float64(span)
	x := func(p int) float64 { return sampleLeft + (float64(p)+0.5)*colW }
	y := func(d int) float64 { return treeTop + (float64(span-1-d)+0.5)*rowH }

	// A dot wide enough to see, or as wide as its column allows. Below
	// 1.4 a circle is mush; a square of the same size reads crisper
	// and costs fewer bytes.
	r := 2.4
	if paths > treeDense {
		r = math.Max(0.9, colW*0.45)
	}
	mark := func(cx, cy float64, title string) string {
		if r < 1.4 {
			return fmt.Sprintf(`<rect class="dot" x="%.1f" y="%.1f" width="%.1f" height="%.1f"><title>%s</title></rect>`,
				cx-r, cy-r, 2*r, 2*r, title)
		}
		return fmt.Sprintf(`<circle class="dot" cx="%.1f" cy="%.1f" r="%.1f"><title>%s</title></circle>`,
			cx, cy, r, title)
	}

	mergesFlag := 0
	if merges {
		mergesFlag = 1
	}
	var b strings.Builder
	fmt.Fprintf(&b, `<svg class="act act-tree" viewBox="0 0 %d %d" role="img" aria-label="%s" data-axis="tree" data-rows="%d" data-paths="%d" data-span="%d" data-merges="%d" data-since="%s" data-until="%s" data-window="%s">`,
		sampleW, treeH, esc(activitySentence(act)), len(act.Rows), paths, span, mergesFlag,
		esc(act.Since), esc(act.Until), esc(act.Window))
	fmt.Fprintf(&b, `<title>%s</title>`, esc(activitySentence(act)))

	// Directory bands (§5): paths arrive sorted so a directory's files
	// are contiguous; a run of five or more is a column of the plot,
	// labelled at 45° when the band is wide enough to read.
	b.WriteString(`<g class="bands">`)
	start, shade := 0, false
	for i := 1; i <= paths; i++ {
		if i < paths && dirOf(act.Paths[i]) == dirOf(act.Paths[start]) {
			continue
		}
		if n := i - start; n >= 5 {
			label := dirOf(act.Paths[start])
			if label == "" {
				label = "/"
			}
			x0, w := sampleLeft+float64(start)*colW, float64(n)*colW
			fmt.Fprintf(&b, `<g data-dir="%s">`, esc(label))
			if shade {
				fmt.Fprintf(&b, `<rect class="band" x="%.1f" y="%d" width="%.1f" height="%d"/>`,
					x0, treeTop, w, treePlotH)
			}
			shade = !shade
			if w > treeBandMin {
				fmt.Fprintf(&b, `<text class="dir" transform="rotate(-45 %.1f %d)" x="%.1f" y="%d"><title>%s</title>%s</text>`,
					x0+4, treeTop-10, x0+4, treeTop-10, esc(label), esc(bandLabel(label)))
			}
			b.WriteString(`</g>`)
		}
		start = i
	}
	b.WriteString(`</g>`)

	// The date rail down the left: a rule and a label wherever the
	// month changes, or the year on a window too long for months.
	b.WriteString(`<g class="rail">`)
	if since, err := time.Parse("2006-01-02", act.Since); err == nil {
		prev := ""
		for d := span - 1; d >= 0; d-- {
			t := since.AddDate(0, 0, d)
			label := t.Format("2006-01")
			if span > treeMonthMax {
				label = t.Format("2006")
			}
			if label == prev {
				continue
			}
			prev = label
			yy := y(d)
			fmt.Fprintf(&b, `<line x1="%d" y1="%.1f" x2="%d" y2="%.1f"/><text x="%d" y="%.1f">%s</text>`,
				sampleLeft, yy, sampleW-sampleRight, yy, sampleLeft-6, yy+3, label)
		}
	}
	b.WriteString(`</g>`)

	// Marginals: which files are touched most across the top, how busy
	// each day was down the right edge.
	perPath, perDay := make([]int, paths), make([]int, span)
	for _, t := range act.Touches {
		if t.Inherited != 0 {
			continue
		}
		if t.Path >= 0 && t.Path < paths {
			perPath[t.Path]++
		}
		if t.Day >= 0 && t.Day < span {
			perDay[t.Day]++
		}
	}
	maxP, maxD := 0, 0
	for _, n := range perPath {
		if n > maxP {
			maxP = n
		}
	}
	for _, n := range perDay {
		if n > maxD {
			maxD = n
		}
	}
	b.WriteString(`<g class="mx" data-marginal="paths">`)
	if maxP > 0 {
		scale := float64(treeBarH) / float64(maxP)
		bw := math.Max(1, colW)
		for p, n := range perPath {
			if n == 0 {
				continue
			}
			bh := float64(n) * scale
			fmt.Fprintf(&b, `<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>`,
				sampleLeft+float64(p)*colW, float64(treeBarH)-bh, bw, bh)
		}
	}
	b.WriteString(`</g><g class="my" data-marginal="days">`)
	if maxD > 0 {
		scale := float64(sampleRight-10) / float64(maxD)
		bh := math.Max(1, rowH)
		for d, n := range perDay {
			if n == 0 {
				continue
			}
			fmt.Fprintf(&b, `<rect x="%d" y="%.1f" width="%.1f" height="%.1f"/>`,
				sampleW-sampleRight+4, y(d)-rowH/2, float64(n)*scale, bh)
		}
	}
	b.WriteString(`</g>`)

	byAuthor := make([][]string, len(act.Authors))
	for _, t := range act.Touches {
		if t.Inherited != 0 || t.Author < 0 || t.Author >= len(byAuthor) || t.Path < 0 || t.Path >= paths {
			continue
		}
		byAuthor[t.Author] = append(byAuthor[t.Author], mark(x(t.Path), y(t.Day), fmt.Sprintf("%s %s %s",
			esc(act.Authors[t.Author].Name), dayAfter(act.Since, t.Day), esc(act.Paths[t.Path]))))
	}
	writeAuthorGroups(&b, act, byAuthor)
	b.WriteString(`</svg>`)
	return b.String()
}

// writeAuthorGroups writes the marks one group per author: the colour
// is set once per person, on the group, not once per dot.
func writeAuthorGroups(b *strings.Builder, act activityOut, byAuthor [][]string) {
	for i, dots := range byAuthor {
		if len(dots) == 0 {
			continue
		}
		fmt.Fprintf(b, `<g class="au" data-author="%d" style="--c:%s">`, i, activityColour(act.Authors[i]))
		for _, d := range dots {
			b.WriteString(d)
		}
		b.WriteString(`</g>`)
	}
}

// bandLabel keeps the tail of a directory: the margin fits about
// fourteen characters and the head is what the bands above share.
func bandLabel(dir string) string {
	const room = 14
	if len(dir) <= room {
		return dir
	}
	for i := strings.IndexByte(dir, '/'); i >= 0; i = strings.IndexByte(dir, '/') {
		dir = dir[i+1:]
		if len(dir)+2 <= room {
			return "…/" + dir
		}
	}
	return "…" + dir[len(dir)-room+1:]
}

func dirOf(path string) string {
	if i := strings.LastIndexByte(path, '/'); i >= 0 {
		return path[:i]
	}
	return ""
}

// activitySentence is the chart's aria-label: the numbers a sighted
// reader takes from the shape, in one sentence (§10).
func activitySentence(act activityOut) string {
	lead := ""
	if len(act.Authors) > 0 && len(act.Rows) > 0 {
		a := act.Authors[0]
		lead = fmt.Sprintf("; %s led with %d%%", a.Name, a.Checkins*100/len(act.Rows))
	}
	return fmt.Sprintf("%d check-ins by %d people, %s to %s%s",
		len(act.Rows), len(act.Authors), act.Since, act.Until, lead)
}

// The slice: one block per span (a calendar year, or the home page's
// last year), laid out the way GitHub taught everyone to read a year —
// a column per week, a row per weekday — so eight years stack on a
// page without scrolling. A cell is the day's leading author's colour
// at the day's volume, with a second-author stripe at 30% share and a
// release notch; the block's right column carries the ownership bar
// and the year's numbers (§7).
const (
	sliceCell   = 11
	sliceStep   = 13 // cell plus gap
	sliceTop    = 16 // month labels above the grid
	sliceGap    = 14 // between blocks
	sliceLabelW = 46
	sliceBarW   = 150
	sliceRightW = 210
	sliceStripH = 22 // the home page's one-row strip
)

// sliceYears is how many blocks the activity page shows unless asked
// for all of them.
const sliceYears = 8

type sliceSpan struct {
	Label string
	From  string // ISO, inclusive
	Days  int
}

// yearSpans is every calendar year from the first check-in to the
// last, newest first — the slice reads like a core, top is now.
func yearSpans(d activityDaysOut) []sliceSpan {
	first, err1 := time.Parse("2006-01-02", d.First)
	last, err2 := time.Parse("2006-01-02", d.Last)
	if err1 != nil || err2 != nil || last.Before(first) {
		return nil
	}
	var out []sliceSpan
	for y := last.Year(); y >= first.Year(); y-- {
		days := 365
		if y%4 == 0 && (y%100 != 0 || y%400 == 0) {
			days = 366
		}
		out = append(out, sliceSpan{Label: fmt.Sprint(y), From: fmt.Sprintf("%d-01-01", y), Days: days})
	}
	return out
}

// lastYearSpan is the home page's block: the 365 days ending at the
// last check-in.
func lastYearSpan(d activityDaysOut) []sliceSpan {
	last, err := time.Parse("2006-01-02", d.Last)
	if err != nil {
		return nil
	}
	return []sliceSpan{{Label: "", From: last.AddDate(0, 0, -364).Format("2006-01-02"), Days: 365}}
}

// coreSliceSVG draws the slice. With fit true it is the home page's
// strip instead: one row, a cell per day with no gaps, stretched to
// its box — the compact door, not the grid.
func coreSliceSVG(d activityDaysOut, spans []sliceSpan, fit bool) (string, []activityYear) {
	if len(spans) == 0 {
		return "", nil
	}
	var years []activityYear
	// Columns are weeks; a span starting late in the week can need 54.
	cols := 0
	for _, s := range spans {
		from, err := time.Parse("2006-01-02", s.From)
		if err != nil {
			return "", nil
		}
		if c := (int(from.Weekday())+s.Days-1)/7 + 1; c > cols {
			cols = c
		}
	}
	cellsX := float64(sliceLabelW)
	if fit {
		cellsX = 0
	}
	gridW := cols*sliceStep - (sliceStep - sliceCell)
	gridH := 7*sliceStep - (sliceStep - sliceCell)
	blockH := sliceTop + gridH
	barX := cellsX + float64(gridW) + 18
	w := int(barX) + sliceRightW
	h := len(spans)*(blockH+sliceGap) - sliceGap + 2
	if fit {
		w, h = spans[0].Days*sliceCell, sliceStripH
	}

	colour := func(i int) string {
		if i < 0 || i >= len(d.Authors) {
			return "var(--muted)"
		}
		return activityColour(d.Authors[i])
	}
	name := func(i int) string {
		if i < 0 || i >= len(d.Authors) {
			return "?"
		}
		return d.Authors[i].Name
	}

	var b strings.Builder
	active := 0
	for _, s := range spans {
		for i := 0; i < s.Days; i++ {
			if _, ok := d.Days[dayAfter(s.From, i)]; ok {
				active++
			}
		}
	}
	// A cell's opacity is the day's volume on a log scale against the
	// repository's own busy days (the 95th percentile reads full), so a
	// 40-check-in day and a 400-check-in day both read "full" rather
	// than one of them washing out.
	var counts []int
	for _, day := range d.Days {
		if day.N > 0 {
			counts = append(counts, day.N)
		}
	}
	sort.Ints(counts)
	p95 := 3
	if len(counts) > 0 {
		if n := counts[len(counts)*95/100]; n > p95 {
			p95 = n
		}
	}
	opacity := func(n int) float64 {
		level := math.Log1p(float64(n)) / math.Log1p(float64(p95))
		if level > 1 {
			level = 1
		}
		return 0.3 + 0.7*level
	}
	plural := func(n int, one, many string) string {
		if n == 1 {
			return one
		}
		return many
	}
	label := fmt.Sprintf("%d active %s across %d %s, %s to %s", active, plural(active, "day", "days"),
		len(spans), plural(len(spans), "year", "years"), d.First, d.Last)
	size := ""
	if fit {
		size = ` preserveAspectRatio="none"`
	}
	fmt.Fprintf(&b, `<svg class="slice"%s viewBox="0 0 %d %d" role="img" aria-label="%s" data-days="%d" data-spans="%d" data-cols="%d">`,
		size, w, h, esc(label), active, len(spans), cols)
	fmt.Fprintf(&b, `<title>%s</title>`, esc(label))

	for si, s := range spans {
		top := float64(si*(blockH+sliceGap)) + 1
		gy := top + sliceTop
		from, _ := time.Parse("2006-01-02", s.From)
		dow0 := int(from.Weekday())
		// Group cells by leading author so the colour is set once.
		cells := map[int][]string{}
		stripes := map[int][]string{}
		var notches, months []string
		led := map[int]int{}
		checkins, merges, days := 0, 0, 0
		for i := 0; i < s.Days; i++ {
			date := dayAfter(s.From, i)
			day, ok := d.Days[date]
			cx := cellsX + float64((dow0+i)/7*sliceStep)
			cy := gy + float64((dow0+i)%7*sliceStep)
			cw, ch := sliceCell, sliceCell
			if fit {
				cx, cy, ch = float64(i*sliceCell), 0, sliceStripH
			}
			if t := from.AddDate(0, 0, i); t.Day() == 1 && !fit {
				months = append(months, fmt.Sprintf(`<text class="mo" x="%.0f" y="%.0f">%s</text>`, cx, top+11, t.Month().String()[:3]))
			}
			if tag, rel := d.Releases[date]; rel {
				nx, nw := cx+sliceCell-4, 4
				if fit {
					nx, nw = cx, cw
				}
				notches = append(notches, fmt.Sprintf(`<rect class="rel" x="%.0f" y="%.0f" width="%d" height="4" data-date="%s"><title>%s · release %s</title></rect>`,
					nx, cy, nw, esc(date), esc(date), esc(tag)))
			}
			if !ok || day.N == 0 {
				continue
			}
			checkins += day.N
			merges += day.Merges
			days++
			lead := -1
			if len(day.Top) > 0 && len(day.Top[0]) == 2 {
				lead = day.Top[0][0]
			}
			led[lead]++
			title := fmt.Sprintf("%s · %d check-in", date, day.N)
			if day.N != 1 {
				title += "s"
			}
			if day.Merges > 0 {
				title += fmt.Sprintf(" (%d merge", day.Merges)
				if day.Merges != 1 {
					title += "s"
				}
				title += ")"
			}
			for k, t := range day.Top {
				if len(t) != 2 {
					continue
				}
				if k == 0 {
					title += " · "
				} else {
					title += ", "
				}
				title += fmt.Sprintf("%s %d", name(t[0]), t[1])
			}
			if day.Path >= 0 && day.Path < len(d.Paths) {
				p := d.Paths[day.Path]
				if p == "" {
					p = "/"
				}
				title += " · " + p
			}
			cells[lead] = append(cells[lead], fmt.Sprintf(`<rect class="c" x="%.0f" y="%.0f" width="%d" height="%d" fill-opacity="%.2f" data-date="%s"><title>%s</title></rect>`,
				cx, cy, cw, ch, opacity(day.N), esc(date), esc(title)))
			if len(day.Top) > 1 && len(day.Top[1]) == 2 && day.Top[1][1]*10 >= day.N*3 {
				sh := 3
				if fit {
					sh = 6
				}
				stripes[day.Top[1][0]] = append(stripes[day.Top[1][0]], fmt.Sprintf(`<rect class="s" x="%.0f" y="%.0f" width="%d" height="%d"/>`,
					cx, cy+float64(ch-sh), cw, sh))
			}
		}
		fmt.Fprintf(&b, `<g class="row" data-span="%s" data-checkins="%d" data-days="%d" data-merges="%d">`, esc(s.Label), checkins, days, merges)
		yr := activityYear{Label: s.Label, Checkins: checkins, Days: days, Merges: merges}
		if s.Label != "" {
			fmt.Fprintf(&b, `<text class="yr" x="0" y="%.0f">%s</text>`, top+12, esc(s.Label))
		}
		b.WriteString(strings.Join(months, ""))
		for _, i := range authorKeys(cells) {
			fmt.Fprintf(&b, `<g class="au" data-author="%d" style="--c:%s">%s</g>`, i, colour(i), strings.Join(cells[i], ""))
		}
		for _, i := range authorKeys(stripes) {
			fmt.Fprintf(&b, `<g class="au" data-author="%d" style="--c:%s">%s</g>`, i, colour(i), strings.Join(stripes[i], ""))
		}
		b.WriteString(strings.Join(notches, ""))
		// The right column: the year's numbers and who led how many of
		// its days.
		if days > 0 && !fit {
			fmt.Fprintf(&b, `<text class="n" x="%.0f" y="%.0f">%s check-%s · %d active %s</text>`,
				barX, gy+10, commas(checkins), plural(checkins, "in", "ins"), days, plural(days, "day", "days"))
			fmt.Fprintf(&b, `<g class="own" data-led="%d">`, len(led))
			x := barX
			for _, i := range sortedByCount(led) {
				bw := float64(sliceBarW) * float64(led[i]) / float64(days)
				fmt.Fprintf(&b, `<rect class="au" data-author="%d" style="--c:%s" x="%.1f" y="%.0f" width="%.1f" height="12"><title>%s led %d of %d days</title></rect>`,
					i, colour(i), x, gy+17, bw, esc(name(i)), led[i], days)
				x += bw
			}
			b.WriteString(`</g>`)
			leads := sortedByCount(led)
			yr.Lead, yr.LeadPct = name(leads[0]), led[leads[0]]*100/days
			fmt.Fprintf(&b, `<text class="m" x="%.0f" y="%.0f">%s led %d%% of days</text>`, barX, gy+45, esc(yr.Lead), yr.LeadPct)
			fmt.Fprintf(&b, `<text class="m" x="%.0f" y="%.0f">%s %s · %d%%</text>`, barX, gy+61, commas(merges), plural(merges, "merge", "merges"), merges*100/max(checkins, 1))
		}
		years = append(years, yr)
		b.WriteString(`</g>`)
	}
	b.WriteString(`</svg>`)
	return b.String(), years
}

// commas writes 12345 as 12,345.
func commas(n int) string {
	s := strconv.Itoa(n)
	for i := len(s) - 3; i > 0; i -= 3 {
		s = s[:i] + "," + s[i:]
	}
	return s
}

func authorKeys(m map[int][]string) []int {
	out := make([]int, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	sort.Ints(out)
	return out
}

func sortedByCount(m map[int]int) []int {
	out := make([]int, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	sort.Slice(out, func(i, j int) bool {
		if m[out[i]] != m[out[j]] {
			return m[out[i]] > m[out[j]]
		}
		return out[i] < out[j]
	})
	return out
}

// sliceHoverAttr is the slice's hover readout, as Datastar attributes
// on the container: pointerover reads the cell's own <title> — the
// no-script hover and the screen reader's text — into a signal that
// the "slice-tip" card shows beside the pointer. Nothing is duplicated
// per cell, so the SVG costs the same bytes with or without it. The
// card is positioned in the container's own box, so the container must
// not be the strip's scroller — a card hanging out of a scroll box
// scrolls the strip away vertically.
const sliceHoverAttr template.HTMLAttr = `data-signals="{sliceTip: '', sliceX: 0, sliceY: 0}" ` +
	`data-on:pointerover="$sliceTip = evt.target.closest('rect') && evt.target.closest('rect').firstElementChild ? evt.target.closest('rect').firstElementChild.textContent : ''" ` +
	`data-on:pointermove="$sliceX = evt.clientX - el.getBoundingClientRect().left; $sliceY = evt.clientY - el.getBoundingClientRect().top" ` +
	`data-on:pointerout="$sliceTip = ''"`

// homeSlice is the repository home's door: the last year as one row.
func homeSlice(r *ops.Registry, req *http.Request, repo string) template.HTML {
	out, err := invoke(req.Context(), r, "repo.activity.days", url.Values{"repo": {repo}})
	if err != nil {
		return ""
	}
	var days activityDaysOut
	remarshal(out, &days)
	svg, _ := coreSliceSVG(days, lastYearSpan(days), true)
	return template.HTML(svg)
}

var activityPage = template.Must(template.Must(base.Clone()).Parse(`{{define "act-view"}}{{with .Activity}}
{{- /* Two controls, both links (§7): which axis, and which branch.
       There is no person control — the legend is the door, and a
       chosen person is shown as the current legend entry.
       Axis and person links morph #act-view in place (morphAttr): the
       href is the cold-loadable page, pushState puts it in the
       address bar. Branch links stay whole-page loads because the
       year slice below the view depends on the branch too. */ -}}
<div class="act-controls">
<nav class="seg-box" aria-label="axis">
<a href="{{activityURL $.Repo "clock" .Branch .User .Merges}}"{{if eq .Axis "clock"}} class="here" aria-current="true"{{end}} {{morph (activityURL $.Repo "clock" .Branch .User .Merges)}}>clock</a>
<a href="{{activityURL $.Repo "tree" .Branch .User .Merges}}"{{if eq .Axis "tree"}} class="here" aria-current="true"{{end}} {{morph (activityURL $.Repo "tree" .Branch .User .Merges)}}>tree</a>
</nav>
{{- /* Only the tree axis has merges to show, so the control is only
       there; off it the flag is dropped from every URL. */ -}}
{{if eq .Axis "tree"}}
<nav class="seg-box act-merges" aria-label="merges">
<a href="{{activityURL $.Repo "tree" .Branch .User false}}"{{if not .Merges}} class="here" aria-current="true"{{end}} {{morph (activityURL $.Repo "tree" .Branch .User false)}}>authored</a>
<a href="{{activityURL $.Repo "tree" .Branch .User true}}"{{if .Merges}} class="here" aria-current="true"{{end}} {{morph (activityURL $.Repo "tree" .Branch .User true)}}>with merges</a>
</nav>{{end}}
{{if .Branches}}<details class="act-branches"><summary>branch: {{if .Branch}}{{.Branch}}{{else}}all{{end}}</summary>
<ul><li><a href="{{activityURL $.Repo .Axis "" .User .Merges}}"{{if not .Branch}} aria-current="true"{{end}}>all branches</a></li>
{{range .Branches}}<li><a href="{{activityURL $.Repo $.Activity.Axis . $.Activity.User $.Activity.Merges}}"{{if eq . $.Activity.Branch}} aria-current="true"{{end}}>{{.}}</a></li>{{end}}</ul></details>{{end}}
{{if .User}}<a class="act-clear" href="{{activityURL $.Repo .Axis .Branch "" .Merges}}" {{morph (activityURL $.Repo .Axis .Branch "" .Merges)}}>everyone</a>{{end}}
</div>
<p class="act-window" data-window="{{.Window}}" data-halved="{{.Halved}}">{{.Since}} to {{.Until}} · {{count .Rows}} {{plural .Rows "check-in" "check-ins"}}{{if eq .Axis "tree"}} · {{count .Touches}} {{plural .Touches "file change" "file changes"}}{{end}}{{if .Halved}} · the window was shortened to keep this page small; the API has the rest{{end}}</p>
<div class="act-sample">{{.Sample}}</div>
{{if .Legend}}<ol class="act-legend">
{{range .Legend}}<li><a href="{{.URL}}" data-author="{{.Index}}"{{if .Current}} aria-current="true"{{end}} {{morph .URL}}><span class="sw" style="--c:{{.Colour}}"></span> {{.Name}} <span class="act-n" title="check-ins">{{count .Checkins}}</span></a></li>
{{end}}</ol>{{end}}
{{if .Summary}}<table class="sr-only" data-summary="{{.Axis}}"><caption>{{.SummaryLabel}}</caption>
{{range .Summary}}<tr><th scope="row">{{.Label}}</th><td>{{.N}}</td></tr>{{end}}</table>{{end}}
{{end}}{{end}}
{{define "content"}}
{{with .Activity}}
<div id="act-view" data-on:popstate__window="@get(location.pathname + location.search + (location.search ? '&' : '?') + 'frag=1')">{{template "act-view" $}}</div>
{{if .Slice}}<h2 class="act-h">Year by year</h2>
<div class="act-strata" {{sliceHover}}><div class="act-slice">{{.Slice}}</div>{{template "slice-tip"}}</div>
<p class="act-key">a column per week, a row per weekday; the cell is the day's leading person, the stripe a second one, the notch a release{{if gt .YearsTotal (len .Years)}} · <a class="act-years" href="{{activityURL $.Repo .Axis .Branch .User .Merges}}{{if or .Branch .User (ne .Axis "clock")}}&amp;{{else}}?{{end}}years=all">all {{.YearsTotal}} years</a>{{else if .AllYears}} · <a class="act-years" href="{{activityURL $.Repo .Axis .Branch .User .Merges}}">recent years</a>{{end}}</p>
<table class="sr-only" data-summary="years"><caption>per year</caption><tr><th>year</th><th>check-ins</th><th>active days</th><th>merges</th><th>led most days</th></tr>
{{range .Years}}<tr><th scope="row">{{.Label}}</th><td>{{.Checkins}}</td><td>{{.Days}}</td><td>{{.Merges}}</td><td>{{.Lead}}{{if .Lead}} {{.LeadPct}}%{{end}}</td></tr>{{end}}</table>{{end}}
{{end}}
{{end}}`))