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