internal/web/web.go
323 lines · 9312 bytes
1// Package web holds the server-rendered templates and static assets for the
2// read-only UI. No JavaScript, no build step.
3package web
4
5import (
6 "embed"
7 "fmt"
8 "html/template"
9 "io"
10 "io/fs"
11 "reflect"
12 "slices"
13 "sort"
14 "strconv"
15 "strings"
16 "time"
17)
18
19//go:embed templates/*.html
20var templateFS embed.FS
21
22//go:embed static/style.css
23var StyleCSS []byte
24
25//go:embed static/app.js
26var AppJS []byte
27
28//go:embed static/favicon.svg
29var FaviconSVG []byte
30
31//go:embed static/fonts/*.woff2
32var FontFS embed.FS
33
34//go:embed static/img/*.gif static/img/*.webm static/img/*.mp4
35var ImageFS embed.FS
36
37// StyleVersion and ScriptVersion identify the bytes /static/style.css and
38// /static/app.js serve. The httpd package sets them so a deploy busts
39// browser caches automatically.
40var StyleVersion string
41var ScriptVersion string
42
43// railItem is one destination of the account menu.
44type railItem struct {
45 Href string
46 Icon string
47 Name string
48 Current bool
49 Count int64 // unused by railOptItems; present so "raillink" can read it uniformly
50 Show bool
51}
52
53// railField and railBool read a named field off the page value the
54// layout was given — the same reflection str/field already do for the
55// repo header, duplicated narrowly here rather than exported, since
56// railOptItems is their only other caller.
57func railField(v any, name string) string {
58 rv := reflect.ValueOf(v)
59 for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
60 rv = rv.Elem()
61 }
62 if rv.Kind() != reflect.Struct {
63 return ""
64 }
65 f := rv.FieldByName(name)
66 if !f.IsValid() || f.Kind() != reflect.String {
67 return ""
68 }
69 return f.String()
70}
71
72func railBool(v any, name string) bool {
73 rv := reflect.ValueOf(v)
74 for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
75 rv = rv.Elem()
76 }
77 if rv.Kind() != reflect.Struct {
78 return false
79 }
80 f := rv.FieldByName(name)
81 return f.IsValid() && f.Kind() == reflect.Bool && f.Bool()
82}
83
84// railOptItems is the account menu's "Settings", "Admin" and "Log out"
85// destinations, in the order the menu shows them. v is the
86// page value the layout renders (any page struct that embeds
87// basePage), read by field name since the layout has no single common
88// type for every page.
89func railOptItems(v any) []railItem {
90 tab := railField(v, "Tab")
91 admin := railBool(v, "Admin")
92 return []railItem{
93 {Href: "/settings", Icon: "gear", Name: "Settings", Current: tab == "account", Show: true},
94 {Href: "/admin", Icon: "shield", Name: "Admin", Current: tab == "admin", Show: admin},
95 {Href: "/logout", Icon: "signout", Name: "Log out", Show: true},
96 }
97}
98
99var funcs = template.FuncMap{
100 "styleVersion": func() string { return StyleVersion },
101 "scriptVersion": func() string { return ScriptVersion },
102 "join": strings.Join,
103 "hasStr": slices.Contains[[]string, string],
104 // paragraphs splits plain text on blank lines for safe rich display.
105 "paragraphs": func(s string) []string {
106 var out []string
107 for _, p := range strings.Split(s, "\n\n") {
108 if p = strings.TrimSpace(p); p != "" {
109 out = append(out, p)
110 }
111 }
112 return out
113 },
114 // short abbreviates a commit SHA for display.
115 "short": func(s string) string {
116 if len(s) > 10 {
117 return s[:10]
118 }
119 return s
120 },
121 // dict builds a map for {{template}} calls that need several values.
122 "dict": func(pairs ...any) map[string]any {
123 m := map[string]any{}
124 for i := 0; i+1 < len(pairs); i += 2 {
125 if k, ok := pairs[i].(string); ok {
126 m[k] = pairs[i+1]
127 }
128 }
129 return m
130 },
131 "add": func(a, b int) int { return a + b },
132 "sub": func(a, b int) int { return a - b },
133 // topTab maps a page's Tab to the repo header tab that should read as
134 // current. Everything that browses the tree or its history sits under
135 // code, whose own toolbar carries the log, search, and refs links.
136 "topTab": func(tab string) string {
137 switch tab {
138 case "files", "log", "refs", "search":
139 return "code"
140 case "issues":
141 return "issues"
142 case "merge requests":
143 return "mrs"
144 }
145 return tab
146 },
147 // initial is the avatar letter for a username.
148 "initial": func(s string) string {
149 for _, r := range s {
150 return strings.ToUpper(string(r))
151 }
152 return "?"
153 },
154 "railOptItems": railOptItems,
155 // str is field, narrowed to strings: missing or non-string fields
156 // yield "", which comparisons handle without erroring.
157 "str": func(v any, name string) string {
158 rv := reflect.ValueOf(v)
159 for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
160 rv = rv.Elem()
161 }
162 if rv.Kind() != reflect.Struct {
163 return ""
164 }
165 f := rv.FieldByName(name)
166 if !f.IsValid() || f.Kind() != reflect.String {
167 return ""
168 }
169 return f.String()
170 },
171 // field reads a field the page struct may not have, so the layout can
172 // render repo navigation without every page carrying repo context.
173 // Missing fields yield nil, which templates treat as absent.
174 "field": func(v any, name string) any {
175 rv := reflect.ValueOf(v)
176 for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
177 rv = rv.Elem()
178 }
179 if rv.Kind() != reflect.Struct {
180 return nil
181 }
182 f := rv.FieldByName(name)
183 if !f.IsValid() || !f.CanInterface() {
184 return nil
185 }
186 return f.Interface()
187 },
188 // sigLabel turns a stored signature state into words. The state names
189 // are the CLI's vocabulary and belong in its output; a reader of the
190 // web UI needs to know what is wrong, not what the column is called.
191 "sigLabel": func(state string) string {
192 switch state {
193 case "verified":
194 return "Verified"
195 case "signed_unknown_key":
196 return "Unregistered key"
197 case "signed_email_mismatch":
198 return "Email mismatch"
199 case "signed_key_expired":
200 return "Key expired"
201 case "signed_key_revoked":
202 return "Key revoked"
203 case "bad_signature":
204 return "Bad signature"
205 case "unsigned":
206 return "Unsigned"
207 }
208 return state
209 },
210 // ago renders a time as a coarse relative age, which is what a
211 // listing column is actually read for. The zero time yields "".
212 // slug turns a language name into a CSS class suffix, so the palette
213 // lives in the stylesheet rather than in inline styles the CSP would
214 // have to allow.
215 "slug": func(s string) string {
216 var b strings.Builder
217 for _, r := range strings.ToLower(s) {
218 switch {
219 case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
220 b.WriteRune(r)
221 default:
222 b.WriteByte('-')
223 }
224 }
225 return b.String()
226 },
227 // pct renders a share to one decimal, dropping a trailing ".0".
228 "pct": func(f float64) string {
229 s := strconv.FormatFloat(f, 'f', 1, 64)
230 return strings.TrimSuffix(s, ".0")
231 },
232 "ago": func(t time.Time) string {
233 if t.IsZero() {
234 return ""
235 }
236 d := time.Since(t)
237 if d < 0 {
238 d = 0
239 }
240 plural := func(n int, unit string) string {
241 if n == 1 {
242 return "1 " + unit + " ago"
243 }
244 return strconv.Itoa(n) + " " + unit + "s ago"
245 }
246 switch {
247 case d < time.Minute:
248 return "just now"
249 case d < time.Hour:
250 return plural(int(d/time.Minute), "minute")
251 case d < 24*time.Hour:
252 return plural(int(d/time.Hour), "hour")
253 case d < 30*24*time.Hour:
254 return plural(int(d/(24*time.Hour)), "day")
255 case d < 365*24*time.Hour:
256 return plural(int(d/(30*24*time.Hour)), "month")
257 }
258 return plural(int(d/(365*24*time.Hour)), "year")
259 },
260 // when formats a stored RFC3339 timestamp for display; unparseable
261 // values pass through unchanged.
262 "when": func(s string) string {
263 t, err := time.Parse(time.RFC3339Nano, s)
264 if err != nil {
265 return s
266 }
267 return t.UTC().Format("2006-01-02 15:04 UTC")
268 },
269 // whenT is when for a value that is already a time.Time rather than
270 // a stored string.
271 "whenT": func(t time.Time) string {
272 return t.UTC().Format("2006-01-02 15:04 UTC")
273 },
274}
275
276// pages holds every page template parsed once with the layout, at
277// start-up: a template that does not parse fails the process before it
278// serves anything, rather than the first visit to a rarely-hit page, and
279// a request no longer re-parses the layout (#116).
280var pages = func() map[string]*template.Template {
281 entries, err := fs.ReadDir(templateFS, "templates")
282 if err != nil {
283 panic(err)
284 }
285 m := map[string]*template.Template{}
286 for _, e := range entries {
287 name := e.Name()
288 if name == "layout.html" || !strings.HasSuffix(name, ".html") {
289 continue
290 }
291 layout := template.Must(template.New("layout.html").Funcs(funcs).ParseFS(templateFS, "templates/layout.html"))
292 m[name] = template.Must(layout.ParseFS(templateFS, "templates/"+name))
293 }
294 return m
295}()
296
297// TemplateSource returns a template's raw text, for tests that inspect the
298// markup rather than the rendered output — an accessibility rule about
299// labels and ids is a property of the source, and holds whatever data a
300// page is given.
301func TemplateSource(name string) (string, error) {
302 b, err := templateFS.ReadFile("templates/" + name)
303 return string(b), err
304}
305
306// Pages lists the page template names, for tests that render each one.
307func Pages() []string {
308 names := make([]string, 0, len(pages))
309 for name := range pages {
310 names = append(names, name)
311 }
312 sort.Strings(names)
313 return names
314}
315
316// Render executes the named page template with the shared layout.
317func Render(w io.Writer, page string, data any) error {
318 t, ok := pages[page]
319 if !ok {
320 return fmt.Errorf("no page template %q", page)
321 }
322 return t.ExecuteTemplate(w, "layout", data)
323}