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