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