feat(11.1-02): add the documentation theme, chroma highlighting and docs:serve
- WinterCMS-style shell: header with search and theme toggle, grouped sidebar, on-page TOC, pager, page actions, callouts, heading permalinks, footer and a 404 page - fenced code highlighted at build time by chroma/v2 into tok-* classes, with a copy button; no inline script, style or handler - vendored DM Sans/DM Mono fonts and Lucide icons with their licences - client-side search over search-index.json built with textContent only - summer docs:serve builds into a temp dir, serves on loopback by default, returns 404.html with status 404 and rebuilds on change
This commit is contained in:
@@ -148,6 +148,8 @@ npm --prefix admin run gen:api # regenerate TypeScript types from admin/open
|
||||
|
||||
`summer docs:build` renders `docs/` and every module README into a static site under `site/` (use `--out` for another directory, `--check` to validate without writing). Code blocks with a `src=` reference are copies of real source; after changing that source, run `summer docs:sync` to refresh the copies.
|
||||
|
||||
`summer docs:serve` builds the same site into a temporary directory and previews it at `http://127.0.0.1:8088` (`--addr` to change it), rebuilding when the docs, a module or a `src=` source changes; a failed rebuild prints its problems and keeps serving the last good build. It listens only on a loopback address unless you pass `--allow-remote`. Search needs this server: browsers block the search index over `file://`.
|
||||
|
||||
## Design notes
|
||||
|
||||
Decisions and background live in [`.planning/notes/`](.planning/notes/), including:
|
||||
|
||||
@@ -3,6 +3,10 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"git.golem15.com/golem15/summercms/internal/docsite"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
@@ -79,6 +83,43 @@ func docsSyncCommand() bonfire.Command {
|
||||
}
|
||||
}
|
||||
|
||||
func docsServeCommand() bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "docs:serve",
|
||||
Description: "Build the documentation site and preview it on a local address",
|
||||
Flags: []bonfire.Flag{
|
||||
{Name: "root", Description: "Repository root; src= paths and modules/ resolve against it", Default: "."},
|
||||
{Name: "src", Description: "Docs source directory (default <root>/docs)"},
|
||||
{Name: "base-url", Description: "Base URL for site links (overrides site.yaml base_url)"},
|
||||
{Name: "addr", Description: "Listen address; must be loopback unless --allow-remote", Default: docsite.DefaultServeAddr},
|
||||
{Name: "allow-remote", Description: "Allow a non-loopback --addr (serves the docs on the network)", Bare: true},
|
||||
},
|
||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||
addr, _ := in.Flag("addr")
|
||||
if addr == "" {
|
||||
addr = docsite.DefaultServeAddr
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return docsite.Serve(ctx, docsOptions(in), addr, flagTrue(in, "allow-remote"), outputWriter{mu: &sync.Mutex{}, out: out})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// outputWriter adapts bonfire.Output to io.Writer for docsite.Serve, which
|
||||
// writes from its watch goroutine too.
|
||||
type outputWriter struct {
|
||||
mu *sync.Mutex
|
||||
out bonfire.Output
|
||||
}
|
||||
|
||||
func (w outputWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.out.Printf("%s", p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func docsOptions(in bonfire.Input) docsite.Options {
|
||||
opts := docsite.Options{Commands: docsCommands()}
|
||||
opts.Root, _ = in.Flag("root")
|
||||
|
||||
@@ -59,6 +59,12 @@ func TestDocsBuildRealTree(t *testing.T) {
|
||||
"setup/installation.html", "setup/installation.md",
|
||||
"llms.txt", "llms-full.txt", "search-index.json",
|
||||
"assets/site.css", docsite.MarkerFile,
|
||||
"404.html", "assets/site.js", "assets/search.js", "assets/theme-init.js",
|
||||
"assets/LICENSE-lucide.txt", "assets/fonts/LICENSE-dm-sans.txt", "assets/fonts/LICENSE-dm-mono.txt",
|
||||
"assets/fonts/dm-sans-latin-400-normal.woff2", "assets/fonts/dm-sans-latin-600-normal.woff2",
|
||||
"assets/fonts/dm-sans-latin-ext-400-normal.woff2", "assets/fonts/dm-sans-latin-ext-600-normal.woff2",
|
||||
"assets/fonts/dm-sans-latin-400-italic.woff2", "assets/fonts/dm-sans-latin-ext-400-italic.woff2",
|
||||
"assets/fonts/dm-mono-latin-400-normal.woff2", "assets/fonts/dm-mono-latin-ext-400-normal.woff2",
|
||||
} {
|
||||
if _, err := os.Stat(filepath.Join(out, name)); err != nil {
|
||||
t.Errorf("missing %s: %v", name, err)
|
||||
@@ -139,6 +145,9 @@ func TestDocsAIOutputsInSync(t *testing.T) {
|
||||
if strings.HasPrefix(rel, "assets/") {
|
||||
return nil
|
||||
}
|
||||
if rel == "404.html" {
|
||||
return nil
|
||||
}
|
||||
switch filepath.Ext(rel) {
|
||||
case ".html":
|
||||
htmlFiles = append(htmlFiles, strings.TrimSuffix(rel, ".html"))
|
||||
|
||||
@@ -48,6 +48,7 @@ func toolCommands() []bonfire.Command {
|
||||
delegateCommand("queue:clear", "Clear pending queued jobs in the app binary"),
|
||||
docsBuildCommand(),
|
||||
docsSyncCommand(),
|
||||
docsServeCommand(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestToolCommandNames(t *testing.T) {
|
||||
for _, c := range toolCommands() {
|
||||
names = append(names, c.Name)
|
||||
}
|
||||
for _, want := range []string{"build", "make:plugin", "make:model", "make:migration", "make:command", "make:job", "make:admin-controller", "plugin:add", "dev", "migrate", "migrate:rollback", "migrate:status", "serve", "queue:work", "queue:clear", "schedule:run", "parity:broadcasts", "docs:build", "docs:sync"} {
|
||||
for _, want := range []string{"build", "make:plugin", "make:model", "make:migration", "make:command", "make:job", "make:admin-controller", "plugin:add", "dev", "migrate", "migrate:rollback", "migrate:status", "serve", "queue:work", "queue:clear", "schedule:run", "parity:broadcasts", "docs:build", "docs:sync", "docs:serve"} {
|
||||
if !slices.Contains(names, want) {
|
||||
t.Fatalf("missing %s in %v", want, names)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ func TestToolCommandNames(t *testing.T) {
|
||||
"parity:broadcasts": {"--flow", "--step", "--ids", "127.0.0.1:8424"},
|
||||
"docs:build": {"--out", "--src", "--root", "--base-url", "--check"},
|
||||
"docs:sync": {"--src", "--root"},
|
||||
"docs:serve": {"--root", "--src", "--base-url", "--addr", "--allow-remote", "127.0.0.1:8088"},
|
||||
}
|
||||
for cmd, wants := range helpWants {
|
||||
var buf bytes.Buffer
|
||||
|
||||
2
go.mod
2
go.mod
@@ -6,6 +6,7 @@ go 1.27.0
|
||||
ignore ./admin/node_modules
|
||||
|
||||
require (
|
||||
github.com/alecthomas/chroma/v2 v2.27.0
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
@@ -48,6 +49,7 @@ require (
|
||||
github.com/containerd/platforms v0.2.1 // indirect
|
||||
github.com/cpuguy83/dockercfg v0.3.2 // indirect
|
||||
github.com/distribution/reference v0.6.0 // indirect
|
||||
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
|
||||
github.com/docker/go-connections v0.7.0 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
|
||||
10
go.sum
10
go.sum
@@ -30,6 +30,12 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
|
||||
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
|
||||
github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs=
|
||||
github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8=
|
||||
github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs=
|
||||
github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
|
||||
@@ -92,6 +98,8 @@ github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0=
|
||||
github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
@@ -149,6 +157,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
|
||||
github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
|
||||
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA=
|
||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
|
||||
|
||||
@@ -26,7 +26,8 @@ type Commands struct {
|
||||
App []string
|
||||
}
|
||||
|
||||
// shellLangs are the fence languages whose lines are read as commands.
|
||||
// shellLangs are the fence languages read as shell sessions: their lines
|
||||
// are checked as commands and highlighted with prompts.
|
||||
var shellLangs = []string{"sh", "shell", "bash", "console"}
|
||||
|
||||
// commandToken finds `summer <name>` and `./bin/<app> <name>` at the start
|
||||
|
||||
@@ -129,7 +129,7 @@ func TestReadmeIngestion(t *testing.T) {
|
||||
return string(b)
|
||||
}
|
||||
html := read("api/alpha.html")
|
||||
for _, want := range []string{`href="/api/delta.html#api"`, `href="/setup/start.html"`, `<h2 id="usage">Usage</h2>`} {
|
||||
for _, want := range []string{`href="/api/delta.html#api"`, `href="/setup/start.html"`, `<h2 id="usage">Usage<a class="heading-anchor" href="#usage" aria-label="Link to section: Usage">#</a></h2>`} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("api/alpha.html missing %s", want)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"path"
|
||||
"strings"
|
||||
@@ -25,6 +26,11 @@ func (s *site) url(p string) string {
|
||||
return s.base + "/" + p
|
||||
}
|
||||
|
||||
// writeIcon writes the inline Lucide SVG named name (icons.html).
|
||||
func writeIcon(w io.Writer, name string) {
|
||||
_ = pageTmpl.ExecuteTemplate(w, "icon-"+name, nil)
|
||||
}
|
||||
|
||||
type navItem struct {
|
||||
Title string
|
||||
URL string
|
||||
@@ -33,21 +39,62 @@ type navItem struct {
|
||||
|
||||
type navSection struct {
|
||||
Title string
|
||||
// API marks the API reference section, whose items are module names
|
||||
// set in DM Mono.
|
||||
API bool
|
||||
Items []navItem
|
||||
}
|
||||
|
||||
type tocItem struct {
|
||||
ID string
|
||||
Text string
|
||||
Level int
|
||||
}
|
||||
|
||||
type pagerLink struct {
|
||||
Title string
|
||||
URL string
|
||||
// Section is set only when the target is in another section.
|
||||
Section string
|
||||
}
|
||||
|
||||
// pageView is the data of page.html and 404.html.
|
||||
type pageView struct {
|
||||
DocTitle string
|
||||
Title string
|
||||
Description string
|
||||
Eyebrow string
|
||||
Content template.HTML
|
||||
CSS string
|
||||
Assets string
|
||||
HomeURL string
|
||||
SearchIndex string
|
||||
LLMS string
|
||||
LLMSFull string
|
||||
EditURL string
|
||||
MarkdownURL string
|
||||
Nav []navSection
|
||||
TOC []tocItem
|
||||
Prev, Next *pagerLink
|
||||
}
|
||||
|
||||
// minTOC is the number of H2/H3 headings a page needs for a TOC.
|
||||
const minTOC = 2
|
||||
|
||||
// baseView fills the fields every page shares.
|
||||
func (s *site) baseView(current *Page) pageView {
|
||||
return pageView{
|
||||
Assets: s.url("assets"),
|
||||
HomeURL: s.url("index.html"),
|
||||
SearchIndex: s.url("search-index.json"),
|
||||
LLMS: s.url("llms.txt"),
|
||||
LLMSFull: s.url("llms-full.txt"),
|
||||
Nav: s.nav(current),
|
||||
}
|
||||
}
|
||||
|
||||
// render renders every page and fills s.outputs with the HTML pages, their
|
||||
// Markdown siblings, llms.txt, llms-full.txt, search-index.json and assets.
|
||||
// Markdown siblings, 404.html, llms.txt, llms-full.txt, search-index.json
|
||||
// and assets.
|
||||
func (s *site) render() ([]Problem, error) {
|
||||
md := newMarkdown()
|
||||
var problems []Problem
|
||||
@@ -60,17 +107,33 @@ func (s *site) render() ([]Problem, error) {
|
||||
rendered[i] = r
|
||||
}
|
||||
for i, p := range s.pages {
|
||||
view := pageView{
|
||||
DocTitle: p.Title + " · " + s.cfg.Title + " docs",
|
||||
Title: p.Title,
|
||||
Description: p.Description,
|
||||
Content: template.HTML(rendered[i].html), //nolint:gosec // goldmark output in safe mode
|
||||
CSS: s.url("assets/site.css"),
|
||||
HomeURL: s.url("index.html"),
|
||||
Nav: s.nav(p),
|
||||
view := s.baseView(p)
|
||||
view.DocTitle = p.Title + " · " + s.cfg.Title + " docs"
|
||||
view.Title = p.Title
|
||||
view.Description = p.Description
|
||||
view.Content = template.HTML(rendered[i].html) //nolint:gosec // goldmark output in safe mode
|
||||
view.MarkdownURL = s.url(p.URL + ".md")
|
||||
if s.cfg.EditURL != "" {
|
||||
view.EditURL = strings.ReplaceAll(s.cfg.EditURL, "{path}", p.Source)
|
||||
}
|
||||
if p.Section == indexSection {
|
||||
view.DocTitle = s.cfg.Title + " documentation"
|
||||
} else {
|
||||
view.Eyebrow = s.cfg.sectionTitle(p.Section)
|
||||
}
|
||||
for _, h := range rendered[i].headings {
|
||||
if h.Level == 2 || h.Level == 3 {
|
||||
view.TOC = append(view.TOC, tocItem{ID: h.ID, Text: h.Text, Level: h.Level})
|
||||
}
|
||||
}
|
||||
if len(view.TOC) < minTOC {
|
||||
view.TOC = nil
|
||||
}
|
||||
if i > 0 {
|
||||
view.Prev = s.pagerLink(p, s.pages[i-1])
|
||||
}
|
||||
if i < len(s.pages)-1 {
|
||||
view.Next = s.pagerLink(p, s.pages[i+1])
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := pageTmpl.ExecuteTemplate(&buf, "page.html", view); err != nil {
|
||||
@@ -78,6 +141,15 @@ func (s *site) render() ([]Problem, error) {
|
||||
}
|
||||
s.outputs[p.URL+".html"] = buf.Bytes()
|
||||
}
|
||||
notFound := s.baseView(nil)
|
||||
notFound.DocTitle = "Page not found · " + s.cfg.Title + " docs"
|
||||
notFound.Title = "Page not found"
|
||||
notFound.Description = "This page does not exist or has moved."
|
||||
var buf bytes.Buffer
|
||||
if err := pageTmpl.ExecuteTemplate(&buf, "404.html", notFound); err != nil {
|
||||
return nil, fmt.Errorf("docsite: render 404.html: %w", err)
|
||||
}
|
||||
s.outputs["404.html"] = buf.Bytes()
|
||||
bodies := make([]string, len(s.pages))
|
||||
for i, p := range s.pages {
|
||||
bodies[i] = markdownBody(p, rendered[i].mdLinks)
|
||||
@@ -96,16 +168,26 @@ func (s *site) render() ([]Problem, error) {
|
||||
return problems, nil
|
||||
}
|
||||
|
||||
// pagerLink describes a prev/next target; the section line is kept only
|
||||
// when the target sits in another section (and is not the index page).
|
||||
func (s *site) pagerLink(from, to *Page) *pagerLink {
|
||||
l := &pagerLink{Title: to.Title, URL: s.url(to.URL + ".html")}
|
||||
if to.Section != from.Section && to.Section != indexSection {
|
||||
l.Section = s.cfg.sectionTitle(to.Section)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// nav builds the sidebar: every site.yaml section in order with its pages.
|
||||
func (s *site) nav(current *Page) []navSection {
|
||||
var out []navSection
|
||||
for _, sec := range s.cfg.Sections {
|
||||
ns := navSection{Title: sec.Title}
|
||||
ns := navSection{Title: sec.Title, API: sec.Name == apiSection}
|
||||
for _, p := range s.pages {
|
||||
if p.Section != sec.Name {
|
||||
continue
|
||||
}
|
||||
ns.Items = append(ns.Items, navItem{Title: p.Title, URL: s.url(p.URL + ".html"), Current: p == current})
|
||||
ns.Items = append(ns.Items, navItem{Title: p.Title, URL: s.url(p.URL + ".html"), Current: current != nil && p == current})
|
||||
}
|
||||
out = append(out, ns)
|
||||
}
|
||||
|
||||
200
internal/docsite/highlight.go
Normal file
200
internal/docsite/highlight.go
Normal file
@@ -0,0 +1,200 @@
|
||||
package docsite
|
||||
|
||||
import (
|
||||
"html"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/alecthomas/chroma/v2"
|
||||
"github.com/alecthomas/chroma/v2/lexers"
|
||||
"github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/renderer"
|
||||
"github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
// codeRenderer renders every fenced code block as the UI-SPEC code block:
|
||||
// <figure class="code">, a <figcaption> naming the source of a src= fence
|
||||
// (linked to source_url), a copy button that stays hidden until site.js
|
||||
// finds a clipboard, and <pre><code> highlighted at build time. Tokens
|
||||
// come from chroma/v2 lexers and are mapped onto the tok-* classes; the
|
||||
// chroma HTML formatter and its styles are not used, so the output has no
|
||||
// inline style and only the UI-SPEC class names.
|
||||
type codeRenderer struct{}
|
||||
|
||||
func (codeRenderer) RegisterFuncs(r renderer.NodeRendererFuncRegisterer) {
|
||||
r.Register(ast.KindFencedCodeBlock, renderFence)
|
||||
}
|
||||
|
||||
func attrString(n ast.Node, name string) string {
|
||||
v, ok := n.AttributeString(name)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
b, _ := v.([]byte)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func renderFence(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
if !entering {
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
n := node.(*ast.FencedCodeBlock)
|
||||
_, _ = w.WriteString(`<figure class="code">`)
|
||||
if ref := attrString(n, "data-src"); ref != "" {
|
||||
_, _ = w.WriteString("<figcaption>")
|
||||
if href := attrString(n, "data-href"); href != "" {
|
||||
_, _ = w.WriteString(`<a href="` + html.EscapeString(href) + `">` + html.EscapeString(ref) + "</a>")
|
||||
} else {
|
||||
_, _ = w.WriteString(html.EscapeString(ref))
|
||||
}
|
||||
_, _ = w.WriteString("</figcaption>")
|
||||
}
|
||||
_, _ = w.WriteString(`<button type="button" class="copy-button" aria-label="Copy code" hidden>`)
|
||||
writeIcon(w, "copy")
|
||||
writeIcon(w, "check")
|
||||
_, _ = w.WriteString("</button><pre><code")
|
||||
lang := ""
|
||||
if l := n.Language(src); l != nil {
|
||||
lang = string(l)
|
||||
_, _ = w.WriteString(` class="language-` + html.EscapeString(lang) + `"`)
|
||||
}
|
||||
_ = w.WriteByte('>')
|
||||
var code strings.Builder
|
||||
for i := 0; i < n.Lines().Len(); i++ {
|
||||
line := n.Lines().At(i)
|
||||
code.Write(line.Value(src))
|
||||
}
|
||||
_, _ = w.WriteString(highlight(lang, code.String()))
|
||||
_, _ = w.WriteString("</code></pre></figure>\n")
|
||||
return ast.WalkSkipChildren, nil
|
||||
}
|
||||
|
||||
// highlight returns code as escaped HTML with tok-* spans. Unknown
|
||||
// languages, plain text and lexer errors fall back to escaped text.
|
||||
func highlight(lang, code string) string {
|
||||
var b strings.Builder
|
||||
if slices.Contains(shellLangs, lang) {
|
||||
highlightShell(&b, code)
|
||||
return b.String()
|
||||
}
|
||||
lexer := lexerFor(lang)
|
||||
if lexer == nil || !writeTokens(&b, lexer, lang, code) {
|
||||
return html.EscapeString(code)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// lexerFor returns the chroma lexer for a fence language, or nil for
|
||||
// plain text and unknown languages.
|
||||
func lexerFor(lang string) chroma.Lexer {
|
||||
switch lang {
|
||||
case "", "text", "txt", "plain", "plaintext":
|
||||
return nil
|
||||
}
|
||||
l := lexers.Get(lang)
|
||||
if l == nil {
|
||||
return nil
|
||||
}
|
||||
return chroma.Coalesce(l)
|
||||
}
|
||||
|
||||
// writeTokens tokenises code and writes each token as a tok-* span or as
|
||||
// escaped plain text. It reports false when the lexer fails.
|
||||
func writeTokens(b *strings.Builder, lexer chroma.Lexer, lang, code string) bool {
|
||||
it, err := lexer.Tokenise(nil, code)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
tokens := it.Tokens()
|
||||
// Lexers configured with EnsureNL append a newline the source did not
|
||||
// have; drop it so a shell line fragment stays one line.
|
||||
if n := len(tokens); n > 0 && !strings.HasSuffix(code, "\n") {
|
||||
tokens[n-1].Value = strings.TrimSuffix(tokens[n-1].Value, "\n")
|
||||
}
|
||||
for _, tok := range tokens {
|
||||
writeSpan(b, tokClass(tok.Type, lang), tok.Value)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeSpan(b *strings.Builder, class, value string) {
|
||||
if value == "" {
|
||||
return
|
||||
}
|
||||
if class == "" {
|
||||
b.WriteString(html.EscapeString(value))
|
||||
return
|
||||
}
|
||||
b.WriteString(`<span class="` + class + `">` + html.EscapeString(value) + "</span>")
|
||||
}
|
||||
|
||||
// tokClass maps a chroma token type onto a UI-SPEC syntax class, or "" for
|
||||
// plain text (identifiers, operators, punctuation).
|
||||
func tokClass(t chroma.TokenType, lang string) string {
|
||||
data := lang == "yaml" || lang == "yml" || lang == "json"
|
||||
switch {
|
||||
case t == chroma.GenericPrompt:
|
||||
return "tok-prompt"
|
||||
case t.InCategory(chroma.Comment):
|
||||
return "tok-com"
|
||||
case t == chroma.NameTag || t == chroma.NameAttribute:
|
||||
return "tok-key"
|
||||
case t == chroma.KeywordConstant && data:
|
||||
// YAML and JSON booleans and null.
|
||||
return "tok-num"
|
||||
case t.InCategory(chroma.Keyword):
|
||||
return "tok-kw"
|
||||
case t.InSubCategory(chroma.LiteralString):
|
||||
return "tok-str"
|
||||
case t.InSubCategory(chroma.LiteralNumber):
|
||||
return "tok-num"
|
||||
case t == chroma.Literal && data:
|
||||
// A plain YAML scalar is a string.
|
||||
return "tok-str"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// highlightShell highlights a shell session line by line: a leading "$ "
|
||||
// is a tok-prompt (never copied), a "#" line is a comment, the command
|
||||
// word is tok-kw and the rest goes through the bash lexer. Continuation
|
||||
// lines (after a trailing "\") have no command word.
|
||||
func highlightShell(b *strings.Builder, code string) {
|
||||
lexer := lexerFor("bash")
|
||||
cont := false
|
||||
lines := strings.SplitAfter(code, "\n")
|
||||
for _, line := range lines {
|
||||
body := strings.TrimSuffix(line, "\n")
|
||||
nl := len(body) < len(line)
|
||||
rest := body
|
||||
if !cont {
|
||||
trimmed := strings.TrimLeft(body, " \t")
|
||||
b.WriteString(html.EscapeString(body[:len(body)-len(trimmed)]))
|
||||
rest = trimmed
|
||||
if p, ok := strings.CutPrefix(rest, "$ "); ok {
|
||||
writeSpan(b, "tok-prompt", "$ ")
|
||||
rest = p
|
||||
}
|
||||
if strings.HasPrefix(rest, "#") {
|
||||
writeSpan(b, "tok-com", rest)
|
||||
rest = ""
|
||||
} else if rest != "" {
|
||||
word, tail, found := strings.Cut(rest, " ")
|
||||
writeSpan(b, "tok-kw", word)
|
||||
if found {
|
||||
b.WriteString(" ")
|
||||
}
|
||||
rest = tail
|
||||
}
|
||||
}
|
||||
if rest != "" {
|
||||
if lexer == nil || !writeTokens(b, lexer, "bash", rest) {
|
||||
b.WriteString(html.EscapeString(rest))
|
||||
}
|
||||
}
|
||||
cont = strings.HasSuffix(strings.TrimRight(body, " \t"), `\`)
|
||||
if nl {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"html"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -33,11 +34,16 @@ func newMarkdown() goldmark.Markdown {
|
||||
util.Prioritized(h1Stripper{}, 100),
|
||||
util.Prioritized(linkRewriter{}, 200),
|
||||
util.Prioritized(fenceAnnotator{}, 300),
|
||||
util.Prioritized(calloutTransformer{}, 400),
|
||||
),
|
||||
),
|
||||
// goldmark registers lower priority values last, so 100 overrides the
|
||||
// default html renderer (1000) for fenced code blocks.
|
||||
goldmark.WithRendererOptions(renderer.WithNodeRenderers(util.Prioritized(codeRenderer{}, 100))),
|
||||
// default html renderer (1000) for fenced code blocks and headings.
|
||||
goldmark.WithRendererOptions(renderer.WithNodeRenderers(
|
||||
util.Prioritized(codeRenderer{}, 100),
|
||||
util.Prioritized(headingRenderer{}, 100),
|
||||
util.Prioritized(calloutRenderer{}, 100),
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -65,49 +71,123 @@ func (fenceAnnotator) Transform(doc *ast.Document, reader text.Reader, pc parser
|
||||
})
|
||||
}
|
||||
|
||||
// codeRenderer renders every fenced code block inside <figure class="code">;
|
||||
// a src= fence gets a <figcaption> naming its source, linked to source_url.
|
||||
type codeRenderer struct{}
|
||||
// headingRenderer renders headings with their slug ID and, on H2 and H3,
|
||||
// a permalink after the text.
|
||||
type headingRenderer struct{}
|
||||
|
||||
func (codeRenderer) RegisterFuncs(r renderer.NodeRendererFuncRegisterer) {
|
||||
r.Register(ast.KindFencedCodeBlock, renderFence)
|
||||
func (headingRenderer) RegisterFuncs(r renderer.NodeRendererFuncRegisterer) {
|
||||
r.Register(ast.KindHeading, renderHeading)
|
||||
}
|
||||
|
||||
func attrString(n ast.Node, name string) string {
|
||||
v, ok := n.AttributeString(name)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
b, _ := v.([]byte)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func renderFence(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
if !entering {
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
n := node.(*ast.FencedCodeBlock)
|
||||
_, _ = w.WriteString(`<figure class="code">`)
|
||||
if ref := attrString(n, "data-src"); ref != "" {
|
||||
_, _ = w.WriteString("<figcaption>")
|
||||
if href := attrString(n, "data-href"); href != "" {
|
||||
_, _ = w.WriteString(`<a href="` + html.EscapeString(href) + `">` + html.EscapeString(ref) + "</a>")
|
||||
} else {
|
||||
_, _ = w.WriteString(html.EscapeString(ref))
|
||||
}
|
||||
_, _ = w.WriteString("</figcaption>")
|
||||
}
|
||||
_, _ = w.WriteString("<pre><code")
|
||||
if lang := n.Language(src); lang != nil {
|
||||
_, _ = w.WriteString(` class="language-` + html.EscapeString(string(lang)) + `"`)
|
||||
func renderHeading(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
n := node.(*ast.Heading)
|
||||
tag := fmt.Sprintf("h%d", n.Level)
|
||||
id := attrString(n, "id")
|
||||
if entering {
|
||||
_, _ = w.WriteString("<" + tag)
|
||||
if id != "" {
|
||||
_, _ = w.WriteString(` id="` + html.EscapeString(id) + `"`)
|
||||
}
|
||||
_ = w.WriteByte('>')
|
||||
for i := 0; i < n.Lines().Len(); i++ {
|
||||
line := n.Lines().At(i)
|
||||
_, _ = w.WriteString(html.EscapeString(string(line.Value(src))))
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
_, _ = w.WriteString("</code></pre></figure>\n")
|
||||
return ast.WalkSkipChildren, nil
|
||||
if id != "" && (n.Level == 2 || n.Level == 3) {
|
||||
_, _ = w.WriteString(`<a class="heading-anchor" href="#` + html.EscapeString(id) +
|
||||
`" aria-label="Link to section: ` + html.EscapeString(plainText(n, src)) + `">#</a>`)
|
||||
}
|
||||
_, _ = w.WriteString("</" + tag + ">\n")
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
|
||||
// kindCallout is the AST node kind of a > [!NOTE], [!TIP] or [!WARNING]
|
||||
// blockquote.
|
||||
var kindCallout = ast.NewNodeKind("Callout")
|
||||
|
||||
// calloutNode holds the blocks of a callout; CalloutType is NOTE, TIP or WARNING.
|
||||
type calloutNode struct {
|
||||
ast.BaseBlock
|
||||
CalloutType string
|
||||
}
|
||||
|
||||
func (n *calloutNode) Kind() ast.NodeKind { return kindCallout }
|
||||
|
||||
func (n *calloutNode) Dump(src []byte, level int) {
|
||||
ast.DumpHelper(n, src, level, map[string]string{"CalloutType": n.CalloutType}, nil)
|
||||
}
|
||||
|
||||
// calloutTransformer turns a blockquote whose first line is exactly
|
||||
// [!NOTE], [!TIP] or [!WARNING] into a callout without that line. Other
|
||||
// types stay blockquotes; checkPolicy reports them.
|
||||
type calloutTransformer struct{}
|
||||
|
||||
func (calloutTransformer) Transform(doc *ast.Document, reader text.Reader, _ parser.Context) {
|
||||
src := reader.Source()
|
||||
var quotes []*ast.Blockquote
|
||||
_ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
if bq, ok := n.(*ast.Blockquote); ok && entering {
|
||||
quotes = append(quotes, bq)
|
||||
}
|
||||
return ast.WalkContinue, nil
|
||||
})
|
||||
for _, bq := range quotes {
|
||||
para, ok := bq.FirstChild().(*ast.Paragraph)
|
||||
if !ok || para.Lines().Len() == 0 {
|
||||
continue
|
||||
}
|
||||
first := para.Lines().At(0)
|
||||
m := calloutLine.FindStringSubmatch(strings.TrimSpace(string(first.Value(src))))
|
||||
if m == nil || !slices.Contains(calloutTypes, m[1]) {
|
||||
continue
|
||||
}
|
||||
for c := para.FirstChild(); c != nil; {
|
||||
next := c.NextSibling()
|
||||
t, ok := c.(*ast.Text)
|
||||
if !ok || t.Segment.Start >= first.Stop {
|
||||
break
|
||||
}
|
||||
para.RemoveChild(para, c)
|
||||
c = next
|
||||
}
|
||||
if para.ChildCount() == 0 {
|
||||
bq.RemoveChild(bq, para)
|
||||
}
|
||||
callout := &calloutNode{CalloutType: m[1]}
|
||||
for c := bq.FirstChild(); c != nil; {
|
||||
next := c.NextSibling()
|
||||
callout.AppendChild(callout, c)
|
||||
c = next
|
||||
}
|
||||
bq.Parent().ReplaceChild(bq.Parent(), bq, callout)
|
||||
}
|
||||
}
|
||||
|
||||
// calloutLine matches the marker line of a callout.
|
||||
var calloutLine = regexp.MustCompile(`^\[!([A-Za-z]+)\]$`)
|
||||
|
||||
// calloutRenderer renders a callout as <aside class="callout callout-…">
|
||||
// with its icon and title.
|
||||
type calloutRenderer struct{}
|
||||
|
||||
func (calloutRenderer) RegisterFuncs(r renderer.NodeRendererFuncRegisterer) {
|
||||
r.Register(kindCallout, renderCallout)
|
||||
}
|
||||
|
||||
var calloutMeta = map[string]struct{ class, icon, title string }{
|
||||
"NOTE": {"callout-note", "info", "Note"},
|
||||
"TIP": {"callout-tip", "lightbulb", "Tip"},
|
||||
"WARNING": {"callout-warning", "triangle-alert", "Warning"},
|
||||
}
|
||||
|
||||
func renderCallout(w util.BufWriter, _ []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
meta := calloutMeta[node.(*calloutNode).CalloutType]
|
||||
if !entering {
|
||||
_, _ = w.WriteString("</div></aside>\n")
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
_, _ = w.WriteString(`<aside class="callout ` + meta.class + `" role="note"><p class="callout-title">`)
|
||||
writeIcon(w, meta.icon)
|
||||
_, _ = w.WriteString("<span>" + meta.title + `</span></p><div class="callout-body">`)
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
|
||||
// h1Stripper removes the page's leading "# Title" heading; the template
|
||||
|
||||
287
internal/docsite/serve.go
Normal file
287
internal/docsite/serve.go
Normal file
@@ -0,0 +1,287 @@
|
||||
package docsite
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
)
|
||||
|
||||
// DefaultServeAddr is the loopback address docs:serve listens on.
|
||||
const DefaultServeAddr = "127.0.0.1:8088"
|
||||
|
||||
const serveDebounce = 200 * time.Millisecond
|
||||
|
||||
// Serve builds the site into a fresh temporary directory (removed on
|
||||
// return), serves it on addr and rebuilds when the docs, a module or a
|
||||
// src= source directory changes. A failed rebuild prints its problems and
|
||||
// keeps serving the last good build. addr must be a loopback address
|
||||
// unless allowRemote is set (the flag behind docs:serve --allow-remote).
|
||||
// Serve returns when ctx is done.
|
||||
func Serve(ctx context.Context, opts Options, addr string, allowRemote bool, out io.Writer) error {
|
||||
if err := checkServeAddr(addr, allowRemote); err != nil {
|
||||
return err
|
||||
}
|
||||
opts, err := opts.normalize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "summer-docs-")
|
||||
if err != nil {
|
||||
return fmt.Errorf("docs:serve: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
|
||||
s := &server{opts: opts, tmp: tmp, out: out}
|
||||
if !s.rebuild() {
|
||||
return errors.New("docs:serve: build failed")
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("docs:serve: %w", err)
|
||||
}
|
||||
srv := &http.Server{Handler: dirHandler(s.dir), ReadHeaderTimeout: 10 * time.Second}
|
||||
serveErr := make(chan error, 1)
|
||||
go func() { serveErr <- srv.Serve(ln) }()
|
||||
fmt.Fprintf(out, "Serving docs at http://%s (press Ctrl+C to stop)\n", ln.Addr())
|
||||
|
||||
watchErr := make(chan error, 1)
|
||||
watchCtx, stopWatch := context.WithCancel(ctx)
|
||||
defer stopWatch()
|
||||
go func() { watchErr <- s.watch(watchCtx) }()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case err := <-serveErr:
|
||||
return fmt.Errorf("docs:serve: %w", err)
|
||||
case err := <-watchErr:
|
||||
if err != nil {
|
||||
_ = srv.Close()
|
||||
return err
|
||||
}
|
||||
<-ctx.Done()
|
||||
}
|
||||
stopWatch()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutdownCtx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkServeAddr refuses a listen address whose host is not localhost or
|
||||
// a loopback IP, unless allowRemote is set.
|
||||
func checkServeAddr(addr string, allowRemote bool) error {
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("docs:serve: invalid --addr %q: %w", addr, err)
|
||||
}
|
||||
if allowRemote || host == "localhost" {
|
||||
return nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("docs:serve: refusing to listen on %s: not a loopback address. Pass --allow-remote to serve on the network.", addr)
|
||||
}
|
||||
|
||||
// server owns the served build directory and swaps it after each good
|
||||
// rebuild.
|
||||
type server struct {
|
||||
opts Options
|
||||
tmp string
|
||||
out io.Writer
|
||||
|
||||
mu sync.RWMutex
|
||||
current string
|
||||
stale string
|
||||
builds int
|
||||
}
|
||||
|
||||
func (s *server) dir() string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.current
|
||||
}
|
||||
|
||||
// rebuild builds into a new directory and swaps it in only when the build
|
||||
// has no problems. The build before the previous one is removed, so an
|
||||
// in-flight request never loses its directory.
|
||||
func (s *server) rebuild() bool {
|
||||
s.builds++
|
||||
dir := filepath.Join(s.tmp, fmt.Sprintf("build-%d", s.builds))
|
||||
opts := s.opts
|
||||
opts.Out = dir
|
||||
_, problems, err := Build(opts)
|
||||
if err != nil || len(problems) > 0 {
|
||||
for _, p := range problems {
|
||||
fmt.Fprintln(s.out, p)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(s.out, err)
|
||||
}
|
||||
_ = os.RemoveAll(dir)
|
||||
if s.dir() != "" {
|
||||
fmt.Fprintln(s.out, "docs:serve: build failed, still serving the previous version")
|
||||
}
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
old := s.stale
|
||||
s.stale, s.current = s.current, dir
|
||||
s.mu.Unlock()
|
||||
if old != "" {
|
||||
_ = os.RemoveAll(old)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// watch rebuilds on changes under Src, modules/ and every src= source
|
||||
// directory, debounced.
|
||||
func (s *server) watch(ctx context.Context) error {
|
||||
w, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return fmt.Errorf("docs:serve: watcher: %w", err)
|
||||
}
|
||||
defer w.Close()
|
||||
s.addWatches(w)
|
||||
|
||||
var timer *time.Timer
|
||||
fire := make(chan struct{}, 1)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
return nil
|
||||
case ev, ok := <-w.Events:
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(filepath.Base(ev.Name), ".") || ev.Op == fsnotify.Chmod {
|
||||
continue
|
||||
}
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
timer = time.AfterFunc(serveDebounce, func() {
|
||||
select {
|
||||
case fire <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
})
|
||||
case err, ok := <-w.Errors:
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintf(s.out, "docs:serve: watch: %v\n", err)
|
||||
case <-fire:
|
||||
if s.rebuild() {
|
||||
fmt.Fprintln(s.out, "docs:serve: rebuilt")
|
||||
}
|
||||
s.addWatches(w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// addWatches watches every directory of Src and modules/ and the
|
||||
// directory of every src= reference. Adding a watched path again is a
|
||||
// no-op.
|
||||
func (s *server) addWatches(w *fsnotify.Watcher) {
|
||||
dirs := map[string]bool{}
|
||||
for _, base := range []string{s.opts.Src, filepath.Join(s.opts.Root, "modules")} {
|
||||
_ = filepath.WalkDir(base, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || !d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if p != base && (strings.HasPrefix(d.Name(), ".") || d.Name() == "testdata" || d.Name() == "node_modules") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
dirs[p] = true
|
||||
return nil
|
||||
})
|
||||
}
|
||||
pages, _, err := Pages(s.opts)
|
||||
if err == nil {
|
||||
for _, p := range pages {
|
||||
lines := strings.Split(string(p.Body), "\n")
|
||||
for _, f := range scanFences(lines) {
|
||||
if ref, ok := ParseSrc(f.info); ok {
|
||||
dirs[filepath.Join(s.opts.Root, filepath.FromSlash(path.Dir(ref.Path)))] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for d := range dirs {
|
||||
if within(d, s.opts.Root) {
|
||||
_ = w.Add(d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handler serves the built site in dir: files by path, a directory's
|
||||
// index.html, 404.html with status 404 for anything missing, and never a
|
||||
// dot-file.
|
||||
func Handler(dir string) http.Handler {
|
||||
return dirHandler(func() string { return dir })
|
||||
}
|
||||
|
||||
func dirHandler(dir func() string) 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, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
root := dir()
|
||||
clean := path.Clean("/" + r.URL.Path)
|
||||
for _, seg := range strings.Split(clean, "/") {
|
||||
if strings.HasPrefix(seg, ".") {
|
||||
notFound(w, root)
|
||||
return
|
||||
}
|
||||
}
|
||||
name := filepath.Join(root, filepath.FromSlash(clean))
|
||||
info, err := os.Stat(name)
|
||||
if err == nil && info.IsDir() {
|
||||
name = filepath.Join(name, "index.html")
|
||||
info, err = os.Stat(name)
|
||||
}
|
||||
if err != nil || !info.Mode().IsRegular() || !within(name, root) {
|
||||
notFound(w, root)
|
||||
return
|
||||
}
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
notFound(w, root)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
http.ServeContent(w, r, filepath.Base(name), info.ModTime(), f)
|
||||
})
|
||||
}
|
||||
|
||||
// notFound writes the site's 404.html with status 404.
|
||||
func notFound(w http.ResponseWriter, root string) {
|
||||
body, err := os.ReadFile(filepath.Join(root, "404.html"))
|
||||
if err != nil {
|
||||
http.NotFound(w, nil)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = io.Copy(w, bytes.NewReader(body))
|
||||
}
|
||||
43
internal/docsite/theme/assets/LICENSE-lucide.txt
Normal file
43
internal/docsite/theme/assets/LICENSE-lucide.txt
Normal file
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
93
internal/docsite/theme/assets/fonts/LICENSE-dm-mono.txt
Normal file
93
internal/docsite/theme/assets/fonts/LICENSE-dm-mono.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) DMMono-LightItalic.ttf: Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) DMMono-Regular.ttf: Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) DMMono-Italic.ttf: Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) DMMono-Medium.ttf: Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) DMMono-MediumItalic.ttf: Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
93
internal/docsite/theme/assets/fonts/LICENSE-dm-sans.txt
Normal file
93
internal/docsite/theme/assets/fonts/LICENSE-dm-sans.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts) DMSans-Italic[opsz,wght].ttf: Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
393
internal/docsite/theme/assets/search.js
Normal file
393
internal/docsite/theme/assets/search.js
Normal file
@@ -0,0 +1,393 @@
|
||||
// SummerCMS docs: client-side search over search-index.json.
|
||||
// The index is fetched lazily on the first open and cached. Result rows are
|
||||
// built with createElement and textContent only; indexed text is never
|
||||
// parsed as HTML.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var MAX_RESULTS = 20;
|
||||
var QUERY_KEY = "summer-docs-query";
|
||||
var dialog = document.getElementById("search");
|
||||
var input = document.getElementById("search-input");
|
||||
var list = document.getElementById("search-results");
|
||||
var status = document.getElementById("search-status");
|
||||
var live = document.getElementById("search-live");
|
||||
var trigger = document.querySelector(".search-trigger");
|
||||
if (!dialog || !input || !list || !status || typeof dialog.showModal !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
var items = null; // null until loaded
|
||||
var loading = null; // the pending load promise
|
||||
var loadError = ""; // "server" or "index" after a failed load
|
||||
var results = [];
|
||||
var activeIndex = -1;
|
||||
|
||||
var isMac = /mac/i.test((navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || "");
|
||||
var kbd = trigger && trigger.querySelector("kbd");
|
||||
if (kbd && isMac) {
|
||||
kbd.textContent = "⌘ K";
|
||||
}
|
||||
|
||||
try {
|
||||
input.value = window.sessionStorage.getItem(QUERY_KEY) || "";
|
||||
} catch (e) {
|
||||
// No session storage: start empty.
|
||||
}
|
||||
|
||||
function el(tag, className, text) {
|
||||
var node = document.createElement(tag);
|
||||
if (className) {
|
||||
node.className = className;
|
||||
}
|
||||
if (text !== undefined) {
|
||||
node.textContent = text;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// appendRich appends text in which `code spans` become <code> elements.
|
||||
function appendRich(parent, text) {
|
||||
var parts = text.split("`");
|
||||
for (var i = 0; i < parts.length; i++) {
|
||||
if (!parts[i]) {
|
||||
continue;
|
||||
}
|
||||
parent.appendChild(i % 2 ? el("code", "", parts[i]) : document.createTextNode(parts[i]));
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(title, body) {
|
||||
status.textContent = "";
|
||||
if (title) {
|
||||
status.appendChild(el("p", "search-status-title", title));
|
||||
}
|
||||
if (body) {
|
||||
var p = el("p");
|
||||
appendRich(p, body);
|
||||
status.appendChild(p);
|
||||
}
|
||||
}
|
||||
|
||||
function announce(text) {
|
||||
if (live) {
|
||||
live.textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
function clearResults() {
|
||||
results = [];
|
||||
activeIndex = -1;
|
||||
list.textContent = "";
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
input.setAttribute("aria-activedescendant", "");
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (items || loading) {
|
||||
return loading || Promise.resolve();
|
||||
}
|
||||
setStatus("", "Loading the search index…");
|
||||
loading = fetch(list.getAttribute("data-index"))
|
||||
.then(
|
||||
function (res) {
|
||||
if (!res.ok) {
|
||||
throw new Error("index");
|
||||
}
|
||||
return res.json().catch(function () {
|
||||
throw new Error("index");
|
||||
});
|
||||
},
|
||||
function () {
|
||||
throw new Error("server");
|
||||
}
|
||||
)
|
||||
.then(function (data) {
|
||||
items = buildItems(data);
|
||||
loadError = "";
|
||||
})
|
||||
.catch(function (err) {
|
||||
loadError = err && err.message === "server" ? "server" : "index";
|
||||
})
|
||||
.then(function () {
|
||||
loading = null;
|
||||
update();
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
// buildItems flattens the index: one item per page (title hit) and one
|
||||
// per section entry (heading and text hits).
|
||||
function buildItems(data) {
|
||||
if (!data || !Array.isArray(data.p) || !Array.isArray(data.e)) {
|
||||
throw new Error("index");
|
||||
}
|
||||
var out = [];
|
||||
data.p.forEach(function (page) {
|
||||
out.push({ url: page.u, title: page.t, section: page.s, heading: page.t, text: "", pageHit: true });
|
||||
});
|
||||
data.e.forEach(function (entry) {
|
||||
var page = data.p[entry.p];
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
out.push({
|
||||
url: page.u + (entry.a ? "#" + entry.a : ""),
|
||||
title: page.t,
|
||||
section: page.s,
|
||||
heading: entry.h || page.t,
|
||||
text: entry.x || "",
|
||||
pageHit: false
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function tokenize(q) {
|
||||
return q.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
}
|
||||
|
||||
// search ranks with AND-token matching: a title hit outranks a heading
|
||||
// hit, which outranks a text hit.
|
||||
function search(tokens) {
|
||||
var scored = [];
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
var it = items[i];
|
||||
var title = it.title.toLowerCase();
|
||||
var heading = it.pageHit ? "" : it.heading.toLowerCase();
|
||||
var text = it.text.toLowerCase();
|
||||
var score = 0;
|
||||
var all = true;
|
||||
for (var j = 0; j < tokens.length; j++) {
|
||||
var t = tokens[j];
|
||||
var s = 0;
|
||||
if (title.indexOf(t) >= 0) {
|
||||
s += 100;
|
||||
}
|
||||
if (heading.indexOf(t) >= 0) {
|
||||
s += 10;
|
||||
}
|
||||
if (text.indexOf(t) >= 0) {
|
||||
s += 1;
|
||||
}
|
||||
if (!s) {
|
||||
all = false;
|
||||
break;
|
||||
}
|
||||
score += s;
|
||||
}
|
||||
if (all) {
|
||||
if (it.pageHit) {
|
||||
score += 5;
|
||||
}
|
||||
scored.push({ item: it, score: score, order: i });
|
||||
}
|
||||
}
|
||||
scored.sort(function (a, b) {
|
||||
return b.score - a.score || a.order - b.order;
|
||||
});
|
||||
return scored.slice(0, MAX_RESULTS).map(function (s) {
|
||||
return s.item;
|
||||
});
|
||||
}
|
||||
|
||||
// appendMarked appends text with every token occurrence wrapped in a
|
||||
// <mark> element.
|
||||
function appendMarked(parent, text, tokens) {
|
||||
var lower = text.toLowerCase();
|
||||
var pos = 0;
|
||||
while (pos < text.length) {
|
||||
var best = -1;
|
||||
var len = 0;
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
var at = lower.indexOf(tokens[i], pos);
|
||||
if (at >= 0 && (best < 0 || at < best || (at === best && tokens[i].length > len))) {
|
||||
best = at;
|
||||
len = tokens[i].length;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
parent.appendChild(document.createTextNode(text.slice(pos)));
|
||||
return;
|
||||
}
|
||||
if (best > pos) {
|
||||
parent.appendChild(document.createTextNode(text.slice(pos, best)));
|
||||
}
|
||||
parent.appendChild(el("mark", "", text.slice(best, best + len)));
|
||||
pos = best + len;
|
||||
}
|
||||
}
|
||||
|
||||
// excerpt starts the text near its first match.
|
||||
function excerpt(text, tokens) {
|
||||
var lower = text.toLowerCase();
|
||||
var first = -1;
|
||||
tokens.forEach(function (t) {
|
||||
var at = lower.indexOf(t);
|
||||
if (at >= 0 && (first < 0 || at < first)) {
|
||||
first = at;
|
||||
}
|
||||
});
|
||||
if (first > 60) {
|
||||
var start = text.lastIndexOf(" ", first - 40);
|
||||
return "…" + text.slice(start > 0 ? start + 1 : first - 40);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function render(tokens) {
|
||||
clearResults();
|
||||
results = search(tokens);
|
||||
if (!results.length) {
|
||||
setStatus('No results for "' + input.value.trim() + '"', "Check the spelling, or try a shorter term such as a module or command name.");
|
||||
announce("No results");
|
||||
return;
|
||||
}
|
||||
setStatus("", "");
|
||||
results.forEach(function (it, i) {
|
||||
var li = el("li", "search-result");
|
||||
li.id = "search-result-" + i;
|
||||
li.setAttribute("role", "option");
|
||||
li.setAttribute("aria-selected", "false");
|
||||
li.appendChild(el("div", "search-result-path", it.section + " › " + it.title));
|
||||
var heading = el("div", "search-result-heading");
|
||||
appendMarked(heading, it.heading, tokens);
|
||||
li.appendChild(heading);
|
||||
if (it.text) {
|
||||
var ex = el("div", "search-result-excerpt");
|
||||
appendMarked(ex, excerpt(it.text, tokens), tokens);
|
||||
li.appendChild(ex);
|
||||
}
|
||||
li.addEventListener("click", function () {
|
||||
go(i);
|
||||
});
|
||||
li.addEventListener("mousemove", function () {
|
||||
setActive(i);
|
||||
});
|
||||
list.appendChild(li);
|
||||
});
|
||||
input.setAttribute("aria-expanded", "true");
|
||||
setActive(0);
|
||||
announce(results.length === 1 ? "1 result" : results.length + " results");
|
||||
}
|
||||
|
||||
function setActive(i) {
|
||||
var rows = list.children;
|
||||
if (!rows.length) {
|
||||
return;
|
||||
}
|
||||
if (activeIndex >= 0 && rows[activeIndex]) {
|
||||
rows[activeIndex].setAttribute("aria-selected", "false");
|
||||
}
|
||||
activeIndex = (i + rows.length) % rows.length;
|
||||
var row = rows[activeIndex];
|
||||
row.setAttribute("aria-selected", "true");
|
||||
input.setAttribute("aria-activedescendant", row.id);
|
||||
if (row.scrollIntoView) {
|
||||
row.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
}
|
||||
|
||||
function go(i) {
|
||||
var it = results[i];
|
||||
if (!it) {
|
||||
return;
|
||||
}
|
||||
dialog.close();
|
||||
window.location.href = it.url;
|
||||
}
|
||||
|
||||
function update() {
|
||||
try {
|
||||
window.sessionStorage.setItem(QUERY_KEY, input.value);
|
||||
} catch (e) {
|
||||
// Session-only query is optional.
|
||||
}
|
||||
if (loadError === "server") {
|
||||
clearResults();
|
||||
setStatus("", "Search needs a web server. Run `summer docs:serve` and open the address it prints.");
|
||||
return;
|
||||
}
|
||||
if (loadError === "index") {
|
||||
clearResults();
|
||||
setStatus("", "The search index could not be loaded. Reload the page to try again.");
|
||||
return;
|
||||
}
|
||||
if (!items) {
|
||||
clearResults();
|
||||
setStatus("", "Loading the search index…");
|
||||
return;
|
||||
}
|
||||
var tokens = tokenize(input.value);
|
||||
if (!tokens.length) {
|
||||
clearResults();
|
||||
setStatus("Search the documentation", "Type a module name, a command or a topic, for example `surf`, `migrate` or `relations`.");
|
||||
announce("");
|
||||
return;
|
||||
}
|
||||
render(tokens);
|
||||
}
|
||||
|
||||
function open() {
|
||||
if (dialog.open) {
|
||||
return;
|
||||
}
|
||||
dialog.showModal();
|
||||
input.focus();
|
||||
input.select();
|
||||
if (!items && !loadError) {
|
||||
load();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
if (trigger) {
|
||||
trigger.addEventListener("click", open);
|
||||
}
|
||||
|
||||
dialog.addEventListener("close", function () {
|
||||
if (trigger) {
|
||||
trigger.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// A click on the backdrop (outside the dialog box) closes the dialog.
|
||||
dialog.addEventListener("click", function (e) {
|
||||
if (e.target === dialog) {
|
||||
dialog.close();
|
||||
}
|
||||
});
|
||||
|
||||
input.addEventListener("input", update);
|
||||
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setActive(activeIndex + 1);
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActive(activeIndex - 1);
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
go(activeIndex);
|
||||
}
|
||||
});
|
||||
|
||||
function inTextField(target) {
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
var tag = target.tagName;
|
||||
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if ((e.metaKey || e.ctrlKey) && !e.altKey && (e.key === "k" || e.key === "K")) {
|
||||
e.preventDefault();
|
||||
open();
|
||||
} else if (e.key === "/" && !e.metaKey && !e.ctrlKey && !e.altKey && !inTextField(e.target) && !dialog.open) {
|
||||
e.preventDefault();
|
||||
open();
|
||||
}
|
||||
});
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
228
internal/docsite/theme/assets/site.js
Normal file
228
internal/docsite/theme/assets/site.js
Normal file
@@ -0,0 +1,228 @@
|
||||
// SummerCMS docs: theme toggle, mobile drawer, TOC scroll spy, active
|
||||
// sidebar item and copy buttons. No framework; every DOM change uses
|
||||
// element APIs and textContent.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var STORAGE_KEY = "summer-docs-theme";
|
||||
var THEMES = ["system", "light", "dark"];
|
||||
var LABELS = { system: "System", light: "Light", dark: "Dark" };
|
||||
var root = document.documentElement;
|
||||
var live = document.getElementById("live-region");
|
||||
|
||||
function announce(text) {
|
||||
if (!live) {
|
||||
return;
|
||||
}
|
||||
live.textContent = "";
|
||||
window.setTimeout(function () {
|
||||
live.textContent = text;
|
||||
}, 50);
|
||||
}
|
||||
|
||||
// Theme toggle: System -> Light -> Dark -> System. If storage throws the
|
||||
// choice still applies for this page view and no error is shown.
|
||||
function currentTheme() {
|
||||
var t = root.getAttribute("data-theme");
|
||||
return THEMES.indexOf(t) >= 0 ? t : "system";
|
||||
}
|
||||
|
||||
function applyTheme(theme, button) {
|
||||
root.classList.remove("light", "dark");
|
||||
if (theme !== "system") {
|
||||
root.classList.add(theme);
|
||||
}
|
||||
root.setAttribute("data-theme", theme);
|
||||
if (button) {
|
||||
var next = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
|
||||
var label = "Color theme: " + LABELS[theme] + ". Switch to " + LABELS[next] + ".";
|
||||
button.setAttribute("data-theme", theme);
|
||||
button.setAttribute("aria-label", label);
|
||||
button.setAttribute("title", label);
|
||||
}
|
||||
}
|
||||
|
||||
var toggle = document.querySelector(".theme-toggle");
|
||||
if (toggle) {
|
||||
applyTheme(currentTheme(), toggle);
|
||||
toggle.addEventListener("click", function () {
|
||||
var theme = THEMES[(THEMES.indexOf(currentTheme()) + 1) % THEMES.length];
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch (e) {
|
||||
// Session-only choice.
|
||||
}
|
||||
applyTheme(theme, toggle);
|
||||
});
|
||||
}
|
||||
|
||||
// Mobile drawer (below 1024px).
|
||||
var menu = document.querySelector(".menu-button");
|
||||
var panel = document.getElementById("sidebar");
|
||||
var scrim = document.querySelector(".scrim");
|
||||
|
||||
function drawerOpen() {
|
||||
return panel && panel.classList.contains("open");
|
||||
}
|
||||
|
||||
function focusables() {
|
||||
return panel ? Array.prototype.slice.call(panel.querySelectorAll("a[href], button:not([disabled])")) : [];
|
||||
}
|
||||
|
||||
function openDrawer() {
|
||||
if (!panel || !menu) {
|
||||
return;
|
||||
}
|
||||
panel.classList.add("open");
|
||||
if (scrim) {
|
||||
scrim.hidden = false;
|
||||
}
|
||||
document.body.classList.add("drawer-open");
|
||||
menu.setAttribute("aria-expanded", "true");
|
||||
menu.setAttribute("aria-label", "Close navigation");
|
||||
var items = focusables();
|
||||
if (items.length) {
|
||||
items[0].focus();
|
||||
}
|
||||
}
|
||||
|
||||
function closeDrawer(returnFocus) {
|
||||
if (!drawerOpen()) {
|
||||
return;
|
||||
}
|
||||
panel.classList.remove("open");
|
||||
if (scrim) {
|
||||
scrim.hidden = true;
|
||||
}
|
||||
document.body.classList.remove("drawer-open");
|
||||
menu.setAttribute("aria-expanded", "false");
|
||||
menu.setAttribute("aria-label", "Open navigation");
|
||||
if (returnFocus) {
|
||||
menu.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (menu && panel) {
|
||||
menu.addEventListener("click", function () {
|
||||
if (drawerOpen()) {
|
||||
closeDrawer(true);
|
||||
} else {
|
||||
openDrawer();
|
||||
}
|
||||
});
|
||||
if (scrim) {
|
||||
scrim.addEventListener("click", function () {
|
||||
closeDrawer(true);
|
||||
});
|
||||
}
|
||||
panel.addEventListener("click", function (e) {
|
||||
if (e.target.closest && e.target.closest("a")) {
|
||||
closeDrawer(false);
|
||||
}
|
||||
});
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (!drawerOpen()) {
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
closeDrawer(true);
|
||||
return;
|
||||
}
|
||||
if (e.key !== "Tab") {
|
||||
return;
|
||||
}
|
||||
// Keep focus inside the drawer and its close button.
|
||||
var items = [menu].concat(focusables());
|
||||
var first = items[0];
|
||||
var last = items[items.length - 1];
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
} else if (items.indexOf(document.activeElement) < 0) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
});
|
||||
window.matchMedia("(min-width: 1024px)").addEventListener("change", function (m) {
|
||||
if (m.matches) {
|
||||
closeDrawer(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Scroll the active sidebar item into view, without animation.
|
||||
var active = document.querySelector('.sidebar a[aria-current="page"]');
|
||||
// The sticky sidebar is fully on screen at 1024px and up, so "nearest"
|
||||
// scrolls only the sidebar, never the page (a #fragment jump is kept).
|
||||
if (active && active.scrollIntoView && window.matchMedia("(min-width: 1024px)").matches) {
|
||||
active.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
|
||||
// TOC scroll spy: the heading nearest the top is current.
|
||||
var tocLinks = Array.prototype.slice.call(document.querySelectorAll(".toc a"));
|
||||
if (tocLinks.length && "IntersectionObserver" in window) {
|
||||
var headings = [];
|
||||
tocLinks.forEach(function (link) {
|
||||
var id = decodeURIComponent(link.getAttribute("href").slice(1));
|
||||
var h = document.getElementById(id);
|
||||
if (h) {
|
||||
headings.push({ el: h, link: link });
|
||||
}
|
||||
});
|
||||
var setCurrent = function () {
|
||||
var current = null;
|
||||
for (var i = 0; i < headings.length; i++) {
|
||||
if (headings[i].el.getBoundingClientRect().top <= 112) {
|
||||
current = headings[i];
|
||||
}
|
||||
}
|
||||
if (!current && headings.length) {
|
||||
current = headings[0];
|
||||
}
|
||||
tocLinks.forEach(function (link) {
|
||||
link.removeAttribute("aria-current");
|
||||
});
|
||||
if (current) {
|
||||
current.link.setAttribute("aria-current", "location");
|
||||
}
|
||||
};
|
||||
var observer = new IntersectionObserver(setCurrent, { rootMargin: "-64px 0px -60% 0px" });
|
||||
headings.forEach(function (h) {
|
||||
observer.observe(h.el);
|
||||
});
|
||||
setCurrent();
|
||||
}
|
||||
|
||||
// Copy buttons, only when the clipboard API exists.
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
|
||||
Array.prototype.forEach.call(document.querySelectorAll("figure.code .copy-button"), function (button) {
|
||||
button.hidden = false;
|
||||
button.addEventListener("click", function () {
|
||||
var code = button.parentNode.querySelector("pre code");
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
var copy = code.cloneNode(true);
|
||||
Array.prototype.forEach.call(copy.querySelectorAll(".tok-prompt"), function (p) {
|
||||
p.parentNode.removeChild(p);
|
||||
});
|
||||
navigator.clipboard.writeText(copy.textContent).then(
|
||||
function () {
|
||||
button.classList.add("copied");
|
||||
announce("Copied");
|
||||
window.setTimeout(function () {
|
||||
button.classList.remove("copied");
|
||||
}, 2000);
|
||||
},
|
||||
function () {
|
||||
announce("Copy failed. Select the code and copy it manually.");
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
})();
|
||||
22
internal/docsite/theme/assets/theme-init.js
Normal file
22
internal/docsite/theme/assets/theme-init.js
Normal file
@@ -0,0 +1,22 @@
|
||||
// SummerCMS docs: applies the stored colour theme before first paint.
|
||||
// Loaded synchronously in <head>, before the stylesheet. "system" (the
|
||||
// default) sets neither class and lets prefers-color-scheme decide.
|
||||
(function () {
|
||||
"use strict";
|
||||
var root = document.documentElement;
|
||||
var theme = "system";
|
||||
try {
|
||||
var stored = window.localStorage.getItem("summer-docs-theme");
|
||||
if (stored === "light" || stored === "dark") {
|
||||
theme = stored;
|
||||
}
|
||||
} catch (e) {
|
||||
// Storage is unavailable (private mode, disabled): behave as system.
|
||||
}
|
||||
root.classList.add("js");
|
||||
root.classList.remove("light", "dark");
|
||||
if (theme !== "system") {
|
||||
root.classList.add(theme);
|
||||
}
|
||||
root.setAttribute("data-theme", theme);
|
||||
})();
|
||||
22
internal/docsite/theme/templates/404.html
Normal file
22
internal/docsite/theme/templates/404.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
{{template "head" .}}
|
||||
</head>
|
||||
<body class="docs docs-404">
|
||||
{{template "shell-start" .}}
|
||||
<main id="content" tabindex="-1">
|
||||
<div class="page">
|
||||
<article class="page-body">
|
||||
<h1>{{.Title}}</h1>
|
||||
<p class="lead">{{.Description}}</p>
|
||||
<div class="prose">
|
||||
<p>Use the sidebar or search to find what you need, or go back to the <a href="{{.HomeURL}}">documentation home</a>.</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
{{template "footer" .}}
|
||||
</main>
|
||||
{{template "shell-end" .}}
|
||||
</body>
|
||||
</html>
|
||||
6
internal/docsite/theme/templates/footer.html
Normal file
6
internal/docsite/theme/templates/footer.html
Normal file
@@ -0,0 +1,6 @@
|
||||
{{define "footer" -}}
|
||||
<footer class="site-footer">
|
||||
<span>SummerCMS documentation</span>
|
||||
<span class="footer-links"><a href="{{.LLMS}}">llms.txt</a><a href="{{.LLMSFull}}">llms-full.txt</a></span>
|
||||
</footer>
|
||||
{{- end}}
|
||||
9
internal/docsite/theme/templates/header.html
Normal file
9
internal/docsite/theme/templates/header.html
Normal file
@@ -0,0 +1,9 @@
|
||||
{{define "header" -}}
|
||||
<header class="site-header">
|
||||
<button class="menu-button icon-button" type="button" aria-label="Open navigation" aria-expanded="false" aria-controls="sidebar">{{template "icon-menu"}}{{template "icon-x"}}</button>
|
||||
<a class="wordmark" href="{{.HomeURL}}" aria-label="SummerCMS documentation home"><span class="wordmark-sun">{{template "icon-sun"}}</span><span class="wordmark-text">Summer<span class="wordmark-cms">CMS</span></span></a>
|
||||
<div class="header-spacer"></div>
|
||||
<button class="search-trigger" type="button" aria-label="Search docs" aria-haspopup="dialog" aria-controls="search">{{template "icon-search"}}<span class="search-trigger-label">Search docs</span><kbd>Ctrl K</kbd></button>
|
||||
<button class="theme-toggle" type="button" data-theme="system" aria-label="Color theme: System. Switch to Light." title="Color theme: System. Switch to Light.">{{template "icon-monitor"}}{{template "icon-sun"}}{{template "icon-moon"}}</button>
|
||||
</header>
|
||||
{{- end}}
|
||||
16
internal/docsite/theme/templates/icons.html
Normal file
16
internal/docsite/theme/templates/icons.html
Normal file
@@ -0,0 +1,16 @@
|
||||
{{/* Lucide 1.17.0 icons (ISC, see assets/LICENSE-lucide.txt), path data copied from @lucide/vue. */}}
|
||||
{{define "icon-sun"}}<svg class="icon icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>{{end}}
|
||||
{{define "icon-moon"}}<svg class="icon icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"/></svg>{{end}}
|
||||
{{define "icon-monitor"}}<svg class="icon icon-monitor" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>{{end}}
|
||||
{{define "icon-search"}}<svg class="icon icon-search" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21 21-4.34-4.34"/><circle cx="11" cy="11" r="8"/></svg>{{end}}
|
||||
{{define "icon-menu"}}<svg class="icon icon-menu" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>{{end}}
|
||||
{{define "icon-x"}}<svg class="icon icon-x" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>{{end}}
|
||||
{{define "icon-chevron-left"}}<svg class="icon icon-chevron-left" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>{{end}}
|
||||
{{define "icon-chevron-right"}}<svg class="icon icon-chevron-right" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg>{{end}}
|
||||
{{define "icon-pencil"}}<svg class="icon icon-pencil" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/></svg>{{end}}
|
||||
{{define "icon-file-text"}}<svg class="icon icon-file-text" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>{{end}}
|
||||
{{define "icon-copy"}}<svg class="icon icon-copy" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>{{end}}
|
||||
{{define "icon-check"}}<svg class="icon icon-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>{{end}}
|
||||
{{define "icon-info"}}<svg class="icon icon-info" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>{{end}}
|
||||
{{define "icon-lightbulb"}}<svg class="icon icon-lightbulb" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg>{{end}}
|
||||
{{define "icon-triangle-alert"}}<svg class="icon icon-triangle-alert" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>{{end}}
|
||||
@@ -1,32 +1,62 @@
|
||||
{{define "head" -}}
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>{{.DocTitle}}</title>
|
||||
<meta name="description" content="{{.Description}}">
|
||||
<meta property="og:title" content="{{.Title}}">
|
||||
<meta property="og:description" content="{{.Description}}">
|
||||
{{- if .MarkdownURL}}
|
||||
<link rel="alternate" type="text/markdown" href="{{.MarkdownURL}}">
|
||||
{{- end}}
|
||||
<script src="{{.Assets}}/theme-init.js"></script>
|
||||
<link rel="stylesheet" href="{{.Assets}}/site.css">
|
||||
<script src="{{.Assets}}/site.js" defer></script>
|
||||
<script src="{{.Assets}}/search.js" defer></script>
|
||||
{{- end -}}
|
||||
{{define "shell-start" -}}
|
||||
<a class="skip-link" href="#content">Skip to content</a>
|
||||
{{template "header" .}}
|
||||
<div class="layout">
|
||||
{{template "sidebar" .}}
|
||||
<div class="scrim" hidden></div>
|
||||
{{- end -}}
|
||||
{{define "shell-end" -}}
|
||||
</div>
|
||||
{{template "search" .}}
|
||||
<div class="sr-only" id="live-region" aria-live="polite"></div>
|
||||
{{- end -}}
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{{.DocTitle}}</title>
|
||||
<meta name="description" content="{{.Description}}">
|
||||
<link rel="stylesheet" href="{{.CSS}}">
|
||||
{{template "head" .}}
|
||||
</head>
|
||||
<body class="docs">
|
||||
<div class="layout">
|
||||
<nav class="sidebar" aria-label="Documentation">
|
||||
<a class="sidebar-home" href="{{.HomeURL}}">SummerCMS</a>
|
||||
{{- range .Nav}}
|
||||
<div class="sidebar-section">
|
||||
<p class="sidebar-title">{{.Title}}</p>
|
||||
<ul>
|
||||
{{- range .Items}}
|
||||
<li><a href="{{.URL}}"{{if .Current}} aria-current="page"{{end}}>{{.Title}}</a></li>
|
||||
{{template "shell-start" .}}
|
||||
<main id="content" tabindex="-1">
|
||||
<div class="page{{if .TOC}} has-toc{{end}}">
|
||||
<article class="page-body">
|
||||
{{- if .Eyebrow}}
|
||||
<p class="eyebrow">{{.Eyebrow}}</p>
|
||||
{{- end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{- end}}
|
||||
</nav>
|
||||
<main id="content">
|
||||
<h1>{{.Title}}</h1>
|
||||
<p class="lead">{{.Description}}</p>
|
||||
{{.Content}}
|
||||
</main>
|
||||
<div class="page-actions">
|
||||
{{- if .EditURL}}
|
||||
<a href="{{.EditURL}}">{{template "icon-pencil"}}<span>Edit this page</span></a>
|
||||
{{- end}}
|
||||
<a href="{{.MarkdownURL}}">{{template "icon-file-text"}}<span>View as Markdown</span></a>
|
||||
</div>
|
||||
{{template "toc-inline" .}}
|
||||
<div class="prose">
|
||||
{{.Content}}
|
||||
</div>
|
||||
{{template "pager" .}}
|
||||
</article>
|
||||
{{template "toc" .}}
|
||||
</div>
|
||||
{{template "footer" .}}
|
||||
</main>
|
||||
{{template "shell-end" .}}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
14
internal/docsite/theme/templates/pager.html
Normal file
14
internal/docsite/theme/templates/pager.html
Normal file
@@ -0,0 +1,14 @@
|
||||
{{define "pager" -}}
|
||||
{{- if or .Prev .Next}}
|
||||
<nav class="pager" aria-label="Previous and next page">
|
||||
{{- if .Prev}}
|
||||
<a class="pager-card pager-prev" href="{{.Prev.URL}}"><span class="pager-label">{{template "icon-chevron-left"}}Previous</span><span class="pager-title">{{.Prev.Title}}</span>{{if .Prev.Section}}<span class="pager-section">{{.Prev.Section}}</span>{{end}}</a>
|
||||
{{- else}}
|
||||
<span class="pager-empty"></span>
|
||||
{{- end}}
|
||||
{{- if .Next}}
|
||||
<a class="pager-card pager-next" href="{{.Next.URL}}"><span class="pager-label">Next{{template "icon-chevron-right"}}</span><span class="pager-title">{{.Next.Title}}</span>{{if .Next.Section}}<span class="pager-section">{{.Next.Section}}</span>{{end}}</a>
|
||||
{{- end}}
|
||||
</nav>
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
8
internal/docsite/theme/templates/search.html
Normal file
8
internal/docsite/theme/templates/search.html
Normal file
@@ -0,0 +1,8 @@
|
||||
{{define "search" -}}
|
||||
<dialog class="search" id="search">
|
||||
<div class="search-field">{{template "icon-search"}}<input class="search-input" id="search-input" type="search" placeholder="Search the docs" aria-label="Search the docs" autocomplete="off" spellcheck="false" role="combobox" aria-expanded="false" aria-controls="search-results" aria-autocomplete="list" aria-activedescendant=""></div>
|
||||
<div class="search-status" id="search-status"></div>
|
||||
<ul id="search-results" class="search-results" role="listbox" aria-label="Search results" data-index="{{.SearchIndex}}"></ul>
|
||||
<div class="sr-only" id="search-live" aria-live="polite"></div>
|
||||
</dialog>
|
||||
{{- end}}
|
||||
16
internal/docsite/theme/templates/sidebar.html
Normal file
16
internal/docsite/theme/templates/sidebar.html
Normal file
@@ -0,0 +1,16 @@
|
||||
{{define "sidebar" -}}
|
||||
<div class="sidebar-panel" id="sidebar">
|
||||
<nav class="sidebar" aria-label="Documentation">
|
||||
{{- range .Nav}}
|
||||
<div class="sidebar-section{{if .API}} sidebar-api{{end}}">
|
||||
<p class="sidebar-title">{{.Title}}</p>
|
||||
<ul>
|
||||
{{- range .Items}}
|
||||
<li><a href="{{.URL}}"{{if .Current}} aria-current="page"{{end}}>{{.Title}}</a></li>
|
||||
{{- end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{- end}}
|
||||
</nav>
|
||||
</div>
|
||||
{{- end}}
|
||||
24
internal/docsite/theme/templates/toc.html
Normal file
24
internal/docsite/theme/templates/toc.html
Normal file
@@ -0,0 +1,24 @@
|
||||
{{define "toc" -}}
|
||||
{{- if .TOC}}
|
||||
<aside class="toc" aria-label="On this page">
|
||||
<p class="toc-title">On this page</p>
|
||||
<ul>
|
||||
{{- range .TOC}}
|
||||
<li class="toc-h{{.Level}}"><a href="#{{.ID}}">{{.Text}}</a></li>
|
||||
{{- end}}
|
||||
</ul>
|
||||
</aside>
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
{{define "toc-inline" -}}
|
||||
{{- if .TOC}}
|
||||
<details class="toc-inline">
|
||||
<summary>On this page</summary>
|
||||
<ul>
|
||||
{{- range .TOC}}
|
||||
<li class="toc-h{{.Level}}"><a href="#{{.ID}}">{{.Text}}</a></li>
|
||||
{{- end}}
|
||||
</ul>
|
||||
</details>
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
295
internal/docsite/theme_test.go
Normal file
295
internal/docsite/theme_test.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package docsite
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// themeTree is a two-section fixture: the index (two H2 headings, a
|
||||
// callout), two setup pages and one API page with a Go fence.
|
||||
func themeTree(t *testing.T) string {
|
||||
t.Helper()
|
||||
return writeTree(t, map[string]string{
|
||||
"docs/site.yaml": fixtureSite + "edit_url: \"https://forge.example/edit/{path}\"\n",
|
||||
"docs/index.md": page("Acme docs", "index", 0,
|
||||
"## Alpha\n\nText.\n\n### Detail\n\n> [!NOTE]\n> A note.\n\n> [!TIP]\n> A tip.\n\n> [!WARNING]\n> Careful.\n\n"+
|
||||
"```sh\n$ summer docs:build\n```\n\n## Beta\n\nMore.\n"),
|
||||
"docs/setup/start.md": page("Start", "setup", 10, "## Only heading\n\nText.\n"),
|
||||
"docs/setup/second.md": page("Second", "setup", 20, "Text.\n"),
|
||||
"modules/alpha/alpha.go": "package alpha\n",
|
||||
"modules/alpha/README.md": "# alpha\n\nAlpha does one thing well.\n\n## Usage\n\n" +
|
||||
"```go\nfunc main() {\n\treturn \"x\" // done\n}\n```\n\n```yaml\nkey: true\n```\n",
|
||||
})
|
||||
}
|
||||
|
||||
func buildTheme(t *testing.T) string {
|
||||
t.Helper()
|
||||
out := filepath.Join(t.TempDir(), "site")
|
||||
if _, problems, err := Build(Options{Root: themeTree(t), Commands: fixtureCommands, Out: out}); err != nil || len(problems) > 0 {
|
||||
t.Fatalf("Build: %v %q", err, problemLines(problems))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func readOut(t *testing.T, out, name string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(filepath.Join(out, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
var (
|
||||
scriptTag = regexp.MustCompile(`<script[^>]*>`)
|
||||
anyTag = regexp.MustCompile(`<[a-zA-Z][^>]*>`)
|
||||
styleAttr = regexp.MustCompile(`\sstyle=`)
|
||||
handlerAttr = regexp.MustCompile(`\son[a-z]+=`)
|
||||
)
|
||||
|
||||
// assertCSPSafe fails on inline script bodies, inline styles and inline
|
||||
// event handlers (script-src 'self'; style-src 'self').
|
||||
func assertCSPSafe(t *testing.T, name, html string) {
|
||||
t.Helper()
|
||||
for _, loc := range scriptTag.FindAllStringIndex(html, -1) {
|
||||
tag := html[loc[0]:loc[1]]
|
||||
if !strings.Contains(tag, ` src="`) || !strings.HasPrefix(html[loc[1]:], "</script>") {
|
||||
t.Errorf("%s has an inline script: %s", name, tag)
|
||||
}
|
||||
}
|
||||
for _, tag := range anyTag.FindAllString(html, -1) {
|
||||
if styleAttr.MatchString(tag) || handlerAttr.MatchString(tag) {
|
||||
t.Errorf("%s has an inline style or handler: %s", name, tag)
|
||||
}
|
||||
}
|
||||
if strings.Contains(html, "<style") {
|
||||
t.Errorf("%s has a <style> element", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSiteMarkers(t *testing.T) {
|
||||
out := buildTheme(t)
|
||||
index := readOut(t, out, "index.html")
|
||||
for _, marker := range []string{
|
||||
`<body class="docs">`,
|
||||
`<header class="site-header">`,
|
||||
`<nav class="sidebar" aria-label="Documentation">`,
|
||||
`<aside class="toc" aria-label="On this page">`,
|
||||
`<details class="toc-inline">`,
|
||||
`<div class="page-actions">`,
|
||||
`<nav class="pager" aria-label="Previous and next page">`,
|
||||
`<footer class="site-footer">`,
|
||||
`<dialog class="search" id="search">`,
|
||||
`<button class="theme-toggle"`,
|
||||
`<figure class="code">`,
|
||||
`<aside class="callout callout-note" role="note">`,
|
||||
`<aside class="callout callout-tip" role="note">`,
|
||||
`<aside class="callout callout-warning" role="note">`,
|
||||
`<a class="heading-anchor" href="#alpha" aria-label="Link to section: Alpha">#</a>`,
|
||||
`<svg class="icon icon-`,
|
||||
`<link rel="stylesheet" href="/assets/site.css">`,
|
||||
`<script src="/assets/theme-init.js"></script>`,
|
||||
`<meta name="color-scheme" content="light dark">`,
|
||||
`<meta property="og:title" content="Acme docs">`,
|
||||
`<link rel="alternate" type="text/markdown" href="/index.md">`,
|
||||
`href="https://forge.example/edit/docs/index.md"`,
|
||||
`View as Markdown`,
|
||||
`aria-label="SummerCMS documentation home"`,
|
||||
`aria-controls="sidebar"`,
|
||||
`<span class="tok-prompt">$ </span><span class="tok-kw">summer</span>`,
|
||||
`href="/llms.txt"`,
|
||||
`href="/llms-full.txt"`,
|
||||
`class="toc-h3"`,
|
||||
} {
|
||||
if !strings.Contains(index, marker) {
|
||||
t.Errorf("index.html missing %s", marker)
|
||||
}
|
||||
}
|
||||
if strings.Contains(index, "[!NOTE]") {
|
||||
t.Error("callout marker line rendered")
|
||||
}
|
||||
if i, j := strings.Index(index, "theme-init.js"), strings.Index(index, "site.css"); i < 0 || j < 0 || i > j {
|
||||
t.Error("theme-init.js must load before the stylesheet")
|
||||
}
|
||||
|
||||
// First page: Next only (the empty Previous cell keeps Next on the right).
|
||||
if !strings.Contains(index, `<span class="pager-empty"></span>`) || strings.Contains(index, "pager-prev") || !strings.Contains(index, "pager-next") {
|
||||
t.Error("index.html pager should hold Next only")
|
||||
}
|
||||
// One H2 and no H3: no TOC; the pager crosses into the API section.
|
||||
start := readOut(t, out, "setup/start.html")
|
||||
if strings.Contains(start, `class="toc"`) || strings.Contains(start, "toc-inline") {
|
||||
t.Error("setup/start.html has a TOC with one heading")
|
||||
}
|
||||
if !strings.Contains(start, `<p class="eyebrow">Setup</p>`) {
|
||||
t.Error("setup/start.html has no section eyebrow")
|
||||
}
|
||||
second := readOut(t, out, "setup/second.html")
|
||||
if !strings.Contains(second, `<span class="pager-section">API reference</span>`) {
|
||||
t.Error("cross-section Next has no section line")
|
||||
}
|
||||
if strings.Count(second, `class="pager-section"`) != 1 {
|
||||
t.Error("same-section Previous must not carry a section line")
|
||||
}
|
||||
// Last page: Previous only.
|
||||
api := readOut(t, out, "api/alpha.html")
|
||||
if !strings.Contains(api, "pager-prev") || strings.Contains(api, "pager-next") {
|
||||
t.Error("api/alpha.html pager should hold Previous only")
|
||||
}
|
||||
for _, want := range []string{
|
||||
`<span class="tok-kw">func</span>`,
|
||||
`<span class="tok-str">"x"</span>`,
|
||||
`<span class="tok-com">// done</span>`,
|
||||
`<span class="tok-key">key</span>`,
|
||||
`<span class="tok-num">true</span>`,
|
||||
`<code class="language-go">`,
|
||||
`<button type="button" class="copy-button" aria-label="Copy code" hidden>`,
|
||||
`<div class="sidebar-section sidebar-api">`,
|
||||
`aria-current="page"`,
|
||||
} {
|
||||
if !strings.Contains(api, want) {
|
||||
t.Errorf("api/alpha.html missing %s", want)
|
||||
}
|
||||
}
|
||||
|
||||
notFound := readOut(t, out, "404.html")
|
||||
for _, want := range []string{`<body class="docs docs-404">`, "<h1>Page not found</h1>", "This page does not exist or has moved.", `>documentation home</a>`} {
|
||||
if !strings.Contains(notFound, want) {
|
||||
t.Errorf("404.html missing %s", want)
|
||||
}
|
||||
}
|
||||
for _, not := range []string{`aria-current="page"`, `class="toc"`, `class="pager"`, "page-actions"} {
|
||||
if strings.Contains(notFound, not) {
|
||||
t.Errorf("404.html must not contain %s", not)
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range []string{"index.html", "setup/start.html", "setup/second.html", "api/alpha.html", "404.html"} {
|
||||
html := readOut(t, out, name)
|
||||
assertCSPSafe(t, name, html)
|
||||
if strings.Contains(html, "//fonts.") || strings.Contains(html, "cdn") {
|
||||
t.Errorf("%s references a third-party asset origin", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"assets/site.js", "assets/search.js", "assets/theme-init.js", "assets/fonts/dm-mono-latin-400-normal.woff2"} {
|
||||
if _, err := os.Stat(filepath.Join(out, name)); err != nil {
|
||||
t.Errorf("missing %s", name)
|
||||
}
|
||||
}
|
||||
|
||||
// A one-page site renders no pager.
|
||||
var buf bytes.Buffer
|
||||
if err := pageTmpl.ExecuteTemplate(&buf, "pager", pageView{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.TrimSpace(buf.String()) != "" {
|
||||
t.Errorf("pager without prev/next = %q, want nothing", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeHandler(t *testing.T) {
|
||||
srv := httptest.NewServer(Handler(buildTheme(t)))
|
||||
defer srv.Close()
|
||||
get := func(p string) (int, string) {
|
||||
t.Helper()
|
||||
res, err := http.Get(srv.URL + p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
return res.StatusCode, string(body)
|
||||
}
|
||||
for _, p := range []string{"/index.html", "/", "/setup/start.html", "/assets/site.css", "/search-index.json"} {
|
||||
if code, _ := get(p); code != http.StatusOK {
|
||||
t.Errorf("GET %s = %d, want 200", p, code)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{"/missing.html", "/setup/", "/.summer-docs", "/assets/../.summer-docs", "/%2e%2e/etc/passwd"} {
|
||||
code, body := get(p)
|
||||
if code != http.StatusNotFound || !strings.Contains(body, "Page not found") {
|
||||
t.Errorf("GET %s = %d, want 404 with the Page not found body", p, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncBuffer is a goroutine-safe bytes.Buffer.
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *syncBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *syncBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
var servingLine = regexp.MustCompile(`Serving docs at (http://\S+) \(press Ctrl\+C to stop\)`)
|
||||
|
||||
func TestServeRefusesNonLoopback(t *testing.T) {
|
||||
opts := Options{Root: themeTree(t), Commands: fixtureCommands}
|
||||
for _, addr := range []string{"0.0.0.0:8088", "192.0.2.1:8088", "example.com:8088", ":8088"} {
|
||||
var out bytes.Buffer
|
||||
err := Serve(context.Background(), opts, addr, false, &out)
|
||||
want := "docs:serve: refusing to listen on " + addr + ": not a loopback address. Pass --allow-remote to serve on the network."
|
||||
if err == nil || err.Error() != want {
|
||||
t.Errorf("Serve(%s) = %v, want %q", addr, err, want)
|
||||
}
|
||||
}
|
||||
if err := checkServeAddr("0.0.0.0:0", true); err != nil {
|
||||
t.Errorf("--allow-remote still refused: %v", err)
|
||||
}
|
||||
|
||||
for _, addr := range []string{"127.0.0.1:0", "localhost:0"} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
out := &syncBuffer{}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- Serve(ctx, opts, addr, false, out) }()
|
||||
var base string
|
||||
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
|
||||
if m := servingLine.FindStringSubmatch(out.String()); m != nil {
|
||||
base = m[1]
|
||||
break
|
||||
}
|
||||
}
|
||||
if base == "" {
|
||||
cancel()
|
||||
t.Fatalf("Serve(%s) printed no serving line: %s", addr, out.String())
|
||||
}
|
||||
res, err := http.Get(base + "/index.html")
|
||||
if err != nil {
|
||||
cancel()
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Serve(%s) GET /index.html = %d", addr, res.StatusCode)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Errorf("Serve(%s) = %v after cancel", addr, err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("Serve(%s) did not return after cancel", addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,15 @@ run_deps() {
|
||||
*) refuse "go.mod added $dep, which no phase decision approves" ;;
|
||||
esac
|
||||
done
|
||||
# D-15: chroma/v2 highlights code at build time, as a direct requirement.
|
||||
(cd "$ROOT" && go mod edit -json) | python3 -c '
|
||||
import json, sys
|
||||
direct = [r for r in json.load(sys.stdin).get("Require") or [] if r["Path"] == "github.com/alecthomas/chroma/v2" and not r.get("Indirect")]
|
||||
sys.exit(0 if direct else 1)
|
||||
' || refuse "go.mod does not require github.com/alecthomas/chroma/v2 directly"
|
||||
if grep -q 'goldmark-highlighting' "$ROOT/go.mod"; then
|
||||
refuse "go.mod requires goldmark-highlighting (D-15 rejects it)"
|
||||
fi
|
||||
echo "phase11.1 deps passed"
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user