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