v0.21.0 ef38ad0

assets.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6	"crypto/sha256"
7	"embed"
8	"encoding/hex"
9	"encoding/json"
10	"errors"
11	"io/fs"
12	"net/http"
13	"path"
14	"sort"
15	"strings"
16)
17
18//go:embed static
19var staticFS embed.FS
20
21// StaticPrefix is where the embedded assets are served.
22const StaticPrefix = "/-/static/"
23
24// Assets are the URLs of the assets a page loads. Their names carry a hash of
25// the content, so they can be cached for ever.
26type Assets struct {
27	CSS, HTMX, Live, SSE, App, Files, Passkey, Log, MR, Icon string
28	// Manifest is the web app manifest (install on a phone's home screen),
29	// AppleIcon the home screen icon iOS reads from a link instead.
30	Manifest, AppleIcon string
31	// Font is the UI font, preloaded by every page.
32	Font string
33	// Rules is the speculation rules file named by the Speculation-Rules header.
34	Rules string
35}
36
37// asset is one embedded file under its content-hashed name.
38type asset struct {
39	body []byte
40	typ  string
41	// gz is the gzip form of body, compressed once at load; nil when the type
42	// is already compressed or gzip does not make the body smaller.
43	gz []byte
44}
45
46// assetSet is the embedded files by hashed URL path (under StaticPrefix).
47type assetSet struct {
48	byName map[string]asset
49	urls   Assets
50	sw     serviceWorker
51}
52
53// scripts are the JavaScript files of the page, in embedded static/js: the
54// file to serve, as it is named in Assets.
55var scripts = []struct {
56	file string
57	set  func(*Assets, string)
58}{
59	{"htmx.min.js", func(a *Assets, u string) { a.HTMX = u }},
60	{"hx-live.min.js", func(a *Assets, u string) { a.Live = u }},
61	{"hx-sse.min.js", func(a *Assets, u string) { a.SSE = u }},
62	{"ermite.js", func(a *Assets, u string) { a.App = u }},
63	{"files.js", func(a *Assets, u string) { a.Files = u }},
64	{"passkey.js", func(a *Assets, u string) { a.Passkey = u }},
65	{"log.js", func(a *Assets, u string) { a.Log = u }},
66	{"mr.js", func(a *Assets, u string) { a.MR = u }},
67}
68
69// sheetAssets are the files the stylesheet references as url(<dir>/<file>):
70// fonts and icons (pages hold no inline SVG; icons are CSS masks).
71var sheetAssets = []struct{ glob, typ string }{
72	{"static/fonts/*.woff2", "font/woff2"},
73	{"static/icons/*.svg", "image/svg+xml"},
74}
75
76// loadAssets hashes the embedded files. The stylesheet is the concatenation
77// of static/css/*.css in name order; its url(<dir>/<file>) references become
78// the hashed URLs of the files of sheetAssets.
79func loadAssets() (*assetSet, error) {
80	s := &assetSet{byName: map[string]asset{}}
81	put := func(dir, file string, body []byte, typ string) string {
82		sum := sha256.Sum256(body)
83		ext := path.Ext(file)
84		name := dir + "/" + strings.TrimSuffix(file, ext) + "." + hex.EncodeToString(sum[:6]) + ext
85		a := asset{body: body, typ: typ}
86		if compressible(typ) {
87			if z, err := gzipBest(body); err == nil && len(z) < len(body) {
88				a.gz = z
89			}
90		}
91		s.byName[name] = a
92		return StaticPrefix + name
93	}
94
95	var refs []string
96	for _, sa := range sheetAssets {
97		files, err := fs.Glob(staticFS, sa.glob)
98		if err != nil {
99			return nil, err
100		}
101		for _, f := range files {
102			b, err := staticFS.ReadFile(f)
103			if err != nil {
104				return nil, err
105			}
106			dir := path.Base(path.Dir(f))
107			u := put(dir, path.Base(f), b, sa.typ)
108			refs = append(refs, "url("+dir+"/"+path.Base(f)+")", "url("+u+")")
109			if f == "static/fonts/atkinson-next.woff2" {
110				s.urls.Font = u
111			}
112		}
113	}
114
115	files, err := fs.Glob(staticFS, "static/css/*.css")
116	if err != nil {
117		return nil, err
118	}
119	sort.Strings(files)
120	var css strings.Builder
121	for _, f := range files {
122		b, err := staticFS.ReadFile(f)
123		if err != nil {
124			return nil, err
125		}
126		css.WriteString("/* " + path.Base(f) + " */\n")
127		css.Write(b)
128	}
129	if s.urls.Font == "" {
130		return nil, errors.New("web: the UI font static/fonts/atkinson-next.woff2 is missing")
131	}
132	sheet := strings.NewReplacer(refs...).Replace(css.String())
133	s.urls.CSS = put("css", "ermite.css", []byte(sheet), "text/css; charset=utf-8")
134
135	rules, err := staticFS.ReadFile("static/rules.json")
136	if err != nil {
137		return nil, err
138	}
139	s.urls.Rules = put("rules", "rules.json", rules, "application/speculationrules+json")
140
141	for _, sc := range scripts {
142		b, err := staticFS.ReadFile("static/js/" + sc.file)
143		if err != nil {
144			return nil, err
145		}
146		sc.set(&s.urls, put("js", sc.file, b, "text/javascript; charset=utf-8"))
147	}
148
149	// The favicon is the brand picture of the header.
150	icon, err := staticFS.ReadFile("static/icons/brand.svg")
151	if err != nil {
152		return nil, err
153	}
154	s.urls.Icon = put("img", "icon.svg", icon, "image/svg+xml")
155
156	if err := s.loadApp(put); err != nil {
157		return nil, err
158	}
159	sw, err := loadServiceWorker()
160	if err != nil {
161		return nil, err
162	}
163	s.sw = sw
164	return s, nil
165}
166
167// appIcons are the PNG icons of the installed app (static/app), in the
168// manifest; purpose "maskable" has the picture inside the safe zone on a
169// full-bleed background, for launchers that crop to a circle or a squircle.
170var appIcons = []struct{ file, sizes, purpose string }{
171	{"icon-192.png", "192x192", "any"},
172	{"icon-512.png", "512x512", "any"},
173	{"icon-maskable-512.png", "512x512", "maskable"},
174}
175
176// webManifest is the shape of the web app manifest: what a browser asks for to
177// offer "install" / "add to home screen", and the id and description of the
178// richer install dialog.
179type webManifest struct {
180	// ID is the identity of the app, independent of the (hashed) URL of the
181	// manifest and of start_url.
182	ID              string         `json:"id"`
183	Name            string         `json:"name"`
184	ShortName       string         `json:"short_name"`
185	Description     string         `json:"description"`
186	StartURL        string         `json:"start_url"`
187	Scope           string         `json:"scope"`
188	Display         string         `json:"display"`
189	BackgroundColor string         `json:"background_color"`
190	ThemeColor      string         `json:"theme_color"`
191	Icons           []manifestIcon `json:"icons"`
192}
193
194type manifestIcon struct {
195	Src     string `json:"src"`
196	Sizes   string `json:"sizes"`
197	Type    string `json:"type"`
198	Purpose string `json:"purpose"`
199}
200
201// appColor is the dark canvas: the splash screen and the bar of the installed
202// app (the pages follow the system theme; the manifest takes one colour).
203const appColor = "#050505"
204
205// loadApp adds the app icons and the manifest, which names them by their
206// hashed URLs.
207func (s *assetSet) loadApp(put func(dir, name string, b []byte, typ string) string) error {
208	m := webManifest{
209		ID: "/", Name: "ermite", ShortName: "ermite", StartURL: "/", Scope: "/", Display: "standalone",
210		Description:     "Self-hosted Git forge: browse code, review merge requests and follow CI.",
211		BackgroundColor: appColor, ThemeColor: appColor,
212	}
213	for _, ic := range appIcons {
214		b, err := staticFS.ReadFile("static/app/" + ic.file)
215		if err != nil {
216			return err
217		}
218		m.Icons = append(m.Icons, manifestIcon{Src: put("app", ic.file, b, "image/png"), Sizes: ic.sizes, Type: "image/png", Purpose: ic.purpose})
219	}
220	apple, err := staticFS.ReadFile("static/app/apple-touch-icon.png")
221	if err != nil {
222		return err
223	}
224	s.urls.AppleIcon = put("app", "apple-touch-icon.png", apple, "image/png")
225	b, err := json.Marshal(m)
226	if err != nil {
227		return err
228	}
229	s.urls.Manifest = put("app", "manifest.webmanifest", b, "application/manifest+json")
230	return nil
231}
232
233// serve answers GET /-/static/<hashed name>. A name that does not match a
234// current asset is a 404, so a stale hash never serves the wrong content.
235func (s *assetSet) serve(w http.ResponseWriter, r *http.Request) {
236	a, ok := s.byName[strings.TrimPrefix(r.URL.Path, StaticPrefix)]
237	if !ok {
238		http.NotFound(w, r)
239		return
240	}
241	h := w.Header()
242	h.Set("Content-Type", a.typ)
243	h.Set("Cache-Control", "public, max-age=31536000, immutable")
244	body := a.body
245	if a.gz != nil {
246		addVary(h, "Accept-Encoding")
247		if acceptsGzip(r.Header) {
248			body = a.gz
249			h.Set("Content-Encoding", "gzip")
250		}
251	}
252	h.Set("Content-Length", itoa(len(body)))
253	if r.Method != http.MethodHead {
254		_, _ = w.Write(body)
255	}
256}
257
258// compressible tells whether a content type is worth gzip: text and
259// structured text. Fonts (woff2) and raster images are compressed already.
260func compressible(typ string) bool {
261	mt, _, _ := strings.Cut(typ, ";")
262	mt = strings.TrimSpace(strings.ToLower(mt))
263	return strings.HasPrefix(mt, "text/") || mt == "image/svg+xml" ||
264		mt == "application/javascript" || strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "/json")
265}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 2

Tags 45

↑↓ moveenter openesc close