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