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 "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 "longTimeFmt": func(t time.Time) string {
199 return t.Format("Jan 2, 2006, 3:04 PM MST")
200 },
201 "iso8601DateTimeFmt": func(t time.Time) string {
202 return t.Format("2006-01-02T15:04:05-07:00")
203 },
204 "iso8601DurationFmt": func(duration time.Duration) string {
205 days := int64(duration.Hours() / 24)
206 hours := int64(math.Mod(duration.Hours(), 24))
207 minutes := int64(math.Mod(duration.Minutes(), 60))
208 seconds := int64(math.Mod(duration.Seconds(), 60))
209 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
210 },
211 "durationFmt": func(duration time.Duration) string {
212 return durationFmt(duration, [4]string{"d", "hr", "min", "s"})
213 },
214 "longDurationFmt": func(duration time.Duration) string {
215 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
216 },
217 "byteFmt": humanize.Bytes,
218 "length": func(slice any) int {
219 v := reflect.ValueOf(slice)
220 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
221 return v.Len()
222 }
223 return 0
224 },
225 "splitN": func(s, sep string, n int) []string {
226 return strings.SplitN(s, sep, n)
227 },
228 "escapeHtml": func(s string) template.HTML {
229 if s == "" {
230 return template.HTML("<br>")
231 }
232 return template.HTML(s)
233 },
234 "unescapeHtml": func(s string) string {
235 return html.UnescapeString(s)
236 },
237 "nl2br": func(text string) template.HTML {
238 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
239 },
240 "unwrapText": func(text string) string {
241 paragraphs := strings.Split(text, "\n\n")
242
243 for i, p := range paragraphs {
244 lines := strings.Split(p, "\n")
245 paragraphs[i] = strings.Join(lines, " ")
246 }
247
248 return strings.Join(paragraphs, "\n\n")
249 },
250 "sequence": func(n int) []struct{} {
251 return make([]struct{}, n)
252 },
253 // take atmost N items from this slice
254 "take": func(slice any, n int) any {
255 v := reflect.ValueOf(slice)
256 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
257 return nil
258 }
259 if v.Len() == 0 {
260 return nil
261 }
262 return v.Slice(0, min(n, v.Len())).Interface()
263 },
264 "markdown": func(text string) template.HTML {
265 p.rctx.RendererType = markup.RendererTypeDefault
266 htmlString := p.rctx.RenderMarkdown(text)
267 sanitized := p.rctx.SanitizeDefault(htmlString)
268 return template.HTML(sanitized)
269 },
270 "description": func(text string) template.HTML {
271 p.rctx.RendererType = markup.RendererTypeDefault
272 htmlString := p.rctx.RenderMarkdownWith(text, goldmark.New(
273 goldmark.WithExtensions(
274 emoji.Emoji,
275 ),
276 ))
277 sanitized := p.rctx.SanitizeDescription(htmlString)
278 return template.HTML(sanitized)
279 },
280 "readme": func(text string) template.HTML {
281 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
282 htmlString := p.rctx.RenderMarkdown(text)
283 sanitized := p.rctx.SanitizeDefault(htmlString)
284 return template.HTML(sanitized)
285 },
286 "code": func(content, path string) string {
287 var style *chroma.Style = styles.Get("catpuccin-latte")
288 formatter := chromahtml.New(
289 chromahtml.InlineCode(false),
290 chromahtml.WithLineNumbers(true),
291 chromahtml.WithLinkableLineNumbers(true, "L"),
292 chromahtml.Standalone(false),
293 chromahtml.WithClasses(true),
294 )
295
296 lexer := lexers.Get(filepath.Base(path))
297 if lexer == nil {
298 if firstLine, _, ok := strings.Cut(content, "\n"); ok && strings.HasPrefix(firstLine, "#!") {
299 // extract interpreter from shebang (handles "#!/usr/bin/env nu", "#!/usr/bin/nu", etc.)
300 fields := strings.Fields(firstLine[2:])
301 if len(fields) > 0 {
302 interp := filepath.Base(fields[len(fields)-1])
303 lexer = lexers.Get(interp)
304 }
305 }
306 }
307 if lexer == nil {
308 lexer = lexers.Analyse(content)
309 }
310 if lexer == nil {
311 lexer = lexers.Fallback
312 }
313
314 iterator, err := lexer.Tokenise(nil, content)
315 if err != nil {
316 p.logger.Error("chroma tokenize", "err", "err")
317 return ""
318 }
319
320 var code bytes.Buffer
321 err = formatter.Format(&code, style, iterator)
322 if err != nil {
323 p.logger.Error("chroma format", "err", "err")
324 return ""
325 }
326
327 return code.String()
328 },
329 "trimUriScheme": func(text string) string {
330 text = strings.TrimPrefix(text, "https://")
331 text = strings.TrimPrefix(text, "http://")
332 return text
333 },
334 "isNil": func(t any) bool {
335 // returns false for other "zero" values
336 return t == nil
337 },
338 "list": func(args ...any) []any {
339 return args
340 },
341 "dict": func(values ...any) (map[string]any, error) {
342 if len(values)%2 != 0 {
343 return nil, errors.New("invalid dict call")
344 }
345 dict := make(map[string]any, len(values)/2)
346 for i := 0; i < len(values); i += 2 {
347 key, ok := values[i].(string)
348 if !ok {
349 return nil, errors.New("dict keys must be strings")
350 }
351 dict[key] = values[i+1]
352 }
353 return dict, nil
354 },
355 "queryParams": func(params ...any) (url.Values, error) {
356 if len(params)%2 != 0 {
357 return nil, errors.New("invalid queryParams call")
358 }
359 vals := make(url.Values, len(params)/2)
360 for i := 0; i < len(params); i += 2 {
361 key, ok := params[i].(string)
362 if !ok {
363 return nil, errors.New("queryParams keys must be strings")
364 }
365 v, ok := params[i+1].(string)
366 if !ok {
367 return nil, errors.New("queryParams values must be strings")
368 }
369 vals.Add(key, v)
370 }
371 return vals, nil
372 },
373 "deref": func(v any) any {
374 val := reflect.ValueOf(v)
375 if val.Kind() == reflect.Pointer && !val.IsNil() {
376 return val.Elem().Interface()
377 }
378 return nil
379 },
380 "i": func(name string, classes ...string) template.HTML {
381 data, err := p.icon(name, classes)
382 if err != nil {
383 log.Printf("icon %s does not exist", name)
384 data, _ = p.icon("airplay", classes)
385 }
386 return template.HTML(data)
387 },
388 "cssContentHash": p.CssContentHash,
389 "pathEscape": func(s string) string {
390 return url.PathEscape(s)
391 },
392 "pathUnescape": func(s string) string {
393 u, _ := url.PathUnescape(s)
394 return u
395 },
396 "safeUrl": func(s string) template.URL {
397 return template.URL(s)
398 },
399 "tinyAvatar": func(handle string) string {
400 return p.AvatarUrl(handle, "tiny")
401 },
402 "fullAvatar": func(handle string) string {
403 return p.AvatarUrl(handle, "")
404 },
405 "placeholderAvatar": func(size string) template.HTML {
406 sizeClass := "size-6"
407 iconSize := "size-4"
408 if size == "tiny" {
409 sizeClass = "size-6"
410 iconSize = "size-4"
411 } else if size == "small" {
412 sizeClass = "size-8"
413 iconSize = "size-5"
414 } else {
415 sizeClass = "size-12"
416 iconSize = "size-8"
417 }
418 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"})
419 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))
420 },
421 "profileAvatarUrl": func(profile *models.Profile, size string) string {
422 if profile != nil {
423 return p.AvatarUrl(profile.Did, size)
424 }
425 return ""
426 },
427 "langColor": enry.GetColor,
428 "reverse": func(s any) any {
429 if s == nil {
430 return nil
431 }
432
433 v := reflect.ValueOf(s)
434
435 if v.Kind() != reflect.Slice {
436 return s
437 }
438
439 length := v.Len()
440 reversed := reflect.MakeSlice(v.Type(), length, length)
441
442 for i := range length {
443 reversed.Index(i).Set(v.Index(length - 1 - i))
444 }
445
446 return reversed.Interface()
447 },
448 "normalizeForHtmlId": func(s string) string {
449 normalized := strings.ReplaceAll(s, ":", "_")
450 normalized = strings.ReplaceAll(normalized, ".", "_")
451 return normalized
452 },
453 "sshFingerprint": func(pubKey string) string {
454 fp, err := crypto.SSHFingerprint(pubKey)
455 if err != nil {
456 return "error"
457 }
458 return fp
459 },
460 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
461 result := make([]oauth.AccountInfo, 0, len(accounts))
462 for _, acc := range accounts {
463 if acc.Did != activeDid {
464 result = append(result, acc)
465 }
466 }
467 return result
468 },
469 "isGenerated": func(path string) bool {
470 return enry.IsGenerated(path, nil)
471 },
472 // constant values used to define a template
473 "const": func() map[string]any {
474 return map[string]any{
475 "OrderedReactionKinds": models.OrderedReactionKinds,
476 // would be great to have ordered maps right about now
477 "UserSettingsTabs": []tab{
478 {"Name": "profile", "Icon": "user"},
479 {"Name": "keys", "Icon": "key"},
480 {"Name": "emails", "Icon": "mail"},
481 {"Name": "notifications", "Icon": "bell"},
482 {"Name": "knots", "Icon": "volleyball"},
483 {"Name": "spindles", "Icon": "spool"},
484 {"Name": "sites", "Icon": "globe"},
485 },
486 "RepoSettingsTabs": []tab{
487 {"Name": "general", "Icon": "sliders-horizontal"},
488 {"Name": "access", "Icon": "users"},
489 {"Name": "pipelines", "Icon": "layers-2"},
490 {"Name": "hooks", "Icon": "webhook"},
491 {"Name": "sites", "Icon": "globe"},
492 },
493 }
494 },
495 }
496}
497
498func (p *Pages) resolveDid(did string) string {
499 identity, err := p.resolver.ResolveIdent(context.Background(), did)
500
501 if err != nil {
502 return did
503 }
504
505 if identity.Handle.IsInvalidHandle() {
506 return "handle.invalid"
507 }
508
509 return identity.Handle.String()
510}
511
512func (p *Pages) AvatarUrl(actor, size string) string {
513 actor = strings.TrimPrefix(actor, "@")
514
515 identity, err := p.resolver.ResolveIdent(context.Background(), actor)
516 var did string
517 if err != nil {
518 did = actor
519 } else {
520 did = identity.DID.String()
521 }
522
523 secret := p.avatar.SharedSecret
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 profile, err := db.GetProfile(p.db, did)
530 version := ""
531 if err == nil && profile != nil && profile.Avatar != "" {
532 // Use first 8 chars of avatar CID as version
533 if len(profile.Avatar) > 8 {
534 version = profile.Avatar[:8]
535 } else {
536 version = profile.Avatar
537 }
538 }
539
540 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did)
541 if size != "" {
542 if version != "" {
543 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version)
544 }
545 return fmt.Sprintf("%s?size=%s", baseUrl, size)
546 }
547 if version != "" {
548 return fmt.Sprintf("%s?v=%s", baseUrl, version)
549 }
550 return baseUrl
551}
552
553func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
554 iconPath := filepath.Join("static", "icons", name)
555
556 if filepath.Ext(name) == "" {
557 iconPath += ".svg"
558 }
559
560 data, err := Files.ReadFile(iconPath)
561 if err != nil {
562 return "", fmt.Errorf("icon %s not found: %w", name, err)
563 }
564
565 // Convert SVG data to string
566 svgStr := string(data)
567
568 svgTagEnd := strings.Index(svgStr, ">")
569 if svgTagEnd == -1 {
570 return "", fmt.Errorf("invalid SVG format for icon %s", name)
571 }
572
573 classTag := ` class="` + strings.Join(classes, " ") + `"`
574
575 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
576 return template.HTML(modifiedSVG), nil
577}
578
579func durationFmt(duration time.Duration, names [4]string) string {
580 days := int64(duration.Hours() / 24)
581 hours := int64(math.Mod(duration.Hours(), 24))
582 minutes := int64(math.Mod(duration.Minutes(), 60))
583 seconds := int64(math.Mod(duration.Seconds(), 60))
584
585 chunks := []struct {
586 name string
587 amount int64
588 }{
589 {names[0], days},
590 {names[1], hours},
591 {names[2], minutes},
592 {names[3], seconds},
593 }
594
595 parts := []string{}
596
597 for _, chunk := range chunks {
598 if chunk.amount != 0 {
599 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
600 }
601 }
602
603 return strings.Join(parts, " ")
604}