internal/web/web.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/web/web.go

326 lines · 9551 bytes

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