Shop shelves: tag pages with words of their own #32

Merged
jcoffey-dev merged 3 commits from shop/shelves into main 2026-10-17 00:38:53 +00:00
12 changed files with 251 additions and 14 deletions

No files matched your search

+6
View File
@@ -194,6 +194,12 @@ func funcs(s *site.Site, a *Assets, md *site.Markdown, icons Icons) template.Fun
"excerpt": func(n int, v any) string { return site.Excerpt(n, fmt.Sprint(v)) },
// termURL "tags" "Open Source" -> /tags/open-source/ (or "" if it has none).
"termURL": s.TermURL,
// term "tags" "Linux" -> that term's page (nil if there is none), with
// what content/tags/linux.md says about it.
"term": s.TermPage,
// tagged "tags" "Linux" (collection "products"): the products tagged
// Linux, in the collection's order.
"tagged": s.Tagged,
// isExternal: an absolute link to another site.
"isExternal": md.External,
// Cloudflare's markers that turn Email Address Obfuscation off for a
+4 -2
View File
@@ -8,6 +8,7 @@ import (
"path"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"time"
@@ -79,7 +80,8 @@ func (s *Server) apiQuick(w http.ResponseWriter, r *http.Request, sess *Session,
}
// collectionNames lists the site's collections: folders in content/, and
// any configured in site.yaml.
// any configured in site.yaml. A folder named for a taxonomy (content/tags/)
// describes its terms and isn't one.
func collectionNames(siteDir string, cfg *site.Config) []string {
seen := map[string]bool{}
entries, _ := os.ReadDir(filepath.Join(siteDir, "content"))
@@ -93,7 +95,7 @@ func collectionNames(siteDir string, cfg *site.Config) []string {
}
var out []string
for name := range seen {
if slug(name) == name {
if slug(name) == name && !slices.Contains(cfg.Taxonomies, name) {
out = append(out, name)
}
}
+4
View File
@@ -68,6 +68,10 @@ func TestShortSummary(t *testing.T) {
if got := shortSummary(one); len([]rune(got)) > 160 || !strings.HasSuffix(got, "word…") {
t.Errorf("one long sentence: %q (%d)", got, len([]rune(got)))
}
dotted := "A black heavyweight tee with the kitten on it. A small mark sits on the left chest. The full mark and example.org run across the back. Sizes S to 4XL, printed to order."
if got := shortSummary(dotted); got != "A black heavyweight tee with the kitten on it. A small mark sits on the left chest. The full mark and example.org run across the back." {
t.Errorf("a full stop inside a word: %q", got)
}
if got := shortSummary("Short and sweet."); got != "Short and sweet." {
t.Errorf("short: %q", got)
}
+11 -3
View File
@@ -293,6 +293,8 @@ func Write(items []Item, opt Options) (*Report, error) {
var mdImage = regexp.MustCompile(`!\[([^\]]*)\]\(\s*<?([^)\s>]+)`)
var sentenceEnd = regexp.MustCompile(`[.!?]+(\s+|$)`)
// shortSummary keeps a summary to what search results show (about 160
// characters): whole sentences while they fit, else the first one cut at a
// word. WordPress's excerpts are its first 55 words, twice that.
@@ -301,12 +303,18 @@ func shortSummary(s string) string {
if len([]rune(s)) <= max {
return s
}
// Whole sentences, one after another: a full stop inside a word
// (example.org, 1.5) doesn't end one.
out := ""
for _, sent := range regexp.MustCompile(`[^.!?]+[.!?]+(\s+|$)`).FindAllString(s, -1) {
if len([]rune(out+sent)) > max {
for rest := s; rest != ""; {
end := len(rest)
if loc := sentenceEnd.FindStringIndex(rest); loc != nil {
end = loc[1]
}
if len([]rune(out+rest[:end])) > max {
break
}
out += sent
out, rest = out+rest[:end], rest[end:]
}
if out = strings.TrimSpace(out); out != "" {
return out
+14 -1
View File
@@ -160,14 +160,22 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
{"content/products/kit.md", "---\ntitle: Starter kit\nsummary: A jar of starter.\nprice: 24\ncurrency: USD\nweight: 1\nphotos:\n - { image: /media/a.png, alt: A jar }\n - { image: /media/b.png, alt: The card }\nbuy: \"https://buy.stripe.com/test_1\"\noptions:\n - { name: With a basket, price: 39.5, buy: \"https://buy.stripe.com/test_2\" }\n---\nWhat's in the box.\n"},
{"content/products/mug.md", "---\ntitle: Mug\nsummary: A mug.\nprice: 12\ncurrency: EUR\nweight: 2\nsold_out: true\n---\n"},
{"content/products/tee.md", "---\ntitle: Tee\nsummary: A tee.\nprice: 24\nprice_from: true\ncurrency: USD\nweight: 3\ntags: [Linux, Shirts]\nphotos:\n - { image: /media/a.png, alt: The tee }\nchoose: Size\nvariants:\n - { name: S, price: 24, id: v1 }\n - { name: 2XL, price: 26, id: v2 }\n - { name: 3XL, price: 28, id: v3, sold_out: true }\ncheckout: { action: \"https://shop.example/cart/checkout\", field: products, item: \"{id}:{qty}\", join: \",\", fields: { currency: USD } }\n---\n"},
{"content/products/cap.md", "---\ntitle: Cap\nsummary: A cap.\nprice: 20\ncurrency: USD\nweight: 4\nvariants:\n - { group: Black, name: One size, price: 20, value: \"c1:1\" }\ncheckout: { action: \"https://shop.example/cart/checkout\" }\n---\n"},
{"content/products/cap.md", "---\ntitle: Cap\nsummary: A cap.\nprice: 20\ncurrency: USD\nweight: 4\ntags: [linux]\nvariants:\n - { group: Black, name: One size, price: 20, value: \"c1:1\" }\ncheckout: { action: \"https://shop.example/cart/checkout\" }\n---\n"},
{"content/cart.md", "---\ntitle: Your cart\nlayout: cart\nsuggest: 3\n---\n"},
{"content/tags/linux.md", "---\ntitle: Linux things\nlayout: shelf\n---\nFor the penguin people.\n"},
{"content/tags/kitchen.md", "---\ntitle: Kitchen\n---\nComing soon.\n"},
{"content/tags/shirts.md", "---\ntitle: Shirts\nsummary: Cotton, mostly.\nlayout: shelf\n---\n"},
{"content/picks.md", "---\ntitle: Picks\nsummary: Picks.\nsections:\n - products: { heading: Penguin picks, tag: Linux, more: All Linux things }\n---\n"},
{"content/products/print.md", "---\ntitle: Print\nsummary: A print.\nprice: 30\ncurrency: USD\nweight: 5\nvariants:\n - { group: Matte, name: A4, price: 30, buy: \"https://buy.stripe.com/a4\" }\n - { group: Matte, name: A3, price: 40, buy: \"https://buy.stripe.com/a3\", sold_out: true }\n---\n"},
}, map[string][]string{
"products/tee/index.html": {`<form class="product-form" method="get" action="https://shop.example/cart/checkout" data-cart data-field="products" data-item="{id}:{qty}" data-join="," data-title="Tee" data-href="/products/tee/" data-currency="USD" data-image="/media/a.png">`, `<input type="hidden" name="currency" value="USD">`, "<legend>Size</legend>", `name="products" value="v1:1" required data-cart-variant data-id="v1" data-name="S" data-price="24">`, "2XL <small>$26.00</small>", `value="v3:1" required disabled data-cart-variant`, "<span>3XL <small>sold out</small>", `data-cart-add hidden>Add to cart</button>`, `product-buy-button" type="submit">Buy now</button>`, `<script src="/hotdog-cart.`, `data-page="/cart/"`, `<a class="cart-link" href="/cart/" data-cart-link hidden>`, `<span class="product-from">From</span> $24.00`, `"@type":"AggregateOffer"`, `"lowPrice":"24.00"`, `"highPrice":"28.00"`, `"offerCount":3`},
"products/cap/index.html": {`<input type="hidden" name="products" value="c1:1" data-cart-variant data-id="c1:1" data-name="Black · One size" data-price="20">`, ">Buy now</button>"},
"cart/index.html": {`<div class="cart-view" data-cart-view data-shop="/products/">`, "The cart needs JavaScript.", `data-cart-suggest data-count="3" hidden>`, `<li class="shop-card" data-product="/products/tee/" data-tags="Linux,Shirts">`},
"privacy/index.html": {"What you put in your cart"},
"tags/linux/index.html": {"<h1>Linux things</h1>", "For the penguin people.", `class="wrap page shop shelf"`, `data-product="/products/tee/"`, `data-product="/products/cap/"`},
"tags/kitchen/index.html": {"Kitchen", "Coming soon."},
"tags/shirts/index.html": {`<p class="shelf-summary">Cotton, mostly.</p>`, `data-product="/products/tee/"`},
"picks/index.html": {"Penguin picks", `data-product="/products/tee/"`, `data-product="/products/cap/"`, `href="/tags/linux/">All Linux things`},
"products/print/index.html": {`href="https://buy.stripe.com/a4" rel="noopener">Matte · A4 · $30.00`, `<span class="btn variant-sold">Matte · A3 · sold out</span>`},
"products/index.html": {`href="/products/kit/"`, "$24.00", "€12.00 · <em>Sold out</em>"},
"products/kit/index.html": {`href="https://buy.stripe.com/test_1" rel="noopener">Buy`, "With a basket · $39.50", `alt="The card"`, `"@type":"Product"`, `"priceCurrency":"USD"`, `"price":"24.00"`, "InStock"},
@@ -301,6 +309,11 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
absent := map[string]map[string][]string{
"link-in-bio": {"links/index.html": {`<header class="top">`}},
"coming-soon": {"soon/index.html": {`<header class="top">`}},
"shop": {
"tags/linux/index.html": {`data-product="/products/kit/"`},
"picks/index.html": {`data-product="/products/kit/"`},
"tags/index.html": {"/tags/kitchen/"},
},
}
for _, c := range cases {
t.Run(c.pack, func(t *testing.T) {
+2
View File
@@ -46,6 +46,7 @@ type Site struct {
Banners []Banner
Markdown *Markdown
terms map[string]*termIndex
termDocs map[string]map[string]*Page // taxonomy -> term ("" for the index) -> content/<taxonomy>/ page
}
// Options change what Load includes.
@@ -436,6 +437,7 @@ func unquote(s string) string {
// neighbours, taxonomies, permalinks, and the list pages nobody wrote.
func (s *Site) assemble() {
cfg := s.Config
s.takeTermDocs()
for _, p := range s.Pages {
p.Permalink = cfg.URL + p.Path
switch p.Kind {
+99
View File
@@ -1,6 +1,7 @@
package site
import (
"slices"
"sort"
"strings"
"unicode"
@@ -63,6 +64,44 @@ func mostUsed(counts map[string]int, seen []string) string {
return best
}
// A folder in content/ named for a taxonomy describes its terms instead of
// being a collection: content/tags/linux.md (or tags/linux/index.md) gives
// /tags/linux/ a title, words, a picture, a layout and any other front
// matter, and content/tags/_index.md does the same for /tags/. The term's
// pages are still listed by the taxonomy.
func (s *Site) takeTermDocs() {
s.termDocs = map[string]map[string]*Page{}
kept := s.Pages[:0]
for _, p := range s.Pages {
tax := p.Collection
if tax == "" || !slices.Contains(s.Config.Taxonomies, tax) || (p.Kind != KindPage && p.Kind != KindList) {
kept = append(kept, p)
continue
}
if s.termDocs[tax] == nil {
s.termDocs[tax] = map[string]*Page{}
}
term := ""
if p.Kind == KindPage {
term = strings.Trim(strings.TrimPrefix(p.Path, "/"+tax+"/"), "/")
}
s.termDocs[tax][term] = p
}
s.Pages = kept
}
// describe gives a generated term or terms page what its content/ file says.
func (p *Page) describe(d *Page) {
if d == nil {
return
}
p.Source, p.Title, p.Summary = d.Source, d.Title, d.Summary
p.Content, p.Raw, p.WordCount, p.LeadImage = d.Content, d.Raw, d.WordCount, d.LeadImage
p.Params, p.Sections, p.Layout, p.Weight = d.Params, d.Sections, d.Layout, d.Weight
p.Image, p.ImageAlt = d.Image, d.ImageAlt
p.NoIndex = p.NoIndex || d.NoIndex
}
func (s *Site) assembleTaxonomies() {
cfg := s.Config
s.terms = map[string]*termIndex{}
@@ -98,6 +137,22 @@ func (s *Site) assembleTaxonomies() {
for k := range slugCounts {
ti.canon[k] = mostUsed(slugCounts[k], slugSeen[k])
}
// A term with a page in content/ but on no page yet still gets its page.
docs := map[string]*Page{}
for term, d := range s.termDocs[tax] {
if term == "" {
continue
}
slug := ti.Slug(term)
if slug == "" {
continue
}
docs[slug] = d
if _, used := ti.canon[hyphenBlind(slug)]; !used {
ti.canon[hyphenBlind(slug)] = slug
ti.infos[slug] = &TermInfo{Slug: slug, Label: d.Title, URL: "/" + tax + "/" + slug + "/"}
}
}
// Pass 2: counts, labels and the pages under each term.
labelCounts := map[string]map[string]int{}
labelSeen := map[string][]string{}
@@ -132,7 +187,18 @@ func (s *Site) assembleTaxonomies() {
sort.SliceStable(ti.order, func(i, j int) bool { return ti.infos[ti.order[i]].Count > ti.infos[ti.order[j]].Count })
index := &Page{Kind: KindTerms, Title: titleCase(tax), Path: "/" + tax + "/", Taxonomy: tax, Term: tax,
Params: map[string]any{}, Terms: map[string][]string{}, Site: s}
index.describe(s.termDocs[tax][""])
index.Permalink = cfg.URL + index.Path
for slug, info := range ti.infos {
if info.Count == 0 { // described but not used: a page, but not in the lists
tp := &Page{Kind: KindTerm, Title: info.Label, Path: info.URL, Taxonomy: tax, Term: slug,
Params: map[string]any{}, Terms: map[string][]string{}, Site: s}
tp.describe(docs[slug])
tp.Permalink = cfg.URL + tp.Path
info.Page = tp
s.Pages = append(s.Pages, tp)
}
}
for _, slug := range ti.order {
info := ti.infos[slug]
info.Label = mostUsed(labelCounts[slug], labelSeen[slug])
@@ -140,6 +206,7 @@ func (s *Site) assembleTaxonomies() {
Pages: termPages[slug], Params: map[string]any{}, Terms: map[string][]string{}, Site: s}
tp.Permalink = cfg.URL + tp.Path
tp.NoIndex = cfg.TermIndexMin > 0 && len(tp.Pages) < cfg.TermIndexMin
tp.describe(docs[slug])
info.Page = tp
s.Pages = append(s.Pages, tp)
index.Pages = append(index.Pages, tp)
@@ -177,6 +244,38 @@ func (s *Site) Terms(tax string) []TermInfo {
return ti.byCount
}
// TermPage is the page of the term a spelling belongs to, or nil if there is
// none: term "tags" "Linux" has the title, words and front matter of
// content/tags/linux.md, when there is one, and the pages tagged Linux.
func (s *Site) TermPage(tax, v string) *Page {
ti := s.terms[tax]
if ti == nil {
return nil
}
if info := ti.infos[ti.Slug(v)]; info != nil {
return info.Page
}
return nil
}
// Tagged keeps the pages that carry a term, in the order given: tagged
// "tags" "Linux" (collection "products") is the products tagged Linux, in
// the shop's order. Any spelling of the term matches, as on its page.
func (s *Site) Tagged(tax, v string, pages []*Page) []*Page {
ti := s.terms[tax]
if ti == nil {
return nil
}
slug := ti.Slug(v)
var out []*Page
for _, p := range pages {
if slices.Contains(p.Terms[tax], slug) {
out = append(out, p)
}
}
return out
}
// TermsByLabel lists a taxonomy's terms in label order.
func (s *Site) TermsByLabel(tax string) []TermInfo {
ti := s.terms[tax]
+68
View File
@@ -0,0 +1,68 @@
package site
import (
"strings"
"testing"
)
// A file in content/tags/ describes its term instead of being a collection,
// and tagged keeps the order it is given.
func TestTermDocsAndTagged(t *testing.T) {
dir := writeSite(t, map[string]string{
"site.yaml": "name: T\nurl: https://example.org\ntaxonomies: [tags]\ncollections:\n products:\n sort: weight\n",
"content/products/b.md": "---\ntitle: B\nweight: 2\ntags: [Open Source]\n---\n",
"content/products/a.md": "---\ntitle: A\nweight: 1\ntags: [open-source, Mugs]\n---\n",
"content/products/c.md": "---\ntitle: C\nweight: 3\ntags: [Mugs]\n---\n",
"content/tags/_index.md": "---\ntitle: Shelves\n---\nEvery shelf.\n",
"content/tags/opensource.md": "---\ntitle: Free software\nlayout: shelf\nlook: green\n---\nShare it.\n",
"content/tags/later.md": "---\ntitle: Later\n---\nNothing yet.\n",
})
s, err := Load(dir, Options{})
if err != nil {
t.Fatal(err)
}
if _, ok := s.Collections["tags"]; ok {
t.Error("content/tags/ became a collection")
}
tp := s.TermPage("tags", "Open Source")
if tp == nil {
t.Fatal("no page for Open Source")
}
if tp.Title != "Free software" || tp.Layout != "shelf" || tp.Params["look"] != "green" || !strings.Contains(string(tp.Content), "Share it.") || tp.Source != "tags/opensource.md" {
t.Errorf("term page = %q, layout %q, params %v, content %q, source %q", tp.Title, tp.Layout, tp.Params, tp.Content, tp.Source)
}
if len(tp.Pages) != 2 {
t.Errorf("open source lists %d pages, want 2", len(tp.Pages))
}
var got []string
for _, p := range s.Tagged("tags", "OPEN SOURCE", s.Collection("products")) {
got = append(got, p.Title)
}
if strings.Join(got, ",") != "A,B" {
t.Errorf("tagged = %v, want A,B in the collection's order", got)
}
if later := s.TermPage("tags", "later"); later == nil || later.Title != "Later" || len(later.Pages) != 0 {
t.Errorf("a described term nobody uses: %+v", later)
}
for _, info := range s.Terms("tags") {
if info.Slug == "later" {
t.Error("an unused term is listed")
}
}
paths := map[string]*Page{}
for _, p := range s.Pages {
if paths[p.Path] != nil {
t.Errorf("two pages at %s", p.Path)
}
paths[p.Path] = p
}
if idx := paths["/tags/"]; idx == nil || idx.Title != "Shelves" {
t.Errorf("tags index = %+v", idx)
}
if paths["/tags/later/"] == nil {
t.Error("no /tags/later/")
}
if s.TermPage("tags", "nothing") != nil || s.Tagged("colors", "red", s.Collection("products")) != nil {
t.Error("unknown terms or taxonomies should find nothing")
}
}
+8 -2
View File
@@ -8,8 +8,9 @@ link), which takes the payment, the address, any tax and sends the receipt.
hotdog-cms pack add shop
There's no cart: each product (or option) has its own checkout, which suits
a shop with a handful of things to sell. Card details never touch your site,
Each product (or option) has its own checkout, which suits a shop with a
handful of things to sell; a cart is optional (below). Card details never
touch your site,
and nothing from the provider loads until someone chooses Buy. Products are
also written as schema.org Product data, with the price and whether they're
in stock, for search engines.
@@ -27,3 +28,8 @@ to cart beside Buy now. The cart is kept in the visitor's own browser and
reaches the shop only at checkout; its page suggests other products, those
sharing a tag with what's in the cart first. Without JavaScript, Buy now
still works.
Tags make shelves. A page at `content/tags/<tag>.md` with `layout: shelf`
gives `/tags/<tag>/` its own title and words above that tag's products, in
the shop's order, and any other front matter the theme wants to read. The
"Products" section's tag field shows one tag's products on any page.
+13
View File
@@ -0,0 +1,13 @@
{{ define "main" }}
{{/* One tag's products, in the shop's order: for content/tags/<tag>.md
with layout: shelf. collection: picks the products (default products). */}}
<link rel="stylesheet" href="{{ asset "packs/shop/shop.css" }}">
{{ $c := default "products" .Params.collection }}
{{ $list := .Pages }}{{ if eq .Kind "term" }}{{ $list = tagged .Taxonomy .Term (collection $c) }}{{ end }}
<section class="wrap page shop shelf">
{{ with index .Site.Lists $c }}<p class="eyebrow"><a href="{{ .Path }}">{{ .Title }}</a></p>{{ end }}
<h1>{{ .Title }}</h1>
{{ with .Content }}<div class="prose">{{ . }}</div>{{ else }}{{ with .Summary }}<p class="shelf-summary">{{ . }}</p>{{ end }}{{ end }}
<ul class="shop-grid">{{ range $list }}{{ template "product-card" . }}{{ end }}</ul>
</section>
{{ end }}
+13 -2
View File
@@ -1,7 +1,7 @@
name: shop
version: 1.2.0
version: 1.3.0
title: Shop
description: A product catalog with a page per product (photos, price, options), where each Buy button opens your payment provider's checkout. No cart, no card details on your site, no script.
description: A product catalog with a page per product (photos, price, options), where Buy opens your payment provider's checkout, and an optional cart. No card details on your site.
license: MIT
author: Coffey Labs LLC
collections:
@@ -61,6 +61,17 @@ notes: |
tag with what's in the cart first. Without JavaScript, Buy now still
works.
Shelves: give a tag a page of its own, content/tags/<tag>.md, with
layout: shelf, and /tags/<tag>/ shows that tag's words and its products
in the shop's order. The "Products" section's tag field shows just one
tag's products on any page.
---
title: Kitchen
layout: shelf
---
Everything for baking, from starters to baskets.
sold_out: true shows Sold out instead of the buttons. weight sets the
order (lowest first). /products/ lists them; the "Products" section shows
some on any page. Mention your payment provider in your privacy notice.
+9 -4
View File
@@ -1,19 +1,24 @@
{{/* section
label: Products
about: Products from the shop, with their photos and prices.
about: Products from the shop, with their photos and prices; all of them, or those with one tag.
fields:
- { name: heading, type: text, default: Shop }
- { name: intro, type: markdown }
- { name: collection, type: collection, default: products, label: Products from }
- { name: tag, type: text, label: Only those tagged, help: "Leave empty for every product." }
- { name: taxonomy, type: text, default: tags, label: Tagged in, help: "The taxonomy the tag belongs to, as in site.yaml." }
- { name: count, type: number, default: 4, label: How many }
- { name: more, type: text, default: Everything in the shop, label: Link to the rest }
*/}}
{{ $c := default "products" .Data.collection }}
{{ $c := default "products" .Data.collection }}{{ $tax := default "tags" .Data.taxonomy }}
{{ $list := collection $c }}{{ $href := printf "/%s/" $c }}
{{ with .Data.tag }}{{ $list = tagged $tax . $list }}{{ with term $tax . }}{{ $href = .Path }}{{ end }}{{ end }}
<link rel="stylesheet" href="{{ asset "packs/shop/shop.css" }}">
<section class="block shop">
<div class="wrap">
{{ with .Data.heading }}<h2>{{ . }}</h2>{{ end }}
{{ with .Data.intro }}<div class="intro">{{ markdownify . }}</div>{{ end }}
<ul class="shop-grid">{{ range limit (default 4 .Data.count) (collection $c) }}{{ template "product-card" . }}{{ end }}</ul>
<p><a class="more" href="/{{ $c }}/">Everything in the shop</a></p>
<ul class="shop-grid">{{ range limit (default 4 .Data.count) $list }}{{ template "product-card" . }}{{ end }}</ul>
<p><a class="more" href="{{ $href }}">{{ default "Everything in the shop" .Data.more }}</a></p>
</div>
</section>