Phase 6 part 5, step 1: a shared site theme

internal/theme embeds a Hugo theme from federated-website's look and the
13 section types both sites share, with the header, footer, colors, font
and logo set per site in hugo.toml, and a README of each type's fields.
The catalogue reader reads themes' sections and READMEs after the site's
own; lead forms know a theme site needs only the Lead Capture address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:14:24 -07:00
co-authored by Claude Opus 5.5
parent 98913971ea
commit 5d7db5c5bf
36 changed files with 2641 additions and 79 deletions
+36 -13
View File
@@ -82,25 +82,36 @@ var (
partialRef = regexp.MustCompile(`partial\s+"sections/([\w-]+)\.html"\s*(?:(\$s|\.)(?:\s|-?\}\}|\)))?`)
dollarS = regexp.MustCompile(`\$s\.([a-z]\w*)`)
bareDot = regexp.MustCompile(`(?:^|[\s(])\.([a-z]\w*)`)
typeTest = regexp.MustCompile(`eq \.type "([\w-]+)"`)
readmeList = regexp.MustCompile("^\\s*[-*]\\s+`([\\w-]+)`\\s+[—–-]+\\s+(.+)$")
readmeRow = regexp.MustCompile("^\\|\\s*`([\\w-]+)`\\s*\\|\\s*(.+?)\\s*\\|\\s*$")
)
// Read reads the catalogue from a working copy of the site.
func Read(dir string, pathOf PathFunc) (*Catalog, error) {
partDir := filepath.Join(dir, "layouts", "partials", "sections")
entries, err := os.ReadDir(partDir)
if err != nil && !os.IsNotExist(err) {
return nil, err
// The site's own layouts, then its themes' (the site's win, as in Hugo).
roots := []string{dir}
if themes, err := filepath.Glob(filepath.Join(dir, "themes", "*")); err == nil {
sort.Strings(themes)
roots = append(roots, themes...)
}
partials := map[string]string{}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".html") {
for _, root := range roots {
partDir := filepath.Join(root, "layouts", "partials", "sections")
entries, err := os.ReadDir(partDir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
for _, e := range entries {
name := strings.TrimSuffix(e.Name(), ".html")
if e.IsDir() || !strings.HasSuffix(e.Name(), ".html") || partials[name] != "" {
continue
}
raw, err := os.ReadFile(filepath.Join(partDir, e.Name()))
if err != nil {
return nil, err
}
partials[strings.TrimSuffix(e.Name(), ".html")] = string(raw)
partials[name] = string(raw)
}
}
// Partials named by another partial, or by render-sections, are
@@ -115,9 +126,16 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
}
}
if raw, err := os.ReadFile(filepath.Join(dir, "layouts", "partials", "render-sections.html")); err == nil {
for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) {
referenced[m[1]] = true
dispatched := map[string]bool{} // types render-sections picks by name
for _, root := range roots {
if raw, err := os.ReadFile(filepath.Join(root, "layouts", "partials", "render-sections.html")); err == nil {
for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) {
referenced[m[1]] = true
}
for _, m := range typeTest.FindAllStringSubmatch(string(raw), -1) {
dispatched[m[1]] = true
}
break
}
}
@@ -135,7 +153,7 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
root := filepath.Join(dir, "content")
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
if os.IsNotExist(err) && p == root {
return fs.SkipDir
@@ -208,13 +226,18 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
for name := range partials {
if referenced[name] && uses[name] == nil {
if referenced[name] && uses[name] == nil && !dispatched[name] {
c.Helpers = append(c.Helpers, name)
continue
}
get(name)
}
docs := readmeDocs(dir)
docs := map[string]string{}
for i := len(roots) - 1; i >= 0; i-- { // the site's README wins
for k, v := range readmeDocs(roots[i]) {
docs[k] = v
}
}
for name, t := range uses {
_, has := partials[name]
t.Missing = !has
+21 -62
View File
@@ -15,6 +15,7 @@ import (
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/seo"
"supermarket/internal/theme"
)
// Lead forms: a site's `form` sections post to EspoCRM's Lead Capture
@@ -34,58 +35,9 @@ const LeadScriptPath = "static/js/supermarket-leads.js"
var LeadPayloadFields = []string{"First Name", "Last Name", "Email", "Account Name", "Phone", "Description"}
// leadScript defines window.leadPost(form, data), which the form's own
// script calls in place of its fetch: it returns the fetch's promise.
const leadScript = `/* Sends the site's lead forms to EspoCRM's Lead Capture. Written by
Supermarket: the form posts here instead of to [params.leads] action
directly, so its fields can be mapped onto a Lead's. */
(function () {
var mapped = { email: 'emailAddress', 'e-mail': 'emailAddress', phone: 'phoneNumber', tel: 'phoneNumber',
company: 'accountName', organization: 'accountName', organisation: 'accountName', church: 'accountName' };
function label(form, name) {
var el = form.querySelector('[name="' + name + '"]');
var l = el && el.id && form.querySelector('label[for="' + el.id + '"]');
return l ? l.childNodes[0].textContent.trim() : name;
}
window.leadPost = function (form, data) {
var lead = { firstName: null, lastName: null, emailAddress: null, accountName: null, phoneNumber: null };
var notes = [];
data.forEach(function (value, name) {
value = String(value).trim();
if (!value) return;
var key = name.toLowerCase();
if (key === 'name' || key === 'full_name' || key === 'fullname') {
var parts = value.split(/\s+/);
lead.lastName = parts.pop();
lead.firstName = parts.length ? parts.join(' ') : null;
} else if (key === 'first_name' || key === 'firstname') {
lead.firstName = value;
} else if (key === 'last_name' || key === 'lastname') {
lead.lastName = value;
} else if (mapped[key]) {
lead[mapped[key]] = value;
} else if (key === 'source') {
notes.unshift('Form: ' + value);
} else if (key === 'page') {
notes.push('Page: ' + location.origin + value);
} else {
notes.push(label(form, name) + ': ' + value);
}
});
if (!lead.lastName) lead.lastName = lead.emailAddress || 'Website visitor';
var q = new URLSearchParams(location.search);
['utm_campaign', 'utm_source', 'utm_medium', 'utm_content'].forEach(function (k) {
if (q.get(k)) notes.push(k + ': ' + q.get(k));
});
if (document.referrer) notes.push('Came from: ' + document.referrer);
lead.description = notes.join('\n') || null;
return fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(lead)
});
};
})();
`
// script calls in place of its fetch: it returns the fetch's promise. It's
// the theme's, so new sites have it from the start.
var leadScript = theme.LeadScript()
var (
captureURL = regexp.MustCompile(`^https://[^/\s]+/(?:[^\s?#]*/)?api/v1/LeadCapture/[A-Za-z0-9]+$`)
@@ -216,10 +168,14 @@ func ReadForms(wc *hugorepo.Repo, cat *Catalog) FormState {
st.Action = LeadsAction(string(raw))
}
}
st.Script = wc.Exists(LeadScriptPath)
st.Script = wc.Exists(LeadScriptPath) || wc.Exists(theme.Dir+"/"+LeadScriptPath)
if raw, err := os.ReadFile(wc.Dir + "/layouts/partials/sections/form.html"); err == nil {
st.Patched = strings.Contains(string(raw), "window.leadPost")
_, st.Supported = PatchFormPartial(string(raw))
} else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/layouts/partials/sections/form.html"); err == nil {
// The theme's form already posts through the script.
st.Patched = strings.Contains(string(raw), "window.leadPost")
st.Supported = st.Patched
}
if cat != nil {
if t := cat.Type("form"); t != nil {
@@ -252,14 +208,18 @@ func ConnectForms(ctx context.Context, ap *seo.Applier, capture string, formPage
return nil, errors.New("the site's settings aren't in a TOML file (hugo.toml), which is all Supermarket can change for now")
}
partial := "layouts/partials/sections/form.html"
raw, err := os.ReadFile(wc.Dir + "/" + partial)
if err != nil {
var files []struct{ path, body string }
if raw, err := os.ReadFile(wc.Dir + "/" + partial); err == nil {
patched, ok := PatchFormPartial(string(raw))
if !ok {
return nil, errors.New("the site's form section doesn't post the way Supermarket knows (a fetch of form.action with the form's data), so it can't be connected automatically")
}
files = append(files, struct{ path, body string }{partial, patched}, struct{ path, body string }{LeadScriptPath, leadScript})
} else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/" + partial); err == nil && strings.Contains(string(raw), "window.leadPost") {
// Supermarket's theme: its form and script are ready; only the address is needed.
} else {
return nil, errors.New("the site has no form section (layouts/partials/sections/form.html)")
}
patched, ok := PatchFormPartial(string(raw))
if !ok {
return nil, errors.New("the site's form section doesn't post the way Supermarket knows (a fetch of form.action with the form's data), so it can't be connected automatically")
}
branch := "supermarket/lead-forms"
if err := wc.NewBranch(ctx, branch); err != nil {
return nil, err
@@ -268,9 +228,8 @@ func ConnectForms(ctx context.Context, ap *seo.Applier, capture string, formPage
if err != nil {
return nil, err
}
for _, f := range []struct{ path, body string }{
{cfg, SetLeadsAction(string(cfgRaw), capture)}, {partial, patched}, {LeadScriptPath, leadScript},
} {
files = append(files, struct{ path, body string }{cfg, SetLeadsAction(string(cfgRaw), capture)})
for _, f := range files {
if err := wc.WriteFile(f.path, f.body); err != nil {
return nil, err
}
+49
View File
@@ -0,0 +1,49 @@
package sites
import (
"slices"
"strings"
"testing"
"supermarket/internal/theme"
)
func TestReadThemeSite(t *testing.T) {
files := map[string]string{
"hugo.toml": "theme = 'supermarket'\n",
"content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hi\n - type: faq\n items: [{q: A, a: B}]\n---\n",
"README.md": "| `faq` | the site's own words |\n",
"layouts/partials/sections/faq.html": "{{ $s := . }}{{ range $s.items }}{{ .q }}{{ .a }}{{ end }}",
}
for p, b := range theme.Files() {
files[theme.Dir+"/"+p] = b
}
dir := write(t, files)
c, err := Read(dir, path)
if err != nil {
t.Fatal(err)
}
var names []string
for _, ty := range c.Types {
names = append(names, ty.Name)
}
slices.Sort(names)
want := []string{"callout", "cards", "checklist", "faq", "features", "final-cta", "form", "hero", "split", "stats", "steps", "table", "text"}
if !slices.Equal(names, want) {
t.Errorf("types: %v", names)
}
if !slices.Equal(c.Helpers, []string{"ctas", "head", "wrapper"}) {
t.Errorf("helpers: %v", c.Helpers)
}
if d := c.Type("hero").Doc; !strings.Contains(d, "`eyebrow`, `title`, `subhead`") {
t.Errorf("hero doc from the theme: %q", d)
}
// The site's own README and layout win over the theme's.
faq := c.Type("faq")
if faq.Doc != "the site's own words" || slices.Contains(faq.Layout, "ctas") {
t.Errorf("faq: %+v", faq)
}
if c.Type("form").Missing || !slices.Contains(c.Type("table").Layout, "rows") {
t.Errorf("form/table: %+v %+v", c.Type("form"), c.Type("table"))
}
}