| 1 | package gitgraph |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "html" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | // SVG tekent de lanelijnen. Alleen getallen en paletkleuren, veilig als HTML. |
| 10 | func (g *Graph) SVG() string { |
| 11 | if g == nil || len(g.Rows) == 0 || g.Lanes < 1 { |
| 12 | return "" |
| 13 | } |
| 14 | w, h := g.Width, g.Height |
| 15 | var b strings.Builder |
| 16 | b.WriteString(fmt.Sprintf(`<svg class="commitgraph-svg" viewBox="0 0 %d %d" width="%d" height="%d" aria-hidden="true">`, w, h, w, h)) |
| 17 | for _, e := range g.Edges { |
| 18 | col := safeColor(e.Color) |
| 19 | x1, y1 := laneX(e.FromLane), rowY(e.FromRow) |
| 20 | x2, y2 := laneX(e.ToLane), rowY(e.ToRow) |
| 21 | if e.FromLane == e.ToLane { |
| 22 | fmt.Fprintf(&b, `<path d="M %.1f %.1f V %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`, x1, y1, y2, col) |
| 23 | continue |
| 24 | } |
| 25 | // Boog tussen lanes: horizontaal op halve rij, dan verticaal. |
| 26 | midY := y1 + float64(RowH)/2 |
| 27 | if e.ToRow == e.FromRow+1 { |
| 28 | // korte merge/fork naar de volgende rij |
| 29 | fmt.Fprintf(&b, `<path d="M %.1f %.1f C %.1f %.1f, %.1f %.1f, %.1f %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`, |
| 30 | x1, y1, x1, midY, x2, midY, x2, y2, col) |
| 31 | continue |
| 32 | } |
| 33 | fmt.Fprintf(&b, `<path d="M %.1f %.1f C %.1f %.1f, %.1f %.1f, %.1f %.1f V %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`, |
| 34 | x1, y1, x1, midY, x2, midY, x2, y1+float64(RowH), y2, col) |
| 35 | } |
| 36 | for i, r := range g.Rows { |
| 37 | fmt.Fprintf(&b, `<circle cx="%.1f" cy="%.1f" r="%.1f" fill="%s"/>`, laneX(r.Lane), rowY(i), DotR, safeColor(r.Color)) |
| 38 | } |
| 39 | b.WriteString(`</svg>`) |
| 40 | return b.String() |
| 41 | } |
| 42 | |
| 43 | func laneX(lane int) float64 { |
| 44 | return float64(lane)*float64(LaneW) + float64(LaneW)/2 |
| 45 | } |
| 46 | |
| 47 | func rowY(row int) float64 { |
| 48 | return float64(row)*float64(RowH) + float64(RowH)/2 |
| 49 | } |
| 50 | |
| 51 | func safeColor(c string) string { |
| 52 | c = strings.TrimSpace(c) |
| 53 | if c == "var(--blue)" || c == "var(--muted)" { |
| 54 | return html.EscapeString(c) |
| 55 | } |
| 56 | if strings.HasPrefix(c, "var(--graph-") && strings.HasSuffix(c, ")") { |
| 57 | mid := c[len("var(--graph-") : len(c)-1] |
| 58 | if len(mid) == 1 && mid[0] >= '0' && mid[0] < '0'+byte(PaletteSize) { |
| 59 | return html.EscapeString(c) |
| 60 | } |
| 61 | } |
| 62 | return "var(--muted)" |
| 63 | } |