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