vitrine

render.go

package main

import (
	"bytes"
	_ "embed"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"strings"

	"github.com/yuin/goldmark"
	gmext "github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/parser"
	gmutil "github.com/yuin/goldmark/util"
)

// maxRenderSize caps how much we'll read into memory for rendered views.
// Bigger files still work fine via ?fmt=raw, which streams.
const maxRenderSize = 4 << 20

var markdown = goldmark.New(
	goldmark.WithExtensions(gmext.GFM),
	goldmark.WithParserOptions(
		parser.WithAutoHeadingID(),
		parser.WithASTTransformers(gmutil.Prioritized(headingAnchors{}, 100)),
	),
)

//go:embed style.css
var styleCSS []byte

type dirEntry struct {
	Name string
	Href string
}

type crumb struct {
	Name string
	Href string
}

type pageData struct {
	Title   string
	Crumbs  []crumb
	RawHref string        // if set, a "raw" link is shown
	Listing []dirEntry    // directory listing mode
	Content template.HTML // rendered-markdown mode
	Iframe  string        // iframe-passthrough mode: src URL
}

// joinURL joins a mount name and a tree-relative path into one URL path
// (no leading slash); rel of "." means the mount root itself.
func joinURL(mount, rel string) string {
	if rel == "." {
		return mount
	}
	return mount + "/" + rel
}

// crumbs builds a breadcrumb trail from a URL path (no leading slash):
// home, then each path segment.  The last segment gets no href;
// it's the page being viewed.
func crumbs(urlpath string) []crumb {
	cs := []crumb{{Name: "vitrine", Href: "/"}}
	if urlpath == "" {
		cs[0].Href = ""
		return cs
	}
	href := "/"
	for _, seg := range strings.Split(urlpath, "/") {
		href += seg + "/"
		cs = append(cs, crumb{Name: seg, Href: href})
	}
	cs[len(cs)-1].Href = ""
	return cs
}

// serveRendered shows a file as a page: markdown rendered to HTML,
// anything else passed through in an iframe pointed at the raw view.
func serveRendered(w http.ResponseWriter, r *http.Request, root *os.Root, mount, rel string, size int64) {
	pd := pageData{
		Title:   mount + "/" + rel,
		Crumbs:  crumbs(joinURL(mount, rel)),
		RawHref: "?fmt=raw",
	}
	if strings.HasSuffix(rel, ".md") && size <= maxRenderSize {
		src, err := root.ReadFile(rel)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		var buf bytes.Buffer
		// A fresh IDs registry per document keeps duplicate-heading suffixes deterministic.
		ctx := parser.NewContext(parser.WithIDs(newSlugIDs()))
		if err := markdown.Convert(src, &buf, parser.WithContext(ctx)); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		pd.Content = template.HTML(buf.String())
	} else {
		pd.Iframe = "?fmt=raw"
	}
	renderPage(w, pd)
}

var pageTmpl = template.Must(template.New("page").Parse(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<link rel="stylesheet" href="/-/style.css">
</head>
<body>
<nav>
{{range $i, $c := .Crumbs}}{{if $i}} / {{end}}{{if $c.Href}}<a href="{{$c.Href}}">{{$c.Name}}</a>{{else}}{{$c.Name}}{{end}}{{end}}
{{if .RawHref}}<a class="raw" href="{{.RawHref}}">raw</a>{{end}}
</nav>
{{if .Listing}}<ul class="listing">{{range .Listing}}<li><a href="{{.Href}}">{{.Name}}</a></li>{{end}}</ul>{{end}}
{{if .Content}}<article>{{.Content}}</article>{{end}}
{{if .Iframe}}<iframe class="passthrough" src="{{.Iframe}}"></iframe>{{end}}
</body>
</html>
`))

func renderPage(w http.ResponseWriter, pd pageData) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := pageTmpl.Execute(w, pd); err != nil {
		fmt.Fprintf(w, "\n<!-- template error: %v -->", err)
	}
}

render.go · 3.6 KiB · 538bf4237f