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