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 lexer = lexers.Fallback
299 }
300
301 iterator, err := lexer.Tokenise(nil, content)
302 if err != nil {
303 p.logger.Error("chroma tokenize", "err", "err")
304 return ""
305 }
306
307 var code bytes.Buffer
308 err = formatter.Format(&code, style, iterator)
309 if err != nil {
310 p.logger.Error("chroma format", "err", "err")
311 return ""
312 }
313
314 return code.String()
315 },
316 "trimUriScheme": func(text string) string {
317 text = strings.TrimPrefix(text, "https://")
318 text = strings.TrimPrefix(text, "http://")
319 return text
320 },
321 "isNil": func(t any) bool {
322 // returns false for other "zero" values
323 return t == nil
324 },
325 "list": func(args ...any) []any {
326 return args
327 },
328 "dict": func(values ...any) (map[string]any, error) {
329 if len(values)%2 != 0 {
330 return nil, errors.New("invalid dict call")
331 }
332 dict := make(map[string]any, len(values)/2)
333 for i := 0; i < len(values); i += 2 {
334 key, ok := values[i].(string)
335 if !ok {
336 return nil, errors.New("dict keys must be strings")
337 }
338 dict[key] = values[i+1]
339 }
340 return dict, nil
341 },
342 "queryParams": func(params ...any) (url.Values, error) {
343 if len(params)%2 != 0 {
344 return nil, errors.New("invalid queryParams call")
345 }
346 vals := make(url.Values, len(params)/2)
347 for i := 0; i < len(params); i += 2 {
348 key, ok := params[i].(string)
349 if !ok {
350 return nil, errors.New("queryParams keys must be strings")
351 }
352 v, ok := params[i+1].(string)
353 if !ok {
354 return nil, errors.New("queryParams values must be strings")
355 }
356 vals.Add(key, v)
357 }
358 return vals, nil
359 },
360 "deref": func(v any) any {
361 val := reflect.ValueOf(v)
362 if val.Kind() == reflect.Pointer && !val.IsNil() {
363 return val.Elem().Interface()
364 }
365 return nil
366 },
367 "i": func(name string, classes ...string) template.HTML {
368 data, err := p.icon(name, classes)
369 if err != nil {
370 log.Printf("icon %s does not exist", name)
371 data, _ = p.icon("airplay", classes)
372 }
373 return template.HTML(data)
374 },
375 "cssContentHash": p.CssContentHash,
376 "pathEscape": func(s string) string {
377 return url.PathEscape(s)
378 },
379 "pathUnescape": func(s string) string {
380 u, _ := url.PathUnescape(s)
381 return u
382 },
383 "safeUrl": func(s string) template.URL {
384 return template.URL(s)
385 },
386 "tinyAvatar": func(handle string) string {
387 return p.AvatarUrl(handle, "tiny")
388 },
389 "fullAvatar": func(handle string) string {
390 return p.AvatarUrl(handle, "")
391 },
392 "placeholderAvatar": func(size string) template.HTML {
393 sizeClass := "size-6"
394 iconSize := "size-4"
395 if size == "tiny" {
396 sizeClass = "size-6"
397 iconSize = "size-4"
398 } else if size == "small" {
399 sizeClass = "size-8"
400 iconSize = "size-5"
401 } else {
402 sizeClass = "size-12"
403 iconSize = "size-8"
404 }
405 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"})
406 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))
407 },
408 "profileAvatarUrl": func(profile *models.Profile, size string) string {
409 if profile != nil {
410 return p.AvatarUrl(profile.Did, size)
411 }
412 return ""
413 },
414 "langColor": enry.GetColor,
415 "reverse": func(s any) any {
416 if s == nil {
417 return nil
418 }
419
420 v := reflect.ValueOf(s)
421
422 if v.Kind() != reflect.Slice {
423 return s
424 }
425
426 length := v.Len()
427 reversed := reflect.MakeSlice(v.Type(), length, length)
428
429 for i := range length {
430 reversed.Index(i).Set(v.Index(length - 1 - i))
431 }
432
433 return reversed.Interface()
434 },
435 "normalizeForHtmlId": func(s string) string {
436 normalized := strings.ReplaceAll(s, ":", "_")
437 normalized = strings.ReplaceAll(normalized, ".", "_")
438 return normalized
439 },
440 "sshFingerprint": func(pubKey string) string {
441 fp, err := crypto.SSHFingerprint(pubKey)
442 if err != nil {
443 return "error"
444 }
445 return fp
446 },
447 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
448 result := make([]oauth.AccountInfo, 0, len(accounts))
449 for _, acc := range accounts {
450 if acc.Did != activeDid {
451 result = append(result, acc)
452 }
453 }
454 return result
455 },
456 "isGenerated": func(path string) bool {
457 return enry.IsGenerated(path, nil)
458 },
459 // constant values used to define a template
460 "const": func() map[string]any {
461 return map[string]any{
462 "OrderedReactionKinds": models.OrderedReactionKinds,
463 // would be great to have ordered maps right about now
464 "UserSettingsTabs": []tab{
465 {"Name": "profile", "Icon": "user"},
466 {"Name": "keys", "Icon": "key"},
467 {"Name": "emails", "Icon": "mail"},
468 {"Name": "notifications", "Icon": "bell"},
469 {"Name": "knots", "Icon": "volleyball"},
470 {"Name": "spindles", "Icon": "spool"},
471 {"Name": "sites", "Icon": "globe"},
472 },
473 "RepoSettingsTabs": []tab{
474 {"Name": "general", "Icon": "sliders-horizontal"},
475 {"Name": "access", "Icon": "users"},
476 {"Name": "pipelines", "Icon": "layers-2"},
477 {"Name": "hooks", "Icon": "webhook"},
478 {"Name": "sites", "Icon": "globe"},
479 },
480 }
481 },
482 }
483}
484
485func (p *Pages) resolveDid(did string) string {
486 identity, err := p.resolver.ResolveIdent(context.Background(), did)
487
488 if err != nil {
489 return did
490 }
491
492 if identity.Handle.IsInvalidHandle() {
493 return "handle.invalid"
494 }
495
496 return identity.Handle.String()
497}
498
499func (p *Pages) AvatarUrl(actor, size string) string {
500 actor = strings.TrimPrefix(actor, "@")
501
502 identity, err := p.resolver.ResolveIdent(context.Background(), actor)
503 var did string
504 if err != nil {
505 did = actor
506 } else {
507 did = identity.DID.String()
508 }
509
510 secret := p.avatar.SharedSecret
511 h := hmac.New(sha256.New, []byte(secret))
512 h.Write([]byte(did))
513 signature := hex.EncodeToString(h.Sum(nil))
514
515 // Get avatar CID for cache busting
516 profile, err := db.GetProfile(p.db, did)
517 version := ""
518 if err == nil && profile != nil && profile.Avatar != "" {
519 // Use first 8 chars of avatar CID as version
520 if len(profile.Avatar) > 8 {
521 version = profile.Avatar[:8]
522 } else {
523 version = profile.Avatar
524 }
525 }
526
527 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did)
528 if size != "" {
529 if version != "" {
530 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version)
531 }
532 return fmt.Sprintf("%s?size=%s", baseUrl, size)
533 }
534 if version != "" {
535 return fmt.Sprintf("%s?v=%s", baseUrl, version)
536 }
537 return baseUrl
538}
539
540func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
541 iconPath := filepath.Join("static", "icons", name)
542
543 if filepath.Ext(name) == "" {
544 iconPath += ".svg"
545 }
546
547 data, err := Files.ReadFile(iconPath)
548 if err != nil {
549 return "", fmt.Errorf("icon %s not found: %w", name, err)
550 }
551
552 // Convert SVG data to string
553 svgStr := string(data)
554
555 svgTagEnd := strings.Index(svgStr, ">")
556 if svgTagEnd == -1 {
557 return "", fmt.Errorf("invalid SVG format for icon %s", name)
558 }
559
560 classTag := ` class="` + strings.Join(classes, " ") + `"`
561
562 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
563 return template.HTML(modifiedSVG), nil
564}
565
566func durationFmt(duration time.Duration, names [4]string) string {
567 days := int64(duration.Hours() / 24)
568 hours := int64(math.Mod(duration.Hours(), 24))
569 minutes := int64(math.Mod(duration.Minutes(), 60))
570 seconds := int64(math.Mod(duration.Seconds(), 60))
571
572 chunks := []struct {
573 name string
574 amount int64
575 }{
576 {names[0], days},
577 {names[1], hours},
578 {names[2], minutes},
579 {names[3], seconds},
580 }
581
582 parts := []string{}
583
584 for _, chunk := range chunks {
585 if chunk.amount != 0 {
586 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
587 }
588 }
589
590 return strings.Join(parts, " ")
591}