showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
render.go
10.2 KB · 332 lines
1// Package render turns data into static HTML files.2package render34import (5 "bytes"6 "cmp"7 "crypto/sha256"8 "encoding/hex"9 "fmt"10 "hash/fnv"11 "html/template"12 "io/fs"13 "os"14 "path"15 "path/filepath"16 "regexp"17 "strconv"18 "strings"19 "time"2021 "daum.dev/showcase/web"22)2324type Renderer struct {25 Now time.Time // fixed per build so output is deterministic26 css string // short hash of style.css, so caches never serve a stale one27 Theme string // saturn palette name, the default without JS28 Base string // base_path ("/projects"), put in front of every root-relative link29 pages map[string]*template.Template30 syms map[string][]byte // sprite symbols by id: f-<glyph> file icons, i-<name> UI icons31}3233// Page is what every template receives.34type Page struct {35 Title string36 Meta string // optional meta description37 GoImport string // optional go-import meta content38 D any3940 Theme string // filled in by Write41 CSS string42}4344func New(now time.Time) (*Renderer, error) {45 h := sha256.New() // one version for the stylesheet and both scripts46 for _, f := range []string{"static/style.css", "static/theme.js", "static/copy.js"} {47 b, err := web.FS.ReadFile(f)48 if err != nil {49 return nil, err50 }51 h.Write(b)52 }53 r := &Renderer{Now: now, css: hex.EncodeToString(h.Sum(nil)[:5]), pages: map[string]*template.Template{}}54 var err error55 if r.syms, err = loadSymbols(); err != nil {56 return nil, err57 }58 funcs := template.FuncMap{59 "ago": r.ago,60 "fresh": r.fresh,61 "live": func(t time.Time) bool { return !t.IsZero() && r.Now.Sub(t) < 24*time.Hour },62 "isnew": func(t time.Time) bool { return !t.IsZero() && r.Now.Sub(t) < 7*24*time.Hour },63 "ficon": fileIcon,64 "dec": func(i int) int { return i - 1 },65 "dict": func(kv ...any) map[string]any {66 m := map[string]any{}67 for i := 0; i+1 < len(kv); i += 2 {68 m[kv[i].(string)] = kv[i+1]69 }70 return m71 },72 "trimScheme": func(u string) string {73 return strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(u, "https://"), "http://"), "/")74 },75 "pct": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },76 "date": func(t time.Time) string { return t.UTC().Format("2006-01-02") },77 "lang": langClass,78 "size": humanSize,79 "inc": func(i int) int { return i + 1 },80 "day": func(t time.Time) string { return t.UTC().Format("02 Jan 06") },81 "diff": diffClass,82 }83 names, err := fs.Glob(web.FS, "templates/*.html")84 if err != nil {85 return nil, err86 }87 for _, n := range names {88 if path.Base(n) == "base.html" || strings.HasPrefix(path.Base(n), "_") {89 continue90 }91 // base.html and _*.html partials are shared by every page.92 t, err := template.New("").Funcs(funcs).ParseFS(web.FS, "templates/base.html", "templates/_*.html", n)93 if err != nil {94 return nil, err95 }96 r.pages[strings.TrimSuffix(path.Base(n), ".html")] = t97 }98 return r, nil99}100101// Write renders template name into dir/rel.102func (r *Renderer) Write(dir, rel, name string, p Page) error {103 t, ok := r.pages[name]104 if !ok {105 return fmt.Errorf("render: no template %q", name)106 }107 p.Theme, p.CSS = r.Theme, r.css108 var buf bytes.Buffer109 if err := t.ExecuteTemplate(&buf, "base", p); err != nil {110 return fmt.Errorf("render %s: %w", rel, err)111 }112 return WriteFile(filepath.Join(dir, filepath.FromSlash(rel)), r.rebase(r.fillSprite(buf.Bytes())))113}114115// rootLink matches a root-relative href or src: html/template always quotes116// attributes with ", and quotes inside text and values are escaped, so this117// only finds real attributes. "//host" links are left alone.118var rootLink = regexp.MustCompile(`(\s(?:href|src)=")/([^/])`)119120// rebase moves every root-relative link under r.Base. Templates and the121// builder write links from the site root; this one pass keeps them all,122// README links included, right when the pages live under a path.123func (r *Renderer) rebase(b []byte) []byte {124 if r.Base == "" {125 return b126 }127 return rootLink.ReplaceAll(b, []byte("${1}"+r.Base+"/${2}"))128}129130// WriteFile writes b to name, creating parent directories.131func WriteFile(name string, b []byte) error {132 if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil {133 return err134 }135 return os.WriteFile(name, b, 0o644)136}137138// CopyStatic copies the embedded static assets into dir/static.139func CopyStatic(dir string) error {140 return fs.WalkDir(web.FS, "static", func(p string, d fs.DirEntry, err error) error {141 if err != nil || d.IsDir() {142 return err143 }144 if strings.HasPrefix(p, "static/icons/") { // inlined into pages, never fetched145 return nil146 }147 b, err := web.FS.ReadFile(p)148 if err != nil {149 return err150 }151 return WriteFile(filepath.Join(dir, filepath.FromSlash(p)), b)152 })153}154155func (r *Renderer) ago(t time.Time) string {156 d := r.Now.Sub(t)157 days := int(d.Hours() / 24)158 switch {159 case t.IsZero():160 return ""161 case d < time.Minute:162 return "just now"163 case d < time.Hour:164 return plural(int(d.Minutes()), "minute")165 case d < 24*time.Hour:166 return plural(int(d.Hours()), "hour")167 case days < 7:168 return plural(days, "day")169 case days < 30:170 return plural(days/7, "week")171 case days < 365:172 return plural(days/30, "month")173 }174 return plural(days/365, "year")175}176177// fresh classes an age so recent changes stand out: within a day, a week178// or a month.179func (r *Renderer) fresh(t time.Time) string {180 switch d := r.Now.Sub(t); {181 case t.IsZero():182 return ""183 case d < 24*time.Hour:184 return "fresh-1"185 case d < 7*24*time.Hour:186 return "fresh-2"187 case d < 30*24*time.Hour:188 return "fresh-3"189 }190 return ""191}192193func plural(n int, unit string) string {194 switch {195 case n == 1 && (unit == "week" || unit == "month" || unit == "year"):196 return "last " + unit197 case n != 1:198 unit += "s"199 }200 return fmt.Sprintf("%d %s ago", n, unit)201}202203// langColors gives common languages fixed accent slots, chosen so languages204// that often share a repo get different colours. Others hash into a slot.205var langColors = map[string]int{206 "CSS": 0, "Kotlin": 0, "Elixir": 0,207 "Go": 1, "TypeScript": 1, "Lua": 1,208 "C": 2, "Nix": 2, "Dockerfile": 2, "Vue": 2,209 "JavaScript": 3, "Python": 3, "Svelte": 3,210 "HTML": 4, "Ruby": 4, "Objective-C": 4,211 "Swift": 5, "Rust": 5, "Java": 5, "C++": 5,212 "Shell": 6, "Templ": 6, "PHP": 6,213 "Makefile": 7, "Just": 7, "Markdown": 7, "SCSS": 7,214}215216// langClass maps a language name to one of eight accent colour classes.217func langClass(name string) string {218 if i, ok := langColors[name]; ok {219 return fmt.Sprintf("lang-%d", i)220 }221 h := fnv.New32a()222 h.Write([]byte(name))223 return fmt.Sprintf("lang-%d", h.Sum32()%8)224}225226func humanSize(n int64) string {227 switch {228 case n < 1<<10:229 return fmt.Sprintf("%d B", n)230 case n < 1<<20:231 return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))232 case n < 1<<30:233 return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))234 }235 return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))236}237238// diffClass maps a diff line kind to a CSS class; +/- reuse saturn's roles.239func diffClass(kind byte) string {240 switch kind {241 case '+':242 return "hl-added"243 case '-':244 return "hl-removed"245 case '@':246 return "hunk"247 }248 return ""249}250251// fileIcon picks a material-icon-theme icon (see scripts/icons.py) by file252// or folder name, then by extension, longest first ("test.ts" before "ts").253// The current folder in breadcrumbs ("tree-open") gets the open folder.254func fileIcon(name, typ string) template.HTML {255 n, icon := strings.ToLower(name), "file"256 switch {257 case typ == "tree-open":258 icon = "folder-open"259 case typ == "tree" || typ == "commit":260 icon = cmp.Or(iconFolders[n], "folder")261 case iconNames[n] != "":262 icon = iconNames[n]263 default:264 for _, rest, ok := strings.Cut(n, "."); ok; _, rest, ok = strings.Cut(rest, ".") {265 if i := iconExts[rest]; i != "" {266 icon = i267 break268 }269 }270 }271 return template.HTML(`<svg class="ficon" width="16" height="16" aria-hidden="true" focusable="false"><use href="#f-` + icon + `"></use></svg>`)272}273274// The page sprite: base.html emits it empty, and Write fills in the symbols275// the page refers to, so each page carries only the icons it shows. Symbols276// are inline because the CSP blocks data: URLs and external sprites.277const spriteTag = `<svg class="sprite" width="0" height="0" aria-hidden="true" focusable="false">`278279var (280 useRe = regexp.MustCompile(`href="#([fi]-[a-z0-9-]+)"`)281 viewBoxRe = regexp.MustCompile(`viewBox="([0-9 .-]+)"`)282 localIDRe = regexp.MustCompile(`(id="|href="#|url\(#)([A-Za-z][\w-]*)`) // ids inside one icon283 rootAttrRe = regexp.MustCompile(`\s([a-z-]+)="([^"]*)"`) // fill="none" and such on <svg>284)285286func (r *Renderer) fillSprite(page []byte) []byte {287 var syms []byte288 seen := map[string]bool{}289 for _, m := range useRe.FindAllSubmatch(page, -1) {290 if id := string(m[1]); !seen[id] {291 seen[id] = true292 syms = append(syms, r.syms[id]...) // unknown ids (a README's own #f-x link) add nothing293 }294 }295 return bytes.Replace(page, []byte(spriteTag), append([]byte(spriteTag), syms...), 1)296}297298// loadSymbols turns the embedded icons into <symbol>s: Material file icons299// (f-) and Octicons (i-). Ids inside an icon get its symbol id as a prefix,300// since many icons reuse the same ids and they all share one page.301func loadSymbols() (map[string][]byte, error) {302 syms := map[string][]byte{}303 for prefix, dir := range map[string]string{"f-": "static/icons/material", "i-": "static/icons/octicons"} {304 files, err := fs.Glob(web.FS, dir+"/*.svg")305 if err != nil {306 return nil, err307 }308 for _, f := range files {309 b, err := web.FS.ReadFile(f)310 if err != nil {311 return nil, err312 }313 vb := viewBoxRe.FindSubmatch(b)314 start, end := bytes.IndexByte(b, '>'), bytes.LastIndex(b, []byte("</svg>"))315 if vb == nil || start < 0 || end < start {316 return nil, fmt.Errorf("render: can't read icon %s", f)317 }318 id := prefix + strings.TrimSuffix(path.Base(f), ".svg")319 // the root's presentation attributes move to the symbol, so its320 // content still inherits them (fill="none" hides a background)321 var attrs []byte322 for _, a := range rootAttrRe.FindAllSubmatch(b[:start], -1) {323 if k := string(a[1]); k != "viewbox" && k != "width" && k != "height" && k != "xmlns" {324 attrs = fmt.Appendf(attrs, ` %s="%s"`, k, a[2])325 }326 }327 body := localIDRe.ReplaceAll(b[start+1:end], []byte("${1}x"+id+"-${2}"))328 syms[id] = fmt.Appendf(nil, `<symbol id="%s" viewBox="%s"%s>%s</symbol>`, id, vb[1], attrs, body)329 }330 }331 return syms, nil332}