package web
import (
"bytes"
"embed"
"html/template"
"io/fs"
"net/http"
"testing/fstest"
"time"
"amadan.net/oficina/estilo.git/base"
"amadan.net/oficina/estilo.git/brand"
"amadan.net/oficina/estilo.git/busy"
"amadan.net/oficina/estilo.git/chrome"
estilomenu "amadan.net/oficina/estilo.git/menu"
"amadan.net/oficina/estilo.git/theme"
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/sessions"
"amadan.net/rastrillo/rastrillo/ui"
)
//go:embed templates static
var appFS embed.FS
const assetPrefix = "/static/"
// The stylesheets in the suite's order: rastrillo's tokens, estilo's
// theme (Calma), then estilo's base, menu and chrome, then Alta's own.
// The brand mark is estilo's Oficina mark: Alta is not an app in the
// switcher and has no mark of its own.
var assets = rastrillo.NewAssets(func() fs.FS {
files := fstest.MapFS{
"static/tokens.css": {Data: ui.TokensCSS()},
"static/theme.css": {Data: theme.CSS()},
"static/estilo/base.css": {Data: base.CSS()},
"static/estilo/menu.css": {Data: estilomenu.CSS()},
"static/estilo/chrome.css": {Data: chrome.CSS()},
"static/oficina.svg": {Data: brand.SVG("oficina")},
}
b, err := appFS.ReadFile("static/alta.css")
if err != nil {
panic(err)
}
files["static/alta.css"] = &fstest.MapFile{Data: b}
return files
}())
func assetHandler() http.Handler {
busyH, files := busy.Handler(), assets.Handler()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) > len(busy.Prefix) && r.URL.Path[:len(busy.Prefix)] == busy.Prefix {
busyH.ServeHTTP(w, r)
return
}
files.ServeHTTP(w, r)
})
}
var pageNames = []string{"index", "team_new", "team", "run", "retire", "initialize", "notfound", "signedout"}
var pages = map[string]*template.Template{}
func init() {
for _, name := range pageNames {
t := template.New("layout").Funcs(ui.Funcs()).Funcs(template.FuncMap{
"asset": assets.Path,
"busyJS": func() string { return busy.Prefix + "busy.js" },
"busyCSS": func() string { return busy.Prefix + "busy.css" },
"when": func(t time.Time) string { return t.UTC().Format("2 Jan 15:04 UTC") },
"unix": func(n int64) string { return time.Unix(n, 0).UTC().Format("2 Jan 15:04 UTC") },
"describe": describe,
})
t = template.Must(t.ParseFS(ui.Templates(), "*.html"))
t = template.Must(t.ParseFS(chrome.Templates(), "templates/*.html"))
t = template.Must(t.ParseFS(estilomenu.Templates(), "templates/*.html"))
pages[name] = template.Must(t.ParseFS(appFS, "templates/layout.html", "templates/"+name+".html"))
}
}
// page is every template's data.
type page struct {
Title, Context string
Error, Notice string
Bare bool
Data map[string]any
Frame frame
}
type frame struct {
Chrome chrome.Bar
Theme string
}
func (a *App) frame(r *http.Request, p page) frame {
bar := chrome.Bar{
App: chrome.App{Name: "Alta", Slug: "alta", Home: "/", Icon: assets.Path("static/oficina.svg")},
Context: p.Context,
Labels: chrome.BarLabels{Skip: "Skip to content", Menu: "Menu"},
}
if s, ok := sessions.Current(r); ok && s.Subject == a.cfg.OperatorSubject && !p.Bare {
bar.Nav = []chrome.Link{{Href: "/", Label: "Teams", Current: r.URL.Path == "/"}, {Href: "/teams/new", Label: "New team", Current: r.URL.Path == "/teams/new"}}
bar.NavLabel = "Alta"
bar.Account = &chrome.Account{
TriggerLabel: "Account",
Initials: "P",
Address: "Paul",
Labels: chrome.AccountLabels{SignedInAs: "Signed in as", Appearance: "Appearance", Help: "Help"},
SignOut: chrome.SignOut{Action: "/signout", Label: "Sign out"},
}
} else {
bar.App.Home = ""
}
return frame{Chrome: bar, Theme: chrome.ThemeAttr(chrome.Appearance(r))}
}
func (a *App) render(w http.ResponseWriter, r *http.Request, status int, name string, p page) {
p.Frame = a.frame(r, p)
if p.Data == nil {
p.Data = map[string]any{}
}
var buf bytes.Buffer
if err := pages[name].ExecuteTemplate(&buf, "layout", p); err != nil {
a.cfg.Logger.Error("alta render", "page", name, "err", err)
a.plain(w, http.StatusInternalServerError, "Something went wrong.")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = buf.WriteTo(w)
}
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
a.render(w, r, http.StatusNotFound, "notfound", page{Title: "Not found", Bare: true})
}
func (a *App) plain(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = w.Write([]byte(msg + "\n"))
}