this repo has no description
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("Jan 2, 2006, 3:04 PM MST") 111 }, 112 "iso8601Fmt": func(t time.Time) string { 113 return t.Format("2006-01-02T15:04:05-07:00") 114 }, 115 "commaFmt": humanize.Comma, 116 "shortTimeFmt": func(t time.Time) string { 117 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{ 118 {time.Second, "now", time.Second}, 119 {2 * time.Second, "1s %s", 1}, 120 {time.Minute, "%ds %s", time.Second}, 121 {2 * time.Minute, "1min %s", 1}, 122 {time.Hour, "%dmin %s", time.Minute}, 123 {2 * time.Hour, "1hr %s", 1}, 124 {humanize.Day, "%dhrs %s", time.Hour}, 125 {2 * humanize.Day, "1d %s", 1}, 126 {20 * humanize.Day, "%dd %s", humanize.Day}, 127 {8 * humanize.Week, "%dw %s", humanize.Week}, 128 {humanize.Year, "%dmo %s", humanize.Month}, 129 {18 * humanize.Month, "1y %s", 1}, 130 {2 * humanize.Year, "2y %s", 1}, 131 {humanize.LongTime, "%dy %s", humanize.Year}, 132 {math.MaxInt64, "a long while %s", 1}, 133 }) 134 }, 135 "durationFmt": func(duration time.Duration) string { 136 days := int64(duration.Hours() / 24) 137 hours := int64(math.Mod(duration.Hours(), 24)) 138 minutes := int64(math.Mod(duration.Minutes(), 60)) 139 seconds := int64(math.Mod(duration.Seconds(), 60)) 140 141 chunks := []struct { 142 name string 143 amount int64 144 }{ 145 {"d", days}, 146 {"hr", hours}, 147 {"min", minutes}, 148 {"s", seconds}, 149 } 150 151 parts := []string{} 152 153 for _, chunk := range chunks { 154 if chunk.amount != 0 { 155 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name)) 156 } 157 } 158 159 return strings.Join(parts, " ") 160 }, 161 "byteFmt": humanize.Bytes, 162 "length": func(slice any) int { 163 v := reflect.ValueOf(slice) 164 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { 165 return v.Len() 166 } 167 return 0 168 }, 169 "splitN": func(s, sep string, n int) []string { 170 return strings.SplitN(s, sep, n) 171 }, 172 "escapeHtml": func(s string) template.HTML { 173 if s == "" { 174 return template.HTML("<br>") 175 } 176 return template.HTML(s) 177 }, 178 "unescapeHtml": func(s string) string { 179 return html.UnescapeString(s) 180 }, 181 "nl2br": func(text string) template.HTML { 182 return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1)) 183 }, 184 "unwrapText": func(text string) string { 185 paragraphs := strings.Split(text, "\n\n") 186 187 for i, p := range paragraphs { 188 lines := strings.Split(p, "\n") 189 paragraphs[i] = strings.Join(lines, " ") 190 } 191 192 return strings.Join(paragraphs, "\n\n") 193 }, 194 "sequence": func(n int) []struct{} { 195 return make([]struct{}, n) 196 }, 197 // take atmost N items from this slice 198 "take": func(slice any, n int) any { 199 v := reflect.ValueOf(slice) 200 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { 201 return nil 202 } 203 if v.Len() == 0 { 204 return nil 205 } 206 return v.Slice(0, min(n, v.Len()-1)).Interface() 207 }, 208 209 "markdown": func(text string) template.HTML { 210 rctx := &markup.RenderContext{RendererType: markup.RendererTypeDefault} 211 return template.HTML(bluemonday.UGCPolicy().Sanitize(rctx.RenderMarkdown(text))) 212 }, 213 "isNil": func(t any) bool { 214 // returns false for other "zero" values 215 return t == nil 216 }, 217 "list": func(args ...any) []any { 218 return args 219 }, 220 "dict": func(values ...any) (map[string]any, error) { 221 if len(values)%2 != 0 { 222 return nil, errors.New("invalid dict call") 223 } 224 dict := make(map[string]any, len(values)/2) 225 for i := 0; i < len(values); i += 2 { 226 key, ok := values[i].(string) 227 if !ok { 228 return nil, errors.New("dict keys must be strings") 229 } 230 dict[key] = values[i+1] 231 } 232 return dict, nil 233 }, 234 "deref": func(v any) any { 235 val := reflect.ValueOf(v) 236 if val.Kind() == reflect.Ptr && !val.IsNil() { 237 return val.Elem().Interface() 238 } 239 return nil 240 }, 241 "i": func(name string, classes ...string) template.HTML { 242 data, err := icon(name, classes) 243 if err != nil { 244 log.Printf("icon %s does not exist", name) 245 data, _ = icon("airplay", classes) 246 } 247 return template.HTML(data) 248 }, 249 "cssContentHash": CssContentHash, 250 "fileTree": filetree.FileTree, 251 "pathUnescape": func(s string) string { 252 u, _ := url.PathUnescape(s) 253 return u 254 }, 255 256 "tinyAvatar": p.tinyAvatar, 257 } 258} 259 260func (p *Pages) tinyAvatar(handle string) string { 261 handle = strings.TrimPrefix(handle, "@") 262 secret := p.avatar.SharedSecret 263 h := hmac.New(sha256.New, []byte(secret)) 264 h.Write([]byte(handle)) 265 signature := hex.EncodeToString(h.Sum(nil)) 266 return fmt.Sprintf("%s/%s/%s?size=tiny", p.avatar.Host, signature, handle) 267} 268 269func icon(name string, classes []string) (template.HTML, error) { 270 iconPath := filepath.Join("static", "icons", name) 271 272 if filepath.Ext(name) == "" { 273 iconPath += ".svg" 274 } 275 276 data, err := Files.ReadFile(iconPath) 277 if err != nil { 278 return "", fmt.Errorf("icon %s not found: %w", name, err) 279 } 280 281 // Convert SVG data to string 282 svgStr := string(data) 283 284 svgTagEnd := strings.Index(svgStr, ">") 285 if svgTagEnd == -1 { 286 return "", fmt.Errorf("invalid SVG format for icon %s", name) 287 } 288 289 classTag := ` class="` + strings.Join(classes, " ") + `"` 290 291 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:] 292 return template.HTML(modifiedSVG), nil 293}