1package pages
2
3import (
4 "bytes"
5 "context"
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "html"
12 "html/template"
13 "log"
14 "math"
15 "net/url"
16 "path/filepath"
17 "reflect"
18 "strings"
19 "time"
20
21 "github.com/alecthomas/chroma/v2"
22 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
23 "github.com/alecthomas/chroma/v2/lexers"
24 "github.com/alecthomas/chroma/v2/styles"
25 "github.com/bluesky-social/indigo/atproto/syntax"
26 "github.com/dustin/go-humanize"
27 "github.com/go-enry/go-enry/v2"
28 "github.com/yuin/goldmark"
29 "tangled.org/core/appview/filetree"
30 "tangled.org/core/appview/pages/markup"
31 "tangled.org/core/crypto"
32)
33
34func (p *Pages) funcMap() template.FuncMap {
35 return template.FuncMap{
36 "split": func(s string) []string {
37 return strings.Split(s, "\n")
38 },
39 "trimPrefix": func(s, prefix string) string {
40 return strings.TrimPrefix(s, prefix)
41 },
42 "join": func(elems []string, sep string) string {
43 return strings.Join(elems, sep)
44 },
45 "contains": func(s string, target string) bool {
46 return strings.Contains(s, target)
47 },
48 "stripPort": func(hostname string) string {
49 if strings.Contains(hostname, ":") {
50 return strings.Split(hostname, ":")[0]
51 }
52 return hostname
53 },
54 "mapContains": func(m any, key any) bool {
55 mapValue := reflect.ValueOf(m)
56 if mapValue.Kind() != reflect.Map {
57 return false
58 }
59 keyValue := reflect.ValueOf(key)
60 return mapValue.MapIndex(keyValue).IsValid()
61 },
62 "resolve": func(s string) string {
63 identity, err := p.resolver.ResolveIdent(context.Background(), s)
64
65 if err != nil {
66 return s
67 }
68
69 if identity.Handle.IsInvalidHandle() {
70 return "handle.invalid"
71 }
72
73 return identity.Handle.String()
74 },
75 "truncateAt30": func(s string) string {
76 if len(s) <= 30 {
77 return s
78 }
79 return s[:30] + "…"
80 },
81 "splitOn": func(s, sep string) []string {
82 return strings.Split(s, sep)
83 },
84 "string": func(v any) string {
85 return fmt.Sprint(v)
86 },
87 "int64": func(a int) int64 {
88 return int64(a)
89 },
90 "add": func(a, b int) int {
91 return a + b
92 },
93 "now": func() time.Time {
94 return time.Now()
95 },
96 // the absolute state of go templates
97 "add64": func(a, b int64) int64 {
98 return a + b
99 },
100 "sub": func(a, b int) int {
101 return a - b
102 },
103 "f64": func(a int) float64 {
104 return float64(a)
105 },
106 "addf64": func(a, b float64) float64 {
107 return a + b
108 },
109 "subf64": func(a, b float64) float64 {
110 return a - b
111 },
112 "mulf64": func(a, b float64) float64 {
113 return a * b
114 },
115 "divf64": func(a, b float64) float64 {
116 if b == 0 {
117 return 0
118 }
119 return a / b
120 },
121 "negf64": func(a float64) float64 {
122 return -a
123 },
124 "cond": func(cond any, a, b string) string {
125 if cond == nil {
126 return b
127 }
128
129 if boolean, ok := cond.(bool); boolean && ok {
130 return a
131 }
132
133 return b
134 },
135 "didOrHandle": func(did, handle string) string {
136 if handle != "" && handle != syntax.HandleInvalid.String() {
137 return handle
138 } else {
139 return did
140 }
141 },
142 "assoc": func(values ...string) ([][]string, error) {
143 if len(values)%2 != 0 {
144 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
145 }
146 pairs := make([][]string, 0)
147 for i := 0; i < len(values); i += 2 {
148 pairs = append(pairs, []string{values[i], values[i+1]})
149 }
150 return pairs, nil
151 },
152 "append": func(s []string, values ...string) []string {
153 s = append(s, values...)
154 return s
155 },
156 "commaFmt": humanize.Comma,
157 "relTimeFmt": humanize.Time,
158 "shortRelTimeFmt": func(t time.Time) string {
159 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{
160 {D: time.Second, Format: "now", DivBy: time.Second},
161 {D: 2 * time.Second, Format: "1s %s", DivBy: 1},
162 {D: time.Minute, Format: "%ds %s", DivBy: time.Second},
163 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1},
164 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute},
165 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1},
166 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour},
167 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
168 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day},
169 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week},
170 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month},
171 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1},
172 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1},
173 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year},
174 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
175 })
176 },
177 "longTimeFmt": func(t time.Time) string {
178 return t.Format("Jan 2, 2006, 3:04 PM MST")
179 },
180 "iso8601DateTimeFmt": func(t time.Time) string {
181 return t.Format("2006-01-02T15:04:05-07:00")
182 },
183 "iso8601DurationFmt": func(duration time.Duration) string {
184 days := int64(duration.Hours() / 24)
185 hours := int64(math.Mod(duration.Hours(), 24))
186 minutes := int64(math.Mod(duration.Minutes(), 60))
187 seconds := int64(math.Mod(duration.Seconds(), 60))
188 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
189 },
190 "durationFmt": func(duration time.Duration) string {
191 return durationFmt(duration, [4]string{"d", "hr", "min", "s"})
192 },
193 "longDurationFmt": func(duration time.Duration) string {
194 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
195 },
196 "byteFmt": humanize.Bytes,
197 "length": func(slice any) int {
198 v := reflect.ValueOf(slice)
199 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
200 return v.Len()
201 }
202 return 0
203 },
204 "splitN": func(s, sep string, n int) []string {
205 return strings.SplitN(s, sep, n)
206 },
207 "escapeHtml": func(s string) template.HTML {
208 if s == "" {
209 return template.HTML("<br>")
210 }
211 return template.HTML(s)
212 },
213 "unescapeHtml": func(s string) string {
214 return html.UnescapeString(s)
215 },
216 "nl2br": func(text string) template.HTML {
217 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
218 },
219 "unwrapText": func(text string) string {
220 paragraphs := strings.Split(text, "\n\n")
221
222 for i, p := range paragraphs {
223 lines := strings.Split(p, "\n")
224 paragraphs[i] = strings.Join(lines, " ")
225 }
226
227 return strings.Join(paragraphs, "\n\n")
228 },
229 "sequence": func(n int) []struct{} {
230 return make([]struct{}, n)
231 },
232 // take atmost N items from this slice
233 "take": func(slice any, n int) any {
234 v := reflect.ValueOf(slice)
235 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
236 return nil
237 }
238 if v.Len() == 0 {
239 return nil
240 }
241 return v.Slice(0, min(n, v.Len())).Interface()
242 },
243 "markdown": func(text string) template.HTML {
244 p.rctx.RendererType = markup.RendererTypeDefault
245 htmlString := p.rctx.RenderMarkdown(text)
246 sanitized := p.rctx.SanitizeDefault(htmlString)
247 return template.HTML(sanitized)
248 },
249 "description": func(text string) template.HTML {
250 p.rctx.RendererType = markup.RendererTypeDefault
251 htmlString := p.rctx.RenderMarkdownWith(text, goldmark.New())
252 sanitized := p.rctx.SanitizeDescription(htmlString)
253 return template.HTML(sanitized)
254 },
255 "readme": func(text string) template.HTML {
256 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
257 htmlString := p.rctx.RenderMarkdown(text)
258 sanitized := p.rctx.SanitizeDefault(htmlString)
259 return template.HTML(sanitized)
260 },
261 "code": func(content, path string) string {
262 var style *chroma.Style = styles.Get("catpuccin-latte")
263 formatter := chromahtml.New(
264 chromahtml.InlineCode(false),
265 chromahtml.WithLineNumbers(true),
266 chromahtml.WithLinkableLineNumbers(true, "L"),
267 chromahtml.Standalone(false),
268 chromahtml.WithClasses(true),
269 )
270
271 lexer := lexers.Get(filepath.Base(path))
272 if lexer == nil {
273 lexer = lexers.Fallback
274 }
275
276 iterator, err := lexer.Tokenise(nil, content)
277 if err != nil {
278 p.logger.Error("chroma tokenize", "err", "err")
279 return ""
280 }
281
282 var code bytes.Buffer
283 err = formatter.Format(&code, style, iterator)
284 if err != nil {
285 p.logger.Error("chroma format", "err", "err")
286 return ""
287 }
288
289 return code.String()
290 },
291 "trimUriScheme": func(text string) string {
292 text = strings.TrimPrefix(text, "https://")
293 text = strings.TrimPrefix(text, "http://")
294 return text
295 },
296 "isNil": func(t any) bool {
297 // returns false for other "zero" values
298 return t == nil
299 },
300 "list": func(args ...any) []any {
301 return args
302 },
303 "dict": func(values ...any) (map[string]any, error) {
304 if len(values)%2 != 0 {
305 return nil, errors.New("invalid dict call")
306 }
307 dict := make(map[string]any, len(values)/2)
308 for i := 0; i < len(values); i += 2 {
309 key, ok := values[i].(string)
310 if !ok {
311 return nil, errors.New("dict keys must be strings")
312 }
313 dict[key] = values[i+1]
314 }
315 return dict, nil
316 },
317 "deref": func(v any) any {
318 val := reflect.ValueOf(v)
319 if val.Kind() == reflect.Ptr && !val.IsNil() {
320 return val.Elem().Interface()
321 }
322 return nil
323 },
324 "i": func(name string, classes ...string) template.HTML {
325 data, err := p.icon(name, classes)
326 if err != nil {
327 log.Printf("icon %s does not exist", name)
328 data, _ = p.icon("airplay", classes)
329 }
330 return template.HTML(data)
331 },
332 "cssContentHash": p.CssContentHash,
333 "fileTree": filetree.FileTree,
334 "pathEscape": func(s string) string {
335 return url.PathEscape(s)
336 },
337 "pathUnescape": func(s string) string {
338 u, _ := url.PathUnescape(s)
339 return u
340 },
341 "safeUrl": func(s string) template.URL {
342 return template.URL(s)
343 },
344 "tinyAvatar": func(handle string) string {
345 return p.AvatarUrl(handle, "tiny")
346 },
347 "fullAvatar": func(handle string) string {
348 return p.AvatarUrl(handle, "")
349 },
350 "langColor": enry.GetColor,
351 "layoutSide": func() string {
352 return "col-span-1 md:col-span-2 lg:col-span-3"
353 },
354 "layoutCenter": func() string {
355 return "col-span-1 md:col-span-8 lg:col-span-6"
356 },
357
358 "normalizeForHtmlId": func(s string) string {
359 normalized := strings.ReplaceAll(s, ":", "_")
360 normalized = strings.ReplaceAll(normalized, ".", "_")
361 return normalized
362 },
363 "sshFingerprint": func(pubKey string) string {
364 fp, err := crypto.SSHFingerprint(pubKey)
365 if err != nil {
366 return "error"
367 }
368 return fp
369 },
370 }
371}
372
373func (p *Pages) AvatarUrl(handle, size string) string {
374 handle = strings.TrimPrefix(handle, "@")
375
376 secret := p.avatar.SharedSecret
377 h := hmac.New(sha256.New, []byte(secret))
378 h.Write([]byte(handle))
379 signature := hex.EncodeToString(h.Sum(nil))
380
381 sizeArg := ""
382 if size != "" {
383 sizeArg = fmt.Sprintf("size=%s", size)
384 }
385 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
386}
387
388func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
389 iconPath := filepath.Join("static", "icons", name)
390
391 if filepath.Ext(name) == "" {
392 iconPath += ".svg"
393 }
394
395 data, err := Files.ReadFile(iconPath)
396 if err != nil {
397 return "", fmt.Errorf("icon %s not found: %w", name, err)
398 }
399
400 // Convert SVG data to string
401 svgStr := string(data)
402
403 svgTagEnd := strings.Index(svgStr, ">")
404 if svgTagEnd == -1 {
405 return "", fmt.Errorf("invalid SVG format for icon %s", name)
406 }
407
408 classTag := ` class="` + strings.Join(classes, " ") + `"`
409
410 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
411 return template.HTML(modifiedSVG), nil
412}
413
414func durationFmt(duration time.Duration, names [4]string) string {
415 days := int64(duration.Hours() / 24)
416 hours := int64(math.Mod(duration.Hours(), 24))
417 minutes := int64(math.Mod(duration.Minutes(), 60))
418 seconds := int64(math.Mod(duration.Seconds(), 60))
419
420 chunks := []struct {
421 name string
422 amount int64
423 }{
424 {names[0], days},
425 {names[1], hours},
426 {names[2], minutes},
427 {names[3], seconds},
428 }
429
430 parts := []string{}
431
432 for _, chunk := range chunks {
433 if chunk.amount != 0 {
434 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
435 }
436 }
437
438 return strings.Join(parts, " ")
439}