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 "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 "placeholderAvatar": func(size string) template.HTML {
388 sizeClass := "size-6"
389 iconSize := "size-4"
390 if size == "tiny" {
391 sizeClass = "size-6"
392 iconSize = "size-4"
393 } else if size == "small" {
394 sizeClass = "size-8"
395 iconSize = "size-5"
396 } else {
397 sizeClass = "size-12"
398 iconSize = "size-8"
399 }
400 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"})
401 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))
402 },
403 "profileAvatarUrl": func(profile *models.Profile, size string) string {
404 if profile != nil {
405 return p.AvatarUrl(profile.Did, size)
406 }
407 return ""
408 },
409 "langColor": enry.GetColor,
410 "reverse": func(s any) any {
411 if s == nil {
412 return nil
413 }
414
415 v := reflect.ValueOf(s)
416
417 if v.Kind() != reflect.Slice {
418 return s
419 }
420
421 length := v.Len()
422 reversed := reflect.MakeSlice(v.Type(), length, length)
423
424 for i := range length {
425 reversed.Index(i).Set(v.Index(length - 1 - i))
426 }
427
428 return reversed.Interface()
429 },
430 "normalizeForHtmlId": func(s string) string {
431 normalized := strings.ReplaceAll(s, ":", "_")
432 normalized = strings.ReplaceAll(normalized, ".", "_")
433 return normalized
434 },
435 "sshFingerprint": func(pubKey string) string {
436 fp, err := crypto.SSHFingerprint(pubKey)
437 if err != nil {
438 return "error"
439 }
440 return fp
441 },
442 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
443 result := make([]oauth.AccountInfo, 0, len(accounts))
444 for _, acc := range accounts {
445 if acc.Did != activeDid {
446 result = append(result, acc)
447 }
448 }
449 return result
450 },
451 // constant values used to define a template
452 "const": func() map[string]any {
453 return map[string]any{
454 "OrderedReactionKinds": models.OrderedReactionKinds,
455 // would be great to have ordered maps right about now
456 "UserSettingsTabs": []tab{
457 {"Name": "profile", "Icon": "user"},
458 {"Name": "keys", "Icon": "key"},
459 {"Name": "emails", "Icon": "mail"},
460 {"Name": "notifications", "Icon": "bell"},
461 {"Name": "knots", "Icon": "volleyball"},
462 {"Name": "spindles", "Icon": "spool"},
463 },
464 "RepoSettingsTabs": []tab{
465 {"Name": "general", "Icon": "sliders-horizontal"},
466 {"Name": "access", "Icon": "users"},
467 {"Name": "pipelines", "Icon": "layers-2"},
468 },
469 }
470 },
471 }
472}
473
474func (p *Pages) resolveDid(did string) string {
475 identity, err := p.resolver.ResolveIdent(context.Background(), did)
476
477 if err != nil {
478 return did
479 }
480
481 if identity.Handle.IsInvalidHandle() {
482 return "handle.invalid"
483 }
484
485 return identity.Handle.String()
486}
487
488func (p *Pages) AvatarUrl(handle, size string) string {
489 handle = strings.TrimPrefix(handle, "@")
490
491 handle = p.resolveDid(handle)
492
493 secret := p.avatar.SharedSecret
494 h := hmac.New(sha256.New, []byte(secret))
495 h.Write([]byte(handle))
496 signature := hex.EncodeToString(h.Sum(nil))
497
498 sizeArg := ""
499 if size != "" {
500 sizeArg = fmt.Sprintf("size=%s", size)
501 }
502 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
503}
504
505func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
506 iconPath := filepath.Join("static", "icons", name)
507
508 if filepath.Ext(name) == "" {
509 iconPath += ".svg"
510 }
511
512 data, err := Files.ReadFile(iconPath)
513 if err != nil {
514 return "", fmt.Errorf("icon %s not found: %w", name, err)
515 }
516
517 // Convert SVG data to string
518 svgStr := string(data)
519
520 svgTagEnd := strings.Index(svgStr, ">")
521 if svgTagEnd == -1 {
522 return "", fmt.Errorf("invalid SVG format for icon %s", name)
523 }
524
525 classTag := ` class="` + strings.Join(classes, " ") + `"`
526
527 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
528 return template.HTML(modifiedSVG), nil
529}
530
531func durationFmt(duration time.Duration, names [4]string) string {
532 days := int64(duration.Hours() / 24)
533 hours := int64(math.Mod(duration.Hours(), 24))
534 minutes := int64(math.Mod(duration.Minutes(), 60))
535 seconds := int64(math.Mod(duration.Seconds(), 60))
536
537 chunks := []struct {
538 name string
539 amount int64
540 }{
541 {names[0], days},
542 {names[1], hours},
543 {names[2], minutes},
544 {names[3], seconds},
545 }
546
547 parts := []string{}
548
549 for _, chunk := range chunks {
550 if chunk.amount != 0 {
551 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
552 }
553 }
554
555 return strings.Join(parts, " ")
556}