diff --git a/internal/build/cards.go b/internal/build/cards.go index 3a5c2ee..85e429c 100644 --- a/internal/build/cards.go +++ b/internal/build/cards.go @@ -47,7 +47,11 @@ const cardsDrawing = "1" // look is the card style's fingerprint. func cardPath(s *site.Site, p *site.Page, look string) string { cc := s.Config.Cards - if !cc.On() || p.Image != "" || p.RedirectTo != "" || p.NoIndex || (p.Kind != site.KindPage && p.Kind != site.KindList) { + // A tag's page gets one only when the site wrote it a page of its own + // (content/tags/.md): an archive with a thousand tags doesn't want + // a thousand cards. + ownTerm := (p.Kind == site.KindTerm || p.Kind == site.KindTerms) && p.Source != "" + if !cc.On() || p.Image != "" || p.RedirectTo != "" || p.NoIndex || (p.Kind != site.KindPage && p.Kind != site.KindList && !ownTerm) { return "" } name := strings.Trim(strings.ReplaceAll(p.Path, "/", "-"), "-") diff --git a/internal/build/funcs.go b/internal/build/funcs.go index 933899c..87b78c8 100644 --- a/internal/build/funcs.go +++ b/internal/build/funcs.go @@ -16,6 +16,7 @@ import ( "path/filepath" "reflect" "regexp" + "strconv" "strings" "time" @@ -304,6 +305,14 @@ func funcs(s *site.Site, a *Assets, md *site.Markdown, icons Icons) template.Fun "pageData": func(p *site.Page) []map[string]any { return pageData(s, p) }, // money 24 "USD" -> "$24.00": a price as people read it. "money": money, + // price .Params.price: the amount as a plain number with two + // decimals ("24.40"), for machines (link previews); "" if it isn't one. + "price": func(v any) string { + if f, ok := amount(v); ok { + return strconv.FormatFloat(f, 'f', 2, 64) + } + return "" + }, // closed "2026-11-01": whether that day is over, in the site's time // zone, when the site is built (a job's closing date, say). "closed": func(v any) bool { return closed(s, v) }, diff --git a/internal/build/packfuncs_test.go b/internal/build/packfuncs_test.go index dd4aeb1..44562c2 100644 --- a/internal/build/packfuncs_test.go +++ b/internal/build/packfuncs_test.go @@ -90,3 +90,54 @@ func TestProductReviewsData(t *testing.T) { t.Error("a product without reviews has a rating") } } + +func TestProductGroupData(t *testing.T) { + list := &site.Page{Kind: site.KindList, Title: "Shop", Path: "/products/", Collection: "products", Params: map[string]any{"brand": "Acme"}} + tee := &site.Page{Kind: site.KindPage, Title: "Tee", Path: "/products/tee/", Collection: "products", Permalink: "https://example.org/products/tee/", Params: map[string]any{ + "price": 24, "choose": "Size", + "variants": []any{ + map[string]any{"group": "Red", "name": "S", "price": 24, "sku": "T-R-S"}, + map[string]any{"group": "Red", "name": "XL", "price": 26.5, "sold_out": true}, + }, + }} + s := &site.Site{Config: &site.Config{Name: "Shop", URL: "https://example.org", Collections: map[string]site.CollectionConfig{"products": {Layout: "product"}}}, Pages: []*site.Page{list, tee}} + if d := pageData(s, list); len(d) != 0 { + t.Errorf("the shop's list page is described as %v", d) + } + d := productData(s, tee) + if d["@type"] != "ProductGroup" || d["brand"].(map[string]any)["name"] != "Acme" || d["productGroupID"] != "products/tee" { + t.Fatalf("group: %v", d) + } + if by, _ := d["variesBy"].([]any); len(by) != 2 || by[0] != "https://schema.org/size" || by[1] != "https://schema.org/color" { + t.Errorf("variesBy: %v", d["variesBy"]) + } + vs, _ := d["hasVariant"].([]any) + if len(vs) != 2 { + t.Fatalf("hasVariant: %v", d["hasVariant"]) + } + xl := vs[1].(map[string]any) + o := xl["offers"].(map[string]any) + if xl["name"] != "Tee (Red, XL)" || xl["size"] != "XL" || xl["color"] != "Red" || o["price"] != "26.50" || o["availability"] != "https://schema.org/OutOfStock" { + t.Errorf("variant: %v", xl) + } + if vs[0].(map[string]any)["sku"] != "T-R-S" { + t.Errorf("sku: %v", vs[0]) + } + // One variant is just a product. + tee.Params["variants"] = tee.Params["variants"].([]any)[:1] + if d := productData(s, tee); d["@type"] != "Product" || d["offers"].(map[string]any)["price"] != "24.00" { + t.Errorf("one variant: %v", d) + } +} + +func TestCardsForOwnTagPages(t *testing.T) { + s := &site.Site{Config: &site.Config{Name: "Shop", Cards: &site.CardsConfig{Enabled: true}}} + own := &site.Page{Kind: site.KindTerm, Path: "/tags/shirts/", Title: "Shirts", Source: "content/tags/shirts.md"} + bare := &site.Page{Kind: site.KindTerm, Path: "/tags/hats/", Title: "Hats"} + if cardPath(s, own, "x") == "" { + t.Error("a tag page with its own content file gets no card") + } + if cardPath(s, bare, "x") != "" { + t.Error("a generated tag page gets a card") + } +} diff --git a/internal/build/schema.go b/internal/build/schema.go index 8e168a3..7860016 100644 --- a/internal/build/schema.go +++ b/internal/build/schema.go @@ -49,7 +49,9 @@ func pageData(s *site.Site, p *site.Page) []map[string]any { } } layout := p.Layout - if layout == "" && p.Collection != "" { + // A collection's layout is its pages' layout, not its list page's: the + // shop's list isn't a product. + if layout == "" && p.Collection != "" && p.Kind == site.KindPage { layout = s.Config.Collections[p.Collection].Layout } switch layout { @@ -478,18 +480,29 @@ func money(v any, currency string) string { return n + " " + cur } +// productData is a Product, or a ProductGroup when the product comes in +// sizes or colors: one Product per variant with its own price, SKU and +// availability, which is how search engines want variants described. func productData(s *site.Site, p *site.Page) map[string]any { + vs := list(p.Params["variants"]) out := ldBase("Product") + if len(vs) > 1 { + out = ldBase("ProductGroup") + } out["name"] = p.Title out["url"] = p.Permalink if p.Summary != "" { out["description"] = p.Summary } var images []string + groupImage := map[string]string{} // a color's first photo for _, ph := range list(p.Params["photos"]) { m, _ := ph.(map[string]any) if im := str(m["image"]); im != "" { images = append(images, abs(s, im)) + if g := str(m["group"]); g != "" && groupImage[g] == "" { + groupImage[g] = abs(s, im) + } } } if len(images) > 0 { @@ -498,29 +511,79 @@ func productData(s *site.Site, p *site.Page) map[string]any { if v := str(p.Params["sku"]); v != "" { out["sku"] = v } + brand := map[string]any{"@type": "Brand", "name": productBrand(s, p)} + out["brand"] = brand if f, ok := amount(p.Params["price"]); ok { cur := strings.ToUpper(str(p.Params["currency"])) if cur == "" { cur = "USD" } - avail := "https://schema.org/InStock" - if str(p.Params["sold_out"]) == "true" { - avail = "https://schema.org/OutOfStock" + offer := func(price float64, soldOut bool) map[string]any { + avail := "https://schema.org/InStock" + if soldOut { + avail = "https://schema.org/OutOfStock" + } + return map[string]any{"@type": "Offer", "price": strconv.FormatFloat(price, 'f', 2, 64), "priceCurrency": cur, "availability": avail, "url": p.Permalink} } - out["offers"] = map[string]any{"@type": "Offer", "price": strconv.FormatFloat(f, 'f', 2, 64), "priceCurrency": cur, "availability": avail, "url": p.Permalink} - // Sizes and colors at different prices: the range, and how many. - if vs := list(p.Params["variants"]); len(vs) > 1 { - lo, hi := f, f + soldOut := str(p.Params["sold_out"]) == "true" + if len(vs) <= 1 { + out["offers"] = offer(f, soldOut) + } else { + // What the variants differ by: the choice's own name (choose:, + // "Size") and, when they come in groups, the group's + // (choose_group:, "Color"), where schema.org has a property for it. + sizeKey, groupKey := variesBy(str(p.Params["choose"])), variesBy(str(p.Params["choose_group"])) + if groupKey == "" && str(p.Params["choose_group"]) == "" { + groupKey = "color" + } + var by []any + var variants []any + grouped := false for _, v := range vs { m, _ := v.(map[string]any) - if pr, ok := amount(m["price"]); ok { - lo, hi = min(lo, pr), max(hi, pr) + name, group := str(m["name"]), str(m["group"]) + grouped = grouped || group != "" + vp := ldBase("Product") + delete(vp, "@context") + label := name + if group != "" { + label = group + ", " + name } + vp["name"] = p.Title + " (" + label + ")" + if sku := str(m["sku"]); sku != "" { + vp["sku"] = sku + } + if sizeKey != "" && name != "" { + vp[sizeKey] = name + } + if groupKey != "" && group != "" { + vp[groupKey] = group + } + if im := groupImage[group]; im != "" { + vp["image"] = im + } else if len(images) > 0 { + vp["image"] = images[0] + } + price := f + if pr, ok := amount(m["price"]); ok { + price = pr + } + vp["offers"] = offer(price, soldOut || str(m["sold_out"]) == "true") + variants = append(variants, vp) } - out["offers"] = map[string]any{"@type": "AggregateOffer", "lowPrice": strconv.FormatFloat(lo, 'f', 2, 64), "highPrice": strconv.FormatFloat(hi, 'f', 2, 64), "offerCount": len(vs), "priceCurrency": cur, "availability": avail, "url": p.Permalink} + if sizeKey != "" { + by = append(by, "https://schema.org/"+sizeKey) + } + if grouped && groupKey != "" && groupKey != sizeKey { + by = append(by, "https://schema.org/"+groupKey) + } + if len(by) > 0 { + out["variesBy"] = by + } + out["productGroupID"] = productGroupID(p) + out["hasVariant"] = variants } } - out["brand"] = map[string]any{"@type": "Brand", "name": s.Config.Name} // Customers' reviews of the product (the reviews pack). A business's // reviews of itself get none: search engines ignore those. if r := ratings(p.Params["reviews"]); r.Count > 0 { @@ -548,6 +611,47 @@ func productData(s *site.Site, p *site.Page) map[string]any { return out } +// variesBy is the schema.org property for a choice's label: "Size" is +// size, "Colour" is color. Anything else has none. +func variesBy(label string) string { + switch strings.ToLower(strings.TrimSpace(label)) { + case "size", "sizes": + return "size" + case "color", "colour", "colors", "colours": + return "color" + case "material": + return "material" + case "pattern": + return "pattern" + } + return "" +} + +// productBrand is the brand: the product's brand:, else its collection +// page's, else the site's name. +func productBrand(s *site.Site, p *site.Page) string { + if b := str(p.Params["brand"]); b != "" { + return b + } + if p.Collection != "" { + if l := s.PageAt(s.CollectionPath(p.Collection)); l != nil { + if b := str(l.Params["brand"]); b != "" { + return b + } + } + } + return s.Config.Name +} + +// productGroupID ties a product's variants together: its sku:, else its +// address. +func productGroupID(p *site.Page) string { + if v := str(p.Params["sku"]); v != "" { + return v + } + return strings.Trim(p.Path, "/") +} + var ( mdLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`) mdStrong = regexp.MustCompile("(\\*\\*|__|\\*|`)") diff --git a/internal/packs/bundled_test.go b/internal/packs/bundled_test.go index baa5b6e..f4e0574 100644 --- a/internal/packs/bundled_test.go +++ b/internal/packs/bundled_test.go @@ -169,7 +169,7 @@ func TestBundledPacksBuildAndPass(t *testing.T) { {"content/picks.md", "---\ntitle: Picks\nsummary: Picks.\nsections:\n - products: { heading: Gardener's picks, tag: Garden, more: All garden 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": {`
`, ``, "Size", `name="products" value="v1:1" required data-option="S" data-cart-variant data-id="v1" data-name="S" data-price="24">`, "2XL $26.00", `value="v3:1" required disabled data-option="3XL" data-cart-variant`, "3XL sold out", `data-cart-add hidden>Add to cart`, `product-buy-button" type="submit">Buy now`, `