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