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