package web import ( "fmt" "html/template" "net/url" "strconv" "strings" "gitbay.org/cmc/gallery/internal/library" "gitbay.org/cmc/gallery/internal/render" ) var funcs = template.FuncMap{ "albumURL": albumURL, "photoURL": photoURL, "imgURL": imgURL, "srcset": srcset, "preloadSrcset": preloadSrcset, "ar": aspect, "exif": exifLine, "add": func(a, b int) int { return a + b }, } func albumURL(a *library.Album) string { return "/" + url.PathEscape(a.Slug) + "/" } func photoURL(it *library.Item) string { return "/" + url.PathEscape(it.Album) + "/" + url.PathEscape(it.Name) + "/" } func imgURL(it *library.Item, w int) string { return fmt.Sprintf("/img/%s/%s/%d.jpg?v=%d", url.PathEscape(it.Album), url.PathEscape(it.Name), w, it.ModTime.UnixNano()) } // srcset lists allowed widths up to the first one that reaches the source width. func srcset(it *library.Item) string { var parts []string for _, w := range render.Widths { actual := w reached := it.Meta.Width > 0 && w >= it.Meta.Width if reached { actual = it.Meta.Width } parts = append(parts, fmt.Sprintf("%s %dw", imgURL(it, w), actual)) if reached { break } } return strings.Join(parts, ", ") } // preloadSrcset renders the whole imagesrcset attribute: html/template treats // any unknown attribute containing "src" as a single URL and would escape the // spaces and commas a srcset list needs. func preloadSrcset(it *library.Item) template.HTMLAttr { return template.HTMLAttr(`imagesrcset="` + template.HTMLEscapeString(srcset(it)) + `"`) } func aspect(it *library.Item) string { if it.Meta.Height == 0 { return "1" } return strconv.FormatFloat(float64(it.Meta.Width)/float64(it.Meta.Height), 'f', 4, 64) } func exifLine(it *library.Item) string { m := it.Meta var parts []string for _, s := range []string{m.Camera, m.Lens, m.Aperture, m.Shutter} { if s != "" { parts = append(parts, s) } } if m.ISO > 0 { parts = append(parts, "ISO "+strconv.Itoa(m.ISO)) } if !m.Taken.IsZero() { parts = append(parts, m.Taken.Format("2006-01-02")) } return strings.Join(parts, " ยท ") }