aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/templates.go
blob: 6a43fcbfea94bf2753f7261417d5a64443cd9155 (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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package app

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

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

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

type templateData struct {
	Debugp               bool
	Printer              i18n.Printer
	Printers             map[string]i18n.Printer
	Code, Type, FilterBy string
	Year                 int
	CountryMintages      CountryMintageTable
	YearMintages         YearMintageTable
	Countries            []country
}

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

func BuildTemplates(dir fs.FS) {
	buildTemplates(dir, Debugp)
}

func buildTemplates(dir fs.FS, debugp bool) {
	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 {
		if e.IsDir() {
			continue
		}
		name := e.Name()
		buildAndSetTemplate(dir, name)
		if debugp {
			go watch.FileFS(dir, name, func() {
				defer func() {
					if p := recover(); p != nil {
						log.Println(p)
					}
				}()

				if strings.HasPrefix(name, "-") {
					buildTemplates(dir, false)
					log.Println("All templates updated")
				} else {
					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"
	}
	return template.Must(template.
		New("-base.html.tmpl").
		Funcs(funcmap).
		ParseFS(dir, names[:]...))
}

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

func toString(s template.HTML) string {
	return string(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 evenp(n int) bool {
	return n&1 == 0
}

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

func withTranslation(tag, bcp, text string, trans template.HTML,
	spanAttrs ...string) template.HTML {
	name, _, _ := strings.Cut(tag, " ")

	var bob strings.Builder
	bob.WriteByte('<')
	bob.WriteString(tag)
	bob.WriteString(`><span lang="`)
	bob.WriteString(bcp)
	bob.WriteString(`">`)
	bob.WriteString(text)
	bob.WriteString("</span>")

	if text != string(trans) {
		bob.WriteString(`<br><span class="translation"`)
		for _, s := range spanAttrs {
			bob.WriteByte(' ')
			bob.WriteString(s)
		}
		bob.WriteByte('>')
		bob.WriteString(string(trans))
		bob.WriteString("</span>")
	}

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

func withTranslations(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 plus1(x int) int {
	return x + 1
}

func years() []int {
	sy, ey := 1999, time.Now().Year()
	xs := make([]int, ey-sy+1)
	for i := range xs {
		xs[i] = sy + i
	}
	return xs
}

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

func (td templateData) GetC(fmt, ctx string, args ...map[string]any) template.HTML {
	return template.HTML(td.Printer.GetC(fmt, ctx, 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...))
}