forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
1package pages 2 3import ( 4 "context" 5 "crypto/hmac" 6 "crypto/sha256" 7 "encoding/hex" 8 "errors" 9 "fmt" 10 "html" 11 "html/template" 12 "log" 13 "math" 14 "net/url" 15 "path/filepath" 16 "reflect" 17 "strings" 18 "time" 19 20 "github.com/dustin/go-humanize" 21 "github.com/go-enry/go-enry/v2" 22 "tangled.sh/tangled.sh/core/appview/filetree" 23 "tangled.sh/tangled.sh/core/appview/pages/markup" 24) 25 26func (p *Pages) funcMap() template.FuncMap { 27 return template.FuncMap{ 28 "split": func(s string) []string { 29 return strings.Split(s, "\n") 30 }, 31 "resolve": func(s string) string { 32 identity, err := p.resolver.ResolveIdent(context.Background(), s) 33 34 if err != nil { 35 return s 36 } 37 38 if identity.Handle.IsInvalidHandle() { 39 return "handle.invalid" 40 } 41 42 return "@" + identity.Handle.String() 43 }, 44 "truncateAt30": func(s string) string { 45 if len(s) <= 30 { 46 return s 47 } 48 return s[:30] + "…" 49 }, 50 "splitOn": func(s, sep string) []string { 51 return strings.Split(s, sep) 52 }, 53 "int64": func(a int) int64 { 54 return int64(a) 55 }, 56 "add": func(a, b int) int { 57 return a + b 58 }, 59 "now": func() time.Time { 60 return time.Now() 61 }, 62 // the absolute state of go templates 63 "add64": func(a, b int64) int64 { 64 return a + b 65 }, 66 "sub": func(a, b int) int { 67 return a - b 68 }, 69 "f64": func(a int) float64 { 70 return float64(a) 71 }, 72 "addf64": func(a, b float64) float64 { 73 return a + b 74 }, 75 "subf64": func(a, b float64) float64 { 76 return a - b 77 }, 78 "mulf64": func(a, b float64) float64 { 79 return a * b 80 }, 81 "divf64": func(a, b float64) float64 { 82 if b == 0 { 83 return 0 84 } 85 return a / b 86 }, 87 "negf64": func(a float64) float64 { 88 return -a 89 }, 90 "cond": func(cond any, a, b string) string { 91 if cond == nil { 92 return b 93 } 94 95 if boolean, ok := cond.(bool); boolean && ok { 96 return a 97 } 98 99 return b 100 }, 101 "didOrHandle": func(did, handle string) string { 102 if handle != "" { 103 return fmt.Sprintf("@%s", handle) 104 } else { 105 return did 106 } 107 }, 108 "assoc": func(values ...string) ([][]string, error) { 109 if len(values)%2 != 0 { 110 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments") 111 } 112 pairs := make([][]string, 0) 113 for i := 0; i < len(values); i += 2 { 114 pairs = append(pairs, []string{values[i], values[i+1]}) 115 } 116 return pairs, nil 117 }, 118 "append": func(s []string, values ...string) []string { 119 s = append(s, values...) 120 return s 121 }, 122 "commaFmt": humanize.Comma, 123 "relTimeFmt": humanize.Time, 124 "shortRelTimeFmt": func(t time.Time) string { 125 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{ 126 {time.Second, "now", time.Second}, 127 {2 * time.Second, "1s %s", 1}, 128 {time.Minute, "%ds %s", time.Second}, 129 {2 * time.Minute, "1min %s", 1}, 130 {time.Hour, "%dmin %s", time.Minute}, 131 {2 * time.Hour, "1hr %s", 1}, 132 {humanize.Day, "%dhrs %s", time.Hour}, 133 {2 * humanize.Day, "1d %s", 1}, 134 {20 * humanize.Day, "%dd %s", humanize.Day}, 135 {8 * humanize.Week, "%dw %s", humanize.Week}, 136 {humanize.Year, "%dmo %s", humanize.Month}, 137 {18 * humanize.Month, "1y %s", 1}, 138 {2 * humanize.Year, "2y %s", 1}, 139 {humanize.LongTime, "%dy %s", humanize.Year}, 140 {math.MaxInt64, "a long while %s", 1}, 141 }) 142 }, 143 "longTimeFmt": func(t time.Time) string { 144 return t.Format("Jan 2, 2006, 3:04 PM MST") 145 }, 146 "iso8601DateTimeFmt": func(t time.Time) string { 147 return t.Format("2006-01-02T15:04:05-07:00") 148 }, 149 "iso8601DurationFmt": func(duration time.Duration) string { 150 days := int64(duration.Hours() / 24) 151 hours := int64(math.Mod(duration.Hours(), 24)) 152 minutes := int64(math.Mod(duration.Minutes(), 60)) 153 seconds := int64(math.Mod(duration.Seconds(), 60)) 154 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds) 155 }, 156 "durationFmt": func(duration time.Duration) string { 157 return durationFmt(duration, [4]string{"d", "hr", "min", "s"}) 158 }, 159 "longDurationFmt": func(duration time.Duration) string { 160 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"}) 161 }, 162 "byteFmt": humanize.Bytes, 163 "length": func(slice any) int { 164 v := reflect.ValueOf(slice) 165 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { 166 return v.Len() 167 } 168 return 0 169 }, 170 "splitN": func(s, sep string, n int) []string { 171 return strings.SplitN(s, sep, n) 172 }, 173 "escapeHtml": func(s string) template.HTML { 174 if s == "" { 175 return template.HTML("<br>") 176 } 177 return template.HTML(s) 178 }, 179 "unescapeHtml": func(s string) string { 180 return html.UnescapeString(s) 181 }, 182 "nl2br": func(text string) template.HTML { 183 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>")) 184 }, 185 "unwrapText": func(text string) string { 186 paragraphs := strings.Split(text, "\n\n") 187 188 for i, p := range paragraphs { 189 lines := strings.Split(p, "\n") 190 paragraphs[i] = strings.Join(lines, " ") 191 } 192 193 return strings.Join(paragraphs, "\n\n") 194 }, 195 "sequence": func(n int) []struct{} { 196 return make([]struct{}, n) 197 }, 198 // take atmost N items from this slice 199 "take": func(slice any, n int) any { 200 v := reflect.ValueOf(slice) 201 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { 202 return nil 203 } 204 if v.Len() == 0 { 205 return nil 206 } 207 return v.Slice(0, min(n, v.Len())).Interface() 208 }, 209 "markdown": func(text string) template.HTML { 210 p.rctx.RendererType = markup.RendererTypeDefault 211 htmlString := p.rctx.RenderMarkdown(text) 212 sanitized := p.rctx.SanitizeDefault(htmlString) 213 return template.HTML(sanitized) 214 }, 215 "description": func(text string) template.HTML { 216 p.rctx.RendererType = markup.RendererTypeDefault 217 htmlString := p.rctx.RenderMarkdown(text) 218 sanitized := p.rctx.SanitizeDescription(htmlString) 219 return template.HTML(sanitized) 220 }, 221 "isNil": func(t any) bool { 222 // returns false for other "zero" values 223 return t == nil 224 }, 225 "list": func(args ...any) []any { 226 return args 227 }, 228 "dict": func(values ...any) (map[string]any, error) { 229 if len(values)%2 != 0 { 230 return nil, errors.New("invalid dict call") 231 } 232 dict := make(map[string]any, len(values)/2) 233 for i := 0; i < len(values); i += 2 { 234 key, ok := values[i].(string) 235 if !ok { 236 return nil, errors.New("dict keys must be strings") 237 } 238 dict[key] = values[i+1] 239 } 240 return dict, nil 241 }, 242 "deref": func(v any) any { 243 val := reflect.ValueOf(v) 244 if val.Kind() == reflect.Ptr && !val.IsNil() { 245 return val.Elem().Interface() 246 } 247 return nil 248 }, 249 "i": func(name string, classes ...string) template.HTML { 250 data, err := icon(name, classes) 251 if err != nil { 252 log.Printf("icon %s does not exist", name) 253 data, _ = icon("airplay", classes) 254 } 255 return template.HTML(data) 256 }, 257 "cssContentHash": CssContentHash, 258 "fileTree": filetree.FileTree, 259 "pathEscape": func(s string) string { 260 return url.PathEscape(s) 261 }, 262 "pathUnescape": func(s string) string { 263 u, _ := url.PathUnescape(s) 264 return u 265 }, 266 267 "tinyAvatar": func(handle string) string { 268 return p.avatarUri(handle, "tiny") 269 }, 270 "fullAvatar": func(handle string) string { 271 return p.avatarUri(handle, "") 272 }, 273 "langColor": enry.GetColor, 274 "layoutSide": func() string { 275 return "col-span-1 md:col-span-2 lg:col-span-3" 276 }, 277 "layoutCenter": func() string { 278 return "col-span-1 md:col-span-8 lg:col-span-6" 279 }, 280 } 281} 282 283func (p *Pages) avatarUri(handle, size string) string { 284 handle = strings.TrimPrefix(handle, "@") 285 286 secret := p.avatar.SharedSecret 287 h := hmac.New(sha256.New, []byte(secret)) 288 h.Write([]byte(handle)) 289 signature := hex.EncodeToString(h.Sum(nil)) 290 291 sizeArg := "" 292 if size != "" { 293 sizeArg = fmt.Sprintf("size=%s", size) 294 } 295 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg) 296} 297 298func icon(name string, classes []string) (template.HTML, error) { 299 iconPath := filepath.Join("static", "icons", name) 300 301 if filepath.Ext(name) == "" { 302 iconPath += ".svg" 303 } 304 305 data, err := Files.ReadFile(iconPath) 306 if err != nil { 307 return "", fmt.Errorf("icon %s not found: %w", name, err) 308 } 309 310 // Convert SVG data to string 311 svgStr := string(data) 312 313 svgTagEnd := strings.Index(svgStr, ">") 314 if svgTagEnd == -1 { 315 return "", fmt.Errorf("invalid SVG format for icon %s", name) 316 } 317 318 classTag := ` class="` + strings.Join(classes, " ") + `"` 319 320 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:] 321 return template.HTML(modifiedSVG), nil 322} 323 324func durationFmt(duration time.Duration, names [4]string) string { 325 days := int64(duration.Hours() / 24) 326 hours := int64(math.Mod(duration.Hours(), 24)) 327 minutes := int64(math.Mod(duration.Minutes(), 60)) 328 seconds := int64(math.Mod(duration.Seconds(), 60)) 329 330 chunks := []struct { 331 name string 332 amount int64 333 }{ 334 {names[0], days}, 335 {names[1], hours}, 336 {names[2], minutes}, 337 {names[3], seconds}, 338 } 339 340 parts := []string{} 341 342 for _, chunk := range chunks { 343 if chunk.amount != 0 { 344 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name)) 345 } 346 } 347 348 return strings.Join(parts, " ") 349}