Files
LektorenPlan/web/web/render.go
T

420 lines
16 KiB
Go

package web
import (
"bytes"
"fmt"
"html/template"
"log"
"math"
"net/http"
"strconv"
"strings"
"time"
"lektorenplan/domain"
"lektorenplan/store"
)
type viewData struct {
Title string
Active string
User *store.User
Session *store.Session
Tenant *store.Tenant
Tenants []store.Tenant
CSRF string
Flash string
FlashKind string
IsEditor bool
IsAdmin bool
Version string
DemoMode bool
LoginQuote string
LoginQuoteSource string
Data any
}
func (s *Server) baseView(w http.ResponseWriter, r *http.Request, title, active string) viewData {
user := userFrom(r)
session := sessionFrom(r)
tenant := tenantFrom(r)
flash, kind := s.popFlash(w, r)
data := viewData{
Title: title, Active: active, User: user, Session: session, Tenant: tenant,
Flash: flash, FlashKind: kind, Version: s.opts.Version, DemoMode: s.opts.DemoMode,
LoginQuote: s.loginQuote(r),
LoginQuoteSource: s.loginQuoteSource(r),
}
if session != nil {
data.CSRF = session.CSRFToken
}
if user != nil {
data.IsAdmin = user.Role.IsAdmin()
tenants, _ := s.store.TenantsForUser(r.Context(), user)
data.Tenants = tenants
if tenant != nil {
data.IsEditor = s.store.CanEditTenant(r.Context(), user, tenant.ID)
}
}
return data
}
func (s *Server) render(w http.ResponseWriter, r *http.Request, status int, name string, data viewData) {
t, ok := s.views[name]
if !ok {
http.Error(w, "template missing: "+name, http.StatusInternalServerError)
return
}
// Render into a buffer first: a template error must not leave a
// half-written 200 response behind.
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, "layout", data); err != nil {
log.Printf("render %s: %v", name, err)
http.Error(w, "Die Seite konnte nicht erstellt werden.", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
if _, err := buf.WriteTo(w); err != nil {
log.Printf("write %s: %v", name, err)
}
}
func (s *Server) renderPage(w http.ResponseWriter, r *http.Request, name string, data viewData) {
s.render(w, r, http.StatusOK, name, data)
}
func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, title, message string) {
data := s.baseView(w, r, title, "")
data.Data = struct {
Title string
Message string
Status int
}{title, message, status}
s.render(w, r, status, "error", data)
}
func templateFunctions() template.FuncMap {
return template.FuncMap{
"longDate": domain.LongString,
"mediumDate": domain.MediumString,
"shortDate": dayMonthYear,
"isoDate": domain.Key,
"isoDatePtr": func(value *time.Time) string {
if value == nil {
return ""
}
return domain.Key(*value)
},
"dayNumber": domain.DayNumber,
"monthNumber": domain.Month,
"yearOf": domain.Year,
"monthName": domain.MonthName,
"monthNumberName": func(number int) string {
if number < 1 || number > 12 {
return ""
}
return domain.MonthName(time.Date(2024, time.Month(number), 1, 12, 0, 0, 0, time.UTC))
},
"shortMonthNumber": func(number int) string {
if number < 1 || number > 12 {
return ""
}
return domain.ShortMonthName(time.Date(2024, time.Month(number), 1, 12, 0, 0, 0, time.UTC))
},
"shortMonth": domain.ShortMonthName,
"weekdayName": domain.WeekdayName,
"shortWeekday": domain.ShortWeekdayName,
"weekdayNumberName": func(number int) string {
for _, option := range weekdays {
if option.Number == number {
return option.Name
}
}
return "?"
},
"upperWeekday": func(t time.Time) string { return strings.ToUpper(domain.ShortWeekdayName(t)) },
"addDays": func(days int, t time.Time) time.Time { return domain.AddingDays(days, t) },
"addMonths": domain.AddingMonths,
"rangeTitle": func(r domain.DayRange) string { return r.Title() },
"rangeShort": func(r domain.DayRange) string { return r.ShortTitle() },
"rangeLong": func(r domain.DayRange) string { return r.LongTitle() },
"dayCount": func(r domain.DayRange) int { return r.DayCount() },
"timeLabel": domain.TimeString,
"roleTitle": func(role domain.Role) string { return role.Title() },
"rolePlural": func(role domain.Role) string { return role.Plural() },
"roleShort": func(role domain.Role) string { return role.ShortCode() },
"userRole": func(role store.UserRole) string { return store.UserRoleTitle(role) },
"dioceses": func() any { return dioceseOptions },
"percent": percentLabel,
"coverage": func(stats domain.RangeStatistics) string { return percentLabel(stats.CoverageRate()) },
"preferencePct": func(stats domain.RangeStatistics) string { return percentLabel(stats.PreferenceRate()) },
"initial": initial,
"initials": initials,
"deref": derefString,
"derefTime": func(value *time.Time) time.Time {
if value == nil {
return time.Time{}
}
return *value
},
"formatFloat": func(value float64) string {
// Template output uses one decimal with a German comma. Round
// half-up explicitly; FormatFloat alone rounds 0.25 to 0.2.
rounded := math.Round(value*10) / 10
return strings.Replace(strconv.FormatFloat(rounded, 'f', 1, 64), ".", ",", 1)
},
"setting": sSetting,
"safe": func(value string) template.HTML { return template.HTML(value) },
"churchGlyph": churchGlyph,
"feastGlyph": feastGlyph,
"icon": iconSVG,
"barHeight": barHeight,
"percentage": percentageWidth,
"ratio": func(value, max int) float64 {
if max <= 0 || value <= 0 {
return 0
}
return float64(value) / float64(max)
},
"plural": plural,
"abs": func(value int) int {
if value < 0 {
return -value
}
return value
},
"join": strings.Join,
"trim": strings.TrimSpace,
"lower": strings.ToLower,
"eqs": func(a, b string) bool { return a == b },
"containsInt": domain.IntContains,
"containsString": domain.StringContains,
"hasRole": func(person domain.Person, role domain.Role) bool { return person.CanFill(role) },
"roleChecked": func(person domain.Person, role string) bool {
return person.CanFill(domain.Role(role))
},
"monthLabel": func(key string) string { return monthLabel(key) },
"add": func(a, b int) int { return a + b },
"sub": func(a, b int) int { return a - b },
"seq": func(from, to int) []int {
if to < from {
return nil
}
out := make([]int, 0, to-from+1)
for i := from; i <= to; i++ {
out = append(out, i)
}
return out
},
"liturgicalColor": func(day *domain.LiturgicalDay) string {
if day == nil {
return "#C2A14D"
}
return day.ColorHex()
},
}
}
// sSetting is a stub placeholder kept out of templates that need context; the
// actual values are passed in page data.
func sSetting(key string) string { return "" }
func dayMonthYear(t time.Time) string {
return fmt.Sprintf("%02d.%02d.%d", domain.DayNumber(t), domain.Month(t), domain.Year(t))
}
func monthLabel(key string) string {
parts := strings.Split(key, "-")
if len(parts) < 2 {
return key
}
date, ok := domain.DateFromKey(key + "-01")
if !ok {
return key
}
return domain.MonthName(date) + " " + parts[0]
}
func percentLabel(value float64) string {
if math.IsNaN(value) || math.IsInf(value, 0) {
return "0 %"
}
return fmt.Sprintf("%.0f %%", value*100)
}
func percentageWidth(value float64) string {
if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 {
value = 0
}
if value > 1 {
value = 1
}
return fmt.Sprintf("%.1f%%", value*100)
}
func barHeight(value, maxValue int) string {
if maxValue <= 0 || value <= 0 {
return "2px"
}
height := 4 + int(90*float64(value)/float64(maxValue))
return fmt.Sprintf("%dpx", height)
}
func initial(name string) string {
runes := []rune(strings.TrimSpace(name))
if len(runes) == 0 {
return "?"
}
return strings.ToUpper(string(runes[0]))
}
func initials(first, last string) string {
out := ""
if runes := []rune(strings.TrimSpace(first)); len(runes) > 0 {
out += strings.ToUpper(string(runes[0]))
}
if runes := []rune(strings.TrimSpace(last)); len(runes) > 0 {
out += strings.ToUpper(string(runes[0]))
}
if out == "" {
return "?"
}
return out
}
func derefString(value *string) string {
if value == nil {
return ""
}
return *value
}
func plural(count int, singular, pluralForm string) string {
if count == 1 {
return fmt.Sprintf("%d %s", count, singular)
}
return fmt.Sprintf("%d %s", count, pluralForm)
}
// Church glyphs -------------------------------------------------------------
var glyphBodies = map[string]string{
"basilica": `
<path d="M42 42 L60 28 L78 42 L78 75 L42 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M39 43 L60 26 L81 43"/>
<path d="M27 55 L27 75 L42 75 L42 50 L32 47"/>
<path d="M78 50 L78 75 L93 75 L93 55 L83 59"/>
<path d="M88 26 L99 26 L99 75 L88 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M86 27 L93.5 12 L101 27"/>
<path d="M55 75 L55 62 Q60 54 65 62 L65 75"/>
<path d="M48 68 L48 58 Q51 53 54 58 L54 68"/>
<path d="M72 68 L72 58 Q75 53 78 58 L78 68"/>
<path d="M93.5 12 L93.5 4 M90.5 7 L96.5 7"/>`,
"gothic": `
<path d="M36 75 L36 44 Q46 37 60 35 Q74 37 84 44 L84 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M31 45 L60 8 L89 45"/>
<path d="M88 29 L101 29 L101 75 L88 75"/>
<path d="M85 30 L94.5 10 L104 30"/>
<path d="M54 75 L54 57 Q60 48 66 57 L66 75"/>
<circle cx="60" cy="54" r="10"/>
<path d="M69 54 L60 54 M64.5 61.8 L60 54 M55.5 61.8 L60 54 M51 54 L60 54 M55.5 46.2 L60 54 M64.5 46.2 L60 54"/>
<path d="M60 8 L60 1 M57 4 L63 4"/>`,
"modern": `
<path d="M30 75 L34 43 L63 31 L87 46 L86 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M28 45 L63 28 L89 46"/>
<path d="M91 24 L103 24 L103 75 L91 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M96.5 34 L96.5 62 M98.5 34 L98.5 62"/>
<path d="M97 24 L97 12 M92 17 L102 17"/>
<path d="M38 72 L38 50 L58 43 L58 72 Z"/>
<path d="M40 70 L42.5 47 M46 70 L48.5 47 M52 70 L54.5 47"/>
<path d="M66 75 L66 56 L82 51 L82 75"/>`,
"rotunda": `
<path d="M28 75 L32 53 Q60 39 88 53 L92 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M32 53 Q60 26 88 53"/>
<path d="M56 36 L64 36 L64 31 L56 31 Z"/>
<path d="M60 31 L60 20 M55.5 24 L64.5 24"/>
<path d="M38 70 L38 58 M47 70 L47 58 M73 70 L73 58 M82 70 L82 58"/>
<path d="M55 75 L55 61 Q60 55 65 61 L65 75"/>`,
"roundTower": `
<path d="M35 75 L35 35 L78 35 L78 75"/>
<path d="M30 36 L56.5 12 L83 36"/>
<ellipse cx="94" cy="55" rx="10" ry="20" fill="currentColor" fill-opacity=".055"/>
<path d="M82 35 Q94 20 106 35"/>
<path d="M94 24 L94 14 M90 18 L98 18"/>
<path d="M51 70 L51 48 Q56 42 61 48 L61 70"/>`,
"chapel": `
<path d="M40 75 L40 46 L78 46 L78 75 Z" fill="currentColor" fill-opacity=".055"/>
<path d="M35 47 L59 24 L83 47"/>
<path d="M59 24 L59 13 M55 17 L63 17"/>
<path d="M55 75 L55 60 Q60 53 65 60 L65 75"/>
<ellipse cx="48.5" cy="60.5" rx="3.5" ry="5.5"/>
<ellipse cx="70.5" cy="60.5" rx="3.5" ry="5.5"/>`,
}
func churchGlyph(symbol any, color string) template.HTML {
key := fmt.Sprint(symbol)
body, ok := glyphBodies[key]
if !ok {
body = glyphBodies["chapel"]
}
if strings.TrimSpace(color) == "" {
color = "#2E5C57"
}
return template.HTML(fmt.Sprintf(
`<svg class="church-glyph" viewBox="0 0 120 86" role="img" aria-hidden="true" style="color:%s" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">%s<path d="M8 76 L112 76" stroke-opacity=".35" stroke-width=".8" stroke-dasharray="2 3"/></svg>`,
template.HTMLEscapeString(color), body))
}
var feastGlyphPaths = map[string]string{
"star": `<path d="M12 2.5l2.6 6.1 6.4.6-4.9 4.3 1.5 6.3L12 16.4l-5.6 3.4 1.5-6.3-4.9-4.3 6.4-.6z"/>`,
"sun": `<circle cx="12" cy="12" r="4.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22M4.9 4.9l1.7 1.7M17.4 17.4l1.7 1.7M19.1 4.9l-1.7 1.7M6.6 17.4l-1.7 1.7"/>`,
"flame": `<path d="M12 21c4 0 6.5-2.7 6.5-6.2 0-2.6-1.4-4.6-3.1-6.4-1.3-1.4-2.4-3-2.7-5.4-2.1 1.6-3.5 3.6-3.5 6 0 1.3.4 2.2 1 3.1-.9.1-2.4-.9-2.9-2.2-.4 1.2-.6 2.4-.6 3.5C6.7 18.1 8.5 21 12 21z"/>`,
"lily": `<path d="M12 21V9M12 9C9.2 7.6 8.3 4.6 9.4 2c2.2.6 3.4 2.2 2.6 7zM12 9c2.8-1.4 3.7-4.4 2.6-7-2.2.6-3.4 2.2-2.6 7z"/><path d="M12 16c-2.6 0-4.4 1.5-5 3.4M12 16c2.6 0 4.4 1.5 5 3.4"/>`,
"crown": `<path d="M3 18h18l-1.4-9-4.8 3.3L12 6l-2.8 6.3L4.4 9z"/><path d="M4 21h16"/>`,
"heart": `<path d="M12 20.5S3.5 15.2 3.5 9.3C3.5 6.5 5.6 4.5 8 4.5c1.7 0 3.2 1 4 2.5.8-1.5 2.3-2.5 4-2.5 2.4 0 4.5 2 4.5 4.8 0 5.9-8.5 11.2-8.5 11.2z"/>`,
"book": `<path d="M4 5.5c2.8-1 5.6-1 8 .5 2.4-1.5 5.2-1.5 8-.5v14c-2.8-1-5.6-1-8 .5-2.4-1.5-5.2-1.5-8-.5z"/><path d="M12 6v14"/>`,
"candle": `<path d="M9 21h6V9H9zM12 9V6M12 6c-1.6 0-2.6-1.2-2.6-2.6C10.8 3.4 12 4.4 12 6zm0 0c1.6 0 2.6-1.2 2.6-2.6C13.2 3.4 12 4.4 12 6z"/><path d="M6 21h12"/>`,
"dove": `<path d="M20.5 5.5c-2.2.2-4 1.2-5.2 2.8C14 6.6 12.6 5.5 10.5 5.5c-3 0-5 2.3-5 5.2 0 4 3.9 7 8.5 8.3 4.6-1.3 8.5-4.3 8.5-8.3 0-1.7-.7-3.2-1.5-4.2z"/><path d="M9 13c2 .2 3.8 1 5 2.2"/>`,
"cross": `<path d="M12 2v20M6 8h12"/>`,
}
func feastGlyph(symbol any) template.HTML {
key := fmt.Sprint(symbol)
body, ok := feastGlyphPaths[key]
if !ok {
body = feastGlyphPaths["book"]
}
return template.HTML(`<svg class="feast-glyph" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`)
}
var iconPaths = map[string]string{
"calendar": `<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/>`,
"list": `<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>`,
"users": `<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>`,
"chart": `<path d="M3 3v18h18"/><path d="M7 16v-5M12 16V7M17 16v-8"/>`,
"exchange": `<path d="M4 7h13l-3-3M20 17H7l3 3"/>`,
"settings": `<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 8.6 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 8.6a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.1.4.3.8.6 1 .3.3.7.4 1.1.4H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51.6z"/>`,
"shield": `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/>`,
"printer": `<path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>`,
"plus": `<path d="M12 5v14M5 12h14"/>`,
"left": `<path d="M15 18l-6-6 6-6"/>`,
"right": `<path d="M9 18l6-6-6-6"/>`,
"sparkles": `<path d="M12 3l1.9 4.6L18.5 9.5l-4.6 1.9L12 16l-1.9-4.6L5.5 9.5l4.6-1.9z"/><path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9z"/>`,
"logout": `<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/>`,
"church": `<path d="M12 2v6M9 5h6M6 22V11l6-4 6 4v11z"/><path d="M10 22v-5h4v5"/>`,
"check": `<path d="M20 6L9 17l-5-5"/>`,
"trash": `<path d="M3 6h18M8 6V4h8v2M19 6l-1 15H6L5 6M10 11v6M14 11v6"/>`,
"external": `<path d="M14 3h7v7M10 14L21 3M21 14v7H3V3h7"/>`,
"menu": `<path d="M4 7h16M4 12h16M4 17h16"/>`,
"close": `<path d="M6 6l12 12M18 6L6 18"/>`,
}
func iconSVG(name string) template.HTML {
body, ok := iconPaths[name]
if !ok {
body = iconPaths["calendar"]
}
return template.HTML(`<svg class="icon" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`)
}