this repo has no description
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/filetree"
30 "tangled.org/core/appview/models"
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 "deref": func(v any) any {
338 val := reflect.ValueOf(v)
339 if val.Kind() == reflect.Ptr && !val.IsNil() {
340 return val.Elem().Interface()
341 }
342 return nil
343 },
344 "i": func(name string, classes ...string) template.HTML {
345 data, err := p.icon(name, classes)
346 if err != nil {
347 log.Printf("icon %s does not exist", name)
348 data, _ = p.icon("airplay", classes)
349 }
350 return template.HTML(data)
351 },
352 "cssContentHash": p.CssContentHash,
353 "fileTree": filetree.FileTree,
354 "pathEscape": func(s string) string {
355 return url.PathEscape(s)
356 },
357 "pathUnescape": func(s string) string {
358 u, _ := url.PathUnescape(s)
359 return u
360 },
361 "safeUrl": func(s string) template.URL {
362 return template.URL(s)
363 },
364 "tinyAvatar": func(handle string) string {
365 return p.AvatarUrl(handle, "tiny")
366 },
367 "fullAvatar": func(handle string) string {
368 return p.AvatarUrl(handle, "")
369 },
370 "langColor": enry.GetColor,
371 "layoutSide": func() string {
372 return "col-span-1 md:col-span-2 lg:col-span-3"
373 },
374 "layoutCenter": func() string {
375 return "col-span-1 md:col-span-8 lg:col-span-6"
376 },
377
378 "normalizeForHtmlId": func(s string) string {
379 normalized := strings.ReplaceAll(s, ":", "_")
380 normalized = strings.ReplaceAll(normalized, ".", "_")
381 return normalized
382 },
383 "sshFingerprint": func(pubKey string) string {
384 fp, err := crypto.SSHFingerprint(pubKey)
385 if err != nil {
386 return "error"
387 }
388 return fp
389 },
390 // constant values used to define a template
391 "const": func() map[string]any {
392 return map[string]any{
393 "OrderedReactionKinds": models.OrderedReactionKinds,
394 // would be great to have ordered maps right about now
395 "UserSettingsTabs": []tab{
396 {"Name": "profile", "Icon": "user"},
397 {"Name": "keys", "Icon": "key"},
398 {"Name": "emails", "Icon": "mail"},
399 {"Name": "notifications", "Icon": "bell"},
400 {"Name": "knots", "Icon": "volleyball"},
401 {"Name": "spindles", "Icon": "spool"},
402 },
403 "RepoSettingsTabs": []tab{
404 {"Name": "general", "Icon": "sliders-horizontal"},
405 {"Name": "access", "Icon": "users"},
406 {"Name": "pipelines", "Icon": "layers-2"},
407 },
408 }
409 },
410 }
411}
412
413func (p *Pages) resolveDid(did string) string {
414 identity, err := p.resolver.ResolveIdent(context.Background(), did)
415
416 if err != nil {
417 return did
418 }
419
420 if identity.Handle.IsInvalidHandle() {
421 return "handle.invalid"
422 }
423
424 return identity.Handle.String()
425}
426
427func (p *Pages) AvatarUrl(handle, size string) string {
428 handle = strings.TrimPrefix(handle, "@")
429
430 handle = p.resolveDid(handle)
431
432 secret := p.avatar.SharedSecret
433 h := hmac.New(sha256.New, []byte(secret))
434 h.Write([]byte(handle))
435 signature := hex.EncodeToString(h.Sum(nil))
436
437 sizeArg := ""
438 if size != "" {
439 sizeArg = fmt.Sprintf("size=%s", size)
440 }
441 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
442}
443
444func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
445 iconPath := filepath.Join("static", "icons", name)
446
447 if filepath.Ext(name) == "" {
448 iconPath += ".svg"
449 }
450
451 data, err := Files.ReadFile(iconPath)
452 if err != nil {
453 return "", fmt.Errorf("icon %s not found: %w", name, err)
454 }
455
456 // Convert SVG data to string
457 svgStr := string(data)
458
459 svgTagEnd := strings.Index(svgStr, ">")
460 if svgTagEnd == -1 {
461 return "", fmt.Errorf("invalid SVG format for icon %s", name)
462 }
463
464 classTag := ` class="` + strings.Join(classes, " ") + `"`
465
466 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
467 return template.HTML(modifiedSVG), nil
468}
469
470func durationFmt(duration time.Duration, names [4]string) string {
471 days := int64(duration.Hours() / 24)
472 hours := int64(math.Mod(duration.Hours(), 24))
473 minutes := int64(math.Mod(duration.Minutes(), 60))
474 seconds := int64(math.Mod(duration.Seconds(), 60))
475
476 chunks := []struct {
477 name string
478 amount int64
479 }{
480 {names[0], days},
481 {names[1], hours},
482 {names[2], minutes},
483 {names[3], seconds},
484 }
485
486 parts := []string{}
487
488 for _, chunk := range chunks {
489 if chunk.amount != 0 {
490 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
491 }
492 }
493
494 return strings.Join(parts, " ")
495}