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