Forked monorepo for Tangled
0

Configure Feed

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

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