aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/templates.go
blob: d6b82b8be3d2394247176fd1f3f01d216f4381c2 (plain) (blame)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package app

import (
	"bytes"
	"html/template"
	"io/fs"
	"log"
	"strings"

	. "git.thomasvoss.com/euro-cash.eu/pkg/try"
	"git.thomasvoss.com/euro-cash.eu/pkg/watch"

	"git.thomasvoss.com/euro-cash.eu/src/dbx"
	"git.thomasvoss.com/euro-cash.eu/src/i18n"
)

type templateData struct {
	Debugp     bool
	Printer    i18n.Printer
	Printers   map[string]i18n.Printer
	Code, Type string
	Mintages   dbx.MintageData
	Countries  []country
}

var (
	notFoundTmpl *template.Template
	errorTmpl    *template.Template
	templates    map[string]*template.Template
	funcmap      = map[string]any{
		"ifElse":                     ifElse,
		"locales":                    i18n.Locales,
		"map":                        templateMakeMap,
		"safe":                       asHTML,
		"toUpper":                    strings.ToUpper,
		"tuple":                      templateMakeTuple,
		"makeHeaderWithTranslations": makeHeaderWithTranslations,
	}
)

func BuildTemplates(dir fs.FS) {
	ents := Try2(fs.ReadDir(dir, "."))
	notFoundTmpl = buildTemplate(dir, "-404")
	errorTmpl = buildTemplate(dir, "-error")
	templates = make(map[string]*template.Template, len(ents))

	for _, e := range ents {
		name := e.Name()
		buildAndSetTemplate(dir, name)
		if Debugp {
			go watch.FileFS(dir, name, func() {
				defer func() {
					if p := recover(); p != nil {
						log.Print(p)
					}
				}()

				buildAndSetTemplate(dir, name)
				log.Printf("Template ‘%s’ updated\n", name)
			})
		}
	}
}

func buildAndSetTemplate(dir fs.FS, name string) {
	path := "/"
	name = strings.TrimSuffix(name, ".html.tmpl")
	switch {
	case name[0] == '-':
		return
	case name != "index":
		path += strings.ReplaceAll(name, "-", "/")
	}
	templates[path] = buildTemplate(dir, name)
}

func buildTemplate(dir fs.FS, name string) *template.Template {
	names := [...]string{"-base", "-navbar", name}
	for i, s := range names {
		names[i] = s + ".html.tmpl"
	}
	t := template.New("-base.html.tmpl").Funcs(funcmap)
	t = t.Funcs(includeIfExists(t))
	return template.Must(t.ParseFS(dir, names[:]...))
}

func asHTML(s string) template.HTML {
	return template.HTML(s)
}

func templateMakeTuple(args ...any) []any {
	return args
}

func templateMakeMap(args ...any) map[string]any {
	if len(args)&1 != 0 {
		/* TODO: Handle error */
		args = args[:len(args)-1]
	}
	m := make(map[string]any, len(args)/2)
	for i := 0; i < len(args); i += 2 {
		k, ok := args[i].(string)
		if !ok {
			/* TODO: Handle error */
			continue
		}
		m[k] = args[i+1]
	}
	return m
}

func includeIfExists(tmpl *template.Template) template.FuncMap {
	return template.FuncMap{
		"includeIfExists": func(name string, data any) (template.HTML, error) {
			t := tmpl.Lookup(name)
			if t == nil {
				return "", nil
			}
			var buf bytes.Buffer
			err := t.Execute(&buf, data)
			return template.HTML(buf.String()), err
		},
	}
}

func ifElse(b bool, x, y any) any {
	if b {
		return x
	}
	return y
}

func makeHeaderWithTranslations(tag string, text string,
	translations ...[]any) template.HTML {
	var bob strings.Builder
	bob.WriteByte('<')
	bob.WriteString(tag)
	bob.WriteByte('>')
	bob.WriteString(text)

	/* TODO: Assert that the pairs are [2]string */
	for _, pair := range translations {
		if text == pair[1] {
			continue
		}
		bob.WriteString(`<br><span class="translation"`)
		if pair[0].(string) != "" {
			bob.WriteString(` lang="`)
			bob.WriteString(pair[0].(string))
			bob.WriteString(`">`)
		} else {
			bob.WriteByte('>')
		}
		bob.WriteString(pair[1].(string))
		bob.WriteString("</span>")
	}

	bob.WriteString("</")
	bob.WriteString(tag)
	bob.WriteByte('>')
	return template.HTML(bob.String())
}

func (td templateData) Get(fmt string, args ...map[string]any) template.HTML {
	return template.HTML(td.Printer.Get(fmt, args...))
}

func (td templateData) GetN(fmtS, fmtP string, n int, args ...map[string]any) template.HTML {
	return template.HTML(td.Printer.GetN(fmtS, fmtP, n, args...))
}