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