Monorepo for Tangled
0

Configure Feed

Select the types of activity you want to include in your feed.

tangled-core / appview / pages / funcmap.go
19 kB 694 lines
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/appview/pages/markup/sanitizer" 38 "tangled.org/core/crypto" 39 "tangled.org/core/idresolver" 40) 41 42type tab map[string]string 43 44func (p *Pages) funcMap() template.FuncMap { 45 return template.FuncMap{ 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 if t.Unix() == 0 { 227 return "at the beginning of time" 228 } 229 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{ 230 {D: time.Second, Format: "now", DivBy: time.Second}, 231 {D: 2 * time.Second, Format: "1s %s", DivBy: 1}, 232 {D: time.Minute, Format: "%ds %s", DivBy: time.Second}, 233 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1}, 234 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute}, 235 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1}, 236 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour}, 237 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1}, 238 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day}, 239 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week}, 240 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month}, 241 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1}, 242 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1}, 243 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year}, 244 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1}, 245 }) 246 }, 247 "shortTimeFmt": func(t time.Time) string { 248 return t.Format("Jan 2, 2006") 249 }, 250 "longTimeFmt": func(t time.Time) string { 251 return t.Format("Jan 2, 2006, 3:04 PM MST") 252 }, 253 "iso8601DateTimeFmt": func(t time.Time) string { 254 return t.Format("2006-01-02T15:04:05-07:00") 255 }, 256 "iso8601DurationFmt": func(duration time.Duration) string { 257 days := int64(duration.Hours() / 24) 258 hours := int64(math.Mod(duration.Hours(), 24)) 259 minutes := int64(math.Mod(duration.Minutes(), 60)) 260 seconds := int64(math.Mod(duration.Seconds(), 60)) 261 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds) 262 }, 263 "durationFmt": func(duration time.Duration) string { 264 return durationFmt(duration, [4]string{"d", "h", "m", "s"}) 265 }, 266 "longDurationFmt": func(duration time.Duration) string { 267 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"}) 268 }, 269 "byteFmt": humanize.Bytes, 270 "length": func(slice any) int { 271 v := reflect.ValueOf(slice) 272 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { 273 return v.Len() 274 } 275 return 0 276 }, 277 "splitN": func(s, sep string, n int) []string { 278 return strings.SplitN(s, sep, n) 279 }, 280 "escapeHtml": func(s string) template.HTML { 281 if s == "" { 282 return template.HTML("<br>") 283 } 284 return template.HTML(s) 285 }, 286 "unescapeHtml": func(s string) string { 287 return html.UnescapeString(s) 288 }, 289 "nl2br": func(text string) template.HTML { 290 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>")) 291 }, 292 "unwrapText": func(text string) string { 293 paragraphs := strings.Split(text, "\n\n") 294 295 for i, p := range paragraphs { 296 lines := strings.Split(p, "\n") 297 paragraphs[i] = strings.Join(lines, " ") 298 } 299 300 return strings.Join(paragraphs, "\n\n") 301 }, 302 "sequence": func(n int) []struct{} { 303 return make([]struct{}, n) 304 }, 305 // take atmost N items from this slice 306 "take": func(slice any, n int) any { 307 v := reflect.ValueOf(slice) 308 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { 309 return nil 310 } 311 if v.Len() == 0 { 312 return nil 313 } 314 return v.Slice(0, min(n, v.Len())).Interface() 315 }, 316 "markdown": func(text string) template.HTML { 317 rctx := p.rctx.Clone() 318 rctx.RendererType = markup.RendererTypeDefault 319 htmlString := rctx.RenderMarkdown(text) 320 sanitized := sanitizer.SanitizeDefault(htmlString) 321 return template.HTML(sanitized) 322 }, 323 "description": func(text string) template.HTML { 324 rctx := p.rctx.Clone() 325 rctx.RendererType = markup.RendererTypeDefault 326 htmlString := rctx.RenderMarkdownWith(text, goldmark.New( 327 goldmark.WithExtensions( 328 emoji.Emoji, 329 ), 330 )) 331 sanitized := sanitizer.SanitizeDescription(htmlString) 332 return template.HTML(sanitized) 333 }, 334 "readme": func(text string) template.HTML { 335 rctx := p.rctx.Clone() 336 rctx.RendererType = markup.RendererTypeRepoMarkdown 337 htmlString := rctx.RenderMarkdown(text) 338 sanitized := sanitizer.SanitizeDefault(htmlString) 339 return template.HTML(sanitized) 340 }, 341 "code": func(content, path string) string { 342 var style *chroma.Style = styles.Get("catpuccin-latte") 343 formatter := chromahtml.New( 344 chromahtml.InlineCode(false), 345 chromahtml.WithLineNumbers(true), 346 chromahtml.WithLinkableLineNumbers(true, "L"), 347 chromahtml.Standalone(false), 348 chromahtml.WithClasses(true), 349 ) 350 351 lexer := lexers.Get(filepath.Base(path)) 352 if lexer == nil { 353 if firstLine, _, ok := strings.Cut(content, "\n"); ok && strings.HasPrefix(firstLine, "#!") { 354 // extract interpreter from shebang (handles "#!/usr/bin/env nu", "#!/usr/bin/nu", etc.) 355 fields := strings.Fields(firstLine[2:]) 356 if len(fields) > 0 { 357 interp := filepath.Base(fields[len(fields)-1]) 358 lexer = lexers.Get(interp) 359 } 360 } 361 } 362 if lexer == nil { 363 lexer = lexers.Analyse(content) 364 } 365 if lexer == nil { 366 lexer = lexers.Fallback 367 } 368 369 iterator, err := lexer.Tokenise(nil, content) 370 if err != nil { 371 p.logger.Error("chroma tokenize", "err", "err") 372 return "" 373 } 374 375 var code bytes.Buffer 376 err = formatter.Format(&code, style, iterator) 377 if err != nil { 378 p.logger.Error("chroma format", "err", "err") 379 return "" 380 } 381 382 return code.String() 383 }, 384 "trimUriScheme": func(text string) string { 385 text = strings.TrimPrefix(text, "https://") 386 text = strings.TrimPrefix(text, "http://") 387 return text 388 }, 389 "isNil": func(t any) bool { 390 // returns false for other "zero" values 391 return t == nil 392 }, 393 "hasPrefix": strings.HasPrefix, 394 "list": func(args ...any) []any { 395 return args 396 }, 397 "dict": func(values ...any) (map[string]any, error) { 398 if len(values)%2 != 0 { 399 return nil, errors.New("invalid dict call") 400 } 401 dict := make(map[string]any, len(values)/2) 402 for i := 0; i < len(values); i += 2 { 403 key, ok := values[i].(string) 404 if !ok { 405 return nil, errors.New("dict keys must be strings") 406 } 407 dict[key] = values[i+1] 408 } 409 return dict, nil 410 }, 411 "queryParams": func(params ...any) (url.Values, error) { 412 if len(params)%2 != 0 { 413 return nil, errors.New("invalid queryParams call") 414 } 415 vals := make(url.Values, len(params)/2) 416 for i := 0; i < len(params); i += 2 { 417 key, ok := params[i].(string) 418 if !ok { 419 return nil, errors.New("queryParams keys must be strings") 420 } 421 v, ok := params[i+1].(string) 422 if !ok { 423 return nil, errors.New("queryParams values must be strings") 424 } 425 vals.Add(key, v) 426 } 427 return vals, nil 428 }, 429 "deref": func(v any) any { 430 val := reflect.ValueOf(v) 431 if val.Kind() == reflect.Pointer && !val.IsNil() { 432 return val.Elem().Interface() 433 } 434 return nil 435 }, 436 "i": func(name string, classes ...string) template.HTML { 437 data, err := p.icon(name, classes) 438 if err != nil { 439 log.Printf("icon %s does not exist", name) 440 data, _ = p.icon("airplay", classes) 441 } 442 return template.HTML(data) 443 }, 444 "cssContentHash": p.CssContentHash, 445 "pathEscape": func(s string) string { 446 return url.PathEscape(s) 447 }, 448 "pathUnescape": func(s string) string { 449 u, _ := url.PathUnescape(s) 450 return u 451 }, 452 "safeUrl": func(s string) template.URL { 453 return template.URL(s) 454 }, 455 "tinyAvatar": func(handle string) string { 456 return p.AvatarUrl(handle, "tiny") 457 }, 458 "fullAvatar": func(handle string) string { 459 return p.AvatarUrl(handle, "") 460 }, 461 "placeholderAvatar": func(size string) template.HTML { 462 sizeClass := "size-6" 463 iconSize := "size-4" 464 switch size { 465 case "tiny": 466 sizeClass = "size-6" 467 iconSize = "size-4" 468 case "small": 469 sizeClass = "size-8" 470 iconSize = "size-5" 471 default: 472 sizeClass = "size-12" 473 iconSize = "size-8" 474 } 475 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"}) 476 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)) 477 }, 478 "profileAvatarUrl": func(profile *models.Profile, size string) string { 479 if profile != nil { 480 return p.AvatarUrl(profile.Did, size) 481 } 482 return "" 483 }, 484 "langColor": enry.GetColor, 485 "reverse": func(s any) any { 486 if s == nil { 487 return nil 488 } 489 490 v := reflect.ValueOf(s) 491 492 if v.Kind() != reflect.Slice { 493 return s 494 } 495 496 length := v.Len() 497 reversed := reflect.MakeSlice(v.Type(), length, length) 498 499 for i := range length { 500 reversed.Index(i).Set(v.Index(length - 1 - i)) 501 } 502 503 return reversed.Interface() 504 }, 505 "normalizeForHtmlId": func(s string) string { 506 normalized := strings.ReplaceAll(s, ":", "_") 507 normalized = strings.ReplaceAll(normalized, ".", "_") 508 return normalized 509 }, 510 "sshFingerprint": func(pubKey string) string { 511 fp, err := crypto.SSHFingerprint(pubKey) 512 if err != nil { 513 return "error" 514 } 515 return fp 516 }, 517 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo { 518 result := make([]oauth.AccountInfo, 0, len(accounts)) 519 for _, acc := range accounts { 520 if acc.Did != activeDid { 521 result = append(result, acc) 522 } 523 } 524 return result 525 }, 526 "isGenerated": func(path string) bool { 527 return enry.IsGenerated(path, nil) 528 }, 529 // NOTE(boltless): I know... I hate doing this too 530 "asReactionMapMap": func(dict any) map[syntax.ATURI]map[models.ReactionKind]models.ReactionDisplayData { 531 if dict == nil { 532 return make(map[syntax.ATURI]map[models.ReactionKind]models.ReactionDisplayData) 533 } 534 m, _ := dict.(map[syntax.ATURI]map[models.ReactionKind]models.ReactionDisplayData) 535 return m 536 }, 537 "asReactionStatusMapMap": func(dict any) map[syntax.ATURI]map[models.ReactionKind]bool { 538 if dict == nil { 539 log.Println("returning empty map") 540 return make(map[syntax.ATURI]map[models.ReactionKind]bool) 541 } 542 m, _ := dict.(map[syntax.ATURI]map[models.ReactionKind]bool) 543 return m 544 }, 545 // constant values used to define a template 546 "const": func() map[string]any { 547 return map[string]any{ 548 "OrderedReactionKinds": models.OrderedReactionKinds, 549 // would be great to have ordered maps right about now 550 "UserSettingsTabs": []tab{ 551 {"Name": "profile", "Label": "Profile", "Icon": "user"}, 552 {"Name": "keys", "Label": "Keys", "Icon": "key"}, 553 {"Name": "emails", "Label": "Emails", "Icon": "mail"}, 554 {"Name": "notifications", "Label": "Notifications", "Icon": "bell"}, 555 {"Name": "knots", "Label": "Knots", "Icon": "volleyball"}, 556 {"Name": "spindles", "Label": "Spindles", "Icon": "spool"}, 557 {"Name": "sites", "Label": "Sites", "Icon": "globe"}, 558 }, 559 "RepoSettingsTabs": []tab{ 560 {"Name": "general", "Label": "General", "Icon": "sliders-horizontal"}, 561 {"Name": "access", "Label": "Access", "Icon": "users"}, 562 {"Name": "pipelines", "Label": "Pipelines", "Icon": "layers-2"}, 563 {"Name": "hooks", "Label": "Hooks", "Icon": "webhook"}, 564 {"Name": "sites", "Label": "Sites", "Icon": "globe"}, 565 }, 566 "PdsUserDomain": p.pdsCfg.UserDomain, 567 } 568 }, 569 "did": func(s string) syntax.DID { 570 // cast to DID 571 return syntax.DID(s) 572 }, 573 } 574} 575 576func primaryHandle(r *idresolver.Resolver, s string) string { 577 identity, err := r.ResolveIdent(context.Background(), s) 578 if err != nil || identity.Handle.IsInvalidHandle() { 579 return "handle.invalid" 580 } 581 return identity.Handle.String() 582} 583 584func (p *Pages) DisplayHandle(ctx context.Context, did string) string { 585 if p.db != nil { 586 if h := cache.LookupPreferredHandle(ctx, p.rdb, p.db, did); h != "" { 587 return h 588 } 589 } 590 if id, err := p.resolver.ResolveIdent(ctx, did); err == nil && !id.Handle.IsInvalidHandle() { 591 return id.Handle.String() 592 } 593 return did 594} 595 596func (p *Pages) AvatarUrl(actor, size string) string { 597 actor = strings.TrimPrefix(actor, "@") 598 599 identity, err := p.resolver.ResolveIdent(context.Background(), actor) 600 var did string 601 if err != nil { 602 did = actor 603 } else { 604 did = identity.DID.String() 605 } 606 607 secret := p.avatar.SharedSecret 608 if secret == "" { 609 return "" 610 } 611 h := hmac.New(sha256.New, []byte(secret)) 612 h.Write([]byte(did)) 613 signature := hex.EncodeToString(h.Sum(nil)) 614 615 // Get avatar CID for cache busting 616 version := "" 617 if p.db != nil { 618 profile, err := db.GetProfile(p.db, did) 619 if err == nil && profile != nil && profile.Avatar != "" { 620 // Use first 8 chars of avatar CID as version 621 if len(profile.Avatar) > 8 { 622 version = profile.Avatar[:8] 623 } else { 624 version = profile.Avatar 625 } 626 } 627 } 628 629 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did) 630 if size != "" { 631 if version != "" { 632 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version) 633 } 634 return fmt.Sprintf("%s?size=%s", baseUrl, size) 635 } 636 if version != "" { 637 return fmt.Sprintf("%s?v=%s", baseUrl, version) 638 } 639 640 return baseUrl 641} 642 643func (p *Pages) icon(name string, classes []string) (template.HTML, error) { 644 iconPath := filepath.Join("static", "icons", name) 645 646 if filepath.Ext(name) == "" { 647 iconPath += ".svg" 648 } 649 650 data, err := Files.ReadFile(iconPath) 651 if err != nil { 652 return "", fmt.Errorf("icon %s not found: %w", name, err) 653 } 654 655 // Convert SVG data to string 656 svgStr := string(data) 657 658 svgTagEnd := strings.Index(svgStr, ">") 659 if svgTagEnd == -1 { 660 return "", fmt.Errorf("invalid SVG format for icon %s", name) 661 } 662 663 classTag := ` class="` + strings.Join(classes, " ") + `"` 664 665 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:] 666 return template.HTML(modifiedSVG), nil 667} 668 669func durationFmt(duration time.Duration, names [4]string) string { 670 days := int64(duration.Hours() / 24) 671 hours := int64(math.Mod(duration.Hours(), 24)) 672 minutes := int64(math.Mod(duration.Minutes(), 60)) 673 seconds := int64(math.Mod(duration.Seconds(), 60)) 674 675 chunks := []struct { 676 name string 677 amount int64 678 }{ 679 {names[0], days}, 680 {names[1], hours}, 681 {names[2], minutes}, 682 {names[3], seconds}, 683 } 684 685 parts := []string{} 686 687 for _, chunk := range chunks { 688 if chunk.amount != 0 { 689 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name)) 690 } 691 } 692 693 return strings.Join(parts, " ") 694}