v0.27.0 0039612

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

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 3

Tags 44

↑↓ moveenter openesc close