package charts
import (
"fmt"
"html"
"math"
"strconv"
"strings"
"time"
)
var weekdayNames = [7]string{"Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"}
var weekdayLong = [7]string{"Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"}
// hourRanges: "9–10 Uhr" für die Infozeile.
func hourRanges() []string {
l := make([]string, 24)
for i := range l {
l[i] = fmt.Sprintf("%d–%d Uhr", i, i+1)
}
return l
}
func hourLabels() []string {
l := make([]string, 24)
for i := range l {
l[i] = strconv.Itoa(i)
}
return l
}
// --- SVG ---
// Maße im viewBox-Raum. narrow entspricht der schmalen Inhaltsspalte (600 px),
// wide der breiten Statistik-Seite (1200 px); bis dorthin wird 1:1 gezeichnet,
// darunter skaliert das SVG mit.
type size struct{ w, h int }
var (
narrow = size{600, 240}
wide = size{1200, 300}
)
const (
padLeft = 44
padRight = 12
padTop = 12
padBottom = 26
fontSize = 13
)
const colorGrid = "#ddd"
// colorStack sind die Füllfarben der Stapel, Reihenfolge wie postKinds.
var colorStack = [2]string{"#444", "#aaa"}
type svg struct{ strings.Builder }
// f hängt formatierten Text an; Schreiben in einen strings.Builder scheitert nie.
func (b *svg) f(format string, a ...any) { _, _ = fmt.Fprintf(b, format, a...) }
func svgOpen(b *svg, sz size, label string) {
b.f(``, sz.w/2, sz.h/2)
return b.String()
}
// niceScale wählt eine runde Schrittweite (1, 2, 5 × 10^k) für etwa vier
// Gitterlinien und die darauf aufgerundete Obergrenze.
func niceScale(max float64) (step, top float64) {
if max <= 0 {
max = 1
}
raw := max / 4
mag := math.Pow(10, math.Floor(math.Log10(raw)))
step = 10 * mag
for _, m := range []float64{1, 2, 5} {
if m*mag >= raw {
step = m * mag
break
}
}
return step, math.Ceil(max/step-1e-9) * step
}
// fmtNum schreibt eine Zahl mit höchstens zwei Nachkommastellen und
// deutschem Komma.
func fmtNum(v float64) string {
return strings.Replace(strconv.FormatFloat(math.Round(v*100)/100, 'f', -1, 64), ".", ",", 1)
}
// yAxis zeichnet Gitterlinien mit Beschriftung und liefert die Abbildung
// Wert -> y-Koordinate.
func yAxis(b *svg, sz size, max float64, top int) func(float64) float64 {
step, maxV := niceScale(max)
bottom := float64(sz.h - padBottom)
y := func(v float64) float64 { return bottom - v/maxV*(bottom-float64(top)) }
for v := 0.0; v <= maxV+step/2; v += step {
yy := y(v)
color := colorGrid
if v == 0 {
color = "black"
}
b.f(``, padLeft, yy, sz.w-padRight, yy, color)
b.f(`%s`, padLeft-6, yy+4, fmtNum(v))
}
return y
}
func maxOf(vals []float64) float64 {
m := 0.0
for _, v := range vals {
m = math.Max(m, v)
}
return m
}
// series ist eine Tagesreihe für lineChart.
type series struct {
label, unit string
days []time.Time
vals []float64
}
// lineChart zeichnet eine Tagesreihe als Linie. Alle Tage seit Beginn werden
// auf die volle Breite gestaucht; unsichtbare Streifen je Tag tragen den
// Tooltip (
), denselben Text in data-tip für die Infozeile unter dem
// Diagramm (StatsPage.tsx) und eine senkrechte Markierung.
func lineChart(sz size, s series) string {
if len(s.days) == 0 {
return emptyChart(sz, s.label)
}
days, vals := s.days, s.vals
var b svg
svgOpen(&b, sz, s.label)
y := yAxis(&b, sz, maxOf(vals), padTop)
plotW := float64(sz.w - padLeft - padRight)
n := len(days)
x := func(i int) float64 {
if n == 1 {
return padLeft + plotW/2
}
return padLeft + float64(i)*plotW/float64(n-1)
}
bottom := sz.h - padBottom
for _, i := range dateTicks(days) {
xx := x(i)
b.f(``, xx, bottom, xx, bottom+4)
tx := math.Min(math.Max(xx, padLeft+16), float64(sz.w-padRight-16))
b.f(`%s`, tx, bottom+18, dateTickLabel(days[i]))
}
var pts strings.Builder
for i, v := range vals {
fmt.Fprintf(&pts, "%.1f,%.1f ", x(i), y(v))
}
if n == 1 {
b.f(``, x(0), y(vals[0]))
} else {
b.f(``,
strings.TrimSpace(pts.String()))
}
slot := plotW / float64(max(n-1, 1))
for i, d := range days {
tip := fmt.Sprintf("%s, %s: %s %s", weekdayNames[isoWeekday(d)], d.Format("02.01.2006"), fmtNum(vals[i]), s.unit)
// Die Markierungslinie ist versteckt; das CSS zeigt sie beim Hovern
// über den Streifen (.chart g:hover .mark).
b.f(`%s`,
tip, tip, x(i)-slot/2, padTop, slot, bottom-padTop)
b.f(``,
x(i), padTop, x(i), bottom)
}
b.f(``)
return b.String()
}
var monthNames = [12]string{"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"}
const maxTicks = 8
// dateTicks wählt die beschrifteten Tage: Monatsanfänge, bei langen Reihen
// nur jedes Quartal, Halbjahr oder Jahr; bei Reihen unter zwei Monaten die
// Montage. Höchstens maxTicks Beschriftungen.
func dateTicks(days []time.Time) []int {
if months := indicesWhere(days, func(d time.Time) bool { return d.Day() == 1 }); len(months) >= 2 {
for _, step := range []int{1, 3, 6} {
if picked := everyNthMonth(days, months, step); len(picked) <= maxTicks {
return picked
}
}
return everyNthMonth(days, months, 12)
}
mondays := indicesWhere(days, func(d time.Time) bool { return d.Weekday() == time.Monday })
for len(mondays) > maxTicks {
mondays = everyOther(mondays)
}
return mondays
}
func indicesWhere(days []time.Time, match func(time.Time) bool) []int {
var idx []int
for i, d := range days {
if match(d) {
idx = append(idx, i)
}
}
return idx
}
// everyNthMonth behält die Monatsanfänge jedes step-ten Monats, gezählt ab
// Januar (step 3: Quartalsanfänge).
func everyNthMonth(days []time.Time, months []int, step int) []int {
var picked []int
for _, i := range months {
if (int(days[i].Month())-1)%step == 0 {
picked = append(picked, i)
}
}
return picked
}
func everyOther(idx []int) []int {
var half []int
for j := 0; j < len(idx); j += 2 {
half = append(half, idx[j])
}
return half
}
// dateTickLabel: "02.10." bei Wochen-Ticks, sonst Monatsname; der Januar
// zeigt stattdessen die Jahreszahl.
func dateTickLabel(d time.Time) string {
if d.Day() != 1 {
return d.Format("02.01.")
}
if d.Month() == time.January {
return strconv.Itoa(d.Year())
}
return monthNames[d.Month()-1]
}
// bars sind Kategorien mit je Ø Threads und Antworten für stackedBars.
type bars struct {
label string
labels []string // Achsenbeschriftung
tipLabels []string // Kategorie im Tooltip
vals [][2]float64
}
// stackedBars zeichnet Ø Threads (unten) und Antworten (oben) je Kategorie
// als gestapelte Säulen mit Legende.
func stackedBars(sz size, bs bars) string {
vals := bs.vals
totals := make([]float64, len(vals))
for i, v := range vals {
totals[i] = v[0] + v[1]
}
if maxOf(totals) == 0 {
return emptyChart(sz, bs.label)
}
var b svg
svgOpen(&b, sz, bs.label)
top := padTop + 20
x0 := padLeft + 4
for k, name := range postKinds {
b.f(``, x0, padTop-2, colorStack[k])
b.f(`%s`, x0+16, padTop+8, name)
x0 += 16 + 9*len(name) + 16
}
y := yAxis(&b, sz, maxOf(totals), top)
bottom := float64(sz.h - padBottom)
slot := float64(sz.w-padLeft-padRight) / float64(len(vals))
barW := slot * 0.7
for i, v := range vals {
x := padLeft + float64(i)*slot + (slot-barW)/2
tip := html.EscapeString(fmt.Sprintf("%s: Ø %s Beiträge pro Tag (%s Threads, %s Antworten)",
bs.tipLabels[i], fmtNum(totals[i]), fmtNum(v[0]), fmtNum(v[1])))
b.f(`%s`, tip, tip)
// Unsichtbare volle Säule, damit auch kurze Balken gut zu treffen sind.
b.f(``,
padLeft+float64(i)*slot, top, slot, bottom-float64(top))
base := 0.0
for k := range postKinds {
if v[k] > 0 {
b.f(``,
x, y(base+v[k]), barW, y(base)-y(base+v[k]), colorStack[k])
}
base += v[k]
}
b.f(``)
b.f(`%s`, x+barW/2, bottom+18, html.EscapeString(bs.labels[i]))
}
b.f(``)
return b.String()
}