template.go 8.6 KiB raw
1
package main
2
3
import (
4
	"embed"
5
	"fmt"
6
	"html"
7
	"html/template"
8
	"io"
9
	"path"
10
	"regexp"
11
	"strings"
12
	"time"
13
)
14
15
//go:embed templates/*.html
16
var templateFS embed.FS
17
18
//go:embed static/style.css
19
var cssContent []byte
20
21
//go:embed static/radiant.svg
22
var logoContent []byte
23
24
//go:embed static/fonts/*
25
var fontsFS embed.FS
26
27
//go:embed static/avatars/*
28
var avatarsFS embed.FS
29
30
type templateSet struct {
31
	templates map[string]*template.Template
32
}
33
34
var funcMap = template.FuncMap{
35
	"shortHash": func(h string) string {
36
		if len(h) > 8 {
37
			return h[:8]
38
		}
39
		return h
40
	},
41
	"timeAgo": func(t time.Time) template.HTML {
42
		d := time.Since(t)
43
		var ago string
44
		switch {
45
		case d < time.Minute:
46
			ago = "just now"
47
		case d < time.Hour:
48
			m := int(d.Minutes())
49
			if m == 1 {
50
				ago = "1 minute"
51
			} else {
52
				ago = fmt.Sprintf("%d minutes", m)
53
			}
54
		case d < 24*time.Hour:
55
			h := int(d.Hours())
56
			if h == 1 {
57
				ago = "1 hour"
58
			} else {
59
				ago = fmt.Sprintf("%d hours", h)
60
			}
61
		case d < 30*24*time.Hour:
62
			days := int(d.Hours() / 24)
63
			if days == 1 {
64
				ago = "1 day"
65
			} else {
66
				ago = fmt.Sprintf("%d days", days)
67
			}
68
		case d < 365*24*time.Hour:
69
			months := int(d.Hours() / 24 / 30)
70
			if months == 1 {
71
				ago = "1 month"
72
			} else {
73
				ago = fmt.Sprintf("%d months", months)
74
			}
75
		default:
76
			years := int(d.Hours() / 24 / 365)
77
			if years == 1 {
78
				ago = "1 year"
79
			} else {
80
				ago = fmt.Sprintf("%d years", years)
81
			}
82
		}
83
		full := t.Format("2006-01-02 15:04:05 -0700")
84
		return template.HTML(fmt.Sprintf(`<time title="%s">%s</time>`, full, ago))
85
	},
86
	"formatDate": func(t time.Time) string {
87
		return t.Format("2006-01-02 15:04:05 -0700")
88
	},
89
	"add":          func(a, b int) int { return a + b },
90
	"diffFileName": diffFileName,
91
	"statusLabel": func(s string) string {
92
		switch s {
93
		case "A":
94
			return "added"
95
		case "D":
96
			return "deleted"
97
		case "M":
98
			return "modified"
99
		case "R":
100
			return "renamed"
101
		}
102
		return s
103
	},
104
	"formatSize": func(size int64) string {
105
		switch {
106
		case size < 1024:
107
			return fmt.Sprintf("%d B", size)
108
		case size < 1024*1024:
109
			return fmt.Sprintf("%.1f KiB", float64(size)/1024)
110
		default:
111
			return fmt.Sprintf("%.1f MiB", float64(size)/(1024*1024))
112
		}
113
	},
114
	"diffBar": func(added, deleted int) template.HTML {
115
		total := added + deleted
116
		if total == 0 {
117
			return ""
118
		}
119
		const maxBlocks = 5
120
		blocks := maxBlocks
121
		if total < blocks {
122
			blocks = total
123
		}
124
		addBlocks := 0
125
		if total > 0 {
126
			addBlocks = (added*blocks + total - 1) / total
127
		}
128
		if addBlocks > blocks {
129
			addBlocks = blocks
130
		}
131
		delBlocks := blocks - addBlocks
132
		var b strings.Builder
133
		b.WriteString(`<span class="diffstat-bar">`)
134
		for i := 0; i < addBlocks; i++ {
135
			b.WriteString(`<span class="bar-add"></span>`)
136
		}
137
		for i := 0; i < delBlocks; i++ {
138
			b.WriteString(`<span class="bar-del"></span>`)
139
		}
140
		for i := addBlocks + delBlocks; i < maxBlocks; i++ {
141
			b.WriteString(`<span class="bar-neutral"></span>`)
142
		}
143
		b.WriteString(`</span>`)
144
		return template.HTML(b.String())
145
	},
146
	"highlightLines": highlightLines,
147
	"parentPath": func(p string) string {
148
		dir := path.Dir(p)
149
		if dir == "." {
150
			return ""
151
		}
152
		return dir
153
	},
154
	"indent": func(depth int) string {
155
		if depth == 0 {
156
			return ""
157
		}
158
		return fmt.Sprintf("padding-left: %grem", float64(depth)*1.2)
159
	},
160
	"formatBody": func(s string) template.HTML {
161
		s = strings.TrimSpace(s)
162
		if s == "" {
163
			return ""
164
		}
165
		var b strings.Builder
166
		// Split into alternating prose / fenced-code-block segments.
167
		for s != "" {
168
			// Find the next opening fence.
169
			openIdx := strings.Index(s, "```")
170
			if openIdx < 0 {
171
				formatParagraphs(&b, s)
172
				break
173
			}
174
			// Prose before the fence.
175
			if openIdx > 0 {
176
				formatParagraphs(&b, s[:openIdx])
177
			}
178
			// Skip the opening ``` and any language tag on the same line.
179
			rest := s[openIdx+3:]
180
			if nl := strings.Index(rest, "\n"); nl >= 0 {
181
				rest = rest[nl+1:]
182
			} else {
183
				// ``` at end of input with nothing after — treat as prose.
184
				formatParagraphs(&b, s[openIdx:])
185
				break
186
			}
187
			// Find the closing fence.
188
			closeIdx := strings.Index(rest, "```")
189
			var code string
190
			if closeIdx < 0 {
191
				code = rest
192
				s = ""
193
			} else {
194
				code = rest[:closeIdx]
195
				s = rest[closeIdx+3:]
196
			}
197
			code = strings.TrimRight(code, "\n")
198
			b.WriteString("<pre><code>")
199
			b.WriteString(html.EscapeString(code))
200
			b.WriteString("</code></pre>")
201
		}
202
		return template.HTML(b.String())
203
	},
204
	"discussionPath": func(baseURL, repo string) string {
205
		if repo == "" {
206
			return baseURL + "/discussions"
207
		}
208
		return baseURL + "/" + repo + "/discussions"
209
	},
210
	"autolink": func(s string) template.HTML {
211
		var b strings.Builder
212
		last := 0
213
		for _, loc := range urlRe.FindAllStringIndex(s, -1) {
214
			// Strip trailing punctuation.
215
			end := loc[1]
216
			for end > loc[0] && strings.ContainsRune(".,;:!?)]", rune(s[end-1])) {
217
				end--
218
			}
219
			b.WriteString(html.EscapeString(s[last:loc[0]]))
220
			u := s[loc[0]:end]
221
			b.WriteString(`<a href="`)
222
			b.WriteString(html.EscapeString(u))
223
			b.WriteString(`">`)
224
			b.WriteString(html.EscapeString(u))
225
			b.WriteString(`</a>`)
226
			last = end
227
		}
228
		b.WriteString(html.EscapeString(s[last:]))
229
		return template.HTML(b.String())
230
	},
231
}
232
233
var urlRe = regexp.MustCompile(`https?://[^\s<>"'` + "`" + `\x00-\x1f]+`)
234
235
// inlineRe matches (in order): backtick code, angle-bracket links, bare URLs, or *italic*.
236
var inlineRe = regexp.MustCompile("`" + `([^` + "`" + `\n]+)` + "`" +
237
	`|<(https?://[^\s<>]+)>` +
238
	`|(https?://[^\s<>"'` + "`" + `\x00-\x1f]+)` +
239
	`|\*([^\s*][^*]*[^\s*])\*|\*([^\s*])\*`)
240
241
// formatParagraphs splits prose text on blank lines and writes <p> elements
242
// with inline formatting into b.
243
func formatParagraphs(b *strings.Builder, s string) {
244
	for _, p := range strings.Split(s, "\n\n") {
245
		p = strings.TrimSpace(p)
246
		if p == "" {
247
			continue
248
		}
249
		b.WriteString("<p>")
250
		b.WriteString(formatInline(p))
251
		b.WriteString("</p>")
252
	}
253
}
254
255
// formatInline applies inline formatting to a paragraph of raw text.
256
// It handles backtick `code`, *italic*, <https://...> links, and bare URLs.
257
func formatInline(p string) string {
258
	var b strings.Builder
259
	last := 0
260
	for _, m := range inlineRe.FindAllStringSubmatchIndex(p, -1) {
261
		start, end := m[0], m[1]
262
		b.WriteString(html.EscapeString(p[last:start]))
263
264
		switch {
265
		case m[2] >= 0: // backtick code: group 1
266
			code := p[m[2]:m[3]]
267
			b.WriteString("<code>")
268
			b.WriteString(html.EscapeString(code))
269
			b.WriteString("</code>")
270
		case m[4] >= 0: // angle-bracket link: group 2
271
			u := p[m[4]:m[5]]
272
			b.WriteString(`<a href="`)
273
			b.WriteString(html.EscapeString(u))
274
			b.WriteString(`">`)
275
			b.WriteString(html.EscapeString(u))
276
			b.WriteString("</a>")
277
		case m[6] >= 0: // bare URL: group 3
278
			// Strip trailing punctuation.
279
			urlEnd := m[7]
280
			for urlEnd > m[6] && strings.ContainsRune(".,;:!?)]", rune(p[urlEnd-1])) {
281
				urlEnd--
282
			}
283
			u := p[m[6]:urlEnd]
284
			b.WriteString(`<a href="`)
285
			b.WriteString(html.EscapeString(u))
286
			b.WriteString(`">`)
287
			b.WriteString(html.EscapeString(u))
288
			b.WriteString("</a>")
289
			// Anything between stripped punctuation and regex end is plain text.
290
			b.WriteString(html.EscapeString(p[urlEnd:end]))
291
		case m[8] >= 0: // italic (multi-char): group 4
292
			inner := p[m[8]:m[9]]
293
			b.WriteString("<em>")
294
			b.WriteString(html.EscapeString(inner))
295
			b.WriteString("</em>")
296
		case m[10] >= 0: // italic (single-char): group 5
297
			inner := p[m[10]:m[11]]
298
			b.WriteString("<em>")
299
			b.WriteString(html.EscapeString(inner))
300
			b.WriteString("</em>")
301
		}
302
		last = end
303
	}
304
	b.WriteString(html.EscapeString(p[last:]))
305
	return b.String()
306
}
307
308
func loadTemplates() (*templateSet, error) {
309
	layoutContent, err := templateFS.ReadFile("templates/layout.html")
310
	if err != nil {
311
		return nil, fmt.Errorf("read layout: %w", err)
312
	}
313
314
	pages := []string{"index", "home", "log", "commit", "refs", "error", "discussions", "discussion", "discussion_new", "login"}
315
	ts := &templateSet{
316
		templates: make(map[string]*template.Template, len(pages)),
317
	}
318
319
	for _, page := range pages {
320
		t := template.New("layout").Funcs(funcMap)
321
		t, err = t.Parse(string(layoutContent))
322
		if err != nil {
323
			return nil, fmt.Errorf("parse layout: %w", err)
324
		}
325
326
		pageContent, err := templateFS.ReadFile(fmt.Sprintf("templates/%s.html", page))
327
		if err != nil {
328
			return nil, fmt.Errorf("read %s: %w", page, err)
329
		}
330
331
		t, err = t.Parse(string(pageContent))
332
		if err != nil {
333
			return nil, fmt.Errorf("parse %s: %w", page, err)
334
		}
335
336
		ts.templates[page] = t
337
	}
338
339
	return ts, nil
340
}
341
342
func (ts *templateSet) render(w io.Writer, name string, data any) {
343
	t, ok := ts.templates[name]
344
	if !ok {
345
		fmt.Fprintf(w, "template %q not found", name)
346
		return
347
	}
348
	if err := t.Execute(w, data); err != nil {
349
		fmt.Fprintf(w, "template error: %v", err)
350
	}
351
}