This repository has no description
0

Configure Feed

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

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