slidewalk/web/gen_chroma_css.go
2026-07-15 20:14:07 +02:00

65 lines
2 KiB
Go

//go:build ignore
// Command gen_chroma_css regenerates assets/chroma.css, the syntax-highlighting
// stylesheet for fenced code blocks (see internal/parser/markdown.go). Run it
// via `go generate ./web` whenever the chosen Chroma styles should change.
package main
import (
"bytes"
"fmt"
"os"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/styles"
)
// lightStyleName and darkStyleName are the Chroma styles used for syntax
// highlighting in, respectively, light and dark mode. "github"/"github-dark"
// is a matched light/dark pair, mirroring the codebase's own light/dark
// palette in web/assets/style.css.
const (
lightStyleName = "github"
darkStyleName = "github-dark"
)
func main() {
formatter := chromahtml.New(chromahtml.WithClasses(true))
var out bytes.Buffer
out.WriteString("/* Generated by web/gen_chroma_css.go via `go generate ./web` — do not edit by hand. */\n\n")
if err := writeStyle(&out, formatter, lightStyleName); err != nil {
fail(err)
}
out.WriteString("\n@media (prefers-color-scheme: dark) {\n")
if err := writeStyle(&out, formatter, darkStyleName); err != nil {
fail(err)
}
out.WriteString("}\n")
// pre already carries the slide deck's own code background
// (--color-code-bg, matching plain, non-highlighted code blocks); this
// overrides Chroma's own background class so highlighted blocks look
// consistent with the rest of the deck instead of introducing a second
// background color.
out.WriteString("\npre.chroma, pre.chroma code {\n background: var(--color-code-bg);\n}\n")
if err := os.WriteFile("assets/vendor/chroma.css", out.Bytes(), 0o644); err != nil {
fail(err)
}
}
func writeStyle(w *bytes.Buffer, formatter *chromahtml.Formatter, name string) error {
style := styles.Get(name)
if style == nil {
return fmt.Errorf("unknown chroma style %q", name)
}
return formatter.WriteCSS(w, style)
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "gen_chroma_css:", err)
os.Exit(1)
}