// Package look is Base's face: the layout, the stylesheet and the fonts. // // Each consumer (Base's own web package, and later the apps Base ships) // supplies its page templates as an fs.FS and renders them through a // Renderer, so every page shares the same atmosphere. package look import ( "bytes" "embed" "fmt" "html/template" "io/fs" "net/http" "strings" "time" "amadan.net/rastrillo/rastrillo" ) // all: keeps the .keep file that holds the git-ignored timeless directory open. // //go:embed all:static templates var embedded embed.FS // Assets fingerprints the embedded static tree: {{asset "static/app.css"}} // in a template yields a content-hashed URL. Mount Assets.Handler() at // GET /static/. var Assets = rastrillo.NewAssets(embedded) const fontPrefix = "/static/fonts/" // FontHandler serves the embedded fonts. Mount it at GET /static/fonts/, // ahead of the generic static route. Font paths carry their version, so // files are immutable for a year. A font that is not there (Timeless Sans // until hack/fonts.sh has run) answers 404 and the page falls back to DM Sans. func FontHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { w.Header().Set("Allow", "GET, HEAD") http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) return } name := strings.TrimPrefix(r.URL.Path, "/") if !strings.HasPrefix(r.URL.Path, fontPrefix) || !fs.ValidPath(name) || !strings.HasSuffix(name, ".woff2") { http.NotFound(w, r) return } body, err := embedded.ReadFile(name) if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "font/woff2") w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(body)) }) } // Renderer renders page templates inside the shared layout. type Renderer struct { // pages holds each page once per theme ("" follows the device), so // the layout draws a member's Appearance without a script. pages map[string]map[string]*template.Template } // themes are the Appearances a page is drawn in: "" follows the device's // light or dark setting; "light" and "dark" hold that one. var themes = []string{"", "light", "dark"} // NewRenderer parses every top-level *.html in pageFS as a page named after // the file (without .html). A page defines the layout's "title" and "main" // blocks. Templates in partials/*.html are not pages: every page can use // what they define. funcs are extra template functions; "asset" is always // provided, and "theme" (the layout's: the Appearance it draws). func NewRenderer(pageFS fs.FS, funcs template.FuncMap) (*Renderer, error) { files, err := fs.Glob(pageFS, "*.html") if err != nil { return nil, err } partials, err := fs.Glob(pageFS, "partials/*.html") if err != nil { return nil, err } all := template.FuncMap{"asset": Assets.Path} for k, v := range funcs { all[k] = v } r := &Renderer{pages: make(map[string]map[string]*template.Template, len(themes))} for _, theme := range themes { r.pages[theme] = make(map[string]*template.Template, len(files)) all["theme"] = func() string { return theme } for _, f := range files { t, err := template.New("layout").Funcs(all).ParseFS(embedded, "templates/layout.html") if err != nil { return nil, err } if len(partials) > 0 { if t, err = t.ParseFS(pageFS, partials...); err != nil { return nil, fmt.Errorf("look: partials: %w", err) } } if t, err = t.ParseFS(pageFS, f); err != nil { return nil, fmt.Errorf("look: page %s: %w", f, err) } r.pages[theme][strings.TrimSuffix(f, ".html")] = t } } return r, nil } // Page renders the named page in layout.html with status 200. It executes // into a buffer first, so a template error writes nothing to w. func (r *Renderer) Page(w http.ResponseWriter, name string, data any) error { return r.PageStatus(w, http.StatusOK, name, data) } // PageStatus is Page with another status, such as 409 for a refused save // shown again with what the person typed. The page follows the device's // light or dark setting. func (r *Renderer) PageStatus(w http.ResponseWriter, status int, name string, data any) error { return r.PageTheme(w, status, name, data, "") } // PageTheme is PageStatus in a member's Appearance: "light" or "dark" holds // that theme; anything else follows the device. func (r *Renderer) PageTheme(w http.ResponseWriter, status int, name string, data any, theme string) error { byName, ok := r.pages[theme] if !ok { byName = r.pages[""] } t, ok := byName[name] if !ok { return fmt.Errorf("look: no page %q", name) } var buf bytes.Buffer if err := t.ExecuteTemplate(&buf, "layout", data); err != nil { return fmt.Errorf("look: render %s: %w", name, err) } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) _, err := buf.WriteTo(w) return err }