summaryrefslogtreecommitdiff
path: root/internal/generator/themes.go
blob: e7fd3a32e13c71217413716f14e614b7b9419093 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package generator

import (
	"log"

	"codeberg.org/snonux/snonux/internal/generator/templates"
)

// fallbackThemeName is returned by getTheme when an unknown name is requested,
// matching the previous behaviour of the hand-maintained themeRegistry map.
const fallbackThemeName = "neon"

// themeSet caches the list of theme names available in the embedded template FS
// so ListThemes and getTheme do not re-read the directory on every call.
var themeSet = loadThemeSet()

func loadThemeSet() map[string]struct{} {
	names, err := templates.ThemeNames()
	if err != nil {
		// At build time the embed //go:embed directive guarantees the FS is
		// populated, so this should never happen; log and continue with an
		// empty set so getTheme() falls back cleanly.
		log.Printf("warning: could not enumerate themes from embedded FS: %v", err)
		return map[string]struct{}{}
	}

	out := make(map[string]struct{}, len(names))
	for _, n := range names {
		out[n] = struct{}{}
	}
	return out
}

// getTheme returns the HTML template body for the given theme name, loading it
// from the embedded template FS. It falls back to the neon theme if the name
// is unknown (preserving previous behaviour of the hand-maintained map).
func getTheme(name string) string {
	if _, ok := themeSet[name]; !ok {
		name = fallbackThemeName
	}

	body, err := templates.Theme(name)
	if err != nil {
		// Last-resort fallback: try neon. If that also fails, return an empty
		// string; template.Parse will then produce a diagnostic error.
		if body, err = templates.Theme(fallbackThemeName); err != nil {
			log.Printf("warning: could not load fallback theme %q: %v", fallbackThemeName, err)
			return ""
		}
	}

	return body
}

// ListThemes returns a sorted list of all available theme names.
func ListThemes() []string {
	names, err := templates.ThemeNames()
	if err != nil {
		log.Printf("warning: could not list themes from embedded FS: %v", err)
		return nil
	}
	return names
}