Monorepo for Tangled
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 "math/rand"
16 "net/url"
17 "path/filepath"
18 "reflect"
19 "strings"
20 "time"
21
22 "github.com/alecthomas/chroma/v2"
23 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
24 "github.com/alecthomas/chroma/v2/lexers"
25 "github.com/alecthomas/chroma/v2/styles"
26 "github.com/dustin/go-humanize"
27 "github.com/go-enry/go-enry/v2"
28 "github.com/yuin/goldmark"
29 emoji "github.com/yuin/goldmark-emoji"
30 "tangled.org/core/appview/db"
31 "tangled.org/core/appview/models"
32 "tangled.org/core/appview/oauth"
33 "tangled.org/core/appview/pages/markup"
34 "tangled.org/core/crypto"
35)
36
37type tab map[string]string
38
39func (p *Pages) funcMap() template.FuncMap {
40 return template.FuncMap{
41 "split": func(s string) []string {
42 return strings.Split(s, "\n")
43 },
44 "trimPrefix": func(s, prefix string) string {
45 return strings.TrimPrefix(s, prefix)
46 },
47 "join": func(elems []string, sep string) string {
48 return strings.Join(elems, sep)
49 },
50 "contains": func(s string, target string) bool {
51 return strings.Contains(s, target)
52 },
53 "stripPort": func(hostname string) string {
54 if strings.Contains(hostname, ":") {
55 return strings.Split(hostname, ":")[0]
56 }
57 return hostname
58 },
59 "mapContains": func(m any, key any) bool {
60 mapValue := reflect.ValueOf(m)
61 if mapValue.Kind() != reflect.Map {
62 return false
63 }
64 keyValue := reflect.ValueOf(key)
65 return mapValue.MapIndex(keyValue).IsValid()
66 },
67 "resolve": func(s string) string {
68 identity, err := p.resolver.ResolveIdent(context.Background(), s)
69
70 if err != nil {
71 return s
72 }
73
74 if identity.Handle.IsInvalidHandle() {
75 return "handle.invalid"
76 }
77
78 return identity.Handle.String()
79 },
80 "ownerSlashRepo": func(repo *models.Repo) string {
81 if repo.RepoDid != "" {
82 return repo.RepoDid
83 }
84 ownerId, err := p.resolver.ResolveIdent(context.Background(), repo.Did)
85 if err != nil {
86 return repo.RepoIdentifier()
87 }
88 handle := ownerId.Handle
89 if handle != "" && !handle.IsInvalidHandle() {
90 return string(handle) + "/" + repo.Name
91 }
92 return repo.RepoIdentifier()
93 },
94 "truncateAt30": func(s string) string {
95 if len(s) <= 30 {
96 return s
97 }
98 return s[:30] + "…"
99 },
100 "splitOn": func(s, sep string) []string {
101 return strings.Split(s, sep)
102 },
103 "string": func(v any) string {
104 return fmt.Sprint(v)
105 },
106 "int64": func(a int) int64 {
107 return int64(a)
108 },
109 "add": func(a, b int) int {
110 return a + b
111 },
112 "now": func() time.Time {
113 return time.Now()
114 },
115 // the absolute state of go templates
116 "add64": func(a, b int64) int64 {
117 return a + b
118 },
119 "sub": func(a, b int) int {
120 return a - b
121 },
122 "mul": func(a, b int) int {
123 return a * b
124 },
125 "div": func(a, b int) int {
126 return a / b
127 },
128 "mod": func(a, b int) int {
129 return a % b
130 },
131 "randInt": func(bound int) int {
132 return rand.Intn(bound)
133 },
134 "f64": func(a int) float64 {
135 return float64(a)
136 },
137 "addf64": func(a, b float64) float64 {
138 return a + b
139 },
140 "subf64": func(a, b float64) float64 {
141 return a - b
142 },
143 "mulf64": func(a, b float64) float64 {
144 return a * b
145 },
146 "divf64": func(a, b float64) float64 {
147 if b == 0 {
148 return 0
149 }
150 return a / b
151 },
152 "negf64": func(a float64) float64 {
153 return -a
154 },
155 "cond": func(cond any, a, b string) string {
156 if cond == nil {
157 return b
158 }
159
160 if boolean, ok := cond.(bool); boolean && ok {
161 return a
162 }
163
164 return b
165 },
166 "assoc": func(values ...string) ([][]string, error) {
167 if len(values)%2 != 0 {
168 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
169 }
170 pairs := make([][]string, 0)
171 for i := 0; i < len(values); i += 2 {
172 pairs = append(pairs, []string{values[i], values[i+1]})
173 }
174 return pairs, nil
175 },
176 "append": func(s []any, values ...any) []any {
177 s = append(s, values...)
178 return s
179 },
180 "commaFmt": humanize.Comma,
181 "relTimeFmt": humanize.Time,
182 "shortRelTimeFmt": func(t time.Time) string {
183 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{
184 {D: time.Second, Format: "now", DivBy: time.Second},
185 {D: 2 * time.Second, Format: "1s %s", DivBy: 1},
186 {D: time.Minute, Format: "%ds %s", DivBy: time.Second},
187 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1},
188 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute},
189 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1},
190 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour},
191 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
192 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day},
193 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week},
194 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month},
195 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1},
196 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1},
197 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year},
198 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
199 })
200 },
201 "longTimeFmt": func(t time.Time) string {
202 return t.Format("Jan 2, 2006, 3:04 PM MST")
203 },
204 "iso8601DateTimeFmt": func(t time.Time) string {
205 return t.Format("2006-01-02T15:04:05-07:00")
206 },
207 "iso8601DurationFmt": func(duration time.Duration) string {
208 days := int64(duration.Hours() / 24)
209 hours := int64(math.Mod(duration.Hours(), 24))
210 minutes := int64(math.Mod(duration.Minutes(), 60))
211 seconds := int64(math.Mod(duration.Seconds(), 60))
212 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
213 },
214 "durationFmt": func(duration time.Duration) string {
215 return durationFmt(duration, [4]string{"d", "hr", "min", "s"})
216 },
217 "longDurationFmt": func(duration time.Duration) string {
218 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
219 },
220 "byteFmt": humanize.Bytes,
221 "length": func(slice any) int {
222 v := reflect.ValueOf(slice)
223 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
224 return v.Len()
225 }
226 return 0
227 },
228 "splitN": func(s, sep string, n int) []string {
229 return strings.SplitN(s, sep, n)
230 },
231 "escapeHtml": func(s string) template.HTML {
232 if s == "" {
233 return template.HTML("<br>")
234 }
235 return template.HTML(s)
236 },
237 "unescapeHtml": func(s string) string {
238 return html.UnescapeString(s)
239 },
240 "nl2br": func(text string) template.HTML {
241 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
242 },
243 "unwrapText": func(text string) string {
244 paragraphs := strings.Split(text, "\n\n")
245
246 for i, p := range paragraphs {
247 lines := strings.Split(p, "\n")
248 paragraphs[i] = strings.Join(lines, " ")
249 }
250
251 return strings.Join(paragraphs, "\n\n")
252 },
253 "sequence": func(n int) []struct{} {
254 return make([]struct{}, n)
255 },
256 // take atmost N items from this slice
257 "take": func(slice any, n int) any {
258 v := reflect.ValueOf(slice)
259 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
260 return nil
261 }
262 if v.Len() == 0 {
263 return nil
264 }
265 return v.Slice(0, min(n, v.Len())).Interface()
266 },
267 "markdown": func(text string) template.HTML {
268 p.rctx.RendererType = markup.RendererTypeDefault
269 htmlString := p.rctx.RenderMarkdown(text)
270 sanitized := p.rctx.SanitizeDefault(htmlString)
271 return template.HTML(sanitized)
272 },
273 "description": func(text string) template.HTML {
274 p.rctx.RendererType = markup.RendererTypeDefault
275 htmlString := p.rctx.RenderMarkdownWith(text, goldmark.New(
276 goldmark.WithExtensions(
277 emoji.Emoji,
278 ),
279 ))
280 sanitized := p.rctx.SanitizeDescription(htmlString)
281 return template.HTML(sanitized)
282 },
283 "readme": func(text string) template.HTML {
284 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
285 htmlString := p.rctx.RenderMarkdown(text)
286 sanitized := p.rctx.SanitizeDefault(htmlString)
287 return template.HTML(sanitized)
288 },
289 "code": func(content, path string) string {
290 var style *chroma.Style = styles.Get("catpuccin-latte")
291 formatter := chromahtml.New(
292 chromahtml.InlineCode(false),
293 chromahtml.WithLineNumbers(true),
294 chromahtml.WithLinkableLineNumbers(true, "L"),
295 chromahtml.Standalone(false),
296 chromahtml.WithClasses(true),
297 )
298
299 lexer := lexers.Get(filepath.Base(path))
300 if lexer == nil {
301 lexer = lexers.Fallback
302 }
303
304 iterator, err := lexer.Tokenise(nil, content)
305 if err != nil {
306 p.logger.Error("chroma tokenize", "err", "err")
307 return ""
308 }
309
310 var code bytes.Buffer
311 err = formatter.Format(&code, style, iterator)
312 if err != nil {
313 p.logger.Error("chroma format", "err", "err")
314 return ""
315 }
316
317 return code.String()
318 },
319 "trimUriScheme": func(text string) string {
320 text = strings.TrimPrefix(text, "https://")
321 text = strings.TrimPrefix(text, "http://")
322 return text
323 },
324 "isNil": func(t any) bool {
325 // returns false for other "zero" values
326 return t == nil
327 },
328 "list": func(args ...any) []any {
329 return args
330 },
331 "dict": func(values ...any) (map[string]any, error) {
332 if len(values)%2 != 0 {
333 return nil, errors.New("invalid dict call")
334 }
335 dict := make(map[string]any, len(values)/2)
336 for i := 0; i < len(values); i += 2 {
337 key, ok := values[i].(string)
338 if !ok {
339 return nil, errors.New("dict keys must be strings")
340 }
341 dict[key] = values[i+1]
342 }
343 return dict, nil
344 },
345 "queryParams": func(params ...any) (url.Values, error) {
346 if len(params)%2 != 0 {
347 return nil, errors.New("invalid queryParams call")
348 }
349 vals := make(url.Values, len(params)/2)
350 for i := 0; i < len(params); i += 2 {
351 key, ok := params[i].(string)
352 if !ok {
353 return nil, errors.New("queryParams keys must be strings")
354 }
355 v, ok := params[i+1].(string)
356 if !ok {
357 return nil, errors.New("queryParams values must be strings")
358 }
359 vals.Add(key, v)
360 }
361 return vals, nil
362 },
363 "deref": func(v any) any {
364 val := reflect.ValueOf(v)
365 if val.Kind() == reflect.Pointer && !val.IsNil() {
366 return val.Elem().Interface()
367 }
368 return nil
369 },
370 "i": func(name string, classes ...string) template.HTML {
371 data, err := p.icon(name, classes)
372 if err != nil {
373 log.Printf("icon %s does not exist", name)
374 data, _ = p.icon("airplay", classes)
375 }
376 return template.HTML(data)
377 },
378 "cssContentHash": p.CssContentHash,
379 "pathEscape": func(s string) string {
380 return url.PathEscape(s)
381 },
382 "pathUnescape": func(s string) string {
383 u, _ := url.PathUnescape(s)
384 return u
385 },
386 "safeUrl": func(s string) template.URL {
387 return template.URL(s)
388 },
389 "tinyAvatar": func(handle string) string {
390 return p.AvatarUrl(handle, "tiny")
391 },
392 "fullAvatar": func(handle string) string {
393 return p.AvatarUrl(handle, "")
394 },
395 "placeholderAvatar": func(size string) template.HTML {
396 sizeClass := "size-6"
397 iconSize := "size-4"
398 if size == "tiny" {
399 sizeClass = "size-6"
400 iconSize = "size-4"
401 } else if size == "small" {
402 sizeClass = "size-8"
403 iconSize = "size-5"
404 } else {
405 sizeClass = "size-12"
406 iconSize = "size-8"
407 }
408 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"})
409 return template.HTML(fmt.Sprintf(`<div class="%s rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">%s</div>`, sizeClass, icon))
410 },
411 "profileAvatarUrl": func(profile *models.Profile, size string) string {
412 if profile != nil {
413 return p.AvatarUrl(profile.Did, size)
414 }
415 return ""
416 },
417 "langColor": enry.GetColor,
418 "reverse": func(s any) any {
419 if s == nil {
420 return nil
421 }
422
423 v := reflect.ValueOf(s)
424
425 if v.Kind() != reflect.Slice {
426 return s
427 }
428
429 length := v.Len()
430 reversed := reflect.MakeSlice(v.Type(), length, length)
431
432 for i := range length {
433 reversed.Index(i).Set(v.Index(length - 1 - i))
434 }
435
436 return reversed.Interface()
437 },
438 "normalizeForHtmlId": func(s string) string {
439 normalized := strings.ReplaceAll(s, ":", "_")
440 normalized = strings.ReplaceAll(normalized, ".", "_")
441 return normalized
442 },
443 "sshFingerprint": func(pubKey string) string {
444 fp, err := crypto.SSHFingerprint(pubKey)
445 if err != nil {
446 return "error"
447 }
448 return fp
449 },
450 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
451 result := make([]oauth.AccountInfo, 0, len(accounts))
452 for _, acc := range accounts {
453 if acc.Did != activeDid {
454 result = append(result, acc)
455 }
456 }
457 return result
458 },
459 // constant values used to define a template
460 "const": func() map[string]any {
461 return map[string]any{
462 "OrderedReactionKinds": models.OrderedReactionKinds,
463 // would be great to have ordered maps right about now
464 "UserSettingsTabs": []tab{
465 {"Name": "profile", "Icon": "user"},
466 {"Name": "keys", "Icon": "key"},
467 {"Name": "emails", "Icon": "mail"},
468 {"Name": "notifications", "Icon": "bell"},
469 {"Name": "knots", "Icon": "volleyball"},
470 {"Name": "spindles", "Icon": "spool"},
471 },
472 "RepoSettingsTabs": []tab{
473 {"Name": "general", "Icon": "sliders-horizontal"},
474 {"Name": "access", "Icon": "users"},
475 {"Name": "pipelines", "Icon": "layers-2"},
476 {"Name": "hooks", "Icon": "webhook"},
477 },
478 }
479 },
480 }
481}
482
483func (p *Pages) resolveDid(did string) string {
484 identity, err := p.resolver.ResolveIdent(context.Background(), did)
485
486 if err != nil {
487 return did
488 }
489
490 if identity.Handle.IsInvalidHandle() {
491 return "handle.invalid"
492 }
493
494 return identity.Handle.String()
495}
496
497func (p *Pages) AvatarUrl(actor, size string) string {
498 actor = strings.TrimPrefix(actor, "@")
499
500 identity, err := p.resolver.ResolveIdent(context.Background(), actor)
501 var did string
502 if err != nil {
503 did = actor
504 } else {
505 did = identity.DID.String()
506 }
507
508 secret := p.avatar.SharedSecret
509 h := hmac.New(sha256.New, []byte(secret))
510 h.Write([]byte(did))
511 signature := hex.EncodeToString(h.Sum(nil))
512
513 // Get avatar CID for cache busting
514 profile, err := db.GetProfile(p.db, did)
515 version := ""
516 if err == nil && profile != nil && profile.Avatar != "" {
517 // Use first 8 chars of avatar CID as version
518 if len(profile.Avatar) > 8 {
519 version = profile.Avatar[:8]
520 } else {
521 version = profile.Avatar
522 }
523 }
524
525 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did)
526 if size != "" {
527 if version != "" {
528 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version)
529 }
530 return fmt.Sprintf("%s?size=%s", baseUrl, size)
531 }
532 if version != "" {
533 return fmt.Sprintf("%s?v=%s", baseUrl, version)
534 }
535 return baseUrl
536}
537
538func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
539 iconPath := filepath.Join("static", "icons", name)
540
541 if filepath.Ext(name) == "" {
542 iconPath += ".svg"
543 }
544
545 data, err := Files.ReadFile(iconPath)
546 if err != nil {
547 return "", fmt.Errorf("icon %s not found: %w", name, err)
548 }
549
550 // Convert SVG data to string
551 svgStr := string(data)
552
553 svgTagEnd := strings.Index(svgStr, ">")
554 if svgTagEnd == -1 {
555 return "", fmt.Errorf("invalid SVG format for icon %s", name)
556 }
557
558 classTag := ` class="` + strings.Join(classes, " ") + `"`
559
560 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
561 return template.HTML(modifiedSVG), nil
562}
563
564func durationFmt(duration time.Duration, names [4]string) string {
565 days := int64(duration.Hours() / 24)
566 hours := int64(math.Mod(duration.Hours(), 24))
567 minutes := int64(math.Mod(duration.Minutes(), 60))
568 seconds := int64(math.Mod(duration.Seconds(), 60))
569
570 chunks := []struct {
571 name string
572 amount int64
573 }{
574 {names[0], days},
575 {names[1], hours},
576 {names[2], minutes},
577 {names[3], seconds},
578 }
579
580 parts := []string{}
581
582 for _, chunk := range chunks {
583 if chunk.amount != 0 {
584 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
585 }
586 }
587
588 return strings.Join(parts, " ")
589}