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